text stringlengths 54 60.6k |
|---|
<commit_before>#ifndef BFC_COMBINE_INC_VISITOR_HPP
#define BFC_COMBINE_INC_VISITOR_HPP
#include "ast/mod.hpp"
#include "ast/base.hpp"
#include "test_visitor.hpp"
#include "types.h"
namespace bfc {
namespace ast {
class combine_inc_visitor : public opt_seq_base_visitor {
public:
status visit(add &node) {
// discard any zero value node
if (node.value() == 0) {
return CONTINUE;
}
// Only attempt to combine if there is a previous node
if (!opt_seq.empty()) {
// try to combine with the previous node if possible
try_combine_inc_visitor v(node.offset(), node.value(), true);
if (opt_seq.back().accept(v) == CONTINUE) {
opt_seq.pop_back();
// discard the combined node if it is 0
if (v.new_value() != 0) {
if (v.type() == ADD) {
opt_seq.emplace_back(new add(node.loc(), node.offset(), v.new_value());
} else {
opt_seq.emplace_back(new sub(node.loc(), node.offset(), v.new_value());
}
}
return CONTINUE;
}
}
// else make node copy
return opt_seq_base_visitor::handle_add(node);
}
status visit(const add &node) {
// discard any zero value node
if (node.value() == 0) {
return CONTINUE;
}
// Only attempt to combine if there is a previous node
if (!opt_seq.empty()) {
// try to combine with the previous node if possible
try_combine_inc_visitor v(node.offset(), node.value(), true);
if (opt_seq.back().accept(v) == CONTINUE) {
opt_seq.pop_back();
// discard the combined node if it is 0
if (v.new_value() != 0) {
if (v.type() == ADD) {
opt_seq.emplace_back(new add(node.loc(), node.offset(), v.new_value());
} else {
opt_seq.emplace_back(new sub(node.loc(), node.offset(), v.new_value());
}
}
return CONTINUE;
}
}
// else make node copy
return opt_seq_base_visitor::handle_add(node);
}
status visit(sub &node) {
// discard any zero value node
if (node.value() == 0) {
return CONTINUE;
}
// Only attempt to combine if there is a previous node
if (!opt_seq.empty()) {
// try to combine with the previous node if possible
try_combine_inc_visitor v(node.offset(), node.value(), false);
if (opt_seq.back().accept(v) == CONTINUE) {
opt_seq.pop_back();
// discard the combined node if it is 0
if (v.new_value() != 0) {
if (v.type() == ADD) {
opt_seq.emplace_back(new add(node.loc(), node.offset(), v.new_value());
} else {
opt_seq.emplace_back(new sub(node.loc(), node.offset(), v.new_value());
}
return CONTINUE;
}
}
}
// else make node copy
return opt_seq_base_visitor::handle_sub(node);
}
status visit(const sub &node) {
// discard any zero value node
if (node.value() == 0) {
return CONTINUE;
}
// Only attempt to combine if there is a previous node
if (!opt_seq.empty()) {
// try to combine with the previous node if possible
try_combine_inc_visitor v(node.offset(), node.value(), false);
if (opt_seq.back().accept(v) == CONTINUE) {
opt_seq.pop_back();
// discard the combined node if it is 0
if (v.new_value() != 0) {
if (v.type() == ADD) {
opt_seq.emplace_back(new add(node.loc(), node.offset(), v.new_value());
} else {
opt_seq.emplace_back(new sub(node.loc(), node.offset(), v.new_value());
}
return CONTINUE;
}
return CONTINUE;
}
}
// else make node copy
return opt_seq_base_visitor::handle_sub(node);
}
private:
class try_combine_inc_visitor : public test_visitor {
enum node_type {
ADD = 0,
SUB
};
public:
try_combine_inc_visitor(ptrdiff_t offset, bf_value val, bool isAdd) :
next_off(offset), next_val(val), isAdd(isAdd) {}
bf_value new_value() {
return new_val;
}
node_type type() {
return type;
}
status visit(add &node) {
if (node.offset() != next_off) {
return BREAK;
}
new_val = node.value();
isAdd ? new_val += next_val : new_val -= next_val;
type = ADD;
return CONTINUE;
}
status visit(const add &node) {
if (node.offset() != next_off) {
return BREAK;
}
new_val = node.value();
isAdd ? new_val += next_val : new_val -= next_val;
type = ADD;
return CONTINUE;
}
status visit(sub &node) {
if (node.offset() != next_off) {
return BREAK;
}
new_val = node.value();
isAdd ? new_val -= next_val : new_val += next_val;
type = SUB;
return CONTINUE;
}
status visit(const sub &node) {
if (node.offset() != next_off) {
return BREAK;
}
new_val = node.value();
isAdd ? new_val -= next_val : new_val += next_val;
type = SUB;
return CONTINUE;
}
private:
bool isAdd;
ptrdiff_t next_off;
bf_value next_val;
bf_value new_val;
node_type type;
};
};
}
}
#endif /* !BFC_COMBINE_INC_VISITOR_HPP */
<commit_msg>Pull out nested enum<commit_after>#ifndef BFC_COMBINE_INC_VISITOR_HPP
#define BFC_COMBINE_INC_VISITOR_HPP
#include "ast/mod.hpp"
#include "ast/base.hpp"
#include "test_visitor.hpp"
#include "types.h"
namespace bfc {
namespace ast {
class combine_inc_visitor : public opt_seq_base_visitor {
public:
enum node_type {
ADD = 0,
SUB
};
status visit(add &node) {
// discard any zero value node
if (node.value() == 0) {
return CONTINUE;
}
// Only attempt to combine if there is a previous node
if (!opt_seq.empty()) {
// try to combine with the previous node if possible
try_combine_inc_visitor v(node.offset(), node.value(), true);
if (opt_seq.back().accept(v) == CONTINUE) {
opt_seq.pop_back();
// discard the combined node if it is 0
if (v.new_value() != 0) {
if (v.type() == ADD) {
opt_seq.emplace_back(new add(node.loc(), node.offset(), v.new_value());
} else {
opt_seq.emplace_back(new sub(node.loc(), node.offset(), v.new_value());
}
}
return CONTINUE;
}
}
// else make node copy
return opt_seq_base_visitor::handle_add(node);
}
status visit(const add &node) {
// discard any zero value node
if (node.value() == 0) {
return CONTINUE;
}
// Only attempt to combine if there is a previous node
if (!opt_seq.empty()) {
// try to combine with the previous node if possible
try_combine_inc_visitor v(node.offset(), node.value(), true);
if (opt_seq.back().accept(v) == CONTINUE) {
opt_seq.pop_back();
// discard the combined node if it is 0
if (v.new_value() != 0) {
if (v.type() == ADD) {
opt_seq.emplace_back(new add(node.loc(), node.offset(), v.new_value());
} else {
opt_seq.emplace_back(new sub(node.loc(), node.offset(), v.new_value());
}
}
return CONTINUE;
}
}
// else make node copy
return opt_seq_base_visitor::handle_add(node);
}
status visit(sub &node) {
// discard any zero value node
if (node.value() == 0) {
return CONTINUE;
}
// Only attempt to combine if there is a previous node
if (!opt_seq.empty()) {
// try to combine with the previous node if possible
try_combine_inc_visitor v(node.offset(), node.value(), false);
if (opt_seq.back().accept(v) == CONTINUE) {
opt_seq.pop_back();
// discard the combined node if it is 0
if (v.new_value() != 0) {
if (v.type() == ADD) {
opt_seq.emplace_back(new add(node.loc(), node.offset(), v.new_value());
} else {
opt_seq.emplace_back(new sub(node.loc(), node.offset(), v.new_value());
}
return CONTINUE;
}
}
}
// else make node copy
return opt_seq_base_visitor::handle_sub(node);
}
status visit(const sub &node) {
// discard any zero value node
if (node.value() == 0) {
return CONTINUE;
}
// Only attempt to combine if there is a previous node
if (!opt_seq.empty()) {
// try to combine with the previous node if possible
try_combine_inc_visitor v(node.offset(), node.value(), false);
if (opt_seq.back().accept(v) == CONTINUE) {
opt_seq.pop_back();
// discard the combined node if it is 0
if (v.new_value() != 0) {
if (v.type() == ADD) {
opt_seq.emplace_back(new add(node.loc(), node.offset(), v.new_value());
} else {
opt_seq.emplace_back(new sub(node.loc(), node.offset(), v.new_value());
}
return CONTINUE;
}
return CONTINUE;
}
}
// else make node copy
return opt_seq_base_visitor::handle_sub(node);
}
private:
class try_combine_inc_visitor : public test_visitor {
public:
try_combine_inc_visitor(ptrdiff_t offset, bf_value val, bool isAdd) :
next_off(offset), next_val(val), isAdd(isAdd) {}
bf_value new_value() {
return new_val;
}
node_type type() {
return type;
}
status visit(add &node) {
if (node.offset() != next_off) {
return BREAK;
}
new_val = node.value();
isAdd ? new_val += next_val : new_val -= next_val;
type = ADD;
return CONTINUE;
}
status visit(const add &node) {
if (node.offset() != next_off) {
return BREAK;
}
new_val = node.value();
isAdd ? new_val += next_val : new_val -= next_val;
type = ADD;
return CONTINUE;
}
status visit(sub &node) {
if (node.offset() != next_off) {
return BREAK;
}
new_val = node.value();
isAdd ? new_val -= next_val : new_val += next_val;
type = SUB;
return CONTINUE;
}
status visit(const sub &node) {
if (node.offset() != next_off) {
return BREAK;
}
new_val = node.value();
isAdd ? new_val -= next_val : new_val += next_val;
type = SUB;
return CONTINUE;
}
private:
bool isAdd;
ptrdiff_t next_off;
bf_value next_val;
bf_value new_val;
node_type type;
};
};
}
}
#endif /* !BFC_COMBINE_INC_VISITOR_HPP */
<|endoftext|> |
<commit_before>#include <lms/framework.h>
#include <lms/executionmanager.h>
#include <pugixml.hpp>
#include <fstream>
#include <csignal>
#include <map>
#include <cstdlib>
#include "lms/extra/backtrace_formatter.h"
#include "lms/logging/log_level.h"
#include "lms/extra/time.h"
#include "unistd.h"
#include "lms/type/module_config.h"
#include "lms/extra/string.h"
namespace lms{
std::string Framework::externalDirectory = EXTERNAL_DIR;
std::string Framework::configsDirectory = CONFIGS_DIR;
Framework::Framework(const ArgumentHandler &arguments) :
logger("FRAMEWORK", &rootLogger), argumentHandler(arguments), executionManager(rootLogger),
clockEnabled(false), clock(rootLogger), monitorEnabled(false) {
rootLogger.filter(std::unique_ptr<logging::LoggingFilter>(new logging::PrefixAndLevelFilter(
arguments.argLoggingMinLevel(), arguments.argLoggingPrefixes())));
SignalHandler::getInstance()
.addListener(SIGINT, this)
.addListener(SIGSEGV, this);
logger.info() << "RunLevel " << arguments.argRunLevel();
//parse framework config
if(arguments.argRunLevel() >= RunLevel::CONFIG) {
parseConfig(LoadConfigFlag::LOAD_EVERYTHING);
}
if(arguments.argRunLevel() >= RunLevel::ENABLE) {
// enable modules after they were made available
logger.info() << "Start enabling modules";
for(ModuleToLoad mod : tempModulesToLoadList) {
executionManager.enableModule(mod.name, mod.logLevel);
}
if(arguments.argRunLevel() == RunLevel::ENABLE) {
executionManager.getDataManager().printMapping();
executionManager.validate();
executionManager.printCycleList();
}
}
if(arguments.argRunLevel() >= RunLevel::CYCLE) {
//Execution
running = true;
while(running) {
if(clockEnabled) {
clock.beforeLoopIteration();
}
executionManager.loop();
if(clockEnabled) {
clock.afterLoopIteration();
}
if(lms::extra::FILE_MONITOR_SUPPORTED && monitorEnabled
&& monitor.hasChangedFiles()) {
monitor.unwatchAll();
parseConfig(LoadConfigFlag::ONLY_MODULE_CONFIG);
}
}
}
}
/*
* TODO suffix for config
*/
void Framework::parseConfig(LoadConfigFlag flag){
logger.debug("parseConfig") << "EXTERNAL: " << externalDirectory
<< std::endl << "CONFIGS: " << configsDirectory;
std::string configPath = configsDirectory + "/";
if(argumentHandler.argLoadConfiguration().empty()) {
configPath += "framework_conf.xml";
} else {
configPath += argumentHandler.argLoadConfiguration() + ".xml";
}
parseFile(configPath, flag);
}
void Framework::parseFile(const std::string &file, LoadConfigFlag flag) {
logger.debug("parseFile") << "Reading XML file: " << file;
if(!monitor.watch(file)) {
logger.error("parseFile") << "Could not monitor " << file;
}
std::ifstream ifs;
ifs.open (file, std::ifstream::in);
if(ifs.is_open()){
pugi::xml_document doc;
pugi::xml_parse_result result = doc.load(ifs);
if (result){
pugi::xml_node rootNode = doc.child("framework");
if(flag != LoadConfigFlag::ONLY_MODULE_CONFIG) {
// parse <execution> tag (or deprecated <executionManager>)
parseExecution(rootNode);
// parse <moduleToEnable> tag (or deprecated <modulesToLoad>)
parseModulesToEnable(rootNode);
}
// parse all <module> tags
parseModules(rootNode, file, flag);
// parse all <include> tags
parseIncludes(rootNode, file, flag);
} else {
logger.error() << "Failed to parse " << file << " as XML";
}
} else {
logger.error() << "Failed to open XML file " << file;
}
}
void Framework::parseExecution(pugi::xml_node rootNode) {
pugi::xml_node execNode = rootNode.child("execution");
if(!execNode) {
execNode = rootNode.child("executionManager");
if(execNode) {
logger.warn("parseExecution")
<< "Found deprecated tag <executionManager>, use <execution> instead";
} else {
// do not parse anything
return;
}
}
pugi::xml_node threadPoolNode = execNode.child("maxThreadCount");
if(threadPoolNode) {
int maxThreads = atoi(threadPoolNode.child_value());
executionManager.setMaxThreads(maxThreads);
logger.info("parseExecution") << "Thread pool size: " << maxThreads;
}
pugi::xml_node clockNode = execNode.child("clock");
if(clockNode) {
std::string clockUnit;
std::int64_t clockValue = atoll(clockNode.child_value());
pugi::xml_attribute enabledAttr = clockNode.attribute("enable");
pugi::xml_attribute unitAttr = clockNode.attribute("unit");
if(enabledAttr) {
clockEnabled = enabledAttr.as_bool();
} else {
// if no enabled attribute is given then the clock is considered
// to be enabled
clockEnabled = true;
}
if(unitAttr) {
clockUnit = unitAttr.value();
} else {
logger.warn("parseExecution")
<< "Missing attribute unit=\"hz/ms/us\" for tag <clock>";
clockEnabled = false;
}
if(clockEnabled) {
if(clockUnit == "hz") {
clock.cycleTime(extra::PrecisionTime::fromMicros(1000000 / clockValue));
} else if(clockUnit == "ms") {
clock.cycleTime(extra::PrecisionTime::fromMillis(clockValue));
} else if(clockUnit == "us") {
clock.cycleTime(extra::PrecisionTime::fromMicros(clockValue));
} else {
logger.error("parseConfig")
<< "Invalid value for attribute unit in <clock>: "
<< clockUnit;
clockEnabled = false;
}
}
}
if(clockEnabled) {
logger.info("parseConfig") << "Enabled clock with " << clock.cycleTime();
} else {
logger.info("parseConfig") << "Disabled clock";
}
pugi::xml_node configMonitorNode = execNode.child("configMonitor");
if(configMonitorNode) {
std::string configMonitorText = configMonitorNode.child_value();
if(configMonitorText == "true") {
monitorEnabled = true;
} else if(configMonitorText == "false") {
monitorEnabled = false;
} else {
logger.warn("parseConfig") << "Invalid value for <configMonitor>";
}
}
if(monitorEnabled) {
logger.info("parseConfig") << "Enabled config monitor";
} else {
logger.info("parseConfig") << "Disable config monitor";
}
}
void Framework::parseModulesToEnable(pugi::xml_node rootNode) {
pugi::xml_node enableNode = rootNode.child("modulesToEnable");
if(! enableNode) {
enableNode = rootNode.child("modulesToLoad");
if(enableNode) {
logger.warn("parseModulesToEnable")
<< "Found deprecated tag <modulesToLoad>, use <modulesToEnable> instead";
} else {
// do not parse anything
return;
}
}
lms::logging::LogLevel defaultModuleLevel = lms::logging::SMALLEST_LEVEL;
// get attribute "logLevel" of node <modulesToLoad>
// its value will be the default for logLevel of <module>
pugi::xml_attribute globalLogLevelAttr = enableNode.attribute("logLevel");
if(globalLogLevelAttr) {
defaultModuleLevel = lms::logging::levelFromName(globalLogLevelAttr.value());
}
for (pugi::xml_node moduleNode : enableNode.children("module")){
//parse module content
ModuleToLoad mod;
mod.name = moduleNode.child_value();
// get the attribute "logLevel"
pugi::xml_attribute logLevelAttr = moduleNode.attribute("logLevel");
if(logLevelAttr) {
mod.logLevel = lms::logging::levelFromName(logLevelAttr.value());
} else {
mod.logLevel = defaultModuleLevel;
}
tempModulesToLoadList.push_back(mod);
}
}
void Framework::parseModules(pugi::xml_node rootNode,
const std::string ¤tFile,
LoadConfigFlag flag) {
// parse all <module> nodes
for (pugi::xml_node moduleNode : rootNode.children("module")) {
Loader::module_entry module;
std::map<std::string, type::ModuleConfig> configMap;
module.name = moduleNode.child("name").child_value();
logger.info("parseModules") << "Found def for module " << module.name;
pugi::xml_node libpathNode = moduleNode.child("libpath");
pugi::xml_node libnameNode = moduleNode.child("libname");
std::string libname;
if(libnameNode) {
libname = Loader::getModulePath(libnameNode.child_value());
} else {
libname = Loader::getModulePath(module.name);
}
if(libpathNode) {
// TODO better relative path here
module.libpath = externalDirectory + "/modules/" +
libpathNode.child_value() + "/" + libname;
} else {
module.libpath = externalDirectory + "/modules/" + module.name + "/"
+ libname;
}
pugi::xml_node writePrioNode = moduleNode.child("writePriority");
if(writePrioNode) {
module.writePriority = atoi(writePrioNode.child_value());
} else {
module.writePriority = 0;
}
// parse all channel mappings
for(pugi::xml_node mappingNode : moduleNode.children("channelMapping")) {
pugi::xml_attribute fromAttr = mappingNode.attribute("from");
pugi::xml_attribute toAttr = mappingNode.attribute("to");
if(fromAttr && toAttr) {
module.channelMapping[fromAttr.value()] = toAttr.value();
} else {
logger.warn("parseModules")
<< "Tag <channelMapping> requires from and to attributes";
}
}
// parse all config
for(pugi::xml_node configNode : moduleNode.children("config")) {
pugi::xml_attribute srcAttr = configNode.attribute("src");
pugi::xml_attribute nameAttr = configNode.attribute("name");
std::string name = "default";
if(nameAttr) {
name = nameAttr.value();
}
if(srcAttr) {
std::string lconfPath = srcAttr.value();
if(extra::isAbsolute(lconfPath)) {
lconfPath = configsDirectory + lconfPath;
} else {
lconfPath = extra::dirname(currentFile) + "/" + lconfPath;
}
bool loadResult = configMap[name].loadFromFile(lconfPath);
if(!loadResult) {
logger.error("parseModules") << "Tried to load "
<< srcAttr.value() << " for " << module.name << " but failed";
} else {
logger.info("parseModules") << "Loaded " << lconfPath;
if(!monitor.watch(lconfPath)) {
logger.error("parseModules") << "Failed to monitor "
<< lconfPath;
}
}
} else {
// if there was no src attribut then parse the tag's content
for (pugi::xml_node configPropNode: configNode.children()) {
logger.debug("parseModules") << configPropNode.name();
configMap[name].set(configPropNode.name(),
std::string(configPropNode.child_value()));
}
}
}
for(std::pair<std::string, type::ModuleConfig> pair : configMap) {
executionManager.getDataManager()
.setChannel<type::ModuleConfig>(
"CONFIG_" + module.name + "_" + pair.first, pair.second);
}
if(flag != LoadConfigFlag::ONLY_MODULE_CONFIG) {
executionManager.addAvailableModule(module);
}
}
}
void Framework::parseIncludes(pugi::xml_node rootNode,
const std::string ¤tFile,
LoadConfigFlag flag) {
for(pugi::xml_node includeNode : rootNode.children("include")) {
pugi::xml_attribute srcAttr = includeNode.attribute("src");
if(srcAttr) {
logger.info("parseIncludes") << "Found include " << srcAttr.value();
std::string includePath = srcAttr.value();
if(extra::isAbsolute(includePath)) {
// if absolute then start from configs dir
includePath = configsDirectory + includePath;
} else {
// otherwise go from current file's directory
includePath = extra::dirname(currentFile) + "/" + includePath;
}
parseFile(includePath, flag);
} else {
logger.error("Include tag has no src attribute");
}
}
}
Framework::~Framework() {
logger.info() << "Removing Signal listeners";
SignalHandler::getInstance()
.removeListener(SIGINT, this)
.removeListener(SIGSEGV, this);
}
void Framework::signal(int s) {
switch (s) {
case SIGINT:
running = false;
logger.warn() << "Terminating after next Cycle. Press CTRL+C again to terminate immediately";
SignalHandler::getInstance().removeListener(SIGINT, this);
break;
case SIGSEGV:
//Segmentation Fault - try to identify what went wrong;
logger.error()
<< "######################################################" << std::endl
<< " Segfault Found " << std::endl
<< "######################################################";
//In Case of Segfault while recovering - shutdown.
SignalHandler::getInstance().removeListener(SIGSEGV, this);
extra::printStacktrace();
exit(EXIT_FAILURE);
break;
}
}
}
<commit_msg>Add additional checks for monitor.watch in Framework<commit_after>#include <lms/framework.h>
#include <lms/executionmanager.h>
#include <pugixml.hpp>
#include <fstream>
#include <csignal>
#include <map>
#include <cstdlib>
#include "lms/extra/backtrace_formatter.h"
#include "lms/logging/log_level.h"
#include "lms/extra/time.h"
#include "unistd.h"
#include "lms/type/module_config.h"
#include "lms/extra/string.h"
namespace lms{
std::string Framework::externalDirectory = EXTERNAL_DIR;
std::string Framework::configsDirectory = CONFIGS_DIR;
Framework::Framework(const ArgumentHandler &arguments) :
logger("FRAMEWORK", &rootLogger), argumentHandler(arguments), executionManager(rootLogger),
clockEnabled(false), clock(rootLogger), monitorEnabled(false) {
rootLogger.filter(std::unique_ptr<logging::LoggingFilter>(new logging::PrefixAndLevelFilter(
arguments.argLoggingMinLevel(), arguments.argLoggingPrefixes())));
SignalHandler::getInstance()
.addListener(SIGINT, this)
.addListener(SIGSEGV, this);
logger.info() << "RunLevel " << arguments.argRunLevel();
//parse framework config
if(arguments.argRunLevel() >= RunLevel::CONFIG) {
parseConfig(LoadConfigFlag::LOAD_EVERYTHING);
}
if(arguments.argRunLevel() >= RunLevel::ENABLE) {
// enable modules after they were made available
logger.info() << "Start enabling modules";
for(ModuleToLoad mod : tempModulesToLoadList) {
executionManager.enableModule(mod.name, mod.logLevel);
}
if(arguments.argRunLevel() == RunLevel::ENABLE) {
executionManager.getDataManager().printMapping();
executionManager.validate();
executionManager.printCycleList();
}
}
if(arguments.argRunLevel() >= RunLevel::CYCLE) {
//Execution
running = true;
while(running) {
if(clockEnabled) {
clock.beforeLoopIteration();
}
executionManager.loop();
if(clockEnabled) {
clock.afterLoopIteration();
}
if(lms::extra::FILE_MONITOR_SUPPORTED && monitorEnabled
&& monitor.hasChangedFiles()) {
monitor.unwatchAll();
parseConfig(LoadConfigFlag::ONLY_MODULE_CONFIG);
}
}
}
}
/*
* TODO suffix for config
*/
void Framework::parseConfig(LoadConfigFlag flag){
logger.debug("parseConfig") << "EXTERNAL: " << externalDirectory
<< std::endl << "CONFIGS: " << configsDirectory;
std::string configPath = configsDirectory + "/";
if(argumentHandler.argLoadConfiguration().empty()) {
configPath += "framework_conf.xml";
} else {
configPath += argumentHandler.argLoadConfiguration() + ".xml";
}
parseFile(configPath, flag);
}
void Framework::parseFile(const std::string &file, LoadConfigFlag flag) {
logger.debug("parseFile") << "Reading XML file: " << file;
if(lms::extra::FILE_MONITOR_SUPPORTED && monitorEnabled
&& !monitor.watch(file)) {
logger.error("parseFile") << "Could not monitor " << file;
}
std::ifstream ifs;
ifs.open (file, std::ifstream::in);
if(ifs.is_open()){
pugi::xml_document doc;
pugi::xml_parse_result result = doc.load(ifs);
if (result){
pugi::xml_node rootNode = doc.child("framework");
if(flag != LoadConfigFlag::ONLY_MODULE_CONFIG) {
// parse <execution> tag (or deprecated <executionManager>)
parseExecution(rootNode);
// parse <moduleToEnable> tag (or deprecated <modulesToLoad>)
parseModulesToEnable(rootNode);
}
// parse all <module> tags
parseModules(rootNode, file, flag);
// parse all <include> tags
parseIncludes(rootNode, file, flag);
} else {
logger.error() << "Failed to parse " << file << " as XML";
}
} else {
logger.error() << "Failed to open XML file " << file;
}
}
void Framework::parseExecution(pugi::xml_node rootNode) {
pugi::xml_node execNode = rootNode.child("execution");
if(!execNode) {
execNode = rootNode.child("executionManager");
if(execNode) {
logger.warn("parseExecution")
<< "Found deprecated tag <executionManager>, use <execution> instead";
} else {
// do not parse anything
return;
}
}
pugi::xml_node threadPoolNode = execNode.child("maxThreadCount");
if(threadPoolNode) {
int maxThreads = atoi(threadPoolNode.child_value());
executionManager.setMaxThreads(maxThreads);
logger.info("parseExecution") << "Thread pool size: " << maxThreads;
}
pugi::xml_node clockNode = execNode.child("clock");
if(clockNode) {
std::string clockUnit;
std::int64_t clockValue = atoll(clockNode.child_value());
pugi::xml_attribute enabledAttr = clockNode.attribute("enable");
pugi::xml_attribute unitAttr = clockNode.attribute("unit");
if(enabledAttr) {
clockEnabled = enabledAttr.as_bool();
} else {
// if no enabled attribute is given then the clock is considered
// to be enabled
clockEnabled = true;
}
if(unitAttr) {
clockUnit = unitAttr.value();
} else {
logger.warn("parseExecution")
<< "Missing attribute unit=\"hz/ms/us\" for tag <clock>";
clockEnabled = false;
}
if(clockEnabled) {
if(clockUnit == "hz") {
clock.cycleTime(extra::PrecisionTime::fromMicros(1000000 / clockValue));
} else if(clockUnit == "ms") {
clock.cycleTime(extra::PrecisionTime::fromMillis(clockValue));
} else if(clockUnit == "us") {
clock.cycleTime(extra::PrecisionTime::fromMicros(clockValue));
} else {
logger.error("parseConfig")
<< "Invalid value for attribute unit in <clock>: "
<< clockUnit;
clockEnabled = false;
}
}
}
if(clockEnabled) {
logger.info("parseConfig") << "Enabled clock with " << clock.cycleTime();
} else {
logger.info("parseConfig") << "Disabled clock";
}
pugi::xml_node configMonitorNode = execNode.child("configMonitor");
if(configMonitorNode) {
std::string configMonitorText = configMonitorNode.child_value();
if(configMonitorText == "true") {
monitorEnabled = true;
} else if(configMonitorText == "false") {
monitorEnabled = false;
} else {
logger.warn("parseConfig") << "Invalid value for <configMonitor>";
}
}
if(monitorEnabled) {
logger.info("parseConfig") << "Enabled config monitor";
} else {
logger.info("parseConfig") << "Disable config monitor";
}
}
void Framework::parseModulesToEnable(pugi::xml_node rootNode) {
pugi::xml_node enableNode = rootNode.child("modulesToEnable");
if(! enableNode) {
enableNode = rootNode.child("modulesToLoad");
if(enableNode) {
logger.warn("parseModulesToEnable")
<< "Found deprecated tag <modulesToLoad>, use <modulesToEnable> instead";
} else {
// do not parse anything
return;
}
}
lms::logging::LogLevel defaultModuleLevel = lms::logging::SMALLEST_LEVEL;
// get attribute "logLevel" of node <modulesToLoad>
// its value will be the default for logLevel of <module>
pugi::xml_attribute globalLogLevelAttr = enableNode.attribute("logLevel");
if(globalLogLevelAttr) {
defaultModuleLevel = lms::logging::levelFromName(globalLogLevelAttr.value());
}
for (pugi::xml_node moduleNode : enableNode.children("module")){
//parse module content
ModuleToLoad mod;
mod.name = moduleNode.child_value();
// get the attribute "logLevel"
pugi::xml_attribute logLevelAttr = moduleNode.attribute("logLevel");
if(logLevelAttr) {
mod.logLevel = lms::logging::levelFromName(logLevelAttr.value());
} else {
mod.logLevel = defaultModuleLevel;
}
tempModulesToLoadList.push_back(mod);
}
}
void Framework::parseModules(pugi::xml_node rootNode,
const std::string ¤tFile,
LoadConfigFlag flag) {
// parse all <module> nodes
for (pugi::xml_node moduleNode : rootNode.children("module")) {
Loader::module_entry module;
std::map<std::string, type::ModuleConfig> configMap;
module.name = moduleNode.child("name").child_value();
logger.info("parseModules") << "Found def for module " << module.name;
pugi::xml_node libpathNode = moduleNode.child("libpath");
pugi::xml_node libnameNode = moduleNode.child("libname");
std::string libname;
if(libnameNode) {
libname = Loader::getModulePath(libnameNode.child_value());
} else {
libname = Loader::getModulePath(module.name);
}
if(libpathNode) {
// TODO better relative path here
module.libpath = externalDirectory + "/modules/" +
libpathNode.child_value() + "/" + libname;
} else {
module.libpath = externalDirectory + "/modules/" + module.name + "/"
+ libname;
}
pugi::xml_node writePrioNode = moduleNode.child("writePriority");
if(writePrioNode) {
module.writePriority = atoi(writePrioNode.child_value());
} else {
module.writePriority = 0;
}
// parse all channel mappings
for(pugi::xml_node mappingNode : moduleNode.children("channelMapping")) {
pugi::xml_attribute fromAttr = mappingNode.attribute("from");
pugi::xml_attribute toAttr = mappingNode.attribute("to");
if(fromAttr && toAttr) {
module.channelMapping[fromAttr.value()] = toAttr.value();
} else {
logger.warn("parseModules")
<< "Tag <channelMapping> requires from and to attributes";
}
}
// parse all config
for(pugi::xml_node configNode : moduleNode.children("config")) {
pugi::xml_attribute srcAttr = configNode.attribute("src");
pugi::xml_attribute nameAttr = configNode.attribute("name");
std::string name = "default";
if(nameAttr) {
name = nameAttr.value();
}
if(srcAttr) {
std::string lconfPath = srcAttr.value();
if(extra::isAbsolute(lconfPath)) {
lconfPath = configsDirectory + lconfPath;
} else {
lconfPath = extra::dirname(currentFile) + "/" + lconfPath;
}
bool loadResult = configMap[name].loadFromFile(lconfPath);
if(!loadResult) {
logger.error("parseModules") << "Tried to load "
<< srcAttr.value() << " for " << module.name << " but failed";
} else {
logger.info("parseModules") << "Loaded " << lconfPath;
if(lms::extra::FILE_MONITOR_SUPPORTED && monitorEnabled
&& !monitor.watch(lconfPath)) {
logger.error("parseModules") << "Failed to monitor "
<< lconfPath;
}
}
} else {
// if there was no src attribut then parse the tag's content
for (pugi::xml_node configPropNode: configNode.children()) {
logger.debug("parseModules") << configPropNode.name();
configMap[name].set(configPropNode.name(),
std::string(configPropNode.child_value()));
}
}
}
for(std::pair<std::string, type::ModuleConfig> pair : configMap) {
executionManager.getDataManager()
.setChannel<type::ModuleConfig>(
"CONFIG_" + module.name + "_" + pair.first, pair.second);
}
if(flag != LoadConfigFlag::ONLY_MODULE_CONFIG) {
executionManager.addAvailableModule(module);
}
}
}
void Framework::parseIncludes(pugi::xml_node rootNode,
const std::string ¤tFile,
LoadConfigFlag flag) {
for(pugi::xml_node includeNode : rootNode.children("include")) {
pugi::xml_attribute srcAttr = includeNode.attribute("src");
if(srcAttr) {
logger.info("parseIncludes") << "Found include " << srcAttr.value();
std::string includePath = srcAttr.value();
if(extra::isAbsolute(includePath)) {
// if absolute then start from configs dir
includePath = configsDirectory + includePath;
} else {
// otherwise go from current file's directory
includePath = extra::dirname(currentFile) + "/" + includePath;
}
parseFile(includePath, flag);
} else {
logger.error("Include tag has no src attribute");
}
}
}
Framework::~Framework() {
logger.info() << "Removing Signal listeners";
SignalHandler::getInstance()
.removeListener(SIGINT, this)
.removeListener(SIGSEGV, this);
}
void Framework::signal(int s) {
switch (s) {
case SIGINT:
running = false;
logger.warn() << "Terminating after next Cycle. Press CTRL+C again to terminate immediately";
SignalHandler::getInstance().removeListener(SIGINT, this);
break;
case SIGSEGV:
//Segmentation Fault - try to identify what went wrong;
logger.error()
<< "######################################################" << std::endl
<< " Segfault Found " << std::endl
<< "######################################################";
//In Case of Segfault while recovering - shutdown.
SignalHandler::getInstance().removeListener(SIGSEGV, this);
extra::printStacktrace();
exit(EXIT_FAILURE);
break;
}
}
}
<|endoftext|> |
<commit_before>#include "./Common.h"
#include "KAI/Core/Object/GetStorageBase.h"
USING_NAMESPACE_KAI
class TestMap : public KAITestClass
{
protected:
void AddrequiredClasses() override
{
reg.AddClass<Map>();
}
};
TEST_F(TestMap, TestCreation)
{
Pointer<Map> map = reg.New<Map>();
ASSERT_TRUE(map.Exists());
ASSERT_TRUE(map->Size() == 0);
ASSERT_TRUE(map->Empty());
reg.GarbageCollect();
ASSERT_FALSE(map.Exists());
}
TEST_F(TestMap, TestInsertDelete)
{
Pointer<Map> map = reg.New<Map>();
Pointer<Map> dangling = reg.New<Map>();
// add the map to the root of the object tree, so it can be
// found and hence not GC'd
tree.GetRoot().Set("map", map);
reg.GarbageCollect();
// the map will still exist after the GC - but the `dangling` map
// won't because it can't be reached by the Registry reg
ASSERT_TRUE(map.Exists());
ASSERT_FALSE(dangling.Exists());
// make a key and a value to insert into map
Pointer<int> n = reg.New(42);
Pointer<String> s = reg.New<String>("Hello");
map->Insert(n, s);
ASSERT_TRUE(map->ContainsKey(n));
Object found = map->GetValue(n);
ASSERT_STREQ(ConstDeref<String>(found).c_str(), "Hello");
ASSERT_EQ(found.GetHandle(), s.GetHandle());
ASSERT_TRUE(map.Exists());
ASSERT_TRUE(n.Exists());
ASSERT_TRUE(found.Exists());
// by removing the key associated with n, we also remove the value
map->Erase(n);
reg.GarbageCollect();
// now, neither the key nor value should exist,
// but the map itself should exist because it was added
// to the root of the tree above
ASSERT_TRUE(map.Exists());
ASSERT_FALSE(n.Exists());
ASSERT_FALSE(found.Exists());
}
TEST_F(TestMap, TestComparison)
{
}
TEST_F(TestMap, TestStringStream)
{
}
TEST_F(TestMap, TestBinaryStream)
{
}
<commit_msg>Add MapTest::TestComparison<commit_after>#include "./Common.h"
#include "KAI/Core/Object/GetStorageBase.h"
USING_NAMESPACE_KAI
class TestMap : public KAITestClass
{
protected:
void AddrequiredClasses() override
{
reg.AddClass<Map>();
}
};
TEST_F(TestMap, TestCreation)
{
Pointer<Map> map = reg.New<Map>();
ASSERT_TRUE(map.Exists());
ASSERT_TRUE(map->Size() == 0);
ASSERT_TRUE(map->Empty());
reg.GarbageCollect();
ASSERT_FALSE(map.Exists());
}
TEST_F(TestMap, TestInsertDelete)
{
Pointer<Map> map = reg.New<Map>();
Pointer<Map> dangling = reg.New<Map>();
// add the map to the root of the object tree, so it can be
// found and hence not GC'd
tree.GetRoot().Set("map", map);
reg.GarbageCollect();
// the map will still exist after the GC - but the `dangling` map
// won't because it can't be reached by the Registry reg
ASSERT_TRUE(map.Exists());
ASSERT_FALSE(dangling.Exists());
// make a key and a value to insert into map
Pointer<int> n = reg.New(42);
Pointer<String> s = reg.New<String>("Hello");
map->Insert(n, s);
ASSERT_TRUE(map->ContainsKey(n));
Object found = map->GetValue(n);
ASSERT_STREQ(ConstDeref<String>(found).c_str(), "Hello");
ASSERT_EQ(found.GetHandle(), s.GetHandle());
ASSERT_TRUE(map.Exists());
ASSERT_TRUE(n.Exists());
ASSERT_TRUE(found.Exists());
// by removing the key associated with n, we also remove the value
map->Erase(n);
reg.GarbageCollect();
// now, neither the key nor value should exist,
// but the map itself should exist because it was added
// to the root of the tree above
ASSERT_TRUE(map.Exists());
ASSERT_FALSE(n.Exists());
ASSERT_FALSE(found.Exists());
}
TEST_F(TestMap, TestComparison)
{
Pointer<Map> m0 = reg.New<Map>();
Pointer<Map> m1 = reg.New<Map>();
Object n = reg.New(42);
Pointer<String> s0 = reg.New<String>("World");
Pointer<String> s1 = reg.New<String>("World");
// make two value-identical maps (but with different value objects)
m0->Insert(n, s0);
m1->Insert(n, s1);
// get a reference to the class for maps to make things easier to type
ClassBase const &k = *m0.GetClass();
// test that both maps are the same size and have same set of key/value pairs (by object value)
ASSERT_TRUE(k.Equiv(m0, m1));
// change the value that the second map has for it's key valued 42
*s1 = "Hello";
ASSERT_FALSE(k.Equiv(m0, m1));
// and just to prove that wasn't a fluke:
*s1 = "World";
ASSERT_TRUE(k.Equiv(m0, m1));
}
TEST_F(TestMap, TestStringStream)
{
}
TEST_F(TestMap, TestBinaryStream)
{
}
<|endoftext|> |
<commit_before>#include "player.hpp"
#include "lvl.hpp"
#include <vector>
#include <string>
#include <cstdio>
void fatal(const char*, ...);
struct Plat2d {
static const unsigned int Ops[];
static const unsigned int Nops;
enum { UnitCost = true };
typedef int Cost;
static const int InfCost = -1;
typedef int Oper;
static const int Nop = -1;
Plat2d(FILE*);
struct State {
State(void) { }
State(unsigned int x, unsigned int y, unsigned int z,
unsigned int w, unsigned int h) : player(x, y, z, w, h) { }
Player player;
};
struct PackedState {
// hash does nothing since the hash table
// for plat2d states doesn't store anything.
unsigned long hash(void) { return -1; }
bool eq(PackedState &) const {
fatal("Unimplemented");
return false;
}
double x, y, dy;
unsigned char z, jframes;
bool fall;
};
struct Undo {
Undo(State&, Oper) { }
};
State initialstate(void);
Cost h(State &s) {
return 0;
}
Cost d(State &s) {
return 0;
}
bool isgoal(State &s) {
Lvl::Blkinfo bi = lvl.majorblk(s.player.body.z, s.player.body.bbox);
const Tile &t = bi.tile;
return t.flags & Tile::Down;
}
unsigned int nops(State &s) {
return Nops;
}
Oper nthop(State &s, unsigned int n) {
return Ops[n];
}
Oper revop(State &s, Oper op) {
return Nop;
}
Cost opcost(State &s, Oper op) {
return 1;
}
void undo(State &s, Undo &u) { }
State &apply(State &buf, State &s, Oper op) {
assert (op != Nop);
buf = s;
buf.player.act(lvl, (unsigned int) op);
return buf;
}
void pack(PackedState &dst, State &src) {
dst.x = src.player.body.bbox.min.x;
dst.y = src.player.body.bbox.min.y;
dst.dy = src.player.body.dy;
dst.z = src.player.body.z;
dst.fall = src.player.body.fall;
dst.jframes = src.player.jframes;
}
State &unpack(State &buf, PackedState &pkd) {
buf.player.jframes = pkd.jframes;
buf.player.body.z = pkd.z;
buf.player.body.fall = pkd.fall;
buf.player.body.dy = pkd.dy;
buf.player.body.bbox.min.x = pkd.x;
buf.player.body.bbox.min.y = pkd.y;
buf.player.body.bbox.max.x = pkd.x + Player::Width;
buf.player.body.bbox.max.y = pkd.y + Player::Height;
return buf;
}
static void dumpstate(FILE *out, State &s) {
fprintf(out, "%g, %g\n", s.player.loc().x, s.player.loc().y);
}
Lvl &level(void) { return lvl; }
private:
Lvl lvl;
};
// controlstr converts a vector of controls to an ASCII string.
std::string controlstr(const std::vector<unsigned int>&);
// controlvec converts a string of controls back into a vector.
std::vector<unsigned int> controlvec(const std::string&);
<commit_msg>plat2d: more state packing. Pack the fall flag into the upper bit of jframes. This doesn't seem to save anything because of struct padding but it will stay because padding can change from compiler to compiler and system to system.<commit_after>#include "player.hpp"
#include "lvl.hpp"
#include <vector>
#include <string>
#include <cstdio>
void fatal(const char*, ...);
struct Plat2d {
static const unsigned int Ops[];
static const unsigned int Nops;
enum { UnitCost = true };
typedef int Cost;
static const int InfCost = -1;
typedef int Oper;
static const int Nop = -1;
Plat2d(FILE*);
struct State {
State(void) { }
State(unsigned int x, unsigned int y, unsigned int z,
unsigned int w, unsigned int h) : player(x, y, z, w, h) { }
Player player;
};
struct PackedState {
// hash does nothing since the hash table
// for plat2d states doesn't store anything.
unsigned long hash(void) { return -1; }
bool eq(PackedState &o) const {
return jframes == o.jframes &&
z == o.z &&
doubleeq(x, o.x) &&
doubleeq(y, o.y) &&
doubleeq(dy, o.dy);
}
double x, y, dy;
unsigned char z;
// The body's fall flag is packed as the high-order bit
// of jframes.
unsigned char jframes;
};
struct Undo {
Undo(State&, Oper) { }
};
State initialstate(void);
Cost h(State &s) {
return 0;
}
Cost d(State &s) {
return 0;
}
bool isgoal(State &s) {
Lvl::Blkinfo bi = lvl.majorblk(s.player.body.z, s.player.body.bbox);
const Tile &t = bi.tile;
return t.flags & Tile::Down;
}
unsigned int nops(State &s) {
return Nops;
}
Oper nthop(State &s, unsigned int n) {
return Ops[n];
}
Oper revop(State &s, Oper op) {
return Nop;
}
Cost opcost(State &s, Oper op) {
return 1;
}
void undo(State &s, Undo &u) { }
State &apply(State &buf, State &s, Oper op) {
assert (op != Nop);
buf = s;
buf.player.act(lvl, (unsigned int) op);
return buf;
}
void pack(PackedState &dst, State &src) {
dst.x = src.player.body.bbox.min.x;
dst.y = src.player.body.bbox.min.y;
dst.dy = src.player.body.dy;
dst.z = src.player.body.z;
dst.jframes = src.player.jframes;
if (src.player.body.fall)
dst.jframes |= 1 << 7;
}
State &unpack(State &buf, PackedState &pkd) {
buf.player.jframes = pkd.jframes & 0x7F;
buf.player.body.fall = pkd.jframes & (1 << 7);
buf.player.body.z = pkd.z;
buf.player.body.dy = pkd.dy;
buf.player.body.bbox.min.x = pkd.x;
buf.player.body.bbox.min.y = pkd.y;
buf.player.body.bbox.max.x = pkd.x + Player::Width;
buf.player.body.bbox.max.y = pkd.y + Player::Height;
return buf;
}
static void dumpstate(FILE *out, State &s) {
fprintf(out, "%g, %g\n", s.player.loc().x, s.player.loc().y);
}
Lvl &level(void) { return lvl; }
private:
Lvl lvl;
};
// controlstr converts a vector of controls to an ASCII string.
std::string controlstr(const std::vector<unsigned int>&);
// controlvec converts a string of controls back into a vector.
std::vector<unsigned int> controlvec(const std::string&);
<|endoftext|> |
<commit_before>/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "modules/canbus/canbus_component.h"
#include "modules/canbus/common/canbus_gflags.h"
#include "modules/canbus/vehicle/vehicle_factory.h"
#include "modules/common/adapters/adapter_gflags.h"
#include "modules/common/time/time.h"
#include "modules/common/util/util.h"
#include "modules/drivers/canbus/can_client/can_client_factory.h"
namespace apollo {
namespace canbus {
using apollo::common::ErrorCode;
using apollo::common::time::Clock;
using apollo::control::ControlCommand;
using apollo::drivers::canbus::CanClientFactory;
using apollo::guardian::GuardianCommand;
std::string CanbusComponent::Name() const { return FLAGS_canbus_module_name; }
CanbusComponent::CanbusComponent()
: monitor_logger_buffer_(
apollo::common::monitor::MonitorMessageItem::CANBUS) {}
bool CanbusComponent::Init() {
if (!GetProtoConfig(&canbus_conf_)) {
AERROR << "Unable to load canbus conf file: " << ConfigFilePath();
return false;
}
AINFO << "The canbus conf file is loaded: " << FLAGS_canbus_conf_file;
ADEBUG << "Canbus_conf:" << canbus_conf_.ShortDebugString();
// Init can client
auto can_factory = CanClientFactory::Instance();
can_factory->RegisterCanClients();
can_client_ = can_factory->CreateCANClient(canbus_conf_.can_card_parameter());
if (!can_client_) {
AERROR << "Failed to create can client.";
return false;
}
AINFO << "Can client is successfully created.";
VehicleFactory vehicle_factory;
vehicle_factory.RegisterVehicleFactory();
auto vehicle_object =
vehicle_factory.CreateVehicle(canbus_conf_.vehicle_parameter());
if (!vehicle_object) {
AERROR << "Failed to create vehicle:";
return false;
}
message_manager_ = vehicle_object->CreateMessageManager();
if (message_manager_ == nullptr) {
AERROR << "Failed to create message manager.";
return false;
}
AINFO << "Message manager is successfully created.";
if (can_receiver_.Init(can_client_.get(), message_manager_.get(),
canbus_conf_.enable_receiver_log()) != ErrorCode::OK) {
AERROR << "Failed to init can receiver.";
return false;
}
AINFO << "The can receiver is successfully initialized.";
if (can_sender_.Init(can_client_.get(), canbus_conf_.enable_sender_log()) !=
ErrorCode::OK) {
AERROR << "Failed to init can sender.";
return false;
}
AINFO << "The can sender is successfully initialized.";
vehicle_controller_ = vehicle_object->CreateVehicleController();
if (vehicle_controller_ == nullptr) {
AERROR << "Failed to create vehicle controller.";
return false;
}
AINFO << "The vehicle controller is successfully created.";
if (vehicle_controller_->Init(canbus_conf_.vehicle_parameter(), &can_sender_,
message_manager_.get()) != ErrorCode::OK) {
AERROR << "Failed to init vehicle controller.";
return false;
}
AINFO << "The vehicle controller is successfully"
<< " initialized with canbus conf as : "
<< canbus_conf_.vehicle_parameter().ShortDebugString();
cybertron::ReaderConfig guardian_cmd_reader_config;
guardian_cmd_reader_config.channel_name = FLAGS_guardian_topic;
guardian_cmd_reader_config.pending_queue_size =
FLAGS_guardian_cmd_pending_queue_size;
cybertron::ReaderConfig control_cmd_reader_config;
control_cmd_reader_config.channel_name = FLAGS_control_command_topic;
control_cmd_reader_config.pending_queue_size =
FLAGS_control_cmd_pending_queue_size;
if (FLAGS_receive_guardian) {
guardian_cmd_reader_ = node_->CreateReader<GuardianCommand>(
guardian_cmd_reader_config,
[this](const std::shared_ptr<GuardianCommand> &cmd) {
ADEBUG << "Received guardian data: run canbus callback.";
OnGuardianCommand(*cmd);
});
} else {
control_command_reader_ = node_->CreateReader<ControlCommand>(
control_cmd_reader_config,
[this](const std::shared_ptr<ControlCommand> &cmd) {
ADEBUG << "Received control data: run canbus callback.";
OnControlCommand(*cmd);
});
}
chassis_writer_ = node_->CreateWriter<Chassis>(FLAGS_chassis_topic);
chassis_detail_writer_ =
node_->CreateWriter<ChassisDetail>(FLAGS_chassis_detail_topic);
// 1. init and start the can card hardware
if (can_client_->Start() != ErrorCode::OK) {
AERROR << "Failed to start can client";
return false;
}
AINFO << "Can client is started.";
// 2. start receive first then send
if (can_receiver_.Start() != ErrorCode::OK) {
AERROR << "Failed to start can receiver.";
return false;
}
AINFO << "Can receiver is started.";
// 3. start send
if (can_sender_.Start() != ErrorCode::OK) {
AERROR << "Failed to start can sender.";
return false;
}
// 4. start controller
if (vehicle_controller_->Start() == false) {
AERROR << "Failed to start vehicle controller.";
return false;
}
monitor_logger_buffer_.INFO("Canbus is started.");
return true;
}
void CanbusComponent::PublishChassis() {
Chassis chassis = vehicle_controller_->chassis();
common::util::FillHeader(node_->Name(), &chassis);
chassis_writer_->Write(std::make_shared<Chassis>(chassis));
ADEBUG << chassis.ShortDebugString();
}
void CanbusComponent::PublishChassisDetail() {
ChassisDetail chassis_detail;
message_manager_->GetSensorData(&chassis_detail);
ADEBUG << chassis_detail.ShortDebugString();
chassis_detail_writer_->Write(
std::make_shared<ChassisDetail>(chassis_detail));
}
bool CanbusComponent::Proc() {
PublishChassis();
if (FLAGS_enable_chassis_detail_pub) {
PublishChassisDetail();
}
return true;
}
void CanbusComponent::OnControlCommand(const ControlCommand &control_command) {
int64_t current_timestamp =
apollo::common::time::AsInt64<common::time::micros>(Clock::Now());
// if command coming too soon, just ignore it.
if (current_timestamp - last_timestamp_ < FLAGS_min_cmd_interval * 1000) {
ADEBUG << "Control command comes too soon. Ignore.\n Required "
"FLAGS_min_cmd_interval["
<< FLAGS_min_cmd_interval << "], actual time interval["
<< current_timestamp - last_timestamp_ << "].";
return;
}
last_timestamp_ = current_timestamp;
ADEBUG << "Control_sequence_number:"
<< control_command.header().sequence_num() << ", Time_of_delay:"
<< current_timestamp - control_command.header().timestamp_sec();
if (vehicle_controller_->Update(control_command) != ErrorCode::OK) {
AERROR << "Failed to process callback function OnControlCommand because "
"vehicle_controller_->Update error.";
return;
}
can_sender_.Update();
}
void CanbusComponent::OnGuardianCommand(
const GuardianCommand &guardian_command) {
apollo::control::ControlCommand control_command;
control_command.CopyFrom(guardian_command.control_command());
OnControlCommand(control_command);
}
common::Status CanbusComponent::OnError(const std::string &error_msg) {
monitor_logger_buffer_.ERROR(error_msg);
return ::apollo::common::Status(ErrorCode::CANBUS_ERROR, error_msg);
}
} // namespace canbus
} // namespace apollo
<commit_msg>canbus: fix lint error.<commit_after>/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "modules/canbus/canbus_component.h"
#include "modules/canbus/common/canbus_gflags.h"
#include "modules/canbus/vehicle/vehicle_factory.h"
#include "modules/common/adapters/adapter_gflags.h"
#include "modules/common/time/time.h"
#include "modules/common/util/util.h"
#include "modules/drivers/canbus/can_client/can_client_factory.h"
namespace apollo {
namespace canbus {
using apollo::common::ErrorCode;
using apollo::common::time::Clock;
using apollo::control::ControlCommand;
using apollo::drivers::canbus::CanClientFactory;
using apollo::guardian::GuardianCommand;
std::string CanbusComponent::Name() const { return FLAGS_canbus_module_name; }
CanbusComponent::CanbusComponent()
: monitor_logger_buffer_(
apollo::common::monitor::MonitorMessageItem::CANBUS) {}
bool CanbusComponent::Init() {
if (!GetProtoConfig(&canbus_conf_)) {
AERROR << "Unable to load canbus conf file: " << ConfigFilePath();
return false;
}
AINFO << "The canbus conf file is loaded: " << FLAGS_canbus_conf_file;
ADEBUG << "Canbus_conf:" << canbus_conf_.ShortDebugString();
// Init can client
auto can_factory = CanClientFactory::Instance();
can_factory->RegisterCanClients();
can_client_ = can_factory->CreateCANClient(canbus_conf_.can_card_parameter());
if (!can_client_) {
AERROR << "Failed to create can client.";
return false;
}
AINFO << "Can client is successfully created.";
VehicleFactory vehicle_factory;
vehicle_factory.RegisterVehicleFactory();
auto vehicle_object =
vehicle_factory.CreateVehicle(canbus_conf_.vehicle_parameter());
if (!vehicle_object) {
AERROR << "Failed to create vehicle:";
return false;
}
message_manager_ = vehicle_object->CreateMessageManager();
if (message_manager_ == nullptr) {
AERROR << "Failed to create message manager.";
return false;
}
AINFO << "Message manager is successfully created.";
if (can_receiver_.Init(can_client_.get(), message_manager_.get(),
canbus_conf_.enable_receiver_log()) != ErrorCode::OK) {
AERROR << "Failed to init can receiver.";
return false;
}
AINFO << "The can receiver is successfully initialized.";
if (can_sender_.Init(can_client_.get(), canbus_conf_.enable_sender_log()) !=
ErrorCode::OK) {
AERROR << "Failed to init can sender.";
return false;
}
AINFO << "The can sender is successfully initialized.";
vehicle_controller_ = vehicle_object->CreateVehicleController();
if (vehicle_controller_ == nullptr) {
AERROR << "Failed to create vehicle controller.";
return false;
}
AINFO << "The vehicle controller is successfully created.";
if (vehicle_controller_->Init(canbus_conf_.vehicle_parameter(), &can_sender_,
message_manager_.get()) != ErrorCode::OK) {
AERROR << "Failed to init vehicle controller.";
return false;
}
AINFO << "The vehicle controller is successfully"
<< " initialized with canbus conf as : "
<< canbus_conf_.vehicle_parameter().ShortDebugString();
cybertron::ReaderConfig guardian_cmd_reader_config;
guardian_cmd_reader_config.channel_name = FLAGS_guardian_topic;
guardian_cmd_reader_config.pending_queue_size =
FLAGS_guardian_cmd_pending_queue_size;
cybertron::ReaderConfig control_cmd_reader_config;
control_cmd_reader_config.channel_name = FLAGS_control_command_topic;
control_cmd_reader_config.pending_queue_size =
FLAGS_control_cmd_pending_queue_size;
if (FLAGS_receive_guardian) {
guardian_cmd_reader_ = node_->CreateReader<GuardianCommand>(
guardian_cmd_reader_config,
[this](const std::shared_ptr<GuardianCommand> &cmd) {
ADEBUG << "Received guardian data: run canbus callback.";
OnGuardianCommand(*cmd);
});
} else {
control_command_reader_ = node_->CreateReader<ControlCommand>(
control_cmd_reader_config,
[this](const std::shared_ptr<ControlCommand> &cmd) {
ADEBUG << "Received control data: run canbus callback.";
OnControlCommand(*cmd);
});
}
chassis_writer_ = node_->CreateWriter<Chassis>(FLAGS_chassis_topic);
chassis_detail_writer_ =
node_->CreateWriter<ChassisDetail>(FLAGS_chassis_detail_topic);
// 1. init and start the can card hardware
if (can_client_->Start() != ErrorCode::OK) {
AERROR << "Failed to start can client";
return false;
}
AINFO << "Can client is started.";
// 2. start receive first then send
if (can_receiver_.Start() != ErrorCode::OK) {
AERROR << "Failed to start can receiver.";
return false;
}
AINFO << "Can receiver is started.";
// 3. start send
if (can_sender_.Start() != ErrorCode::OK) {
AERROR << "Failed to start can sender.";
return false;
}
// 4. start controller
if (vehicle_controller_->Start() == false) {
AERROR << "Failed to start vehicle controller.";
return false;
}
monitor_logger_buffer_.INFO("Canbus is started.");
return true;
}
void CanbusComponent::PublishChassis() {
Chassis chassis = vehicle_controller_->chassis();
common::util::FillHeader(node_->Name(), &chassis);
chassis_writer_->Write(std::make_shared<Chassis>(chassis));
ADEBUG << chassis.ShortDebugString();
}
void CanbusComponent::PublishChassisDetail() {
ChassisDetail chassis_detail;
message_manager_->GetSensorData(&chassis_detail);
ADEBUG << chassis_detail.ShortDebugString();
chassis_detail_writer_->Write(
std::make_shared<ChassisDetail>(chassis_detail));
}
bool CanbusComponent::Proc() {
PublishChassis();
if (FLAGS_enable_chassis_detail_pub) {
PublishChassisDetail();
}
return true;
}
void CanbusComponent::OnControlCommand(const ControlCommand &control_command) {
int64_t current_timestamp =
apollo::common::time::AsInt64<common::time::micros>(Clock::Now());
// if command coming too soon, just ignore it.
if (current_timestamp - last_timestamp_ < FLAGS_min_cmd_interval * 1000) {
ADEBUG << "Control command comes too soon. Ignore.\n Required "
"FLAGS_min_cmd_interval["
<< FLAGS_min_cmd_interval << "], actual time interval["
<< current_timestamp - last_timestamp_ << "].";
return;
}
last_timestamp_ = current_timestamp;
ADEBUG << "Control_sequence_number:"
<< control_command.header().sequence_num() << ", Time_of_delay:"
<< current_timestamp - control_command.header().timestamp_sec();
if (vehicle_controller_->Update(control_command) != ErrorCode::OK) {
AERROR << "Failed to process callback function OnControlCommand because "
"vehicle_controller_->Update error.";
return;
}
can_sender_.Update();
}
void CanbusComponent::OnGuardianCommand(
const GuardianCommand &guardian_command) {
apollo::control::ControlCommand control_command;
control_command.CopyFrom(guardian_command.control_command());
OnControlCommand(control_command);
}
common::Status CanbusComponent::OnError(const std::string &error_msg) {
monitor_logger_buffer_.ERROR(error_msg);
return ::apollo::common::Status(ErrorCode::CANBUS_ERROR, error_msg);
}
} // namespace canbus
} // namespace apollo
<|endoftext|> |
<commit_before>// Copyright (c) 2020, Joseph Mirabel
// Authors: Joseph Mirabel (joseph.mirabel@laas.fr)
// Olivier Roussel (olivier.roussel@laas.fr)
//
// This file is part of hpp-core.
// hpp-core is free software: you can redistribute it
// and/or modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation, either version
// 3 of the License, or (at your option) any later version.
//
// hpp-core 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 Lesser Public License for more details. You should have
// received a copy of the GNU Lesser General Public License along with
// hpp-core. If not, see <http://www.gnu.org/licenses/>.
#include <pinocchio/multibody/model.hpp>
#include <hpp/pinocchio/device.hh>
#include <hpp/pinocchio/joint-collection.hh>
#include <hpp/core/path.hh>
#include <hpp/core/path-vector.hh>
#include <hpp/core/path-optimizer.hh>
#include <hpp/core/plugin.hh>
#include <hpp/core/problem.hh>
#include <hpp/core/problem-solver.hh>
#include <hpp/core/time-parameterization/piecewise-polynomial.hh>
#include <toppra/toppra.hpp>
#include <toppra/geometric_path.hpp>
#include <toppra/algorithm/toppra.hpp>
#include <toppra/constraint/linear_joint_velocity.hpp>
#include <toppra/constraint/linear_joint_acceleration.hpp>
#include <toppra/constraint/joint_torque/pinocchio.hpp>
namespace hpp {
namespace core {
class PathWrapper : public toppra::GeometricPath
{
public:
PathWrapper(PathPtr_t path)
: toppra::GeometricPath((int)path->outputSize(), (int)path->outputDerivativeSize()), path_(path)
{
}
toppra::Vector eval_single(toppra::value_type time, int order) const
{
bool success;
toppra::Vector res;
if (order == 0)
{
res = path_->eval(time, success);
assert(success);
}
else
{
res.resize(dof());
path_->derivative(res, time, order);
}
return res;
}
toppra::Bound pathInterval() const
{
const interval_t &tr = path_->timeRange();
return (toppra::Bound() << tr.first, tr.second).finished();
}
private:
PathPtr_t path_;
};
namespace pathOptimization
{
class TOPPRA;
typedef boost::shared_ptr<TOPPRA> TOPPRAPtr_t;
class TOPPRA : public PathOptimizer
{
public:
static TOPPRAPtr_t create(const Problem &p)
{
return TOPPRAPtr_t(new TOPPRA(p));
}
PathVectorPtr_t optimize(const PathVectorPtr_t &path)
{
using pinocchio::Model;
const Model &model = problem().robot()->model();
using namespace toppra::constraint;
// Create the TOPPRA constraints
toppra::LinearConstraintPtrs v{
std::make_shared<LinearJointVelocity>(
-model.velocityLimit, model.velocityLimit),
// std::make_shared<LinearJointAcceleration>(
// - 1000 * model.velocityLimit, 1000 * model.velocityLimit)};
std::make_shared<jointTorque::Pinocchio<Model>>(
model, toppra::Vector::Constant(model.nv, 0.00))};
PathWrapper pathWrapper(path);
toppra::algorithm::TOPPRA algo(v, pathWrapper);
algo.setN(50);
auto ret_code = algo.computePathParametrization();
if (ret_code != toppra::ReturnCode::OK)
{
std::stringstream ss;
ss << "TOPPRA failed, returned code: " << static_cast<int>(ret_code) << std::endl;
throw std::runtime_error(ss.str());
}
const auto out_data = algo.getParameterizationData();
// forward integration of time parameterization (trapezoidal integration)
assert(out_data.gridpoints.size() == out_data.parametrization.size());
const size_t num_pts = out_data.gridpoints.size();
auto sd = toppra::Vector(num_pts);
for (auto i = 0ul; i < num_pts; ++i)
{
sd[i] = std::sqrt(std::max(out_data.parametrization[i], 0.));
}
auto t = toppra::Vector(num_pts);
t[0] = 0.; // start time is 0
for (auto i = 1ul; i < num_pts; ++i)
{
const auto sd_avg = (sd[i - 1] + sd[i]) * 0.5;
const auto ds = out_data.gridpoints[i] - out_data.gridpoints[i - 1];
assert(sd_avg > 0.);
const auto dt = ds / sd_avg;
t[i] = t[i - 1] + dt;
}
// time parameterization based on linear interpolation
// TODO compute hermite cubic spline coefficients to build piecewise polynomial paramaterization
constexpr int order = 1;
typedef timeParameterization::PiecewisePolynomial<order> timeparm;
auto params = timeparm::ParameterMatrix_t(order + 1, num_pts - 1);
const auto& s = out_data.gridpoints;
for (auto i = 1ul; i < num_pts; ++i)
{
const auto dt = t[i] - t[i-1];
const auto dp = (s[i] - s[i-1]) / dt;
params(0, i-1) = s[i-1] - t[i-1] * dp;
params(1, i-1) = dp;
}
path->timeParameterization(TimeParameterizationPtr_t(new timeparm(params, t)),
interval_t(t[0], t[num_pts - 1]));
return path;
}
protected:
TOPPRA(const Problem &problem) : PathOptimizer(problem)
{
}
};
} // namespace pathOptimization
class TOPPRAPlugin : public ProblemSolverPlugin
{
public:
TOPPRAPlugin()
: ProblemSolverPlugin("TOPPRAPlugin", "0.0")
{
}
protected:
virtual bool impl_initialize(ProblemSolverPtr_t ps)
{
ps->pathOptimizers.add("TOPPRA", pathOptimization::TOPPRA::create);
return true;
}
};
} // namespace core
} // namespace hpp
HPP_CORE_DEFINE_PLUGIN(hpp::core::TOPPRAPlugin)
<commit_msg>[TOPPRA] Add some parameters + fix time parameterization.<commit_after>// Copyright (c) 2020, Joseph Mirabel
// Authors: Joseph Mirabel (joseph.mirabel@laas.fr)
// Olivier Roussel (olivier.roussel@laas.fr)
//
// This file is part of hpp-core.
// hpp-core is free software: you can redistribute it
// and/or modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation, either version
// 3 of the License, or (at your option) any later version.
//
// hpp-core 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 Lesser Public License for more details. You should have
// received a copy of the GNU Lesser General Public License along with
// hpp-core. If not, see <http://www.gnu.org/licenses/>.
#include <pinocchio/multibody/model.hpp>
#include <hpp/pinocchio/device.hh>
#include <hpp/pinocchio/joint-collection.hh>
#include <hpp/core/path.hh>
#include <hpp/core/path-vector.hh>
#include <hpp/core/path-optimizer.hh>
#include <hpp/core/plugin.hh>
#include <hpp/core/problem.hh>
#include <hpp/core/problem-solver.hh>
#include <hpp/core/time-parameterization/piecewise-polynomial.hh>
#include <toppra/toppra.hpp>
#include <toppra/geometric_path.hpp>
#include <toppra/algorithm/toppra.hpp>
#include <toppra/solver/glpk-wrapper.hpp>
#include <toppra/solver/qpOASES-wrapper.hpp>
#include <toppra/constraint/linear_joint_velocity.hpp>
#include <toppra/constraint/linear_joint_acceleration.hpp>
#include <toppra/constraint/joint_torque/pinocchio.hpp>
namespace hpp {
namespace core {
class PathWrapper : public toppra::GeometricPath
{
public:
PathWrapper(PathPtr_t path)
: toppra::GeometricPath((int)path->outputSize(), (int)path->outputDerivativeSize()), path_(path)
{
}
toppra::Vector eval_single(toppra::value_type time, int order) const
{
bool success;
toppra::Vector res;
if (order == 0)
{
res = path_->eval(time, success);
assert(success);
}
else
{
res.resize(dof());
path_->derivative(res, time, order);
}
return res;
}
toppra::Bound pathInterval() const
{
const interval_t &tr = path_->timeRange();
return (toppra::Bound() << tr.first, tr.second).finished();
}
private:
PathPtr_t path_;
};
#define PARAM_HEAD "PathOptimization/TOPPRA/"
namespace pathOptimization
{
class TOPPRA;
typedef boost::shared_ptr<TOPPRA> TOPPRAPtr_t;
class TOPPRA : public PathOptimizer
{
public:
static TOPPRAPtr_t create(const Problem &p)
{
return TOPPRAPtr_t(new TOPPRA(p));
}
PathVectorPtr_t optimize(const PathVectorPtr_t &path)
{
const size_type solver = problem().getParameter(PARAM_HEAD "solver").intValue();
const value_type effortScale = problem().getParameter(PARAM_HEAD "effortScale").floatValue();
const value_type velScale = problem().getParameter(PARAM_HEAD "velocityScale").floatValue();
using pinocchio::Model;
const Model &model = problem().robot()->model();
using namespace toppra::constraint;
// Create the TOPPRA constraints
auto torqueConstraint = std::make_shared<jointTorque::Pinocchio<Model> >
(model, toppra::Vector::Constant(model.nv, 0.)); // No friction
torqueConstraint->lowerBounds(effortScale * torqueConstraint->lowerBounds());
torqueConstraint->upperBounds(effortScale * torqueConstraint->upperBounds());
toppra::LinearConstraintPtrs v{
std::make_shared<LinearJointVelocity>(
-velScale * model.velocityLimit, velScale * model.velocityLimit)
//, std::make_shared<LinearJointAcceleration>(
//- 10 * model.velocityLimit, 10 * model.velocityLimit)
, torqueConstraint
};
std::shared_ptr<PathWrapper> pathWrapper (std::make_shared<PathWrapper>(path));
toppra::algorithm::TOPPRA algo(v, pathWrapper);
algo.setN((int)problem().getParameter(PARAM_HEAD "N").intValue());
switch(solver) {
default:
hppDout (error, "Solver " << solver << " does not exists. Using GLPK");
case 0:
algo.solver(std::make_shared<toppra::solver::GLPKWrapper>());
break;
case 1:
algo.solver(std::make_shared<toppra::solver::qpOASESWrapper>());
break;
}
auto ret_code = algo.computePathParametrization();
if (ret_code != toppra::ReturnCode::OK)
{
std::stringstream ss;
ss << "TOPPRA failed, returned code: " << static_cast<int>(ret_code) << std::endl;
throw std::runtime_error(ss.str());
}
const auto out_data = algo.getParameterizationData();
// forward integration of time parameterization (trapezoidal integration)
assert(out_data.gridpoints.size() == out_data.parametrization.size());
const size_t num_pts = out_data.gridpoints.size();
auto sd = toppra::Vector(num_pts);
for (auto i = 0ul; i < num_pts; ++i)
{
sd[i] = std::sqrt(std::max(out_data.parametrization[i], 0.));
}
auto t = toppra::Vector(num_pts);
t[0] = 0.; // start time is 0
for (auto i = 1ul; i < num_pts; ++i)
{
const auto sd_avg = (sd[i - 1] + sd[i]) * 0.5;
const auto ds = out_data.gridpoints[i] - out_data.gridpoints[i - 1];
assert(sd_avg > 0.);
const auto dt = ds / sd_avg;
t[i] = t[i - 1] + dt;
}
// time parameterization based on linear interpolation
// TODO compute hermite cubic spline coefficients to build piecewise polynomial paramaterization
constexpr int order = 1;
typedef timeParameterization::PiecewisePolynomial<order> timeparm;
auto params = timeparm::ParameterMatrix_t(order + 1, num_pts - 1);
const auto& s = out_data.gridpoints;
for (auto i = 1ul; i < num_pts; ++i)
{
const auto dt = t[i] - t[i-1];
const auto dp = (s[i] - s[i-1]) / dt;
params(0, i-1) = s[i-1] - t[i-1] * dp;
params(1, i-1) = dp;
}
PathVectorPtr_t res = PathVector::createCopy(path);
res->timeParameterization(TimeParameterizationPtr_t(new timeparm(params, t)),
interval_t(t[0], t[num_pts - 1]));
return res;
}
protected:
TOPPRA(const Problem &problem) : PathOptimizer(problem)
{
}
};
HPP_START_PARAMETER_DECLARATION(TOPPRA)
Problem::declareParameter(ParameterDescription (Parameter::FLOAT,
PARAM_HEAD "effortScale",
"Effort rescaling value.",
Parameter((value_type)1)));
Problem::declareParameter(ParameterDescription (Parameter::FLOAT,
PARAM_HEAD "velocityScale",
"Velocity rescaling value.",
Parameter((value_type)1)));
Problem::declareParameter(ParameterDescription (Parameter::INT,
PARAM_HEAD "solver",
"0: GLPK\n"
"1: qpOASES",
Parameter((size_type)1)));
Problem::declareParameter(ParameterDescription (Parameter::INT,
PARAM_HEAD "N",
"Number of sampling point.",
Parameter((size_type)50)));
HPP_END_PARAMETER_DECLARATION(TOPPRA)
} // namespace pathOptimization
class TOPPRAPlugin : public ProblemSolverPlugin
{
public:
TOPPRAPlugin()
: ProblemSolverPlugin("TOPPRAPlugin", "0.0")
{
}
protected:
virtual bool impl_initialize(ProblemSolverPtr_t ps)
{
ps->pathOptimizers.add("TOPPRA", pathOptimization::TOPPRA::create);
return true;
}
};
} // namespace core
} // namespace hpp
HPP_CORE_DEFINE_PLUGIN(hpp::core::TOPPRAPlugin)
<|endoftext|> |
<commit_before>#include "HTTPClientAndroidImpl.h"
#include "components/Exceptions.h"
#include "utils/AndroidUtils.h"
#include "utils/JNIUniqueGlobalRef.h"
#include "utils/Log.h"
#include <chrono>
#include <limits>
#include <regex>
#include <boost/lexical_cast.hpp>
namespace carto {
struct HTTPClient::AndroidImpl::URLClass {
JNIUniqueGlobalRef<jclass> clazz;
jmethodID constructor;
jmethodID openConnection;
explicit URLClass(JNIEnv* jenv) {
clazz = JNIUniqueGlobalRef<jclass>(jenv->NewGlobalRef(jenv->FindClass("java/net/URL")));
constructor = jenv->GetMethodID(clazz, "<init>", "(Ljava/lang/String;)V");
openConnection = jenv->GetMethodID(clazz, "openConnection", "()Ljava/net/URLConnection;");
}
};
struct HTTPClient::AndroidImpl::HttpURLConnectionClass {
JNIUniqueGlobalRef<jclass> clazz;
jmethodID setRequestMethod;
jmethodID setDoInput;
jmethodID setDoOutput;
jmethodID setUseCaches;
jmethodID setAllowUserInteraction;
jmethodID setInstanceFollowRedirects;
jmethodID setRequestProperty;
jmethodID connect;
jmethodID disconnect;
jmethodID getResponseCode;
jmethodID getHeaderFieldKey;
jmethodID getHeaderField;
jmethodID getInputStream;
jmethodID getOutputStream;
jmethodID getErrorStream;
explicit HttpURLConnectionClass(JNIEnv* jenv) {
clazz = JNIUniqueGlobalRef<jclass>(jenv->NewGlobalRef(jenv->FindClass("java/net/HttpURLConnection")));
setRequestMethod = jenv->GetMethodID(clazz, "setRequestMethod", "(Ljava/lang/String;)V");
setDoInput = jenv->GetMethodID(clazz, "setDoInput", "(Z)V");
setDoOutput = jenv->GetMethodID(clazz, "setDoOutput", "(Z)V");
setUseCaches = jenv->GetMethodID(clazz, "setUseCaches", "(Z)V");
setAllowUserInteraction = jenv->GetMethodID(clazz, "setAllowUserInteraction", "(Z)V");
setInstanceFollowRedirects = jenv->GetMethodID(clazz, "setInstanceFollowRedirects", "(Z)V");
setRequestProperty = jenv->GetMethodID(clazz, "setRequestProperty", "(Ljava/lang/String;Ljava/lang/String;)V");
connect = jenv->GetMethodID(clazz, "connect", "()V");
disconnect = jenv->GetMethodID(clazz, "disconnect", "()V");
getResponseCode = jenv->GetMethodID(clazz, "getResponseCode", "()I");
getHeaderFieldKey = jenv->GetMethodID(clazz, "getHeaderFieldKey", "(I)Ljava/lang/String;");
getHeaderField = jenv->GetMethodID(clazz, "getHeaderField", "(I)Ljava/lang/String;");
getInputStream = jenv->GetMethodID(clazz, "getInputStream", "()Ljava/io/InputStream;");
getOutputStream = jenv->GetMethodID(clazz, "getOutputStream", "()Ljava/io/OutputStream;");
getErrorStream = jenv->GetMethodID(clazz, "getErrorStream", "()Ljava/io/InputStream;");
}
};
struct HTTPClient::AndroidImpl::BufferedInputStreamClass {
JNIUniqueGlobalRef<jclass> clazz;
jmethodID constructor;
jmethodID read;
jmethodID close;
explicit BufferedInputStreamClass(JNIEnv* jenv) {
clazz = JNIUniqueGlobalRef<jclass>(jenv->NewGlobalRef(jenv->FindClass("java/io/BufferedInputStream")));
constructor = jenv->GetMethodID(clazz, "<init>", "(Ljava/io/InputStream;)V");
read = jenv->GetMethodID(clazz, "read", "([B)I");
close = jenv->GetMethodID(clazz, "close", "()V");
}
};
struct HTTPClient::AndroidImpl::OutputStreamClass {
JNIUniqueGlobalRef<jclass> clazz;
jmethodID write;
jmethodID close;
explicit OutputStreamClass(JNIEnv* jenv) {
clazz = JNIUniqueGlobalRef<jclass>(jenv->NewGlobalRef(jenv->FindClass("java/io/OutputStream")));
write = jenv->GetMethodID(clazz, "write", "([B)V");
close = jenv->GetMethodID(clazz, "close", "()V");
}
};
HTTPClient::AndroidImpl::AndroidImpl(bool log) :
_log(log)
{
}
bool HTTPClient::AndroidImpl::makeRequest(const HTTPClient::Request& request, HeadersFn headersFn, DataFn dataFn) const {
JNIEnv* jenv = AndroidUtils::GetCurrentThreadJNIEnv();
AndroidUtils::JNILocalFrame jframe(jenv, 32, "HTTPClient::AndroidImpl::HTTPClientAndroidImpl");
if (!jframe.isValid()) {
Log::Error("HTTPClient::AndroidImpl::makeRequest: JNILocalFrame not valid");
throw std::runtime_error("JNILocalFrame not valid");
}
{
std::lock_guard<std::mutex> lock(_Mutex);
if (!_URLClass) {
_URLClass = std::unique_ptr<URLClass>(new URLClass(jenv));
}
if (!_HttpURLConnectionClass) {
_HttpURLConnectionClass = std::unique_ptr<HttpURLConnectionClass>(new HttpURLConnectionClass(jenv));
}
if (!_BufferedInputStreamClass) {
_BufferedInputStreamClass = std::unique_ptr<BufferedInputStreamClass>(new BufferedInputStreamClass(jenv));
}
if (!_OutputStreamClass) {
_OutputStreamClass = std::unique_ptr<OutputStreamClass>(new OutputStreamClass(jenv));
}
}
// Create URL
jobject url = jenv->NewObject(_URLClass->clazz, _URLClass->constructor, jenv->NewStringUTF(request.url.c_str()));
if (jenv->ExceptionCheck()) {
jenv->ExceptionClear();
throw NetworkException("Invalid URL", request.url);
}
// Open HTTP connection
jobject conn = jenv->CallObjectMethod(url, _URLClass->openConnection);
if (jenv->ExceptionCheck()) {
jenv->ExceptionClear();
throw NetworkException("Unable to open connection", request.url);
}
// Configure connection parameters
jenv->CallVoidMethod(conn, _HttpURLConnectionClass->setRequestMethod, jenv->NewStringUTF("GET"));
jenv->CallVoidMethod(conn, _HttpURLConnectionClass->setDoInput, (jboolean)true);
jenv->CallVoidMethod(conn, _HttpURLConnectionClass->setDoOutput, (jboolean)!request.contentType.empty());
jenv->CallVoidMethod(conn, _HttpURLConnectionClass->setUseCaches, (jboolean)false);
jenv->CallVoidMethod(conn, _HttpURLConnectionClass->setAllowUserInteraction, (jboolean)false);
jenv->CallVoidMethod(conn, _HttpURLConnectionClass->setAllowUserInteraction, (jboolean)true);
// Set request headers
for (auto it = request.headers.begin(); it != request.headers.end(); it++) {
jstring key = jenv->NewStringUTF(it->first.c_str());
jstring value = jenv->NewStringUTF(it->second.c_str());
jenv->CallVoidMethod(conn, _HttpURLConnectionClass->setRequestProperty, key, value);
}
// If Content-Type is set, write request body to output stream
if (!request.contentType.empty()) {
jobject outputStream = jenv->CallObjectMethod(conn, _HttpURLConnectionClass->getOutputStream);
if (jenv->ExceptionCheck()) {
jenv->ExceptionClear();
throw NetworkException("Unable to get output stream", request.url);
}
jbyteArray jbuf = jenv->NewByteArray(request.body.size());
jenv->SetByteArrayRegion(jbuf, 0, request.body.size(), reinterpret_cast<const jbyte*>(request.body.data()));
jenv->CallVoidMethod(outputStream, _OutputStreamClass->write, jbuf);
if (jenv->ExceptionCheck()) {
jenv->ExceptionClear();
throw NetworkException("Unable to write data", request.url);
}
jenv->CallVoidMethod(outputStream, _OutputStreamClass->close);
if (jenv->ExceptionCheck()) {
jenv->ExceptionClear();
throw NetworkException("Unable to write data", request.url);
}
}
// Connect
jenv->CallVoidMethod(conn, _HttpURLConnectionClass->connect);
if (jenv->ExceptionCheck()) {
jenv->ExceptionClear();
throw NetworkException("Unable to connect", request.url);
}
// Read response header
jint responseCode = jenv->CallIntMethod(conn, _HttpURLConnectionClass->getResponseCode);
std::map<std::string, std::string> headers;
for (int i = 0; true; i++) {
jstring key = (jstring)jenv->CallObjectMethod(conn, _HttpURLConnectionClass->getHeaderFieldKey, (jint)i);
if (!key) {
break;
}
jstring value = (jstring)jenv->CallObjectMethod(conn, _HttpURLConnectionClass->getHeaderField, (jint)i);
const char* keyStr = jenv->GetStringUTFChars(key, NULL);
const char* valueStr = jenv->GetStringUTFChars(value, NULL);
headers[keyStr] = valueStr;
jenv->ReleaseStringUTFChars(value, valueStr);
jenv->ReleaseStringUTFChars(key, keyStr);
}
bool cancel = false;
if (!headersFn(responseCode, headers)) {
cancel = true;
}
// Read Content-Length
std::uint64_t contentLength = std::numeric_limits<std::uint64_t>::max();
auto it = headers.find("Content-Length");
if (it != headers.end()) {
contentLength = boost::lexical_cast<std::uint64_t>(it->second);
}
// Create BufferedInputStream for data
jobject inputStream = jenv->CallObjectMethod(conn, _HttpURLConnectionClass->getInputStream);
if (jenv->ExceptionCheck()) {
jenv->ExceptionClear();
inputStream = jenv->CallObjectMethod(conn, _HttpURLConnectionClass->getErrorStream);
}
jobject bufferedInputStream = jenv->NewObject(_BufferedInputStreamClass->clazz, _BufferedInputStreamClass->constructor, inputStream);
try {
jbyte buf[4096];
jbyteArray jbuf = jenv->NewByteArray(sizeof(buf));
for (std::uint64_t offset = 0; offset < contentLength && !cancel; ) {
jint numBytesRead = jenv->CallIntMethod(bufferedInputStream, _BufferedInputStreamClass->read, jbuf);
if (jenv->ExceptionCheck()) {
jenv->ExceptionClear();
throw NetworkException("Unable to read data", request.url);
}
if (numBytesRead < 0) {
if (contentLength == std::numeric_limits<std::uint64_t>::max()) {
break;
}
throw NetworkException("Unable to read full data", request.url);
}
jenv->GetByteArrayRegion(jbuf, 0, numBytesRead, buf);
if (!dataFn(reinterpret_cast<const unsigned char*>(&buf[0]), numBytesRead)) {
cancel = true;
}
offset += numBytesRead;
}
}
catch (...) {
jenv->CallVoidMethod(bufferedInputStream, _BufferedInputStreamClass->close);
if (jenv->ExceptionCheck()) {
jenv->ExceptionClear();
}
jenv->CallVoidMethod(conn, _HttpURLConnectionClass->disconnect);
throw;
}
// Done
jenv->CallVoidMethod(bufferedInputStream, _BufferedInputStreamClass->close);
if (jenv->ExceptionCheck()) {
jenv->ExceptionClear();
}
jenv->CallVoidMethod(conn, _HttpURLConnectionClass->disconnect);
return !cancel;
}
std::unique_ptr<HTTPClient::AndroidImpl::URLClass> HTTPClient::AndroidImpl::_URLClass;
std::unique_ptr<HTTPClient::AndroidImpl::HttpURLConnectionClass> HTTPClient::AndroidImpl::_HttpURLConnectionClass;
std::unique_ptr<HTTPClient::AndroidImpl::BufferedInputStreamClass> HTTPClient::AndroidImpl::_BufferedInputStreamClass;
std::unique_ptr<HTTPClient::AndroidImpl::OutputStreamClass> HTTPClient::AndroidImpl::_OutputStreamClass;
std::mutex HTTPClient::AndroidImpl::_Mutex;
}
<commit_msg>Additional JNI exception checks in Android HTTP library<commit_after>#include "HTTPClientAndroidImpl.h"
#include "components/Exceptions.h"
#include "utils/AndroidUtils.h"
#include "utils/JNIUniqueGlobalRef.h"
#include "utils/Log.h"
#include <chrono>
#include <limits>
#include <regex>
#include <boost/lexical_cast.hpp>
namespace carto {
struct HTTPClient::AndroidImpl::URLClass {
JNIUniqueGlobalRef<jclass> clazz;
jmethodID constructor;
jmethodID openConnection;
explicit URLClass(JNIEnv* jenv) {
clazz = JNIUniqueGlobalRef<jclass>(jenv->NewGlobalRef(jenv->FindClass("java/net/URL")));
constructor = jenv->GetMethodID(clazz, "<init>", "(Ljava/lang/String;)V");
openConnection = jenv->GetMethodID(clazz, "openConnection", "()Ljava/net/URLConnection;");
}
};
struct HTTPClient::AndroidImpl::HttpURLConnectionClass {
JNIUniqueGlobalRef<jclass> clazz;
jmethodID setRequestMethod;
jmethodID setDoInput;
jmethodID setDoOutput;
jmethodID setUseCaches;
jmethodID setAllowUserInteraction;
jmethodID setInstanceFollowRedirects;
jmethodID setRequestProperty;
jmethodID connect;
jmethodID disconnect;
jmethodID getResponseCode;
jmethodID getHeaderFieldKey;
jmethodID getHeaderField;
jmethodID getInputStream;
jmethodID getOutputStream;
jmethodID getErrorStream;
explicit HttpURLConnectionClass(JNIEnv* jenv) {
clazz = JNIUniqueGlobalRef<jclass>(jenv->NewGlobalRef(jenv->FindClass("java/net/HttpURLConnection")));
setRequestMethod = jenv->GetMethodID(clazz, "setRequestMethod", "(Ljava/lang/String;)V");
setDoInput = jenv->GetMethodID(clazz, "setDoInput", "(Z)V");
setDoOutput = jenv->GetMethodID(clazz, "setDoOutput", "(Z)V");
setUseCaches = jenv->GetMethodID(clazz, "setUseCaches", "(Z)V");
setAllowUserInteraction = jenv->GetMethodID(clazz, "setAllowUserInteraction", "(Z)V");
setInstanceFollowRedirects = jenv->GetMethodID(clazz, "setInstanceFollowRedirects", "(Z)V");
setRequestProperty = jenv->GetMethodID(clazz, "setRequestProperty", "(Ljava/lang/String;Ljava/lang/String;)V");
connect = jenv->GetMethodID(clazz, "connect", "()V");
disconnect = jenv->GetMethodID(clazz, "disconnect", "()V");
getResponseCode = jenv->GetMethodID(clazz, "getResponseCode", "()I");
getHeaderFieldKey = jenv->GetMethodID(clazz, "getHeaderFieldKey", "(I)Ljava/lang/String;");
getHeaderField = jenv->GetMethodID(clazz, "getHeaderField", "(I)Ljava/lang/String;");
getInputStream = jenv->GetMethodID(clazz, "getInputStream", "()Ljava/io/InputStream;");
getOutputStream = jenv->GetMethodID(clazz, "getOutputStream", "()Ljava/io/OutputStream;");
getErrorStream = jenv->GetMethodID(clazz, "getErrorStream", "()Ljava/io/InputStream;");
}
};
struct HTTPClient::AndroidImpl::BufferedInputStreamClass {
JNIUniqueGlobalRef<jclass> clazz;
jmethodID constructor;
jmethodID read;
jmethodID close;
explicit BufferedInputStreamClass(JNIEnv* jenv) {
clazz = JNIUniqueGlobalRef<jclass>(jenv->NewGlobalRef(jenv->FindClass("java/io/BufferedInputStream")));
constructor = jenv->GetMethodID(clazz, "<init>", "(Ljava/io/InputStream;)V");
read = jenv->GetMethodID(clazz, "read", "([B)I");
close = jenv->GetMethodID(clazz, "close", "()V");
}
};
struct HTTPClient::AndroidImpl::OutputStreamClass {
JNIUniqueGlobalRef<jclass> clazz;
jmethodID write;
jmethodID close;
explicit OutputStreamClass(JNIEnv* jenv) {
clazz = JNIUniqueGlobalRef<jclass>(jenv->NewGlobalRef(jenv->FindClass("java/io/OutputStream")));
write = jenv->GetMethodID(clazz, "write", "([B)V");
close = jenv->GetMethodID(clazz, "close", "()V");
}
};
HTTPClient::AndroidImpl::AndroidImpl(bool log) :
_log(log)
{
}
bool HTTPClient::AndroidImpl::makeRequest(const HTTPClient::Request& request, HeadersFn headersFn, DataFn dataFn) const {
JNIEnv* jenv = AndroidUtils::GetCurrentThreadJNIEnv();
AndroidUtils::JNILocalFrame jframe(jenv, 32, "HTTPClient::AndroidImpl::HTTPClientAndroidImpl");
if (!jframe.isValid()) {
Log::Error("HTTPClient::AndroidImpl::makeRequest: JNILocalFrame not valid");
throw std::runtime_error("JNILocalFrame not valid");
}
{
std::lock_guard<std::mutex> lock(_Mutex);
if (!_URLClass) {
_URLClass = std::unique_ptr<URLClass>(new URLClass(jenv));
}
if (!_HttpURLConnectionClass) {
_HttpURLConnectionClass = std::unique_ptr<HttpURLConnectionClass>(new HttpURLConnectionClass(jenv));
}
if (!_BufferedInputStreamClass) {
_BufferedInputStreamClass = std::unique_ptr<BufferedInputStreamClass>(new BufferedInputStreamClass(jenv));
}
if (!_OutputStreamClass) {
_OutputStreamClass = std::unique_ptr<OutputStreamClass>(new OutputStreamClass(jenv));
}
}
// Create URL
jobject url = jenv->NewObject(_URLClass->clazz, _URLClass->constructor, jenv->NewStringUTF(request.url.c_str()));
if (jenv->ExceptionCheck()) {
jenv->ExceptionClear();
throw NetworkException("Invalid URL", request.url);
}
// Open HTTP connection
jobject conn = jenv->CallObjectMethod(url, _URLClass->openConnection);
if (jenv->ExceptionCheck()) {
jenv->ExceptionClear();
throw NetworkException("Unable to open connection", request.url);
}
// Configure connection parameters
jenv->CallVoidMethod(conn, _HttpURLConnectionClass->setRequestMethod, jenv->NewStringUTF("GET"));
jenv->CallVoidMethod(conn, _HttpURLConnectionClass->setDoInput, (jboolean)true);
jenv->CallVoidMethod(conn, _HttpURLConnectionClass->setDoOutput, (jboolean)!request.contentType.empty());
jenv->CallVoidMethod(conn, _HttpURLConnectionClass->setUseCaches, (jboolean)false);
jenv->CallVoidMethod(conn, _HttpURLConnectionClass->setAllowUserInteraction, (jboolean)false);
jenv->CallVoidMethod(conn, _HttpURLConnectionClass->setAllowUserInteraction, (jboolean)true);
// Set request headers
for (auto it = request.headers.begin(); it != request.headers.end(); it++) {
jstring key = jenv->NewStringUTF(it->first.c_str());
jstring value = jenv->NewStringUTF(it->second.c_str());
jenv->CallVoidMethod(conn, _HttpURLConnectionClass->setRequestProperty, key, value);
}
// If Content-Type is set, write request body to output stream
if (!request.contentType.empty()) {
jobject outputStream = jenv->CallObjectMethod(conn, _HttpURLConnectionClass->getOutputStream);
if (jenv->ExceptionCheck()) {
jenv->ExceptionClear();
throw NetworkException("Unable to get output stream", request.url);
}
jbyteArray jbuf = jenv->NewByteArray(request.body.size());
jenv->SetByteArrayRegion(jbuf, 0, request.body.size(), reinterpret_cast<const jbyte*>(request.body.data()));
jenv->CallVoidMethod(outputStream, _OutputStreamClass->write, jbuf);
if (jenv->ExceptionCheck()) {
jenv->ExceptionClear();
throw NetworkException("Unable to write data", request.url);
}
jenv->CallVoidMethod(outputStream, _OutputStreamClass->close);
if (jenv->ExceptionCheck()) {
jenv->ExceptionClear();
throw NetworkException("Unable to write data", request.url);
}
}
// Connect
jenv->CallVoidMethod(conn, _HttpURLConnectionClass->connect);
if (jenv->ExceptionCheck()) {
jenv->ExceptionClear();
throw NetworkException("Unable to connect", request.url);
}
// Read response header
jint responseCode = jenv->CallIntMethod(conn, _HttpURLConnectionClass->getResponseCode);
if (jenv->ExceptionCheck()) {
jenv->ExceptionClear();
throw NetworkException("Unable to read response code", request.url);
}
std::map<std::string, std::string> headers;
for (int i = 0; true; i++) {
jstring key = (jstring)jenv->CallObjectMethod(conn, _HttpURLConnectionClass->getHeaderFieldKey, (jint)i);
if (!key) {
break;
}
jstring value = (jstring)jenv->CallObjectMethod(conn, _HttpURLConnectionClass->getHeaderField, (jint)i);
const char* keyStr = jenv->GetStringUTFChars(key, NULL);
const char* valueStr = jenv->GetStringUTFChars(value, NULL);
headers[keyStr] = valueStr;
jenv->ReleaseStringUTFChars(value, valueStr);
jenv->ReleaseStringUTFChars(key, keyStr);
}
bool cancel = false;
if (!headersFn(responseCode, headers)) {
cancel = true;
}
// Read Content-Length
std::uint64_t contentLength = std::numeric_limits<std::uint64_t>::max();
auto it = headers.find("Content-Length");
if (it != headers.end()) {
contentLength = boost::lexical_cast<std::uint64_t>(it->second);
}
// Create BufferedInputStream for data
jobject inputStream = jenv->CallObjectMethod(conn, _HttpURLConnectionClass->getInputStream);
if (jenv->ExceptionCheck()) {
jenv->ExceptionClear();
inputStream = jenv->CallObjectMethod(conn, _HttpURLConnectionClass->getErrorStream);
if (jenv->ExceptionCheck()) {
jenv->ExceptionClear();
throw NetworkException("Unable to get input stream", request.url);
}
}
jobject bufferedInputStream = jenv->NewObject(_BufferedInputStreamClass->clazz, _BufferedInputStreamClass->constructor, inputStream);
try {
jbyte buf[4096];
jbyteArray jbuf = jenv->NewByteArray(sizeof(buf));
for (std::uint64_t offset = 0; offset < contentLength && !cancel; ) {
jint numBytesRead = jenv->CallIntMethod(bufferedInputStream, _BufferedInputStreamClass->read, jbuf);
if (jenv->ExceptionCheck()) {
jenv->ExceptionClear();
throw NetworkException("Unable to read data", request.url);
}
if (numBytesRead < 0) {
if (contentLength == std::numeric_limits<std::uint64_t>::max()) {
break;
}
throw NetworkException("Unable to read full data", request.url);
}
jenv->GetByteArrayRegion(jbuf, 0, numBytesRead, buf);
if (!dataFn(reinterpret_cast<const unsigned char*>(&buf[0]), numBytesRead)) {
cancel = true;
}
offset += numBytesRead;
}
}
catch (...) {
jenv->CallVoidMethod(bufferedInputStream, _BufferedInputStreamClass->close);
if (jenv->ExceptionCheck()) {
jenv->ExceptionClear();
}
jenv->CallVoidMethod(conn, _HttpURLConnectionClass->disconnect);
throw;
}
// Done
jenv->CallVoidMethod(bufferedInputStream, _BufferedInputStreamClass->close);
if (jenv->ExceptionCheck()) {
jenv->ExceptionClear();
}
jenv->CallVoidMethod(conn, _HttpURLConnectionClass->disconnect);
return !cancel;
}
std::unique_ptr<HTTPClient::AndroidImpl::URLClass> HTTPClient::AndroidImpl::_URLClass;
std::unique_ptr<HTTPClient::AndroidImpl::HttpURLConnectionClass> HTTPClient::AndroidImpl::_HttpURLConnectionClass;
std::unique_ptr<HTTPClient::AndroidImpl::BufferedInputStreamClass> HTTPClient::AndroidImpl::_BufferedInputStreamClass;
std::unique_ptr<HTTPClient::AndroidImpl::OutputStreamClass> HTTPClient::AndroidImpl::_OutputStreamClass;
std::mutex HTTPClient::AndroidImpl::_Mutex;
}
<|endoftext|> |
<commit_before>//===- FileCheck.cpp - Check that File's Contents match what is expected --===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// FileCheck does a line-by line check of a file that validates whether it
// contains the expected content. This is useful for regression tests etc.
//
// This program exits with an error status of 2 on error, exit status of 0 if
// the file matched the expected contents, and exit status of 1 if it did not
// contain the expected contents.
//
//===----------------------------------------------------------------------===//
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/Support/SourceMgr.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/System/Signals.h"
using namespace llvm;
static cl::opt<std::string>
CheckFilename(cl::Positional, cl::desc("<check-file>"), cl::Required);
static cl::opt<std::string>
InputFilename("input-file", cl::desc("File to check (defaults to stdin)"),
cl::init("-"), cl::value_desc("filename"));
static cl::opt<std::string>
CheckPrefix("check-prefix", cl::init("CHECK"),
cl::desc("Prefix to use from check file (defaults to 'CHECK')"));
static cl::opt<bool>
NoCanonicalizeWhiteSpace("strict-whitespace",
cl::desc("Do not treat all horizontal whitespace as equivalent"));
/// CheckString - This is a check that we found in the input file.
struct CheckString {
/// Str - The string to match.
std::string Str;
/// Loc - The location in the match file that the check string was specified.
SMLoc Loc;
/// IsCheckNext - This is true if this is a CHECK-NEXT: directive (as opposed
/// to a CHECK: directive.
bool IsCheckNext;
CheckString(const std::string &S, SMLoc L, bool isCheckNext)
: Str(S), Loc(L), IsCheckNext(isCheckNext) {}
};
/// ReadCheckFile - Read the check file, which specifies the sequence of
/// expected strings. The strings are added to the CheckStrings vector.
static bool ReadCheckFile(SourceMgr &SM,
std::vector<CheckString> &CheckStrings) {
// Open the check file, and tell SourceMgr about it.
std::string ErrorStr;
MemoryBuffer *F =
MemoryBuffer::getFileOrSTDIN(CheckFilename.c_str(), &ErrorStr);
if (F == 0) {
errs() << "Could not open check file '" << CheckFilename << "': "
<< ErrorStr << '\n';
return true;
}
SM.AddNewSourceBuffer(F, SMLoc());
// Find all instances of CheckPrefix followed by : in the file.
StringRef Buffer = F->getBuffer();
while (1) {
// See if Prefix occurs in the memory buffer.
Buffer = Buffer.substr(Buffer.find(CheckPrefix));
// If we didn't find a match, we're done.
if (Buffer.empty())
break;
const char *CheckPrefixStart = Buffer.data();
// When we find a check prefix, keep track of whether we find CHECK: or
// CHECK-NEXT:
bool IsCheckNext;
// Verify that the : is present after the prefix.
if (Buffer[CheckPrefix.size()] == ':') {
Buffer = Buffer.substr(CheckPrefix.size()+1);
IsCheckNext = false;
} else if (Buffer.size() > CheckPrefix.size()+6 &&
memcmp(Buffer.data()+CheckPrefix.size(), "-NEXT:", 6) == 0) {
Buffer = Buffer.substr(CheckPrefix.size()+7);
IsCheckNext = true;
} else {
Buffer = Buffer.substr(1);
continue;
}
// Okay, we found the prefix, yay. Remember the rest of the line, but
// ignore leading and trailing whitespace.
while (!Buffer.empty() && (Buffer[0] == ' ' || Buffer[0] == '\t'))
Buffer = Buffer.substr(1);
// Scan ahead to the end of line.
size_t EOL = Buffer.find_first_of("\n\r");
if (EOL == StringRef::npos) EOL = Buffer.size();
// Ignore trailing whitespace.
while (EOL && (Buffer[EOL-1] == ' ' || Buffer[EOL-1] == '\t'))
--EOL;
// Check that there is something on the line.
if (EOL == 0) {
SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()),
"found empty check string with prefix '"+CheckPrefix+":'",
"error");
return true;
}
// Verify that CHECK-NEXT lines have at least one CHECK line before them.
if (IsCheckNext && CheckStrings.empty()) {
SM.PrintMessage(SMLoc::getFromPointer(CheckPrefixStart),
"found '"+CheckPrefix+"-NEXT:' without previous '"+
CheckPrefix+ ": line", "error");
return true;
}
// Okay, add the string we captured to the output vector and move on.
CheckStrings.push_back(CheckString(std::string(Buffer.data(),
Buffer.data()+EOL),
SMLoc::getFromPointer(Buffer.data()),
IsCheckNext));
Buffer = Buffer.substr(EOL);
}
if (CheckStrings.empty()) {
errs() << "error: no check strings found with prefix '" << CheckPrefix
<< ":'\n";
return true;
}
return false;
}
// CanonicalizeCheckStrings - Replace all sequences of horizontal whitespace in
// the check strings with a single space.
static void CanonicalizeCheckStrings(std::vector<CheckString> &CheckStrings) {
for (unsigned i = 0, e = CheckStrings.size(); i != e; ++i) {
std::string &Str = CheckStrings[i].Str;
for (unsigned C = 0; C != Str.size(); ++C) {
// If C is not a horizontal whitespace, skip it.
if (Str[C] != ' ' && Str[C] != '\t')
continue;
// Replace the character with space, then remove any other space
// characters after it.
Str[C] = ' ';
while (C+1 != Str.size() &&
(Str[C+1] == ' ' || Str[C+1] == '\t'))
Str.erase(Str.begin()+C+1);
}
}
}
/// CanonicalizeInputFile - Remove duplicate horizontal space from the specified
/// memory buffer, free it, and return a new one.
static MemoryBuffer *CanonicalizeInputFile(MemoryBuffer *MB) {
SmallVector<char, 16> NewFile;
NewFile.reserve(MB->getBufferSize());
for (const char *Ptr = MB->getBufferStart(), *End = MB->getBufferEnd();
Ptr != End; ++Ptr) {
// If C is not a horizontal whitespace, skip it.
if (*Ptr != ' ' && *Ptr != '\t') {
NewFile.push_back(*Ptr);
continue;
}
// Otherwise, add one space and advance over neighboring space.
NewFile.push_back(' ');
while (Ptr+1 != End &&
(Ptr[1] == ' ' || Ptr[1] == '\t'))
++Ptr;
}
// Free the old buffer and return a new one.
MemoryBuffer *MB2 =
MemoryBuffer::getMemBufferCopy(NewFile.data(),
NewFile.data() + NewFile.size(),
MB->getBufferIdentifier());
delete MB;
return MB2;
}
static void PrintCheckFailed(const SourceMgr &SM, const CheckString &CheckStr,
StringRef Buffer) {
// Otherwise, we have an error, emit an error message.
SM.PrintMessage(CheckStr.Loc, "expected string not found in input",
"error");
// Print the "scanning from here" line. If the current position is at the
// end of a line, advance to the start of the next line.
Buffer = Buffer.substr(Buffer.find_first_not_of(" \t\n\r"));
SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), "scanning from here",
"note");
}
static unsigned CountNumNewlinesBetween(const char *Start, const char *End) {
unsigned NumNewLines = 0;
for (; Start != End; ++Start) {
// Scan for newline.
if (Start[0] != '\n' && Start[0] != '\r')
continue;
++NumNewLines;
// Handle \n\r and \r\n as a single newline.
if (Start+1 != End &&
(Start[0] == '\n' || Start[0] == '\r') &&
(Start[0] != Start[1]))
++Start;
}
return NumNewLines;
}
int main(int argc, char **argv) {
sys::PrintStackTraceOnErrorSignal();
PrettyStackTraceProgram X(argc, argv);
cl::ParseCommandLineOptions(argc, argv);
SourceMgr SM;
// Read the expected strings from the check file.
std::vector<CheckString> CheckStrings;
if (ReadCheckFile(SM, CheckStrings))
return 2;
// Remove duplicate spaces in the check strings if requested.
if (!NoCanonicalizeWhiteSpace)
CanonicalizeCheckStrings(CheckStrings);
// Open the file to check and add it to SourceMgr.
std::string ErrorStr;
MemoryBuffer *F =
MemoryBuffer::getFileOrSTDIN(InputFilename.c_str(), &ErrorStr);
if (F == 0) {
errs() << "Could not open input file '" << InputFilename << "': "
<< ErrorStr << '\n';
return true;
}
// Remove duplicate spaces in the input file if requested.
if (!NoCanonicalizeWhiteSpace)
F = CanonicalizeInputFile(F);
SM.AddNewSourceBuffer(F, SMLoc());
// Check that we have all of the expected strings, in order, in the input
// file.
StringRef Buffer = F->getBuffer();
const char *LastMatch = 0;
for (unsigned StrNo = 0, e = CheckStrings.size(); StrNo != e; ++StrNo) {
const CheckString &CheckStr = CheckStrings[StrNo];
StringRef SearchFrom = Buffer;
// Find StrNo in the file.
Buffer = Buffer.substr(Buffer.find(CheckStr.Str));
// If we didn't find a match, reject the input.
if (Buffer.empty()) {
PrintCheckFailed(SM, CheckStr, SearchFrom);
return 1;
}
// If this check is a "CHECK-NEXT", verify that the previous match was on
// the previous line (i.e. that there is one newline between them).
if (CheckStr.IsCheckNext) {
// Count the number of newlines between the previous match and this one.
assert(LastMatch && "CHECK-NEXT can't be the first check in a file");
unsigned NumNewLines = CountNumNewlinesBetween(LastMatch, Buffer.data());
if (NumNewLines == 0) {
SM.PrintMessage(CheckStr.Loc,
CheckPrefix+"-NEXT: is on the same line as previous match",
"error");
SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()),
"'next' match was here", "note");
SM.PrintMessage(SMLoc::getFromPointer(LastMatch),
"previous match was here", "note");
return 1;
}
if (NumNewLines != 1) {
SM.PrintMessage(CheckStr.Loc,
CheckPrefix+
"-NEXT: is not on the line after the previous match",
"error");
SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()),
"'next' match was here", "note");
SM.PrintMessage(SMLoc::getFromPointer(LastMatch),
"previous match was here", "note");
return 1;
}
}
// Otherwise, everything is good. Remember this as the last match and move
// on to the next one.
LastMatch = Buffer.data();
Buffer = Buffer.substr(CheckStr.Str.size());
}
return 0;
}
<commit_msg>implement and document support for CHECK-NOT<commit_after>//===- FileCheck.cpp - Check that File's Contents match what is expected --===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// FileCheck does a line-by line check of a file that validates whether it
// contains the expected content. This is useful for regression tests etc.
//
// This program exits with an error status of 2 on error, exit status of 0 if
// the file matched the expected contents, and exit status of 1 if it did not
// contain the expected contents.
//
//===----------------------------------------------------------------------===//
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/Support/SourceMgr.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/System/Signals.h"
using namespace llvm;
static cl::opt<std::string>
CheckFilename(cl::Positional, cl::desc("<check-file>"), cl::Required);
static cl::opt<std::string>
InputFilename("input-file", cl::desc("File to check (defaults to stdin)"),
cl::init("-"), cl::value_desc("filename"));
static cl::opt<std::string>
CheckPrefix("check-prefix", cl::init("CHECK"),
cl::desc("Prefix to use from check file (defaults to 'CHECK')"));
static cl::opt<bool>
NoCanonicalizeWhiteSpace("strict-whitespace",
cl::desc("Do not treat all horizontal whitespace as equivalent"));
/// CheckString - This is a check that we found in the input file.
struct CheckString {
/// Str - The string to match.
std::string Str;
/// Loc - The location in the match file that the check string was specified.
SMLoc Loc;
/// IsCheckNext - This is true if this is a CHECK-NEXT: directive (as opposed
/// to a CHECK: directive.
bool IsCheckNext;
/// NotStrings - These are all of the strings that are disallowed from
/// occurring between this match string and the previous one (or start of
/// file).
std::vector<std::pair<SMLoc, std::string> > NotStrings;
CheckString(const std::string &S, SMLoc L, bool isCheckNext)
: Str(S), Loc(L), IsCheckNext(isCheckNext) {}
};
/// ReadCheckFile - Read the check file, which specifies the sequence of
/// expected strings. The strings are added to the CheckStrings vector.
static bool ReadCheckFile(SourceMgr &SM,
std::vector<CheckString> &CheckStrings) {
// Open the check file, and tell SourceMgr about it.
std::string ErrorStr;
MemoryBuffer *F =
MemoryBuffer::getFileOrSTDIN(CheckFilename.c_str(), &ErrorStr);
if (F == 0) {
errs() << "Could not open check file '" << CheckFilename << "': "
<< ErrorStr << '\n';
return true;
}
SM.AddNewSourceBuffer(F, SMLoc());
// Find all instances of CheckPrefix followed by : in the file.
StringRef Buffer = F->getBuffer();
std::vector<std::pair<SMLoc, std::string> > NotMatches;
while (1) {
// See if Prefix occurs in the memory buffer.
Buffer = Buffer.substr(Buffer.find(CheckPrefix));
// If we didn't find a match, we're done.
if (Buffer.empty())
break;
const char *CheckPrefixStart = Buffer.data();
// When we find a check prefix, keep track of whether we find CHECK: or
// CHECK-NEXT:
bool IsCheckNext = false, IsCheckNot = false;
// Verify that the : is present after the prefix.
if (Buffer[CheckPrefix.size()] == ':') {
Buffer = Buffer.substr(CheckPrefix.size()+1);
} else if (Buffer.size() > CheckPrefix.size()+6 &&
memcmp(Buffer.data()+CheckPrefix.size(), "-NEXT:", 6) == 0) {
Buffer = Buffer.substr(CheckPrefix.size()+7);
IsCheckNext = true;
} else if (Buffer.size() > CheckPrefix.size()+5 &&
memcmp(Buffer.data()+CheckPrefix.size(), "-NOT:", 5) == 0) {
Buffer = Buffer.substr(CheckPrefix.size()+6);
IsCheckNot = true;
} else {
Buffer = Buffer.substr(1);
continue;
}
// Okay, we found the prefix, yay. Remember the rest of the line, but
// ignore leading and trailing whitespace.
Buffer = Buffer.substr(Buffer.find_first_not_of(" \t"));
// Scan ahead to the end of line.
size_t EOL = Buffer.find_first_of("\n\r");
if (EOL == StringRef::npos) EOL = Buffer.size();
// Ignore trailing whitespace.
while (EOL && (Buffer[EOL-1] == ' ' || Buffer[EOL-1] == '\t'))
--EOL;
// Check that there is something on the line.
if (EOL == 0) {
SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()),
"found empty check string with prefix '"+CheckPrefix+":'",
"error");
return true;
}
StringRef PatternStr = Buffer.substr(0, EOL);
// Handle CHECK-NOT.
if (IsCheckNot) {
NotMatches.push_back(std::make_pair(SMLoc::getFromPointer(Buffer.data()),
PatternStr.str()));
Buffer = Buffer.substr(EOL);
continue;
}
// Verify that CHECK-NEXT lines have at least one CHECK line before them.
if (IsCheckNext && CheckStrings.empty()) {
SM.PrintMessage(SMLoc::getFromPointer(CheckPrefixStart),
"found '"+CheckPrefix+"-NEXT:' without previous '"+
CheckPrefix+ ": line", "error");
return true;
}
// Okay, add the string we captured to the output vector and move on.
CheckStrings.push_back(CheckString(PatternStr.str(),
SMLoc::getFromPointer(Buffer.data()),
IsCheckNext));
std::swap(NotMatches, CheckStrings.back().NotStrings);
Buffer = Buffer.substr(EOL);
}
if (CheckStrings.empty()) {
errs() << "error: no check strings found with prefix '" << CheckPrefix
<< ":'\n";
return true;
}
if (!NotMatches.empty()) {
errs() << "error: '" << CheckPrefix
<< "-NOT:' not supported after last check line.\n";
return true;
}
return false;
}
// CanonicalizeCheckStrings - Replace all sequences of horizontal whitespace in
// the check strings with a single space.
static void CanonicalizeCheckStrings(std::vector<CheckString> &CheckStrings) {
for (unsigned i = 0, e = CheckStrings.size(); i != e; ++i) {
std::string &Str = CheckStrings[i].Str;
for (unsigned C = 0; C != Str.size(); ++C) {
// If C is not a horizontal whitespace, skip it.
if (Str[C] != ' ' && Str[C] != '\t')
continue;
// Replace the character with space, then remove any other space
// characters after it.
Str[C] = ' ';
while (C+1 != Str.size() &&
(Str[C+1] == ' ' || Str[C+1] == '\t'))
Str.erase(Str.begin()+C+1);
}
}
}
/// CanonicalizeInputFile - Remove duplicate horizontal space from the specified
/// memory buffer, free it, and return a new one.
static MemoryBuffer *CanonicalizeInputFile(MemoryBuffer *MB) {
SmallVector<char, 16> NewFile;
NewFile.reserve(MB->getBufferSize());
for (const char *Ptr = MB->getBufferStart(), *End = MB->getBufferEnd();
Ptr != End; ++Ptr) {
// If C is not a horizontal whitespace, skip it.
if (*Ptr != ' ' && *Ptr != '\t') {
NewFile.push_back(*Ptr);
continue;
}
// Otherwise, add one space and advance over neighboring space.
NewFile.push_back(' ');
while (Ptr+1 != End &&
(Ptr[1] == ' ' || Ptr[1] == '\t'))
++Ptr;
}
// Free the old buffer and return a new one.
MemoryBuffer *MB2 =
MemoryBuffer::getMemBufferCopy(NewFile.data(),
NewFile.data() + NewFile.size(),
MB->getBufferIdentifier());
delete MB;
return MB2;
}
static void PrintCheckFailed(const SourceMgr &SM, const CheckString &CheckStr,
StringRef Buffer) {
// Otherwise, we have an error, emit an error message.
SM.PrintMessage(CheckStr.Loc, "expected string not found in input",
"error");
// Print the "scanning from here" line. If the current position is at the
// end of a line, advance to the start of the next line.
Buffer = Buffer.substr(Buffer.find_first_not_of(" \t\n\r"));
SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), "scanning from here",
"note");
}
static unsigned CountNumNewlinesBetween(const char *Start, const char *End) {
unsigned NumNewLines = 0;
for (; Start != End; ++Start) {
// Scan for newline.
if (Start[0] != '\n' && Start[0] != '\r')
continue;
++NumNewLines;
// Handle \n\r and \r\n as a single newline.
if (Start+1 != End &&
(Start[0] == '\n' || Start[0] == '\r') &&
(Start[0] != Start[1]))
++Start;
}
return NumNewLines;
}
int main(int argc, char **argv) {
sys::PrintStackTraceOnErrorSignal();
PrettyStackTraceProgram X(argc, argv);
cl::ParseCommandLineOptions(argc, argv);
SourceMgr SM;
// Read the expected strings from the check file.
std::vector<CheckString> CheckStrings;
if (ReadCheckFile(SM, CheckStrings))
return 2;
// Remove duplicate spaces in the check strings if requested.
if (!NoCanonicalizeWhiteSpace)
CanonicalizeCheckStrings(CheckStrings);
// Open the file to check and add it to SourceMgr.
std::string ErrorStr;
MemoryBuffer *F =
MemoryBuffer::getFileOrSTDIN(InputFilename.c_str(), &ErrorStr);
if (F == 0) {
errs() << "Could not open input file '" << InputFilename << "': "
<< ErrorStr << '\n';
return true;
}
// Remove duplicate spaces in the input file if requested.
if (!NoCanonicalizeWhiteSpace)
F = CanonicalizeInputFile(F);
SM.AddNewSourceBuffer(F, SMLoc());
// Check that we have all of the expected strings, in order, in the input
// file.
StringRef Buffer = F->getBuffer();
const char *LastMatch = Buffer.data();
for (unsigned StrNo = 0, e = CheckStrings.size(); StrNo != e; ++StrNo) {
const CheckString &CheckStr = CheckStrings[StrNo];
StringRef SearchFrom = Buffer;
// Find StrNo in the file.
Buffer = Buffer.substr(Buffer.find(CheckStr.Str));
// If we didn't find a match, reject the input.
if (Buffer.empty()) {
PrintCheckFailed(SM, CheckStr, SearchFrom);
return 1;
}
// If this check is a "CHECK-NEXT", verify that the previous match was on
// the previous line (i.e. that there is one newline between them).
if (CheckStr.IsCheckNext) {
// Count the number of newlines between the previous match and this one.
assert(LastMatch != F->getBufferStart() &&
"CHECK-NEXT can't be the first check in a file");
unsigned NumNewLines = CountNumNewlinesBetween(LastMatch, Buffer.data());
if (NumNewLines == 0) {
SM.PrintMessage(CheckStr.Loc,
CheckPrefix+"-NEXT: is on the same line as previous match",
"error");
SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()),
"'next' match was here", "note");
SM.PrintMessage(SMLoc::getFromPointer(LastMatch),
"previous match was here", "note");
return 1;
}
if (NumNewLines != 1) {
SM.PrintMessage(CheckStr.Loc,
CheckPrefix+
"-NEXT: is not on the line after the previous match",
"error");
SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()),
"'next' match was here", "note");
SM.PrintMessage(SMLoc::getFromPointer(LastMatch),
"previous match was here", "note");
return 1;
}
}
// If this match had "not strings", verify that they don't exist in the
// skipped region.
StringRef SkippedRegion(LastMatch, Buffer.data()-LastMatch);
for (unsigned i = 0, e = CheckStr.NotStrings.size(); i != e; ++i) {
size_t Pos = SkippedRegion.find(CheckStr.NotStrings[i].second);
if (Pos == StringRef::npos) continue;
SM.PrintMessage(SMLoc::getFromPointer(LastMatch+Pos),
CheckPrefix+"-NOT: string occurred!", "error");
SM.PrintMessage(CheckStr.NotStrings[i].first,
CheckPrefix+"-NOT: pattern specified here", "note");
return 1;
}
// Otherwise, everything is good. Remember this as the last match and move
// on to the next one.
LastMatch = Buffer.data();
Buffer = Buffer.substr(CheckStr.Str.size());
}
return 0;
}
<|endoftext|> |
<commit_before>/**
* Appcelerator Titanium - licensed under the Apache Public License 2
* see LICENSE in the root folder for details on the license.
* Copyright (c) 2008 Appcelerator, Inc. All Rights Reserved.
*/
#include "growl_osx.h"
#import "GrowlApplicationBridge.h"
#import <Foundation/Foundation.h>
#import <Cocoa/Cocoa.h>
#include <sys/types.h>
#include <sys/stat.h>
using namespace kroll;
using namespace ti;
namespace ti {
GrowlOSX::GrowlOSX(SharedBoundObject global) : GrowlBinding(global) {
delegate = [[TiGrowlDelegate alloc] init];
//Delegate will have a retain count of one from the alloc init.
}
GrowlOSX::~GrowlOSX() {
[delegate release];
}
void * GrowlOSX::URLWithAppCString(const char * inputCString)
{
if (inputCString == NULL) return nil;
NSString * inputString = [NSString stringWithUTF8String:inputCString];
NSURL * result = [NSURL URLWithString:inputString];
NSString * scheme = [result scheme];
BOOL isAppPath = [scheme isEqualToString:@"app"] || [scheme isEqualToString:@"ti"];
if ((scheme != nil) && !isAppPath) return result;
NSString * resourceSpecifier = [result resourceSpecifier];
if (isAppPath || [resourceSpecifier hasPrefix:@"//"]){
resourceSpecifier = [resourceSpecifier substringFromIndex:2];
}
SharedValue iconPathValue = global->CallNS("App.appURLToPath", Value::NewString([resourceSpecifier UTF8String]));
if (!(iconPathValue->IsString())) return nil;
std::string iconPath = iconPathValue->ToString();
const char * iconPathCString = iconPath.c_str();
if (iconPathCString == NULL) return nil;
return [NSURL fileURLWithPath:[NSString stringWithUTF8String:iconPathCString]];
}
void GrowlOSX::ShowNotification(std::string& title, std::string& description, std::string& iconURL, int notification_delay, SharedBoundMethod callback)
{
NSData *iconData = nil;
if (iconURL.size() > 0) {
const char * iconURLCString = iconURL.c_str();
//TODO: This should be more generalized and using centralized methods, but for now,
NSURL * iconNSURL = (NSURL *)URLWithAppCString(iconURLCString);
if ([iconNSURL isFileURL]){
iconData = [NSData dataWithContentsOfURL:iconNSURL];
} else if (iconNSURL != nil){
iconData = [NSData dataWithContentsOfURL:iconNSURL];
//TODO: Delayed load and fire.
}
}
NSMutableDictionary* clickContext = [[NSMutableDictionary alloc] initWithCapacity:10];
if (!callback.isNull()) {
[clickContext setObject:[[MethodWrapper alloc] initWithMethod:new SharedBoundMethod(callback)] forKey:@"method_wrapper"];
}
const char * titleCString = title.c_str();
NSString * titleString = nil;
if (titleCString != NULL) {
titleString = [NSString stringWithUTF8String:titleCString];
}
const char * descriptionCString = description.c_str();
NSString * descriptionString = nil;
if (descriptionCString != NULL) {
descriptionString = [NSString stringWithUTF8String:descriptionCString];
}
[GrowlApplicationBridge
notifyWithTitle:titleString
description:descriptionString
notificationName:@"tiNotification"
iconData:iconData
priority:0
isSticky:NO
clickContext:clickContext];
}
bool GrowlOSX::IsRunning()
{
return [GrowlApplicationBridge isGrowlRunning];
}
void GrowlOSX::CopyToApp(kroll::Host *host, kroll::Module *module)
{
std::string dir = host->GetApplicationHome() + KR_PATH_SEP + "Contents" +
KR_PATH_SEP + "Frameworks" + KR_PATH_SEP + "Growl.framework";
if (!FileUtils::IsDirectory(dir))
{
NSFileManager *fm = [NSFileManager defaultManager];
NSString *src = [NSString stringWithFormat:@"%s/Resources/Growl.framework", module->GetPath()];
NSString *dest = [NSString stringWithFormat:@"%s/Contents/Frameworks", host->GetApplicationHome().c_str()];
[fm copyPath:src toPath:dest handler:nil];
src = [NSString stringWithFormat:@"%s/Resources/Growl Registration Ticket.growlRegDict", module->GetPath()];
dest = [NSString stringWithFormat:@"%s/Contents/Resources", host->GetApplicationHome().c_str()];
[fm copyPath:src toPath:dest handler:nil];
}
}
}
<commit_msg>Disable callbacks for Growl notifications<commit_after>/**
* Appcelerator Titanium - licensed under the Apache Public License 2
* see LICENSE in the root folder for details on the license.
* Copyright (c) 2008 Appcelerator, Inc. All Rights Reserved.
*/
#include "growl_osx.h"
#import "GrowlApplicationBridge.h"
#import <Foundation/Foundation.h>
#import <Cocoa/Cocoa.h>
#include <sys/types.h>
#include <sys/stat.h>
using namespace kroll;
using namespace ti;
namespace ti {
GrowlOSX::GrowlOSX(SharedBoundObject global) : GrowlBinding(global) {
delegate = [[TiGrowlDelegate alloc] init];
//Delegate will have a retain count of one from the alloc init.
}
GrowlOSX::~GrowlOSX() {
[delegate release];
}
void * GrowlOSX::URLWithAppCString(const char * inputCString)
{
if (inputCString == NULL) return nil;
NSString * inputString = [NSString stringWithUTF8String:inputCString];
NSURL * result = [NSURL URLWithString:inputString];
NSString * scheme = [result scheme];
BOOL isAppPath = [scheme isEqualToString:@"app"] || [scheme isEqualToString:@"ti"];
if ((scheme != nil) && !isAppPath) return result;
NSString * resourceSpecifier = [result resourceSpecifier];
if (isAppPath || [resourceSpecifier hasPrefix:@"//"]){
resourceSpecifier = [resourceSpecifier substringFromIndex:2];
}
SharedValue iconPathValue = global->CallNS("App.appURLToPath", Value::NewString([resourceSpecifier UTF8String]));
if (!(iconPathValue->IsString())) return nil;
std::string iconPath = iconPathValue->ToString();
const char * iconPathCString = iconPath.c_str();
if (iconPathCString == NULL) return nil;
return [NSURL fileURLWithPath:[NSString stringWithUTF8String:iconPathCString]];
}
void GrowlOSX::ShowNotification(std::string& title, std::string& description, std::string& iconURL, int notification_delay, SharedBoundMethod callback)
{
NSData *iconData = nil;
if (iconURL.size() > 0) {
const char * iconURLCString = iconURL.c_str();
//TODO: This should be more generalized and using centralized methods, but for now,
NSURL * iconNSURL = (NSURL *)URLWithAppCString(iconURLCString);
if ([iconNSURL isFileURL]){
iconData = [NSData dataWithContentsOfURL:iconNSURL];
} else if (iconNSURL != nil){
iconData = [NSData dataWithContentsOfURL:iconNSURL];
//TODO: Delayed load and fire.
}
}
NSMutableDictionary* clickContext = [[NSMutableDictionary alloc] initWithCapacity:10];
if (!callback.isNull()) {
[clickContext setObject:[[MethodWrapper alloc] initWithMethod:new SharedBoundMethod(callback)] forKey:@"method_wrapper"];
}
const char * titleCString = title.c_str();
NSString * titleString = nil;
if (titleCString != NULL) {
titleString = [NSString stringWithUTF8String:titleCString];
}
const char * descriptionCString = description.c_str();
NSString * descriptionString = nil;
if (descriptionCString != NULL) {
descriptionString = [NSString stringWithUTF8String:descriptionCString];
}
[GrowlApplicationBridge
notifyWithTitle:titleString
description:descriptionString
notificationName:@"tiNotification"
iconData:iconData
priority:0
isSticky:NO
clickContext:nil];
}
bool GrowlOSX::IsRunning()
{
return [GrowlApplicationBridge isGrowlRunning];
}
void GrowlOSX::CopyToApp(kroll::Host *host, kroll::Module *module)
{
std::string dir = host->GetApplicationHome() + KR_PATH_SEP + "Contents" +
KR_PATH_SEP + "Frameworks" + KR_PATH_SEP + "Growl.framework";
if (!FileUtils::IsDirectory(dir))
{
NSFileManager *fm = [NSFileManager defaultManager];
NSString *src = [NSString stringWithFormat:@"%s/Resources/Growl.framework", module->GetPath()];
NSString *dest = [NSString stringWithFormat:@"%s/Contents/Frameworks", host->GetApplicationHome().c_str()];
[fm copyPath:src toPath:dest handler:nil];
src = [NSString stringWithFormat:@"%s/Resources/Growl Registration Ticket.growlRegDict", module->GetPath()];
dest = [NSString stringWithFormat:@"%s/Contents/Resources", host->GetApplicationHome().c_str()];
[fm copyPath:src toPath:dest handler:nil];
}
}
}
<|endoftext|> |
<commit_before>/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// Intel License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000, Intel Corporation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's 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.
//
// * The name of Intel Corporation may not 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 Intel Corporation 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.
//
//M*/
#include "precomp.hpp"
#if defined HAVE_FFMPEG && !defined WIN32
#include "cap_ffmpeg_impl.hpp"
#else
#include "cap_ffmpeg_api.hpp"
#endif
static CvCreateFileCapture_Plugin icvCreateFileCapture_FFMPEG_p = 0;
static CvReleaseCapture_Plugin icvReleaseCapture_FFMPEG_p = 0;
static CvGrabFrame_Plugin icvGrabFrame_FFMPEG_p = 0;
static CvRetrieveFrame_Plugin icvRetrieveFrame_FFMPEG_p = 0;
static CvSetCaptureProperty_Plugin icvSetCaptureProperty_FFMPEG_p = 0;
static CvGetCaptureProperty_Plugin icvGetCaptureProperty_FFMPEG_p = 0;
static CvCreateVideoWriter_Plugin icvCreateVideoWriter_FFMPEG_p = 0;
static CvReleaseVideoWriter_Plugin icvReleaseVideoWriter_FFMPEG_p = 0;
static CvWriteFrame_Plugin icvWriteFrame_FFMPEG_p = 0;
static cv::Mutex _icvInitFFMPEG_mutex;
class icvInitFFMPEG
{
public:
static void Init()
{
cv::AutoLock al(_icvInitFFMPEG_mutex);
static icvInitFFMPEG init;
}
private:
#if defined WIN32 || defined _WIN32
HMODULE icvFFOpenCV;
~icvInitFFMPEG()
{
if (icvFFOpenCV)
{
FreeLibrary(icvFFOpenCV);
icvFFOpenCV = 0;
}
}
#endif
icvInitFFMPEG()
{
#if defined WIN32 || defined _WIN32
# ifdef WINRT
const wchar_t* module_name = L"opencv_ffmpeg"
CVAUX_STRW(CV_MAJOR_VERSION) CVAUX_STRW(CV_MINOR_VERSION) CVAUX_STRW(CV_SUBMINOR_VERSION)
#if (defined _MSC_VER && defined _M_X64) || (defined __GNUC__ && defined __x86_64__)
L"_64"
#endif
L".dll";
icvFFOpenCV = LoadPackagedLibrary( module_name, 0 );
# else
const char* module_name = "opencv_ffmpeg"
CVAUX_STR(CV_MAJOR_VERSION) CVAUX_STR(CV_MINOR_VERSION) CVAUX_STR(CV_SUBMINOR_VERSION)
#if (defined _MSC_VER && defined _M_X64) || (defined __GNUC__ && defined __x86_64__)
"_64"
#endif
".dll";
icvFFOpenCV = LoadLibrary( module_name );
# endif
if( icvFFOpenCV )
{
icvCreateFileCapture_FFMPEG_p =
(CvCreateFileCapture_Plugin)GetProcAddress(icvFFOpenCV, "cvCreateFileCapture_FFMPEG");
icvReleaseCapture_FFMPEG_p =
(CvReleaseCapture_Plugin)GetProcAddress(icvFFOpenCV, "cvReleaseCapture_FFMPEG");
icvGrabFrame_FFMPEG_p =
(CvGrabFrame_Plugin)GetProcAddress(icvFFOpenCV, "cvGrabFrame_FFMPEG");
icvRetrieveFrame_FFMPEG_p =
(CvRetrieveFrame_Plugin)GetProcAddress(icvFFOpenCV, "cvRetrieveFrame_FFMPEG");
icvSetCaptureProperty_FFMPEG_p =
(CvSetCaptureProperty_Plugin)GetProcAddress(icvFFOpenCV, "cvSetCaptureProperty_FFMPEG");
icvGetCaptureProperty_FFMPEG_p =
(CvGetCaptureProperty_Plugin)GetProcAddress(icvFFOpenCV, "cvGetCaptureProperty_FFMPEG");
icvCreateVideoWriter_FFMPEG_p =
(CvCreateVideoWriter_Plugin)GetProcAddress(icvFFOpenCV, "cvCreateVideoWriter_FFMPEG");
icvReleaseVideoWriter_FFMPEG_p =
(CvReleaseVideoWriter_Plugin)GetProcAddress(icvFFOpenCV, "cvReleaseVideoWriter_FFMPEG");
icvWriteFrame_FFMPEG_p =
(CvWriteFrame_Plugin)GetProcAddress(icvFFOpenCV, "cvWriteFrame_FFMPEG");
#if 0
if( icvCreateFileCapture_FFMPEG_p != 0 &&
icvReleaseCapture_FFMPEG_p != 0 &&
icvGrabFrame_FFMPEG_p != 0 &&
icvRetrieveFrame_FFMPEG_p != 0 &&
icvSetCaptureProperty_FFMPEG_p != 0 &&
icvGetCaptureProperty_FFMPEG_p != 0 &&
icvCreateVideoWriter_FFMPEG_p != 0 &&
icvReleaseVideoWriter_FFMPEG_p != 0 &&
icvWriteFrame_FFMPEG_p != 0 )
{
printf("Successfully initialized ffmpeg plugin!\n");
}
else
{
printf("Failed to load FFMPEG plugin: module handle=%p\n", icvFFOpenCV);
}
#endif
}
#elif defined HAVE_FFMPEG
icvCreateFileCapture_FFMPEG_p = (CvCreateFileCapture_Plugin)cvCreateFileCapture_FFMPEG;
icvReleaseCapture_FFMPEG_p = (CvReleaseCapture_Plugin)cvReleaseCapture_FFMPEG;
icvGrabFrame_FFMPEG_p = (CvGrabFrame_Plugin)cvGrabFrame_FFMPEG;
icvRetrieveFrame_FFMPEG_p = (CvRetrieveFrame_Plugin)cvRetrieveFrame_FFMPEG;
icvSetCaptureProperty_FFMPEG_p = (CvSetCaptureProperty_Plugin)cvSetCaptureProperty_FFMPEG;
icvGetCaptureProperty_FFMPEG_p = (CvGetCaptureProperty_Plugin)cvGetCaptureProperty_FFMPEG;
icvCreateVideoWriter_FFMPEG_p = (CvCreateVideoWriter_Plugin)cvCreateVideoWriter_FFMPEG;
icvReleaseVideoWriter_FFMPEG_p = (CvReleaseVideoWriter_Plugin)cvReleaseVideoWriter_FFMPEG;
icvWriteFrame_FFMPEG_p = (CvWriteFrame_Plugin)cvWriteFrame_FFMPEG;
#endif
}
};
class CvCapture_FFMPEG_proxy :
public CvCapture
{
public:
CvCapture_FFMPEG_proxy() { ffmpegCapture = 0; }
virtual ~CvCapture_FFMPEG_proxy() { close(); }
virtual double getProperty(int propId) const
{
return ffmpegCapture ? icvGetCaptureProperty_FFMPEG_p(ffmpegCapture, propId) : 0;
}
virtual bool setProperty(int propId, double value)
{
return ffmpegCapture ? icvSetCaptureProperty_FFMPEG_p(ffmpegCapture, propId, value)!=0 : false;
}
virtual bool grabFrame()
{
return ffmpegCapture ? icvGrabFrame_FFMPEG_p(ffmpegCapture)!=0 : false;
}
virtual IplImage* retrieveFrame(int)
{
unsigned char* data = 0;
int step=0, width=0, height=0, cn=0;
if (!ffmpegCapture ||
!icvRetrieveFrame_FFMPEG_p(ffmpegCapture, &data, &step, &width, &height, &cn))
return 0;
cvInitImageHeader(&frame, cvSize(width, height), 8, cn);
cvSetData(&frame, data, step);
return &frame;
}
virtual bool open( const char* filename )
{
icvInitFFMPEG::Init();
close();
if( !icvCreateFileCapture_FFMPEG_p )
return false;
ffmpegCapture = icvCreateFileCapture_FFMPEG_p( filename );
return ffmpegCapture != 0;
}
virtual void close()
{
if( ffmpegCapture && icvReleaseCapture_FFMPEG_p )
icvReleaseCapture_FFMPEG_p( &ffmpegCapture );
assert( ffmpegCapture == 0 );
ffmpegCapture = 0;
}
protected:
void* ffmpegCapture;
IplImage frame;
};
CvCapture* cvCreateFileCapture_FFMPEG_proxy(const char * filename)
{
CvCapture_FFMPEG_proxy* result = new CvCapture_FFMPEG_proxy;
if( result->open( filename ))
return result;
delete result;
return 0;
}
class CvVideoWriter_FFMPEG_proxy :
public CvVideoWriter
{
public:
CvVideoWriter_FFMPEG_proxy() { ffmpegWriter = 0; }
virtual ~CvVideoWriter_FFMPEG_proxy() { close(); }
virtual bool writeFrame( const IplImage* image )
{
if(!ffmpegWriter)
return false;
CV_Assert(image->depth == 8);
return icvWriteFrame_FFMPEG_p(ffmpegWriter, (const uchar*)image->imageData,
image->widthStep, image->width, image->height, image->nChannels, image->origin) !=0;
}
virtual bool open( const char* filename, int fourcc, double fps, CvSize frameSize, bool isColor )
{
icvInitFFMPEG::Init();
close();
if( !icvCreateVideoWriter_FFMPEG_p )
return false;
ffmpegWriter = icvCreateVideoWriter_FFMPEG_p( filename, fourcc, fps, frameSize.width, frameSize.height, isColor );
return ffmpegWriter != 0;
}
virtual void close()
{
if( ffmpegWriter && icvReleaseVideoWriter_FFMPEG_p )
icvReleaseVideoWriter_FFMPEG_p( &ffmpegWriter );
assert( ffmpegWriter == 0 );
ffmpegWriter = 0;
}
protected:
void* ffmpegWriter;
};
CvVideoWriter* cvCreateVideoWriter_FFMPEG_proxy( const char* filename, int fourcc,
double fps, CvSize frameSize, int isColor )
{
CvVideoWriter_FFMPEG_proxy* result = new CvVideoWriter_FFMPEG_proxy;
if( result->open( filename, fourcc, fps, frameSize, isColor != 0 ))
return result;
delete result;
return 0;
}
<commit_msg>ffmpeg: try to load ffmpeg wrapper dll from the current module directory<commit_after>/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// Intel License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000, Intel Corporation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's 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.
//
// * The name of Intel Corporation may not 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 Intel Corporation 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.
//
//M*/
#include "precomp.hpp"
#include <string>
#if defined HAVE_FFMPEG && !defined WIN32
#include "cap_ffmpeg_impl.hpp"
#else
#include "cap_ffmpeg_api.hpp"
#endif
static CvCreateFileCapture_Plugin icvCreateFileCapture_FFMPEG_p = 0;
static CvReleaseCapture_Plugin icvReleaseCapture_FFMPEG_p = 0;
static CvGrabFrame_Plugin icvGrabFrame_FFMPEG_p = 0;
static CvRetrieveFrame_Plugin icvRetrieveFrame_FFMPEG_p = 0;
static CvSetCaptureProperty_Plugin icvSetCaptureProperty_FFMPEG_p = 0;
static CvGetCaptureProperty_Plugin icvGetCaptureProperty_FFMPEG_p = 0;
static CvCreateVideoWriter_Plugin icvCreateVideoWriter_FFMPEG_p = 0;
static CvReleaseVideoWriter_Plugin icvReleaseVideoWriter_FFMPEG_p = 0;
static CvWriteFrame_Plugin icvWriteFrame_FFMPEG_p = 0;
static cv::Mutex _icvInitFFMPEG_mutex;
#if defined WIN32 || defined _WIN32
static const HMODULE cv_GetCurrentModule()
{
HMODULE h = 0;
::GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
reinterpret_cast<LPCTSTR>(cv_GetCurrentModule),
&h);
return h;
}
#endif
class icvInitFFMPEG
{
public:
static void Init()
{
cv::AutoLock al(_icvInitFFMPEG_mutex);
static icvInitFFMPEG init;
}
private:
#if defined WIN32 || defined _WIN32
HMODULE icvFFOpenCV;
~icvInitFFMPEG()
{
if (icvFFOpenCV)
{
FreeLibrary(icvFFOpenCV);
icvFFOpenCV = 0;
}
}
#endif
icvInitFFMPEG()
{
#if defined WIN32 || defined _WIN32
# ifdef WINRT
const wchar_t* module_name = L"opencv_ffmpeg"
CVAUX_STRW(CV_MAJOR_VERSION) CVAUX_STRW(CV_MINOR_VERSION) CVAUX_STRW(CV_SUBMINOR_VERSION)
#if (defined _MSC_VER && defined _M_X64) || (defined __GNUC__ && defined __x86_64__)
L"_64"
#endif
L".dll";
icvFFOpenCV = LoadPackagedLibrary( module_name, 0 );
# else
const std::wstring module_name = L"opencv_ffmpeg"
CVAUX_STRW(CV_MAJOR_VERSION) CVAUX_STRW(CV_MINOR_VERSION) CVAUX_STRW(CV_SUBMINOR_VERSION)
#if (defined _MSC_VER && defined _M_X64) || (defined __GNUC__ && defined __x86_64__)
L"_64"
#endif
L".dll";
const wchar_t* ffmpeg_env_path = _wgetenv(L"OPENCV_FFMPEG_DLL_DIR");
std::wstring module_path =
ffmpeg_env_path
? ((std::wstring(ffmpeg_env_path) + L"\\") + module_name)
: module_name;
icvFFOpenCV = LoadLibraryW(module_path.c_str());
if(!icvFFOpenCV && !ffmpeg_env_path)
{
HMODULE m = cv_GetCurrentModule();
if (m)
{
wchar_t path[MAX_PATH];
size_t sz = GetModuleFileNameW(m, path, sizeof(path));
if (sz > 0 && ERROR_SUCCESS == GetLastError())
{
wchar_t* s = wcsrchr(path, L'\\');
if (s)
{
s[0] = 0;
module_path = (std::wstring(path) + L"\\") + module_name;
icvFFOpenCV = LoadLibraryW(module_path.c_str());
}
}
}
}
# endif
if( icvFFOpenCV )
{
icvCreateFileCapture_FFMPEG_p =
(CvCreateFileCapture_Plugin)GetProcAddress(icvFFOpenCV, "cvCreateFileCapture_FFMPEG");
icvReleaseCapture_FFMPEG_p =
(CvReleaseCapture_Plugin)GetProcAddress(icvFFOpenCV, "cvReleaseCapture_FFMPEG");
icvGrabFrame_FFMPEG_p =
(CvGrabFrame_Plugin)GetProcAddress(icvFFOpenCV, "cvGrabFrame_FFMPEG");
icvRetrieveFrame_FFMPEG_p =
(CvRetrieveFrame_Plugin)GetProcAddress(icvFFOpenCV, "cvRetrieveFrame_FFMPEG");
icvSetCaptureProperty_FFMPEG_p =
(CvSetCaptureProperty_Plugin)GetProcAddress(icvFFOpenCV, "cvSetCaptureProperty_FFMPEG");
icvGetCaptureProperty_FFMPEG_p =
(CvGetCaptureProperty_Plugin)GetProcAddress(icvFFOpenCV, "cvGetCaptureProperty_FFMPEG");
icvCreateVideoWriter_FFMPEG_p =
(CvCreateVideoWriter_Plugin)GetProcAddress(icvFFOpenCV, "cvCreateVideoWriter_FFMPEG");
icvReleaseVideoWriter_FFMPEG_p =
(CvReleaseVideoWriter_Plugin)GetProcAddress(icvFFOpenCV, "cvReleaseVideoWriter_FFMPEG");
icvWriteFrame_FFMPEG_p =
(CvWriteFrame_Plugin)GetProcAddress(icvFFOpenCV, "cvWriteFrame_FFMPEG");
#if 0
if( icvCreateFileCapture_FFMPEG_p != 0 &&
icvReleaseCapture_FFMPEG_p != 0 &&
icvGrabFrame_FFMPEG_p != 0 &&
icvRetrieveFrame_FFMPEG_p != 0 &&
icvSetCaptureProperty_FFMPEG_p != 0 &&
icvGetCaptureProperty_FFMPEG_p != 0 &&
icvCreateVideoWriter_FFMPEG_p != 0 &&
icvReleaseVideoWriter_FFMPEG_p != 0 &&
icvWriteFrame_FFMPEG_p != 0 )
{
printf("Successfully initialized ffmpeg plugin!\n");
}
else
{
printf("Failed to load FFMPEG plugin: module handle=%p\n", icvFFOpenCV);
}
#endif
}
#elif defined HAVE_FFMPEG
icvCreateFileCapture_FFMPEG_p = (CvCreateFileCapture_Plugin)cvCreateFileCapture_FFMPEG;
icvReleaseCapture_FFMPEG_p = (CvReleaseCapture_Plugin)cvReleaseCapture_FFMPEG;
icvGrabFrame_FFMPEG_p = (CvGrabFrame_Plugin)cvGrabFrame_FFMPEG;
icvRetrieveFrame_FFMPEG_p = (CvRetrieveFrame_Plugin)cvRetrieveFrame_FFMPEG;
icvSetCaptureProperty_FFMPEG_p = (CvSetCaptureProperty_Plugin)cvSetCaptureProperty_FFMPEG;
icvGetCaptureProperty_FFMPEG_p = (CvGetCaptureProperty_Plugin)cvGetCaptureProperty_FFMPEG;
icvCreateVideoWriter_FFMPEG_p = (CvCreateVideoWriter_Plugin)cvCreateVideoWriter_FFMPEG;
icvReleaseVideoWriter_FFMPEG_p = (CvReleaseVideoWriter_Plugin)cvReleaseVideoWriter_FFMPEG;
icvWriteFrame_FFMPEG_p = (CvWriteFrame_Plugin)cvWriteFrame_FFMPEG;
#endif
}
};
class CvCapture_FFMPEG_proxy :
public CvCapture
{
public:
CvCapture_FFMPEG_proxy() { ffmpegCapture = 0; }
virtual ~CvCapture_FFMPEG_proxy() { close(); }
virtual double getProperty(int propId) const
{
return ffmpegCapture ? icvGetCaptureProperty_FFMPEG_p(ffmpegCapture, propId) : 0;
}
virtual bool setProperty(int propId, double value)
{
return ffmpegCapture ? icvSetCaptureProperty_FFMPEG_p(ffmpegCapture, propId, value)!=0 : false;
}
virtual bool grabFrame()
{
return ffmpegCapture ? icvGrabFrame_FFMPEG_p(ffmpegCapture)!=0 : false;
}
virtual IplImage* retrieveFrame(int)
{
unsigned char* data = 0;
int step=0, width=0, height=0, cn=0;
if (!ffmpegCapture ||
!icvRetrieveFrame_FFMPEG_p(ffmpegCapture, &data, &step, &width, &height, &cn))
return 0;
cvInitImageHeader(&frame, cvSize(width, height), 8, cn);
cvSetData(&frame, data, step);
return &frame;
}
virtual bool open( const char* filename )
{
icvInitFFMPEG::Init();
close();
if( !icvCreateFileCapture_FFMPEG_p )
return false;
ffmpegCapture = icvCreateFileCapture_FFMPEG_p( filename );
return ffmpegCapture != 0;
}
virtual void close()
{
if( ffmpegCapture && icvReleaseCapture_FFMPEG_p )
icvReleaseCapture_FFMPEG_p( &ffmpegCapture );
assert( ffmpegCapture == 0 );
ffmpegCapture = 0;
}
protected:
void* ffmpegCapture;
IplImage frame;
};
CvCapture* cvCreateFileCapture_FFMPEG_proxy(const char * filename)
{
CvCapture_FFMPEG_proxy* result = new CvCapture_FFMPEG_proxy;
if( result->open( filename ))
return result;
delete result;
return 0;
}
class CvVideoWriter_FFMPEG_proxy :
public CvVideoWriter
{
public:
CvVideoWriter_FFMPEG_proxy() { ffmpegWriter = 0; }
virtual ~CvVideoWriter_FFMPEG_proxy() { close(); }
virtual bool writeFrame( const IplImage* image )
{
if(!ffmpegWriter)
return false;
CV_Assert(image->depth == 8);
return icvWriteFrame_FFMPEG_p(ffmpegWriter, (const uchar*)image->imageData,
image->widthStep, image->width, image->height, image->nChannels, image->origin) !=0;
}
virtual bool open( const char* filename, int fourcc, double fps, CvSize frameSize, bool isColor )
{
icvInitFFMPEG::Init();
close();
if( !icvCreateVideoWriter_FFMPEG_p )
return false;
ffmpegWriter = icvCreateVideoWriter_FFMPEG_p( filename, fourcc, fps, frameSize.width, frameSize.height, isColor );
return ffmpegWriter != 0;
}
virtual void close()
{
if( ffmpegWriter && icvReleaseVideoWriter_FFMPEG_p )
icvReleaseVideoWriter_FFMPEG_p( &ffmpegWriter );
assert( ffmpegWriter == 0 );
ffmpegWriter = 0;
}
protected:
void* ffmpegWriter;
};
CvVideoWriter* cvCreateVideoWriter_FFMPEG_proxy( const char* filename, int fourcc,
double fps, CvSize frameSize, int isColor )
{
CvVideoWriter_FFMPEG_proxy* result = new CvVideoWriter_FFMPEG_proxy;
if( result->open( filename, fourcc, fps, frameSize, isColor != 0 ))
return result;
delete result;
return 0;
}
<|endoftext|> |
<commit_before>/*************************************************************************/
/* godot_plugin_jni.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "godot_plugin_jni.h"
#include <core/engine.h>
#include <core/error_macros.h>
#include <core/project_settings.h>
#include <platform/android/api/jni_singleton.h>
#include <platform/android/jni_utils.h>
#include <platform/android/string_android.h>
static HashMap<String, JNISingleton *> jni_singletons;
extern "C" {
JNIEXPORT void JNICALL Java_org_godotengine_godot_plugin_GodotPlugin_nativeRegisterSingleton(JNIEnv *env, jclass clazz, jstring name, jobject obj) {
String singname = jstring_to_string(name, env);
JNISingleton *s = (JNISingleton *)ClassDB::instance("JNISingleton");
s->set_instance(env->NewGlobalRef(obj));
jni_singletons[singname] = s;
Engine::get_singleton()->add_singleton(Engine::Singleton(singname, s));
ProjectSettings::get_singleton()->set(singname, s);
}
JNIEXPORT void JNICALL Java_org_godotengine_godot_plugin_GodotPlugin_nativeRegisterMethod(JNIEnv *env, jclass clazz, jstring sname, jstring name, jstring ret, jobjectArray args) {
String singname = jstring_to_string(sname, env);
ERR_FAIL_COND(!jni_singletons.has(singname));
JNISingleton *s = jni_singletons.get(singname);
String mname = jstring_to_string(name, env);
String retval = jstring_to_string(ret, env);
Vector<Variant::Type> types;
String cs = "(";
int stringCount = env->GetArrayLength(args);
for (int i = 0; i < stringCount; i++) {
jstring string = (jstring)env->GetObjectArrayElement(args, i);
const String rawString = jstring_to_string(string, env);
types.push_back(get_jni_type(rawString));
cs += get_jni_sig(rawString);
}
cs += ")";
cs += get_jni_sig(retval);
jclass cls = env->GetObjectClass(s->get_instance());
jmethodID mid = env->GetMethodID(cls, mname.ascii().get_data(), cs.ascii().get_data());
if (!mid) {
print_line("Failed getting method ID " + mname);
}
s->add_method(mname, mid, types, get_jni_type(retval));
}
JNIEXPORT void JNICALL Java_org_godotengine_godot_plugin_GodotPlugin_nativeRegisterSignal(JNIEnv *env, jobject obj, jstring j_plugin_name, jstring j_signal_name, jobjectArray j_signal_param_types) {
String singleton_name = jstring_to_string(j_plugin_name, env);
ERR_FAIL_COND(!jni_singletons.has(singleton_name));
JNISingleton *singleton = jni_singletons.get(singleton_name);
String signal_name = jstring_to_string(j_signal_name, env);
Vector<Variant::Type> types;
int stringCount = env->GetArrayLength(j_signal_param_types);
for (int i = 0; i < stringCount; i++) {
jstring j_signal_param_type = (jstring)env->GetObjectArrayElement(j_signal_param_types, i);
const String signal_param_type = jstring_to_string(j_signal_param_type, env);
types.push_back(get_jni_type(signal_param_type));
}
singleton->add_signal(signal_name, types);
}
JNIEXPORT void JNICALL Java_org_godotengine_godot_plugin_GodotPlugin_nativeEmitSignal(JNIEnv *env, jobject obj, jstring j_plugin_name, jstring j_signal_name, jobjectArray j_signal_params) {
String singleton_name = jstring_to_string(j_plugin_name, env);
ERR_FAIL_COND(!jni_singletons.has(singleton_name));
JNISingleton *singleton = jni_singletons.get(singleton_name);
String signal_name = jstring_to_string(j_signal_name, env);
int count = env->GetArrayLength(j_signal_params);
const Variant *args[count];
for (int i = 0; i < count; i++) {
jobject j_param = env->GetObjectArrayElement(j_signal_params, i);
Variant variant = _jobject_to_variant(env, j_param);
args[i] = &variant;
env->DeleteLocalRef(j_param);
};
singleton->emit_signal(signal_name, args, count);
}
JNIEXPORT void JNICALL Java_org_godotengine_godot_plugin_GodotPlugin_nativeRegisterGDNativeLibraries(JNIEnv *env, jobject obj, jobjectArray gdnlib_paths) {
int gdnlib_count = env->GetArrayLength(gdnlib_paths);
if (gdnlib_count == 0) {
return;
}
// Retrieve the current list of gdnative libraries.
Array singletons = Array();
if (ProjectSettings::get_singleton()->has_setting("gdnative/singletons")) {
singletons = ProjectSettings::get_singleton()->get("gdnative/singletons");
}
// Insert the libraries provided by the plugin
for (int i = 0; i < gdnlib_count; i++) {
jstring relative_path = (jstring)env->GetObjectArrayElement(gdnlib_paths, i);
String path = "res://" + jstring_to_string(relative_path, env);
if (!singletons.has(path)) {
singletons.push_back(path);
}
env->DeleteLocalRef(relative_path);
}
// Insert the updated list back into project settings.
ProjectSettings::get_singleton()->set("gdnative/singletons", singletons);
}
}
<commit_msg>Fix parameters passing when emitting signal<commit_after>/*************************************************************************/
/* godot_plugin_jni.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "godot_plugin_jni.h"
#include <core/engine.h>
#include <core/error_macros.h>
#include <core/project_settings.h>
#include <platform/android/api/jni_singleton.h>
#include <platform/android/jni_utils.h>
#include <platform/android/string_android.h>
static HashMap<String, JNISingleton *> jni_singletons;
extern "C" {
JNIEXPORT void JNICALL Java_org_godotengine_godot_plugin_GodotPlugin_nativeRegisterSingleton(JNIEnv *env, jclass clazz, jstring name, jobject obj) {
String singname = jstring_to_string(name, env);
JNISingleton *s = (JNISingleton *)ClassDB::instance("JNISingleton");
s->set_instance(env->NewGlobalRef(obj));
jni_singletons[singname] = s;
Engine::get_singleton()->add_singleton(Engine::Singleton(singname, s));
ProjectSettings::get_singleton()->set(singname, s);
}
JNIEXPORT void JNICALL Java_org_godotengine_godot_plugin_GodotPlugin_nativeRegisterMethod(JNIEnv *env, jclass clazz, jstring sname, jstring name, jstring ret, jobjectArray args) {
String singname = jstring_to_string(sname, env);
ERR_FAIL_COND(!jni_singletons.has(singname));
JNISingleton *s = jni_singletons.get(singname);
String mname = jstring_to_string(name, env);
String retval = jstring_to_string(ret, env);
Vector<Variant::Type> types;
String cs = "(";
int stringCount = env->GetArrayLength(args);
for (int i = 0; i < stringCount; i++) {
jstring string = (jstring)env->GetObjectArrayElement(args, i);
const String rawString = jstring_to_string(string, env);
types.push_back(get_jni_type(rawString));
cs += get_jni_sig(rawString);
}
cs += ")";
cs += get_jni_sig(retval);
jclass cls = env->GetObjectClass(s->get_instance());
jmethodID mid = env->GetMethodID(cls, mname.ascii().get_data(), cs.ascii().get_data());
if (!mid) {
print_line("Failed getting method ID " + mname);
}
s->add_method(mname, mid, types, get_jni_type(retval));
}
JNIEXPORT void JNICALL Java_org_godotengine_godot_plugin_GodotPlugin_nativeRegisterSignal(JNIEnv *env, jobject obj, jstring j_plugin_name, jstring j_signal_name, jobjectArray j_signal_param_types) {
String singleton_name = jstring_to_string(j_plugin_name, env);
ERR_FAIL_COND(!jni_singletons.has(singleton_name));
JNISingleton *singleton = jni_singletons.get(singleton_name);
String signal_name = jstring_to_string(j_signal_name, env);
Vector<Variant::Type> types;
int stringCount = env->GetArrayLength(j_signal_param_types);
for (int i = 0; i < stringCount; i++) {
jstring j_signal_param_type = (jstring)env->GetObjectArrayElement(j_signal_param_types, i);
const String signal_param_type = jstring_to_string(j_signal_param_type, env);
types.push_back(get_jni_type(signal_param_type));
}
singleton->add_signal(signal_name, types);
}
JNIEXPORT void JNICALL Java_org_godotengine_godot_plugin_GodotPlugin_nativeEmitSignal(JNIEnv *env, jobject obj, jstring j_plugin_name, jstring j_signal_name, jobjectArray j_signal_params) {
String singleton_name = jstring_to_string(j_plugin_name, env);
ERR_FAIL_COND(!jni_singletons.has(singleton_name));
JNISingleton *singleton = jni_singletons.get(singleton_name);
String signal_name = jstring_to_string(j_signal_name, env);
int count = env->GetArrayLength(j_signal_params);
ERR_FAIL_COND_MSG(count > VARIANT_ARG_MAX, "Maximum argument count exceeded!");
Variant variant_params[VARIANT_ARG_MAX];
const Variant *args[VARIANT_ARG_MAX];
for (int i = 0; i < count; i++) {
jobject j_param = env->GetObjectArrayElement(j_signal_params, i);
variant_params[i] = _jobject_to_variant(env, j_param);
args[i] = &variant_params[i];
env->DeleteLocalRef(j_param);
};
singleton->emit_signal(signal_name, args, count);
}
JNIEXPORT void JNICALL Java_org_godotengine_godot_plugin_GodotPlugin_nativeRegisterGDNativeLibraries(JNIEnv *env, jobject obj, jobjectArray gdnlib_paths) {
int gdnlib_count = env->GetArrayLength(gdnlib_paths);
if (gdnlib_count == 0) {
return;
}
// Retrieve the current list of gdnative libraries.
Array singletons = Array();
if (ProjectSettings::get_singleton()->has_setting("gdnative/singletons")) {
singletons = ProjectSettings::get_singleton()->get("gdnative/singletons");
}
// Insert the libraries provided by the plugin
for (int i = 0; i < gdnlib_count; i++) {
jstring relative_path = (jstring)env->GetObjectArrayElement(gdnlib_paths, i);
String path = "res://" + jstring_to_string(relative_path, env);
if (!singletons.has(path)) {
singletons.push_back(path);
}
env->DeleteLocalRef(relative_path);
}
// Insert the updated list back into project settings.
ProjectSettings::get_singleton()->set("gdnative/singletons", singletons);
}
}
<|endoftext|> |
<commit_before>#include "ug_bitext_pstats.h"
namespace Moses
{
namespace bitext
{
#if UG_BITEXT_TRACK_ACTIVE_THREADS
ThreadSafeCounter pstats::active;
#endif
pstats::
pstats() : raw_cnt(0), sample_cnt(0), good(0), sum_pairs(0), in_progress(0)
{
for (int i = 0; i <= Moses::LRModel::NONE; ++i)
ofwd[i] = obwd[i] = 0;
}
pstats::
~pstats()
{
#if UG_BITEXT_TRACK_ACTIVE_THREADS
// counter may not exist any more at destruction time, so try ... catch
try { --active; } catch (...) {}
#endif
}
void
pstats::
register_worker()
{
this->lock.lock();
++this->in_progress;
this->lock.unlock();
}
void
pstats::
release()
{
this->lock.lock();
if (this->in_progress-- == 1) // last one - >we're done
this->ready.notify_all();
this->lock.unlock();
}
void
pstats
::count_sample(int const docid, size_t const num_pairs,
int const po_fwd, int const po_bwd)
{
boost::lock_guard<boost::mutex> guard(lock);
++sample_cnt;
if (num_pairs == 0) return;
++good;
sum_pairs += num_pairs;
++ofwd[po_fwd];
++obwd[po_bwd];
while (int(indoc.size()) <= docid) indoc.push_back(0);
++indoc[docid];
}
bool
pstats::
add(uint64_t pid, float const w,
vector<uchar> const& a,
uint32_t const cnt2,
uint32_t fwd_o,
uint32_t bwd_o, int const docid)
{
boost::lock_guard<boost::mutex> guard(this->lock);
jstats& entry = this->trg[pid];
entry.add(w, a, cnt2, fwd_o, bwd_o, docid);
if (this->good < entry.rcnt())
{
UTIL_THROW(util::Exception, "more joint counts than good counts:"
<< entry.rcnt() << "/" << this->good << "!");
}
return true;
}
}
}
<commit_msg>Bug fix.<commit_after>#include "ug_bitext_pstats.h"
namespace Moses
{
namespace bitext
{
#if UG_BITEXT_TRACK_ACTIVE_THREADS
ThreadSafeCounter pstats::active;
#endif
pstats::
pstats() : raw_cnt(0), sample_cnt(0), good(0), sum_pairs(0), in_progress(0)
{
for (int i = 0; i <= Moses::LRModel::NONE; ++i)
ofwd[i] = obwd[i] = 0;
}
pstats::
~pstats()
{
#if UG_BITEXT_TRACK_ACTIVE_THREADS
// counter may not exist any more at destruction time, so try ... catch
try { --active; } catch (...) {}
#endif
}
void
pstats::
register_worker()
{
this->lock.lock();
++this->in_progress;
this->lock.unlock();
}
void
pstats::
release()
{
this->lock.lock();
if (this->in_progress-- == 1) // last one - >we're done
this->ready.notify_all();
this->lock.unlock();
}
void
pstats
::count_sample(int const docid, size_t const num_pairs,
int const po_fwd, int const po_bwd)
{
boost::lock_guard<boost::mutex> guard(lock);
++sample_cnt;
if (num_pairs == 0) return;
++good;
sum_pairs += num_pairs;
++ofwd[po_fwd];
++obwd[po_bwd];
if (docid >= 0)
{
while (int(indoc.size()) <= docid) indoc.push_back(0);
++indoc[docid];
}
}
bool
pstats::
add(uint64_t pid, float const w,
vector<uchar> const& a,
uint32_t const cnt2,
uint32_t fwd_o,
uint32_t bwd_o, int const docid)
{
boost::lock_guard<boost::mutex> guard(this->lock);
jstats& entry = this->trg[pid];
entry.add(w, a, cnt2, fwd_o, bwd_o, docid);
if (this->good < entry.rcnt())
{
UTIL_THROW(util::Exception, "more joint counts than good counts:"
<< entry.rcnt() << "/" << this->good << "!");
}
return true;
}
}
}
<|endoftext|> |
<commit_before>// $Id$
#include "LanguageModelFactory.h"
#include "UserMessage.h"
#include "TypeDef.h"
// include appropriate header
#ifdef LM_SRI
# include "LanguageModel_SRI.h"
#endif
#ifdef LM_IRST
# include "LanguageModel_IRST.h"
#endif
namespace LanguageModelFactory
{
LanguageModel* createLanguageModel(LMType lmType)
{
LanguageModel *lm = NULL;
switch (lmType)
{
case SRI:
#ifdef LM_SRI
lm = new LanguageModel_SRI();
#endif
break;
case IRST:
#ifdef LM_IRST
lm = new LanguageModel_IRST();
#endif
break;
}
if (lm == NULL)
{
UserMessage::Add("Lnaguage model type unknown. Probably not compiled into library");
}
return lm;
}
}
<commit_msg>fallback to another LM if what we have isn't compiled into lib<commit_after>// $Id$
#include "LanguageModelFactory.h"
#include "UserMessage.h"
#include "TypeDef.h"
// include appropriate header
#ifdef LM_SRI
# include "LanguageModel_SRI.h"
#endif
#ifdef LM_IRST
# include "LanguageModel_IRST.h"
#endif
namespace LanguageModelFactory
{
LanguageModel* createLanguageModel(LMType lmType)
{
LanguageModel *lm = NULL;
switch (lmType)
{
case SRI:
#ifdef LM_SRI
lm = new LanguageModel_SRI();
#endif
break;
case IRST:
#ifdef LM_IRST
lm = new LanguageModel_IRST();
#endif
break;
}
if (lm == NULL)
{
// fall back. pick what we have
#ifdef LM_SRI
lm = new LanguageModel_SRI();
#else
#ifdef LM_IRST
lm = new LanguageModel_IRST();
#else
UserMessage::Add("Lnaguage model type unknown. Probably not compiled into library");
#endif
#endif
}
return lm;
}
}
<|endoftext|> |
<commit_before>//
// kern_cpuf.cpp
// CPUFriend
//
// Copyright © 2017 Vanilla. All rights reserved.
//
#include <Headers/kern_api.hpp>
#include "kern_cpuf.hpp"
static const char *binList[] {
"/System/Library/Extensions/IOPlatformPluginFamily.kext/Contents/PlugIns/X86PlatformPlugin.kext/Contents/MacOS/X86PlatformPlugin"
};
static const char *idList[] {
"com.apple.driver.X86PlatformPlugin"
};
static const char *symbolList[] {
"__ZN17X86PlatformPlugin22configResourceCallbackEjiPKvjPv"
};
static KernelPatcher::KextInfo kextList[] {
{ idList[0], &binList[0], arrsize(binList), {false, false}, {}, KernelPatcher::KextInfo::Unloaded }
};
static constexpr size_t kextListSize {arrsize(kextList)};
static CPUFriendPlugin *callbackCpuf {nullptr};
OSDefineMetaClassAndStructors(CPUFriendPlatform, IOService)
IOService *CPUFriendPlatform::probe(IOService *provider, SInt32 *score) {
if (provider) {
if (callbackCpuf) {
if (!callbackCpuf->frequencyData) {
auto name = provider->getName();
if (!name)
name = "(null)";
DBGLOG("cpuf", "looking for cf-frequency-data in %s", name);
auto data = OSDynamicCast(OSData, provider->getProperty("cf-frequency-data"));
if (!data) {
auto cpu = provider->getParentEntry(gIOServicePlane);
if (cpu) {
name = cpu->getName();
if (!name)
name = "(null)";
DBGLOG("cpuf", "looking for cf-frequency-data in %s", name);
data = OSDynamicCast(OSData, cpu->getProperty("cf-frequency-data"));
} else {
DBGLOG("cpuf", "unable to access cpu parent");
}
}
if (data) {
callbackCpuf->frequencyDataSize = data->getLength();
callbackCpuf->frequencyData = data->getBytesNoCopy();
} else {
DBGLOG("cpuf", "failed to obtain cf-frequency-data");
}
}
} else {
DBGLOG("cpuf", "missing storage instance");
}
}
return nullptr;
}
bool CPUFriendPlugin::init() {
callbackCpuf = this;
LiluAPI::Error error = lilu.onKextLoad(kextList, kextListSize,
[](void *user, KernelPatcher &patcher, size_t index, mach_vm_address_t address, size_t size) {
static_cast<CPUFriendPlugin *>(user)->processKext(patcher, index, address, size);
}, this);
if (error != LiluAPI::Error::NoError) {
DBGLOG("cpuf", "failed to register onKextLoad method %d", error);
return false;
}
return true;
}
void CPUFriendPlugin::myConfigResourceCallback(uint32_t requestTag, kern_return_t result, const void *resourceData, uint32_t resourceDataLength, void *context) {
if (callbackCpuf && callbackCpuf->orgConfigLoadCallback) {
auto data = callbackCpuf->frequencyData;
auto sz = callbackCpuf->frequencyDataSize;
if (data && sz > 0) {
DBGLOG("cpuf", "feeding frequency data %u", sz);
resourceData = data;
resourceDataLength = sz;
result = kOSReturnSuccess;
} else {
DBGLOG("cpuf", "failed to feed cpu data (%u, %d)", sz, data != nullptr);
}
callbackCpuf->orgConfigLoadCallback(requestTag, result, resourceData, resourceDataLength, context);
} else {
DBGLOG("cpuf", "config callback arrived at nowhere");
}
}
void CPUFriendPlugin::processKext(KernelPatcher &patcher, size_t index, mach_vm_address_t address, size_t size) {
if (progressState != cpufessingState::EverythingDone) {
for (size_t i = 0; i < kextListSize; i++) {
if (kextList[i].loadIndex == index) {
DBGLOG("cpuf", "current kext is %s progressState %d", kextList[i].id, progressState);
if (!strcmp(kextList[i].id, idList[0])) {
auto callback = patcher.solveSymbol(index, symbolList[0]);
if (callback) {
orgConfigLoadCallback = reinterpret_cast<t_callback>(patcher.routeFunction(callback, reinterpret_cast<mach_vm_address_t>(myConfigResourceCallback), true));
if (patcher.getError() == KernelPatcher::Error::NoError) {
DBGLOG("cpuf", "routed %s", symbolList[0]);
} else {
DBGLOG("cpuf", "failed to route %s", symbolList[0]);
}
} else {
DBGLOG("cpuf", "failed to find %s", symbolList[0]);
}
progressState |= cpufessingState::CallbackRouted;
}
// Ignore all the errors for other processors
patcher.clearError();
break;
}
}
}
}
<commit_msg>Slightly optimised logging<commit_after>//
// kern_cpuf.cpp
// CPUFriend
//
// Copyright © 2017 Vanilla. All rights reserved.
//
#include <Headers/kern_api.hpp>
#include "kern_cpuf.hpp"
static const char *binList[] {
"/System/Library/Extensions/IOPlatformPluginFamily.kext/Contents/PlugIns/X86PlatformPlugin.kext/Contents/MacOS/X86PlatformPlugin"
};
static const char *idList[] {
"com.apple.driver.X86PlatformPlugin"
};
static const char *symbolList[] {
"__ZN17X86PlatformPlugin22configResourceCallbackEjiPKvjPv"
};
static KernelPatcher::KextInfo kextList[] {
{ idList[0], &binList[0], arrsize(binList), {false, false}, {}, KernelPatcher::KextInfo::Unloaded }
};
static constexpr size_t kextListSize {arrsize(kextList)};
static CPUFriendPlugin *callbackCpuf {nullptr};
OSDefineMetaClassAndStructors(CPUFriendPlatform, IOService)
IOService *CPUFriendPlatform::probe(IOService *provider, SInt32 *score) {
if (provider) {
if (callbackCpuf) {
if (!callbackCpuf->frequencyData) {
auto name = provider->getName();
if (!name)
name = "(null)";
DBGLOG("probing", "looking for cf-frequency-data in %s", name);
auto data = OSDynamicCast(OSData, provider->getProperty("cf-frequency-data"));
if (!data) {
auto cpu = provider->getParentEntry(gIOServicePlane);
if (cpu) {
name = cpu->getName();
if (!name)
name = "(null)";
DBGLOG("probing", "looking for cf-frequency-data in %s", name);
data = OSDynamicCast(OSData, cpu->getProperty("cf-frequency-data"));
} else {
DBGLOG("probing", "unable to access cpu parent");
}
}
if (data) {
callbackCpuf->frequencyDataSize = data->getLength();
callbackCpuf->frequencyData = data->getBytesNoCopy();
} else {
DBGLOG("probing", "failed to obtain cf-frequency-data");
}
}
} else {
DBGLOG("probing", "missing storage instance");
}
}
return nullptr;
}
bool CPUFriendPlugin::init() {
callbackCpuf = this;
LiluAPI::Error error = lilu.onKextLoad(kextList, kextListSize,
[](void *user, KernelPatcher &patcher, size_t index, mach_vm_address_t address, size_t size) {
static_cast<CPUFriendPlugin *>(user)->processKext(patcher, index, address, size);
}, this);
if (error != LiluAPI::Error::NoError) {
SYSLOG("init", "failed to register onKextLoad method %d", error);
return false;
}
return true;
}
void CPUFriendPlugin::myConfigResourceCallback(uint32_t requestTag, kern_return_t result, const void *resourceData, uint32_t resourceDataLength, void *context) {
if (callbackCpuf && callbackCpuf->orgConfigLoadCallback) {
auto data = callbackCpuf->frequencyData;
auto sz = callbackCpuf->frequencyDataSize;
if (data && sz > 0) {
DBGLOG("myConfigResourceCallback", "feeding frequency data %u", sz);
resourceData = data;
resourceDataLength = sz;
result = kOSReturnSuccess;
} else {
DBGLOG("myConfigResourceCallback", "failed to feed cpu data (%u, %d)", sz, data != nullptr);
}
callbackCpuf->orgConfigLoadCallback(requestTag, result, resourceData, resourceDataLength, context);
} else {
DBGLOG("myConfigResourceCallback", "config callback arrived at nowhere");
}
}
void CPUFriendPlugin::processKext(KernelPatcher &patcher, size_t index, mach_vm_address_t address, size_t size) {
if (progressState != cpufessingState::EverythingDone) {
for (size_t i = 0; i < kextListSize; i++) {
if (kextList[i].loadIndex == index) {
DBGLOG("processKext", "current kext is %s progressState %d", kextList[i].id, progressState);
if (!strcmp(kextList[i].id, idList[0])) {
auto callback = patcher.solveSymbol(index, symbolList[0]);
if (callback) {
orgConfigLoadCallback = reinterpret_cast<t_callback>(patcher.routeFunction(callback, reinterpret_cast<mach_vm_address_t>(myConfigResourceCallback), true));
if (patcher.getError() == KernelPatcher::Error::NoError) {
DBGLOG("processKext", "routed %s", symbolList[0]);
} else {
DBGLOG("processKext", "failed to route %s", symbolList[0]);
}
} else {
DBGLOG("processKext", "failed to find %s", symbolList[0]);
}
progressState |= cpufessingState::CallbackRouted;
}
// Ignore all the errors for other processors
patcher.clearError();
break;
}
}
}
}
<|endoftext|> |
<commit_before>/**
* @file hmm_train_main.cpp
* @author Ryan Curtin
*
* Executable which trains an HMM and saves the trained HMM to file.
*/
#include <mlpack/core.hpp>
#include "hmm.hpp"
#include "hmm_util.hpp"
#include <mlpack/methods/gmm/gmm.hpp>
PROGRAM_INFO("Hidden Markov Model (HMM) Training", "This program allows a "
"Hidden Markov Model to be trained on labeled or unlabeled data. It "
"support three types of HMMs: discrete HMMs, Gaussian HMMs, or GMM HMMs."
"\n\n"
"Either one input sequence can be specified (with --input_file), or, a "
"file containing files in which input sequences can be found (when "
"--input_file and --batch are used together). In addition, labels can be "
"provided in the file specified by --label_file, and if --batch is used, "
"the file given to --label_file should contain a list of files of labels "
"corresponding to the sequences in the file given to --input_file."
"\n\n"
"The HMM is trained with the Baum-Welch algorithm if no labels are "
"provided. The tolerance of the Baum-Welch algorithm can be set with the "
"--tolerance option."
"\n\n"
"Optionally, a pre-created HMM model can be used as a guess for the "
"transition matrix and emission probabilities; this is specifiable with "
"--model_file.");
PARAM_STRING_REQ("input_file", "File containing input observations.", "i");
PARAM_STRING_REQ("type", "Type of HMM: discrete | gaussian | gmm.", "t");
PARAM_FLAG("batch", "If true, input_file (and if passed, labels_file) are "
"expected to contain a list of files to use as input observation sequences "
"(and label sequences).", "b");
PARAM_INT("states", "Number of hidden states in HMM (necessary, unless "
"model_file is specified.", "n", 0);
PARAM_INT("gaussians", "Number of gaussians in each GMM (necessary when type is"
" 'gmm'.", "g", 0);
PARAM_STRING("model_file", "Pre-existing HMM model (optional).", "m", "");
PARAM_STRING("labels_file", "Optional file of hidden states, used for "
"labeled training.", "l", "");
PARAM_STRING("output_file", "File to save trained HMM to.", "o",
"output_hmm.xml");
PARAM_INT("seed", "Random seed. If 0, 'std::time(NULL)' is used.", "s", 0);
PARAM_DOUBLE("tolerance", "Tolerance of the Baum-Welch algorithm.", "T", 1e-5);
using namespace mlpack;
using namespace mlpack::hmm;
using namespace mlpack::distribution;
using namespace mlpack::util;
using namespace mlpack::gmm;
using namespace mlpack::math;
using namespace arma;
using namespace std;
// Because we don't know what the type of our HMM is, we need to write a
// function that can take arbitrary HMM types.
struct Train
{
template<typename HMMType>
static void Apply(HMMType& hmm, vector<mat>* trainSeqPtr)
{
const bool batch = CLI::HasParam("batch");
const double tolerance = CLI::GetParam<double>("tolerance");
// Do we need to replace the tolerance?
if (CLI::HasParam("tolerance"))
hmm.Tolerance() = tolerance;
const string labelsFile = CLI::GetParam<string>("labels_file");
// Verify that the dimensionality of our observations is the same as the
// dimensionality of our HMM's emissions.
vector<mat>& trainSeq = *trainSeqPtr;
for (size_t i = 0; i < trainSeq.size(); ++i)
if (trainSeq[i].n_rows != hmm.Emission()[0].Dimensionality())
Log::Fatal << "Dimensionality of training sequence " << i << " ("
<< trainSeq[i].n_rows << ") is not equal to the dimensionality of "
<< "the HMM (" << hmm.Emission()[0].Dimensionality() << ")!"
<< endl;
vector<arma::Col<size_t> > labelSeq; // May be empty.
if (labelsFile != "")
{
// Do we have multiple label files to load?
char lineBuf[1024];
if (batch)
{
fstream f(labelsFile);
if (!f.is_open())
Log::Fatal << "Could not open '" << labelsFile << "' for reading."
<< endl;
// Now read each line in.
f.getline(lineBuf, 1024, '\n');
while (!f.eof())
{
Log::Info << "Adding training sequence labels from '" << lineBuf
<< "'." << endl;
// Now read the matrix.
Mat<size_t> label;
data::Load(lineBuf, label, true); // Fatal on failure.
// Ensure that matrix only has one column.
if (label.n_rows == 1)
label = trans(label);
if (label.n_cols > 1)
Log::Fatal << "Invalid labels; must be one-dimensional." << endl;
labelSeq.push_back(label.col(0));
f.getline(lineBuf, 1024, '\n');
}
f.close();
}
else
{
Mat<size_t> label;
data::Load(labelsFile, label, true);
// Ensure that matrix only has one column.
if (label.n_rows == 1)
label = trans(label);
if (label.n_cols > 1)
Log::Fatal << "Invalid labels; must be one-dimensional." << endl;
// Verify the same number of observations as the data.
if (label.n_elem != trainSeq[labelSeq.size()].n_cols)
Log::Fatal << "Label sequence " << labelSeq.size() << " does not have"
<< " the same number of points as observation sequence "
<< labelSeq.size() << "!" << endl;
labelSeq.push_back(label.col(0));
}
// Now perform the training with labels.
hmm.Train(trainSeq, labelSeq);
}
else
{
// Perform unsupervised training.
hmm.Train(trainSeq);
}
// Save the model.
const string modelFile = CLI::GetParam<string>("model_file");
SaveHMM(hmm, modelFile);
}
};
int main(int argc, char** argv)
{
// Parse command line options.
CLI::ParseCommandLine(argc, argv);
// Set random seed.
if (CLI::GetParam<int>("seed") != 0)
RandomSeed((size_t) CLI::GetParam<int>("seed"));
else
RandomSeed((size_t) time(NULL));
// Validate parameters.
const string modelFile = CLI::GetParam<string>("model_file");
const string inputFile = CLI::GetParam<string>("input_file");
const string type = CLI::GetParam<string>("type");
const size_t states = CLI::GetParam<int>("states");
const double tolerance = CLI::GetParam<double>("tolerance");
const bool batch = CLI::HasParam("batch");
// Verify that either a model or a type was given.
if (modelFile == "" && type == "")
Log::Fatal << "No model file specified and no HMM type given! At least "
<< "one is required." << endl;
// If no model is specified, make sure we are training with valid parameters.
if (modelFile == "")
{
// Validate number of states.
if (states == 0)
Log::Fatal << "Must specify number of states if model file is not "
<< "specified!" << endl;
}
if (modelFile != "" && CLI::HasParam("tolerance"))
Log::Info << "Tolerance of existing model in '" << modelFile << "' will be "
<< "replaced with specified tolerance of " << tolerance << "." << endl;
// Load the input data.
vector<mat> trainSeq;
if (batch)
{
// The input file contains a list of files to read.
Log::Info << "Reading list of training sequences from '" << inputFile
<< "'." << endl;
fstream f(inputFile.c_str(), ios_base::in);
if (!f.is_open())
Log::Fatal << "Could not open '" << inputFile << "' for reading."
<< endl;
// Now read each line in.
char lineBuf[1024]; // Max 1024 characters... hopefully long enough.
f.getline(lineBuf, 1024, '\n');
while (!f.eof())
{
Log::Info << "Adding training sequence from '" << lineBuf << "'."
<< endl;
// Now read the matrix.
trainSeq.push_back(mat());
data::Load(lineBuf, trainSeq.back(), true); // Fatal on failure.
// See if we need to transpose the data.
if (type == "discrete")
{
if (trainSeq.back().n_cols == 1)
trainSeq.back() = trans(trainSeq.back());
}
f.getline(lineBuf, 1024, '\n');
}
f.close();
}
else
{
// Only one input file.
trainSeq.resize(1);
data::Load(inputFile, trainSeq[0], true);
}
// If we have a model file, we can autodetect the type.
if (modelFile != "")
{
LoadHMMAndPerformAction<Train>(modelFile, &trainSeq);
}
else
{
// We need to read in the type and build the HMM by hand.
const string type = CLI::GetParam<string>("type");
if (type == "discrete")
{
// Maximum observation is necessary so we know how to train the discrete
// distribution.
size_t maxEmission = 0;
for (vector<mat>::iterator it = trainSeq.begin(); it != trainSeq.end();
++it)
{
size_t maxSeq = size_t(as_scalar(max(trainSeq[0], 1))) + 1;
if (maxSeq > maxEmission)
maxEmission = maxSeq;
}
Log::Info << maxEmission << " discrete observations in the input data."
<< endl;
// Create HMM object.
HMM<DiscreteDistribution> hmm(size_t(states),
DiscreteDistribution(maxEmission), tolerance);
// Now train it. Pass the already-loaded training data.
Train::Apply(hmm, &trainSeq);
}
else if (type == "gaussian")
{
// Find dimension of the data.
const size_t dimensionality = trainSeq[0].n_rows;
// Verify dimensionality of data.
for (size_t i = 0; i < trainSeq.size(); ++i)
if (trainSeq[i].n_rows != dimensionality)
Log::Fatal << "Observation sequence " << i << " dimensionality ("
<< trainSeq[i].n_rows << " is incorrect (should be "
<< dimensionality << ")!" << endl;
HMM<GaussianDistribution> hmm(size_t(states),
GaussianDistribution(dimensionality), tolerance);
// Now train it.
Train::Apply(hmm, &trainSeq);
}
else if (type == "gmm")
{
// Find dimension of the data.
const size_t dimensionality = trainSeq[0].n_rows;
const int gaussians = CLI::GetParam<int>("gaussians");
if (gaussians == 0)
Log::Fatal << "Number of gaussians for each GMM must be specified (-g) "
<< "when type = 'gmm'!" << endl;
if (gaussians < 0)
Log::Fatal << "Invalid number of gaussians (" << gaussians << "); must "
<< "be greater than or equal to 1." << endl;
// Create HMM object.
HMM<GMM<>> hmm(size_t(states), GMM<>(size_t(gaussians), dimensionality),
tolerance);
// Issue a warning if the user didn't give labels.
if (!CLI::HasParam("label_file"))
Log::Warn << "Unlabeled training of GMM HMMs is almost certainly not "
<< "going to produce good results!" << endl;
Train::Apply(hmm, &trainSeq);
}
else
{
Log::Fatal << "Unknown HMM type: " << type << "; must be 'discrete', "
<< "'gaussian', or 'gmm'." << endl;
}
}
}
<commit_msg>Use CLI parameters correctly.<commit_after>/**
* @file hmm_train_main.cpp
* @author Ryan Curtin
*
* Executable which trains an HMM and saves the trained HMM to file.
*/
#include <mlpack/core.hpp>
#include "hmm.hpp"
#include "hmm_util.hpp"
#include <mlpack/methods/gmm/gmm.hpp>
PROGRAM_INFO("Hidden Markov Model (HMM) Training", "This program allows a "
"Hidden Markov Model to be trained on labeled or unlabeled data. It "
"support three types of HMMs: discrete HMMs, Gaussian HMMs, or GMM HMMs."
"\n\n"
"Either one input sequence can be specified (with --input_file), or, a "
"file containing files in which input sequences can be found (when "
"--input_file and --batch are used together). In addition, labels can be "
"provided in the file specified by --labels_file, and if --batch is used, "
"the file given to --labels_file should contain a list of files of labels "
"corresponding to the sequences in the file given to --input_file."
"\n\n"
"The HMM is trained with the Baum-Welch algorithm if no labels are "
"provided. The tolerance of the Baum-Welch algorithm can be set with the "
"--tolerance option."
"\n\n"
"Optionally, a pre-created HMM model can be used as a guess for the "
"transition matrix and emission probabilities; this is specifiable with "
"--model_file.");
PARAM_STRING_REQ("input_file", "File containing input observations.", "i");
PARAM_STRING_REQ("type", "Type of HMM: discrete | gaussian | gmm.", "t");
PARAM_FLAG("batch", "If true, input_file (and if passed, labels_file) are "
"expected to contain a list of files to use as input observation sequences "
"(and label sequences).", "b");
PARAM_INT("states", "Number of hidden states in HMM (necessary, unless "
"model_file is specified.", "n", 0);
PARAM_INT("gaussians", "Number of gaussians in each GMM (necessary when type is"
" 'gmm'.", "g", 0);
PARAM_STRING("model_file", "Pre-existing HMM model (optional).", "m", "");
PARAM_STRING("labels_file", "Optional file of hidden states, used for "
"labeled training.", "l", "");
PARAM_STRING("output_model_file", "File to save trained HMM to.", "o",
"output_hmm.xml");
PARAM_INT("seed", "Random seed. If 0, 'std::time(NULL)' is used.", "s", 0);
PARAM_DOUBLE("tolerance", "Tolerance of the Baum-Welch algorithm.", "T", 1e-5);
using namespace mlpack;
using namespace mlpack::hmm;
using namespace mlpack::distribution;
using namespace mlpack::util;
using namespace mlpack::gmm;
using namespace mlpack::math;
using namespace arma;
using namespace std;
// Because we don't know what the type of our HMM is, we need to write a
// function that can take arbitrary HMM types.
struct Train
{
template<typename HMMType>
static void Apply(HMMType& hmm, vector<mat>* trainSeqPtr)
{
const bool batch = CLI::HasParam("batch");
const double tolerance = CLI::GetParam<double>("tolerance");
// Do we need to replace the tolerance?
if (CLI::HasParam("tolerance"))
hmm.Tolerance() = tolerance;
const string labelsFile = CLI::GetParam<string>("labels_file");
// Verify that the dimensionality of our observations is the same as the
// dimensionality of our HMM's emissions.
vector<mat>& trainSeq = *trainSeqPtr;
for (size_t i = 0; i < trainSeq.size(); ++i)
if (trainSeq[i].n_rows != hmm.Emission()[0].Dimensionality())
Log::Fatal << "Dimensionality of training sequence " << i << " ("
<< trainSeq[i].n_rows << ") is not equal to the dimensionality of "
<< "the HMM (" << hmm.Emission()[0].Dimensionality() << ")!"
<< endl;
vector<arma::Col<size_t> > labelSeq; // May be empty.
if (labelsFile != "")
{
// Do we have multiple label files to load?
char lineBuf[1024];
if (batch)
{
fstream f(labelsFile);
if (!f.is_open())
Log::Fatal << "Could not open '" << labelsFile << "' for reading."
<< endl;
// Now read each line in.
f.getline(lineBuf, 1024, '\n');
while (!f.eof())
{
Log::Info << "Adding training sequence labels from '" << lineBuf
<< "'." << endl;
// Now read the matrix.
Mat<size_t> label;
data::Load(lineBuf, label, true); // Fatal on failure.
// Ensure that matrix only has one column.
if (label.n_rows == 1)
label = trans(label);
if (label.n_cols > 1)
Log::Fatal << "Invalid labels; must be one-dimensional." << endl;
labelSeq.push_back(label.col(0));
f.getline(lineBuf, 1024, '\n');
}
f.close();
}
else
{
Mat<size_t> label;
data::Load(labelsFile, label, true);
// Ensure that matrix only has one column.
if (label.n_rows == 1)
label = trans(label);
if (label.n_cols > 1)
Log::Fatal << "Invalid labels; must be one-dimensional." << endl;
// Verify the same number of observations as the data.
if (label.n_elem != trainSeq[labelSeq.size()].n_cols)
Log::Fatal << "Label sequence " << labelSeq.size() << " does not have"
<< " the same number of points as observation sequence "
<< labelSeq.size() << "!" << endl;
labelSeq.push_back(label.col(0));
}
// Now perform the training with labels.
hmm.Train(trainSeq, labelSeq);
}
else
{
// Perform unsupervised training.
hmm.Train(trainSeq);
}
// Save the model.
if (CLI::HasParam("output_model_file"))
{
const string modelFile = CLI::GetParam<string>("output_model_file");
SaveHMM(hmm, modelFile);
}
}
};
int main(int argc, char** argv)
{
// Parse command line options.
CLI::ParseCommandLine(argc, argv);
// Set random seed.
if (CLI::GetParam<int>("seed") != 0)
RandomSeed((size_t) CLI::GetParam<int>("seed"));
else
RandomSeed((size_t) time(NULL));
// Validate parameters.
const string modelFile = CLI::GetParam<string>("model_file");
const string inputFile = CLI::GetParam<string>("input_file");
const string type = CLI::GetParam<string>("type");
const size_t states = CLI::GetParam<int>("states");
const double tolerance = CLI::GetParam<double>("tolerance");
const bool batch = CLI::HasParam("batch");
// Verify that either a model or a type was given.
if (modelFile == "" && type == "")
Log::Fatal << "No model file specified and no HMM type given! At least "
<< "one is required." << endl;
// If no model is specified, make sure we are training with valid parameters.
if (modelFile == "")
{
// Validate number of states.
if (states == 0)
Log::Fatal << "Must specify number of states if model file is not "
<< "specified!" << endl;
}
if (modelFile != "" && CLI::HasParam("tolerance"))
Log::Info << "Tolerance of existing model in '" << modelFile << "' will be "
<< "replaced with specified tolerance of " << tolerance << "." << endl;
// Load the input data.
vector<mat> trainSeq;
if (batch)
{
// The input file contains a list of files to read.
Log::Info << "Reading list of training sequences from '" << inputFile
<< "'." << endl;
fstream f(inputFile.c_str(), ios_base::in);
if (!f.is_open())
Log::Fatal << "Could not open '" << inputFile << "' for reading."
<< endl;
// Now read each line in.
char lineBuf[1024]; // Max 1024 characters... hopefully long enough.
f.getline(lineBuf, 1024, '\n');
while (!f.eof())
{
Log::Info << "Adding training sequence from '" << lineBuf << "'."
<< endl;
// Now read the matrix.
trainSeq.push_back(mat());
data::Load(lineBuf, trainSeq.back(), true); // Fatal on failure.
// See if we need to transpose the data.
if (type == "discrete")
{
if (trainSeq.back().n_cols == 1)
trainSeq.back() = trans(trainSeq.back());
}
f.getline(lineBuf, 1024, '\n');
}
f.close();
}
else
{
// Only one input file.
trainSeq.resize(1);
data::Load(inputFile, trainSeq[0], true);
}
// If we have a model file, we can autodetect the type.
if (modelFile != "")
{
LoadHMMAndPerformAction<Train>(modelFile, &trainSeq);
}
else
{
// We need to read in the type and build the HMM by hand.
const string type = CLI::GetParam<string>("type");
if (type == "discrete")
{
// Maximum observation is necessary so we know how to train the discrete
// distribution.
size_t maxEmission = 0;
for (vector<mat>::iterator it = trainSeq.begin(); it != trainSeq.end();
++it)
{
size_t maxSeq = size_t(as_scalar(max(trainSeq[0], 1))) + 1;
if (maxSeq > maxEmission)
maxEmission = maxSeq;
}
Log::Info << maxEmission << " discrete observations in the input data."
<< endl;
// Create HMM object.
HMM<DiscreteDistribution> hmm(size_t(states),
DiscreteDistribution(maxEmission), tolerance);
// Now train it. Pass the already-loaded training data.
Train::Apply(hmm, &trainSeq);
}
else if (type == "gaussian")
{
// Find dimension of the data.
const size_t dimensionality = trainSeq[0].n_rows;
// Verify dimensionality of data.
for (size_t i = 0; i < trainSeq.size(); ++i)
if (trainSeq[i].n_rows != dimensionality)
Log::Fatal << "Observation sequence " << i << " dimensionality ("
<< trainSeq[i].n_rows << " is incorrect (should be "
<< dimensionality << ")!" << endl;
HMM<GaussianDistribution> hmm(size_t(states),
GaussianDistribution(dimensionality), tolerance);
// Now train it.
Train::Apply(hmm, &trainSeq);
}
else if (type == "gmm")
{
// Find dimension of the data.
const size_t dimensionality = trainSeq[0].n_rows;
const int gaussians = CLI::GetParam<int>("gaussians");
if (gaussians == 0)
Log::Fatal << "Number of gaussians for each GMM must be specified (-g) "
<< "when type = 'gmm'!" << endl;
if (gaussians < 0)
Log::Fatal << "Invalid number of gaussians (" << gaussians << "); must "
<< "be greater than or equal to 1." << endl;
// Create HMM object.
HMM<GMM<>> hmm(size_t(states), GMM<>(size_t(gaussians), dimensionality),
tolerance);
// Issue a warning if the user didn't give labels.
if (!CLI::HasParam("labels_file"))
Log::Warn << "Unlabeled training of GMM HMMs is almost certainly not "
<< "going to produce good results!" << endl;
Train::Apply(hmm, &trainSeq);
}
else
{
Log::Fatal << "Unknown HMM type: " << type << "; must be 'discrete', "
<< "'gaussian', or 'gmm'." << endl;
}
}
}
<|endoftext|> |
<commit_before>/**
* @file kmeans_impl.hpp
* @author Parikshit Ram (pram@cc.gatech.edu)
* @author Ryan Curtin
*
* Implementation for the K-means method for getting an initial point.
*/
#include "kmeans.hpp"
#include <mlpack/core/metrics/lmetric.hpp>
namespace mlpack {
namespace kmeans {
/**
* Construct the K-Means object.
*/
template<typename DistanceMetric,
typename InitialPartitionPolicy,
typename EmptyClusterPolicy>
KMeans<
DistanceMetric,
InitialPartitionPolicy,
EmptyClusterPolicy>::
KMeans(const size_t maxIterations,
const double overclusteringFactor,
const DistanceMetric metric,
const InitialPartitionPolicy partitioner,
const EmptyClusterPolicy emptyClusterAction) :
maxIterations(maxIterations),
metric(metric),
partitioner(partitioner),
emptyClusterAction(emptyClusterAction)
{
// Validate overclustering factor.
if (overclusteringFactor < 1.0)
{
Log::Warn << "KMeans::KMeans(): overclustering factor must be >= 1.0 ("
<< overclusteringFactor << " given). Setting factor to 1.0.\n";
this->overclusteringFactor = 1.0;
}
else
{
this->overclusteringFactor = overclusteringFactor;
}
}
/**
* Perform K-Means clustering on the data, returning a list of cluster
* assignments.
*/
template<typename DistanceMetric,
typename InitialPartitionPolicy,
typename EmptyClusterPolicy>
template<typename MatType>
void KMeans<
DistanceMetric,
InitialPartitionPolicy,
EmptyClusterPolicy>::
Cluster(const MatType& data,
const size_t clusters,
arma::Col<size_t>& assignments) const
{
// Make sure we have more points than clusters.
if (clusters > data.n_cols)
Log::Warn << "KMeans::Cluster(): more clusters requested than points given."
<< std::endl;
// Make sure our overclustering factor is valid.
size_t actualClusters = size_t(overclusteringFactor * clusters);
if (actualClusters > data.n_cols)
{
Log::Warn << "KMeans::Cluster(): overclustering factor is too large. No "
<< "overclustering will be done." << std::endl;
actualClusters = clusters;
}
// Now, the initial assignments. First determine if they are necessary.
if (assignments.n_elem != data.n_cols)
{
// Use the partitioner to come up with the partition assignments.
partitioner.Cluster(data, actualClusters, assignments);
}
// Centroids of each cluster. Each column corresponds to a centroid.
MatType centroids(data.n_rows, actualClusters);
// Counts of points in each cluster.
arma::Col<size_t> counts(actualClusters);
counts.zeros();
// Set counts correctly.
for (size_t i = 0; i < assignments.n_elem; i++)
counts[assignments[i]]++;
size_t changedAssignments = 0;
size_t iteration = 0;
do
{
// Update step.
// Calculate centroids based on given assignments.
centroids.zeros();
for (size_t i = 0; i < data.n_cols; i++)
centroids.col(assignments[i]) += data.col(i);
for (size_t i = 0; i < actualClusters; i++)
centroids.col(i) /= counts[i];
// Assignment step.
// Find the closest centroid to each point. We will keep track of how many
// assignments change. When no assignments change, we are done.
changedAssignments = 0;
for (size_t i = 0; i < data.n_cols; i++)
{
// Find the closest centroid to this point.
double minDistance = std::numeric_limits<double>::infinity();
size_t closestCluster = actualClusters; // Invalid value.
for (size_t j = 0; j < actualClusters; j++)
{
double distance = metric::SquaredEuclideanDistance::Evaluate(
data.col(i), centroids.col(j));
if (distance < minDistance)
{
minDistance = distance;
closestCluster = j;
}
}
// Reassign this point to the closest cluster.
if (assignments[i] != closestCluster)
{
// Update counts.
counts[assignments[i]]--;
counts[closestCluster]++;
// Update assignment.
assignments[i] = closestCluster;
changedAssignments++;
}
}
// If we are not allowing empty clusters, then check that all of our
// clusters have points.
for (size_t i = 0; i < actualClusters; i++)
if (counts[i] == 0)
changedAssignments += emptyClusterAction.EmptyCluster(data, i,
centroids, counts, assignments);
iteration++;
} while (changedAssignments > 0 && iteration != maxIterations);
// If we have overclustered, we need to merge the nearest clusters.
if (actualClusters != clusters)
{
// Generate a list of all the clusters' distances from each other. This
// list will become mangled and unused as the number of clusters decreases.
size_t numDistances = ((actualClusters - 1) * actualClusters) / 2;
size_t clustersLeft = actualClusters;
arma::vec distances(numDistances);
arma::Col<size_t> firstCluster(numDistances);
arma::Col<size_t> secondCluster(numDistances);
// Keep the mappings of clusters that we are changing.
arma::Col<size_t> mappings = arma::linspace<arma::Col<size_t> >(0,
actualClusters - 1, actualClusters);
size_t i = 0;
for (size_t first = 0; first < actualClusters; first++)
{
for (size_t second = first + 1; second < actualClusters; second++)
{
distances(i) = metric::SquaredEuclideanDistance::Evaluate(
centroids.col(first), centroids.col(second));
firstCluster(i) = first;
secondCluster(i) = second;
i++;
}
}
while (clustersLeft != clusters)
{
arma::u32 minIndex;
distances.min(minIndex);
// Now we merge the clusters which that distance belongs to.
size_t first = firstCluster(minIndex);
size_t second = secondCluster(minIndex);
for (size_t j = 0; j < assignments.n_elem; j++)
if (assignments(j) == second)
assignments(j) = first;
// Now merge the centroids.
centroids.col(first) *= counts[first];
centroids.col(first) += (counts[second] * centroids.col(second));
centroids.col(first) /= (counts[first] + counts[second]);
// Update the counts.
counts[first] += counts[second];
counts[second] = 0;
// Now update all the relevant distances.
// First the distances where either cluster is the second cluster.
for (size_t cluster = 0; cluster < second; cluster++)
{
// The offset is sum^n i - sum^(n - m) i, where n is actualClusters and
// m is the cluster we are trying to offset to.
size_t offset = (((actualClusters - 1) * cluster)
+ (cluster - pow(cluster, 2)) / 2) - 1;
// See if we need to update the distance from this cluster to the first
// cluster.
if (cluster < first)
{
// Make sure it isn't already DBL_MAX.
if (distances(offset + (first - cluster)) != DBL_MAX)
distances(offset + (first - cluster)) =
metric::SquaredEuclideanDistance::Evaluate(
centroids.col(first), centroids.col(cluster));
}
distances(offset + (second - cluster)) = DBL_MAX;
}
// Now the distances where the first cluster is the first cluster.
size_t offset = (((actualClusters - 1) * first)
+ (first - pow(first, 2)) / 2) - 1;
for (size_t cluster = first + 1; cluster < actualClusters; cluster++)
{
// Make sure it isn't already DBL_MAX.
if (distances(offset + (cluster - first)) != DBL_MAX)
{
distances(offset + (cluster - first)) =
metric::SquaredEuclideanDistance::Evaluate(
centroids.col(first), centroids.col(cluster));
}
}
// Max the distance between the first and second clusters.
distances(offset + (second - first)) = DBL_MAX;
// Now max the distances for the second cluster (which no longer has
// anything in it).
offset = (((actualClusters - 1) * second) + (second - pow(second, 2)) / 2)
- 1;
for (size_t cluster = second + 1; cluster < actualClusters; cluster++)
distances(offset + (cluster - second)) = DBL_MAX;
clustersLeft--;
// Update the cluster mappings.
mappings(second) = first;
// Also update any mappings that were pointed at the previous cluster.
for (size_t cluster = 0; cluster < actualClusters; cluster++)
if (mappings(cluster) == second)
mappings(cluster) = first;
}
// Now remap the mappings down to the smallest possible numbers.
// Could this process be sped up?
arma::Col<size_t> remappings(actualClusters);
remappings.fill(actualClusters);
size_t remap = 0; // Counter variable.
for (size_t cluster = 0; cluster < actualClusters; cluster++)
{
// If the mapping of the current cluster has not been assigned a value
// yet, we will assign it a cluster number.
if (remappings(mappings(cluster)) == actualClusters)
{
remappings(mappings(cluster)) = remap;
remap++;
}
}
// Fix the assignments using the mappings we created.
for (size_t j = 0; j < assignments.n_elem; j++)
assignments(j) = remappings(mappings(assignments(j)));
}
}
}; // namespace gmm
}; // namespace mlpack
<commit_msg>fixed some stupid typecasting warnings<commit_after>/**
* @file kmeans_impl.hpp
* @author Parikshit Ram (pram@cc.gatech.edu)
* @author Ryan Curtin
*
* Implementation for the K-means method for getting an initial point.
*/
#include "kmeans.hpp"
#include <mlpack/core/metrics/lmetric.hpp>
namespace mlpack {
namespace kmeans {
/**
* Construct the K-Means object.
*/
template<typename DistanceMetric,
typename InitialPartitionPolicy,
typename EmptyClusterPolicy>
KMeans<
DistanceMetric,
InitialPartitionPolicy,
EmptyClusterPolicy>::
KMeans(const size_t maxIterations,
const double overclusteringFactor,
const DistanceMetric metric,
const InitialPartitionPolicy partitioner,
const EmptyClusterPolicy emptyClusterAction) :
maxIterations(maxIterations),
metric(metric),
partitioner(partitioner),
emptyClusterAction(emptyClusterAction)
{
// Validate overclustering factor.
if (overclusteringFactor < 1.0)
{
Log::Warn << "KMeans::KMeans(): overclustering factor must be >= 1.0 ("
<< overclusteringFactor << " given). Setting factor to 1.0.\n";
this->overclusteringFactor = 1.0;
}
else
{
this->overclusteringFactor = overclusteringFactor;
}
}
/**
* Perform K-Means clustering on the data, returning a list of cluster
* assignments.
*/
template<typename DistanceMetric,
typename InitialPartitionPolicy,
typename EmptyClusterPolicy>
template<typename MatType>
void KMeans<
DistanceMetric,
InitialPartitionPolicy,
EmptyClusterPolicy>::
Cluster(const MatType& data,
const size_t clusters,
arma::Col<size_t>& assignments) const
{
// Make sure we have more points than clusters.
if (clusters > data.n_cols)
Log::Warn << "KMeans::Cluster(): more clusters requested than points given."
<< std::endl;
// Make sure our overclustering factor is valid.
size_t actualClusters = size_t(overclusteringFactor * clusters);
if (actualClusters > data.n_cols)
{
Log::Warn << "KMeans::Cluster(): overclustering factor is too large. No "
<< "overclustering will be done." << std::endl;
actualClusters = clusters;
}
// Now, the initial assignments. First determine if they are necessary.
if (assignments.n_elem != data.n_cols)
{
// Use the partitioner to come up with the partition assignments.
partitioner.Cluster(data, actualClusters, assignments);
}
// Centroids of each cluster. Each column corresponds to a centroid.
MatType centroids(data.n_rows, actualClusters);
// Counts of points in each cluster.
arma::Col<size_t> counts(actualClusters);
counts.zeros();
// Set counts correctly.
for (size_t i = 0; i < assignments.n_elem; i++)
counts[assignments[i]]++;
size_t changedAssignments = 0;
size_t iteration = 0;
do
{
// Update step.
// Calculate centroids based on given assignments.
centroids.zeros();
for (size_t i = 0; i < data.n_cols; i++)
centroids.col(assignments[i]) += data.col(i);
for (size_t i = 0; i < actualClusters; i++)
centroids.col(i) /= counts[i];
// Assignment step.
// Find the closest centroid to each point. We will keep track of how many
// assignments change. When no assignments change, we are done.
changedAssignments = 0;
for (size_t i = 0; i < data.n_cols; i++)
{
// Find the closest centroid to this point.
double minDistance = std::numeric_limits<double>::infinity();
size_t closestCluster = actualClusters; // Invalid value.
for (size_t j = 0; j < actualClusters; j++)
{
double distance = metric::SquaredEuclideanDistance::Evaluate(
data.col(i), centroids.col(j));
if (distance < minDistance)
{
minDistance = distance;
closestCluster = j;
}
}
// Reassign this point to the closest cluster.
if (assignments[i] != closestCluster)
{
// Update counts.
counts[assignments[i]]--;
counts[closestCluster]++;
// Update assignment.
assignments[i] = closestCluster;
changedAssignments++;
}
}
// If we are not allowing empty clusters, then check that all of our
// clusters have points.
for (size_t i = 0; i < actualClusters; i++)
if (counts[i] == 0)
changedAssignments += emptyClusterAction.EmptyCluster(data, i,
centroids, counts, assignments);
iteration++;
} while (changedAssignments > 0 && iteration != maxIterations);
// If we have overclustered, we need to merge the nearest clusters.
if (actualClusters != clusters)
{
// Generate a list of all the clusters' distances from each other. This
// list will become mangled and unused as the number of clusters decreases.
size_t numDistances = ((actualClusters - 1) * actualClusters) / 2;
size_t clustersLeft = actualClusters;
arma::vec distances(numDistances);
arma::Col<size_t> firstCluster(numDistances);
arma::Col<size_t> secondCluster(numDistances);
// Keep the mappings of clusters that we are changing.
arma::Col<size_t> mappings = arma::linspace<arma::Col<size_t> >(0,
actualClusters - 1, actualClusters);
size_t i = 0;
for (size_t first = 0; first < actualClusters; first++)
{
for (size_t second = first + 1; second < actualClusters; second++)
{
distances(i) = metric::SquaredEuclideanDistance::Evaluate(
centroids.col(first), centroids.col(second));
firstCluster(i) = first;
secondCluster(i) = second;
i++;
}
}
while (clustersLeft != clusters)
{
arma::u32 minIndex;
distances.min(minIndex);
// Now we merge the clusters which that distance belongs to.
size_t first = firstCluster(minIndex);
size_t second = secondCluster(minIndex);
for (size_t j = 0; j < assignments.n_elem; j++)
if (assignments(j) == second)
assignments(j) = first;
// Now merge the centroids.
centroids.col(first) *= counts[first];
centroids.col(first) += (counts[second] * centroids.col(second));
centroids.col(first) /= (counts[first] + counts[second]);
// Update the counts.
counts[first] += counts[second];
counts[second] = 0;
// Now update all the relevant distances.
// First the distances where either cluster is the second cluster.
for (size_t cluster = 0; cluster < second; cluster++)
{
// The offset is sum^n i - sum^(n - m) i, where n is actualClusters and
// m is the cluster we are trying to offset to.
size_t offset = (size_t) (((actualClusters - 1) * cluster)
+ (cluster - pow(cluster, 2)) / 2) - 1;
// See if we need to update the distance from this cluster to the first
// cluster.
if (cluster < first)
{
// Make sure it isn't already DBL_MAX.
if (distances(offset + (first - cluster)) != DBL_MAX)
distances(offset + (first - cluster)) =
metric::SquaredEuclideanDistance::Evaluate(
centroids.col(first), centroids.col(cluster));
}
distances(offset + (second - cluster)) = DBL_MAX;
}
// Now the distances where the first cluster is the first cluster.
size_t offset = (size_t) (((actualClusters - 1) * first)
+ (first - pow(first, 2)) / 2) - 1;
for (size_t cluster = first + 1; cluster < actualClusters; cluster++)
{
// Make sure it isn't already DBL_MAX.
if (distances(offset + (cluster - first)) != DBL_MAX)
{
distances(offset + (cluster - first)) =
metric::SquaredEuclideanDistance::Evaluate(
centroids.col(first), centroids.col(cluster));
}
}
// Max the distance between the first and second clusters.
distances(offset + (second - first)) = DBL_MAX;
// Now max the distances for the second cluster (which no longer has
// anything in it).
offset = (size_t) (((actualClusters - 1) * second)
+ (second - pow(second, 2)) / 2) - 1;
for (size_t cluster = second + 1; cluster < actualClusters; cluster++)
distances(offset + (cluster - second)) = DBL_MAX;
clustersLeft--;
// Update the cluster mappings.
mappings(second) = first;
// Also update any mappings that were pointed at the previous cluster.
for (size_t cluster = 0; cluster < actualClusters; cluster++)
if (mappings(cluster) == second)
mappings(cluster) = first;
}
// Now remap the mappings down to the smallest possible numbers.
// Could this process be sped up?
arma::Col<size_t> remappings(actualClusters);
remappings.fill(actualClusters);
size_t remap = 0; // Counter variable.
for (size_t cluster = 0; cluster < actualClusters; cluster++)
{
// If the mapping of the current cluster has not been assigned a value
// yet, we will assign it a cluster number.
if (remappings(mappings(cluster)) == actualClusters)
{
remappings(mappings(cluster)) = remap;
remap++;
}
}
// Fix the assignments using the mappings we created.
for (size_t j = 0; j < assignments.n_elem; j++)
assignments(j) = remappings(mappings(assignments(j)));
}
}
}; // namespace gmm
}; // namespace mlpack
<|endoftext|> |
<commit_before>#ifndef CONVERTERS_HPP_QNX3RWUJ
#define CONVERTERS_HPP_QNX3RWUJ
#include <stdexcept>
#include <memory>
#include <Spark/SparseMatrix.hpp>
#include <Eigen/Sparse>
#include <Spark/SparseMatrix.hpp>
#include <boost/numeric/ublas/io.hpp>
namespace spark {
namespace converters {
using EigenSparseMatrix = std::unique_ptr<Eigen::SparseMatrix<double, Eigen::RowMajor, int32_t>>;
// convert a Spark COO matrix to an Eigen Sparse Matrix
inline EigenSparseMatrix tripletToEigen(spark::sparse::SparkCooMatrix<double> mat) {
auto coo = mat.data;
EigenSparseMatrix m(new Eigen::SparseMatrix<double, Eigen::RowMajor, int32_t>(mat.n, mat.m));
std::vector<Eigen::Triplet<double>> trips;
for (size_t i = 0; i < coo.size(); i++)
trips.push_back(
Eigen::Triplet<double>(
std::get<0>(coo[i]),
std::get<1>(coo[i]),
std::get<2>(coo[i])));
m->setFromTriplets(trips.begin(), trips.end());
return m;
}
inline Eigen::VectorXd stdvectorToEigen(std::vector<double> v) {
Eigen::VectorXd m(v.size());
for (size_t i = 0; i < v.size(); i++)
m[i] = v[i];
return m;
}
inline std::vector<double> eigenVectorToStdVector(const Eigen::VectorXd& v) {
std::vector<double> m(v.size());
for (int i = 0; i < v.size(); i++)
m[i] = v[i];
return m;
}
}
}
#endif /* end of include guard: CONVERTERS_HPP_QNX3RWUJ */
<commit_msg>Remove final instance of ublas. Close #2<commit_after>#ifndef CONVERTERS_HPP_QNX3RWUJ
#define CONVERTERS_HPP_QNX3RWUJ
#include <stdexcept>
#include <memory>
#include <Spark/SparseMatrix.hpp>
#include <Eigen/Sparse>
#include <Spark/SparseMatrix.hpp>
namespace spark {
namespace converters {
using EigenSparseMatrix = std::unique_ptr<Eigen::SparseMatrix<double, Eigen::RowMajor, int32_t>>;
// convert a Spark COO matrix to an Eigen Sparse Matrix
inline EigenSparseMatrix tripletToEigen(spark::sparse::SparkCooMatrix<double> mat) {
auto coo = mat.data;
EigenSparseMatrix m(new Eigen::SparseMatrix<double, Eigen::RowMajor, int32_t>(mat.n, mat.m));
std::vector<Eigen::Triplet<double>> trips;
for (size_t i = 0; i < coo.size(); i++)
trips.push_back(
Eigen::Triplet<double>(
std::get<0>(coo[i]),
std::get<1>(coo[i]),
std::get<2>(coo[i])));
m->setFromTriplets(trips.begin(), trips.end());
return m;
}
inline Eigen::VectorXd stdvectorToEigen(std::vector<double> v) {
Eigen::VectorXd m(v.size());
for (size_t i = 0; i < v.size(); i++)
m[i] = v[i];
return m;
}
inline std::vector<double> eigenVectorToStdVector(const Eigen::VectorXd& v) {
std::vector<double> m(v.size());
for (int i = 0; i < v.size(); i++)
m[i] = v[i];
return m;
}
}
}
#endif /* end of include guard: CONVERTERS_HPP_QNX3RWUJ */
<|endoftext|> |
<commit_before>#include <network.hpp>
namespace MCPP {
namespace NetworkImpl {
void ReferenceManagerHandle::destroy () noexcept {
if (manager!=nullptr) {
manager->End();
manager=nullptr;
}
}
ReferenceManagerHandle::ReferenceManagerHandle (ReferenceManager & manager) noexcept : manager(&manager) {
manager.Begin();
}
ReferenceManagerHandle::ReferenceManagerHandle (const ReferenceManagerHandle & other) noexcept : manager(other.manager) {
if (manager!=nullptr) manager->Begin();
}
ReferenceManagerHandle::ReferenceManagerHandle (ReferenceManagerHandle && other) noexcept : manager(other.manager) {
other.manager=nullptr;
}
ReferenceManagerHandle & ReferenceManagerHandle::operator = (const ReferenceManagerHandle & other) noexcept {
if (this!=&other) {
destroy();
manager=other.manager;
if (manager!=nullptr) manager->Begin();
}
return *this;
}
ReferenceManagerHandle & ReferenceManagerHandle::operator = (ReferenceManagerHandle && other) noexcept {
if (this!=&other) {
destroy();
manager=other.manager;
other.manager=nullptr;
}
return *this;
}
ReferenceManagerHandle::~ReferenceManagerHandle () noexcept {
destroy();
}
ReferenceManager::ReferenceManager () noexcept : count(0) { }
ReferenceManager::~ReferenceManager () noexcept {
Wait();
}
void ReferenceManager::Begin () noexcept {
lock.Execute([&] () mutable { ++count; });
}
void ReferenceManager::End () noexcept {
lock.Execute([&] () mutable { --count; });
}
ReferenceManagerHandle ReferenceManager::Get () noexcept {
return ReferenceManagerHandle(*this);
}
void ReferenceManager::Wait () const noexcept {
lock.Execute([&] () mutable { while (count!=0) wait.Sleep(lock); });
}
void ReferenceManager::Reset () noexcept {
lock.Execute([&] () mutable { count=0; });
}
}
}
<commit_msg>Windows Network Stack Fix<commit_after>#include <network.hpp>
namespace MCPP {
namespace NetworkImpl {
void ReferenceManagerHandle::destroy () noexcept {
if (manager!=nullptr) {
manager->End();
manager=nullptr;
}
}
ReferenceManagerHandle::ReferenceManagerHandle (ReferenceManager & manager) noexcept : manager(&manager) {
manager.Begin();
}
ReferenceManagerHandle::ReferenceManagerHandle (const ReferenceManagerHandle & other) noexcept : manager(other.manager) {
if (manager!=nullptr) manager->Begin();
}
ReferenceManagerHandle::ReferenceManagerHandle (ReferenceManagerHandle && other) noexcept : manager(other.manager) {
other.manager=nullptr;
}
ReferenceManagerHandle & ReferenceManagerHandle::operator = (const ReferenceManagerHandle & other) noexcept {
if (this!=&other) {
destroy();
manager=other.manager;
if (manager!=nullptr) manager->Begin();
}
return *this;
}
ReferenceManagerHandle & ReferenceManagerHandle::operator = (ReferenceManagerHandle && other) noexcept {
if (this!=&other) {
destroy();
manager=other.manager;
other.manager=nullptr;
}
return *this;
}
ReferenceManagerHandle::~ReferenceManagerHandle () noexcept {
destroy();
}
ReferenceManager::ReferenceManager () noexcept : count(0) { }
ReferenceManager::~ReferenceManager () noexcept {
Wait();
}
void ReferenceManager::Begin () noexcept {
lock.Execute([&] () mutable { ++count; });
}
void ReferenceManager::End () noexcept {
lock.Execute([&] () mutable { if ((--count)==0) wait.WakeAll(); });
}
ReferenceManagerHandle ReferenceManager::Get () noexcept {
return ReferenceManagerHandle(*this);
}
void ReferenceManager::Wait () const noexcept {
lock.Execute([&] () mutable { while (count!=0) wait.Sleep(lock); });
}
void ReferenceManager::Reset () noexcept {
lock.Execute([&] () mutable { count=0; });
}
}
}
<|endoftext|> |
<commit_before>/*
// $Id$
// Fennel is a library of data storage and processing components.
// Copyright (C) 2004-2005 LucidEra, Inc.
// Copyright (C) 2005-2005 The Eigenbase Project
// Portions Copyright (C) 2004-2005 John V. Sichi
//
// This program is free software; you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published by the Free
// Software Foundation; either version 2 of the License, or (at your option)
// any later version approved by The Eigenbase Project.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "fennel/common/CommonPreamble.h"
#include "fennel/farrago/ExecStreamFactory.h"
#include "fennel/lucidera/sorter/ExternalSortExecStream.h"
#include "fennel/lucidera/flatfile/FlatFileExecStream.h"
#include "fennel/lucidera/colstore/LcsClusterAppendExecStream.h"
#include "fennel/lucidera/colstore/LcsRowScanExecStream.h"
#include "fennel/lucidera/bitmap/LbmGeneratorExecStream.h"
#include "fennel/lucidera/bitmap/LbmSplicerExecStream.h"
#include "fennel/lucidera/bitmap/LbmIndexScanExecStream.h"
#include "fennel/lucidera/bitmap/LbmChopperExecStream.h"
#include "fennel/lucidera/bitmap/LbmUnionExecStream.h"
#include "fennel/lucidera/bitmap/LbmIntersectExecStream.h"
#include "fennel/lucidera/hashexe/LhxJoinExecStream.h"
#include "fennel/db/Database.h"
#include "fennel/segment/SegmentFactory.h"
#include "fennel/exec/ExecStreamEmbryo.h"
#include "fennel/cache/QuotaCacheAccessor.h"
#ifdef __MINGW32__
#include <windows.h>
#endif
FENNEL_BEGIN_CPPFILE("$Id$");
class ExecStreamSubFactory_lu
: public ExecStreamSubFactory,
public FemVisitor
{
ExecStreamFactory *pExecStreamFactory;
ExecStreamEmbryo *pEmbryo;
bool created;
char readCharParam(const std::string &val)
{
assert(val.size() <= 1);
if (val.size() == 0) {
return 0;
}
return val.at(0);
}
DynamicParamId readDynamicParamId(const int val)
{
// NOTE: zero is a special code for no parameter id
uint id = (val < 0) ? 0 : (uint) val;
return (DynamicParamId) id;
}
void readClusterScan(
ProxyLcsRowScanStreamDef &streamDef,
LcsRowScanBaseExecStreamParams ¶ms)
{
SharedProxyLcsClusterScanDef pClusterScan = streamDef.getClusterScan();
for ( ; pClusterScan; ++pClusterScan) {
LcsClusterScanDef clusterScanParam;
clusterScanParam.pCacheAccessor = params.pCacheAccessor;
pExecStreamFactory->readBTreeStreamParams(clusterScanParam,
*pClusterScan);
pExecStreamFactory->readTupleDescriptor(
clusterScanParam.clusterTupleDesc,
pClusterScan->getClusterTupleDesc());
params.lcsClusterScanDefs.push_back(clusterScanParam);
}
}
// implement FemVisitor
virtual void visit(ProxySortingStreamDef &streamDef)
{
if (streamDef.getDistinctness() != DUP_ALLOW) {
// can't handle it
created = false;
return;
}
SharedDatabase pDatabase = pExecStreamFactory->getDatabase();
ExternalSortExecStreamParams params;
pExecStreamFactory->readTupleStreamParams(params, streamDef);
// ExternalSortStream requires a private ScratchSegment.
pExecStreamFactory->createPrivateScratchSegment(params);
params.distinctness = streamDef.getDistinctness();
params.pTempSegment = pDatabase->getTempSegment();
params.storeFinalRun = false;
CmdInterpreter::readTupleProjection(
params.keyProj,
streamDef.getKeyProj());
pEmbryo->init(
ExternalSortExecStream::newExternalSortExecStream(),
params);
}
// implement FemVisitor
virtual void visit(ProxyFlatFileTupleStreamDef &streamDef)
{
FlatFileExecStreamParams params;
pExecStreamFactory->readTupleStreamParams(params, streamDef);
assert(streamDef.getDataFilePath().size() > 0);
params.dataFilePath = streamDef.getDataFilePath();
params.errorFilePath = streamDef.getErrorFilePath();
params.fieldDelim = readCharParam(streamDef.getFieldDelimiter());
params.rowDelim = readCharParam(streamDef.getRowDelimiter());
params.quoteChar = readCharParam(streamDef.getQuoteCharacter());
params.escapeChar = readCharParam(streamDef.getEscapeCharacter());
params.header = streamDef.isHasHeader();
params.numRowsScan = streamDef.getNumRowsScan();
params.calcProgram = streamDef.getCalcProgram();
if (params.numRowsScan > 0 && params.calcProgram.size() > 0) {
params.mode = FLATFILE_MODE_SAMPLE;
} else if (params.numRowsScan > 0) {
params.mode = FLATFILE_MODE_DESCRIBE;
}
pEmbryo->init(FlatFileExecStream::newFlatFileExecStream(), params);
}
// implement FemVisitor
virtual void visit(ProxyLcsClusterAppendStreamDef &streamDef)
{
LcsClusterAppendExecStreamParams params;
pExecStreamFactory->readTupleStreamParams(params, streamDef);
pExecStreamFactory->readBTreeStreamParams(params, streamDef);
// LcsClusterAppendExecStream requires a private ScratchSegment.
pExecStreamFactory->createPrivateScratchSegment(params);
params.overwrite = streamDef.isOverwrite();
CmdInterpreter::readTupleProjection(
params.inputProj,
streamDef.getClusterColProj());
pEmbryo->init(
new LcsClusterAppendExecStream(),
params);
}
//implement FemVisitor
virtual void visit(ProxyLcsRowScanStreamDef &streamDef)
{
LcsRowScanExecStreamParams params;
pExecStreamFactory->readTupleStreamParams(params, streamDef);
readClusterScan(streamDef, params);
CmdInterpreter::readTupleProjection(params.outputProj,
streamDef.getOutputProj());
params.isFullScan = streamDef.isFullScan();
params.hasExtraFilter = streamDef.isHasExtraFilter();
pEmbryo->init(new LcsRowScanExecStream(), params);
}
// implement FemVisitor
virtual void visit(ProxyLbmGeneratorStreamDef &streamDef)
{
LbmGeneratorExecStreamParams params;
pExecStreamFactory->readTupleStreamParams(params, streamDef);
pExecStreamFactory->readBTreeStreamParams(params, streamDef);
// LbmGeneratorExecStream requires a private ScratchSegment.
pExecStreamFactory->createPrivateScratchSegment(params);
readClusterScan(streamDef, params);
CmdInterpreter::readTupleProjection(
params.outputProj, streamDef.getOutputProj());
params.dynParamId =
readDynamicParamId(streamDef.getRowCountParamId());
params.createIndex = streamDef.isCreateIndex();
pEmbryo->init(new LbmGeneratorExecStream(), params);
}
// implement FemVisitor
virtual void visit(ProxyLbmSplicerStreamDef &streamDef)
{
LbmSplicerExecStreamParams params;
pExecStreamFactory->readTupleStreamParams(params, streamDef);
pExecStreamFactory->readBTreeStreamParams(params, streamDef);
params.dynParamId =
readDynamicParamId(streamDef.getRowCountParamId());
pEmbryo->init(new LbmSplicerExecStream(), params);
}
// implement FemVisitor
virtual void visit(ProxyLbmIndexScanStreamDef &streamDef)
{
LbmIndexScanExecStreamParams params;
pExecStreamFactory->readBTreeSearchStreamParams(params, streamDef);
params.rowLimitParamId =
readDynamicParamId(streamDef.getRowLimitParamId());
params.startRidParamId =
readDynamicParamId(streamDef.getStartRidParamId());
pEmbryo->init(new LbmIndexScanExecStream(), params);
}
// implement FemVisitor
virtual void visit(ProxyLbmChopperStreamDef &streamDef)
{
LbmChopperExecStreamParams params;
pExecStreamFactory->readTupleStreamParams(params, streamDef);
params.ridLimitParamId =
readDynamicParamId(streamDef.getRidLimitParamId());
pEmbryo->init(new LbmChopperExecStream(), params);
}
// implement FemVisitor
virtual void visit(ProxyLbmUnionStreamDef &streamDef)
{
LbmUnionExecStreamParams params;
pExecStreamFactory->readTupleStreamParams(params, streamDef);
// LbmUnionExecStream requires a private ScratchSegment.
pExecStreamFactory->createPrivateScratchSegment(params);
params.startRidParamId =
readDynamicParamId(streamDef.getConsumerSridParamId());
params.segmentLimitParamId =
readDynamicParamId(streamDef.getSegmentLimitParamId());
params.ridLimitParamId =
readDynamicParamId(streamDef.getRidLimitParamId());
params.maxRid = (LcsRid) 0;
pEmbryo->init(new LbmUnionExecStream(), params);
}
// implement FemVisitor
virtual void visit(ProxyLbmIntersectStreamDef &streamDef)
{
LbmIntersectExecStreamParams params;
pExecStreamFactory->readTupleStreamParams(params, streamDef);
params.rowLimitParamId =
readDynamicParamId(streamDef.getRowLimitParamId());
params.startRidParamId =
readDynamicParamId(streamDef.getStartRidParamId());
pEmbryo->init(new LbmIntersectExecStream(), params);
}
// implement FemVisitor
virtual void visit(ProxyLhxJoinStreamDef &streamDef)
{
TupleProjection tmpProj;
LhxJoinExecStreamParams params;
pExecStreamFactory->readTupleStreamParams(params, streamDef);
/*
* These fields are currently not used by the optimizer. We know that
* optimizer only supports inner equi hash join.
*/
params.leftInner = true;
params.leftOuter = false;
params.rightInner = true;
params.rightOuter = false;
params.eliminateDuplicate = false;
CmdInterpreter::readTupleProjection(
params.leftKeyProj, streamDef.getLeftKeyProj());
CmdInterpreter::readTupleProjection(
params.rightKeyProj, streamDef.getRightKeyProj());
/*
* The optimizer currently estimates these two values.
*/
params.cndKeys = streamDef.getCndBuildKeys();
params.numRows = streamDef.getNumBuildRows();
pEmbryo->init(new LhxJoinExecStream(), params);
}
// implement JniProxyVisitor
virtual void unhandledVisit()
{
// not a stream type we know about
created = false;
}
// implement ExecStreamSubFactory
virtual bool createStream(
ExecStreamFactory &factory,
ProxyExecutionStreamDef &streamDef,
ExecStreamEmbryo &embryo)
{
pExecStreamFactory = &factory;
pEmbryo = &embryo;
created = true;
// dispatch based on polymorphic stream type
FemVisitor::visitTbl.accept(*this, streamDef);
return created;
}
};
#ifdef __MINGW32__
extern "C" JNIEXPORT BOOL APIENTRY DllMain(
HANDLE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved)
{
return TRUE;
}
#endif
extern "C" JNIEXPORT jint JNICALL
JNI_OnLoad(JavaVM *vm,void *)
{
JniUtil::initDebug("FENNEL_RS_JNI_DEBUG");
FENNEL_JNI_ONLOAD_COMMON();
return JniUtil::jniVersion;
}
extern "C" JNIEXPORT void JNICALL
Java_com_lucidera_farrago_fennel_LucidEraJni_registerStreamFactory(
JNIEnv *pEnvInit, jclass, jlong hStreamGraph)
{
JniEnvRef pEnv(pEnvInit);
try {
CmdInterpreter::StreamGraphHandle &streamGraphHandle =
CmdInterpreter::getStreamGraphHandleFromLong(hStreamGraph);
if (streamGraphHandle.pExecStreamFactory) {
streamGraphHandle.pExecStreamFactory->addSubFactory(
SharedExecStreamSubFactory(
new ExecStreamSubFactory_lu()));
}
} catch (std::exception &ex) {
pEnv.handleExcn(ex);
}
}
FENNEL_END_CPPFILE("$Id$");
// End NativeMethods_lu.cpp
<commit_msg>Fennel: hash join needs a private scratch segment.<commit_after>/*
// $Id$
// Fennel is a library of data storage and processing components.
// Copyright (C) 2004-2005 LucidEra, Inc.
// Copyright (C) 2005-2005 The Eigenbase Project
// Portions Copyright (C) 2004-2005 John V. Sichi
//
// This program is free software; you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published by the Free
// Software Foundation; either version 2 of the License, or (at your option)
// any later version approved by The Eigenbase Project.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "fennel/common/CommonPreamble.h"
#include "fennel/farrago/ExecStreamFactory.h"
#include "fennel/lucidera/sorter/ExternalSortExecStream.h"
#include "fennel/lucidera/flatfile/FlatFileExecStream.h"
#include "fennel/lucidera/colstore/LcsClusterAppendExecStream.h"
#include "fennel/lucidera/colstore/LcsRowScanExecStream.h"
#include "fennel/lucidera/bitmap/LbmGeneratorExecStream.h"
#include "fennel/lucidera/bitmap/LbmSplicerExecStream.h"
#include "fennel/lucidera/bitmap/LbmIndexScanExecStream.h"
#include "fennel/lucidera/bitmap/LbmChopperExecStream.h"
#include "fennel/lucidera/bitmap/LbmUnionExecStream.h"
#include "fennel/lucidera/bitmap/LbmIntersectExecStream.h"
#include "fennel/lucidera/hashexe/LhxJoinExecStream.h"
#include "fennel/db/Database.h"
#include "fennel/segment/SegmentFactory.h"
#include "fennel/exec/ExecStreamEmbryo.h"
#include "fennel/cache/QuotaCacheAccessor.h"
#ifdef __MINGW32__
#include <windows.h>
#endif
FENNEL_BEGIN_CPPFILE("$Id$");
class ExecStreamSubFactory_lu
: public ExecStreamSubFactory,
public FemVisitor
{
ExecStreamFactory *pExecStreamFactory;
ExecStreamEmbryo *pEmbryo;
bool created;
char readCharParam(const std::string &val)
{
assert(val.size() <= 1);
if (val.size() == 0) {
return 0;
}
return val.at(0);
}
DynamicParamId readDynamicParamId(const int val)
{
// NOTE: zero is a special code for no parameter id
uint id = (val < 0) ? 0 : (uint) val;
return (DynamicParamId) id;
}
void readClusterScan(
ProxyLcsRowScanStreamDef &streamDef,
LcsRowScanBaseExecStreamParams ¶ms)
{
SharedProxyLcsClusterScanDef pClusterScan = streamDef.getClusterScan();
for ( ; pClusterScan; ++pClusterScan) {
LcsClusterScanDef clusterScanParam;
clusterScanParam.pCacheAccessor = params.pCacheAccessor;
pExecStreamFactory->readBTreeStreamParams(clusterScanParam,
*pClusterScan);
pExecStreamFactory->readTupleDescriptor(
clusterScanParam.clusterTupleDesc,
pClusterScan->getClusterTupleDesc());
params.lcsClusterScanDefs.push_back(clusterScanParam);
}
}
// implement FemVisitor
virtual void visit(ProxySortingStreamDef &streamDef)
{
if (streamDef.getDistinctness() != DUP_ALLOW) {
// can't handle it
created = false;
return;
}
SharedDatabase pDatabase = pExecStreamFactory->getDatabase();
ExternalSortExecStreamParams params;
pExecStreamFactory->readTupleStreamParams(params, streamDef);
// ExternalSortStream requires a private ScratchSegment.
pExecStreamFactory->createPrivateScratchSegment(params);
params.distinctness = streamDef.getDistinctness();
params.pTempSegment = pDatabase->getTempSegment();
params.storeFinalRun = false;
CmdInterpreter::readTupleProjection(
params.keyProj,
streamDef.getKeyProj());
pEmbryo->init(
ExternalSortExecStream::newExternalSortExecStream(),
params);
}
// implement FemVisitor
virtual void visit(ProxyFlatFileTupleStreamDef &streamDef)
{
FlatFileExecStreamParams params;
pExecStreamFactory->readTupleStreamParams(params, streamDef);
assert(streamDef.getDataFilePath().size() > 0);
params.dataFilePath = streamDef.getDataFilePath();
params.errorFilePath = streamDef.getErrorFilePath();
params.fieldDelim = readCharParam(streamDef.getFieldDelimiter());
params.rowDelim = readCharParam(streamDef.getRowDelimiter());
params.quoteChar = readCharParam(streamDef.getQuoteCharacter());
params.escapeChar = readCharParam(streamDef.getEscapeCharacter());
params.header = streamDef.isHasHeader();
params.numRowsScan = streamDef.getNumRowsScan();
params.calcProgram = streamDef.getCalcProgram();
if (params.numRowsScan > 0 && params.calcProgram.size() > 0) {
params.mode = FLATFILE_MODE_SAMPLE;
} else if (params.numRowsScan > 0) {
params.mode = FLATFILE_MODE_DESCRIBE;
}
pEmbryo->init(FlatFileExecStream::newFlatFileExecStream(), params);
}
// implement FemVisitor
virtual void visit(ProxyLcsClusterAppendStreamDef &streamDef)
{
LcsClusterAppendExecStreamParams params;
pExecStreamFactory->readTupleStreamParams(params, streamDef);
pExecStreamFactory->readBTreeStreamParams(params, streamDef);
// LcsClusterAppendExecStream requires a private ScratchSegment.
pExecStreamFactory->createPrivateScratchSegment(params);
params.overwrite = streamDef.isOverwrite();
CmdInterpreter::readTupleProjection(
params.inputProj,
streamDef.getClusterColProj());
pEmbryo->init(
new LcsClusterAppendExecStream(),
params);
}
//implement FemVisitor
virtual void visit(ProxyLcsRowScanStreamDef &streamDef)
{
LcsRowScanExecStreamParams params;
pExecStreamFactory->readTupleStreamParams(params, streamDef);
readClusterScan(streamDef, params);
CmdInterpreter::readTupleProjection(params.outputProj,
streamDef.getOutputProj());
params.isFullScan = streamDef.isFullScan();
params.hasExtraFilter = streamDef.isHasExtraFilter();
pEmbryo->init(new LcsRowScanExecStream(), params);
}
// implement FemVisitor
virtual void visit(ProxyLbmGeneratorStreamDef &streamDef)
{
LbmGeneratorExecStreamParams params;
pExecStreamFactory->readTupleStreamParams(params, streamDef);
pExecStreamFactory->readBTreeStreamParams(params, streamDef);
// LbmGeneratorExecStream requires a private ScratchSegment.
pExecStreamFactory->createPrivateScratchSegment(params);
readClusterScan(streamDef, params);
CmdInterpreter::readTupleProjection(
params.outputProj, streamDef.getOutputProj());
params.dynParamId =
readDynamicParamId(streamDef.getRowCountParamId());
params.createIndex = streamDef.isCreateIndex();
pEmbryo->init(new LbmGeneratorExecStream(), params);
}
// implement FemVisitor
virtual void visit(ProxyLbmSplicerStreamDef &streamDef)
{
LbmSplicerExecStreamParams params;
pExecStreamFactory->readTupleStreamParams(params, streamDef);
pExecStreamFactory->readBTreeStreamParams(params, streamDef);
params.dynParamId =
readDynamicParamId(streamDef.getRowCountParamId());
pEmbryo->init(new LbmSplicerExecStream(), params);
}
// implement FemVisitor
virtual void visit(ProxyLbmIndexScanStreamDef &streamDef)
{
LbmIndexScanExecStreamParams params;
pExecStreamFactory->readBTreeSearchStreamParams(params, streamDef);
params.rowLimitParamId =
readDynamicParamId(streamDef.getRowLimitParamId());
params.startRidParamId =
readDynamicParamId(streamDef.getStartRidParamId());
pEmbryo->init(new LbmIndexScanExecStream(), params);
}
// implement FemVisitor
virtual void visit(ProxyLbmChopperStreamDef &streamDef)
{
LbmChopperExecStreamParams params;
pExecStreamFactory->readTupleStreamParams(params, streamDef);
params.ridLimitParamId =
readDynamicParamId(streamDef.getRidLimitParamId());
pEmbryo->init(new LbmChopperExecStream(), params);
}
// implement FemVisitor
virtual void visit(ProxyLbmUnionStreamDef &streamDef)
{
LbmUnionExecStreamParams params;
pExecStreamFactory->readTupleStreamParams(params, streamDef);
// LbmUnionExecStream requires a private ScratchSegment.
pExecStreamFactory->createPrivateScratchSegment(params);
params.startRidParamId =
readDynamicParamId(streamDef.getConsumerSridParamId());
params.segmentLimitParamId =
readDynamicParamId(streamDef.getSegmentLimitParamId());
params.ridLimitParamId =
readDynamicParamId(streamDef.getRidLimitParamId());
params.maxRid = (LcsRid) 0;
pEmbryo->init(new LbmUnionExecStream(), params);
}
// implement FemVisitor
virtual void visit(ProxyLbmIntersectStreamDef &streamDef)
{
LbmIntersectExecStreamParams params;
pExecStreamFactory->readTupleStreamParams(params, streamDef);
params.rowLimitParamId =
readDynamicParamId(streamDef.getRowLimitParamId());
params.startRidParamId =
readDynamicParamId(streamDef.getStartRidParamId());
pEmbryo->init(new LbmIntersectExecStream(), params);
}
// implement FemVisitor
virtual void visit(ProxyLhxJoinStreamDef &streamDef)
{
TupleProjection tmpProj;
LhxJoinExecStreamParams params;
pExecStreamFactory->readTupleStreamParams(params, streamDef);
// LhxJoinExecStream requires a private ScratchSegment.
pExecStreamFactory->createPrivateScratchSegment(params);
/*
* These fields are currently not used by the optimizer. We know that
* optimizer only supports inner equi hash join.
*/
params.leftInner = true;
params.leftOuter = false;
params.rightInner = true;
params.rightOuter = false;
params.eliminateDuplicate = false;
CmdInterpreter::readTupleProjection(
params.leftKeyProj, streamDef.getLeftKeyProj());
CmdInterpreter::readTupleProjection(
params.rightKeyProj, streamDef.getRightKeyProj());
/*
* The optimizer currently estimates these two values.
*/
params.cndKeys = streamDef.getCndBuildKeys();
params.numRows = streamDef.getNumBuildRows();
pEmbryo->init(new LhxJoinExecStream(), params);
}
// implement JniProxyVisitor
virtual void unhandledVisit()
{
// not a stream type we know about
created = false;
}
// implement ExecStreamSubFactory
virtual bool createStream(
ExecStreamFactory &factory,
ProxyExecutionStreamDef &streamDef,
ExecStreamEmbryo &embryo)
{
pExecStreamFactory = &factory;
pEmbryo = &embryo;
created = true;
// dispatch based on polymorphic stream type
FemVisitor::visitTbl.accept(*this, streamDef);
return created;
}
};
#ifdef __MINGW32__
extern "C" JNIEXPORT BOOL APIENTRY DllMain(
HANDLE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved)
{
return TRUE;
}
#endif
extern "C" JNIEXPORT jint JNICALL
JNI_OnLoad(JavaVM *vm,void *)
{
JniUtil::initDebug("FENNEL_RS_JNI_DEBUG");
FENNEL_JNI_ONLOAD_COMMON();
return JniUtil::jniVersion;
}
extern "C" JNIEXPORT void JNICALL
Java_com_lucidera_farrago_fennel_LucidEraJni_registerStreamFactory(
JNIEnv *pEnvInit, jclass, jlong hStreamGraph)
{
JniEnvRef pEnv(pEnvInit);
try {
CmdInterpreter::StreamGraphHandle &streamGraphHandle =
CmdInterpreter::getStreamGraphHandleFromLong(hStreamGraph);
if (streamGraphHandle.pExecStreamFactory) {
streamGraphHandle.pExecStreamFactory->addSubFactory(
SharedExecStreamSubFactory(
new ExecStreamSubFactory_lu()));
}
} catch (std::exception &ex) {
pEnv.handleExcn(ex);
}
}
FENNEL_END_CPPFILE("$Id$");
// End NativeMethods_lu.cpp
<|endoftext|> |
<commit_before>/******************************************************************************
Copyright (c) Dmitri Dolzhenko
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.
*******************************************************************************/
#pragma once
//------------------------------------------------------------------------------
// include local:
// include std:
#include <vector>
#include <list>
#include <set>
#include <cassert>
#include <string>
#include <map> // Tests
#include <algorithm> // std::find
#include <functional> // std::fucntion
#include <iostream>
#include <iomanip>
// forward declarations:
//------------------------------------------------------------------------------
namespace limo {
class TestContext;
typedef std::string Name;
typedef std::function<TestContext*(void)> TestContextGetter;
typedef std::function<void (TestContextGetter&)> TestFunction;
typedef std::function<void(void)> PrepareFunction;
typedef std::map<Name, TestFunction> Tests;
struct TestSettings
{
TestSettings(Name name, TestContext* suite): m_name(name), m_context(suite) {}
TestSettings& operator<<(TestFunction test) {
m_test = test;
return *this;
}
Name m_name;
TestContext* m_context;
TestFunction m_test;
};
struct Run
{
const char* expected;
const char* recieved;
const char* file;
const int line;
const bool ok;
};
struct Statistics
{
size_t total, passed, failured, crashed;
void reset() { total = passed = failured = crashed = 0; }
bool is_valid() const { return total == passed + failured + crashed; }
Statistics& operator+=(const Statistics& rhs)
{
total += rhs.total;
passed += rhs.passed;
failured += rhs.failured;
crashed += rhs.crashed;
return *this;
};
};
inline std::ostream& operator<<(std::ostream& o, const Run& run)
{
return o << run.file << ":" << run.line << ":: "
<< (run.ok ? "ok" : "failed") << ": "
<< run.expected << std::endl;
};
inline std::ostream& operator<<(std::ostream& o, const Statistics& stats)
{
return o << " crashed " << stats.crashed
<< ", failured " << stats.failured
<< ", passed " << stats.passed
<< ", total " << stats.total
<< ".";
assert(stats.is_valid());
};
class TestContext {
public:
static const bool verbose = true;
PrepareFunction m_before;
PrepareFunction m_after;
Name m_name;
Tests m_tests;
bool m_global;
Statistics stats;
public:
TestContext(Name name, bool global=false)
: m_name(name)
, m_global(global)
{
stats.reset();
m_before = [](){};
m_after = [](){};
if(!m_global && verbose) std::cout << m_name << std::endl;
}
virtual void test(Name name, TestFunction test)
{
run_test(name, test, m_name+".");
}
void run_test(Name name, TestFunction test, Name basename)
{
m_before();
TestContext context(basename + name);
TestContextGetter getter = [&context]() { return &context; };
test(getter);
// results[fullname] = info;
m_after();
stats += context.stats;
}
public: // outcomes
void expect_true(const char* file, int line, const char* expected, bool ok)
{
stats.total++;
Run run = {expected, ok ? "true" : "false", file, line, ok};
// db.push_back(run);
if(ok)
{
stats.passed++;
}
else
{
stats.failured++;
std::cout << run;
}
}
private:
};
class GlobalTestContext : public TestContext {
public:
GlobalTestContext(): TestContext("root", true) {}
bool run()
{
for(const auto& test : m_tests)
{
run_test(test.first, test.second, "");
}
std::cout << stats << std::endl;
return true;
}
virtual void test(Name name, TestFunction test) {
m_tests[name] = test;
}
};
struct Registrator {
Registrator(const TestSettings& w) {
w.m_context->test(w.m_name, w.m_test);
}
};
struct To { template <class T> To(const T&) {} };
// #define LTEST(test_name, ...) \
// To doreg##test_name = \
// get_ltest_context()->add(#test_name)
// limo::TestSettings(#test_name, get_ltest_context()) << \
// [__VA_ARGS__](limo::TestContextGetter& get_ltest_context) mutable -> void
#define LTEST(test_name, ...) \
limo::Registrator ltest_ ## test_name = \
limo::TestSettings(#test_name, get_ltest_context()) << \
[__VA_ARGS__](limo::TestContextGetter& get_ltest_context) mutable -> void
#define LBEFORE limo_context__.m_before = [&]()
#define LAFTER limo_context__.m_after = [&]()
// Unary
#define EXPECT_TRUE(expr) get_ltest_context()->expect_true(__FILE__, __LINE__, #expr, expr)
#define EXPECT_FALSE(expr) EXPECT_TRUE(!(expr))
// Binary
#define EXPECT_EQ(expr1, expr2) EXPECT_TRUE((expr1) == (expr2))
#define EXPECT_NE(expr1, expr2) EXPECT_TRUE((expr1) != (expr2))
#define EXPECT_LT(expr1, expr2) EXPECT_TRUE((expr1) < (expr2))
#define EXPECT_LE(expr1, expr2) EXPECT_TRUE((expr1) <= (expr2))
#define EXPECT_GT(expr1, expr2) EXPECT_TRUE((expr1) > (expr2))
#define EXPECT_GE(expr1, expr2) EXPECT_TRUE((expr1) >= (expr2))
// Complex
template <class T1, class T2>
bool in(const std::initializer_list<T1>& s, const T2& x) {
return std::find(s.begin(), s.end(), x) != s.end();
}
////////////////////////////////////////////////////////////////////////////////////////
} // namespace limo
//------------------------------------------------------------------------------
// globals
inline limo::GlobalTestContext* get_ltest_context() {
static limo::GlobalTestContext context;
return &context;
}
//------------------------------------------------------------------------------
<commit_msg>cut global flag<commit_after>/******************************************************************************
Copyright (c) Dmitri Dolzhenko
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.
*******************************************************************************/
#pragma once
//------------------------------------------------------------------------------
// include local:
// include std:
#include <vector>
#include <list>
#include <set>
#include <cassert>
#include <string>
#include <map> // Tests
#include <algorithm> // std::find
#include <functional> // std::fucntion
#include <iostream>
#include <iomanip>
// forward declarations:
//------------------------------------------------------------------------------
namespace limo {
class TestContext;
typedef std::string Name;
typedef std::function<TestContext*(void)> TestContextGetter;
typedef std::function<void (TestContextGetter&)> TestFunction;
typedef std::function<void(void)> PrepareFunction;
typedef std::map<Name, TestFunction> Tests;
struct TestSettings
{
TestSettings(Name name, TestContext* suite): m_name(name), m_context(suite) {}
TestSettings& operator<<(TestFunction test) {
m_test = test;
return *this;
}
Name m_name;
TestContext* m_context;
TestFunction m_test;
};
struct Run
{
const char* expected;
const char* recieved;
const char* file;
const int line;
const bool ok;
};
struct Statistics
{
size_t total, passed, failured, crashed;
void reset() { total = passed = failured = crashed = 0; }
bool is_valid() const { return total == passed + failured + crashed; }
Statistics& operator+=(const Statistics& rhs)
{
total += rhs.total;
passed += rhs.passed;
failured += rhs.failured;
crashed += rhs.crashed;
return *this;
};
};
inline std::ostream& operator<<(std::ostream& o, const Run& run)
{
return o << run.file << ":" << run.line << ":: "
<< (run.ok ? "ok" : "failed") << ": "
<< run.expected << std::endl;
};
inline std::ostream& operator<<(std::ostream& o, const Statistics& stats)
{
return o << " crashed " << stats.crashed
<< ", failured " << stats.failured
<< ", passed " << stats.passed
<< ", total " << stats.total
<< ".";
assert(stats.is_valid());
};
class TestContext {
public:
static const bool verbose = true;
PrepareFunction m_before;
PrepareFunction m_after;
Name m_name;
Tests m_tests;
Statistics stats;
public:
TestContext(Name name)
: m_name(name)
{
stats.reset();
m_before = [](){};
m_after = [](){};
if(verbose) std::cout << m_name << std::endl;
}
virtual void test(Name name, TestFunction test)
{
run_test(name, test, m_name+".");
}
void run_test(Name name, TestFunction test, Name basename)
{
m_before();
TestContext context(basename + name);
TestContextGetter getter = [&context]() { return &context; };
test(getter);
// results[fullname] = info;
m_after();
stats += context.stats;
}
public: // outcomes
void expect_true(const char* file, int line, const char* expected, bool ok)
{
stats.total++;
Run run = {expected, ok ? "true" : "false", file, line, ok};
// db.push_back(run);
if(ok)
{
stats.passed++;
}
else
{
stats.failured++;
std::cout << run;
}
}
private:
};
class GlobalTestContext : public TestContext {
public:
GlobalTestContext(): TestContext("root") {}
bool run()
{
for(const auto& test : m_tests)
{
run_test(test.first, test.second, "");
}
std::cout << stats << std::endl;
return true;
}
virtual void test(Name name, TestFunction test) {
m_tests[name] = test;
}
};
struct Registrator {
Registrator(const TestSettings& w) {
w.m_context->test(w.m_name, w.m_test);
}
};
struct To { template <class T> To(const T&) {} };
// #define LTEST(test_name, ...) \
// To doreg##test_name = \
// get_ltest_context()->add(#test_name)
// limo::TestSettings(#test_name, get_ltest_context()) << \
// [__VA_ARGS__](limo::TestContextGetter& get_ltest_context) mutable -> void
#define LTEST(test_name, ...) \
limo::Registrator ltest_ ## test_name = \
limo::TestSettings(#test_name, get_ltest_context()) << \
[__VA_ARGS__](limo::TestContextGetter& get_ltest_context) mutable -> void
#define LBEFORE limo_context__.m_before = [&]()
#define LAFTER limo_context__.m_after = [&]()
// Unary
#define EXPECT_TRUE(expr) get_ltest_context()->expect_true(__FILE__, __LINE__, #expr, expr)
#define EXPECT_FALSE(expr) EXPECT_TRUE(!(expr))
// Binary
#define EXPECT_EQ(expr1, expr2) EXPECT_TRUE((expr1) == (expr2))
#define EXPECT_NE(expr1, expr2) EXPECT_TRUE((expr1) != (expr2))
#define EXPECT_LT(expr1, expr2) EXPECT_TRUE((expr1) < (expr2))
#define EXPECT_LE(expr1, expr2) EXPECT_TRUE((expr1) <= (expr2))
#define EXPECT_GT(expr1, expr2) EXPECT_TRUE((expr1) > (expr2))
#define EXPECT_GE(expr1, expr2) EXPECT_TRUE((expr1) >= (expr2))
// Complex
template <class T1, class T2>
bool in(const std::initializer_list<T1>& s, const T2& x) {
return std::find(s.begin(), s.end(), x) != s.end();
}
////////////////////////////////////////////////////////////////////////////////////////
} // namespace limo
//------------------------------------------------------------------------------
// globals
inline limo::GlobalTestContext* get_ltest_context() {
static limo::GlobalTestContext context;
return &context;
}
//------------------------------------------------------------------------------
<|endoftext|> |
<commit_before>#include "GameScene.h"
#include "utils\global.h"
#include <chrono>
#include <algorithm>
USING_NS_CC;
using namespace std::chrono;
Scene* GameScene::createScene()
{
// 'scene' is an autorelease object
auto scene = Scene::createWithPhysics();
scene->getPhysicsWorld()->setAutoStep(false);
scene->getPhysicsWorld()->setGravity(Vec2::ZERO);
// 'layer' is an autorelease object
auto layer = GameScene::create();
layer->mWorld = scene->getPhysicsWorld();
// add layer as a child to scene
scene->addChild(layer);
// return the scene
return scene;
}
// on "init" you need to initialize your instance
bool GameScene::init()
{
//////////////////////////////
// 1. super init first
if ( !Layer::init() )
{
return false;
}
this->addListener();
this->visibleSize = Director::getInstance()->getVisibleSize();
this->origin = Director::getInstance()->getVisibleOrigin();
auto background = Sprite::create("background.jpg");
gameArea = background->getContentSize();
background->setPosition(gameArea / 2);
this->addChild(background, -1);
// received as the game starts
GSocket->on("initData", [=](GameSocket* client, Document& dom) {
this->selfId = dom["data"]["selfId"].GetString();
auto& arr = dom["data"]["players"];
for (SizeType i = 0; i < arr.Size(); i++) {
const std::string& id = arr[i].GetString();
if (id == selfId) {
this->selfPlayer = Player::create(gameArea / 2);
this->addChild(selfPlayer, 1);
// make the camera follow the player
this->runAction(Follow::create(selfPlayer));
}
else {
auto player = Player::create(gameArea / 2);
this->addChild(player, 1);
this->otherPlayers.insert(std::make_pair(id, player));
}
}
started = true;
});
// received periodically, like every x frames
GSocket->on("sync", [=](GameSocket* client, Document& dom) {
auto& arr = dom["data"];
for (SizeType i = 0; i < arr.Size(); i++) {
auto& data = arr[i]["data"];
// check ping
// milliseconds ms = duration_cast<milliseconds>(system_clock::now().time_since_epoch());
// CCLOG("ping: %lld", ms.count() - data["timestamp"].GetInt64());
const std::string& id = arr[i]["id"].GetString();
auto it = this->otherPlayers.find(id);
if (it == this->otherPlayers.end()) continue; // data of selfPlayer, just ignore it
auto player = it->second;
player->sync(data);
}
});
// deal with other players' shots
GSocket->on("shoot", [=](GameSocket* client, Document& dom) {
auto& data = dom["data"];
auto bullet = Bullet::create(Vec2(data["posX"].GetDouble(), data["posY"].GetDouble()), data["angle"].GetDouble());
this->addChild(bullet, 1);
});
// manually update the physics world
this->schedule(schedule_selector(GameScene::update), 1.0f / FRAME_RATE, kRepeatForever, 0.1f);
return true;
}
void GameScene::update(float dt) {
using std::max;
using std::min;
if (!started) return;
static int frameCounter = 0;
this->getScene()->getPhysicsWorld()->step(1.0f / FRAME_RATE);
frameCounter++;
if (frameCounter == SYNC_LIMIT) {
frameCounter = 0;
GSocket->sendEvent("sync", this->selfPlayer->createSyncData());
}
// bound the player in the map
auto pos = selfPlayer->getPosition();
auto size = selfPlayer->getContentSize() * selfPlayer->getScale();
pos.x = min(pos.x, gameArea.x - size.width / 2);
pos.x = max(pos.x, size.width / 2);
pos.y = min(pos.y, gameArea.y - size.height / 2);
pos.y = max(pos.y, size.height / 2);
selfPlayer->setPosition(pos);
}
void GameScene::onKeyPressed(EventKeyboard::KeyCode code, Event* event) {
switch (code) {
case cocos2d::EventKeyboard::KeyCode::KEY_W:
selfPlayer->setVelocityY(200.0f);
break;
case cocos2d::EventKeyboard::KeyCode::KEY_S:
selfPlayer->setVelocityY(-200.0f);
break;
case cocos2d::EventKeyboard::KeyCode::KEY_A:
selfPlayer->setVelocityX(-200.0f);
break;
case cocos2d::EventKeyboard::KeyCode::KEY_D:
selfPlayer->setVelocityX(200.0f);
break;
}
}
void GameScene::onKeyReleased(EventKeyboard::KeyCode code, Event* event) {
auto body = selfPlayer->getPhysicsBody();
switch (code) {
case cocos2d::EventKeyboard::KeyCode::KEY_W:
if (body->getVelocity().y < 0.0f) break;
selfPlayer->setVelocityY(0.0f);
break;
case cocos2d::EventKeyboard::KeyCode::KEY_S:
if (body->getVelocity().y > 0.0f) break;
selfPlayer->setVelocityY(0.0f);
break;
case cocos2d::EventKeyboard::KeyCode::KEY_A:
if (body->getVelocity().x > 0.0f) break;
selfPlayer->setVelocityX(0.0f);
break;
case cocos2d::EventKeyboard::KeyCode::KEY_D:
if (body->getVelocity().x < 0.0f) break;
selfPlayer->setVelocityX(0.0f);
break;
}
}
void GameScene::onMouseMove(EventMouse* event) {
auto pos = Vec2(event->getCursorX(), event->getCursorY());
// position of physicsBody as relative to the camera
selfPlayer->setRotation(-CC_RADIANS_TO_DEGREES((pos - selfPlayer->getPhysicsBody()->getPosition()).getAngle()) + 90.0f);
}
void GameScene::onMouseDown(EventMouse* event) {
// create a bullet
auto bullet = Bullet::create(selfPlayer->getPosition(), selfPlayer->getRotation());
this->addChild(bullet, 1);
// broadcast shooting event
bullet->broadcast();
}
bool GameScene::onContactBegin(PhysicsContact &contact) {
// TODO: better contacting item type check
// now only deal with bullet-player contact
auto node1 = (Sprite*)contact.getShapeA()->getBody()->getNode();
auto node2 = (Sprite*)contact.getShapeB()->getBody()->getNode();
auto boom = Boom::create(node1->getPosition());
this->addChild(boom, 2);
if (node1->getPhysicsBody()->getCategoryBitmask() == 0x00000002) {
node1->removeFromParentAndCleanup(true);
outOfRangeCheck.erase(node1);
}
else {
node2->removeFromParentAndCleanup(true);
outOfRangeCheck.erase(node2);
}
if (node1 == selfPlayer || node2 == selfPlayer) {
// self-player was hit
Document dom;
dom.SetObject();
dom.AddMember("type", "hit", dom.GetAllocator());
dom.AddMember("damage", 20.0f, dom.GetAllocator()); // TODO: damage determined by bullet type
GSocket->sendEvent("broadcast", dom);
}
return false;
}
void GameScene::addListener() {
auto keyboardListener = EventListenerKeyboard::create();
keyboardListener->onKeyPressed = CC_CALLBACK_2(GameScene::onKeyPressed, this);
keyboardListener->onKeyReleased = CC_CALLBACK_2(GameScene::onKeyReleased, this);
auto mouseListener = EventListenerMouse::create();
mouseListener->onMouseMove = CC_CALLBACK_1(GameScene::onMouseMove, this);
mouseListener->onMouseDown = CC_CALLBACK_1(GameScene::onMouseDown, this);
auto contactListener = EventListenerPhysicsContact::create();
contactListener->onContactBegin = CC_CALLBACK_1(GameScene::onContactBegin, this);
_eventDispatcher->addEventListenerWithSceneGraphPriority(keyboardListener, this);
_eventDispatcher->addEventListenerWithSceneGraphPriority(mouseListener, this);
_eventDispatcher->addEventListenerWithSceneGraphPriority(contactListener, this);
}
void resetPhysics(Node* node, PhysicsBody* body) {
node->removeComponent(node->getPhysicsBody());
node->setPhysicsBody(body);
}
<commit_msg>left-key-only shooting<commit_after>#include "GameScene.h"
#include "utils\global.h"
#include <chrono>
#include <algorithm>
USING_NS_CC;
using namespace std::chrono;
Scene* GameScene::createScene()
{
// 'scene' is an autorelease object
auto scene = Scene::createWithPhysics();
scene->getPhysicsWorld()->setAutoStep(false);
scene->getPhysicsWorld()->setGravity(Vec2::ZERO);
// 'layer' is an autorelease object
auto layer = GameScene::create();
layer->mWorld = scene->getPhysicsWorld();
// add layer as a child to scene
scene->addChild(layer);
// return the scene
return scene;
}
// on "init" you need to initialize your instance
bool GameScene::init()
{
//////////////////////////////
// 1. super init first
if ( !Layer::init() )
{
return false;
}
this->addListener();
this->visibleSize = Director::getInstance()->getVisibleSize();
this->origin = Director::getInstance()->getVisibleOrigin();
auto background = Sprite::create("background.jpg");
gameArea = background->getContentSize();
background->setPosition(gameArea / 2);
this->addChild(background, -1);
// received as the game starts
GSocket->on("initData", [=](GameSocket* client, Document& dom) {
this->selfId = dom["data"]["selfId"].GetString();
auto& arr = dom["data"]["players"];
for (SizeType i = 0; i < arr.Size(); i++) {
const std::string& id = arr[i].GetString();
if (id == selfId) {
this->selfPlayer = Player::create(gameArea / 2);
this->addChild(selfPlayer, 1);
// make the camera follow the player
this->runAction(Follow::create(selfPlayer));
}
else {
auto player = Player::create(gameArea / 2);
this->addChild(player, 1);
this->otherPlayers.insert(std::make_pair(id, player));
}
}
started = true;
});
// received periodically, like every x frames
GSocket->on("sync", [=](GameSocket* client, Document& dom) {
auto& arr = dom["data"];
for (SizeType i = 0; i < arr.Size(); i++) {
auto& data = arr[i]["data"];
// check ping
// milliseconds ms = duration_cast<milliseconds>(system_clock::now().time_since_epoch());
// CCLOG("ping: %lld", ms.count() - data["timestamp"].GetInt64());
const std::string& id = arr[i]["id"].GetString();
auto it = this->otherPlayers.find(id);
if (it == this->otherPlayers.end()) continue; // data of selfPlayer, just ignore it
auto player = it->second;
player->sync(data);
}
});
// deal with other players' shots
GSocket->on("shoot", [=](GameSocket* client, Document& dom) {
auto& data = dom["data"];
auto bullet = Bullet::create(Vec2(data["posX"].GetDouble(), data["posY"].GetDouble()), data["angle"].GetDouble());
this->addChild(bullet, 1);
});
// manually update the physics world
this->schedule(schedule_selector(GameScene::update), 1.0f / FRAME_RATE, kRepeatForever, 0.1f);
return true;
}
void GameScene::update(float dt) {
using std::max;
using std::min;
if (!started) return;
static int frameCounter = 0;
this->getScene()->getPhysicsWorld()->step(1.0f / FRAME_RATE);
frameCounter++;
if (frameCounter == SYNC_LIMIT) {
frameCounter = 0;
GSocket->sendEvent("sync", this->selfPlayer->createSyncData());
}
// bound the player in the map
auto pos = selfPlayer->getPosition();
auto size = selfPlayer->getContentSize() * selfPlayer->getScale();
pos.x = min(pos.x, gameArea.x - size.width / 2);
pos.x = max(pos.x, size.width / 2);
pos.y = min(pos.y, gameArea.y - size.height / 2);
pos.y = max(pos.y, size.height / 2);
selfPlayer->setPosition(pos);
}
void GameScene::onKeyPressed(EventKeyboard::KeyCode code, Event* event) {
switch (code) {
case cocos2d::EventKeyboard::KeyCode::KEY_W:
selfPlayer->setVelocityY(200.0f);
break;
case cocos2d::EventKeyboard::KeyCode::KEY_S:
selfPlayer->setVelocityY(-200.0f);
break;
case cocos2d::EventKeyboard::KeyCode::KEY_A:
selfPlayer->setVelocityX(-200.0f);
break;
case cocos2d::EventKeyboard::KeyCode::KEY_D:
selfPlayer->setVelocityX(200.0f);
break;
}
}
void GameScene::onKeyReleased(EventKeyboard::KeyCode code, Event* event) {
auto body = selfPlayer->getPhysicsBody();
switch (code) {
case cocos2d::EventKeyboard::KeyCode::KEY_W:
if (body->getVelocity().y < 0.0f) break;
selfPlayer->setVelocityY(0.0f);
break;
case cocos2d::EventKeyboard::KeyCode::KEY_S:
if (body->getVelocity().y > 0.0f) break;
selfPlayer->setVelocityY(0.0f);
break;
case cocos2d::EventKeyboard::KeyCode::KEY_A:
if (body->getVelocity().x > 0.0f) break;
selfPlayer->setVelocityX(0.0f);
break;
case cocos2d::EventKeyboard::KeyCode::KEY_D:
if (body->getVelocity().x < 0.0f) break;
selfPlayer->setVelocityX(0.0f);
break;
}
}
void GameScene::onMouseMove(EventMouse* event) {
auto pos = Vec2(event->getCursorX(), event->getCursorY());
// position of physicsBody as relative to the camera
selfPlayer->setRotation(-CC_RADIANS_TO_DEGREES((pos - selfPlayer->getPhysicsBody()->getPosition()).getAngle()) + 90.0f);
}
void GameScene::onMouseDown(EventMouse* event) {
Bullet* bullet;
switch (event->getMouseButton()) {
case EventMouse::MouseButton::BUTTON_LEFT:
// create a bullet
bullet = Bullet::create(selfPlayer->getPosition(), selfPlayer->getRotation());
this->addChild(bullet, 1);
// broadcast shooting event
bullet->broadcast();
break;
case EventMouse::MouseButton::BUTTON_RIGHT:
default:
break;
}
}
bool GameScene::onContactBegin(PhysicsContact &contact) {
// TODO: better contacting item type check
// now only deal with bullet-player contact
auto node1 = (Sprite*)contact.getShapeA()->getBody()->getNode();
auto node2 = (Sprite*)contact.getShapeB()->getBody()->getNode();
auto boom = Boom::create(node1->getPosition());
this->addChild(boom, 2);
if (node1->getPhysicsBody()->getCategoryBitmask() == 0x00000002) {
node1->removeFromParentAndCleanup(true);
outOfRangeCheck.erase(node1);
}
else {
node2->removeFromParentAndCleanup(true);
outOfRangeCheck.erase(node2);
}
if (node1 == selfPlayer || node2 == selfPlayer) {
// self-player was hit
Document dom;
dom.SetObject();
dom.AddMember("type", "hit", dom.GetAllocator());
dom.AddMember("damage", 20.0f, dom.GetAllocator()); // TODO: damage determined by bullet type
GSocket->sendEvent("broadcast", dom);
}
return false;
}
void GameScene::addListener() {
auto keyboardListener = EventListenerKeyboard::create();
keyboardListener->onKeyPressed = CC_CALLBACK_2(GameScene::onKeyPressed, this);
keyboardListener->onKeyReleased = CC_CALLBACK_2(GameScene::onKeyReleased, this);
auto mouseListener = EventListenerMouse::create();
mouseListener->onMouseMove = CC_CALLBACK_1(GameScene::onMouseMove, this);
mouseListener->onMouseDown = CC_CALLBACK_1(GameScene::onMouseDown, this);
auto contactListener = EventListenerPhysicsContact::create();
contactListener->onContactBegin = CC_CALLBACK_1(GameScene::onContactBegin, this);
_eventDispatcher->addEventListenerWithSceneGraphPriority(keyboardListener, this);
_eventDispatcher->addEventListenerWithSceneGraphPriority(mouseListener, this);
_eventDispatcher->addEventListenerWithSceneGraphPriority(contactListener, this);
}
void resetPhysics(Node* node, PhysicsBody* body) {
node->removeComponent(node->getPhysicsBody());
node->setPhysicsBody(body);
}
<|endoftext|> |
<commit_before>// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:
/*
Copyright (c) 2008 Aristid Breitkreuz, Ruediger Sonderfeld
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#ifndef FLUSSPFERD_ARRAY_HPP
#define FLUSSPFERD_ARRAY_HPP
#include "object.hpp"
namespace flusspferd {
/**
* A class for holding a Javascript Array.
*
* @ingroup value_types
*/
class array : public object {
public:
/// Construct an #array from a Javascript Array object.
array(object const &o);
/// Assign a Javascript Array object to an #array object.
array &operator=(object const &o);
public:
/// Get the length of the Array.
std::size_t get_length() const;
/// Set the length of the array, resizing it in the process.
void set_length(std::size_t);
/// Get an array element.
value get_element(std::size_t n) const;
/// Set an array element.
void set_element(std::size_t n, value const &x);
private:
void check();
};
template<>
struct detail::convert<array> {
typedef to_value_helper<array> to_value;
struct from_value {
root_array root;
array perform(value const &v) {
root = array(v.to_object());
return root;
}
};
};
}
#endif
<commit_msg>doc: i guess array should be in property_types too as it manipulates properties with indexes instead of string names<commit_after>// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:
/*
Copyright (c) 2008 Aristid Breitkreuz, Ruediger Sonderfeld
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#ifndef FLUSSPFERD_ARRAY_HPP
#define FLUSSPFERD_ARRAY_HPP
#include "object.hpp"
namespace flusspferd {
/**
* A class for holding a Javascript Array.
*
* @ingroup value_types
* @ingroup property_types
*/
class array : public object {
public:
/// Construct an #array from a Javascript Array object.
array(object const &o);
/// Assign a Javascript Array object to an #array object.
array &operator=(object const &o);
public:
/// Get the length of the Array.
std::size_t get_length() const;
/// Set the length of the array, resizing it in the process.
void set_length(std::size_t);
/// Get an array element.
value get_element(std::size_t n) const;
/// Set an array element.
void set_element(std::size_t n, value const &x);
private:
void check();
};
template<>
struct detail::convert<array> {
typedef to_value_helper<array> to_value;
struct from_value {
root_array root;
array perform(value const &v) {
root = array(v.to_object());
return root;
}
};
};
}
#endif
<|endoftext|> |
<commit_before>#include "PositionModule.hpp"
#include <assert.h>
#include <sys/stat.h>
#include <errno.h>
#include <string>
#include <ros/console.h>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/calib3d/calib3d.hpp>
#include "sensor_msgs/Image.h"
#include "api_application/Ping.h"
#include "api_application/Announce.h"
PositionModule::PositionModule(IPositionReceiver* receiver)
{
assert(receiver != 0);
this->receiver = receiver;
_isInitialized = true;
isCalibrating = false;
isRunning = false;
ros::NodeHandle n;
this->pictureSendingActivationPublisher = n.advertise<camera_application::PictureSendingActivation>("PictureSendingActivation", 4);
this->pingPublisher = n.advertise<api_application::Ping>("Ping", 4);
this->pictureSubscriber = n.subscribe("Picture", 128, &PositionModule::pictureCallback, this);
this->systemSubscriber = n.subscribe("System", 4, &PositionModule::systemCallback, this);
this->rawPositionSubscriber = n.subscribe("RawPosition", 1024, &PositionModule::rawPositionCallback, this);
this->startCalibrationService = n.advertiseService("StartCalibration", &PositionModule::startCalibrationCallback, this);
this->takeCalibrationPictureService = n.advertiseService("TakeCalibrationPicture", &PositionModule::takeCalibrationPictureCallback, this);
this->calculateCalibrationService = n.advertiseService("CalculateCalibration", &PositionModule::calculateCalibrationCallback, this);
// Advertise myself to API
ros::ServiceClient announceClient = n.serviceClient<api_application::Announce>("Announce");
api_application::Announce announce;
announce.request.type = 3; // 3 means position module
announce.request.initializeServiceName = std::string("InitializePositionModule");
if (announceClient.call(announce))
{
rosId = announce.response.ID;
if (rosId == ~0 /* -1 */)
{
ROS_ERROR("Error! Got id -1");
_isInitialized = false;
}
else
{
ROS_INFO("Position module successfully announced. Got id %d", rosId);
}
}
else
{
ROS_ERROR("Error! Could not announce myself to API!");
_isInitialized = false;
}
msg = new KitrokopterMessages(rosId);
if (_isInitialized)
{
ROS_DEBUG("PositionModule initialized.");
}
}
PositionModule::~PositionModule()
{
msg->~KitrokopterMessages();
// TODO: Free picture cache.
ROS_DEBUG("PositionModule destroyed.");
}
// Service
bool PositionModule::startCalibrationCallback(control_application::StartCalibration::Request &req, control_application::StartCalibration::Response &res)
{
res.ok = !isCalibrating;
if (!isCalibrating)
{
setPictureSendingActivated(true);
calibrationPictureCount = 0;
boardSize = cv::Size(req.chessboardWidth, req.chessboardHeight);
}
isCalibrating = true;
return true;
}
// Service
bool PositionModule::takeCalibrationPictureCallback(control_application::TakeCalibrationPicture::Request &req, control_application::TakeCalibrationPicture::Response &res)
{
int id = 0;
for (std::vector<cv::Mat*>::iterator it = pictureCache.begin(); it != pictureCache.end(); it++, id++)
{
if (*it != 0)
{
// TODO: check if image is "good"
std::vector<cv::Point2f> corners;
bool foundAllCorners = cv::findChessboardCorners(**it, boardSize, corners, CV_CALIB_CB_ADAPTIVE_THRESH | CV_CALIB_CB_FILTER_QUADS | CV_CALIB_CB_FAST_CHECK | CV_CALIB_CB_NORMALIZE_IMAGE);
if (!foundAllCorners)
{
ROS_INFO("Took bad picture (id %d)", id);
continue;
}
else
{
ROS_INFO("Took good picture (id %d)", id);
// Create directory for images.
int error = mkdir("~/calibrationImages", 770);
if (error != 0 && error != EEXIST)
{
ROS_ERROR("Could not create directory for calibration images: %d", error);
return false;
}
std::stringstream ss;
ss << "~/calibrationImages/cam" << id << "_image" << calibrationPictureCount << ".png";
cv::imwrite(ss.str(), **it);
sensor_msgs::Image img;
img.width = 640;
img.height = 480;
img.step = 3 * 640;
for (int i = 0; i < 640 * 480 * 3; i++)
{
img.data[i] = (*it)->data[i];
}
res.images.push_back(img);
}
delete *it;
*it = 0;
}
}
calibrationPictureCount++;
return true;
}
// Service
bool PositionModule::calculateCalibrationCallback(control_application::CalculateCalibration::Request &req, control_application::CalculateCalibration::Response &res)
{
// TODO: Do stuff with danis code...
return true;
}
// Topic
void PositionModule::pictureCallback(const camera_application::Picture &msg)
{
if (isCalibrating)
{
// Don't know if it works that way and I really can randomly insert now...
pictureCache.reserve(msg.ID + 1);
pictureTimes.reserve(msg.ID + 1);
if (pictureCache[msg.ID] != 0)
{
delete pictureCache[msg.ID];
pictureCache[msg.ID] = 0;
}
cv::Mat* image = new cv::Mat(cv::Size(640, 480), CV_8UC3);
for (int i = 0; i < 640 * 480 * 3; i++)
{
image->data[i] = msg.image[i];
}
pictureCache[msg.ID] = image;
pictureTimes[msg.ID] = msg.timestamp;
}
}
// Topic
void PositionModule::systemCallback(const api_application::System &msg)
{
isRunning = msg.command == 1;
}
// Topic
void PositionModule::rawPositionCallback(const camera_application::RawPosition &msg)
{
// TODO: Calculate position in our coordinate system.
}
void PositionModule::setPictureSendingActivated(bool activated)
{
camera_application::PictureSendingActivation msg;
msg.ID = 0;
msg.active = activated;
pictureSendingActivationPublisher.publish(msg);
}
void PositionModule::sendPing()
{
api_application::Ping msg;
msg.ID = rosId;
pingPublisher.publish(msg);
}
bool PositionModule::isInitialized()
{
return _isInitialized;
}<commit_msg>Adapted network protocol changes<commit_after>#include "PositionModule.hpp"
#include <assert.h>
#include <sys/stat.h>
#include <errno.h>
#include <string>
#include <ros/console.h>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/calib3d/calib3d.hpp>
#include "sensor_msgs/Image.h"
#include "api_application/Ping.h"
#include "api_application/Announce.h"
PositionModule::PositionModule(IPositionReceiver* receiver)
{
assert(receiver != 0);
this->receiver = receiver;
_isInitialized = true;
isCalibrating = false;
isRunning = false;
ros::NodeHandle n;
this->pictureSendingActivationPublisher = n.advertise<camera_application::PictureSendingActivation>("PictureSendingActivation", 4);
this->pingPublisher = n.advertise<api_application::Ping>("Ping", 4);
this->pictureSubscriber = n.subscribe("Picture", 128, &PositionModule::pictureCallback, this);
this->systemSubscriber = n.subscribe("System", 4, &PositionModule::systemCallback, this);
this->rawPositionSubscriber = n.subscribe("RawPosition", 1024, &PositionModule::rawPositionCallback, this);
this->startCalibrationService = n.advertiseService("StartCalibration", &PositionModule::startCalibrationCallback, this);
this->takeCalibrationPictureService = n.advertiseService("TakeCalibrationPicture", &PositionModule::takeCalibrationPictureCallback, this);
this->calculateCalibrationService = n.advertiseService("CalculateCalibration", &PositionModule::calculateCalibrationCallback, this);
// Advertise myself to API
ros::ServiceClient announceClient = n.serviceClient<api_application::Announce>("Announce");
api_application::Announce announce;
announce.request.type = 3; // 3 means position module
if (announceClient.call(announce))
{
rosId = announce.response.id;
if (rosId == ~0 /* -1 */)
{
ROS_ERROR("Error! Got id -1");
_isInitialized = false;
}
else
{
ROS_INFO("Position module successfully announced. Got id %d", rosId);
}
}
else
{
ROS_ERROR("Error! Could not announce myself to API!");
_isInitialized = false;
}
msg = new KitrokopterMessages(rosId);
if (_isInitialized)
{
ROS_DEBUG("PositionModule initialized.");
}
}
PositionModule::~PositionModule()
{
msg->~KitrokopterMessages();
// TODO: Free picture cache.
ROS_DEBUG("PositionModule destroyed.");
}
// Service
bool PositionModule::startCalibrationCallback(control_application::StartCalibration::Request &req, control_application::StartCalibration::Response &res)
{
res.ok = !isCalibrating;
if (!isCalibrating)
{
setPictureSendingActivated(true);
calibrationPictureCount = 0;
boardSize = cv::Size(req.chessboardWidth, req.chessboardHeight);
}
isCalibrating = true;
return true;
}
// Service
bool PositionModule::takeCalibrationPictureCallback(control_application::TakeCalibrationPicture::Request &req, control_application::TakeCalibrationPicture::Response &res)
{
int id = 0;
for (std::vector<cv::Mat*>::iterator it = pictureCache.begin(); it != pictureCache.end(); it++, id++)
{
if (*it != 0)
{
// TODO: check if image is "good"
std::vector<cv::Point2f> corners;
bool foundAllCorners = cv::findChessboardCorners(**it, boardSize, corners, CV_CALIB_CB_ADAPTIVE_THRESH | CV_CALIB_CB_FILTER_QUADS | CV_CALIB_CB_FAST_CHECK | CV_CALIB_CB_NORMALIZE_IMAGE);
if (!foundAllCorners)
{
ROS_INFO("Took bad picture (id %d)", id);
continue;
}
else
{
ROS_INFO("Took good picture (id %d)", id);
// Create directory for images.
int error = mkdir("~/calibrationImages", 770);
if (error != 0 && error != EEXIST)
{
ROS_ERROR("Could not create directory for calibration images: %d", error);
return false;
}
std::stringstream ss;
ss << "~/calibrationImages/cam" << id << "_image" << calibrationPictureCount << ".png";
cv::imwrite(ss.str(), **it);
sensor_msgs::Image img;
img.width = 640;
img.height = 480;
img.step = 3 * 640;
for (int i = 0; i < 640 * 480 * 3; i++)
{
img.data[i] = (*it)->data[i];
}
res.images.push_back(img);
}
delete *it;
*it = 0;
}
}
calibrationPictureCount++;
return true;
}
// Service
bool PositionModule::calculateCalibrationCallback(control_application::CalculateCalibration::Request &req, control_application::CalculateCalibration::Response &res)
{
// TODO: Do stuff with danis code...
return true;
}
// Topic
void PositionModule::pictureCallback(const camera_application::Picture &msg)
{
if (isCalibrating)
{
// Don't know if it works that way and I really can randomly insert now...
pictureCache.reserve(msg.ID + 1);
pictureTimes.reserve(msg.ID + 1);
if (pictureCache[msg.ID] != 0)
{
delete pictureCache[msg.ID];
pictureCache[msg.ID] = 0;
}
cv::Mat* image = new cv::Mat(cv::Size(640, 480), CV_8UC3);
for (int i = 0; i < 640 * 480 * 3; i++)
{
image->data[i] = msg.image[i];
}
pictureCache[msg.ID] = image;
pictureTimes[msg.ID] = msg.timestamp;
}
}
// Topic
void PositionModule::systemCallback(const api_application::System &msg)
{
isRunning = msg.command == 1;
}
// Topic
void PositionModule::rawPositionCallback(const camera_application::RawPosition &msg)
{
// TODO: Calculate position in our coordinate system.
}
void PositionModule::setPictureSendingActivated(bool activated)
{
camera_application::PictureSendingActivation msg;
msg.ID = 0;
msg.active = activated;
pictureSendingActivationPublisher.publish(msg);
}
void PositionModule::sendPing()
{
api_application::Ping msg;
msg.ID = rosId;
pingPublisher.publish(msg);
}
bool PositionModule::isInitialized()
{
return _isInitialized;
}<|endoftext|> |
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: vtkCutter.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 1993-2001 Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names
of any contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
* Modified source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS''
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
=========================================================================*/
#include <math.h>
#include "vtkCutter.h"
#include "vtkMergePoints.h"
#include "vtkImplicitFunction.h"
#include "vtkContourValues.h"
#include "vtkObjectFactory.h"
//------------------------------------------------------------------------------
vtkCutter* vtkCutter::New()
{
// First try to create the object from the vtkObjectFactory
vtkObject* ret = vtkObjectFactory::CreateInstance("vtkCutter");
if(ret)
{
return (vtkCutter*)ret;
}
// If the factory was unable to create the object, then create it here.
return new vtkCutter;
}
// Construct with user-specified implicit function; initial value of 0.0; and
// generating cut scalars turned off.
vtkCutter::vtkCutter(vtkImplicitFunction *cf)
{
this->ContourValues = vtkContourValues::New();
this->SortBy = VTK_SORT_BY_VALUE;
this->CutFunction = cf;
this->GenerateCutScalars = 0;
this->Locator = NULL;
}
vtkCutter::~vtkCutter()
{
this->ContourValues->Delete();
this->SetCutFunction(NULL);
if ( this->Locator )
{
this->Locator->UnRegister(this);
this->Locator = NULL;
}
}
// Overload standard modified time function. If cut functions is modified,
// or contour values modified, then this object is modified as well.
unsigned long vtkCutter::GetMTime()
{
unsigned long mTime=this->vtkDataSetToPolyDataFilter::GetMTime();
unsigned long contourValuesMTime=this->ContourValues->GetMTime();
unsigned long time;
mTime = ( contourValuesMTime > mTime ? contourValuesMTime : mTime );
if ( this->CutFunction != NULL )
{
time = this->CutFunction->GetMTime();
mTime = ( time > mTime ? time : mTime );
}
if ( this->Locator != NULL )
{
time = this->Locator->GetMTime();
mTime = ( time > mTime ? time : mTime );
}
return mTime;
}
//
// Cut through data generating surface.
//
void vtkCutter::Execute()
{
int cellId, i, iter;
vtkPoints *cellPts;
vtkScalars *cellScalars=vtkScalars::New();
vtkCell *cell;
vtkCellArray *newVerts, *newLines, *newPolys;
vtkPoints *newPoints;
vtkScalars *cutScalars;
float value, s;
vtkPolyData *output = this->GetOutput();
vtkDataSet *input=this->GetInput();
int estimatedSize, numCells=input->GetNumberOfCells();
int numPts=input->GetNumberOfPoints(), numCellPts;
vtkPointData *inPD, *outPD;
vtkCellData *inCD=input->GetCellData(), *outCD=output->GetCellData();
vtkIdList *cellIds;
int numContours=this->ContourValues->GetNumberOfContours();
vtkDebugMacro(<< "Executing cutter");
//
// Initialize self; create output objects
//
if ( !this->CutFunction )
{
vtkErrorMacro(<<"No cut function specified");
return;
}
if ( numPts < 1 )
{
vtkErrorMacro(<<"No data to cut");
return;
}
//
// Create objects to hold output of contour operation
//
estimatedSize = (int) pow ((double) numCells, .75) * numContours;
estimatedSize = estimatedSize / 1024 * 1024; //multiple of 1024
if (estimatedSize < 1024)
{
estimatedSize = 1024;
}
newPoints = vtkPoints::New();
newPoints->Allocate(estimatedSize,estimatedSize/2);
newVerts = vtkCellArray::New();
newVerts->Allocate(estimatedSize,estimatedSize/2);
newLines = vtkCellArray::New();
newLines->Allocate(estimatedSize,estimatedSize/2);
newPolys = vtkCellArray::New();
newPolys->Allocate(estimatedSize,estimatedSize/2);
cutScalars = vtkScalars::New();
cutScalars->SetNumberOfScalars(numPts);
// Interpolate data along edge. If generating cut scalars, do necessary setup
if ( this->GenerateCutScalars )
{
inPD = vtkPointData::New();
inPD->ShallowCopy(input->GetPointData());//copies original attributes
inPD->SetScalars(cutScalars);
}
else
{
inPD = input->GetPointData();
}
outPD = output->GetPointData();
outPD->InterpolateAllocate(inPD,estimatedSize,estimatedSize/2);
outCD->CopyAllocate(inCD,estimatedSize,estimatedSize/2);
// locator used to merge potentially duplicate points
if ( this->Locator == NULL )
{
this->CreateDefaultLocator();
}
this->Locator->InitPointInsertion (newPoints, input->GetBounds());
//
// Loop over all cells creating scalar function determined by evaluating cell
// points using cut function.
//
for ( i=0; i < numPts; i++ )
{
s = this->CutFunction->FunctionValue(input->GetPoint(i));
cutScalars->SetScalar(i,s);
}
switch (this->SortBy)
{
case VTK_SORT_BY_CELL:
{
//
// Loop over all contour values. Then for each contour value,
// loop over all cells.
//
for (iter=0; iter < numContours; iter++)
{
//
// Loop over all cells creating scalar function determined by evaluating cell
// points using cut function.
//
for (cellId=0; cellId < numCells; cellId++)
{
cell = input->GetCell(cellId);
cellPts = cell->GetPoints();
cellIds = cell->GetPointIds();
numCellPts = cellPts->GetNumberOfPoints();
cellScalars->SetNumberOfScalars(numCellPts);
for (i=0; i < numCellPts; i++)
{
s = cutScalars->GetScalar(cellIds->GetId(i));
cellScalars->SetScalar(i,s);
}
value = this->ContourValues->GetValue(iter);
cell->Contour(value, cellScalars, this->Locator,
newVerts, newLines, newPolys, inPD, outPD,
inCD, cellId, outCD);
} // for all cells
} // for all contour values
} // sort by cell
case VTK_SORT_BY_VALUE:
{
//
// Loop over all cells creating scalar function determined by evaluating cell
// points using cut function.
//
for (cellId=0; cellId < numCells; cellId++)
{
cell = input->GetCell(cellId);
cellPts = cell->GetPoints();
cellIds = cell->GetPointIds();
numCellPts = cellPts->GetNumberOfPoints();
cellScalars->SetNumberOfScalars(numCellPts);
for (i=0; i < numCellPts; i++)
{
s = cutScalars->GetScalar(cellIds->GetId(i));
cellScalars->SetScalar(i,s);
}
//
// Loop over all contour values. Then for each contour value,
// loop over all cells.
//
for (iter=0; iter < numContours; iter++)
{
value = this->ContourValues->GetValue(iter);
cell->Contour(value, cellScalars, this->Locator,
newVerts, newLines, newPolys, inPD, outPD,
inCD, cellId, outCD);
} // for all contour values
} // for all cells
} // sort by value
} // end switch
//
// Update ourselves. Because we don't know upfront how many verts, lines,
// polys we've created, take care to reclaim memory.
//
cellScalars->Delete();
cutScalars->Delete();
if ( this->GenerateCutScalars )
{
inPD->Delete();
}
output->SetPoints(newPoints);
newPoints->Delete();
if (newVerts->GetNumberOfCells())
{
output->SetVerts(newVerts);
}
newVerts->Delete();
if (newLines->GetNumberOfCells())
{
output->SetLines(newLines);
}
newLines->Delete();
if (newPolys->GetNumberOfCells())
{
output->SetPolys(newPolys);
}
newPolys->Delete();
this->Locator->Initialize();//release any extra memory
output->Squeeze();
}
// Specify a spatial locator for merging points. By default,
// an instance of vtkMergePoints is used.
void vtkCutter::SetLocator(vtkPointLocator *locator)
{
if ( this->Locator == locator )
{
return;
}
if ( this->Locator )
{
this->Locator->UnRegister(this);
this->Locator = NULL;
}
if ( locator )
{
locator->Register(this);
}
this->Locator = locator;
this->Modified();
}
void vtkCutter::CreateDefaultLocator()
{
if ( this->Locator == NULL )
{
this->Locator = vtkMergePoints::New();
}
}
void vtkCutter::PrintSelf(ostream& os, vtkIndent indent)
{
vtkDataSetToPolyDataFilter::PrintSelf(os,indent);
os << indent << "Cut Function: " << this->CutFunction << "\n";
os << indent << "Sort By: " << this->GetSortByAsString() << "\n";
if ( this->Locator )
{
os << indent << "Locator: " << this->Locator << "\n";
}
else
{
os << indent << "Locator: (none)\n";
}
this->ContourValues->PrintSelf(os,indent);
os << indent << "Generate Cut Scalars: " << (this->GenerateCutScalars ? "On\n" : "Off\n");
}
<commit_msg>ERR:Double execution<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: vtkCutter.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 1993-2001 Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names
of any contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
* Modified source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS''
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
=========================================================================*/
#include <math.h>
#include "vtkCutter.h"
#include "vtkMergePoints.h"
#include "vtkImplicitFunction.h"
#include "vtkContourValues.h"
#include "vtkObjectFactory.h"
//------------------------------------------------------------------------------
vtkCutter* vtkCutter::New()
{
// First try to create the object from the vtkObjectFactory
vtkObject* ret = vtkObjectFactory::CreateInstance("vtkCutter");
if(ret)
{
return (vtkCutter*)ret;
}
// If the factory was unable to create the object, then create it here.
return new vtkCutter;
}
// Construct with user-specified implicit function; initial value of 0.0; and
// generating cut scalars turned off.
vtkCutter::vtkCutter(vtkImplicitFunction *cf)
{
this->ContourValues = vtkContourValues::New();
this->SortBy = VTK_SORT_BY_VALUE;
this->CutFunction = cf;
this->GenerateCutScalars = 0;
this->Locator = NULL;
}
vtkCutter::~vtkCutter()
{
this->ContourValues->Delete();
this->SetCutFunction(NULL);
if ( this->Locator )
{
this->Locator->UnRegister(this);
this->Locator = NULL;
}
}
// Overload standard modified time function. If cut functions is modified,
// or contour values modified, then this object is modified as well.
unsigned long vtkCutter::GetMTime()
{
unsigned long mTime=this->vtkDataSetToPolyDataFilter::GetMTime();
unsigned long contourValuesMTime=this->ContourValues->GetMTime();
unsigned long time;
mTime = ( contourValuesMTime > mTime ? contourValuesMTime : mTime );
if ( this->CutFunction != NULL )
{
time = this->CutFunction->GetMTime();
mTime = ( time > mTime ? time : mTime );
}
if ( this->Locator != NULL )
{
time = this->Locator->GetMTime();
mTime = ( time > mTime ? time : mTime );
}
return mTime;
}
//
// Cut through data generating surface.
//
void vtkCutter::Execute()
{
int cellId, i, iter;
vtkPoints *cellPts;
vtkScalars *cellScalars=vtkScalars::New();
vtkCell *cell;
vtkCellArray *newVerts, *newLines, *newPolys;
vtkPoints *newPoints;
vtkScalars *cutScalars;
float value, s;
vtkPolyData *output = this->GetOutput();
vtkDataSet *input=this->GetInput();
int estimatedSize, numCells=input->GetNumberOfCells();
int numPts=input->GetNumberOfPoints(), numCellPts;
vtkPointData *inPD, *outPD;
vtkCellData *inCD=input->GetCellData(), *outCD=output->GetCellData();
vtkIdList *cellIds;
int numContours=this->ContourValues->GetNumberOfContours();
vtkDebugMacro(<< "Executing cutter");
//
// Initialize self; create output objects
//
if ( !this->CutFunction )
{
vtkErrorMacro(<<"No cut function specified");
return;
}
if ( numPts < 1 )
{
vtkErrorMacro(<<"No data to cut");
return;
}
//
// Create objects to hold output of contour operation
//
estimatedSize = (int) pow ((double) numCells, .75) * numContours;
estimatedSize = estimatedSize / 1024 * 1024; //multiple of 1024
if (estimatedSize < 1024)
{
estimatedSize = 1024;
}
newPoints = vtkPoints::New();
newPoints->Allocate(estimatedSize,estimatedSize/2);
newVerts = vtkCellArray::New();
newVerts->Allocate(estimatedSize,estimatedSize/2);
newLines = vtkCellArray::New();
newLines->Allocate(estimatedSize,estimatedSize/2);
newPolys = vtkCellArray::New();
newPolys->Allocate(estimatedSize,estimatedSize/2);
cutScalars = vtkScalars::New();
cutScalars->SetNumberOfScalars(numPts);
// Interpolate data along edge. If generating cut scalars, do necessary setup
if ( this->GenerateCutScalars )
{
inPD = vtkPointData::New();
inPD->ShallowCopy(input->GetPointData());//copies original attributes
inPD->SetScalars(cutScalars);
}
else
{
inPD = input->GetPointData();
}
outPD = output->GetPointData();
outPD->InterpolateAllocate(inPD,estimatedSize,estimatedSize/2);
outCD->CopyAllocate(inCD,estimatedSize,estimatedSize/2);
// locator used to merge potentially duplicate points
if ( this->Locator == NULL )
{
this->CreateDefaultLocator();
}
this->Locator->InitPointInsertion (newPoints, input->GetBounds());
//
// Loop over all cells creating scalar function determined by evaluating cell
// points using cut function.
//
for ( i=0; i < numPts; i++ )
{
s = this->CutFunction->FunctionValue(input->GetPoint(i));
cutScalars->SetScalar(i,s);
}
switch (this->SortBy)
{
case VTK_SORT_BY_CELL:
{
//
// Loop over all contour values. Then for each contour value,
// loop over all cells.
//
for (iter=0; iter < numContours; iter++)
{
//
// Loop over all cells creating scalar function determined by evaluating cell
// points using cut function.
//
for (cellId=0; cellId < numCells; cellId++)
{
cell = input->GetCell(cellId);
cellPts = cell->GetPoints();
cellIds = cell->GetPointIds();
numCellPts = cellPts->GetNumberOfPoints();
cellScalars->SetNumberOfScalars(numCellPts);
for (i=0; i < numCellPts; i++)
{
s = cutScalars->GetScalar(cellIds->GetId(i));
cellScalars->SetScalar(i,s);
}
value = this->ContourValues->GetValue(iter);
cell->Contour(value, cellScalars, this->Locator,
newVerts, newLines, newPolys, inPD, outPD,
inCD, cellId, outCD);
} // for all cells
} // for all contour values
} // sort by cell
break;
case VTK_SORT_BY_VALUE:
{
//
// Loop over all cells creating scalar function determined by evaluating cell
// points using cut function.
//
for (cellId=0; cellId < numCells; cellId++)
{
cell = input->GetCell(cellId);
cellPts = cell->GetPoints();
cellIds = cell->GetPointIds();
numCellPts = cellPts->GetNumberOfPoints();
cellScalars->SetNumberOfScalars(numCellPts);
for (i=0; i < numCellPts; i++)
{
s = cutScalars->GetScalar(cellIds->GetId(i));
cellScalars->SetScalar(i,s);
}
//
// Loop over all contour values. Then for each contour value,
// loop over all cells.
//
for (iter=0; iter < numContours; iter++)
{
value = this->ContourValues->GetValue(iter);
cell->Contour(value, cellScalars, this->Locator,
newVerts, newLines, newPolys, inPD, outPD,
inCD, cellId, outCD);
} // for all contour values
} // for all cells
} // sort by value
} // end switch
//
// Update ourselves. Because we don't know upfront how many verts, lines,
// polys we've created, take care to reclaim memory.
//
cellScalars->Delete();
cutScalars->Delete();
if ( this->GenerateCutScalars )
{
inPD->Delete();
}
output->SetPoints(newPoints);
newPoints->Delete();
if (newVerts->GetNumberOfCells())
{
output->SetVerts(newVerts);
}
newVerts->Delete();
if (newLines->GetNumberOfCells())
{
output->SetLines(newLines);
}
newLines->Delete();
if (newPolys->GetNumberOfCells())
{
output->SetPolys(newPolys);
}
newPolys->Delete();
this->Locator->Initialize();//release any extra memory
output->Squeeze();
}
// Specify a spatial locator for merging points. By default,
// an instance of vtkMergePoints is used.
void vtkCutter::SetLocator(vtkPointLocator *locator)
{
if ( this->Locator == locator )
{
return;
}
if ( this->Locator )
{
this->Locator->UnRegister(this);
this->Locator = NULL;
}
if ( locator )
{
locator->Register(this);
}
this->Locator = locator;
this->Modified();
}
void vtkCutter::CreateDefaultLocator()
{
if ( this->Locator == NULL )
{
this->Locator = vtkMergePoints::New();
}
}
void vtkCutter::PrintSelf(ostream& os, vtkIndent indent)
{
vtkDataSetToPolyDataFilter::PrintSelf(os,indent);
os << indent << "Cut Function: " << this->CutFunction << "\n";
os << indent << "Sort By: " << this->GetSortByAsString() << "\n";
if ( this->Locator )
{
os << indent << "Locator: " << this->Locator << "\n";
}
else
{
os << indent << "Locator: (none)\n";
}
this->ContourValues->PrintSelf(os,indent);
os << indent << "Generate Cut Scalars: " << (this->GenerateCutScalars ? "On\n" : "Off\n");
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: vtkMapper.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 1993-2001 Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names
of any contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
* Modified source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS''
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
=========================================================================*/
#include "vtkMapper.h"
#include "vtkLookupTable.h"
// Initialize static member that controls global immediate mode rendering
static int vtkMapperGlobalImmediateModeRendering = 0;
// Initialize static member that controls global coincidence resolution
static int vtkMapperGlobalResolveCoincidentTopology = VTK_RESOLVE_OFF;
static double vtkMapperGlobalResolveCoincidentTopologyZShift = 0.01;
static float vtkMapperGlobalResolveCoincidentTopologyPolygonOffsetFactor = 1.0;
static float vtkMapperGlobalResolveCoincidentTopologyPolygonOffsetUnits = 1.0;
// Construct with initial range (0,1).
vtkMapper::vtkMapper()
{
this->Colors = NULL;
this->LookupTable = NULL;
this->ScalarVisibility = 1;
this->ScalarRange[0] = 0.0; this->ScalarRange[1] = 1.0;
this->UseLookupTableScalarRange = 0;
this->ImmediateModeRendering = 0;
this->ColorMode = VTK_COLOR_MODE_DEFAULT;
this->ScalarMode = VTK_SCALAR_MODE_DEFAULT;
this->Bounds[0] = this->Bounds[2] = this->Bounds[4] = -1.0;
this->Bounds[1] = this->Bounds[3] = this->Bounds[5] = 1.0;
this->Center[0] = this->Center[1] = this->Center[2] = 0.0;
this->RenderTime = 0.0;
strcpy(this->ArrayName, "");
this->ArrayId = -1;
this->ArrayComponent = -1;
this->ArrayAccessMode = -1;
}
vtkMapper::~vtkMapper()
{
if (this->LookupTable)
{
this->LookupTable->UnRegister(this);
}
if ( this->Colors != NULL )
{
this->Colors->UnRegister(this);
}
}
// Get the bounds for the input of this mapper as
// (Xmin,Xmax,Ymin,Ymax,Zmin,Zmax).
float *vtkMapper::GetBounds()
{
static float bounds[] = {-1.0,1.0, -1.0,1.0, -1.0,1.0};
if ( ! this->GetInput() )
{
return bounds;
}
else
{
this->Update();
this->GetInput()->GetBounds(this->Bounds);
return this->Bounds;
}
}
vtkDataSet *vtkMapper::GetInput()
{
if (this->NumberOfInputs < 1)
{
return NULL;
}
return (vtkDataSet *)(this->Inputs[0]);
}
void vtkMapper::SetGlobalImmediateModeRendering(int val)
{
if (val == vtkMapperGlobalImmediateModeRendering)
{
return;
}
vtkMapperGlobalImmediateModeRendering = val;
}
int vtkMapper::GetGlobalImmediateModeRendering()
{
return vtkMapperGlobalImmediateModeRendering;
}
void vtkMapper::SetResolveCoincidentTopology(int val)
{
if (val == vtkMapperGlobalResolveCoincidentTopology)
{
return;
}
vtkMapperGlobalResolveCoincidentTopology = val;
}
int vtkMapper::GetResolveCoincidentTopology()
{
return vtkMapperGlobalResolveCoincidentTopology;
}
void vtkMapper::SetResolveCoincidentTopologyToDefault()
{
vtkMapperGlobalResolveCoincidentTopology = VTK_RESOLVE_OFF;
}
void vtkMapper::SetResolveCoincidentTopologyZShift(double val)
{
if (val == vtkMapperGlobalResolveCoincidentTopologyZShift)
{
return;
}
vtkMapperGlobalResolveCoincidentTopologyZShift = val;
}
double vtkMapper::GetResolveCoincidentTopologyZShift()
{
return vtkMapperGlobalResolveCoincidentTopologyZShift;
}
void vtkMapper::SetResolveCoincidentTopologyPolygonOffsetParameters(
float factor, float units)
{
if (factor == vtkMapperGlobalResolveCoincidentTopologyPolygonOffsetFactor &&
units == vtkMapperGlobalResolveCoincidentTopologyPolygonOffsetUnits )
{
return;
}
vtkMapperGlobalResolveCoincidentTopologyPolygonOffsetFactor = factor;
vtkMapperGlobalResolveCoincidentTopologyPolygonOffsetFactor = units;
}
void vtkMapper::GetResolveCoincidentTopologyPolygonOffsetParameters(
float& factor, float& units)
{
factor = vtkMapperGlobalResolveCoincidentTopologyPolygonOffsetFactor;
units = vtkMapperGlobalResolveCoincidentTopologyPolygonOffsetUnits;
}
// Overload standard modified time function. If lookup table is modified,
// then this object is modified as well.
unsigned long vtkMapper::GetMTime()
{
unsigned long mTime=this->MTime.GetMTime();
unsigned long lutMTime;
if ( this->LookupTable != NULL )
{
lutMTime = this->LookupTable->GetMTime();
mTime = ( lutMTime > mTime ? lutMTime : mTime );
}
return mTime;
}
void vtkMapper::ShallowCopy(vtkMapper *m)
{
this->SetLookupTable(m->GetLookupTable());
this->SetClippingPlanes(m->GetClippingPlanes());
this->SetScalarVisibility(m->GetScalarVisibility());
this->SetScalarRange(m->GetScalarRange());
this->SetColorMode(m->GetColorMode());
this->SetScalarMode(m->GetScalarMode());
this->SetImmediateModeRendering(m->GetImmediateModeRendering());
}
// a side effect of this is that this->Colors is also set
// to the return value
vtkScalars *vtkMapper::GetColors()
{
vtkScalars *scalars = NULL;
vtkDataArray *dataArray=0;
vtkPointData *pd;
vtkCellData *cd;
vtkIdType i, numScalars;
// make sure we have an input
if (!this->GetInput())
{
return NULL;
}
// get and scalar data according to scalar mode
if ( this->ScalarMode == VTK_SCALAR_MODE_DEFAULT )
{
scalars = this->GetInput()->GetPointData()->GetScalars();
if (!scalars)
{
scalars = this->GetInput()->GetCellData()->GetScalars();
}
}
else if ( this->ScalarMode == VTK_SCALAR_MODE_USE_POINT_DATA )
{
scalars = this->GetInput()->GetPointData()->GetScalars();
}
else if ( this->ScalarMode == VTK_SCALAR_MODE_USE_CELL_DATA )
{
scalars = this->GetInput()->GetCellData()->GetScalars();
}
else if ( this->ScalarMode == VTK_SCALAR_MODE_USE_POINT_FIELD_DATA )
{
pd = this->GetInput()->GetPointData();
if (pd)
{
if (this->ArrayAccessMode == VTK_GET_ARRAY_BY_ID)
{
dataArray = pd->GetArray(this->ArrayId);
}
else
{
dataArray = pd->GetArray(this->ArrayName);
}
}
if (dataArray &&
(this->ArrayComponent < dataArray->GetNumberOfComponents()))
{
scalars = vtkScalars::New();
numScalars = dataArray->GetNumberOfTuples();
scalars->SetNumberOfScalars(numScalars);
if (dataArray->GetNumberOfComponents() == 1)
{
scalars->SetData(dataArray);
}
else
{ // I do not know how useful it is to color by a componenet.
// This could probably be done with out a copy
// by using active component.
for (i = 0; i < numScalars; i++)
{
scalars->
InsertScalar(i, dataArray->GetComponent(i, this->ArrayComponent));
}
}
}
}
else if ( this->ScalarMode == VTK_SCALAR_MODE_USE_CELL_FIELD_DATA )
{
cd = this->GetInput()->GetCellData();
if (cd)
{
if (this->ArrayAccessMode == VTK_GET_ARRAY_BY_ID)
{
dataArray = cd->GetArray(this->ArrayId);
}
else
{
dataArray = cd->GetArray(this->ArrayName);
}
}
if (dataArray &&
(this->ArrayComponent < dataArray->GetNumberOfComponents()))
{
scalars = vtkScalars::New();
numScalars = dataArray->GetNumberOfTuples();
scalars->SetNumberOfScalars(numScalars);
if (dataArray->GetNumberOfComponents() == 1)
{
scalars->SetData(dataArray);
}
else
{ // I do not know how useful it is to color by a componenet.
// This could probably be done with out a copy
// by using active component.
for (i = 0; i < numScalars; i++)
{
scalars->
InsertScalar(i, dataArray->GetComponent(i, this->ArrayComponent));
}
}
}
}
// do we have any scalars ?
if (scalars && this->ScalarVisibility)
{
// if the scalars have a lookup table use it instead
if (scalars->GetLookupTable())
{
this->SetLookupTable(scalars->GetLookupTable());
}
else
{
// make sure we have a lookup table
if ( this->LookupTable == NULL )
{
this->CreateDefaultLookupTable();
}
this->LookupTable->Build();
}
// Setup mapper/scalar object for color generation
if (!this->UseLookupTableScalarRange)
{
this->LookupTable->SetRange(this->ScalarRange);
}
if (this->Colors)
{
this->Colors->UnRegister(this);
}
this->Colors = scalars;
this->Colors->Register(this);
this->Colors->InitColorTraversal(1.0, this->LookupTable, this->ColorMode);
}
else //scalars not visible
{
if ( this->Colors )
{
this->Colors->UnRegister(this);
}
this->Colors = NULL;
}
if (((this->ScalarMode == VTK_SCALAR_MODE_USE_POINT_FIELD_DATA) ||
(this->ScalarMode == VTK_SCALAR_MODE_USE_CELL_FIELD_DATA)) &&
scalars)
{
scalars->Delete();
}
return this->Colors;
}
void vtkMapper::ColorByArrayComponent(int arrayNum, int component)
{
if (this->ArrayId == arrayNum && component == this->ArrayComponent &&
this->ArrayAccessMode == VTK_GET_ARRAY_BY_ID)
{
return;
}
this->Modified();
this->ArrayId = arrayNum;
this->ArrayComponent = component;
this->ArrayAccessMode = VTK_GET_ARRAY_BY_ID;
}
void vtkMapper::ColorByArrayComponent(char* arrayName, int component)
{
if (strcmp(this->ArrayName, arrayName) == 0 &&
component == this->ArrayComponent &&
this->ArrayAccessMode == VTK_GET_ARRAY_BY_ID)
{
return;
}
this->Modified();
strcpy(this->ArrayName, arrayName);
this->ArrayComponent = component;
this->ArrayAccessMode = VTK_GET_ARRAY_BY_NAME;
}
// Specify a lookup table for the mapper to use.
void vtkMapper::SetLookupTable(vtkScalarsToColors *lut)
{
if ( this->LookupTable != lut )
{
if ( this->LookupTable)
{
this->LookupTable->UnRegister(this);
}
this->LookupTable = lut;
if (lut)
{
lut->Register(this);
}
this->Modified();
}
}
vtkScalarsToColors *vtkMapper::GetLookupTable()
{
if ( this->LookupTable == NULL )
{
this->CreateDefaultLookupTable();
}
return this->LookupTable;
}
void vtkMapper::CreateDefaultLookupTable()
{
if ( this->LookupTable)
{
this->LookupTable->UnRegister(this);
}
this->LookupTable = vtkLookupTable::New();
}
// Update the network connected to this mapper.
void vtkMapper::Update()
{
if ( this->GetInput() )
{
this->GetInput()->Update();
}
}
// Return the method of coloring scalar data.
const char *vtkMapper::GetColorModeAsString(void)
{
if ( this->ColorMode == VTK_COLOR_MODE_LUMINANCE )
{
return "Luminance";
}
else if ( this->ColorMode == VTK_COLOR_MODE_MAP_SCALARS )
{
return "MapScalars";
}
else
{
return "Default";
}
}
// Return the method for obtaining scalar data.
const char *vtkMapper::GetScalarModeAsString(void)
{
if ( this->ScalarMode == VTK_SCALAR_MODE_USE_CELL_DATA )
{
return "UseCellData";
}
else if ( this->ScalarMode == VTK_SCALAR_MODE_USE_POINT_DATA )
{
return "UsePointData";
}
else if ( this->ScalarMode == VTK_SCALAR_MODE_USE_POINT_FIELD_DATA )
{
return "UsePointFieldData";
}
else if ( this->ScalarMode == VTK_SCALAR_MODE_USE_CELL_FIELD_DATA )
{
return "UseCellFieldData";
}
else
{
return "Default";
}
}
void vtkMapper::PrintSelf(ostream& os, vtkIndent indent)
{
this->vtkAbstractMapper3D::PrintSelf(os,indent);
if ( this->LookupTable )
{
os << indent << "Lookup Table:\n";
this->LookupTable->PrintSelf(os,indent.GetNextIndent());
}
else
{
os << indent << "Lookup Table: (none)\n";
}
os << indent << "Immediate Mode Rendering: "
<< (this->ImmediateModeRendering ? "On\n" : "Off\n");
os << indent << "Global Immediate Mode Rendering: " <<
(vtkMapperGlobalImmediateModeRendering ? "On\n" : "Off\n");
os << indent << "Scalar Visibility: "
<< (this->ScalarVisibility ? "On\n" : "Off\n");
float *range = this->GetScalarRange();
os << indent << "Scalar Range: (" << range[0] << ", " << range[1] << ")\n";
os << indent << "UseLookupTableScalarRange: " << this->UseLookupTableScalarRange << "\n";
os << indent << "Color Mode: " << this->GetColorModeAsString() << endl;
os << indent << "Scalar Mode: " << this->GetScalarModeAsString() << endl;
os << indent << "RenderTime: " << this->RenderTime << endl;
os << indent << "Resolve Coincident Topology: ";
if ( vtkMapperGlobalResolveCoincidentTopology == VTK_RESOLVE_OFF )
{
os << "Off" << endl;
}
else if ( vtkMapperGlobalResolveCoincidentTopology == VTK_RESOLVE_POLYGON_OFFSET )
{
os << "Polygon Offset" << endl;
}
else
{
os << "Shift Z-Buffer" << endl;
}
}
<commit_msg>ENH:Notify the user that the indicated data array was not found when performing scalar coloring<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: vtkMapper.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 1993-2001 Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names
of any contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
* Modified source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS''
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
=========================================================================*/
#include "vtkMapper.h"
#include "vtkLookupTable.h"
// Initialize static member that controls global immediate mode rendering
static int vtkMapperGlobalImmediateModeRendering = 0;
// Initialize static member that controls global coincidence resolution
static int vtkMapperGlobalResolveCoincidentTopology = VTK_RESOLVE_OFF;
static double vtkMapperGlobalResolveCoincidentTopologyZShift = 0.01;
static float vtkMapperGlobalResolveCoincidentTopologyPolygonOffsetFactor = 1.0;
static float vtkMapperGlobalResolveCoincidentTopologyPolygonOffsetUnits = 1.0;
// Construct with initial range (0,1).
vtkMapper::vtkMapper()
{
this->Colors = NULL;
this->LookupTable = NULL;
this->ScalarVisibility = 1;
this->ScalarRange[0] = 0.0; this->ScalarRange[1] = 1.0;
this->UseLookupTableScalarRange = 0;
this->ImmediateModeRendering = 0;
this->ColorMode = VTK_COLOR_MODE_DEFAULT;
this->ScalarMode = VTK_SCALAR_MODE_DEFAULT;
this->Bounds[0] = this->Bounds[2] = this->Bounds[4] = -1.0;
this->Bounds[1] = this->Bounds[3] = this->Bounds[5] = 1.0;
this->Center[0] = this->Center[1] = this->Center[2] = 0.0;
this->RenderTime = 0.0;
strcpy(this->ArrayName, "");
this->ArrayId = -1;
this->ArrayComponent = -1;
this->ArrayAccessMode = -1;
}
vtkMapper::~vtkMapper()
{
if (this->LookupTable)
{
this->LookupTable->UnRegister(this);
}
if ( this->Colors != NULL )
{
this->Colors->UnRegister(this);
}
}
// Get the bounds for the input of this mapper as
// (Xmin,Xmax,Ymin,Ymax,Zmin,Zmax).
float *vtkMapper::GetBounds()
{
static float bounds[] = {-1.0,1.0, -1.0,1.0, -1.0,1.0};
if ( ! this->GetInput() )
{
return bounds;
}
else
{
this->Update();
this->GetInput()->GetBounds(this->Bounds);
return this->Bounds;
}
}
vtkDataSet *vtkMapper::GetInput()
{
if (this->NumberOfInputs < 1)
{
return NULL;
}
return (vtkDataSet *)(this->Inputs[0]);
}
void vtkMapper::SetGlobalImmediateModeRendering(int val)
{
if (val == vtkMapperGlobalImmediateModeRendering)
{
return;
}
vtkMapperGlobalImmediateModeRendering = val;
}
int vtkMapper::GetGlobalImmediateModeRendering()
{
return vtkMapperGlobalImmediateModeRendering;
}
void vtkMapper::SetResolveCoincidentTopology(int val)
{
if (val == vtkMapperGlobalResolveCoincidentTopology)
{
return;
}
vtkMapperGlobalResolveCoincidentTopology = val;
}
int vtkMapper::GetResolveCoincidentTopology()
{
return vtkMapperGlobalResolveCoincidentTopology;
}
void vtkMapper::SetResolveCoincidentTopologyToDefault()
{
vtkMapperGlobalResolveCoincidentTopology = VTK_RESOLVE_OFF;
}
void vtkMapper::SetResolveCoincidentTopologyZShift(double val)
{
if (val == vtkMapperGlobalResolveCoincidentTopologyZShift)
{
return;
}
vtkMapperGlobalResolveCoincidentTopologyZShift = val;
}
double vtkMapper::GetResolveCoincidentTopologyZShift()
{
return vtkMapperGlobalResolveCoincidentTopologyZShift;
}
void vtkMapper::SetResolveCoincidentTopologyPolygonOffsetParameters(
float factor, float units)
{
if (factor == vtkMapperGlobalResolveCoincidentTopologyPolygonOffsetFactor &&
units == vtkMapperGlobalResolveCoincidentTopologyPolygonOffsetUnits )
{
return;
}
vtkMapperGlobalResolveCoincidentTopologyPolygonOffsetFactor = factor;
vtkMapperGlobalResolveCoincidentTopologyPolygonOffsetFactor = units;
}
void vtkMapper::GetResolveCoincidentTopologyPolygonOffsetParameters(
float& factor, float& units)
{
factor = vtkMapperGlobalResolveCoincidentTopologyPolygonOffsetFactor;
units = vtkMapperGlobalResolveCoincidentTopologyPolygonOffsetUnits;
}
// Overload standard modified time function. If lookup table is modified,
// then this object is modified as well.
unsigned long vtkMapper::GetMTime()
{
unsigned long mTime=this->MTime.GetMTime();
unsigned long lutMTime;
if ( this->LookupTable != NULL )
{
lutMTime = this->LookupTable->GetMTime();
mTime = ( lutMTime > mTime ? lutMTime : mTime );
}
return mTime;
}
void vtkMapper::ShallowCopy(vtkMapper *m)
{
this->SetLookupTable(m->GetLookupTable());
this->SetClippingPlanes(m->GetClippingPlanes());
this->SetScalarVisibility(m->GetScalarVisibility());
this->SetScalarRange(m->GetScalarRange());
this->SetColorMode(m->GetColorMode());
this->SetScalarMode(m->GetScalarMode());
this->SetImmediateModeRendering(m->GetImmediateModeRendering());
}
// a side effect of this is that this->Colors is also set
// to the return value
vtkScalars *vtkMapper::GetColors()
{
vtkScalars *scalars = NULL;
vtkDataArray *dataArray=0;
vtkPointData *pd;
vtkCellData *cd;
vtkIdType i, numScalars;
// make sure we have an input
if (!this->GetInput())
{
return NULL;
}
// get and scalar data according to scalar mode
if ( this->ScalarMode == VTK_SCALAR_MODE_DEFAULT )
{
scalars = this->GetInput()->GetPointData()->GetScalars();
if (!scalars)
{
scalars = this->GetInput()->GetCellData()->GetScalars();
}
}
else if ( this->ScalarMode == VTK_SCALAR_MODE_USE_POINT_DATA )
{
scalars = this->GetInput()->GetPointData()->GetScalars();
}
else if ( this->ScalarMode == VTK_SCALAR_MODE_USE_CELL_DATA )
{
scalars = this->GetInput()->GetCellData()->GetScalars();
}
else if ( this->ScalarMode == VTK_SCALAR_MODE_USE_POINT_FIELD_DATA )
{
pd = this->GetInput()->GetPointData();
if (pd)
{
if (this->ArrayAccessMode == VTK_GET_ARRAY_BY_ID)
{
dataArray = pd->GetArray(this->ArrayId);
}
else
{
dataArray = pd->GetArray(this->ArrayName);
}
}
if (dataArray &&
(this->ArrayComponent < dataArray->GetNumberOfComponents()))
{
scalars = vtkScalars::New();
numScalars = dataArray->GetNumberOfTuples();
scalars->SetNumberOfScalars(numScalars);
if (dataArray->GetNumberOfComponents() == 1)
{
scalars->SetData(dataArray);
}
else
{ // I do not know how useful it is to color by a componenet.
// This could probably be done with out a copy
// by using active component.
for (i = 0; i < numScalars; i++)
{
scalars->
InsertScalar(i, dataArray->GetComponent(i, this->ArrayComponent));
}
}
}
else
{
vtkWarningMacro(<<"Data array (used for coloring) not found");
}
}
else if ( this->ScalarMode == VTK_SCALAR_MODE_USE_CELL_FIELD_DATA )
{
cd = this->GetInput()->GetCellData();
if (cd)
{
if (this->ArrayAccessMode == VTK_GET_ARRAY_BY_ID)
{
dataArray = cd->GetArray(this->ArrayId);
}
else
{
dataArray = cd->GetArray(this->ArrayName);
}
}
if (dataArray &&
(this->ArrayComponent < dataArray->GetNumberOfComponents()))
{
scalars = vtkScalars::New();
numScalars = dataArray->GetNumberOfTuples();
scalars->SetNumberOfScalars(numScalars);
if (dataArray->GetNumberOfComponents() == 1)
{
scalars->SetData(dataArray);
}
else
{ // I do not know how useful it is to color by a componenet.
// This could probably be done with out a copy
// by using active component.
for (i = 0; i < numScalars; i++)
{
scalars->
InsertScalar(i, dataArray->GetComponent(i, this->ArrayComponent));
}
}
}
else
{
vtkWarningMacro(<<"Data array (used for coloring) not found");
}
}
// do we have any scalars ?
if (scalars && this->ScalarVisibility)
{
// if the scalars have a lookup table use it instead
if (scalars->GetLookupTable())
{
this->SetLookupTable(scalars->GetLookupTable());
}
else
{
// make sure we have a lookup table
if ( this->LookupTable == NULL )
{
this->CreateDefaultLookupTable();
}
this->LookupTable->Build();
}
// Setup mapper/scalar object for color generation
if (!this->UseLookupTableScalarRange)
{
this->LookupTable->SetRange(this->ScalarRange);
}
if (this->Colors)
{
this->Colors->UnRegister(this);
}
this->Colors = scalars;
this->Colors->Register(this);
this->Colors->InitColorTraversal(1.0, this->LookupTable, this->ColorMode);
}
else //scalars not visible
{
if ( this->Colors )
{
this->Colors->UnRegister(this);
}
this->Colors = NULL;
}
if (((this->ScalarMode == VTK_SCALAR_MODE_USE_POINT_FIELD_DATA) ||
(this->ScalarMode == VTK_SCALAR_MODE_USE_CELL_FIELD_DATA)) &&
scalars)
{
scalars->Delete();
}
return this->Colors;
}
void vtkMapper::ColorByArrayComponent(int arrayNum, int component)
{
if (this->ArrayId == arrayNum && component == this->ArrayComponent &&
this->ArrayAccessMode == VTK_GET_ARRAY_BY_ID)
{
return;
}
this->Modified();
this->ArrayId = arrayNum;
this->ArrayComponent = component;
this->ArrayAccessMode = VTK_GET_ARRAY_BY_ID;
}
void vtkMapper::ColorByArrayComponent(char* arrayName, int component)
{
if (strcmp(this->ArrayName, arrayName) == 0 &&
component == this->ArrayComponent &&
this->ArrayAccessMode == VTK_GET_ARRAY_BY_ID)
{
return;
}
this->Modified();
strcpy(this->ArrayName, arrayName);
this->ArrayComponent = component;
this->ArrayAccessMode = VTK_GET_ARRAY_BY_NAME;
}
// Specify a lookup table for the mapper to use.
void vtkMapper::SetLookupTable(vtkScalarsToColors *lut)
{
if ( this->LookupTable != lut )
{
if ( this->LookupTable)
{
this->LookupTable->UnRegister(this);
}
this->LookupTable = lut;
if (lut)
{
lut->Register(this);
}
this->Modified();
}
}
vtkScalarsToColors *vtkMapper::GetLookupTable()
{
if ( this->LookupTable == NULL )
{
this->CreateDefaultLookupTable();
}
return this->LookupTable;
}
void vtkMapper::CreateDefaultLookupTable()
{
if ( this->LookupTable)
{
this->LookupTable->UnRegister(this);
}
this->LookupTable = vtkLookupTable::New();
}
// Update the network connected to this mapper.
void vtkMapper::Update()
{
if ( this->GetInput() )
{
this->GetInput()->Update();
}
}
// Return the method of coloring scalar data.
const char *vtkMapper::GetColorModeAsString(void)
{
if ( this->ColorMode == VTK_COLOR_MODE_LUMINANCE )
{
return "Luminance";
}
else if ( this->ColorMode == VTK_COLOR_MODE_MAP_SCALARS )
{
return "MapScalars";
}
else
{
return "Default";
}
}
// Return the method for obtaining scalar data.
const char *vtkMapper::GetScalarModeAsString(void)
{
if ( this->ScalarMode == VTK_SCALAR_MODE_USE_CELL_DATA )
{
return "UseCellData";
}
else if ( this->ScalarMode == VTK_SCALAR_MODE_USE_POINT_DATA )
{
return "UsePointData";
}
else if ( this->ScalarMode == VTK_SCALAR_MODE_USE_POINT_FIELD_DATA )
{
return "UsePointFieldData";
}
else if ( this->ScalarMode == VTK_SCALAR_MODE_USE_CELL_FIELD_DATA )
{
return "UseCellFieldData";
}
else
{
return "Default";
}
}
void vtkMapper::PrintSelf(ostream& os, vtkIndent indent)
{
this->vtkAbstractMapper3D::PrintSelf(os,indent);
if ( this->LookupTable )
{
os << indent << "Lookup Table:\n";
this->LookupTable->PrintSelf(os,indent.GetNextIndent());
}
else
{
os << indent << "Lookup Table: (none)\n";
}
os << indent << "Immediate Mode Rendering: "
<< (this->ImmediateModeRendering ? "On\n" : "Off\n");
os << indent << "Global Immediate Mode Rendering: " <<
(vtkMapperGlobalImmediateModeRendering ? "On\n" : "Off\n");
os << indent << "Scalar Visibility: "
<< (this->ScalarVisibility ? "On\n" : "Off\n");
float *range = this->GetScalarRange();
os << indent << "Scalar Range: (" << range[0] << ", " << range[1] << ")\n";
os << indent << "UseLookupTableScalarRange: " << this->UseLookupTableScalarRange << "\n";
os << indent << "Color Mode: " << this->GetColorModeAsString() << endl;
os << indent << "Scalar Mode: " << this->GetScalarModeAsString() << endl;
os << indent << "RenderTime: " << this->RenderTime << endl;
os << indent << "Resolve Coincident Topology: ";
if ( vtkMapperGlobalResolveCoincidentTopology == VTK_RESOLVE_OFF )
{
os << "Off" << endl;
}
else if ( vtkMapperGlobalResolveCoincidentTopology == VTK_RESOLVE_POLYGON_OFFSET )
{
os << "Polygon Offset" << endl;
}
else
{
os << "Shift Z-Buffer" << endl;
}
}
<|endoftext|> |
<commit_before>#ifndef HUM_GAME_HPP
#define HUM_GAME_HPP
#include <vector>
#include <unordered_set>
#include "Exceptions.hpp"
#include "Time.hpp"
#include "ActorPool.hpp"
namespace hum
{
class Plugin;
class Actor;
class Game
{
public:
/*!
\brief Class constructor
`fixed_tickrate` is the frequency of the `fixedUpdate`. By default 60Hz.
*/
Game(unsigned int fixed_tickrate = 60);
/*!
\brief Class destructor
Takes care of destroying any remaining Actor%s and Plugin%s.
*/
~Game();
/*!
\brief Run the Game
Starts running the game loop. See the Game class description for the flow chart
of the main loop's steps.
*/
void run();
/*!
\brief Get the delta Time of the game update.
\return Time elapsed between previous update and current update.
*/
const Time& deltaTime() const;
/*!
\brief Get the delta Time of the game fixedUpdate.
\return Time elapsed between previous fixedUpdate and current fixedUpdate.
*/
Time fixedUpdateTime() const;
/*!
\brief Get the Time since the last fixedUpdate.
\return Time elapsed since the last fixedUpdate.
*/
Time fixedUpdateLag() const;
/*!
\brief Set the Game's running status.
*/
void setRunning(bool running);
/*!
\brief Create a new Actor instance.
\return The new Actor instance's pointer.
*/
Actor* makeActor();
/*!
\brief Mark an Actor to be destroyed.
*/
void destroy(Actor* actor);
/*!
\brief Mark an Actor to be destroyed.
*/
void destroy(Actor& actor);
/*!
\brief Get the Actor object pool.
\return An ActorPool instance
*/
const ActorPool& actors() const;
/*!
\brief Get the Actor object pool.
\return An ActorPool instance
*/
ActorPool& actors();
/*!
\brief Add a new Plugin to the Game.
\tparam P The Plugin's type.
\tparam Args The parameters for P's constructor.
\return A `P` pointer to the new Plugin instance.
*/
template <typename P, class... Args>
P* addPlugin(Args&&... args)
{
P* p = new P(args...);
p->p_game = this;
p_plugins.push_back(p);
return p;
}
/*!
\brief Get and exisitng Plugin from the Game.
\tparam P The Plugin's type.
If the Game doesn't contain a Plugin of the given type it will throw a
exception::PluginNotFound exception.
\return A `P` pointer to the Plugin instance.
*/
template <typename P>
const P* getPlugin() const throw(exception::PluginNotFound)
{
P* plugin;
for (Plugin* p : p_plugins)
if ((plugin = dynamic_cast<P*>(p)) != nullptr)
return plugin;
throw exception::PluginNotFound();
}
/*!
\brief Get and exisitng Plugin from the Game.
\tparam P The Plugin's type.
If the Game doesn't contain a Plugin of the given type it will throw a
exception::PluginNotFound exception.
\return A `P` pointer to the Plugin instance.
*/
template <typename P>
P* getPlugin() throw(exception::PluginNotFound)
{
P* plugin;
for (Plugin* p : p_plugins)
if ((plugin = dynamic_cast<P*>(p)) != nullptr)
return plugin;
throw exception::PluginNotFound();
}
private:
bool p_running;
const long c_nanoseconds_per_fixed_update;
long p_fixed_update_lag;
Time p_delta_time;
ActorPool p_actor_pool;
std::vector<Plugin*> p_plugins;
};
/*!
\class hum::Game
\brief The class that runs the Game.
The Game class handles the game loop and the lifecycle of the game. To start
running a Game just call `Game::run()` and the Game instance will enter the
following flow chart. The flow chart shows the lifecycle of a Game and the
different steps that happen through it.
\image html game_loop.png
\image latex game_loop.png "Game loop"
A Game instance can be queried for Time information at any step (when the
Game is running). This information can be the deltaTime(), which is the Time
that passed between the previous `update` and the current `update`; the fixedUpdateTime() which is
the Time that passes between `fixedUpdate` and `fixedUpdate` and is calculated
from the `fixed_tickrate` constructor parameter; and the
fixedUpdateLag(), this last value is the Time since the last `fixedUpdate`.
The running state of the Game can be controlled by using setRunning(). If set
to `false` the game loop will exit and the Game will end. A Game instance
should not be reused once the Game is done running, as the final state is not
guaranteed in any way.
The Game class also owns the Actor object pool and therefore handles the
creation and destruction of Actors. Example code:
\code
hum::Game game;
hum::Actor* new_actor = game.makeActor(); // creation of a new Actor;
// ...
game.destroy(new_actor); // mark the Actor to be destroyed.
\endcode
Actor%s are not destroyed right away, but marked to be destroyed and destroyed
after `Plugin::postUpdate()`. All Actor%s are destroyed automatically after
`Plugin:gameEnd()`.
A Game instance can also contain Plugin%s. Plugin%s can implement functionality
for the Game such as a rendering pipeline, scene management, etc. They can be
added and queried by typename using addPlugin() and getPlugin() template methods
respectively (example below).
\code
class MyPlugin : public hum::Plugin {...};
hum::Game game;
MyPlugin* mp = game.addPlugin<MyPlugin>();
// somewhere else in the code (p.e. inside a Behavior)
MyPlugin* mp = game().getPlugin<MyPlugin>();
\endcode
A Plugin shouldn't be added after calling run().
*/
}
#endif
<commit_msg>Remove unneeded methods from Game header<commit_after>#ifndef HUM_GAME_HPP
#define HUM_GAME_HPP
#include <vector>
#include <unordered_set>
#include "Exceptions.hpp"
#include "Time.hpp"
#include "ActorPool.hpp"
namespace hum
{
class Plugin;
class Actor;
class Game
{
public:
/*!
\brief Class constructor
`fixed_tickrate` is the frequency of the `fixedUpdate`. By default 60Hz.
*/
Game(unsigned int fixed_tickrate = 60);
/*!
\brief Class destructor
Takes care of destroying any remaining Actor%s and Plugin%s.
*/
~Game();
/*!
\brief Run the Game
Starts running the game loop. See the Game class description for the flow chart
of the main loop's steps.
*/
void run();
/*!
\brief Get the delta Time of the game update.
\return Time elapsed between previous update and current update.
*/
const Time& deltaTime() const;
/*!
\brief Get the delta Time of the game fixedUpdate.
\return Time elapsed between previous fixedUpdate and current fixedUpdate.
*/
Time fixedUpdateTime() const;
/*!
\brief Get the Time since the last fixedUpdate.
\return Time elapsed since the last fixedUpdate.
*/
Time fixedUpdateLag() const;
/*!
\brief Set the Game's running status.
*/
void setRunning(bool running);
/*!
\brief Get the Actor object pool.
\return An ActorPool instance
*/
const ActorPool& actors() const;
/*!
\brief Get the Actor object pool.
\return An ActorPool instance
*/
ActorPool& actors();
/*!
\brief Add a new Plugin to the Game.
\tparam P The Plugin's type.
\tparam Args The parameters for P's constructor.
\return A `P` pointer to the new Plugin instance.
*/
template <typename P, class... Args>
P* addPlugin(Args&&... args)
{
P* p = new P(args...);
p->p_game = this;
p_plugins.push_back(p);
return p;
}
/*!
\brief Get and exisitng Plugin from the Game.
\tparam P The Plugin's type.
If the Game doesn't contain a Plugin of the given type it will throw a
exception::PluginNotFound exception.
\return A `P` pointer to the Plugin instance.
*/
template <typename P>
const P* getPlugin() const throw(exception::PluginNotFound)
{
P* plugin;
for (Plugin* p : p_plugins)
if ((plugin = dynamic_cast<P*>(p)) != nullptr)
return plugin;
throw exception::PluginNotFound();
}
/*!
\brief Get and exisitng Plugin from the Game.
\tparam P The Plugin's type.
If the Game doesn't contain a Plugin of the given type it will throw a
exception::PluginNotFound exception.
\return A `P` pointer to the Plugin instance.
*/
template <typename P>
P* getPlugin() throw(exception::PluginNotFound)
{
P* plugin;
for (Plugin* p : p_plugins)
if ((plugin = dynamic_cast<P*>(p)) != nullptr)
return plugin;
throw exception::PluginNotFound();
}
private:
bool p_running;
const long c_nanoseconds_per_fixed_update;
long p_fixed_update_lag;
Time p_delta_time;
ActorPool p_actor_pool;
std::vector<Plugin*> p_plugins;
};
/*!
\class hum::Game
\brief The class that runs the Game.
The Game class handles the game loop and the lifecycle of the game. To start
running a Game just call `Game::run()` and the Game instance will enter the
following flow chart. The flow chart shows the lifecycle of a Game and the
different steps that happen through it.
\image html game_loop.png
\image latex game_loop.png "Game loop"
A Game instance can be queried for Time information at any step (when the
Game is running). This information can be the deltaTime(), which is the Time
that passed between the previous `update` and the current `update`; the fixedUpdateTime() which is
the Time that passes between `fixedUpdate` and `fixedUpdate` and is calculated
from the `fixed_tickrate` constructor parameter; and the
fixedUpdateLag(), this last value is the Time since the last `fixedUpdate`.
The running state of the Game can be controlled by using setRunning(). If set
to `false` the game loop will exit and the Game will end. A Game instance
should not be reused once the Game is done running, as the final state is not
guaranteed in any way.
The Game class also owns the Actor object pool and therefore handles the
creation and destruction of Actors. Example code:
\code
hum::Game game;
hum::Actor* new_actor = game.makeActor(); // creation of a new Actor;
// ...
game.destroy(new_actor); // mark the Actor to be destroyed.
\endcode
Actor%s are not destroyed right away, but marked to be destroyed and destroyed
after `Plugin::postUpdate()`. All Actor%s are destroyed automatically after
`Plugin:gameEnd()`.
A Game instance can also contain Plugin%s. Plugin%s can implement functionality
for the Game such as a rendering pipeline, scene management, etc. They can be
added and queried by typename using addPlugin() and getPlugin() template methods
respectively (example below).
\code
class MyPlugin : public hum::Plugin {...};
hum::Game game;
MyPlugin* mp = game.addPlugin<MyPlugin>();
// somewhere else in the code (p.e. inside a Behavior)
MyPlugin* mp = game().getPlugin<MyPlugin>();
\endcode
A Plugin shouldn't be added after calling run().
*/
}
#endif
<|endoftext|> |
<commit_before>
#include "game/debugtools/formpreview.h"
#include "framework/framework.h"
namespace OpenApoc
{
FormPreview::FormPreview() : Stage()
{
displayform = nullptr;
currentSelected = nullptr;
currentSelectedControl = nullptr;
glowindex = 0;
previewselector.reset(new Form(nullptr));
previewselector->Size.x = 200;
previewselector->Size.y = 300;
previewselector->Location.x = 2;
previewselector->Location.y = 2;
previewselector->BackgroundColour.r = 192;
previewselector->BackgroundColour.g = 192;
previewselector->BackgroundColour.b = 192;
Control *ch = new Control(previewselector.get());
ch->Location.x = 2;
ch->Location.y = 2;
ch->Size.x = previewselector->Size.x - 4;
ch->Size.y = previewselector->Size.y - 4;
ch->BackgroundColour.r = 80;
ch->BackgroundColour.g = 80;
ch->BackgroundColour.b = 80;
Control *c = new Control(ch);
c->Location.x = 2;
c->Location.y = 2;
c->Size.x = previewselector->Size.x - 4;
c->Size.y = previewselector->Size.y - 4;
c->BackgroundColour.r = 80;
c->BackgroundColour.g = 80;
c->BackgroundColour.b = 80;
Label *l = new Label(c, "Pick Form:", fw().gamecore->GetFont("SMALFONT"));
l->Location.x = 0;
l->Location.y = 0;
l->Size.x = c->Size.x;
l->Size.y = fw().gamecore->GetFont("SMALFONT")->GetFontHeight();
l->BackgroundColour.b = l->BackgroundColour.r;
l->BackgroundColour.g = l->BackgroundColour.r;
interactWithDisplay = new CheckBox(c);
interactWithDisplay->Size.y = fw().gamecore->GetFont("SMALFONT")->GetFontHeight();
interactWithDisplay->Size.x = interactWithDisplay->Size.y;
interactWithDisplay->Location.x = 0;
interactWithDisplay->Location.y = c->Size.y - interactWithDisplay->Size.y;
interactWithDisplay->BackgroundColour.r = 80;
interactWithDisplay->BackgroundColour.g = 80;
interactWithDisplay->BackgroundColour.b = 80;
interactWithDisplay->Checked = true;
l = new Label(c, "Interact?", fw().gamecore->GetFont("SMALFONT"));
l->Location.x = interactWithDisplay->Size.x + 2;
l->Location.y = interactWithDisplay->Location.y;
l->Size.x = c->Size.x - l->Location.x;
l->Size.y = interactWithDisplay->Size.y;
l->BackgroundColour.r = 80;
l->BackgroundColour.g = 80;
l->BackgroundColour.b = 80;
ListBox *lb = new ListBox(c);
lb->Location.x = 0;
lb->Location.y = fw().gamecore->GetFont("SMALFONT")->GetFontHeight();
lb->Size.x = c->Size.x;
lb->Size.y = interactWithDisplay->Location.y - lb->Location.y;
lb->Name = "FORM_LIST";
lb->ItemSize = lb->Location.y;
lb->BackgroundColour.r = 24;
lb->BackgroundColour.g = 24;
lb->BackgroundColour.b = 24;
std::vector<UString> idlist = fw().gamecore->GetFormIDs();
for (auto idx = idlist.begin(); idx != idlist.end(); idx++)
{
l = new Label(lb, (UString)*idx, fw().gamecore->GetFont("SMALFONT"));
l->Name = l->GetText();
l->BackgroundColour.r = 192;
l->BackgroundColour.g = 80;
l->BackgroundColour.b = 80;
l->BackgroundColour.a = 0;
// lb->AddItem( l );
}
propertyeditor.reset(new Form(nullptr));
propertyeditor->Location.x = 2;
propertyeditor->Location.y = 304;
propertyeditor->Size.x = 200;
propertyeditor->Size.y = fw().Display_GetHeight() - propertyeditor->Location.y - 2;
propertyeditor->BackgroundColour.r = 192;
propertyeditor->BackgroundColour.g = 192;
propertyeditor->BackgroundColour.b = 192;
}
FormPreview::~FormPreview() {}
void FormPreview::Begin() {}
void FormPreview::Pause() {}
void FormPreview::Resume() {}
void FormPreview::Finish() {}
void FormPreview::EventOccurred(Event *e)
{
previewselector->EventOccured(e);
if (propertyeditor != nullptr)
{
propertyeditor->EventOccured(e);
}
if (displayform != nullptr && interactWithDisplay->Checked)
{
displayform->EventOccured(e);
}
fw().gamecore->MouseCursor->EventOccured(e);
if (e->Type == EVENT_KEY_DOWN)
{
if (e->Data.Keyboard.KeyCode == SDLK_ESCAPE)
{
stageCmd.cmd = StageCmd::Command::POP;
return;
}
}
if (e->Type == EVENT_FORM_INTERACTION && e->Data.Forms.EventFlag == FormEventType::MouseClick)
{
if (displayform != nullptr && e->Data.Forms.RaisedBy->GetForm() == displayform.get())
{
currentSelectedControl = e->Data.Forms.RaisedBy;
ConfigureSelectedControlForm();
}
else
{
currentSelectedControl = nullptr;
ConfigureSelectedControlForm();
}
if (e->Data.Forms.RaisedBy->GetForm() == previewselector.get() &&
e->Data.Forms.RaisedBy->GetParent()->Name == "FORM_LIST")
{
if (currentSelected != nullptr)
{
currentSelected->BackgroundColour.a = 0;
}
currentSelected = (Label *)e->Data.Forms.RaisedBy;
currentSelected->BackgroundColour.a = 255;
displayform.reset(fw().gamecore->GetForm(currentSelected->Name));
return;
}
}
}
void FormPreview::Update(StageCmd *const cmd)
{
previewselector->Update();
if (propertyeditor != nullptr)
{
propertyeditor->Update();
}
if (displayform != nullptr)
{
displayform->Update();
}
*cmd = this->stageCmd;
// Reset the command to default
this->stageCmd = StageCmd();
glowindex = (glowindex + 4) % 511;
}
void FormPreview::Render()
{
if (displayform != nullptr)
{
displayform->Render();
}
previewselector->Render();
if (propertyeditor != nullptr)
{
propertyeditor->Render();
}
if (currentSelectedControl != nullptr)
{
Vec2<int> border = currentSelectedControl->GetLocationOnScreen();
if (glowindex < 256)
{
fw().renderer->drawRect(border, currentSelectedControl->Size,
OpenApoc::Colour(glowindex, glowindex, glowindex), 3.0f);
}
else
{
int revglow = 255 - (glowindex - 256);
fw().renderer->drawRect(border, currentSelectedControl->Size,
OpenApoc::Colour(revglow, revglow, revglow), 3.0f);
}
}
fw().gamecore->MouseCursor->Render();
}
bool FormPreview::IsTransition() { return false; }
void FormPreview::ConfigureSelectedControlForm()
{
if (currentSelectedControl == nullptr)
{
}
else
{
}
}
}; // namespace OpenApoc
<commit_msg>Fix form previewer colors<commit_after>
#include "game/debugtools/formpreview.h"
#include "framework/framework.h"
namespace OpenApoc
{
FormPreview::FormPreview() : Stage()
{
displayform = nullptr;
currentSelected = nullptr;
currentSelectedControl = nullptr;
glowindex = 0;
previewselector.reset(new Form(nullptr));
previewselector->Size = {200, 300};
previewselector->Location = {2, 2};
previewselector->BackgroundColour = {192, 192, 192, 255};
Control *ch = new Control(previewselector.get());
ch->Location = {2, 2};
ch->Size = previewselector->Size - 4;
ch->BackgroundColour = {80, 80, 80, 255};
Control *c = new Control(ch);
c->Location = {2, 2};
c->Size = previewselector->Size - 4;
c->BackgroundColour = {80, 80, 80, 255};
Label *l = new Label(c, "Pick Form:", fw().gamecore->GetFont("SMALFONT"));
l->Location = {0, 0};
l->Size.x = c->Size.x;
l->Size.y = fw().gamecore->GetFont("SMALFONT")->GetFontHeight();
l->BackgroundColour = {80, 80, 80, 255};
interactWithDisplay = new CheckBox(c);
interactWithDisplay->Size.y = fw().gamecore->GetFont("SMALFONT")->GetFontHeight();
interactWithDisplay->Size.x = interactWithDisplay->Size.y;
interactWithDisplay->Location.x = 0;
interactWithDisplay->Location.y = c->Size.y - interactWithDisplay->Size.y;
interactWithDisplay->BackgroundColour = {80, 80, 80, 255};
interactWithDisplay->SetChecked(true);
l = new Label(c, "Interact?", fw().gamecore->GetFont("SMALFONT"));
l->Location.x = interactWithDisplay->Size.x + 2;
l->Location.y = interactWithDisplay->Location.y;
l->Size.x = c->Size.x - l->Location.x;
l->Size.y = interactWithDisplay->Size.y;
l->BackgroundColour = {80, 80, 80, 255};
ListBox *lb = new ListBox(c);
lb->Location.x = 0;
lb->Location.y = fw().gamecore->GetFont("SMALFONT")->GetFontHeight();
lb->Size.x = c->Size.x;
lb->Size.y = interactWithDisplay->Location.y - lb->Location.y;
lb->Name = "FORM_LIST";
lb->ItemSize = lb->Location.y;
lb->BackgroundColour = {24, 24, 24, 255};
std::vector<UString> idlist = fw().gamecore->GetFormIDs();
for (auto idx = idlist.begin(); idx != idlist.end(); idx++)
{
l = new Label(lb, (UString)*idx, fw().gamecore->GetFont("SMALFONT"));
l->Name = l->GetText();
l->BackgroundColour = {192, 80, 80, 0};
// lb->AddItem( l );
}
propertyeditor.reset(new Form(nullptr));
propertyeditor->Location = {2, 304};
propertyeditor->Size.x = 200;
propertyeditor->Size.y = fw().Display_GetHeight() - propertyeditor->Location.y - 2;
propertyeditor->BackgroundColour = {192, 192, 192, 255};
}
FormPreview::~FormPreview() {}
void FormPreview::Begin() {}
void FormPreview::Pause() {}
void FormPreview::Resume() {}
void FormPreview::Finish() {}
void FormPreview::EventOccurred(Event *e)
{
previewselector->EventOccured(e);
if (propertyeditor != nullptr)
{
propertyeditor->EventOccured(e);
}
if (displayform != nullptr && interactWithDisplay->IsChecked())
{
displayform->EventOccured(e);
}
fw().gamecore->MouseCursor->EventOccured(e);
if (e->Type == EVENT_KEY_DOWN)
{
if (e->Data.Keyboard.KeyCode == SDLK_ESCAPE)
{
stageCmd.cmd = StageCmd::Command::POP;
return;
}
}
if (e->Type == EVENT_FORM_INTERACTION && e->Data.Forms.EventFlag == FormEventType::MouseClick)
{
if (displayform != nullptr && e->Data.Forms.RaisedBy->GetForm() == displayform.get())
{
currentSelectedControl = e->Data.Forms.RaisedBy;
ConfigureSelectedControlForm();
}
else
{
currentSelectedControl = nullptr;
ConfigureSelectedControlForm();
}
if (e->Data.Forms.RaisedBy->GetForm() == previewselector.get() &&
e->Data.Forms.RaisedBy->GetParent()->Name == "FORM_LIST")
{
if (currentSelected != nullptr)
{
currentSelected->BackgroundColour.a = 0;
}
currentSelected = (Label *)e->Data.Forms.RaisedBy;
currentSelected->BackgroundColour.a = 255;
displayform.reset(fw().gamecore->GetForm(currentSelected->Name));
return;
}
}
}
void FormPreview::Update(StageCmd *const cmd)
{
previewselector->Update();
if (propertyeditor != nullptr)
{
propertyeditor->Update();
}
if (displayform != nullptr)
{
displayform->Update();
}
*cmd = this->stageCmd;
// Reset the command to default
this->stageCmd = StageCmd();
glowindex = (glowindex + 4) % 511;
}
void FormPreview::Render()
{
if (displayform != nullptr)
{
displayform->Render();
}
previewselector->Render();
if (propertyeditor != nullptr)
{
propertyeditor->Render();
}
if (currentSelectedControl != nullptr)
{
Vec2<int> border = currentSelectedControl->GetLocationOnScreen();
if (glowindex < 256)
{
fw().renderer->drawRect(border, currentSelectedControl->Size,
OpenApoc::Colour(glowindex, glowindex, glowindex), 3.0f);
}
else
{
int revglow = 255 - (glowindex - 256);
fw().renderer->drawRect(border, currentSelectedControl->Size,
OpenApoc::Colour(revglow, revglow, revglow), 3.0f);
}
}
fw().gamecore->MouseCursor->Render();
}
bool FormPreview::IsTransition() { return false; }
void FormPreview::ConfigureSelectedControlForm()
{
if (currentSelectedControl == nullptr)
{
}
else
{
}
}
}; // namespace OpenApoc
<|endoftext|> |
<commit_before>/*!
http://www.codeguru.com/cpp/controls/controls/dateselectioncontrolsetc/article.php/c2229/
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/sysinfo/base/converting_a_time_t_value_to_a_file_time.asp
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/shellcc/platform/commctls/monthcal/structures/nmdaystate.asp
* \file dcxcalendar.cpp
* \brief blah
*
* blah
*
* \author David Legault ( clickhere at scriptsdb dot org )
* \version 1.0
*
* \b Revisions
*
* ScriptsDB.org - 2006
*/
#include "dcxcalendar.h"
#include "dcxdialog.h"
/*!
* \brief Constructor
*
* \param ID Control ID
* \param p_Dialog Parent DcxDialog Object
* \param rc Window Rectangle
* \param styles Window Style Tokenized List
*/
DcxCalendar::DcxCalendar( UINT ID, DcxDialog * p_Dialog, RECT * rc, TString & styles )
: DcxControl( ID, p_Dialog )
{
LONG Styles = 0, ExStyles = 0;
BOOL bNoTheme = FALSE;
this->parseControlStyles( styles, &Styles, &ExStyles, &bNoTheme );
this->m_Hwnd = CreateWindowEx(
ExStyles | WS_EX_CLIENTEDGE,
DCX_CALENDARCLASS,
NULL,
WS_CHILD | WS_VISIBLE | WS_CLIPCHILDREN | Styles,
rc->left, rc->top, rc->right - rc->left, rc->bottom - rc->top,
p_Dialog->getHwnd( ),
(HMENU) ID,
GetModuleHandle( NULL ),
NULL);
if ( bNoTheme )
dcxSetWindowTheme( this->m_Hwnd , L" ", L" " );
this->setControlFont( (HFONT) GetStockObject( DEFAULT_GUI_FONT ), FALSE );
this->registreDefaultWindowProc( );
SetProp( this->m_Hwnd, "dcx_cthis", (HANDLE) this );
}
/*!
* \brief Constructor
*
* \param ID Control ID
* \param p_Dialog Parent DcxDialog Object
* \param mParentHwnd Parent Window Handle
* \param rc Window Rectangle
* \param styles Window Style Tokenized List
*/
DcxCalendar::DcxCalendar( UINT ID, DcxDialog * p_Dialog, HWND mParentHwnd, RECT * rc, TString & styles )
: DcxControl( ID, p_Dialog )
{
LONG Styles = 0, ExStyles = 0;
BOOL bNoTheme = FALSE;
this->parseControlStyles( styles, &Styles, &ExStyles, &bNoTheme );
this->m_Hwnd = CreateWindowEx(
ExStyles | WS_EX_CLIENTEDGE,
DCX_CALENDARCLASS,
NULL,
WS_CHILD | WS_VISIBLE | WS_CLIPCHILDREN | Styles,
rc->left, rc->top, rc->right - rc->left, rc->bottom - rc->top,
mParentHwnd,
(HMENU) ID,
GetModuleHandle(NULL),
NULL);
if ( bNoTheme )
dcxSetWindowTheme( this->m_Hwnd , L" ", L" " );
this->setControlFont( (HFONT) GetStockObject( DEFAULT_GUI_FONT ), FALSE );
this->registreDefaultWindowProc( );
SetProp( this->m_Hwnd, "dcx_cthis", (HANDLE) this );
}
/*!
* \brief blah
*
* blah
*/
DcxCalendar::~DcxCalendar( ) {
this->unregistreDefaultWindowProc( );
}
/*!
* \brief blah
*
* blah
*/
void DcxCalendar::parseControlStyles(TString & styles, LONG * Styles, LONG * ExStyles, BOOL * bNoTheme) {
unsigned int i = 1, numtok = styles.numtok(" ");
while (i <= numtok) {
if (styles.gettok(i , " ") == "multi")
*Styles |= MCS_MULTISELECT;
else if (styles.gettok(i , " ") == "notoday")
*Styles |= MCS_NOTODAY;
else if (styles.gettok(i , " ") == "notodaycircle")
*Styles |= MCS_NOTODAYCIRCLE;
else if (styles.gettok(i , " ") == "weeknum")
*Styles |= MCS_WEEKNUMBERS;
else if (styles.gettok(i , " ") == "daystate")
*Styles |= MCS_DAYSTATE;
i++;
}
this->parseGeneralControlStyles(styles, Styles, ExStyles, bNoTheme);
}
/*!
* \brief $xdid Parsing Function
*
* \param input [NAME] [ID] [PROP] (OPTIONS)
* \param szReturnValue mIRC Data Container
*
* \return > void
*/
void DcxCalendar::parseInfoRequest( TString & input, char * szReturnValue ) {
// int numtok = input.numtok( " " );
// [NAME] [ID] [PROP]
if ( input.gettok( 3, " " ) == "text" ) {
}
else if ( this->parseGlobalInfoRequest( input, szReturnValue ) ) {
return;
}
szReturnValue[0] = 0;
}
/*!
* \brief blah
*
* blah
*/
void DcxCalendar::parseCommandRequest( TString & input ) {
XSwitchFlags flags;
ZeroMemory((void*) &flags, sizeof(XSwitchFlags));
this->parseSwitchFlags(input.gettok(3, " "), &flags);
//GetCurSel
//GetMaxSelCount
//GetRange (calendar range)
//GetSelRange (selection range)
//GetToday
//SetCurSel
//SetDayState
//SetRange
//SetSelRange
int numtok = input.numtok(" ");
// xdid -k [NAME] [ID] [SWITCH] [+FLAGS] [$RGB]
if (flags.switch_flags[10] && numtok > 4) {
TString flags = input.gettok(4, " ");
COLORREF col = (COLORREF) input.gettok(5, " ").to_int();
// Retrieve the background color displayed between months.
if (flags.find('b', 0))
MonthCal_SetColor(this->m_Hwnd, MCSC_BACKGROUND, col);
// Retrieve the background color displayed within the month.
if (flags.find('g', 0))
MonthCal_SetColor(this->m_Hwnd, MCSC_MONTHBK, col);
// Retrieve the color used to display text within a month.
if (flags.find('t', 0))
MonthCal_SetColor(this->m_Hwnd, MCSC_TEXT, col);
// Retrieve the background color displayed in the calendar's title.
if (flags.find('i', 0))
MonthCal_SetColor(this->m_Hwnd, MCSC_TITLEBK, col);
// Retrieve the color used to display text within the calendar's title.
if (flags.find('a', 0))
MonthCal_SetColor(this->m_Hwnd, MCSC_TITLETEXT, col);
// Retrieve the color used to display header day and trailing day text. Header and trailing days are the days from the previous and following months that appear on the current month calendar.
if (flags.find('r', 0))
MonthCal_SetColor(this->m_Hwnd, MCSC_TRAILINGTEXT, col);
}
//xdid -m [NAME] [ID] [SWITCH] [MAX]
else if (flags.switch_flags[12] && numtok > 3) {
int max = input.gettok(4, -1, " ").to_int();
MonthCal_SetMaxSelCount(this->m_Hwnd, max);
}
//xdid -t [NAME] [ID] [SWITCH] [TIMESTAMP]
else if (flags.switch_flags[19]) {
SYSTEMTIME sysTime;
long mircTime = (long) input.gettok(4, " ").to_num();
sysTime = MircTimeToSystemTime(mircTime);
MonthCal_SetToday(this->m_Hwnd, &sysTime);
}
else
this->parseGlobalCommandRequest( input, flags );
}
/*!
* \brief blah
*
* blah
*/
LRESULT DcxCalendar::ParentMessage(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL & bParsed) {
switch (uMsg) {
case WM_NOTIFY: {
LPNMHDR hdr = (LPNMHDR) lParam;
if (!hdr)
break;
switch(hdr->code) {
case MCN_GETDAYSTATE: {
LPNMDAYSTATE lpNMDayState = (LPNMDAYSTATE) lParam;
MONTHDAYSTATE mds[12];
int iMax = lpNMDayState->cDayState;
char eval[100];
for (int i = 0; i < iMax; i++) {
// daystate ctrlid startdate
this->callAliasEx(eval, "%s,%d,%d", "daystate", this->getUserID(),
SystemTimeToMircTime(lpNMDayState->stStart));
mds[i] = (MONTHDAYSTATE) 0;
TString strDays(eval);
strDays.trim();
for (int x = 1; x <= strDays.numtok(","); x++) {
TString tok = strDays.gettok(x, ",");
tok.trim();
BOLDDAY(mds[i], tok.to_int());
}
// increment the month so we get a proper offset
lpNMDayState->stStart.wMonth++;
if (lpNMDayState->stStart.wMonth > 12) {
lpNMDayState->stStart.wMonth = 1;
lpNMDayState->stStart.wYear++;
}
}
lpNMDayState->prgDayState = mds;
bParsed = TRUE;
return FALSE;
break;
}
case MCN_SELCHANGE: {
this->callAliasEx(NULL, "%s,%d", "selchange", this->getUserID());
break;
}
case MCN_SELECT: {
// specific code to handle multiselect dates
if (this->isStyle(MCS_MULTISELECT)) {
// get the selected range
SYSTEMTIME selrange[2];
MonthCal_GetSelRange(this->m_Hwnd, selrange);
// send event to callback
this->callAliasEx(NULL, "%s,%d,%d,%d", "select", this->getUserID(),
SystemTimeToMircTime(selrange[0]),
SystemTimeToMircTime(selrange[1]));
}
// code to handle single selected dates
else {
SYSTEMTIME st;
MonthCal_GetCurSel(this->m_Hwnd, &st);
// send event to callback
this->callAliasEx(NULL, "%s,%d,%d", "select", this->getUserID(), SystemTimeToMircTime(st));
}
break;
}
case NM_RELEASEDCAPTURE: {
if (this->m_pParentDialog->getEventMask() & DCX_EVENT_CLICK)
this->callAliasEx(NULL, "%s,%d", "sclick", this->getUserID());
break;
}
default: {
//mIRCError("ELSE");
break;
}
} // end switch
}
}
return 0L;
}
LRESULT DcxCalendar::PostMessage(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL & bParsed) {
switch (uMsg) {
case WM_HELP: {
if (this->m_pParentDialog->getEventMask() & DCX_EVENT_HELP)
this->callAliasEx( NULL, "%s,%d", "help", this->getUserID( ) );
break;
}
//case WM_GETDLGCODE:
//{
// return DLGC_WANTARROWS;
// break;
//}
case WM_MOUSEMOVE: {
this->m_pParentDialog->setMouseControl(this->getUserID());
break;
}
case WM_SETFOCUS: {
this->m_pParentDialog->setFocusControl(this->getUserID());
break;
}
case WM_SETCURSOR: {
if (LOWORD(lParam) == HTCLIENT && (HWND) wParam == this->m_Hwnd && this->m_hCursor != NULL) {
SetCursor( this->m_hCursor );
bParsed = TRUE;
return TRUE;
}
break;
}
case WM_DESTROY: {
delete this;
bParsed = TRUE;
break;
}
default:
break;
}
return 0L;
}
SYSTEMTIME DcxCalendar::MircTimeToSystemTime(long mircTime) {
char eval[100];
TString str;
SYSTEMTIME st;
ZeroMemory(&st, sizeof(SYSTEMTIME));
str.sprintf("$asctime(%ld, d m yyyy)", mircTime);
mIRCeval(str.to_chr(), eval);
delete eval;
str = TString(eval);
st.wDay = str.gettok(1, " ").to_int();
st.wMonth = str.gettok(2, " ").to_int();
st.wYear = str.gettok(3, " ").to_int();
return st;
}
long DcxCalendar::SystemTimeToMircTime(SYSTEMTIME st) {
char ret[100];
TString months[12] = {
"January",
"Feburary",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
};
wsprintf(ret, "$ctime(%d %s %d)",
st.wDay,
months[st.wMonth -1].to_chr(),
st.wYear);
mIRCeval(ret, ret);
return atoi(ret);
}
<commit_msg>[calendar] - fixed incorrect parsing for /xdid -m - added /xdid -r for restricting the range of the calendar - added /xdid -s for selecting dates for the calendar - fixed bug with MircTimeToSystemTime()<commit_after>/*!
http://www.codeguru.com/cpp/controls/controls/dateselectioncontrolsetc/article.php/c2229/
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/sysinfo/base/converting_a_time_t_value_to_a_file_time.asp
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/shellcc/platform/commctls/monthcal/structures/nmdaystate.asp
* \file dcxcalendar.cpp
* \brief blah
*
* blah
*
* \author David Legault ( clickhere at scriptsdb dot org )
* \version 1.0
*
* \b Revisions
*
* ScriptsDB.org - 2006
*/
#include "dcxcalendar.h"
#include "dcxdialog.h"
/*!
* \brief Constructor
*
* \param ID Control ID
* \param p_Dialog Parent DcxDialog Object
* \param rc Window Rectangle
* \param styles Window Style Tokenized List
*/
DcxCalendar::DcxCalendar( UINT ID, DcxDialog * p_Dialog, RECT * rc, TString & styles )
: DcxControl( ID, p_Dialog )
{
LONG Styles = 0, ExStyles = 0;
BOOL bNoTheme = FALSE;
this->parseControlStyles( styles, &Styles, &ExStyles, &bNoTheme );
this->m_Hwnd = CreateWindowEx(
ExStyles | WS_EX_CLIENTEDGE,
DCX_CALENDARCLASS,
NULL,
WS_CHILD | WS_VISIBLE | WS_CLIPCHILDREN | Styles,
rc->left, rc->top, rc->right - rc->left, rc->bottom - rc->top,
p_Dialog->getHwnd( ),
(HMENU) ID,
GetModuleHandle( NULL ),
NULL);
if ( bNoTheme )
dcxSetWindowTheme( this->m_Hwnd , L" ", L" " );
this->setControlFont( (HFONT) GetStockObject( DEFAULT_GUI_FONT ), FALSE );
this->registreDefaultWindowProc( );
SetProp( this->m_Hwnd, "dcx_cthis", (HANDLE) this );
}
/*!
* \brief Constructor
*
* \param ID Control ID
* \param p_Dialog Parent DcxDialog Object
* \param mParentHwnd Parent Window Handle
* \param rc Window Rectangle
* \param styles Window Style Tokenized List
*/
DcxCalendar::DcxCalendar( UINT ID, DcxDialog * p_Dialog, HWND mParentHwnd, RECT * rc, TString & styles )
: DcxControl( ID, p_Dialog )
{
LONG Styles = 0, ExStyles = 0;
BOOL bNoTheme = FALSE;
this->parseControlStyles( styles, &Styles, &ExStyles, &bNoTheme );
this->m_Hwnd = CreateWindowEx(
ExStyles | WS_EX_CLIENTEDGE,
DCX_CALENDARCLASS,
NULL,
WS_CHILD | WS_VISIBLE | WS_CLIPCHILDREN | Styles,
rc->left, rc->top, rc->right - rc->left, rc->bottom - rc->top,
mParentHwnd,
(HMENU) ID,
GetModuleHandle(NULL),
NULL);
if ( bNoTheme )
dcxSetWindowTheme( this->m_Hwnd , L" ", L" " );
this->setControlFont( (HFONT) GetStockObject( DEFAULT_GUI_FONT ), FALSE );
this->registreDefaultWindowProc( );
SetProp( this->m_Hwnd, "dcx_cthis", (HANDLE) this );
}
/*!
* \brief blah
*
* blah
*/
DcxCalendar::~DcxCalendar( ) {
this->unregistreDefaultWindowProc( );
}
/*!
* \brief blah
*
* blah
*/
void DcxCalendar::parseControlStyles(TString & styles, LONG * Styles, LONG * ExStyles, BOOL * bNoTheme) {
unsigned int i = 1, numtok = styles.numtok(" ");
while (i <= numtok) {
if (styles.gettok(i , " ") == "multi")
*Styles |= MCS_MULTISELECT;
else if (styles.gettok(i , " ") == "notoday")
*Styles |= MCS_NOTODAY;
else if (styles.gettok(i , " ") == "notodaycircle")
*Styles |= MCS_NOTODAYCIRCLE;
else if (styles.gettok(i , " ") == "weeknum")
*Styles |= MCS_WEEKNUMBERS;
else if (styles.gettok(i , " ") == "daystate")
*Styles |= MCS_DAYSTATE;
i++;
}
this->parseGeneralControlStyles(styles, Styles, ExStyles, bNoTheme);
}
/*!
* \brief $xdid Parsing Function
*
* \param input [NAME] [ID] [PROP] (OPTIONS)
* \param szReturnValue mIRC Data Container
*
* \return > void
*/
void DcxCalendar::parseInfoRequest(TString &input, char *szReturnValue) {
//GetCurSel
//GetMaxSelCount
//GetRange (calendar range)
//GetSelRange (selection range)
//GetToday
// int numtok = input.numtok( " " );
// [NAME] [ID] [PROP]
if (input.gettok(3, " ") == "text") {
}
else if (this->parseGlobalInfoRequest(input, szReturnValue)) {
return;
}
szReturnValue[0] = 0;
}
/*!
* \brief blah
*
* blah
*/
void DcxCalendar::parseCommandRequest(TString &input) {
XSwitchFlags flags;
ZeroMemory((void*) &flags, sizeof(XSwitchFlags));
this->parseSwitchFlags(input.gettok(3, " "), &flags);
//SetDayState
int numtok = input.numtok(" ");
// xdid -k [NAME] [ID] [SWITCH] [+FLAGS] [$RGB]
if (flags.switch_flags[10] && numtok > 4) {
TString flags = input.gettok(4, " ");
COLORREF col = (COLORREF) input.gettok(5, " ").to_int();
// Retrieve the background color displayed between months.
if (flags.find('b', 0))
MonthCal_SetColor(this->m_Hwnd, MCSC_BACKGROUND, col);
// Retrieve the background color displayed within the month.
if (flags.find('g', 0))
MonthCal_SetColor(this->m_Hwnd, MCSC_MONTHBK, col);
// Retrieve the color used to display text within a month.
if (flags.find('t', 0))
MonthCal_SetColor(this->m_Hwnd, MCSC_TEXT, col);
// Retrieve the background color displayed in the calendar's title.
if (flags.find('i', 0))
MonthCal_SetColor(this->m_Hwnd, MCSC_TITLEBK, col);
// Retrieve the color used to display text within the calendar's title.
if (flags.find('a', 0))
MonthCal_SetColor(this->m_Hwnd, MCSC_TITLETEXT, col);
// Retrieve the color used to display header day and trailing day text. Header and trailing days are the days from the previous and following months that appear on the current month calendar.
if (flags.find('r', 0))
MonthCal_SetColor(this->m_Hwnd, MCSC_TRAILINGTEXT, col);
}
//xdid -m [NAME] [ID] [SWITCH] [MAX]
else if (flags.switch_flags[12] && numtok > 3) {
int max = input.gettok(4, " ").to_int();
MonthCal_SetMaxSelCount(this->m_Hwnd, max);
}
//xdid -r [NAME] [ID] [SWITCH] [MIN] [MAX]
else if (flags.switch_flags[17] && numtok > 4) {
long min = (long) input.gettok(4, " ").to_num();
long max = (long) input.gettok(5, " ").to_num();
SYSTEMTIME range[2];
ZeroMemory(range, sizeof(SYSTEMTIME) *2);
range[0] = MircTimeToSystemTime(min);
range[1] = MircTimeToSystemTime(max);
MonthCal_SetRange(this->m_Hwnd, GDTR_MAX | GDTR_MIN, range);
}
//xdid -s [NAME] [ID] [SWITCH] [MIN] (MAX)
else if (flags.switch_flags[18] && numtok > 3) {
long min = (long) input.gettok(4, " ").to_num();
long max = 0;
SYSTEMTIME range[2];
ZeroMemory(range, sizeof(SYSTEMTIME) *2);
range[0] = MircTimeToSystemTime(min);
if (isStyle(MCS_MULTISELECT)) {
// if only one date specified, select the same date
if (numtok < 5)
range[1] = range[0];
else {
max = (long) input.gettok(5, " ").to_num();
range[1] = MircTimeToSystemTime(max);
}
MonthCal_SetSelRange(this->m_Hwnd, range);
}
else {
MonthCal_SetCurSel(this->m_Hwnd, &(range[0]));
}
}
//xdid -t [NAME] [ID] [SWITCH] [TIMESTAMP]
else if (flags.switch_flags[19]) {
SYSTEMTIME sysTime;
long mircTime = (long) input.gettok(4, " ").to_num();
sysTime = MircTimeToSystemTime(mircTime);
MonthCal_SetToday(this->m_Hwnd, &sysTime);
}
else
this->parseGlobalCommandRequest( input, flags );
}
/*!
* \brief blah
*
* blah
*/
LRESULT DcxCalendar::ParentMessage(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL & bParsed) {
switch (uMsg) {
case WM_NOTIFY: {
LPNMHDR hdr = (LPNMHDR) lParam;
if (!hdr)
break;
switch(hdr->code) {
case MCN_GETDAYSTATE: {
LPNMDAYSTATE lpNMDayState = (LPNMDAYSTATE) lParam;
MONTHDAYSTATE mds[12];
int iMax = lpNMDayState->cDayState;
char eval[100];
for (int i = 0; i < iMax; i++) {
// daystate ctrlid startdate
this->callAliasEx(eval, "%s,%d,%d", "daystate", this->getUserID(),
SystemTimeToMircTime(lpNMDayState->stStart));
mds[i] = (MONTHDAYSTATE) 0;
TString strDays(eval);
strDays.trim();
for (int x = 1; x <= strDays.numtok(","); x++) {
TString tok = strDays.gettok(x, ",");
tok.trim();
BOLDDAY(mds[i], tok.to_int());
}
// increment the month so we get a proper offset
lpNMDayState->stStart.wMonth++;
if (lpNMDayState->stStart.wMonth > 12) {
lpNMDayState->stStart.wMonth = 1;
lpNMDayState->stStart.wYear++;
}
}
lpNMDayState->prgDayState = mds;
bParsed = TRUE;
return FALSE;
break;
}
case MCN_SELCHANGE: {
this->callAliasEx(NULL, "%s,%d", "selchange", this->getUserID());
break;
}
case MCN_SELECT: {
// specific code to handle multiselect dates
if (this->isStyle(MCS_MULTISELECT)) {
// get the selected range
SYSTEMTIME selrange[2];
MonthCal_GetSelRange(this->m_Hwnd, selrange);
// send event to callback
this->callAliasEx(NULL, "%s,%d,%d,%d", "select", this->getUserID(),
SystemTimeToMircTime(selrange[0]),
SystemTimeToMircTime(selrange[1]));
}
// code to handle single selected dates
else {
SYSTEMTIME st;
MonthCal_GetCurSel(this->m_Hwnd, &st);
// send event to callback
this->callAliasEx(NULL, "%s,%d,%d", "select", this->getUserID(), SystemTimeToMircTime(st));
}
break;
}
case NM_RELEASEDCAPTURE: {
if (this->m_pParentDialog->getEventMask() & DCX_EVENT_CLICK)
this->callAliasEx(NULL, "%s,%d", "sclick", this->getUserID());
break;
}
default: {
//mIRCError("ELSE");
break;
}
} // end switch
}
}
return 0L;
}
LRESULT DcxCalendar::PostMessage(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL & bParsed) {
switch (uMsg) {
case WM_HELP: {
if (this->m_pParentDialog->getEventMask() & DCX_EVENT_HELP)
this->callAliasEx( NULL, "%s,%d", "help", this->getUserID( ) );
break;
}
//case WM_GETDLGCODE:
//{
// return DLGC_WANTARROWS;
// break;
//}
case WM_MOUSEMOVE: {
this->m_pParentDialog->setMouseControl(this->getUserID());
break;
}
case WM_SETFOCUS: {
this->m_pParentDialog->setFocusControl(this->getUserID());
break;
}
case WM_SETCURSOR: {
if (LOWORD(lParam) == HTCLIENT && (HWND) wParam == this->m_Hwnd && this->m_hCursor != NULL) {
SetCursor( this->m_hCursor );
bParsed = TRUE;
return TRUE;
}
break;
}
case WM_DESTROY: {
delete this;
bParsed = TRUE;
break;
}
default:
break;
}
return 0L;
}
SYSTEMTIME DcxCalendar::MircTimeToSystemTime(long mircTime) {
char eval[100];
TString str;
SYSTEMTIME st;
ZeroMemory(&st, sizeof(SYSTEMTIME));
str.sprintf("$asctime(%ld, d m yyyy)", mircTime);
mIRCeval(str.to_chr(), eval);
str = TString(eval);
st.wDay = str.gettok(1, " ").to_int();
st.wMonth = str.gettok(2, " ").to_int();
st.wYear = str.gettok(3, " ").to_int();
return st;
}
long DcxCalendar::SystemTimeToMircTime(SYSTEMTIME st) {
char ret[100];
TString months[12] = {
"January",
"Feburary",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
};
wsprintf(ret, "$ctime(%d %s %d)",
st.wDay,
months[st.wMonth -1].to_chr(),
st.wYear);
mIRCeval(ret, ret);
return atoi(ret);
}
<|endoftext|> |
<commit_before>/****************************************************************/
/* DO NOT MODIFY THIS HEADER */
/* MOOSE - Multiphysics Object Oriented Simulation Environment */
/* */
/* (c) 2010 Battelle Energy Alliance, LLC */
/* ALL RIGHTS RESERVED */
/* */
/* Prepared by Battelle Energy Alliance, LLC */
/* Under Contract No. DE-AC07-05ID14517 */
/* With the U. S. Department of Energy */
/* */
/* See COPYRIGHT for full restrictions */
/****************************************************************/
#include "DiracKernelInfo.h"
#include "MooseMesh.h"
// LibMesh
#include "libmesh/point_locator_base.h"
#include "libmesh/elem.h"
DiracKernelInfo::DiracKernelInfo() :
_point_locator(),
_point_equal_distance_sq(libMesh::TOLERANCE * libMesh::TOLERANCE)
{
}
DiracKernelInfo::~DiracKernelInfo()
{
}
void
DiracKernelInfo::addPoint(const Elem * elem, Point p)
{
_elements.insert(elem);
std::pair<std::vector<Point>, std::vector<unsigned int> > & multi_point_list = _points[elem];
const unsigned int npoint = multi_point_list.first.size();
mooseAssert(npoint == multi_point_list.second.size(), "Different sizes for location and multiplicity data");
for (unsigned int i = 0; i < npoint; ++i)
if (pointsFuzzyEqual(multi_point_list.first[i], p))
{
// a point at the same (within a tolerance) location as p exists, increase its multiplicity
multi_point_list.second[i]++;
return;
}
// no prior point found at this location, add it with a multiplicity of one
multi_point_list.first.push_back(p);
multi_point_list.second.push_back(1);
}
void
DiracKernelInfo::clearPoints()
{
_elements.clear();
_points.clear();
}
bool
DiracKernelInfo::hasPoint(const Elem * elem, Point p)
{
std::vector<Point> & point_list = _points[elem].first;
for (const auto & pt : point_list)
if (pointsFuzzyEqual(pt, p))
return true;
// If we haven't found it, we don't have it.
return false;
}
void
DiracKernelInfo::updatePointLocator(const MooseMesh& mesh)
{
// Note: we could update the PointLocator *every* time we call this
// function, but that may introduce an unacceptable overhead in
// problems which don't need a PointLocator at all. This issue will
// most likely become a moot point when we eventually add a shared
// "CachingPointLocator" to MOOSE.
// _point_locator = PointLocatorBase::build(TREE_LOCAL_ELEMENTS, mesh);
// Construct the PointLocator object if *any* processors have Dirac
// points. Note: building a PointLocator object is a parallel_only()
// function, so this is an all-or-nothing thing.
unsigned pl_needs_rebuild = _elements.size();
mesh.comm().max(pl_needs_rebuild);
if (pl_needs_rebuild)
{
// PointLocatorBase::build() is a parallel_only function! So we
// can't skip building it just becuase our local _elements is
// empty, it might be non-empty on some other processor!
_point_locator = PointLocatorBase::build(TREE_LOCAL_ELEMENTS, mesh);
// We may be querying for points which are not in the semilocal
// part of a distributed mesh.
_point_locator->enable_out_of_mesh_mode();
}
else
{
// There are no elements with Dirac points, but we have been
// requested to update the PointLocator so we have to assume the
// old one is invalid. Therefore we reset it to NULL... however
// adding this line causes the code to hang because it triggers
// the PointLocator to be rebuilt in a non-parallel-only segment
// of the code later... so it's commented out for now even though
// it's probably the right behavior.
// _point_locator.reset(NULL);
}
}
const Elem *
DiracKernelInfo::findPoint(Point p, const MooseMesh& mesh)
{
// If the PointLocator has never been created, do so now. NOTE - WE
// CAN'T DO THIS if findPoint() is only called on some processors,
// PointLocatorBase::build() is a 'parallel_only' method!
if (_point_locator.get() == NULL)
_point_locator = PointLocatorBase::build(TREE_LOCAL_ELEMENTS, mesh);
// Check that the PointLocator is ready to start locating points.
// So far I do not have any tests that trip this...
if (_point_locator->initialized() == false)
mooseError("Error, PointLocator is not initialized!");
// Note: The PointLocator object returns NULL when the Point is not
// found within the Mesh. This is not considered to be an error as
// far as the DiracKernels are concerned: sometimes the Mesh moves
// out from the Dirac point entirely and in that case the Point just
// gets "deactivated".
const Elem * elem = (*_point_locator)(p);
// The processors may not agree on which Elem the point is in. This
// can happen if a Dirac point lies on the processor boundary, and
// two or more neighboring processors think the point is in the Elem
// on *their* side.
dof_id_type elem_id = elem ? elem->id() : DofObject::invalid_id;
// We are going to let the element with the smallest ID "win", all other
// procs will return NULL.
dof_id_type min_elem_id = elem_id;
mesh.comm().min(min_elem_id);
return min_elem_id == elem_id ? elem : NULL;
}
bool
DiracKernelInfo::pointsFuzzyEqual(const Point & a, const Point & b)
{
const Real dist_sq = (a - b).norm_sq();
return dist_sq < _point_equal_distance_sq;
}
<commit_msg>One more enable_out_of_mesh_mode for Dirac points<commit_after>/****************************************************************/
/* DO NOT MODIFY THIS HEADER */
/* MOOSE - Multiphysics Object Oriented Simulation Environment */
/* */
/* (c) 2010 Battelle Energy Alliance, LLC */
/* ALL RIGHTS RESERVED */
/* */
/* Prepared by Battelle Energy Alliance, LLC */
/* Under Contract No. DE-AC07-05ID14517 */
/* With the U. S. Department of Energy */
/* */
/* See COPYRIGHT for full restrictions */
/****************************************************************/
#include "DiracKernelInfo.h"
#include "MooseMesh.h"
// LibMesh
#include "libmesh/point_locator_base.h"
#include "libmesh/elem.h"
DiracKernelInfo::DiracKernelInfo() :
_point_locator(),
_point_equal_distance_sq(libMesh::TOLERANCE * libMesh::TOLERANCE)
{
}
DiracKernelInfo::~DiracKernelInfo()
{
}
void
DiracKernelInfo::addPoint(const Elem * elem, Point p)
{
_elements.insert(elem);
std::pair<std::vector<Point>, std::vector<unsigned int> > & multi_point_list = _points[elem];
const unsigned int npoint = multi_point_list.first.size();
mooseAssert(npoint == multi_point_list.second.size(), "Different sizes for location and multiplicity data");
for (unsigned int i = 0; i < npoint; ++i)
if (pointsFuzzyEqual(multi_point_list.first[i], p))
{
// a point at the same (within a tolerance) location as p exists, increase its multiplicity
multi_point_list.second[i]++;
return;
}
// no prior point found at this location, add it with a multiplicity of one
multi_point_list.first.push_back(p);
multi_point_list.second.push_back(1);
}
void
DiracKernelInfo::clearPoints()
{
_elements.clear();
_points.clear();
}
bool
DiracKernelInfo::hasPoint(const Elem * elem, Point p)
{
std::vector<Point> & point_list = _points[elem].first;
for (const auto & pt : point_list)
if (pointsFuzzyEqual(pt, p))
return true;
// If we haven't found it, we don't have it.
return false;
}
void
DiracKernelInfo::updatePointLocator(const MooseMesh& mesh)
{
// Note: we could update the PointLocator *every* time we call this
// function, but that may introduce an unacceptable overhead in
// problems which don't need a PointLocator at all. This issue will
// most likely become a moot point when we eventually add a shared
// "CachingPointLocator" to MOOSE.
// _point_locator = PointLocatorBase::build(TREE_LOCAL_ELEMENTS, mesh);
// Construct the PointLocator object if *any* processors have Dirac
// points. Note: building a PointLocator object is a parallel_only()
// function, so this is an all-or-nothing thing.
unsigned pl_needs_rebuild = _elements.size();
mesh.comm().max(pl_needs_rebuild);
if (pl_needs_rebuild)
{
// PointLocatorBase::build() is a parallel_only function! So we
// can't skip building it just becuase our local _elements is
// empty, it might be non-empty on some other processor!
_point_locator = PointLocatorBase::build(TREE_LOCAL_ELEMENTS, mesh);
// We may be querying for points which are not in the semilocal
// part of a distributed mesh.
_point_locator->enable_out_of_mesh_mode();
}
else
{
// There are no elements with Dirac points, but we have been
// requested to update the PointLocator so we have to assume the
// old one is invalid. Therefore we reset it to NULL... however
// adding this line causes the code to hang because it triggers
// the PointLocator to be rebuilt in a non-parallel-only segment
// of the code later... so it's commented out for now even though
// it's probably the right behavior.
// _point_locator.reset(NULL);
}
}
const Elem *
DiracKernelInfo::findPoint(Point p, const MooseMesh& mesh)
{
// If the PointLocator has never been created, do so now. NOTE - WE
// CAN'T DO THIS if findPoint() is only called on some processors,
// PointLocatorBase::build() is a 'parallel_only' method!
if (_point_locator.get() == NULL)
{
_point_locator = PointLocatorBase::build(TREE_LOCAL_ELEMENTS, mesh);
_point_locator->enable_out_of_mesh_mode();
}
// Check that the PointLocator is ready to start locating points.
// So far I do not have any tests that trip this...
if (_point_locator->initialized() == false)
mooseError("Error, PointLocator is not initialized!");
// Note: The PointLocator object returns NULL when the Point is not
// found within the Mesh. This is not considered to be an error as
// far as the DiracKernels are concerned: sometimes the Mesh moves
// out from the Dirac point entirely and in that case the Point just
// gets "deactivated".
const Elem * elem = (*_point_locator)(p);
// The processors may not agree on which Elem the point is in. This
// can happen if a Dirac point lies on the processor boundary, and
// two or more neighboring processors think the point is in the Elem
// on *their* side.
dof_id_type elem_id = elem ? elem->id() : DofObject::invalid_id;
// We are going to let the element with the smallest ID "win", all other
// procs will return NULL.
dof_id_type min_elem_id = elem_id;
mesh.comm().min(min_elem_id);
return min_elem_id == elem_id ? elem : NULL;
}
bool
DiracKernelInfo::pointsFuzzyEqual(const Point & a, const Point & b)
{
const Real dist_sq = (a - b).norm_sq();
return dist_sq < _point_equal_distance_sq;
}
<|endoftext|> |
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2017 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#ifndef MAPNIK_QUAD_TREE_HPP
#define MAPNIK_QUAD_TREE_HPP
// mapnik
#include <mapnik/geometry/box2d.hpp>
#include <mapnik/util/noncopyable.hpp>
#include <mapnik/make_unique.hpp>
// stl
#include <memory>
#include <new>
#include <vector>
#include <type_traits>
#include <cstring>
namespace mapnik
{
template <typename T0, typename T1 = box2d<double>>
class quad_tree : util::noncopyable
{
using value_type = T0;
using bbox_type = T1;
struct node
{
using cont_type = std::vector<T0>;
using iterator = typename cont_type::iterator;
using const_iterator = typename cont_type::const_iterator;
bbox_type extent_;
cont_type cont_;
node * children_[4];
explicit node(bbox_type const& ext)
: extent_(ext)
{
std::fill(children_, children_ + 4, nullptr);
}
bbox_type const& extent() const
{
return extent_;
}
iterator begin()
{
return cont_.begin();
}
const_iterator begin() const
{
return cont_.begin();
}
iterator end()
{
return cont_.end();
}
const_iterator end() const
{
return cont_.end();
}
int num_subnodes() const
{
int _count = 0;
for (int i = 0; i < 4; ++i)
{
if (children_[i]) ++_count;
}
return _count;
}
~node () {}
};
using nodes_type = std::vector<std::unique_ptr<node> >;
using cont_type = typename node::cont_type;
using node_data_iterator = typename cont_type::iterator;
public:
using iterator = typename nodes_type::iterator;
using const_iterator = typename nodes_type::const_iterator;
using result_type = typename std::vector<std::reference_wrapper<value_type> >;
using query_iterator = typename result_type::iterator;
explicit quad_tree(bbox_type const& ext,
unsigned int max_depth = 8,
double ratio = 0.55)
: max_depth_(max_depth),
ratio_(ratio),
query_result_(),
nodes_()
{
nodes_.push_back(std::make_unique<node>(ext));
root_ = nodes_[0].get();
}
void insert(value_type data, bbox_type const& box)
{
unsigned int depth = 0;
do_insert_data(data, box, root_, depth);
}
query_iterator query_in_box(bbox_type const& box)
{
query_result_.clear();
query_node(box, query_result_, root_);
return query_result_.begin();
}
query_iterator query_end()
{
return query_result_.end();
}
const_iterator begin() const
{
return nodes_.begin();
}
const_iterator end() const
{
return nodes_.end();
}
void clear ()
{
bbox_type ext = root_->extent_;
nodes_.clear();
nodes_.push_back(std::make_unique<node>(ext));
root_ = nodes_[0].get();
}
bbox_type const& extent() const
{
return root_->extent_;
}
int count() const
{
return count_nodes(root_);
}
int count_items() const
{
int _count = 0;
count_items(root_, _count);
return _count;
}
void trim()
{
trim_tree(root_);
}
template <typename OutputStream>
void write(OutputStream & out)
{
static_assert(std::is_standard_layout<value_type>::value,
"Values stored in quad-tree must be standard layout types to allow serialisation");
char header[16];
std::memset(header,0,16);
std::strcpy(header,"mapnik-index");
out.write(header,16);
write_node(out,root_);
}
private:
void query_node(bbox_type const& box, result_type & result, node * node_) const
{
if (node_)
{
bbox_type const& node_extent = node_->extent();
if (box.intersects(node_extent))
{
for (auto & n : *node_)
{
result.push_back(std::ref(n));
}
for (int k = 0; k < 4; ++k)
{
query_node(box,result,node_->children_[k]);
}
}
}
}
void do_insert_data(value_type data, bbox_type const& box, node * n, unsigned int& depth)
{
if (++depth >= max_depth_)
{
n->cont_.push_back(data);
}
else
{
bbox_type const& node_extent = n->extent();
bbox_type ext[4];
split_box(node_extent,ext);
for (int i = 0; i < 4; ++i)
{
if (ext[i].contains(box))
{
if (!n->children_[i])
{
nodes_.push_back(std::make_unique<node>(ext[i]));
n->children_[i]=nodes_.back().get();
}
do_insert_data(data,box,n->children_[i],depth);
return;
}
}
n->cont_.push_back(data);
}
}
void split_box(bbox_type const& node_extent,bbox_type * ext)
{
typename bbox_type::value_type width = node_extent.width();
typename bbox_type::value_type height = node_extent.height();
typename bbox_type::value_type lox = node_extent.minx();
typename bbox_type::value_type loy = node_extent.miny();
typename bbox_type::value_type hix = node_extent.maxx();
typename bbox_type::value_type hiy = node_extent.maxy();
ext[0] = bbox_type(lox, loy, lox + width * ratio_, loy + height * ratio_);
ext[1] = bbox_type(hix - width * ratio_, loy, hix, loy + height * ratio_);
ext[2] = bbox_type(lox, hiy - height * ratio_, lox + width * ratio_, hiy);
ext[3] = bbox_type(hix - width * ratio_, hiy - height * ratio_, hix, hiy);
}
void trim_tree(node *& n)
{
if (n)
{
for (int i = 0; i < 4; ++i)
{
trim_tree(n->children_[i]);
}
if (n->num_subnodes() == 1 && n->cont_.size() == 0)
{
for (int i = 0; i < 4; ++i)
{
if (n->children_[i])
{
n = n->children_[i];
break;
}
}
}
}
}
int count_nodes(node const* n) const
{
if (!n) return 0;
else
{
int _count = 1;
for (int i = 0; i < 4; ++i)
{
_count += count_nodes(n->children_[i]);
}
return _count;
}
}
void count_items(node const* n, int& _count) const
{
if (n)
{
_count += n->cont_.size();
for (int i = 0; i < 4; ++i)
{
count_items(n->children_[i],_count);
}
}
}
int subnode_offset(node const* n) const
{
int offset = 0;
for (int i = 0; i < 4; i++)
{
if (n->children_[i])
{
offset +=sizeof(bbox_type) + (n->children_[i]->cont_.size() * sizeof(value_type)) + 3 * sizeof(int);
offset +=subnode_offset(n->children_[i]);
}
}
return offset;
}
template <typename OutputStream>
void write_node(OutputStream & out, node const* n) const
{
if (n)
{
int offset = subnode_offset(n);
int shape_count = n->cont_.size();
int recsize = sizeof(bbox_type) + 3 * sizeof(int) + shape_count * sizeof(value_type);
std::unique_ptr<char[]> node_record(new char[recsize]);
std::memset(node_record.get(), 0, recsize);
std::memcpy(node_record.get(), &offset, 4);
std::memcpy(node_record.get() + 4, &n->extent_, sizeof(bbox_type));
std::memcpy(node_record.get() + 4 + sizeof(bbox_type), &shape_count, 4);
for (int i=0; i < shape_count; ++i)
{
memcpy(node_record.get() + 8 + sizeof(bbox_type) + i * sizeof(value_type), &(n->cont_[i]), sizeof(value_type));
}
int num_subnodes=0;
for (int i = 0; i < 4; ++i)
{
if (n->children_[i])
{
++num_subnodes;
}
}
std::memcpy(node_record.get() + 8 + sizeof(bbox_type) + shape_count * sizeof(value_type), &num_subnodes, 4);
out.write(node_record.get(),recsize);
for (int i = 0; i < 4; ++i)
{
write_node(out, n->children_[i]);
}
}
}
const unsigned int max_depth_;
const double ratio_;
result_type query_result_;
nodes_type nodes_;
node * root_;
};
}
#endif // MAPNIK_QUAD_TREE_HPP
<commit_msg>simplify impl + const correctness + minor cleanup<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2017 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#ifndef MAPNIK_QUAD_TREE_HPP
#define MAPNIK_QUAD_TREE_HPP
// mapnik
#include <mapnik/geometry/box2d.hpp>
#include <mapnik/util/noncopyable.hpp>
#include <mapnik/make_unique.hpp>
// stl
#include <memory>
#include <new>
#include <vector>
#include <type_traits>
#include <cstring>
namespace mapnik
{
template <typename T0, typename T1 = box2d<double>>
class quad_tree : util::noncopyable
{
using value_type = T0;
using bbox_type = T1;
struct node
{
using cont_type = std::vector<T0>;
using iterator = typename cont_type::iterator;
using const_iterator = typename cont_type::const_iterator;
bbox_type extent_;
cont_type cont_;
node * children_[4];
explicit node(bbox_type const& ext)
: extent_(ext)
{
std::fill(children_, children_ + 4, nullptr);
}
bbox_type const& extent() const
{
return extent_;
}
iterator begin()
{
return cont_.begin();
}
const_iterator begin() const
{
return cont_.begin();
}
iterator end()
{
return cont_.end();
}
const_iterator end() const
{
return cont_.end();
}
int num_subnodes() const
{
int _count = 0;
for (int i = 0; i < 4; ++i)
{
if (children_[i]) ++_count;
}
return _count;
}
~node () {}
};
using nodes_type = std::vector<std::unique_ptr<node> >;
using cont_type = typename node::cont_type;
using node_data_iterator = typename cont_type::iterator;
public:
using iterator = typename nodes_type::iterator;
using const_iterator = typename nodes_type::const_iterator;
using result_type = typename std::vector<std::reference_wrapper<value_type> >;
using query_iterator = typename result_type::iterator;
explicit quad_tree(bbox_type const& ext,
unsigned int max_depth = 8,
double ratio = 0.55)
: max_depth_(max_depth),
ratio_(ratio),
query_result_(),
nodes_()
{
nodes_.push_back(std::make_unique<node>(ext));
root_ = nodes_[0].get();
}
void insert(value_type const& data, bbox_type const& box)
{
unsigned int depth = 0;
do_insert_data(data, box, root_, depth);
}
query_iterator query_in_box(bbox_type const& box)
{
query_result_.clear();
query_node(box, query_result_, root_);
return query_result_.begin();
}
query_iterator query_end()
{
return query_result_.end();
}
const_iterator begin() const
{
return nodes_.begin();
}
const_iterator end() const
{
return nodes_.end();
}
void clear ()
{
bbox_type ext = root_->extent_;
nodes_.clear();
nodes_.push_back(std::make_unique<node>(ext));
root_ = nodes_[0].get();
}
bbox_type const& extent() const
{
return root_->extent_;
}
int count() const
{
return count_nodes(root_);
}
int count_items() const
{
int _count = 0;
count_items(root_, _count);
return _count;
}
void trim()
{
trim_tree(root_);
}
template <typename OutputStream>
void write(OutputStream & out)
{
static_assert(std::is_standard_layout<value_type>::value,
"Values stored in quad-tree must be standard layout types to allow serialisation");
char header[16];
std::memset(header,0,16);
std::strcpy(header,"mapnik-index");
out.write(header,16);
write_node(out,root_);
}
private:
void query_node(bbox_type const& box, result_type & result, node * node_) const
{
if (node_)
{
bbox_type const& node_extent = node_->extent();
if (box.intersects(node_extent))
{
for (auto & n : *node_)
{
result.push_back(std::ref(n));
}
for (int k = 0; k < 4; ++k)
{
query_node(box,result,node_->children_[k]);
}
}
}
}
void do_insert_data(value_type const& data, bbox_type const& box, node * n, unsigned int& depth)
{
if (++depth < max_depth_)
{
bbox_type const& node_extent = n->extent();
bbox_type ext[4];
split_box(node_extent,ext);
for (int i = 0; i < 4; ++i)
{
if (ext[i].contains(box))
{
if (!n->children_[i])
{
nodes_.push_back(std::make_unique<node>(ext[i]));
n->children_[i] = nodes_.back().get();
}
do_insert_data(data, box, n->children_[i], depth);
return;
}
}
}
n->cont_.push_back(data);
}
void split_box(bbox_type const& node_extent, bbox_type * ext)
{
typename bbox_type::value_type width = node_extent.width();
typename bbox_type::value_type height = node_extent.height();
typename bbox_type::value_type lox = node_extent.minx();
typename bbox_type::value_type loy = node_extent.miny();
typename bbox_type::value_type hix = node_extent.maxx();
typename bbox_type::value_type hiy = node_extent.maxy();
ext[0] = bbox_type(lox, loy, lox + width * ratio_, loy + height * ratio_);
ext[1] = bbox_type(hix - width * ratio_, loy, hix, loy + height * ratio_);
ext[2] = bbox_type(lox, hiy - height * ratio_, lox + width * ratio_, hiy);
ext[3] = bbox_type(hix - width * ratio_, hiy - height * ratio_, hix, hiy);
}
void trim_tree(node *& n)
{
if (n)
{
for (int i = 0; i < 4; ++i)
{
trim_tree(n->children_[i]);
}
if (n->num_subnodes() == 1 && n->cont_.size() == 0)
{
for (int i = 0; i < 4; ++i)
{
if (n->children_[i])
{
n = n->children_[i];
break;
}
}
}
}
}
int count_nodes(node const* n) const
{
if (!n) return 0;
else
{
int _count = 1;
for (int i = 0; i < 4; ++i)
{
_count += count_nodes(n->children_[i]);
}
return _count;
}
}
void count_items(node const* n, int& _count) const
{
if (n)
{
_count += n->cont_.size();
for (int i = 0; i < 4; ++i)
{
count_items(n->children_[i],_count);
}
}
}
int subnode_offset(node const* n) const
{
int offset = 0;
for (int i = 0; i < 4; i++)
{
if (n->children_[i])
{
offset +=sizeof(bbox_type) + (n->children_[i]->cont_.size() * sizeof(value_type)) + 3 * sizeof(int);
offset +=subnode_offset(n->children_[i]);
}
}
return offset;
}
template <typename OutputStream>
void write_node(OutputStream & out, node const* n) const
{
if (n)
{
int offset = subnode_offset(n);
int shape_count = n->cont_.size();
int recsize = sizeof(bbox_type) + 3 * sizeof(int) + shape_count * sizeof(value_type);
std::unique_ptr<char[]> node_record(new char[recsize]);
std::memset(node_record.get(), 0, recsize);
std::memcpy(node_record.get(), &offset, 4);
std::memcpy(node_record.get() + 4, &n->extent_, sizeof(bbox_type));
std::memcpy(node_record.get() + 4 + sizeof(bbox_type), &shape_count, 4);
for (int i=0; i < shape_count; ++i)
{
memcpy(node_record.get() + 8 + sizeof(bbox_type) + i * sizeof(value_type), &(n->cont_[i]), sizeof(value_type));
}
int num_subnodes=0;
for (int i = 0; i < 4; ++i)
{
if (n->children_[i])
{
++num_subnodes;
}
}
std::memcpy(node_record.get() + 8 + sizeof(bbox_type) + shape_count * sizeof(value_type), &num_subnodes, 4);
out.write(node_record.get(),recsize);
for (int i = 0; i < 4; ++i)
{
write_node(out, n->children_[i]);
}
}
}
const unsigned int max_depth_;
const double ratio_;
result_type query_result_;
nodes_type nodes_;
node * root_;
};
}
#endif // MAPNIK_QUAD_TREE_HPP
<|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 "net/socket/ssl_client_socket.h"
#include <errno.h>
#include <string.h>
#include <openssl/bio.h>
#include <openssl/bn.h>
#include <openssl/evp.h>
#include <openssl/pem.h>
#include <openssl/rsa.h>
#include "base/file_util.h"
#include "base/files/file_path.h"
#include "base/memory/ref_counted.h"
#include "base/memory/scoped_handle.h"
#include "base/message_loop/message_loop_proxy.h"
#include "base/values.h"
#include "crypto/openssl_util.h"
#include "net/base/address_list.h"
#include "net/base/io_buffer.h"
#include "net/base/net_errors.h"
#include "net/base/net_log.h"
#include "net/base/net_log_unittest.h"
#include "net/base/test_completion_callback.h"
#include "net/base/test_data_directory.h"
#include "net/cert/mock_cert_verifier.h"
#include "net/cert/test_root_certs.h"
#include "net/dns/host_resolver.h"
#include "net/http/transport_security_state.h"
#include "net/socket/client_socket_factory.h"
#include "net/socket/client_socket_handle.h"
#include "net/socket/socket_test_util.h"
#include "net/socket/tcp_client_socket.h"
#include "net/ssl/default_server_bound_cert_store.h"
#include "net/ssl/openssl_client_key_store.h"
#include "net/ssl/server_bound_cert_service.h"
#include "net/ssl/ssl_cert_request_info.h"
#include "net/ssl/ssl_config_service.h"
#include "net/test/cert_test_util.h"
#include "net/test/spawned_test_server/spawned_test_server.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "testing/platform_test.h"
namespace net {
namespace {
typedef OpenSSLClientKeyStore::ScopedEVP_PKEY ScopedEVP_PKEY;
// BIO_free is a macro, it can't be used as a template parameter.
void BIO_free_func(BIO* bio) {
BIO_free(bio);
}
typedef crypto::ScopedOpenSSL<BIO, BIO_free_func> ScopedBIO;
typedef crypto::ScopedOpenSSL<RSA, RSA_free> ScopedRSA;
typedef crypto::ScopedOpenSSL<BIGNUM, BN_free> ScopedBIGNUM;
const SSLConfig kDefaultSSLConfig;
// A ServerBoundCertStore that always returns an error when asked for a
// certificate.
class FailingServerBoundCertStore : public ServerBoundCertStore {
virtual int GetServerBoundCert(const std::string& server_identifier,
base::Time* expiration_time,
std::string* private_key_result,
std::string* cert_result,
const GetCertCallback& callback) OVERRIDE {
return ERR_UNEXPECTED;
}
virtual void SetServerBoundCert(const std::string& server_identifier,
base::Time creation_time,
base::Time expiration_time,
const std::string& private_key,
const std::string& cert) OVERRIDE {}
virtual void DeleteServerBoundCert(const std::string& server_identifier,
const base::Closure& completion_callback)
OVERRIDE {}
virtual void DeleteAllCreatedBetween(base::Time delete_begin,
base::Time delete_end,
const base::Closure& completion_callback)
OVERRIDE {}
virtual void DeleteAll(const base::Closure& completion_callback) OVERRIDE {}
virtual void GetAllServerBoundCerts(const GetCertListCallback& callback)
OVERRIDE {}
virtual int GetCertCount() OVERRIDE { return 0; }
virtual void SetForceKeepSessionState() OVERRIDE {}
};
// Loads a PEM-encoded private key file into a scoped EVP_PKEY object.
// |filepath| is the private key file path.
// |*pkey| is reset to the new EVP_PKEY on success, untouched otherwise.
// Returns true on success, false on failure.
bool LoadPrivateKeyOpenSSL(
const base::FilePath& filepath,
OpenSSLClientKeyStore::ScopedEVP_PKEY* pkey) {
std::string data;
if (!base::ReadFileToString(filepath, &data)) {
LOG(ERROR) << "Could not read private key file: "
<< filepath.value() << ": " << strerror(errno);
return false;
}
ScopedBIO bio(
BIO_new_mem_buf(
const_cast<char*>(reinterpret_cast<const char*>(data.data())),
static_cast<int>(data.size())));
if (!bio.get()) {
LOG(ERROR) << "Could not allocate BIO for buffer?";
return false;
}
EVP_PKEY* result = PEM_read_bio_PrivateKey(bio.get(), NULL, NULL, NULL);
if (result == NULL) {
LOG(ERROR) << "Could not decode private key file: "
<< filepath.value();
return false;
}
pkey->reset(result);
return true;
}
class SSLClientSocketOpenSSLClientAuthTest : public PlatformTest {
public:
SSLClientSocketOpenSSLClientAuthTest()
: socket_factory_(net::ClientSocketFactory::GetDefaultFactory()),
cert_verifier_(new net::MockCertVerifier),
transport_security_state_(new net::TransportSecurityState) {
cert_verifier_->set_default_result(net::OK);
context_.cert_verifier = cert_verifier_.get();
context_.transport_security_state = transport_security_state_.get();
key_store_ = net::OpenSSLClientKeyStore::GetInstance();
}
virtual ~SSLClientSocketOpenSSLClientAuthTest() {
key_store_->Flush();
}
protected:
void EnabledChannelID() {
cert_service_.reset(
new ServerBoundCertService(new DefaultServerBoundCertStore(NULL),
base::MessageLoopProxy::current()));
context_.server_bound_cert_service = cert_service_.get();
}
void EnabledFailingChannelID() {
cert_service_.reset(
new ServerBoundCertService(new FailingServerBoundCertStore(),
base::MessageLoopProxy::current()));
context_.server_bound_cert_service = cert_service_.get();
}
scoped_ptr<SSLClientSocket> CreateSSLClientSocket(
scoped_ptr<StreamSocket> transport_socket,
const HostPortPair& host_and_port,
const SSLConfig& ssl_config) {
scoped_ptr<ClientSocketHandle> connection(new ClientSocketHandle);
connection->SetSocket(transport_socket.Pass());
return socket_factory_->CreateSSLClientSocket(connection.Pass(),
host_and_port,
ssl_config,
context_);
}
// Connect to a HTTPS test server.
bool ConnectToTestServer(SpawnedTestServer::SSLOptions& ssl_options) {
test_server_.reset(new SpawnedTestServer(SpawnedTestServer::TYPE_HTTPS,
ssl_options,
base::FilePath()));
if (!test_server_->Start()) {
LOG(ERROR) << "Could not start SpawnedTestServer";
return false;
}
if (!test_server_->GetAddressList(&addr_)) {
LOG(ERROR) << "Could not get SpawnedTestServer address list";
return false;
}
transport_.reset(new TCPClientSocket(
addr_, &log_, NetLog::Source()));
int rv = callback_.GetResult(
transport_->Connect(callback_.callback()));
if (rv != OK) {
LOG(ERROR) << "Could not connect to SpawnedTestServer";
return false;
}
return true;
}
// Record a certificate's private key to ensure it can be used
// by the OpenSSL-based SSLClientSocket implementation.
// |ssl_config| provides a client certificate.
// |private_key| must be an EVP_PKEY for the corresponding private key.
// Returns true on success, false on failure.
bool RecordPrivateKey(SSLConfig& ssl_config,
EVP_PKEY* private_key) {
return key_store_->RecordClientCertPrivateKey(
ssl_config.client_cert.get(), private_key);
}
// Create an SSLClientSocket object and use it to connect to a test
// server, then wait for connection results. This must be called after
// a succesful ConnectToTestServer() call.
// |ssl_config| the SSL configuration to use.
// |result| will retrieve the ::Connect() result value.
// Returns true on succes, false otherwise. Success means that the socket
// could be created and its Connect() was called, not that the connection
// itself was a success.
bool CreateAndConnectSSLClientSocket(SSLConfig& ssl_config,
int* result) {
sock_ = CreateSSLClientSocket(transport_.Pass(),
test_server_->host_port_pair(),
ssl_config);
if (sock_->IsConnected()) {
LOG(ERROR) << "SSL Socket prematurely connected";
return false;
}
*result = callback_.GetResult(sock_->Connect(callback_.callback()));
return true;
}
// Check that the client certificate was sent.
// Returns true on success.
bool CheckSSLClientSocketSentCert() {
SSLInfo ssl_info;
sock_->GetSSLInfo(&ssl_info);
return ssl_info.client_cert_sent;
}
scoped_ptr<ServerBoundCertService> cert_service_;
ClientSocketFactory* socket_factory_;
scoped_ptr<MockCertVerifier> cert_verifier_;
scoped_ptr<TransportSecurityState> transport_security_state_;
SSLClientSocketContext context_;
OpenSSLClientKeyStore* key_store_;
scoped_ptr<SpawnedTestServer> test_server_;
AddressList addr_;
TestCompletionCallback callback_;
CapturingNetLog log_;
scoped_ptr<StreamSocket> transport_;
scoped_ptr<SSLClientSocket> sock_;
};
// Connect to a server requesting client authentication, do not send
// any client certificates. It should refuse the connection.
TEST_F(SSLClientSocketOpenSSLClientAuthTest, NoCert) {
SpawnedTestServer::SSLOptions ssl_options;
ssl_options.request_client_certificate = true;
ASSERT_TRUE(ConnectToTestServer(ssl_options));
base::FilePath certs_dir = GetTestCertsDirectory();
SSLConfig ssl_config = kDefaultSSLConfig;
int rv;
ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config, &rv));
EXPECT_EQ(ERR_SSL_CLIENT_AUTH_CERT_NEEDED, rv);
EXPECT_FALSE(sock_->IsConnected());
}
// Connect to a server requesting client authentication, and send it
// an empty certificate. It should refuse the connection.
TEST_F(SSLClientSocketOpenSSLClientAuthTest, SendEmptyCert) {
SpawnedTestServer::SSLOptions ssl_options;
ssl_options.request_client_certificate = true;
ssl_options.client_authorities.push_back(
GetTestClientCertsDirectory().AppendASCII("client_1_ca.pem"));
ASSERT_TRUE(ConnectToTestServer(ssl_options));
base::FilePath certs_dir = GetTestCertsDirectory();
SSLConfig ssl_config = kDefaultSSLConfig;
ssl_config.send_client_cert = true;
ssl_config.client_cert = NULL;
int rv;
ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config, &rv));
EXPECT_EQ(OK, rv);
EXPECT_TRUE(sock_->IsConnected());
}
// Connect to a server requesting client authentication. Send it a
// matching certificate. It should allow the connection.
TEST_F(SSLClientSocketOpenSSLClientAuthTest, SendGoodCert) {
SpawnedTestServer::SSLOptions ssl_options;
ssl_options.request_client_certificate = true;
ssl_options.client_authorities.push_back(
GetTestClientCertsDirectory().AppendASCII("client_1_ca.pem"));
ASSERT_TRUE(ConnectToTestServer(ssl_options));
base::FilePath certs_dir = GetTestCertsDirectory();
SSLConfig ssl_config = kDefaultSSLConfig;
ssl_config.send_client_cert = true;
ssl_config.client_cert = ImportCertFromFile(certs_dir, "client_1.pem");
// This is required to ensure that signing works with the client
// certificate's private key.
OpenSSLClientKeyStore::ScopedEVP_PKEY client_private_key;
ASSERT_TRUE(LoadPrivateKeyOpenSSL(certs_dir.AppendASCII("client_1.key"),
&client_private_key));
EXPECT_TRUE(RecordPrivateKey(ssl_config, client_private_key.get()));
int rv;
ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config, &rv));
EXPECT_EQ(OK, rv);
EXPECT_TRUE(sock_->IsConnected());
EXPECT_TRUE(CheckSSLClientSocketSentCert());
sock_->Disconnect();
EXPECT_FALSE(sock_->IsConnected());
}
// Connect to a server using channel id. It should allow the connection.
TEST_F(SSLClientSocketOpenSSLClientAuthTest, SendChannelID) {
SpawnedTestServer::SSLOptions ssl_options;
ASSERT_TRUE(ConnectToTestServer(ssl_options));
EnabledChannelID();
SSLConfig ssl_config = kDefaultSSLConfig;
ssl_config.channel_id_enabled = true;
int rv;
ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config, &rv));
EXPECT_EQ(OK, rv);
EXPECT_TRUE(sock_->IsConnected());
EXPECT_TRUE(sock_->WasChannelIDSent());
sock_->Disconnect();
EXPECT_FALSE(sock_->IsConnected());
}
// Connect to a server using channel id but without sending a key. It should
// fail.
TEST_F(SSLClientSocketOpenSSLClientAuthTest, FailingChannelID) {
SpawnedTestServer::SSLOptions ssl_options;
ASSERT_TRUE(ConnectToTestServer(ssl_options));
EnabledFailingChannelID();
SSLConfig ssl_config = kDefaultSSLConfig;
ssl_config.channel_id_enabled = true;
int rv;
ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config, &rv));
EXPECT_EQ(ERR_UNEXPECTED, rv);
EXPECT_FALSE(sock_->IsConnected());
}
} // namespace
} // namespace net
<commit_msg>Fix link error when compiling with OpenSSL while using OS certs.<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 "net/socket/ssl_client_socket.h"
#include <errno.h>
#include <string.h>
#include <openssl/bio.h>
#include <openssl/bn.h>
#include <openssl/evp.h>
#include <openssl/pem.h>
#include <openssl/rsa.h>
#include "base/file_util.h"
#include "base/files/file_path.h"
#include "base/memory/ref_counted.h"
#include "base/memory/scoped_handle.h"
#include "base/message_loop/message_loop_proxy.h"
#include "base/values.h"
#include "crypto/openssl_util.h"
#include "net/base/address_list.h"
#include "net/base/io_buffer.h"
#include "net/base/net_errors.h"
#include "net/base/net_log.h"
#include "net/base/net_log_unittest.h"
#include "net/base/test_completion_callback.h"
#include "net/base/test_data_directory.h"
#include "net/cert/mock_cert_verifier.h"
#include "net/cert/test_root_certs.h"
#include "net/dns/host_resolver.h"
#include "net/http/transport_security_state.h"
#include "net/socket/client_socket_factory.h"
#include "net/socket/client_socket_handle.h"
#include "net/socket/socket_test_util.h"
#include "net/socket/tcp_client_socket.h"
#include "net/ssl/default_server_bound_cert_store.h"
#include "net/ssl/openssl_client_key_store.h"
#include "net/ssl/server_bound_cert_service.h"
#include "net/ssl/ssl_cert_request_info.h"
#include "net/ssl/ssl_config_service.h"
#include "net/test/cert_test_util.h"
#include "net/test/spawned_test_server/spawned_test_server.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "testing/platform_test.h"
namespace net {
namespace {
// These client auth tests are currently dependent on OpenSSL's struct X509.
#if defined(USE_OPENSSL_CERTS)
typedef OpenSSLClientKeyStore::ScopedEVP_PKEY ScopedEVP_PKEY;
// BIO_free is a macro, it can't be used as a template parameter.
void BIO_free_func(BIO* bio) {
BIO_free(bio);
}
typedef crypto::ScopedOpenSSL<BIO, BIO_free_func> ScopedBIO;
typedef crypto::ScopedOpenSSL<RSA, RSA_free> ScopedRSA;
typedef crypto::ScopedOpenSSL<BIGNUM, BN_free> ScopedBIGNUM;
const SSLConfig kDefaultSSLConfig;
// A ServerBoundCertStore that always returns an error when asked for a
// certificate.
class FailingServerBoundCertStore : public ServerBoundCertStore {
virtual int GetServerBoundCert(const std::string& server_identifier,
base::Time* expiration_time,
std::string* private_key_result,
std::string* cert_result,
const GetCertCallback& callback) OVERRIDE {
return ERR_UNEXPECTED;
}
virtual void SetServerBoundCert(const std::string& server_identifier,
base::Time creation_time,
base::Time expiration_time,
const std::string& private_key,
const std::string& cert) OVERRIDE {}
virtual void DeleteServerBoundCert(const std::string& server_identifier,
const base::Closure& completion_callback)
OVERRIDE {}
virtual void DeleteAllCreatedBetween(base::Time delete_begin,
base::Time delete_end,
const base::Closure& completion_callback)
OVERRIDE {}
virtual void DeleteAll(const base::Closure& completion_callback) OVERRIDE {}
virtual void GetAllServerBoundCerts(const GetCertListCallback& callback)
OVERRIDE {}
virtual int GetCertCount() OVERRIDE { return 0; }
virtual void SetForceKeepSessionState() OVERRIDE {}
};
// Loads a PEM-encoded private key file into a scoped EVP_PKEY object.
// |filepath| is the private key file path.
// |*pkey| is reset to the new EVP_PKEY on success, untouched otherwise.
// Returns true on success, false on failure.
bool LoadPrivateKeyOpenSSL(
const base::FilePath& filepath,
OpenSSLClientKeyStore::ScopedEVP_PKEY* pkey) {
std::string data;
if (!base::ReadFileToString(filepath, &data)) {
LOG(ERROR) << "Could not read private key file: "
<< filepath.value() << ": " << strerror(errno);
return false;
}
ScopedBIO bio(
BIO_new_mem_buf(
const_cast<char*>(reinterpret_cast<const char*>(data.data())),
static_cast<int>(data.size())));
if (!bio.get()) {
LOG(ERROR) << "Could not allocate BIO for buffer?";
return false;
}
EVP_PKEY* result = PEM_read_bio_PrivateKey(bio.get(), NULL, NULL, NULL);
if (result == NULL) {
LOG(ERROR) << "Could not decode private key file: "
<< filepath.value();
return false;
}
pkey->reset(result);
return true;
}
class SSLClientSocketOpenSSLClientAuthTest : public PlatformTest {
public:
SSLClientSocketOpenSSLClientAuthTest()
: socket_factory_(net::ClientSocketFactory::GetDefaultFactory()),
cert_verifier_(new net::MockCertVerifier),
transport_security_state_(new net::TransportSecurityState) {
cert_verifier_->set_default_result(net::OK);
context_.cert_verifier = cert_verifier_.get();
context_.transport_security_state = transport_security_state_.get();
key_store_ = net::OpenSSLClientKeyStore::GetInstance();
}
virtual ~SSLClientSocketOpenSSLClientAuthTest() {
key_store_->Flush();
}
protected:
void EnabledChannelID() {
cert_service_.reset(
new ServerBoundCertService(new DefaultServerBoundCertStore(NULL),
base::MessageLoopProxy::current()));
context_.server_bound_cert_service = cert_service_.get();
}
void EnabledFailingChannelID() {
cert_service_.reset(
new ServerBoundCertService(new FailingServerBoundCertStore(),
base::MessageLoopProxy::current()));
context_.server_bound_cert_service = cert_service_.get();
}
scoped_ptr<SSLClientSocket> CreateSSLClientSocket(
scoped_ptr<StreamSocket> transport_socket,
const HostPortPair& host_and_port,
const SSLConfig& ssl_config) {
scoped_ptr<ClientSocketHandle> connection(new ClientSocketHandle);
connection->SetSocket(transport_socket.Pass());
return socket_factory_->CreateSSLClientSocket(connection.Pass(),
host_and_port,
ssl_config,
context_);
}
// Connect to a HTTPS test server.
bool ConnectToTestServer(SpawnedTestServer::SSLOptions& ssl_options) {
test_server_.reset(new SpawnedTestServer(SpawnedTestServer::TYPE_HTTPS,
ssl_options,
base::FilePath()));
if (!test_server_->Start()) {
LOG(ERROR) << "Could not start SpawnedTestServer";
return false;
}
if (!test_server_->GetAddressList(&addr_)) {
LOG(ERROR) << "Could not get SpawnedTestServer address list";
return false;
}
transport_.reset(new TCPClientSocket(
addr_, &log_, NetLog::Source()));
int rv = callback_.GetResult(
transport_->Connect(callback_.callback()));
if (rv != OK) {
LOG(ERROR) << "Could not connect to SpawnedTestServer";
return false;
}
return true;
}
// Record a certificate's private key to ensure it can be used
// by the OpenSSL-based SSLClientSocket implementation.
// |ssl_config| provides a client certificate.
// |private_key| must be an EVP_PKEY for the corresponding private key.
// Returns true on success, false on failure.
bool RecordPrivateKey(SSLConfig& ssl_config,
EVP_PKEY* private_key) {
return key_store_->RecordClientCertPrivateKey(
ssl_config.client_cert.get(), private_key);
}
// Create an SSLClientSocket object and use it to connect to a test
// server, then wait for connection results. This must be called after
// a succesful ConnectToTestServer() call.
// |ssl_config| the SSL configuration to use.
// |result| will retrieve the ::Connect() result value.
// Returns true on succes, false otherwise. Success means that the socket
// could be created and its Connect() was called, not that the connection
// itself was a success.
bool CreateAndConnectSSLClientSocket(SSLConfig& ssl_config,
int* result) {
sock_ = CreateSSLClientSocket(transport_.Pass(),
test_server_->host_port_pair(),
ssl_config);
if (sock_->IsConnected()) {
LOG(ERROR) << "SSL Socket prematurely connected";
return false;
}
*result = callback_.GetResult(sock_->Connect(callback_.callback()));
return true;
}
// Check that the client certificate was sent.
// Returns true on success.
bool CheckSSLClientSocketSentCert() {
SSLInfo ssl_info;
sock_->GetSSLInfo(&ssl_info);
return ssl_info.client_cert_sent;
}
scoped_ptr<ServerBoundCertService> cert_service_;
ClientSocketFactory* socket_factory_;
scoped_ptr<MockCertVerifier> cert_verifier_;
scoped_ptr<TransportSecurityState> transport_security_state_;
SSLClientSocketContext context_;
OpenSSLClientKeyStore* key_store_;
scoped_ptr<SpawnedTestServer> test_server_;
AddressList addr_;
TestCompletionCallback callback_;
CapturingNetLog log_;
scoped_ptr<StreamSocket> transport_;
scoped_ptr<SSLClientSocket> sock_;
};
// Connect to a server requesting client authentication, do not send
// any client certificates. It should refuse the connection.
TEST_F(SSLClientSocketOpenSSLClientAuthTest, NoCert) {
SpawnedTestServer::SSLOptions ssl_options;
ssl_options.request_client_certificate = true;
ASSERT_TRUE(ConnectToTestServer(ssl_options));
base::FilePath certs_dir = GetTestCertsDirectory();
SSLConfig ssl_config = kDefaultSSLConfig;
int rv;
ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config, &rv));
EXPECT_EQ(ERR_SSL_CLIENT_AUTH_CERT_NEEDED, rv);
EXPECT_FALSE(sock_->IsConnected());
}
// Connect to a server requesting client authentication, and send it
// an empty certificate. It should refuse the connection.
TEST_F(SSLClientSocketOpenSSLClientAuthTest, SendEmptyCert) {
SpawnedTestServer::SSLOptions ssl_options;
ssl_options.request_client_certificate = true;
ssl_options.client_authorities.push_back(
GetTestClientCertsDirectory().AppendASCII("client_1_ca.pem"));
ASSERT_TRUE(ConnectToTestServer(ssl_options));
base::FilePath certs_dir = GetTestCertsDirectory();
SSLConfig ssl_config = kDefaultSSLConfig;
ssl_config.send_client_cert = true;
ssl_config.client_cert = NULL;
int rv;
ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config, &rv));
EXPECT_EQ(OK, rv);
EXPECT_TRUE(sock_->IsConnected());
}
// Connect to a server requesting client authentication. Send it a
// matching certificate. It should allow the connection.
TEST_F(SSLClientSocketOpenSSLClientAuthTest, SendGoodCert) {
SpawnedTestServer::SSLOptions ssl_options;
ssl_options.request_client_certificate = true;
ssl_options.client_authorities.push_back(
GetTestClientCertsDirectory().AppendASCII("client_1_ca.pem"));
ASSERT_TRUE(ConnectToTestServer(ssl_options));
base::FilePath certs_dir = GetTestCertsDirectory();
SSLConfig ssl_config = kDefaultSSLConfig;
ssl_config.send_client_cert = true;
ssl_config.client_cert = ImportCertFromFile(certs_dir, "client_1.pem");
// This is required to ensure that signing works with the client
// certificate's private key.
OpenSSLClientKeyStore::ScopedEVP_PKEY client_private_key;
ASSERT_TRUE(LoadPrivateKeyOpenSSL(certs_dir.AppendASCII("client_1.key"),
&client_private_key));
EXPECT_TRUE(RecordPrivateKey(ssl_config, client_private_key.get()));
int rv;
ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config, &rv));
EXPECT_EQ(OK, rv);
EXPECT_TRUE(sock_->IsConnected());
EXPECT_TRUE(CheckSSLClientSocketSentCert());
sock_->Disconnect();
EXPECT_FALSE(sock_->IsConnected());
}
// Connect to a server using channel id. It should allow the connection.
TEST_F(SSLClientSocketOpenSSLClientAuthTest, SendChannelID) {
SpawnedTestServer::SSLOptions ssl_options;
ASSERT_TRUE(ConnectToTestServer(ssl_options));
EnabledChannelID();
SSLConfig ssl_config = kDefaultSSLConfig;
ssl_config.channel_id_enabled = true;
int rv;
ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config, &rv));
EXPECT_EQ(OK, rv);
EXPECT_TRUE(sock_->IsConnected());
EXPECT_TRUE(sock_->WasChannelIDSent());
sock_->Disconnect();
EXPECT_FALSE(sock_->IsConnected());
}
// Connect to a server using channel id but without sending a key. It should
// fail.
TEST_F(SSLClientSocketOpenSSLClientAuthTest, FailingChannelID) {
SpawnedTestServer::SSLOptions ssl_options;
ASSERT_TRUE(ConnectToTestServer(ssl_options));
EnabledFailingChannelID();
SSLConfig ssl_config = kDefaultSSLConfig;
ssl_config.channel_id_enabled = true;
int rv;
ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config, &rv));
EXPECT_EQ(ERR_UNEXPECTED, rv);
EXPECT_FALSE(sock_->IsConnected());
}
#endif // defined(USE_OPENSSL_CERTS)
} // namespace
} // namespace net
<|endoftext|> |
<commit_before>// C++
#include <iostream>
// Libmesh
#include "libmesh/libmesh.h" //for libmeshinit
// FEMuS
#include "FemusDefault.hpp"
#include "Files.hpp"
#include "GeomEl.hpp"
#include "Box.hpp"
#include "GenCase.hpp"
#include "FEElemBase.hpp"
#include "FEQuad4.hpp"
#include "FEQuad9.hpp"
#include "FEHex8.hpp"
#include "FEHex27.hpp"
#include "FETri3.hpp"
#include "FETri6.hpp"
#include "FETet4.hpp"
#include "FETet10.hpp"
#include "FETypeEnum.hpp"
#include "RunTimeMap.hpp"
#include "TimeLoop.hpp"
#include "CmdLine.hpp"
// ==========================================
// GENCASE
// ==========================================
//The goal of the gencase program is to put some files
// into the input/ directory of the corresponding Application
//If you want to generate the mesh with libmesh, set libmesh_gen=1
//If you want to read it from an external file:
// - set libmesh_gen=0,
// - put the external file (e.g. mesh.gam) into the CONFIG directory
// - and set the file name in F_MESH_READ in "param_files.in"
// Only, beware that "dimension" is the same as the mesh dimension in the file
// (anyway we have a check for that)
//This is a special application in the sense all that its configuration
//is dependent on the App that we are considering,
//so it is a sort of "service application"
// Considering instead the configuration of the classes, the classes that are involved
// are the FE because you must know how the dofs are arranged, the GeomEl which gives you
// the type of Geometric element of the class. Strangely, Mesh is not involved. This is because
//Mesh only "dialogues" with the output files of gencase. But clearly, Mesh depends on GeomEl,
//so there cannot be TWO DIFFERENT GeomEl for Gencase and for the App, as it happens to be the case of course.
//TODO can we make the gencase output in parallel?!
// The fact of the parallel output is what refrains me from thinking of some alternative
// to redirecting std output INSIDE C++ instead of FROM SHELL... maybe there is a shell variable
// that holds the MPI Rank... the problem is that it would exist after a command
// of the type "mpiexec > file$MYPROC.txt" would be launched...
int main(int argc, char** argv) {
LibMeshInit init(argc, argv); // Initialize libMesh
CmdLine::parse(argc,argv);
std::string chosen_app = CmdLine::get("--app");
std::cout << "**************************************************************" << std::endl;
std::cout << "***** The application I will generate the case for is ****** " << chosen_app << std::endl;
std::cout << "**************************************************************" << std::endl;
// ======= Files =====
Files::CheckDirOrAbort("../",chosen_app);
std::string basepath = "../" + chosen_app + "/";
Files files(basepath);
std::cout << "******The basepath starting from the gencase directory is ***** " << files.get_basepath() << std::endl;
// files.CheckDirOrAbort(files.get_basepath(),DEFAULT_CONFIGDIR);
// files.get_frtmap_ptr()->read(); // THE ERROR IS IN HERE.. BUT NOT IN THE APPS... WHAT IS DIFFERENT WRT THEM ?!? ... LIBMESH...! but... ONLY IN DEBUG MODE!!!!
files.get_frtmap().read();
files.get_frtmap().print();
files.CheckDir(files.get_basepath(),DEFAULT_CASEDIR); //here, we must check if the input directory where gencase writes is there //if not, we make it
//======== first of all, check for restart ======
//======== don't rerun gencase in that case, to avoid spending time on rebuilding the operators and so on ======
//======== actually we will change the logic, we will read EVERYTHING from THE PREVIOUS RUN ======
RunTimeMap<double> timemap("TimeLoop",files.get_basepath()); //here you don't need to instantiate a TimeLoop object, but only to read its RUNTIME MAP
timemap.read();
timemap.print();
TimeLoop::check_time_par(timemap);
const uint restart = (uint) timemap.get("restart"); // restart param
if (restart) {std::cout << "No GenCase because of restart flag !=0 " << std::endl; abort();}
// ======= Mesh =====
RunTimeMap<double> mesh_map("Mesh",files.get_basepath());
mesh_map.read();
mesh_map.print();
// =======GeomEl =====
uint geomel_type = (uint) mesh_map.get("geomel_type");
uint dimension = (uint) mesh_map.get("dimension");
GeomEl geomel(dimension,geomel_type);
// =======FEElems =====
std::vector<FEElemBase*> FEElements(QL); //these are basically used only for the embedding matrix
for (int fe=0; fe<QL; fe++) FEElements[fe] = FEElemBase::build(&geomel,fe);
// ======= Domain =====
//here we miss the "service" nature of the gencase program
//we must instantiate the domain explicitly
//we should do the ifdefs here for all types of Domains...
//the Domain is not related to the MESH ORDER.
//it may be related to the MESH MAPPING if we have curved elements or not
//but the fact of having curved elements might be more dependent on
//the Mesh than the Doamin shape.
//anyway, now we do like this
// ========= GenCase =====
GenCase gencase(files,mesh_map,geomel,FEElements);
gencase.GenerateCase();
std::cout << "=======End of GenCase========" << std::endl;
//clean
//remember that the CHILD destructor is not called here. This is because
//these things are of FEElemBase type
//TODO Do I have to put a delete [] or only delete? Do standard vectors have an overloading of the "delete" operator?
for (int fe=0; fe<QL; fe++) delete FEElements[fe];
return 0;
}
<commit_msg>Greatly simplified restart check on gencase<commit_after>// C++
#include <iostream>
// Libmesh
#include "libmesh/libmesh.h" //for libmeshinit
// FEMuS
#include "FemusDefault.hpp"
#include "Files.hpp"
#include "GeomEl.hpp"
#include "Box.hpp"
#include "GenCase.hpp"
#include "FEElemBase.hpp"
#include "FEQuad4.hpp"
#include "FEQuad9.hpp"
#include "FEHex8.hpp"
#include "FEHex27.hpp"
#include "FETri3.hpp"
#include "FETri6.hpp"
#include "FETet4.hpp"
#include "FETet10.hpp"
#include "FETypeEnum.hpp"
#include "RunTimeMap.hpp"
#include "TimeLoop.hpp"
#include "CmdLine.hpp"
// ==========================================
// GENCASE
// ==========================================
//The goal of the gencase program is to put some files
// into the input/ directory of the corresponding Application
//If you want to generate the mesh with libmesh, set libmesh_gen=1
//If you want to read it from an external file:
// - set libmesh_gen=0,
// - put the external file (e.g. mesh.gam) into the CONFIG directory
// - and set the file name in F_MESH_READ in "param_files.in"
// Only, beware that "dimension" is the same as the mesh dimension in the file
// (anyway we have a check for that)
//This is a special application in the sense all that its configuration
//is dependent on the App that we are considering,
//so it is a sort of "service application"
// Considering instead the configuration of the classes, the classes that are involved
// are the FE because you must know how the dofs are arranged, the GeomEl which gives you
// the type of Geometric element of the class. Strangely, Mesh is not involved. This is because
//Mesh only "dialogues" with the output files of gencase. But clearly, Mesh depends on GeomEl,
//so there cannot be TWO DIFFERENT GeomEl for Gencase and for the App, as it happens to be the case of course.
//TODO can we make the gencase output in parallel?!
// The fact of the parallel output is what refrains me from thinking of some alternative
// to redirecting std output INSIDE C++ instead of FROM SHELL... maybe there is a shell variable
// that holds the MPI Rank... the problem is that it would exist after a command
// of the type "mpiexec > file$MYPROC.txt" would be launched...
//TODO see what happens with libmesh in debug mode
int main(int argc, char** argv) {
LibMeshInit init(argc, argv); // Initialize libMesh
CmdLine::parse(argc,argv);
std::string chosen_app = CmdLine::get("--app");
std::cout << "**************************************************************" << std::endl;
std::cout << "***** The application I will generate the case for is ****** " << chosen_app << std::endl;
std::cout << "**************************************************************" << std::endl;
// ======= Files =====
Files::CheckDirOrAbort("../",chosen_app);
std::string basepath = "../" + chosen_app + "/";
Files files(basepath);
std::cout << "******The basepath starting from the gencase directory is ***** " << files.get_basepath() << std::endl;
//======== first of all, check for restart ======
//======== don't rerun gencase in that case, to avoid spending time on rebuilding the operators and so on ======
files.ConfigureRestart();
if (files._restart_flag == true) { std::cout << "Do not rerun gencase in case of restart" << std::endl; abort(); }
files.get_frtmap().read();
files.get_frtmap().print();
files.CheckDir(files.get_basepath(),DEFAULT_CASEDIR); //here, we must check if the input directory where gencase writes is there //if not, we make it
// ======= Mesh =====
RunTimeMap<double> mesh_map("Mesh",files.get_basepath());
mesh_map.read();
mesh_map.print();
// =======GeomEl =====
uint geomel_type = (uint) mesh_map.get("geomel_type");
uint dimension = (uint) mesh_map.get("dimension");
GeomEl geomel(dimension,geomel_type);
// =======FEElems =====
std::vector<FEElemBase*> FEElements(QL); //these are basically used only for the embedding matrix
for (int fe=0; fe<QL; fe++) FEElements[fe] = FEElemBase::build(&geomel,fe);
// ======= Domain =====
//here we miss the "service" nature of the gencase program
//we must instantiate the domain explicitly
//we should do the ifdefs here for all types of Domains...
//the Domain is not related to the MESH ORDER.
//it may be related to the MESH MAPPING if we have curved elements or not
//but the fact of having curved elements might be more dependent on
//the Mesh than the Doamin shape.
//anyway, now we do like this
// ========= GenCase =====
GenCase gencase(files,mesh_map,geomel,FEElements);
gencase.GenerateCase();
std::cout << "=======End of GenCase========" << std::endl;
//clean
//remember that the CHILD destructor is not called here. This is because
//these things are of FEElemBase type
//TODO Do I have to put a delete [] or only delete? Do standard vectors have an overloading of the "delete" operator?
for (int fe=0; fe<QL; fe++) delete FEElements[fe];
return 0;
}
<|endoftext|> |
<commit_before>/****************************************************************************
*
* Copyright (c) 2015 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
/**
* @file px4_sem.cpp
*
* PX4 Middleware Wrapper Linux Implementation
*/
#include <px4_defines.h>
#include <px4_middleware.h>
#include <px4_workqueue.h>
#include <stdint.h>
#include <stdio.h>
#include <pthread.h>
#ifdef __PX4_DARWIN
#include <px4_posix.h>
#include <list>
int px4_sem_init(px4_sem_t *s, int pshared, unsigned value)
{
// We do not used the process shared arg
(void)pshared;
s->value = value;
pthread_cond_init(&(s->wait), NULL);
pthread_mutex_init(&(s->lock), NULL);
return 0;
}
int px4_sem_wait(px4_sem_t *s)
{
pthread_mutex_lock(&(s->lock));
s->value--;
if (s->value < 0) {
pthread_cond_wait(&(s->wait), &(s->lock));
}
pthread_mutex_unlock(&(s->lock));
return 0;
}
int px4_sem_timedwait(px4_sem_t * s, const struct timespec * abstime)
{
pthread_mutex_lock(&(s->lock));
s->value--;
if (s->value < 0) {
pthread_cond_timedwait(&(s->wait), &(s->lock), abstime);
}
pthread_mutex_unlock(&(s->lock));
return 0;
}
int px4_sem_post(px4_sem_t *s)
{
pthread_mutex_lock(&(s->lock));
s->value++;
if (s->value <= 0) {
pthread_cond_signal(&(s->wait));
}
pthread_mutex_unlock(&(s->lock));
return 0;
}
int px4_sem_getvalue(px4_sem_t *s, int *sval)
{
pthread_mutex_lock(&(s->lock));
*sval = s->value;
pthread_mutex_unlock(&(s->lock));
return 0;
}
int px4_sem_destroy(px4_sem_t *s)
{
pthread_mutex_lock(&(s->lock));
pthread_cond_destroy(&(s->wait));
pthread_mutex_unlock(&(s->lock));
pthread_mutex_destroy(&(s->lock));
return 0;
}
#endif
<commit_msg>PX4 semaphores: Formatting fix<commit_after>/****************************************************************************
*
* Copyright (c) 2015 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
/**
* @file px4_sem.cpp
*
* PX4 Middleware Wrapper Linux Implementation
*/
#include <px4_defines.h>
#include <px4_middleware.h>
#include <px4_workqueue.h>
#include <stdint.h>
#include <stdio.h>
#include <pthread.h>
#ifdef __PX4_DARWIN
#include <px4_posix.h>
#include <list>
int px4_sem_init(px4_sem_t *s, int pshared, unsigned value)
{
// We do not used the process shared arg
(void)pshared;
s->value = value;
pthread_cond_init(&(s->wait), NULL);
pthread_mutex_init(&(s->lock), NULL);
return 0;
}
int px4_sem_wait(px4_sem_t *s)
{
pthread_mutex_lock(&(s->lock));
s->value--;
if (s->value < 0) {
pthread_cond_wait(&(s->wait), &(s->lock));
}
pthread_mutex_unlock(&(s->lock));
return 0;
}
int px4_sem_timedwait(px4_sem_t *s, const struct timespec *abstime)
{
pthread_mutex_lock(&(s->lock));
s->value--;
if (s->value < 0) {
pthread_cond_timedwait(&(s->wait), &(s->lock), abstime);
}
pthread_mutex_unlock(&(s->lock));
return 0;
}
int px4_sem_post(px4_sem_t *s)
{
pthread_mutex_lock(&(s->lock));
s->value++;
if (s->value <= 0) {
pthread_cond_signal(&(s->wait));
}
pthread_mutex_unlock(&(s->lock));
return 0;
}
int px4_sem_getvalue(px4_sem_t *s, int *sval)
{
pthread_mutex_lock(&(s->lock));
*sval = s->value;
pthread_mutex_unlock(&(s->lock));
return 0;
}
int px4_sem_destroy(px4_sem_t *s)
{
pthread_mutex_lock(&(s->lock));
pthread_cond_destroy(&(s->wait));
pthread_mutex_unlock(&(s->lock));
pthread_mutex_destroy(&(s->lock));
return 0;
}
#endif
<|endoftext|> |
<commit_before>#include "qasioeventdispatcher.h"
#include <boost/asio/io_service.hpp>
#include <boost/asio/posix/stream_descriptor.hpp>
#include <boost/asio/steady_timer.hpp>
#include <boost/bind.hpp>
#include <qpa/qwindowsysteminterface.h>
//#include "qplatformdefs.h"
#include "qcoreapplication.h"
#include "qpair.h"
#include "qsocketnotifier.h"
#include "qthread.h"
#include "qelapsedtimer.h"
#include "private/qtimerinfo_unix_p.h"
#define LOG(expr) #expr": " << (expr) << "; "
/* TODO:
* - error types of sockets
* - handling flags passed to processEvents
*/
// One object per fd; three QSocketNotifier's may be connected to it;
struct QAsioSockNotifier
{
QSocketNotifier *notif[3]={0, 0, 0}; //notifiers for {Read, Write, Exception}
int revision[3]={0, 0, 0}; //revision[x] is incremented each time notif[i] is changed (therefore a new completion handler loop is started)
int fd;
boost::asio::posix::stream_descriptor *sd;
int pending_operations = 0;
};
class Q_CORE_EXPORT QAsioEventDispatcherPrivate : public QAbstractEventDispatcherPrivate
{
Q_DECLARE_PUBLIC(QAsioEventDispatcher)
public:
QAsioEventDispatcherPrivate(boost::asio::io_service &io_service);
~QAsioEventDispatcherPrivate();
boost::asio::io_service &io_service;
boost::asio::steady_timer nearest_timer;
QList<QAsioSockNotifier *> socketNotifiers;
QTimerInfoList timerList;
QAtomicInt interrupt;
QAsioSockNotifier *socketNotifierForFd(int fd, bool createIfNotFound);
void cleanupSocketNotifiers(bool forceRemoveAll);
void timerTimeout(const boost::system::error_code &error);
void timerStart();
void timerCancel();
};
QAsioEventDispatcherPrivate::QAsioEventDispatcherPrivate(boost::asio::io_service &io_service_)
: io_service(io_service_)
, nearest_timer(io_service)
{
}
QAsioEventDispatcherPrivate::~QAsioEventDispatcherPrivate()
{
cleanupSocketNotifiers(true);
Q_ASSERT(socketNotifiers.empty());
// cleanup timers
qDeleteAll(timerList);
}
QAsioEventDispatcher::QAsioEventDispatcher(boost::asio::io_service &io_service, QObject *parent)
: QAbstractEventDispatcher(*new QAsioEventDispatcherPrivate(io_service), parent)
{
}
QAsioEventDispatcher::QAsioEventDispatcher(QAsioEventDispatcherPrivate &dd, QObject *parent)
: QAbstractEventDispatcher(dd, parent)
{ }
QAsioEventDispatcher::~QAsioEventDispatcher()
{
}
void QAsioEventDispatcherPrivate::timerTimeout(const boost::system::error_code& error)
{
if(!error) {
(void) timerList.activateTimers();
}
}
void QAsioEventDispatcherPrivate::timerStart()
{
timespec tv = { 0l, 0l };
#if BOOST_ASIO_HAS_STD_CHRONO
using namespace std::chrono;
#else
using namespace boost::chrono;
#endif
if (/*FIXME: !(src->processEventsFlags & QEventLoop::X11ExcludeTimers) && */timerList.timerWait(tv)) {
nearest_timer.cancel();
nearest_timer.expires_from_now(seconds(tv.tv_sec) + nanoseconds(tv.tv_nsec ));
nearest_timer.async_wait(boost::bind(&QAsioEventDispatcherPrivate::timerTimeout, this, _1));
}
}
void QAsioEventDispatcherPrivate::timerCancel()
{
nearest_timer.cancel();
}
void QAsioEventDispatcher::registerTimer(int timerId, int interval, Qt::TimerType timerType, QObject *obj)
{
#ifndef QT_NO_DEBUG
if (timerId < 1 || interval < 0 || !obj) {
qWarning("QAsioEventDispatcher::registerTimer: invalid arguments");
return;
} else if (obj->thread() != thread() || thread() != QThread::currentThread()) {
qWarning("QObject::startTimer: timers cannot be started from another thread");
return;
}
#endif
Q_D(QAsioEventDispatcher);
d->timerList.registerTimer(timerId, interval, timerType, obj);
}
/*!
\internal
*/
bool QAsioEventDispatcher::unregisterTimer(int timerId)
{
#ifndef QT_NO_DEBUG
if (timerId < 1) {
qWarning("QAsioEventDispatcher::unregisterTimer: invalid argument");
return false;
} else if (thread() != QThread::currentThread()) {
qWarning("QObject::killTimer: timers cannot be stopped from another thread");
return false;
}
#endif
Q_D(QAsioEventDispatcher);
return d->timerList.unregisterTimer(timerId);
}
/*!
\internal
*/
bool QAsioEventDispatcher::unregisterTimers(QObject *object)
{
#ifndef QT_NO_DEBUG
if (!object) {
qWarning("QAsioEventDispatcher::unregisterTimers: invalid argument");
return false;
} else if (object->thread() != thread() || thread() != QThread::currentThread()) {
qWarning("QObject::killTimers: timers cannot be stopped from another thread");
return false;
}
#endif
Q_D(QAsioEventDispatcher);
return d->timerList.unregisterTimers(object);
}
QList<QAsioEventDispatcher::TimerInfo>
QAsioEventDispatcher::registeredTimers(QObject *object) const
{
if (!object) {
qWarning("QAsioEventDispatcher:registeredTimers: invalid argument");
return QList<TimerInfo>();
}
Q_D(const QAsioEventDispatcher);
return d->timerList.registeredTimers(object);
}
int QAsioEventDispatcher::remainingTime(int timerId)
{
#ifndef QT_NO_DEBUG
if (timerId < 1) {
qWarning("QAsioEventDispatcher::remainingTime: invalid argument");
return -1;
}
#endif
//FIXME
Q_D(QAsioEventDispatcher);
return d->timerList.timerRemainingTime(timerId);
}
QAsioSockNotifier *QAsioEventDispatcherPrivate::socketNotifierForFd(int fd, bool createIfNotFound)
{
for(int i = 0; i < socketNotifiers.count(); ++i) {
QAsioSockNotifier *n = socketNotifiers.at(i);
if(n->fd == fd) return n;
}
if(createIfNotFound)
{
QAsioSockNotifier *sn = new QAsioSockNotifier;
sn->fd = fd;
sn->sd = new boost::asio::posix::stream_descriptor(io_service, fd);
socketNotifiers.push_back(sn);
return sn;
}
return 0;
}
void QAsioEventDispatcherPrivate::cleanupSocketNotifiers(bool forceRemoveAll = false)
{
for(int i = 0; i < socketNotifiers.count();) {
QAsioSockNotifier *sn = socketNotifiers.at(i);
if(sn->pending_operations == 0 || forceRemoveAll) {
if(!forceRemoveAll) {
Q_ASSERT(sn->notif[0] == 0
&& sn->notif[1] == 0
&& sn->notif[2] == 0);
}
//removeAll, but there should be only one instance in the list
socketNotifiers.removeAll(sn);
delete sn->sd;
delete sn;
}
else {
++i;
}
}
}
static void fdReadStart(QAsioSockNotifier *sn);
static void fdWriteStart(QAsioSockNotifier *sn);
static void fdReadReady(QAsioSockNotifier *sn, const boost::system::error_code& error, int revision)
{
sn->pending_operations--;
int type = (int)QSocketNotifier::Read;
bool sn_changed = sn->revision[type] != revision;
if(!sn_changed && !error) {
fdReadStart(sn);
QEvent event(QEvent::SockAct);
QCoreApplication::sendEvent(sn->notif[type], &event);
}
else {
}
}
static void fdWriteReady(QAsioSockNotifier *sn, const boost::system::error_code& error, int revision)
{
sn->pending_operations--;
int type = (int)QSocketNotifier::Write;
bool sn_changed = sn->revision[type] != revision;
if(!sn_changed && !error) {
fdWriteStart(sn);
QEvent event(QEvent::SockAct);
QCoreApplication::sendEvent(sn->notif[type], &event);
}
else {
}
}
static void fdReadStart(QAsioSockNotifier *sn)
{
int type = (int)QSocketNotifier::Read;
sn->pending_operations++;
Q_ASSERT(sn->notif[type]);
sn->sd->async_read_some(boost::asio::null_buffers(), boost::bind(fdReadReady, sn, _1, sn->revision[type]));
}
static void fdWriteStart(QAsioSockNotifier *sn)
{
int type = (int)QSocketNotifier::Write;
sn->pending_operations++;
Q_ASSERT(sn->notif[type]);
sn->sd->async_write_some(boost::asio::null_buffers(), boost::bind(fdWriteReady, sn, _1, sn->revision[type]));
}
void QAsioEventDispatcher::registerSocketNotifier(QSocketNotifier *notifier)
{
//std::clog<< __PRETTY_FUNCTION__ << LOG(notifier->type()) << LOG(notifier->socket()) << std::endl;
Q_ASSERT(notifier);
int sockfd = notifier->socket();
int type = notifier->type();
#ifndef QT_NO_DEBUG
if (sockfd < 0
|| unsigned(sockfd) >= FD_SETSIZE) {
qWarning("QSocketNotifier: Internal error");
return;
} else if (notifier->thread() != thread()
|| thread() != QThread::currentThread()) {
qWarning("QSocketNotifier: socket notifiers cannot be enabled from another thread");
return;
}
#endif
Q_D(QAsioEventDispatcher);
//std::clog << LOG(d->socketNotifiers.size()) << std::endl;
QAsioSockNotifier *sn = d->socketNotifierForFd(sockfd, true);
Q_ASSERT(sn);
Q_ASSERT(type<3 && type>=0);
Q_ASSERT(sn->notif[type] == 0);
sn->notif[type] = notifier;
sn->revision[type]++;
switch(type)
{
case QSocketNotifier::Read:
fdReadStart(sn);
break;
case QSocketNotifier::Write:
fdWriteStart(sn);
break;
default:
qFatal("Not supported socket type");
//TODO: write, error...
}
}
void QAsioEventDispatcher::unregisterSocketNotifier(QSocketNotifier *notifier)
{
//std::clog<< __PRETTY_FUNCTION__ << LOG(notifier->type()) << LOG(notifier->socket()) << std::endl;
Q_ASSERT(notifier);
int sockfd = notifier->socket();
int type = notifier->type();
#ifndef QT_NO_DEBUG
if (sockfd < 0
|| unsigned(sockfd) >= FD_SETSIZE) {
qWarning("QSocketNotifier: Internal error");
return;
} else if (notifier->thread() != thread()
|| thread() != QThread::currentThread()) {
qWarning("QSocketNotifier: socket notifiers cannot be disabled from another thread");
return;
}
#endif
Q_D(QAsioEventDispatcher);
QAsioSockNotifier *sn = d->socketNotifierForFd(sockfd, false);
Q_ASSERT(sn);
if(sn)
{
Q_ASSERT(sn->notif[type] == notifier);
sn->notif[type] = 0;
sn->revision[type]++;
if(sn->notif[0] == 0
&& sn->notif[1] == 0
&& sn->notif[2] == 0
) {
//if no more socket notifiers on given fd are pending, we don't need it anymore
//but we cannot delete "sn" yet, since some handlers that use it may be pending (see fdMaybeCleanup())
sn->sd->cancel();
//sn->sd->close();
//d->removeSocketNotifier(sn);
//FIXME: what if we create a new sn on the same fd soon (while handlers are still pending)?
}
//if not all notifiers are unregistered, we don't cancel pending handler, since we cannot do it selectively (i.e. cancel only read or only write)
//however, it's not a problem, since it will notice that sn->revision doesn't match and will "cancel" itself during the next call
}
}
bool QAsioEventDispatcher::processEvents(QEventLoop::ProcessEventsFlags flags)
{
Q_D(QAsioEventDispatcher);
d->interrupt.store(0);
//QCoreApplicationPrivate::sendPostedEvents(0, 0, d->threadData); //unix dispatcher use this
QCoreApplication::sendPostedEvents(); //glib dispatcher call this after every call of "awake".
const bool canWait = (/*d->threadData->canWaitLocked()
&&*/ !d->interrupt.load() //it may have been set during the call of QCoreApplication::sendPostedEvents()
&& (flags & QEventLoop::WaitForMoreEvents));
if (d->interrupt.load())
{
return false; //unix event dispatcher returns false if nothing more than "postedEvents" were dispatched
}
if (!(flags & QEventLoop::X11ExcludeTimers)) {
d->timerStart();
}
int total_events = 0; /* FIXME: +1 for stop? */
if (canWait) {
//run at least one handler - may block
emit aboutToBlock();
d->io_service.reset();
total_events += d->io_service.run_one();
emit awake();
}
int events;
do
{
if (!(flags & QEventLoop::X11ExcludeTimers)) {
d->timerStart();
}
d->io_service.reset();
//run all ready handlers
events = d->io_service.poll();
if ((flags & QEventLoop::ExcludeSocketNotifiers)) {
//FIXME: ignore stream descriptors
}
if ((flags & QEventLoop::X11ExcludeTimers)) {
//FIXME: ignore timers?
}
total_events += events;
QCoreApplication::sendPostedEvents();
total_events += QWindowSystemInterface::sendWindowSystemEvents(flags) ? 1 : 0;
} while(events>0);
d->cleanupSocketNotifiers();
// return true if we handled events, false otherwise
return (total_events > 0);
}
bool QAsioEventDispatcher::hasPendingEvents()
{
//This is copy-pasted from QUnixEventDispatcherQPA. I don't really understand how it works.
extern uint qGlobalPostedEventsCount(); // from qapplication.cpp
return qGlobalPostedEventsCount() || QWindowSystemInterface::windowSystemEventsQueued();
}
void QAsioEventDispatcher::wakeUp()
{
Q_D(QAsioEventDispatcher);
//I don't know what a logic stays behind it, but qeventdispatcher_glib works in such a way, that after every "wakeUp", the following function is called
//io_service.post(QCoreApplication::sendPostedEvents);
d->io_service.stop(); //exit from run_one
}
void QAsioEventDispatcher::interrupt()
{
Q_D(QAsioEventDispatcher);
d->interrupt.store(1);
wakeUp();
}
void QAsioEventDispatcher::flush()
{
/* It does nothing in glib event dispatcher.
*
* QUnixEventDispatcherQPA calls QCoreApplication::instance()->sendPostedEvents here.
*
* But the docs of QAbstractEventDispatcher says:
* "flushes the event queue. This normally returns almost immediately. Does nothing on platforms other than X11"
*
* I'm a bit confused. FIXME
*/
}
QT_END_NAMESPACE
<commit_msg>Don't demand c++11.<commit_after>#include "qasioeventdispatcher.h"
#include <boost/asio/io_service.hpp>
#include <boost/asio/posix/stream_descriptor.hpp>
#include <boost/asio/steady_timer.hpp>
#include <boost/bind.hpp>
#include <qpa/qwindowsysteminterface.h>
//#include "qplatformdefs.h"
#include "qcoreapplication.h"
#include "qpair.h"
#include "qsocketnotifier.h"
#include "qthread.h"
#include "qelapsedtimer.h"
#include "private/qtimerinfo_unix_p.h"
#define LOG(expr) #expr": " << (expr) << "; "
/* TODO:
* - error types of sockets
* - handling flags passed to processEvents
*/
// One object per fd; three QSocketNotifier's may be connected to it;
struct QAsioSockNotifier
{
QAsioSockNotifier()
: pending_operations(0)
{
for(int i=0; i<3; ++i) {
notif[i]=0;
revision[i]=0;
}
}
QSocketNotifier *notif[3]; //notifiers for {Read, Write, Exception}
int revision[3]; //revision[x] is incremented each time notif[i] is changed (therefore a new completion handler loop is started)
int fd;
boost::asio::posix::stream_descriptor *sd;
int pending_operations;
};
class Q_CORE_EXPORT QAsioEventDispatcherPrivate : public QAbstractEventDispatcherPrivate
{
Q_DECLARE_PUBLIC(QAsioEventDispatcher)
public:
QAsioEventDispatcherPrivate(boost::asio::io_service &io_service);
~QAsioEventDispatcherPrivate();
boost::asio::io_service &io_service;
boost::asio::steady_timer nearest_timer;
QList<QAsioSockNotifier *> socketNotifiers;
QTimerInfoList timerList;
QAtomicInt interrupt;
QAsioSockNotifier *socketNotifierForFd(int fd, bool createIfNotFound);
void cleanupSocketNotifiers(bool forceRemoveAll);
void timerTimeout(const boost::system::error_code &error);
void timerStart();
void timerCancel();
};
QAsioEventDispatcherPrivate::QAsioEventDispatcherPrivate(boost::asio::io_service &io_service_)
: io_service(io_service_)
, nearest_timer(io_service)
{
}
QAsioEventDispatcherPrivate::~QAsioEventDispatcherPrivate()
{
cleanupSocketNotifiers(true);
Q_ASSERT(socketNotifiers.empty());
// cleanup timers
qDeleteAll(timerList);
}
QAsioEventDispatcher::QAsioEventDispatcher(boost::asio::io_service &io_service, QObject *parent)
: QAbstractEventDispatcher(*new QAsioEventDispatcherPrivate(io_service), parent)
{
}
QAsioEventDispatcher::QAsioEventDispatcher(QAsioEventDispatcherPrivate &dd, QObject *parent)
: QAbstractEventDispatcher(dd, parent)
{ }
QAsioEventDispatcher::~QAsioEventDispatcher()
{
}
void QAsioEventDispatcherPrivate::timerTimeout(const boost::system::error_code& error)
{
if(!error) {
(void) timerList.activateTimers();
}
}
void QAsioEventDispatcherPrivate::timerStart()
{
timespec tv = { 0l, 0l };
#if BOOST_ASIO_HAS_STD_CHRONO
using namespace std::chrono;
#else
using namespace boost::chrono;
#endif
if (/*FIXME: !(src->processEventsFlags & QEventLoop::X11ExcludeTimers) && */timerList.timerWait(tv)) {
nearest_timer.cancel();
nearest_timer.expires_from_now(seconds(tv.tv_sec) + nanoseconds(tv.tv_nsec ));
nearest_timer.async_wait(boost::bind(&QAsioEventDispatcherPrivate::timerTimeout, this, _1));
}
}
void QAsioEventDispatcherPrivate::timerCancel()
{
nearest_timer.cancel();
}
void QAsioEventDispatcher::registerTimer(int timerId, int interval, Qt::TimerType timerType, QObject *obj)
{
#ifndef QT_NO_DEBUG
if (timerId < 1 || interval < 0 || !obj) {
qWarning("QAsioEventDispatcher::registerTimer: invalid arguments");
return;
} else if (obj->thread() != thread() || thread() != QThread::currentThread()) {
qWarning("QObject::startTimer: timers cannot be started from another thread");
return;
}
#endif
Q_D(QAsioEventDispatcher);
d->timerList.registerTimer(timerId, interval, timerType, obj);
}
/*!
\internal
*/
bool QAsioEventDispatcher::unregisterTimer(int timerId)
{
#ifndef QT_NO_DEBUG
if (timerId < 1) {
qWarning("QAsioEventDispatcher::unregisterTimer: invalid argument");
return false;
} else if (thread() != QThread::currentThread()) {
qWarning("QObject::killTimer: timers cannot be stopped from another thread");
return false;
}
#endif
Q_D(QAsioEventDispatcher);
return d->timerList.unregisterTimer(timerId);
}
/*!
\internal
*/
bool QAsioEventDispatcher::unregisterTimers(QObject *object)
{
#ifndef QT_NO_DEBUG
if (!object) {
qWarning("QAsioEventDispatcher::unregisterTimers: invalid argument");
return false;
} else if (object->thread() != thread() || thread() != QThread::currentThread()) {
qWarning("QObject::killTimers: timers cannot be stopped from another thread");
return false;
}
#endif
Q_D(QAsioEventDispatcher);
return d->timerList.unregisterTimers(object);
}
QList<QAsioEventDispatcher::TimerInfo>
QAsioEventDispatcher::registeredTimers(QObject *object) const
{
if (!object) {
qWarning("QAsioEventDispatcher:registeredTimers: invalid argument");
return QList<TimerInfo>();
}
Q_D(const QAsioEventDispatcher);
return d->timerList.registeredTimers(object);
}
int QAsioEventDispatcher::remainingTime(int timerId)
{
#ifndef QT_NO_DEBUG
if (timerId < 1) {
qWarning("QAsioEventDispatcher::remainingTime: invalid argument");
return -1;
}
#endif
//FIXME
Q_D(QAsioEventDispatcher);
return d->timerList.timerRemainingTime(timerId);
}
QAsioSockNotifier *QAsioEventDispatcherPrivate::socketNotifierForFd(int fd, bool createIfNotFound)
{
for(int i = 0; i < socketNotifiers.count(); ++i) {
QAsioSockNotifier *n = socketNotifiers.at(i);
if(n->fd == fd) return n;
}
if(createIfNotFound)
{
QAsioSockNotifier *sn = new QAsioSockNotifier;
sn->fd = fd;
sn->sd = new boost::asio::posix::stream_descriptor(io_service, fd);
socketNotifiers.push_back(sn);
return sn;
}
return 0;
}
void QAsioEventDispatcherPrivate::cleanupSocketNotifiers(bool forceRemoveAll = false)
{
for(int i = 0; i < socketNotifiers.count();) {
QAsioSockNotifier *sn = socketNotifiers.at(i);
if(sn->pending_operations == 0 || forceRemoveAll) {
if(!forceRemoveAll) {
Q_ASSERT(sn->notif[0] == 0
&& sn->notif[1] == 0
&& sn->notif[2] == 0);
}
//removeAll, but there should be only one instance in the list
socketNotifiers.removeAll(sn);
delete sn->sd;
delete sn;
}
else {
++i;
}
}
}
static void fdReadStart(QAsioSockNotifier *sn);
static void fdWriteStart(QAsioSockNotifier *sn);
static void fdReadReady(QAsioSockNotifier *sn, const boost::system::error_code& error, int revision)
{
sn->pending_operations--;
int type = (int)QSocketNotifier::Read;
bool sn_changed = sn->revision[type] != revision;
if(!sn_changed && !error) {
fdReadStart(sn);
QEvent event(QEvent::SockAct);
QCoreApplication::sendEvent(sn->notif[type], &event);
}
else {
}
}
static void fdWriteReady(QAsioSockNotifier *sn, const boost::system::error_code& error, int revision)
{
sn->pending_operations--;
int type = (int)QSocketNotifier::Write;
bool sn_changed = sn->revision[type] != revision;
if(!sn_changed && !error) {
fdWriteStart(sn);
QEvent event(QEvent::SockAct);
QCoreApplication::sendEvent(sn->notif[type], &event);
}
else {
}
}
static void fdReadStart(QAsioSockNotifier *sn)
{
int type = (int)QSocketNotifier::Read;
sn->pending_operations++;
Q_ASSERT(sn->notif[type]);
sn->sd->async_read_some(boost::asio::null_buffers(), boost::bind(fdReadReady, sn, _1, sn->revision[type]));
}
static void fdWriteStart(QAsioSockNotifier *sn)
{
int type = (int)QSocketNotifier::Write;
sn->pending_operations++;
Q_ASSERT(sn->notif[type]);
sn->sd->async_write_some(boost::asio::null_buffers(), boost::bind(fdWriteReady, sn, _1, sn->revision[type]));
}
void QAsioEventDispatcher::registerSocketNotifier(QSocketNotifier *notifier)
{
//std::clog<< __PRETTY_FUNCTION__ << LOG(notifier->type()) << LOG(notifier->socket()) << std::endl;
Q_ASSERT(notifier);
int sockfd = notifier->socket();
int type = notifier->type();
#ifndef QT_NO_DEBUG
if (sockfd < 0
|| unsigned(sockfd) >= FD_SETSIZE) {
qWarning("QSocketNotifier: Internal error");
return;
} else if (notifier->thread() != thread()
|| thread() != QThread::currentThread()) {
qWarning("QSocketNotifier: socket notifiers cannot be enabled from another thread");
return;
}
#endif
Q_D(QAsioEventDispatcher);
//std::clog << LOG(d->socketNotifiers.size()) << std::endl;
QAsioSockNotifier *sn = d->socketNotifierForFd(sockfd, true);
Q_ASSERT(sn);
Q_ASSERT(type<3 && type>=0);
Q_ASSERT(sn->notif[type] == 0);
sn->notif[type] = notifier;
sn->revision[type]++;
switch(type)
{
case QSocketNotifier::Read:
fdReadStart(sn);
break;
case QSocketNotifier::Write:
fdWriteStart(sn);
break;
default:
qFatal("Not supported socket type");
//TODO: write, error...
}
}
void QAsioEventDispatcher::unregisterSocketNotifier(QSocketNotifier *notifier)
{
//std::clog<< __PRETTY_FUNCTION__ << LOG(notifier->type()) << LOG(notifier->socket()) << std::endl;
Q_ASSERT(notifier);
int sockfd = notifier->socket();
int type = notifier->type();
#ifndef QT_NO_DEBUG
if (sockfd < 0
|| unsigned(sockfd) >= FD_SETSIZE) {
qWarning("QSocketNotifier: Internal error");
return;
} else if (notifier->thread() != thread()
|| thread() != QThread::currentThread()) {
qWarning("QSocketNotifier: socket notifiers cannot be disabled from another thread");
return;
}
#endif
Q_D(QAsioEventDispatcher);
QAsioSockNotifier *sn = d->socketNotifierForFd(sockfd, false);
Q_ASSERT(sn);
if(sn)
{
Q_ASSERT(sn->notif[type] == notifier);
sn->notif[type] = 0;
sn->revision[type]++;
if(sn->notif[0] == 0
&& sn->notif[1] == 0
&& sn->notif[2] == 0
) {
//if no more socket notifiers on given fd are pending, we don't need it anymore
//but we cannot delete "sn" yet, since some handlers that use it may be pending (see fdMaybeCleanup())
sn->sd->cancel();
//sn->sd->close();
//d->removeSocketNotifier(sn);
//FIXME: what if we create a new sn on the same fd soon (while handlers are still pending)?
}
//if not all notifiers are unregistered, we don't cancel pending handler, since we cannot do it selectively (i.e. cancel only read or only write)
//however, it's not a problem, since it will notice that sn->revision doesn't match and will "cancel" itself during the next call
}
}
bool QAsioEventDispatcher::processEvents(QEventLoop::ProcessEventsFlags flags)
{
Q_D(QAsioEventDispatcher);
d->interrupt.store(0);
//QCoreApplicationPrivate::sendPostedEvents(0, 0, d->threadData); //unix dispatcher use this
QCoreApplication::sendPostedEvents(); //glib dispatcher call this after every call of "awake".
const bool canWait = (/*d->threadData->canWaitLocked()
&&*/ !d->interrupt.load() //it may have been set during the call of QCoreApplication::sendPostedEvents()
&& (flags & QEventLoop::WaitForMoreEvents));
if (d->interrupt.load())
{
return false; //unix event dispatcher returns false if nothing more than "postedEvents" were dispatched
}
if (!(flags & QEventLoop::X11ExcludeTimers)) {
d->timerStart();
}
int total_events = 0; /* FIXME: +1 for stop? */
if (canWait) {
//run at least one handler - may block
emit aboutToBlock();
d->io_service.reset();
total_events += d->io_service.run_one();
emit awake();
}
int events;
do
{
if (!(flags & QEventLoop::X11ExcludeTimers)) {
d->timerStart();
}
d->io_service.reset();
//run all ready handlers
events = d->io_service.poll();
if ((flags & QEventLoop::ExcludeSocketNotifiers)) {
//FIXME: ignore stream descriptors
}
if ((flags & QEventLoop::X11ExcludeTimers)) {
//FIXME: ignore timers?
}
total_events += events;
QCoreApplication::sendPostedEvents();
total_events += QWindowSystemInterface::sendWindowSystemEvents(flags) ? 1 : 0;
} while(events>0);
d->cleanupSocketNotifiers();
// return true if we handled events, false otherwise
return (total_events > 0);
}
bool QAsioEventDispatcher::hasPendingEvents()
{
//This is copy-pasted from QUnixEventDispatcherQPA. I don't really understand how it works.
extern uint qGlobalPostedEventsCount(); // from qapplication.cpp
return qGlobalPostedEventsCount() || QWindowSystemInterface::windowSystemEventsQueued();
}
void QAsioEventDispatcher::wakeUp()
{
Q_D(QAsioEventDispatcher);
//I don't know what a logic stays behind it, but qeventdispatcher_glib works in such a way, that after every "wakeUp", the following function is called
//io_service.post(QCoreApplication::sendPostedEvents);
d->io_service.stop(); //exit from run_one
}
void QAsioEventDispatcher::interrupt()
{
Q_D(QAsioEventDispatcher);
d->interrupt.store(1);
wakeUp();
}
void QAsioEventDispatcher::flush()
{
/* It does nothing in glib event dispatcher.
*
* QUnixEventDispatcherQPA calls QCoreApplication::instance()->sendPostedEvents here.
*
* But the docs of QAbstractEventDispatcher says:
* "flushes the event queue. This normally returns almost immediately. Does nothing on platforms other than X11"
*
* I'm a bit confused. FIXME
*/
}
QT_END_NAMESPACE
<|endoftext|> |
<commit_before>#include "Halide.h"
using namespace Halide;
#include <image_io.h>
#include <iostream>
#include <limits>
#include <sys/time.h>
double now() {
struct timeval tv;
gettimeofday(&tv, NULL);
static bool first_call = true;
static time_t first_sec = 0;
if (first_call) {
first_call = false;
first_sec = tv.tv_sec;
}
assert(tv.tv_sec >= first_sec);
return (tv.tv_sec - first_sec) + (tv.tv_usec / 1000000.0);
}
enum InterpolationType {
BOX, LINEAR, CUBIC
};
Expr kernel_box(Expr x) {
Expr xx = abs(x);
return select(xx <= 0.5f, 1.0f, 0.0f);
}
Expr kernel_linear(Expr x) {
Expr xx = abs(x);
return select(xx < 1.0f, xx, 0.0f);
}
Expr kernel_cubic(Expr x) {
Expr xx = abs(x);
Expr xx2 = xx * xx;
Expr xx3 = xx2 * xx;
float a = -0.5f;
return select(xx < 1.0f, (a + 2.0f) * xx3 + (a + 3.0f) * xx2 + 1,
select (xx < 2.0f, a * xx3 - 5 * a * xx2 + 8 * a * xx - 4.0f * a,
0.0f));
}
struct KernelInfo {
const char *name;
float size;
Expr (*kernel)(Expr);
};
static KernelInfo kernelInfo[] = {
{ "box", 0.5f, kernel_box },
{ "linear", 1.0f, kernel_linear },
{ "cubic", 2.0f, kernel_cubic }
};
Expr scaled(Expr x, Expr magnification) {
return (x + 0.5f) / magnification;
}
int main(int argc, char **argv) {
std::string infile, outfile;
InterpolationType interpolationType = LINEAR;
float scaleFactor = 1.0f;
bool show_usage = false;
for (int i = 1; i < argc; i++) {
std::string arg = argv[i];
if (arg == "-s" && i+1 < argc) {
scaleFactor = atof(argv[++i]);
} else if (arg == "-t" && i+1 < argc) {
arg = argv[++i];
if (arg == "box") {
interpolationType = BOX;
} else if (arg == "linear") {
interpolationType = LINEAR;
} else if (arg == "cubic") {
interpolationType = CUBIC;
} else {
fprintf(stderr, "Invalid interpolation type '%s' specified.\n",
arg.c_str());
show_usage = true;
}
} else if (infile.empty()) {
infile = arg;
} else if (outfile.empty()) {
outfile = arg;
} else {
fprintf(stderr, "Unexpected command line option '%s'.\n", arg.c_str());
}
}
if (infile.empty() || outfile.empty() || show_usage) {
fprintf(stderr,
"Usage:\n"
"\t./resample [-s scalefactor] [-t box|linear|cubic] in.png out.png\n");
return 1;
}
ImageParam input(Float(32), 3);
Var x("x"), y("y"), c("c"), k("k");
Func clamped("clamped");
clamped(x, y, c) = input(clamp(x, 0, input.width()-1), clamp(y, 0, input.height()-1), c);
// For downscaling, widen the interpolation kernel to perform lowpass
// filtering.
float kernelScaling = (scaleFactor < 1.0f) ? scaleFactor : 1.0f;
float kernelSize = kernelInfo[interpolationType].size / kernelScaling;
// source[xy] are the (non-integer) coordinates inside the source image
Expr sourcex = scaled(x, scaleFactor);
Expr sourcey = scaled(y, scaleFactor);
// Initialize interpolation kernels. Since we allow an arbitrary
// scaleFactor factor, the filter coefficients are different for each x
// and y coordinate.
Func kernelx("kernelx"), kernely("kernely");
Expr beginx = cast<int>(sourcex - kernelSize + 0.5f);
Expr beginy = cast<int>(sourcey - kernelSize + 0.5f);
RDom domx(0, static_cast<int>(2.0f*kernelSize)+1, "domx");
RDom domy(0, static_cast<int>(2.0f*kernelSize)+1, "domy");
{
const KernelInfo &info = kernelInfo[interpolationType];
Func kx, ky;
kx(x, k) = info.kernel((k + beginx - sourcex) * kernelScaling);
ky(y, k) = info.kernel((k + beginy - sourcey) * kernelScaling);
kernelx(x, k) = kx(x, k) / sum(kx(x, domx));
kernely(y, k) = ky(y, k) / sum(ky(y, domy));
}
// Perform separable resizing
Func resized_x("resized_x");
Func resized_y("resized_y");
resized_x(x, y, c) = sum(kernelx(x, domx) * cast<float>(clamped(domx + beginx, y, c)));
resized_y(x, y, c) = sum(kernely(y, domy) * resized_x(x, domy + beginy, c));
Func final("final");
final(x, y, c) = clamp(resized_y(x, y, c), 0.0f, 1.0f);
std::cout << "Finished function setup." << std::endl;
// Scheduling
kernelx.compute_root();
kernely.compute_at(final, y);
resized_x.compute_root();
resized_x.vectorize(x, 4);
final.vectorize(x, 4);
resized_x.parallel(y);
final.parallel(y);
Target target = get_jit_target_from_environment();
final.compile_jit(target);
printf("Loading '%s'\n", infile.c_str());
Image<float> in_png = load<float>(infile);
int out_width = in_png.width() * scaleFactor;
int out_height = in_png.height() * scaleFactor;
Image<float> out(out_width, out_height, 3);
input.set(in_png);
printf("Resampling '%s' from %dx%d to %dx%d using %s interpolation\n",
infile.c_str(),
in_png.width(), in_png.height(),
out_width, out_height,
kernelInfo[interpolationType].name);
double min = std::numeric_limits<double>::infinity();
const unsigned int iters = 20;
for (unsigned int x = 0; x < iters; ++x) {
double before = now();
final.realize(out);
double after = now();
double amt = after - before;
std::cout << " " << amt * 1000 << std::endl;
if (amt < min) min = amt;
}
std::cout << " took " << min * 1000 << " msec." << std::endl;
save(out, outfile);
}
<commit_msg>Add different schedules and redefine '-s' option to switch between them.<commit_after>#include "Halide.h"
using namespace Halide;
#include <image_io.h>
#include <iostream>
#include <limits>
#include <sys/time.h>
double now() {
struct timeval tv;
gettimeofday(&tv, NULL);
static bool first_call = true;
static time_t first_sec = 0;
if (first_call) {
first_call = false;
first_sec = tv.tv_sec;
}
assert(tv.tv_sec >= first_sec);
return (tv.tv_sec - first_sec) + (tv.tv_usec / 1000000.0);
}
enum InterpolationType {
BOX, LINEAR, CUBIC
};
Expr kernel_box(Expr x) {
Expr xx = abs(x);
return select(xx <= 0.5f, 1.0f, 0.0f);
}
Expr kernel_linear(Expr x) {
Expr xx = abs(x);
return select(xx < 1.0f, xx, 0.0f);
}
Expr kernel_cubic(Expr x) {
Expr xx = abs(x);
Expr xx2 = xx * xx;
Expr xx3 = xx2 * xx;
float a = -0.5f;
return select(xx < 1.0f, (a + 2.0f) * xx3 + (a + 3.0f) * xx2 + 1,
select (xx < 2.0f, a * xx3 - 5 * a * xx2 + 8 * a * xx - 4.0f * a,
0.0f));
}
struct KernelInfo {
const char *name;
float size;
Expr (*kernel)(Expr);
};
static KernelInfo kernelInfo[] = {
{ "box", 0.5f, kernel_box },
{ "linear", 1.0f, kernel_linear },
{ "cubic", 2.0f, kernel_cubic }
};
std::string infile, outfile;
InterpolationType interpolationType = LINEAR;
float scaleFactor = 1.0f;
bool show_usage = false;
int schedule = 0;
void parse_commandline(int argc, char **argv) {
for (int i = 1; i < argc; i++) {
std::string arg = argv[i];
if (arg == "-f" && i+1 < argc) {
scaleFactor = atof(argv[++i]);
} else if (arg == "-s" && i+1 < argc) {
schedule = atoi(argv[++i]);
if (schedule < 0 || schedule > 3) {
fprintf(stderr, "Invalid schedule\n");
show_usage = true;
}
} else if (arg == "-t" && i+1 < argc) {
arg = argv[++i];
if (arg == "box") {
interpolationType = BOX;
} else if (arg == "linear") {
interpolationType = LINEAR;
} else if (arg == "cubic") {
interpolationType = CUBIC;
} else {
fprintf(stderr, "Invalid interpolation type '%s' specified.\n",
arg.c_str());
show_usage = true;
}
} else if (infile.empty()) {
infile = arg;
} else if (outfile.empty()) {
outfile = arg;
} else {
fprintf(stderr, "Unexpected command line option '%s'.\n", arg.c_str());
}
}
}
int main(int argc, char **argv) {
parse_commandline(argc, argv);
if (infile.empty() || outfile.empty() || show_usage) {
fprintf(stderr,
"Usage:\n"
"\t./resample [-f scalefactor] [-s schedule] [-t box|linear|cubic] in.png out.png\n"
"\t\tSchedules: 0=default 1=vectorized 2=parallel 3=vectorized+parallel\n");
return 1;
}
ImageParam input(Float(32), 3);
Var x("x"), y("y"), c("c"), k("k");
Func clamped("clamped");
clamped(x, y, c) = input(clamp(x, 0, input.width()-1), clamp(y, 0, input.height()-1), c);
// For downscaling, widen the interpolation kernel to perform lowpass
// filtering.
float kernelScaling = std::min(scaleFactor, 1.0f);
float kernelSize = kernelInfo[interpolationType].size / kernelScaling;
// source[xy] are the (non-integer) coordinates inside the source image
Expr sourcex = (x + 0.5f) / scaleFactor;
Expr sourcey = (y + 0.5f) / scaleFactor;
// Initialize interpolation kernels. Since we allow an arbitrary
// scaling factor, the filter coefficients are different for each x
// and y coordinate.
Func kernelx("kernelx"), kernely("kernely");
Expr beginx = cast<int>(sourcex - kernelSize + 0.5f);
Expr beginy = cast<int>(sourcey - kernelSize + 0.5f);
RDom domx(0, static_cast<int>(2.0f*kernelSize)+1, "domx");
RDom domy(0, static_cast<int>(2.0f*kernelSize)+1, "domy");
{
const KernelInfo &info = kernelInfo[interpolationType];
Func kx, ky;
kx(x, k) = info.kernel((k + beginx - sourcex) * kernelScaling);
ky(y, k) = info.kernel((k + beginy - sourcey) * kernelScaling);
kernelx(x, k) = kx(x, k) / sum(kx(x, domx));
kernely(y, k) = ky(y, k) / sum(ky(y, domy));
}
// Perform separable resizing
Func resized_x("resized_x");
Func resized_y("resized_y");
resized_x(x, y, c) = sum(kernelx(x, domx) * cast<float>(clamped(domx + beginx, y, c)));
resized_y(x, y, c) = sum(kernely(y, domy) * resized_x(x, domy + beginy, c));
Func final("final");
final(x, y, c) = clamp(resized_y(x, y, c), 0.0f, 1.0f);
std::cout << "Finished function setup." << std::endl;
// Scheduling
bool parallelize = (schedule >= 2);
bool vectorize = (schedule == 1 || schedule == 3);
kernelx.compute_root();
kernely.compute_at(final, y);
if (vectorize) {
resized_x.vectorize(x, 4);
final.vectorize(x, 4);
}
if (parallelize) {
resized_x.compute_root();
resized_x.parallel(y);
final.parallel(y);
} else {
// resized_x.store_root().compute_at(final, y);
resized_x.compute_root();
}
Target target = get_jit_target_from_environment();
final.compile_jit(target);
printf("Loading '%s'\n", infile.c_str());
Image<float> in_png = load<float>(infile);
int out_width = in_png.width() * scaleFactor;
int out_height = in_png.height() * scaleFactor;
Image<float> out(out_width, out_height, 3);
input.set(in_png);
printf("Resampling '%s' from %dx%d to %dx%d using %s interpolation\n",
infile.c_str(),
in_png.width(), in_png.height(),
out_width, out_height,
kernelInfo[interpolationType].name);
double min = std::numeric_limits<double>::infinity();
const unsigned int iters = 20;
for (unsigned int x = 0; x < iters; ++x) {
double before = now();
final.realize(out);
double after = now();
double amt = after - before;
std::cout << " " << amt * 1000 << std::endl;
if (amt < min) min = amt;
}
std::cout << " took " << min * 1000 << " msec." << std::endl;
save(out, outfile);
}
<|endoftext|> |
<commit_before>/*
This file is part of KOrganizer.
Copyright (c) 2001 Cornelius Schumacher <schumacher@kde.org>
Copyright (C) 2004 Reinhold Kainhofer <reinhold@kainhofer.com>
Copyright (C) 2005 Thomas Zander <zander@kde.org>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
As a special exception, permission is given to link this program
with any edition of Qt, and distribute the resulting executable,
without including the source code for Qt in the source distribution.
*/
#include <QPushButton>
#include <QCheckBox>
#include <QLineEdit>
#include <QRadioButton>
#include <QList>
#include <kdebug.h>
#include <klocale.h>
#include <kmessagebox.h>
#include <knuminput.h>
#include <kcal/calfilter.h>
#include <libkdepim/categoryselectdialog.h>
#include "koprefs.h"
#include "ui_filteredit_base.h"
#include "filtereditdialog.h"
#include "filtereditdialog.moc"
FilterEditDialog::FilterEditDialog( QList<CalFilter*> *filters, QWidget *parent )
: KDialog( parent)
{
setCaption( i18n("Edit Calendar Filters") );
setButtons( Ok | Apply | Cancel );
setMainWidget( mFilterEdit = new FilterEdit(filters, this));
connect(mFilterEdit, SIGNAL(dataConsistent(bool)),
SLOT(setDialogConsistent(bool)));
updateFilterList();
connect( mFilterEdit, SIGNAL( editCategories() ), SIGNAL( editCategories() ) );
connect( mFilterEdit, SIGNAL( filterChanged() ), SIGNAL( filterChanged() ) );
connect( this, SIGNAL(okClicked()), this, SLOT(slotOk()));
connect( this, SIGNAL(applyClicked()), this, SLOT(slotApply()));
}
FilterEditDialog::~FilterEditDialog()
{
delete mFilterEdit;
mFilterEdit = 0L;
}
void FilterEditDialog::updateFilterList()
{
mFilterEdit->updateFilterList();
}
void FilterEditDialog::updateCategoryConfig()
{
mFilterEdit->updateCategoryConfig();
}
void FilterEditDialog::slotApply()
{
mFilterEdit->saveChanges();
}
void FilterEditDialog::slotOk()
{
slotApply();
accept();
}
void FilterEditDialog::setDialogConsistent(bool consistent) {
enableButton( Ok, consistent );
enableButtonApply( consistent );
}
FilterEdit::FilterEdit(QList<CalFilter*> *filters, QWidget *parent)
: QWidget( parent ), current(0), mCategorySelectDialog( 0 )
{
setupUi( this );
mFilters = filters;
mNewButton->setWhatsThis( i18n( "Press this button to define a new filter." ) );
mDeleteButton->setWhatsThis( i18n( "Press this button to remove the currently active filter." ) );
connect( mRulesList, SIGNAL(itemSelectionChanged()), this, SLOT(filterSelected()) );
connect( mNewButton, SIGNAL( clicked() ), SLOT( bNewPressed() ) );
connect( mDeleteButton, SIGNAL( clicked() ), SLOT( bDeletePressed() ) );
connect( mNameLineEdit, SIGNAL( textChanged(const QString &) ), SLOT( updateSelectedName(const QString &) ) );
connect( mCatEditButton, SIGNAL( clicked() ), SLOT( editCategorySelection() ) );
}
FilterEdit::~FilterEdit() {
}
void FilterEdit::updateFilterList()
{
mRulesList->clear();
if ( !mFilters || mFilters->empty() )
emit( dataConsistent(false) );
else {
QList<CalFilter*>::iterator i;
for ( i = mFilters->begin(); i != mFilters->end(); ++i ) {
if ( *i ) {
mRulesList->addItem( (*i)->name() );
}
}
if( mRulesList->currentRow() != -1 )
{
CalFilter *f = mFilters->at( mRulesList->currentRow() );
if ( f )
filterSelected( f );
}
emit( dataConsistent(true) );
}
if ( mFilters && current == 0L && mFilters->count() > 0 )
filterSelected( mFilters->at(0) );
mDeleteButton->setEnabled( !mFilters->isEmpty() );
}
void FilterEdit::saveChanges()
{
if(current == 0L)
return;
current->setName(mNameLineEdit->text());
int criteria = 0;
if ( mCompletedCheck->isChecked() ) criteria |= CalFilter::HideCompletedTodos;
if ( mRecurringCheck->isChecked() ) criteria |= CalFilter::HideRecurring;
if ( mCatShowCheck->isChecked() ) criteria |= CalFilter::ShowCategories;
if ( mHideInactiveTodosCheck->isChecked() ) criteria |= CalFilter::HideInactiveTodos;
if ( mHideTodosNotAssignedToMeCheck->isChecked() )
criteria |= CalFilter::HideNoMatchingAttendeeTodos;
current->setCriteria( criteria );
current->setCompletedTimeSpan( mCompletedTimeSpan->value() );
QStringList categoryList;
for( int i = 0; i < mCatList->count(); ++i ) {
QListWidgetItem *item = mCatList->item(i);
if ( item ) categoryList.append( item->text() );
}
current->setCategoryList( categoryList );
emit filterChanged();
}
void FilterEdit::filterSelected()
{
filterSelected( mFilters->at(mRulesList->currentRow()) );
}
void FilterEdit::filterSelected(CalFilter *filter)
{
if(filter == current) return;
kDebug(5850) << "Selected filter " << filter->name() << endl;
saveChanges();
current = filter;
mNameLineEdit->blockSignals(true);
mNameLineEdit->setText(current ? current->name() : QString::null);
mNameLineEdit->blockSignals(false);
mDetailsFrame->setEnabled(true);
mCompletedCheck->setChecked( current->criteria() & CalFilter::HideCompletedTodos );
mCompletedTimeSpan->setValue( current->completedTimeSpan() );
mRecurringCheck->setChecked( current->criteria() & CalFilter::HideRecurring );
mHideInactiveTodosCheck->setChecked( current->criteria() & CalFilter::HideInactiveTodos );
mHideTodosNotAssignedToMeCheck->setChecked(
current->criteria() & CalFilter::HideNoMatchingAttendeeTodos );
if ( current->criteria() & CalFilter::ShowCategories ) {
mCatShowCheck->setChecked( true );
} else {
mCatHideCheck->setChecked( true );
}
mCatList->clear();
mCatList->addItems( current->categoryList() );
}
void FilterEdit::bNewPressed() {
CalFilter *newFilter = new CalFilter( i18n("New Filter %1", mFilters->count()) );
mFilters->append( newFilter );
updateFilterList();
mRulesList->setCurrentRow( mRulesList->count()-1 );
emit filterChanged();
}
void FilterEdit::bDeletePressed() {
if ( !mRulesList->currentItem() ) return; // nothing selected
if ( mFilters->isEmpty() ) return; // We need at least a default filter object.
int result = KMessageBox::warningContinueCancel( this,
i18n("This item will be permanently deleted."), i18n("Delete Confirmation"), KGuiItem(i18n("Delete"),"edit-delete") );
if ( result != KMessageBox::Continue )
return;
int selected = mRulesList->currentRow();
CalFilter *filter = mFilters->at( selected );
mFilters->removeAll( filter );
delete filter;
current = 0L;
updateFilterList();
mRulesList->setCurrentRow( qMin(mRulesList->count()-1, selected) );
emit filterChanged();
}
void FilterEdit::updateSelectedName(const QString &newText) {
mRulesList->blockSignals( true );
QListWidgetItem *item = mRulesList->currentItem();
if ( item ) item->setText( newText );
mRulesList->blockSignals( false );
bool allOk = true;
foreach ( CalFilter *i, *mFilters ) {
if ( i && i->name().isEmpty() ) allOk = false;
}
emit dataConsistent(allOk);
}
void FilterEdit::editCategorySelection()
{
if( !current ) return;
if ( !mCategorySelectDialog ) {
mCategorySelectDialog = new KPIM::CategorySelectDialog( KOPrefs::instance(), this, "filterCatSelect" );
connect( mCategorySelectDialog,
SIGNAL( categoriesSelected( const QStringList & ) ),
SLOT( updateCategorySelection( const QStringList & ) ) );
connect( mCategorySelectDialog, SIGNAL( editCategories() ),
SIGNAL( editCategories() ) );
}
// we need the children not to autoselect or else some unselected
// children can also become selected
mCategorySelectDialog->setAutoselectChildren( false );
mCategorySelectDialog->setSelected( current->categoryList() );
mCategorySelectDialog->setAutoselectChildren( true );
mCategorySelectDialog->show();
}
void FilterEdit::updateCategorySelection( const QStringList &categories )
{
mCatList->clear();
mCatList->addItems( categories );
current->setCategoryList(categories);
}
void FilterEdit::updateCategoryConfig()
{
if ( mCategorySelectDialog ) mCategorySelectDialog->updateCategoryConfig();
}
<commit_msg>Readd signal/slot which was missing during port<commit_after>/*
This file is part of KOrganizer.
Copyright (c) 2001 Cornelius Schumacher <schumacher@kde.org>
Copyright (C) 2004 Reinhold Kainhofer <reinhold@kainhofer.com>
Copyright (C) 2005 Thomas Zander <zander@kde.org>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
As a special exception, permission is given to link this program
with any edition of Qt, and distribute the resulting executable,
without including the source code for Qt in the source distribution.
*/
#include <QPushButton>
#include <QCheckBox>
#include <QLineEdit>
#include <QRadioButton>
#include <QList>
#include <kdebug.h>
#include <klocale.h>
#include <kmessagebox.h>
#include <knuminput.h>
#include <kcal/calfilter.h>
#include <libkdepim/categoryselectdialog.h>
#include "koprefs.h"
#include "ui_filteredit_base.h"
#include "filtereditdialog.h"
#include "filtereditdialog.moc"
FilterEditDialog::FilterEditDialog( QList<CalFilter*> *filters, QWidget *parent )
: KDialog( parent)
{
setCaption( i18n("Edit Calendar Filters") );
setButtons( Ok | Apply | Cancel );
setMainWidget( mFilterEdit = new FilterEdit(filters, this));
connect(mFilterEdit, SIGNAL(dataConsistent(bool)),
SLOT(setDialogConsistent(bool)));
updateFilterList();
connect( mFilterEdit, SIGNAL( editCategories() ), SIGNAL( editCategories() ) );
connect( mFilterEdit, SIGNAL( filterChanged() ), SIGNAL( filterChanged() ) );
connect( this, SIGNAL(okClicked()), this, SLOT(slotOk()));
connect( this, SIGNAL(applyClicked()), this, SLOT(slotApply()));
}
FilterEditDialog::~FilterEditDialog()
{
delete mFilterEdit;
mFilterEdit = 0L;
}
void FilterEditDialog::updateFilterList()
{
mFilterEdit->updateFilterList();
}
void FilterEditDialog::updateCategoryConfig()
{
mFilterEdit->updateCategoryConfig();
}
void FilterEditDialog::slotApply()
{
mFilterEdit->saveChanges();
}
void FilterEditDialog::slotOk()
{
slotApply();
accept();
}
void FilterEditDialog::setDialogConsistent(bool consistent) {
enableButton( Ok, consistent );
enableButtonApply( consistent );
}
FilterEdit::FilterEdit(QList<CalFilter*> *filters, QWidget *parent)
: QWidget( parent ), current(0), mCategorySelectDialog( 0 )
{
setupUi( this );
mFilters = filters;
mNewButton->setWhatsThis( i18n( "Press this button to define a new filter." ) );
mDeleteButton->setWhatsThis( i18n( "Press this button to remove the currently active filter." ) );
connect( mRulesList, SIGNAL(itemSelectionChanged()), this, SLOT(filterSelected()) );
connect( mNewButton, SIGNAL( clicked() ), SLOT( bNewPressed() ) );
connect( mDeleteButton, SIGNAL( clicked() ), SLOT( bDeletePressed() ) );
connect( mNameLineEdit, SIGNAL( textChanged(const QString &) ), SLOT( updateSelectedName(const QString &) ) );
connect( mCatEditButton, SIGNAL( clicked() ), SLOT( editCategorySelection() ) );
connect( mCompletedCheck, SIGNAL(toggled(bool)), mCompletedTimeSpanLabel, SLOT(setEnabled(bool)));
connect( mCompletedCheck, SIGNAL(toggled(bool)), mCompletedTimeSpan, SLOT(setEnabled(bool)));
}
FilterEdit::~FilterEdit() {
}
void FilterEdit::updateFilterList()
{
mRulesList->clear();
if ( !mFilters || mFilters->empty() )
emit( dataConsistent(false) );
else {
QList<CalFilter*>::iterator i;
for ( i = mFilters->begin(); i != mFilters->end(); ++i ) {
if ( *i ) {
mRulesList->addItem( (*i)->name() );
}
}
if( mRulesList->currentRow() != -1 )
{
CalFilter *f = mFilters->at( mRulesList->currentRow() );
if ( f )
filterSelected( f );
}
emit( dataConsistent(true) );
}
if ( mFilters && current == 0L && mFilters->count() > 0 )
filterSelected( mFilters->at(0) );
mDeleteButton->setEnabled( !mFilters->isEmpty() );
}
void FilterEdit::saveChanges()
{
if(current == 0L)
return;
current->setName(mNameLineEdit->text());
int criteria = 0;
if ( mCompletedCheck->isChecked() ) criteria |= CalFilter::HideCompletedTodos;
if ( mRecurringCheck->isChecked() ) criteria |= CalFilter::HideRecurring;
if ( mCatShowCheck->isChecked() ) criteria |= CalFilter::ShowCategories;
if ( mHideInactiveTodosCheck->isChecked() ) criteria |= CalFilter::HideInactiveTodos;
if ( mHideTodosNotAssignedToMeCheck->isChecked() )
criteria |= CalFilter::HideNoMatchingAttendeeTodos;
current->setCriteria( criteria );
current->setCompletedTimeSpan( mCompletedTimeSpan->value() );
QStringList categoryList;
for( int i = 0; i < mCatList->count(); ++i ) {
QListWidgetItem *item = mCatList->item(i);
if ( item ) categoryList.append( item->text() );
}
current->setCategoryList( categoryList );
emit filterChanged();
}
void FilterEdit::filterSelected()
{
filterSelected( mFilters->at(mRulesList->currentRow()) );
}
void FilterEdit::filterSelected(CalFilter *filter)
{
if(filter == current) return;
kDebug(5850) << "Selected filter " << filter->name() << endl;
saveChanges();
current = filter;
mNameLineEdit->blockSignals(true);
mNameLineEdit->setText(current ? current->name() : QString::null);
mNameLineEdit->blockSignals(false);
mDetailsFrame->setEnabled(true);
mCompletedCheck->setChecked( current->criteria() & CalFilter::HideCompletedTodos );
mCompletedTimeSpan->setValue( current->completedTimeSpan() );
mRecurringCheck->setChecked( current->criteria() & CalFilter::HideRecurring );
mHideInactiveTodosCheck->setChecked( current->criteria() & CalFilter::HideInactiveTodos );
mHideTodosNotAssignedToMeCheck->setChecked(
current->criteria() & CalFilter::HideNoMatchingAttendeeTodos );
if ( current->criteria() & CalFilter::ShowCategories ) {
mCatShowCheck->setChecked( true );
} else {
mCatHideCheck->setChecked( true );
}
mCatList->clear();
mCatList->addItems( current->categoryList() );
}
void FilterEdit::bNewPressed() {
CalFilter *newFilter = new CalFilter( i18n("New Filter %1", mFilters->count()) );
mFilters->append( newFilter );
updateFilterList();
mRulesList->setCurrentRow( mRulesList->count()-1 );
emit filterChanged();
}
void FilterEdit::bDeletePressed() {
if ( !mRulesList->currentItem() ) return; // nothing selected
if ( mFilters->isEmpty() ) return; // We need at least a default filter object.
int result = KMessageBox::warningContinueCancel( this,
i18n("This item will be permanently deleted."), i18n("Delete Confirmation"), KGuiItem(i18n("Delete"),"edit-delete") );
if ( result != KMessageBox::Continue )
return;
int selected = mRulesList->currentRow();
CalFilter *filter = mFilters->at( selected );
mFilters->removeAll( filter );
delete filter;
current = 0L;
updateFilterList();
mRulesList->setCurrentRow( qMin(mRulesList->count()-1, selected) );
emit filterChanged();
}
void FilterEdit::updateSelectedName(const QString &newText) {
mRulesList->blockSignals( true );
QListWidgetItem *item = mRulesList->currentItem();
if ( item ) item->setText( newText );
mRulesList->blockSignals( false );
bool allOk = true;
foreach ( CalFilter *i, *mFilters ) {
if ( i && i->name().isEmpty() ) allOk = false;
}
emit dataConsistent(allOk);
}
void FilterEdit::editCategorySelection()
{
if( !current ) return;
if ( !mCategorySelectDialog ) {
mCategorySelectDialog = new KPIM::CategorySelectDialog( KOPrefs::instance(), this, "filterCatSelect" );
connect( mCategorySelectDialog,
SIGNAL( categoriesSelected( const QStringList & ) ),
SLOT( updateCategorySelection( const QStringList & ) ) );
connect( mCategorySelectDialog, SIGNAL( editCategories() ),
SIGNAL( editCategories() ) );
}
// we need the children not to autoselect or else some unselected
// children can also become selected
mCategorySelectDialog->setAutoselectChildren( false );
mCategorySelectDialog->setSelected( current->categoryList() );
mCategorySelectDialog->setAutoselectChildren( true );
mCategorySelectDialog->show();
}
void FilterEdit::updateCategorySelection( const QStringList &categories )
{
mCatList->clear();
mCatList->addItems( categories );
current->setCategoryList(categories);
}
void FilterEdit::updateCategoryConfig()
{
if ( mCategorySelectDialog ) mCategorySelectDialog->updateCategoryConfig();
}
<|endoftext|> |
<commit_before>
#include "NNApplication.h"
#include "NNAudioSystem.h"
#include "SpriteExample.h"
#include "LabelExample.h"
#include "SoundExample.h"
#include "InputExample.h"
#include "CustomObjectExample.h"
#include "MainMenuScene.h"
#include "PlayScene.h"
#include "ReturnScene.h"
int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpszCmdParam, int nShowCmd )
{
#ifdef _DEBUG
_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF|_CRTDBG_LEAK_CHECK_DF);
//_CrtSetBreakAlloc( );
AllocConsole();
FILE* pStream;
freopen_s( &pStream, "CONOUT$", "wt", stdout );
#endif
NNApplication* Application = NNApplication::GetInstance();
Application->Init( L"JuGums", 1000, 700, D2D );
// Sprite Example
// NNSceneDirector::GetInstance()->ChangeScene( SpriteExample::Create() );
// Label Example
// NNSceneDirector::GetInstance()->ChangeScene( LabelExample::Create() );
// Input Example
// NNSceneDirector::GetInstance()->ChangeScene( InputExample::Create() );
// Sound Example
// NNSceneDirector::GetInstance()->ChangeScene( SoundExample::Create() );
// CustomObject Example
// NNSceneDirector::GetInstance()->ChangeScene( CustomObjectExample::Create() );
// TestMenuScene
NNSceneDirector::GetInstance()->ChangeScene( CMainMenuScene::Create() );
// Playtest
// NNSceneDirector::GetInstance()->ChangeScene( CPlaytest::Create() );
// ReturnScene
// NNSceneDirector::GetInstance()->ChangeScene( CReturnScene::Create() );
Application->Run();
Application->Release();
// for debugging
FreeConsole();
return 0;
}<commit_msg>main 에서 필요없는 라인(example실행코드) 삭제<commit_after>
#include "NNApplication.h"
#include "NNAudioSystem.h"
#include "SpriteExample.h"
#include "LabelExample.h"
#include "SoundExample.h"
#include "InputExample.h"
#include "CustomObjectExample.h"
#include "MainMenuScene.h"
#include "PlayScene.h"
#include "ReturnScene.h"
int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpszCmdParam, int nShowCmd )
{
#ifdef _DEBUG
_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF|_CRTDBG_LEAK_CHECK_DF);
//_CrtSetBreakAlloc( );
AllocConsole();
FILE* pStream;
freopen_s( &pStream, "CONOUT$", "wt", stdout );
#endif
NNApplication* Application = NNApplication::GetInstance();
Application->Init( L"JuGums", 1000, 700, D2D );
NNSceneDirector::GetInstance()->ChangeScene( CMainMenuScene::Create() );
Application->Run();
Application->Release();
// for debugging
FreeConsole();
return 0;
}<|endoftext|> |
<commit_before>#ifndef ORG_EEROS_CONTROL_I_HPP_
#define ORG_EEROS_CONTROL_I_HPP_
#include <eeros/control/Block1i1o.hpp>
namespace eeros {
namespace control {
template < typename T = double >
class I: public Block1i1o<T> {
public:
I() : first(true), enabled(false) { prev.clear(); clearLimits(); }
virtual void run() {
if(first) { // first run, set output to init condition
this->out.getSignal().setValue(this->prev.getValue());
this->out.getSignal().setTimestamp(this->in.getSignal().getTimestamp());
this->prev.setTimestamp(this->out.getSignal().getTimestamp());
first = false;
}
else {
double tin = this->in.getSignal().getTimestamp() / 1000000000.0;
double tprev = this->prev.getTimestamp() / 1000000000.0;
double dt = (tin - tprev);
T valin = this->in.getSignal().getValue();
T valprev = this->prev.getValue();
T output;
if(enabled)
output = valprev + valin * dt;
else
output = valprev;
if (output > upperLimit) output = upperLimit;
if (output < lowerLimit) output = lowerLimit;
this->out.getSignal().setValue(output);
this->out.getSignal().setTimestamp(this->in.getSignal().getTimestamp());
this->prev = this->out.getSignal();
}
}
virtual void enable() {
this->enabled = true;
}
virtual void disable() {
this->enabled = false;
}
virtual void setInitCondition(T val) {
this->prev.setValue(val);
}
virtual void setLimit(T upper, T lower) {
this->upperLimit = upper;
this->lowerLimit = lower;
T val = prev.getValue();
if (val > upper) prev.setValue(upper);
if (val < lower) prev.setValue(lower);
}
protected:
bool first;
bool enabled;
Signal<T> prev;
T upperLimit, lowerLimit;
private:
virtual void clearLimits() {
_clear<T>();
}
template <typename S> typename std::enable_if<std::is_integral<S>::value>::type _clear() {
upperLimit = std::numeric_limits<int32_t>::max();
lowerLimit = std::numeric_limits<int32_t>::min();
}
template <typename S> typename std::enable_if<std::is_floating_point<S>::value>::type _clear() {
upperLimit = std::numeric_limits<double>::max();
lowerLimit = std::numeric_limits<double>::min();
}
template <typename S> typename std::enable_if<!std::is_arithmetic<S>::value && std::is_integral<typename S::value_type>::value>::type _clear() {
upperLimit.fill(std::numeric_limits<int32_t>::max());
lowerLimit.fill(std::numeric_limits<int32_t>::min());
}
template <typename S> typename std::enable_if< !std::is_arithmetic<S>::value && std::is_floating_point<typename S::value_type>::value>::type _clear() {
upperLimit.fill(std::numeric_limits<double>::max());
lowerLimit.fill(std::numeric_limits<double>::min());
}
};
/********** Print functions **********/
template <typename T>
std::ostream& operator<<(std::ostream& os, I<T>& i) {
os << "Block integrator: '" << i.getName();
}
};
};
#endif /* ORG_EEROS_CONTROL_I_HPP_ */
<commit_msg>comment limits out<commit_after>#ifndef ORG_EEROS_CONTROL_I_HPP_
#define ORG_EEROS_CONTROL_I_HPP_
#include <eeros/control/Block1i1o.hpp>
namespace eeros {
namespace control {
template < typename T = double >
class I: public Block1i1o<T> {
public:
I() : first(true), enabled(false) { prev.clear(); clearLimits(); }
virtual void run() {
if(first) { // first run, set output to init condition
this->out.getSignal().setValue(this->prev.getValue());
this->out.getSignal().setTimestamp(this->in.getSignal().getTimestamp());
this->prev.setTimestamp(this->out.getSignal().getTimestamp());
first = false;
}
else {
double tin = this->in.getSignal().getTimestamp() / 1000000000.0;
double tprev = this->prev.getTimestamp() / 1000000000.0;
double dt = (tin - tprev);
T valin = this->in.getSignal().getValue();
T valprev = this->prev.getValue();
T output;
if(enabled)
output = valprev + valin * dt;
else
output = valprev;
// if (output > upperLimit) output = upperLimit;
// if (output < lowerLimit) output = lowerLimit;
this->out.getSignal().setValue(output);
this->out.getSignal().setTimestamp(this->in.getSignal().getTimestamp());
this->prev = this->out.getSignal();
}
}
virtual void enable() {
this->enabled = true;
}
virtual void disable() {
this->enabled = false;
}
virtual void setInitCondition(T val) {
this->prev.setValue(val);
}
virtual void setLimit(T upper, T lower) {
this->upperLimit = upper;
this->lowerLimit = lower;
T val = prev.getValue();
if (val > upper) prev.setValue(upper);
if (val < lower) prev.setValue(lower);
}
protected:
bool first;
bool enabled;
Signal<T> prev;
T upperLimit, lowerLimit;
private:
virtual void clearLimits() {
_clear<T>();
}
template <typename S> typename std::enable_if<std::is_integral<S>::value>::type _clear() {
upperLimit = std::numeric_limits<int32_t>::max();
lowerLimit = std::numeric_limits<int32_t>::min();
}
template <typename S> typename std::enable_if<std::is_floating_point<S>::value>::type _clear() {
upperLimit = std::numeric_limits<double>::max();
lowerLimit = std::numeric_limits<double>::min();
}
template <typename S> typename std::enable_if<!std::is_arithmetic<S>::value && std::is_integral<typename S::value_type>::value>::type _clear() {
upperLimit.fill(std::numeric_limits<int32_t>::max());
lowerLimit.fill(std::numeric_limits<int32_t>::min());
}
template <typename S> typename std::enable_if< !std::is_arithmetic<S>::value && std::is_floating_point<typename S::value_type>::value>::type _clear() {
upperLimit.fill(std::numeric_limits<double>::max());
lowerLimit.fill(std::numeric_limits<double>::min());
}
};
/********** Print functions **********/
template <typename T>
std::ostream& operator<<(std::ostream& os, I<T>& i) {
os << "Block integrator: '" << i.getName();
}
};
};
#endif /* ORG_EEROS_CONTROL_I_HPP_ */
<|endoftext|> |
<commit_before>#include <iostream>
#include <string>
#include "glad/glad.h"
#include <GLFW/glfw3.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#define COLOR_INC_VALUE 3;
std::string vert_shader =
R"***(
#version 440
in vec2 position;
void main()
{
gl_Position = vec4(position, 0.0, 1.0);
}
)***";
std::string frag_shader =
R"***(
#version 440
// Uniforms
uniform vec3 triangleColor;
uniform float time;
out vec4 outColor;
vec3 light = vec3(800.0, 450.0, 200.0);
float intersect(vec3 ray, vec3 dir, vec3 center, float radius)
{
vec3 oc = center - ray;
float dot_loc = dot(dir, oc);
float lsq = dot(dir, dir);
float discriminant = (dot_loc * dot_loc) - lsq * (dot(oc, oc) - (radius * radius));
if (discriminant < 0.0) {
return -1.0;
}
float i0 = (-dot_loc - sqrt(discriminant)) / lsq;
if (i0 >= 0.0) {
return i0;
}
float i1 = (-dot_loc + sqrt(discriminant)) / lsq;
return i1;
}
void main()
{
outColor = vec4(triangleColor, 1.0);
vec3 spherePos = vec3(800.0, 450.0, -20.0);
float sphereRadius = 175.0;
light.x = light.x + 100 * sin(mod(time, 60.0) * 3.14);
light.y = light.y + 100 * cos(mod(time, 60.0) * 3.14);
//light.z = light.z + 10 * sin(mod(time, 60.0) * 3.14) + 10 * cos(mod(time, 60.0) * 3.14);
if (length(gl_FragCoord.xyz - spherePos) > sphereRadius)
discard;
vec3 rayOrigin = gl_FragCoord.xyz;
rayOrigin.z = 0.0;
vec3 rayDir = normalize(vec3(0.0, 0.0, -1.0));
float t = intersect(rayOrigin, rayDir, spherePos, sphereRadius);
if (t < 0.0) {
outColor = 0.5 * vec4(triangleColor, 1.0);
return;
}
vec3 intersectionPoint = rayOrigin + t * rayDir;
vec3 sphereNormal = normalize(intersectionPoint - spherePos);
rayDir = normalize(rayOrigin - intersectionPoint);
rayDir = reflect(rayDir, sphereNormal);
float intensity = dot(sphereNormal, intersectionPoint - light) * .2;
outColor = vec4((intensity / 100.0) * triangleColor, 1.0);
}
)***";
int main()
{
// GLFW3 init stuff
glfwInit();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);
GLFWwindow* window = glfwCreateWindow(1600, 900, "Ray Tracing Screensaver", glfwGetPrimaryMonitor(), nullptr);
glfwMakeContextCurrent(window);
//glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
// GLAD init stuff
if (!gladLoadGL()) {
std::cout << "Failed to initialize OpenGL context" << std::endl;
return -1;
}
float vertices[] = {
-1.0f, 1.0f, // Top Left Corner
1.0f, 1.0f, // Top Right Corner
1.0f, -1.0f, // Bottom Right Corner
-1.0f, -1.0f // Bottom Left Corner
};
// generate vertex buffer object
GLuint vbo;
glGenBuffers(1, &vbo);
// make vbo the active buffer
glBindBuffer(GL_ARRAY_BUFFER, vbo);
// copy vertices to active buffer
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
// vertex shader
GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER);
const GLchar* vs = vert_shader.c_str();
glShaderSource(vertexShader, 1, &vs, NULL);
glCompileShader(vertexShader);
// check vertex shader compile status
GLint status;
glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &status);
if (status != GL_TRUE) {
char buffer[512];
glGetShaderInfoLog(vertexShader, 512, NULL, buffer);
std::cout << buffer << std::endl;
glfwTerminate();
return 0;
}
// fragment shader
GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
const GLchar* fs = frag_shader.c_str();
glShaderSource(fragmentShader, 1, &fs, NULL);
glCompileShader(fragmentShader);
// check fragment shader compile status
glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &status);
if (status != GL_TRUE) {
char buffer[512];
glGetShaderInfoLog(fragmentShader, 512, NULL, buffer);
std::cout << buffer << std::endl;
glfwTerminate();
return 0;
}
// create shader program
GLuint shaderProgram = glCreateProgram();
glAttachShader(shaderProgram, vertexShader);
glAttachShader(shaderProgram, fragmentShader);
glLinkProgram(shaderProgram);
glUseProgram(shaderProgram);
GLint uniColor = glGetUniformLocation(shaderProgram, "triangleColor");
GLint time = glGetUniformLocation(shaderProgram, "time");
// setup vertex array object (attribute object)
GLuint vao;
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);
GLint posAttrib = glGetAttribLocation(shaderProgram, "position");
glVertexAttribPointer(posAttrib, 2, GL_FLOAT, GL_FALSE, 0, 0);
glEnableVertexAttribArray(posAttrib);
unsigned int r = 50, g = 50, b = 50;
double startTime = glfwGetTime();
enum {
redUp,
redDown,
greenUp,
greenDown,
blueUp,
blueDown
} color_inc_state = redUp;
while (!glfwWindowShouldClose(window)) {
// handle events
if (glfwGetKey(window, GLFW_KEY_ESCAPE) || glfwGetKey(window, GLFW_KEY_ENTER) || glfwGetKey(window, GLFW_KEY_SPACE)) {
glfwSetWindowShouldClose(window, GL_TRUE);
} else if (glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_LEFT) || glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_RIGHT)) {
glfwSetWindowShouldClose(window, GL_TRUE);
}
if (glfwGetTime() - startTime > 0.032) {
startTime = glfwGetTime();
switch (color_inc_state) {
case redUp:
if (r >= 255) {
r = 255;
color_inc_state = redDown;
} else {
r += COLOR_INC_VALUE;
}
break;
case redDown:
if (r <= 50) {
r = 50;
color_inc_state = greenUp;
} else {
r -= COLOR_INC_VALUE;
}
break;
case greenUp:
if (g >= 255) {
g = 255;
color_inc_state = greenDown;
} else {
g += COLOR_INC_VALUE;
}
break;
case greenDown:
if (g <= 50) {
g = 50;
color_inc_state = blueUp;
} else {
g -= COLOR_INC_VALUE;
}
break;
case blueUp:
if (b >= 255) {
b = 255;
color_inc_state = blueDown;
} else {
b += COLOR_INC_VALUE;
}
break;
case blueDown:
if (b <= 50) {
b = 50;
color_inc_state = redUp;
} else {
b -= COLOR_INC_VALUE;
}
break;
default:
break;
}
// rendering
//// make vbo the active buffer
glBindBuffer(GL_ARRAY_BUFFER, vbo);
//// copy vertices to active buffer
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
glUseProgram(shaderProgram);
//// actual drawing
glClear(GL_COLOR_BUFFER_BIT);
glUniform3f(uniColor, (float)r / 255.0f, (float)g / 255.0f, (float)b / 255.0f);
glUniform1f(time, (float)glfwGetTime());
glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
// swapping buffers and polling input
glfwSwapBuffers(window);
}
glfwPollEvents();
}
glfwTerminate();
return 0;
}
<commit_msg>added glfw-style error handling<commit_after>#include <iostream>
#include <string>
#include "glad/glad.h"
#include <GLFW/glfw3.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#define COLOR_INC_VALUE 3;
std::string vert_shader =
R"***(
#version 440
in vec2 position;
void main()
{
gl_Position = vec4(position, 0.0, 1.0);
}
)***";
std::string frag_shader =
R"***(
#version 440
// Uniforms
uniform vec3 triangleColor;
uniform float time;
out vec4 outColor;
vec3 light = vec3(800.0, 450.0, 200.0);
float intersect(vec3 ray, vec3 dir, vec3 center, float radius)
{
vec3 oc = center - ray;
float dot_loc = dot(dir, oc);
float lsq = dot(dir, dir);
float discriminant = (dot_loc * dot_loc) - lsq * (dot(oc, oc) - (radius * radius));
if (discriminant < 0.0) {
return -1.0;
}
float i0 = (-dot_loc - sqrt(discriminant)) / lsq;
if (i0 >= 0.0) {
return i0;
}
float i1 = (-dot_loc + sqrt(discriminant)) / lsq;
return i1;
}
void main()
{
outColor = vec4(triangleColor, 1.0);
vec3 spherePos = vec3(800.0, 450.0, -20.0);
float sphereRadius = 175.0;
light.x = light.x + 100 * sin(mod(time, 60.0) * 3.14);
light.y = light.y + 100 * cos(mod(time, 60.0) * 3.14);
//light.z = light.z + 10 * sin(mod(time, 60.0) * 3.14) + 10 * cos(mod(time, 60.0) * 3.14);
if (length(gl_FragCoord.xyz - spherePos) > sphereRadius)
discard;
vec3 rayOrigin = gl_FragCoord.xyz;
rayOrigin.z = 0.0;
vec3 rayDir = normalize(vec3(0.0, 0.0, -1.0));
float t = intersect(rayOrigin, rayDir, spherePos, sphereRadius);
if (t < 0.0) {
outColor = 0.5 * vec4(triangleColor, 1.0);
return;
}
vec3 intersectionPoint = rayOrigin + t * rayDir;
vec3 sphereNormal = normalize(intersectionPoint - spherePos);
rayDir = normalize(rayOrigin - intersectionPoint);
rayDir = reflect(rayDir, sphereNormal);
float intensity = dot(sphereNormal, intersectionPoint - light) * .2;
outColor = vec4((intensity / 100.0) * triangleColor, 1.0);
}
)***";
extern "C" void error_callback(int error, const char* description)
{
std::cout << "ERROR " << error << " -- " << description << std::endl;;
}
int main()
{
// GLFW3 init stuff
glfwInit();
glfwSetErrorCallback(error_callback);
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);
GLFWwindow* window = glfwCreateWindow(1600, 900, "Ray Tracing Screensaver", glfwGetPrimaryMonitor(), nullptr);
if (!window) {
std::cout << "Failed to create window" << std::endl;
glfwTerminate();
return -1;
}
glfwMakeContextCurrent(window);
//glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
// GLAD init stuff
if (!gladLoadGL()) {
std::cout << "Failed to initialize OpenGL context" << std::endl;
return -1;
}
float vertices[] = {
-1.0f, 1.0f, // Top Left Corner
1.0f, 1.0f, // Top Right Corner
1.0f, -1.0f, // Bottom Right Corner
-1.0f, -1.0f // Bottom Left Corner
};
// generate vertex buffer object
GLuint vbo;
glGenBuffers(1, &vbo);
// make vbo the active buffer
glBindBuffer(GL_ARRAY_BUFFER, vbo);
// copy vertices to active buffer
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
// vertex shader
GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER);
const GLchar* vs = vert_shader.c_str();
glShaderSource(vertexShader, 1, &vs, NULL);
glCompileShader(vertexShader);
// check vertex shader compile status
GLint status;
glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &status);
if (status != GL_TRUE) {
char buffer[512];
glGetShaderInfoLog(vertexShader, 512, NULL, buffer);
std::cout << buffer << std::endl;
glfwTerminate();
return 0;
}
// fragment shader
GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
const GLchar* fs = frag_shader.c_str();
glShaderSource(fragmentShader, 1, &fs, NULL);
glCompileShader(fragmentShader);
// check fragment shader compile status
glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &status);
if (status != GL_TRUE) {
char buffer[512];
glGetShaderInfoLog(fragmentShader, 512, NULL, buffer);
std::cout << buffer << std::endl;
glfwTerminate();
return 0;
}
// create shader program
GLuint shaderProgram = glCreateProgram();
glAttachShader(shaderProgram, vertexShader);
glAttachShader(shaderProgram, fragmentShader);
glLinkProgram(shaderProgram);
glUseProgram(shaderProgram);
GLint uniColor = glGetUniformLocation(shaderProgram, "triangleColor");
GLint time = glGetUniformLocation(shaderProgram, "time");
// setup vertex array object (attribute object)
GLuint vao;
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);
GLint posAttrib = glGetAttribLocation(shaderProgram, "position");
glVertexAttribPointer(posAttrib, 2, GL_FLOAT, GL_FALSE, 0, 0);
glEnableVertexAttribArray(posAttrib);
unsigned int r = 50, g = 50, b = 50;
double startTime = glfwGetTime();
enum {
redUp,
redDown,
greenUp,
greenDown,
blueUp,
blueDown
} color_inc_state = redUp;
while (!glfwWindowShouldClose(window)) {
// handle events
if (glfwGetKey(window, GLFW_KEY_ESCAPE) || glfwGetKey(window, GLFW_KEY_ENTER) || glfwGetKey(window, GLFW_KEY_SPACE)) {
glfwSetWindowShouldClose(window, GL_TRUE);
} else if (glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_LEFT) || glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_RIGHT)) {
glfwSetWindowShouldClose(window, GL_TRUE);
}
if (glfwGetTime() - startTime > 0.032) {
startTime = glfwGetTime();
switch (color_inc_state) {
case redUp:
if (r >= 255) {
r = 255;
color_inc_state = redDown;
} else {
r += COLOR_INC_VALUE;
}
break;
case redDown:
if (r <= 50) {
r = 50;
color_inc_state = greenUp;
} else {
r -= COLOR_INC_VALUE;
}
break;
case greenUp:
if (g >= 255) {
g = 255;
color_inc_state = greenDown;
} else {
g += COLOR_INC_VALUE;
}
break;
case greenDown:
if (g <= 50) {
g = 50;
color_inc_state = blueUp;
} else {
g -= COLOR_INC_VALUE;
}
break;
case blueUp:
if (b >= 255) {
b = 255;
color_inc_state = blueDown;
} else {
b += COLOR_INC_VALUE;
}
break;
case blueDown:
if (b <= 50) {
b = 50;
color_inc_state = redUp;
} else {
b -= COLOR_INC_VALUE;
}
break;
default:
break;
}
// rendering
//// make vbo the active buffer
glBindBuffer(GL_ARRAY_BUFFER, vbo);
//// copy vertices to active buffer
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
glUseProgram(shaderProgram);
//// actual drawing
glClear(GL_COLOR_BUFFER_BIT);
glUniform3f(uniColor, (float)r / 255.0f, (float)g / 255.0f, (float)b / 255.0f);
glUniform1f(time, (float)glfwGetTime());
glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
// swapping buffers and polling input
glfwSwapBuffers(window);
}
glfwPollEvents();
}
glfwTerminate();
return 0;
}
<|endoftext|> |
<commit_before>#include "apps_starter.h"
std::vector<job> apps_vect; // Определение вектора запущенных программ
struct termios hos_tmode; // настройки терминала для hos
void sighandler(int signo)
{
if (signo == SIGTSTP) {
}
if (signo == SIGINT) {
}
}
void fg_job(job &j)
{
int status;
std::vector<job>::iterator it;
j.running = true;
tcsetpgrp(STDIN_FILENO, j.pid);
kill(-j.pid, SIGCONT);
waitpid(j.pid, &status, WUNTRACED);
if(WIFSTOPPED(status)) {
j.running = false;
tcsetpgrp(STDIN_FILENO, getpid());
tcgetattr(STDIN_FILENO, &j.tmode);
tcsetattr(STDIN_FILENO, TCSADRAIN, &hos_tmode);
}
if(WIFEXITED(status)) {
tcsetpgrp(STDIN_FILENO, getpid());
tcsetattr(STDIN_FILENO, TCSADRAIN, &hos_tmode);
for(it = apps_vect.begin() ; it != apps_vect.end(); it++)
if (it->pid == j.pid)
apps_vect.erase(it);
}
}
void bg_jobs(job &j)
{
j.running = true;
kill(-j.pid, SIGCONT);
}
void init_signals()
{
signal(SIGINT, &sighandler);
signal(SIGTSTP, &sighandler);
signal(SIGTTIN, SIG_IGN);
signal(SIGTTOU, SIG_IGN);
}
void list_process() {
timeout(-1);
std::vector <std::string> apps_names;
DLGSTR apps_dlg = {};
unsigned int maxX,
maxY;
int key_pressed;
getmaxyx(stdscr, maxY, maxX);
apps_dlg.title = "Background applications";
apps_dlg.style = RED_WIN;
apps_dlg.xpos = maxX / 2 - llength(apps_dlg.title) / 2;
apps_dlg.ypos = maxY / 2;
apps_dlg.ymax = maxY / 2;
apps_dlg.border_menu = true;
for (unsigned int i = 0; i < apps_vect.size(); i++) {
apps_names.push_back(apps_vect[i].name);
}
key_pressed = 0;
while (key_pressed != 27) {
menu_win(apps_dlg, apps_names);
key_pressed = getch();
switch (key_pressed) {
case KEY_UP: if (apps_dlg.selected != 0)
apps_dlg.selected--;
break;
case KEY_DOWN: if (apps_dlg.selected != apps_names.size())
apps_dlg.selected++;
break;
case '\n': bg_jobs(apps_vect[apps_dlg.selected - 1]);
return;
}
}
}
int app_start(int number_of_app, char** argv) {
std::string name_app = configurator(APPS_FILE, str(number_of_app) + "_app_launcher", "", false);
std::string path_to_dir = configurator(APPS_FILE, str(number_of_app) + "_app_path", "", false);
erase();
endwin();
int status;
pid_t chpid = fork();
job j = {
.name = name_app,
.pid = chpid
};
j.running = true;
// Помещаем процесс в список запущенных процессов
apps_vect.insert(apps_vect.end(), j);
if (chpid == 0) {
signal(SIGTTIN, SIG_IGN);
signal(SIGTTOU, SIG_IGN);
tcsetpgrp(STDIN_FILENO, getpid());
chdir(path_to_dir.c_str());
setpgid(getpid(), getpid()); // Создаём группу процессов
if (execl(name_app.c_str(), "", NULL) == -1) // parent process
exit(0);
} else {
waitpid(chpid, &status,WUNTRACED);
tcsetpgrp(STDIN_FILENO, getpid());
tcgetattr(STDIN_FILENO, &j.tmode);
tcsetattr(STDIN_FILENO, TCSADRAIN, &hos_tmode);
if (WIFSTOPPED(status)) { /* Если процесс был остановлен во время выполнения */
apps_vect.back().running = false;
}
if(WIFEXITED(status)) {
apps_vect.pop_back();
}
init_display();
init_color();
}
return 0;
}<commit_msg>changed to fg<commit_after>#include "apps_starter.h"
std::vector<job> apps_vect; // Определение вектора запущенных программ
struct termios hos_tmode; // настройки терминала для hos
void sighandler(int signo)
{
if (signo == SIGTSTP) {
}
if (signo == SIGINT) {
}
}
void fg_job(job &j)
{
int status;
std::vector<job>::iterator it;
j.running = true;
tcsetpgrp(STDIN_FILENO, j.pid);
kill(-j.pid, SIGCONT);
waitpid(j.pid, &status, WUNTRACED);
if(WIFSTOPPED(status)) {
j.running = false;
tcsetpgrp(STDIN_FILENO, getpid());
tcgetattr(STDIN_FILENO, &j.tmode);
tcsetattr(STDIN_FILENO, TCSADRAIN, &hos_tmode);
}
if(WIFEXITED(status)) {
tcsetpgrp(STDIN_FILENO, getpid());
tcsetattr(STDIN_FILENO, TCSADRAIN, &hos_tmode);
for(it = apps_vect.begin() ; it != apps_vect.end(); it++)
if (it->pid == j.pid)
apps_vect.erase(it);
}
}
void bg_job(job &j)
{
j.running = true;
kill(-j.pid, SIGCONT);
}
void init_signals()
{
signal(SIGINT, &sighandler);
signal(SIGTSTP, &sighandler);
signal(SIGTTIN, SIG_IGN);
signal(SIGTTOU, SIG_IGN);
}
void list_process() {
timeout(-1);
std::vector <std::string> apps_names;
DLGSTR apps_dlg = {};
unsigned int maxX,
maxY;
int key_pressed;
getmaxyx(stdscr, maxY, maxX);
apps_dlg.title = "Background applications";
apps_dlg.style = RED_WIN;
apps_dlg.xpos = maxX / 2 - llength(apps_dlg.title) / 2;
apps_dlg.ypos = maxY / 2;
apps_dlg.ymax = maxY / 2;
apps_dlg.border_menu = true;
if(!apps_vect.empty()) {
for (unsigned int i = 0; i < apps_vect.size(); i++) {
apps_names.push_back(apps_vect[i].name);
}
key_pressed = 0;
while (key_pressed != 27) {
menu_win(apps_dlg, apps_names);
key_pressed = getch();
switch (key_pressed) {
case KEY_UP: if (apps_dlg.selected != 0)
apps_dlg.selected--;
break;
case KEY_DOWN: if (apps_dlg.selected != apps_names.size())
apps_dlg.selected++;
break;
case '\n': fg_job(apps_vect[apps_dlg.selected - 1]);
init_display();
init_color();
break;
}
}
}
}
int app_start(int number_of_app, char** argv) {
std::string name_app = configurator(APPS_FILE, str(number_of_app) + "_app_launcher", "", false);
std::string path_to_dir = configurator(APPS_FILE, str(number_of_app) + "_app_path", "", false);
erase();
endwin();
int status;
pid_t chpid = fork();
job j = {
.name = name_app,
.pid = chpid
};
j.running = true;
// Помещаем процесс в список запущенных процессов
apps_vect.insert(apps_vect.end(), j);
if (chpid == 0) {
signal(SIGTTIN, SIG_IGN);
signal(SIGTTOU, SIG_IGN);
tcsetpgrp(STDIN_FILENO, getpid());
chdir(path_to_dir.c_str());
setpgid(getpid(), getpid()); // Создаём группу процессов
if (execl(name_app.c_str(), "", NULL) == -1) // parent process
exit(0);
} else {
waitpid(chpid, &status,WUNTRACED);
tcsetpgrp(STDIN_FILENO, getpid());
tcgetattr(STDIN_FILENO, &j.tmode);
tcsetattr(STDIN_FILENO, TCSADRAIN, &hos_tmode);
if (WIFSTOPPED(status)) { /* Если процесс был остановлен во время выполнения */
apps_vect.back().running = false;
}
if(WIFEXITED(status)) {
apps_vect.pop_back();
}
init_display();
init_color();
}
return 0;
}<|endoftext|> |
<commit_before>#include "pta_uchar.cxx"
#include "pta_float.cxx"
#include "ramfile.cxx"
#include "referenceCount.cxx"
#include "stringDecoder.cxx"
#include "subStream.cxx"
#include "subStreamBuf.cxx"
#include "textEncoder.cxx"
#include "threadSafePointerTo.cxx"
#include "threadSafePointerToBase.cxx"
#include "trueClock.cxx"
#include "typedReferenceCount.cxx"
#include "unicodeLatinMap.cxx"
#include "vector_uchar.cxx"
#include "vector_float.cxx"
#include "virtualFile.cxx"
#include "virtualFileComposite.cxx"
#include "virtualFileList.cxx"
#include "virtualFileMount.cxx"
#include "virtualFileMountMultifile.cxx"
#include "virtualFileMountSystem.cxx"
#include "virtualFileSimple.cxx"
#include "virtualFileSystem.cxx"
#include "weakPointerCallback.cxx"
#include "weakPointerTo.cxx"
#include "weakPointerToBase.cxx"
#include "weakPointerToVoid.cxx"
#include "weakReferenceList.cxx"
#include "windowsRegistry.cxx"
#include "zStream.cxx"
#include "zStreamBuf.cxx"
<commit_msg>add pta_int.cxx to this composite (moved from putil)<commit_after>#include "pta_int.cxx"
#include "pta_uchar.cxx"
#include "pta_float.cxx"
#include "ramfile.cxx"
#include "referenceCount.cxx"
#include "stringDecoder.cxx"
#include "subStream.cxx"
#include "subStreamBuf.cxx"
#include "textEncoder.cxx"
#include "threadSafePointerTo.cxx"
#include "threadSafePointerToBase.cxx"
#include "trueClock.cxx"
#include "typedReferenceCount.cxx"
#include "unicodeLatinMap.cxx"
#include "vector_uchar.cxx"
#include "vector_float.cxx"
#include "virtualFile.cxx"
#include "virtualFileComposite.cxx"
#include "virtualFileList.cxx"
#include "virtualFileMount.cxx"
#include "virtualFileMountMultifile.cxx"
#include "virtualFileMountSystem.cxx"
#include "virtualFileSimple.cxx"
#include "virtualFileSystem.cxx"
#include "weakPointerCallback.cxx"
#include "weakPointerTo.cxx"
#include "weakPointerToBase.cxx"
#include "weakPointerToVoid.cxx"
#include "weakReferenceList.cxx"
#include "windowsRegistry.cxx"
#include "zStream.cxx"
#include "zStreamBuf.cxx"
<|endoftext|> |
<commit_before>#include "../include/Units.h"
#include "../include/Constants.h"
Int_t VerticalTubeParaMagField()
{
// -- Simple Tube example for Mike P, that includes Wall Losses and finding the average field in a parabolic mag field
// Loading useful libraries (if they aren't already loaded)
gSystem->Load("libPhysics");
gSystem->Load("libGeom");
gSystem->Load("libEG");
gSystem->Load("libUCN");
// Create the geoManager
TUCNGeoManager* geoManager = new TUCNGeoManager("GeoManager", "Geometry Manager");
// Create the UCNNavigator and initialise in the UCNManager
Info("TUCNRun", "Creating a new Navigator...");
TUCNGeoNavigator* navigator = new TUCNGeoNavigator(geoManager);
Int_t navigatorIndex = geoManager->AddNavigator(navigator);
geoManager->SetCurrentNavigator(navigatorIndex);
// -------------------------------------
// BUILDING GEOMETRY
cerr << "Building Geometry..." << endl;
// Input parameters to calculate f -- All numbers come from Mike P (presumable from data), for a specific energy group, from which we can calculate f.
Double_t observedLifetime = 150.*Units::s;
Double_t fermiPotential = (0.91*Units::m)*Constants::height_equivalent_conversion;
Double_t totalEnergy = (0.52*Units::m)*Constants::height_equivalent_conversion;
Double_t initialVelocity = TMath::Sqrt(2.*totalEnergy/Constants::neutron_mass);
Double_t meanFreePath = 0.16*Units::m;
// Calculate f = W/V and hence W
Double_t X = totalEnergy/fermiPotential;
Double_t L = 2.0*((1./X)*TMath::ASin(TMath::Sqrt(X)) - TMath::Sqrt((1./X) - 1.));
Double_t f = meanFreePath/(initialVelocity*observedLifetime*L);
Double_t W = f*fermiPotential;
cerr << "Input Parameters: " << endl;
cerr << "E: " << totalEnergy/Units::neV << "\t" << "V: " << fermiPotential/Units::neV << "\t" << "E/V: " << X << "\t"<< "L: " << L << endl;
cerr << "f: " << f << "\t" << "W: " << W/Units::neV << endl;
// Materials
TUCNGeoMaterial* matTracking = new TUCNGeoMaterial("Tracking Material", 0,0);
TUCNGeoMaterial* matBlackHole = new TUCNGeoMaterial("BlackHole", 0,0);
TUCNGeoMaterial* matBoundary = new TUCNGeoMaterial("Boundary Material", fermiPotential, W);
matTracking->IsTrackingMaterial(kTRUE);
matBlackHole->IsBlackHole(kTRUE);
// -- Making Mediums
TGeoMedium* vacuum = new TGeoMedium("Vacuum",1, matTracking);
TGeoMedium* blackHole = new TGeoMedium("BlackHole",2, matBlackHole);
TGeoMedium* boundary = new TGeoMedium("Boundary",3, matBoundary);
// -- Making Top Volume
TGeoVolume* chamber = geoManager->MakeUCNBox("TOP",blackHole,20,20,20);
geoManager->SetTopVolume(chamber);
// -- Make a GeoTube object via the UCNGeoManager
Double_t rMin = 0.0, rMax = 0.236, length = 0.121;
TGeoVolume* tube = geoManager->MakeUCNTube("tube",boundary, rMin, rMax, length/2.);
TGeoVolume* innerTube = geoManager->MakeUCNTube("innerTube",vacuum, rMin, rMax-0.001, (length-0.001)/2.);
// -- Define the transformation of the volume
TGeoRotation r1,r2;
r1.SetAngles(0,0,0); //rotation defined by Euler angles
r2.SetAngles(0,0,0);
TGeoTranslation t1(0.,0.,length/2.);
TGeoTranslation t2(0.,0.,0.);
TGeoCombiTrans c1(t1,r1);
TGeoCombiTrans c2(t2,r2);
TGeoHMatrix hm = c1 * c2; // composition is done via TGeoHMatrix class
TGeoHMatrix *matrix = new TGeoHMatrix(hm);
TGeoVolume* volume = tube;
TGeoVolume* innerVolume = innerTube;
// -- Create the nodes
volume->AddNode(innerVolume,1);
chamber->AddNode(volume,1, matrix);
// -- Define the Source in our geometry where we will create the particles
geoManager->SetSourceVolume(innerVolume);
geoManager->SetSourceMatrix(matrix);
// -- Arrange and close geometry
geoManager->CloseGeometry();
/* // Turn on/off gravity
geoManager->SetGravity(kTRUE);
// -- Define Mag Field
// TUCNUniformMagField* magField = new TUCNUniformMagField("Uniform magnetic field", 0.0,1.0,1.0);
TUCNParabolicMagField* magField = new TUCNParabolicMagField("Parabolic magnetic field",0.1,1.0,0.235);
geoManager->AddMagField(magField);
*/
// -- Write out geometry to file
cerr << "Geometry Built... Writing to file: " << endl;
geoManager->Export("geom.root");
return 0;
}
<commit_msg>Added missing library to geometry macro<commit_after>#include "../include/Units.h"
#include "../include/Constants.h"
Int_t VerticalTubeParaMagField()
{
// -- Simple Tube example for Mike P, that includes Wall Losses and finding the average field in a parabolic mag field
// Loading useful libraries (if they aren't already loaded)
gSystem->Load("libPhysics");
gSystem->Load("libGeom");
gSystem->Load("libGeomPainter");
gSystem->Load("libEG");
gSystem->Load("libUCN");
// Create the geoManager
TUCNGeoManager* geoManager = new TUCNGeoManager("GeoManager", "Geometry Manager");
// Create the UCNNavigator and initialise in the UCNManager
Info("TUCNRun", "Creating a new Navigator...");
TUCNGeoNavigator* navigator = new TUCNGeoNavigator(geoManager);
Int_t navigatorIndex = geoManager->AddNavigator(navigator);
geoManager->SetCurrentNavigator(navigatorIndex);
// -------------------------------------
// BUILDING GEOMETRY
cerr << "Building Geometry..." << endl;
// Input parameters to calculate f -- All numbers come from Mike P (presumable from data), for a specific energy group, from which we can calculate f.
Double_t observedLifetime = 150.*Units::s;
Double_t fermiPotential = (0.91*Units::m)*Constants::height_equivalent_conversion;
Double_t totalEnergy = (0.52*Units::m)*Constants::height_equivalent_conversion;
Double_t initialVelocity = TMath::Sqrt(2.*totalEnergy/Constants::neutron_mass);
Double_t meanFreePath = 0.16*Units::m;
// Calculate f = W/V and hence W
Double_t X = totalEnergy/fermiPotential;
Double_t L = 2.0*((1./X)*TMath::ASin(TMath::Sqrt(X)) - TMath::Sqrt((1./X) - 1.));
Double_t f = meanFreePath/(initialVelocity*observedLifetime*L);
Double_t W = f*fermiPotential;
cerr << "Input Parameters: " << endl;
cerr << "E: " << totalEnergy/Units::neV << "\t" << "V: " << fermiPotential/Units::neV << "\t" << "E/V: " << X << "\t"<< "L: " << L << endl;
cerr << "f: " << f << "\t" << "W: " << W/Units::neV << endl;
// Materials
TUCNGeoMaterial* matTracking = new TUCNGeoMaterial("Tracking Material", 0,0);
TUCNGeoMaterial* matBlackHole = new TUCNGeoMaterial("BlackHole", 0,0);
TUCNGeoMaterial* matBoundary = new TUCNGeoMaterial("Boundary Material", fermiPotential, W);
matTracking->IsTrackingMaterial(kTRUE);
matBlackHole->IsBlackHole(kTRUE);
// -- Making Mediums
TGeoMedium* vacuum = new TGeoMedium("Vacuum",1, matTracking);
TGeoMedium* blackHole = new TGeoMedium("BlackHole",2, matBlackHole);
TGeoMedium* boundary = new TGeoMedium("Boundary",3, matBoundary);
// -- Making Top Volume
TGeoVolume* chamber = geoManager->MakeUCNBox("TOP",blackHole,20,20,20);
geoManager->SetTopVolume(chamber);
// -- Make a GeoTube object via the UCNGeoManager
Double_t rMin = 0.0, rMax = 0.236, length = 0.121;
TGeoVolume* tube = geoManager->MakeUCNTube("tube",boundary, rMin, rMax, length/2.);
TGeoVolume* innerTube = geoManager->MakeUCNTube("innerTube",vacuum, rMin, rMax-0.001, (length-0.001)/2.);
// -- Define the transformation of the volume
TGeoRotation r1,r2;
r1.SetAngles(0,0,0); //rotation defined by Euler angles
r2.SetAngles(0,0,0);
TGeoTranslation t1(0.,0.,length/2.);
TGeoTranslation t2(0.,0.,0.);
TGeoCombiTrans c1(t1,r1);
TGeoCombiTrans c2(t2,r2);
TGeoHMatrix hm = c1 * c2; // composition is done via TGeoHMatrix class
TGeoHMatrix *matrix = new TGeoHMatrix(hm);
TGeoVolume* volume = tube;
TGeoVolume* innerVolume = innerTube;
// -- Create the nodes
volume->AddNode(innerVolume,1);
chamber->AddNode(volume,1, matrix);
// -- Define the Source in our geometry where we will create the particles
geoManager->SetSourceVolume(innerVolume);
geoManager->SetSourceMatrix(matrix);
// -- Arrange and close geometry
geoManager->CloseGeometry();
/* // Turn on/off gravity
geoManager->SetGravity(kTRUE);
// -- Define Mag Field
// TUCNUniformMagField* magField = new TUCNUniformMagField("Uniform magnetic field", 0.0,1.0,1.0);
TUCNParabolicMagField* magField = new TUCNParabolicMagField("Parabolic magnetic field",0.1,1.0,0.235);
geoManager->AddMagField(magField);
*/
// -- Write out geometry to file
cerr << "Geometry Built... Writing to file: " << endl;
geoManager->Export("geom.root");
return 0;
}
<|endoftext|> |
<commit_before>/*
Q Light Controller Plus
rgbtext.cpp
Copyright (c) Heikki Junnila
Massimo Callegari
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.txt
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 <QXmlStreamReader>
#include <QXmlStreamWriter>
#include <QPainter>
#include <QImage>
#include <QDebug>
#include "rgbtext.h"
#define KXMLQLCRGBTextContent "Content"
#define KXMLQLCRGBTextFont "Font"
#define KXMLQLCRGBTextAnimationStyle "Animation"
#define KXMLQLCRGBTextOffset "Offset"
#define KXMLQLCRGBTextOffsetX "X"
#define KXMLQLCRGBTextOffsetY "Y"
RGBText::RGBText(Doc * doc)
: RGBAlgorithm(doc)
, m_text(" Q LIGHT CONTROLLER + ")
, m_animationStyle(Horizontal)
, m_xOffset(0)
, m_yOffset(0)
{
}
RGBText::RGBText(const RGBText& t)
: RGBAlgorithm(t.doc())
, m_text(t.text())
, m_font(t.font())
, m_animationStyle(t.animationStyle())
, m_xOffset(t.xOffset())
, m_yOffset(t.yOffset())
{
}
RGBText::~RGBText()
{
}
RGBAlgorithm* RGBText::clone() const
{
RGBText* txt = new RGBText(*this);
return static_cast<RGBAlgorithm*> (txt);
}
/****************************************************************************
* Text & Font
****************************************************************************/
void RGBText::setText(const QString& str)
{
m_text = str;
}
QString RGBText::text() const
{
return m_text;
}
void RGBText::setFont(const QFont& font)
{
m_font = font;
}
QFont RGBText::font() const
{
return m_font;
}
/****************************************************************************
* Animation
****************************************************************************/
void RGBText::setAnimationStyle(RGBText::AnimationStyle ani)
{
if (ani >= StaticLetters && ani <= Vertical)
m_animationStyle = ani;
else
m_animationStyle = StaticLetters;
}
RGBText::AnimationStyle RGBText::animationStyle() const
{
return m_animationStyle;
}
QString RGBText::animationStyleToString(RGBText::AnimationStyle ani)
{
switch (ani)
{
default:
case StaticLetters:
return QString("Letters");
case Horizontal:
return QString("Horizontal");
case Vertical:
return QString("Vertical");
}
}
RGBText::AnimationStyle RGBText::stringToAnimationStyle(const QString& str)
{
if (str == QString("Horizontal"))
return Horizontal;
else if (str == QString("Vertical"))
return Vertical;
else
return StaticLetters;
}
QStringList RGBText::animationStyles()
{
QStringList list;
list << animationStyleToString(StaticLetters);
list << animationStyleToString(Horizontal);
list << animationStyleToString(Vertical);
return list;
}
void RGBText::setXOffset(int offset)
{
m_xOffset = offset;
}
int RGBText::xOffset() const
{
return m_xOffset;
}
void RGBText::setYOffset(int offset)
{
m_yOffset = offset;
}
int RGBText::yOffset() const
{
return m_yOffset;
}
int RGBText::scrollingTextStepCount() const
{
QFontMetrics fm(m_font);
if (animationStyle() == Vertical)
return m_text.length() * fm.ascent();
else{
#if (QT_VERSION < QT_VERSION_CHECK(5, 11, 0))
return fm.width(m_text);
#else
return fm.horizontalAdvance(m_text);
#endif
}
}
void RGBText::renderScrollingText(const QSize& size, uint rgb, int step, RGBMap &map) const
{
QImage image;
if (animationStyle() == Horizontal)
image = QImage(scrollingTextStepCount(), size.height(), QImage::Format_RGB32);
else
image = QImage(size.width(), scrollingTextStepCount(), QImage::Format_RGB32);
image.fill(QRgb(0));
QPainter p(&image);
p.setRenderHint(QPainter::TextAntialiasing, false);
p.setRenderHint(QPainter::Antialiasing, false);
p.setFont(m_font);
p.setPen(QColor(rgb));
if (animationStyle() == Vertical)
{
QFontMetrics fm(m_font);
QRect rect(0, 0, image.width(), image.height());
for (int i = 0; i < m_text.length(); i++)
{
rect.setY((i * fm.ascent()) + yOffset());
rect.setX(xOffset());
rect.setHeight(fm.ascent());
p.drawText(rect, Qt::AlignLeft | Qt::AlignVCenter, m_text.mid(i, 1));
}
}
else
{
// Draw the whole text each time
QRect rect(xOffset(), yOffset(), image.width(), image.height());
p.drawText(rect, Qt::AlignLeft | Qt::AlignVCenter, m_text);
}
p.end();
// Treat the RGBMap as a "window" on top of the fully-drawn text and pick the
// correct pixels according to $step.
map.resize(size.height());
for (int y = 0; y < size.height(); y++)
{
map[y].resize(size.width());
for (int x = 0; x < size.width(); x++)
{
if (animationStyle() == Horizontal)
{
if (step + x < image.width())
map[y][x] = image.pixel(step + x, y);
}
else
{
if (step + y < image.height())
map[y][x] = image.pixel(x, step + y);
}
}
}
}
void RGBText::renderStaticLetters(const QSize& size, uint rgb, int step, RGBMap &map) const
{
QImage image(size, QImage::Format_RGB32);
image.fill(QRgb(0));
QPainter p(&image);
p.setRenderHint(QPainter::TextAntialiasing, false);
p.setRenderHint(QPainter::Antialiasing, false);
p.setFont(m_font);
p.setPen(QColor(rgb));
// Draw one letter at a time
QRect rect(xOffset(), yOffset(), size.width(), size.height());
p.drawText(rect, Qt::AlignCenter, m_text.mid(step, 1));
p.end();
map.resize(size.height());
for (int y = 0; y < size.height(); y++)
{
map[y].resize(size.width());
for (int x = 0; x < size.width(); x++)
map[y][x] = image.pixel(x, y);
}
}
/****************************************************************************
* RGBAlgorithm
****************************************************************************/
int RGBText::rgbMapStepCount(const QSize& size)
{
Q_UNUSED(size);
if (animationStyle() == StaticLetters)
return m_text.length();
else
return scrollingTextStepCount();
}
void RGBText::rgbMap(const QSize& size, uint rgb, int step, RGBMap &map)
{
if (animationStyle() == StaticLetters)
return renderStaticLetters(size, rgb, step, map);
else
return renderScrollingText(size, rgb, step, map);
}
QString RGBText::name() const
{
return QString("Text");
}
QString RGBText::author() const
{
return QString("Heikki Junnila");
}
int RGBText::apiVersion() const
{
return 1;
}
RGBAlgorithm::Type RGBText::type() const
{
return RGBAlgorithm::Text;
}
int RGBText::acceptColors() const
{
return 2; // start and end colors accepted
}
bool RGBText::loadXML(QXmlStreamReader &root)
{
if (root.name() != KXMLQLCRGBAlgorithm)
{
qWarning() << Q_FUNC_INFO << "RGB Algorithm node not found";
return false;
}
if (root.attributes().value(KXMLQLCRGBAlgorithmType).toString() != KXMLQLCRGBText)
{
qWarning() << Q_FUNC_INFO << "RGB Algorithm is not Text";
return false;
}
while (root.readNextStartElement())
{
if (root.name() == KXMLQLCRGBTextContent)
{
setText(root.readElementText());
}
else if (root.name() == KXMLQLCRGBTextFont)
{
QFont font;
QString fontName = root.readElementText();
if (font.fromString(fontName) == true)
setFont(font);
else
qWarning() << Q_FUNC_INFO << "Invalid font:" << fontName;
}
else if (root.name() == KXMLQLCRGBTextAnimationStyle)
{
setAnimationStyle(stringToAnimationStyle(root.readElementText()));
}
else if (root.name() == KXMLQLCRGBTextOffset)
{
QString str;
int value;
bool ok;
QXmlStreamAttributes attrs = root.attributes();
str = attrs.value(KXMLQLCRGBTextOffsetX).toString();
ok = false;
value = str.toInt(&ok);
if (ok == true)
setXOffset(value);
else
qWarning() << Q_FUNC_INFO << "Invalid X offset:" << str;
str = attrs.value(KXMLQLCRGBTextOffsetY).toString();
ok = false;
value = str.toInt(&ok);
if (ok == true)
setYOffset(value);
else
qWarning() << Q_FUNC_INFO << "Invalid Y offset:" << str;
root.skipCurrentElement();
}
else
{
qWarning() << Q_FUNC_INFO << "Unknown RGBText tag:" << root.name();
root.skipCurrentElement();
}
}
return true;
}
bool RGBText::saveXML(QXmlStreamWriter *doc) const
{
Q_ASSERT(doc != NULL);
doc->writeStartElement(KXMLQLCRGBAlgorithm);
doc->writeAttribute(KXMLQLCRGBAlgorithmType, KXMLQLCRGBText);
doc->writeTextElement(KXMLQLCRGBTextContent, m_text);
doc->writeTextElement(KXMLQLCRGBTextFont, m_font.toString());
doc->writeTextElement(KXMLQLCRGBTextAnimationStyle, animationStyleToString(animationStyle()));
doc->writeStartElement(KXMLQLCRGBTextOffset);
doc->writeAttribute(KXMLQLCRGBTextOffsetX, QString::number(xOffset()));
doc->writeAttribute(KXMLQLCRGBTextOffsetY, QString::number(yOffset()));
doc->writeEndElement();
/* End the <Algorithm> tag */
doc->writeEndElement();
return true;
}
<commit_msg>engine: no need to return anything<commit_after>/*
Q Light Controller Plus
rgbtext.cpp
Copyright (c) Heikki Junnila
Massimo Callegari
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.txt
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 <QXmlStreamReader>
#include <QXmlStreamWriter>
#include <QPainter>
#include <QImage>
#include <QDebug>
#include "rgbtext.h"
#define KXMLQLCRGBTextContent "Content"
#define KXMLQLCRGBTextFont "Font"
#define KXMLQLCRGBTextAnimationStyle "Animation"
#define KXMLQLCRGBTextOffset "Offset"
#define KXMLQLCRGBTextOffsetX "X"
#define KXMLQLCRGBTextOffsetY "Y"
RGBText::RGBText(Doc * doc)
: RGBAlgorithm(doc)
, m_text(" Q LIGHT CONTROLLER + ")
, m_animationStyle(Horizontal)
, m_xOffset(0)
, m_yOffset(0)
{
}
RGBText::RGBText(const RGBText& t)
: RGBAlgorithm(t.doc())
, m_text(t.text())
, m_font(t.font())
, m_animationStyle(t.animationStyle())
, m_xOffset(t.xOffset())
, m_yOffset(t.yOffset())
{
}
RGBText::~RGBText()
{
}
RGBAlgorithm* RGBText::clone() const
{
RGBText* txt = new RGBText(*this);
return static_cast<RGBAlgorithm*> (txt);
}
/****************************************************************************
* Text & Font
****************************************************************************/
void RGBText::setText(const QString& str)
{
m_text = str;
}
QString RGBText::text() const
{
return m_text;
}
void RGBText::setFont(const QFont& font)
{
m_font = font;
}
QFont RGBText::font() const
{
return m_font;
}
/****************************************************************************
* Animation
****************************************************************************/
void RGBText::setAnimationStyle(RGBText::AnimationStyle ani)
{
if (ani >= StaticLetters && ani <= Vertical)
m_animationStyle = ani;
else
m_animationStyle = StaticLetters;
}
RGBText::AnimationStyle RGBText::animationStyle() const
{
return m_animationStyle;
}
QString RGBText::animationStyleToString(RGBText::AnimationStyle ani)
{
switch (ani)
{
default:
case StaticLetters:
return QString("Letters");
case Horizontal:
return QString("Horizontal");
case Vertical:
return QString("Vertical");
}
}
RGBText::AnimationStyle RGBText::stringToAnimationStyle(const QString& str)
{
if (str == QString("Horizontal"))
return Horizontal;
else if (str == QString("Vertical"))
return Vertical;
else
return StaticLetters;
}
QStringList RGBText::animationStyles()
{
QStringList list;
list << animationStyleToString(StaticLetters);
list << animationStyleToString(Horizontal);
list << animationStyleToString(Vertical);
return list;
}
void RGBText::setXOffset(int offset)
{
m_xOffset = offset;
}
int RGBText::xOffset() const
{
return m_xOffset;
}
void RGBText::setYOffset(int offset)
{
m_yOffset = offset;
}
int RGBText::yOffset() const
{
return m_yOffset;
}
int RGBText::scrollingTextStepCount() const
{
QFontMetrics fm(m_font);
if (animationStyle() == Vertical)
return m_text.length() * fm.ascent();
else{
#if (QT_VERSION < QT_VERSION_CHECK(5, 11, 0))
return fm.width(m_text);
#else
return fm.horizontalAdvance(m_text);
#endif
}
}
void RGBText::renderScrollingText(const QSize& size, uint rgb, int step, RGBMap &map) const
{
QImage image;
if (animationStyle() == Horizontal)
image = QImage(scrollingTextStepCount(), size.height(), QImage::Format_RGB32);
else
image = QImage(size.width(), scrollingTextStepCount(), QImage::Format_RGB32);
image.fill(QRgb(0));
QPainter p(&image);
p.setRenderHint(QPainter::TextAntialiasing, false);
p.setRenderHint(QPainter::Antialiasing, false);
p.setFont(m_font);
p.setPen(QColor(rgb));
if (animationStyle() == Vertical)
{
QFontMetrics fm(m_font);
QRect rect(0, 0, image.width(), image.height());
for (int i = 0; i < m_text.length(); i++)
{
rect.setY((i * fm.ascent()) + yOffset());
rect.setX(xOffset());
rect.setHeight(fm.ascent());
p.drawText(rect, Qt::AlignLeft | Qt::AlignVCenter, m_text.mid(i, 1));
}
}
else
{
// Draw the whole text each time
QRect rect(xOffset(), yOffset(), image.width(), image.height());
p.drawText(rect, Qt::AlignLeft | Qt::AlignVCenter, m_text);
}
p.end();
// Treat the RGBMap as a "window" on top of the fully-drawn text and pick the
// correct pixels according to $step.
map.resize(size.height());
for (int y = 0; y < size.height(); y++)
{
map[y].resize(size.width());
for (int x = 0; x < size.width(); x++)
{
if (animationStyle() == Horizontal)
{
if (step + x < image.width())
map[y][x] = image.pixel(step + x, y);
}
else
{
if (step + y < image.height())
map[y][x] = image.pixel(x, step + y);
}
}
}
}
void RGBText::renderStaticLetters(const QSize& size, uint rgb, int step, RGBMap &map) const
{
QImage image(size, QImage::Format_RGB32);
image.fill(QRgb(0));
QPainter p(&image);
p.setRenderHint(QPainter::TextAntialiasing, false);
p.setRenderHint(QPainter::Antialiasing, false);
p.setFont(m_font);
p.setPen(QColor(rgb));
// Draw one letter at a time
QRect rect(xOffset(), yOffset(), size.width(), size.height());
p.drawText(rect, Qt::AlignCenter, m_text.mid(step, 1));
p.end();
map.resize(size.height());
for (int y = 0; y < size.height(); y++)
{
map[y].resize(size.width());
for (int x = 0; x < size.width(); x++)
map[y][x] = image.pixel(x, y);
}
}
/****************************************************************************
* RGBAlgorithm
****************************************************************************/
int RGBText::rgbMapStepCount(const QSize& size)
{
Q_UNUSED(size);
if (animationStyle() == StaticLetters)
return m_text.length();
else
return scrollingTextStepCount();
}
void RGBText::rgbMap(const QSize& size, uint rgb, int step, RGBMap &map)
{
if (animationStyle() == StaticLetters)
renderStaticLetters(size, rgb, step, map);
else
renderScrollingText(size, rgb, step, map);
}
QString RGBText::name() const
{
return QString("Text");
}
QString RGBText::author() const
{
return QString("Heikki Junnila");
}
int RGBText::apiVersion() const
{
return 1;
}
RGBAlgorithm::Type RGBText::type() const
{
return RGBAlgorithm::Text;
}
int RGBText::acceptColors() const
{
return 2; // start and end colors accepted
}
bool RGBText::loadXML(QXmlStreamReader &root)
{
if (root.name() != KXMLQLCRGBAlgorithm)
{
qWarning() << Q_FUNC_INFO << "RGB Algorithm node not found";
return false;
}
if (root.attributes().value(KXMLQLCRGBAlgorithmType).toString() != KXMLQLCRGBText)
{
qWarning() << Q_FUNC_INFO << "RGB Algorithm is not Text";
return false;
}
while (root.readNextStartElement())
{
if (root.name() == KXMLQLCRGBTextContent)
{
setText(root.readElementText());
}
else if (root.name() == KXMLQLCRGBTextFont)
{
QFont font;
QString fontName = root.readElementText();
if (font.fromString(fontName) == true)
setFont(font);
else
qWarning() << Q_FUNC_INFO << "Invalid font:" << fontName;
}
else if (root.name() == KXMLQLCRGBTextAnimationStyle)
{
setAnimationStyle(stringToAnimationStyle(root.readElementText()));
}
else if (root.name() == KXMLQLCRGBTextOffset)
{
QString str;
int value;
bool ok;
QXmlStreamAttributes attrs = root.attributes();
str = attrs.value(KXMLQLCRGBTextOffsetX).toString();
ok = false;
value = str.toInt(&ok);
if (ok == true)
setXOffset(value);
else
qWarning() << Q_FUNC_INFO << "Invalid X offset:" << str;
str = attrs.value(KXMLQLCRGBTextOffsetY).toString();
ok = false;
value = str.toInt(&ok);
if (ok == true)
setYOffset(value);
else
qWarning() << Q_FUNC_INFO << "Invalid Y offset:" << str;
root.skipCurrentElement();
}
else
{
qWarning() << Q_FUNC_INFO << "Unknown RGBText tag:" << root.name();
root.skipCurrentElement();
}
}
return true;
}
bool RGBText::saveXML(QXmlStreamWriter *doc) const
{
Q_ASSERT(doc != NULL);
doc->writeStartElement(KXMLQLCRGBAlgorithm);
doc->writeAttribute(KXMLQLCRGBAlgorithmType, KXMLQLCRGBText);
doc->writeTextElement(KXMLQLCRGBTextContent, m_text);
doc->writeTextElement(KXMLQLCRGBTextFont, m_font.toString());
doc->writeTextElement(KXMLQLCRGBTextAnimationStyle, animationStyleToString(animationStyle()));
doc->writeStartElement(KXMLQLCRGBTextOffset);
doc->writeAttribute(KXMLQLCRGBTextOffsetX, QString::number(xOffset()));
doc->writeAttribute(KXMLQLCRGBTextOffsetY, QString::number(yOffset()));
doc->writeEndElement();
/* End the <Algorithm> tag */
doc->writeEndElement();
return true;
}
<|endoftext|> |
<commit_before>// program_gnuplot.C -- gnuplot interface
//
// Copyright 2005 Per Abrahamsen and KVL.
//
// This file is part of Daisy.
//
// Daisy is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser Public License as published by
// the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// Daisy 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 Public License for more details.
//
// You should have received a copy of the GNU Lesser Public License
// along with Daisy; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#include "program.h"
#include "time.h"
#include "path.h"
#include "treelog.h"
#include "tmpstream.h"
#include "lexer_data.h"
#include "mathlib.h"
#include "path.h"
#include <string>
struct ProgramGnuplot : public Program
{
// Content.
const std::string program;
const std::string tmpdir;
// Source.
struct Source
{
const std::string filename;
const std::string tag;
const std::string title;
std::string dimension;
const std::vector<std::string> missing;
std::string field_sep;
std::vector<Time> times;
std::vector<double> values;
// Read.
static int find_tag (std::map<std::string,int>& tag_pos,
const std::string& tag);
std::string get_entry (LexerData& lex) const;
std::vector<std::string> get_entries (LexerData& lex) const;
static int get_date_component (LexerData& lex,
const std::vector<std::string>& entries,
int column,
int default_value);
static double convert_to_double (LexerData& lex, const std::string& value);
bool load (Treelog& msg);
// Create and Destroy.
static void load_syntax (Syntax& syntax, AttributeList&);
static std::vector<std::string> s2s (const std::vector<symbol>&);
Source (const AttributeList& al);
~Source ();
};
/* const */ std::vector<Source*> source;
// Use.
void run (Treelog& msg);
// Create and Destroy.
void initialize (const Syntax*, const AttributeList*, Treelog&)
{ }
bool check (Treelog&)
{ return true; }
ProgramGnuplot (const AttributeList& al)
: Program (al),
program (al.name ("program")),
tmpdir (al.name ("directory")),
source (map_construct<Source> (al.alist_sequence ("source")))
{ }
~ProgramGnuplot ()
{ sequence_delete (source.begin (), source.end ()); }
};
int
ProgramGnuplot::Source::find_tag (std::map<std::string,int>& tag_pos,
const std::string& tag)
{
if (tag_pos.find (tag) == tag_pos.end ())
return -1;
return tag_pos[tag];
}
std::string
ProgramGnuplot::Source::get_entry (LexerData& lex) const
{
std::string tmp_term; // Data storage.
const char* field_term;
switch (field_sep.size ())
{
case 0:
// Whitespace
field_term = " \t\n";
break;
case 1:
// Single character field seperator.
tmp_term = field_sep + "\n";
field_term = tmp_term.c_str ();
break;
default:
// Multi-character field seperator.
daisy_assert (false);
}
// Find it.
std::string entry = "";
while (lex.good ())
{
int c = lex.peek ();
if (strchr (field_term, c))
break;
entry += int2char (lex.get ());
}
return entry;
}
std::vector<std::string>
ProgramGnuplot::Source::get_entries (LexerData& lex) const
{
lex.skip ("\n");
std::vector<std::string> entries;
while (lex.good ())
{
entries.push_back (get_entry (lex));
if (lex.peek () == '\n')
break;
if (field_sep == "")
lex.skip_space ();
else
lex.skip(field_sep.c_str ());
}
return entries;
}
int
ProgramGnuplot::Source::get_date_component (LexerData& lex,
const std::vector<std::string>&
/**/ entries,
int column,
int default_value)
{
if (column < 0)
return default_value;
daisy_assert (column < entries.size ());
const char *const str = entries[column].c_str ();
const char* end_ptr = str;
const long lval = strtol (str, const_cast<char**> (&end_ptr), 10);
if (*end_ptr != '\0')
lex.error (std::string ("Junk at end of number '") + end_ptr + "'");
const int ival = lval;
if (ival != lval)
lex.error ("Number out of range");
return ival;
}
double
ProgramGnuplot::Source::convert_to_double (LexerData& lex,
const std::string& value)
{
const char *const str = value.c_str ();
const char* end_ptr = str;
const double val = strtod (str, const_cast<char**> (&end_ptr));
if (*end_ptr != '\0')
lex.error (std::string ("Junk at end of number '") + end_ptr + "'");
return val;
}
bool
ProgramGnuplot::Source::load (Treelog& msg)
{
LexerData lex (filename, msg);
// Open errors?
if (!lex.good ())
return false;
// Read first line.
const std::string type = lex.get_word ();
if (type == "dwf-0.0")
{
field_sep = "";
}
else if (type == "dlf-0.0" || type == "ddf-0.0")
{
field_sep = "\t";
}
else
lex.error ("Unknown file type '" + type + "'");
lex.skip_line ();
lex.next_line ();
// Skip keywords.
while (lex.good () && lex.peek () != '-')
{
lex.skip_line ();
lex.next_line ();
}
// Skip hyphens.
while (lex.good () && lex.peek () == '-')
lex.get ();
lex.skip_space ();
// Read tags.
std::map<std::string,int> tag_pos;
const std::vector<std::string> tag_names = get_entries (lex);
for (int count = 0; count < tag_names.size (); count++)
{
const std::string candidate = tag_names[count];
if (tag_pos.find (candidate) == tag_pos.end ())
tag_pos[candidate] = count;
else
lex.warning ("Duplicate tag: " + candidate);
}
const int tag_c = find_tag (tag_pos, tag);
const int year_c = find_tag (tag_pos, "year");
const int month_c = find_tag (tag_pos, "month");
const int mday_c = find_tag (tag_pos, "mday");
const int hour_c = find_tag (tag_pos, "hour");
if (tag_c < 0)
{
lex.error ("Tag '" + tag + "' not found");
return false;
}
// Read dimensions.
const std::vector<std::string> dim_names = get_entries (lex);
if (dim_names.size () != tag_names.size ())
if (dim_names.size () > tag_c)
lex.warning ("Number of dimensions does not match number of tags");
else
{
lex.error ("No dimension for '" + tag + "' found");
return false;
}
if (dimension == Syntax::Unknown ())
dimension = dim_names[tag_c];
// Read data.
while (lex.good ())
{
// Read entries.
const std::vector<std::string> entries = get_entries (lex);
if (entries.size () != tag_names.size ())
{
if (entries.size () != 0 && lex.good ())
lex.warning ("Wrong number of entries on this line");
continue;
}
// Extract date.
int year = get_date_component (lex, entries, year_c, 1000);
int month = get_date_component (lex, entries, month_c, 1);
int mday = get_date_component (lex, entries, mday_c, 1);
int hour = get_date_component (lex, entries, hour_c, 0);
if (!Time::valid (year, month, mday, hour))
{
lex.warning ("Invalid date");
continue;
}
const Time time (year, month, mday, hour);
// Extract value.
const std::string value = entries[tag_c];
if (std::find (missing.begin (), missing.end (), value)
== missing.end ())
{
times.push_back (time);
const double val = convert_to_double (lex, value);
values.push_back (val);
}
else
msg.message ("Ignoring missing value '" + value + "'");
}
// Done.
return true;
}
void
ProgramGnuplot::Source::load_syntax (Syntax& syntax, AttributeList& al)
{
syntax.add ("file", Syntax::String, Syntax::Const, "\
Name of Daisy log file where data is found.");
syntax.add ("tag", Syntax::String, Syntax::Const, "\
Name of column in Daisy log file where data is found.");
syntax.add ("title", Syntax::String, Syntax::OptionalConst, "\
Name of data legend in plot, by default the same as 'tag'.");
syntax.add ("dimension", Syntax::String, Syntax::OptionalConst, "\
Dimension of data for use by y-axis.\n\
By default use the name specified in data file.");
syntax.add ("missing", Syntax::String, Syntax::Const, Syntax::Sequence, "\
List of strings indicating 'missing value'.");
std::vector<symbol> misses;
misses.push_back (symbol (""));
misses.push_back (symbol ("00.00"));
al.add ("missing", misses);
}
std::vector<std::string>
ProgramGnuplot::Source::s2s (const std::vector<symbol>& v)
{
std::vector<std::string> result;
for (size_t i = 0; i < v.size (); i++)
result.push_back (v[i].name ());
return result;
}
ProgramGnuplot::Source::Source (const AttributeList& al)
: filename (al.name ("file")),
tag (al.name ("tag")),
title (al.name ("title", tag)),
dimension (al.name ("dimension", Syntax::Unknown ())),
missing (s2s (al.identifier_sequence ("missing"))),
field_sep ("UNINITIALIZED")
{ }
ProgramGnuplot::Source::~Source ()
{ }
void
ProgramGnuplot::run (Treelog& msg)
{
for (size_t i = 0; i < source.size(); i++)
{
TmpStream tmp;
tmp () << name << "[" << i << "]: " << source[i]->tag;
Treelog::Open nest (msg, tmp.str ());
if (!source[i]->load (msg))
return;
}
Path::InDirectory dir (tmpdir);
if (!dir.check ())
{
msg.error ("Could not cd to '" + tmpdir + "'");
return;
}
const std::string tmpfile = "daisy.gnuplot";
Path::Output output (tmpfile);
std::ostream& out = output.stream ();
// Dimensions.
std::vector<std::string> dims;
std::vector<int> axis;
for (size_t i = 0; i < source.size (); i++)
{
const std::string dim = source[i]->dimension;
for (size_t j = 0; j < dims.size (); j++)
if (dim == dims[j])
{
axis.push_back (j);
goto cont2;
}
axis.push_back (dims.size ());
dims.push_back (dim);
cont2: ;
}
if (dims.size () > 0)
out << "set ylabel \"" << dims[0] << "\"\n";
// Header
out << "\
set xdata time\n\
set timefmt \"%Y-%m-%d\"\n\
set style data lines\n\
plot ";
// Sources.
for (size_t i = 0; i < source.size (); i++)
{
if (i != 0)
out << ", ";
out << "'-' using 1:2 title \"" << source[i]->title << "\"";
}
out << "\n";
for (size_t i = 0; i < source.size (); i++)
{
const size_t size = source[i]->times.size ();
daisy_assert (size == source[i]->values.size ());
for (size_t j = 0; j < size; j++)
{
const Time time = source[i]->times[j];
out << time.year () << "-" << time.month () << "-" << time.mday ()
<< "T" << time.hour () << "\t" << source[i]->values[j] << "\n";
}
out << "e\n";
}
out << "pause mouse\n";
if (!output.good ())
msg.error ("Problems writting to temporary file '" + tmpfile + "'");
}
static struct ProgramGnuplotSyntax
{
static Program&
make (const AttributeList& al)
{ return *new ProgramGnuplot (al); }
ProgramGnuplotSyntax ()
{
Syntax& syntax = *new Syntax ();
AttributeList& alist = *new AttributeList ();
alist.add ("description",
"Generate plot from Daisy log files with gnuplot.\n\
UNDER CONSTRUCTION, DO NOT USE!");
syntax.add ("program", Syntax::String, Syntax::Const, "\
File name of the gnuplot executable.");
syntax.add ("directory", Syntax::String, Syntax::Const, "\
Temporary directory to run gnuplot in.");
syntax.add_submodule_sequence ("source", Syntax::State, "\
Fertilizer application by date.", ProgramGnuplot::Source::load_syntax);
Librarian<Program>::add_type ("gnuplot", alist, syntax, &make);
}
} ProgramGnuplot_syntax;
<commit_msg>x40<commit_after>// program_gnuplot.C -- gnuplot interface
//
// Copyright 2005 Per Abrahamsen and KVL.
//
// This file is part of Daisy.
//
// Daisy is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser Public License as published by
// the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// Daisy 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 Public License for more details.
//
// You should have received a copy of the GNU Lesser Public License
// along with Daisy; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#include "program.h"
#include "vcheck.h"
#include "time.h"
#include "path.h"
#include "treelog.h"
#include "tmpstream.h"
#include "lexer_data.h"
#include "path.h"
#include "mathlib.h"
#include <string>
struct ProgramGnuplot : public Program
{
// Content.
const std::string program;
const std::string tmpdir;
const std::string file;
const std::string device;
// Source.
struct Source
{
const std::string filename;
const std::string tag;
const std::string title;
std::string dimension;
const std::vector<std::string> missing;
std::string field_sep;
std::vector<Time> times;
std::vector<double> values;
// Read.
static int find_tag (std::map<std::string,int>& tag_pos,
const std::string& tag);
std::string get_entry (LexerData& lex) const;
std::vector<std::string> get_entries (LexerData& lex) const;
static int get_date_component (LexerData& lex,
const std::vector<std::string>& entries,
int column,
int default_value);
static double convert_to_double (LexerData& lex, const std::string& value);
bool load (Treelog& msg);
// Create and Destroy.
static void load_syntax (Syntax& syntax, AttributeList&);
static std::vector<std::string> s2s (const std::vector<symbol>&);
Source (const AttributeList& al);
~Source ();
};
/* const */ std::vector<Source*> source;
// Use.
void run (Treelog& msg);
// Create and Destroy.
void initialize (const Syntax*, const AttributeList*, Treelog&)
{ }
bool check (Treelog&)
{ return true; }
static std::string file2device (const std::string& file);
ProgramGnuplot (const AttributeList& al)
: Program (al),
program (al.name ("program")),
tmpdir (al.name ("directory")),
file (al.name ("where", "")),
device (file2device (file)),
source (map_construct<Source> (al.alist_sequence ("source")))
{ }
~ProgramGnuplot ()
{ sequence_delete (source.begin (), source.end ()); }
};
int
ProgramGnuplot::Source::find_tag (std::map<std::string,int>& tag_pos,
const std::string& tag)
{
if (tag_pos.find (tag) == tag_pos.end ())
return -1;
return tag_pos[tag];
}
std::string
ProgramGnuplot::Source::get_entry (LexerData& lex) const
{
std::string tmp_term; // Data storage.
const char* field_term;
switch (field_sep.size ())
{
case 0:
// Whitespace
field_term = " \t\n";
break;
case 1:
// Single character field seperator.
tmp_term = field_sep + "\n";
field_term = tmp_term.c_str ();
break;
default:
// Multi-character field seperator.
daisy_assert (false);
}
// Find it.
std::string entry = "";
while (lex.good ())
{
int c = lex.peek ();
if (strchr (field_term, c))
break;
entry += int2char (lex.get ());
}
return entry;
}
std::vector<std::string>
ProgramGnuplot::Source::get_entries (LexerData& lex) const
{
lex.skip ("\n");
std::vector<std::string> entries;
while (lex.good ())
{
entries.push_back (get_entry (lex));
if (lex.peek () == '\n')
break;
if (field_sep == "")
lex.skip_space ();
else
lex.skip(field_sep.c_str ());
}
return entries;
}
int
ProgramGnuplot::Source::get_date_component (LexerData& lex,
const std::vector<std::string>&
/**/ entries,
int column,
int default_value)
{
if (column < 0)
return default_value;
daisy_assert (column < entries.size ());
const char *const str = entries[column].c_str ();
const char* end_ptr = str;
const long lval = strtol (str, const_cast<char**> (&end_ptr), 10);
if (*end_ptr != '\0')
lex.error (std::string ("Junk at end of number '") + end_ptr + "'");
const int ival = lval;
if (ival != lval)
lex.error ("Number out of range");
return ival;
}
double
ProgramGnuplot::Source::convert_to_double (LexerData& lex,
const std::string& value)
{
const char *const str = value.c_str ();
const char* end_ptr = str;
const double val = strtod (str, const_cast<char**> (&end_ptr));
if (*end_ptr != '\0')
lex.error (std::string ("Junk at end of number '") + end_ptr + "'");
return val;
}
bool
ProgramGnuplot::Source::load (Treelog& msg)
{
LexerData lex (filename, msg);
// Open errors?
if (!lex.good ())
return false;
// Read first line.
const std::string type = lex.get_word ();
if (type == "dwf-0.0")
{
field_sep = "";
}
else if (type == "dlf-0.0" || type == "ddf-0.0")
{
field_sep = "\t";
}
else
lex.error ("Unknown file type '" + type + "'");
lex.skip_line ();
lex.next_line ();
// Skip keywords.
while (lex.good () && lex.peek () != '-')
{
lex.skip_line ();
lex.next_line ();
}
// Skip hyphens.
while (lex.good () && lex.peek () == '-')
lex.get ();
lex.skip_space ();
// Read tags.
std::map<std::string,int> tag_pos;
const std::vector<std::string> tag_names = get_entries (lex);
for (int count = 0; count < tag_names.size (); count++)
{
const std::string candidate = tag_names[count];
if (tag_pos.find (candidate) == tag_pos.end ())
tag_pos[candidate] = count;
else
lex.warning ("Duplicate tag: " + candidate);
}
const int tag_c = find_tag (tag_pos, tag);
const int year_c = find_tag (tag_pos, "year");
const int month_c = find_tag (tag_pos, "month");
const int mday_c = find_tag (tag_pos, "mday");
const int hour_c = find_tag (tag_pos, "hour");
if (tag_c < 0)
{
lex.error ("Tag '" + tag + "' not found");
return false;
}
// Read dimensions.
const std::vector<std::string> dim_names = get_entries (lex);
if (dim_names.size () != tag_names.size ())
if (dim_names.size () > tag_c)
lex.warning ("Number of dimensions does not match number of tags");
else
{
lex.error ("No dimension for '" + tag + "' found");
return false;
}
if (dimension == Syntax::Unknown ())
dimension = dim_names[tag_c];
// Read data.
while (lex.good ())
{
// Read entries.
const std::vector<std::string> entries = get_entries (lex);
if (entries.size () != tag_names.size ())
{
if (entries.size () != 0 && lex.good ())
lex.warning ("Wrong number of entries on this line");
continue;
}
// Extract date.
int year = get_date_component (lex, entries, year_c, 1000);
int month = get_date_component (lex, entries, month_c, 1);
int mday = get_date_component (lex, entries, mday_c, 1);
int hour = get_date_component (lex, entries, hour_c, 0);
if (!Time::valid (year, month, mday, hour))
{
lex.warning ("Invalid date");
continue;
}
const Time time (year, month, mday, hour);
// Extract value.
const std::string value = entries[tag_c];
if (std::find (missing.begin (), missing.end (), value)
== missing.end ())
{
times.push_back (time);
const double val = convert_to_double (lex, value);
values.push_back (val);
}
else
msg.message ("Ignoring missing value '" + value + "'");
}
// Done.
return true;
}
void
ProgramGnuplot::Source::load_syntax (Syntax& syntax, AttributeList& al)
{
syntax.add ("file", Syntax::String, Syntax::Const, "\
Name of Daisy log file where data is found.");
syntax.add ("tag", Syntax::String, Syntax::Const, "\
Name of column in Daisy log file where data is found.");
syntax.add ("title", Syntax::String, Syntax::OptionalConst, "\
Name of data legend in plot, by default the same as 'tag'.");
syntax.add ("dimension", Syntax::String, Syntax::OptionalConst, "\
Dimension of data for use by y-axis.\n\
By default use the name specified in data file.");
syntax.add ("missing", Syntax::String, Syntax::Const, Syntax::Sequence, "\
List of strings indicating 'missing value'.");
std::vector<symbol> misses;
misses.push_back (symbol (""));
misses.push_back (symbol ("00.00"));
al.add ("missing", misses);
}
std::vector<std::string>
ProgramGnuplot::Source::s2s (const std::vector<symbol>& v)
{
std::vector<std::string> result;
for (size_t i = 0; i < v.size (); i++)
result.push_back (v[i].name ());
return result;
}
ProgramGnuplot::Source::Source (const AttributeList& al)
: filename (al.name ("file")),
tag (al.name ("tag")),
title (al.name ("title", tag)),
dimension (al.name ("dimension", Syntax::Unknown ())),
missing (s2s (al.identifier_sequence ("missing"))),
field_sep ("UNINITIALIZED")
{ }
ProgramGnuplot::Source::~Source ()
{ }
void
ProgramGnuplot::run (Treelog& msg)
{
for (size_t i = 0; i < source.size(); i++)
{
TmpStream tmp;
tmp () << name << "[" << i << "]: " << source[i]->tag;
Treelog::Open nest (msg, tmp.str ());
if (!source[i]->load (msg))
return;
}
Path::InDirectory dir (tmpdir);
if (!dir.check ())
{
msg.error ("Could not cd to '" + tmpdir + "'");
return;
}
const std::string tmpfile = "daisy.gnuplot";
Path::Output output (tmpfile);
std::ostream& out = output.stream ();
// Dimensions.
std::vector<std::string> dims;
std::vector<int> axis;
for (size_t i = 0; i < source.size (); i++)
{
const std::string dim = source[i]->dimension;
for (size_t j = 0; j < dims.size (); j++)
if (dim == dims[j])
{
axis.push_back (j);
goto cont2;
}
axis.push_back (dims.size ());
dims.push_back (dim);
cont2: ;
}
switch (dims.size ())
{
case 2:
out << "set y2label \"" << dims[1] << "\"\n";
// Fallthrough.
case 1:
out << "set ylabel \"" << dims[0] << "\"\n";
break;
default:
msg.error ("Can only plot one or two units at a time");
return;
}
// Header
if (device != "default" && device != "unknown")
out << "set output \"" << file << "\"\n"
<< "set terminal " << device << "\n";
out << "\
set xdata time\n\
set timefmt \"%Y-%m-%dT%H\"\n\
set style data lines\n\
plot ";
// Sources.
daisy_assert (axis.size () == source.size ());
for (size_t i = 0; i < source.size (); i++)
{
if (i != 0)
out << ", ";
out << "'-' using 1:2 title \"" << source[i]->title << "\"";
if (axis[i] == 1)
out << " axes x1y2";
else
daisy_assert (axis[i] == 0);
}
out << "\n";
for (size_t i = 0; i < source.size (); i++)
{
const size_t size = source[i]->times.size ();
daisy_assert (size == source[i]->values.size ());
for (size_t j = 0; j < size; j++)
{
const Time time = source[i]->times[j];
out << time.year () << "-" << time.month () << "-" << time.mday ()
<< "T" << time.hour () << "\t" << source[i]->values[j] << "\n";
}
out << "e\n";
}
if (device == "default" || device == "unknown")
out << "pause mouse\n";
if (!output.good ())
{
msg.error ("Problems writting to temporary file '" + tmpfile + "'");
return;
}
const std::string command = program + " " + tmpfile;
if (system (command.c_str ()) != 0)
msg.error ("There were trouble executing '" + command + "'");
}
std::string
ProgramGnuplot::file2device (const std::string& file)
{
if (file == "")
return "default";
if (file.size () < 5 || file[file.size () - 4] != '.')
return "unknown";
std::string ext;
ext += file[file.size () - 3];
ext += file[file.size () - 2];
ext += file[file.size () - 1];
if (ext == "tex")
return "pslatex";
if (ext == "eps")
return "postscript";
if (ext == "pdf")
return "pdf";
return "unknown";
}
static struct ProgramGnuplotSyntax
{
static Program&
make (const AttributeList& al)
{ return *new ProgramGnuplot (al); }
ProgramGnuplotSyntax ()
{
Syntax& syntax = *new Syntax ();
AttributeList& alist = *new AttributeList ();
alist.add ("description",
"Generate plot from Daisy log files with gnuplot.\n\
UNDER CONSTRUCTION, DO NOT USE!");
syntax.add ("program", Syntax::String, Syntax::Const, "\
File name of the gnuplot executable.");
syntax.add ("directory", Syntax::String, Syntax::Const, "\
Temporary directory to run gnuplot in.");
syntax.add ("where", Syntax::String, Syntax::OptionalConst, "\
File to store results in. By default, show them on a window.\n\
The format is determined from the file name extension:\n\
*.tex: LaTeX code with PostScript specials.\n\
*.eps: Encapsulated PostScript.\n\
*.pdf: Adobe PDF files.");
static struct CheckWhere : public VCheck
{
void check (const Syntax& syntax, const AttributeList& alist,
const std::string& key) const throw (std::string)
{
daisy_assert (key == "where");
daisy_assert (syntax.lookup (key) == Syntax::String);
daisy_assert (syntax.size (key) == Syntax::Singleton);
const std::string file = alist.name (key);
if (ProgramGnuplot::file2device (file) == "unknown")
throw std::string ("Unknown file extension '") + file + "'";
}
} check_where;
syntax.add_check ("where", check_where);
syntax.add_submodule_sequence ("source", Syntax::State, "\
Fertilizer application by date.", ProgramGnuplot::Source::load_syntax);
Librarian<Program>::add_type ("gnuplot", alist, syntax, &make);
}
} ProgramGnuplot_syntax;
<|endoftext|> |
<commit_before>/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Copyright (C) 2017 ScyllaDB
*
* Modified by ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#include <boost/range/algorithm/transform.hpp>
#include <boost/range/adaptors.hpp>
#include "clustering_bounds_comparator.hh"
#include "cql3/statements/select_statement.hh"
#include "cql3/util.hh"
#include "db/view/view.hh"
namespace db {
namespace view {
cql3::statements::select_statement& view::select_statement() const {
if (!_select_statement) {
std::vector<sstring_view> included;
if (!_schema->view_info()->include_all_columns()) {
included.reserve(_schema->all_columns_in_select_order().size());
boost::transform(_schema->all_columns_in_select_order(), std::back_inserter(included), std::mem_fn(&column_definition::name_as_text));
}
auto raw = cql3::util::build_select_statement(_schema->view_info()->base_name(), _schema->view_info()->where_clause(), std::move(included));
raw->prepare_keyspace(_schema->ks_name());
raw->set_bound_variables({});
cql3::cql_stats ignored;
auto prepared = raw->prepare(service::get_local_storage_proxy().get_db().local(), ignored, true);
_select_statement = static_pointer_cast<cql3::statements::select_statement>(prepared->statement);
}
return *_select_statement;
}
const query::partition_slice& view::partition_slice() const {
if (!_partition_slice) {
_partition_slice = select_statement().make_partition_slice(cql3::query_options({ }));
}
return *_partition_slice;
}
const dht::partition_range_vector& view::partition_ranges() const {
if (!_partition_ranges) {
_partition_ranges = select_statement().get_restrictions()->get_partition_key_ranges(cql3::query_options({ }));
}
return *_partition_ranges;
}
bool view::partition_key_matches(const ::schema& base, const dht::decorated_key& key) const {
dht::ring_position rp(key);
auto& ranges = partition_ranges();
return std::any_of(ranges.begin(), ranges.end(), [&] (auto&& range) {
return range.contains(rp, dht::ring_position_comparator(base));
});
}
bool view::clustering_prefix_matches(const ::schema& base, const partition_key& key, const clustering_key_prefix& ck) const {
bound_view::compare less(base);
auto& ranges = partition_slice().row_ranges(base, key);
return std::any_of(ranges.begin(), ranges.end(), [&] (auto&& range) {
auto bounds = bound_view::from_range(range);
return !less(ck, bounds.first) && !less(bounds.second, ck);
});
}
bool view::may_be_affected_by(const ::schema& base, const dht::decorated_key& key, const rows_entry& update) const {
// We can guarantee that the view won't be affected if:
// - the primary key is excluded by the view filter (note that this isn't true of the filter on regular columns:
// even if an update don't match a view condition on a regular column, that update can still invalidate a
// pre-existing entry);
// - the update doesn't modify any of the columns impacting the view (where "impacting" the view means that column
// is neither included in the view, nor used by the view filter).
if (!partition_key_matches(base, key) && !clustering_prefix_matches(base, key.key(), update.key())) {
return false;
}
// We want to check if the update modifies any of the columns that are part of the view (in which case the view is
// affected). But iff the view includes all the base table columns, or the update has either a row deletion or a
// row marker, we know the view is affected right away.
if (_schema->view_info()->include_all_columns() || update.row().deleted_at() || update.row().marker().is_live()) {
return true;
}
bool affected = false;
update.row().cells().for_each_cell_until([&] (column_id id, const atomic_cell_or_collection& cell) {
affected = _schema->get_column_definition(base.column_at(column_kind::regular_column, id).name());
return stop_iteration(affected);
});
return affected;
}
bool view::matches_view_filter(const ::schema& base, const partition_key& key, const clustering_row& update, gc_clock::time_point now) const {
return clustering_prefix_matches(base, key, update.key()) &&
boost::algorithm::all_of(
select_statement().get_restrictions()->get_non_pk_restriction() | boost::adaptors::map_values,
[&] (auto&& r) {
return r->is_satisfied_by(base, key, update.key(), update.cells(), cql3::query_options({ }), now);
});
}
void view::set_base_non_pk_column_in_view_pk(const ::schema& base) {
for (auto&& base_col : base.regular_columns()) {
auto view_col = _schema->get_column_definition(base_col.name());
if (view_col && view_col->is_primary_key()) {
_base_non_pk_column_in_view_pk = view_col;
return;
}
}
_base_non_pk_column_in_view_pk = nullptr;
}
class view_updates final {
lw_shared_ptr<const db::view::view> _view;
schema_ptr _base;
std::unordered_map<partition_key, mutation_partition, partition_key::hashing, partition_key::equality> _updates;
public:
explicit view_updates(lw_shared_ptr<const db::view::view> view, schema_ptr base)
: _view(std::move(view))
, _base(std::move(base))
, _updates(8, partition_key::hashing(*_base), partition_key::equality(*_base)) {
}
void move_to(std::vector<mutation>& mutations) && {
auto& partitioner = dht::global_partitioner();
std::transform(_updates.begin(), _updates.end(), std::back_inserter(mutations), [&, this] (auto&& m) {
return mutation(_view->schema(), partitioner.decorate_key(*_base, std::move(m.first)), std::move(m.second));
});
}
private:
mutation_partition& partition_for(partition_key&& key) {
auto it = _updates.find(key);
if (it != _updates.end()) {
return it->second;
}
return _updates.emplace(std::move(key), mutation_partition(_view->schema())).first->second;
}
};
} // namespace view
} // namespace db
<commit_msg>view_updates: Compute row marker<commit_after>/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Copyright (C) 2017 ScyllaDB
*
* Modified by ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#include <boost/range/algorithm/transform.hpp>
#include <boost/range/adaptors.hpp>
#include "clustering_bounds_comparator.hh"
#include "cql3/statements/select_statement.hh"
#include "cql3/util.hh"
#include "db/view/view.hh"
namespace db {
namespace view {
cql3::statements::select_statement& view::select_statement() const {
if (!_select_statement) {
std::vector<sstring_view> included;
if (!_schema->view_info()->include_all_columns()) {
included.reserve(_schema->all_columns_in_select_order().size());
boost::transform(_schema->all_columns_in_select_order(), std::back_inserter(included), std::mem_fn(&column_definition::name_as_text));
}
auto raw = cql3::util::build_select_statement(_schema->view_info()->base_name(), _schema->view_info()->where_clause(), std::move(included));
raw->prepare_keyspace(_schema->ks_name());
raw->set_bound_variables({});
cql3::cql_stats ignored;
auto prepared = raw->prepare(service::get_local_storage_proxy().get_db().local(), ignored, true);
_select_statement = static_pointer_cast<cql3::statements::select_statement>(prepared->statement);
}
return *_select_statement;
}
const query::partition_slice& view::partition_slice() const {
if (!_partition_slice) {
_partition_slice = select_statement().make_partition_slice(cql3::query_options({ }));
}
return *_partition_slice;
}
const dht::partition_range_vector& view::partition_ranges() const {
if (!_partition_ranges) {
_partition_ranges = select_statement().get_restrictions()->get_partition_key_ranges(cql3::query_options({ }));
}
return *_partition_ranges;
}
bool view::partition_key_matches(const ::schema& base, const dht::decorated_key& key) const {
dht::ring_position rp(key);
auto& ranges = partition_ranges();
return std::any_of(ranges.begin(), ranges.end(), [&] (auto&& range) {
return range.contains(rp, dht::ring_position_comparator(base));
});
}
bool view::clustering_prefix_matches(const ::schema& base, const partition_key& key, const clustering_key_prefix& ck) const {
bound_view::compare less(base);
auto& ranges = partition_slice().row_ranges(base, key);
return std::any_of(ranges.begin(), ranges.end(), [&] (auto&& range) {
auto bounds = bound_view::from_range(range);
return !less(ck, bounds.first) && !less(bounds.second, ck);
});
}
bool view::may_be_affected_by(const ::schema& base, const dht::decorated_key& key, const rows_entry& update) const {
// We can guarantee that the view won't be affected if:
// - the primary key is excluded by the view filter (note that this isn't true of the filter on regular columns:
// even if an update don't match a view condition on a regular column, that update can still invalidate a
// pre-existing entry);
// - the update doesn't modify any of the columns impacting the view (where "impacting" the view means that column
// is neither included in the view, nor used by the view filter).
if (!partition_key_matches(base, key) && !clustering_prefix_matches(base, key.key(), update.key())) {
return false;
}
// We want to check if the update modifies any of the columns that are part of the view (in which case the view is
// affected). But iff the view includes all the base table columns, or the update has either a row deletion or a
// row marker, we know the view is affected right away.
if (_schema->view_info()->include_all_columns() || update.row().deleted_at() || update.row().marker().is_live()) {
return true;
}
bool affected = false;
update.row().cells().for_each_cell_until([&] (column_id id, const atomic_cell_or_collection& cell) {
affected = _schema->get_column_definition(base.column_at(column_kind::regular_column, id).name());
return stop_iteration(affected);
});
return affected;
}
bool view::matches_view_filter(const ::schema& base, const partition_key& key, const clustering_row& update, gc_clock::time_point now) const {
return clustering_prefix_matches(base, key, update.key()) &&
boost::algorithm::all_of(
select_statement().get_restrictions()->get_non_pk_restriction() | boost::adaptors::map_values,
[&] (auto&& r) {
return r->is_satisfied_by(base, key, update.key(), update.cells(), cql3::query_options({ }), now);
});
}
void view::set_base_non_pk_column_in_view_pk(const ::schema& base) {
for (auto&& base_col : base.regular_columns()) {
auto view_col = _schema->get_column_definition(base_col.name());
if (view_col && view_col->is_primary_key()) {
_base_non_pk_column_in_view_pk = view_col;
return;
}
}
_base_non_pk_column_in_view_pk = nullptr;
}
class view_updates final {
lw_shared_ptr<const db::view::view> _view;
schema_ptr _base;
std::unordered_map<partition_key, mutation_partition, partition_key::hashing, partition_key::equality> _updates;
public:
explicit view_updates(lw_shared_ptr<const db::view::view> view, schema_ptr base)
: _view(std::move(view))
, _base(std::move(base))
, _updates(8, partition_key::hashing(*_base), partition_key::equality(*_base)) {
}
void move_to(std::vector<mutation>& mutations) && {
auto& partitioner = dht::global_partitioner();
std::transform(_updates.begin(), _updates.end(), std::back_inserter(mutations), [&, this] (auto&& m) {
return mutation(_view->schema(), partitioner.decorate_key(*_base, std::move(m.first)), std::move(m.second));
});
}
private:
mutation_partition& partition_for(partition_key&& key) {
auto it = _updates.find(key);
if (it != _updates.end()) {
return it->second;
}
return _updates.emplace(std::move(key), mutation_partition(_view->schema())).first->second;
}
row_marker compute_row_marker(const clustering_row& base_row) const;
};
row_marker view_updates::compute_row_marker(const clustering_row& base_row) const {
/*
* We need to compute both the timestamp and expiration.
*
* For the timestamp, it makes sense to use the bigger timestamp for all view PK columns.
*
* This is more complex for the expiration. We want to maintain consistency between the base and the view, so the
* entry should only exist as long as the base row exists _and_ has non-null values for all the columns that are part
* of the view PK.
* Which means we really have 2 cases:
* 1) There is a column that is not in the base PK but is in the view PK. In that case, as long as that column
* lives, the view entry does too, but as soon as it expires (or is deleted for that matter) the entry also
* should expire. So the expiration for the view is the one of that column, regardless of any other expiration.
* To take an example of that case, if you have:
* CREATE TABLE t (a int, b int, c int, PRIMARY KEY (a, b))
* CREATE MATERIALIZED VIEW mv AS SELECT * FROM t WHERE c IS NOT NULL AND a IS NOT NULL AND b IS NOT NULL PRIMARY KEY (c, a, b)
* INSERT INTO t(a, b) VALUES (0, 0) USING TTL 3;
* UPDATE t SET c = 0 WHERE a = 0 AND b = 0;
* then even after 3 seconds elapsed, the row will still exist (it just won't have a "row marker" anymore) and so
* the MV should still have a corresponding entry.
* 2) The columns for the base and view PKs are exactly the same. In that case, the view entry should live
* as long as the base row lives. This means the view entry should only expire once *everything* in the
* base row has expired. So, the row TTL should be the max of any other TTL. This is particularly important
* in the case where the base row has a TTL, but a column *absent* from the view holds a greater TTL.
*/
auto marker = base_row.marker();
auto* col = _view->base_non_pk_column_in_view_pk();
if (col) {
// Note: multi-cell columns can't be part of the primary key.
auto cell = base_row.cells().cell_at(col->id).as_atomic_cell();
auto timestamp = std::max(marker.timestamp(), cell.timestamp());
return cell.is_live_and_has_ttl() ? row_marker(timestamp, cell.ttl(), cell.expiry()) : row_marker(timestamp);
}
if (!marker.is_expiring()) {
return marker;
}
auto ttl = marker.ttl();
auto expiry = marker.expiry();
auto maybe_update_expiry_and_ttl = [&] (atomic_cell_view&& cell) {
// Note: Cassandra compares cell.ttl() here, but that seems very wrong.
// See CASSANDRA-13127.
if (cell.is_live_and_has_ttl() && cell.expiry() > expiry) {
expiry = cell.expiry();
ttl = cell.ttl();
}
};
base_row.cells().for_each_cell([&] (column_id id, const atomic_cell_or_collection& c) {
auto& def = _base->regular_column_at(id);
if (def.is_atomic()) {
maybe_update_expiry_and_ttl(c.as_atomic_cell());
} else {
static_pointer_cast<const collection_type_impl>(def.type)->for_each_cell(c.as_collection_mutation(), maybe_update_expiry_and_ttl);
}
});
return row_marker(marker.timestamp(), ttl, expiry);
}
} // namespace view
} // namespace db
<|endoftext|> |
<commit_before>b838bb9c-35ca-11e5-8390-6c40088e03e4<commit_msg>b83fa26c-35ca-11e5-a4f5-6c40088e03e4<commit_after>b83fa26c-35ca-11e5-a4f5-6c40088e03e4<|endoftext|> |
<commit_before>7897e490-2e3a-11e5-9530-c03896053bdd<commit_msg>78a49114-2e3a-11e5-9495-c03896053bdd<commit_after>78a49114-2e3a-11e5-9495-c03896053bdd<|endoftext|> |
<commit_before>8fd04902-2d14-11e5-af21-0401358ea401<commit_msg>8fd04903-2d14-11e5-af21-0401358ea401<commit_after>8fd04903-2d14-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>76d8982e-2d3d-11e5-816a-c82a142b6f9b<commit_msg>773389c0-2d3d-11e5-b9a3-c82a142b6f9b<commit_after>773389c0-2d3d-11e5-b9a3-c82a142b6f9b<|endoftext|> |
<commit_before>#include <iostream>
#include "layers/conv2d.hpp"
#include "basics/tensor.hpp"
#include "basics/session.hpp"
#include "initializers/gaussian_kernel_initializer.hpp"
#include <assert.h>
void test_session() {
std::cout<< "Testing Session .."<<std::endl;
Session* session = Session::GetSession();
session->gpu = true;
std::cout<< "use gpu: "<< session->gpu <<std::endl;
}
void test_conv_layer() {
std::cout<< "Testing Conv2D .."<<std::endl;
// inputs: filter_height, filter_width, in_channels, out_channels, stride
Conv2D<float>* conv_layer = new Conv2D<float>(5, 5, 3, 5, 1);
assert(conv_layer->kernel_height==5);
assert(conv_layer->kernel_width==5);
assert(conv_layer->in_channels==3);
assert(conv_layer->out_channels==5);
assert(conv_layer->stride==1);
delete conv_layer;
}
void test_tensor() {
std::cout<< "Testing Tensor .."<<std::endl;
// inputs: tensor dimensions
Tensor<float>* tensor = new Tensor<float>({3,3,3});
assert(tensor->GetIdx({2,2,2})==26);
assert(tensor->GetIdx({1,2,2})==17);
assert(tensor->GetIdx({2,1,2})==23);
assert(tensor->GetIdx({2,2,1})==25);
delete tensor;
}
void test_gaussian_kernel() {
std::cout<< "Testing gaussian kernel initializer .. "<<std::endl;
std::cout<<Session::GetNewSession()->gpu<<std::endl;
Tensor<float>* W = new Tensor<float>({5,5,1,1});
Tensor<float>* b = new Tensor<float>({1});
GaussianKernelInitializer<float>(5.0).Initialize(W, b);
for (unsigned i = 0; i < W->GetDims()[0]; i++) {
for (unsigned j = 0; j < W->GetDims()[1]; j++) {
std::cout<<W->at({i, j, 0, 0})<<"\t";
}
std::cout<<std::endl;
}
delete W;
delete b;
}
int main(void) {
test_conv_layer();
test_tensor();
test_session();
test_gaussian_kernel();
}<commit_msg>update tests<commit_after>#include <iostream>
#include "layers/conv2d.hpp"
#include "basics/tensor.hpp"
#include "basics/session.hpp"
#include "initializers/gaussian_kernel_initializer.hpp"
#include <assert.h>
#include <cmath>
void test_session() {
std::cout<< "Testing Session .."<<std::endl;
Session* session = Session::GetSession();
session->gpu = true;
std::cout<< "use gpu: "<< session->gpu <<std::endl;
}
void test_conv_layer() {
std::cout<< "Testing Conv2D .."<<std::endl;
// inputs: filter_height, filter_width, in_channels, out_channels, stride
Conv2D<float>* conv_layer = new Conv2D<float>(5, 5, 3, 5, 1);
assert(conv_layer->kernel_height==5);
assert(conv_layer->kernel_width==5);
assert(conv_layer->in_channels==3);
assert(conv_layer->out_channels==5);
assert(conv_layer->stride==1);
delete conv_layer;
}
void test_tensor() {
std::cout<< "Testing Tensor .."<<std::endl;
// inputs: tensor dimensions
Tensor<float>* tensor = new Tensor<float>({3,3,3});
assert(tensor->GetIdx({2,2,2})==26);
assert(tensor->GetIdx({1,2,2})==17);
assert(tensor->GetIdx({2,1,2})==23);
assert(tensor->GetIdx({2,2,1})==25);
delete tensor;
}
void test_gaussian_kernel() {
std::cout<< "Testing gaussian kernel initializer .. "<<std::endl;
std::cout<<Session::GetNewSession()->gpu<<std::endl;
Tensor<float>W = Tensor<float>({5,5,1,1});
Tensor<float>b = Tensor<float>({1});
GaussianKernelInitializer<float>(5.0).Initialize(&W, &b);
double sum = 0.0;
for (unsigned i = 0; i < W.GetDims()[0]; i++) {
for (unsigned j = 0; j < W.GetDims()[1]; j++) {
sum += W.at({i, j, 0, 0});
std::cout<<W.at({i, j, 0, 0})<<"\t";
}
std::cout<<std::endl;
}
assert(std::abs(sum-1.0)<0.00001);
}
int main(void) {
test_conv_layer();
test_tensor();
test_session();
test_gaussian_kernel();
}<|endoftext|> |
<commit_before>8c3d2100-2d14-11e5-af21-0401358ea401<commit_msg>8c3d2101-2d14-11e5-af21-0401358ea401<commit_after>8c3d2101-2d14-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>f5155c23-2e4e-11e5-86e8-28cfe91dbc4b<commit_msg>f51baf17-2e4e-11e5-9fb4-28cfe91dbc4b<commit_after>f51baf17-2e4e-11e5-9fb4-28cfe91dbc4b<|endoftext|> |
<commit_before>8e9faba9-2d14-11e5-af21-0401358ea401<commit_msg>8e9fabaa-2d14-11e5-af21-0401358ea401<commit_after>8e9fabaa-2d14-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>bb63bd3a-327f-11e5-82a8-9cf387a8033e<commit_msg>bb69d5d9-327f-11e5-ac10-9cf387a8033e<commit_after>bb69d5d9-327f-11e5-ac10-9cf387a8033e<|endoftext|> |
<commit_before>b9d41200-35ca-11e5-bc49-6c40088e03e4<commit_msg>b9dad838-35ca-11e5-8845-6c40088e03e4<commit_after>b9dad838-35ca-11e5-8845-6c40088e03e4<|endoftext|> |
<commit_before>#include "opencv2/imgproc.hpp"
#include "opencv2/highgui.hpp"
/* #include "opencv2/gpu/gpu.hpp" */
#include <iostream>
#include <string>
#include <stdlib.h>
using namespace std;
using namespace cv;
int run_video(char* file);
void on_lRed_thresh_trackbar(int, void *);
void on_uRed_thresh_trackbar(int, void *);
void on_lGreen_thresh_trackbar(int, void *);
void on_uGreen_thresh_trackbar(int, void *);
void on_lBlue_thresh_trackbar(int, void *);
void on_uBlue_thresh_trackbar(int, void *);
//RGB RANGE
//int lRed = 0, lGreen = 215, lBlue = 0, uRed = 179, uGreen = 255, uBlue = 241;
//HSV RANGE
int lBlue = 80, lGreen = 220, lRed = 130, uBlue = 130, uGreen = 255, uRed = 255;
/* int lH = 48, lS = 80, lV = 210, uH = 80, uS = 246, uV = 255; */
int main(int v,char* argv[]){
//VideoCapture cap("nvcamerasrc ! video/x-raw(memory:NVMM), width=(int)1280, height=(int)720,format=(string)I420, framerate=(fraction)24/1 ! nvvidconv flip-method=2 ! video/x-raw, format=(string)BGRx ! videoconvert ! video/x-raw, format=(string)BGR ! appsink"); //open the default camera
cout << argv[1] << "\n";
/* namedWindow("original", WINDOW_NORMAL); */
namedWindow("filtered", WINDOW_NORMAL);
/* namedWindow("hsv", WINDOW_NORMAL); */
createTrackbar("Low R","filtered", &lRed, 255, on_lRed_thresh_trackbar);
createTrackbar("High R","filtered", &uRed, 255, on_uRed_thresh_trackbar);
createTrackbar("Low G","filtered", &lGreen, 255, on_lGreen_thresh_trackbar);
createTrackbar("High G","filtered", &uGreen, 255, on_uGreen_thresh_trackbar);
createTrackbar("Low B","filtered", &lBlue, 255, on_lBlue_thresh_trackbar);
createTrackbar("High B","filtered", &uBlue, 255, on_uBlue_thresh_trackbar);
while(1) { run_video(argv[1]); }
return 0;
}
int run_video(char* file)
{
Mat hsv, hsv_blur, filter, edged;
Mat map1, map2, cameraMatrix, distCoeffs, imageSize;
int largest_area = 0, largest_contour_index=0;
double focalLength = 1089.88;//1084.36;
double distance;
Rect bounding_rect;
Size imageSize;
vector<vector<Point> > contours;
vector<Vec4i> hierarchy;
VideoCapture cap;
cap.set(CV_CAP_PROP_FRAME_WIDTH, 1280);
cap.set(CV_CAP_PROP_FRAME_HEIGHT, 720);
cap.open(0);
//cap.set(CV_CAP_PROP_FOURCC, CV_FOURCC('A','V','C',1));
//cap.open(0);
if(!cap.isOpened()) { // check if we succeeded
cerr << "Fail to open camera " << endl;
return 0;
}
cameraMatrix = Mat::eye(3, 3, CV_64F);
initUndistortRectifyMap(cameraMatrix, distCoeffs, Mat(), getOptimalNewCameraMatrix(cameraMatrix, distCoeffs, imageSize, 1, imageSize, 0), imageSize, CV_16SC2, map1, map2);
for(;;)
{
Mat frame, smallerframe;
cap.read(frame); // get a new frame from camera
Mat temp = frame.clone();
undistort(temp, frame, cameraMatrix, distCoeffs);
resize(frame, smallerframe, Size(480,320));
cvtColor(smallerframe, hsv, COLOR_BGR2HSV);
inRange(hsv, Scalar(lBlue, lGreen, lRed), Scalar(uBlue, uGreen, uRed), filter);
//GaussianBlur(hsv, hsv_blur, Size(3, 3), 0, 0);
/* inRange(hsv, Scalar(lH, lS, lV), Scalar(uH, uS, uV), filter); */
/* imshow("hsv", hsv); */
/* cv::Canny(filter, edged, 35, 125, 3); */
/* cv::findContours(edged, contours, hierarchy, CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE, Point(0, 0)); */
/* for (size_t i=0; i<contours.size(); i++) */
/* { */
/* double area = contourArea ( contours[i]); */
/* if (area > largest_area) */
/* { */
/* largest_area = area; */
/* largest_contour_index = i; */
/* bounding_rect = boundingRect( contours[i]); */
/* } */
/* } */
/* drawContours(filter, contours, largest_contour_index, Scalar( 0, 255, 0 ), 2); */
/* distance = focalLength * 4.0 / bounding_rect.height; */
/* std::string title = std::to_string(distance) + "(in)"; */
/* putText(frame, title, Point(50, 50), FONT_HERSHEY_SIMPLEX, 1, Scalar(0,255,0)); */
cout<<"r"<<lRed<<" "<<uRed<<"b"<<lBlue<<" "<<uBlue<<"g"<<lGreen<<" "<<uGreen<<endl;
largest_contour_index = 0;
largest_area = 0;
/* imshow("original", frame); */
imshow("filtered", filter);
waitKey(1);
}
// the camera will be deinitialized automatically in VideoCapture destructor
cap.release();
return 1;
}
void on_lRed_thresh_trackbar(int, void *)
{
lRed = min(uRed-1, lRed);
setTrackbarPos("Low R","filtered", lRed);
}
void on_uRed_thresh_trackbar(int, void *)
{
uRed = max(uRed, lRed+1);
setTrackbarPos("High R", "filtered", uRed);
}
void on_lGreen_thresh_trackbar(int, void *)
{
lGreen = min(uGreen-1, lGreen);
setTrackbarPos("Low G","filtered", lGreen);
}
void on_uGreen_thresh_trackbar(int, void *)
{
uGreen = max(uGreen, lGreen+1);
setTrackbarPos("High G", "filtered", uGreen);
}
void on_lBlue_thresh_trackbar(int, void *)
{
lBlue= min(uBlue-1, lBlue);
setTrackbarPos("Low B","filtered", lBlue);
}
void on_uBlue_thresh_trackbar(int, void *)
{
uBlue = max(uBlue, lBlue+1);
setTrackbarPos("High B", "filtered", uBlue);
}
/*#include <opencv2/opencv.hpp>
using namespace cv;
int main()
{
string gst = "nvcamerasrc ! video/x-raw(memory:NVMM), width=(int)1280, height=(int)720, format=(string)I420, framerate=(fraction)24/1 ! nvvidconv flip-method=2 ! video/x-raw, format=(string)BGRx ! videoconvert ! video/x-raw, format(string)BGR ! appsink";
cv::Mat img;
VideoCapture input(1);
namedWindow("img", 1);
while(true){
Mat frame;
input.read(frame);
imshow("img", frame);
if(waitKey(30)>=0){
break;
}
}
}*/
<commit_msg>hsvFiltering<commit_after>#include "opencv2/imgproc.hpp"
#include "opencv2/highgui.hpp"
/* #include "opencv2/gpu/gpu.hpp" */
#include <iostream>
#include <string>
#include <stdlib.h>
using namespace std;
using namespace cv;
int run_video(char* file);
void on_lRed_thresh_trackbar(int, void *);
void on_uRed_thresh_trackbar(int, void *);
void on_lGreen_thresh_trackbar(int, void *);
void on_uGreen_thresh_trackbar(int, void *);
void on_lBlue_thresh_trackbar(int, void *);
void on_uBlue_thresh_trackbar(int, void *);
//RGB RANGE
//int lRed = 0, lGreen = 215, lBlue = 0, uRed = 179, uGreen = 255, uBlue = 241;
//HSV RANGE
int lBlue = 80, lGreen = 220, lRed = 130, uBlue = 130, uGreen = 255, uRed = 255;
/* int lH = 48, lS = 80, lV = 210, uH = 80, uS = 246, uV = 255; */
int main(int v,char* argv[]){
//VideoCapture cap("nvcamerasrc ! video/x-raw(memory:NVMM), width=(int)1280, height=(int)720,format=(string)I420, framerate=(fraction)24/1 ! nvvidconv flip-method=2 ! video/x-raw, format=(string)BGRx ! videoconvert ! video/x-raw, format=(string)BGR ! appsink"); //open the default camera
cout << argv[1] << "\n";
/* namedWindow("original", WINDOW_NORMAL); */
namedWindow("filtered", WINDOW_NORMAL);
/* namedWindow("hsv", WINDOW_NORMAL); */
createTrackbar("Low R","filtered", &lRed, 255, on_lRed_thresh_trackbar);
createTrackbar("High R","filtered", &uRed, 255, on_uRed_thresh_trackbar);
createTrackbar("Low G","filtered", &lGreen, 255, on_lGreen_thresh_trackbar);
createTrackbar("High G","filtered", &uGreen, 255, on_uGreen_thresh_trackbar);
createTrackbar("Low B","filtered", &lBlue, 255, on_lBlue_thresh_trackbar);
createTrackbar("High B","filtered", &uBlue, 255, on_uBlue_thresh_trackbar);
while(1) { run_video(argv[1]); }
return 0;
}
int run_video(char* file)
{
Mat hsv, hsv_blur, filter, edged;
//Mat map1, map2, cameraMatrix, distCoeffs, imageSize;
int largest_area = 0, largest_contour_index=0;
double focalLength = 1089.88;//1084.36;
double distance;
Rect bounding_rect;
Size imageSize;
vector<vector<Point> > contours;
vector<Vec4i> hierarchy;
VideoCapture cap;
cap.set(CV_CAP_PROP_FRAME_WIDTH, 1280);
cap.set(CV_CAP_PROP_FRAME_HEIGHT, 720);
cap.open(0);
//cap.set(CV_CAP_PROP_FOURCC, CV_FOURCC('A','V','C',1));
//cap.open(0);
if(!cap.isOpened()) { // check if we succeeded
cerr << "Fail to open camera " << endl;
return 0;
}
//cameraMatrix = Mat::eye(3, 3, CV_64F);
//initUndistortRectifyMap(cameraMatrix, distCoeffs, Mat(), getOptimalNewCameraMatrix(cameraMatrix, distCoeffs, imageSize, 1, imageSize, 0), imageSize, CV_16SC2, map1, map2);
for(;;)
{
Mat frame, smallerframe;
cap.read(frame); // get a new frame from camera
//Mat temp = frame.clone();
//undistort(temp, frame, cameraMatrix, distCoeffs);
resize(frame, smallerframe, Size(480,320));
cvtColor(smallerframe, hsv, COLOR_BGR2HSV);
inRange(hsv, Scalar(lBlue, lGreen, lRed), Scalar(uBlue, uGreen, uRed), filter);
//GaussianBlur(hsv, hsv_blur, Size(3, 3), 0, 0);
/* inRange(hsv, Scalar(lH, lS, lV), Scalar(uH, uS, uV), filter); */
/* imshow("hsv", hsv); */
/* cv::Canny(filter, edged, 35, 125, 3); */
/* cv::findContours(edged, contours, hierarchy, CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE, Point(0, 0)); */
/* for (size_t i=0; i<contours.size(); i++) */
/* { */
/* double area = contourArea ( contours[i]); */
/* if (area > largest_area) */
/* { */
/* largest_area = area; */
/* largest_contour_index = i; */
/* bounding_rect = boundingRect( contours[i]); */
/* } */
/* } */
/* drawContours(filter, contours, largest_contour_index, Scalar( 0, 255, 0 ), 2); */
/* distance = focalLength * 4.0 / bounding_rect.height; */
/* std::string title = std::to_string(distance) + "(in)"; */
/* putText(frame, title, Point(50, 50), FONT_HERSHEY_SIMPLEX, 1, Scalar(0,255,0)); */
cout<<"r"<<lRed<<" "<<uRed<<"b"<<lBlue<<" "<<uBlue<<"g"<<lGreen<<" "<<uGreen<<endl;
largest_contour_index = 0;
largest_area = 0;
//imshow("original", frame);
imshow("filtered", filter);
waitKey(1);
}
// the camera will be deinitialized automatically in VideoCapture destructor
cap.release();
return 1;
}
void on_lRed_thresh_trackbar(int, void *)
{
lRed = min(uRed-1, lRed);
setTrackbarPos("Low R","filtered", lRed);
}
void on_uRed_thresh_trackbar(int, void *)
{
uRed = max(uRed, lRed+1);
setTrackbarPos("High R", "filtered", uRed);
}
void on_lGreen_thresh_trackbar(int, void *)
{
lGreen = min(uGreen-1, lGreen);
setTrackbarPos("Low G","filtered", lGreen);
}
void on_uGreen_thresh_trackbar(int, void *)
{
uGreen = max(uGreen, lGreen+1);
setTrackbarPos("High G", "filtered", uGreen);
}
void on_lBlue_thresh_trackbar(int, void *)
{
lBlue= min(uBlue-1, lBlue);
setTrackbarPos("Low B","filtered", lBlue);
}
void on_uBlue_thresh_trackbar(int, void *)
{
uBlue = max(uBlue, lBlue+1);
setTrackbarPos("High B", "filtered", uBlue);
}
/*#include <opencv2/opencv.hpp>
using namespace cv;
int main()
{
string gst = "nvcamerasrc ! video/x-raw(memory:NVMM), width=(int)1280, height=(int)720, format=(string)I420, framerate=(fraction)24/1 ! nvvidconv flip-method=2 ! video/x-raw, format=(string)BGRx ! videoconvert ! video/x-raw, format(string)BGR ! appsink";
cv::Mat img;
VideoCapture input(1);
namedWindow("img", 1);
while(true){
Mat frame;
input.read(frame);
imshow("img", frame);
if(waitKey(30)>=0){
break;
}
}
}*/
<|endoftext|> |
<commit_before>#include <iostream>
#include <string>
#include <fstream>
#include <ctime>
#include <cstdlib>
using namespace std;
//벻Ҫ²ע T T
string instrn[8][20] = {{"1","addu","subu","slt","sltu","sllv","srlv","srav","and","or","xor","nor","end"},
{"0","addiu","subiu","slti","sltiu","andi","ori","xori","end"},
{"1","beq","bne","end"},
{"0","sb","sh","sw","end"},
{"0","mthi","mtlo","end"},
{"1","mult","multu","div","divu","end"},
{"0","blez","bgtz","bltz","bgez","end"},
{"0","sll","sra","srl","end"}};
string instrf[6][20] = {{"addu","subu","slt","sltu","srl","sllv","srlv","srav","and","or","xor","nor","end"},
{"addiu","subiu","slti","sltiu","andi","ori","xori","end"},
{"lb","lbu","lh","lhu","lw","end"},
{"mfhi","mflo","end"},
{"lui","end"},
{"sll","sra","srl","end"}};
int label = 0;
int offset = 0;
int rdmnum(int width)
{
return rand()%width; //rand趨Χ
}
void Nowinstr(string instr, int tag, int type)
{
ofstream code;
int rdm1, rdm2, rdm3;
rdm1 = rdmnum(6);
rdm2 = rdmnum(6); //0-6
rdm3 = rdmnum(65536);
code.open("code.txt",ios::app);
switch(type)
{
case 2: //btype-1
{
if(tag)
{
code << instr << " $t0 $s" << rdm1 << " to" << label << "\n";
code << "nop\n";
code << "to" << label << ": addi $t7 $t7 1\nnop\n";
label++;
}
else
{
code << instr << " $s" << rdm1 << " $t0 to" << label << "\n";
code << "nop\n";
code << "to" << label << ": addi $t7 $t7 1\nnop\n";
label++;
}
break;
}
case 6: //btype-2
{
code << instr << " $t0 to" << label << "\n";
code << "nop\n";
code << "to" << label << ": addi $t7 $t7 1\nnop\n";
label++;
break;
}
case 0: //r
{
if(tag)
{
code << instr << " $t1 $s" << rdm1 << " $t0" << "\n";
code << "sw" << " $t1 " << offset << "($s7)\n";
offset+=4;
}
else
{
code << instr << " $t1 $t0 $s" << rdm1 << "\n";
code << "sw" << " $t1 " << offset << "($s7)\n";
offset+=4;
}
break;
}
case 1: //i
{
code << instr << " $t1 $t0 " << rdm3 << "\n";
code << "sw" << " $t1 " << offset << "($s7)\n";
offset+=4;
break;
}
case 3: //store
{
code << instr << " $t0 " << offset << "($s7)\n";
offset+=4;
break;
}
case 4: //mt
{
code << instr << " $t0\n";
break;
}
case 5: //muldiv
{
if(tag)
{
code << instr << " $t0 $s" << rdm1 << "\n";
}
else
{
code << instr << " $s" << rdm2 << " $t0\n";
}
break;
}
case 7:
{
code << instr << " $t1 $t0 "<< rdm2 << "\n";
code << "sw" << " $t1 " << offset << "($s7)\n";
offset+=4;
break;
}
}
code.close();
}
void Forwardinstr(string instr, int type)
{
ofstream code;
int rdm1, rdm2, rdm3;
rdm1 = rdmnum(6);
rdm2 = rdmnum(6); //0-6
rdm3 = rdmnum(65536); //2^16
code.open("code.txt",ios::app);
switch(type)
{
case 0: //r
{
code << instr << " $t0 $s" << rdm1 << " $s" << rdm2 << "\n";
break;
}
case 1: //i
{
code << instr << " $t0 $s" << rdm1 << " " << rdm3 << "\n";
break;
}
case 3: //mf
{
code << instr << " $t0" << "\n";
break;
}
case 2: //load
{
if(offset==0)
code << instr << " $t0 "<< offset <<"($s7)\n";
else
code << instr << " $t0 "<< offset-4 <<"($s7)\n";
break;
}
case 4:
{
code << instr << " $t0 " << rdm3 << "\n";
break;
}
case 5:
{
code << instr << " $t0 $s" << rdm1 << " " << rdm2 << "\n";
break;
}
}
code.close();
}
int main()
{
srand((unsigned)time(NULL)); //ڱ֤
ofstream clearcode;
clearcode.open("code.txt");
clearcode << "#initial\n";
clearcode << "addi $s0 $0 100\naddi $s1 $0 1234\naddi $s2 $0 134345\naddi $s3 $0 111111\nlui $s5 0xABCD\nlui $s6 0x1A24\n";
clearcode << "#initial done\n";
clearcode.close();
int func; // func
cout << "-------------------CODE AUTO MAKER------------------------------------------\n";
cout << "| Powered By Henry Liu |\n";
cout << "| From Padio Planet |\n";
cout << "| Version 0.1 |\n";
cout << "| Contact 583448542@qq.com |\n";
cout << "----------------------------------------------------------------------------\n";
cout << "\n\nPlease read the README.txt first.";
cout << "\n\nPlease input the function code: (0|1|2)";
cin >> func;
while(func<0||func>2)
{
cout << "function code is wrong. Please input 0|1|2\n";
cin >> func;
}
switch(func)
{
case 0:
{
for(int i=0; i<6; i++)
{
int indexi = 0; //ÿһе±
while(instrf[i][indexi] != "end")
{
for(int j=0; j<8; j++)
{
int indexj = 1;
int tag; //tag = 1 rs,rtͻ
if(instrn[j][0] == "0")
tag = 0;
else
tag = 1;
while(instrn[j][indexj] != "end")
{
while(tag >= 0)
{
ofstream insertnop;
Forwardinstr(instrf[i][indexi],i);
Nowinstr(instrn[j][indexj],tag,j);
insertnop.open("code.txt",ios::app);
insertnop << "\n";
insertnop.close();
Forwardinstr(instrf[i][indexi],i);
insertnop.open("code.txt",ios::app);
insertnop << "nop\n";
insertnop.close();
Nowinstr(instrn[j][indexj],tag,j);
insertnop.open("code.txt",ios::app);
insertnop << "\n";
insertnop.close();
Forwardinstr(instrf[i][indexi],i);
insertnop.open("code.txt",ios::app);
insertnop << "nop\n";
insertnop << "nop\n";
insertnop.close();
Nowinstr(instrn[j][indexj],tag,j);
insertnop.open("code.txt",ios::app);
insertnop << "\n";
insertnop.close();
tag--;
}
indexj++;
}
if(offset >= 100)
{
ofstream insertnop;
insertnop.open("code.txt",ios::app);
insertnop << "\n\n\n#-----------------------------------------ķָ---------------------------------------------\n";
insertnop << "\n\n\n";
insertnop.close();
offset = 0;
}
}
indexi++;
}
}
break;
}
case 1:
{
for(int i=0; i<6; i++)
{
int indexi = 0; //ÿһе±
while(indexi != 2)
{
for(int j=0; j<8; j++)
{
int indexj = 1;
int tag; //tag = 1 rs,rtͻ
if(instrn[j][0] == "0")
tag = 0;
else
tag = 1;
while(indexj != 2)
{
while(tag >= 0)
{
ofstream insertnop;
Forwardinstr(instrf[i][indexi],i);
Nowinstr(instrn[j][indexj],tag,j);
insertnop.open("code.txt",ios::app);
insertnop << "\n";
insertnop.close();
Forwardinstr(instrf[i][indexi],i);
insertnop.open("code.txt",ios::app);
insertnop << "nop\n";
insertnop.close();
Nowinstr(instrn[j][indexj],tag,j);
insertnop.open("code.txt",ios::app);
insertnop << "\n";
insertnop.close();
Forwardinstr(instrf[i][indexi],i);
insertnop.open("code.txt",ios::app);
insertnop << "nop\n";
insertnop << "nop\n";
insertnop.close();
Nowinstr(instrn[j][indexj],tag,j);
insertnop.open("code.txt",ios::app);
insertnop << "\n";
insertnop.close();
tag--;
}
indexj++;
}
}
indexi++;
}
}
break;
}
case 2:
{
int number;
cout << "Please input the number of instruction pairs you needed: ";
cin >> number;
for(int i=0; i<number; i++)
{
ofstream insertnop;
int fline, fcolumn, nline, ncolumn, nopnum, tag;
fline = rdmnum(6);
nline = rdmnum(8);
nopnum = rdmnum(3);
tag = rdmnum(2);
switch(fline)
{
case 0:
{
fcolumn = rdmnum(11);
break;
}
case 1:
{
fcolumn = rdmnum(7);
break;
}
case 2:
{
fcolumn = rdmnum(4);
break;
}
case 3:
{
fcolumn = rdmnum(2);
break;
}
case 4:
{
fcolumn = 0;
break;
}
case 5:
{
fcolumn = rdmnum(3);
break;
}
}
switch(nline)
{
case 0:
{
ncolumn = rdmnum(11)+1;
break;
}
case 1:
{
ncolumn = rdmnum(7)+1;
break;
}
case 2:
{
ncolumn = rdmnum(2)+1;
break;
}
case 3:
{
ncolumn = rdmnum(3)+1;
break;
}
case 4:
{
ncolumn = rdmnum(2)+1;
break;
}
case 5:
{
ncolumn = rdmnum(4)+1;
break;
}
case 6:
{
ncolumn = rdmnum(4)+1;
break;
}
case 7:
{
ncolumn = rdmnum(3)+1;
break;
}
}
Forwardinstr(instrf[fline][fcolumn],fline);
insertnop.open("code.txt",ios::app);
for(int j=0;j<nopnum;j++)
{
insertnop << "nop\n";
}
insertnop.close();
Nowinstr(instrn[nline][ncolumn],tag,nline);
}
break;
}
}
cout << "\nThe generating is done, Please check your code.txt\n";
return 0;
}
<commit_msg>v0.4 solve little errors<commit_after>#include <iostream>
#include <string>
#include <fstream>
#include <ctime>
#include <cstdlib>
using namespace std;
//벻Ҫ²ע T T
string instrn[8][20] = {{"1","addu","subu","slt","sltu","sllv","srlv","srav","and","or","xor","nor","end"},
{"0","addiu","subiu","slti","sltiu","andi","ori","xori","end"},
{"1","beq","bne","end"},
{"0","sb","sh","sw","end"},
{"0","mthi","mtlo","end"},
{"1","mult","multu","div","divu","end"},
{"0","blez","bgtz","bltz","bgez","end"},
{"0","sll","sra","srl","end"}};
string instrf[6][20] = {{"addu","subu","slt","sltu","sllv","srlv","srav","and","or","xor","nor","end"},
{"addiu","subiu","slti","sltiu","andi","ori","xori","end"},
{"lb","lbu","lh","lhu","lw","end"},
{"mfhi","mflo","end"},
{"lui","end"},
{"sll","sra","srl","end"}};
int label = 0;
int offset = 0;
int rdmnum(int width)
{
return rand()%width; //rand趨Χ
}
void Nowinstr(string instr, int tag, int type)
{
ofstream code;
int rdm1, rdm2, rdm3;
rdm1 = rdmnum(6);
rdm2 = rdmnum(6); //0-6
rdm3 = rdmnum(65536);
code.open("code.txt",ios::app);
switch(type)
{
case 2: //btype-1
{
if(tag)
{
code << instr << " $t0 $s" << rdm1 << " to" << label << "\n";
code << "nop\n";
code << "to" << label << ": addi $t7 $t7 1\nnop\n";
label++;
}
else
{
code << instr << " $s" << rdm1 << " $t0 to" << label << "\n";
code << "nop\n";
code << "to" << label << ": addi $t7 $t7 1\nnop\n";
label++;
}
break;
}
case 6: //btype-2
{
code << instr << " $t0 to" << label << "\n";
code << "nop\n";
code << "to" << label << ": addi $t7 $t7 1\nnop\n";
label++;
break;
}
case 0: //r
{
if(tag)
{
code << instr << " $t1 $s" << rdm1 << " $t0" << "\n";
code << "sw" << " $t1 " << offset << "($s7)\n";
offset+=4;
}
else
{
code << instr << " $t1 $t0 $s" << rdm1 << "\n";
code << "sw" << " $t1 " << offset << "($s7)\n";
offset+=4;
}
break;
}
case 1: //i
{
code << instr << " $t1 $t0 " << rdm3 << "\n";
code << "sw" << " $t1 " << offset << "($s7)\n";
offset+=4;
break;
}
case 3: //store
{
code << instr << " $t0 " << offset << "($s7)\n";
offset+=4;
break;
}
case 4: //mt
{
code << instr << " $t0\n";
break;
}
case 5: //muldiv
{
if(tag)
{
code << instr << " $t0 $s" << rdm1 << "\n";
}
else
{
code << instr << " $s" << rdm2 << " $t0\n";
}
break;
}
case 7:
{
code << instr << " $t1 $t0 "<< rdm2 << "\n";
code << "sw" << " $t1 " << offset << "($s7)\n";
offset+=4;
break;
}
}
code.close();
}
void Forwardinstr(string instr, int type)
{
ofstream code;
int rdm1, rdm2, rdm3;
rdm1 = rdmnum(6);
rdm2 = rdmnum(6); //0-6
rdm3 = rdmnum(65536); //2^16
code.open("code.txt",ios::app);
switch(type)
{
case 0: //r
{
code << instr << " $t0 $s" << rdm1 << " $s" << rdm2 << "\n";
break;
}
case 1: //i
{
code << instr << " $t0 $s" << rdm1 << " " << rdm3 << "\n";
break;
}
case 3: //mf
{
code << instr << " $t0" << "\n";
break;
}
case 2: //load
{
if(offset==0)
code << instr << " $t0 "<< offset <<"($s7)\n";
else
code << instr << " $t0 "<< offset-4 <<"($s7)\n";
break;
}
case 4:
{
code << instr << " $t0 " << rdm3 << "\n";
break;
}
case 5:
{
code << instr << " $t0 $s" << rdm1 << " " << rdm2 << "\n";
break;
}
}
code.close();
}
int main()
{
srand((unsigned)time(NULL)); //ڱ֤
ofstream clearcode;
clearcode.open("code.txt");
clearcode << "#initial\n";
clearcode << "addi $s0 $0 100\naddi $s1 $0 1234\naddi $s2 $0 134345\naddi $s3 $0 111111\nlui $s5 0xABCD\nlui $s6 0x1A24\n";
clearcode << "#initial done\n";
clearcode.close();
int func; // func
cout << "-------------------CODE AUTO MAKER------------------------------------------\n";
cout << "| Powered By Henry Liu |\n";
cout << "| From Padio Planet |\n";
cout << "| Version 0.1 |\n";
cout << "| Contact 583448542@qq.com |\n";
cout << "----------------------------------------------------------------------------\n";
cout << "\n\nPlease read the README.txt first.";
cout << "\n\nPlease input the function code: (0|1|2)";
cin >> func;
while(func<0||func>2)
{
cout << "function code is wrong. Please input 0|1|2\n";
cin >> func;
}
switch(func)
{
case 0:
{
for(int i=0; i<6; i++)
{
int indexi = 0; //ÿһе±
while(instrf[i][indexi] != "end")
{
for(int j=0; j<8; j++)
{
int indexj = 1;
int tag; //tag = 1 rs,rtͻ
if(instrn[j][0] == "0")
tag = 0;
else
tag = 1;
while(instrn[j][indexj] != "end")
{
while(tag >= 0)
{
ofstream insertnop;
Forwardinstr(instrf[i][indexi],i);
Nowinstr(instrn[j][indexj],tag,j);
insertnop.open("code.txt",ios::app);
insertnop << "\n";
insertnop.close();
Forwardinstr(instrf[i][indexi],i);
insertnop.open("code.txt",ios::app);
insertnop << "nop\n";
insertnop.close();
Nowinstr(instrn[j][indexj],tag,j);
insertnop.open("code.txt",ios::app);
insertnop << "\n";
insertnop.close();
Forwardinstr(instrf[i][indexi],i);
insertnop.open("code.txt",ios::app);
insertnop << "nop\n";
insertnop << "nop\n";
insertnop.close();
Nowinstr(instrn[j][indexj],tag,j);
insertnop.open("code.txt",ios::app);
insertnop << "\n";
insertnop.close();
tag--;
}
indexj++;
}
if(offset >= 100)
{
ofstream insertnop;
insertnop.open("code.txt",ios::app);
insertnop << "\n\n\n#-----------------------------------------ķָ---------------------------------------------\n";
insertnop << "\n\n\n";
insertnop.close();
offset = 0;
}
}
indexi++;
}
}
break;
}
case 1:
{
for(int i=0; i<6; i++)
{
int indexi = 0; //ÿһе±
while(indexi != 2)
{
for(int j=0; j<8; j++)
{
int indexj = 1;
int tag; //tag = 1 rs,rtͻ
if(instrn[j][0] == "0")
tag = 0;
else
tag = 1;
while(indexj != 2)
{
while(tag >= 0)
{
ofstream insertnop;
Forwardinstr(instrf[i][indexi],i);
Nowinstr(instrn[j][indexj],tag,j);
insertnop.open("code.txt",ios::app);
insertnop << "\n";
insertnop.close();
Forwardinstr(instrf[i][indexi],i);
insertnop.open("code.txt",ios::app);
insertnop << "nop\n";
insertnop.close();
Nowinstr(instrn[j][indexj],tag,j);
insertnop.open("code.txt",ios::app);
insertnop << "\n";
insertnop.close();
Forwardinstr(instrf[i][indexi],i);
insertnop.open("code.txt",ios::app);
insertnop << "nop\n";
insertnop << "nop\n";
insertnop.close();
Nowinstr(instrn[j][indexj],tag,j);
insertnop.open("code.txt",ios::app);
insertnop << "\n";
insertnop.close();
tag--;
}
indexj++;
}
}
indexi++;
}
}
break;
}
case 2:
{
int number;
cout << "Please input the number of instruction pairs you needed: ";
cin >> number;
for(int i=0; i<number; i++)
{
ofstream insertnop;
int fline, fcolumn, nline, ncolumn, nopnum, tag;
fline = rdmnum(6);
nline = rdmnum(8);
nopnum = rdmnum(3);
tag = rdmnum(2);
switch(fline)
{
case 0:
{
fcolumn = rdmnum(11);
break;
}
case 1:
{
fcolumn = rdmnum(7);
break;
}
case 2:
{
fcolumn = rdmnum(4);
break;
}
case 3:
{
fcolumn = rdmnum(2);
break;
}
case 4:
{
fcolumn = 0;
break;
}
case 5:
{
fcolumn = rdmnum(3);
break;
}
}
switch(nline)
{
case 0:
{
ncolumn = rdmnum(11)+1;
break;
}
case 1:
{
ncolumn = rdmnum(7)+1;
break;
}
case 2:
{
ncolumn = rdmnum(2)+1;
break;
}
case 3:
{
ncolumn = rdmnum(3)+1;
break;
}
case 4:
{
ncolumn = rdmnum(2)+1;
break;
}
case 5:
{
ncolumn = rdmnum(4)+1;
break;
}
case 6:
{
ncolumn = rdmnum(4)+1;
break;
}
case 7:
{
ncolumn = rdmnum(3)+1;
break;
}
}
Forwardinstr(instrf[fline][fcolumn],fline);
insertnop.open("code.txt",ios::app);
for(int j=0;j<nopnum;j++)
{
insertnop << "nop\n";
}
insertnop.close();
Nowinstr(instrn[nline][ncolumn],tag,nline);
}
break;
}
}
cout << "\nThe generating is done, Please check your code.txt\n";
return 0;
}
<|endoftext|> |
<commit_before>db8957d9-2e4e-11e5-8d0f-28cfe91dbc4b<commit_msg>db90e270-2e4e-11e5-b12e-28cfe91dbc4b<commit_after>db90e270-2e4e-11e5-b12e-28cfe91dbc4b<|endoftext|> |
<commit_before>e5eb693a-585a-11e5-ab73-6c40088e03e4<commit_msg>e5f28440-585a-11e5-9b10-6c40088e03e4<commit_after>e5f28440-585a-11e5-9b10-6c40088e03e4<|endoftext|> |
<commit_before>6647888c-2e3a-11e5-9f70-c03896053bdd<commit_msg>66563140-2e3a-11e5-aea9-c03896053bdd<commit_after>66563140-2e3a-11e5-aea9-c03896053bdd<|endoftext|> |
<commit_before>7b9d6c80-5216-11e5-aa89-6c40088e03e4<commit_msg>7ba44b90-5216-11e5-857c-6c40088e03e4<commit_after>7ba44b90-5216-11e5-857c-6c40088e03e4<|endoftext|> |
<commit_before>4b30d6cc-2748-11e6-a463-e0f84713e7b8<commit_msg>That didn't fix it<commit_after>4b3d4d63-2748-11e6-bf0a-e0f84713e7b8<|endoftext|> |
<commit_before>8b332522-2d14-11e5-af21-0401358ea401<commit_msg>8b332523-2d14-11e5-af21-0401358ea401<commit_after>8b332523-2d14-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>f745ddde-2747-11e6-9ecc-e0f84713e7b8<commit_msg>Really doesn't crash if X, now<commit_after>f75915f0-2747-11e6-8c5a-e0f84713e7b8<|endoftext|> |
<commit_before>77ad4735-2749-11e6-912f-e0f84713e7b8<commit_msg>new flies<commit_after>77bc56c2-2749-11e6-8fbc-e0f84713e7b8<|endoftext|> |
<commit_before>#include <iostream>
#include <string>
#include <fstream>
#include "main.h"
#include "extraction.h"
#include "bond_angle.cpp"
#include "elements.cpp"
#include "bond_length.cpp"
#include "bond_angle.h"
using namespace std;
/**
* @mainpage The Gaussian Optimization Analytical Tool (GOAT)
*
* Welcome to the Gaussian Optimization Analytical Tool (GOAT) documentation site!
* Users may find relevant info related to this program, a program designed to provide
* structural analyses of biomolecules successfully optimized using Gaussian software.
*
* @short Main program
* @file main.cpp
* @author Kate Charbonnet, Hannah Lozano, and Thomas Summers
* @param none
* @return 0 on success
*
* The purpose of this program is to provide preliminary structural information on biomolecules
* optimized using Gaussian computational chemistry software. Structural and chemical properties
* identified include: element identification, bond length, bond order, central angles, and torsional
* angles. Input of the file to be analyzed will result in an output file listing all the structural
* information of the biomolecule.
*/
int main(int argc, char* argv[])
{
ofstream logfile;
fstream bond_angle;
//Check that inputfile was directed into the command line
if (argc < 2)
{
cout << "Error: Inputfile not specified in command line\n";
return 1;
}
//Generate a logfile
logfile.open("log.txt");
if (!logfile.is_open())
{
cout << "Error: Unable to open the logfile.";
return 3;
} else {
logfile << "Logfile for Gaussian Optimization Analytical Tool\n";
}
//Extract the raw coordinates from the inputfile in the commandline
Extraction molecule(argv[1]);
//Clean the coords file
molecule.trim_coords(2);
//Open the file bond_angle.cpp and check that it opened
bond_angle.open("bond_angle.cpp");
if (!bond_angle.is_open()) {
cout << "Error: Unable to open bond_angle file.";
return 1;
}
//Close the file bond_angle.cpp
bond_angle.close();
cout << "Bond angle calculation complete.";
return 0;
}
<commit_msg>added dihedral angle files with open and close<commit_after>#include <iostream>
#include <string>
#include <fstream>
#include "main.h"
#include "extraction.h"
#include "bond_angle.cpp"
#include "elements.cpp"
#include "bond_length.cpp"
#include "bond_angle.h"
#include "dihedral_angle.cpp"
#include "dihedral_angle.h"
using namespace std;
/**
* @mainpage The Gaussian Optimization Analytical Tool (GOAT)
*
* Welcome to the Gaussian Optimization Analytical Tool (GOAT) documentation site!
* Users may find relevant info related to this program, a program designed to provide
* structural analyses of biomolecules successfully optimized using Gaussian software.
*
* @short Main program
* @file main.cpp
* @author Kate Charbonnet, Hannah Lozano, and Thomas Summers
* @param none
* @return 0 on success
*
* The purpose of this program is to provide preliminary structural information on biomolecules
* optimized using Gaussian computational chemistry software. Structural and chemical properties
* identified include: element identification, bond length, bond order, central angles, and torsional
* angles. Input of the file to be analyzed will result in an output file listing all the structural
* information of the biomolecule.
*/
int main(int argc, char* argv[])
{
ofstream logfile;
fstream bond_angle;
//Check that inputfile was directed into the command line
if (argc < 2)
{
cout << "Error: Inputfile not specified in command line\n";
return 1;
}
//Generate a logfile
logfile.open("log.txt");
if (!logfile.is_open())
{
cout << "Error: Unable to open the logfile.";
return 3;
} else {
logfile << "Logfile for Gaussian Optimization Analytical Tool\n";
}
//Extract the raw coordinates from the inputfile in the commandline
Extraction molecule(argv[1]);
//Clean the coords file
molecule.trim_coords(2);
//Open the file bond_angle.cpp and check that it opened
bond_angle.open("bond_angle.cpp");
if (!bond_angle.is_open()) {
cout << "Error: Unable to open file bond_angle.";
return 1;
}
//Close the file bond_angle.cpp
bond_angle.close();
cout << "Bond angle calculation complete.";
return 0;
//Open the file dihedral_angle.cpp and check that it opened
dihedral_angle.open("dihedral_angle.cpp");
if (!dihedral_angle.is_open()) {
cout << "Error: Unable to open file dihedral_angle.";
return 1;
}
//Close the file dihedral_angle.cpp
dihedral_angle.close();
cout << "Dihedral angle calculation complete.";
return 0;
}
<|endoftext|> |
<commit_before>ab781aee-2e4f-11e5-999f-28cfe91dbc4b<commit_msg>ab7fa354-2e4f-11e5-8925-28cfe91dbc4b<commit_after>ab7fa354-2e4f-11e5-8925-28cfe91dbc4b<|endoftext|> |
<commit_before>ec695123-327f-11e5-b4e2-9cf387a8033e<commit_msg>ec6f9585-327f-11e5-aee8-9cf387a8033e<commit_after>ec6f9585-327f-11e5-aee8-9cf387a8033e<|endoftext|> |
<commit_before>8fd04892-2d14-11e5-af21-0401358ea401<commit_msg>8fd04893-2d14-11e5-af21-0401358ea401<commit_after>8fd04893-2d14-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>4d2415b6-5216-11e5-91f8-6c40088e03e4<commit_msg>4d2c492c-5216-11e5-8161-6c40088e03e4<commit_after>4d2c492c-5216-11e5-8161-6c40088e03e4<|endoftext|> |
<commit_before>786333c0-2d53-11e5-baeb-247703a38240<commit_msg>7863b2aa-2d53-11e5-baeb-247703a38240<commit_after>7863b2aa-2d53-11e5-baeb-247703a38240<|endoftext|> |
<commit_before>0f58723a-2e4f-11e5-9010-28cfe91dbc4b<commit_msg>0f5fd566-2e4f-11e5-b4f4-28cfe91dbc4b<commit_after>0f5fd566-2e4f-11e5-b4f4-28cfe91dbc4b<|endoftext|> |
<commit_before>82f03a0c-2749-11e6-8e12-e0f84713e7b8<commit_msg>Deal with it<commit_after>82fa9af8-2749-11e6-846c-e0f84713e7b8<|endoftext|> |
<commit_before>b3aec985-2d3e-11e5-96d4-c82a142b6f9b<commit_msg>b418d985-2d3e-11e5-8d7f-c82a142b6f9b<commit_after>b418d985-2d3e-11e5-8d7f-c82a142b6f9b<|endoftext|> |
<commit_before>ae6aaaf0-35ca-11e5-8ce0-6c40088e03e4<commit_msg>ae729eae-35ca-11e5-8acc-6c40088e03e4<commit_after>ae729eae-35ca-11e5-8acc-6c40088e03e4<|endoftext|> |
<commit_before>53259aa1-2d3d-11e5-9fbd-c82a142b6f9b<commit_msg>537e9705-2d3d-11e5-bc92-c82a142b6f9b<commit_after>537e9705-2d3d-11e5-bc92-c82a142b6f9b<|endoftext|> |
<commit_before>/*
Analysis Control for J-PET
04-7-2013, M. Silarski:
v0- skeleton of AC program reading unpacked ROOT tree using exactly the same class
structure. The program is next filling a small exemplary structure Sig.
A tree TR is created and filled with this structure.
Usage after compiling and linking with Makefie:
./main filename.root (opens filename.root)
or
./main runNr_start runNr_end (opens files with run numbers between runNr_start
and runNr_end. This is however not fully implemented yet)
*/
#include <TApplication.h>
#include <TROOT.h>
#include <TTree.h>
#include <TFile.h>
#include <TObject.h>
#include <cstdio>
#include <stdlib.h>
#include <iostream>
#include <fstream>
#include <sstream>
#include <map>
#include "framework/Event/Event.h"
#include "framework/ADCHit/ADCHit.h"
#include "framework/TDCHit/TDCHit.h"
#include "string"
#include "map"
#include "TSystem.h"
#include "framework/Sig/Sig.h"
using namespace std;
int pet_init(Event *&event,TClonesArray *&tdc, TClonesArray *&adc,TTree *&Tn,TFile *&f)
{
//function called in main() once per run/file
Tn = (TTree*)f->Get("T");
TBranch *branch=Tn->GetBranch("event");
branch->SetAddress(&event);
tdc = event->GetTDCHitsArray();
adc = event->GetTDCHitsArray();
return 0;
}
int pet_event(Sig *signal,int i,Event *event,TClonesArray *tdc, TClonesArray *adc,TTree *Tn,TFile *f)
{
Int_t nev,Tot_NADCHits,Tot_NTDCHits,TDCReferenceTime;
Int_t maxChannelHits,j,k,ii,nChannels;
Long64_t nbytes;
//Sig signal;
maxChannelHits = 20; //the maximum number of hits per one channel fixed in the structure
nbytes += Tn->GetEntry(i);
//cout <<"Event nr: " <<i <<endl;
Tot_NADCHits = event->GetTotalNTDCHits();
//cout <<"Total number of ADC hits=" <<Tot_NADCHits<<endl;
Tot_NTDCHits = event->GetTotalNADCHits();
//cout <<"Total number of TDC hits="<<Tot_NTDCHits<<endl;
TDCReferenceTime = event->GetTDCReferenceTime();
//cout <<"TDC reference time"<<TDCReferenceTime<<endl;
tdc = event->GetTDCHitsArray();
adc = event->GetADCHitsArray();
signal->nChannel = tdc->GetEntriesFast();//Number of channels fired in event
signal->nSig = event->GetTotalNADCHits();
//loop over all channels
for(ii=0;ii<signal->nSig; ii++)
{
TDCHit* tshit = (TDCHit*) tdc->At(ii);
signal->channel[ii] = tshit->GetChannel();
for(j=0;j<maxChannelHits;j++)
{
signal->LTimes[ii][j] = tshit->GetLeadTime(j);
signal->TTimes[ii][j] = tshit->GetTrailTime(j);
}
}
return 0;
}
int pet_anaEv(Sig *sig,TTree *Tn)
//This routine is called for every event in the file/run
{
Tn->Fill();
sig->Clear();
return 0;
}
int pet_book(TTree *&Tr,TFile *&file,Sig *&sigp)
{
file = new TFile("treeRaw.root","recreate");
Tr = new TTree("TR","Raw structure");
Tr->Branch("Str","Sig",&sigp,64000,2);
return 0;
}
int pet_close(TFile *fm,TFile *Fr,TTree *Tr)
{
//This function is called once per file/run and contains
//all procedures for closing files etc.
fm->Close();
Tr->Write();
Tr->Print();
Tr->Show(100000);
delete Tr;
Fr->Close();
cout<<"Files closed successfully"<<endl;
cout<<"Do widzenia"<<endl;
return 0;
}
# ifndef __CINT__
int main(int argc, char *argv[])
{
gSystem->Load("libTree"); //lading ROOT libraries
Event* eventm = new Event();
TTree *Tnm;
TClonesArray *tdcm;
TClonesArray *adcm;
//const char *cRootFile = name.c_str();
string zonk;
Int_t nEntries,i,run_first,run_last;
Sig* sig = new Sig();
TTree *Tr;
TFile *Fr;
if(argc<2)
{
cout<<"Wrong number of arguments: Give at least the root file name!!"<<endl;
return 0;}
else{
if(argc==2){zonk = argv[1];}
else{
run_first = atoi(argv[1]); //string/char->int conversion
run_last = atoi(argv[2]); //to convert float use atof()
cout<<"Analysing Runs from "<<run_first<<" to "<<run_last<<endl;
return 0;
}
}
const char *cRootFile = zonk.c_str();
TFile *fm = new TFile(cRootFile);
pet_init(eventm,tdcm,adcm,Tnm,fm);
pet_book(Tr,Fr,sig);
nEntries = Tnm->GetEntries();
cout<<"File: "<<zonk<<endl;
cout <<"Number of Entries: "<<nEntries<<endl;
for ( i=0; i<nEntries; i++)
{
pet_event(sig,i,eventm,tdcm,adcm,Tnm,fm);
pet_anaEv(sig,Tr);
//getchar();
}
pet_close(fm,Fr,Tr);
return 0;
}
#endif
<commit_msg>usunięcie zbędnego maina z głównego katalogu<commit_after><|endoftext|> |
<commit_before>85627981-2d15-11e5-af21-0401358ea401<commit_msg>85627982-2d15-11e5-af21-0401358ea401<commit_after>85627982-2d15-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>7812416e-5216-11e5-ab4e-6c40088e03e4<commit_msg>78190efa-5216-11e5-bb50-6c40088e03e4<commit_after>78190efa-5216-11e5-bb50-6c40088e03e4<|endoftext|> |
<commit_before>85627977-2d15-11e5-af21-0401358ea401<commit_msg>85627978-2d15-11e5-af21-0401358ea401<commit_after>85627978-2d15-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>870f74b8-2e4f-11e5-a2ff-28cfe91dbc4b<commit_msg>8716895e-2e4f-11e5-a61f-28cfe91dbc4b<commit_after>8716895e-2e4f-11e5-a61f-28cfe91dbc4b<|endoftext|> |
<commit_before>ffabb4c6-585a-11e5-8e2a-6c40088e03e4<commit_msg>ffb28288-585a-11e5-8317-6c40088e03e4<commit_after>ffb28288-585a-11e5-8317-6c40088e03e4<|endoftext|> |
<commit_before>98f3cb5c-35ca-11e5-8261-6c40088e03e4<commit_msg>98faf470-35ca-11e5-bfde-6c40088e03e4<commit_after>98faf470-35ca-11e5-bfde-6c40088e03e4<|endoftext|> |
<commit_before>
#include <string>
#include <iostream>
#include <libdevcore/Common.h>
#include <libdevcore/CommonData.h>
#include <libdevcore/CommonIO.h>
#include <libsolidity/Scanner.h>
#include <libsolidity/Parser.h>
#include <libsolidity/ASTPrinter.h>
#include <libsolidity/NameAndTypeResolver.h>
namespace dev
{
namespace solidity
{
ASTPointer<ContractDefinition> parseAST(std::string const& _source)
{
ASTPointer<Scanner> scanner = std::make_shared<Scanner>(CharStream(_source));
Parser parser;
return parser.parse(scanner);
}
}
} // end namespaces
void help()
{
std::cout
<< "Usage solc [OPTIONS] <file>" << std::endl
<< "Options:" << std::endl
<< " -h,--help Show this help message and exit." << std::endl
<< " -V,--version Show the version and exit." << std::endl;
exit(0);
}
void version()
{
std::cout
<< "solc, the solidity complier commandline interface " << dev::Version << std::endl
<< " by Christian <c@ethdev.com>, (c) 2014." << std::endl
<< "Build: " << DEV_QUOTED(ETH_BUILD_PLATFORM) << "/" << DEV_QUOTED(ETH_BUILD_TYPE) << std::endl;
exit(0);
}
int main(int argc, char** argv)
{
std::string infile;
for (int i = 1; i < argc; ++i)
{
std::string arg = argv[i];
if (arg == "-h" || arg == "--help")
help();
else if (arg == "-V" || arg == "--version")
version();
else
infile = argv[i];
}
std::string src;
if (infile.empty())
{
std::string s;
while (!std::cin.eof())
{
getline(std::cin, s);
src.append(s);
}
}
else
{
src = dev::asString(dev::contents(infile));
}
std::cout << "Parsing..." << std::endl;
// @todo catch exception
dev::solidity::ASTPointer<dev::solidity::ContractDefinition> ast = dev::solidity::parseAST(src);
std::cout << "Syntax tree for the contract:" << std::endl;
dev::solidity::ASTPrinter printer(ast, src);
printer.print(std::cout);
std::cout << "Resolving identifiers..." << std::endl;
dev::solidity::NameAndTypeResolver resolver;
resolver.resolveNamesAndTypes(*ast.get());
return 0;
}
<commit_msg>Improved exceptions and reporting exceptions for command-line compiler.<commit_after>
#include <string>
#include <iostream>
#include <libdevcore/Common.h>
#include <libdevcore/CommonData.h>
#include <libdevcore/CommonIO.h>
#include <libsolidity/Scanner.h>
#include <libsolidity/Parser.h>
#include <libsolidity/ASTPrinter.h>
#include <libsolidity/NameAndTypeResolver.h>
#include <libsolidity/Exceptions.h>
using namespace dev;
using namespace solidity;
void help()
{
std::cout
<< "Usage solc [OPTIONS] <file>" << std::endl
<< "Options:" << std::endl
<< " -h,--help Show this help message and exit." << std::endl
<< " -V,--version Show the version and exit." << std::endl;
exit(0);
}
void version()
{
std::cout
<< "solc, the solidity complier commandline interface " << dev::Version << std::endl
<< " by Christian <c@ethdev.com>, (c) 2014." << std::endl
<< "Build: " << DEV_QUOTED(ETH_BUILD_PLATFORM) << "/" << DEV_QUOTED(ETH_BUILD_TYPE) << std::endl;
exit(0);
}
void printSourcePart(std::ostream& _stream, Location const& _location, Scanner const& _scanner)
{
int startLine;
int startColumn;
std::tie(startLine, startColumn) = _scanner.translatePositionToLineColumn(_location.start);
_stream << " starting at line " << (startLine + 1) << ", column " << (startColumn + 1) << "\n";
int endLine;
int endColumn;
std::tie(endLine, endColumn) = _scanner.translatePositionToLineColumn(_location.end);
if (startLine == endLine)
{
_stream << _scanner.getLineAtPosition(_location.start) << "\n"
<< std::string(startColumn, ' ') << "^";
if (endColumn > startColumn + 2)
_stream << std::string(endColumn - startColumn - 2, '-');
if (endColumn > startColumn + 1)
_stream << "^";
_stream << "\n";
}
else
{
_stream << _scanner.getLineAtPosition(_location.start) << "\n"
<< std::string(startColumn, ' ') << "^\n"
<< "Spanning multiple lines.\n";
}
}
int main(int argc, char** argv)
{
std::string infile;
for (int i = 1; i < argc; ++i)
{
std::string arg = argv[i];
if (arg == "-h" || arg == "--help")
help();
else if (arg == "-V" || arg == "--version")
version();
else
infile = argv[i];
}
std::string sourceCode;
if (infile.empty())
{
std::string s;
while (!std::cin.eof())
{
getline(std::cin, s);
sourceCode.append(s);
}
}
else
sourceCode = asString(dev::contents(infile));
ASTPointer<ContractDefinition> ast;
std::shared_ptr<Scanner> scanner = std::make_shared<Scanner>(CharStream(sourceCode));
Parser parser;
try
{
ast = parser.parse(scanner);
}
catch (ParserError const& exc)
{
int line;
int column;
std::tie(line, column) = scanner->translatePositionToLineColumn(exc.getPosition());
std::cerr << exc.what() << " at line " << (line + 1) << ", column " << (column + 1) << std::endl;
std::cerr << scanner->getLineAtPosition(exc.getPosition()) << std::endl;
std::cerr << std::string(column, ' ') << "^" << std::endl;
return -1;
}
dev::solidity::NameAndTypeResolver resolver;
try
{
resolver.resolveNamesAndTypes(*ast.get());
}
catch (DeclarationError const& exc)
{
std::cerr << exc.what() << std::endl;
printSourcePart(std::cerr, exc.getLocation(), *scanner);
return -1;
}
catch (TypeError const& exc)
{
std::cerr << exc.what() << std::endl;
printSourcePart(std::cerr, exc.getLocation(), *scanner);
return -1;
}
std::cout << "Syntax tree for the contract:" << std::endl;
dev::solidity::ASTPrinter printer(ast, sourceCode);
printer.print(std::cout);
return 0;
}
<|endoftext|> |
<commit_before>14dd611e-2f67-11e5-af7e-6c40088e03e4<commit_msg>14e4a96c-2f67-11e5-83e9-6c40088e03e4<commit_after>14e4a96c-2f67-11e5-83e9-6c40088e03e4<|endoftext|> |
<commit_before>92323adb-2d14-11e5-af21-0401358ea401<commit_msg>92323adc-2d14-11e5-af21-0401358ea401<commit_after>92323adc-2d14-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>142ab762-585b-11e5-85c8-6c40088e03e4<commit_msg>1431ebc0-585b-11e5-9545-6c40088e03e4<commit_after>1431ebc0-585b-11e5-9545-6c40088e03e4<|endoftext|> |
<commit_before>c5e9c7f8-2747-11e6-b869-e0f84713e7b8<commit_msg>Really doesn't crash if X, now<commit_after>c6190a0f-2747-11e6-88e6-e0f84713e7b8<|endoftext|> |
<commit_before>b4121a99-327f-11e5-8229-9cf387a8033e<commit_msg>b417f0ee-327f-11e5-9d6c-9cf387a8033e<commit_after>b417f0ee-327f-11e5-9d6c-9cf387a8033e<|endoftext|> |
<commit_before>91de3f8a-ad5c-11e7-bbf2-ac87a332f658<commit_msg>Really doesn't crash if X, now<commit_after>92535aa3-ad5c-11e7-bb62-ac87a332f658<|endoftext|> |
<commit_before>d42c62b0-35ca-11e5-8cc2-6c40088e03e4<commit_msg>d433cf00-35ca-11e5-a3b2-6c40088e03e4<commit_after>d433cf00-35ca-11e5-a3b2-6c40088e03e4<|endoftext|> |
<commit_before>a02b11c7-327f-11e5-ac2e-9cf387a8033e<commit_msg>a0311919-327f-11e5-b1c6-9cf387a8033e<commit_after>a0311919-327f-11e5-b1c6-9cf387a8033e<|endoftext|> |
<commit_before>e74e633a-327f-11e5-b866-9cf387a8033e<commit_msg>e7552b0c-327f-11e5-911e-9cf387a8033e<commit_after>e7552b0c-327f-11e5-911e-9cf387a8033e<|endoftext|> |
<commit_before>5f89494c-2d16-11e5-af21-0401358ea401<commit_msg>5f89494d-2d16-11e5-af21-0401358ea401<commit_after>5f89494d-2d16-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>5d24fcb0-ad58-11e7-b478-ac87a332f658<commit_msg>Deal with it<commit_after>5d99f9a3-ad58-11e7-bded-ac87a332f658<|endoftext|> |
<commit_before>3702f7f0-5216-11e5-9395-6c40088e03e4<commit_msg>370a7b42-5216-11e5-ab88-6c40088e03e4<commit_after>370a7b42-5216-11e5-ab88-6c40088e03e4<|endoftext|> |
<commit_before>09f24618-2f67-11e5-91b4-6c40088e03e4<commit_msg>09f8f148-2f67-11e5-ae0c-6c40088e03e4<commit_after>09f8f148-2f67-11e5-ae0c-6c40088e03e4<|endoftext|> |
<commit_before>e2106bee-585a-11e5-a38d-6c40088e03e4<commit_msg>e21975ae-585a-11e5-99bf-6c40088e03e4<commit_after>e21975ae-585a-11e5-99bf-6c40088e03e4<|endoftext|> |
<commit_before>945d1c68-2e4f-11e5-8e1d-28cfe91dbc4b<commit_msg>94679c4c-2e4f-11e5-b7ba-28cfe91dbc4b<commit_after>94679c4c-2e4f-11e5-b7ba-28cfe91dbc4b<|endoftext|> |
<commit_before>ae1338f5-2e4f-11e5-b3b2-28cfe91dbc4b<commit_msg>ae19d5e3-2e4f-11e5-8824-28cfe91dbc4b<commit_after>ae19d5e3-2e4f-11e5-8824-28cfe91dbc4b<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.