text
stringlengths
54
60.6k
<commit_before>/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2008, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the Willow Garage nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *********************************************************************/ // Original version: Melonee Wise <[email protected]> #include "control_toolbox/pid.h" #include "tinyxml.h" namespace control_toolbox { Pid::Pid(double p, double i, double d, double i_max, double i_min) : p_gain_(p), i_gain_(i), d_gain_(d), i_max_(i_max), i_min_(i_min) { this->reset(); } Pid::~Pid() { } void Pid::initPid(double p, double i, double d, double i_max, double i_min) { this->setGains(p,i,d,i_max,i_min); reset(); } void Pid::reset() { p_error_last_ = 0.0; p_error_ = 0.0; d_error_ = 0.0; i_term_ = 0.0; cmd_ = 0.0; } void Pid::getGains(double &p, double &i, double &d, double &i_max, double &i_min) { p = p_gain_; i = i_gain_; d = d_gain_; i_max = i_max_; i_min = i_min_; } void Pid::setGains(double p, double i, double d, double i_max, double i_min) { p_gain_ = p; i_gain_ = i; d_gain_ = d; i_max_ = i_max; i_min_ = i_min; } bool Pid::initParam(const std::string& prefix) { ros::NodeHandle node(prefix); if (!node.getParam("p", p_gain_)) { ROS_ERROR("No p gain specified for pid. Prefix: %s", prefix.c_str()); return false; } node.param("i", i_gain_, 0.0) ; node.param("d", d_gain_, 0.0) ; node.param("i_clamp", i_max_, 0.0) ; i_min_ = -i_max_; reset(); return true; } bool Pid::initXml(TiXmlElement *config) { p_gain_ = config->Attribute("p") ? atof(config->Attribute("p")) : 0.0; i_gain_ = config->Attribute("i") ? atof(config->Attribute("i")) : 0.0; d_gain_ = config->Attribute("d") ? atof(config->Attribute("d")) : 0.0; i_max_ = config->Attribute("iClamp") ? atof(config->Attribute("iClamp")) : 0.0; i_min_ = -i_max_; reset(); return true; } bool Pid::init(const ros::NodeHandle &node) { ros::NodeHandle n(node); if (!n.getParam("p", p_gain_)) { ROS_ERROR("No p gain specified for pid. Namespace: %s", n.getNamespace().c_str()); return false; } n.param("i", i_gain_, 0.0); n.param("d", d_gain_, 0.0); n.param("i_clamp", i_max_, 0.0); i_min_ = -i_max_; reset(); return true; } double Pid::setError(double error, ros::Duration dt) { double p_term, d_term; p_error_ = error; //this is pError = pState-pTarget if (dt == ros::Duration(0.0) || std::isnan(error) || std::isinf(error)) return 0.0; // Calculate proportional contribution to command p_term = p_gain_ * p_error_; //Calculate integral contribution to command i_term_ = i_term_ + i_gain_ * dt.toSec() * p_error_; // Limit i_term_ so that the limit is meaningful in the output i_term_ = std::max( i_min_, std::min( i_term_, i_max_) ); // Calculate the derivative error if (dt.toSec() > 0.0) { d_error_ = (p_error_ - p_error_last_) / dt.toSec(); p_error_last_ = p_error_; } // Calculate derivative contribution to command d_term = d_gain_ * d_error_; cmd_ = p_term + i_term_ + d_term; return cmd_; } double Pid::updatePid(double error, ros::Duration dt) { double p_term, d_term; p_error_ = error; //this is pError = pState-pTarget if (dt == ros::Duration(0.0) || std::isnan(error) || std::isinf(error)) return 0.0; // Calculate proportional contribution to command p_term = p_gain_ * p_error_; //Calculate integral contribution to command i_term_ = i_term_ + i_gain_ * dt.toSec() * p_error_; // Limit i_term_ so that the limit is meaningful in the output i_term_ = std::max( i_min_, std::min( i_term_, i_max_) ); // Calculate the derivative error if (dt.toSec() > 0.0) { d_error_ = (p_error_ - p_error_last_) / dt.toSec(); p_error_last_ = p_error_; } // Calculate derivative contribution to command d_term = d_gain_ * d_error_; cmd_ = - p_term - i_term - d_term; return cmd_; } double Pid::setError(double error, double error_dot, ros::Duration dt) { double p_term, d_term; p_error_ = error; //this is pError = pState-pTarget d_error_ = error_dot; if (dt == ros::Duration(0.0) || std::isnan(error) || std::isinf(error) || std::isnan(error_dot) || std::isinf(error_dot)) return 0.0; // Calculate proportional contribution to command p_term = p_gain_ * p_error_; //Calculate integral contribution to command i_term_ = i_term_ + i_gain_ * dt.toSec() * p_error_; // Limit i_term_ so that the limit is meaningful in the output i_term_ = std::max( i_min_, std::min( i_term_, i_max_) ); // Calculate derivative contribution to command d_term = d_gain_ * d_error_; cmd_ = p_term + i_term_ + d_term; return cmd_; } double Pid::updatePid(double error, double error_dot, ros::Duration dt) { double p_term, d_term; p_error_ = error; //this is pError = pState-pTarget d_error_ = error_dot; if (dt == ros::Duration(0.0) || std::isnan(error) || std::isinf(error) || std::isnan(error_dot) || std::isinf(error_dot)) return 0.0; // Calculate proportional contribution to command p_term = p_gain_ * p_error_; //Calculate integral contribution to command i_term_ = i_term_ + i_gain_ * dt.toSec() * p_error_; // Limit i_term_ so that the limit is meaningful in the output i_term_ = std::max( i_min_, std::min( i_term_, i_max_) ); // Calculate derivative contribution to command d_term = d_gain_ * d_error_; cmd_ = - p_term - i_term - d_term; return cmd_; } void Pid::setCurrentCmd(double cmd) { cmd_ = cmd; } double Pid::getCurrentCmd() { return cmd_; } void Pid::getCurrentPIDErrors(double *pe, double *ie, double *de) { *pe = p_error_; *ie = i_gain_ ? i_term_/i_gain_ : 0.0; *de = d_error_; } } <commit_msg>Fixing merge error<commit_after>/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2008, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the Willow Garage nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *********************************************************************/ // Original version: Melonee Wise <[email protected]> #include "control_toolbox/pid.h" #include "tinyxml.h" namespace control_toolbox { Pid::Pid(double p, double i, double d, double i_max, double i_min) : p_gain_(p), i_gain_(i), d_gain_(d), i_max_(i_max), i_min_(i_min) { this->reset(); } Pid::~Pid() { } void Pid::initPid(double p, double i, double d, double i_max, double i_min) { this->setGains(p,i,d,i_max,i_min); reset(); } void Pid::reset() { p_error_last_ = 0.0; p_error_ = 0.0; d_error_ = 0.0; i_term_ = 0.0; cmd_ = 0.0; } void Pid::getGains(double &p, double &i, double &d, double &i_max, double &i_min) { p = p_gain_; i = i_gain_; d = d_gain_; i_max = i_max_; i_min = i_min_; } void Pid::setGains(double p, double i, double d, double i_max, double i_min) { p_gain_ = p; i_gain_ = i; d_gain_ = d; i_max_ = i_max; i_min_ = i_min; } bool Pid::initParam(const std::string& prefix) { ros::NodeHandle node(prefix); if (!node.getParam("p", p_gain_)) { ROS_ERROR("No p gain specified for pid. Prefix: %s", prefix.c_str()); return false; } node.param("i", i_gain_, 0.0) ; node.param("d", d_gain_, 0.0) ; node.param("i_clamp", i_max_, 0.0) ; i_min_ = -i_max_; reset(); return true; } bool Pid::initXml(TiXmlElement *config) { p_gain_ = config->Attribute("p") ? atof(config->Attribute("p")) : 0.0; i_gain_ = config->Attribute("i") ? atof(config->Attribute("i")) : 0.0; d_gain_ = config->Attribute("d") ? atof(config->Attribute("d")) : 0.0; i_max_ = config->Attribute("iClamp") ? atof(config->Attribute("iClamp")) : 0.0; i_min_ = -i_max_; reset(); return true; } bool Pid::init(const ros::NodeHandle &node) { ros::NodeHandle n(node); if (!n.getParam("p", p_gain_)) { ROS_ERROR("No p gain specified for pid. Namespace: %s", n.getNamespace().c_str()); return false; } n.param("i", i_gain_, 0.0); n.param("d", d_gain_, 0.0); n.param("i_clamp", i_max_, 0.0); i_min_ = -i_max_; reset(); return true; } double Pid::setError(double error, ros::Duration dt) { double p_term, d_term; p_error_ = error; //this is pError = pState-pTarget if (dt == ros::Duration(0.0) || std::isnan(error) || std::isinf(error)) return 0.0; // Calculate proportional contribution to command p_term = p_gain_ * p_error_; //Calculate integral contribution to command i_term_ = i_term_ + i_gain_ * dt.toSec() * p_error_; // Limit i_term_ so that the limit is meaningful in the output i_term_ = std::max( i_min_, std::min( i_term_, i_max_) ); // Calculate the derivative error if (dt.toSec() > 0.0) { d_error_ = (p_error_ - p_error_last_) / dt.toSec(); p_error_last_ = p_error_; } // Calculate derivative contribution to command d_term = d_gain_ * d_error_; cmd_ = p_term + i_term_ + d_term; return cmd_; } double Pid::updatePid(double error, ros::Duration dt) { double p_term, d_term; p_error_ = error; //this is pError = pState-pTarget if (dt == ros::Duration(0.0) || std::isnan(error) || std::isinf(error)) return 0.0; // Calculate proportional contribution to command p_term = p_gain_ * p_error_; //Calculate integral contribution to command i_term_ = i_term_ + i_gain_ * dt.toSec() * p_error_; // Limit i_term_ so that the limit is meaningful in the output i_term_ = std::max( i_min_, std::min( i_term_, i_max_) ); // Calculate the derivative error if (dt.toSec() > 0.0) { d_error_ = (p_error_ - p_error_last_) / dt.toSec(); p_error_last_ = p_error_; } // Calculate derivative contribution to command d_term = d_gain_ * d_error_; cmd_ = - p_term - i_term_ - d_term; return cmd_; } double Pid::setError(double error, double error_dot, ros::Duration dt) { double p_term, d_term; p_error_ = error; //this is pError = pState-pTarget d_error_ = error_dot; if (dt == ros::Duration(0.0) || std::isnan(error) || std::isinf(error) || std::isnan(error_dot) || std::isinf(error_dot)) return 0.0; // Calculate proportional contribution to command p_term = p_gain_ * p_error_; //Calculate integral contribution to command i_term_ = i_term_ + i_gain_ * dt.toSec() * p_error_; // Limit i_term_ so that the limit is meaningful in the output i_term_ = std::max( i_min_, std::min( i_term_, i_max_) ); // Calculate derivative contribution to command d_term = d_gain_ * d_error_; cmd_ = p_term + i_term_ + d_term; return cmd_; } double Pid::updatePid(double error, double error_dot, ros::Duration dt) { double p_term, d_term; p_error_ = error; //this is pError = pState-pTarget d_error_ = error_dot; if (dt == ros::Duration(0.0) || std::isnan(error) || std::isinf(error) || std::isnan(error_dot) || std::isinf(error_dot)) return 0.0; // Calculate proportional contribution to command p_term = p_gain_ * p_error_; //Calculate integral contribution to command i_term_ = i_term_ + i_gain_ * dt.toSec() * p_error_; // Limit i_term_ so that the limit is meaningful in the output i_term_ = std::max( i_min_, std::min( i_term_, i_max_) ); // Calculate derivative contribution to command d_term = d_gain_ * d_error_; cmd_ = - p_term - i_term_ - d_term; return cmd_; } void Pid::setCurrentCmd(double cmd) { cmd_ = cmd; } double Pid::getCurrentCmd() { return cmd_; } void Pid::getCurrentPIDErrors(double *pe, double *ie, double *de) { *pe = p_error_; *ie = i_gain_ ? i_term_/i_gain_ : 0.0; *de = d_error_; } } <|endoftext|>
<commit_before>#include "common.h" #include <functional> #include <memory> #ifdef LINUX #include <dlfcn.h> #endif #include "jsobject.h" #include "typeconv.h" #include "python-util.h" #include "error.h" #include "gil-lock.h" #include "debug.h" #include "pymodule.h" class AtExit { public: AtExit(std::function<void (void)> atExit): atExit(atExit) {} ~AtExit() { atExit(); } private: std::function<void (void)> atExit; }; void Builtins(v8::Local<v8::String> name, const Nan::PropertyCallbackInfo<v8::Value> &args) { GILStateHolder gilholder; Nan::HandleScope scope; PyObjectWithRef object(PyImport_ImportModule("builtins")); args.GetReturnValue().Set(JsPyWrapper::NewInstance(object)); } void Import(const Nan::FunctionCallbackInfo<v8::Value> &args) { GILStateHolder gilholder; Nan::HandleScope scope; if (args.Length() == 0 || !args[0]->IsString()) return Nan::ThrowTypeError("invalid module name"); PyObjectWithRef object(PyImport_ImportModule(*static_cast<v8::String::Utf8Value>(args[0]->ToString()))); CHECK_PYTHON_ERROR; args.GetReturnValue().Set(JsPyWrapper::NewInstance(object)); } void Eval(const Nan::FunctionCallbackInfo<v8::Value> &args) { GILStateHolder gilholder; Nan::HandleScope scope; if (args.Length() == 0 || !args[0]->IsString()) return Nan::ThrowTypeError("invalid Python code"); PyObjectWithRef global(PyDict_New()), local(PyDict_New()); PyObjectWithRef object(PyRun_String(*Nan::Utf8String(args[0]), Py_eval_input, global, local)); CHECK_PYTHON_ERROR; args.GetReturnValue().Set(PyToJs(object, JsPyWrapper::implicitConversionEnabled)); } void Module(v8::Local<v8::String> name, const Nan::PropertyCallbackInfo<v8::Value> &args) { GILStateHolder gilholder; Nan::HandleScope scope; PyObjectWithRef object = PyObjectMakeRef(JsPyModule::GetModule()); args.GetReturnValue().Set(JsPyWrapper::NewInstance(object)); } void Init(v8::Local<v8::Object> exports) { // find process.argv first v8::Local<v8::Array> jsArgv = Nan::GetCurrentContext()->Global() ->Get(Nan::New("process").ToLocalChecked())->ToObject() ->Get(Nan::New("argv").ToLocalChecked()).As<v8::Array>(); if (jsArgv->Length() > 0) { wchar_t *name = Py_DecodeLocale(*Nan::Utf8String(jsArgv->Get(0)->ToString()), nullptr); Py_SetProgramName(name); PyMem_RawFree(name); } // python initialize void *python_lib; #ifdef LINUX python_lib = dlopen(PYTHON_LIB, RTLD_LAZY | RTLD_GLOBAL); #endif Py_InitializeEx(0); // not working? //node::AtExit([] (void *) { Py_Finalize(); std::cout << "exit" << std::endl; }); static AtExit exitHandler([python_lib] { if (!PyGILState_Check()) PyGILState_Ensure(); Py_Finalize(); #ifdef LINUX dlclose(python_lib); #endif }); GILLock::Init(); TypeConvInit(); JsPyWrapper::Init(exports); // init sys.argv int argc = jsArgv->Length(); argc && --argc; std::unique_ptr<wchar_t *[]> argv(new wchar_t *[argc]); for (int i = 0; i < argc; i++) { argv[i] = Py_DecodeLocale(*Nan::Utf8String(jsArgv->Get(i + 1)->ToString()), nullptr); } PySys_SetArgv(argc, argv.get()); for (int i = 0; i < argc; i++) { PyMem_RawFree(argv[i]); } // py module init JsPyModule::Init(); Nan::SetAccessor(exports, Nan::New("module").ToLocalChecked(), Module); Nan::SetAccessor(exports, Nan::New("builtins").ToLocalChecked(), Builtins); Nan::SetMethod(exports, "import", Import); Nan::SetMethod(exports, "eval", Eval); } NODE_MODULE(pyjs, Init) <commit_msg>better cap with older python version (3.3~)<commit_after>#include "common.h" #include <functional> #include <memory> #ifdef LINUX #include <dlfcn.h> #endif #include "jsobject.h" #include "typeconv.h" #include "python-util.h" #include "error.h" #include "gil-lock.h" #include "debug.h" #include "pymodule.h" class AtExit { public: AtExit(std::function<void (void)> atExit): atExit(atExit) {} ~AtExit() { atExit(); } private: std::function<void (void)> atExit; }; void Builtins(v8::Local<v8::String> name, const Nan::PropertyCallbackInfo<v8::Value> &args) { GILStateHolder gilholder; Nan::HandleScope scope; PyObjectWithRef object(PyImport_ImportModule("builtins")); args.GetReturnValue().Set(JsPyWrapper::NewInstance(object)); } void Import(const Nan::FunctionCallbackInfo<v8::Value> &args) { GILStateHolder gilholder; Nan::HandleScope scope; if (args.Length() == 0 || !args[0]->IsString()) return Nan::ThrowTypeError("invalid module name"); PyObjectWithRef object(PyImport_ImportModule(*static_cast<v8::String::Utf8Value>(args[0]->ToString()))); CHECK_PYTHON_ERROR; args.GetReturnValue().Set(JsPyWrapper::NewInstance(object)); } void Eval(const Nan::FunctionCallbackInfo<v8::Value> &args) { GILStateHolder gilholder; Nan::HandleScope scope; if (args.Length() == 0 || !args[0]->IsString()) return Nan::ThrowTypeError("invalid Python code"); PyObjectWithRef global(PyDict_New()), local(PyDict_New()); PyObjectWithRef object(PyRun_String(*Nan::Utf8String(args[0]), Py_eval_input, global, local)); CHECK_PYTHON_ERROR; args.GetReturnValue().Set(PyToJs(object, JsPyWrapper::implicitConversionEnabled)); } void Module(v8::Local<v8::String> name, const Nan::PropertyCallbackInfo<v8::Value> &args) { GILStateHolder gilholder; Nan::HandleScope scope; PyObjectWithRef object = PyObjectMakeRef(JsPyModule::GetModule()); args.GetReturnValue().Set(JsPyWrapper::NewInstance(object)); } void Init(v8::Local<v8::Object> exports) { // find process.argv first v8::Local<v8::Array> jsArgv = Nan::GetCurrentContext()->Global() ->Get(Nan::New("process").ToLocalChecked())->ToObject() ->Get(Nan::New("argv").ToLocalChecked()).As<v8::Array>(); if (jsArgv->Length() > 0) { //wchar_t *name = Py_DecodeLocale(*Nan::Utf8String(jsArgv->Get(0)->ToString()), nullptr); PyObjectWithRef pyname(PyUnicode_DecodeLocale(*Nan::Utf8String(jsArgv->Get(0)->ToString()), nullptr)); wchar_t *name = PyUnicode_AsUnicode(pyname.borrow()); Py_SetProgramName(name); //PyMem_RawFree(name); } // python initialize void *python_lib; #ifdef LINUX python_lib = dlopen(PYTHON_LIB, RTLD_LAZY | RTLD_GLOBAL); #endif Py_InitializeEx(0); // not working? //node::AtExit([] (void *) { Py_Finalize(); std::cout << "exit" << std::endl; }); static AtExit exitHandler([python_lib] { if (!PyGILState_Check()) PyGILState_Ensure(); Py_Finalize(); #ifdef LINUX dlclose(python_lib); #endif }); GILLock::Init(); TypeConvInit(); JsPyWrapper::Init(exports); // init sys.argv int argc = jsArgv->Length(); argc && --argc; std::unique_ptr<wchar_t *[]> argv(new wchar_t *[argc]); std::vector<PyObjectWithRef> pyargv; for (int i = 0; i < argc; i++) { PyObjectWithRef a(PyUnicode_DecodeLocale(*Nan::Utf8String(jsArgv->Get(i + 1)->ToString()), nullptr)); //argv[i] = Py_DecodeLocale(*Nan::Utf8String(jsArgv->Get(i + 1)->ToString()), nullptr); argv[i] = PyUnicode_AsUnicode(a.borrow()); pyargv.push_back(a); } PySys_SetArgv(argc, argv.get()); for (int i = 0; i < argc; i++) { //PyMem_RawFree(argv[i]); pyargv.clear(); } // py module init JsPyModule::Init(); Nan::SetAccessor(exports, Nan::New("module").ToLocalChecked(), Module); Nan::SetAccessor(exports, Nan::New("builtins").ToLocalChecked(), Builtins); Nan::SetMethod(exports, "import", Import); Nan::SetMethod(exports, "eval", Eval); } NODE_MODULE(pyjs, Init) <|endoftext|>
<commit_before>#include "rlp.h" #include <cstring> #include <cstdint> #include<stdexcept> using namespace std; RLP::RLP(const vector<uint8_t> & contents) : RLP{contents, 0, contents.size()} {} RLP::RLP(const vector<uint8_t> & contents, size_t offset, size_t maxLength) : _contents{contents}, _prefixOff{offset} { if (maxLength == 0) throw BadRLPFormat(); uint8_t prefix = _contents[_prefixOff]; if (prefix < 128) { _dataLen = 1; _totalLen = 1; _dataOff = _prefixOff; } else if (prefix <= 183) { _dataLen = prefix - 128; _totalLen = 1 + _dataLen; _dataOff = _prefixOff + 1; } else if (prefix < 192) { size_t dataLengthSize = prefix - 183; if (maxLength < 1 + dataLengthSize) throw BadRLPFormat(); parseDataLength(dataLengthSize); _totalLen = 1 + dataLengthSize + _dataLen; _dataOff = _prefixOff + 1 + dataLengthSize; } else if (prefix <= 247) { _dataLen = prefix - 192; _totalLen = 1 + _dataLen; _dataOff = _prefixOff + 1; } else { size_t dataLengthSize = prefix - 247; if (maxLength < 1 + dataLengthSize) throw BadRLPFormat(); parseDataLength(dataLengthSize); _totalLen = 1 + dataLengthSize + _dataLen; _dataOff = _prefixOff + 1 + dataLengthSize; } if (_totalLen > maxLength) throw BadRLPFormat(); /* Add children */ if (prefix >= 192) parseItems(); } void RLP::parseDataLength(size_t dataLengthSize) { _dataLen = 0; for (size_t i = 0; i < dataLengthSize; ++i) { _dataLen *= 256; _dataLen += _contents[_prefixOff + 1 + i]; } } void RLP::parseItems() { size_t remLen = _dataLen; size_t parseOffset = _dataOff; while (remLen > 0) { _items.push_back(RLP{_contents, parseOffset, remLen}); remLen -= _items.back().totalLength(); parseOffset += _items.back().totalLength(); } } vector<uint8_t> RLP::serialize(const vector<RLPField> & dataFields) { vector<uint8_t> items; for (auto f : dataFields) { if (!f.isSerialized) { if (f.bytes.size() == 0) { items.push_back(128u); } else if (f.bytes.size() == 1 && f.bytes[0] < 128u) { items.push_back(f.bytes[0]); } else if (f.bytes.size() < 56) { items.push_back(128u + f.bytes.size()); size_t tmp = items.size(); items.resize(tmp + f.bytes.size()); memcpy(items.data() + tmp, f.bytes.data(), f.bytes.size()); } else { vector<uint8_t> s; size_t tmp = f.bytes.size(); while (tmp > 0) { s.push_back(tmp % 256); tmp /= 256; } items.push_back(183u + s.size()); while (!s.empty()) { items.push_back(s.back()); s.pop_back(); } tmp = items.size(); items.resize(tmp + f.bytes.size()); memcpy(items.data() + tmp, f.bytes.data(), f.bytes.size()); } } else { if (f.bytes.size() == 0) { items.push_back(192u); } else { size_t tmp = items.size(); items.resize(tmp + f.bytes.size()); memcpy(items.data() + tmp, f.bytes.data(), f.bytes.size()); } } } if (dataFields.size() == 1 && !dataFields[0].isSerialized) return items; vector<uint8_t> prefix; if (items.size() < 56) { prefix.push_back(192u + items.size()); } else { vector<uint8_t> s; size_t tmp = items.size(); while (tmp > 0) { s.push_back(tmp % 256); tmp /= 256; } prefix.push_back(247u + s.size()); while (!s.empty()) { prefix.push_back(s.back()); s.pop_back(); } } vector<uint8_t> result; result.resize(prefix.size() + items.size()); memcpy(result.data(), prefix.data(), prefix.size()); memcpy(result.data() + prefix.size(), items.data(), items.size()); return result; } vector<uint8_t> numberToVector(size_t input) { vector<uint8_t> result; vector<uint8_t> tmp; //will be filled with bytes and later reversed into result vector while (input > 0) { tmp.push_back(input % 256); input /= 256; } while (!tmp.empty()) { result.push_back(tmp.back()); tmp.pop_back(); } return result; } <commit_msg>Fix invalid read reported in issue: https://github.com/kasparjarek/PA193_test_parser_Ethereum/issues/2<commit_after>#include "rlp.h" #include <cstring> #include <cstdint> #include<stdexcept> using namespace std; RLP::RLP(const vector<uint8_t> & contents) : RLP{contents, 0, contents.size()} {} RLP::RLP(const vector<uint8_t> & contents, size_t offset, size_t maxLength) : _contents{contents}, _prefixOff{offset} { if (maxLength == 0) throw BadRLPFormat(); uint8_t prefix = _contents[_prefixOff]; if (prefix < 128) { _dataLen = 1; _totalLen = 1; _dataOff = _prefixOff; } else if (prefix <= 183) { _dataLen = prefix - 128; _totalLen = 1 + _dataLen; _dataOff = _prefixOff + 1; } else if (prefix < 192) { size_t dataLengthSize = prefix - 183; if (maxLength < 1 + dataLengthSize) throw BadRLPFormat(); parseDataLength(dataLengthSize); _totalLen = 1 + dataLengthSize + _dataLen; _dataOff = _prefixOff + 1 + dataLengthSize; } else if (prefix <= 247) { _dataLen = prefix - 192; _totalLen = 1 + _dataLen; _dataOff = _prefixOff + 1; } else { size_t dataLengthSize = prefix - 247; if (maxLength < 1 + dataLengthSize) throw BadRLPFormat(); parseDataLength(dataLengthSize); _totalLen = 1 + dataLengthSize + _dataLen; _dataOff = _prefixOff + 1 + dataLengthSize; } if (_totalLen > maxLength) throw BadRLPFormat(); /* Add children */ if (prefix >= 192) parseItems(); } void RLP::parseDataLength(size_t dataLengthSize) { _dataLen = 0; for (size_t i = 0; i < dataLengthSize; ++i) { _dataLen *= 256; _dataLen += _contents[_prefixOff + 1 + i]; if (_dataLen > _contents.size() - _prefixOff + dataLengthSize + 1) { throw runtime_error("DataLen too big"); } } } void RLP::parseItems() { size_t remLen = _dataLen; size_t parseOffset = _dataOff; while (remLen > 0) { _items.push_back(RLP{_contents, parseOffset, remLen}); remLen -= _items.back().totalLength(); parseOffset += _items.back().totalLength(); } } vector<uint8_t> RLP::serialize(const vector<RLPField> & dataFields) { vector<uint8_t> items; for (auto f : dataFields) { if (!f.isSerialized) { if (f.bytes.size() == 0) { items.push_back(128u); } else if (f.bytes.size() == 1 && f.bytes[0] < 128u) { items.push_back(f.bytes[0]); } else if (f.bytes.size() < 56) { items.push_back(128u + f.bytes.size()); size_t tmp = items.size(); items.resize(tmp + f.bytes.size()); memcpy(items.data() + tmp, f.bytes.data(), f.bytes.size()); } else { vector<uint8_t> s; size_t tmp = f.bytes.size(); while (tmp > 0) { s.push_back(tmp % 256); tmp /= 256; } items.push_back(183u + s.size()); while (!s.empty()) { items.push_back(s.back()); s.pop_back(); } tmp = items.size(); items.resize(tmp + f.bytes.size()); memcpy(items.data() + tmp, f.bytes.data(), f.bytes.size()); } } else { if (f.bytes.size() == 0) { items.push_back(192u); } else { size_t tmp = items.size(); items.resize(tmp + f.bytes.size()); memcpy(items.data() + tmp, f.bytes.data(), f.bytes.size()); } } } if (dataFields.size() == 1 && !dataFields[0].isSerialized) return items; vector<uint8_t> prefix; if (items.size() < 56) { prefix.push_back(192u + items.size()); } else { vector<uint8_t> s; size_t tmp = items.size(); while (tmp > 0) { s.push_back(tmp % 256); tmp /= 256; } prefix.push_back(247u + s.size()); while (!s.empty()) { prefix.push_back(s.back()); s.pop_back(); } } vector<uint8_t> result; result.resize(prefix.size() + items.size()); memcpy(result.data(), prefix.data(), prefix.size()); memcpy(result.data() + prefix.size(), items.data(), items.size()); return result; } vector<uint8_t> numberToVector(size_t input) { vector<uint8_t> result; vector<uint8_t> tmp; //will be filled with bytes and later reversed into result vector while (input > 0) { tmp.push_back(input % 256); input /= 256; } while (!tmp.empty()) { result.push_back(tmp.back()); tmp.pop_back(); } return result; } <|endoftext|>
<commit_before>#include "util.h" #include <set> #include <cstdlib> #include <cstring> #include "util_stl.h" #include "types.h" std::set<void*> clone_ptrs; void free_cloned_buffer(void *ptr) { if (found(clone_ptrs,ptr)) { free(ptr); clone_ptrs.erase(ptr); } } void free_all_cloned_buffers() { traverse(clone_ptrs,ptr) free(*ptr); clone_ptrs.clear(); } void *clone(void *data, size_t size, bool gc) { void *buf = malloc(size); memcpy(buf, data, size); if (gc) clone_ptrs.insert(buf); return buf; } byte *clone_cstr(byte *data, int length, bool gc) { if (!length) length = strlen((char *)data); void *newstr = clone((void *)data, length+1, gc); newstr[length] = 0; return (byte *)newstr; } int bstrcmp(byte *s1, byte *s2, int minimum_charcode) { for (int i=0; ; ++i) { if (s1[i] < minimum_charcode) { if (s2[i] < minimum_charcode) return 0; else return s1[i] > s2[i] ? 1 : -1; } else if (s2[i] < minimum_charcode) { return 1; } else if (s1[i] != s2[i]) { return s1[i] > s2[i] ? 1 : -1; } } return 0; /* byte *p1 = s1, *p2 = s2; while ((*p1 >= minimum_charcode) && (*p1 == *p2)) { ++p1; ++p2; } if (*p1 > *p2) return 1; else if (*p1 < *p2) return -1; else return 0; */ } int bstrncmp(byte *s1, byte *s2, size_t n, int minimum_charcode) { for (int i=0; i<n; ++i) { if (s1[i] < minimum_charcode) { if (s2[i] < minimum_charcode) return 0; else return s1[i] > s2[i] ? 1 : -1; } else if (s2[i] < minimum_charcode) { return 1; } else if (s1[i] != s2[i]) { return s1[i] > s2[i] ? 1 : -1; } } return 0; } int pbstrcmp(const void *s1, const void *s2) { return bstrcmp(*(byte **)s1, *(byte **)s2); } int pbsrncmp(const void *s1, const void *s2, size_t n) { return bstrncmp(*(byte **)s1, *(byte **)s2, n); } byte *strhead(byte *ptr) { byte *p = ptr; while (*p) --p; return p+1; } <commit_msg>clone_cstr()のbug fix<commit_after>#include "util.h" #include <set> #include <cstdlib> #include <cstring> #include "util_stl.h" #include "types.h" std::set<void*> clone_ptrs; void free_cloned_buffer(void *ptr) { if (found(clone_ptrs,ptr)) { free(ptr); clone_ptrs.erase(ptr); } } void free_all_cloned_buffers() { traverse(clone_ptrs,ptr) free(*ptr); clone_ptrs.clear(); } void *clone(void *data, size_t size, bool gc) { void *buf = malloc(size); memcpy(buf, data, size); if (gc) clone_ptrs.insert(buf); return buf; } byte *clone_cstr(byte *data, int length, bool gc) { if (!length) length = strlen((char *)data); void *newstr = clone((void *)data, length+1, gc); ((byte *)newstr)[length] = 0; return (byte *)newstr; } int bstrcmp(byte *s1, byte *s2, int minimum_charcode) { for (int i=0; ; ++i) { if (s1[i] < minimum_charcode) { if (s2[i] < minimum_charcode) return 0; else return s1[i] > s2[i] ? 1 : -1; } else if (s2[i] < minimum_charcode) { return 1; } else if (s1[i] != s2[i]) { return s1[i] > s2[i] ? 1 : -1; } } return 0; /* byte *p1 = s1, *p2 = s2; while ((*p1 >= minimum_charcode) && (*p1 == *p2)) { ++p1; ++p2; } if (*p1 > *p2) return 1; else if (*p1 < *p2) return -1; else return 0; */ } int bstrncmp(byte *s1, byte *s2, size_t n, int minimum_charcode) { for (int i=0; i<n; ++i) { if (s1[i] < minimum_charcode) { if (s2[i] < minimum_charcode) return 0; else return s1[i] > s2[i] ? 1 : -1; } else if (s2[i] < minimum_charcode) { return 1; } else if (s1[i] != s2[i]) { return s1[i] > s2[i] ? 1 : -1; } } return 0; } int pbstrcmp(const void *s1, const void *s2) { return bstrcmp(*(byte **)s1, *(byte **)s2); } int pbsrncmp(const void *s1, const void *s2, size_t n) { return bstrncmp(*(byte **)s1, *(byte **)s2, n); } byte *strhead(byte *ptr) { byte *p = ptr; while (*p) --p; return p+1; } <|endoftext|>
<commit_before>//============================================================================ // Name : Text.cpp // Author : Duarte Peixinho // Version : // Copyright : ;) // Description : Text //============================================================================ #include <string> #include "Text.h" namespace p3d { namespace Renderables { Text::Text(const uint32 &Handle, const std::string& text, const f32 &charWidth, const f32 &charHeight, const Vec4 &color) { this->charWidth = charWidth; this->charHeight = charHeight; this->fontHandle = Handle; geometry = new TextGeometry(); // Generate Font Font* font = (Font*)AssetManager::GetAsset(fontHandle)->AssetPTR; font->CreateText(text); UpdateText(text, color); } Text::Text(const uint32 &Handle, const std::string& text, const f32 &charWidth, const f32 &charHeight, const std::vector<Vec4> &colors) { this->charWidth = charWidth; this->charHeight = charHeight; this->fontHandle = Handle; geometry = new TextGeometry(); // Generate Font Font* font = (Font*)AssetManager::GetAsset(fontHandle)->AssetPTR; font->CreateText(text); UpdateText(text, colors); } void Text::UpdateText(const std::string &text,const Vec4 &color) { if (geometry->index.size()>0) { geometry->Dispose(); geometry->index.clear(); geometry->tVertex.clear(); geometry->tNormal.clear(); geometry->tTexcoord.clear(); } // Generate Font Font* font = (Font*)AssetManager::GetAsset(fontHandle)->AssetPTR; font->CreateText(text); f32 width = 0.0f; f32 height = 0.0f; f32 offsetX = 0; f32 offsetY = 0; uint32 quads = 0; f32 lineSize = 0.0f; for (uint32 i = 0;i<text.size();i++) { switch(text[i]) { case '\n': // Build Quads in the bottom offsetY-=lineSize*1.5; offsetX = 0.0f; break; case ' ': offsetX+=font->GetFontSize()/2; break; default: glyph_properties glp = font->GetGlyphs()[text[i]]; width = glp.size.x; height = glp.size.y; // Build Quads to the right f32 w2 = width; f32 h2 = height; if (height + glp.offset.y >lineSize) lineSize = height + glp.offset.y; Vec3 a = Vec3(offsetX, offsetY-glp.offset.y ,0); Vec3 b = Vec3(w2+offsetX, offsetY-glp.offset.y ,0); Vec3 c = Vec3(w2+offsetX, h2+offsetY-glp.offset.y ,0); Vec3 d = Vec3(offsetX, h2+offsetY-glp.offset.y ,0); // Apply Dimensions a.x = charWidth * a.x / font->GetFontSize(); a.y = charHeight * a.y / font->GetFontSize(); b.x = charWidth * b.x / font->GetFontSize(); b.y = charHeight * b.y / font->GetFontSize(); c.x = charWidth * c.x / font->GetFontSize(); c.y = charHeight * c.y / font->GetFontSize(); d.x = charWidth * d.x / font->GetFontSize(); d.y = charHeight * d.y / font->GetFontSize(); Vec3 normal = Vec3(color.x,color.y,color.z); geometry->tVertex.push_back(a); geometry->tNormal.push_back(normal); geometry->tVertex.push_back(b); geometry->tNormal.push_back(normal); geometry->tVertex.push_back(c); geometry->tNormal.push_back(normal); geometry->tVertex.push_back(d); geometry->tNormal.push_back(normal); Texture t = font->GetTexture(); geometry->tTexcoord.push_back(Vec2(glp.startingPoint.x,glp.startingPoint.y + glp.size.y/(f32)t.GetHeight())); geometry->tTexcoord.push_back(Vec2(glp.startingPoint.x + glp.size.x/(f32)t.GetWidth(),glp.startingPoint.y + glp.size.y/(f32)t.GetHeight())); geometry->tTexcoord.push_back(Vec2(glp.startingPoint.x + glp.size.x/(f32)t.GetWidth(),glp.startingPoint.y)); geometry->tTexcoord.push_back(Vec2(glp.startingPoint.x,glp.startingPoint.y)); geometry->index.push_back(quads*4+0); geometry->index.push_back(quads*4+1); geometry->index.push_back(quads*4+2); geometry->index.push_back(quads*4+2); geometry->index.push_back(quads*4+3); geometry->index.push_back(quads*4+0); offsetX+=width + glp.offset.x; quads++; break; } } // Build and Send Buffers Build(); } void Text::UpdateText(const std::string &text,const std::vector<Vec4> &colors) { if (geometry->index.size()>0) { geometry->Dispose(); geometry->index.clear(); geometry->tVertex.clear(); geometry->tNormal.clear(); geometry->tTexcoord.clear(); } // Generate Font Font* font = (Font*)AssetManager::GetAsset(fontHandle)->AssetPTR; font->CreateText(text); f32 width = 0.0f; f32 height = 0.0f; f32 offsetX = 0; f32 offsetY = 0; uint32 quads = 0; f32 lineSize = 0.0f; for (uint32 i = 0;i<text.size();i++) { switch(text[i]) { case '\n': // Build Quads in the bottom offsetY-=lineSize*1.5; offsetX = 0.0f; break; case ' ': offsetX+=font->GetFontSize()/2; break; default: glyph_properties glp = font->GetGlyphs()[text[i]]; width = glp.size.x; height = glp.size.y; // Build Quads to the right f32 w2 = width; f32 h2 = height; if (height + glp.offset.y >lineSize) lineSize = height + glp.offset.y; Vec3 a = Vec3(offsetX, offsetY-glp.offset.y ,0); Vec3 b = Vec3(w2+offsetX, offsetY-glp.offset.y ,0); Vec3 c = Vec3(w2+offsetX, h2+offsetY-glp.offset.y ,0); Vec3 d = Vec3(offsetX, h2+offsetY-glp.offset.y ,0); // Apply Dimensions a.x = charWidth * a.x / font->GetFontSize(); a.y = charHeight * a.y / font->GetFontSize(); b.x = charWidth * b.x / font->GetFontSize(); b.y = charHeight * b.y / font->GetFontSize(); c.x = charWidth * c.x / font->GetFontSize(); c.y = charHeight * c.y / font->GetFontSize(); d.x = charWidth * d.x / font->GetFontSize(); d.y = charHeight * d.y / font->GetFontSize(); // Set Color Vec3 normal = Vec3(colors[i].x,colors[i].y,colors[i].z); std::cout << normal.toString() << std::endl; geometry->tVertex.push_back(a); geometry->tNormal.push_back(normal); geometry->tVertex.push_back(b); geometry->tNormal.push_back(normal); geometry->tVertex.push_back(c); geometry->tNormal.push_back(normal); geometry->tVertex.push_back(d); geometry->tNormal.push_back(normal); Texture t = font->GetTexture(); geometry->tTexcoord.push_back(Vec2(glp.startingPoint.x,glp.startingPoint.y + glp.size.y/(f32)t.GetHeight())); geometry->tTexcoord.push_back(Vec2(glp.startingPoint.x + glp.size.x/(f32)t.GetWidth(),glp.startingPoint.y + glp.size.y/(f32)t.GetHeight())); geometry->tTexcoord.push_back(Vec2(glp.startingPoint.x + glp.size.x/(f32)t.GetWidth(),glp.startingPoint.y)); geometry->tTexcoord.push_back(Vec2(glp.startingPoint.x,glp.startingPoint.y)); geometry->index.push_back(quads*4+0); geometry->index.push_back(quads*4+1); geometry->index.push_back(quads*4+2); geometry->index.push_back(quads*4+2); geometry->index.push_back(quads*4+3); geometry->index.push_back(quads*4+0); offsetX+=width + glp.offset.x; quads++; break; } } // Build and Send Buffers Build(); } Text::~Text() { } }; }<commit_msg>Another Fix from Last Commit<commit_after>//============================================================================ // Name : Text.cpp // Author : Duarte Peixinho // Version : // Copyright : ;) // Description : Text //============================================================================ #include <string> #include "Text.h" namespace p3d { namespace Renderables { Text::Text(const uint32 &Handle, const std::string& text, const f32 &charWidth, const f32 &charHeight, const Vec4 &color) { this->charWidth = charWidth; this->charHeight = charHeight; this->fontHandle = Handle; geometry = new TextGeometry(); // Generate Font Font* font = (Font*)AssetManager::GetAsset(fontHandle)->AssetPTR; font->CreateText(text); UpdateText(text, color); } Text::Text(const uint32 &Handle, const std::string& text, const f32 &charWidth, const f32 &charHeight, const std::vector<Vec4> &colors) { this->charWidth = charWidth; this->charHeight = charHeight; this->fontHandle = Handle; geometry = new TextGeometry(); // Generate Font Font* font = (Font*)AssetManager::GetAsset(fontHandle)->AssetPTR; font->CreateText(text); UpdateText(text, colors); } void Text::UpdateText(const std::string &text,const Vec4 &color) { if (geometry->index.size()>0) { geometry->Dispose(); geometry->index.clear(); geometry->tVertex.clear(); geometry->tNormal.clear(); geometry->tTexcoord.clear(); } // Generate Font Font* font = (Font*)AssetManager::GetAsset(fontHandle)->AssetPTR; font->CreateText(text); f32 width = 0.0f; f32 height = 0.0f; f32 offsetX = 0; f32 offsetY = 0; uint32 quads = 0; f32 lineSize = 0.0f; for (uint32 i = 0;i<text.size();i++) { switch(text[i]) { case '\n': // Build Quads in the bottom offsetY-=lineSize*1.5; offsetX = 0.0f; break; case ' ': offsetX+=font->GetFontSize()/2; break; default: glyph_properties glp = font->GetGlyphs()[text[i]]; width = glp.size.x; height = glp.size.y; // Build Quads to the right f32 w2 = width; f32 h2 = height; if (height + glp.offset.y >lineSize) lineSize = height + glp.offset.y; Vec3 a = Vec3(offsetX, offsetY-glp.offset.y ,0); Vec3 b = Vec3(w2+offsetX, offsetY-glp.offset.y ,0); Vec3 c = Vec3(w2+offsetX, h2+offsetY-glp.offset.y ,0); Vec3 d = Vec3(offsetX, h2+offsetY-glp.offset.y ,0); // Apply Dimensions a.x = charWidth * a.x / font->GetFontSize(); a.y = charHeight * a.y / font->GetFontSize(); b.x = charWidth * b.x / font->GetFontSize(); b.y = charHeight * b.y / font->GetFontSize(); c.x = charWidth * c.x / font->GetFontSize(); c.y = charHeight * c.y / font->GetFontSize(); d.x = charWidth * d.x / font->GetFontSize(); d.y = charHeight * d.y / font->GetFontSize(); Vec3 normal = Vec3(color.x,color.y,color.z); geometry->tVertex.push_back(a); geometry->tNormal.push_back(normal); geometry->tVertex.push_back(b); geometry->tNormal.push_back(normal); geometry->tVertex.push_back(c); geometry->tNormal.push_back(normal); geometry->tVertex.push_back(d); geometry->tNormal.push_back(normal); Texture t = font->GetTexture(); geometry->tTexcoord.push_back(Vec2(glp.startingPoint.x,glp.startingPoint.y + glp.size.y/(f32)t.GetHeight())); geometry->tTexcoord.push_back(Vec2(glp.startingPoint.x + glp.size.x/(f32)t.GetWidth(),glp.startingPoint.y + glp.size.y/(f32)t.GetHeight())); geometry->tTexcoord.push_back(Vec2(glp.startingPoint.x + glp.size.x/(f32)t.GetWidth(),glp.startingPoint.y)); geometry->tTexcoord.push_back(Vec2(glp.startingPoint.x,glp.startingPoint.y)); geometry->index.push_back(quads*4+0); geometry->index.push_back(quads*4+1); geometry->index.push_back(quads*4+2); geometry->index.push_back(quads*4+2); geometry->index.push_back(quads*4+3); geometry->index.push_back(quads*4+0); offsetX+=width + glp.offset.x; quads++; break; } } // Build and Send Buffers Build(); } void Text::UpdateText(const std::string &text,const std::vector<Vec4> &colors) { if (geometry->index.size()>0) { geometry->Dispose(); geometry->index.clear(); geometry->tVertex.clear(); geometry->tNormal.clear(); geometry->tTexcoord.clear(); } // Generate Font Font* font = (Font*)AssetManager::GetAsset(fontHandle)->AssetPTR; font->CreateText(text); f32 width = 0.0f; f32 height = 0.0f; f32 offsetX = 0; f32 offsetY = 0; uint32 quads = 0; f32 lineSize = 0.0f; for (uint32 i = 0;i<text.size();i++) { switch(text[i]) { case '\n': // Build Quads in the bottom offsetY-=lineSize*1.5; offsetX = 0.0f; break; case ' ': offsetX+=font->GetFontSize()/2; break; default: glyph_properties glp = font->GetGlyphs()[text[i]]; width = glp.size.x; height = glp.size.y; // Build Quads to the right f32 w2 = width; f32 h2 = height; if (height + glp.offset.y >lineSize) lineSize = height + glp.offset.y; Vec3 a = Vec3(offsetX, offsetY-glp.offset.y ,0); Vec3 b = Vec3(w2+offsetX, offsetY-glp.offset.y ,0); Vec3 c = Vec3(w2+offsetX, h2+offsetY-glp.offset.y ,0); Vec3 d = Vec3(offsetX, h2+offsetY-glp.offset.y ,0); // Apply Dimensions a.x = charWidth * a.x / font->GetFontSize(); a.y = charHeight * a.y / font->GetFontSize(); b.x = charWidth * b.x / font->GetFontSize(); b.y = charHeight * b.y / font->GetFontSize(); c.x = charWidth * c.x / font->GetFontSize(); c.y = charHeight * c.y / font->GetFontSize(); d.x = charWidth * d.x / font->GetFontSize(); d.y = charHeight * d.y / font->GetFontSize(); // Set Color Vec3 normal = Vec3(colors[i].x,colors[i].y,colors[i].z); geometry->tVertex.push_back(a); geometry->tNormal.push_back(normal); geometry->tVertex.push_back(b); geometry->tNormal.push_back(normal); geometry->tVertex.push_back(c); geometry->tNormal.push_back(normal); geometry->tVertex.push_back(d); geometry->tNormal.push_back(normal); Texture t = font->GetTexture(); geometry->tTexcoord.push_back(Vec2(glp.startingPoint.x,glp.startingPoint.y + glp.size.y/(f32)t.GetHeight())); geometry->tTexcoord.push_back(Vec2(glp.startingPoint.x + glp.size.x/(f32)t.GetWidth(),glp.startingPoint.y + glp.size.y/(f32)t.GetHeight())); geometry->tTexcoord.push_back(Vec2(glp.startingPoint.x + glp.size.x/(f32)t.GetWidth(),glp.startingPoint.y)); geometry->tTexcoord.push_back(Vec2(glp.startingPoint.x,glp.startingPoint.y)); geometry->index.push_back(quads*4+0); geometry->index.push_back(quads*4+1); geometry->index.push_back(quads*4+2); geometry->index.push_back(quads*4+2); geometry->index.push_back(quads*4+3); geometry->index.push_back(quads*4+0); offsetX+=width + glp.offset.x; quads++; break; } } // Build and Send Buffers Build(); } Text::~Text() { } }; }<|endoftext|>
<commit_before>/* * Copyright(c) Sophist Solutions, Inc. 1990-2018. All rights reserved */ #ifndef _Stroika_Foundation_Containers_DataHyperRectangle_inl_ #define _Stroika_Foundation_Containers_DataHyperRectangle_inl_ #include "../Configuration/Concepts.h" #include "../Debug/Assertions.h" #include "Private/IterableUtils.h" namespace Stroika { namespace Foundation { namespace Containers { /* ******************************************************************************** ************************ DataHyperRectangle<T, INDEXES> ************************ ******************************************************************************** */ template <typename T, typename... INDEXES> inline DataHyperRectangle<T, INDEXES...>::DataHyperRectangle (const DataHyperRectangle<T, INDEXES...>& src) noexcept : inherited (src) { _AssertRepValidType (); } template <typename T, typename... INDEXES> inline DataHyperRectangle<T, INDEXES...>::DataHyperRectangle (DataHyperRectangle<T, INDEXES...>&& src) noexcept : inherited (move (src)) { _AssertRepValidType (); } template <typename T, typename... INDEXES> inline DataHyperRectangle<T, INDEXES...>::DataHyperRectangle (const _DataHyperRectangleRepSharedPtr& src) noexcept : inherited (src) { RequireNotNull (src); _AssertRepValidType (); } template <typename T, typename... INDEXES> inline DataHyperRectangle<T, INDEXES...>::DataHyperRectangle (_DataHyperRectangleRepSharedPtr&& src) noexcept : inherited ((RequireNotNull (src), move (src))) { _AssertRepValidType (); } template <typename T, typename... INDEXES> inline T DataHyperRectangle<T, INDEXES...>::GetAt (INDEXES... indexes) const { return _SafeReadRepAccessor<_IRep>{this}._ConstGetRep ().GetAt (std::forward<INDEXES> (indexes)...); } template <typename T, typename... INDEXES> inline void DataHyperRectangle<T, INDEXES...>::SetAt (INDEXES... indexes, Configuration::ArgByValueType<T> v) { _SafeReadWriteRepAccessor<_IRep>{this}._GetWriteableRep ().SetAt (std::forward<INDEXES> (indexes)..., v); } template <typename T, typename... INDEXES> template <typename EQUALS_COMPARER> bool DataHyperRectangle<T, INDEXES...>::Equals (const DataHyperRectangle<T, INDEXES...>& rhs) const { return Private::Equals_<T, EQUALS_COMPARER> (*this, rhs); } template <typename T, typename... INDEXES> inline void DataHyperRectangle<T, INDEXES...>::_AssertRepValidType () const { #if qDebug _SafeReadRepAccessor<_IRep>{this}; #endif } /* ******************************************************************************** ********************* DataHyperRectangle operators ***************************** ******************************************************************************** */ template <typename T, typename... INDEXES> inline bool operator== (const DataHyperRectangle<T, INDEXES...>& lhs, const DataHyperRectangle<T, INDEXES...>& rhs) { return lhs.Equals (rhs); } template <typename T, typename... INDEXES> inline bool operator!= (const DataHyperRectangle<T, INDEXES...>& lhs, const DataHyperRectangle<T, INDEXES...>& rhs) { return not lhs.Equals (rhs); } } } } #endif /* _Stroika_Foundation_Containers_DataHyperRectangle_inl_ */ <commit_msg>fix Containers like Set, Stack, Queue etc - which dont intrinsically have a need for an Equals Comparer - so Equals() method takes STL-style equals-comparer<commit_after>/* * Copyright(c) Sophist Solutions, Inc. 1990-2018. All rights reserved */ #ifndef _Stroika_Foundation_Containers_DataHyperRectangle_inl_ #define _Stroika_Foundation_Containers_DataHyperRectangle_inl_ #include "../Configuration/Concepts.h" #include "../Debug/Assertions.h" #include "Private/IterableUtils.h" namespace Stroika { namespace Foundation { namespace Containers { /* ******************************************************************************** ************************ DataHyperRectangle<T, INDEXES> ************************ ******************************************************************************** */ template <typename T, typename... INDEXES> inline DataHyperRectangle<T, INDEXES...>::DataHyperRectangle (const DataHyperRectangle<T, INDEXES...>& src) noexcept : inherited (src) { _AssertRepValidType (); } template <typename T, typename... INDEXES> inline DataHyperRectangle<T, INDEXES...>::DataHyperRectangle (DataHyperRectangle<T, INDEXES...>&& src) noexcept : inherited (move (src)) { _AssertRepValidType (); } template <typename T, typename... INDEXES> inline DataHyperRectangle<T, INDEXES...>::DataHyperRectangle (const _DataHyperRectangleRepSharedPtr& src) noexcept : inherited (src) { RequireNotNull (src); _AssertRepValidType (); } template <typename T, typename... INDEXES> inline DataHyperRectangle<T, INDEXES...>::DataHyperRectangle (_DataHyperRectangleRepSharedPtr&& src) noexcept : inherited ((RequireNotNull (src), move (src))) { _AssertRepValidType (); } template <typename T, typename... INDEXES> inline T DataHyperRectangle<T, INDEXES...>::GetAt (INDEXES... indexes) const { return _SafeReadRepAccessor<_IRep>{this}._ConstGetRep ().GetAt (std::forward<INDEXES> (indexes)...); } template <typename T, typename... INDEXES> inline void DataHyperRectangle<T, INDEXES...>::SetAt (INDEXES... indexes, Configuration::ArgByValueType<T> v) { _SafeReadWriteRepAccessor<_IRep>{this}._GetWriteableRep ().SetAt (std::forward<INDEXES> (indexes)..., v); } template <typename T, typename... INDEXES> template <typename EQUALS_COMPARER> bool DataHyperRectangle<T, INDEXES...>::Equals (const DataHyperRectangle& rhs, , const EQUALS_COMPARER& equalsComparer) const { return Private::Equals__<T, EQUALS_COMPARER> (*this, rhs, equalsComparer); } template <typename T, typename... INDEXES> inline void DataHyperRectangle<T, INDEXES...>::_AssertRepValidType () const { #if qDebug _SafeReadRepAccessor<_IRep>{this}; #endif } /* ******************************************************************************** ********************* DataHyperRectangle operators ***************************** ******************************************************************************** */ template <typename T, typename... INDEXES> inline bool operator== (const DataHyperRectangle<T, INDEXES...>& lhs, const DataHyperRectangle<T, INDEXES...>& rhs) { return lhs.Equals (rhs); } template <typename T, typename... INDEXES> inline bool operator!= (const DataHyperRectangle<T, INDEXES...>& lhs, const DataHyperRectangle<T, INDEXES...>& rhs) { return not lhs.Equals (rhs); } } } } #endif /* _Stroika_Foundation_Containers_DataHyperRectangle_inl_ */ <|endoftext|>
<commit_before>// -*- C++ -*- // The MIT License (MIT) // // Copyright (c) 2021 Alexander Samoilov // // 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 "ChebyshevDifferentiate.hpp" /// /// as \f$T_n(\cos\theta)=\cos n\theta\f$, then /// /// \f[ /// \frac{T'_{n+1}(x)}{n+1}-\frac{T'_{n-1}(x)}{n-1}=\frac2{c_n}T_n(x) /// \quad(n>=0) /// \f] /// /// where \f$c_0=2,\,c_n=1\,(n\le1)\f$ and \f$T'_0=T'_{-1}=0\f$, implies if /// /// \f[ /// \frac d{dx}\sum^N_{n=0}a_nT_n(x)=\sum^N_{n=0}b_nT_n(x) /// \f] /// /// then /// /// \f{align*}{ /// \sum^N_{n=0}a_nT'_n(x) /// &=\sum^N_{n=0}c_nb_n\left[T_n(x) /// \frac{T'_{n+1}(x)}{n+1}-\frac{T'_{n-1}(x)}{n-1}\right]\\ /// &=\sum^{N+1}_{n=0}[c_{n-1}b_{n-1}-b_{n+1}]T'_n(x)/n /// \f} /// /// equating \f$T'_n(x)\f$ for \f$n=1,\dots,N+1\f$ /// we derive recurrent equations for Chebyshev polynomials derivatives /// /// \f{alignat*}{{2} /// c_{n-1}b_{n-1}-b_{n+1} &= 2na_n &&\quad(1\le n\le N)\\ /// b_n &=0 &&\quad(n\ge N) /// \f} /// /// if approximate solution is at each collocation point \f$(x_j)\f$ /// /// \f[ /// u(x,t) = \sum_{k=1}^{N+1}a_{k}T_{k-1}(x) /// \f] /// /// then, in particular, spatial derivatives can be defined directly in terms /// of undifferentiated Chebyshev polynomials, i.e. /// /// \f[ /// \frac{\partial{u}}{\partial{x}} = \sum_{k=1}^{N}a_{k}^{(1)}T_{k-1}(x) /// \f] /// /// and /// /// \f[ /// \frac{\partial^2{u}}{\partial{x^2}} = \sum_{k=1}^{N-1}a_{k}^{(2)}T_{k-1}(x) /// \f] /// /// Specifically, the following recurrence relations permit all /// the \f$a_k^{(1)}, a_k^{(2)}\f$ coefficients to be obtained in \f$O(N)\f$ operations /// /// \f{alignat*}{{2} /// a_k^{(1)} &= a_{k+2}^{(1)} + 2k a_{k+1} &&\quad(2\le k\le N)\\ /// a_k^{(2)} &= a_{k+2}^{(2)} + 2k a_{k+1}^{(1)} &&\quad(2\le k\le N-1)\\ /// \f} /// /// and /// /// \f[ /// a_1^{(1)} = 0.5 a_3^{(1)} + 2k a_2, \quad a_1^{(2)} = 0.5 a_3^{(2)} + 2k a_2^{(1)} /// \f] /// /// and /// /// \f[ /// a_{N+1}^{(1)} = a_{N+2}^{(1)} = 0, \quad a_{N}^{(2)} = a_{N+1}^{(2)} = 0 /// \f] void SpectralDifferentiate(Eigen::Ref<RowVectorXd> data, Eigen::Ref<RowVectorXd> rslt, double span, unsigned n) { double temp1 = data[n-1], temp2 = data[n-2]; rslt[n-1] = 2.0*n*span*data[n]; rslt[n-2] = 2.0*(n-1)*span*temp1; for (unsigned j=n-3; j>0; j--) { temp1 = data[j]; rslt[j] = rslt[j+2]+2.0*(j+1)*span*temp2; temp2 = temp1; } rslt[0] = 0.5*rslt[2]+span*temp2; rslt[n] = 0.0; } void BoundaryConditions(Eigen::Ref<RowVectorXd> data, Eigen::Ref<RowVectorXd> rslt, unsigned n) { double evens,odds; for (unsigned i=0; i<=n; i++) { evens = odds = 0.0; for (unsigned j=1; j<=n-2; j+=2) { odds -= data(i, j); evens -= data(i, j+1); } for (unsigned j=0; j<=n-2; j++) { rslt(i, j) = data(i, j); } rslt(i, n-1) = odds; rslt(i, n ) = evens-data(i, 0); /* rslt(i, 0) = rslt(i, 1) = 0.0; */ } } <commit_msg>slightly more terse dox on spectral differentiation.<commit_after>// -*- C++ -*- // The MIT License (MIT) // // Copyright (c) 2021 Alexander Samoilov // // 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 "ChebyshevDifferentiate.hpp" /// /// as \f$T_n(\cos\theta)=\cos n\theta\f$, then /// /// \f[ /// \frac{T'_{n+1}(x)}{n+1}-\frac{T'_{n-1}(x)}{n-1}=\frac2{c_n}T_n(x) /// \quad(n>=0) /// \f] /// /// where \f$c_0=2,\,c_n=1\,(n\le1)\f$ and \f$T'_0=T'_{-1}=0\f$, implies if /// /// \f[ /// \frac d{dx}\sum^N_{n=0}a_nT_n(x)=\sum^N_{n=0}b_nT_n(x) /// \f] /// /// then /// /// \f{align*}{ /// \sum^N_{n=0}a_nT'_n(x) /// &=\sum^N_{n=0}c_nb_n\left[T_n(x) /// \frac{T'_{n+1}(x)}{n+1}-\frac{T'_{n-1}(x)}{n-1}\right]\\ /// &=\sum^{N+1}_{n=0}[c_{n-1}b_{n-1}-b_{n+1}]T'_n(x)/n /// \f} /// /// equating \f$T'_n(x)\f$ for \f$n=1,\dots,N+1\f$ /// we derive recurrent equations for Chebyshev polynomials derivatives /// /// \f{alignat*}{{2} /// c_{n-1}b_{n-1}-b_{n+1} &= 2na_n &&\quad(1\le n\le N)\\ /// b_n &=0 &&\quad(n\ge N) /// \f} /// /// if approximate solution is at each collocation point \f$(x_j)\f$ /// /// \f[ /// u(x,t) = \sum_{k=1}^{N+1}a_{k}T_{k-1}(x) /// \f] /// /// then, in particular, spatial derivatives can be defined directly in terms /// of undifferentiated Chebyshev polynomials, i.e. /// /// \f[ /// \frac{\partial{u}}{\partial{x}} = \sum_{k=1}^{N}a_{k}^{(1)}T_{k-1}(x) /// \f] /// /// and /// /// \f[ /// \frac{\partial^2{u}}{\partial{x^2}} = \sum_{k=1}^{N-1}a_{k}^{(2)}T_{k-1}(x) /// \f] /// /// Specifically, the following recurrence relations permit all /// the \f$a_k^{(1)}, a_k^{(2)}\f$ coefficients to be obtained in \f$O(N)\f$ operations /// /// \f{alignat*}{{2} /// a_k^{(1)} &= a_{k+2}^{(1)} + 2k a_{k+1} &&\quad(2\le k\le N)\\ /// a_k^{(2)} &= a_{k+2}^{(2)} + 2k a_{k+1}^{(1)} &&\quad(2\le k\le N-1)\\ /// \f} /// /// and \f$\qquad a_1^{(1)} = 0.5 a_3^{(1)} + 2k a_2, \quad a_1^{(2)} = 0.5 a_3^{(2)} + 2k a_2^{(1)}\f$ /// /// and \f$\qquad a_{N+1}^{(1)} = a_{N+2}^{(1)} = 0, \quad a_{N}^{(2)} = a_{N+1}^{(2)} = 0\f$ void SpectralDifferentiate(Eigen::Ref<RowVectorXd> data, Eigen::Ref<RowVectorXd> rslt, double span, unsigned n) { double temp1 = data[n-1], temp2 = data[n-2]; rslt[n-1] = 2.0*n*span*data[n]; rslt[n-2] = 2.0*(n-1)*span*temp1; for (unsigned j=n-3; j>0; j--) { temp1 = data[j]; rslt[j] = rslt[j+2]+2.0*(j+1)*span*temp2; temp2 = temp1; } rslt[0] = 0.5*rslt[2]+span*temp2; rslt[n] = 0.0; } void BoundaryConditions(Eigen::Ref<RowVectorXd> data, Eigen::Ref<RowVectorXd> rslt, unsigned n) { double evens,odds; for (unsigned i=0; i<=n; i++) { evens = odds = 0.0; for (unsigned j=1; j<=n-2; j+=2) { odds -= data(i, j); evens -= data(i, j+1); } for (unsigned j=0; j<=n-2; j++) { rslt(i, j) = data(i, j); } rslt(i, n-1) = odds; rslt(i, n ) = evens-data(i, 0); /* rslt(i, 0) = rslt(i, 1) = 0.0; */ } } <|endoftext|>
<commit_before>/* * Copyright (C) 2015 Cloudius Systems, Ltd. */ #include "repair.hh" #include "streaming/stream_plan.hh" #include "streaming/stream_state.hh" #include "gms/inet_address.hh" static logging::logger logger("repair"); static std::vector<sstring> list_column_families(const database& db, const sstring& keyspace) { std::vector<sstring> ret; for (auto &&e : db.get_column_families_mapping()) { if (e.first.first == keyspace) { ret.push_back(e.first.second); } } return ret; } template<typename Collection, typename T> void remove_item(Collection& c, T& item) { auto it = std::find(c.begin(), c.end(), item); if (it != c.end()) { c.erase(it); } } // Return all of the neighbors with whom we share the provided range. static std::vector<gms::inet_address> get_neighbors(database& db, const sstring& ksname, query::range<dht::token> range //Collection<String> dataCenters, Collection<String> hosts) ) { keyspace& ks = db.find_keyspace(ksname); auto& rs = ks.get_replication_strategy(); dht::token tok = range.end() ? range.end()->value() : dht::maximum_token(); auto ret = rs.get_natural_endpoints(tok); remove_item(ret, utils::fb_utilities::get_broadcast_address()); return ret; #if 0 // Origin's ActiveRepairService.getNeighbors() contains a lot of important // stuff we need to do, like verifying the requested range fits a local // range, and also taking the "datacenters" and "hosts" options. StorageService ss = StorageService.instance; Map<Range<Token>, List<InetAddress>> replicaSets = ss.getRangeToAddressMap(keyspaceName); Range<Token> rangeSuperSet = null; for (Range<Token> range : ss.getLocalRanges(keyspaceName)) { if (range.contains(toRepair)) { rangeSuperSet = range; break; } else if (range.intersects(toRepair)) { throw new IllegalArgumentException("Requested range intersects a local range but is not fully contained in one; this would lead to imprecise repair"); } } if (rangeSuperSet == null || !replicaSets.containsKey(rangeSuperSet)) return Collections.emptySet(); Set<InetAddress> neighbors = new HashSet<>(replicaSets.get(rangeSuperSet)); neighbors.remove(FBUtilities.getBroadcastAddress()); if (dataCenters != null && !dataCenters.isEmpty()) { TokenMetadata.Topology topology = ss.getTokenMetadata().cloneOnlyTokenMap().getTopology(); Set<InetAddress> dcEndpoints = Sets.newHashSet(); Multimap<String,InetAddress> dcEndpointsMap = topology.getDatacenterEndpoints(); for (String dc : dataCenters) { Collection<InetAddress> c = dcEndpointsMap.get(dc); if (c != null) dcEndpoints.addAll(c); } return Sets.intersection(neighbors, dcEndpoints); } else if (hosts != null && !hosts.isEmpty()) { Set<InetAddress> specifiedHost = new HashSet<>(); for (final String host : hosts) { try { final InetAddress endpoint = InetAddress.getByName(host.trim()); if (endpoint.equals(FBUtilities.getBroadcastAddress()) || neighbors.contains(endpoint)) specifiedHost.add(endpoint); } catch (UnknownHostException e) { throw new IllegalArgumentException("Unknown host specified " + host, e); } } if (!specifiedHost.contains(FBUtilities.getBroadcastAddress())) throw new IllegalArgumentException("The current host must be part of the repair"); if (specifiedHost.size() <= 1) { String msg = "Repair requires at least two endpoints that are neighbours before it can continue, the endpoint used for this repair is %s, " + "other available neighbours are %s but these neighbours were not part of the supplied list of hosts to use during the repair (%s)."; throw new IllegalArgumentException(String.format(msg, specifiedHost, neighbors, hosts)); } specifiedHost.remove(FBUtilities.getBroadcastAddress()); return specifiedHost; } return neighbors; #endif } // Each repair_start() call returns a unique integer which the user can later // use to follow the status of this repair. static std::atomic<int> next_repair_command {0}; // repair_start() can run on any cpu; It runs on cpu0 the function // do_repair_start(). The benefit of always running that function on the same // CPU is that it allows us to keep some state (like a list of ongoing // repairs). It is fine to always do this on one CPU, because the function // itself does very little (mainly tell other nodes and CPUs what to do). // Repair a single range. Comparable to RepairSession in Origin // In Origin, this is composed of several "repair jobs", each with one cf, // but our streaming already works for several cfs. static void repair_range(seastar::sharded<database>& db, sstring keyspace, query::range<dht::token> range, std::vector<sstring> cfs) { auto sp = streaming::stream_plan("repair"); auto id = utils::UUID_gen::get_time_UUID(); auto neighbors = get_neighbors(db.local(), keyspace, range); logger.info("[repair #{}] new session: will sync {} on range {} for {}.{}", id, neighbors, range, keyspace, cfs); for (auto peer : neighbors) { // FIXME: think: if we have several neighbors, perhaps we need to // request ranges from all of them and only later transfer ranges to // all of them? Otherwise, we won't necessarily fully repair the // other ndoes, just this one? What does Cassandra do here? sp.transfer_ranges(peer, peer, keyspace, {range}, cfs); sp.request_ranges(peer, peer, keyspace, {range}, cfs); sp.execute().handle_exception([id] (auto ep) { logger.error("repair session #{} stream failed: {}", id, ep); }); } } static std::vector<query::range<dht::token>> get_ranges_for_endpoint( database& db, sstring keyspace, gms::inet_address ep) { auto& rs = db.find_keyspace(keyspace).get_replication_strategy(); return rs.get_ranges(ep); } static std::vector<query::range<dht::token>> get_local_ranges( database& db, sstring keyspace) { return get_ranges_for_endpoint(db, keyspace, utils::fb_utilities::get_broadcast_address()); } static void do_repair_start(seastar::sharded<database>& db, sstring keyspace, std::unordered_map<sstring, sstring> options) { logger.info("starting user-requested repair for keyspace {}", keyspace); // If the "ranges" option is not explicitly specified, we repair all the // local ranges (the token ranges for which this node holds a replica of). // Each of these ranges may have a different set of replicas, so the // repair of each range is performed separately with repair_range(). std::vector<query::range<dht::token>> ranges; // FIXME: if the "ranges" options exists, use that instead of // get_local_ranges() below. Also, translate the following Origin code: #if 0 if (option.isPrimaryRange()) { // when repairing only primary range, neither dataCenters nor hosts can be set if (option.getDataCenters().isEmpty() && option.getHosts().isEmpty()) option.getRanges().addAll(getPrimaryRanges(keyspace)); // except dataCenters only contain local DC (i.e. -local) else if (option.getDataCenters().size() == 1 && option.getDataCenters().contains(DatabaseDescriptor.getLocalDataCenter())) option.getRanges().addAll(getPrimaryRangesWithinDC(keyspace)); else throw new IllegalArgumentException("You need to run primary range repair on all nodes in the cluster."); } else #endif ranges = get_local_ranges(db.local(), keyspace); // FIXME: let the cfs be overriden by an option std::vector<sstring> cfs = list_column_families(db.local(), keyspace); for (auto range : ranges) { repair_range(db, keyspace, range, cfs); } } int repair_start(seastar::sharded<database>& db, sstring keyspace, std::unordered_map<sstring, sstring> options) { int i = next_repair_command++; db.invoke_on(0, [&db, keyspace = std::move(keyspace), options = std::move(options)] (database& localdb) { do_repair_start(db, std::move(keyspace), std::move(options)); }); // Note we ignore the value of this future return i; } <commit_msg>repair: fix use of handle_exception()<commit_after>/* * Copyright (C) 2015 Cloudius Systems, Ltd. */ #include "repair.hh" #include "streaming/stream_plan.hh" #include "streaming/stream_state.hh" #include "gms/inet_address.hh" static logging::logger logger("repair"); static std::vector<sstring> list_column_families(const database& db, const sstring& keyspace) { std::vector<sstring> ret; for (auto &&e : db.get_column_families_mapping()) { if (e.first.first == keyspace) { ret.push_back(e.first.second); } } return ret; } template<typename Collection, typename T> void remove_item(Collection& c, T& item) { auto it = std::find(c.begin(), c.end(), item); if (it != c.end()) { c.erase(it); } } // Return all of the neighbors with whom we share the provided range. static std::vector<gms::inet_address> get_neighbors(database& db, const sstring& ksname, query::range<dht::token> range //Collection<String> dataCenters, Collection<String> hosts) ) { keyspace& ks = db.find_keyspace(ksname); auto& rs = ks.get_replication_strategy(); dht::token tok = range.end() ? range.end()->value() : dht::maximum_token(); auto ret = rs.get_natural_endpoints(tok); remove_item(ret, utils::fb_utilities::get_broadcast_address()); return ret; #if 0 // Origin's ActiveRepairService.getNeighbors() contains a lot of important // stuff we need to do, like verifying the requested range fits a local // range, and also taking the "datacenters" and "hosts" options. StorageService ss = StorageService.instance; Map<Range<Token>, List<InetAddress>> replicaSets = ss.getRangeToAddressMap(keyspaceName); Range<Token> rangeSuperSet = null; for (Range<Token> range : ss.getLocalRanges(keyspaceName)) { if (range.contains(toRepair)) { rangeSuperSet = range; break; } else if (range.intersects(toRepair)) { throw new IllegalArgumentException("Requested range intersects a local range but is not fully contained in one; this would lead to imprecise repair"); } } if (rangeSuperSet == null || !replicaSets.containsKey(rangeSuperSet)) return Collections.emptySet(); Set<InetAddress> neighbors = new HashSet<>(replicaSets.get(rangeSuperSet)); neighbors.remove(FBUtilities.getBroadcastAddress()); if (dataCenters != null && !dataCenters.isEmpty()) { TokenMetadata.Topology topology = ss.getTokenMetadata().cloneOnlyTokenMap().getTopology(); Set<InetAddress> dcEndpoints = Sets.newHashSet(); Multimap<String,InetAddress> dcEndpointsMap = topology.getDatacenterEndpoints(); for (String dc : dataCenters) { Collection<InetAddress> c = dcEndpointsMap.get(dc); if (c != null) dcEndpoints.addAll(c); } return Sets.intersection(neighbors, dcEndpoints); } else if (hosts != null && !hosts.isEmpty()) { Set<InetAddress> specifiedHost = new HashSet<>(); for (final String host : hosts) { try { final InetAddress endpoint = InetAddress.getByName(host.trim()); if (endpoint.equals(FBUtilities.getBroadcastAddress()) || neighbors.contains(endpoint)) specifiedHost.add(endpoint); } catch (UnknownHostException e) { throw new IllegalArgumentException("Unknown host specified " + host, e); } } if (!specifiedHost.contains(FBUtilities.getBroadcastAddress())) throw new IllegalArgumentException("The current host must be part of the repair"); if (specifiedHost.size() <= 1) { String msg = "Repair requires at least two endpoints that are neighbours before it can continue, the endpoint used for this repair is %s, " + "other available neighbours are %s but these neighbours were not part of the supplied list of hosts to use during the repair (%s)."; throw new IllegalArgumentException(String.format(msg, specifiedHost, neighbors, hosts)); } specifiedHost.remove(FBUtilities.getBroadcastAddress()); return specifiedHost; } return neighbors; #endif } // Each repair_start() call returns a unique integer which the user can later // use to follow the status of this repair. static std::atomic<int> next_repair_command {0}; // repair_start() can run on any cpu; It runs on cpu0 the function // do_repair_start(). The benefit of always running that function on the same // CPU is that it allows us to keep some state (like a list of ongoing // repairs). It is fine to always do this on one CPU, because the function // itself does very little (mainly tell other nodes and CPUs what to do). // Repair a single range. Comparable to RepairSession in Origin // In Origin, this is composed of several "repair jobs", each with one cf, // but our streaming already works for several cfs. static void repair_range(seastar::sharded<database>& db, sstring keyspace, query::range<dht::token> range, std::vector<sstring> cfs) { auto sp = streaming::stream_plan("repair"); auto id = utils::UUID_gen::get_time_UUID(); auto neighbors = get_neighbors(db.local(), keyspace, range); logger.info("[repair #{}] new session: will sync {} on range {} for {}.{}", id, neighbors, range, keyspace, cfs); for (auto peer : neighbors) { // FIXME: think: if we have several neighbors, perhaps we need to // request ranges from all of them and only later transfer ranges to // all of them? Otherwise, we won't necessarily fully repair the // other ndoes, just this one? What does Cassandra do here? sp.transfer_ranges(peer, peer, keyspace, {range}, cfs); sp.request_ranges(peer, peer, keyspace, {range}, cfs); sp.execute().discard_result().handle_exception([id] (auto ep) { logger.error("repair session #{} stream failed: {}", id, ep); }); } } static std::vector<query::range<dht::token>> get_ranges_for_endpoint( database& db, sstring keyspace, gms::inet_address ep) { auto& rs = db.find_keyspace(keyspace).get_replication_strategy(); return rs.get_ranges(ep); } static std::vector<query::range<dht::token>> get_local_ranges( database& db, sstring keyspace) { return get_ranges_for_endpoint(db, keyspace, utils::fb_utilities::get_broadcast_address()); } static void do_repair_start(seastar::sharded<database>& db, sstring keyspace, std::unordered_map<sstring, sstring> options) { logger.info("starting user-requested repair for keyspace {}", keyspace); // If the "ranges" option is not explicitly specified, we repair all the // local ranges (the token ranges for which this node holds a replica of). // Each of these ranges may have a different set of replicas, so the // repair of each range is performed separately with repair_range(). std::vector<query::range<dht::token>> ranges; // FIXME: if the "ranges" options exists, use that instead of // get_local_ranges() below. Also, translate the following Origin code: #if 0 if (option.isPrimaryRange()) { // when repairing only primary range, neither dataCenters nor hosts can be set if (option.getDataCenters().isEmpty() && option.getHosts().isEmpty()) option.getRanges().addAll(getPrimaryRanges(keyspace)); // except dataCenters only contain local DC (i.e. -local) else if (option.getDataCenters().size() == 1 && option.getDataCenters().contains(DatabaseDescriptor.getLocalDataCenter())) option.getRanges().addAll(getPrimaryRangesWithinDC(keyspace)); else throw new IllegalArgumentException("You need to run primary range repair on all nodes in the cluster."); } else #endif ranges = get_local_ranges(db.local(), keyspace); // FIXME: let the cfs be overriden by an option std::vector<sstring> cfs = list_column_families(db.local(), keyspace); for (auto range : ranges) { repair_range(db, keyspace, range, cfs); } } int repair_start(seastar::sharded<database>& db, sstring keyspace, std::unordered_map<sstring, sstring> options) { int i = next_repair_command++; db.invoke_on(0, [&db, keyspace = std::move(keyspace), options = std::move(options)] (database& localdb) { do_repair_start(db, std::move(keyspace), std::move(options)); }); // Note we ignore the value of this future return i; } <|endoftext|>
<commit_before>#include "gtest/gtest.h" #include "code/ylikuutio/string/ylikuutio_string.hpp" // Include standard headers #include <string> // std::string #include <vector> // std::vector TEST(extract_string_from_memory, nothing_must_be_extracted_when_source_string_is_empty_string_and_end_string_is_empty_string) { char text[] = ""; char* text_pointer = text; char end_string[] = ""; std::size_t array_size = 128; char* dest_array = new char[array_size]; const char* orig_dest_array = dest_array; string::extract_string(text, text_pointer, sizeof(text), dest_array, dest_array, array_size, end_string); ASSERT_EQ(dest_array, orig_dest_array); ASSERT_EQ(*dest_array, 0); } TEST(extract_string_from_memory, nothing_must_be_extracted_when_source_string_is_empty_string_and_end_string_is_1_char) { char text[] = ""; char* text_pointer = text; char end_string[] = "a"; std::size_t array_size = 128; char* dest_array = new char[array_size]; const char* orig_dest_array = dest_array; string::extract_string(text, text_pointer, sizeof(text), dest_array, dest_array, array_size, end_string); ASSERT_EQ(dest_array, orig_dest_array); ASSERT_EQ(*dest_array, 0); } TEST(extract_string_from_memory, nothing_must_be_extracted_when_source_string_is_empty_string_and_end_string_is_2_same_chars) { char text[] = ""; char* text_pointer = text; char end_string[] = "aa"; std::size_t array_size = 128; char* dest_array = new char[array_size]; const char* orig_dest_array = dest_array; string::extract_string(text, text_pointer, sizeof(text), dest_array, dest_array, array_size, end_string); ASSERT_EQ(dest_array, orig_dest_array); ASSERT_EQ(*dest_array, 0); } TEST(extract_string_from_memory, nothing_must_be_extracted_when_source_string_is_empty_string_and_end_string_is_2_different_chars) { char text[] = ""; char* text_pointer = text; char end_string[] = "ab"; std::size_t array_size = 128; char* dest_array = new char[array_size]; const char* orig_dest_array = dest_array; string::extract_string(text, text_pointer, sizeof(text), dest_array, dest_array, array_size, end_string); ASSERT_EQ(dest_array, orig_dest_array); ASSERT_EQ(*dest_array, 0); } TEST(extract_string_from_memory, 1_char_must_be_extracted_when_source_string_is_1_char_and_end_string_is_1_char) { char text[] = "a"; char* text_pointer = text; char end_string[] = "a"; std::size_t array_size = 128; char* dest_array = new char[array_size]; const char* orig_dest_array = dest_array; string::extract_string(text, text_pointer, sizeof(text), dest_array, dest_array, array_size, end_string); ASSERT_EQ(dest_array, orig_dest_array); ASSERT_EQ(*dest_array, 0); } TEST(extract_string_from_memory, iloinen_lokki_laulaa_ja_nukkuu) { char text[] = "iloinen lokki laulaa ja nukkuu"; char* text_pointer = text; char end_string[] = "ja"; std::size_t array_size = 128; char* dest_array = new char[array_size]; const char* orig_dest_array = dest_array; string::extract_string(text, text_pointer, sizeof(text), dest_array, dest_array, array_size, end_string); ASSERT_EQ(dest_array, orig_dest_array); ASSERT_EQ(*dest_array++, 'i'); ASSERT_EQ(*dest_array++, 'l'); ASSERT_EQ(*dest_array++, 'o'); ASSERT_EQ(*dest_array++, 'i'); ASSERT_EQ(*dest_array++, 'n'); ASSERT_EQ(*dest_array++, 'e'); ASSERT_EQ(*dest_array++, 'n'); ASSERT_EQ(*dest_array++, ' '); ASSERT_EQ(*dest_array++, 'l'); ASSERT_EQ(*dest_array++, 'o'); ASSERT_EQ(*dest_array++, 'k'); ASSERT_EQ(*dest_array++, 'k'); ASSERT_EQ(*dest_array++, 'i'); ASSERT_EQ(*dest_array++, ' '); ASSERT_EQ(*dest_array++, 'l'); ASSERT_EQ(*dest_array++, 'a'); ASSERT_EQ(*dest_array++, 'u'); ASSERT_EQ(*dest_array++, 'l'); ASSERT_EQ(*dest_array++, 'a'); ASSERT_EQ(*dest_array++, 'a'); ASSERT_EQ(*dest_array++, ' '); ASSERT_EQ(*dest_array++, 0); } <commit_msg>Fix: change a misleading name of a test.<commit_after>#include "gtest/gtest.h" #include "code/ylikuutio/string/ylikuutio_string.hpp" // Include standard headers #include <string> // std::string #include <vector> // std::vector TEST(extract_string_from_memory, nothing_must_be_extracted_when_source_string_is_empty_string_and_end_string_is_empty_string) { char text[] = ""; char* text_pointer = text; char end_string[] = ""; std::size_t array_size = 128; char* dest_array = new char[array_size]; const char* orig_dest_array = dest_array; string::extract_string(text, text_pointer, sizeof(text), dest_array, dest_array, array_size, end_string); ASSERT_EQ(dest_array, orig_dest_array); ASSERT_EQ(*dest_array, 0); } TEST(extract_string_from_memory, nothing_must_be_extracted_when_source_string_is_empty_string_and_end_string_is_1_char) { char text[] = ""; char* text_pointer = text; char end_string[] = "a"; std::size_t array_size = 128; char* dest_array = new char[array_size]; const char* orig_dest_array = dest_array; string::extract_string(text, text_pointer, sizeof(text), dest_array, dest_array, array_size, end_string); ASSERT_EQ(dest_array, orig_dest_array); ASSERT_EQ(*dest_array, 0); } TEST(extract_string_from_memory, nothing_must_be_extracted_when_source_string_is_empty_string_and_end_string_is_2_same_chars) { char text[] = ""; char* text_pointer = text; char end_string[] = "aa"; std::size_t array_size = 128; char* dest_array = new char[array_size]; const char* orig_dest_array = dest_array; string::extract_string(text, text_pointer, sizeof(text), dest_array, dest_array, array_size, end_string); ASSERT_EQ(dest_array, orig_dest_array); ASSERT_EQ(*dest_array, 0); } TEST(extract_string_from_memory, nothing_must_be_extracted_when_source_string_is_empty_string_and_end_string_is_2_different_chars) { char text[] = ""; char* text_pointer = text; char end_string[] = "ab"; std::size_t array_size = 128; char* dest_array = new char[array_size]; const char* orig_dest_array = dest_array; string::extract_string(text, text_pointer, sizeof(text), dest_array, dest_array, array_size, end_string); ASSERT_EQ(dest_array, orig_dest_array); ASSERT_EQ(*dest_array, 0); } TEST(extract_string_from_memory, nothing_must_be_extracted_when_source_string_is_1_char_and_end_string_is_same_char) { char text[] = "a"; char* text_pointer = text; char end_string[] = "a"; std::size_t array_size = 128; char* dest_array = new char[array_size]; const char* orig_dest_array = dest_array; string::extract_string(text, text_pointer, sizeof(text), dest_array, dest_array, array_size, end_string); ASSERT_EQ(dest_array, orig_dest_array); ASSERT_EQ(*dest_array, 0); } TEST(extract_string_from_memory, iloinen_lokki_laulaa_ja_nukkuu) { char text[] = "iloinen lokki laulaa ja nukkuu"; char* text_pointer = text; char end_string[] = "ja"; std::size_t array_size = 128; char* dest_array = new char[array_size]; const char* orig_dest_array = dest_array; string::extract_string(text, text_pointer, sizeof(text), dest_array, dest_array, array_size, end_string); ASSERT_EQ(dest_array, orig_dest_array); ASSERT_EQ(*dest_array++, 'i'); ASSERT_EQ(*dest_array++, 'l'); ASSERT_EQ(*dest_array++, 'o'); ASSERT_EQ(*dest_array++, 'i'); ASSERT_EQ(*dest_array++, 'n'); ASSERT_EQ(*dest_array++, 'e'); ASSERT_EQ(*dest_array++, 'n'); ASSERT_EQ(*dest_array++, ' '); ASSERT_EQ(*dest_array++, 'l'); ASSERT_EQ(*dest_array++, 'o'); ASSERT_EQ(*dest_array++, 'k'); ASSERT_EQ(*dest_array++, 'k'); ASSERT_EQ(*dest_array++, 'i'); ASSERT_EQ(*dest_array++, ' '); ASSERT_EQ(*dest_array++, 'l'); ASSERT_EQ(*dest_array++, 'a'); ASSERT_EQ(*dest_array++, 'u'); ASSERT_EQ(*dest_array++, 'l'); ASSERT_EQ(*dest_array++, 'a'); ASSERT_EQ(*dest_array++, 'a'); ASSERT_EQ(*dest_array++, ' '); ASSERT_EQ(*dest_array++, 0); } <|endoftext|>
<commit_before>#include "rtkinlinefdk_ggo.h" #include "rtkGgoFunctions.h" #include "rtkConfiguration.h" #include "itkThreeDCircularProjectionGeometryXMLFile.h" #include "itkProjectionsReader.h" #include "itkDisplacedDetectorImageFilter.h" #include "itkParkerShortScanImageFilter.h" #include "itkFDKConeBeamReconstructionFilter.h" #if CUDA_FOUND # include "itkCudaFDKConeBeamReconstructionFilter.h" #endif #if OPENCL_FOUND # include "itkOpenCLFDKConeBeamReconstructionFilter.h" #endif #include <itkRegularExpressionSeriesFileNames.h> #include <itkImageFileWriter.h> #include <itkSimpleFastMutexLock.h> #include <itkMultiThreader.h> #include <itksys/SystemTools.hxx> // Pass projection name, projection parameters, last struct ThreadInfoStruct { itk::SimpleFastMutexLock mutex; args_info_rtkinlinefdk *args_info; bool stop; unsigned int nproj; double sid; double sdd; double gantryAngle; double projOffsetX; double projOffsetY; double outOfPlaneAngle; double inPlaneAngle; double sourceOffsetX; double sourceOffsetY; std::string fileName; }; void *AcquisitionCallback(void *arg); void *InlineThreadCallback(void *arg); int main(int argc, char * argv[]) { GGO(rtkinlinefdk, args_info); // Launch threads, one for acquisition, one for reconstruction with inline processing ThreadInfoStruct threadInfo; threadInfo.args_info = &args_info; threadInfo.nproj = 0; itk::MultiThreader::Pointer threader = itk::MultiThreader::New(); threader->SetMultipleMethod(0, AcquisitionCallback, (void*)&threadInfo); threader->SetMultipleMethod(1, InlineThreadCallback, (void*)&threadInfo); threader->SetNumberOfThreads(2); TRY_AND_EXIT_ON_ITK_EXCEPTION( threader->MultipleMethodExecute () ); return EXIT_SUCCESS; } // This thread reads in a geometry file and a sequence of projection file names // and communicates them one by one to the other thread via a ThreadinfoStruct. void *AcquisitionCallback(void *arg) { ThreadInfoStruct *threadInfo = (ThreadInfoStruct *)(((itk::MultiThreader::ThreadInfoStruct *)(arg))->UserData); threadInfo->mutex.Lock(); // Generate file names itk::RegularExpressionSeriesFileNames::Pointer names = itk::RegularExpressionSeriesFileNames::New(); names->SetDirectory(threadInfo->args_info->path_arg); names->SetNumericSort(false); names->SetRegularExpression(threadInfo->args_info->regexp_arg); names->SetSubMatch(0); if(threadInfo->args_info->verbose_flag) std::cout << "Regular expression matches " << names->GetFileNames().size() << " file(s)..." << std::endl; // Geometry if(threadInfo->args_info->verbose_flag) std::cout << "Reading geometry information from " << threadInfo->args_info->geometry_arg << "..." << std::endl; itk::ThreeDCircularProjectionGeometryXMLFileReader::Pointer geometryReader; geometryReader = itk::ThreeDCircularProjectionGeometryXMLFileReader::New(); geometryReader->SetFilename(threadInfo->args_info->geometry_arg); TRY_AND_EXIT_ON_ITK_EXCEPTION( geometryReader->GenerateOutputInformation() ); threadInfo->mutex.Unlock(); // Mock an inline acquisition unsigned int nproj = geometryReader->GetOutputObject()->GetMatrices().size(); itk::ThreeDCircularProjectionGeometry *geometry = geometryReader->GetOutputObject(); for(unsigned int i=0; i<nproj; i++) { threadInfo->mutex.Lock(); threadInfo->sdd = geometry->GetSourceToDetectorDistances()[i]; threadInfo->sid = geometry->GetSourceToIsocenterDistances()[i]; threadInfo->gantryAngle = geometry->GetGantryAngles()[i]; threadInfo->sourceOffsetX = geometry->GetSourceOffsetsX()[i]; threadInfo->sourceOffsetY = geometry->GetSourceOffsetsY()[i]; threadInfo->projOffsetX = geometry->GetProjectionOffsetsX()[i]; threadInfo->projOffsetY = geometry->GetProjectionOffsetsY()[i]; threadInfo->inPlaneAngle = geometry->GetInPlaneAngles()[i]; threadInfo->outOfPlaneAngle = geometry->GetOutOfPlaneAngles()[i]; threadInfo->fileName = names->GetFileNames()[ vnl_math_min( i, (unsigned int)names->GetFileNames().size()-1 ) ]; threadInfo->nproj = i+1; threadInfo->stop = (i==nproj-1); if(threadInfo->args_info->verbose_flag) std::cout << std::endl << "AcquisitionCallback has simulated the acquisition of projection #" << i << std::endl; threadInfo->mutex.Unlock(); itksys::SystemTools::Delay(200); } return NULL; } // This thread receives information of each projection (one-by-one) and process // directly the projections for which it has enough information. This thread // currently assumes that the projections are sequentially sent with increasing // gantry angles. Specific management with a queue must be implemented if the // projections are not exactly sequential. Displaced detector and short // scans have not been implemented yet because these filters currently require // the full geometry of the acquisition. Management with a mock geometry file // would be possible but it is still to be implemented. void *InlineThreadCallback(void *arg) { ThreadInfoStruct *threadInfo = (ThreadInfoStruct *)(((itk::MultiThreader::ThreadInfoStruct *)(arg))->UserData); threadInfo->mutex.Lock(); typedef float OutputPixelType; const unsigned int Dimension = 3; typedef itk::Image< OutputPixelType, Dimension > OutputImageType; itk::ThreeDCircularProjectionGeometry::Pointer geometry = itk::ThreeDCircularProjectionGeometry::New(); std::vector< std::string > fileNames; // Projections reader typedef itk::ProjectionsReader< OutputImageType > ReaderType; ReaderType::Pointer reader = ReaderType::New(); // Create reconstructed image typedef itk::ConstantImageSource< OutputImageType > ConstantImageSourceType; ConstantImageSourceType::Pointer constantImageSource = ConstantImageSourceType::New(); rtk::SetConstantImageSourceFromGgo<ConstantImageSourceType, args_info_rtkinlinefdk>(constantImageSource, *(threadInfo->args_info)); // Extract filter to process one projection at a time typedef itk::ExtractImageFilter<OutputImageType, OutputImageType> ExtractFilterType; ExtractFilterType::Pointer extract = ExtractFilterType::New(); extract->SetInput( reader->GetOutput() ); ExtractFilterType::InputImageRegionType subsetRegion; // Displaced detector weighting // typedef itk::DisplacedDetectorImageFilter< OutputImageType > DDFType; // DDFType::Pointer ddf = DDFType::New(); // ddf->SetInput( extract->GetOutput() ); // ddf->SetGeometry( geometry ); // Short scan image filter // typedef itk::ParkerShortScanImageFilter< OutputImageType > PSSFType; // PSSFType::Pointer pssf = PSSFType::New(); // pssf->SetInput( ddf->GetOutput() ); // pssf->SetGeometry( geometryReader->GetOutputObject() ); // pssf->InPlaceOff(); // This macro sets options for fdk filter which I can not see how to do better // because TFFTPrecision is not the same, e.g. for CPU and CUDA (SR) #define SET_FELDKAMP_OPTIONS(f) \ f->SetInput( 0, constantImageSource->GetOutput() ); \ f->SetInput( 1, extract->GetOutput() ); \ f->SetGeometry( geometry ); \ f->GetRampFilter()->SetTruncationCorrection(threadInfo->args_info->pad_arg); \ f->GetRampFilter()->SetHannCutFrequency(threadInfo->args_info->hann_arg); // FDK reconstruction filtering itk::ImageToImageFilter<OutputImageType, OutputImageType>::Pointer feldkamp; typedef itk::FDKConeBeamReconstructionFilter< OutputImageType > FDKCPUType; #if CUDA_FOUND typedef itk::CudaFDKConeBeamReconstructionFilter FDKCUDAType; #endif #if OPENCL_FOUND typedef itk::OpenCLFDKConeBeamReconstructionFilter FDKOPENCLType; #endif if(!strcmp(threadInfo->args_info->hardware_arg, "cpu") ) { feldkamp = FDKCPUType::New(); SET_FELDKAMP_OPTIONS( static_cast<FDKCPUType*>(feldkamp.GetPointer()) ); } else if(!strcmp(threadInfo->args_info->hardware_arg, "cuda") ) { #if CUDA_FOUND feldkamp = FDKCUDAType::New(); SET_FELDKAMP_OPTIONS( static_cast<FDKCUDAType*>(feldkamp.GetPointer()) ); #else std::cerr << "The program has not been compiled with cuda option" << std::endl; exit(EXIT_FAILURE); #endif } else if(!strcmp(threadInfo->args_info->hardware_arg, "opencl") ) { #if OPENCL_FOUND feldkamp = FDKOPENCLType::New(); SET_FELDKAMP_OPTIONS( static_cast<FDKOPENCLType*>(feldkamp.GetPointer()) ); #else std::cerr << "The program has not been compiled with opencl option" << std::endl; exit(EXIT_FAILURE); #endif } // Writer typedef itk::ImageFileWriter< OutputImageType > WriterType; WriterType::Pointer writer = WriterType::New(); writer->SetFileName( threadInfo->args_info->output_arg ); threadInfo->mutex.Unlock(); // Inline loop for(;;) { threadInfo->mutex.Lock(); if(geometry->GetMatrices().size()<threadInfo->nproj) { if(threadInfo->args_info->verbose_flag) std::cerr << "InlineThreadCallback has received projection #" << threadInfo->nproj-1 << std::endl; if(threadInfo->fileName != "" && (fileNames.size()==0 || fileNames.back() != threadInfo->fileName)) fileNames.push_back(threadInfo->fileName); geometry->AddProjection(threadInfo->sid, threadInfo->sdd, threadInfo->gantryAngle, threadInfo->projOffsetX, threadInfo->projOffsetY, threadInfo->outOfPlaneAngle, threadInfo->inPlaneAngle, threadInfo->sourceOffsetX, threadInfo->sourceOffsetY); if(geometry->GetMatrices().size()!=threadInfo->nproj) { std::cerr << "Missed one projection in InlineThreadCallback" << std::endl; exit(EXIT_FAILURE); } if(geometry->GetMatrices().size()<3) { threadInfo->mutex.Unlock(); continue; } reader->SetFileNames( fileNames ); reader->UpdateOutputInformation(); subsetRegion = reader->GetOutput()->GetLargestPossibleRegion(); subsetRegion.SetIndex(Dimension-1, geometry->GetMatrices().size()-2); subsetRegion.SetSize(Dimension-1, 1); extract->SetExtractionRegion(subsetRegion); TRY_AND_EXIT_ON_ITK_EXCEPTION( feldkamp->Update() ); if(threadInfo->args_info->verbose_flag) std::cout << "Projection #" << subsetRegion.GetIndex(Dimension-1) << " has been processed in reconstruction." << std::endl; OutputImageType::Pointer pimg = feldkamp->GetOutput(); pimg->DisconnectPipeline(); feldkamp->SetInput( pimg ); TRY_AND_EXIT_ON_ITK_EXCEPTION( feldkamp->GetOutput()->UpdateOutputInformation() ); TRY_AND_EXIT_ON_ITK_EXCEPTION( feldkamp->GetOutput()->PropagateRequestedRegion() ); if(threadInfo->stop) { // Process first projection subsetRegion.SetIndex(Dimension-1, 0); extract->SetExtractionRegion(subsetRegion); TRY_AND_EXIT_ON_ITK_EXCEPTION( feldkamp->Update() ); if(threadInfo->args_info->verbose_flag) std::cout << "Projection #" << subsetRegion.GetIndex(Dimension-1) << " has been processed in reconstruction." << std::endl; pimg = feldkamp->GetOutput(); pimg->DisconnectPipeline(); feldkamp->SetInput( pimg ); TRY_AND_EXIT_ON_ITK_EXCEPTION( feldkamp->GetOutput()->UpdateOutputInformation() ); TRY_AND_EXIT_ON_ITK_EXCEPTION( feldkamp->GetOutput()->PropagateRequestedRegion() ); // Process last projection subsetRegion.SetIndex(Dimension-1, geometry->GetMatrices().size()-1); extract->SetExtractionRegion(subsetRegion); TRY_AND_EXIT_ON_ITK_EXCEPTION( feldkamp->Update() ); if(threadInfo->args_info->verbose_flag) std::cout << "Projection #" << subsetRegion.GetIndex(Dimension-1) << " has been processed in reconstruction." << std::endl; //Write to disk and exit writer->SetInput( feldkamp->GetOutput() ); TRY_AND_EXIT_ON_ITK_EXCEPTION( writer->Update() ); exit(EXIT_SUCCESS); } } threadInfo->mutex.Unlock(); } return NULL; } <commit_msg>Fixed error in multithreading for Windows<commit_after>#include "rtkinlinefdk_ggo.h" #include "rtkGgoFunctions.h" #include "rtkConfiguration.h" #include "itkThreeDCircularProjectionGeometryXMLFile.h" #include "itkProjectionsReader.h" #include "itkDisplacedDetectorImageFilter.h" #include "itkParkerShortScanImageFilter.h" #include "itkFDKConeBeamReconstructionFilter.h" #if CUDA_FOUND # include "itkCudaFDKConeBeamReconstructionFilter.h" #endif #if OPENCL_FOUND # include "itkOpenCLFDKConeBeamReconstructionFilter.h" #endif #include <itkRegularExpressionSeriesFileNames.h> #include <itkImageFileWriter.h> #include <itkSimpleFastMutexLock.h> #include <itkMultiThreader.h> #include <itksys/SystemTools.hxx> // Pass projection name, projection parameters, last struct ThreadInfoStruct { itk::SimpleFastMutexLock mutex; args_info_rtkinlinefdk *args_info; bool stop; unsigned int nproj; double sid; double sdd; double gantryAngle; double projOffsetX; double projOffsetY; double outOfPlaneAngle; double inPlaneAngle; double sourceOffsetX; double sourceOffsetY; std::string fileName; }; static ITK_THREAD_RETURN_TYPE AcquisitionCallback(void *arg); static ITK_THREAD_RETURN_TYPE InlineThreadCallback(void *arg); int main(int argc, char * argv[]) { GGO(rtkinlinefdk, args_info); // Launch threads, one for acquisition, one for reconstruction with inline processing ThreadInfoStruct threadInfo; threadInfo.args_info = &args_info; threadInfo.nproj = 0; itk::MultiThreader::Pointer threader = itk::MultiThreader::New(); threader->SetMultipleMethod(0, AcquisitionCallback, (void*)&threadInfo); threader->SetMultipleMethod(1, InlineThreadCallback, (void*)&threadInfo); threader->SetNumberOfThreads(2); TRY_AND_EXIT_ON_ITK_EXCEPTION( threader->MultipleMethodExecute () ); return EXIT_SUCCESS; } // This thread reads in a geometry file and a sequence of projection file names // and communicates them one by one to the other thread via a ThreadinfoStruct. void *AcquisitionCallback(void *arg) { ThreadInfoStruct *threadInfo = (ThreadInfoStruct *)(((itk::MultiThreader::ThreadInfoStruct *)(arg))->UserData); threadInfo->mutex.Lock(); // Generate file names itk::RegularExpressionSeriesFileNames::Pointer names = itk::RegularExpressionSeriesFileNames::New(); names->SetDirectory(threadInfo->args_info->path_arg); names->SetNumericSort(false); names->SetRegularExpression(threadInfo->args_info->regexp_arg); names->SetSubMatch(0); if(threadInfo->args_info->verbose_flag) std::cout << "Regular expression matches " << names->GetFileNames().size() << " file(s)..." << std::endl; // Geometry if(threadInfo->args_info->verbose_flag) std::cout << "Reading geometry information from " << threadInfo->args_info->geometry_arg << "..." << std::endl; itk::ThreeDCircularProjectionGeometryXMLFileReader::Pointer geometryReader; geometryReader = itk::ThreeDCircularProjectionGeometryXMLFileReader::New(); geometryReader->SetFilename(threadInfo->args_info->geometry_arg); TRY_AND_EXIT_ON_ITK_EXCEPTION( geometryReader->GenerateOutputInformation() ); threadInfo->mutex.Unlock(); // Mock an inline acquisition unsigned int nproj = geometryReader->GetOutputObject()->GetMatrices().size(); itk::ThreeDCircularProjectionGeometry *geometry = geometryReader->GetOutputObject(); for(unsigned int i=0; i<nproj; i++) { threadInfo->mutex.Lock(); threadInfo->sdd = geometry->GetSourceToDetectorDistances()[i]; threadInfo->sid = geometry->GetSourceToIsocenterDistances()[i]; threadInfo->gantryAngle = geometry->GetGantryAngles()[i]; threadInfo->sourceOffsetX = geometry->GetSourceOffsetsX()[i]; threadInfo->sourceOffsetY = geometry->GetSourceOffsetsY()[i]; threadInfo->projOffsetX = geometry->GetProjectionOffsetsX()[i]; threadInfo->projOffsetY = geometry->GetProjectionOffsetsY()[i]; threadInfo->inPlaneAngle = geometry->GetInPlaneAngles()[i]; threadInfo->outOfPlaneAngle = geometry->GetOutOfPlaneAngles()[i]; threadInfo->fileName = names->GetFileNames()[ vnl_math_min( i, (unsigned int)names->GetFileNames().size()-1 ) ]; threadInfo->nproj = i+1; threadInfo->stop = (i==nproj-1); if(threadInfo->args_info->verbose_flag) std::cout << std::endl << "AcquisitionCallback has simulated the acquisition of projection #" << i << std::endl; threadInfo->mutex.Unlock(); itksys::SystemTools::Delay(200); } return NULL; } // This thread receives information of each projection (one-by-one) and process // directly the projections for which it has enough information. This thread // currently assumes that the projections are sequentially sent with increasing // gantry angles. Specific management with a queue must be implemented if the // projections are not exactly sequential. Displaced detector and short // scans have not been implemented yet because these filters currently require // the full geometry of the acquisition. Management with a mock geometry file // would be possible but it is still to be implemented. void *InlineThreadCallback(void *arg) { ThreadInfoStruct *threadInfo = (ThreadInfoStruct *)(((itk::MultiThreader::ThreadInfoStruct *)(arg))->UserData); threadInfo->mutex.Lock(); typedef float OutputPixelType; const unsigned int Dimension = 3; typedef itk::Image< OutputPixelType, Dimension > OutputImageType; itk::ThreeDCircularProjectionGeometry::Pointer geometry = itk::ThreeDCircularProjectionGeometry::New(); std::vector< std::string > fileNames; // Projections reader typedef itk::ProjectionsReader< OutputImageType > ReaderType; ReaderType::Pointer reader = ReaderType::New(); // Create reconstructed image typedef itk::ConstantImageSource< OutputImageType > ConstantImageSourceType; ConstantImageSourceType::Pointer constantImageSource = ConstantImageSourceType::New(); rtk::SetConstantImageSourceFromGgo<ConstantImageSourceType, args_info_rtkinlinefdk>(constantImageSource, *(threadInfo->args_info)); // Extract filter to process one projection at a time typedef itk::ExtractImageFilter<OutputImageType, OutputImageType> ExtractFilterType; ExtractFilterType::Pointer extract = ExtractFilterType::New(); extract->SetInput( reader->GetOutput() ); ExtractFilterType::InputImageRegionType subsetRegion; // Displaced detector weighting // typedef itk::DisplacedDetectorImageFilter< OutputImageType > DDFType; // DDFType::Pointer ddf = DDFType::New(); // ddf->SetInput( extract->GetOutput() ); // ddf->SetGeometry( geometry ); // Short scan image filter // typedef itk::ParkerShortScanImageFilter< OutputImageType > PSSFType; // PSSFType::Pointer pssf = PSSFType::New(); // pssf->SetInput( ddf->GetOutput() ); // pssf->SetGeometry( geometryReader->GetOutputObject() ); // pssf->InPlaceOff(); // This macro sets options for fdk filter which I can not see how to do better // because TFFTPrecision is not the same, e.g. for CPU and CUDA (SR) #define SET_FELDKAMP_OPTIONS(f) \ f->SetInput( 0, constantImageSource->GetOutput() ); \ f->SetInput( 1, extract->GetOutput() ); \ f->SetGeometry( geometry ); \ f->GetRampFilter()->SetTruncationCorrection(threadInfo->args_info->pad_arg); \ f->GetRampFilter()->SetHannCutFrequency(threadInfo->args_info->hann_arg); // FDK reconstruction filtering itk::ImageToImageFilter<OutputImageType, OutputImageType>::Pointer feldkamp; typedef itk::FDKConeBeamReconstructionFilter< OutputImageType > FDKCPUType; #if CUDA_FOUND typedef itk::CudaFDKConeBeamReconstructionFilter FDKCUDAType; #endif #if OPENCL_FOUND typedef itk::OpenCLFDKConeBeamReconstructionFilter FDKOPENCLType; #endif if(!strcmp(threadInfo->args_info->hardware_arg, "cpu") ) { feldkamp = FDKCPUType::New(); SET_FELDKAMP_OPTIONS( static_cast<FDKCPUType*>(feldkamp.GetPointer()) ); } else if(!strcmp(threadInfo->args_info->hardware_arg, "cuda") ) { #if CUDA_FOUND feldkamp = FDKCUDAType::New(); SET_FELDKAMP_OPTIONS( static_cast<FDKCUDAType*>(feldkamp.GetPointer()) ); #else std::cerr << "The program has not been compiled with cuda option" << std::endl; exit(EXIT_FAILURE); #endif } else if(!strcmp(threadInfo->args_info->hardware_arg, "opencl") ) { #if OPENCL_FOUND feldkamp = FDKOPENCLType::New(); SET_FELDKAMP_OPTIONS( static_cast<FDKOPENCLType*>(feldkamp.GetPointer()) ); #else std::cerr << "The program has not been compiled with opencl option" << std::endl; exit(EXIT_FAILURE); #endif } // Writer typedef itk::ImageFileWriter< OutputImageType > WriterType; WriterType::Pointer writer = WriterType::New(); writer->SetFileName( threadInfo->args_info->output_arg ); threadInfo->mutex.Unlock(); // Inline loop for(;;) { threadInfo->mutex.Lock(); if(geometry->GetMatrices().size()<threadInfo->nproj) { if(threadInfo->args_info->verbose_flag) std::cerr << "InlineThreadCallback has received projection #" << threadInfo->nproj-1 << std::endl; if(threadInfo->fileName != "" && (fileNames.size()==0 || fileNames.back() != threadInfo->fileName)) fileNames.push_back(threadInfo->fileName); geometry->AddProjection(threadInfo->sid, threadInfo->sdd, threadInfo->gantryAngle, threadInfo->projOffsetX, threadInfo->projOffsetY, threadInfo->outOfPlaneAngle, threadInfo->inPlaneAngle, threadInfo->sourceOffsetX, threadInfo->sourceOffsetY); if(geometry->GetMatrices().size()!=threadInfo->nproj) { std::cerr << "Missed one projection in InlineThreadCallback" << std::endl; exit(EXIT_FAILURE); } if(geometry->GetMatrices().size()<3) { threadInfo->mutex.Unlock(); continue; } reader->SetFileNames( fileNames ); reader->UpdateOutputInformation(); subsetRegion = reader->GetOutput()->GetLargestPossibleRegion(); subsetRegion.SetIndex(Dimension-1, geometry->GetMatrices().size()-2); subsetRegion.SetSize(Dimension-1, 1); extract->SetExtractionRegion(subsetRegion); TRY_AND_EXIT_ON_ITK_EXCEPTION( feldkamp->Update() ); if(threadInfo->args_info->verbose_flag) std::cout << "Projection #" << subsetRegion.GetIndex(Dimension-1) << " has been processed in reconstruction." << std::endl; OutputImageType::Pointer pimg = feldkamp->GetOutput(); pimg->DisconnectPipeline(); feldkamp->SetInput( pimg ); TRY_AND_EXIT_ON_ITK_EXCEPTION( feldkamp->GetOutput()->UpdateOutputInformation() ); TRY_AND_EXIT_ON_ITK_EXCEPTION( feldkamp->GetOutput()->PropagateRequestedRegion() ); if(threadInfo->stop) { // Process first projection subsetRegion.SetIndex(Dimension-1, 0); extract->SetExtractionRegion(subsetRegion); TRY_AND_EXIT_ON_ITK_EXCEPTION( feldkamp->Update() ); if(threadInfo->args_info->verbose_flag) std::cout << "Projection #" << subsetRegion.GetIndex(Dimension-1) << " has been processed in reconstruction." << std::endl; pimg = feldkamp->GetOutput(); pimg->DisconnectPipeline(); feldkamp->SetInput( pimg ); TRY_AND_EXIT_ON_ITK_EXCEPTION( feldkamp->GetOutput()->UpdateOutputInformation() ); TRY_AND_EXIT_ON_ITK_EXCEPTION( feldkamp->GetOutput()->PropagateRequestedRegion() ); // Process last projection subsetRegion.SetIndex(Dimension-1, geometry->GetMatrices().size()-1); extract->SetExtractionRegion(subsetRegion); TRY_AND_EXIT_ON_ITK_EXCEPTION( feldkamp->Update() ); if(threadInfo->args_info->verbose_flag) std::cout << "Projection #" << subsetRegion.GetIndex(Dimension-1) << " has been processed in reconstruction." << std::endl; //Write to disk and exit writer->SetInput( feldkamp->GetOutput() ); TRY_AND_EXIT_ON_ITK_EXCEPTION( writer->Update() ); exit(EXIT_SUCCESS); } } threadInfo->mutex.Unlock(); } return NULL; } <|endoftext|>
<commit_before>#include "simplifymesh.h" #include<algorithm> #include<iostream> #define INF 99999999; using namespace std; bool operator>(const ident &a, const ident &b){ return a. value > b. value; } bool operator <(const ident &a,const ident &b){ return a. value < b. value; } void simplify_mesh::Simp_shorstest(const size_t &iter_times){ //find the shortest edge make_priority(); // string Output = "../data/output/cube_tu_",fix = ".obj"; for(size_t i = 0; i < iter_times; i++){ for (size_t j = 0;j < 10; j++){ cout<<"edge id is " << priority[j]. id << " length is " << priority[j]. value <<"\n"; } cout<<"\n"; cout << i << " iteration:\n"; nsize_t edge_id = priority[ 0 ]. id; int edge_oppo_id = mesh_init. HalfEdges[ edge_id ]. oppo_; //check the manifold int result; do{ result = check_manifold(edge_id, edge_oppo_id); cout << "result of check of manifold is "<< result <<"\n"; }while(result == -1); //pop the priority pop_priority(edge_id); //change the topology cout << "the edge to be collapsed is " << edge_id <<"\n"; change_topology(edge_id,edge_oppo_id,result); // //output // stringstream temp; // string temp_; // temp<<i; // temp>>temp_; // Output. append(temp_); // Output. append(fix); // cout << Output <<"\n"; // mesh_init. halfedge_to_obj(Output); cout<<"\n\n"; } } void simplify_mesh::change_topology( const size_t &edge_id, const int &edge_oppo_id, const int &result){ size_t edge_r_id = edge_id;{//delete the edges do{ mesh_init.HalfEdges[edge_r_id].is_exist = false; edge_r_id = mesh_init.HalfEdges[edge_r_id].next_; }while(edge_id != edge_r_id); edge_r_id = edge_oppo_id; do{ mesh_init.HalfEdges[edge_r_id].is_exist = false; edge_r_id = mesh_init.HalfEdges[edge_r_id].next_; }while(edge_oppo_id != edge_r_id); cout <<"the edges have been deleted.\n"; } size_t vertex_r_id = mesh_init.HalfEdges [ edge_oppo_id ].vertex_;{ //delete the vertex mesh_init.Vertexs [ vertex_r_id-1 ].is_exist = false; cout<<"the vertex " << vertex_r_id <<" has been deleted.\n"; } size_t face_r_id = mesh_init.HalfEdges[ edge_id ].face_;{ //delete the face mesh_init. Faces[ face_r_id ]. is_exist = false; if( edge_oppo_id != -1) { face_r_id = mesh_init. HalfEdges[ edge_oppo_id ]. face_; mesh_init. Faces[ face_r_id ]. is_exist = false; } cout<<"the face has been deleted.\n"; } { //change the vertex const size_t vertex_ur_id = mesh_init.HalfEdges[ edge_id]. vertex_; size_t edge_change_id_1, edge_change_id_2, edge_end_id; if (result == -2){ edge_change_id_1 = edge_oppo_id; edge_end_id = mesh_init. HalfEdges [edge_id]. prev_; } else { edge_change_id_1 = result; edge_end_id = -1; } do{ mesh_init. HalfEdges[ edge_change_id_1]. vertex_ = vertex_ur_id; edge_change_id_2 = mesh_init. HalfEdges [edge_change_id_1]. next_; double length;{ //change the length size_t vertex_pre_id = mesh_init. HalfEdges [edge_change_id_2]. vertex_; length = sqrt( pow((mesh_init.Vertexs[vertex_ur_id-1].x-mesh_init.Vertexs[vertex_pre_id-1].x),2)+ pow((mesh_init.Vertexs[vertex_ur_id-1].y-mesh_init.Vertexs[vertex_pre_id-1].y),2)+ pow((mesh_init.Vertexs[vertex_ur_id-1].z-mesh_init.Vertexs[vertex_pre_id-1].z),2)); mesh_init. HalfEdges [edge_change_id_1]. length = length; priority [edge_change_id_1]. value = length; mesh_init. HalfEdges [edge_change_id_2]. length = length; priority [edge_change_id_2]. value = length; } edge_change_id_1 = mesh_init. HalfEdges [edge_change_id_2]. oppo_; }while ( edge_change_id_1 != edge_end_id); } { //change the opposite edge size_t edge_oppo_ur = mesh_init. HalfEdges [edge_id]. next_; edge_oppo_ur = mesh_init. HalfEdges [edge_oppo_ur]. oppo_; size_t edge_change_id = mesh_init. HalfEdges [edge_id]. prev_; edge_change_id = mesh_init. HalfEdges [edge_change_id]. oppo_; mesh_init. HalfEdges [edge_change_id]. oppo_ = edge_oppo_ur; mesh_init. HalfEdges [edge_oppo_ur]. oppo_ = edge_change_id; edge_oppo_ur = mesh_init. HalfEdges [edge_oppo_id]. prev_; edge_oppo_ur = mesh_init. HalfEdges [edge_oppo_ur]. oppo_; edge_change_id = mesh_init. HalfEdges [edge_oppo_id]. next_; edge_change_id = mesh_init. HalfEdges [edge_change_id]. oppo_; mesh_init. HalfEdges [edge_change_id]. oppo_ = edge_oppo_ur; mesh_init. HalfEdges [edge_oppo_ur]. oppo_ = edge_change_id; } cout << "the vertex have been changed.\n"; } void simplify_mesh::make_priority(){ size_t num = mesh_init.HalfEdges.size(); priority = vector<ident>(num); for (size_t i = 0; i < num; i++){ priority[i].id = i; priority[i].value = mesh_init.HalfEdges[i].length; } make_heap(priority.begin(),priority.end(),greater<ident>()); } void simplify_mesh::pop_priority(const size_t &edge_id){ if (mesh_init. HalfEdges[edge_id]. oppo_ !=-1){ pop_heap (priority.begin(), priority.end(),greater<ident>()); priority.pop_back(); pop_heap (priority.begin(), priority.end(),greater<ident>()); priority.pop_back(); } else{ pop_heap (priority.begin(), priority.end(),greater<ident>()); priority.pop_back(); } } int simplify_mesh::check_manifold(size_t &edge_id, int &edge_oppo_id){ int edge_bound_id=-2; bool is_cllap = true; if(!mesh_init. HalfEdges [edge_id].is_exist) { is_cllap = false; goto pop; } // if (edge_id == 1406){ // size_t id = edge_id; // do{ // cout << "the edge is " << id <<" is exist "<< mesh_init. HalfEdges[id].is_exist<< " the vertex is "<< mesh_init. HalfEdges [id]. vertex_ << "\n"; // id = mesh_init. HalfEdges [id].next_; // cout << "the edge is " << id <<"\n "; // id = mesh_init. HalfEdges [id].oppo_; // }while(id != edge_id); // } if ( edge_oppo_id != -1 ){ bool is_bound_p = false;{ //check if p is on the boundry int edge_r = edge_id; do{ edge_r = mesh_init. HalfEdges [edge_r]. next_; edge_r = mesh_init. HalfEdges [edge_r]. oppo_; if (edge_r == -1) { is_bound_p = true; break; } }while(edge_r != edge_id); } if(! is_bound_p) cout<<"p is not on the bound\n"; bool is_bound_q = false;{ // check if q is on the boundry int edge_r_1 = edge_id,edge_r_2; do{ edge_r_2 = mesh_init. HalfEdges [edge_r_1]. prev_; edge_r_1 = mesh_init. HalfEdges [edge_r_2]. oppo_; if (edge_r_1 == -1) { edge_bound_id = edge_r_2; is_bound_q = true; break; } }while(edge_r_1 != edge_id); } if (!is_bound_q) cout << "q is not on the bound\n"; if (is_bound_q && is_bound_p){ is_cllap == false; cout << "the p and q is on the bound.\n"; goto pop; }} { // check if this edge is in three triangles int edge_r = mesh_init. HalfEdges [edge_id]. next_; edge_r = mesh_init. HalfEdges [edge_r]. oppo_; edge_r = mesh_init. HalfEdges [edge_r]. prev_; edge_r = mesh_init. HalfEdges [edge_r]. oppo_; edge_r = mesh_init. HalfEdges [edge_r]. prev_; edge_r = mesh_init. HalfEdges [edge_r]. oppo_; edge_r = mesh_init. HalfEdges [edge_r]. next_; if (edge_r == edge_id) { is_cllap = false; goto pop; } if (edge_oppo_id != -1){ edge_r = mesh_init. HalfEdges [edge_oppo_id]. next_; edge_r = mesh_init. HalfEdges [edge_r]. oppo_; edge_r = mesh_init. HalfEdges [edge_r]. prev_; edge_r = mesh_init. HalfEdges [edge_r]. oppo_; edge_r = mesh_init. HalfEdges [edge_r]. prev_; edge_r = mesh_init. HalfEdges [edge_r]. oppo_; edge_r = mesh_init. HalfEdges [edge_r]. next_; if (edge_r == edge_id) { is_cllap = false; cout << "the edge has three triangles.\n"; goto pop; } } } if (is_cllap) cout<< "the edge is collapsable\n"; pop: if (is_cllap == false) { pop_priority(edge_id); edge_bound_id = -1; edge_id = priority[0]. id; edge_oppo_id = mesh_init. HalfEdges [edge_id]. oppo_; } return edge_bound_id; } void simplify_mesh::modify_priority (const ident &new_ident){//You must modify priority before modify the Halfedges vector double length_old = mesh_init. HalfEdges[new_ident.id]. length; for () } <commit_msg>add cmath and modify the ==<commit_after>#include<cmath> #include "simplifymesh.h" #include<algorithm> #include<iostream> #define INF 99999999; using namespace std; bool operator>(const ident &a, const ident &b){ return a. value > b. value; } bool operator <(const ident &a,const ident &b){ return a. value < b. value; } void simplify_mesh::Simp_shorstest(const size_t &iter_times){ //find the shortest edge make_priority(); // string Output = "../data/output/cube_tu_",fix = ".obj"; for(size_t i = 0; i < iter_times; i++){ for (size_t j = 0;j < 10; j++){ cout<<"edge id is " << priority[j]. id << " length is " << priority[j]. value <<"\n"; } cout<<"\n"; cout << i << " iteration:\n"; size_t edge_id = priority[ 0 ]. id; int edge_oppo_id = mesh_init. HalfEdges[ edge_id ]. oppo_; //check the manifold int result; do{ result = check_manifold(edge_id, edge_oppo_id); cout << "result of check of manifold is "<< result <<"\n"; }while(result == -1); //pop the priority pop_priority(edge_id); //change the topology cout << "the edge to be collapsed is " << edge_id <<"\n"; change_topology(edge_id,edge_oppo_id,result); // //output // stringstream temp; // string temp_; // temp<<i; // temp>>temp_; // Output. append(temp_); // Output. append(fix); // cout << Output <<"\n"; // mesh_init. halfedge_to_obj(Output); cout<<"\n\n"; } } void simplify_mesh::change_topology( const size_t &edge_id, const int &edge_oppo_id, const int &result){ size_t edge_r_id = edge_id;{//delete the edges do{ mesh_init.HalfEdges[edge_r_id].is_exist = false; edge_r_id = mesh_init.HalfEdges[edge_r_id].next_; }while(edge_id != edge_r_id); edge_r_id = edge_oppo_id; do{ mesh_init.HalfEdges[edge_r_id].is_exist = false; edge_r_id = mesh_init.HalfEdges[edge_r_id].next_; }while(edge_oppo_id != edge_r_id); cout <<"the edges have been deleted.\n"; } size_t vertex_r_id = mesh_init.HalfEdges [ edge_oppo_id ].vertex_;{ //delete the vertex mesh_init.Vertexs [ vertex_r_id-1 ].is_exist = false; cout<<"the vertex " << vertex_r_id <<" has been deleted.\n"; } size_t face_r_id = mesh_init.HalfEdges[ edge_id ].face_;{ //delete the face mesh_init. Faces[ face_r_id ]. is_exist = false; if( edge_oppo_id != -1) { face_r_id = mesh_init. HalfEdges[ edge_oppo_id ]. face_; mesh_init. Faces[ face_r_id ]. is_exist = false; } cout<<"the face has been deleted.\n"; } { //change the vertex const size_t vertex_ur_id = mesh_init.HalfEdges[ edge_id]. vertex_; size_t edge_change_id_1, edge_change_id_2, edge_end_id; if (result == -2){ edge_change_id_1 = edge_oppo_id; edge_end_id = mesh_init. HalfEdges [edge_id]. prev_; } else { edge_change_id_1 = result; edge_end_id = -1; } do{ mesh_init. HalfEdges[ edge_change_id_1]. vertex_ = vertex_ur_id; edge_change_id_2 = mesh_init. HalfEdges [edge_change_id_1]. next_; double length;{ //change the length size_t vertex_pre_id = mesh_init. HalfEdges [edge_change_id_2]. vertex_; length = sqrt( pow((mesh_init.Vertexs[vertex_ur_id-1].x-mesh_init.Vertexs[vertex_pre_id-1].x),2)+ pow((mesh_init.Vertexs[vertex_ur_id-1].y-mesh_init.Vertexs[vertex_pre_id-1].y),2)+ pow((mesh_init.Vertexs[vertex_ur_id-1].z-mesh_init.Vertexs[vertex_pre_id-1].z),2)); mesh_init. HalfEdges [edge_change_id_1]. length = length; priority [edge_change_id_1]. value = length; mesh_init. HalfEdges [edge_change_id_2]. length = length; priority [edge_change_id_2]. value = length; } edge_change_id_1 = mesh_init. HalfEdges [edge_change_id_2]. oppo_; }while ( edge_change_id_1 != edge_end_id); } { //change the opposite edge size_t edge_oppo_ur = mesh_init. HalfEdges [edge_id]. next_; edge_oppo_ur = mesh_init. HalfEdges [edge_oppo_ur]. oppo_; size_t edge_change_id = mesh_init. HalfEdges [edge_id]. prev_; edge_change_id = mesh_init. HalfEdges [edge_change_id]. oppo_; mesh_init. HalfEdges [edge_change_id]. oppo_ = edge_oppo_ur; mesh_init. HalfEdges [edge_oppo_ur]. oppo_ = edge_change_id; edge_oppo_ur = mesh_init. HalfEdges [edge_oppo_id]. prev_; edge_oppo_ur = mesh_init. HalfEdges [edge_oppo_ur]. oppo_; edge_change_id = mesh_init. HalfEdges [edge_oppo_id]. next_; edge_change_id = mesh_init. HalfEdges [edge_change_id]. oppo_; mesh_init. HalfEdges [edge_change_id]. oppo_ = edge_oppo_ur; mesh_init. HalfEdges [edge_oppo_ur]. oppo_ = edge_change_id; } cout << "the vertex have been changed.\n"; } void simplify_mesh::make_priority(){ size_t num = mesh_init.HalfEdges.size(); priority = vector<ident>(num); for (size_t i = 0; i < num; i++){ priority[i].id = i; priority[i].value = mesh_init.HalfEdges[i].length; } make_heap(priority.begin(),priority.end(),greater<ident>()); } void simplify_mesh::pop_priority(const size_t &edge_id){ if (mesh_init. HalfEdges[edge_id]. oppo_ !=-1){ pop_heap (priority.begin(), priority.end(),greater<ident>()); priority.pop_back(); pop_heap (priority.begin(), priority.end(),greater<ident>()); priority.pop_back(); } else{ pop_heap (priority.begin(), priority.end(),greater<ident>()); priority.pop_back(); } } int simplify_mesh::check_manifold(size_t &edge_id, int &edge_oppo_id){ int edge_bound_id=-2; bool is_cllap = true; if(!mesh_init. HalfEdges [edge_id].is_exist) { is_cllap = false; goto pop; } // if (edge_id == 1406){ // size_t id = edge_id; // do{ // cout << "the edge is " << id <<" is exist "<< mesh_init. HalfEdges[id].is_exist<< " the vertex is "<< mesh_init. HalfEdges [id]. vertex_ << "\n"; // id = mesh_init. HalfEdges [id].next_; // cout << "the edge is " << id <<"\n "; // id = mesh_init. HalfEdges [id].oppo_; // }while(id != edge_id); // } if ( edge_oppo_id != -1 ){ bool is_bound_p = false;{ //check if p is on the boundry int edge_r = edge_id; do{ edge_r = mesh_init. HalfEdges [edge_r]. next_; edge_r = mesh_init. HalfEdges [edge_r]. oppo_; if (edge_r == -1) { is_bound_p = true; break; } }while(edge_r != edge_id); } if(! is_bound_p) cout<<"p is not on the bound\n"; bool is_bound_q = false;{ // check if q is on the boundry int edge_r_1 = edge_id,edge_r_2; do{ edge_r_2 = mesh_init. HalfEdges [edge_r_1]. prev_; edge_r_1 = mesh_init. HalfEdges [edge_r_2]. oppo_; if (edge_r_1 == -1) { edge_bound_id = edge_r_2; is_bound_q = true; break; } }while(edge_r_1 != edge_id); } if (!is_bound_q) cout << "q is not on the bound\n"; if (is_bound_q && is_bound_p){ is_cllap = false; cout << "the p and q is on the bound.\n"; goto pop; }} { // check if this edge is in three triangles int edge_r = mesh_init. HalfEdges [edge_id]. next_; edge_r = mesh_init. HalfEdges [edge_r]. oppo_; edge_r = mesh_init. HalfEdges [edge_r]. prev_; edge_r = mesh_init. HalfEdges [edge_r]. oppo_; edge_r = mesh_init. HalfEdges [edge_r]. prev_; edge_r = mesh_init. HalfEdges [edge_r]. oppo_; edge_r = mesh_init. HalfEdges [edge_r]. next_; if (edge_r == edge_id) { is_cllap = false; goto pop; } if (edge_oppo_id != -1){ edge_r = mesh_init. HalfEdges [edge_oppo_id]. next_; edge_r = mesh_init. HalfEdges [edge_r]. oppo_; edge_r = mesh_init. HalfEdges [edge_r]. prev_; edge_r = mesh_init. HalfEdges [edge_r]. oppo_; edge_r = mesh_init. HalfEdges [edge_r]. prev_; edge_r = mesh_init. HalfEdges [edge_r]. oppo_; edge_r = mesh_init. HalfEdges [edge_r]. next_; if (edge_r == edge_id) { is_cllap = false; cout << "the edge has three triangles.\n"; goto pop; } } } if (is_cllap) cout<< "the edge is collapsable\n"; pop: if (is_cllap == false) { pop_priority(edge_id); edge_bound_id = -1; edge_id = priority[0]. id; edge_oppo_id = mesh_init. HalfEdges [edge_id]. oppo_; } return edge_bound_id; } void simplify_mesh::modify_priority (const ident &new_ident){//You must modify priority before modify the Halfedges vector double length_old = mesh_init. HalfEdges[new_ident.id]. length; //x for () } <|endoftext|>
<commit_before>// Filename: collisionHandlerFluidPusher.cxx // Created by: drose (16Mar02) // //////////////////////////////////////////////////////////////////// // // PANDA 3D SOFTWARE // Copyright (c) 2001 - 2004, Disney Enterprises, Inc. All rights reserved // // All use of this software is subject to the terms of the Panda 3d // Software license. You should have received a copy of this license // along with this source code; you will also find a current copy of // the license at http://etc.cmu.edu/panda3d/docs/license/ . // // To contact the maintainers of this program write to // [email protected] . // //////////////////////////////////////////////////////////////////// #include "collisionHandlerFluidPusher.h" #include "collisionNode.h" #include "collisionEntry.h" #include "collisionPolygon.h" #include "config_collide.h" #include "dcast.h" TypeHandle CollisionHandlerFluidPusher::_type_handle; //////////////////////////////////////////////////////////////////// // Function: CollisionHandlerFluidPusher::Constructor // Access: Public // Description: //////////////////////////////////////////////////////////////////// CollisionHandlerFluidPusher:: CollisionHandlerFluidPusher() { _wants_all_potential_collidees = true; } //////////////////////////////////////////////////////////////////// // Function: CollisionHandlerFluidPusher::add_entry // Access: Public, Virtual // Description: Called between a begin_group() .. end_group() // sequence for each collision that is detected. //////////////////////////////////////////////////////////////////// void CollisionHandlerFluidPusher:: add_entry(CollisionEntry *entry) { nassertv(entry != (CollisionEntry *)NULL); // skip over CollisionHandlerPhysical::add_entry, since it filters // out collidees by orientation; our collider can change direction // mid-frame, so it may collide with something that would have been // filtered out CollisionHandlerEvent::add_entry(entry); // filter out non-tangibles if (entry->get_from()->is_tangible() && (!entry->has_into() || entry->get_into()->is_tangible())) { _from_entries[entry->get_from_node_path()].push_back(entry); _has_contact = true; } } //////////////////////////////////////////////////////////////////// // Function: CollisionHandlerFluidPusher::handle_entries // Access: Protected, Virtual // Description: Calculates a reasonable final position for a // collider given a set of collidees //////////////////////////////////////////////////////////////////// bool CollisionHandlerFluidPusher:: handle_entries() { /* This pusher repeatedly calculates the first collision, calculates a new trajectory based on that collision, and repeats until the original motion is exhausted or the collider becomes "stuck". This solves the "acute collisions" problem where colliders could bounce their way through to the other side of a wall. Pseudocode: INPUTS PosA = collider's previous position PosB = collider's current position M = movement vector (PosB - PosA) BV = bounding sphere that includes collider at PosA and PosB CS = 'collision set', all 'collidables' within BV (collision polys, tubes, etc) VARIABLES N = movement vector since most recent collision (or start of frame) SCS = 'sub collision set', all collidables that could still be collided with C = single collider currently being collided with PosX = new position given movement along N interrupted by collision with C OUTPUTS final position is PosX 1. N = M, SCS = CS, PosX = PosB 2. compute, using SCS and N, which collidable C is the first collision 3. if no collision found, DONE 4. if movement in direction M is now blocked, then PosX = initial point of contact with C along N, DONE 5. calculate PosX (and new N) assuming that there will be no more collisions 6. remove C from SCS (assumes that you can't collide against a solid more than once per frame) 7. go to 2 */ bool okflag = true; if (!_horizontal) { collide_cat.error() << "collisionHandlerFluidPusher::handle_entries is only supported in " "horizontal mode" << endl; nassertr(false, false); } // for every fluid mover being pushed... FromEntries::iterator fei; for (fei = _from_entries.begin(); fei != _from_entries.end(); ++fei) { NodePath from_node_path = fei->first; Entries *entries = &fei->second; Colliders::iterator ci; ci = _colliders.find(from_node_path); if (ci == _colliders.end()) { // Hmm, someone added a CollisionNode to a traverser and gave // it this CollisionHandler pointer--but they didn't tell us // about the node. collide_cat.error() << "CollisionHandlerFluidPusher doesn't know about " << from_node_path << ", disabling.\n"; okflag = false; } else { ColliderDef &def = (*ci).second; // extract the collision entries into a vector that we can safely modify Entries entries(*entries); Entries next_entries; // extract out the initial set of collision solids CollisionSolids SCS; Entries::iterator ei; for (ei = entries.begin(); ei != entries.end(); ++ei) { SCS.push_back((*ei)->get_into()); } // currently we only support spheres as the collider const CollisionSphere *sphere; DCAST_INTO_R(sphere, (*entries.front()).get_from(), 0); // use a slightly larger radius value so that when we move along // collision planes we don't re-collide float sphere_radius = sphere->get_radius() * 1.001; // make a copy of the original from_nodepath that we can mess with // in the process of calculating the final position _from_node_path_copy = from_node_path.copy_to(from_node_path.get_parent()); LPoint3f N(from_node_path.get_pos_delta(*_root)); const LPoint3f orig_pos(_from_node_path_copy.get_pos()); // this will hold the final calculated position LPoint3f PosX(orig_pos); // unit vector facing back into original direction of motion LVector3f reverse_vec(-N); if (_horizontal) { reverse_vec[2] = 0.0f; } reverse_vec.normalize(); // unit vector pointing out to the right relative to the direction of motion, // looking into the direction of motion const LVector3f right_unit(LVector3f::up().cross(reverse_vec)); // if both of these become true, we're stuck in a 'corner' bool left_halfspace_obstructed = false; bool right_halfspace_obstructed = false; float left_plane_dot = 200.0f; float right_plane_dot = 200.0f; // iterate until the mover runs out of movement or gets stuck while (true) { CollisionEntry *C = 0; // find the first (earliest) collision for (ei = entries.begin(); ei != entries.end(); ++ei) { CollisionEntry *entry = (*ei); nassertr(entry != (CollisionEntry *)NULL, false); if ((C == 0) || (entry->get_t() < C->get_t())) { nassertr(from_node_path == entry->get_from_node_path(), false); C = entry; break; } } // if no collisions, we're done if (C == 0) { break; } // calculate point of collision, move back to it nassertr(C->has_surface_point(), true); nassertr(C->has_surface_normal(), true); nassertr(C->has_interior_point(), true); LVector3f surface_normal = C->get_surface_normal(_from_node_path_copy); if (_horizontal) { surface_normal[2] = 0.0f; } surface_normal.normalize(); PosX = C->get_surface_point(_from_node_path_copy) + (sphere_radius * surface_normal); // check to see if we're stuck, given this collision float dot = right_unit.dot(surface_normal); if (dot > 0.0f) { // positive dot means plane is coming from the left (looking along original // direction of motion) if (dot < left_plane_dot) { if (right_halfspace_obstructed) { // we have obstructions from both directions, we're stuck break; } left_halfspace_obstructed = true; } } else { // negative dot means plane is coming from the right (looking along original // direction of motion) dot = -dot; if (dot < right_plane_dot) { if (left_halfspace_obstructed) { // we have obstructions from both directions, we're stuck break; } right_halfspace_obstructed = true; } } // set up new current/last positions, re-calculate collisions CPT(TransformState) prev_trans(_from_node_path_copy.get_prev_transform()); prev_trans->set_pos(_from_node_path_copy.get_pos()); _from_node_path_copy.set_prev_transform(prev_trans); _from_node_path_copy.set_pos(PosX); // calculate new collisions given new movement vector CollisionEntry new_entry; new_entry._from_node_path = _from_node_path_copy; new_entry._from = sphere; next_entries.clear(); CollisionSolids::iterator csi; for (csi = SCS.begin(); csi != SCS.end(); ++csi) { PT(CollisionEntry) result = (*csi)->test_intersection_from_sphere(new_entry); if (result != (CollisionEntry *)NULL) { next_entries.push_back(result); } } // swap in the new set of collision events entries.swap(next_entries); } LVector3f net_shove(PosX - orig_pos); LVector3f force_normal(net_shove); force_normal.normalize(); // This is the part where the node actually gets moved: CPT(TransformState) trans = def._target.get_transform(); LVecBase3f pos = trans->get_pos(); pos += net_shove * trans->get_mat(); def._target.set_transform(trans->set_pos(pos)); def.updated_transform(); // We call this to allow derived classes to do other // fix-ups as they see fit: apply_net_shove(def, net_shove, force_normal); apply_linear_force(def, force_normal); } } return okflag; } <commit_msg>closer to working<commit_after>// Filename: collisionHandlerFluidPusher.cxx // Created by: drose (16Mar02) // //////////////////////////////////////////////////////////////////// // // PANDA 3D SOFTWARE // Copyright (c) 2001 - 2004, Disney Enterprises, Inc. All rights reserved // // All use of this software is subject to the terms of the Panda 3d // Software license. You should have received a copy of this license // along with this source code; you will also find a current copy of // the license at http://etc.cmu.edu/panda3d/docs/license/ . // // To contact the maintainers of this program write to // [email protected] . // //////////////////////////////////////////////////////////////////// #include "collisionHandlerFluidPusher.h" #include "collisionNode.h" #include "collisionEntry.h" #include "collisionPolygon.h" #include "config_collide.h" #include "dcast.h" TypeHandle CollisionHandlerFluidPusher::_type_handle; //////////////////////////////////////////////////////////////////// // Function: CollisionHandlerFluidPusher::Constructor // Access: Public // Description: //////////////////////////////////////////////////////////////////// CollisionHandlerFluidPusher:: CollisionHandlerFluidPusher() { _wants_all_potential_collidees = true; } //////////////////////////////////////////////////////////////////// // Function: CollisionHandlerFluidPusher::add_entry // Access: Public, Virtual // Description: Called between a begin_group() .. end_group() // sequence for each collision that is detected. //////////////////////////////////////////////////////////////////// void CollisionHandlerFluidPusher:: add_entry(CollisionEntry *entry) { nassertv(entry != (CollisionEntry *)NULL); // skip over CollisionHandlerPhysical::add_entry, since it filters // out collidees by orientation; our collider can change direction // mid-frame, so it may collide with something that would have been // filtered out CollisionHandlerEvent::add_entry(entry); // filter out non-tangibles if (entry->get_from()->is_tangible() && (!entry->has_into() || entry->get_into()->is_tangible())) { _from_entries[entry->get_from_node_path()].push_back(entry); _has_contact = true; } } //////////////////////////////////////////////////////////////////// // Function: CollisionHandlerFluidPusher::handle_entries // Access: Protected, Virtual // Description: Calculates a reasonable final position for a // collider given a set of collidees //////////////////////////////////////////////////////////////////// bool CollisionHandlerFluidPusher:: handle_entries() { /* This pusher repeatedly calculates the first collision, calculates a new trajectory based on that collision, and repeats until the original motion is exhausted or the collider becomes "stuck". This solves the "acute collisions" problem where colliders could bounce their way through to the other side of a wall. Pseudocode: INPUTS PosA = collider's previous position PosB = collider's current position M = movement vector (PosB - PosA) BV = bounding sphere that includes collider at PosA and PosB CS = 'collision set', all 'collidables' within BV (collision polys, tubes, etc) VARIABLES N = movement vector since most recent collision (or start of frame) SCS = 'sub collision set', all collidables that could still be collided with C = single collider currently being collided with PosX = new position given movement along N interrupted by collision with C OUTPUTS final position is PosX 1. N = M, SCS = CS, PosX = PosB 2. compute, using SCS and N, which collidable C is the first collision 3. if no collision found, DONE 4. if movement in direction M is now blocked, then PosX = initial point of contact with C along N, DONE 5. calculate PosX (and new N) assuming that there will be no more collisions 6. remove C from SCS (assumes that you can't collide against a solid more than once per frame) 7. go to 2 */ bool okflag = true; if (!_horizontal) { collide_cat.error() << "collisionHandlerFluidPusher::handle_entries is only supported in " "horizontal mode" << endl; nassertr(false, false); } // for every fluid mover being pushed... FromEntries::iterator fei; for (fei = _from_entries.begin(); fei != _from_entries.end(); ++fei) { NodePath from_node_path = fei->first; Entries *entries = &fei->second; Colliders::iterator ci; ci = _colliders.find(from_node_path); if (ci == _colliders.end()) { // Hmm, someone added a CollisionNode to a traverser and gave // it this CollisionHandler pointer--but they didn't tell us // about the node. collide_cat.error() << "CollisionHandlerFluidPusher doesn't know about " << from_node_path << ", disabling.\n"; okflag = false; } else { ColliderDef &def = (*ci).second; // extract the collision entries into a vector that we can safely modify Entries entries(*entries); Entries next_entries; // extract out the initial set of collision solids CollisionSolids SCS; Entries::iterator ei; for (ei = entries.begin(); ei != entries.end(); ++ei) { SCS.push_back((*ei)->get_into()); } // currently we only support spheres as the collider const CollisionSphere *sphere; DCAST_INTO_R(sphere, (*entries.front()).get_from(), 0); // use a slightly larger radius value so that when we move along // collision planes we don't re-collide float sphere_radius = sphere->get_radius() * 1.001; // make a copy of the original from_nodepath that we can mess with // in the process of calculating the final position _from_node_path_copy = from_node_path.copy_to(from_node_path.get_parent()); LPoint3f N(from_node_path.get_pos_delta(*_root)); if (_horizontal) { N[2] = 0.0f; } const LPoint3f orig_pos(from_node_path.get_pos(*_root)); // this will hold the final calculated position LPoint3f PosX(orig_pos); // unit vector facing back into original direction of motion LVector3f reverse_vec(-N); if (_horizontal) { reverse_vec[2] = 0.0f; } reverse_vec.normalize(); // unit vector pointing out to the right relative to the direction of motion, // looking into the direction of motion const LVector3f right_unit(LVector3f::up().cross(reverse_vec)); // if both of these become true, we're stuck in a 'corner' bool left_halfspace_obstructed = false; bool right_halfspace_obstructed = false; float left_plane_dot = 200.0f; float right_plane_dot = 200.0f; // iterate until the mover runs out of movement or gets stuck while (true) { CollisionEntry *C = 0; // find the first (earliest) collision for (ei = entries.begin(); ei != entries.end(); ++ei) { CollisionEntry *entry = (*ei); nassertr(entry != (CollisionEntry *)NULL, false); if ((C == 0) || (entry->get_t() < C->get_t())) { nassertr(from_node_path == entry->get_from_node_path(), false); C = entry; break; } } // if no collisions, we're done if (C == 0) { break; } // calculate point of collision, move back to it nassertr(C->has_surface_point(), true); nassertr(C->has_surface_normal(), true); nassertr(C->has_interior_point(), true); LVector3f surface_normal = C->get_surface_normal(*_root); if (_horizontal) { surface_normal[2] = 0.0f; } surface_normal.normalize(); collide_cat.info() << "normal: " << surface_normal << endl; PosX = C->get_surface_point(*_root) + (sphere_radius * surface_normal); // check to see if we're stuck, given this collision float dot = right_unit.dot(surface_normal); if (dot > 0.0f) { // positive dot means plane is coming from the left (looking along original // direction of motion) if (dot < left_plane_dot) { if (right_halfspace_obstructed) { // we have obstructions from both directions, we're stuck break; } left_halfspace_obstructed = true; } } else { // negative dot means plane is coming from the right (looking along original // direction of motion) dot = -dot; if (dot < right_plane_dot) { if (left_halfspace_obstructed) { // we have obstructions from both directions, we're stuck break; } right_halfspace_obstructed = true; } } // set up new current/last positions, re-calculate collisions CPT(TransformState) prev_trans(_from_node_path_copy.get_prev_transform(*_root)); prev_trans->set_pos(_from_node_path_copy.get_pos(*_root)); _from_node_path_copy.set_prev_transform(*_root, prev_trans); _from_node_path_copy.set_pos(PosX); // calculate new collisions given new movement vector CollisionEntry new_entry; new_entry._from_node_path = _from_node_path_copy; new_entry._from = sphere; next_entries.clear(); CollisionSolids::iterator csi; for (csi = SCS.begin(); csi != SCS.end(); ++csi) { PT(CollisionEntry) result = (*csi)->test_intersection_from_sphere(new_entry); if (result != (CollisionEntry *)NULL) { next_entries.push_back(result); } } // swap in the new set of collision events entries.swap(next_entries); } LVector3f net_shove(PosX - orig_pos); if (_horizontal) { net_shove[2] = 0.0f; } LVector3f force_normal(net_shove); force_normal.normalize(); collide_cat.info() << "PosX: " << PosX << endl; collide_cat.info() << "orig_pos: " << orig_pos << endl; collide_cat.info() << "net_shove: " << net_shove << endl; collide_cat.info() << endl; // This is the part where the node actually gets moved: CPT(TransformState) trans = def._target.get_transform(*_root); LVecBase3f pos = trans->get_pos(); pos += net_shove * trans->get_mat(); def._target.set_transform(*_root, trans->set_pos(pos)); def.updated_transform(); // We call this to allow derived classes to do other // fix-ups as they see fit: apply_net_shove(def, net_shove, force_normal); apply_linear_force(def, force_normal); } } return okflag; } <|endoftext|>
<commit_before>// @(#)root/base:$Id$ // Author: Rene Brun 02/09/2000 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ //______________________________________________________________________________ // // A TFolder object is a collection of objects and folders. // Folders have a name and a title and are identified in the folder hierarchy // by a "Unix-like" naming mechanism. The root of all folders is //root. // New folders can be dynamically added or removed to/from a folder. // The folder hierarchy can be visualized via the TBrowser. // // The Root folders hierarchy can be seen as a whiteboard where objects // are posted. Other classes/tasks can access these objects by specifying // only a string pathname. This whiteboard facility greatly improves the // modularity of an application, minimizing the class relationship problem // that penalizes large applications. // // Pointers are efficient to communicate between classes. // However, one has interest to minimize direct coupling between classes // in the form of direct pointers. One better uses the naming and search // service provided by the Root folders hierarchy. This makes the classes // loosely coupled and also greatly facilitates I/O operations. // In a client/server environment, this mechanism facilitates the access // to any kind of object in //root stores running on different processes. // // A TFolder is created by invoking the TFolder constructor. It is placed // inside an existing folder via the TFolder::AddFolder method. // One can search for a folder or an object in a folder using the FindObject // method. FindObject analyzes the string passed as its argument and searches // in the hierarchy until it finds an object or folder matching the name. // // When a folder is deleted, its reference from the parent folder and // possible other folders is deleted. // // If a folder has been declared the owner of its objects/folders via // TFolder::SetOwner, then the contained objects are deleted when the // folder is deleted. By default, a folder does not own its contained objects. // NOTE that folder ownership can be set // - via TFolder::SetOwner // - or via TCollection::SetOwner on the collection specified to TFolder::AddFolder // // Standard Root objects are automatically added to the folder hierarchy. // For example, the following folders exist: // //root/Files with the list of currently connected Root files // //root/Classes with the list of active classes // //root/Geometries with active geometries // //root/Canvases with the list of active canvases // //root/Styles with the list of graphics styles // //root/Colors with the list of active colors // // For example, if a file "myFile.root" is added to the list of files, one can // retrieve a pointer to the corresponding TFile object with a statement like: // TFile *myFile = (TFile*)gROOT->FindObject("//root/Files/myFile.root"); // The above statement can be abbreviated to: // TFile *myFile = (TFile*)gROOT->FindObject("/Files/myFile.root"); // or even to: // TFile *myFile = (TFile*)gROOT->FindObjectAny("myFile.root"); // In this last case, the TROOT::FindObjectAny function will scan the folder hierarchy // starting at //root and will return the first object named "myFile.root". // // Because a string-based search mechanism is expensive, it is recommended // to save the pointer to the object as a class member or local variable // if this pointer is used frequently or inside loops. // //Begin_Html /* <img src="gif/folder.gif"> */ //End_Html #include "Riostream.h" #include "Strlen.h" #include "TFolder.h" #include "TBrowser.h" #include "TROOT.h" #include "TClass.h" #include "TError.h" #include "TRegexp.h" static const char *gFolderD[64]; static Int_t gFolderLevel = -1; static char gFolderPath[512]; ClassImp(TFolder) //______________________________________________________________________________ TFolder::TFolder() : TNamed() { // Default constructor used by the Input functions. // // This constructor should not be called by a user directly. // The normal way to create a folder is by calling TFolder::AddFolder. fFolders = 0; fIsOwner = kFALSE; } //______________________________________________________________________________ TFolder::TFolder(const char *name, const char *title) : TNamed(name,title) { // Create a normal folder. // Use Add or AddFolder to add objects or folders to this folder. fFolders = new TList(); fIsOwner = kFALSE; } //______________________________________________________________________________ TFolder::TFolder(const TFolder &folder) : TNamed(folder),fFolders(0),fIsOwner(kFALSE) { // Copy constructor. ((TFolder&)folder).Copy(*this); } //______________________________________________________________________________ TFolder::~TFolder() { // Folder destructor. Remove all objects from its lists and delete // all its sub folders. TCollection::StartGarbageCollection(); if (fFolders) { fFolders->Clear(); SafeDelete(fFolders); } TCollection::EmptyGarbageCollection(); if (gDebug) cerr << "TFolder dtor called for "<< GetName() << endl; } //______________________________________________________________________________ void TFolder::Add(TObject *obj) { // Add object to this folder. obj must be a TObject or a TFolder. if (obj == 0 || fFolders == 0) return; obj->SetBit(kMustCleanup); fFolders->Add(obj); } //______________________________________________________________________________ TFolder *TFolder::AddFolder(const char *name, const char *title, TCollection *collection) { // Create a new folder and add it to the list of folders of this folder, // return a pointer to the created folder. // Note that a folder can be added to several folders. // // If collection is non NULL, the pointer fFolders is set to the existing // collection, otherwise a default collection (Tlist) is created. // Note that the folder name cannot contain slashes. if (strchr(name,'/')) { ::Error("TFolder::TFolder","folder name cannot contain a slash: %s", name); return 0; } if (strlen(GetName()) == 0) { ::Error("TFolder::TFolder","folder name cannot be \"\""); return 0; } TFolder *folder = new TFolder(); folder->SetName(name); folder->SetTitle(title); if (!fFolders) fFolders = new TList(); //only true when gROOT creates its 1st folder fFolders->Add(folder); if (collection) folder->fFolders = collection; else folder->fFolders = new TList(); return folder; } //______________________________________________________________________________ void TFolder::Browse(TBrowser *b) { // Browse this folder. if (fFolders) fFolders->Browse(b); } //______________________________________________________________________________ void TFolder::Clear(Option_t *option) { // Delete all objects from a folder list. if (fFolders) fFolders->Clear(option); } //______________________________________________________________________________ const char *TFolder::FindFullPathName(const char *name) const { // Return the full pathname corresponding to subpath name. // The returned path will be re-used by the next call to GetPath(). TObject *obj = FindObject(name); if (obj || !fFolders) { gFolderLevel++; gFolderD[gFolderLevel] = GetName(); gFolderPath[0] = '/'; gFolderPath[1] = 0; for (Int_t l=0;l<=gFolderLevel;l++) { strcat(gFolderPath,"/"); strcat(gFolderPath,gFolderD[l]); } strcat(gFolderPath,"/"); strcat(gFolderPath,name); gFolderLevel = -1; return gFolderPath; } if (name[0] == '/') return 0; TIter next(fFolders); TFolder *folder; const char *found; gFolderLevel++; gFolderD[gFolderLevel] = GetName(); while ((obj=next())) { if (!obj->InheritsFrom(TFolder::Class())) continue; if (obj->InheritsFrom(TClass::Class())) continue; folder = (TFolder*)obj; found = folder->FindFullPathName(name); if (found) return found; } gFolderLevel--; return 0; } //______________________________________________________________________________ const char *TFolder::FindFullPathName(const TObject *) const { // Return the full pathname corresponding to subpath name. // The returned path will be re-used by the next call to GetPath(). Error("FindFullPathname","Not yet implemented"); return 0; } //______________________________________________________________________________ TObject *TFolder::FindObject(const TObject *) const { // Find object in an folder. Error("FindObject","Not yet implemented"); return 0; } //______________________________________________________________________________ TObject *TFolder::FindObject(const char *name) const { // Search object identified by name in the tree of folders inside // this folder. // Name may be of the forms: // A, Specify a full pathname starting at the top ROOT folder // //root/xxx/yyy/name // // B, Specify a pathname starting with a single slash. //root is assumed // /xxx/yyy/name // // C, Specify a pathname relative to this folder // xxx/yyy/name // name if (!fFolders) return 0; if (name == 0) return 0; if (name[0] == '/') { if (name[1] == '/') { if (!strstr(name,"//root/")) return 0; return gROOT->GetRootFolder()->FindObject(name+7); } else { return gROOT->GetRootFolder()->FindObject(name+1); } } Int_t nch = strlen(name); char *cname; char csname[128]; if (nch <128) cname = csname; else cname = new char[nch+1]; strcpy(cname,name); TObject *obj; char *slash = strchr(cname,'/'); if (slash) { *slash = 0; obj = fFolders->FindObject(cname); if (!obj) return 0; return obj->FindObject(slash+1); } else { return fFolders->FindObject(name); } if (nch >= 128) delete [] cname; } //______________________________________________________________________________ TObject *TFolder::FindObjectAny(const char *name) const { // Return a pointer to the first object with name starting at this folder. TObject *obj = FindObject(name); if (obj || !fFolders) return obj; //if (!obj->InheritsFrom(TFolder::Class())) continue; if (name[0] == '/') return 0; TIter next(fFolders); TFolder *folder; TObject *found; if (gFolderLevel >= 0) gFolderD[gFolderLevel] = GetName(); while ((obj=next())) { if (!obj->InheritsFrom(TFolder::Class())) continue; if (obj->IsA() == TClass::Class()) continue; folder = (TFolder*)obj; found = folder->FindObjectAny(name); if (found) return found; } return 0; } //______________________________________________________________________________ Bool_t TFolder::IsOwner() const { // Folder ownership has been set via // - TFolder::SetOwner // - TCollection::SetOwner on the collection specified to TFolder::AddFolder if (!fFolders) return kFALSE; return fFolders->IsOwner(); } //______________________________________________________________________________ void TFolder::ls(Option_t *option) const { // List folder contents // If option contains "dump", the Dump function of contained objects is called. // If option contains "print", the Print function of contained objects is called. // By default the ls function of contained objects is called. // Indentation is used to identify the folder tree. // // The if option contains a <regexp> it be used to match the name of the objects. if (!fFolders) return; TROOT::IndentLevel(); cout <<ClassName()<<"*\t\t"<<GetName()<<"\t"<<GetTitle()<<endl; TROOT::IncreaseDirLevel(); TString opt = option; Ssiz_t dump = opt.Index("dump", 0, TString::kIgnoreCase); if (dump != kNPOS) opt.Remove(dump, 4); Ssiz_t print = opt.Index("print", 0, TString::kIgnoreCase); if (print != kNPOS) opt.Remove(print, 5); opt = opt.Strip(TString::kBoth); if (opt == "") opt = "*"; TRegexp re(opt, kTRUE); TObject *obj; TIter nextobj(fFolders); while ((obj = (TObject *) nextobj())) { TString s = obj->GetName(); if (s.Index(re) == kNPOS) continue; if (dump != kNPOS) obj->Dump(); if (print != kNPOS) obj->Print(option); obj->ls(option); } TROOT::DecreaseDirLevel(); } //______________________________________________________________________________ Int_t TFolder::Occurence(const TObject *object) const { // Return occurence number of object in the list of objects of this folder. // The function returns the number of objects with the same name as object // found in the list of objects in this folder before object itself. // If only one object is found, return 0. Int_t n = 0; if (!fFolders) return 0; TIter next(fFolders); TObject *obj; while ((obj=next())) { if (strcmp(obj->GetName(),object->GetName()) == 0) n++; } if (n <=1) return n-1; n = 0; next.Reset(); while ((obj=next())) { if (strcmp(obj->GetName(),object->GetName()) == 0) n++; if (obj == object) return n; } return 0; } //______________________________________________________________________________ void TFolder::RecursiveRemove(TObject *obj) { // Recursively remove object from a folder. if (fFolders) fFolders->RecursiveRemove(obj); } //______________________________________________________________________________ void TFolder::Remove(TObject *obj) { // Remove object from this folder. obj must be a TObject or a TFolder. if (obj == 0 || fFolders == 0) return; fFolders->Remove(obj); } //______________________________________________________________________________ void TFolder::SaveAs(const char *filename, Option_t *option) const { // Save all objects in this folder in filename. // Each object in this folder will have a key in the file where the name of // the key will be the name of the object. if (gDirectory) gDirectory->SaveObjectAs(this,filename,option); } //______________________________________________________________________________ void TFolder::SetOwner(Bool_t owner) { // Set ownership. // If the folder is declared owner, when the folder is deleted, all // the objects added via TFolder::Add are deleted via TObject::Delete, // otherwise TObject::Clear is called. // // NOTE that folder ownership can be set: // - via TFolder::SetOwner // - or via TCollection::SetOwner on the collection specified to TFolder::AddFolder if (!fFolders) fFolders = new TList(); fFolders->SetOwner(owner); } <commit_msg>fix coverity 10824.<commit_after>// @(#)root/base:$Id$ // Author: Rene Brun 02/09/2000 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ //______________________________________________________________________________ // // A TFolder object is a collection of objects and folders. // Folders have a name and a title and are identified in the folder hierarchy // by a "Unix-like" naming mechanism. The root of all folders is //root. // New folders can be dynamically added or removed to/from a folder. // The folder hierarchy can be visualized via the TBrowser. // // The Root folders hierarchy can be seen as a whiteboard where objects // are posted. Other classes/tasks can access these objects by specifying // only a string pathname. This whiteboard facility greatly improves the // modularity of an application, minimizing the class relationship problem // that penalizes large applications. // // Pointers are efficient to communicate between classes. // However, one has interest to minimize direct coupling between classes // in the form of direct pointers. One better uses the naming and search // service provided by the Root folders hierarchy. This makes the classes // loosely coupled and also greatly facilitates I/O operations. // In a client/server environment, this mechanism facilitates the access // to any kind of object in //root stores running on different processes. // // A TFolder is created by invoking the TFolder constructor. It is placed // inside an existing folder via the TFolder::AddFolder method. // One can search for a folder or an object in a folder using the FindObject // method. FindObject analyzes the string passed as its argument and searches // in the hierarchy until it finds an object or folder matching the name. // // When a folder is deleted, its reference from the parent folder and // possible other folders is deleted. // // If a folder has been declared the owner of its objects/folders via // TFolder::SetOwner, then the contained objects are deleted when the // folder is deleted. By default, a folder does not own its contained objects. // NOTE that folder ownership can be set // - via TFolder::SetOwner // - or via TCollection::SetOwner on the collection specified to TFolder::AddFolder // // Standard Root objects are automatically added to the folder hierarchy. // For example, the following folders exist: // //root/Files with the list of currently connected Root files // //root/Classes with the list of active classes // //root/Geometries with active geometries // //root/Canvases with the list of active canvases // //root/Styles with the list of graphics styles // //root/Colors with the list of active colors // // For example, if a file "myFile.root" is added to the list of files, one can // retrieve a pointer to the corresponding TFile object with a statement like: // TFile *myFile = (TFile*)gROOT->FindObject("//root/Files/myFile.root"); // The above statement can be abbreviated to: // TFile *myFile = (TFile*)gROOT->FindObject("/Files/myFile.root"); // or even to: // TFile *myFile = (TFile*)gROOT->FindObjectAny("myFile.root"); // In this last case, the TROOT::FindObjectAny function will scan the folder hierarchy // starting at //root and will return the first object named "myFile.root". // // Because a string-based search mechanism is expensive, it is recommended // to save the pointer to the object as a class member or local variable // if this pointer is used frequently or inside loops. // //Begin_Html /* <img src="gif/folder.gif"> */ //End_Html #include "Riostream.h" #include "Strlen.h" #include "TFolder.h" #include "TBrowser.h" #include "TROOT.h" #include "TClass.h" #include "TError.h" #include "TRegexp.h" static const char *gFolderD[64]; static Int_t gFolderLevel = -1; static char gFolderPath[512]; ClassImp(TFolder) //______________________________________________________________________________ TFolder::TFolder() : TNamed() { // Default constructor used by the Input functions. // // This constructor should not be called by a user directly. // The normal way to create a folder is by calling TFolder::AddFolder. fFolders = 0; fIsOwner = kFALSE; } //______________________________________________________________________________ TFolder::TFolder(const char *name, const char *title) : TNamed(name,title) { // Create a normal folder. // Use Add or AddFolder to add objects or folders to this folder. fFolders = new TList(); fIsOwner = kFALSE; } //______________________________________________________________________________ TFolder::TFolder(const TFolder &folder) : TNamed(folder),fFolders(0),fIsOwner(kFALSE) { // Copy constructor. ((TFolder&)folder).Copy(*this); } //______________________________________________________________________________ TFolder::~TFolder() { // Folder destructor. Remove all objects from its lists and delete // all its sub folders. TCollection::StartGarbageCollection(); if (fFolders) { fFolders->Clear(); SafeDelete(fFolders); } TCollection::EmptyGarbageCollection(); if (gDebug) cerr << "TFolder dtor called for "<< GetName() << endl; } //______________________________________________________________________________ void TFolder::Add(TObject *obj) { // Add object to this folder. obj must be a TObject or a TFolder. if (obj == 0 || fFolders == 0) return; obj->SetBit(kMustCleanup); fFolders->Add(obj); } //______________________________________________________________________________ TFolder *TFolder::AddFolder(const char *name, const char *title, TCollection *collection) { // Create a new folder and add it to the list of folders of this folder, // return a pointer to the created folder. // Note that a folder can be added to several folders. // // If collection is non NULL, the pointer fFolders is set to the existing // collection, otherwise a default collection (Tlist) is created. // Note that the folder name cannot contain slashes. if (strchr(name,'/')) { ::Error("TFolder::TFolder","folder name cannot contain a slash: %s", name); return 0; } if (strlen(GetName()) == 0) { ::Error("TFolder::TFolder","folder name cannot be \"\""); return 0; } TFolder *folder = new TFolder(); folder->SetName(name); folder->SetTitle(title); if (!fFolders) fFolders = new TList(); //only true when gROOT creates its 1st folder fFolders->Add(folder); if (collection) folder->fFolders = collection; else folder->fFolders = new TList(); return folder; } //______________________________________________________________________________ void TFolder::Browse(TBrowser *b) { // Browse this folder. if (fFolders) fFolders->Browse(b); } //______________________________________________________________________________ void TFolder::Clear(Option_t *option) { // Delete all objects from a folder list. if (fFolders) fFolders->Clear(option); } //______________________________________________________________________________ const char *TFolder::FindFullPathName(const char *name) const { // Return the full pathname corresponding to subpath name. // The returned path will be re-used by the next call to GetPath(). TObject *obj = FindObject(name); if (obj || !fFolders) { gFolderLevel++; gFolderD[gFolderLevel] = GetName(); gFolderPath[0] = '/'; gFolderPath[1] = 0; for (Int_t l=0;l<=gFolderLevel;l++) { strlcat(gFolderPath, "/", sizeof(gFolderPath)); strlcat(gFolderPath, gFolderD[l], sizeof(gFolderPath)); } strlcat(gFolderPath, "/", sizeof(gFolderPath)); strlcat(gFolderPath,name, sizeof(gFolderPath)); gFolderLevel = -1; return gFolderPath; } if (name[0] == '/') return 0; TIter next(fFolders); TFolder *folder; const char *found; gFolderLevel++; gFolderD[gFolderLevel] = GetName(); while ((obj=next())) { if (!obj->InheritsFrom(TFolder::Class())) continue; if (obj->InheritsFrom(TClass::Class())) continue; folder = (TFolder*)obj; found = folder->FindFullPathName(name); if (found) return found; } gFolderLevel--; return 0; } //______________________________________________________________________________ const char *TFolder::FindFullPathName(const TObject *) const { // Return the full pathname corresponding to subpath name. // The returned path will be re-used by the next call to GetPath(). Error("FindFullPathname","Not yet implemented"); return 0; } //______________________________________________________________________________ TObject *TFolder::FindObject(const TObject *) const { // Find object in an folder. Error("FindObject","Not yet implemented"); return 0; } //______________________________________________________________________________ TObject *TFolder::FindObject(const char *name) const { // Search object identified by name in the tree of folders inside // this folder. // Name may be of the forms: // A, Specify a full pathname starting at the top ROOT folder // //root/xxx/yyy/name // // B, Specify a pathname starting with a single slash. //root is assumed // /xxx/yyy/name // // C, Specify a pathname relative to this folder // xxx/yyy/name // name if (!fFolders) return 0; if (name == 0) return 0; if (name[0] == '/') { if (name[1] == '/') { if (!strstr(name,"//root/")) return 0; return gROOT->GetRootFolder()->FindObject(name+7); } else { return gROOT->GetRootFolder()->FindObject(name+1); } } Int_t nch = strlen(name); char *cname; char csname[128]; if (nch <128) cname = csname; else cname = new char[nch+1]; strcpy(cname,name); TObject *obj; char *slash = strchr(cname,'/'); if (slash) { *slash = 0; obj = fFolders->FindObject(cname); if (!obj) return 0; return obj->FindObject(slash+1); } else { return fFolders->FindObject(name); } if (nch >= 128) delete [] cname; } //______________________________________________________________________________ TObject *TFolder::FindObjectAny(const char *name) const { // Return a pointer to the first object with name starting at this folder. TObject *obj = FindObject(name); if (obj || !fFolders) return obj; //if (!obj->InheritsFrom(TFolder::Class())) continue; if (name[0] == '/') return 0; TIter next(fFolders); TFolder *folder; TObject *found; if (gFolderLevel >= 0) gFolderD[gFolderLevel] = GetName(); while ((obj=next())) { if (!obj->InheritsFrom(TFolder::Class())) continue; if (obj->IsA() == TClass::Class()) continue; folder = (TFolder*)obj; found = folder->FindObjectAny(name); if (found) return found; } return 0; } //______________________________________________________________________________ Bool_t TFolder::IsOwner() const { // Folder ownership has been set via // - TFolder::SetOwner // - TCollection::SetOwner on the collection specified to TFolder::AddFolder if (!fFolders) return kFALSE; return fFolders->IsOwner(); } //______________________________________________________________________________ void TFolder::ls(Option_t *option) const { // List folder contents // If option contains "dump", the Dump function of contained objects is called. // If option contains "print", the Print function of contained objects is called. // By default the ls function of contained objects is called. // Indentation is used to identify the folder tree. // // The if option contains a <regexp> it be used to match the name of the objects. if (!fFolders) return; TROOT::IndentLevel(); cout <<ClassName()<<"*\t\t"<<GetName()<<"\t"<<GetTitle()<<endl; TROOT::IncreaseDirLevel(); TString opt = option; Ssiz_t dump = opt.Index("dump", 0, TString::kIgnoreCase); if (dump != kNPOS) opt.Remove(dump, 4); Ssiz_t print = opt.Index("print", 0, TString::kIgnoreCase); if (print != kNPOS) opt.Remove(print, 5); opt = opt.Strip(TString::kBoth); if (opt == "") opt = "*"; TRegexp re(opt, kTRUE); TObject *obj; TIter nextobj(fFolders); while ((obj = (TObject *) nextobj())) { TString s = obj->GetName(); if (s.Index(re) == kNPOS) continue; if (dump != kNPOS) obj->Dump(); if (print != kNPOS) obj->Print(option); obj->ls(option); } TROOT::DecreaseDirLevel(); } //______________________________________________________________________________ Int_t TFolder::Occurence(const TObject *object) const { // Return occurence number of object in the list of objects of this folder. // The function returns the number of objects with the same name as object // found in the list of objects in this folder before object itself. // If only one object is found, return 0. Int_t n = 0; if (!fFolders) return 0; TIter next(fFolders); TObject *obj; while ((obj=next())) { if (strcmp(obj->GetName(),object->GetName()) == 0) n++; } if (n <=1) return n-1; n = 0; next.Reset(); while ((obj=next())) { if (strcmp(obj->GetName(),object->GetName()) == 0) n++; if (obj == object) return n; } return 0; } //______________________________________________________________________________ void TFolder::RecursiveRemove(TObject *obj) { // Recursively remove object from a folder. if (fFolders) fFolders->RecursiveRemove(obj); } //______________________________________________________________________________ void TFolder::Remove(TObject *obj) { // Remove object from this folder. obj must be a TObject or a TFolder. if (obj == 0 || fFolders == 0) return; fFolders->Remove(obj); } //______________________________________________________________________________ void TFolder::SaveAs(const char *filename, Option_t *option) const { // Save all objects in this folder in filename. // Each object in this folder will have a key in the file where the name of // the key will be the name of the object. if (gDirectory) gDirectory->SaveObjectAs(this,filename,option); } //______________________________________________________________________________ void TFolder::SetOwner(Bool_t owner) { // Set ownership. // If the folder is declared owner, when the folder is deleted, all // the objects added via TFolder::Add are deleted via TObject::Delete, // otherwise TObject::Clear is called. // // NOTE that folder ownership can be set: // - via TFolder::SetOwner // - or via TCollection::SetOwner on the collection specified to TFolder::AddFolder if (!fFolders) fFolders = new TList(); fFolders->SetOwner(owner); } <|endoftext|>
<commit_before>/* * * * * * Implements the people detection algorithm described here: * M. Munaro, F. Basso and E. Menegatti, * Tracking people within groups with RGB-D data, * In Proceedings of the International Conference on Intelligent Robots and Systems (IROS) 2012, Vilamoura (Portugal), 2012. */ #include <signal.h> #include <vector> #include <string> #include <ros/ros.h> #include <ros/package.h> #include <sensor_msgs/PointCloud2.h> #include <visualization_msgs/Marker.h> #include <visualization_msgs/MarkerArray.h> #include <tf/transform_listener.h> #include <tf/tf.h> #include <pcl_ros/impl/transforms.hpp> // PCL specific includes #include <pcl/conversions.h> #include <pcl_conversions/pcl_conversions.h> #include <pcl/point_cloud.h> #include <pcl/console/parse.h> #include <pcl/point_types.h> #include <pcl/visualization/pcl_visualizer.h> #include <pcl/io/openni_grabber.h> #include <pcl/sample_consensus/sac_model_plane.h> #include <pcl/people/ground_based_people_detection_app.h> #include <pcl/common/time.h> #include <pcl/filters/crop_box.h> using namespace std; typedef pcl::PointXYZRGB PointT; typedef pcl::PointCloud<PointT> PointCloudT; //some custom functions #include "utils/file_io.h" #include "utils/viz_utils.h" #include "utils/pcl_utils.h" //some constants bool visualize = false; bool calibrate_plane = false; const std::string data_topic = "nav_kinect/depth_registered/points"; const std::string classifier_location = "/home/bwi/catkin_ws/src/bwi_experimental/pcl_perception/data/classifier.yaml"; const std::string node_name = "segbot_people_detector"; //true if Ctrl-C is pressed bool g_caught_sigint=false; //refresh rate double ros_rate = 10.0; Eigen::VectorXf ground_coeffs; // Mutex: // boost::mutex cloud_mutex; bool new_cloud_available_flag = false; PointCloudT::Ptr cloud (new PointCloudT); PointCloudT::Ptr person_cloud (new PointCloudT); sensor_msgs::PointCloud2 person_cloud_ros; void sig_handler(int sig) { g_caught_sigint = true; ROS_INFO("caught sigint, init shutdown sequence..."); ros::shutdown(); exit(1); }; void cloud_cb (const sensor_msgs::PointCloud2ConstPtr& input) { cloud_mutex.lock (); //convert to PCL format pcl::fromROSMsg (*input, *cloud); //state that a new cloud is available new_cloud_available_flag = true; cloud_mutex.unlock (); } struct callback_args{ // structure used to pass arguments to the callback function PointCloudT::Ptr clicked_points_3d; pcl::visualization::PCLVisualizer::Ptr viewerPtr; }; int main (int argc, char** argv) { // Initialize ROS ros::init (argc, argv, "segbot_background_person_detector"); ros::NodeHandle nh; nh.param<bool>("background_person_detector/visualize", visualize, false); nh.param<double>("background_person_detector/rate", ros_rate, 10.0); string param_out_frame_id; nh.param<std::string>(std::string("background_person_detector/out_frame_id"), param_out_frame_id, "/map"); string param_topic; nh.param<std::string>(std::string("background_person_detector/rgbd_topic"), param_topic, data_topic); string param_classifier; nh.param<std::string>(std::string("background_person_detector/classifier_location"), param_classifier, ros::package::getPath("pcl_perception")+"/data/classifier.yaml"); string param_sensor_frame_id; nh.param<std::string>(std::string("background_person_detector/sensor_frame_id"), param_sensor_frame_id, "/nav_kinect_rgb_optical_frame"); //nh.getParam("background_person_detector/rgbd_topic", data_topic); //initialize marker publisher ros::Publisher marker_pub = nh.advertise<visualization_msgs::Marker>("segbot_pcl_person_detector/marker", 10); ros::Publisher pose_pub = nh.advertise<geometry_msgs::PoseStamped>("segbot_pcl_person_detector/human_poses", 10); ros::Publisher cloud_pub = nh.advertise<sensor_msgs::PointCloud2>("segbot_pcl_person_detector/human_clouds", 10); // Create a ROS subscriber for the input point cloud ros::Subscriber sub = nh.subscribe (param_topic, 1, cloud_cb); // Algorithm parameters: std::string svm_filename = param_classifier; float min_confidence = -1.5;//-1.9 float min_height = 1.3; float max_height = 2.3; float voxel_size = 0.06; Eigen::Matrix3f rgb_intrinsics_matrix; rgb_intrinsics_matrix << 525, 0.0, 319.5, 0.0, 525, 239.5, 0.0, 0.0, 1.0; // Kinect RGB camera intrinsics //register ctrl-c signal(SIGINT, sig_handler); //load ground plane coeffs ground_coeffs.resize(4); string plane_coefs_location = ros::package::getPath("pcl_perception")+"/data/ground_plane_avg.txt"; ground_coeffs = load_vector_from_file(plane_coefs_location.c_str(),4); // Initialize new viewer: pcl::visualization::PCLVisualizer *viewer_display; // viewer initialization if (visualize){ viewer_display = new pcl::visualization::PCLVisualizer("People Viewer"); viewer_display->setCameraPosition(0,0,-2,0,-1,0,0); } // Create classifier for people detection: pcl::people::PersonClassifier<pcl::RGB> person_classifier; person_classifier.loadSVMFromFile(param_classifier); // load trained SVM // People detection app initialization: pcl::people::GroundBasedPeopleDetectionApp<PointT> people_detector; // people detection object people_detector.setVoxelSize(voxel_size); // set the voxel size people_detector.setIntrinsics(rgb_intrinsics_matrix); // set RGB camera intrinsic parameters people_detector.setClassifier(person_classifier); // set person classifier people_detector.setHeightLimits(min_height, max_height); // set person classifier // people_detector.setSensorPortraitOrientation(true); // set sensor orientation to vertical // For timing: static unsigned count = 0; static double last = pcl::getTime (); // int detection_count=0; bool set_ground = false; ros::Rate r(ros_rate); tf::TransformListener listener; tf::StampedTransform transform; // Main loop: while (!g_caught_sigint && ros::ok()) { //collect messages ros::spinOnce(); r.sleep(); if (new_cloud_available_flag && cloud_mutex.try_lock ()) // if a new cloud is available { new_cloud_available_flag = false; // Perform people detection on the new cloud: std::vector<pcl::people::PersonCluster<PointT> > clusters; // vector containing persons clusters std::vector<pcl::people::PersonCluster<PointT> > clusters_filtered; people_detector.setInputCloud(cloud); people_detector.setGround(ground_coeffs); people_detector.compute(clusters); // perform people detection ground_coeffs = people_detector.getGround(); // get updated floor coefficients // Draw cloud and people bounding boxes in the viewer: if (visualize){ viewer_display->removeAllPointClouds(); viewer_display->removeAllShapes(); } pcl::visualization::PointCloudColorHandlerRGBField<PointT> rgb(cloud); if (visualize){ viewer_display->addPointCloud<PointT> (cloud, rgb, "input_cloud"); } //prepare vizualization message visualization_msgs::MarkerArray markers_msg; unsigned int k = 0; for(std::vector<pcl::people::PersonCluster<PointT> >::iterator it = clusters.begin(); it != clusters.end(); ++it) { if(it->getPersonConfidence() > min_confidence) // draw only people with confidence above a threshold { Eigen::Vector3f centroid_k = it->getCenter(); Eigen::Vector3f top_k = it->getTop(); Eigen::Vector3f bottom_k = it->getBottom(); //calculate the distance from the centroid of the cloud to the plane pcl::PointXYZ p_k; p_k.x=bottom_k(0);p_k.y=bottom_k(1);p_k.z=bottom_k(2); double dist_to_ground_bottom = pcl::pointToPlaneDistance(p_k,ground_coeffs); p_k.x=top_k(0);p_k.y=top_k(1);p_k.z=top_k(2); double dist_to_ground_top = pcl::pointToPlaneDistance(p_k,ground_coeffs); p_k.x=centroid_k(0);p_k.y=centroid_k(1);p_k.z=centroid_k(2); double dist_to_ground = pcl::pointToPlaneDistance(p_k,ground_coeffs); /*ROS_INFO("Cluter centroid: %f, %f, %f",centroid_k(0),centroid_k(1),centroid_k(2)); ROS_INFO("\tDistance to ground (top): %f",dist_to_ground_top); ROS_INFO("\tDistance to ground (centroid): %f",dist_to_ground); ROS_INFO("\tDistance to ground (bottom): %f",dist_to_ground_bottom); ROS_INFO("\tCluster height: %f",it->getHeight()); ROS_INFO("\tCluster points: %i",it->getNumberPoints()); ROS_INFO("\tDistance from sensor: %f",it->getDistance()); ROS_INFO("\tconfidence: %f",it->getPersonConfidence()); */ bool accept = true; if (it->getNumberPoints() < 250) //a person should have about 350 points +- 50 depending on distance from kinect accept = false; else if (it->getNumberPoints() > 600) //a person should have about 450 points +- 50 depending on distance from kinect accept = false; else if (it->getHeight() < 1.1) //nobody should be shorter than a meter and 10 cm accept = false; else if (it->getHeight() > 2.2) //or taller than 2.2 meters accept = false; if (dist_to_ground_bottom > 0.3) //or hovering more than 30 cm over the floor accept = false; if (accept){ // draw theoretical person bounding box in the PCL viewer: if (visualize) it->drawTBoundingBox(*viewer_display, k); //get just the person out of the whole cloud pcl_utils::applyBoxFilter(it->getMin(), it->getMax(),cloud,person_cloud); //publish person cloud pcl::toROSMsg(*person_cloud,person_cloud_ros); person_cloud_ros.header.frame_id = param_sensor_frame_id; cloud_pub.publish(person_cloud_ros); //transforms the pose into /map frame geometry_msgs::Pose pose_i; pose_i.position.x=centroid_k(0); pose_i.position.y=0.5; pose_i.position.z=centroid_k(2); pose_i.orientation = tf::createQuaternionMsgFromRollPitchYaw(0,0,-3.14/2); geometry_msgs::PoseStamped stampedPose; stampedPose.header.frame_id = param_sensor_frame_id; stampedPose.header.stamp = ros::Time(0); stampedPose.pose = pose_i; geometry_msgs::PoseStamped stampOut; listener.waitForTransform(param_sensor_frame_id, param_out_frame_id, ros::Time(0), ros::Duration(3.0)); listener.transformPose(param_out_frame_id, stampedPose, stampOut); //transform the human point cloud into presumably the /map frame of reference pcl_ros::transformPointCloud (param_out_frame_id, person_cloud_ros, person_cloud_ros, listener); //save to file for analysis ros::Time nowTime = ros::Time::now(); stringstream ss; ss << ros::package::getPath("pcl_perception") << "/data/human_cloud_" << nowTime.toNSec() << ".pcd"; pcl::io::savePCDFileASCII (ss.str(), *person_cloud); //save cloud in map frame of reference pcl::fromROSMsg(person_cloud_ros,*person_cloud); ss.str(std::string()); ss << ros::package::getPath("pcl_perception") << "/data/human_cloud_map_" << nowTime.toNSec() << ".pcd"; pcl::io::savePCDFileASCII (ss.str(), *person_cloud); //get the actual transform /*tf::StampedTransform transform_to_map; listener.lookupTransform ("/map", param_sensor_frame_id, ros::Time(0), transform_to_map); geometry_msgs::TransformStamped transform_to_map_msg; tf::transformStampedTFToMsg (transform_to_map, transform_to_map_msg) transformPointCloud ("/map", const tf::Transform &net_transform, const sensor_msgs::PointCloud2 &in, sensor_msgs::PointCloud2 &out)*/ stampOut.pose.position.z = 0.7; stampOut.header.stamp = ros::Time::now(); //publish the marker visualization_msgs::Marker marker_k = create_next_person_marker(it,param_out_frame_id,"segbot_pcl_person_detector",detection_count); marker_k.pose = stampOut.pose; marker_pub.publish(marker_k); //publish the pose stampOut.pose.position.z = 0.0; pose_pub.publish(stampOut); k++; detection_count++; } } } if (visualize){ viewer_display->spinOnce(); } cloud_mutex.unlock (); } } return 0; } <commit_msg>continued work on people detector<commit_after>/* * * * * * Implements the people detection algorithm described here: * M. Munaro, F. Basso and E. Menegatti, * Tracking people within groups with RGB-D data, * In Proceedings of the International Conference on Intelligent Robots and Systems (IROS) 2012, Vilamoura (Portugal), 2012. */ #include <signal.h> #include <vector> #include <string> #include <ros/ros.h> #include <ros/package.h> #include <sensor_msgs/PointCloud2.h> #include <visualization_msgs/Marker.h> #include <visualization_msgs/MarkerArray.h> #include <tf/transform_listener.h> #include <tf/tf.h> #include <pcl_ros/impl/transforms.hpp> // PCL specific includes #include <pcl/conversions.h> #include <pcl_conversions/pcl_conversions.h> #include <pcl/point_cloud.h> #include <pcl/console/parse.h> #include <pcl/point_types.h> #include <pcl/visualization/pcl_visualizer.h> #include <pcl/io/openni_grabber.h> #include <pcl/sample_consensus/sac_model_plane.h> #include <pcl/people/ground_based_people_detection_app.h> #include <pcl/common/time.h> #include <pcl/filters/crop_box.h> using namespace std; typedef pcl::PointXYZRGB PointT; typedef pcl::PointCloud<PointT> PointCloudT; //some custom functions #include "utils/file_io.h" #include "utils/viz_utils.h" #include "utils/pcl_utils.h" //some constants bool visualize = false; bool calibrate_plane = false; const std::string data_topic = "nav_kinect/depth_registered/points"; const std::string classifier_location = "/home/bwi/catkin_ws/src/bwi_experimental/pcl_perception/data/classifier.yaml"; const std::string node_name = "segbot_people_detector"; //true if Ctrl-C is pressed bool g_caught_sigint=false; //refresh rate double ros_rate = 10.0; Eigen::VectorXf ground_coeffs; // Mutex: // boost::mutex cloud_mutex; bool new_cloud_available_flag = false; PointCloudT::Ptr cloud (new PointCloudT); PointCloudT::Ptr person_cloud (new PointCloudT); sensor_msgs::PointCloud2 person_cloud_ros; void sig_handler(int sig) { g_caught_sigint = true; ROS_INFO("caught sigint, init shutdown sequence..."); ros::shutdown(); exit(1); }; void cloud_cb (const sensor_msgs::PointCloud2ConstPtr& input) { cloud_mutex.lock (); //convert to PCL format pcl::fromROSMsg (*input, *cloud); //state that a new cloud is available new_cloud_available_flag = true; cloud_mutex.unlock (); } struct callback_args{ // structure used to pass arguments to the callback function PointCloudT::Ptr clicked_points_3d; pcl::visualization::PCLVisualizer::Ptr viewerPtr; }; int main (int argc, char** argv) { // Initialize ROS ros::init (argc, argv, "segbot_background_person_detector"); ros::NodeHandle nh; nh.param<bool>("background_person_detector/visualize", visualize, false); nh.param<double>("background_person_detector/rate", ros_rate, 10.0); string param_out_frame_id; nh.param<std::string>(std::string("background_person_detector/out_frame_id"), param_out_frame_id, "/map"); string param_topic; nh.param<std::string>(std::string("background_person_detector/rgbd_topic"), param_topic, data_topic); string param_classifier; nh.param<std::string>(std::string("background_person_detector/classifier_location"), param_classifier, ros::package::getPath("pcl_perception")+"/data/classifier.yaml"); string param_sensor_frame_id; nh.param<std::string>(std::string("background_person_detector/sensor_frame_id"), param_sensor_frame_id, "/nav_kinect_rgb_optical_frame"); //nh.getParam("background_person_detector/rgbd_topic", data_topic); //initialize marker publisher ros::Publisher marker_pub = nh.advertise<visualization_msgs::Marker>("segbot_pcl_person_detector/marker", 10); ros::Publisher pose_pub = nh.advertise<geometry_msgs::PoseStamped>("segbot_pcl_person_detector/human_poses", 10); ros::Publisher cloud_pub = nh.advertise<sensor_msgs::PointCloud2>("segbot_pcl_person_detector/human_clouds", 10); // Create a ROS subscriber for the input point cloud ros::Subscriber sub = nh.subscribe (param_topic, 1, cloud_cb); // Algorithm parameters: std::string svm_filename = param_classifier; float min_confidence = -1.5;//-1.9 float min_height = 1.3; float max_height = 2.3; float voxel_size = 0.06; Eigen::Matrix3f rgb_intrinsics_matrix; rgb_intrinsics_matrix << 525, 0.0, 319.5, 0.0, 525, 239.5, 0.0, 0.0, 1.0; // Kinect RGB camera intrinsics //register ctrl-c signal(SIGINT, sig_handler); //load ground plane coeffs ground_coeffs.resize(4); string plane_coefs_location = ros::package::getPath("pcl_perception")+"/data/ground_plane_avg.txt"; ground_coeffs = load_vector_from_file(plane_coefs_location.c_str(),4); // Initialize new viewer: pcl::visualization::PCLVisualizer *viewer_display; // viewer initialization if (visualize){ viewer_display = new pcl::visualization::PCLVisualizer("People Viewer"); viewer_display->setCameraPosition(0,0,-2,0,-1,0,0); } // Create classifier for people detection: pcl::people::PersonClassifier<pcl::RGB> person_classifier; person_classifier.loadSVMFromFile(param_classifier); // load trained SVM // People detection app initialization: pcl::people::GroundBasedPeopleDetectionApp<PointT> people_detector; // people detection object people_detector.setVoxelSize(voxel_size); // set the voxel size people_detector.setIntrinsics(rgb_intrinsics_matrix); // set RGB camera intrinsic parameters people_detector.setClassifier(person_classifier); // set person classifier people_detector.setHeightLimits(min_height, max_height); // set person classifier // people_detector.setSensorPortraitOrientation(true); // set sensor orientation to vertical // For timing: static unsigned count = 0; static double last = pcl::getTime (); // int detection_count=0; bool set_ground = false; ros::Rate r(ros_rate); tf::TransformListener listener; tf::StampedTransform transform; // Main loop: while (!g_caught_sigint && ros::ok()) { //collect messages ros::spinOnce(); r.sleep(); if (new_cloud_available_flag && cloud_mutex.try_lock ()) // if a new cloud is available { new_cloud_available_flag = false; // Perform people detection on the new cloud: std::vector<pcl::people::PersonCluster<PointT> > clusters; // vector containing persons clusters std::vector<pcl::people::PersonCluster<PointT> > clusters_filtered; people_detector.setInputCloud(cloud); people_detector.setGround(ground_coeffs); people_detector.compute(clusters); // perform people detection ground_coeffs = people_detector.getGround(); // get updated floor coefficients // Draw cloud and people bounding boxes in the viewer: if (visualize){ viewer_display->removeAllPointClouds(); viewer_display->removeAllShapes(); } pcl::visualization::PointCloudColorHandlerRGBField<PointT> rgb(cloud); if (visualize){ viewer_display->addPointCloud<PointT> (cloud, rgb, "input_cloud"); } //prepare vizualization message visualization_msgs::MarkerArray markers_msg; unsigned int k = 0; for(std::vector<pcl::people::PersonCluster<PointT> >::iterator it = clusters.begin(); it != clusters.end(); ++it) { if(it->getPersonConfidence() > min_confidence) // draw only people with confidence above a threshold { Eigen::Vector3f centroid_k = it->getCenter(); Eigen::Vector3f top_k = it->getTop(); Eigen::Vector3f bottom_k = it->getBottom(); //calculate the distance from the centroid of the cloud to the plane pcl::PointXYZ p_k; p_k.x=bottom_k(0);p_k.y=bottom_k(1);p_k.z=bottom_k(2); double dist_to_ground_bottom = pcl::pointToPlaneDistance(p_k,ground_coeffs); p_k.x=top_k(0);p_k.y=top_k(1);p_k.z=top_k(2); double dist_to_ground_top = pcl::pointToPlaneDistance(p_k,ground_coeffs); p_k.x=centroid_k(0);p_k.y=centroid_k(1);p_k.z=centroid_k(2); double dist_to_ground = pcl::pointToPlaneDistance(p_k,ground_coeffs); /*ROS_INFO("Cluter centroid: %f, %f, %f",centroid_k(0),centroid_k(1),centroid_k(2)); ROS_INFO("\tDistance to ground (top): %f",dist_to_ground_top); ROS_INFO("\tDistance to ground (centroid): %f",dist_to_ground); ROS_INFO("\tDistance to ground (bottom): %f",dist_to_ground_bottom); ROS_INFO("\tCluster height: %f",it->getHeight()); ROS_INFO("\tCluster points: %i",it->getNumberPoints()); ROS_INFO("\tDistance from sensor: %f",it->getDistance()); ROS_INFO("\tconfidence: %f",it->getPersonConfidence()); */ bool accept = true; if (it->getNumberPoints() < 250) //a person should have about 350 points +- 50 depending on distance from kinect accept = false; else if (it->getNumberPoints() > 600) //a person should have about 450 points +- 50 depending on distance from kinect accept = false; else if (it->getHeight() < 1.1) //nobody should be shorter than a meter and 10 cm accept = false; else if (it->getHeight() > 2.2) //or taller than 2.2 meters accept = false; if (dist_to_ground_bottom > 0.3) //or hovering more than 30 cm over the floor accept = false; if (accept){ // draw theoretical person bounding box in the PCL viewer: if (visualize) it->drawTBoundingBox(*viewer_display, k); //get just the person out of the whole cloud pcl_utils::applyBoxFilter(it->getMin(), it->getMax(),cloud,person_cloud); //publish person cloud pcl::toROSMsg(*person_cloud,person_cloud_ros); person_cloud_ros.header.frame_id = param_sensor_frame_id; cloud_pub.publish(person_cloud_ros); //transforms the pose into /map frame geometry_msgs::Pose pose_i; pose_i.position.x=centroid_k(0); pose_i.position.y=0.5; pose_i.position.z=centroid_k(2); pose_i.orientation = tf::createQuaternionMsgFromRollPitchYaw(0,0,-3.14/2); geometry_msgs::PoseStamped stampedPose; stampedPose.header.frame_id = param_sensor_frame_id; stampedPose.header.stamp = ros::Time(0); stampedPose.pose = pose_i; geometry_msgs::PoseStamped stampOut; listener.waitForTransform(param_sensor_frame_id, param_out_frame_id, ros::Time(0), ros::Duration(3.0)); listener.transformPose(param_out_frame_id, stampedPose, stampOut); //transform the human point cloud into presumably the /map frame of reference pcl_ros::transformPointCloud (param_out_frame_id, person_cloud_ros, person_cloud_ros, listener); //save to file for analysis ros::Time nowTime = ros::Time::now(); stringstream ss; ss << ros::package::getPath("pcl_perception") << "/data/human_cloud_" << nowTime.toNSec() << ".pcd"; pcl::io::savePCDFileASCII (ss.str(), *person_cloud); //save cloud in map frame of reference pcl::fromROSMsg(person_cloud_ros,*person_cloud); ss.str(std::string()); ss << ros::package::getPath("pcl_perception") << "/data/human_cloud_map_" << nowTime.toNSec() << ".pcd"; pcl::io::savePCDFileASCII (ss.str(), *person_cloud); stampOut.pose.position.z = 0.7; stampOut.header.stamp = nowTime; //publish the marker visualization_msgs::Marker marker_k = create_next_person_marker(it,param_out_frame_id,"segbot_pcl_person_detector",detection_count); marker_k.pose = stampOut.pose; marker_pub.publish(marker_k); //publish the pose stampOut.pose.position.z = 0.0; pose_pub.publish(stampOut); k++; detection_count++; } } } if (visualize){ viewer_display->spinOnce(); } cloud_mutex.unlock (); } } return 0; } <|endoftext|>
<commit_before>/*************************************************************************/ /* audio_driver_opensl.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2018 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2018 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 "audio_driver_opensl.h" #include <string.h> #define MAX_NUMBER_INTERFACES 3 #define MAX_NUMBER_OUTPUT_DEVICES 6 /* Structure for passing information to callback function */ void AudioDriverOpenSL::_buffer_callback( SLAndroidSimpleBufferQueueItf queueItf /* SLuint32 eventFlags, const void * pBuffer, SLuint32 bufferSize, SLuint32 dataUsed*/) { bool mix = true; if (pause) { mix = false; } else if (mutex) { mix = mutex->try_lock() == OK; } if (mix) { audio_server_process(buffer_size, mixdown_buffer); } else { int32_t *src_buff = mixdown_buffer; for (int i = 0; i < buffer_size * 2; i++) { src_buff[i] = 0; } } if (mutex && mix) mutex->unlock(); const int32_t *src_buff = mixdown_buffer; int16_t *ptr = (int16_t *)buffers[last_free]; last_free = (last_free + 1) % BUFFER_COUNT; for (int i = 0; i < buffer_size * 2; i++) { ptr[i] = src_buff[i] >> 16; } (*queueItf)->Enqueue(queueItf, ptr, 4 * buffer_size); } void AudioDriverOpenSL::_buffer_callbacks( SLAndroidSimpleBufferQueueItf queueItf, void *pContext) { AudioDriverOpenSL *ad = (AudioDriverOpenSL *)pContext; //ad->_buffer_callback(queueItf,eventFlags,pBuffer,bufferSize,dataUsed); ad->_buffer_callback(queueItf); } AudioDriverOpenSL *AudioDriverOpenSL::s_ad = NULL; const char *AudioDriverOpenSL::get_name() const { return "Android"; } Error AudioDriverOpenSL::init() { SLresult res; SLEngineOption EngineOption[] = { (SLuint32)SL_ENGINEOPTION_THREADSAFE, (SLuint32)SL_BOOLEAN_TRUE }; res = slCreateEngine(&sl, 1, EngineOption, 0, NULL, NULL); if (res != SL_RESULT_SUCCESS) { ERR_EXPLAIN("Could not Initialize OpenSL"); ERR_FAIL_V(ERR_INVALID_PARAMETER); } res = (*sl)->Realize(sl, SL_BOOLEAN_FALSE); if (res != SL_RESULT_SUCCESS) { ERR_EXPLAIN("Could not Realize OpenSL"); ERR_FAIL_V(ERR_INVALID_PARAMETER); } return OK; } void AudioDriverOpenSL::start() { mutex = Mutex::create(); active = false; SLint32 numOutputs = 0; SLuint32 deviceID = 0; SLresult res; buffer_size = 1024; for (int i = 0; i < BUFFER_COUNT; i++) { buffers[i] = memnew_arr(int16_t, buffer_size * 2); memset(buffers[i], 0, buffer_size * 4); } mixdown_buffer = memnew_arr(int32_t, buffer_size * 2); /* Callback context for the buffer queue callback function */ /* Get the SL Engine Interface which is implicit */ res = (*sl)->GetInterface(sl, SL_IID_ENGINE, (void *)&EngineItf); ERR_FAIL_COND(res != SL_RESULT_SUCCESS); /* Initialize arrays required[] and iidArray[] */ SLboolean required[MAX_NUMBER_INTERFACES]; SLInterfaceID iidArray[MAX_NUMBER_INTERFACES]; { const SLInterfaceID ids[1] = { SL_IID_ENVIRONMENTALREVERB }; const SLboolean req[1] = { SL_BOOLEAN_FALSE }; res = (*EngineItf)->CreateOutputMix(EngineItf, &OutputMix, 0, ids, req); } ERR_FAIL_COND(res != SL_RESULT_SUCCESS); // Realizing the Output Mix object in synchronous mode. res = (*OutputMix)->Realize(OutputMix, SL_BOOLEAN_FALSE); ERR_FAIL_COND(res != SL_RESULT_SUCCESS); SLDataLocator_AndroidSimpleBufferQueue loc_bufq = { SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE, BUFFER_COUNT }; //bufferQueue.locatorType = SL_DATALOCATOR_BUFFERQUEUE; //bufferQueue.numBuffers = BUFFER_COUNT; /* Four buffers in our buffer queue */ /* Setup the format of the content in the buffer queue */ pcm.formatType = SL_DATAFORMAT_PCM; pcm.numChannels = 2; pcm.samplesPerSec = SL_SAMPLINGRATE_44_1; pcm.bitsPerSample = SL_PCMSAMPLEFORMAT_FIXED_16; pcm.containerSize = SL_PCMSAMPLEFORMAT_FIXED_16; pcm.channelMask = SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT; #ifdef BIG_ENDIAN_ENABLED pcm.endianness = SL_BYTEORDER_BIGENDIAN; #else pcm.endianness = SL_BYTEORDER_LITTLEENDIAN; #endif audioSource.pFormat = (void *)&pcm; audioSource.pLocator = (void *)&loc_bufq; /* Setup the data sink structure */ locator_outputmix.locatorType = SL_DATALOCATOR_OUTPUTMIX; locator_outputmix.outputMix = OutputMix; audioSink.pLocator = (void *)&locator_outputmix; audioSink.pFormat = NULL; /* Initialize the context for Buffer queue callbacks */ //cntxt.pDataBase = (void*)&pcmData; //cntxt.pData = cntxt.pDataBase; //cntxt.size = sizeof(pcmData); /* Set arrays required[] and iidArray[] for SEEK interface (PlayItf is implicit) */ required[0] = SL_BOOLEAN_TRUE; iidArray[0] = SL_IID_BUFFERQUEUE; /* Create the music player */ { const SLInterfaceID ids[2] = { SL_IID_BUFFERQUEUE, SL_IID_EFFECTSEND }; const SLboolean req[2] = { SL_BOOLEAN_TRUE, SL_BOOLEAN_TRUE }; res = (*EngineItf)->CreateAudioPlayer(EngineItf, &player, &audioSource, &audioSink, 1, ids, req); ERR_FAIL_COND(res != SL_RESULT_SUCCESS); } /* Realizing the player in synchronous mode. */ res = (*player)->Realize(player, SL_BOOLEAN_FALSE); ERR_FAIL_COND(res != SL_RESULT_SUCCESS); /* Get seek and play interfaces */ res = (*player)->GetInterface(player, SL_IID_PLAY, (void *)&playItf); ERR_FAIL_COND(res != SL_RESULT_SUCCESS); res = (*player)->GetInterface(player, SL_IID_BUFFERQUEUE, (void *)&bufferQueueItf); ERR_FAIL_COND(res != SL_RESULT_SUCCESS); /* Setup to receive buffer queue event callbacks */ res = (*bufferQueueItf)->RegisterCallback(bufferQueueItf, _buffer_callbacks, this); ERR_FAIL_COND(res != SL_RESULT_SUCCESS); last_free = 0; //fill up buffers for (int i = 0; i < BUFFER_COUNT; i++) { /* Enqueue a few buffers to get the ball rolling */ res = (*bufferQueueItf)->Enqueue(bufferQueueItf, buffers[i], 4 * buffer_size); /* Size given in */ } res = (*playItf)->SetPlayState(playItf, SL_PLAYSTATE_PLAYING); ERR_FAIL_COND(res != SL_RESULT_SUCCESS); active = true; } int AudioDriverOpenSL::get_mix_rate() const { return 44100; } AudioDriver::SpeakerMode AudioDriverOpenSL::get_speaker_mode() const { return SPEAKER_MODE_STEREO; } void AudioDriverOpenSL::lock() { if (active && mutex) mutex->lock(); } void AudioDriverOpenSL::unlock() { if (active && mutex) mutex->unlock(); } void AudioDriverOpenSL::finish() { (*sl)->Destroy(sl); } void AudioDriverOpenSL::set_pause(bool p_pause) { pause = p_pause; if (active) { if (pause) { (*playItf)->SetPlayState(playItf, SL_PLAYSTATE_PAUSED); } else { (*playItf)->SetPlayState(playItf, SL_PLAYSTATE_PLAYING); } } } AudioDriverOpenSL::AudioDriverOpenSL() { s_ad = this; mutex = Mutex::create(); //NULL; pause = false; } <commit_msg>Fix intermittent audio driver crash during startup on Android<commit_after>/*************************************************************************/ /* audio_driver_opensl.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2018 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2018 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 "audio_driver_opensl.h" #include <string.h> #define MAX_NUMBER_INTERFACES 3 #define MAX_NUMBER_OUTPUT_DEVICES 6 /* Structure for passing information to callback function */ void AudioDriverOpenSL::_buffer_callback( SLAndroidSimpleBufferQueueItf queueItf /* SLuint32 eventFlags, const void * pBuffer, SLuint32 bufferSize, SLuint32 dataUsed*/) { bool mix = true; if (pause) { mix = false; } else if (mutex) { mix = mutex->try_lock() == OK; } if (mix) { audio_server_process(buffer_size, mixdown_buffer); } else { int32_t *src_buff = mixdown_buffer; for (int i = 0; i < buffer_size * 2; i++) { src_buff[i] = 0; } } if (mutex && mix) mutex->unlock(); const int32_t *src_buff = mixdown_buffer; int16_t *ptr = (int16_t *)buffers[last_free]; last_free = (last_free + 1) % BUFFER_COUNT; for (int i = 0; i < buffer_size * 2; i++) { ptr[i] = src_buff[i] >> 16; } (*queueItf)->Enqueue(queueItf, ptr, 4 * buffer_size); } void AudioDriverOpenSL::_buffer_callbacks( SLAndroidSimpleBufferQueueItf queueItf, void *pContext) { AudioDriverOpenSL *ad = (AudioDriverOpenSL *)pContext; //ad->_buffer_callback(queueItf,eventFlags,pBuffer,bufferSize,dataUsed); ad->_buffer_callback(queueItf); } AudioDriverOpenSL *AudioDriverOpenSL::s_ad = NULL; const char *AudioDriverOpenSL::get_name() const { return "Android"; } Error AudioDriverOpenSL::init() { SLresult res; SLEngineOption EngineOption[] = { (SLuint32)SL_ENGINEOPTION_THREADSAFE, (SLuint32)SL_BOOLEAN_TRUE }; res = slCreateEngine(&sl, 1, EngineOption, 0, NULL, NULL); if (res != SL_RESULT_SUCCESS) { ERR_EXPLAIN("Could not Initialize OpenSL"); ERR_FAIL_V(ERR_INVALID_PARAMETER); } res = (*sl)->Realize(sl, SL_BOOLEAN_FALSE); if (res != SL_RESULT_SUCCESS) { ERR_EXPLAIN("Could not Realize OpenSL"); ERR_FAIL_V(ERR_INVALID_PARAMETER); } return OK; } void AudioDriverOpenSL::start() { mutex = Mutex::create(); active = false; SLint32 numOutputs = 0; SLuint32 deviceID = 0; SLresult res; buffer_size = 1024; for (int i = 0; i < BUFFER_COUNT; i++) { buffers[i] = memnew_arr(int16_t, buffer_size * 2); memset(buffers[i], 0, buffer_size * 4); } mixdown_buffer = memnew_arr(int32_t, buffer_size * 2); /* Callback context for the buffer queue callback function */ /* Get the SL Engine Interface which is implicit */ res = (*sl)->GetInterface(sl, SL_IID_ENGINE, (void *)&EngineItf); ERR_FAIL_COND(res != SL_RESULT_SUCCESS); /* Initialize arrays required[] and iidArray[] */ SLboolean required[MAX_NUMBER_INTERFACES]; SLInterfaceID iidArray[MAX_NUMBER_INTERFACES]; { const SLInterfaceID ids[1] = { SL_IID_ENVIRONMENTALREVERB }; const SLboolean req[1] = { SL_BOOLEAN_FALSE }; res = (*EngineItf)->CreateOutputMix(EngineItf, &OutputMix, 0, ids, req); } ERR_FAIL_COND(res != SL_RESULT_SUCCESS); // Realizing the Output Mix object in synchronous mode. res = (*OutputMix)->Realize(OutputMix, SL_BOOLEAN_FALSE); ERR_FAIL_COND(res != SL_RESULT_SUCCESS); SLDataLocator_AndroidSimpleBufferQueue loc_bufq = { SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE, BUFFER_COUNT }; //bufferQueue.locatorType = SL_DATALOCATOR_BUFFERQUEUE; //bufferQueue.numBuffers = BUFFER_COUNT; /* Four buffers in our buffer queue */ /* Setup the format of the content in the buffer queue */ pcm.formatType = SL_DATAFORMAT_PCM; pcm.numChannels = 2; pcm.samplesPerSec = SL_SAMPLINGRATE_44_1; pcm.bitsPerSample = SL_PCMSAMPLEFORMAT_FIXED_16; pcm.containerSize = SL_PCMSAMPLEFORMAT_FIXED_16; pcm.channelMask = SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT; #ifdef BIG_ENDIAN_ENABLED pcm.endianness = SL_BYTEORDER_BIGENDIAN; #else pcm.endianness = SL_BYTEORDER_LITTLEENDIAN; #endif audioSource.pFormat = (void *)&pcm; audioSource.pLocator = (void *)&loc_bufq; /* Setup the data sink structure */ locator_outputmix.locatorType = SL_DATALOCATOR_OUTPUTMIX; locator_outputmix.outputMix = OutputMix; audioSink.pLocator = (void *)&locator_outputmix; audioSink.pFormat = NULL; /* Initialize the context for Buffer queue callbacks */ //cntxt.pDataBase = (void*)&pcmData; //cntxt.pData = cntxt.pDataBase; //cntxt.size = sizeof(pcmData); /* Set arrays required[] and iidArray[] for SEEK interface (PlayItf is implicit) */ required[0] = SL_BOOLEAN_TRUE; iidArray[0] = SL_IID_BUFFERQUEUE; /* Create the music player */ { const SLInterfaceID ids[2] = { SL_IID_BUFFERQUEUE, SL_IID_EFFECTSEND }; const SLboolean req[2] = { SL_BOOLEAN_TRUE, SL_BOOLEAN_TRUE }; res = (*EngineItf)->CreateAudioPlayer(EngineItf, &player, &audioSource, &audioSink, 1, ids, req); ERR_FAIL_COND(res != SL_RESULT_SUCCESS); } /* Realizing the player in synchronous mode. */ res = (*player)->Realize(player, SL_BOOLEAN_FALSE); ERR_FAIL_COND(res != SL_RESULT_SUCCESS); /* Get seek and play interfaces */ res = (*player)->GetInterface(player, SL_IID_PLAY, (void *)&playItf); ERR_FAIL_COND(res != SL_RESULT_SUCCESS); res = (*player)->GetInterface(player, SL_IID_BUFFERQUEUE, (void *)&bufferQueueItf); ERR_FAIL_COND(res != SL_RESULT_SUCCESS); /* Setup to receive buffer queue event callbacks */ res = (*bufferQueueItf)->RegisterCallback(bufferQueueItf, _buffer_callbacks, this); ERR_FAIL_COND(res != SL_RESULT_SUCCESS); last_free = 0; //fill up buffers for (int i = 0; i < BUFFER_COUNT; i++) { /* Enqueue a few buffers to get the ball rolling */ res = (*bufferQueueItf)->Enqueue(bufferQueueItf, buffers[i], 4 * buffer_size); /* Size given in */ } res = (*playItf)->SetPlayState(playItf, SL_PLAYSTATE_PLAYING); ERR_FAIL_COND(res != SL_RESULT_SUCCESS); active = true; } int AudioDriverOpenSL::get_mix_rate() const { return 44100; } AudioDriver::SpeakerMode AudioDriverOpenSL::get_speaker_mode() const { return SPEAKER_MODE_STEREO; } void AudioDriverOpenSL::lock() { if (active && mutex) mutex->lock(); } void AudioDriverOpenSL::unlock() { if (active && mutex) mutex->unlock(); } void AudioDriverOpenSL::finish() { (*sl)->Destroy(sl); } void AudioDriverOpenSL::set_pause(bool p_pause) { pause = p_pause; if (active) { if (pause) { (*playItf)->SetPlayState(playItf, SL_PLAYSTATE_PAUSED); } else { (*playItf)->SetPlayState(playItf, SL_PLAYSTATE_PLAYING); } } } AudioDriverOpenSL::AudioDriverOpenSL() { s_ad = this; mutex = Mutex::create(); //NULL; pause = false; active = false; } <|endoftext|>
<commit_before>/* * Copyright (C) 2017 The Android Open Source Project * * 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 <cmath> #include <android/log.h> #include <android/looper.h> #include <android_native_app_glue.h> #include <pio/gpio.h> #include <pio/peripheral_manager_client.h> #include "AndroidSystemProperties.h" const char* TAG = "speaker"; const double NOTE_A4_FREQUENCY = 440.0; const double FREQUENCY_INC_PER_MS = 0.1; #define LOGV(...) __android_log_print(ANDROID_LOG_VERBOSE, TAG, __VA_ARGS__) #define LOGW(...) __android_log_print(ANDROID_LOG_WARN, TAG, __VA_ARGS__) #define LOGI(...) __android_log_print(ANDROID_LOG_INFO, TAG, __VA_ARGS__) #define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, TAG, __VA_ARGS__) #define ASSERT(cond, ...) if (!(cond)) { __android_log_assert(#cond, TAG, __VA_ARGS__);} int64_t millis() { timespec now; clock_gettime(CLOCK_MONOTONIC, &now); return now.tv_sec*1000 + llround(now.tv_nsec / 1e6); } void android_main(android_app* app) { app_dummy(); // prevent native-app-glue to be stripped. AndroidSystemProperties systemProperties(app->activity); const char* SPEAKER_PWM; if (systemProperties.getBuildDevice() == "rpi3") { SPEAKER_PWM = "PWM1"; } else if (systemProperties.getBuildDevice() == "edison") { SPEAKER_PWM = "IO3"; } else if (systemProperties.getBuildDevice() == "imx7d_pico") { SPEAKER_PWM = "PWM2"; } else { LOGE("unsupported device: %s", systemProperties.getBuildDevice().c_str()); return; } APeripheralManagerClient* client = APeripheralManagerClient_new(); ASSERT(client, "failed to open peripheral manager client"); APwm* pwm; int openResult = APeripheralManagerClient_openPwm(client, SPEAKER_PWM, &pwm); ASSERT(openResult == 0, "failed to open PWM: %s", SPEAKER_PWM); int setDutyCycleResult = APwm_setDutyCycle(pwm, 50.0); ASSERT(setDutyCycleResult == 0, "failed to set PWM duty cycle: %s", SPEAKER_PWM); int enablePwmResult = APwm_setEnabled(pwm, 1); ASSERT(enablePwmResult == 0, "failed to enable PWM: %s", SPEAKER_PWM); double frequency = NOTE_A4_FREQUENCY; int64_t lastMs = millis(); while (!app->destroyRequested) { android_poll_source* source; int pollResult = ALooper_pollOnce(0, NULL, NULL, (void**)&source); if (pollResult >= 0) { if (source != NULL) { // forward event to native-app-glue to handle lifecycle and input event // and update `app` state. source->process(app, source); } } if (APwm_setFrequencyHz(pwm, frequency) != 0) { continue; // retry } int64_t now = millis(); int64_t elapsedMs = now - lastMs; frequency += FREQUENCY_INC_PER_MS * elapsedMs; if (frequency > NOTE_A4_FREQUENCY * 2) { frequency = NOTE_A4_FREQUENCY; } lastMs = now; } APwm_setEnabled(pwm, 0); APwm_delete(pwm); APeripheralManagerClient_delete(client); } <commit_msg>sample-nativepio: call set frequency before enabling pwm<commit_after>/* * Copyright (C) 2017 The Android Open Source Project * * 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 <cmath> #include <android/log.h> #include <android/looper.h> #include <android_native_app_glue.h> #include <pio/gpio.h> #include <pio/peripheral_manager_client.h> #include "AndroidSystemProperties.h" const char* TAG = "speaker"; const double NOTE_A4_FREQUENCY = 440.0; const double FREQUENCY_INC_PER_MS = 0.1; #define LOGV(...) __android_log_print(ANDROID_LOG_VERBOSE, TAG, __VA_ARGS__) #define LOGW(...) __android_log_print(ANDROID_LOG_WARN, TAG, __VA_ARGS__) #define LOGI(...) __android_log_print(ANDROID_LOG_INFO, TAG, __VA_ARGS__) #define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, TAG, __VA_ARGS__) #define ASSERT(cond, ...) if (!(cond)) { __android_log_assert(#cond, TAG, __VA_ARGS__);} int64_t millis() { timespec now; clock_gettime(CLOCK_MONOTONIC, &now); return now.tv_sec*1000 + llround(now.tv_nsec / 1e6); } void android_main(android_app* app) { app_dummy(); // prevent native-app-glue to be stripped. AndroidSystemProperties systemProperties(app->activity); const char* SPEAKER_PWM; if (systemProperties.getBuildDevice() == "rpi3") { SPEAKER_PWM = "PWM1"; } else if (systemProperties.getBuildDevice() == "edison") { SPEAKER_PWM = "IO3"; } else if (systemProperties.getBuildDevice() == "imx7d_pico") { SPEAKER_PWM = "PWM2"; } else { LOGE("unsupported device: %s", systemProperties.getBuildDevice().c_str()); return; } APeripheralManagerClient* client = APeripheralManagerClient_new(); ASSERT(client, "failed to open peripheral manager client"); APwm* pwm; int openResult = APeripheralManagerClient_openPwm(client, SPEAKER_PWM, &pwm); ASSERT(openResult == 0, "failed to open PWM: %s", SPEAKER_PWM); int setDutyCycleResult = APwm_setDutyCycle(pwm, 50.0); ASSERT(setDutyCycleResult == 0, "failed to set PWM duty cycle: %s", SPEAKER_PWM); double frequency = NOTE_A4_FREQUENCY; int setFrequencyResult = APwm_setFrequencyHz(pwm, frequency); ASSERT(setFrequencyResult == 0, "failed to set PWM frequency: %s", SPEAKER_PWM); int enablePwmResult = APwm_setEnabled(pwm, 1); ASSERT(enablePwmResult == 0, "failed to enable PWM: %s", SPEAKER_PWM); int64_t lastMs = millis(); while (!app->destroyRequested) { android_poll_source* source; int pollResult = ALooper_pollOnce(0, NULL, NULL, (void**)&source); if (pollResult >= 0) { if (source != NULL) { // forward event to native-app-glue to handle lifecycle and input event // and update `app` state. source->process(app, source); } } if (APwm_setFrequencyHz(pwm, frequency) != 0) { continue; // retry } int64_t now = millis(); int64_t elapsedMs = now - lastMs; frequency += FREQUENCY_INC_PER_MS * elapsedMs; if (frequency > NOTE_A4_FREQUENCY * 2) { frequency = NOTE_A4_FREQUENCY; } lastMs = now; } APwm_setEnabled(pwm, 0); APwm_delete(pwm); APeripheralManagerClient_delete(client); } <|endoftext|>
<commit_before>#include "calibration_impl.h" #include "system.h" #include "global_include.h" #include "px4_custom_mode.h" #include <functional> #include <string> #include <sstream> namespace dronecore { using namespace std::placeholders; CalibrationImpl::CalibrationImpl(System &system) : PluginImplBase(system) { _parent->register_plugin(this); } CalibrationImpl::~CalibrationImpl() { _parent->unregister_plugin(this); } void CalibrationImpl::init() { _parent->register_mavlink_message_handler( MAVLINK_MSG_ID_STATUSTEXT, std::bind(&CalibrationImpl::process_statustext, this, _1), this); } void CalibrationImpl::deinit() { _parent->unregister_all_mavlink_message_handlers(this); } void CalibrationImpl::enable() { // The calibration check should eventually be better than this. // For now, we just do the same as QGC does. _parent->get_param_int_async(std::string("CAL_GYRO0_ID"), std::bind(&CalibrationImpl::receive_param_cal_gyro, this, _1, _2)); _parent->get_param_int_async( std::string("CAL_ACC0_ID"), std::bind(&CalibrationImpl::receive_param_cal_accel, this, _1, _2)); _parent->get_param_int_async(std::string("CAL_MAG0_ID"), std::bind(&CalibrationImpl::receive_param_cal_mag, this, _1, _2)); } void CalibrationImpl::disable() {} void CalibrationImpl::calibrate_gyro_async(const Calibration::calibration_callback_t &callback) { std::lock_guard<std::mutex> lock(_calibration_mutex); if (_parent->is_armed()) { report_failed("System is armed."); return; } if (_state != State::NONE) { if (callback) { _parent->call_user_callback( [callback]() { callback(Calibration::Result::BUSY, NAN, ""); }); } return; } _state = State::GYRO_CALIBRATION; _calibration_callback = callback; MAVLinkCommands::CommandLong command{}; command.command = MAV_CMD_PREFLIGHT_CALIBRATION; MAVLinkCommands::CommandLong::set_as_reserved(command.params, 0.0f); command.params.param1 = 1.0f; // Gyro command.target_component_id = MAV_COMP_ID_AUTOPILOT1; _parent->send_command_async(command, std::bind(&CalibrationImpl::command_result_callback, this, _1, _2)); } void CalibrationImpl::calibrate_accelerometer_async( const Calibration::calibration_callback_t &callback) { std::lock_guard<std::mutex> lock(_calibration_mutex); if (_parent->is_armed()) { report_failed("System is armed."); return; } if (_state != State::NONE) { if (callback) { _parent->call_user_callback( [callback]() { callback(Calibration::Result::BUSY, NAN, ""); }); } return; } _state = State::ACCELEROMETER_CALIBRATION; _calibration_callback = callback; MAVLinkCommands::CommandLong command{}; command.command = MAV_CMD_PREFLIGHT_CALIBRATION; MAVLinkCommands::CommandLong::set_as_reserved(command.params, 0.0f); command.params.param5 = 1.0f; // Accel command.target_component_id = MAV_COMP_ID_AUTOPILOT1; _parent->send_command_async(command, std::bind(&CalibrationImpl::command_result_callback, this, _1, _2)); } void CalibrationImpl::calibrate_magnetometer_async( const Calibration::calibration_callback_t &callback) { std::lock_guard<std::mutex> lock(_calibration_mutex); if (_parent->is_armed()) { report_failed("System is armed."); return; } if (_state != State::NONE) { if (callback) { _parent->call_user_callback( [callback]() { callback(Calibration::Result::BUSY, NAN, ""); }); } return; } _state = State::MAGNETOMETER_CALIBRATION; _calibration_callback = callback; MAVLinkCommands::CommandLong command{}; command.command = MAV_CMD_PREFLIGHT_CALIBRATION; MAVLinkCommands::CommandLong::set_as_reserved(command.params, 0.0f); command.params.param2 = 1.0f; // Mag command.target_component_id = MAV_COMP_ID_AUTOPILOT1; _parent->send_command_async(command, std::bind(&CalibrationImpl::command_result_callback, this, _1, _2)); } bool CalibrationImpl::is_gyro_calibration_ok() const { std::lock_guard<std::mutex> lock(_calibration_mutex); return _is_gyro_ok; } bool CalibrationImpl::is_accelerometer_calibration_ok() const { std::lock_guard<std::mutex> lock(_calibration_mutex); return _is_accelerometer_ok; } bool CalibrationImpl::is_magnetometer_calibration_ok() const { std::lock_guard<std::mutex> lock(_calibration_mutex); return _is_magnetometer_ok; } void CalibrationImpl::command_result_callback(MAVLinkCommands::Result command_result, float progress) { std::lock_guard<std::mutex> lock(_calibration_mutex); if (_state == State::NONE) { // It might be someone else like a ground station trying to do a // calibration. We silently ignore it. return; } // If we get a progress result here, it is the new interface and we can // use the progress info. If we get an ack, we need to translate that to // a first progress update, and then parse the statustexts for progress. switch (command_result) { case MAVLinkCommands::Result::SUCCESS: // Silently ignore. break; case MAVLinkCommands::Result::NO_SYSTEM: // FALLTHROUGH case MAVLinkCommands::Result::CONNECTION_ERROR: // FALLTHROUGH case MAVLinkCommands::Result::BUSY: // FALLTHROUGH case MAVLinkCommands::Result::COMMAND_DENIED: // FALLTHROUGH case MAVLinkCommands::Result::UNKNOWN_ERROR: // FALLTHROUGH case MAVLinkCommands::Result::TIMEOUT: // Report all error cases. if (_calibration_callback) { auto calibration_callback_tmp = _calibration_callback; _parent->call_user_callback([calibration_callback_tmp, command_result]() { calibration_callback_tmp( calibration_result_from_command_result(command_result), NAN, ""); }); } _calibration_callback = nullptr; _state = State::NONE; break; case MAVLinkCommands::Result::IN_PROGRESS: if (_calibration_callback) { auto calibration_callback_tmp = _calibration_callback; _parent->call_user_callback([calibration_callback_tmp, command_result, progress]() { calibration_callback_tmp( calibration_result_from_command_result(command_result), progress, ""); }); } break; }; } Calibration::Result CalibrationImpl::calibration_result_from_command_result(MAVLinkCommands::Result result) { switch (result) { case MAVLinkCommands::Result::SUCCESS: return Calibration::Result::SUCCESS; case MAVLinkCommands::Result::NO_SYSTEM: return Calibration::Result::NO_SYSTEM; case MAVLinkCommands::Result::CONNECTION_ERROR: return Calibration::Result::CONNECTION_ERROR; case MAVLinkCommands::Result::BUSY: return Calibration::Result::BUSY; case MAVLinkCommands::Result::COMMAND_DENIED: return Calibration::Result::COMMAND_DENIED; case MAVLinkCommands::Result::TIMEOUT: return Calibration::Result::TIMEOUT; case MAVLinkCommands::Result::IN_PROGRESS: return Calibration::Result::IN_PROGRESS; default: return Calibration::Result::UNKNOWN; } } void CalibrationImpl::receive_param_cal_gyro(bool success, int value) { if (!success) { LogErr() << "Error: Param for gyro cal failed."; return; } bool ok = (value != 0); set_gyro_calibration(ok); } void CalibrationImpl::receive_param_cal_accel(bool success, int value) { if (!success) { LogErr() << "Error: Param for accel cal failed."; return; } bool ok = (value != 0); set_accelerometer_calibration(ok); } void CalibrationImpl::receive_param_cal_mag(bool success, int value) { if (!success) { LogErr() << "Error: Param for mag cal failed."; return; } bool ok = (value != 0); set_magnetometer_calibration(ok); } void CalibrationImpl::set_gyro_calibration(bool ok) { std::lock_guard<std::mutex> lock(_calibration_mutex); _is_gyro_ok = ok; } void CalibrationImpl::set_accelerometer_calibration(bool ok) { std::lock_guard<std::mutex> lock(_calibration_mutex); _is_accelerometer_ok = ok; } void CalibrationImpl::set_magnetometer_calibration(bool ok) { std::lock_guard<std::mutex> lock(_calibration_mutex); _is_magnetometer_ok = ok; } void CalibrationImpl::process_statustext(const mavlink_message_t &message) { std::lock_guard<std::mutex> lock(_calibration_mutex); if (_state == State::NONE) { return; } mavlink_statustext_t statustext; mavlink_msg_statustext_decode(&message, &statustext); _parser.reset(); _parser.parse(statustext.text); switch (_parser.get_status()) { case CalibrationStatustextParser::Status::NONE: // Ignore it. break; case CalibrationStatustextParser::Status::STARTED: report_started(); break; case CalibrationStatustextParser::Status::DONE: report_done(); break; case CalibrationStatustextParser::Status::FAILED: report_failed(_parser.get_failed_message()); break; case CalibrationStatustextParser::Status::CANCELLED: report_cancelled(); break; case CalibrationStatustextParser::Status::PROGRESS: report_progress(_parser.get_progress()); break; case CalibrationStatustextParser::Status::INSTRUCTION: report_instruction(_parser.get_instruction()); break; } } void CalibrationImpl::report_started() { report_progress(0.0f); } void CalibrationImpl::report_done() { if (_calibration_callback) { auto calibration_callback_tmp = _calibration_callback; _parent->call_user_callback([calibration_callback_tmp]() { calibration_callback_tmp(Calibration::Result::SUCCESS, NAN, ""); }); } } void CalibrationImpl::report_failed(const std::string &failed) { LogErr() << "Calibration failed: " << failed; if (_calibration_callback) { auto calibration_callback_tmp = _calibration_callback; _parent->call_user_callback([calibration_callback_tmp]() { calibration_callback_tmp(Calibration::Result::FAILED, NAN, ""); }); } } void CalibrationImpl::report_cancelled() { LogWarn() << "Calibration was cancelled"; if (_calibration_callback) { auto calibration_callback_tmp = _calibration_callback; _parent->call_user_callback([calibration_callback_tmp]() { calibration_callback_tmp(Calibration::Result::CANCELLED, NAN, ""); }); } } void CalibrationImpl::report_progress(float progress) { if (_calibration_callback) { auto calibration_callback_tmp = _calibration_callback; _parent->call_user_callback([calibration_callback_tmp, progress]() { calibration_callback_tmp(Calibration::Result::IN_PROGRESS, progress, ""); }); } } void CalibrationImpl::report_instruction(const std::string &instruction) { if (_calibration_callback) { auto calibration_callback_tmp = _calibration_callback; _parent->call_user_callback([calibration_callback_tmp, instruction]() { calibration_callback_tmp(Calibration::Result::INSTRUCTION, NAN, instruction); }); } } } // namespace dronecore <commit_msg>calibration: don't forget to reset and clean up<commit_after>#include "calibration_impl.h" #include "system.h" #include "global_include.h" #include "px4_custom_mode.h" #include <functional> #include <string> #include <sstream> namespace dronecore { using namespace std::placeholders; CalibrationImpl::CalibrationImpl(System &system) : PluginImplBase(system) { _parent->register_plugin(this); } CalibrationImpl::~CalibrationImpl() { _parent->unregister_plugin(this); } void CalibrationImpl::init() { _parent->register_mavlink_message_handler( MAVLINK_MSG_ID_STATUSTEXT, std::bind(&CalibrationImpl::process_statustext, this, _1), this); } void CalibrationImpl::deinit() { _parent->unregister_all_mavlink_message_handlers(this); } void CalibrationImpl::enable() { // The calibration check should eventually be better than this. // For now, we just do the same as QGC does. _parent->get_param_int_async(std::string("CAL_GYRO0_ID"), std::bind(&CalibrationImpl::receive_param_cal_gyro, this, _1, _2)); _parent->get_param_int_async( std::string("CAL_ACC0_ID"), std::bind(&CalibrationImpl::receive_param_cal_accel, this, _1, _2)); _parent->get_param_int_async(std::string("CAL_MAG0_ID"), std::bind(&CalibrationImpl::receive_param_cal_mag, this, _1, _2)); } void CalibrationImpl::disable() {} void CalibrationImpl::calibrate_gyro_async(const Calibration::calibration_callback_t &callback) { std::lock_guard<std::mutex> lock(_calibration_mutex); if (_parent->is_armed()) { report_failed("System is armed."); return; } if (_state != State::NONE) { if (callback) { _parent->call_user_callback( [callback]() { callback(Calibration::Result::BUSY, NAN, ""); }); } return; } _state = State::GYRO_CALIBRATION; _calibration_callback = callback; MAVLinkCommands::CommandLong command{}; command.command = MAV_CMD_PREFLIGHT_CALIBRATION; MAVLinkCommands::CommandLong::set_as_reserved(command.params, 0.0f); command.params.param1 = 1.0f; // Gyro command.target_component_id = MAV_COMP_ID_AUTOPILOT1; _parent->send_command_async(command, std::bind(&CalibrationImpl::command_result_callback, this, _1, _2)); } void CalibrationImpl::calibrate_accelerometer_async( const Calibration::calibration_callback_t &callback) { std::lock_guard<std::mutex> lock(_calibration_mutex); if (_parent->is_armed()) { report_failed("System is armed."); return; } if (_state != State::NONE) { if (callback) { _parent->call_user_callback( [callback]() { callback(Calibration::Result::BUSY, NAN, ""); }); } return; } _state = State::ACCELEROMETER_CALIBRATION; _calibration_callback = callback; MAVLinkCommands::CommandLong command{}; command.command = MAV_CMD_PREFLIGHT_CALIBRATION; MAVLinkCommands::CommandLong::set_as_reserved(command.params, 0.0f); command.params.param5 = 1.0f; // Accel command.target_component_id = MAV_COMP_ID_AUTOPILOT1; _parent->send_command_async(command, std::bind(&CalibrationImpl::command_result_callback, this, _1, _2)); } void CalibrationImpl::calibrate_magnetometer_async( const Calibration::calibration_callback_t &callback) { std::lock_guard<std::mutex> lock(_calibration_mutex); if (_parent->is_armed()) { report_failed("System is armed."); return; } if (_state != State::NONE) { if (callback) { _parent->call_user_callback( [callback]() { callback(Calibration::Result::BUSY, NAN, ""); }); } return; } _state = State::MAGNETOMETER_CALIBRATION; _calibration_callback = callback; MAVLinkCommands::CommandLong command{}; command.command = MAV_CMD_PREFLIGHT_CALIBRATION; MAVLinkCommands::CommandLong::set_as_reserved(command.params, 0.0f); command.params.param2 = 1.0f; // Mag command.target_component_id = MAV_COMP_ID_AUTOPILOT1; _parent->send_command_async(command, std::bind(&CalibrationImpl::command_result_callback, this, _1, _2)); } bool CalibrationImpl::is_gyro_calibration_ok() const { std::lock_guard<std::mutex> lock(_calibration_mutex); return _is_gyro_ok; } bool CalibrationImpl::is_accelerometer_calibration_ok() const { std::lock_guard<std::mutex> lock(_calibration_mutex); return _is_accelerometer_ok; } bool CalibrationImpl::is_magnetometer_calibration_ok() const { std::lock_guard<std::mutex> lock(_calibration_mutex); return _is_magnetometer_ok; } void CalibrationImpl::command_result_callback(MAVLinkCommands::Result command_result, float progress) { std::lock_guard<std::mutex> lock(_calibration_mutex); if (_state == State::NONE) { // It might be someone else like a ground station trying to do a // calibration. We silently ignore it. return; } // If we get a progress result here, it is the new interface and we can // use the progress info. If we get an ack, we need to translate that to // a first progress update, and then parse the statustexts for progress. switch (command_result) { case MAVLinkCommands::Result::SUCCESS: // Silently ignore. break; case MAVLinkCommands::Result::NO_SYSTEM: // FALLTHROUGH case MAVLinkCommands::Result::CONNECTION_ERROR: // FALLTHROUGH case MAVLinkCommands::Result::BUSY: // FALLTHROUGH case MAVLinkCommands::Result::COMMAND_DENIED: // FALLTHROUGH case MAVLinkCommands::Result::UNKNOWN_ERROR: // FALLTHROUGH case MAVLinkCommands::Result::TIMEOUT: // Report all error cases. if (_calibration_callback) { auto calibration_callback_tmp = _calibration_callback; _parent->call_user_callback([calibration_callback_tmp, command_result]() { calibration_callback_tmp( calibration_result_from_command_result(command_result), NAN, ""); }); } _calibration_callback = nullptr; _state = State::NONE; break; case MAVLinkCommands::Result::IN_PROGRESS: if (_calibration_callback) { auto calibration_callback_tmp = _calibration_callback; _parent->call_user_callback([calibration_callback_tmp, command_result, progress]() { calibration_callback_tmp( calibration_result_from_command_result(command_result), progress, ""); }); } break; }; } Calibration::Result CalibrationImpl::calibration_result_from_command_result(MAVLinkCommands::Result result) { switch (result) { case MAVLinkCommands::Result::SUCCESS: return Calibration::Result::SUCCESS; case MAVLinkCommands::Result::NO_SYSTEM: return Calibration::Result::NO_SYSTEM; case MAVLinkCommands::Result::CONNECTION_ERROR: return Calibration::Result::CONNECTION_ERROR; case MAVLinkCommands::Result::BUSY: return Calibration::Result::BUSY; case MAVLinkCommands::Result::COMMAND_DENIED: return Calibration::Result::COMMAND_DENIED; case MAVLinkCommands::Result::TIMEOUT: return Calibration::Result::TIMEOUT; case MAVLinkCommands::Result::IN_PROGRESS: return Calibration::Result::IN_PROGRESS; default: return Calibration::Result::UNKNOWN; } } void CalibrationImpl::receive_param_cal_gyro(bool success, int value) { if (!success) { LogErr() << "Error: Param for gyro cal failed."; return; } bool ok = (value != 0); set_gyro_calibration(ok); } void CalibrationImpl::receive_param_cal_accel(bool success, int value) { if (!success) { LogErr() << "Error: Param for accel cal failed."; return; } bool ok = (value != 0); set_accelerometer_calibration(ok); } void CalibrationImpl::receive_param_cal_mag(bool success, int value) { if (!success) { LogErr() << "Error: Param for mag cal failed."; return; } bool ok = (value != 0); set_magnetometer_calibration(ok); } void CalibrationImpl::set_gyro_calibration(bool ok) { std::lock_guard<std::mutex> lock(_calibration_mutex); _is_gyro_ok = ok; } void CalibrationImpl::set_accelerometer_calibration(bool ok) { std::lock_guard<std::mutex> lock(_calibration_mutex); _is_accelerometer_ok = ok; } void CalibrationImpl::set_magnetometer_calibration(bool ok) { std::lock_guard<std::mutex> lock(_calibration_mutex); _is_magnetometer_ok = ok; } void CalibrationImpl::process_statustext(const mavlink_message_t &message) { std::lock_guard<std::mutex> lock(_calibration_mutex); if (_state == State::NONE) { return; } mavlink_statustext_t statustext; mavlink_msg_statustext_decode(&message, &statustext); _parser.reset(); _parser.parse(statustext.text); switch (_parser.get_status()) { case CalibrationStatustextParser::Status::NONE: // Ignore it. break; case CalibrationStatustextParser::Status::STARTED: report_started(); break; case CalibrationStatustextParser::Status::DONE: report_done(); break; case CalibrationStatustextParser::Status::FAILED: report_failed(_parser.get_failed_message()); break; case CalibrationStatustextParser::Status::CANCELLED: report_cancelled(); break; case CalibrationStatustextParser::Status::PROGRESS: report_progress(_parser.get_progress()); break; case CalibrationStatustextParser::Status::INSTRUCTION: report_instruction(_parser.get_instruction()); break; } switch (_parser.get_status()) { case CalibrationStatustextParser::Status::DONE: // FALLTHROUGH case CalibrationStatustextParser::Status::FAILED: // FALLTHROUGH case CalibrationStatustextParser::Status::CANCELLED: _calibration_callback = nullptr; _state == State::NONE; break; default: break; } } void CalibrationImpl::report_started() { report_progress(0.0f); } void CalibrationImpl::report_done() { if (_calibration_callback) { auto calibration_callback_tmp = _calibration_callback; _parent->call_user_callback([calibration_callback_tmp]() { calibration_callback_tmp(Calibration::Result::SUCCESS, NAN, ""); }); } } void CalibrationImpl::report_failed(const std::string &failed) { LogErr() << "Calibration failed: " << failed; if (_calibration_callback) { auto calibration_callback_tmp = _calibration_callback; _parent->call_user_callback([calibration_callback_tmp]() { calibration_callback_tmp(Calibration::Result::FAILED, NAN, ""); }); } } void CalibrationImpl::report_cancelled() { LogWarn() << "Calibration was cancelled"; if (_calibration_callback) { auto calibration_callback_tmp = _calibration_callback; _parent->call_user_callback([calibration_callback_tmp]() { calibration_callback_tmp(Calibration::Result::CANCELLED, NAN, ""); }); } } void CalibrationImpl::report_progress(float progress) { if (_calibration_callback) { auto calibration_callback_tmp = _calibration_callback; _parent->call_user_callback([calibration_callback_tmp, progress]() { calibration_callback_tmp(Calibration::Result::IN_PROGRESS, progress, ""); }); } } void CalibrationImpl::report_instruction(const std::string &instruction) { if (_calibration_callback) { auto calibration_callback_tmp = _calibration_callback; _parent->call_user_callback([calibration_callback_tmp, instruction]() { calibration_callback_tmp(Calibration::Result::INSTRUCTION, NAN, instruction); }); } } } // namespace dronecore <|endoftext|>
<commit_before>/* ** Copyright 2011-2013 Merethis ** ** This file is part of Centreon Broker. ** ** Centreon Broker is free software: you can redistribute it and/or ** modify it under the terms of the GNU General Public License version 2 ** as published by the Free Software Foundation. ** ** Centreon Broker 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 Centreon Broker. If not, see ** <http://www.gnu.org/licenses/>. */ #include <utility> #include <vector> #include <sstream> #include <QVariant> #include <QSqlError> #include "com/centreon/broker/exceptions/msg.hh" #include "com/centreon/broker/notification/objects/downtime.hh" #include "com/centreon/broker/notification/loaders/downtime_loader.hh" using namespace com::centreon::broker::notification; downtime_loader::downtime_loader() {} void downtime_loader::load(QSqlDatabase* db, downtime_builder* output) { // If we don't have any db or output, don't do anything. if (!db || !output) return; QSqlQuery query(*db); // Performance improvement, as we never go back. query.setForwardOnly(true); if (!query.exec("SELECT downtime_id, entry_time, host_id, service_id, author, cancelled, deletion_time, duration, end_time, fixed, start_time, actual_start_time, actual_end_time, started, triggered_by, type FROM downtimes")) throw (exceptions::msg() << "Notification: cannot select downtimes in loader: " << query.lastError().text()); while (query.next()) { shared_ptr<downtime> down(new downtime); unsigned int downtime_id = query.value(0).toUInt(); down->set_entry_time(query.value(1).toUInt()); down->set_host_id(query.value(2).toUInt()); down->set_service_id(query.value(3).toUInt()); down->set_author(query.value(4).toString().toStdString()); down->set_cancelled(query.value(5).toBool()); down->set_deletion_time(query.value(6).toUInt()); down->set_duration(query.value(7).toUInt()); down->set_end_time(query.value(8).toUInt()); down->set_fixed(query.value(9).toBool()); down->set_start_time(query.value(10).toUInt()); down->set_actual_start_time(query.value(11).toUInt()); down->set_actual_end_time(query.value(12).toUInt()); down->set_started(query.value(13).toBool()); down->set_triggered_by(query.value(14).toUInt()); down->set_type(query.value(15).toInt()); output->add_downtime(downtime_id, down); } } <commit_msg>Update new downtimes from neb.<commit_after>/* ** Copyright 2011-2013 Merethis ** ** This file is part of Centreon Broker. ** ** Centreon Broker is free software: you can redistribute it and/or ** modify it under the terms of the GNU General Public License version 2 ** as published by the Free Software Foundation. ** ** Centreon Broker 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 Centreon Broker. If not, see ** <http://www.gnu.org/licenses/>. */ #include <utility> #include <vector> #include <sstream> #include <QVariant> #include <QSqlError> #include "com/centreon/broker/exceptions/msg.hh" #include "com/centreon/broker/notification/objects/downtime.hh" #include "com/centreon/broker/notification/loaders/downtime_loader.hh" using namespace com::centreon::broker::notification; downtime_loader::downtime_loader() {} void downtime_loader::load(QSqlDatabase* db, downtime_builder* output) { // If we don't have any db or output, don't do anything. if (!db || !output) return; QSqlQuery query(*db); // Performance improvement, as we never go back. query.setForwardOnly(true); if (!query.exec("SELECT downtime_id, entry_time, host_id, service_id, author, cancelled, deletion_time, duration, end_time, fixed, start_time, actual_start_time, actual_end_time, started, triggered_by, type FROM downtimes")) throw (exceptions::msg() << "Notification: cannot select downtimes in loader: " << query.lastError().text()); while (query.next()) { shared_ptr<downtime> down(new downtime); unsigned int downtime_id = query.value(0).toUInt(); down->set_entry_time(query.value(1).toUInt()); down->set_host_id(query.value(2).toUInt()); down->set_service_id(query.value(3).toUInt()); down->set_author(query.value(4).toString().toStdString()); down->set_cancelled(query.value(5).toBool()); down->set_deletion_time(query.value(6).toUInt()); down->set_duration(query.value(7).toUInt()); down->set_end_time(query.value(8).toUInt()); down->set_fixed(query.value(9).toBool()); down->set_start_time(query.value(10).toUInt()); down->set_actual_start_time(query.value(11).toUInt()); down->set_actual_end_time(query.value(12).toUInt()); down->set_started(query.value(13).toBool()); down->set_triggered_by(query.value(14).toUInt()); down->set_type(query.value(15).toInt()); output->add_downtime(downtime_id, down); } } void downtime_loader::new_downtime(neb::downtime& new_downtime, downtime_builder& output) { shared_ptr<downtime> down(new downtime); down->set_actual_end_time(new_downtime.actual_end_time); down->set_actual_start_time(new_downtime.actual_start_time); down->set_author(new_downtime.author.toStdString()); down->set_deletion_time(new_downtime.deletion_time); down->set_duration(new_downtime.duration); down->set_end_time(new_downtime.end_time); down->set_entry_time(new_downtime.entry_time); down->set_fixed(new_downtime.fixed); down->set_host_id(new_downtime.host_id); down->set_service_id(new_downtime.service_id); down->set_start_time(new_downtime.start_time); down->set_triggered_by(new_downtime.triggered_by); output.add_downtime(new_downtime.internal_id, down); } <|endoftext|>
<commit_before>// @(#)root/meta:$Id$ // Author: Rene Brun 13/11/95 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // Global variables class (global variables are obtained from CINT). // // This class describes the attributes of a global variable. // // The TROOT class contains a list of all currently defined global // // variables (accessible via TROOT::GetListOfGlobals()). // // // ////////////////////////////////////////////////////////////////////////// #include "TGlobal.h" #include "TInterpreter.h" ClassImp(TGlobal) //______________________________________________________________________________ TGlobal::TGlobal(DataMemberInfo_t *info) : TDictionary(), fInfo(info) { // Default TGlobal ctor. TGlobals are constructed in TROOT via // a call to TCling::UpdateListOfGlobals(). if (fInfo) { SetName(gCling->DataMemberInfo_Name(fInfo)); SetTitle(gCling->DataMemberInfo_Title(fInfo)); } } //______________________________________________________________________________ TGlobal::TGlobal(const TGlobal &rhs) : TDictionary( ), fInfo(0) { // Copy constructor if (rhs.fInfo) { fInfo = gCling->DataMemberInfo_FactoryCopy(rhs.fInfo); SetName(gCling->DataMemberInfo_Name(fInfo)); SetTitle(gCling->DataMemberInfo_Title(fInfo)); } } //______________________________________________________________________________ TGlobal &TGlobal::operator=(const TGlobal &rhs) { // Assignment operator. if (this != &rhs) { gCling->DataMemberInfo_Delete(fInfo); if (rhs.fInfo) { fInfo = gCling->DataMemberInfo_FactoryCopy(rhs.fInfo); SetName(gCling->DataMemberInfo_Name(fInfo)); SetTitle(gCling->DataMemberInfo_Title(fInfo)); } } return *this; } //______________________________________________________________________________ TGlobal::~TGlobal() { // TGlobal dtor deletes adopted CINT DataMemberInfo object. gCling->DataMemberInfo_Delete(fInfo); } //______________________________________________________________________________ void *TGlobal::GetAddress() const { // Return address of global. return (void *)gCling->DataMemberInfo_Offset(fInfo); } //______________________________________________________________________________ Int_t TGlobal::GetArrayDim() const { // Return number of array dimensions. if (!fInfo) return 0; return gCling->DataMemberInfo_ArrayDim(fInfo); } //______________________________________________________________________________ TDictionary::DeclId_t TGlobal::GetDeclId() const { return gInterpreter->GetDeclId(fInfo); } //______________________________________________________________________________ Int_t TGlobal::GetMaxIndex(Int_t dim) const { // Return maximum index for array dimension "dim". if (!fInfo) return 0; return gCling->DataMemberInfo_MaxIndex(fInfo,dim); } //______________________________________________________________________________ const char *TGlobal::GetTypeName() const { // Get type of global variable, e,g.: "class TDirectory*" -> "TDirectory". // Result needs to be used or copied immediately. if (!fInfo) return 0; return gCling->TypeName(gCling->DataMemberInfo_TypeName(fInfo)); } //______________________________________________________________________________ const char *TGlobal::GetFullTypeName() const { // Get full type description of global variable, e,g.: "class TDirectory*". if (!fInfo) return 0; return gCling->DataMemberInfo_TypeName(fInfo); } //______________________________________________________________________________ Long_t TGlobal::Property() const { // Get property description word. For meaning of bits see EProperty. if (!fInfo) return 0; return gCling->DataMemberInfo_Property(fInfo); } //______________________________________________________________________________ Bool_t TGlobal::Update(DataMemberInfo_t *info) { // Update the TFunction to reflect the new info. // // This can be used to implement unloading (info == 0) and then reloading // (info being the 'new' decl address). if (fInfo) gCling->DataMemberInfo_Delete(fInfo); fInfo = info; if (fInfo) { SetName(gCling->DataMemberInfo_Name(fInfo)); SetTitle(gCling->DataMemberInfo_Title(fInfo)); } return kTRUE; } <commit_msg>doc update<commit_after>// @(#)root/meta:$Id$ // Author: Rene Brun 13/11/95 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // Global variables class (global variables are obtained from CINT). // // This class describes the attributes of a global variable. // // The TROOT class contains a list of all currently defined global // // variables (accessible via TROOT::GetListOfGlobals()). // // // ////////////////////////////////////////////////////////////////////////// #include "TGlobal.h" #include "TInterpreter.h" ClassImp(TGlobal) //______________________________________________________________________________ TGlobal::TGlobal(DataMemberInfo_t *info) : TDictionary(), fInfo(info) { // Default TGlobal ctor. if (fInfo) { SetName(gCling->DataMemberInfo_Name(fInfo)); SetTitle(gCling->DataMemberInfo_Title(fInfo)); } } //______________________________________________________________________________ TGlobal::TGlobal(const TGlobal &rhs) : TDictionary( ), fInfo(0) { // Copy constructor if (rhs.fInfo) { fInfo = gCling->DataMemberInfo_FactoryCopy(rhs.fInfo); SetName(gCling->DataMemberInfo_Name(fInfo)); SetTitle(gCling->DataMemberInfo_Title(fInfo)); } } //______________________________________________________________________________ TGlobal &TGlobal::operator=(const TGlobal &rhs) { // Assignment operator. if (this != &rhs) { gCling->DataMemberInfo_Delete(fInfo); if (rhs.fInfo) { fInfo = gCling->DataMemberInfo_FactoryCopy(rhs.fInfo); SetName(gCling->DataMemberInfo_Name(fInfo)); SetTitle(gCling->DataMemberInfo_Title(fInfo)); } } return *this; } //______________________________________________________________________________ TGlobal::~TGlobal() { // TGlobal dtor deletes adopted CINT DataMemberInfo object. gCling->DataMemberInfo_Delete(fInfo); } //______________________________________________________________________________ void *TGlobal::GetAddress() const { // Return address of global. return (void *)gCling->DataMemberInfo_Offset(fInfo); } //______________________________________________________________________________ Int_t TGlobal::GetArrayDim() const { // Return number of array dimensions. if (!fInfo) return 0; return gCling->DataMemberInfo_ArrayDim(fInfo); } //______________________________________________________________________________ TDictionary::DeclId_t TGlobal::GetDeclId() const { return gInterpreter->GetDeclId(fInfo); } //______________________________________________________________________________ Int_t TGlobal::GetMaxIndex(Int_t dim) const { // Return maximum index for array dimension "dim". if (!fInfo) return 0; return gCling->DataMemberInfo_MaxIndex(fInfo,dim); } //______________________________________________________________________________ const char *TGlobal::GetTypeName() const { // Get type of global variable, e,g.: "class TDirectory*" -> "TDirectory". // Result needs to be used or copied immediately. if (!fInfo) return 0; return gCling->TypeName(gCling->DataMemberInfo_TypeName(fInfo)); } //______________________________________________________________________________ const char *TGlobal::GetFullTypeName() const { // Get full type description of global variable, e,g.: "class TDirectory*". if (!fInfo) return 0; return gCling->DataMemberInfo_TypeName(fInfo); } //______________________________________________________________________________ Long_t TGlobal::Property() const { // Get property description word. For meaning of bits see EProperty. if (!fInfo) return 0; return gCling->DataMemberInfo_Property(fInfo); } //______________________________________________________________________________ Bool_t TGlobal::Update(DataMemberInfo_t *info) { // Update the TFunction to reflect the new info. // // This can be used to implement unloading (info == 0) and then reloading // (info being the 'new' decl address). if (fInfo) gCling->DataMemberInfo_Delete(fInfo); fInfo = info; if (fInfo) { SetName(gCling->DataMemberInfo_Name(fInfo)); SetTitle(gCling->DataMemberInfo_Title(fInfo)); } return kTRUE; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: CartesianCoordinateSystem.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2005-09-08 00:50:30 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _CHART_CARTESIANCOORDINATESYSTEM_HXX #define _CHART_CARTESIANCOORDINATESYSTEM_HXX #include "ServiceMacros.hxx" #ifndef _CPPUHELPER_IMPLBASE2_HXX_ #include <cppuhelper/implbase2.hxx> #endif #ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_ #include <com/sun/star/lang/XServiceInfo.hpp> #endif #ifndef _COM_SUN_STAR_CHART2_XCOORDINATESYSTEM_HPP_ #include <com/sun/star/chart2/XCoordinateSystem.hpp> #endif namespace chart { class CartesianCoordinateSystem : public ::cppu::WeakImplHelper2< ::com::sun::star::lang::XServiceInfo, ::com::sun::star::chart2::XCoordinateSystem > { public: explicit CartesianCoordinateSystem( sal_Int32 nDim = 2 ); virtual ~CartesianCoordinateSystem(); // ____ XCoordinateSystem ____ // ___________________________ /// @see ::com::sun::star::chart2::XCoordinateSystem virtual ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XTransformation > SAL_CALL getTransformationToCartesian() throw (::com::sun::star::uno::RuntimeException); /// @see ::com::sun::star::chart2::XCoordinateSystem virtual ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XTransformation > SAL_CALL getTransformationFromCartesian() throw (::com::sun::star::uno::RuntimeException); /// @see ::com::sun::star::chart2::XCoordinateSystem virtual sal_Int32 SAL_CALL getDimension() throw (::com::sun::star::uno::RuntimeException); virtual ::rtl::OUString SAL_CALL getCoordinateSystemType() throw (::com::sun::star::uno::RuntimeException); virtual ::rtl::OUString SAL_CALL getViewServiceName() throw (::com::sun::star::uno::RuntimeException); APPHELPER_XSERVICEINFO_DECL() private: ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XTransformation > m_aTransformationToCartesian; ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XTransformation > m_aTransformationFromCartesian; sal_Int32 m_nDim; }; } // namespace chart // _CHART_CARTESIANCOORDINATESYSTEM_HXX #endif <commit_msg>INTEGRATION: CWS chart2mst3 (1.2.4); FILE MERGED 2006/04/11 15:41:59 bm 1.2.4.5: make creation of coordinate systems available via factory 2005/10/13 17:38:51 iha 1.2.4.4: renamed BoundedCoordinateSystem to CoordinateSystem 2005/10/07 11:49:41 bm 1.2.4.3: RESYNC: (1.2-1.3); FILE MERGED 2004/09/15 17:32:00 bm 1.2.4.2: API simplification 2004/04/01 10:53:05 bm 1.2.4.1: XChartType: may return a coordinate system now<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: CartesianCoordinateSystem.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: vg $ $Date: 2007-05-22 18:28:28 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _CHART_CARTESIANCOORDINATESYSTEM_HXX #define _CHART_CARTESIANCOORDINATESYSTEM_HXX #include "ServiceMacros.hxx" #include "BaseCoordinateSystem.hxx" namespace chart { class CartesianCoordinateSystem : public BaseCoordinateSystem { public: explicit CartesianCoordinateSystem( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext > & xContext, sal_Int32 nDimensionCount = 2, sal_Bool bSwapXAndYAxis = sal_False ); explicit CartesianCoordinateSystem( const CartesianCoordinateSystem & rSource ); virtual ~CartesianCoordinateSystem(); // ____ XCoordinateSystem ____ virtual ::rtl::OUString SAL_CALL getCoordinateSystemType() throw (::com::sun::star::uno::RuntimeException); virtual ::rtl::OUString SAL_CALL getViewServiceName() throw (::com::sun::star::uno::RuntimeException); // ____ XCloneable ____ virtual ::com::sun::star::uno::Reference< ::com::sun::star::util::XCloneable > SAL_CALL createClone() throw (::com::sun::star::uno::RuntimeException); // ____ XServiceInfo ____ APPHELPER_XSERVICEINFO_DECL() }; class CartesianCoordinateSystem2d : public CartesianCoordinateSystem { public: explicit CartesianCoordinateSystem2d( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext > & xContext ); virtual ~CartesianCoordinateSystem2d(); /// establish methods for factory instatiation APPHELPER_SERVICE_FACTORY_HELPER( CartesianCoordinateSystem2d ) // ____ XServiceInfo ____ APPHELPER_XSERVICEINFO_DECL() }; class CartesianCoordinateSystem3d : public CartesianCoordinateSystem { public: explicit CartesianCoordinateSystem3d( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext > & xContext ); virtual ~CartesianCoordinateSystem3d(); /// establish methods for factory instatiation APPHELPER_SERVICE_FACTORY_HELPER( CartesianCoordinateSystem3d ) // ____ XServiceInfo ____ APPHELPER_XSERVICEINFO_DECL() }; } // namespace chart // _CHART_CARTESIANCOORDINATESYSTEM_HXX #endif <|endoftext|>
<commit_before>#include "stdafx.h" #include <CppUnitTest.h> #include "datastore.h" #include "transaction.h" #include "internal/internal_datastore.h" #include "mocks.h" using Assert = Microsoft::VisualStudio::CppUnitTestFramework::Assert; namespace You { namespace DataStore { namespace UnitTests { /// Unit test for DataStore API that is exposed to Query Engine, namely /// \ref DataStore and \ref Transaction TEST_CLASS(DataStoreApiTest) { public: /// Clears xml document tree and save empty xml file static void clearDataStoreState() { Internal::DataStore::get().document.reset(); Internal::DataStore::get().saveData(); } TEST_METHOD(rollbackDeleteTransactionFromStack) { Transaction sut(DataStore::get().begin()); Assert::AreEqual(1U, Internal::DataStore::get().transactionStack.size()); sut.rollback(); Assert::AreEqual(0U, Internal::DataStore::get().transactionStack.size()); } TEST_METHOD(dataStoreOperationPushedToOperationsQueue) { clearDataStoreState(); Transaction sut(DataStore::get().begin()); DataStore::get().post(0, task1); Assert::AreEqual(1U, sut->operationsQueue.size()); DataStore::get().put(0, task2); Assert::AreEqual(2U, sut->operationsQueue.size()); DataStore::get().erase(0); Assert::AreEqual(3U, sut->operationsQueue.size()); } TEST_METHOD(commitTransactionModifyData) { clearDataStoreState(); Transaction sut(DataStore::get().begin()); DataStore::get().post(0, task1); DataStore::get().post(1, task2); DataStore::get().erase(0); auto sizeBefore = DataStore::get().getAllTasks().size(); sut.commit(); auto sizeAfter = DataStore::get().getAllTasks().size(); Assert::AreEqual(sizeBefore + 1, sizeAfter); } TEST_METHOD(nestedTransactionExecuteOperationsInCorrectOrder) { clearDataStoreState(); Transaction sut(DataStore::get().begin()); DataStore::get().post(0, task1); Transaction sut2(DataStore::get().begin()); DataStore::get().post(1, task2); // Data must not be modified since the first transaction has not been // committed ; { auto sizeBefore = DataStore::get().getAllTasks().size(); sut2.commit(); auto sizeAfter = DataStore::get().getAllTasks().size(); Assert::AreEqual(sizeBefore, sizeAfter); } Transaction sut3(DataStore::get().begin()); DataStore::get().erase(0); // Data must not be modified since the first transaction has not been // committed ; { auto sizeBefore = DataStore::get().getAllTasks().size(); sut3.commit(); auto sizeAfter = DataStore::get().getAllTasks().size(); // Hence, this one should be 1U Assert::AreEqual(sizeAfter, sizeBefore); } // Execute all the operations, with the follow order: // add task 0, add task 1, erase task 0 // Therefore the end result should be sizeBefore + 1 ; { auto sizeBefore = DataStore::get().getAllTasks().size(); sut.commit(); auto sizeAfter = DataStore::get().getAllTasks().size(); Assert::AreEqual(sizeBefore + 1, sizeAfter); } } }; } // namespace UnitTests } // namespace DataStore } // namespace You <commit_msg>Use macro to clear DataStore state<commit_after>#include "stdafx.h" #include <CppUnitTest.h> #include "datastore.h" #include "transaction.h" #include "internal/internal_datastore.h" #include "mocks.h" using Assert = Microsoft::VisualStudio::CppUnitTestFramework::Assert; namespace You { namespace DataStore { namespace UnitTests { /// Unit test for DataStore API that is exposed to Query Engine, namely /// \ref DataStore and \ref Transaction TEST_CLASS(DataStoreApiTest) { public: /// Clears xml document tree and save empty xml file TEST_METHOD_INITIALIZE(clearDataStoreState) { Internal::DataStore::get().document.reset(); Internal::DataStore::get().saveData(); } TEST_METHOD(rollbackDeleteTransactionFromStack) { Transaction sut(DataStore::get().begin()); Assert::AreEqual(1U, Internal::DataStore::get().transactionStack.size()); sut.rollback(); Assert::AreEqual(0U, Internal::DataStore::get().transactionStack.size()); } TEST_METHOD(dataStoreOperationPushedToOperationsQueue) { Transaction sut(DataStore::get().begin()); DataStore::get().post(0, task1); Assert::AreEqual(1U, sut->operationsQueue.size()); DataStore::get().put(0, task2); Assert::AreEqual(2U, sut->operationsQueue.size()); DataStore::get().erase(0); Assert::AreEqual(3U, sut->operationsQueue.size()); } TEST_METHOD(commitTransactionModifyData) { Transaction sut(DataStore::get().begin()); DataStore::get().post(0, task1); DataStore::get().post(1, task2); DataStore::get().erase(0); auto sizeBefore = DataStore::get().getAllTasks().size(); sut.commit(); auto sizeAfter = DataStore::get().getAllTasks().size(); Assert::AreEqual(sizeBefore + 1, sizeAfter); } TEST_METHOD(nestedTransactionExecuteOperationsInCorrectOrder) { Transaction sut(DataStore::get().begin()); DataStore::get().post(0, task1); Transaction sut2(DataStore::get().begin()); DataStore::get().post(1, task2); // Data must not be modified since the first transaction has not been // committed ; { auto sizeBefore = DataStore::get().getAllTasks().size(); sut2.commit(); auto sizeAfter = DataStore::get().getAllTasks().size(); Assert::AreEqual(sizeBefore, sizeAfter); } Transaction sut3(DataStore::get().begin()); DataStore::get().erase(0); // Data must not be modified since the first transaction has not been // committed ; { auto sizeBefore = DataStore::get().getAllTasks().size(); sut3.commit(); auto sizeAfter = DataStore::get().getAllTasks().size(); // Hence, this one should be 1U Assert::AreEqual(sizeAfter, sizeBefore); } // Execute all the operations, with the follow order: // add task 0, add task 1, erase task 0 // Therefore the end result should be sizeBefore + 1 ; { auto sizeBefore = DataStore::get().getAllTasks().size(); sut.commit(); auto sizeAfter = DataStore::get().getAllTasks().size(); Assert::AreEqual(sizeBefore + 1, sizeAfter); } } }; } // namespace UnitTests } // namespace DataStore } // namespace You <|endoftext|>
<commit_before>// Copyright © 2017-2018 Dmitriy Khaustov // // 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. // // Author: Dmitriy Khaustov aka xDimon // Contacts: [email protected] // File created on: 2017.08.17 // ClientPart.cpp #include "ClientPart.hpp" #include "../../src/transport/http/HttpRequestExecutor.hpp" #include "Service.hpp" #include "../../src/transport/Transports.hpp" #include "../../src/telemetry/SysInfo.hpp" #include "../../src/utils/Time.hpp" #include "../../src/storage/DbManager.hpp" #include "../../src/transport/http/HttpContext.hpp" #include "../../src/telemetry/TelemetryManager.hpp" #include <iomanip> status::ClientPart::ClientPart(const std::shared_ptr<::Service>& service) : ServicePart(std::dynamic_pointer_cast<status::Service>(service)) { _name = "client"; _log.setName(service->name() + ":" + _name); _log.setDetail(Log::Detail::TRACE); } void status::ClientPart::init(const Setting& setting) { try { std::string transportName; if (!setting.lookupValue("transport", transportName) || transportName.empty()) { throw std::runtime_error("Field transport undefined or empty"); } std::string uri; if (!setting.lookupValue("uri", uri) || uri.empty()) { throw std::runtime_error("Field uri undefined or empty"); } auto transport = Transports::get(transportName); if (!transport) { throw std::runtime_error(std::string("Transport '") + transportName + "' not found"); } try { transport->bindHandler( uri, std::make_shared<ServerTransport::Handler>( [wp = std::weak_ptr<ClientPart>(std::dynamic_pointer_cast<ClientPart>(ptr()))] (const std::shared_ptr<Context>& context) { auto iam = wp.lock(); if (iam) { iam->handle(context); } } ) ); } catch (const std::exception& exception) { throw std::runtime_error("Can't bind uri '" + uri + "' on transport '" + transportName + "': " + exception.what()); } } catch (const std::exception& exception) { throw std::runtime_error("Fail init part '" + _name + "' ← " + exception.what()); } } void status::ClientPart::handle(const std::shared_ptr<Context>& context) { // Приводим тип контекста auto httpContext = std::dynamic_pointer_cast<HttpContext>(context); if (!httpContext) { throw std::runtime_error("Bad context-type for this service"); } SObj input; try { _log.info("IN %s", httpContext->getRequest()->uri().query().c_str()); auto&& rawInput = SerializerFactory::create("uri")->decode( httpContext->getRequest()->uri().query() ); input = rawInput.is<SObj>() ? dynamic_cast<SObj&>(rawInput) : SObj(); std::ostringstream oss; auto tsStart = std::chrono::system_clock::to_time_t(Time::startTime); tm tmStart{}; ::localtime_r(&tsStart, &tmStart); auto tsNow = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()); tm tmNow{}; ::localtime_r(&tsNow, &tmNow); auto run = tsNow - tsStart; oss << "=============================================\n" << "GENERAL\n" << "\n"; char buff1[40]; std::strftime(buff1, sizeof(buff1), "%Y-%m-%d %X %Z", &tmNow); char buff2[40]; std::strftime(buff2, sizeof(buff2), "%Y-%m-%d %X", &tmStart); oss << "Time now: " << buff1 << "\n" << "Run since: " << buff2 << "\n" // << "Time now: " << std::put_time(&tmNow, "%Y-%m-%d %X %Z") << "\n" // << "Run since: " << std::put_time(&tmStart, "%Y-%m-%d %X") << "\n" << "Running: " << std::setw(9) << std::setfill(' ') << (run/86400) << "d " << std::setw(2) << std::setfill('0') << (run/3600%24) << ":" << std::setw(2) << std::setfill('0') << (run/60%60) << ":" << std::setw(2) << std::setfill('0') << (run%60) << "\n" << "PID: " << std::setw(7) << std::setfill(' ') << getpid() << "\n" << "\n"; oss << "=============================================\n" << "RESOURCES\n" << "\n"; if (SysInfo::getInstance()._run) { oss << "CPU current usage: " << std::setw(7) << std::setfill(' ') << std::fixed << std::setprecision(3) << SysInfo::getInstance()._cpuUsageOnPercent->avgPerSec(std::chrono::seconds(15)) << " %\n" << "Physical memory current usage: " << std::setw(7) << std::setfill(' ') << std::fixed << std::setprecision(0) << SysInfo::getInstance()._memoryUsage->avg(std::chrono::seconds(15)) << " kB\n" << "\n" << "User CPU time used: " << std::setw(7) << std::setfill(' ') << std::fixed << std::setprecision(3) << SysInfo::getInstance()._cpuUsageByUserOnTime->sum(1) << " s\n" << "System CPU time used: " << std::setw(7) << std::setfill(' ') << std::fixed << std::setprecision(3) << SysInfo::getInstance()._cpuUsageBySystemOnTime->sum(1) << " s\n" << "Maximum resident set size: " << std::setw(7) << std::setfill(' ') << std::fixed << std::setprecision(0) << SysInfo::getInstance()._memoryMaxUsage->sum(1) << " kB\n" << "Soft/hard page faults: " << std::setw(7) << std::setfill(' ') << std::fixed << std::setprecision(0) << SysInfo::getInstance()._pageSoftFaults->sum(1) << "/" << SysInfo::getInstance()._pageHardFaults->avg(1) << "\n" << "Block input/output operations: " << std::setw(7) << std::setfill(' ') << std::fixed << std::setprecision(0) << SysInfo::getInstance()._blockInputOperations->sum(1) << "/" << SysInfo::getInstance()._blockOutputOperations->avg(1) << "\n" << "Vol./Invol. context switches: " << std::setw(7) << std::setfill(' ') << std::fixed << std::setprecision(0) << SysInfo::getInstance()._voluntaryContextSwitches->sum(1) << "/" << SysInfo::getInstance()._involuntaryContextSwitches->avg(1) << "\n" << "\n"; } else { oss << "SysInfo wasn't run...\n\n"; } oss << "=============================================\n" << "DATABASE\n" << "\n"; DbManager::forEach([&oss](const std::shared_ptr<DbConnectionPool>& pool){ auto queryCount = pool->metricAvgQueryPerSec->sum(std::chrono::seconds(15)); oss << "---------------------------------------------\n" << "[" << pool->name() << "]\n" << "All connections: " << std::setw(7) << std::setfill(' ') << std::fixed << std::setprecision(0) << pool->metricConnectCount->sum(1) << "\n" << "Successful queries: " << std::setw(7) << std::setfill(' ') << std::fixed << std::setprecision(0) << pool->metricSuccessQueryCount->sum(1) << "\n" << "Fail queries: " << std::setw(7) << std::setfill(' ') << std::fixed << std::setprecision(0) << pool->metricFailQueryCount->sum(1) << "\n" << "Current avg execution speed: " << std::setw(7) << std::setfill(' ') << std::fixed << std::setprecision(3) << (queryCount/15) << " qps\n" << "Current avg execution time: " << std::setw(7) << std::setfill(' ') << std::fixed << std::setprecision(3) << (queryCount>0 ? (pool->metricAvgExecutionTime->sum(std::chrono::seconds(15))/queryCount)*1000 : 0) << " ms\n" << "\n"; }); oss << "=============================================\n" << "TRANSPORT\n" << "\n"; Transports::forEach([&oss](const std::shared_ptr<ServerTransport>& transport){ auto requestCount = transport->metricAvgRequestPerSec->sum(std::chrono::seconds(15)); oss << "---------------------------------------------\n" << "[" << transport->name() << "]\n" << "All connections: " << std::setw(7) << std::setfill(' ') << std::fixed << std::setprecision(0) << transport->metricConnectCount->sum(1) << "\n" << "Request received : " << std::setw(7) << std::setfill(' ') << std::fixed << std::setprecision(0) << transport->metricRequestCount->sum(1) << "\n" << "Current avg execution speed: " << std::setw(7) << std::setfill(' ') << std::fixed << std::setprecision(3) << (requestCount/15) << " rps\n" << "Current avg execution time: " << std::setw(7) << std::setfill(' ') << std::fixed << std::setprecision(3) << (requestCount>0 ? (transport->metricAvgExecutionTime->sum(std::chrono::seconds(15))/requestCount)*1000 : 0) << " ms\n" << "\n"; }); oss << "=============================================\n" << "RAW METRICS\n" << "\n"; oss << std::setw(51) << std::left << std::setfill(' ') << "NAME" << std::setw(11) << std::right << std::setfill(' ') << "Sum" << std::setw(11) << std::right << std::setfill(' ') << "Sum 15s" << std::setw(11) << std::right << std::setfill(' ') << "Average" << std::setw(11) << std::right << std::setfill(' ') << "Avg 15s" << std::setw(11) << std::right << std::setfill(' ') << "Avg 1/sec" << "\n"; for (auto i : TelemetryManager::metrics()) { oss << std::setw(50) << std::left << std::setfill(' ') << i.first << " " << std::setw(10) << std::right << std::setfill(' ') << std::fixed << i.second->sum(1) << " " << std::setw(10) << std::right << std::setfill(' ') << std::fixed << i.second->sum(std::chrono::seconds(15)) << " " << std::setw(10) << std::right << std::setfill(' ') << std::fixed << i.second->avg(1) << " " << std::setw(10) << std::right << std::setfill(' ') << std::fixed << i.second->avg(std::chrono::seconds(15)) << " " << std::setw(10) << std::right << std::setfill(' ') << std::fixed << i.second->avgPerSec(std::chrono::seconds(15)) << "\n"; } oss << "=============================================\n"; auto out = oss.str(); httpContext->transmit(out.c_str(), out.length(), "text/pain; charset=utf-8", true); _log.info("OUT Send status info (load=%0.03f%%)", SysInfo::getInstance()._cpuUsageOnPercent->avgPerSec(std::chrono::seconds(15))); } catch (const std::exception& exception) { auto serializer = SerializerFactory::create("json"); SObj output; output.emplace("status", false); output.emplace("message", exception.what()); if (!input.empty()) { output.emplace("receivedData", serializer->encode(input)); } std::string out(serializer->encode(output)); httpContext->transmit(out.c_str(), out.length(), "text/plain; charset=utf-8", true); _log.info("OUT %s", out.c_str()); return; } } <commit_msg>Little change<commit_after>// Copyright © 2017-2018 Dmitriy Khaustov // // 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. // // Author: Dmitriy Khaustov aka xDimon // Contacts: [email protected] // File created on: 2017.08.17 // ClientPart.cpp #include "ClientPart.hpp" #include "../../src/transport/http/HttpRequestExecutor.hpp" #include "Service.hpp" #include "../../src/transport/Transports.hpp" #include "../../src/telemetry/SysInfo.hpp" #include "../../src/utils/Time.hpp" #include "../../src/storage/DbManager.hpp" #include "../../src/transport/http/HttpContext.hpp" #include "../../src/telemetry/TelemetryManager.hpp" #include <iomanip> status::ClientPart::ClientPart(const std::shared_ptr<::Service>& service) : ServicePart(std::dynamic_pointer_cast<status::Service>(service)) { _name = "client"; _log.setName(service->name() + ":" + _name); _log.setDetail(Log::Detail::TRACE); } void status::ClientPart::init(const Setting& setting) { try { std::string transportName; if (!setting.lookupValue("transport", transportName) || transportName.empty()) { throw std::runtime_error("Field transport undefined or empty"); } std::string uri; if (!setting.lookupValue("uri", uri) || uri.empty()) { throw std::runtime_error("Field uri undefined or empty"); } auto transport = Transports::get(transportName); if (!transport) { throw std::runtime_error(std::string("Transport '") + transportName + "' not found"); } try { transport->bindHandler( uri, std::make_shared<ServerTransport::Handler>( [wp = std::weak_ptr<ClientPart>(std::dynamic_pointer_cast<ClientPart>(ptr()))] (const std::shared_ptr<Context>& context) { auto iam = wp.lock(); if (iam) { iam->handle(context); } } ) ); } catch (const std::exception& exception) { throw std::runtime_error("Can't bind uri '" + uri + "' on transport '" + transportName + "': " + exception.what()); } } catch (const std::exception& exception) { throw std::runtime_error("Fail init part '" + _name + "' ← " + exception.what()); } } void status::ClientPart::handle(const std::shared_ptr<Context>& context) { // Приводим тип контекста auto httpContext = std::dynamic_pointer_cast<HttpContext>(context); if (!httpContext) { throw std::runtime_error("Bad context-type for this service"); } SObj input; try { _log.info("IN %s", httpContext->getRequest()->uri().query().c_str()); auto&& rawInput = SerializerFactory::create("uri")->decode( httpContext->getRequest()->uri().query() ); input = rawInput.is<SObj>() ? dynamic_cast<SObj&>(rawInput) : SObj(); std::ostringstream oss; auto tsStart = std::chrono::system_clock::to_time_t(Time::startTime); tm tmStart{}; ::localtime_r(&tsStart, &tmStart); auto tsNow = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()); tm tmNow{}; ::localtime_r(&tsNow, &tmNow); auto run = tsNow - tsStart; oss << "=============================================\n" << "GENERAL\n" << "\n"; char buff1[40]; std::strftime(buff1, sizeof(buff1), "%Y-%m-%d %X %Z", &tmNow); char buff2[40]; std::strftime(buff2, sizeof(buff2), "%Y-%m-%d %X", &tmStart); oss << "Time now: " << buff1 << "\n" << "Run since: " << buff2 << "\n" // << "Time now: " << std::put_time(&tmNow, "%Y-%m-%d %X %Z") << "\n" // << "Run since: " << std::put_time(&tmStart, "%Y-%m-%d %X") << "\n" << "Running: " << std::setw(9) << std::setfill(' ') << (run/86400) << "d " << std::setw(2) << std::setfill('0') << (run/3600%24) << ":" << std::setw(2) << std::setfill('0') << (run/60%60) << ":" << std::setw(2) << std::setfill('0') << (run%60) << "\n" << "PID: " << std::setw(7) << std::setfill(' ') << getpid() << "\n" << "\n"; oss << "=============================================\n" << "RESOURCES\n" << "\n"; if (SysInfo::getInstance()._run) { oss << "CPU current usage: " << std::setw(7) << std::setfill(' ') << std::fixed << std::setprecision(3) << SysInfo::getInstance()._cpuUsageOnPercent->avgPerSec(std::chrono::seconds(15)) << " %\n" << "Physical memory current usage: " << std::setw(7) << std::setfill(' ') << std::fixed << std::setprecision(0) << SysInfo::getInstance()._memoryUsage->avg(std::chrono::seconds(15)) << " kB\n" << "\n" << "User CPU time used: " << std::setw(7) << std::setfill(' ') << std::fixed << std::setprecision(3) << SysInfo::getInstance()._cpuUsageByUserOnTime->sum(1) << " s\n" << "System CPU time used: " << std::setw(7) << std::setfill(' ') << std::fixed << std::setprecision(3) << SysInfo::getInstance()._cpuUsageBySystemOnTime->sum(1) << " s\n" << "Maximum resident set size: " << std::setw(7) << std::setfill(' ') << std::fixed << std::setprecision(0) << SysInfo::getInstance()._memoryMaxUsage->sum(1) << " kB\n" << "Soft/hard page faults: " << std::setw(7) << std::setfill(' ') << std::fixed << std::setprecision(0) << SysInfo::getInstance()._pageSoftFaults->sum(1) << "/" << SysInfo::getInstance()._pageHardFaults->avg(1) << "\n" << "Block input/output operations: " << std::setw(7) << std::setfill(' ') << std::fixed << std::setprecision(0) << SysInfo::getInstance()._blockInputOperations->sum(1) << "/" << SysInfo::getInstance()._blockOutputOperations->avg(1) << "\n" << "Vol./Invol. context switches: " << std::setw(7) << std::setfill(' ') << std::fixed << std::setprecision(0) << SysInfo::getInstance()._voluntaryContextSwitches->sum(1) << "/" << SysInfo::getInstance()._involuntaryContextSwitches->avg(1) << "\n" << "\n"; } else { oss << "SysInfo wasn't run...\n\n"; } oss << "=============================================\n" << "DATABASE\n" << "\n"; DbManager::forEach([&oss](const std::shared_ptr<DbConnectionPool>& pool){ auto queryCount = pool->metricAvgQueryPerSec->sum(std::chrono::seconds(15)); oss << "---------------------------------------------\n" << "[" << pool->name() << "]\n" << "All connections: " << std::setw(7) << std::setfill(' ') << std::fixed << std::setprecision(0) << pool->metricConnectCount->sum(1) << "\n" << "Successful queries: " << std::setw(7) << std::setfill(' ') << std::fixed << std::setprecision(0) << pool->metricSuccessQueryCount->sum(1) << "\n" << "Fail queries: " << std::setw(7) << std::setfill(' ') << std::fixed << std::setprecision(0) << pool->metricFailQueryCount->sum(1) << "\n" << "Current avg execution speed: " << std::setw(7) << std::setfill(' ') << std::fixed << std::setprecision(3) << (queryCount/15) << " qps\n" << "Current avg execution time: " << std::setw(7) << std::setfill(' ') << std::fixed << std::setprecision(3) << (queryCount>0 ? (pool->metricAvgExecutionTime->sum(std::chrono::seconds(15))/queryCount)*1000 : 0) << " ms\n" << "\n"; }); oss << "=============================================\n" << "TRANSPORT\n" << "\n"; Transports::forEach([&oss](const std::shared_ptr<ServerTransport>& transport){ auto requestCount = transport->metricAvgRequestPerSec->sum(std::chrono::seconds(15)); oss << "---------------------------------------------\n" << "[" << transport->name() << "]\n" << "All connections: " << std::setw(7) << std::setfill(' ') << std::fixed << std::setprecision(0) << transport->metricConnectCount->sum(1) << "\n" << "Request received : " << std::setw(7) << std::setfill(' ') << std::fixed << std::setprecision(0) << transport->metricRequestCount->sum(1) << "\n" << "Current avg execution speed: " << std::setw(7) << std::setfill(' ') << std::fixed << std::setprecision(3) << (requestCount/15) << " rps\n" << "Current avg execution time: " << std::setw(7) << std::setfill(' ') << std::fixed << std::setprecision(3) << (requestCount>0 ? (transport->metricAvgExecutionTime->sum(std::chrono::seconds(15))/requestCount)*1000 : 0) << " ms\n" << "\n"; }); oss << "=============================================\n" << "RAW METRICS\n" << "\n"; oss << std::setw(51) << std::left << std::setfill(' ') << "NAME" << std::setw(11) << std::right << std::setfill(' ') << "Sum" << std::setw(11) << std::right << std::setfill(' ') << "Sum 15s" << std::setw(11) << std::right << std::setfill(' ') << "Average" << std::setw(11) << std::right << std::setfill(' ') << "Avg 15s" << std::setw(11) << std::right << std::setfill(' ') << "Avg 1/sec" << "\n"; for (auto i : TelemetryManager::metrics()) { oss << std::setw(50) << std::left << std::setfill(' ') << i.first << " " << std::setw(10) << std::right << std::setfill(' ') << std::fixed << i.second->sum(1) << " " << std::setw(10) << std::right << std::setfill(' ') << std::fixed << i.second->sum(std::chrono::seconds(15)) << " " << std::setw(10) << std::right << std::setfill(' ') << std::fixed << i.second->avg(1) << " " << std::setw(10) << std::right << std::setfill(' ') << std::fixed << i.second->avg(std::chrono::seconds(15)) << " " << std::setw(10) << std::right << std::setfill(' ') << std::fixed << i.second->avgPerSec(std::chrono::seconds(15)) << "\n"; } oss << "=============================================\n"; auto out = oss.str(); httpContext->transmit(out, "text/pain; charset=utf-8", true); _log.info("OUT Send status info (load=%0.03f%%)", SysInfo::getInstance()._cpuUsageOnPercent->avgPerSec(std::chrono::seconds(15))); } catch (const std::exception& exception) { auto serializer = SerializerFactory::create("json"); SObj output; output.emplace("status", false); output.emplace("message", exception.what()); if (!input.empty()) { output.emplace("receivedData", serializer->encode(input)); } std::string out(serializer->encode(output)); httpContext->transmit(out, "text/plain; charset=utf-8", true); _log.info("OUT %s", out.c_str()); return; } } <|endoftext|>
<commit_before>/* * Copyright(c) Sophist Solutions, Inc. 1990-2016. All rights reserved */ #include "../StroikaPreComp.h" #include "../IO/FileAccessException.h" #include "Exceptions.h" #include "ErrNoException.h" using namespace Stroika; using namespace Stroika::Foundation; using namespace Characters; using namespace Execution; using Debug::TraceContextBumper; /* ******************************************************************************** ***************************** errno_ErrorException ***************************** ******************************************************************************** */ errno_ErrorException::errno_ErrorException (Execution::errno_t e) : StringException (SDKString2Wide (LookupMessage (e))) , fError (e) { } SDKString errno_ErrorException::LookupMessage (Execution::errno_t e) { SDKChar buf[2048]; buf[0] = '\0'; #if qPlatform_Windows if (::_tcserror_s (buf, e) != 0) { return buf; } (void)::_stprintf_s (buf, SDKSTR ("errno_t error code: 0x%x"), e); #elif qPlatform_POSIX /* * A bit quirky - gcc and POSIX handle this API fairly differently. Hopefully I have both cases correct??? */ #if (defined (_XOPEN_SOURCE) && _XOPEN_SOURCE >= 600) && !defined (_GNU_SOURCE) if (::strerror_r (e, buf, NEltsOf (buf)) == 0) { return buf; } #else char* res = nullptr; if ((res = ::strerror_r (e, buf, NEltsOf (buf))) != nullptr) { return res; } #endif (void) ::snprintf (buf, NEltsOf (buf), SDKSTR ("errno_t error code: 0x%x"), e); #else AssertNotImplemented (); #endif return buf; } [[noreturn]] void errno_ErrorException::Throw (Execution::errno_t error) { //REVIEW EXCPETIONS ANMD MPAPING - THIS IS NOT GOOD - NOT EVEN CLOSE!!! -- LGP 2011-09-29 switch (error) { case ENOMEM: { Execution::Throw (bad_alloc (), "errno_ErrorException::Throw (ENOMEM) - throwing bad_alloc"); } case ENOENT: { Execution::Throw (IO::FileAccessException ()); // don't know if they were reading or writing at this level..., and don't know file name... } case EACCES: { Execution::Throw (IO::FileAccessException ()); // don't know if they were reading or writing at this level..., and don't know file name... } // If I decide to pursue mapping, this maybe a good place to start // http://aplawrence.com/Unixart/errors.html // -- LGP 2009-01-02 #if 0 case EPERM: { // not sure any point in this unification. Maybe if I added my OWN private 'access denied' exception // the mapping/unification would make sense. // -- LGP 2009-01-02 DbgTrace ("errno_ErrorException::Throw (EPERM) - throwing ERROR_ACCESS_DENIED"); throw Win32Exception (ERROR_ACCESS_DENIED); } #endif } DbgTrace (L"errno_ErrorException (0x%x - %s) - throwing errno_ErrorException", error, SDKString2Wide (LookupMessage (error)).c_str ()); throw errno_ErrorException (error); } <commit_msg>strerror_r support for macos<commit_after>/* * Copyright(c) Sophist Solutions, Inc. 1990-2016. All rights reserved */ #include "../StroikaPreComp.h" #include "../IO/FileAccessException.h" #include "Exceptions.h" #include "ErrNoException.h" using namespace Stroika; using namespace Stroika::Foundation; using namespace Characters; using namespace Execution; using Debug::TraceContextBumper; /* ******************************************************************************** ***************************** errno_ErrorException ***************************** ******************************************************************************** */ errno_ErrorException::errno_ErrorException (Execution::errno_t e) : StringException (SDKString2Wide (LookupMessage (e))) , fError (e) { } SDKString errno_ErrorException::LookupMessage (Execution::errno_t e) { SDKChar buf[2048]; buf[0] = '\0'; #if qPlatform_Windows if (::_tcserror_s (buf, e) != 0) { return buf; } (void)::_stprintf_s (buf, SDKSTR ("errno_t error code: 0x%x"), e); #elif qPlatform_POSIX /* * A bit quirky - gcc and POSIX handle this API fairly differently. Hopefully I have both cases correct??? */ #if (defined (_XOPEN_SOURCE) && _XOPEN_SOURCE >= 600) && !defined (_GNU_SOURCE) if (::strerror_r (e, buf, NEltsOf (buf)) == 0) { return buf; } #else if (::strerror_r (e, buf, NEltsOf (buf)) == 0) { return buf; } #endif (void) ::snprintf (buf, NEltsOf (buf), SDKSTR ("errno_t error code: 0x%x"), e); #else AssertNotImplemented (); #endif return buf; } [[noreturn]] void errno_ErrorException::Throw (Execution::errno_t error) { //REVIEW EXCPETIONS ANMD MPAPING - THIS IS NOT GOOD - NOT EVEN CLOSE!!! -- LGP 2011-09-29 switch (error) { case ENOMEM: { Execution::Throw (bad_alloc (), "errno_ErrorException::Throw (ENOMEM) - throwing bad_alloc"); } case ENOENT: { Execution::Throw (IO::FileAccessException ()); // don't know if they were reading or writing at this level..., and don't know file name... } case EACCES: { Execution::Throw (IO::FileAccessException ()); // don't know if they were reading or writing at this level..., and don't know file name... } // If I decide to pursue mapping, this maybe a good place to start // http://aplawrence.com/Unixart/errors.html // -- LGP 2009-01-02 #if 0 case EPERM: { // not sure any point in this unification. Maybe if I added my OWN private 'access denied' exception // the mapping/unification would make sense. // -- LGP 2009-01-02 DbgTrace ("errno_ErrorException::Throw (EPERM) - throwing ERROR_ACCESS_DENIED"); throw Win32Exception (ERROR_ACCESS_DENIED); } #endif } DbgTrace (L"errno_ErrorException (0x%x - %s) - throwing errno_ErrorException", error, SDKString2Wide (LookupMessage (error)).c_str ()); throw errno_ErrorException (error); } <|endoftext|>
<commit_before>#pragma once #ifndef GUIENVIRONMENT_HPP #define GUIENVIRONMENT_HPP #include <SFML/Graphics.hpp> #include <vector> #include <memory> #include <string> namespace gsf { class Widget; } namespace gsf { class GUIEnvironment : public sf::Drawable { private: const sf::RenderWindow &m_window; std::vector<Widget::Ptr> m_widgets; // Special Widgets are widgets which belongs to other widgets and are parts // of them (e.g. a ComboBoxWidget shows a ListBoxWidget when it was clicked) //std::vector<Widget*> m_specialWidgets; // Is true when ever the mouse is inside the window and false // when the mouse is outside bool m_isMouseInWindow; bool m_isWindowFocused; // If it is enabled window can rought out of the Render Window //bool m_isWindowRoughOutEnabled; public: explicit GUIEnvironment(const sf::RenderWindow &m_window); ~GUIEnvironment(); void addWidget(Widget::Ptr widget); Widget::Ptr removeWidget(const Widget& widget); sf::View getCurrentView() const; // Return a pointer to the widget with the given id. If there are more then // one Widget with the given id, the method return the first occurrence. // When there is no occurrence nullptr is returned Widget* getWidgetByID(const std::string &id) const; /* void addSpecialWidget(Widget *widget); void removeSpecialWidget(const Widget *widget); */ //void setIsWindowRoughOutEnabled(bool isEnabled); //bool isWindowRoughOutEnabled() const; void handleEvent(sf::Event &event); void update(float dt); void draw(sf::RenderTarget &target, sf::RenderStates states) const override; private: // Place the Widget depending on its Orientation void placeWidget(Widget *widget); }; } #endif // GUIENVIRONMENT_HPP <commit_msg>Start scene creation<commit_after>#pragma once #ifndef GUIENVIRONMENT_HPP #define GUIENVIRONMENT_HPP #include <SFML/Graphics.hpp> #include <vector> #include <memory> #include <string> namespace gsf { class Widget; } namespace gsf { class GUIEnvironment : public sf::Drawable { private: const sf::RenderWindow &m_window; std::vector<Widget::Ptr> m_widgets; // Special Widgets are widgets which belongs to other widgets and are parts // of them (e.g. a ComboBoxWidget shows a ListBoxWidget when it was clicked) //std::vector<Widget*> m_specialWidgets; // Is true when ever the mouse is inside the window and false // when the mouse is outside bool m_isMouseInWindow; bool m_isWindowFocused; // If it is enabled window can rought out of the Render Window //bool m_isWindowRoughOutEnabled; public: explicit GUIEnvironment(const sf::RenderWindow &m_window); ~GUIEnvironment(); void addWidget(Widget::Ptr widget); Widget::Ptr removeWidget(const Widget& widget); // Create a scene with the specified scene xml file void createScene(const std::string &path); sf::View getCurrentView() const; // Return a pointer to the widget with the given id. If there are more then // one Widget with the given id, the method return the first occurrence. // When there is no occurrence nullptr is returned Widget* getWidgetByID(const std::string &id) const; /* void addSpecialWidget(Widget *widget); void removeSpecialWidget(const Widget *widget); */ //void setIsWindowRoughOutEnabled(bool isEnabled); //bool isWindowRoughOutEnabled() const; void handleEvent(sf::Event &event); void update(float dt); void draw(sf::RenderTarget &target, sf::RenderStates states) const override; private: // Place the Widget depending on its Orientation void placeWidget(Widget *widget); }; } #endif // GUIENVIRONMENT_HPP <|endoftext|>
<commit_before>/* * MarketDataStore.h * * Created on: Jul 18, 2015 * Author: felix */ #ifndef MARKETDATAPIPE_HPP_ #define MARKETDATAPIPE_HPP_ #include <OmdMessage.hpp> #include <boost/asio.hpp> #include <boost/lockfree/spsc_queue.hpp> #include <boost/thread/mutex.hpp> #include <boost/thread/condition_variable.hpp> namespace meteor { namespace core { struct market_data_message { meteor::omd::packet_buffer buffer; boost::asio::ip::udp::endpoint senderEndpoint; }__attribute((aligned(4))); class MarketDataPipe { public: boost::lockfree::spsc_queue<market_data_message, boost::lockfree::capacity<1000000>> queue; // No encapsulation // Let the programmers knows what they are doing boost::mutex queueLock; boost::condition_variable queueNotEmpty; }; } } #endif /* MARKETDATAPIPE_HPP_ */ <commit_msg>changing namespaces and project names<commit_after>/* * MarketDataStore.h * * Created on: Jul 18, 2015 * Author: felix */ #ifndef MARKETDATAPIPE_HPP_ #define MARKETDATAPIPE_HPP_ #include <OmdMessage.hpp> #include <boost/asio.hpp> #include <boost/lockfree/spsc_queue.hpp> #include <boost/thread/mutex.hpp> #include <boost/thread/condition_variable.hpp> namespace meteor { namespace core { struct market_data_message { meteor::omd::packet_buffer buffer; boost::asio::ip::udp::endpoint senderEndpoint; }__attribute((aligned(4))); class MarketDataPipe { public: boost::lockfree::spsc_queue<market_data_message, boost::lockfree::capacity<10000>> queue; // No encapsulation // Let the programmers knows what they are doing boost::mutex queueLock; boost::condition_variable queueNotEmpty; }; } } #endif /* MARKETDATAPIPE_HPP_ */ <|endoftext|>
<commit_before>#ifndef __CALCULATE_NODE_HPP__ #define __CALCULATE_NODE_HPP__ #include <iterator> #include <ostream> #include <stack> #include <sstream> #include "symbol.hpp" #include "util.hpp" namespace calculate { template<typename Parser> class Node { friend struct std::hash<Node>; friend Parser; public: using Lexer = typename Parser::Lexer; using Type = typename Parser::Type; using Symbol = Symbol<Node>; using SymbolType = typename Symbol::SymbolType; public: using const_iterator = typename std::vector<Node>::const_iterator; class VariableHandler { public: const std::vector<std::string> variables; private: std::size_t _size; std::unique_ptr<Type[]> _values; void _update(std::size_t) const {} template<typename Last> void _update(std::size_t n, Last last) { _values[n] = last; } template<typename Head, typename... Args> void _update(std::size_t n, Head head, Args... args) { _values[n] = head; _update(n + 1, args...); } public: explicit VariableHandler( const std::vector<std::string>& keys, Lexer& lexer ) : variables{keys}, _size{keys.size()}, _values{std::make_unique<Type[]>(_size)} { std::unordered_set<std::string> singles{keys.begin(), keys.end()}; for (const auto &variable : keys) { if (!std::regex_match(variable, lexer.name_regex)) throw UnsuitableName{variable}; else if (singles.erase(variable) == 0) throw RepeatedSymbol{variable}; } } std::size_t index(const std::string& token) const { auto found = std::find(variables.begin(), variables.end(), token); if (found != variables.end()) return found - variables.begin(); throw UndefinedSymbol{token}; } Type& at(const std::string& token) const { return _values[index(token)]; } void update(const std::vector<Type>& values) { if (_size != values.size()) throw ArgumentsMismatch{_size, values.size()}; for (std::size_t i = 0; i < _size; i++) _values[i] = values[i]; } template<typename... Args> void update(Args... args) { if (_size != sizeof...(args)) throw ArgumentsMismatch{_size, sizeof...(args)}; _update(0, args...); } }; private: std::shared_ptr<Lexer> _lexer; std::shared_ptr<VariableHandler> _variables; std::string _token; std::unique_ptr<Symbol> _symbol; std::vector<Node> _nodes; std::size_t _hash; Node() = delete; explicit Node( const std::shared_ptr<Lexer>& _lexer, const std::shared_ptr<VariableHandler>& variables, const std::string& token, std::unique_ptr<Symbol>&& symbol, std::vector<Node>&& nodes, std::size_t hash ) : _lexer{_lexer}, _variables{variables}, _token{token}, _symbol{std::move(symbol)}, _nodes{std::move(nodes)}, _hash{hash} { if (_nodes.size() != _symbol->arguments()) throw ArgumentsMismatch{ _token, _nodes.size(), _symbol->arguments() }; } std::vector<std::string> _pruned() const noexcept { std::istringstream extractor{postfix()}; std::vector<std::string> tokens{ std::istream_iterator<std::string>{extractor}, std::istream_iterator<std::string>{} }; std::vector<std::string> pruned{}; for (const auto& variable : variables()) if ( std::find(tokens.begin(), tokens.end(), variable) != tokens.end() ) pruned.push_back(variable); pruned.erase(std::unique(pruned.begin(), pruned.end()), pruned.end()); return pruned; } void _rebind(const std::shared_ptr<VariableHandler>& context) noexcept { _variables = context; for (auto& node : _nodes) node._rebind(context); } public: Node(const Node& other) noexcept : _lexer{other._lexer}, _variables{}, _token{other._token}, _symbol{other._symbol->clone()}, _nodes{other._nodes}, _hash{other._hash} { _rebind(std::make_shared<VariableHandler>(other._pruned(), *_lexer)); } Node(Node&& other) noexcept : _lexer{std::move(other._lexer)}, _variables{std::move(other._variables)}, _token{std::move(other._token)}, _symbol{std::move(other._symbol)}, _nodes{std::move(other._nodes)}, _hash{std::move(other._hash)} {} const Node& operator=(Node other) noexcept { swap(*this, other); return *this; } friend void swap(Node& one, Node& another) noexcept { using std::swap; swap(one._lexer, another._lexer); swap(one._variables, another._variables); swap(one._token, another._token); swap(one._symbol, another._symbol); swap(one._nodes, another._nodes); } explicit operator Type() const { if (variables().size() > 0) throw ArgumentsMismatch{variables().size(), 0}; return _symbol->evaluate(_nodes); } Type operator()(const std::vector<Type>& values) const { _variables->update(values); return _symbol->evaluate(_nodes); } template<typename... Args> Type operator()(Args&&... args) const { _variables->update(std::forward<Args>(args)...); return _symbol->evaluate(_nodes); } bool operator==(const Node& other) const noexcept { std::stack<std::pair<const_iterator, const_iterator>> these{}; std::stack<const_iterator> those{}; auto equal = [&](auto left, auto right) { try { return left->_variables->index(left->_token) == right->_variables->index(right->_token); } catch (const UndefinedSymbol&) { if (left->_symbol == right->_symbol) return true; return *(left->_symbol) == *(right->_symbol); } }; if (!equal(this, &other)) return false; these.push({this->begin(), this->end()}); those.push(other.begin()); while(!these.empty()) { auto one = these.top(); auto another = those.top(); these.pop(); those.pop(); if (one.first != one.second) { if (!equal(one.first, another)) return false; these.push({one.first->begin(), one.first->end()}); these.push({one.first + 1, one.second}); those.push(another->begin()); those.push(another + 1); } } return true; } bool operator!=(const Node& other) const noexcept { return !operator==(other); } const Node& operator[](std::size_t index) const { return _nodes[index]; } const Node& at(std::size_t index) const { return _nodes.at(index); } const_iterator begin() const noexcept { return _nodes.begin(); } const_iterator end() const noexcept { return _nodes.end(); } friend std::ostream& operator<<( std::ostream& ostream, const Node& node ) noexcept { ostream << node.infix(); return ostream; } static Type evaluate(const Node& node) { return node._symbol->evaluate(node._nodes); } const Lexer& lexer() const noexcept { return *_lexer; } const std::string& token() const noexcept { return _token; } SymbolType symbol() const noexcept { return _symbol->symbol(); } std::size_t branches() const noexcept { return _nodes.size(); } std::string infix() const noexcept { using Operator = Operator<Node>; using Associativity = typename Operator::Associativity; std::string infix{}; auto brace = [&](std::size_t i) { const auto& node = _nodes[i]; if (node._symbol->symbol() == SymbolType::OPERATOR) { auto po = static_cast<Operator*>(_symbol.get()); auto co = static_cast<Operator*>(node._symbol.get()); auto pp = po->precedence(); auto cp = co->precedence(); auto pa = !i ? po->associativity() != Associativity::RIGHT : po->associativity() != Associativity::LEFT; if ((pa && cp < pp) || (!pa && cp <= pp)) return _lexer->left + node.infix() + _lexer->right; } return node.infix(); }; switch (_symbol->symbol()) { case (SymbolType::FUNCTION): infix += _token + _lexer->left; for (const auto& node : _nodes) infix += node.infix() + _lexer->separator; infix.back() = _lexer->right.front(); return infix; case (SymbolType::OPERATOR): infix += brace(0) + _token + brace(1); return infix; default: return _token; } } std::string postfix() const noexcept { std::string postfix{}; for (const auto& node : _nodes) postfix += node.postfix() + " "; return postfix + _token; } std::vector<std::string> variables() const noexcept { return _variables->variables; } }; } namespace std { template<typename Parser> struct hash<calculate::Node<Parser>> { size_t operator()(const calculate::Node<Parser>& node) const { return node._hash; } }; } #endif <commit_msg>Fixed bug in copy of expressions containing variables<commit_after>#ifndef __CALCULATE_NODE_HPP__ #define __CALCULATE_NODE_HPP__ #include <iterator> #include <ostream> #include <stack> #include <sstream> #include "symbol.hpp" #include "util.hpp" namespace calculate { template<typename Parser> class Node { friend struct std::hash<Node>; friend Parser; public: using Lexer = typename Parser::Lexer; using Type = typename Parser::Type; using Symbol = Symbol<Node>; using SymbolType = typename Symbol::SymbolType; public: using const_iterator = typename std::vector<Node>::const_iterator; class VariableHandler { public: const std::vector<std::string> variables; private: std::size_t _size; std::unique_ptr<Type[]> _values; std::pair<std::size_t, std::shared_ptr<VariableHandler>> _temp; void _update(std::size_t) const {} template<typename Last> void _update(std::size_t n, Last last) { _values[n] = last; } template<typename Head, typename... Args> void _update(std::size_t n, Head head, Args... args) { _values[n] = head; _update(n + 1, args...); } public: explicit VariableHandler( const std::vector<std::string>& keys, Lexer& lexer ) : variables{keys}, _size{keys.size()}, _values{std::make_unique<Type[]>(_size)}, _temp{0u, nullptr} { std::unordered_set<std::string> singles{keys.begin(), keys.end()}; for (const auto &variable : keys) { if (!std::regex_match(variable, lexer.name_regex)) throw UnsuitableName{variable}; else if (singles.erase(variable) == 0) throw RepeatedSymbol{variable}; } } explicit VariableHandler(const std::vector<std::string>& keys) : variables{keys}, _size{keys.size()}, _values{std::make_unique<Type[]>(_size)}, _temp{0u, nullptr} {} std::shared_ptr<VariableHandler> clone() noexcept { ++_temp.first; if (bool{_temp.second}) return _temp.second; _temp.second = std::make_shared<VariableHandler>(variables); return _temp.second; } void reset() noexcept { if (!--_temp.first) _temp.second = nullptr; } std::size_t index(const std::string& token) const { auto found = std::find(variables.begin(), variables.end(), token); if (found != variables.end()) return found - variables.begin(); throw UndefinedSymbol{token}; } Type& at(const std::string& token) const { return _values[index(token)]; } void update(const std::vector<Type>& values) { if (_size != values.size()) throw ArgumentsMismatch{_size, values.size()}; for (std::size_t i = 0; i < _size; i++) _values[i] = values[i]; } template<typename... Args> void update(Args... args) { if (_size != sizeof...(args)) throw ArgumentsMismatch{_size, sizeof...(args)}; _update(0, args...); } }; private: std::shared_ptr<Lexer> _lexer; std::shared_ptr<VariableHandler> _variables; std::string _token; std::unique_ptr<Symbol> _symbol; std::vector<Node> _nodes; std::size_t _hash; Node() = delete; explicit Node( const std::shared_ptr<Lexer>& _lexer, const std::shared_ptr<VariableHandler>& variables, const std::string& token, std::unique_ptr<Symbol>&& symbol, std::vector<Node>&& nodes, std::size_t hash ) : _lexer{_lexer}, _variables{variables}, _token{token}, _symbol{std::move(symbol)}, _nodes{std::move(nodes)}, _hash{hash} { if (_nodes.size() != _symbol->arguments()) throw ArgumentsMismatch{ _token, _nodes.size(), _symbol->arguments() }; } std::vector<std::string> _pruned() const noexcept { std::istringstream extractor{postfix()}; std::vector<std::string> tokens{ std::istream_iterator<std::string>{extractor}, std::istream_iterator<std::string>{} }; std::vector<std::string> pruned{}; for (const auto& variable : variables()) if ( std::find(tokens.begin(), tokens.end(), variable) != tokens.end() ) pruned.push_back(variable); pruned.erase(std::unique(pruned.begin(), pruned.end()), pruned.end()); return pruned; } public: Node(const Node& other) noexcept : _lexer{other._lexer}, _variables{other._variables->clone()}, _token{other._token}, _symbol{nullptr}, _nodes{other._nodes}, _hash{other._hash} { using Variable = Variable<Node>; other._variables->reset(); try { _symbol = Variable{_variables->at(_token)}.clone(); } catch (const UndefinedSymbol&) { _symbol = other._symbol->clone(); } } Node(Node&& other) noexcept : _lexer{std::move(other._lexer)}, _variables{std::move(other._variables)}, _token{std::move(other._token)}, _symbol{std::move(other._symbol)}, _nodes{std::move(other._nodes)}, _hash{std::move(other._hash)} {} const Node& operator=(Node other) noexcept { swap(*this, other); return *this; } friend void swap(Node& one, Node& another) noexcept { using std::swap; swap(one._lexer, another._lexer); swap(one._variables, another._variables); swap(one._token, another._token); swap(one._symbol, another._symbol); swap(one._nodes, another._nodes); } explicit operator Type() const { if (variables().size() > 0) throw ArgumentsMismatch{variables().size(), 0}; return _symbol->evaluate(_nodes); } Type operator()(const std::vector<Type>& values) const { _variables->update(values); return _symbol->evaluate(_nodes); } template<typename... Args> Type operator()(Args&&... args) const { _variables->update(std::forward<Args>(args)...); return _symbol->evaluate(_nodes); } bool operator==(const Node& other) const noexcept { std::stack<std::pair<const_iterator, const_iterator>> these{}; std::stack<const_iterator> those{}; auto equal = [&](auto left, auto right) { try { return left->_variables->index(left->_token) == right->_variables->index(right->_token); } catch (const UndefinedSymbol&) { if (left->_symbol == right->_symbol) return true; return *(left->_symbol) == *(right->_symbol); } }; if (!equal(this, &other)) return false; these.push({this->begin(), this->end()}); those.push(other.begin()); while(!these.empty()) { auto one = these.top(); auto another = those.top(); these.pop(); those.pop(); if (one.first != one.second) { if (!equal(one.first, another)) return false; these.push({one.first->begin(), one.first->end()}); these.push({one.first + 1, one.second}); those.push(another->begin()); those.push(another + 1); } } return true; } bool operator!=(const Node& other) const noexcept { return !operator==(other); } const Node& operator[](std::size_t index) const { return _nodes[index]; } const Node& at(std::size_t index) const { return _nodes.at(index); } const_iterator begin() const noexcept { return _nodes.begin(); } const_iterator end() const noexcept { return _nodes.end(); } friend std::ostream& operator<<( std::ostream& ostream, const Node& node ) noexcept { ostream << node.infix(); return ostream; } static Type evaluate(const Node& node) { return node._symbol->evaluate(node._nodes); } const Lexer& lexer() const noexcept { return *_lexer; } const std::string& token() const noexcept { return _token; } SymbolType symbol() const noexcept { return _symbol->symbol(); } std::size_t branches() const noexcept { return _nodes.size(); } std::string infix() const noexcept { using Operator = Operator<Node>; using Associativity = typename Operator::Associativity; std::string infix{}; auto brace = [&](std::size_t i) { const auto& node = _nodes[i]; if (node._symbol->symbol() == SymbolType::OPERATOR) { auto po = static_cast<Operator*>(_symbol.get()); auto co = static_cast<Operator*>(node._symbol.get()); auto pp = po->precedence(); auto cp = co->precedence(); auto pa = !i ? po->associativity() != Associativity::RIGHT : po->associativity() != Associativity::LEFT; if ((pa && cp < pp) || (!pa && cp <= pp)) return _lexer->left + node.infix() + _lexer->right; } return node.infix(); }; switch (_symbol->symbol()) { case (SymbolType::FUNCTION): infix += _token + _lexer->left; for (const auto& node : _nodes) infix += node.infix() + _lexer->separator; infix.back() = _lexer->right.front(); return infix; case (SymbolType::OPERATOR): infix += brace(0) + _token + brace(1); return infix; default: return _token; } } std::string postfix() const noexcept { std::string postfix{}; for (const auto& node : _nodes) postfix += node.postfix() + " "; return postfix + _token; } std::vector<std::string> variables() const noexcept { return _variables->variables; } }; } namespace std { template<typename Parser> struct hash<calculate::Node<Parser>> { size_t operator()(const calculate::Node<Parser>& node) const { return node._hash; } }; } #endif <|endoftext|>
<commit_before>/* * Copyright (C) 2012 * Alessio Sclocco <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ #define __CL_ENABLE_EXCEPTIONS #include <CL/cl.hpp> #include <string> #include <utility> #include <vector> #include <stdexcept> using std::string; using std::make_pair; using std::vector; using std::out_of_range; #include <Timer.hpp> #include <Exceptions.hpp> #include <GPUData.hpp> #include <utils.hpp> using isa::utils::Timer; using isa::Exceptions::OpenCLError; using isa::OpenCL::GPUData; using isa::utils::toStringValue; #ifndef KERNEL_HPP #define KERNEL_HPP namespace isa { namespace OpenCL { template< typename T > class Kernel { public: Kernel(string name, string dataType); ~Kernel(); inline void bindOpenCL(cl::Context *context, cl::Device *device, cl::CommandQueue *queue); inline void setAsync(bool asy); inline void setNvidia(bool nvd); inline string getName() const; inline string getCode() const; inline string getDataType() const; inline string getBuildLog() const; char *getBinary(unsigned int binary); inline Timer& getTimer(); inline double getArithmeticIntensity() const; inline double getGFLOP() const; inline double getGB() const; protected: void compile() throw (OpenCLError); template< typename A > inline void setArgument(unsigned int id, A param) throw (OpenCLError); void run(cl::NDRange &globalSize, cl::NDRange &localSize) throw (OpenCLError); bool async; bool nvidia; string name; string *code; string dataType; string buildLog; cl::Kernel *kernel; cl::Context *clContext; cl::Device *clDevice; cl::CommandQueue *clCommands; cl::Event clEvent; Timer timer; vector< char * > binaries; double arInt; double gflop; double gb; }; // Implementation template< typename T > Kernel< T >::Kernel(string name, string dataType) : async(false), nvidia(false), name(name), code(0), dataType(dataType), buildLog(string()), kernel(0), clContext(0), clDevice(0), clCommands(0), clEvent(cl::Event()), timer(Timer()), binaries(vector< char * >()), arInt(0.0), gflop(0.0), gb(0.0) {} template< typename T > Kernel< T >::~Kernel() { delete code; delete kernel; for ( std::vector< char * >::iterator item = binaries.begin(); item != binaries.end(); item++ ) { delete [] *item; } } template< typename T > void Kernel< T >::compile() throw (OpenCLError) { cl::Program *program = 0; try { cl::Program::Sources sources(1, make_pair(code->c_str(), code->length())); program = new cl::Program(*clContext, sources, NULL); if ( nvidia ) { program->build(vector< cl::Device >(1, *clDevice), "-cl-mad-enable -cl-nv-verbose", NULL, NULL); program->getInfo(CL_PROGRAM_BINARIES, &binaries); } else { program->build(vector< cl::Device >(1, *clDevice), "-cl-mad-enable", NULL, NULL); } buildLog = program->getBuildInfo< CL_PROGRAM_BUILD_LOG >(*clDevice); } catch ( cl::Error err ) { throw OpenCLError("It is not possible to build the " + name + " OpenCL program: " + program->getBuildInfo< CL_PROGRAM_BUILD_LOG >(*clDevice) + "."); } if ( kernel != 0 ) { delete kernel; } try { kernel = new cl::Kernel(*program, name.c_str(), NULL); } catch ( cl::Error err ) { delete program; throw OpenCLError("It is not possible to create the kernel for " + name + ": " + toStringValue< cl_int >(err.err()) + "."); } delete program; } template< typename T > template< typename A > inline void Kernel< T >::setArgument(unsigned int id, A param) throw (OpenCLError) { if ( kernel == 0 ) { throw OpenCLError("First generate the kernel for " + name + "."); } try { kernel->setArg(id, param); } catch ( cl::Error err ) { throw OpenCLError("Impossible to set " + name + " arguments: " + toStringValue< cl_int >(err.err()) + "."); } } template< typename T > void Kernel< T >::run(cl::NDRange &globalSize, cl::NDRange &localSize) throw (OpenCLError) { if ( kernel == 0 ) { throw OpenCLError("First generate the kernel for " + name + "."); } if ( async ) { try { clCommands->enqueueNDRangeKernel(*kernel, cl::NullRange, globalSize, localSize, NULL, NULL); } catch ( cl::Error err ) { throw OpenCLError("Impossible to run " + name + ": " + toStringValue< cl_int >(err.err()) + "."); } } else { try { timer.start(); clCommands->enqueueNDRangeKernel(*kernel, cl::NullRange, globalSize, localSize, NULL, &clEvent); clEvent.wait(); timer.stop(); } catch ( cl::Error err ) { timer.stop(); timer.reset(); throw OpenCLError("Impossible to run " + name + ": " + toStringValue< cl_int >(err.err()) + "."); } } } template< typename T > inline void Kernel< T >::bindOpenCL(cl::Context *context, cl::Device *device, cl::CommandQueue *queue) { clContext = context; clDevice = device; clCommands = queue; } template< typename T > inline void Kernel< T >::setAsync(bool asy) { async = asy; } template< typename T > inline void Kernel< T >::setNvidia(bool nvd) { nvidia = nvd; } template< typename T > inline string Kernel< T >::getName() const { return name; } template< typename T > inline string Kernel< T >::getCode() const { if ( code != 0 ) { return *code; } return string(); } template< typename T > inline string Kernel< T >::getDataType() const { return dataType; } template< typename T > inline string Kernel< T >::getBuildLog() const { return buildLog; } template< typename T > char *Kernel< T >::getBinary(unsigned int binary) { if ( nvidia ) { try { return binaries.at(binary); } catch ( out_of_range err ) { return 0; } } return 0; } template< typename T > inline Timer& Kernel< T >::getTimer() { return Timer; } template< typename T > inline double Kernel< T >::getArithmeticIntensity() const { return arInt; } template< typename T > inline double Kernel< T >::getGFLOP() const { return gflop; } template< typename T > inline double Kernel< T >::getGB() const { return gb; } } // OpenCL } // isa #endif // KERNEL_HPP <commit_msg>This should be the last fix.<commit_after>/* * Copyright (C) 2012 * Alessio Sclocco <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ #define __CL_ENABLE_EXCEPTIONS #include <CL/cl.hpp> #include <string> #include <utility> #include <vector> #include <stdexcept> using std::string; using std::make_pair; using std::vector; using std::out_of_range; #include <Timer.hpp> #include <Exceptions.hpp> #include <GPUData.hpp> #include <utils.hpp> using isa::utils::Timer; using isa::Exceptions::OpenCLError; using isa::OpenCL::GPUData; using isa::utils::toStringValue; #ifndef KERNEL_HPP #define KERNEL_HPP namespace isa { namespace OpenCL { template< typename T > class Kernel { public: Kernel(string name, string dataType); ~Kernel(); inline void bindOpenCL(cl::Context *context, cl::Device *device, cl::CommandQueue *queue); inline void setAsync(bool asy); inline void setNvidia(bool nvd); inline string getName() const; inline string getCode() const; inline string getDataType() const; inline string getBuildLog() const; char *getBinary(unsigned int binary); inline Timer& getTimer(); inline double getArithmeticIntensity() const; inline double getGFLOP() const; inline double getGB() const; protected: void compile() throw (OpenCLError); template< typename A > inline void setArgument(unsigned int id, A param) throw (OpenCLError); void run(cl::NDRange &globalSize, cl::NDRange &localSize) throw (OpenCLError); bool async; bool nvidia; string name; string *code; string dataType; string buildLog; cl::Kernel *kernel; cl::Context *clContext; cl::Device *clDevice; cl::CommandQueue *clCommands; cl::Event clEvent; Timer timer; vector< char * > binaries; double arInt; double gflop; double gb; }; // Implementation template< typename T > Kernel< T >::Kernel(string name, string dataType) : async(false), nvidia(false), name(name), code(0), dataType(dataType), buildLog(string()), kernel(0), clContext(0), clDevice(0), clCommands(0), clEvent(cl::Event()), timer(Timer()), binaries(vector< char * >()), arInt(0.0), gflop(0.0), gb(0.0) {} template< typename T > Kernel< T >::~Kernel() { delete code; delete kernel; for ( std::vector< char * >::iterator item = binaries.begin(); item != binaries.end(); item++ ) { delete [] *item; } } template< typename T > void Kernel< T >::compile() throw (OpenCLError) { cl::Program *program = 0; try { cl::Program::Sources sources(1, make_pair(code->c_str(), code->length())); program = new cl::Program(*clContext, sources, NULL); if ( nvidia ) { program->build(vector< cl::Device >(1, *clDevice), "-cl-mad-enable -cl-nv-verbose", NULL, NULL); program->getInfo(CL_PROGRAM_BINARIES, &binaries); } else { program->build(vector< cl::Device >(1, *clDevice), "-cl-mad-enable", NULL, NULL); } buildLog = program->getBuildInfo< CL_PROGRAM_BUILD_LOG >(*clDevice); } catch ( cl::Error err ) { throw OpenCLError("It is not possible to build the " + name + " OpenCL program: " + program->getBuildInfo< CL_PROGRAM_BUILD_LOG >(*clDevice) + "."); } if ( kernel != 0 ) { delete kernel; } try { kernel = new cl::Kernel(*program, name.c_str(), NULL); } catch ( cl::Error err ) { delete program; throw OpenCLError("It is not possible to create the kernel for " + name + ": " + toStringValue< cl_int >(err.err()) + "."); } delete program; } template< typename T > template< typename A > inline void Kernel< T >::setArgument(unsigned int id, A param) throw (OpenCLError) { if ( kernel == 0 ) { throw OpenCLError("First generate the kernel for " + name + "."); } try { kernel->setArg(id, param); } catch ( cl::Error err ) { throw OpenCLError("Impossible to set " + name + " arguments: " + toStringValue< cl_int >(err.err()) + "."); } } template< typename T > void Kernel< T >::run(cl::NDRange &globalSize, cl::NDRange &localSize) throw (OpenCLError) { if ( kernel == 0 ) { throw OpenCLError("First generate the kernel for " + name + "."); } if ( async ) { try { clCommands->enqueueNDRangeKernel(*kernel, cl::NullRange, globalSize, localSize, NULL, NULL); } catch ( cl::Error err ) { throw OpenCLError("Impossible to run " + name + ": " + toStringValue< cl_int >(err.err()) + "."); } } else { try { timer.start(); clCommands->enqueueNDRangeKernel(*kernel, cl::NullRange, globalSize, localSize, NULL, &clEvent); clEvent.wait(); timer.stop(); } catch ( cl::Error err ) { timer.stop(); timer.reset(); throw OpenCLError("Impossible to run " + name + ": " + toStringValue< cl_int >(err.err()) + "."); } } } template< typename T > inline void Kernel< T >::bindOpenCL(cl::Context *context, cl::Device *device, cl::CommandQueue *queue) { clContext = context; clDevice = device; clCommands = queue; } template< typename T > inline void Kernel< T >::setAsync(bool asy) { async = asy; } template< typename T > inline void Kernel< T >::setNvidia(bool nvd) { nvidia = nvd; } template< typename T > inline string Kernel< T >::getName() const { return name; } template< typename T > inline string Kernel< T >::getCode() const { if ( code != 0 ) { return *code; } return string(); } template< typename T > inline string Kernel< T >::getDataType() const { return dataType; } template< typename T > inline string Kernel< T >::getBuildLog() const { return buildLog; } template< typename T > char *Kernel< T >::getBinary(unsigned int binary) { if ( nvidia ) { try { return binaries.at(binary); } catch ( out_of_range err ) { return 0; } } return 0; } template< typename T > inline Timer& Kernel< T >::getTimer() { return timer; } template< typename T > inline double Kernel< T >::getArithmeticIntensity() const { return arInt; } template< typename T > inline double Kernel< T >::getGFLOP() const { return gflop; } template< typename T > inline double Kernel< T >::getGB() const { return gb; } } // OpenCL } // isa #endif // KERNEL_HPP <|endoftext|>
<commit_before>/** ** \file libport/symbol.hxx ** \brief Inline implementation of libport::Symbol. */ #ifndef LIBPORT_SYMBOL_HXX # define LIBPORT_SYMBOL_HXX # ifdef WITH_BOOST_SERIALIZATION # include <boost/serialization/string.hpp> # endif # include <ostream> # include <libport/symbol.hh> # include <libport/assert.hh> namespace libport { //<< inline const std::string& Symbol::name_get () const { assert (str_); return *str_; } inline Symbol::operator const std::string& () const { assert (str_); return *str_; } inline Symbol& Symbol::operator= (const Symbol& rhs) { if (this != &rhs) str_ = rhs.str_; return *this; } inline bool Symbol::operator== (const Symbol& rhs) const { return str_ == rhs.str_; } inline bool Symbol::operator!= (const Symbol& rhs) const { return !operator== (rhs); } //>> // The value inserted in a `set' container is only duplicated once: // at insertion time. So for sake of speed, we could safely compare // the addresses of the strings. Nevertheless, in order to produce // stable results, we sort the actual string values. inline bool Symbol::operator< (const Symbol& rhs) const { //<< assert (str_); assert (rhs.str_); return *str_ < *rhs.str_; //>> } inline bool Symbol::empty () const { assert (str_); return str_->empty(); } //<< inline std::ostream& operator<< (std::ostream& ostr, const Symbol& the) { return ostr << the.name_get (); } //>> inline Symbol Symbol::make_empty() { static Symbol empty_symbol = Symbol(""); return empty_symbol; } inline std::size_t hash_value(libport::Symbol s) { const std::string* v = &s.name_get(); std::size_t x = static_cast<std::size_t>(reinterpret_cast<std::ptrdiff_t>(v)); return x + (x >> 3); } #ifdef WITH_BOOST_SERIALIZATION template <typename Archive> void Symbol::save(Archive& ar, const unsigned int /* version */) const { ar & *const_cast<std::string*>(str_); } template <typename Archive> void Symbol::load(Archive& ar, const unsigned int /* version */) { std::string s; ar & s; str_ = &*string_set_instance ().insert (s).first; } #endif // WITH_BOOST_SERIALIZATION } #endif // !LIBPORT_SYMBOL_HXX <commit_msg>Formatting changes.<commit_after>/** ** \file libport/symbol.hxx ** \brief Inline implementation of libport::Symbol. */ #ifndef LIBPORT_SYMBOL_HXX # define LIBPORT_SYMBOL_HXX # ifdef WITH_BOOST_SERIALIZATION # include <boost/serialization/string.hpp> # endif # include <ostream> # include <libport/symbol.hh> # include <libport/assert.hh> namespace libport { //<< inline const std::string& Symbol::name_get () const { assert (str_); return *str_; } inline Symbol::operator const std::string& () const { assert (str_); return *str_; } inline Symbol& Symbol::operator= (const Symbol& rhs) { if (this != &rhs) str_ = rhs.str_; return *this; } inline bool Symbol::operator== (const Symbol& rhs) const { return str_ == rhs.str_; } inline bool Symbol::operator!= (const Symbol& rhs) const { return !operator== (rhs); } //>> // The value inserted in a `set' container is only duplicated once: // at insertion time. So for sake of speed, we could safely compare // the addresses of the strings. Nevertheless, in order to produce // stable results, we sort the actual string values. inline bool Symbol::operator< (const Symbol& rhs) const { //<< assert (str_); assert (rhs.str_); return *str_ < *rhs.str_; //>> } inline bool Symbol::empty() const { assert (str_); return str_->empty(); } //<< inline std::ostream& operator<< (std::ostream& ostr, const Symbol& the) { return ostr << the.name_get (); } //>> inline Symbol Symbol::make_empty() { static Symbol empty_symbol = Symbol(""); return empty_symbol; } inline std::size_t hash_value(libport::Symbol s) { const std::string* v = &s.name_get(); std::size_t x = static_cast<std::size_t>(reinterpret_cast<std::ptrdiff_t>(v)); return x + (x >> 3); } #ifdef WITH_BOOST_SERIALIZATION template <typename Archive> void Symbol::save(Archive& ar, const unsigned int /* version */) const { ar & *const_cast<std::string*>(str_); } template <typename Archive> void Symbol::load(Archive& ar, const unsigned int /* version */) { std::string s; ar & s; str_ = &*string_set_instance ().insert (s).first; } #endif // WITH_BOOST_SERIALIZATION } #endif // !LIBPORT_SYMBOL_HXX <|endoftext|>
<commit_before>/*========================================================================= Program: itkUNC Module: itkNeuralNetworkTests2.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 2002 CADDLab @ UNC. All rights reserved. See itkUNCCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif #include <iostream> #include "itkTestMain.h" void RegisterTests() { REGISTER_TEST(RBFTest1); REGISTER_TEST(itkNeuralNetworksPrintTest); } <commit_msg>COMP: some compilers run out of memory woithout the ITK_LEAN_AND_MEAN defined.<commit_after>/*========================================================================= Program: itkUNC Module: itkNeuralNetworkTests2.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 2002 CADDLab @ UNC. All rights reserved. See itkUNCCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif // some compilers have trouble with the size of this test #define ITK_LEAN_AND_MEAN #include <iostream> #include "itkTestMain.h" void RegisterTests() { REGISTER_TEST(RBFTest1); REGISTER_TEST(itkNeuralNetworksPrintTest); } <|endoftext|>
<commit_before>#ifndef PARSERLIB__RULE__HPP #define PARSERLIB__RULE__HPP #include <memory> #include <string_view> #include "rule_reference.hpp" #include "parse_context.hpp" #include "expression_wrapper.hpp" namespace parserlib { /** A grammar rule. @param ParseContext type of parse context to use. */ template <typename ParseContext = parse_context<>> class rule : public expression { public: ///match tag. std::string_view tag; /** Constructor from expression. @param expression expression. */ template <typename T> rule(T&& expression) : m_expression(std::make_unique<expression_wrapper<ParseContext, expression_type_t<T>>>(std::forward<T>(expression))) { } /** Constructor from rule reference. @param r rule. */ rule(rule&& r) : m_expression(std::make_unique<expression_wrapper<rule_reference<ParseContext>>>(r)) { } /** Parses the input with the underlying expression. If the tag is not empty, and parsing is successful, then the corresponding match is added to the parse context. @param pc parse context. @return parse result. */ parse_result parse(ParseContext& pc) const { parse_result result; const bool left_recursion = pc.add_position(this); if (!left_recursion) { if (pc.position > pc.m_left_recursion_position) { const auto prev_start_position = pc.start_position; const auto prev_left_recursion_state = pc.m_left_recursion_state; const auto prev_left_recursion_position = pc.m_left_recursion_position; pc.start_position = pc.position; pc.m_left_recursion_state = ParseContext::left_recursion_state::inactive; pc.m_left_recursion_position = pc.position; result = parse_(pc); pc.start_position = prev_start_position; pc.m_left_recursion_state = prev_left_recursion_state; pc.m_left_recursion_position = prev_left_recursion_position; } else { switch (pc.m_left_recursion_state) { case ParseContext::left_recursion_state::inactive: result = parse_(pc); break; case ParseContext::left_recursion_state::reject: result = parse_(pc); break; case ParseContext::left_recursion_state::accept: result = parse_result::accepted; break; } } } else { switch (pc.m_left_recursion_state) { case ParseContext::left_recursion_state::inactive: pc.m_left_recursion_state = ParseContext::left_recursion_state::reject; result = parse_result::rejected; break; case ParseContext::left_recursion_state::reject: result = parse_result::rejected; break; case ParseContext::left_recursion_state::accept: result = parse_result::accepted; break; } } pc.remove_position(this); return result; } private: //the expression is wrapped by a polymorphic type. std::unique_ptr<expression_interface<ParseContext>> m_expression; //internal parse that adds match on success parse_result parse_(ParseContext& pc) const { const auto start_position = pc.position; const parse_result result = m_expression->parse(pc); if (result == parse_result::accepted && !tag.empty()) { pc.add_match(start_position, pc.position, tag); } return result; } }; /** Specialization for rules. Allows the implicit conversion to rules to rule references. @param ParseContext type of parse context to use. */ template <typename ParseContext> class expression_type<rule<ParseContext>> { public: /** The expression type of a rule is a rule reference, in order to allow recursive declarations of rules. */ typedef rule_reference<ParseContext> type; }; /** Operator that adds a tag to a rule. @param rule rule to set the tag of. @param tag tag to set. @return the rule. */ template <typename ParseContext> rule<ParseContext>& operator >= (rule<ParseContext>& rule, const std::string_view& tag) { rule.tag = tag; return rule; } } //namespace parserlib #endif //PARSERLIB__RULE__HPP <commit_msg>Fixed the start position of the input for rule matching.<commit_after>#ifndef PARSERLIB__RULE__HPP #define PARSERLIB__RULE__HPP #include <memory> #include <string_view> #include "rule_reference.hpp" #include "parse_context.hpp" #include "expression_wrapper.hpp" namespace parserlib { /** A grammar rule. @param ParseContext type of parse context to use. */ template <typename ParseContext = parse_context<>> class rule : public expression { public: ///match tag. std::string_view tag; /** Constructor from expression. @param expression expression. */ template <typename T> rule(T&& expression) : m_expression(std::make_unique<expression_wrapper<ParseContext, expression_type_t<T>>>(std::forward<T>(expression))) { } /** Constructor from rule reference. @param r rule. */ rule(rule&& r) : m_expression(std::make_unique<expression_wrapper<rule_reference<ParseContext>>>(r)) { } /** Parses the input with the underlying expression. If the tag is not empty, and parsing is successful, then the corresponding match is added to the parse context. @param pc parse context. @return parse result. */ parse_result parse(ParseContext& pc) const { parse_result result; const bool left_recursion = pc.add_position(this); if (!left_recursion) { if (pc.position > pc.m_left_recursion_position) { const auto prev_start_position = pc.start_position; const auto prev_left_recursion_state = pc.m_left_recursion_state; const auto prev_left_recursion_position = pc.m_left_recursion_position; pc.start_position = pc.position; pc.m_left_recursion_state = ParseContext::left_recursion_state::inactive; pc.m_left_recursion_position = pc.position; result = parse_(pc); pc.start_position = prev_start_position; pc.m_left_recursion_state = prev_left_recursion_state; pc.m_left_recursion_position = prev_left_recursion_position; } else { switch (pc.m_left_recursion_state) { case ParseContext::left_recursion_state::inactive: result = parse_(pc); break; case ParseContext::left_recursion_state::reject: result = parse_(pc); break; case ParseContext::left_recursion_state::accept: result = parse_result::accepted; break; } } } else { switch (pc.m_left_recursion_state) { case ParseContext::left_recursion_state::inactive: pc.m_left_recursion_state = ParseContext::left_recursion_state::reject; result = parse_result::rejected; break; case ParseContext::left_recursion_state::reject: result = parse_result::rejected; break; case ParseContext::left_recursion_state::accept: result = parse_result::accepted; break; } } pc.remove_position(this); return result; } private: //the expression is wrapped by a polymorphic type. std::unique_ptr<expression_interface<ParseContext>> m_expression; //internal parse that adds match on success parse_result parse_(ParseContext& pc) const { const auto start_position = pc.start_position; const parse_result result = m_expression->parse(pc); if (result == parse_result::accepted && !tag.empty()) { pc.add_match(start_position, pc.position, tag); } return result; } }; /** Specialization for rules. Allows the implicit conversion to rules to rule references. @param ParseContext type of parse context to use. */ template <typename ParseContext> class expression_type<rule<ParseContext>> { public: /** The expression type of a rule is a rule reference, in order to allow recursive declarations of rules. */ typedef rule_reference<ParseContext> type; }; /** Operator that adds a tag to a rule. @param rule rule to set the tag of. @param tag tag to set. @return the rule. */ template <typename ParseContext> rule<ParseContext>& operator >= (rule<ParseContext>& rule, const std::string_view& tag) { rule.tag = tag; return rule; } } //namespace parserlib #endif //PARSERLIB__RULE__HPP <|endoftext|>
<commit_before>#ifndef __PROCESS_THREAD_HPP__ #define __PROCESS_THREAD_HPP__ #include <pthread.h> #include <stdio.h> // For perror. #include <stdlib.h> // For abort. template <typename T> struct ThreadLocal { ThreadLocal() { if (pthread_key_create(&key, NULL) != 0) { perror("Failed to create thread local, pthread_key_create"); abort(); } } ThreadLocal<T>& operator = (T* t) { if (pthread_setspecific(key, t) != 0) { perror("Failed to set thread local, pthread_setspecific"); abort(); } return *this; } operator T* () const { return reinterpret_cast<T*>(pthread_getspecific(key)); } T* operator -> () const { return reinterpret_cast<T*>(pthread_getspecific(key)); } private: // Not expecting any other operators to be used (and the rest?). bool operator * (const ThreadLocal<T>&) const; bool operator == (const ThreadLocal<T>&) const; bool operator != (const ThreadLocal<T>&) const; bool operator < (const ThreadLocal<T>&) const; bool operator > (const ThreadLocal<T>&) const; pthread_key_t key; }; #endif // __PROCESS_THREAD_HPP__ <commit_msg>Removing thread.hpp for version in stout.<commit_after><|endoftext|>
<commit_before>// ============================================================================= // PROJECT CHRONO - http://projectchrono.org // // Copyright (c) 2014 projectchrono.org // All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found // in the LICENSE file at the top level of the distribution and at // http://projectchrono.org/license-chrono.txt. // // ============================================================================= // Authors: Radu Serban // ============================================================================= // // HMMWV chassis subsystem. // // ============================================================================= #include "chrono/assets/ChTriangleMeshShape.h" #include "chrono/utils/ChUtilsInputOutput.h" #include "chrono_vehicle/ChVehicleModelData.h" #include "chrono_models/vehicle/hmmwv/HMMWV_Chassis.h" namespace chrono { namespace vehicle { namespace hmmwv { // ----------------------------------------------------------------------------- // Static variables // ----------------------------------------------------------------------------- const double HMMWV_Chassis::m_mass = 2086.52; const ChVector<> HMMWV_Chassis::m_inertiaXX(1078.52, 2955.66, 3570.20); const ChVector<> HMMWV_Chassis::m_inertiaXY(0, 0, 0); const ChVector<> HMMWV_Chassis::m_COM_loc(0.056, 0, 0.213); const ChCoordsys<> HMMWV_Chassis::m_driverCsys(ChVector<>(0.87, 0.27, 1.05), ChQuaternion<>(1, 0, 0, 0)); // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- HMMWV_Chassis::HMMWV_Chassis(const std::string& name, bool fixed, ChassisCollisionType chassis_collision_type) : ChRigidChassis(name, fixed) { m_inertia(0, 0) = m_inertiaXX.x(); m_inertia(1, 1) = m_inertiaXX.y(); m_inertia(2, 2) = m_inertiaXX.z(); m_inertia(0, 1) = m_inertiaXY.x(); m_inertia(0, 2) = m_inertiaXY.y(); m_inertia(1, 2) = m_inertiaXY.z(); m_inertia(1, 0) = m_inertiaXY.x(); m_inertia(2, 0) = m_inertiaXY.y(); m_inertia(2, 1) = m_inertiaXY.z(); //// TODO: //// A more appropriate contact shape from primitives BoxShape box1(ChVector<>(0.0, 0.0, 0.1), ChQuaternion<>(1, 0, 0, 0), ChVector<>(2.0, 1.0, 0.2)); m_has_primitives = true; m_vis_boxes.push_back(box1); m_has_mesh = true; m_vis_mesh_file = "hmmwv/hmmwv_chassis.obj"; m_has_collision = (chassis_collision_type != ChassisCollisionType::NONE); switch (chassis_collision_type) { case ChassisCollisionType::PRIMITIVES: box1.m_matID = 0; m_coll_boxes.push_back(box1); break; case ChassisCollisionType::MESH: { ConvexHullsShape hull("hmmwv/hmmwv_chassis_simple.obj", 0); m_coll_hulls.push_back(hull); break; } default: break; } } void HMMWV_Chassis::CreateContactMaterials(ChContactMethod contact_method) { // Create the contact materials. // In this model, we use a single material with default properties. MaterialInfo minfo; m_materials.push_back(minfo.CreateMaterial(contact_method)); } } // end namespace hmmwv } // end namespace vehicle } // end namespace chrono <commit_msg>Add a second visualization box for HMMWV chassis<commit_after>// ============================================================================= // PROJECT CHRONO - http://projectchrono.org // // Copyright (c) 2014 projectchrono.org // All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found // in the LICENSE file at the top level of the distribution and at // http://projectchrono.org/license-chrono.txt. // // ============================================================================= // Authors: Radu Serban // ============================================================================= // // HMMWV chassis subsystem. // // ============================================================================= #include "chrono/assets/ChTriangleMeshShape.h" #include "chrono/utils/ChUtilsInputOutput.h" #include "chrono_vehicle/ChVehicleModelData.h" #include "chrono_models/vehicle/hmmwv/HMMWV_Chassis.h" namespace chrono { namespace vehicle { namespace hmmwv { // ----------------------------------------------------------------------------- // Static variables // ----------------------------------------------------------------------------- const double HMMWV_Chassis::m_mass = 2086.52; const ChVector<> HMMWV_Chassis::m_inertiaXX(1078.52, 2955.66, 3570.20); const ChVector<> HMMWV_Chassis::m_inertiaXY(0, 0, 0); const ChVector<> HMMWV_Chassis::m_COM_loc(0.056, 0, 0.213); const ChCoordsys<> HMMWV_Chassis::m_driverCsys(ChVector<>(0.87, 0.27, 1.05), ChQuaternion<>(1, 0, 0, 0)); // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- HMMWV_Chassis::HMMWV_Chassis(const std::string& name, bool fixed, ChassisCollisionType chassis_collision_type) : ChRigidChassis(name, fixed) { m_inertia(0, 0) = m_inertiaXX.x(); m_inertia(1, 1) = m_inertiaXX.y(); m_inertia(2, 2) = m_inertiaXX.z(); m_inertia(0, 1) = m_inertiaXY.x(); m_inertia(0, 2) = m_inertiaXY.y(); m_inertia(1, 2) = m_inertiaXY.z(); m_inertia(1, 0) = m_inertiaXY.x(); m_inertia(2, 0) = m_inertiaXY.y(); m_inertia(2, 1) = m_inertiaXY.z(); //// TODO: //// A more appropriate contact shape from primitives BoxShape box1(ChVector<>(0.0, 0.0, 0.1), ChQuaternion<>(1, 0, 0, 0), ChVector<>(2.0, 1.0, 0.2)); BoxShape box2(ChVector<>(0.0, 0.0, 0.3), ChQuaternion<>(1, 0, 0, 0), ChVector<>(1.0, 0.5, 0.2)); m_has_primitives = true; m_vis_boxes.push_back(box1); m_vis_boxes.push_back(box2); m_has_mesh = true; m_vis_mesh_file = "hmmwv/hmmwv_chassis.obj"; m_has_collision = (chassis_collision_type != ChassisCollisionType::NONE); switch (chassis_collision_type) { case ChassisCollisionType::PRIMITIVES: box1.m_matID = 0; m_coll_boxes.push_back(box1); break; case ChassisCollisionType::MESH: { ConvexHullsShape hull("hmmwv/hmmwv_chassis_simple.obj", 0); m_coll_hulls.push_back(hull); break; } default: break; } } void HMMWV_Chassis::CreateContactMaterials(ChContactMethod contact_method) { // Create the contact materials. // In this model, we use a single material with default properties. MaterialInfo minfo; m_materials.push_back(minfo.CreateMaterial(contact_method)); } } // end namespace hmmwv } // end namespace vehicle } // end namespace chrono <|endoftext|>
<commit_before>/***********************************************************\ * Generic de-/ serializers for annotated types * * ___________ _____ * * / ___| ___/ __ \ * * \ `--.| |_ `' / /' * * `--. \ _| / / * * /\__/ / | ./ /___ * * \____/\_| \_____/ * * * * * * Copyright (c) 2014 Florian Oetke * * * * This file is part of SF2 and distributed under * * the MIT License. See LICENSE file for details. * \***********************************************************/ #pragma once #include <memory> #include <iostream> #include "reflection_data.hpp" namespace sf2 { template<typename Writer> struct Serializer; template<typename Writer> struct Deserializer; using Error_handler = std::function<void (const std::string& msg, uint32_t row, uint32_t column)>; namespace details { using std::begin; using std::end; template<class Writer, class T> struct has_save { private: typedef char one; typedef long two; template <typename C> static one test(decltype(save(std::declval<Serializer<Writer>&>(), std::declval<const C&>()))*); template <typename C> static two test(...); public: enum { value = sizeof(test<T>(0)) == sizeof(char) }; }; template<class Reader, class T> struct has_load { private: typedef char one; typedef long two; template <typename C> static one test(decltype(load(std::declval<Deserializer<Reader>&>(), std::declval<C&>()))*); template <typename C> static two test(...); public: enum { value = sizeof(test<T>(0)) == sizeof(char) }; }; template<class T> struct is_range { private: typedef char one; typedef long two; template <typename C> static one test(decltype(begin(std::declval<C&>()))*, decltype(end(std::declval<C&>()))*); template <typename C> static two test(...); public: enum { value = sizeof(test<T>(0, 0)) == sizeof(char) }; }; template<class T> struct has_key_type { private: typedef char one; typedef long two; template <typename C> static one test(typename C::key_type*); template <typename C> static two test(...); public: enum { value = sizeof(test<T>(0)) == sizeof(char) }; }; template<class T> struct has_mapped_type { private: typedef char one; typedef long two; template <typename C> static one test(typename C::mapped_type*); template <typename C> static two test(...); public: enum { value = sizeof(test<T>(0)) == sizeof(char) }; }; template<class T> struct is_map { enum { value = is_range<T>::value && has_key_type<T>::value && has_mapped_type<T>::value }; }; template<class T> struct is_set { enum { value = is_range<T>::value && has_key_type<T>::value && !has_mapped_type<T>::value }; }; template<class T> struct is_list { enum { value = is_range<T>::value && !has_key_type<T>::value && !has_mapped_type<T>::value }; }; } template<typename T> auto vmember(String_literal name, T& v) { return std::pair<String_literal, T&>(name, v); } template<typename Writer> struct Serializer { Serializer(Writer&& w) : writer(std::move(w)) {} template<class T> std::enable_if_t<is_annotated_struct<T>::value> write(const T& inst) { writer.begin_obj(); get_struct_info<T>().for_each([&](auto n, auto mptr) { write_member(n, inst.*mptr); }); writer.end_current(); } template<typename... Members> inline void write_virtual(Members&&... m) { writer.begin_obj(); auto i = {write_member_pair(m)...}; (void)i; writer.end_current(); } private: Writer writer; template<class K, class T> int write_member_pair(std::pair<K, T&> inst) { writer.write(inst.first); write_value(inst.second); return 0; } template<class T> int write_member_pair(std::pair<String_literal, T&> inst) { writer.write(inst.first.data, inst.first.len); write_value(inst.second); return 0; } template<class T> void write_member(String_literal name, const T& inst) { writer.write(name.data, name.len); write_value(inst); } public: template<class T> void write_value(const T* inst) { if(inst) write_value(*inst); else writer.write_nullptr(); } template<class T> void write_value(const std::unique_ptr<T>& inst) { if(inst) write_value(*inst); else writer.write_nullptr(); } template<class T> void write_value(const std::shared_ptr<T>& inst) { if(inst) write_value(*inst); else writer.write_nullptr(); } // annotated struct template<class T> std::enable_if_t<is_annotated_struct<T>::value> write_value(const T& inst) { writer.begin_obj(); get_struct_info<T>().for_each([&](auto n, auto mptr) { write_member(n, inst.*mptr); }); writer.end_current(); } // annotated enum template<class T> std::enable_if_t<is_annotated_enum<T>::value> write_value(const T& inst) { auto name = get_enum_info<T>().name_of(inst); writer.write(name.data, name.len); } // map template<class T> std::enable_if_t<not is_annotated<T>::value && details::is_map<T>::value> write_value(const T& inst) { writer.begin_obj(); for(auto& v : inst) { write_value(v.first); write_value(v.second); } writer.end_current(); } // other collection template<class T> std::enable_if_t<not is_annotated<T>::value && (details::is_list<T>::value || details::is_set<T>::value)> write_value(const T& inst) { writer.begin_array(); for(auto& v : inst) write_value(v); writer.end_current(); } // manual save-function template<class T> std::enable_if_t<not is_annotated<T>::value && details::has_save<Writer,T>::value> write_value(const T& inst) { save(*this, inst); } // other template<class T> std::enable_if_t<not is_annotated<T>::value && not details::is_range<T>::value && not details::has_save<Writer,T>::value> write_value(const T& inst) { writer.write(inst); } void write_value(const std::string& inst) { writer.write(inst); } void write_value(const char* inst) { writer.write(inst); } }; template<typename Writer, typename T> inline void serialize(Writer&& w, const T& v) { Serializer<Writer>{std::move(w)}.write(v); } template<typename Writer, typename... Members> inline void serialize_virtual(Writer&& w, Members&&... m) { Serializer<Writer>{std::move(w)}.write_virtual(std::forward<Members>(m)...); } template<typename Reader> struct Deserializer { Deserializer(Reader&& r, Error_handler error_handler=Error_handler()) : reader(std::move(r)), error_handler(error_handler) { buffer.reserve(64); } template<class T> std::enable_if_t<is_annotated_struct<T>::value> read(T& inst) { while(reader.in_obj()) { reader.read(buffer); auto match = false; auto key = String_literal{buffer}; get_struct_info<T>().for_each([&](String_literal n, auto mptr) { if(!match && n==key) { read_value(inst.*mptr); match = true; } }); if(!match) { on_error("Unexpected key "+buffer); } } } template<typename... Members> inline void read_virtual(Members&&... m) { while(reader.in_obj()) { reader.read(buffer); bool match = false; auto key = String_literal{buffer}; auto i = {read_member_pair(match, key, m)...}; (void)i; if(!match) { on_error("Unexpected key "+buffer); } } } template<typename Func> inline void read_lambda(Func func) { while(reader.in_obj()) { reader.read(buffer); bool match = func(buffer); if(!match) { on_error("Unexpected key "+buffer); } } } private: Reader reader; std::string buffer; Error_handler error_handler; void on_error(const std::string& e) { if(error_handler) error_handler(e, reader.row(), reader.column()); else std::cerr<<"Error parsing JSON at "<<reader.row()<<":"<<reader.column()<<" : "<<e<<std::endl; } template<class K, class T> int read_member_pair(bool& match, String_literal n, std::pair<K, T&> inst) { if(!match && inst.first==n) { read_value(inst.second); match = true; } return 0; } public: template<class T> void read_value(std::unique_ptr<T>& inst) { if(reader.read_nullptr()) inst = nullptr; else { inst = std::make_unique<T>(); read_value(*inst); } } template<class T> void read_value(std::shared_ptr<T>& inst) { if(reader.read_nullptr()) inst = nullptr; else { inst = std::make_shared<T>(); read_value(*inst); } } // annotated struct template<class T> std::enable_if_t<is_annotated_struct<T>::value> read_value(T& inst) { while(reader.in_obj()) { reader.read(buffer); bool match = false; auto key = String_literal{buffer}; get_struct_info<T>().for_each([&](auto n, auto mptr) { if(!match && n==key) { read_value(inst.*mptr); match = true; } }); if(!match) { on_error("Unexpected key "+buffer); } } } // annotated enum template<class T> std::enable_if_t<is_annotated_enum<T>::value> read_value(T& inst) { reader.read(buffer); inst = get_enum_info<T>().value_of(buffer); } // map template<class T> std::enable_if_t<not is_annotated<T>::value && details::is_map<T>::value> read_value(T& inst) { inst.clear(); typename T::key_type key; typename T::mapped_type val; while(reader.in_obj()) { read_value(key); read_value(val); inst.emplace(std::move(key), std::move(val)); } } //set template<class T> std::enable_if_t<not is_annotated<T>::value && details::is_set<T>::value> read_value(T& inst) { inst.clear(); typename T::value_type v; while(reader.in_array()) { read_value(v); inst.emplace(std::move(v)); } } // other collection template<class T> std::enable_if_t<not is_annotated<T>::value && details::is_list<T>::value> read_value(T& inst) { inst.clear(); typename T::value_type v; while(reader.in_array()) { read_value(v); inst.emplace_back(std::move(v)); } } // manual load-function template<class T> std::enable_if_t<not is_annotated<T>::value && details::has_load<Reader,T>::value> read_value(T& inst) { load(*this, inst); } // other template<class T> std::enable_if_t<not is_annotated<T>::value && not details::is_range<T>::value && not details::has_load<Reader,T>::value> read_value(T& inst) { reader.read(inst); } void read_value(std::string& inst) { reader.read(inst); } }; template<typename Reader, typename T> inline void deserialize(Reader&& r, T& v) { Deserializer<Reader>{std::move(r)}.read(v); } template<typename Reader, typename... Members> inline void deserialize_virtual(Reader&& r, Members&&... m) { Deserializer<Reader>{std::move(r)}.read_virtual(std::forward<Members>(m)...); } } <commit_msg>fixed sfinae error<commit_after>/***********************************************************\ * Generic de-/ serializers for annotated types * * ___________ _____ * * / ___| ___/ __ \ * * \ `--.| |_ `' / /' * * `--. \ _| / / * * /\__/ / | ./ /___ * * \____/\_| \_____/ * * * * * * Copyright (c) 2014 Florian Oetke * * * * This file is part of SF2 and distributed under * * the MIT License. See LICENSE file for details. * \***********************************************************/ #pragma once #include <memory> #include <iostream> #include "reflection_data.hpp" namespace sf2 { template<typename Writer> struct Serializer; template<typename Writer> struct Deserializer; using Error_handler = std::function<void (const std::string& msg, uint32_t row, uint32_t column)>; namespace details { using std::begin; using std::end; template<class Writer, class T> struct has_save { private: typedef char one; typedef long two; template <typename C> static one test(decltype(save(std::declval<Serializer<Writer>&>(), std::declval<const C&>()))*); template <typename C> static two test(...); public: enum { value = sizeof(test<T>(0)) == sizeof(char) }; }; template<class Reader, class T> struct has_load { private: typedef char one; typedef long two; template <typename C> static one test(decltype(load(std::declval<Deserializer<Reader>&>(), std::declval<C&>()))*); template <typename C> static two test(...); public: enum { value = sizeof(test<T>(0)) == sizeof(char) }; }; template<class T> struct is_range { private: typedef char one; typedef long two; template <typename C> static one test(decltype(begin(std::declval<C&>()))*, decltype(end(std::declval<C&>()))*); template <typename C> static two test(...); public: enum { value = sizeof(test<T>(0, 0)) == sizeof(char) }; }; template<class T> struct has_key_type { private: typedef char one; typedef long two; template <typename C> static one test(typename C::key_type*); template <typename C> static two test(...); public: enum { value = sizeof(test<T>(0)) == sizeof(char) }; }; template<class T> struct has_mapped_type { private: typedef char one; typedef long two; template <typename C> static one test(typename C::mapped_type*); template <typename C> static two test(...); public: enum { value = sizeof(test<T>(0)) == sizeof(char) }; }; template<class T> struct is_map { enum { value = is_range<T>::value && has_key_type<T>::value && has_mapped_type<T>::value }; }; template<class T> struct is_set { enum { value = is_range<T>::value && has_key_type<T>::value && !has_mapped_type<T>::value }; }; template<class T> struct is_list { enum { value = is_range<T>::value && !has_key_type<T>::value && !has_mapped_type<T>::value }; }; } template<typename T> auto vmember(String_literal name, T& v) { return std::pair<String_literal, T&>(name, v); } template<typename Writer> struct Serializer { Serializer(Writer&& w) : writer(std::move(w)) {} template<class T> std::enable_if_t<is_annotated_struct<T>::value> write(const T& inst) { writer.begin_obj(); get_struct_info<T>().for_each([&](auto n, auto mptr) { write_member(n, inst.*mptr); }); writer.end_current(); } template<typename... Members> inline void write_virtual(Members&&... m) { writer.begin_obj(); auto i = {write_member_pair(m)...}; (void)i; writer.end_current(); } private: Writer writer; template<class K, class T> int write_member_pair(std::pair<K, T&> inst) { writer.write(inst.first); write_value(inst.second); return 0; } template<class T> int write_member_pair(std::pair<String_literal, T&> inst) { writer.write(inst.first.data, inst.first.len); write_value(inst.second); return 0; } template<class T> void write_member(String_literal name, const T& inst) { writer.write(name.data, name.len); write_value(inst); } public: template<class T> std::enable_if_t<not details::has_save<Writer,T>::value> write_value(const T* inst) { if(inst) write_value(*inst); else writer.write_nullptr(); } template<class T> std::enable_if_t<not details::has_save<Writer,T>::value> write_value(const std::unique_ptr<T>& inst) { if(inst) write_value(*inst); else writer.write_nullptr(); } template<class T> std::enable_if_t<not details::has_save<Writer,T>::value> write_value(const std::shared_ptr<T>& inst) { if(inst) write_value(*inst); else writer.write_nullptr(); } // annotated struct template<class T> std::enable_if_t<is_annotated_struct<T>::value && not details::has_save<Writer,T>::value> write_value(const T& inst) { writer.begin_obj(); get_struct_info<T>().for_each([&](auto n, auto mptr) { write_member(n, inst.*mptr); }); writer.end_current(); } // annotated enum template<class T> std::enable_if_t<is_annotated_enum<T>::value && not details::has_save<Writer,T>::value> write_value(const T& inst) { auto name = get_enum_info<T>().name_of(inst); writer.write(name.data, name.len); } // map template<class T> std::enable_if_t<not is_annotated<T>::value && not details::has_save<Writer,T>::value && details::is_map<T>::value> write_value(const T& inst) { writer.begin_obj(); for(auto& v : inst) { write_value(v.first); write_value(v.second); } writer.end_current(); } // other collection template<class T> std::enable_if_t<not is_annotated<T>::value && not details::has_save<Writer,T>::value && (details::is_list<T>::value || details::is_set<T>::value)> write_value(const T& inst) { writer.begin_array(); for(auto& v : inst) write_value(v); writer.end_current(); } // manual save-function template<class T> std::enable_if_t<details::has_save<Writer,T>::value> write_value(const T& inst) { save(*this, inst); } // other template<class T> std::enable_if_t<not is_annotated<T>::value && not details::is_range<T>::value && not details::has_save<Writer,T>::value> write_value(const T& inst) { writer.write(inst); } void write_value(const std::string& inst) { writer.write(inst); } void write_value(const char* inst) { writer.write(inst); } }; template<typename Writer, typename T> inline void serialize(Writer&& w, const T& v) { Serializer<Writer>{std::move(w)}.write(v); } template<typename Writer, typename... Members> inline void serialize_virtual(Writer&& w, Members&&... m) { Serializer<Writer>{std::move(w)}.write_virtual(std::forward<Members>(m)...); } template<typename Reader> struct Deserializer { Deserializer(Reader&& r, Error_handler error_handler=Error_handler()) : reader(std::move(r)), error_handler(error_handler) { buffer.reserve(64); } template<class T> std::enable_if_t<is_annotated_struct<T>::value> read(T& inst) { while(reader.in_obj()) { reader.read(buffer); auto match = false; auto key = String_literal{buffer}; get_struct_info<T>().for_each([&](String_literal n, auto mptr) { if(!match && n==key) { read_value(inst.*mptr); match = true; } }); if(!match) { on_error("Unexpected key "+buffer); } } } template<typename... Members> inline void read_virtual(Members&&... m) { while(reader.in_obj()) { reader.read(buffer); bool match = false; auto key = String_literal{buffer}; auto i = {read_member_pair(match, key, m)...}; (void)i; if(!match) { on_error("Unexpected key "+buffer); } } } template<typename Func> inline void read_lambda(Func func) { while(reader.in_obj()) { reader.read(buffer); bool match = func(buffer); if(!match) { on_error("Unexpected key "+buffer); } } } private: Reader reader; std::string buffer; Error_handler error_handler; void on_error(const std::string& e) { if(error_handler) error_handler(e, reader.row(), reader.column()); else std::cerr<<"Error parsing JSON at "<<reader.row()<<":"<<reader.column()<<" : "<<e<<std::endl; } template<class K, class T> int read_member_pair(bool& match, String_literal n, std::pair<K, T&> inst) { if(!match && inst.first==n) { read_value(inst.second); match = true; } return 0; } public: template<class T> std::enable_if_t<not details::has_load<Reader,T>::value> read_value(std::unique_ptr<T>& inst) { if(reader.read_nullptr()) inst = nullptr; else { inst = std::make_unique<T>(); read_value(*inst); } } template<class T> std::enable_if_t<not details::has_load<Reader,T>::value> read_value(std::shared_ptr<T>& inst) { if(reader.read_nullptr()) inst = nullptr; else { inst = std::make_shared<T>(); read_value(*inst); } } // annotated struct template<class T> std::enable_if_t<is_annotated_struct<T>::value && not details::has_load<Reader,T>::value> read_value(T& inst) { while(reader.in_obj()) { reader.read(buffer); bool match = false; auto key = String_literal{buffer}; get_struct_info<T>().for_each([&](auto n, auto mptr) { if(!match && n==key) { read_value(inst.*mptr); match = true; } }); if(!match) { on_error("Unexpected key "+buffer); } } } // annotated enum template<class T> std::enable_if_t<is_annotated_enum<T>::value && not details::has_load<Reader,T>::value> read_value(T& inst) { reader.read(buffer); inst = get_enum_info<T>().value_of(buffer); } // map template<class T> std::enable_if_t<not is_annotated<T>::value && not details::has_load<Reader,T>::value && details::is_map<T>::value> read_value(T& inst) { inst.clear(); typename T::key_type key; typename T::mapped_type val; while(reader.in_obj()) { read_value(key); read_value(val); inst.emplace(std::move(key), std::move(val)); } } //set template<class T> std::enable_if_t<not is_annotated<T>::value && not details::has_load<Reader,T>::value && details::is_set<T>::value> read_value(T& inst) { inst.clear(); typename T::value_type v; while(reader.in_array()) { read_value(v); inst.emplace(std::move(v)); } } // other collection template<class T> std::enable_if_t<not is_annotated<T>::value && not details::has_load<Reader,T>::value && details::is_list<T>::value> read_value(T& inst) { inst.clear(); typename T::value_type v; while(reader.in_array()) { read_value(v); inst.emplace_back(std::move(v)); } } // manual load-function template<class T> std::enable_if_t<details::has_load<Reader,T>::value> read_value(T& inst) { load(*this, inst); } // other template<class T> std::enable_if_t<not is_annotated<T>::value && not details::is_range<T>::value && not details::has_load<Reader,T>::value> read_value(T& inst) { reader.read(inst); } void read_value(std::string& inst) { reader.read(inst); } }; template<typename Reader, typename T> inline void deserialize(Reader&& r, T& v) { Deserializer<Reader>{std::move(r)}.read(v); } template<typename Reader, typename... Members> inline void deserialize_virtual(Reader&& r, Members&&... m) { Deserializer<Reader>{std::move(r)}.read_virtual(std::forward<Members>(m)...); } } <|endoftext|>
<commit_before>/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "StompHelper.h" #include <activemq/wireformat/stomp/StompCommandConstants.h> #include <activemq/commands/LocalTransactionId.h> #include <decaf/util/StringTokenizer.h> #include <decaf/lang/Integer.h> #include <decaf/lang/Boolean.h> #include <decaf/lang/Long.h> using namespace std; using namespace activemq; using namespace activemq::commands; using namespace activemq::wireformat; using namespace activemq::wireformat::stomp; using namespace decaf; using namespace decaf::lang; using namespace decaf::util; //////////////////////////////////////////////////////////////////////////////// void StompHelper::convertProperties( const Pointer<StompFrame>& frame, const Pointer<Message>& message ) { const std::string destination = frame->removeProperty( StompCommandConstants::HEADER_DESTINATION ); message->setDestination( convertDestination( destination ) ); const std::string messageId = frame->removeProperty( StompCommandConstants::HEADER_MESSAGEID ); message->setMessageId( convertMessageId( messageId ) ); // the standard JMS headers message->setCorrelationId( StompCommandConstants::HEADER_CORRELATIONID ); if( frame->hasProperty( StompCommandConstants::HEADER_EXPIRES ) ) { message->setExpiration( Long::parseLong( frame->removeProperty( StompCommandConstants::HEADER_EXPIRES ) ) ); } if( frame->hasProperty( StompCommandConstants::HEADER_JMSPRIORITY ) ) { message->setPriority( (unsigned char)Integer::parseInt( frame->removeProperty( StompCommandConstants::HEADER_JMSPRIORITY ) ) ); } if( frame->hasProperty( StompCommandConstants::HEADER_TYPE ) ) { message->setType( frame->removeProperty( StompCommandConstants::HEADER_TYPE ) ); } if( frame->hasProperty( StompCommandConstants::HEADER_REPLYTO ) ) { message->setReplyTo( convertDestination( frame->removeProperty( StompCommandConstants::HEADER_REPLYTO ) ) ); } if( frame->hasProperty( StompCommandConstants::HEADER_PERSISTENT ) ) { message->setPersistent( Boolean::parseBoolean( frame->removeProperty( StompCommandConstants::HEADER_PERSISTENT ) ) ); } if( frame->hasProperty( StompCommandConstants::HEADER_TRANSACTIONID ) ) { std::string transactionId = frame->removeProperty( StompCommandConstants::HEADER_TRANSACTIONID ); message->setTransactionId( convertTransactionId( transactionId ) ); } // Handle JMSX Properties. if( frame->hasProperty( "JMSXDeliveryCount" ) ) { message->setRedeliveryCounter( Integer::parseInt( frame->removeProperty( "JMSXDeliveryCount" ) ) ); } if( frame->hasProperty( "JMSXGroupID" ) ) { message->setGroupID( frame->removeProperty( "JMSXGroupID" ) ); } if( frame->hasProperty( "JMSXGroupSeq" ) ) { message->setGroupSequence( Integer::parseInt( frame->removeProperty( "JMSXGroupSeq" ) ) ); } // Copy the general headers over to the Message. std::vector< std::pair<std::string, std::string> > properties = frame->getProperties().toArray(); std::vector< std::pair<std::string, std::string> >::const_iterator iter = properties.begin(); for( ; iter != properties.end(); ++iter ) { message->getMessageProperties().setString( iter->first, iter->second ); } } //////////////////////////////////////////////////////////////////////////////// void StompHelper::convertProperties( const Pointer<Message>& message, const Pointer<StompFrame>& frame ) { frame->setProperty( StompCommandConstants::HEADER_DESTINATION, convertDestination( message->getDestination() ) ); if( message->getCorrelationId() != "" ) { frame->setProperty( StompCommandConstants::HEADER_CORRELATIONID, message->getCorrelationId() ); } frame->setProperty( StompCommandConstants::HEADER_EXPIRES, Long::toString( message->getExpiration() ) ); frame->setProperty( StompCommandConstants::HEADER_PERSISTENT, Boolean::toString( message->isPersistent() ) ); if( message->getRedeliveryCounter() != 0 ) { frame->setProperty( StompCommandConstants::HEADER_REDELIVERED, "true" ); } frame->setProperty( StompCommandConstants::HEADER_JMSPRIORITY, Integer::toString( message->getPriority() ) ); if( message->getReplyTo() != NULL ) { frame->setProperty( StompCommandConstants::HEADER_REPLYTO, convertDestination( message->getReplyTo() ) ); } frame->setProperty( StompCommandConstants::HEADER_TIMESTAMP, Long::toString( message->getTimestamp() ) ); if( message->getType() != "" ) { frame->setProperty( StompCommandConstants::HEADER_TYPE, message->getType() ); } if( message->getTransactionId() != NULL ) { frame->setProperty( StompCommandConstants::HEADER_TRANSACTIONID, convertTransactionId( message->getTransactionId() ) ); } // Handle JMSX Properties. frame->setProperty( "JMSXDeliveryCount", Integer::toString( message->getRedeliveryCounter() ) ); frame->setProperty( "JMSXGroupSeq", Integer::toString( message->getGroupSequence() ) ); if( message->getGroupID() != "" ) { frame->setProperty( "JMSXGroupID", message->getGroupID() ); } std::vector<std::string> keys = message->getMessageProperties().keySet(); std::vector<std::string>::const_iterator iter = keys.begin(); for( ; iter != keys.end(); ++iter ) { frame->setProperty( *iter, message->getMessageProperties().getString( *iter ) ); } } //////////////////////////////////////////////////////////////////////////////// std::string StompHelper::convertDestination( const Pointer<ActiveMQDestination>& destination ) { if( destination == NULL ) { return ""; } else { switch( destination->getDestinationType() ) { case cms::Destination::TOPIC: return std::string( "/topic/" ) + destination->getPhysicalName(); case cms::Destination::TEMPORARY_TOPIC: if( destination->getPhysicalName().find( "/remote-temp-topic/" ) == 0 ) { return destination->getPhysicalName(); } else { return std::string( "/temp-topic/" ) + destination->getPhysicalName(); } case cms::Destination::TEMPORARY_QUEUE: if( destination->getPhysicalName().find( "/remote-temp-queue/" ) == 0 ) { return destination->getPhysicalName(); } else { return std::string( "/temp-queue/" ) + destination->getPhysicalName(); } default: return std::string( "/queue/" ) + destination->getPhysicalName(); } } } //////////////////////////////////////////////////////////////////////////////// Pointer<ActiveMQDestination> StompHelper::convertDestination( const std::string& destination ) { if( destination == "" ) { return Pointer<ActiveMQDestination>(); } int type = 0; std::string dest = ""; if( destination.find( "/queue/" ) == 0 ) { dest = destination.substr( 7 ); type = cms::Destination::QUEUE; } else if( destination.find( "/topic/" ) == 0 ) { dest = destination.substr( 7 ); type = cms::Destination::TOPIC; } else if( destination.find( "/temp-topic/" ) == 0 ) { dest = destination.substr( 12 ); type = cms::Destination::TEMPORARY_TOPIC; } else if( destination.find( "/temp-queue/" ) == 0 ) { dest = destination.substr( 12 ); type = cms::Destination::TEMPORARY_QUEUE; } else if( destination.find( "/remote-temp-topic/" ) == 0 ) { type = cms::Destination::TEMPORARY_TOPIC; } else if( destination.find( "/remote-temp-queue/" ) == 0 ) { type = cms::Destination::TEMPORARY_QUEUE; } return ActiveMQDestination::createDestination( type, dest ); } //////////////////////////////////////////////////////////////////////////////// std::string StompHelper::convertMessageId( const Pointer<MessageId>& messageId ) { // The Stomp MessageId is always hidden solely in the Producer Id. std::string result = convertProducerId( messageId->getProducerId() ); return result; } //////////////////////////////////////////////////////////////////////////////// Pointer<MessageId> StompHelper::convertMessageId( const std::string& messageId ) { if( messageId == "" ) { return Pointer<MessageId>(); } Pointer<MessageId> id( new MessageId() ); id->setProducerId( convertProducerId( messageId ) ); id->setProducerSequenceId( this->messageIdGenerator.getNextSequenceId() ); return id; } //////////////////////////////////////////////////////////////////////////////// std::string StompHelper::convertConsumerId( const Pointer<ConsumerId>& consumerId ) { return consumerId->getConnectionId() + ":" + Long::toString( consumerId->getSessionId() ) + ":" + Long::toString( consumerId->getValue() ); } //////////////////////////////////////////////////////////////////////////////// Pointer<ConsumerId> StompHelper::convertConsumerId( const std::string& consumerId ) { if( consumerId == "" ) { return Pointer<ConsumerId>(); } Pointer<ConsumerId> id( new ConsumerId() ); StringTokenizer tokenizer( consumerId, ":" ); id->setConnectionId( tokenizer.nextToken() ); while( tokenizer.hasMoreTokens() ){ string text = tokenizer.nextToken(); if( tokenizer.hasMoreTokens() ) { id->setSessionId( Long::parseLong( text ) ); } else { id->setValue( Long::parseLong( text ) ); } } return id; } //////////////////////////////////////////////////////////////////////////////// std::string StompHelper::convertProducerId( const Pointer<ProducerId>& producerId ) { return producerId->getConnectionId(); } //////////////////////////////////////////////////////////////////////////////// Pointer<ProducerId> StompHelper::convertProducerId( const std::string& producerId ) { if( producerId == "" ) { return Pointer<ProducerId>(); } Pointer<ProducerId> id( new ProducerId() ); id->setConnectionId( producerId ); id->setSessionId( -1 ); id->setValue( -1 ); return id; } //////////////////////////////////////////////////////////////////////////////// std::string StompHelper::convertTransactionId( const Pointer<TransactionId>& transactionId ) { Pointer<LocalTransactionId> id = transactionId.dynamicCast<LocalTransactionId>(); std::string result = id->getConnectionId()->getValue() + ":" + Long::toString( id->getValue() ); return result; } //////////////////////////////////////////////////////////////////////////////// Pointer<TransactionId> StompHelper::convertTransactionId( const std::string& transactionId ) { if( transactionId == "" ) { return Pointer<TransactionId>(); } Pointer<LocalTransactionId> id( new LocalTransactionId() ); StringTokenizer tokenizer( transactionId, ":" ); Pointer<ConnectionId> connectionId( new ConnectionId() ); connectionId->setValue( tokenizer.nextToken() ); id->setConnectionId( connectionId ); while( tokenizer.hasMoreTokens() ){ string text = tokenizer.nextToken(); id->setValue( Long::parseLong( text ) ); } return id; } <commit_msg>fix for: https://issues.apache.org/activemq/browse/AMQCPP-317<commit_after>/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "StompHelper.h" #include <activemq/wireformat/stomp/StompCommandConstants.h> #include <activemq/commands/LocalTransactionId.h> #include <decaf/util/StringTokenizer.h> #include <decaf/lang/Integer.h> #include <decaf/lang/Boolean.h> #include <decaf/lang/Long.h> using namespace std; using namespace activemq; using namespace activemq::commands; using namespace activemq::wireformat; using namespace activemq::wireformat::stomp; using namespace decaf; using namespace decaf::lang; using namespace decaf::util; //////////////////////////////////////////////////////////////////////////////// void StompHelper::convertProperties( const Pointer<StompFrame>& frame, const Pointer<Message>& message ) { const std::string destination = frame->removeProperty( StompCommandConstants::HEADER_DESTINATION ); message->setDestination( convertDestination( destination ) ); const std::string messageId = frame->removeProperty( StompCommandConstants::HEADER_MESSAGEID ); message->setMessageId( convertMessageId( messageId ) ); // the standard JMS headers message->setCorrelationId( StompCommandConstants::HEADER_CORRELATIONID ); if( frame->hasProperty( StompCommandConstants::HEADER_EXPIRES ) ) { message->setExpiration( Long::parseLong( frame->removeProperty( StompCommandConstants::HEADER_EXPIRES ) ) ); } if( frame->hasProperty( StompCommandConstants::HEADER_JMSPRIORITY ) ) { message->setPriority( (unsigned char)Integer::parseInt( frame->removeProperty( StompCommandConstants::HEADER_JMSPRIORITY ) ) ); } if( frame->hasProperty( StompCommandConstants::HEADER_TYPE ) ) { message->setType( frame->removeProperty( StompCommandConstants::HEADER_TYPE ) ); } if( frame->hasProperty( StompCommandConstants::HEADER_REPLYTO ) ) { message->setReplyTo( convertDestination( frame->removeProperty( StompCommandConstants::HEADER_REPLYTO ) ) ); } if( frame->hasProperty( StompCommandConstants::HEADER_PERSISTENT ) ) { message->setPersistent( Boolean::parseBoolean( frame->removeProperty( StompCommandConstants::HEADER_PERSISTENT ) ) ); } if( frame->hasProperty( StompCommandConstants::HEADER_TRANSACTIONID ) ) { std::string transactionId = frame->removeProperty( StompCommandConstants::HEADER_TRANSACTIONID ); message->setTransactionId( convertTransactionId( transactionId ) ); } // Handle JMSX Properties. if( frame->hasProperty( "JMSXDeliveryCount" ) ) { message->setRedeliveryCounter( Integer::parseInt( frame->removeProperty( "JMSXDeliveryCount" ) ) ); } if( frame->hasProperty( "JMSXGroupID" ) ) { message->setGroupID( frame->removeProperty( "JMSXGroupID" ) ); } if( frame->hasProperty( "JMSXGroupSeq" ) ) { message->setGroupSequence( Integer::parseInt( frame->removeProperty( "JMSXGroupSeq" ) ) ); } // Copy the general headers over to the Message. std::vector< std::pair<std::string, std::string> > properties = frame->getProperties().toArray(); std::vector< std::pair<std::string, std::string> >::const_iterator iter = properties.begin(); for( ; iter != properties.end(); ++iter ) { message->getMessageProperties().setString( iter->first, iter->second ); } } //////////////////////////////////////////////////////////////////////////////// void StompHelper::convertProperties( const Pointer<Message>& message, const Pointer<StompFrame>& frame ) { frame->setProperty( StompCommandConstants::HEADER_DESTINATION, convertDestination( message->getDestination() ) ); if( message->getCorrelationId() != "" ) { frame->setProperty( StompCommandConstants::HEADER_CORRELATIONID, message->getCorrelationId() ); } frame->setProperty( StompCommandConstants::HEADER_EXPIRES, Long::toString( message->getExpiration() ) ); frame->setProperty( StompCommandConstants::HEADER_PERSISTENT, Boolean::toString( message->isPersistent() ) ); if( message->getRedeliveryCounter() != 0 ) { frame->setProperty( StompCommandConstants::HEADER_REDELIVERED, "true" ); } frame->setProperty( StompCommandConstants::HEADER_JMSPRIORITY, Integer::toString( message->getPriority() ) ); if( message->getReplyTo() != NULL ) { frame->setProperty( StompCommandConstants::HEADER_REPLYTO, convertDestination( message->getReplyTo() ) ); } frame->setProperty( StompCommandConstants::HEADER_TIMESTAMP, Long::toString( message->getTimestamp() ) ); if( message->getType() != "" ) { frame->setProperty( StompCommandConstants::HEADER_TYPE, message->getType() ); } if( message->getTransactionId() != NULL ) { frame->setProperty( StompCommandConstants::HEADER_TRANSACTIONID, convertTransactionId( message->getTransactionId() ) ); } // Handle JMSX Properties. frame->setProperty( "JMSXDeliveryCount", Integer::toString( message->getRedeliveryCounter() ) ); frame->setProperty( "JMSXGroupSeq", Integer::toString( message->getGroupSequence() ) ); if( message->getGroupID() != "" ) { frame->setProperty( "JMSXGroupID", message->getGroupID() ); } std::vector<std::string> keys = message->getMessageProperties().keySet(); std::vector<std::string>::const_iterator iter = keys.begin(); for( ; iter != keys.end(); ++iter ) { frame->setProperty( *iter, message->getMessageProperties().getString( *iter ) ); } } //////////////////////////////////////////////////////////////////////////////// std::string StompHelper::convertDestination( const Pointer<ActiveMQDestination>& destination ) { if( destination == NULL ) { return ""; } else { switch( destination->getDestinationType() ) { case cms::Destination::TOPIC: return std::string( "/topic/" ) + destination->getPhysicalName(); case cms::Destination::TEMPORARY_TOPIC: if( destination->getPhysicalName().find( "/remote-temp-topic/" ) == 0 ) { return destination->getPhysicalName(); } else { return std::string( "/temp-topic/" ) + destination->getPhysicalName(); } case cms::Destination::TEMPORARY_QUEUE: if( destination->getPhysicalName().find( "/remote-temp-queue/" ) == 0 ) { return destination->getPhysicalName(); } else { return std::string( "/temp-queue/" ) + destination->getPhysicalName(); } default: return std::string( "/queue/" ) + destination->getPhysicalName(); } } } //////////////////////////////////////////////////////////////////////////////// Pointer<ActiveMQDestination> StompHelper::convertDestination( const std::string& destination ) { if( destination == "" ) { return Pointer<ActiveMQDestination>(); } int type = 0; std::string dest = ""; if( destination.find( "/queue/" ) == 0 ) { dest = destination.substr( 7 ); type = cms::Destination::QUEUE; } else if( destination.find( "/topic/" ) == 0 ) { dest = destination.substr( 7 ); type = cms::Destination::TOPIC; } else if( destination.find( "/temp-topic/" ) == 0 ) { dest = destination.substr( 12 ); type = cms::Destination::TEMPORARY_TOPIC; } else if( destination.find( "/temp-queue/" ) == 0 ) { dest = destination.substr( 12 ); type = cms::Destination::TEMPORARY_QUEUE; } else if( destination.find( "/remote-temp-topic/" ) == 0 ) { type = cms::Destination::TEMPORARY_TOPIC; } else if( destination.find( "/remote-temp-queue/" ) == 0 ) { type = cms::Destination::TEMPORARY_QUEUE; } return ActiveMQDestination::createDestination( type, dest ); } //////////////////////////////////////////////////////////////////////////////// std::string StompHelper::convertMessageId( const Pointer<MessageId>& messageId ) { // The Stomp MessageId is always hidden solely in the Producer Id. std::string result = convertProducerId( messageId->getProducerId() ); return result; } //////////////////////////////////////////////////////////////////////////////// Pointer<MessageId> StompHelper::convertMessageId( const std::string& messageId ) { if( messageId == "" ) { return Pointer<MessageId>(); } Pointer<MessageId> id( new MessageId() ); id->setProducerId( convertProducerId( messageId ) ); id->setProducerSequenceId( this->messageIdGenerator.getNextSequenceId() ); return id; } //////////////////////////////////////////////////////////////////////////////// std::string StompHelper::convertConsumerId( const Pointer<ConsumerId>& consumerId ) { return consumerId->getConnectionId() + ":" + Long::toString( consumerId->getSessionId() ) + ":" + Long::toString( consumerId->getValue() ); } //////////////////////////////////////////////////////////////////////////////// Pointer<ConsumerId> StompHelper::convertConsumerId( const std::string& consumerId ) { if( consumerId == "" ) { return Pointer<ConsumerId>(); } Pointer<ConsumerId> id( new ConsumerId() ); StringTokenizer tokenizer( consumerId, ":" ); string connectionId; connectionId += tokenizer.nextToken(); connectionId += ":"; connectionId += tokenizer.nextToken(); connectionId += ":"; connectionId += tokenizer.nextToken(); id->setConnectionId( connectionId ); while( tokenizer.hasMoreTokens() ){ string text = tokenizer.nextToken(); if( tokenizer.hasMoreTokens() ) { id->setSessionId( Long::parseLong( text ) ); } else { id->setValue( Long::parseLong( text ) ); } } return id; } //////////////////////////////////////////////////////////////////////////////// std::string StompHelper::convertProducerId( const Pointer<ProducerId>& producerId ) { return producerId->getConnectionId(); } //////////////////////////////////////////////////////////////////////////////// Pointer<ProducerId> StompHelper::convertProducerId( const std::string& producerId ) { if( producerId == "" ) { return Pointer<ProducerId>(); } Pointer<ProducerId> id( new ProducerId() ); id->setConnectionId( producerId ); id->setSessionId( -1 ); id->setValue( -1 ); return id; } //////////////////////////////////////////////////////////////////////////////// std::string StompHelper::convertTransactionId( const Pointer<TransactionId>& transactionId ) { Pointer<LocalTransactionId> id = transactionId.dynamicCast<LocalTransactionId>(); std::string result = id->getConnectionId()->getValue() + ":" + Long::toString( id->getValue() ); return result; } //////////////////////////////////////////////////////////////////////////////// Pointer<TransactionId> StompHelper::convertTransactionId( const std::string& transactionId ) { if( transactionId == "" ) { return Pointer<TransactionId>(); } Pointer<LocalTransactionId> id( new LocalTransactionId() ); StringTokenizer tokenizer( transactionId, ":" ); string connectionIdStr; connectionIdStr += tokenizer.nextToken(); connectionIdStr += ":"; connectionIdStr += tokenizer.nextToken(); Pointer<ConnectionId> connectionId( new ConnectionId() ); connectionId->setValue( connectionIdStr ); id->setConnectionId( connectionId ); while( tokenizer.hasMoreTokens() ){ string text = tokenizer.nextToken(); id->setValue( Long::parseLong( text ) ); } return id; } <|endoftext|>
<commit_before>#ifndef SLICPLUSPLUS_ACTIONS_HPP_ #define SLICPLUSPLUS_ACTIONS_HPP_ #include <vector> #include "MaxFile.hpp" SLIC_BEGIN_NAMESPACE class Actions { std::unique_ptr<max_actions_t, decltype(max_actions_free)*> a; public: explicit Actions(const MaxFile& maxfile, const std::string& mode="") : a(max_actions_init(maxfile.get(), mode.empty() ? NULL : mode.c_str()), max_actions_free) { if (!a) { SLIC_CHECK_ERRORS(maxfile.get()->errors) throw std::runtime_error("Failed to instantiate actions"); } max_errors_mode(a->errors, 0); } max_actions_t* get() const noexcept { return a.get(); } max_actions_t* release() noexcept { return a.release(); } //////////////////// // SCALARS //////////////////// void set(const std::string& blockName, const std::string& regName, uint64_t value) { max_set_uint64t(a.get(), blockName.c_str(), regName.c_str(), value); SLIC_CHECK_ERRORS(a->errors) } void setDouble(const std::string& blockName, const std::string& regName, double value) { max_set_double(a.get(), blockName.c_str(), regName.c_str(), value); SLIC_CHECK_ERRORS(a->errors) } void get(const std::string& blockName, const std::string& regName, uint64_t* ret) { max_get_uint64t(a.get(), blockName.c_str(), regName.c_str(), ret); SLIC_CHECK_ERRORS(a->errors) } void getDouble(const std::string& blockName, const std::string& regName, double* ret) { max_get_double(a.get(), blockName.c_str(), regName.c_str(), ret); SLIC_CHECK_ERRORS(a->errors) } void ignoreScalar(const std::string& blockName, const std::string& regName) { max_ignore_scalar(a.get(), blockName.c_str(), regName.c_str()); SLIC_CHECK_ERRORS(a->errors) } //////////////////// // PARAMS, OFFSETS //////////////////// void setParam(const std::string& name, uint64_t value) { max_set_param_uint64t(a.get(), name.c_str(), value); SLIC_CHECK_ERRORS(a->errors) } void setParamDouble(const std::string& name, double value) { max_set_param_double(a.get(), name.c_str(), value); SLIC_CHECK_ERRORS(a->errors) } void ignoreKernel(const std::string& kernelName) { max_ignore_kernel(a.get(), kernelName.c_str()); SLIC_CHECK_ERRORS(a->errors) } void setTicks(const std::string& kernelName, int ticks) { max_set_ticks(a.get(), kernelName.c_str(), ticks); SLIC_CHECK_ERRORS(a->errors) } void setOffset(const std::string& kernelName, const std::string& varName, int value) { max_set_offset(a.get(), kernelName.c_str(), varName.c_str(), value); SLIC_CHECK_ERRORS(a->errors) } void ignoreOffset(const std::string& kernelName, const std::string& varName) { max_ignore_offset(a.get(), kernelName.c_str(), varName.c_str()); SLIC_CHECK_ERRORS(a->errors) } //////////////////// // MAPPED MEMS //////////////////// void setMem(const std::string& blockName, const std::string& memName, size_t idx, uint64_t value) { max_set_mem_uint64t(a.get(), blockName.c_str(), memName.c_str(), idx, value); SLIC_CHECK_ERRORS(a->errors) } void setMemDouble(const std::string& blockName, const std::string& memName, size_t idx, double value) { max_set_mem_double(a.get(), blockName.c_str(), memName.c_str(), idx, value); SLIC_CHECK_ERRORS(a->errors) } template <typename T> void setMem(const std::string& blockName, const std::string& memName, const std::vector<T>& values) { for (size_t idx = 0; idx < values.size(); ++idx) setMem(blockName, memName, idx, values[idx]); } void getMem(const std::string& blockName, const std::string& memName, size_t idx, uint64_t* ret) { max_get_mem_uint64t(a.get(), blockName.c_str(), memName.c_str(), idx, ret); SLIC_CHECK_ERRORS(a->errors) } void getMemDouble(const std::string& blockName, const std::string& memName, size_t idx, double* ret) { max_get_mem_double(a.get(), blockName.c_str(), memName.c_str(), idx, ret); SLIC_CHECK_ERRORS(a->errors) } void ignoreMem(const std::string& blockName, const std::string& memName) { max_ignore_mem(a.get(), blockName.c_str(), memName.c_str()); SLIC_CHECK_ERRORS(a->errors) } void ignoreMemInput(const std::string& blockName, const std::string& memName) { max_ignore_mem_input(a.get(), blockName.c_str(), memName.c_str()); SLIC_CHECK_ERRORS(a->errors) } void ignoreMemOutput(const std::string& blockName, const std::string& memName) { max_ignore_mem_output(a.get(), blockName.c_str(), memName.c_str()); SLIC_CHECK_ERRORS(a->errors) } //////////////////// // STREAMS //////////////////// void queueInput(const std::string& streamName, const void* data, size_t length) { max_queue_input(a.get(), streamName.c_str(), data, length); SLIC_CHECK_ERRORS(a->errors) } template <typename T> void queueInput(const std::string& streamName, const std::vector<T>& data) { queueInput(streamName, data.data(), data.size()*sizeof(T)); } void queueOutput(const std::string& streamName, void* data, size_t length) { max_queue_output(a.get(), streamName.c_str(), data, length); SLIC_CHECK_ERRORS(a->errors) } //////////////////// // ROUTING //////////////////// void route(const std::string& fromName, const std::string& toName) { max_route(a.get(), fromName.c_str(), toName.empty() ? nullptr : toName.c_str()); SLIC_CHECK_ERRORS(a->errors) } void route(const std::string& route) { max_route_string(a.get(), route.c_str()); SLIC_CHECK_ERRORS(a->errors) } void ignoreRoute(const std::string& blockName) { max_ignore_route(a.get(), blockName.c_str()); SLIC_CHECK_ERRORS(a->errors) } //////////////////// // MISC //////////////////// void disableReset() { max_disable_reset(a.get()); SLIC_CHECK_ERRORS(a->errors) } void disableValidation() { max_disable_validation(a.get()); SLIC_CHECK_ERRORS(a->errors) } /** * 1 = valid, 0 = not valid */ int validate() { auto ret = max_validate(a.get()); SLIC_CHECK_ERRORS(a->errors) return ret; } void setWatchRange(const std::string& kernelName, int minTick, int maxTick) { max_watch_range(a.get(), kernelName.c_str(), minTick, maxTick); SLIC_CHECK_ERRORS(a->errors) } }; SLIC_END_NAMESPACE #endif /* SLICPLUSPLUS_ACTIONS_HPP_ */ <commit_msg>Add ActionsExplicit<commit_after>#ifndef SLICPLUSPLUS_ACTIONS_HPP_ #define SLICPLUSPLUS_ACTIONS_HPP_ #include <vector> #include "MaxFile.hpp" SLIC_BEGIN_NAMESPACE class Actions { protected: std::unique_ptr<max_actions_t, decltype(max_actions_free)*> a; Actions(max_actions_t* actions) : a(actions, max_actions_free) { max_errors_mode(a->errors, 0); } public: explicit Actions(const MaxFile& maxfile, const std::string& mode="") : Actions(max_actions_init(maxfile.get(), mode.empty() ? NULL : mode.c_str())) { if (!a) { SLIC_CHECK_ERRORS(maxfile.get()->errors) throw std::runtime_error("Failed to instantiate actions"); } } max_actions_t* get() const noexcept { return a.get(); } max_actions_t* release() noexcept { return a.release(); } //////////////////// // SCALARS //////////////////// void set(const std::string& blockName, const std::string& regName, uint64_t value) { max_set_uint64t(a.get(), blockName.c_str(), regName.c_str(), value); SLIC_CHECK_ERRORS(a->errors) } void setDouble(const std::string& blockName, const std::string& regName, double value) { max_set_double(a.get(), blockName.c_str(), regName.c_str(), value); SLIC_CHECK_ERRORS(a->errors) } void get(const std::string& blockName, const std::string& regName, uint64_t* ret) { max_get_uint64t(a.get(), blockName.c_str(), regName.c_str(), ret); SLIC_CHECK_ERRORS(a->errors) } void getDouble(const std::string& blockName, const std::string& regName, double* ret) { max_get_double(a.get(), blockName.c_str(), regName.c_str(), ret); SLIC_CHECK_ERRORS(a->errors) } void ignoreScalar(const std::string& blockName, const std::string& regName) { max_ignore_scalar(a.get(), blockName.c_str(), regName.c_str()); SLIC_CHECK_ERRORS(a->errors) } //////////////////// // PARAMS, OFFSETS //////////////////// void setParam(const std::string& name, uint64_t value) { max_set_param_uint64t(a.get(), name.c_str(), value); SLIC_CHECK_ERRORS(a->errors) } void setParamDouble(const std::string& name, double value) { max_set_param_double(a.get(), name.c_str(), value); SLIC_CHECK_ERRORS(a->errors) } void ignoreKernel(const std::string& kernelName) { max_ignore_kernel(a.get(), kernelName.c_str()); SLIC_CHECK_ERRORS(a->errors) } void setTicks(const std::string& kernelName, int ticks) { max_set_ticks(a.get(), kernelName.c_str(), ticks); SLIC_CHECK_ERRORS(a->errors) } void setOffset(const std::string& kernelName, const std::string& varName, int value) { max_set_offset(a.get(), kernelName.c_str(), varName.c_str(), value); SLIC_CHECK_ERRORS(a->errors) } void ignoreOffset(const std::string& kernelName, const std::string& varName) { max_ignore_offset(a.get(), kernelName.c_str(), varName.c_str()); SLIC_CHECK_ERRORS(a->errors) } //////////////////// // MAPPED MEMS //////////////////// void setMem(const std::string& blockName, const std::string& memName, size_t idx, uint64_t value) { max_set_mem_uint64t(a.get(), blockName.c_str(), memName.c_str(), idx, value); SLIC_CHECK_ERRORS(a->errors) } void setMemDouble(const std::string& blockName, const std::string& memName, size_t idx, double value) { max_set_mem_double(a.get(), blockName.c_str(), memName.c_str(), idx, value); SLIC_CHECK_ERRORS(a->errors) } template <typename T> void setMem(const std::string& blockName, const std::string& memName, const std::vector<T>& values) { for (size_t idx = 0; idx < values.size(); ++idx) setMem(blockName, memName, idx, values[idx]); } void getMem(const std::string& blockName, const std::string& memName, size_t idx, uint64_t* ret) { max_get_mem_uint64t(a.get(), blockName.c_str(), memName.c_str(), idx, ret); SLIC_CHECK_ERRORS(a->errors) } void getMemDouble(const std::string& blockName, const std::string& memName, size_t idx, double* ret) { max_get_mem_double(a.get(), blockName.c_str(), memName.c_str(), idx, ret); SLIC_CHECK_ERRORS(a->errors) } void ignoreMem(const std::string& blockName, const std::string& memName) { max_ignore_mem(a.get(), blockName.c_str(), memName.c_str()); SLIC_CHECK_ERRORS(a->errors) } void ignoreMemInput(const std::string& blockName, const std::string& memName) { max_ignore_mem_input(a.get(), blockName.c_str(), memName.c_str()); SLIC_CHECK_ERRORS(a->errors) } void ignoreMemOutput(const std::string& blockName, const std::string& memName) { max_ignore_mem_output(a.get(), blockName.c_str(), memName.c_str()); SLIC_CHECK_ERRORS(a->errors) } //////////////////// // STREAMS //////////////////// void queueInput(const std::string& streamName, const void* data, size_t length) { max_queue_input(a.get(), streamName.c_str(), data, length); SLIC_CHECK_ERRORS(a->errors) } template <typename T> void queueInput(const std::string& streamName, const std::vector<T>& data) { queueInput(streamName, data.data(), data.size()*sizeof(T)); } void queueOutput(const std::string& streamName, void* data, size_t length) { max_queue_output(a.get(), streamName.c_str(), data, length); SLIC_CHECK_ERRORS(a->errors) } //////////////////// // ROUTING //////////////////// void route(const std::string& fromName, const std::string& toName) { max_route(a.get(), fromName.c_str(), toName.empty() ? nullptr : toName.c_str()); SLIC_CHECK_ERRORS(a->errors) } void route(const std::string& route) { max_route_string(a.get(), route.c_str()); SLIC_CHECK_ERRORS(a->errors) } void ignoreRoute(const std::string& blockName) { max_ignore_route(a.get(), blockName.c_str()); SLIC_CHECK_ERRORS(a->errors) } //////////////////// // MISC //////////////////// void disableReset() { max_disable_reset(a.get()); SLIC_CHECK_ERRORS(a->errors) } void disableValidation() { max_disable_validation(a.get()); SLIC_CHECK_ERRORS(a->errors) } /** * 1 = valid, 0 = not valid */ int validate() { auto ret = max_validate(a.get()); SLIC_CHECK_ERRORS(a->errors) return ret; } void setWatchRange(const std::string& kernelName, int minTick, int maxTick) { max_watch_range(a.get(), kernelName.c_str(), minTick, maxTick); SLIC_CHECK_ERRORS(a->errors) } }; class ActionsExplicit : public Actions { explicit ActionsExplicit(const MaxFile& maxfile) : Actions(max_actions_init_explicit(maxfile.get())) { if (!a) { SLIC_CHECK_ERRORS(maxfile.get()->errors) throw std::runtime_error("Failed to instantiate explicit actions"); } } }; SLIC_END_NAMESPACE #endif /* SLICPLUSPLUS_ACTIONS_HPP_ */ <|endoftext|>
<commit_before>#pragma once #include <theui/window.hpp> #include <string> namespace the { namespace ui { using CharSize = Size; template < typename Text > class TextBox: public Window { public: using Texts = typename Text::Container; TextBox( const Texts& content, const Window::Coordinate& top_left, const Size& window_size ) : Window(top_left, window_size) { set_content_and_resize_if_needed( content ); m_dispatcher.register_listener< Resized >( [ this ]( const Resized& ){ handle_resize(); } ); } using Line = Texts; using Lines = std::vector< Texts >; const Lines& lines() const { return m_lines; } void set_content( const Texts& content ) { set_content_and_resize_if_needed( content ); } private: void handle_resize() { Line collapsed_lines; for ( const auto& line : m_lines ) { std::copy( std::begin( line ), std::end( line ), std::back_inserter( collapsed_lines ) ); } set_content_and_resize_if_needed( collapsed_lines ); } void set_content_and_resize_if_needed( const Texts& content ) { const auto previous_number_of_lines( m_lines.size() ); split_up( content ).swap( m_lines ); if ( previous_number_of_lines != m_lines.size() ) { update_height_to_fit_text(); } } void update_height_to_fit_text() { const int needed_height( m_lines.back().back().height() * m_lines.size() ); const int keep_width( size().width ); resize( { keep_width, needed_height } ); } //todo: extract to function outside of TextBox Lines split_up( const Texts& content ) { Lines lines; Line next_line; int current_width{ 0 }; for ( const auto& word : content ) { int next_width( current_width + word.width() ); if ( next_width <= size().width ) { next_line.push_back( word ); current_width = next_width; continue; } lines.push_back( next_line ); Line( 1, word ).swap( next_line ); current_width = word.width(); } const bool has_leftover{ !next_line.empty() }; if ( has_leftover ) { lines.push_back( next_line ); } return lines; } Lines m_lines; }; } } <commit_msg>split up too long line<commit_after>#pragma once #include <theui/window.hpp> #include <string> namespace the { namespace ui { using CharSize = Size; template < typename Text > class TextBox: public Window { public: using Texts = typename Text::Container; TextBox( const Texts& content, const Window::Coordinate& top_left, const Size& window_size ) : Window(top_left, window_size) { set_content_and_resize_if_needed( content ); m_dispatcher.register_listener< Resized >( [ this ]( const Resized& ) { handle_resize(); } ); } using Line = Texts; using Lines = std::vector< Texts >; const Lines& lines() const { return m_lines; } void set_content( const Texts& content ) { set_content_and_resize_if_needed( content ); } private: void handle_resize() { Line collapsed_lines; for ( const auto& line : m_lines ) { std::copy( std::begin( line ), std::end( line ), std::back_inserter( collapsed_lines ) ); } set_content_and_resize_if_needed( collapsed_lines ); } void set_content_and_resize_if_needed( const Texts& content ) { const auto previous_number_of_lines( m_lines.size() ); split_up( content ).swap( m_lines ); if ( previous_number_of_lines != m_lines.size() ) { update_height_to_fit_text(); } } void update_height_to_fit_text() { const int needed_height( m_lines.back().back().height() * m_lines.size() ); const int keep_width( size().width ); resize( { keep_width, needed_height } ); } //todo: extract to function outside of TextBox Lines split_up( const Texts& content ) { Lines lines; Line next_line; int current_width{ 0 }; for ( const auto& word : content ) { int next_width( current_width + word.width() ); if ( next_width <= size().width ) { next_line.push_back( word ); current_width = next_width; continue; } lines.push_back( next_line ); Line( 1, word ).swap( next_line ); current_width = word.width(); } const bool has_leftover{ !next_line.empty() }; if ( has_leftover ) { lines.push_back( next_line ); } return lines; } Lines m_lines; }; } } <|endoftext|>
<commit_before>/************************************************************************/ /* */ /* Copyright 1998-2005 by Ullrich Koethe */ /* Cognitive Systems Group, University of Hamburg, Germany */ /* */ /* This file is part of the VIGRA computer vision library. */ /* You may use, modify, and distribute this software according */ /* to the terms stated in the LICENSE file included in */ /* the VIGRA distribution. */ /* */ /* The VIGRA Website is */ /* http://kogs-www.informatik.uni-hamburg.de/~koethe/vigra/ */ /* Please direct questions, bug reports, and contributions to */ /* [email protected] */ /* */ /* THIS SOFTWARE IS PROVIDED AS IS AND WITHOUT ANY EXPRESS OR */ /* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED */ /* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ /* */ /************************************************************************/ #ifndef VIGRA_MATHUTIL_HXX #define VIGRA_MATHUTIL_HXX #include <cmath> #include <cstdlib> #include "vigra/config.hxx" #include "vigra/numerictraits.hxx" /*! \page MathConstants Mathematical Constants <TT>M_PI, M_SQRT2</TT> <b>\#include</b> "<a href="mathutil_8hxx-source.html">vigra/mathutil.hxx</a>" Since <TT>M_PI</TT> and <TT>M_SQRT2</TT> are not officially standardized, we provide definitions here for those compilers that don't support them. \code #ifndef M_PI # define M_PI 3.14159265358979323846 #endif #ifndef M_SQRT2 # define M_SQRT2 1.41421356237309504880 #endif \endcode */ #ifndef M_PI # define M_PI 3.14159265358979323846 #endif #ifndef M_SQRT2 # define M_SQRT2 1.41421356237309504880 #endif namespace vigra { #ifndef __sun /** \addtogroup MathFunctions Mathematical Functions Useful mathematical functions and functors. */ //@{ /*! The error function. If <tt>erf()</tt> is not provided in the C standard math library (as it should according to the new C99 standard ?), VIGRA implements <tt>erf()</tt> as an approximation of the error function \f[ \mbox{erf}(x) = \int_0^x e^{-x^2} dx \f] according to the formula given in Press et al. "Numerical Recipes". <b>\#include</b> "<a href="mathutil_8hxx-source.html">vigra/mathutil.hxx</a>"<br> Namespace: vigra */ template <class T> double erf(T x) { double t = 1.0/(1.0+0.5*VIGRA_CSTD::fabs(x)); double ans = t*VIGRA_CSTD::exp(-x*x-1.26551223+t*(1.00002368+t*(0.37409196+ t*(0.09678418+t*(-0.18628806+t*(0.27886807+ t*(-1.13520398+t*(1.48851587+t*(-0.82215223+ t*0.17087277))))))))); if (x >= 0.0) return 1.0 - ans; else return ans - 1.0; } #else using VIGRA_CSTD::erf; #endif // import functions into namespace vigra which VIGRA is going to overload using VIGRA_CSTD::pow; using VIGRA_CSTD::floor; using VIGRA_CSTD::ceil; using std::abs; #define VIGRA_DEFINE_UNSIGNED_ABS(T) \ inline T abs(T t) { return t; } VIGRA_DEFINE_UNSIGNED_ABS(bool) VIGRA_DEFINE_UNSIGNED_ABS(unsigned char) VIGRA_DEFINE_UNSIGNED_ABS(unsigned short) VIGRA_DEFINE_UNSIGNED_ABS(unsigned int) VIGRA_DEFINE_UNSIGNED_ABS(unsigned long) #undef VIGRA_DEFINE_UNSIGNED_ABS /*! The rounding function. Defined for all floating point types. Rounds towards the nearest integer for both positive and negative inputs. <b>\#include</b> "<a href="mathutil_8hxx-source.html">vigra/mathutil.hxx</a>"<br> Namespace: vigra */ inline float round(float t) { return t >= 0.0 ? floor(t + 0.5) : ceil(t - 0.5); } inline double round(double t) { return t >= 0.0 ? floor(t + 0.5) : ceil(t - 0.5); } inline long double round(long double t) { return t >= 0.0 ? floor(t + 0.5) : ceil(t - 0.5); } /*! The square function. sq(x) is needed so often that it makes sense to define it as a function. <b>\#include</b> "<a href="mathutil_8hxx-source.html">vigra/mathutil.hxx</a>"<br> Namespace: vigra */ template <class T> inline typename NumericTraits<T>::Promote sq(T t) { return t*t; } #ifdef VIGRA_NO_HYPOT /*! Compute the Euclidean distance (length of the hypothenuse of a right-angled triangle). The hypot() function returns the sqrt(a*a + b*b). It is implemented in a way that minimizes round-off error. <b>\#include</b> "<a href="mathutil_8hxx-source.html">vigra/mathutil.hxx</a>"<br> Namespace: vigra */ template <class T> T hypot(T a, T b) { T absa = abs(a), absb = abs(b); if (absa > absb) return absa * VIGRA_CSTD::sqrt(1.0 + sq(absb/absa)); else return absb == NumericTraits<T>::zero() ? NumericTraits<T>::zero() : absb * VIGRA_CSTD::sqrt(1.0 + sq(absa/absb)); } #else using ::hypot; #endif /*! The sign function. Returns 1, 0, or -1 depending on the sign of \a t. <b>\#include</b> "<a href="mathutil_8hxx-source.html">vigra/mathutil.hxx</a>"<br> Namespace: vigra */ template <class T> T sign(T t) { return t > NumericTraits<T>::zero() ? NumericTraits<T>::one() : t < NumericTraits<T>::zero() ? -NumericTraits<T>::one() : NumericTraits<T>::zero(); } /*! The binary sign function. Transfers the sign of \a t2 to \a t1. <b>\#include</b> "<a href="mathutil_8hxx-source.html">vigra/mathutil.hxx</a>"<br> Namespace: vigra */ template <class T1, class T2> T1 sign(T1 t1, T2 t2) { return t2 >= NumericTraits<T2>::zero() ? abs(t1) : -abs(t1); } #define VIGRA_DEFINE_NORM(T) \ inline NormTraits<T>::SquaredNormType squaredNorm(T t) { return sq(t); } \ inline NormTraits<T>::NormType norm(T t) { return abs(t); } VIGRA_DEFINE_NORM(bool) VIGRA_DEFINE_NORM(signed char) VIGRA_DEFINE_NORM(unsigned char) VIGRA_DEFINE_NORM(short) VIGRA_DEFINE_NORM(unsigned short) VIGRA_DEFINE_NORM(int) VIGRA_DEFINE_NORM(unsigned int) VIGRA_DEFINE_NORM(long) VIGRA_DEFINE_NORM(unsigned long) VIGRA_DEFINE_NORM(float) VIGRA_DEFINE_NORM(double) VIGRA_DEFINE_NORM(long double) #undef VIGRA_DEFINE_NORM template <class T> inline typename NormTraits<std::complex<T> >::SquaredNormType squaredNorm(std::complex<T> const & t) { return sq(t.real()) + sq(t.imag()); } #ifdef DOXYGEN // only for documentation /*! The squared norm of a numerical object. For scalar types: equals <tt>vigra::sq(t)</tt><br>. For vectorial types: equals <tt>vigra::dot(t, t)</tt><br>. For complex types: equals <tt>vigra::sq(t.real()) + vigra::sq(t.imag())</tt><br>. For matrix types: results in the squared Frobenius norm (sum of squares of the matrix elements). */ NormTraits<T>::SquaredNormType squaredNorm(T const & t); #endif /*! The norm of a numerical object. For scalar types: implemented as <tt>abs(t)</tt><br> otherwise: implemented as <tt>sqrt(squaredNorm(t))</tt>. <b>\#include</b> "<a href="mathutil_8hxx-source.html">vigra/mathutil.hxx</a>"<br> Namespace: vigra */ template <class T> inline typename NormTraits<T>::NormType norm(T const & t) { return VIGRA_CSTD::sqrt(static_cast<typename NormTraits<T>::NormType>(squaredNorm(t))); } namespace detail { // both f1 and f2 are unsigned here template<class FPT> inline FPT safeFloatDivision( FPT f1, FPT f2 ) { return f2 < NumericTraits<FPT>::one() && f1 > f2 * NumericTraits<FPT>::max() ? NumericTraits<FPT>::max() : (f2 > NumericTraits<FPT>::one() && f1 < f2 * NumericTraits<FPT>::smallestPositive()) || f1 == NumericTraits<FPT>::zero() ? NumericTraits<FPT>::zero() : f1/f2; } } // namespace detail /*! Tolerance based floating-point equality. Check whether two floating point numbers are equal within the given tolerance. This is useful because floating point numbers that should be equal in theory are rarely exactly equal in practice. If the tolerance \a epsilon is not given, 2.0 the machine epsilon is used. <b>\#include</b> "<a href="mathutil_8hxx-source.html">vigra/mathutil.hxx</a>"<br> Namespace: vigra */ template <class T1, class T2> bool closeAtTolerance(T1 l, T2 r, typename PromoteTraits<T1, T2>::Promote epsilon) { typedef typename PromoteTraits<T1, T2>::Promote T; if(l == 0.0 && r != 0.0) return VIGRA_CSTD::fabs(r) <= epsilon; if(l != 0.0 && r == 0.0) return VIGRA_CSTD::fabs(r) <= epsilon; T diff = VIGRA_CSTD::fabs( l - r ); T d1 = detail::safeFloatDivision<T>( diff, VIGRA_CSTD::fabs( r ) ); T d2 = detail::safeFloatDivision<T>( diff, VIGRA_CSTD::fabs( l ) ); return (d1 <= epsilon && d2 <= epsilon); } template <class T1, class T2> bool closeAtTolerance(T1 l, T2 r) { typedef typename PromoteTraits<T1, T2>::Promote T; return closeAtTolerance(l, r, 2.0 * NumericTraits<T>::epsilon()); } //@} } // namespace vigra #endif /* VIGRA_MATHUTIL_HXX */ <commit_msg>improved documentation<commit_after>/************************************************************************/ /* */ /* Copyright 1998-2005 by Ullrich Koethe */ /* Cognitive Systems Group, University of Hamburg, Germany */ /* */ /* This file is part of the VIGRA computer vision library. */ /* You may use, modify, and distribute this software according */ /* to the terms stated in the LICENSE file included in */ /* the VIGRA distribution. */ /* */ /* The VIGRA Website is */ /* http://kogs-www.informatik.uni-hamburg.de/~koethe/vigra/ */ /* Please direct questions, bug reports, and contributions to */ /* [email protected] */ /* */ /* THIS SOFTWARE IS PROVIDED AS IS AND WITHOUT ANY EXPRESS OR */ /* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED */ /* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ /* */ /************************************************************************/ #ifndef VIGRA_MATHUTIL_HXX #define VIGRA_MATHUTIL_HXX #include <cmath> #include <cstdlib> #include "vigra/config.hxx" #include "vigra/numerictraits.hxx" /*! \page MathConstants Mathematical Constants <TT>M_PI, M_SQRT2</TT> <b>\#include</b> "<a href="mathutil_8hxx-source.html">vigra/mathutil.hxx</a>" Since <TT>M_PI</TT> and <TT>M_SQRT2</TT> are not officially standardized, we provide definitions here for those compilers that don't support them. \code #ifndef M_PI # define M_PI 3.14159265358979323846 #endif #ifndef M_SQRT2 # define M_SQRT2 1.41421356237309504880 #endif \endcode */ #ifndef M_PI # define M_PI 3.14159265358979323846 #endif #ifndef M_SQRT2 # define M_SQRT2 1.41421356237309504880 #endif namespace vigra { #ifndef __sun /** \addtogroup MathFunctions Mathematical Functions Useful mathematical functions and functors. */ //@{ /*! The error function. If <tt>erf()</tt> is not provided in the C standard math library (as it should according to the new C99 standard ?), VIGRA implements <tt>erf()</tt> as an approximation of the error function \f[ \mbox{erf}(x) = \int_0^x e^{-x^2} dx \f] according to the formula given in Press et al. "Numerical Recipes". <b>\#include</b> "<a href="mathutil_8hxx-source.html">vigra/mathutil.hxx</a>"<br> Namespace: vigra */ template <class T> double erf(T x) { double t = 1.0/(1.0+0.5*VIGRA_CSTD::fabs(x)); double ans = t*VIGRA_CSTD::exp(-x*x-1.26551223+t*(1.00002368+t*(0.37409196+ t*(0.09678418+t*(-0.18628806+t*(0.27886807+ t*(-1.13520398+t*(1.48851587+t*(-0.82215223+ t*0.17087277))))))))); if (x >= 0.0) return 1.0 - ans; else return ans - 1.0; } #else using VIGRA_CSTD::erf; #endif // import functions into namespace vigra which VIGRA is going to overload using VIGRA_CSTD::pow; using VIGRA_CSTD::floor; using VIGRA_CSTD::ceil; using std::abs; #define VIGRA_DEFINE_UNSIGNED_ABS(T) \ inline T abs(T t) { return t; } VIGRA_DEFINE_UNSIGNED_ABS(bool) VIGRA_DEFINE_UNSIGNED_ABS(unsigned char) VIGRA_DEFINE_UNSIGNED_ABS(unsigned short) VIGRA_DEFINE_UNSIGNED_ABS(unsigned int) VIGRA_DEFINE_UNSIGNED_ABS(unsigned long) #undef VIGRA_DEFINE_UNSIGNED_ABS /*! The rounding function. Defined for all floating point types. Rounds towards the nearest integer for both positive and negative inputs. <b>\#include</b> "<a href="mathutil_8hxx-source.html">vigra/mathutil.hxx</a>"<br> Namespace: vigra */ inline float round(float t) { return t >= 0.0 ? floor(t + 0.5) : ceil(t - 0.5); } inline double round(double t) { return t >= 0.0 ? floor(t + 0.5) : ceil(t - 0.5); } inline long double round(long double t) { return t >= 0.0 ? floor(t + 0.5) : ceil(t - 0.5); } /*! The square function. sq(x) is needed so often that it makes sense to define it as a function. <b>\#include</b> "<a href="mathutil_8hxx-source.html">vigra/mathutil.hxx</a>"<br> Namespace: vigra */ template <class T> inline typename NumericTraits<T>::Promote sq(T t) { return t*t; } #ifdef VIGRA_NO_HYPOT /*! Compute the Euclidean distance (length of the hypothenuse of a right-angled triangle). The hypot() function returns the sqrt(a*a + b*b). It is implemented in a way that minimizes round-off error. <b>\#include</b> "<a href="mathutil_8hxx-source.html">vigra/mathutil.hxx</a>"<br> Namespace: vigra */ template <class T> T hypot(T a, T b) { T absa = abs(a), absb = abs(b); if (absa > absb) return absa * VIGRA_CSTD::sqrt(1.0 + sq(absb/absa)); else return absb == NumericTraits<T>::zero() ? NumericTraits<T>::zero() : absb * VIGRA_CSTD::sqrt(1.0 + sq(absa/absb)); } #else using ::hypot; #endif /*! The sign function. Returns 1, 0, or -1 depending on the sign of \a t. <b>\#include</b> "<a href="mathutil_8hxx-source.html">vigra/mathutil.hxx</a>"<br> Namespace: vigra */ template <class T> T sign(T t) { return t > NumericTraits<T>::zero() ? NumericTraits<T>::one() : t < NumericTraits<T>::zero() ? -NumericTraits<T>::one() : NumericTraits<T>::zero(); } /*! The binary sign function. Transfers the sign of \a t2 to \a t1. <b>\#include</b> "<a href="mathutil_8hxx-source.html">vigra/mathutil.hxx</a>"<br> Namespace: vigra */ template <class T1, class T2> T1 sign(T1 t1, T2 t2) { return t2 >= NumericTraits<T2>::zero() ? abs(t1) : -abs(t1); } #define VIGRA_DEFINE_NORM(T) \ inline NormTraits<T>::SquaredNormType squaredNorm(T t) { return sq(t); } \ inline NormTraits<T>::NormType norm(T t) { return abs(t); } VIGRA_DEFINE_NORM(bool) VIGRA_DEFINE_NORM(signed char) VIGRA_DEFINE_NORM(unsigned char) VIGRA_DEFINE_NORM(short) VIGRA_DEFINE_NORM(unsigned short) VIGRA_DEFINE_NORM(int) VIGRA_DEFINE_NORM(unsigned int) VIGRA_DEFINE_NORM(long) VIGRA_DEFINE_NORM(unsigned long) VIGRA_DEFINE_NORM(float) VIGRA_DEFINE_NORM(double) VIGRA_DEFINE_NORM(long double) #undef VIGRA_DEFINE_NORM template <class T> inline typename NormTraits<std::complex<T> >::SquaredNormType squaredNorm(std::complex<T> const & t) { return sq(t.real()) + sq(t.imag()); } #ifdef DOXYGEN // only for documentation /*! The squared norm of a numerical object. For scalar types: equals <tt>vigra::sq(t)</tt><br>. For vectorial types: equals <tt>vigra::dot(t, t)</tt><br>. For complex types: equals <tt>vigra::sq(t.real()) + vigra::sq(t.imag())</tt><br>. For matrix types: results in the squared Frobenius norm (sum of squares of the matrix elements). */ NormTraits<T>::SquaredNormType squaredNorm(T const & t); #endif /*! The norm of a numerical object. For scalar types: implemented as <tt>abs(t)</tt><br> otherwise: implemented as <tt>sqrt(squaredNorm(t))</tt>. <b>\#include</b> "<a href="mathutil_8hxx-source.html">vigra/mathutil.hxx</a>"<br> Namespace: vigra */ template <class T> inline typename NormTraits<T>::NormType norm(T const & t) { return VIGRA_CSTD::sqrt(static_cast<typename NormTraits<T>::NormType>(squaredNorm(t))); } namespace detail { // both f1 and f2 are unsigned here template<class FPT> inline FPT safeFloatDivision( FPT f1, FPT f2 ) { return f2 < NumericTraits<FPT>::one() && f1 > f2 * NumericTraits<FPT>::max() ? NumericTraits<FPT>::max() : (f2 > NumericTraits<FPT>::one() && f1 < f2 * NumericTraits<FPT>::smallestPositive()) || f1 == NumericTraits<FPT>::zero() ? NumericTraits<FPT>::zero() : f1/f2; } } // namespace detail /*! Tolerance based floating-point comparison. Check whether two floating point numbers are equal within the given tolerance. This is useful because floating point numbers that should be equal in theory are rarely exactly equal in practice. If the tolerance \a epsilon is not given, twice the machine epsilon is used. <b>\#include</b> "<a href="mathutil_8hxx-source.html">vigra/mathutil.hxx</a>"<br> Namespace: vigra */ template <class T1, class T2> bool closeAtTolerance(T1 l, T2 r, typename PromoteTraits<T1, T2>::Promote epsilon) { typedef typename PromoteTraits<T1, T2>::Promote T; if(l == 0.0 && r != 0.0) return VIGRA_CSTD::fabs(r) <= epsilon; if(l != 0.0 && r == 0.0) return VIGRA_CSTD::fabs(r) <= epsilon; T diff = VIGRA_CSTD::fabs( l - r ); T d1 = detail::safeFloatDivision<T>( diff, VIGRA_CSTD::fabs( r ) ); T d2 = detail::safeFloatDivision<T>( diff, VIGRA_CSTD::fabs( l ) ); return (d1 <= epsilon && d2 <= epsilon); } template <class T1, class T2> bool closeAtTolerance(T1 l, T2 r) { typedef typename PromoteTraits<T1, T2>::Promote T; return closeAtTolerance(l, r, 2.0 * NumericTraits<T>::epsilon()); } //@} } // namespace vigra #endif /* VIGRA_MATHUTIL_HXX */ <|endoftext|>
<commit_before>/** \file classify_leader07a.cc * \author Dr. Johannes Ruscheinski * * A tool for determing the type of object that has a lowercase A in position 07 of the leader. * the create_child_refs.sh shell script. */ /* Copyright (C) 2015, Library of the University of Tübingen This program 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. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <iostream> #include <unordered_map> #include <cstdlib> #include "DirectoryEntry.h" #include "Leader.h" #include "MarcUtil.h" #include "StringUtil.h" #include "Subfields.h" #include "util.h" void Usage() { std::cerr << "Usage: " << progname << " [--verbose] marc_input\n"; std::exit(EXIT_FAILURE); } void ExtractBibliographicLevel( FILE * const input, std::unordered_map<std::string, char> * const control_number_to_bibliographic_level_map) { std::shared_ptr<Leader> leader; std::vector<DirectoryEntry> dir_entries; std::vector<std::string> field_data; std::string err_msg; while (MarcUtil::ReadNextRecord(input, leader, &dir_entries, &field_data, &err_msg)) { if (dir_entries[0].getTag() != "001") Error("First field is not \"001\"!"); (*control_number_to_bibliographic_level_map)[field_data[0]] = leader->getBibliographicLevel(); } if (not err_msg.empty()) Error(err_msg); } void DetermineObjectType(const bool verbose, FILE * const input, const std::unordered_map<std::string, char> &control_number_to_bibliographic_level_map) { std::shared_ptr<Leader> leader; std::vector<DirectoryEntry> dir_entries; std::vector<std::string> field_data; std::string err_msg; unsigned _07a_count(0), review_count(0), misclassified_count(0); while (MarcUtil::ReadNextRecord(input, leader, &dir_entries, &field_data, &err_msg)) { if (dir_entries[0].getTag() != "001") Error("First field is not \"001\"!"); const std::string &control_number(field_data[0]); if (leader->getBibliographicLevel() != 'a') continue; ++_07a_count; bool is_a_review(false); ssize_t _935_index(MarcUtil::GetFieldIndex(dir_entries, "935")); while (_935_index != -1) { const Subfields _935_subfields(field_data[_935_index]); if (_935_subfields.getFirstSubfieldValue('c') == "uwre") { is_a_review = true; ++review_count; break; } // Advance to the next field if it is also a 935-field: if (_935_index == static_cast<ssize_t>(field_data.size() - 1) or dir_entries[_935_index + 1].getTag() != "935") _935_index = -1; else ++_935_index; } if (is_a_review) { if (verbose) std::cout << control_number << " review\n"; continue; } // // If we get here we might assume that we have an article. // const ssize_t _773_index(MarcUtil::GetFieldIndex(dir_entries, "773")); if (_773_index == -1) { if (verbose) std::cout << control_number << " missing field 773\n"; ++misclassified_count; continue; } const Subfields _773_subfields(field_data[_773_index]); const std::string _773w_contents(_773_subfields.getFirstSubfieldValue('w')); if (_773w_contents.empty() or not StringUtil::StartsWith(_773w_contents, "(DE-576)")) { if (verbose) std::cout << control_number << " 773$w is missing or empty\n"; ++misclassified_count; continue; } const std::string parent_control_number(_773w_contents.substr(8)); const auto iter(control_number_to_bibliographic_level_map.find(parent_control_number)); if (iter == control_number_to_bibliographic_level_map.end()) { if (verbose) std::cout << control_number << " no parent found for control number " << parent_control_number << '\n'; ++misclassified_count; continue; } if (iter->second != 's' and iter->second != 'm') { // Neither a serial nor a monograph! if (verbose) std::cout << control_number << " parent w/ control number " << parent_control_number << " is neither a serial nor a monograph\n"; ++misclassified_count; continue; } } if (not err_msg.empty()) Error(err_msg); std::cerr << "Found " << _07a_count << " entries with an 'a' in leader postion 07.\n"; std::cerr << review_count << " records were reviews.\n"; std::cerr << misclassified_count << " records would be classified as unknown if we used strategy 2.\n"; } int main(int argc, char **argv) { progname = argv[0]; if (argc != 2 and argc != 3) Usage(); bool verbose; if (argc == 2) verbose = false; else { // argc == 3 if (std::strcmp(argv[1], "--verbose") != 0) Usage(); verbose = true; } const std::string marc_input_filename(argv[1]); FILE *marc_input(std::fopen(marc_input_filename.c_str(), "rb")); if (marc_input == nullptr) Error("can't open \"" + marc_input_filename + "\" for reading!"); std::unordered_map<std::string, char> control_number_to_bibliographic_level_map; ExtractBibliographicLevel(marc_input, &control_number_to_bibliographic_level_map); std::rewind(marc_input); DetermineObjectType(verbose, marc_input, control_number_to_bibliographic_level_map); std::fclose(marc_input); } <commit_msg>Fixed a problem with identifying the correct command-line argument that is the MARC input file.<commit_after>/** \file classify_leader07a.cc * \author Dr. Johannes Ruscheinski * * A tool for determing the type of object that has a lowercase A in position 07 of the leader. * the create_child_refs.sh shell script. */ /* Copyright (C) 2015, Library of the University of Tübingen This program 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. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <iostream> #include <unordered_map> #include <cstdlib> #include "DirectoryEntry.h" #include "Leader.h" #include "MarcUtil.h" #include "StringUtil.h" #include "Subfields.h" #include "util.h" void Usage() { std::cerr << "Usage: " << progname << " [--verbose] marc_input\n"; std::exit(EXIT_FAILURE); } void ExtractBibliographicLevel( FILE * const input, std::unordered_map<std::string, char> * const control_number_to_bibliographic_level_map) { std::shared_ptr<Leader> leader; std::vector<DirectoryEntry> dir_entries; std::vector<std::string> field_data; std::string err_msg; while (MarcUtil::ReadNextRecord(input, leader, &dir_entries, &field_data, &err_msg)) { if (dir_entries[0].getTag() != "001") Error("First field is not \"001\"!"); (*control_number_to_bibliographic_level_map)[field_data[0]] = leader->getBibliographicLevel(); } if (not err_msg.empty()) Error(err_msg); } void DetermineObjectType(const bool verbose, FILE * const input, const std::unordered_map<std::string, char> &control_number_to_bibliographic_level_map) { std::shared_ptr<Leader> leader; std::vector<DirectoryEntry> dir_entries; std::vector<std::string> field_data; std::string err_msg; unsigned _07a_count(0), review_count(0), misclassified_count(0); while (MarcUtil::ReadNextRecord(input, leader, &dir_entries, &field_data, &err_msg)) { if (dir_entries[0].getTag() != "001") Error("First field is not \"001\"!"); const std::string &control_number(field_data[0]); if (leader->getBibliographicLevel() != 'a') continue; ++_07a_count; bool is_a_review(false); ssize_t _935_index(MarcUtil::GetFieldIndex(dir_entries, "935")); while (_935_index != -1) { const Subfields _935_subfields(field_data[_935_index]); if (_935_subfields.getFirstSubfieldValue('c') == "uwre") { is_a_review = true; ++review_count; break; } // Advance to the next field if it is also a 935-field: if (_935_index == static_cast<ssize_t>(field_data.size() - 1) or dir_entries[_935_index + 1].getTag() != "935") _935_index = -1; else ++_935_index; } if (is_a_review) { if (verbose) std::cout << control_number << " review\n"; continue; } // // If we get here we might assume that we have an article. // const ssize_t _773_index(MarcUtil::GetFieldIndex(dir_entries, "773")); if (_773_index == -1) { if (verbose) std::cout << control_number << " missing field 773\n"; ++misclassified_count; continue; } const Subfields _773_subfields(field_data[_773_index]); const std::string _773w_contents(_773_subfields.getFirstSubfieldValue('w')); if (_773w_contents.empty() or not StringUtil::StartsWith(_773w_contents, "(DE-576)")) { if (verbose) std::cout << control_number << " 773$w is missing or empty\n"; ++misclassified_count; continue; } const std::string parent_control_number(_773w_contents.substr(8)); const auto iter(control_number_to_bibliographic_level_map.find(parent_control_number)); if (iter == control_number_to_bibliographic_level_map.end()) { if (verbose) std::cout << control_number << " no parent found for control number " << parent_control_number << '\n'; ++misclassified_count; continue; } if (iter->second != 's' and iter->second != 'm') { // Neither a serial nor a monograph! if (verbose) std::cout << control_number << " parent w/ control number " << parent_control_number << " is neither a serial nor a monograph\n"; ++misclassified_count; continue; } } if (not err_msg.empty()) Error(err_msg); std::cerr << "Found " << _07a_count << " entries with an 'a' in leader postion 07.\n"; std::cerr << review_count << " records were reviews.\n"; std::cerr << misclassified_count << " records would be classified as unknown if we used strategy 2.\n"; } int main(int argc, char **argv) { progname = argv[0]; if (argc != 2 and argc != 3) Usage(); bool verbose; if (argc == 2) verbose = false; else { // argc == 3 if (std::strcmp(argv[1], "--verbose") != 0) Usage(); verbose = true; } const std::string marc_input_filename(argv[argc == 2 ? 1 : 2]); FILE *marc_input(std::fopen(marc_input_filename.c_str(), "rb")); if (marc_input == nullptr) Error("can't open \"" + marc_input_filename + "\" for reading!"); std::unordered_map<std::string, char> control_number_to_bibliographic_level_map; ExtractBibliographicLevel(marc_input, &control_number_to_bibliographic_level_map); std::rewind(marc_input); DetermineObjectType(verbose, marc_input, control_number_to_bibliographic_level_map); std::fclose(marc_input); } <|endoftext|>
<commit_before>/** * Copyright (c) 2011-2013 libwallet developers (see AUTHORS) * * This file is part of libwallet. * * libwallet 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. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef LIBWALLET_STEALTH_HPP #define LIBWALLET_STEALTH_HPP #include <stdint.h> #include <bitcoin/bitcoin.hpp> #include <wallet/define.hpp> namespace libwallet { using namespace libbitcoin; struct stealth_address { typedef std::vector<ec_point> pubkey_list; enum class flags : uint8_t { reuse_key = 0x01 }; BCW_API bool set_encoded(const std::string& encoded_address); BCW_API std::string encoded() const; uint8_t options = 0; ec_point scan_pubkey; pubkey_list spend_pubkeys; size_t number_signatures = 0; stealth_prefix prefix; }; BCW_API ec_point initiate_stealth( const ec_secret& ephem_secret, const ec_point& scan_pubkey, const ec_point& spend_pubkey); BCW_API ec_point uncover_stealth( const ec_point& ephem_pubkey, const ec_secret& scan_secret, const ec_point& spend_pubkey); BCW_API ec_secret uncover_stealth_secret( const ec_point& ephem_pubkey, const ec_secret& scan_secret, const ec_secret& spend_secret); } // namespace libwallet #endif <commit_msg>change enum<commit_after>/** * Copyright (c) 2011-2013 libwallet developers (see AUTHORS) * * This file is part of libwallet. * * libwallet 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. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef LIBWALLET_STEALTH_HPP #define LIBWALLET_STEALTH_HPP #include <stdint.h> #include <bitcoin/bitcoin.hpp> #include <wallet/define.hpp> namespace libwallet { using namespace libbitcoin; struct stealth_address { typedef std::vector<ec_point> pubkey_list; enum flags : uint8_t { reuse_key = 0x01 }; BCW_API bool set_encoded(const std::string& encoded_address); BCW_API std::string encoded() const; uint8_t options = 0; ec_point scan_pubkey; pubkey_list spend_pubkeys; size_t number_signatures = 0; stealth_prefix prefix; }; BCW_API ec_point initiate_stealth( const ec_secret& ephem_secret, const ec_point& scan_pubkey, const ec_point& spend_pubkey); BCW_API ec_point uncover_stealth( const ec_point& ephem_pubkey, const ec_secret& scan_secret, const ec_point& spend_pubkey); BCW_API ec_secret uncover_stealth_secret( const ec_point& ephem_pubkey, const ec_secret& scan_secret, const ec_secret& spend_secret); } // namespace libwallet #endif <|endoftext|>
<commit_before>#include "game/race_tracker.h" using game::Position; using game::Race; namespace game { RaceTracker::RaceTracker(game::CarTracker& car_tracker, const game::Race& race, const std::string& color) : car_tracker_(car_tracker), race_(race), color_(color) { } void RaceTracker::Record(const std::map<std::string, Position>& positions) { for (auto& p : positions) { if (indexes_.find(p.first) == indexes_.end()) { indexes_[p.first] = enemies_.size(); enemies_.push_back(EnemyTracker(car_tracker_, race_, p.first, p.second)); } else { enemies_[indexes_[p.first]].RecordPosition(p.second); } } } void RaceTracker::RecordLapTime(const std::string& color, int time) { if (indexes_.find(color) == indexes_.end()) return; enemies_[indexes_[color]].RecordLapTime(time); } void RaceTracker::RecordCrash(const std::string& color) { if (indexes_.find(color) == indexes_.end()) return; enemies_[indexes_[color]].RecordCrash(); } // TODO test std::vector<std::string> RaceTracker::CarsBetween(int from, int to, int lane) { std::vector<std::string> result; for (auto& i : indexes_) { if (i.first == color_) continue; if (race_.track().IsBetween(enemies_[i.second].state().position(), from, to) && enemies_[i.second].state().position().end_lane() == lane) result.push_back(i.first); } return result; } std::vector<std::string> RaceTracker::PredictedCarsBetween(int from, int to, int lane) { auto& me = enemies_[indexes_[color_]]; Position position; position.set_piece(to); position.set_piece_distance(0); int time = me.TimeToPosition(position); std::vector<std::string> result; for (auto& i : indexes_) { if (i.first == color_) continue; auto& enemy = enemies_[i.second]; // If Im already ahead - ignore if (race_.track().IsFirstInFront(me.state().position(), enemy.state().position())) continue; // Check lane if (enemy.state().position().end_lane() == lane) { // If dead, check if he respawns after I pass him if (enemy.is_dead() && race_.track().IsFirstInFront( me.PositionAfterTime(enemy.time_to_spawn() - 3), enemy.state().position())) continue; if (race_.track().IsBetween(enemy.PositionAfterTime(time), from, to)) result.push_back(i.first); } } return result; } bool RaceTracker::IsSafeInFront(const Command& command, Command* safe_command) { const auto& my_state = car_tracker_.current_state(); std::map<std::string, CarState> states; for (const auto& enemy : enemies_) { if (enemy.color() == color_) { states[color_] = car_tracker_.Predict(my_state, command); continue; } if (enemy.dead()) { continue; } states[enemy.color()] = car_tracker_.Predict(enemy.state(), Command(0)); } const double kCarLength = race_.cars().at(0).length(); std::set<string> cars_bumped; for (int i = 0; i < 100; ++i) { CarState my_prev = states[color_]; Command c(0); if (i == 0) { c = command; } CarState my_new = car_tracker_.Predict(my_prev, c); states[color_] = my_new; bool bumped = false; double min_velocity = 100000.0; for (const auto& p : states) { if (p.first == color_) continue; if ( double velocity = 0.0; Position bump_position = car_tracker_.PredictPosition(my_new.position(), kCarLength); if (car_tracker_.MinVelocity(p.second, i + 1, bump_position, &velocity)) { // std::cout << "possible bump in " << i + 1 << " ticks" << std::endl; // std::cout << "min_velocity = " << velocity << std::endl; // If the velocity is higher than ours, he probably was behind us. if (velocity < my_new.velocity()) { bumped = true; min_velocity = fmin(min_velocity, velocity); } } } if (!bumped) continue; CarState state = my_new; state.set_velocity(0.8 * min_velocity); if (!car_tracker_.IsSafe(state)) { if (fabs(my_state.position().angle()) < 7) { // std::cout << "decided after " << i << " ticks" << std::endl; // std::cout << "State that is dangerous: " << std::endl; // std::cout << my_new.DebugString(); // std::cout << "min_velocity * 0.8 = " << min_velocity * 0.8 << std::endl; } std::cout << "WE ARE TOO CLOSE AND WILL DIE. Slowing down." << std::endl; *safe_command = Command(0); return false; } } // We survived 100 ticks, we should be ok. return true; } void RaceTracker::FinishedRace(const std::string& color) { if (indexes_.find(color) == indexes_.end()) return; enemies_[indexes_[color]].FinishedRace(); } void RaceTracker::DNF(const std::string& color) { if (indexes_.find(color) == indexes_.end()) return; enemies_[indexes_[color]].DNF(); } void RaceTracker::ResurrectCars() { for (auto& enemy : enemies_) enemy.Resurrect(); } bool RaceTracker::ShouldTryToOvertake(const std::string& color, int from, int to) { return enemy(color_).CanOvertake(enemy(color), from, to); } /* Position RaceTracker::BumpPosition(const std::string& color) { int index = indexes_[color]; // TODO optimize:D for (int i = 0; i < 100; i++) { auto me = enemies_[indexes_[color_]].PositionAfterTime(i); auto he = enemies_[indexes_[color]].PositionAfterTime(i); if ((me.piece() == he.piece() && me.piece_distance() > he.piece_distance()) || (me.piece() + 1) % race_.track().pieces().size() == he.piece()) return me; } // This shouldnt reach here return enemies_[indexes_[color_]].state().position(); } */ } // namespace game <commit_msg>Fix build<commit_after>#include "game/race_tracker.h" using game::Position; using game::Race; namespace game { RaceTracker::RaceTracker(game::CarTracker& car_tracker, const game::Race& race, const std::string& color) : car_tracker_(car_tracker), race_(race), color_(color) { } void RaceTracker::Record(const std::map<std::string, Position>& positions) { for (auto& p : positions) { if (indexes_.find(p.first) == indexes_.end()) { indexes_[p.first] = enemies_.size(); enemies_.push_back(EnemyTracker(car_tracker_, race_, p.first, p.second)); } else { enemies_[indexes_[p.first]].RecordPosition(p.second); } } } void RaceTracker::RecordLapTime(const std::string& color, int time) { if (indexes_.find(color) == indexes_.end()) return; enemies_[indexes_[color]].RecordLapTime(time); } void RaceTracker::RecordCrash(const std::string& color) { if (indexes_.find(color) == indexes_.end()) return; enemies_[indexes_[color]].RecordCrash(); } // TODO test std::vector<std::string> RaceTracker::CarsBetween(int from, int to, int lane) { std::vector<std::string> result; for (auto& i : indexes_) { if (i.first == color_) continue; if (race_.track().IsBetween(enemies_[i.second].state().position(), from, to) && enemies_[i.second].state().position().end_lane() == lane) result.push_back(i.first); } return result; } std::vector<std::string> RaceTracker::PredictedCarsBetween(int from, int to, int lane) { auto& me = enemies_[indexes_[color_]]; Position position; position.set_piece(to); position.set_piece_distance(0); int time = me.TimeToPosition(position); std::vector<std::string> result; for (auto& i : indexes_) { if (i.first == color_) continue; auto& enemy = enemies_[i.second]; // If Im already ahead - ignore if (race_.track().IsFirstInFront(me.state().position(), enemy.state().position())) continue; // Check lane if (enemy.state().position().end_lane() == lane) { // If dead, check if he respawns after I pass him if (enemy.is_dead() && race_.track().IsFirstInFront( me.PositionAfterTime(enemy.time_to_spawn() - 3), enemy.state().position())) continue; if (race_.track().IsBetween(enemy.PositionAfterTime(time), from, to)) result.push_back(i.first); } } return result; } bool RaceTracker::IsSafeInFront(const Command& command, Command* safe_command) { const auto& my_state = car_tracker_.current_state(); std::map<std::string, CarState> states; for (const auto& enemy : enemies_) { if (enemy.color() == color_) { states[color_] = car_tracker_.Predict(my_state, command); continue; } if (enemy.is_dead()) { continue; } states[enemy.color()] = car_tracker_.Predict(enemy.state(), Command(0)); } const double kCarLength = race_.cars().at(0).length(); std::set<string> cars_bumped; for (int i = 0; i < 100; ++i) { CarState my_prev = states[color_]; Command c(0); if (i == 0) { c = command; } CarState my_new = car_tracker_.Predict(my_prev, c); states[color_] = my_new; bool bumped = false; double min_velocity = 100000.0; for (const auto& p : states) { if (p.first == color_) continue; double velocity = 0.0; Position bump_position = car_tracker_.PredictPosition(my_new.position(), kCarLength); if (car_tracker_.MinVelocity(p.second, i + 1, bump_position, &velocity)) { // std::cout << "possible bump in " << i + 1 << " ticks" << std::endl; // std::cout << "min_velocity = " << velocity << std::endl; // If the velocity is higher than ours, he probably was behind us. if (velocity < my_new.velocity()) { bumped = true; min_velocity = fmin(min_velocity, velocity); } } } if (!bumped) continue; CarState state = my_new; state.set_velocity(0.8 * min_velocity); if (!car_tracker_.IsSafe(state)) { if (fabs(my_state.position().angle()) < 7) { // std::cout << "decided after " << i << " ticks" << std::endl; // std::cout << "State that is dangerous: " << std::endl; // std::cout << my_new.DebugString(); // std::cout << "min_velocity * 0.8 = " << min_velocity * 0.8 << std::endl; } std::cout << "WE ARE TOO CLOSE AND WILL DIE. Slowing down." << std::endl; *safe_command = Command(0); return false; } } // We survived 100 ticks, we should be ok. return true; } void RaceTracker::FinishedRace(const std::string& color) { if (indexes_.find(color) == indexes_.end()) return; enemies_[indexes_[color]].FinishedRace(); } void RaceTracker::DNF(const std::string& color) { if (indexes_.find(color) == indexes_.end()) return; enemies_[indexes_[color]].DNF(); } void RaceTracker::ResurrectCars() { for (auto& enemy : enemies_) enemy.Resurrect(); } bool RaceTracker::ShouldTryToOvertake(const std::string& color, int from, int to) { return enemy(color_).CanOvertake(enemy(color), from, to); } /* Position RaceTracker::BumpPosition(const std::string& color) { int index = indexes_[color]; // TODO optimize:D for (int i = 0; i < 100; i++) { auto me = enemies_[indexes_[color_]].PositionAfterTime(i); auto he = enemies_[indexes_[color]].PositionAfterTime(i); if ((me.piece() == he.piece() && me.piece_distance() > he.piece_distance()) || (me.piece() + 1) % race_.track().pieces().size() == he.piece()) return me; } // This shouldnt reach here return enemies_[indexes_[color_]].state().position(); } */ } // namespace game <|endoftext|>
<commit_before>#include "positiontracker.h" #include <cmath> #include <common/config/configmanager.h> PositionTracker::PositionTracker() : LOnGPSData(this), LOnMotionCommand(this), LOnIMUData(this) { } Position PositionTracker::GetPosition() { return _current_estimate; } Position PositionTracker::UpdateWithMeasurement(Position S, Position Measurement) { Position result; result.Latitude.SetValue( ( S.Latitude.Value()*Measurement.Latitude.Variance() + Measurement.Latitude.Value()*S.Latitude.Variance() ) / (S.Latitude.Variance()+Measurement.Latitude.Variance()) ); result.Longitude.SetValue( ( S.Longitude.Value()*Measurement.Longitude.Variance() + Measurement.Longitude.Value()*S.Longitude.Variance() ) / (S.Longitude.Variance()+Measurement.Longitude.Variance()) ); result.Heading.SetValue( ( S.Heading.Value()*Measurement.Heading.Variance() + Measurement.Heading.Value()*S.Heading.Variance() ) / (S.Heading.Variance()+Measurement.Heading.Variance()) ); result.Latitude.SetVariance( 1.0 / (1.0/S.Latitude.Variance() + 1.0 / Measurement.Latitude.Variance()) ); result.Longitude.SetVariance( 1.0 / (1.0/S.Longitude.Variance() + 1.0 / Measurement.Longitude.Variance()) ); result.Heading.SetVariance( 1.0 / (1.0/S.Heading.Variance() + 1.0 / Measurement.Heading.Variance()) ); return result; } Position PositionTracker::UpdateWithMotion(Position S, Position Delta) { Position result; result.Latitude.SetValue(S.Latitude.Value() + Delta.Latitude.Value()); result.Longitude.SetValue(S.Longitude.Value() + Delta.Longitude.Value()); result.Heading.SetValue(S.Heading.Value() + Delta.Heading.Value()); result.Latitude.SetVariance(S.Latitude.Variance() + Delta.Latitude.Variance()); result.Longitude.SetVariance(S.Longitude.Variance() + Delta.Longitude.Variance()); result.Heading.SetVariance(S.Heading.Variance() + Delta.Heading.Variance()); return result; } Position PositionTracker::DeltaFromMotionCommand(MotorCommand cmd) { using namespace std; double V = ( cmd.rightVel + cmd.leftVel ) / 2.0; double W = ( cmd.rightVel - cmd.leftVel ) / ConfigManager::getValue("Robot", "Baseline", 1.0); double t = cmd.millis / 1000.0; double R = V/W; Position delta; double theta = _current_estimate.Heading.Value() * M_PI/180.0; double thetaPrime = (_current_estimate.Heading.Value() + W*t) * M_PI/180.0; delta.Heading.SetValue(W*t); delta.Latitude.SetValue(R*(cos(theta) - cos(thetaPrime))); delta.Longitude.SetValue(R*(sin(thetaPrime) - sin(theta))); // TODO - handle variances return delta; } void PositionTracker::OnGPSData(GPSData data) { Position measurement; measurement.Latitude.SetValue(data.Lat()); measurement.Longitude.SetValue(data.Long()); // TODO - make sure the GPS actually outputs heading data measurement.Heading.SetValue(data.Heading()); // TODO - handle variances _current_estimate = UpdateWithMeasurement(_current_estimate, measurement); } void PositionTracker::OnIMUData(IMUData data) { } void PositionTracker::OnMotionCommand(MotorCommand cmd) { _current_estimate = UpdateWithMotion(_current_estimate, DeltaFromMotionCommand(cmd)); } <commit_msg>Fixes bug in omega calculation.<commit_after>#include "positiontracker.h" #include <cmath> #include <common/config/configmanager.h> PositionTracker::PositionTracker() : LOnGPSData(this), LOnMotionCommand(this), LOnIMUData(this) { } Position PositionTracker::GetPosition() { return _current_estimate; } Position PositionTracker::UpdateWithMeasurement(Position S, Position Measurement) { Position result; result.Latitude.SetValue( ( S.Latitude.Value()*Measurement.Latitude.Variance() + Measurement.Latitude.Value()*S.Latitude.Variance() ) / (S.Latitude.Variance()+Measurement.Latitude.Variance()) ); result.Longitude.SetValue( ( S.Longitude.Value()*Measurement.Longitude.Variance() + Measurement.Longitude.Value()*S.Longitude.Variance() ) / (S.Longitude.Variance()+Measurement.Longitude.Variance()) ); result.Heading.SetValue( ( S.Heading.Value()*Measurement.Heading.Variance() + Measurement.Heading.Value()*S.Heading.Variance() ) / (S.Heading.Variance()+Measurement.Heading.Variance()) ); result.Latitude.SetVariance( 1.0 / (1.0/S.Latitude.Variance() + 1.0 / Measurement.Latitude.Variance()) ); result.Longitude.SetVariance( 1.0 / (1.0/S.Longitude.Variance() + 1.0 / Measurement.Longitude.Variance()) ); result.Heading.SetVariance( 1.0 / (1.0/S.Heading.Variance() + 1.0 / Measurement.Heading.Variance()) ); return result; } Position PositionTracker::UpdateWithMotion(Position S, Position Delta) { Position result; result.Latitude.SetValue(S.Latitude.Value() + Delta.Latitude.Value()); result.Longitude.SetValue(S.Longitude.Value() + Delta.Longitude.Value()); result.Heading.SetValue(S.Heading.Value() + Delta.Heading.Value()); result.Latitude.SetVariance(S.Latitude.Variance() + Delta.Latitude.Variance()); result.Longitude.SetVariance(S.Longitude.Variance() + Delta.Longitude.Variance()); result.Heading.SetVariance(S.Heading.Variance() + Delta.Heading.Variance()); return result; } Position PositionTracker::DeltaFromMotionCommand(MotorCommand cmd) { using namespace std; double V = ( cmd.rightVel + cmd.leftVel ) / 2.0; double W = ( cmd.rightVel - cmd.leftVel ) / ConfigManager::Instance().getValue("Robot", "Baseline", 1.0); double t = cmd.millis / 1000.0; double R = V/W; Position delta; double theta = _current_estimate.Heading.Value() * M_PI/180.0; double thetaPrime = (_current_estimate.Heading.Value() + W*t) * M_PI/180.0; delta.Heading.SetValue(W*t); delta.Latitude.SetValue(R*(cos(theta) - cos(thetaPrime))); delta.Longitude.SetValue(R*(sin(thetaPrime) - sin(theta))); // TODO - handle variances return delta; } void PositionTracker::OnGPSData(GPSData data) { Position measurement; measurement.Latitude.SetValue(data.Lat()); measurement.Longitude.SetValue(data.Long()); // TODO - make sure the GPS actually outputs heading data measurement.Heading.SetValue(data.Heading()); // TODO - handle variances _current_estimate = UpdateWithMeasurement(_current_estimate, measurement); } void PositionTracker::OnIMUData(IMUData data) { } void PositionTracker::OnMotionCommand(MotorCommand cmd) { _current_estimate = UpdateWithMotion(_current_estimate, DeltaFromMotionCommand(cmd)); } <|endoftext|>
<commit_before>#include "alien.h" Alien::Alien(wsp::Image *img) { SetImage(img); resetMotion(); resetPosition(); } void Alien::setShots(Shot **shots) { this->shots = shots; } void Alien::update() { Move(motionX, motionY); if(GetY() < 0) SetY(0); else if(GetY() > 480-GetHeight()) SetY(480-GetHeight()); int i; for(i=0;i<NUM_SHOTS;i++) { if(shots[i]->isFired() == false) continue; if(CollidesWith(shots[i])) { shots[i]->remove(); resetPosition(); resetMotion(); break; } } if(--lockMotionFrames == 0) resetMotion(); if(GetX() < 0) resetPosition(); } void Alien::resetMotion() { motionX = -2; motionY = rand()%10 - 5; lockMotionFrames = Alien::LOCK_MOTION_FRAME_COUNT; } void Alien::resetPosition() { SetPosition(640 + (rand()%Alien::MAX_OFFSCREEN_OFFSET), rand() % (480-GetHeight())); } const int Alien::MAX_OFFSCREEN_OFFSET = 640; const int Alien::LOCK_MOTION_FRAME_COUNT = 100; <commit_msg>Aliens shall move faster, too.<commit_after>#include "alien.h" Alien::Alien(wsp::Image *img) { SetImage(img); resetMotion(); resetPosition(); } void Alien::setShots(Shot **shots) { this->shots = shots; } void Alien::update() { Move(motionX, motionY); if(GetY() < 0) SetY(0); else if(GetY() > 480-GetHeight()) SetY(480-GetHeight()); int i; for(i=0;i<NUM_SHOTS;i++) { if(shots[i]->isFired() == false) continue; if(CollidesWith(shots[i])) { shots[i]->remove(); resetPosition(); resetMotion(); break; } } if(--lockMotionFrames == 0) resetMotion(); if(GetX() < 0) resetPosition(); } void Alien::resetMotion() { motionX = -4; motionY = rand()%10 - 5; lockMotionFrames = Alien::LOCK_MOTION_FRAME_COUNT; } void Alien::resetPosition() { SetPosition(640 + (rand()%Alien::MAX_OFFSCREEN_OFFSET), rand() % (480-GetHeight())); } const int Alien::MAX_OFFSCREEN_OFFSET = 640; const int Alien::LOCK_MOTION_FRAME_COUNT = 100; <|endoftext|>
<commit_before>// // This file is part of the Marble Virtual Globe. // // This program is free software licensed under the GNU LGPL. You can // find a copy of this license in LICENSE.txt in the top directory of // the source code. // // Copyright 2007 Murad Tagirov <[email protected]> // #include "GeoDataLabelStyle.h" #include <QFont> #include "GeoDataTypes.h" namespace Marble { #ifdef Q_OS_MACX static const int defaultSize = 10; #else static const int defaultSize = 8; #endif class GeoDataLabelStylePrivate { public: GeoDataLabelStylePrivate() : m_scale( 1.0 ), m_alignment( GeoDataLabelStyle::Corner ), m_font( QFont("Sans Serif").family(), defaultSize, 50, false ), m_glow( true ) { } explicit GeoDataLabelStylePrivate( const QFont &font ) : m_scale( 1.0 ), m_alignment( GeoDataLabelStyle::Corner ), m_font( font ), m_glow( true ) { } const char* nodeType() const { return GeoDataTypes::GeoDataLabelStyleType; } /// The current scale of the label float m_scale; /// The current alignment of the label GeoDataLabelStyle::Alignment m_alignment; /// The current font of the label QFont m_font; // Not a KML property /// Whether or not the text should glow bool m_glow; // Not a KML property }; GeoDataLabelStyle::GeoDataLabelStyle() : d (new GeoDataLabelStylePrivate ) { setColor( QColor( Qt::black ) ); } GeoDataLabelStyle::GeoDataLabelStyle( const GeoDataLabelStyle& other ) : GeoDataColorStyle( other ), d (new GeoDataLabelStylePrivate( *other.d ) ) { } GeoDataLabelStyle::GeoDataLabelStyle( const QFont &font, const QColor &color ) : d (new GeoDataLabelStylePrivate( font ) ) { setColor( color ); } GeoDataLabelStyle::~GeoDataLabelStyle() { delete d; } GeoDataLabelStyle& GeoDataLabelStyle::operator=( const GeoDataLabelStyle& other ) { GeoDataColorStyle::operator=( other ); *d = *other.d; return *this; } bool GeoDataLabelStyle::operator==( const GeoDataLabelStyle &other ) const { return d->m_scale == other.d->m_scale && d->m_alignment == other.d->m_alignment && d->m_font == other.d->m_font && d->m_glow == other.d->m_glow; } bool GeoDataLabelStyle::operator!=( const GeoDataLabelStyle &other ) const { return !this->operator==( other ); } const char* GeoDataLabelStyle::nodeType() const { return d->nodeType(); } void GeoDataLabelStyle::setAlignment( GeoDataLabelStyle::Alignment alignment ) { d->m_alignment = alignment; } GeoDataLabelStyle::Alignment GeoDataLabelStyle::alignment() const { return d->m_alignment; } void GeoDataLabelStyle::setScale( const float &scale ) { d->m_scale = scale; } float GeoDataLabelStyle::scale() const { return d->m_scale; } void GeoDataLabelStyle::setFont( const QFont &font ) { d->m_font = font; } QFont GeoDataLabelStyle::font() const { return d->m_font; } bool GeoDataLabelStyle::glow() const { return d->m_glow; } void GeoDataLabelStyle::setGlow(bool on) { d->m_glow = on; } void GeoDataLabelStyle::pack( QDataStream& stream ) const { GeoDataColorStyle::pack( stream ); stream << d->m_scale; stream << d->m_alignment; stream << d->m_font; } void GeoDataLabelStyle::unpack( QDataStream& stream ) { int a; GeoDataColorStyle::unpack( stream ); stream >> d->m_scale; stream >> a; stream >> d->m_font; d->m_alignment = static_cast<GeoDataLabelStyle::Alignment>( a ); } } <commit_msg>Solved bug in GeoDataLaberStyle<commit_after>// // This file is part of the Marble Virtual Globe. // // This program is free software licensed under the GNU LGPL. You can // find a copy of this license in LICENSE.txt in the top directory of // the source code. // // Copyright 2007 Murad Tagirov <[email protected]> // #include "GeoDataLabelStyle.h" #include <QFont> #include "GeoDataTypes.h" namespace Marble { #ifdef Q_OS_MACX static const int defaultSize = 10; #else static const int defaultSize = 8; #endif class GeoDataLabelStylePrivate { public: GeoDataLabelStylePrivate() : m_scale( 1.0 ), m_alignment( GeoDataLabelStyle::Corner ), m_font( QFont("Sans Serif").family(), defaultSize, 50, false ), m_glow( true ) { } explicit GeoDataLabelStylePrivate( const QFont &font ) : m_scale( 1.0 ), m_alignment( GeoDataLabelStyle::Corner ), m_font( font ), m_glow( true ) { } const char* nodeType() const { return GeoDataTypes::GeoDataLabelStyleType; } /// The current scale of the label float m_scale; /// The current alignment of the label GeoDataLabelStyle::Alignment m_alignment; /// The current font of the label QFont m_font; // Not a KML property /// Whether or not the text should glow bool m_glow; // Not a KML property }; GeoDataLabelStyle::GeoDataLabelStyle() : d (new GeoDataLabelStylePrivate ) { setColor( QColor( Qt::black ) ); } GeoDataLabelStyle::GeoDataLabelStyle( const GeoDataLabelStyle& other ) : GeoDataColorStyle( other ), d (new GeoDataLabelStylePrivate( *other.d ) ) { } GeoDataLabelStyle::GeoDataLabelStyle( const QFont &font, const QColor &color ) : d (new GeoDataLabelStylePrivate( font ) ) { setColor( color ); } GeoDataLabelStyle::~GeoDataLabelStyle() { delete d; } GeoDataLabelStyle& GeoDataLabelStyle::operator=( const GeoDataLabelStyle& other ) { GeoDataColorStyle::operator=( other ); *d = *other.d; return *this; } bool GeoDataLabelStyle::operator==( const GeoDataLabelStyle &other ) const { if ( GeoDataColorStyle::operator!=( other ) ) { return false; } return d->m_scale == other.d->m_scale && d->m_alignment == other.d->m_alignment && d->m_font == other.d->m_font && d->m_glow == other.d->m_glow; } bool GeoDataLabelStyle::operator!=( const GeoDataLabelStyle &other ) const { return !this->operator==( other ); } const char* GeoDataLabelStyle::nodeType() const { return d->nodeType(); } void GeoDataLabelStyle::setAlignment( GeoDataLabelStyle::Alignment alignment ) { d->m_alignment = alignment; } GeoDataLabelStyle::Alignment GeoDataLabelStyle::alignment() const { return d->m_alignment; } void GeoDataLabelStyle::setScale( const float &scale ) { d->m_scale = scale; } float GeoDataLabelStyle::scale() const { return d->m_scale; } void GeoDataLabelStyle::setFont( const QFont &font ) { d->m_font = font; } QFont GeoDataLabelStyle::font() const { return d->m_font; } bool GeoDataLabelStyle::glow() const { return d->m_glow; } void GeoDataLabelStyle::setGlow(bool on) { d->m_glow = on; } void GeoDataLabelStyle::pack( QDataStream& stream ) const { GeoDataColorStyle::pack( stream ); stream << d->m_scale; stream << d->m_alignment; stream << d->m_font; } void GeoDataLabelStyle::unpack( QDataStream& stream ) { int a; GeoDataColorStyle::unpack( stream ); stream >> d->m_scale; stream >> a; stream >> d->m_font; d->m_alignment = static_cast<GeoDataLabelStyle::Alignment>( a ); } } <|endoftext|>
<commit_before>// AboutBox.cpp // Copyright (c) 2009, Dan Heeks // This program is released under the BSD license. See the file COPYING for details. #include "stdafx.h" #include "AboutBox.h" #include "HeeksFrame.h" BEGIN_EVENT_TABLE( CAboutBox, wxDialog ) EVT_BUTTON( wxID_OK, CAboutBox::OnButtonOK ) END_EVENT_TABLE() CAboutBox::CAboutBox(wxWindow *parent):wxDialog(parent, wxID_ANY, _T(""), wxDefaultPosition, wxDefaultSize, wxDEFAULT_DIALOG_STYLE) { wxPanel *panel = new wxPanel(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL); wxButton *ok_button = new wxButton(panel, wxID_OK, _("OK")); wxBoxSizer *mainsizer = new wxBoxSizer( wxVERTICAL ); wxTextCtrl* text_ctrl = new wxTextCtrl( this, wxID_ANY, _T(""), wxDefaultPosition, wxSize(800,600), wxTE_READONLY | wxTE_MULTILINE); wxString str = wxString(_T("HeeksCAD\n see http://heeks.net, or for source code: http://code.google.com/p/heekscad/\n\nusing Open CASCADE solid modeller - http://www.opencascade.org")) + wxString(_T("\n\nwindows made with wxWidgets 2.8.9 - http://wxwidgets.org")) + wxString(_T("\n\ntext uses glFont Copyright (c) 1998 Brad Fish E-mail: [email protected] Web: http://students.cs.byu.edu/~bfish/")) + wxString(_T("\n\nWritten by:\n Dan Heeks\n Jon Pry\n Jonathan George\n David Nicholls")) + wxString(_T("\n\nWith contributions from:\n Hirutso Enni\n Perttu Ahola\n Dave ( the archivist )\n mpictor\n fenn\n fungunner2\n andrea ( openSUSE )\n g_code\n Luigi Barbati (Italian translation)\n Andr Pascual (French translation)")) + wxString(_T("\n\nThis is free, open source software.")); wxString version_str = wxGetApp().m_version_number; version_str.Replace(_T(" "), _T(".")); this->SetTitle(version_str); text_ctrl->WriteText(str + wxGetApp().m_frame->m_extra_about_box_str); //mainsizer->Add( text_ctrl, wxSizerFlags().Align(wxALIGN_CENTER).Border(wxALL, 10).Expand() ); //mainsizer->Add( ok_button, wxSizerFlags().Align(wxALIGN_CENTER) ); mainsizer->Add( text_ctrl ); mainsizer->Add( ok_button ); mainsizer->RecalcSizes(); // tell frame to make use of sizer (or constraints, if any) panel->SetAutoLayout( true ); panel->SetSizer( mainsizer ); #ifndef __WXWINCE__ // don't allow frame to get smaller than what the sizers tell ye mainsizer->SetSizeHints( this ); #endif Show(true); } void CAboutBox::OnButtonOK(wxCommandEvent& event) { EndModal(wxID_OK); } <commit_msg>utf8 experiment<commit_after>// AboutBox.cpp // Copyright (c) 2009, Dan Heeks // This program is released under the BSD license. See the file COPYING for details. #include "stdafx.h" #include "AboutBox.h" #include "HeeksFrame.h" BEGIN_EVENT_TABLE( CAboutBox, wxDialog ) EVT_BUTTON( wxID_OK, CAboutBox::OnButtonOK ) END_EVENT_TABLE() CAboutBox::CAboutBox(wxWindow *parent):wxDialog(parent, wxID_ANY, _T(""), wxDefaultPosition, wxDefaultSize, wxDEFAULT_DIALOG_STYLE) { wxPanel *panel = new wxPanel(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL); wxButton *ok_button = new wxButton(panel, wxID_OK, _("OK")); wxBoxSizer *mainsizer = new wxBoxSizer( wxVERTICAL ); wxTextCtrl* text_ctrl = new wxTextCtrl( this, wxID_ANY, _T(""), wxDefaultPosition, wxSize(800,600), wxTE_READONLY | wxTE_MULTILINE); wxString str = wxString(_T("HeeksCAD\n see http://heeks.net, or for source code: http://code.google.com/p/heekscad/\n\nusing Open CASCADE solid modeller - http://www.opencascade.org")) + wxString(_T("\n\nwindows made with wxWidgets 2.8.9 - http://wxwidgets.org")) + wxString(_T("\n\ntext uses glFont Copyright (c) 1998 Brad Fish E-mail: [email protected] Web: http://students.cs.byu.edu/~bfish/")) + wxString(_T("\n\nWritten by:\n Dan Heeks\n Jon Pry\n Jonathan George\n David Nicholls")) + wxString(_T("\n\nWith contributions from:\n Hirutso Enni\n Perttu Ahola\n Dave ( the archivist )\n mpictor\n fenn\n fungunner2\n andrea ( openSUSE )\n g_code\n Luigi Barbati (Italian translation)\n André Pascual (French translation)")) + wxString(_T("\n\nThis is free, open source software.")); wxString version_str = wxGetApp().m_version_number; version_str.Replace(_T(" "), _T(".")); this->SetTitle(version_str); text_ctrl->WriteText(str + wxGetApp().m_frame->m_extra_about_box_str); //mainsizer->Add( text_ctrl, wxSizerFlags().Align(wxALIGN_CENTER).Border(wxALL, 10).Expand() ); //mainsizer->Add( ok_button, wxSizerFlags().Align(wxALIGN_CENTER) ); mainsizer->Add( text_ctrl ); mainsizer->Add( ok_button ); mainsizer->RecalcSizes(); // tell frame to make use of sizer (or constraints, if any) panel->SetAutoLayout( true ); panel->SetSizer( mainsizer ); #ifndef __WXWINCE__ // don't allow frame to get smaller than what the sizers tell ye mainsizer->SetSizeHints( this ); #endif Show(true); } void CAboutBox::OnButtonOK(wxCommandEvent& event) { EndModal(wxID_OK); } <|endoftext|>
<commit_before>/* * Appender.cpp * * Copyright 2000, LifeLine Networks BV (www.lifeline.nl). All rights reserved. * Copyright 2000, Bastiaan Bakker. All rights reserved. * * See the COPYING file for the terms of usage and distribution. */ #include <log4cpp/Portability.hh> #include <log4cpp/Appender.hh> namespace log4cpp { #ifdef LOG4CPP_USE_CLEANUP Log4cppCleanup& Appender::_fuckinDummy = Log4cppCleanup::_cleanup; #endif Appender::AppenderMap* Appender::_allAppenders; /* assume _appenderMapMutex locked */ Appender::AppenderMap& Appender::_getAllAppenders() { if (!_allAppenders) _allAppenders = new Appender::AppenderMap(); return *_allAppenders; } Appender* Appender::getAppender(const std::string& name) { threading::ScopedLock lock(_appenderMapMutex); AppenderMap& allAppenders = Appender::_getAllAppenders(); AppenderMap::iterator i = allAppenders.find(name); return (allAppenders.end() == i) ? NULL : ((*i).second); } void Appender::_addAppender(Appender* appender) { //REQUIRE(_allAppenders.find(appender->getName()) == _getAllAppenders().end()) threading::ScopedLock lock(_appenderMapMutex); _getAllAppenders()[appender->getName()] = appender; } void Appender::_removeAppender(Appender* appender) { threading::ScopedLock lock(_appenderMapMutex); _getAllAppenders().erase(appender->getName()); } bool Appender::reopenAll() { threading::ScopedLock lock(_appenderMapMutex); bool result = true; AppenderMap& allAppenders = _getAllAppenders(); for(AppenderMap::iterator i = allAppenders.begin(); i != allAppenders.end(); i++) { result = result && ((*i).second)->reopen(); } return result; } void Appender::closeAll() { threading::ScopedLock lock(_appenderMapMutex); AppenderMap& allAppenders = _getAllAppenders(); for(AppenderMap::iterator i = allAppenders.begin(); i != allAppenders.end(); i++) { ((*i).second)->close(); } } void Appender::_deleteAllAppenders() { threading::ScopedLock lock(_appenderMapMutex); AppenderMap& allAppenders = _getAllAppenders(); for(AppenderMap::iterator i = allAppenders.begin(); i != allAppenders.end(); ) { Appender *app = (*i).second; i++; // increment iterator before delete or iterator will be invalid. delete (app); } } Appender::Appender(const std::string& name) : _name(name) { _addAppender(this); } Appender::~Appender() { _removeAppender(this); } } <commit_msg>added missing Mutex<commit_after>/* * Appender.cpp * * Copyright 2000, LifeLine Networks BV (www.lifeline.nl). All rights reserved. * Copyright 2000, Bastiaan Bakker. All rights reserved. * * See the COPYING file for the terms of usage and distribution. */ #include <log4cpp/Portability.hh> #include <log4cpp/Appender.hh> namespace log4cpp { #ifdef LOG4CPP_USE_CLEANUP Log4cppCleanup& Appender::_fuckinDummy = Log4cppCleanup::_cleanup; #endif Appender::AppenderMap* Appender::_allAppenders; threading::Mutex Appender::_appenderMapMutex; /* assume _appenderMapMutex locked */ Appender::AppenderMap& Appender::_getAllAppenders() { if (!_allAppenders) _allAppenders = new Appender::AppenderMap(); return *_allAppenders; } Appender* Appender::getAppender(const std::string& name) { threading::ScopedLock lock(_appenderMapMutex); AppenderMap& allAppenders = Appender::_getAllAppenders(); AppenderMap::iterator i = allAppenders.find(name); return (allAppenders.end() == i) ? NULL : ((*i).second); } void Appender::_addAppender(Appender* appender) { //REQUIRE(_allAppenders.find(appender->getName()) == _getAllAppenders().end()) threading::ScopedLock lock(_appenderMapMutex); _getAllAppenders()[appender->getName()] = appender; } void Appender::_removeAppender(Appender* appender) { threading::ScopedLock lock(_appenderMapMutex); _getAllAppenders().erase(appender->getName()); } bool Appender::reopenAll() { threading::ScopedLock lock(_appenderMapMutex); bool result = true; AppenderMap& allAppenders = _getAllAppenders(); for(AppenderMap::iterator i = allAppenders.begin(); i != allAppenders.end(); i++) { result = result && ((*i).second)->reopen(); } return result; } void Appender::closeAll() { threading::ScopedLock lock(_appenderMapMutex); AppenderMap& allAppenders = _getAllAppenders(); for(AppenderMap::iterator i = allAppenders.begin(); i != allAppenders.end(); i++) { ((*i).second)->close(); } } void Appender::_deleteAllAppenders() { threading::ScopedLock lock(_appenderMapMutex); AppenderMap& allAppenders = _getAllAppenders(); for(AppenderMap::iterator i = allAppenders.begin(); i != allAppenders.end(); ) { Appender *app = (*i).second; i++; // increment iterator before delete or iterator will be invalid. delete (app); } } Appender::Appender(const std::string& name) : _name(name) { _addAppender(this); } Appender::~Appender() { _removeAppender(this); } } <|endoftext|>
<commit_before><?hh class BaseParam { protected $name; protected $value; protected $required; public function __construct($key, $value) { $this->name = $key; $this->value = $value; $this->required = true; } public function name() {return $this->name;} public function value() {return $this->value;} public function required() {$this->required = true; return $this;} public function isRequired() {return $this->required = true;} public static function IntType($key, $default = null) { $params = array_merge($_GET, $_POST, $_FILES); $value = idx($params, $key); invariant(!($value === null && $default === null), 'Param is required: ' . $key); $value = $value !== null ? $value : $default; $value = filter_var($value, FILTER_SANITIZE_NUMBER_INT); $value = filter_var($value, FILTER_VALIDATE_INT); invariant($value !== false, 'Wrong type: %s', $key); return new BaseParam($key, $value); } public static function EmailType($key, ?string $default = null) { $params = array_merge($_GET, $_POST); $value = idx($params, $key); invariant(!($value === null && $default === null), 'Param is required: ' . $key); if ($value === null && is_string($default)) { return new BaseParam($key, $default); } $value = $value !== null ? $value : $default; $value = filter_var($value, FILTER_SANITIZE_EMAIL); $value = filter_var($value, FILTER_VALIDATE_EMAIL); invariant($value !== false, 'Wrong type: %s', $key); return new BaseParam($key, $value); } public static function FloatType( $key, $default = null) { $params = array_merge($_GET, $_POST, $_FILES); $value = idx($params, $key); invariant(!($value === null && $default === null), 'Param is required: ' . $key); $value = $value !== null ? $value : $default; $value = filter_var( $value, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION); $value = filter_var($value, FILTER_VALIDATE_FLOAT); invariant($value !== false, 'Wrong type: %s', $key); return new BaseParam($key, $value); } public static function ArrayType( $key, $default = null) { $params = array_merge($_GET, $_POST, $_FILES); $value = idx($params, $key); invariant(!($value === null && $default === null), 'Param is required: ' . $key); $value = $value !== null ? $value : $default; invariant(is_array($value) === true, 'Wrong type: %s', $key); return new BaseParam($key, $value); } public static function JSONType( $key, $default = null) { $params = array_merge($_GET, $_POST, $_FILES); $value = idx($params, $key); invariant(!($value === null && $default === null), 'Param is required: ' . $key); $value = $value !== null ? json_decode($value, true) : $default; invariant(JSON_ERROR_NONE === json_last_error(), 'Wrong type: %s', $key); return new BaseParam($key, $value); } public static function StringType( $key, $default = null) { $params = array_merge($_GET, $_POST, $_FILES); $value = trim(idx($params, $key)); invariant(!(empty($value) && $default === null), 'Param is required: ' . $key); $value = $value !== null ? $value : $default; $value = filter_var($value, FILTER_SANITIZE_STRING); invariant(is_string($value), 'Wrong type: %s', $key); return new BaseParam($key, $value); } public static function FileType( $key, $default = null) { invariant(!(idx($_FILES, $key, null) === null && $default === null), 'Param is required: ' . $key); invariant(idx($_FILES, $key, false), 'Wrong type: %s', $key); return new BaseParam($key, $_FILES[$key]); } } <commit_msg>BaseParam: added MongoIdType<commit_after><?hh class BaseParam { protected $name; protected $value; protected $required; public function __construct($key, $value) { $this->name = $key; $this->value = $value; $this->required = true; } public function name() {return $this->name;} public function value() {return $this->value;} public function required() {$this->required = true; return $this;} public function isRequired() {return $this->required = true;} public static function IntType($key, $default = null) { $params = array_merge($_GET, $_POST, $_FILES); $value = idx($params, $key); invariant(!($value === null && $default === null), 'Param is required: ' . $key); $value = $value !== null ? $value : $default; $value = filter_var($value, FILTER_SANITIZE_NUMBER_INT); $value = filter_var($value, FILTER_VALIDATE_INT); invariant($value !== false, 'Wrong type: %s', $key); return new BaseParam($key, $value); } public static function EmailType($key, ?string $default = null) { $params = array_merge($_GET, $_POST); $value = idx($params, $key); invariant(!($value === null && $default === null), 'Param is required: ' . $key); if ($value === null && is_string($default)) { return new BaseParam($key, $default); } $value = $value !== null ? $value : $default; $value = filter_var($value, FILTER_SANITIZE_EMAIL); $value = filter_var($value, FILTER_VALIDATE_EMAIL); invariant($value !== false, 'Wrong type: %s', $key); return new BaseParam($key, $value); } public static function FloatType( $key, $default = null) { $params = array_merge($_GET, $_POST, $_FILES); $value = idx($params, $key); invariant(!($value === null && $default === null), 'Param is required: ' . $key); $value = $value !== null ? $value : $default; $value = filter_var( $value, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION); $value = filter_var($value, FILTER_VALIDATE_FLOAT); invariant($value !== false, 'Wrong type: %s', $key); return new BaseParam($key, $value); } public static function ArrayType( $key, $default = null) { $params = array_merge($_GET, $_POST, $_FILES); $value = idx($params, $key); invariant(!($value === null && $default === null), 'Param is required: ' . $key); $value = $value !== null ? $value : $default; invariant(is_array($value) === true, 'Wrong type: %s', $key); return new BaseParam($key, $value); } public static function JSONType( $key, $default = null) { $params = array_merge($_GET, $_POST, $_FILES); $value = idx($params, $key); invariant(!($value === null && $default === null), 'Param is required: ' . $key); $value = $value !== null ? json_decode($value, true) : $default; invariant(JSON_ERROR_NONE === json_last_error(), 'Wrong type: %s', $key); return new BaseParam($key, $value); } public static function StringType( $key, $default = null) { $params = array_merge($_GET, $_POST); $value = trim(idx($params, $key)); invariant(!(empty($value) && $default === null), 'Param is required: ' . $key); $value = $value !== null ? $value : $default; $value = filter_var($value, FILTER_SANITIZE_STRING); invariant(is_string($value), 'Wrong type: %s', $key); return new BaseParam($key, $value); } public static function FileType( $key, $default = null) { invariant(!(idx($_FILES, $key, null) === null && $default === null), 'Param is required: ' . $key); invariant(idx($_FILES, $key, false), 'Wrong type: %s', $key); return new BaseParam($key, $_FILES[$key]); } public static function MongoIdType( $key, $default = null) { $params = array_merge($_GET, $_POST); $value = trim(idx($params, $key)); invariant(!(empty($value) && $default === null), 'Param is required: ' . $key); if (empty($value) && $default !== null) { return new BaseParam($key, $default); } try { $value = mid($value); } catch (Exception $e) { invariant_violation('Wrong type: %s', $key); } return new BaseParam($key, $value); } } <|endoftext|>
<commit_before><?hh //strict /** * This file is part of package. * * (c) Noritaka Horio <[email protected]> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace package; use Exception; use ReflectionClass; use ReflectionException; final class ClassFile { private ReflectionClass $class; public function __construct( private SourceFileName $name, private PackageNamespace $namespace, private DirectoryPath $packageDirectory ) { $this->class = new ReflectionClass(UnknownClassType::class); $this->initialize(); } /** * Get namespace */ public function getNamespace() : PackageNamespace { return $this->namespace; } /** * Get source file name */ public function getFileName() : SourceFileName { return $this->name; } /** * Get package directory path */ public function getPackageDirectory() : DirectoryPath { return $this->packageDirectory; } /** * Get class full name */ <<__Memoize>> public function getClassName() : string { $relativeClassName = $this->relativeClassNameFrom($this->getFileName()); $fullClassName = $this->getNamespace() . '\\' . $relativeClassName; return $fullClassName; } <<__Memoize>> public function getShortClassName() : string { return preg_replace('/^(\w+\\\\)+/', '', $this->getClassName()); } /** * Get new instance */ public function instantiate<T>(array<mixed> $parameters = []) : T { try { $instance = $this->reflect()->newInstanceArgs($parameters); } catch (Exception $exception) { throw new InstantiationException($this->getClassName()); } return $instance; } private function reflect() : ReflectionClass { try { $class = new ReflectionClass($this->getClassName()); } catch (ReflectionException $exception) { throw new UnknownClassException($this->getClassName()); } return $class; } private function initialize() : void { try { $this->class = new ReflectionClass($this->getClassName()); } catch (ReflectionException $exception) { throw new UnknownClassException($this->getClassName()); } } public function implementsInterface(string $interfaceName) : bool { try { $result = $this->reflect()->implementsInterface($interfaceName); } catch (ReflectionException $exception) { $result = false; } return $result; } public function isSubclassOf(string $className) : bool { return $this->reflect()->isSubclassOf($className); } private function relativeClassNameFrom(SourceFileName $file) : string { $replaceTargets = [ $this->getPackageDirectory() . '/', '/', '.hh' ]; $replaceValues = [ '', '\\', '' ]; $relativeClass = str_replace($replaceTargets, $replaceValues, $file); return $relativeClass; } } <commit_msg>Refactaring<commit_after><?hh //strict /** * This file is part of package. * * (c) Noritaka Horio <[email protected]> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace package; use Exception; use ReflectionClass; use ReflectionException; final class ClassFile { private ReflectionClass $class; public function __construct( private SourceFileName $name, private PackageNamespace $namespace, private DirectoryPath $packageDirectory ) { $this->class = new ReflectionClass(UnknownClassType::class); $this->initialize(); } /** * Get namespace */ public function getNamespace() : PackageNamespace { return $this->namespace; } /** * Get source file name */ public function getFileName() : SourceFileName { return $this->name; } /** * Get package directory path */ public function getPackageDirectory() : DirectoryPath { return $this->packageDirectory; } /** * Get class full name */ <<__Memoize>> public function getClassName() : string { $relativeClassName = $this->relativeClassNameFrom($this->getFileName()); $fullClassName = $this->getNamespace() . '\\' . $relativeClassName; return $fullClassName; } <<__Memoize>> public function getShortClassName() : string { return preg_replace('/^(\w+\\\\)+/', '', $this->getClassName()); } /** * Get new instance */ public function instantiate<T>(array<mixed> $parameters = []) : T { try { $instance = $this->class->newInstanceArgs($parameters); } catch (Exception $exception) { throw new InstantiationException($this->getClassName()); } return $instance; } private function initialize() : void { try { $this->class = new ReflectionClass($this->getClassName()); } catch (ReflectionException $exception) { throw new UnknownClassException($this->getClassName()); } } public function implementsInterface(string $interfaceName) : bool { try { $result = $this->class->implementsInterface($interfaceName); } catch (ReflectionException $exception) { $result = false; } return $result; } public function isSubclassOf(string $className) : bool { return $this->class->isSubclassOf($className); } private function relativeClassNameFrom(SourceFileName $file) : string { $replaceTargets = [ $this->getPackageDirectory() . '/', '/', '.hh' ]; $replaceValues = [ '', '\\', '' ]; $relativeClass = str_replace($replaceTargets, $replaceValues, $file); return $relativeClass; } } <|endoftext|>
<commit_before>/* * Dijkstra.hpp * * Created on: Nov 5, 2014 * Author: Pimenta */ #ifndef DIJKSTRA_HPP_ #define DIJKSTRA_HPP_ #include <queue> #include "Graph.hpp" inline Weight dijkstra(const Graph& G, Vertex source, Vertex target) { struct Path { Vertex v; Weight dist; Path(Vertex v, Weight dist) : v(v), dist(dist) { } bool operator<(const Path& other) const { return dist > other.dist; } }; Weight* dist = new Weight[G.size() + 1]; for (Vertex v = 1; v <= Vertex(G.size()); v++) { dist[v] = INF; } dist[source] = 0; std::priority_queue<Path> Q; Q.push(Path(source, 0)); while (!Q.empty()) { Path edge = Q.top(); Q.pop(); if (edge.v == target) break; if (edge.dist > dist[edge.v]) continue; const std::map<Vertex, Weight>& u = G.at(edge.v); for (auto& kv : u) { Weight alt = edge.dist + kv.second; if (alt < dist[kv.first]) { dist[kv.first] = alt; Q.push(Path(kv.first, alt)); } } } Weight dist_target = dist[target]; delete[] dist; return dist_target; } #endif /* DIJKSTRA_HPP_ */ <commit_msg>Optimizing dijkstra<commit_after>/* * Dijkstra.hpp * * Created on: Nov 5, 2014 * Author: Pimenta */ #ifndef DIJKSTRA_HPP_ #define DIJKSTRA_HPP_ #include <queue> #include "Graph.hpp" inline Weight dijkstra(const Graph& G, Vertex source, Vertex target) { struct Path { Vertex v; Weight dist; Path(Vertex v, Weight dist) : v(v), dist(dist) { } bool operator<(const Path& other) const { return dist > other.dist; } }; Vertex N = int(G.size()); Weight* dist = new Weight[N + 1]; for (Vertex v = 1; v <= N; v++) { dist[v] = INF; } dist[source] = 0; std::priority_queue<Path> Q; Q.push(Path(source, 0)); for (Vertex i = 0; !Q.empty() && i < N; i++) { Path edge = Q.top(); Q.pop(); if (edge.v == target) break; if (edge.dist > dist[edge.v]) { i--; continue; } const std::map<Vertex, Weight>& u = G.at(edge.v); for (auto& kv : u) { Weight alt = edge.dist + kv.second; if (alt < dist[kv.first]) { dist[kv.first] = alt; Q.push(Path(kv.first, alt)); } } } Weight dist_target = dist[target]; delete[] dist; return dist_target; } #endif /* DIJKSTRA_HPP_ */ <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////////// // // Copyright 2006 - 2015, Paul Beckingham, Federico Hernandez. // // 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. // // http://www.opensource.org/licenses/mit-license.php // //////////////////////////////////////////////////////////////////////////////// #include <cmake.h> #include <sstream> #include <string> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <Nibbler.h> #include <Lexer.h> #include <Duration.h> #include <text.h> #define DAY 86400 #define HOUR 3600 #define MINUTE 60 #define SECOND 1 static struct { std::string unit; int seconds; bool standalone; } durations[] = { // These are sorted by first character, then length, so that Nibbler::getOneOf // returns a maximal match. {"annual", 365 * DAY, true}, {"biannual", 730 * DAY, true}, {"bimonthly", 61 * DAY, true}, {"biweekly", 14 * DAY, true}, {"biyearly", 730 * DAY, true}, {"daily", 1 * DAY, true}, {"days", 1 * DAY, false}, {"day", 1 * DAY, true}, {"d", 1 * DAY, false}, {"fortnight", 14 * DAY, true}, {"hours", 1 * HOUR, false}, {"hour", 1 * HOUR, true}, {"h", 1 * HOUR, false}, {"minutes", 1 * MINUTE, false}, {"minute", 1 * MINUTE, false}, {"min", 1 * MINUTE, false}, {"monthly", 30 * DAY, true}, {"months", 30 * DAY, false}, {"month", 30 * DAY, true}, {"mo", 30 * DAY, false}, {"quarterly", 91 * DAY, true}, {"quarters", 91 * DAY, false}, {"quarter", 91 * DAY, true}, {"q", 91 * DAY, false}, {"semiannual", 183 * DAY, true}, {"sennight", 14 * DAY, false}, {"seconds", 1 * SECOND, false}, {"second", 1 * SECOND, true}, {"s", 1 * SECOND, false}, {"weekdays", 1 * DAY, true}, {"weekly", 7 * DAY, true}, {"weeks", 7 * DAY, false}, {"week", 7 * DAY, true}, {"w", 7 * DAY, false}, {"yearly", 365 * DAY, true}, {"years", 365 * DAY, false}, {"year", 365 * DAY, true}, {"y", 365 * DAY, false}, }; #define NUM_DURATIONS (sizeof (durations) / sizeof (durations[0])) //////////////////////////////////////////////////////////////////////////////// Duration::Duration () : _secs (0) { } //////////////////////////////////////////////////////////////////////////////// Duration::Duration (time_t input) : _secs (input) { } //////////////////////////////////////////////////////////////////////////////// Duration::Duration (const std::string& input) : _secs (0) { if (digitsOnly (input)) { time_t value = (time_t) strtol (input.c_str (), NULL, 10); if (value == 0 || value > 60) { _secs = value; return; } } std::string::size_type idx = 0; parse (input, idx); } //////////////////////////////////////////////////////////////////////////////// Duration::~Duration () { } //////////////////////////////////////////////////////////////////////////////// bool Duration::operator< (const Duration& other) { return _secs < other._secs; } //////////////////////////////////////////////////////////////////////////////// bool Duration::operator> (const Duration& other) { return _secs > other._secs; } //////////////////////////////////////////////////////////////////////////////// Duration& Duration::operator= (const Duration& other) { if (this != &other) _secs = other._secs; return *this; } //////////////////////////////////////////////////////////////////////////////// Duration::operator time_t () const { return _secs; } //////////////////////////////////////////////////////////////////////////////// Duration::operator std::string () const { std::stringstream s; s << _secs; return s.str (); } //////////////////////////////////////////////////////////////////////////////// std::string Duration::format () const { char formatted[24]; float days = (float) _secs / 86400.0; if (_secs >= 86400 * 365) sprintf (formatted, "%.1f year%s", (days / 365), ((int) (float) (days / 365) == 1 ? "" : "s")); else if (_secs > 86400 * 84) sprintf (formatted, "%1d month%s", (int) (float) (days / 30), ((int) (float) (days / 30) == 1 ? "" : "s")); else if (_secs > 86400 * 13) sprintf (formatted, "%d week%s", (int) (float) (days / 7.0), ((int) (float) (days / 7.0) == 1 ? "" : "s")); else if (_secs >= 86400) sprintf (formatted, "%d day%s", (int) days, ((int) days == 1 ? "" : "s")); else if (_secs >= 3600) sprintf (formatted, "%d hour%s", (int) (float) (_secs / 3600), ((int) (float) (_secs / 3600) == 1 ? "" : "s")); else if (_secs >= 60) sprintf (formatted, "%d minute%s", (int) (float) (_secs / 60), ((int) (float) (_secs / 60) == 1 ? "" : "s")); else if (_secs >= 1) sprintf (formatted, "%d second%s", (int) _secs, ((int) _secs == 1 ? "" : "s")); else strcpy (formatted, "-"); // no i18n return std::string (formatted); } //////////////////////////////////////////////////////////////////////////////// std::string Duration::formatCompact () const { char formatted[24]; float days = (float) _secs / 86400.0; if (_secs >= 86400 * 365) sprintf (formatted, "%.1fy", (days / 365.0)); else if (_secs >= 86400 * 84) sprintf (formatted, "%1dmo", (int) (days / 30)); else if (_secs >= 86400 * 13) sprintf (formatted, "%dw", (int) (float) (days / 7.0)); else if (_secs >= 86400) sprintf (formatted, "%dd", (int) days); else if (_secs >= 3600) sprintf (formatted, "%dh", (int) (_secs / 3600)); else if (_secs >= 60) sprintf (formatted, "%dmin", (int) (_secs / 60)); else if (_secs >= 1) sprintf (formatted, "%ds", (int) _secs); else formatted[0] = '\0'; return std::string (formatted); } //////////////////////////////////////////////////////////////////////////////// std::string Duration::formatPrecise () const { char formatted[24]; int days = _secs / 86400; int hours = (_secs % 86400) / 3600; int minutes = (_secs % 3600) / 60; int seconds = _secs % 60; if (days > 0) sprintf (formatted, "%dd %d:%02d:%02d", days, hours, minutes, seconds); else sprintf (formatted, "%d:%02d:%02d", hours, minutes, seconds); return std::string (formatted); } //////////////////////////////////////////////////////////////////////////////// std::string Duration::formatSeconds () const { char formatted[24]; sprintf (formatted, "%llus", (unsigned long long)_secs); return std::string (formatted); } //////////////////////////////////////////////////////////////////////////////// std::string Duration::formatISO () const { if (_secs) { time_t t = _secs; int seconds = t % 60; t /= 60; int minutes = t % 60; t /= 60; int hours = t % 24; t /= 24; int days = t % 30; t /= 30; int months = t % 12; t /= 12; int years = t; std::stringstream s; s << 'P'; if (years) s << years << 'Y'; if (months) s << months << 'M'; if (days) s << days << 'D'; if (hours || minutes || seconds) { s << 'T'; if (hours) s << hours << 'H'; if (minutes) s << minutes << 'M'; if (seconds) s << seconds << 'S'; } return s.str (); } else { return "P0S"; } } //////////////////////////////////////////////////////////////////////////////// bool Duration::parse (const std::string& input, std::string::size_type& start) { std::string::size_type original_start = start; Nibbler n (input.substr (start)); // TODO This can be made static, and so preserved between calls. std::vector <std::string> units; for (int i = 0; i < NUM_DURATIONS; i++) units.push_back (durations[i].unit); std::string number; std::string unit; if (n.getOneOf (units, unit)) { if (n.depleted () || Lexer::is_ws (n.next ())) { start = original_start + n.cursor (); // Linear lookup - should be logarithmic. double seconds = 1; for (int i = 0; i < NUM_DURATIONS; i++) { if (durations[i].unit == unit && durations[i].standalone == true) { _secs = static_cast <int> (durations[i].seconds); return true; } } } } else if (n.getNumber (number)) { n.skipWS (); if (n.getOneOf (units, unit)) { if (n.depleted () || Lexer::is_ws (n.next ())) { start = original_start + n.cursor (); double quantity = strtod (number.c_str (), NULL); // Linear lookup - should be logarithmic. double seconds = 1; for (int i = 0; i < NUM_DURATIONS; i++) { if (durations[i].unit == unit) { seconds = durations[i].seconds; _secs = static_cast <int> (quantity * static_cast <double> (seconds)); return true; } } } } } return false; } //////////////////////////////////////////////////////////////////////////////// void Duration::clear () { _secs = 0; } //////////////////////////////////////////////////////////////////////////////// <commit_msg>Converted to Lexer2.<commit_after>//////////////////////////////////////////////////////////////////////////////// // // Copyright 2006 - 2015, Paul Beckingham, Federico Hernandez. // // 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. // // http://www.opensource.org/licenses/mit-license.php // //////////////////////////////////////////////////////////////////////////////// #include <cmake.h> #include <sstream> #include <string> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <Nibbler.h> #include <Lexer2.h> #include <Duration.h> #include <text.h> #define DAY 86400 #define HOUR 3600 #define MINUTE 60 #define SECOND 1 static struct { std::string unit; int seconds; bool standalone; } durations[] = { // These are sorted by first character, then length, so that Nibbler::getOneOf // returns a maximal match. {"annual", 365 * DAY, true}, {"biannual", 730 * DAY, true}, {"bimonthly", 61 * DAY, true}, {"biweekly", 14 * DAY, true}, {"biyearly", 730 * DAY, true}, {"daily", 1 * DAY, true}, {"days", 1 * DAY, false}, {"day", 1 * DAY, true}, {"d", 1 * DAY, false}, {"fortnight", 14 * DAY, true}, {"hours", 1 * HOUR, false}, {"hour", 1 * HOUR, true}, {"h", 1 * HOUR, false}, {"minutes", 1 * MINUTE, false}, {"minute", 1 * MINUTE, false}, {"min", 1 * MINUTE, false}, {"monthly", 30 * DAY, true}, {"months", 30 * DAY, false}, {"month", 30 * DAY, true}, {"mo", 30 * DAY, false}, {"quarterly", 91 * DAY, true}, {"quarters", 91 * DAY, false}, {"quarter", 91 * DAY, true}, {"q", 91 * DAY, false}, {"semiannual", 183 * DAY, true}, {"sennight", 14 * DAY, false}, {"seconds", 1 * SECOND, false}, {"second", 1 * SECOND, true}, {"s", 1 * SECOND, false}, {"weekdays", 1 * DAY, true}, {"weekly", 7 * DAY, true}, {"weeks", 7 * DAY, false}, {"week", 7 * DAY, true}, {"w", 7 * DAY, false}, {"yearly", 365 * DAY, true}, {"years", 365 * DAY, false}, {"year", 365 * DAY, true}, {"y", 365 * DAY, false}, }; #define NUM_DURATIONS (sizeof (durations) / sizeof (durations[0])) //////////////////////////////////////////////////////////////////////////////// Duration::Duration () : _secs (0) { } //////////////////////////////////////////////////////////////////////////////// Duration::Duration (time_t input) : _secs (input) { } //////////////////////////////////////////////////////////////////////////////// Duration::Duration (const std::string& input) : _secs (0) { if (digitsOnly (input)) { time_t value = (time_t) strtol (input.c_str (), NULL, 10); if (value == 0 || value > 60) { _secs = value; return; } } std::string::size_type idx = 0; parse (input, idx); } //////////////////////////////////////////////////////////////////////////////// Duration::~Duration () { } //////////////////////////////////////////////////////////////////////////////// bool Duration::operator< (const Duration& other) { return _secs < other._secs; } //////////////////////////////////////////////////////////////////////////////// bool Duration::operator> (const Duration& other) { return _secs > other._secs; } //////////////////////////////////////////////////////////////////////////////// Duration& Duration::operator= (const Duration& other) { if (this != &other) _secs = other._secs; return *this; } //////////////////////////////////////////////////////////////////////////////// Duration::operator time_t () const { return _secs; } //////////////////////////////////////////////////////////////////////////////// Duration::operator std::string () const { std::stringstream s; s << _secs; return s.str (); } //////////////////////////////////////////////////////////////////////////////// std::string Duration::format () const { char formatted[24]; float days = (float) _secs / 86400.0; if (_secs >= 86400 * 365) sprintf (formatted, "%.1f year%s", (days / 365), ((int) (float) (days / 365) == 1 ? "" : "s")); else if (_secs > 86400 * 84) sprintf (formatted, "%1d month%s", (int) (float) (days / 30), ((int) (float) (days / 30) == 1 ? "" : "s")); else if (_secs > 86400 * 13) sprintf (formatted, "%d week%s", (int) (float) (days / 7.0), ((int) (float) (days / 7.0) == 1 ? "" : "s")); else if (_secs >= 86400) sprintf (formatted, "%d day%s", (int) days, ((int) days == 1 ? "" : "s")); else if (_secs >= 3600) sprintf (formatted, "%d hour%s", (int) (float) (_secs / 3600), ((int) (float) (_secs / 3600) == 1 ? "" : "s")); else if (_secs >= 60) sprintf (formatted, "%d minute%s", (int) (float) (_secs / 60), ((int) (float) (_secs / 60) == 1 ? "" : "s")); else if (_secs >= 1) sprintf (formatted, "%d second%s", (int) _secs, ((int) _secs == 1 ? "" : "s")); else strcpy (formatted, "-"); // no i18n return std::string (formatted); } //////////////////////////////////////////////////////////////////////////////// std::string Duration::formatCompact () const { char formatted[24]; float days = (float) _secs / 86400.0; if (_secs >= 86400 * 365) sprintf (formatted, "%.1fy", (days / 365.0)); else if (_secs >= 86400 * 84) sprintf (formatted, "%1dmo", (int) (days / 30)); else if (_secs >= 86400 * 13) sprintf (formatted, "%dw", (int) (float) (days / 7.0)); else if (_secs >= 86400) sprintf (formatted, "%dd", (int) days); else if (_secs >= 3600) sprintf (formatted, "%dh", (int) (_secs / 3600)); else if (_secs >= 60) sprintf (formatted, "%dmin", (int) (_secs / 60)); else if (_secs >= 1) sprintf (formatted, "%ds", (int) _secs); else formatted[0] = '\0'; return std::string (formatted); } //////////////////////////////////////////////////////////////////////////////// std::string Duration::formatPrecise () const { char formatted[24]; int days = _secs / 86400; int hours = (_secs % 86400) / 3600; int minutes = (_secs % 3600) / 60; int seconds = _secs % 60; if (days > 0) sprintf (formatted, "%dd %d:%02d:%02d", days, hours, minutes, seconds); else sprintf (formatted, "%d:%02d:%02d", hours, minutes, seconds); return std::string (formatted); } //////////////////////////////////////////////////////////////////////////////// std::string Duration::formatSeconds () const { char formatted[24]; sprintf (formatted, "%llus", (unsigned long long)_secs); return std::string (formatted); } //////////////////////////////////////////////////////////////////////////////// std::string Duration::formatISO () const { if (_secs) { time_t t = _secs; int seconds = t % 60; t /= 60; int minutes = t % 60; t /= 60; int hours = t % 24; t /= 24; int days = t % 30; t /= 30; int months = t % 12; t /= 12; int years = t; std::stringstream s; s << 'P'; if (years) s << years << 'Y'; if (months) s << months << 'M'; if (days) s << days << 'D'; if (hours || minutes || seconds) { s << 'T'; if (hours) s << hours << 'H'; if (minutes) s << minutes << 'M'; if (seconds) s << seconds << 'S'; } return s.str (); } else { return "P0S"; } } //////////////////////////////////////////////////////////////////////////////// bool Duration::parse (const std::string& input, std::string::size_type& start) { std::string::size_type original_start = start; Nibbler n (input.substr (start)); // TODO This can be made static, and so preserved between calls. std::vector <std::string> units; for (int i = 0; i < NUM_DURATIONS; i++) units.push_back (durations[i].unit); std::string number; std::string unit; if (n.getOneOf (units, unit)) { if (n.depleted () || Lexer2::isWhitespace (n.next ())) { start = original_start + n.cursor (); // Linear lookup - should be logarithmic. double seconds = 1; for (int i = 0; i < NUM_DURATIONS; i++) { if (durations[i].unit == unit && durations[i].standalone == true) { _secs = static_cast <int> (durations[i].seconds); return true; } } } } else if (n.getNumber (number)) { n.skipWS (); if (n.getOneOf (units, unit)) { if (n.depleted () || Lexer2::isWhitespace (n.next ())) { start = original_start + n.cursor (); double quantity = strtod (number.c_str (), NULL); // Linear lookup - should be logarithmic. double seconds = 1; for (int i = 0; i < NUM_DURATIONS; i++) { if (durations[i].unit == unit) { seconds = durations[i].seconds; _secs = static_cast <int> (quantity * static_cast <double> (seconds)); return true; } } } } } return false; } //////////////////////////////////////////////////////////////////////////////// void Duration::clear () { _secs = 0; } //////////////////////////////////////////////////////////////////////////////// <|endoftext|>
<commit_before>#include "GridView.h" #include <QPen> #include <QCloseEvent> #include <QResizeEvent> #include "GameGrid.h" #include "GolSimulator.h" GridView::GridView(GameGrid& g, QWidget* parent) : QGraphicsView(parent), grid(g) { setWindowTitle(grid.getName().c_str()); currentScaleFactor = 1; scene = new QGraphicsScene; setScene(scene); drawGrid(); /* for(int x = 0; x < size().width(); x += 10) { scene->addLine(x, 0, x, size().height(), QPen(Qt::black)); } for(int y = 0; y < size().height(); y += 10) { scene->addLine(0, y, size().width(), y, QPen(Qt::black)); } */ } void GridView::displayNextGen() { grid = GolSimulator::simulate(grid, 1); } void GridView::drawGrid() { float cellSize; float widthRatio = grid.getTerrainBounds().getWidth() / size().width(); float heightRatio = grid.getTerrainBounds().getHeight() / size().height(); std::cout << "size().width() = " << size().width() << "\n"; std::cout << "size().height() = " << size().height() << "\n"; if(widthRatio > heightRatio) { cellSize = float(size().height()) / grid.getTerrainBounds().getHeight(); std::cout << "using width\n"; } else { cellSize = float(size().width()) / grid.getTerrainBounds().getWidth(); std::cout << "using height\n"; } for(unsigned int x = 0; x < grid.getTerrainBounds().getWidth(); x++) { scene->addLine(x * cellSize, 0, x * cellSize, cellSize * grid.getTerrainBounds().getHeight(), QPen(Qt::black)); } for(unsigned int y = 0; y < grid.getTerrainBounds().getHeight(); y++) { scene->addLine(0, y * cellSize, cellSize * grid.getTerrainBounds().getWidth(), y * cellSize, QPen(Qt::black)); } } void GridView::changeZoom(int factor) { setTransform(QTransform::fromScale(factor, factor)); } void GridView::closeEvent(QCloseEvent* event) { emit gridClosed(); event->accept(); } void GridView::resizeEvent(QResizeEvent* event) { scene->clear(); drawGrid(); } <commit_msg>Started rect drawing, notes in GridView::drawGrid()<commit_after>#include "GridView.h" #include <QPen> #include <QCloseEvent> #include <QResizeEvent> #include <QGraphicsRectItem> #include "GameGrid.h" #include "GolSimulator.h" GridView::GridView(GameGrid& g, QWidget* parent) : QGraphicsView(parent), grid(g) { setWindowTitle(grid.getName().c_str()); currentScaleFactor = 1; scene = new QGraphicsScene; setScene(scene); drawGrid(); /* for(int x = 0; x < size().width(); x += 10) { scene->addLine(x, 0, x, size().height(), QPen(Qt::black)); } for(int y = 0; y < size().height(); y += 10) { scene->addLine(0, y, size().width(), y, QPen(Qt::black)); } */ } void GridView::displayNextGen() { grid = GolSimulator::simulate(grid, 1); } void GridView::drawGrid() { float cellSize; cellSize = float(size().width()) / grid.getTerrainBounds().getWidth(); for(unsigned int x = 0; x < grid.getTerrainBounds().getWidth(); x++) { scene->addLine(x * cellSize, 0, x * cellSize, cellSize * grid.getTerrainBounds().getHeight(), QPen(Qt::black)); } for(unsigned int y = 0; y < grid.getTerrainBounds().getHeight(); y++) { scene->addLine(0, y * cellSize, cellSize * grid.getTerrainBounds().getWidth(), y * cellSize, QPen(Qt::black)); } /* EXAMPLE DRAWING RECT QGraphicsRectItem* rect = new QGraphicsRectItem(0,0,cellSize, cellSize); rect->setBrush(QBrush(Qt::black)); scene->addItem(rect); /* BAD CODE, FIX for(unsigned int x = 0; x < grid.getTerrainBounds().getWidth(); x++) { for(unsigned int y = 0; y < grid.getTerrainBounds().getHeight(); y++) { if(grid.getSquareState(Point(x, y)).getNum() == 1) { int yHigh = size().height() - grid.getTerrainBounds().getTopRight().getY() * cellSize; int yLow = size().height() - grid.getTerrainBounds().getBottomLeft().getY() * cellSize; std::cout << "Here!\n"; std::cout << "yHigh = " << yHigh << ", xHigh = " << yLow << "\n"; QGraphicsRectItem* rect = new QGraphicsRectItem(x * cellSize, yLow, x * cellSize + cellSize, yHigh); rect->setBrush(QBrush(Qt::black)); scene->addItem(rect); } } } */ } void GridView::changeZoom(int factor) { setTransform(QTransform::fromScale(factor, factor)); } void GridView::closeEvent(QCloseEvent* event) { emit gridClosed(); event->accept(); } void GridView::resizeEvent(QResizeEvent* event) { scene->clear(); drawGrid(); } <|endoftext|>
<commit_before>#ifndef LMHISTORY_HH #define LMHISTORY_HH #include <vector> #include "config.hh" #include "history.hh" struct LMHistory { class Word { public: /// \brief The default constructor creates a NULL word (word ID and LM ID /// -1). /// Word(); /// \brief Sets the dictionary and language model ID of the word. /// /// \param word_id Used to uniquely identify every word in the vocabulary, /// and to retrieve their written form from the dictionary. /// \param lm_id Used when computing LM scores. If the language model is /// based on classes, this is the ID of the class of the word in question. /// If the word is not found in the language model, this is -1. /// void set_ids(int word_id, int lm_id); /// \brief Sets the class membership log probability. /// /// \param cm_log_prob If the language model is based on classes, this is /// the class membership log probability. When using multiwords, this is the /// sum of the individual class membership log probabilities. /// void set_cm_log_prob(float cm_log_prob); #ifdef ENABLE_MULTIWORD_SUPPORT /// \brief Adds a component word. For regular words, the entire word has to /// be added as a single component. /// /// \param lm_id Used when computing LM scores. If the language model is /// based on classes, this is the ID of the class of the component word. /// If the word is not found in the language model, this is -1. /// \param cm_log_prob If the language model is based on classes, this is /// the class membership log probability of the component. Otherwise 0. /// void add_component(int lm_id); #endif /// \brief Returns the ID of the word in the dictionary. /// /// Word ID is used to uniquely identify every word in the vocabulary, and /// to retrieve their written form from the dictionary. /// int word_id() const { return m_word_id; } /// \brief Returns the ID of the word (or class) in the language model. /// /// Language model IDs are used when computing LM scores. If the language /// model is based on classes, this is the ID of the class of the word in /// question. If the word is not found in the language model, this is -1. /// int lm_id() const { return m_lm_id; } /// \brief Returns the log probability for the class membership, when the /// language model is based on classes. Otherwise returns 0. If this is a /// multiword, returns the sum of the class membership log probabilities of /// the component words. /// /// We assume each word is a member of at most one class. /// float cm_log_prob() const { return m_cm_log_prob; } #ifdef ENABLE_MULTIWORD_SUPPORT /// \brief Returns the number of components in a multiword (1 for regular /// words). /// int num_components() const { return m_component_lm_ids.size(); } /// \brief Returns the word ID for component \a index in the language model /// (or the whole word if this is not a multiword). /// int component_lm_id(int index) const { return m_component_lm_ids[index]; } #endif private: /// Word ID in the dictionary. int m_word_id; /// Word ID in the language model. int m_lm_id; /// The log probability for the class membership, or 0 if not using a class- /// based language model. float m_cm_log_prob; #ifdef ENABLE_MULTIWORD_SUPPORT /// Word IDs in the language model of the component words. std::vector<int> m_component_lm_ids; #endif }; LMHistory(const Word & last_word, LMHistory * previous); const Word & last() const { return m_last_word; } public: LMHistory * previous; int reference_count; bool printed; int word_start_frame; int word_first_silence_frame; // "end frame", initialized to -1. private: // A reference to TokenPassSearch::m_word_lookup table. const Word & m_last_word; }; inline LMHistory::LMHistory(const Word & last_word, LMHistory * previous) : previous(previous), reference_count(0), printed(false), word_start_frame( 0), word_first_silence_frame(-1), m_last_word(last_word) { if (previous) hist::link(previous); } #endif <commit_msg>Minor edit.<commit_after>#ifndef LMHISTORY_HH #define LMHISTORY_HH #include <vector> #include "config.hh" #include "history.hh" class LMHistory { public: class Word { public: /// \brief The default constructor creates a NULL word (word ID and LM ID /// -1). /// Word(); /// \brief Sets the dictionary and language model ID of the word. /// /// \param word_id Used to uniquely identify every word in the vocabulary, /// and to retrieve their written form from the dictionary. /// \param lm_id Used when computing LM scores. If the language model is /// based on classes, this is the ID of the class of the word in question. /// If the word is not found in the language model, this is -1. /// void set_ids(int word_id, int lm_id); /// \brief Sets the class membership log probability. /// /// \param cm_log_prob If the language model is based on classes, this is /// the class membership log probability. When using multiwords, this is the /// sum of the individual class membership log probabilities. /// void set_cm_log_prob(float cm_log_prob); #ifdef ENABLE_MULTIWORD_SUPPORT /// \brief Adds a component word. For regular words, the entire word has to /// be added as a single component. /// /// \param lm_id Used when computing LM scores. If the language model is /// based on classes, this is the ID of the class of the component word. /// If the word is not found in the language model, this is -1. /// \param cm_log_prob If the language model is based on classes, this is /// the class membership log probability of the component. Otherwise 0. /// void add_component(int lm_id); #endif /// \brief Returns the ID of the word in the dictionary. /// /// Word ID is used to uniquely identify every word in the vocabulary, and /// to retrieve their written form from the dictionary. /// int word_id() const { return m_word_id; } /// \brief Returns the ID of the word (or class) in the language model. /// /// Language model IDs are used when computing LM scores. If the language /// model is based on classes, this is the ID of the class of the word in /// question. If the word is not found in the language model, this is -1. /// int lm_id() const { return m_lm_id; } /// \brief Returns the log probability for the class membership, when the /// language model is based on classes. Otherwise returns 0. If this is a /// multiword, returns the sum of the class membership log probabilities of /// the component words. /// /// We assume each word is a member of at most one class. /// float cm_log_prob() const { return m_cm_log_prob; } #ifdef ENABLE_MULTIWORD_SUPPORT /// \brief Returns the number of components in a multiword (1 for regular /// words). /// int num_components() const { return m_component_lm_ids.size(); } /// \brief Returns the word ID for component \a index in the language model /// (or the whole word if this is not a multiword). /// int component_lm_id(int index) const { return m_component_lm_ids[index]; } #endif private: /// Word ID in the dictionary. int m_word_id; /// Word ID in the language model. int m_lm_id; /// The log probability for the class membership, or 0 if not using a class- /// based language model. float m_cm_log_prob; #ifdef ENABLE_MULTIWORD_SUPPORT /// Word IDs in the language model of the component words. std::vector<int> m_component_lm_ids; #endif }; LMHistory(const Word & last_word, LMHistory * previous); const Word & last() const { return m_last_word; } LMHistory * previous; int reference_count; bool printed; int word_start_frame; int word_first_silence_frame; // "end frame", initialized to -1. private: // A reference to TokenPassSearch::m_word_lookup table. const Word & m_last_word; }; inline LMHistory::LMHistory(const Word & last_word, LMHistory * previous) : previous(previous), reference_count(0), printed(false), word_start_frame( 0), word_first_silence_frame(-1), m_last_word(last_word) { if (previous) hist::link(previous); } #endif <|endoftext|>
<commit_before>/* Copyright (c) 2014 Stanford University * * Permission to use, copy, modify, and distribute this software for any purpose * with or without fee is hereby granted, provided that the above copyright * notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR(S) DISCLAIM ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "Cycles.h" #include "PerfStats.h" namespace RAMCloud { SpinLock PerfStats::mutex; std::vector<PerfStats*> PerfStats::registeredStats; __thread PerfStats PerfStats::threadStats; /** * This method must be called to make a PerfStats structure "known" so that * its contents will be considered by collectStats. Typically this method * is invoked once for the thread-local structure associated with each * thread. This method is idempotent and thread-safe, so it is safe to * invoke it multiple times for the same PerfStats. * * \param stats * PerfStats structure to remember for usage by collectStats. If this * is the first time this structure has been registered, all of its * counters will be initialized. */ void PerfStats::registerStats(PerfStats* stats) { std::lock_guard<SpinLock> lock(mutex); // First see if this structure is already registered; if so, // there is nothing for us to do. foreach (PerfStats* registered, registeredStats) { if (registered == stats) { return; } } // This is a new structure; add it to our list, and reset its contents. stats->readCount = 0; stats->writeCount = 0; stats->activeCycles = 0; registeredStats.push_back(stats); } /** * This method aggregates performance information from all of the * PerfStats structures that have been registered via the registerStats * method. * * \param[out] total * Filled in with the sum of all statistics from all registered * PerfStat structures; any existing contents are overwritten. */ void PerfStats::collectStats(PerfStats* total) { std::lock_guard<SpinLock> lock(mutex); total->readCount = 0; total->writeCount = 0; total->activeCycles = 0; foreach (PerfStats* stats, registeredStats) { RAMCLOUD_LOG(NOTICE, "readCount: %lu", stats->readCount); total->readCount += stats->readCount; total->writeCount += stats->writeCount; total->activeCycles += stats->activeCycles; } total->collectionTime = Cycles::rdtsc(); total->cyclesPerSecond = Cycles::perSecond(); } } // namespace RAMCloud <commit_msg>Removed superfluous log message.<commit_after>/* Copyright (c) 2014 Stanford University * * Permission to use, copy, modify, and distribute this software for any purpose * with or without fee is hereby granted, provided that the above copyright * notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR(S) DISCLAIM ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "Cycles.h" #include "PerfStats.h" namespace RAMCloud { SpinLock PerfStats::mutex; std::vector<PerfStats*> PerfStats::registeredStats; __thread PerfStats PerfStats::threadStats; /** * This method must be called to make a PerfStats structure "known" so that * its contents will be considered by collectStats. Typically this method * is invoked once for the thread-local structure associated with each * thread. This method is idempotent and thread-safe, so it is safe to * invoke it multiple times for the same PerfStats. * * \param stats * PerfStats structure to remember for usage by collectStats. If this * is the first time this structure has been registered, all of its * counters will be initialized. */ void PerfStats::registerStats(PerfStats* stats) { std::lock_guard<SpinLock> lock(mutex); // First see if this structure is already registered; if so, // there is nothing for us to do. foreach (PerfStats* registered, registeredStats) { if (registered == stats) { return; } } // This is a new structure; add it to our list, and reset its contents. stats->readCount = 0; stats->writeCount = 0; stats->activeCycles = 0; registeredStats.push_back(stats); } /** * This method aggregates performance information from all of the * PerfStats structures that have been registered via the registerStats * method. * * \param[out] total * Filled in with the sum of all statistics from all registered * PerfStat structures; any existing contents are overwritten. */ void PerfStats::collectStats(PerfStats* total) { std::lock_guard<SpinLock> lock(mutex); total->readCount = 0; total->writeCount = 0; total->activeCycles = 0; foreach (PerfStats* stats, registeredStats) { total->readCount += stats->readCount; total->writeCount += stats->writeCount; total->activeCycles += stats->activeCycles; } total->collectionTime = Cycles::rdtsc(); total->cyclesPerSecond = Cycles::perSecond(); } } // namespace RAMCloud <|endoftext|>
<commit_before>/* Copyright (C) 2010 George Kiagiadakis <[email protected]> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This 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 Lesser General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "bus.h" #include "message.h" #include "../QGlib/signal.h" #include <gst/gst.h> #include <QtCore/QObject> #include <QtCore/QTimerEvent> #include <QtCore/QHash> #include <QtCore/QBasicTimer> namespace QGst { namespace Private { class BusWatch : public QObject { public: BusWatch(GstBus *bus) : QObject(), m_bus(bus) { m_timer.start(10, this); } void stop() { m_timer.stop(); } private: virtual void timerEvent(QTimerEvent *event) { if (event->timerId() == m_timer.timerId()) { dispatch(); } else { QObject::timerEvent(event); } } void dispatch() { GstMessage *message; gst_object_ref(m_bus); while((message = gst_bus_pop(m_bus)) != NULL) { MessagePtr msg = MessagePtr::wrap(message, false); QGlib::Quark detail = gst_message_type_to_quark(static_cast<GstMessageType>(msg->type())); QGlib::emitWithDetail<void>(m_bus, "message", detail, msg); } gst_object_unref(m_bus); } GstBus *m_bus; QBasicTimer m_timer; }; class BusWatchManager { public: void addWatch(GstBus *bus) { if (m_watches.contains(bus)) { m_watches[bus].second++; //reference count } else { m_watches.insert(bus, qMakePair(new BusWatch(bus), uint(1))); g_object_weak_ref(G_OBJECT(bus), &BusWatchManager::onBusDestroyed, this); } } void removeWatch(GstBus *bus) { if (m_watches.contains(bus) && --m_watches[bus].second == 0) { m_watches[bus].first->stop(); m_watches[bus].first->deleteLater(); m_watches.remove(bus); g_object_weak_unref(G_OBJECT(bus), &BusWatchManager::onBusDestroyed, this); } } private: static void onBusDestroyed(gpointer selfPtr, GObject *busPtr) { BusWatchManager *self = static_cast<BusWatchManager*>(selfPtr); GstBus *bus = reinterpret_cast<GstBus*>(busPtr); //we cannot call removeWatch() here because g_object_weak_unref will complain self->m_watches[bus].first->stop(); self->m_watches[bus].first->deleteLater(); self->m_watches.remove(bus); } QHash< GstBus*, QPair<BusWatch*, uint> > m_watches; }; Q_GLOBAL_STATIC(Private::BusWatchManager, s_watchManager) } //namespace Private //static BusPtr Bus::create() { GstBus *bus = gst_bus_new(); if (bus) { gst_object_ref_sink(bus); } return BusPtr::wrap(bus, false); } bool Bus::hasPendingMessages() const { return gst_bus_have_pending(object<GstBus>()); } MessagePtr Bus::peek() const { return MessagePtr::wrap(gst_bus_peek(object<GstBus>()), false); } MessagePtr Bus::pop(ClockTime timeout) { return MessagePtr::wrap(gst_bus_timed_pop(object<GstBus>(), timeout), false); } MessagePtr Bus::pop(MessageType type, ClockTime timeout) { return MessagePtr::wrap(gst_bus_timed_pop_filtered(object<GstBus>(), timeout, static_cast<GstMessageType>(type)), false); } bool Bus::post(const MessagePtr & message) { return gst_bus_post(object<GstBus>(), gst_message_copy(message)); } void Bus::setFlushing(bool flush) { gst_bus_set_flushing(object<GstBus>(), flush); } void Bus::addSignalWatch() { Private::s_watchManager()->addWatch(object<GstBus>()); } void Bus::removeSignalWatch() { Private::s_watchManager()->removeWatch(object<GstBus>()); } void Bus::enableSyncMessageEmission() { gst_bus_enable_sync_message_emission(object<GstBus>()); } void Bus::disableSyncMessageEmission() { gst_bus_disable_sync_message_emission(object<GstBus>()); } } //namespace QGst <commit_msg>Increase the bus watch timeout to 50 ms.<commit_after>/* Copyright (C) 2010 George Kiagiadakis <[email protected]> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This 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 Lesser General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "bus.h" #include "message.h" #include "../QGlib/signal.h" #include <gst/gst.h> #include <QtCore/QObject> #include <QtCore/QTimerEvent> #include <QtCore/QHash> #include <QtCore/QBasicTimer> namespace QGst { namespace Private { class BusWatch : public QObject { public: BusWatch(GstBus *bus) : QObject(), m_bus(bus) { m_timer.start(50, this); } void stop() { m_timer.stop(); } private: virtual void timerEvent(QTimerEvent *event) { if (event->timerId() == m_timer.timerId()) { dispatch(); } else { QObject::timerEvent(event); } } void dispatch() { GstMessage *message; gst_object_ref(m_bus); while((message = gst_bus_pop(m_bus)) != NULL) { MessagePtr msg = MessagePtr::wrap(message, false); QGlib::Quark detail = gst_message_type_to_quark(static_cast<GstMessageType>(msg->type())); QGlib::emitWithDetail<void>(m_bus, "message", detail, msg); } gst_object_unref(m_bus); } GstBus *m_bus; QBasicTimer m_timer; }; class BusWatchManager { public: void addWatch(GstBus *bus) { if (m_watches.contains(bus)) { m_watches[bus].second++; //reference count } else { m_watches.insert(bus, qMakePair(new BusWatch(bus), uint(1))); g_object_weak_ref(G_OBJECT(bus), &BusWatchManager::onBusDestroyed, this); } } void removeWatch(GstBus *bus) { if (m_watches.contains(bus) && --m_watches[bus].second == 0) { m_watches[bus].first->stop(); m_watches[bus].first->deleteLater(); m_watches.remove(bus); g_object_weak_unref(G_OBJECT(bus), &BusWatchManager::onBusDestroyed, this); } } private: static void onBusDestroyed(gpointer selfPtr, GObject *busPtr) { BusWatchManager *self = static_cast<BusWatchManager*>(selfPtr); GstBus *bus = reinterpret_cast<GstBus*>(busPtr); //we cannot call removeWatch() here because g_object_weak_unref will complain self->m_watches[bus].first->stop(); self->m_watches[bus].first->deleteLater(); self->m_watches.remove(bus); } QHash< GstBus*, QPair<BusWatch*, uint> > m_watches; }; Q_GLOBAL_STATIC(Private::BusWatchManager, s_watchManager) } //namespace Private //static BusPtr Bus::create() { GstBus *bus = gst_bus_new(); if (bus) { gst_object_ref_sink(bus); } return BusPtr::wrap(bus, false); } bool Bus::hasPendingMessages() const { return gst_bus_have_pending(object<GstBus>()); } MessagePtr Bus::peek() const { return MessagePtr::wrap(gst_bus_peek(object<GstBus>()), false); } MessagePtr Bus::pop(ClockTime timeout) { return MessagePtr::wrap(gst_bus_timed_pop(object<GstBus>(), timeout), false); } MessagePtr Bus::pop(MessageType type, ClockTime timeout) { return MessagePtr::wrap(gst_bus_timed_pop_filtered(object<GstBus>(), timeout, static_cast<GstMessageType>(type)), false); } bool Bus::post(const MessagePtr & message) { return gst_bus_post(object<GstBus>(), gst_message_copy(message)); } void Bus::setFlushing(bool flush) { gst_bus_set_flushing(object<GstBus>(), flush); } void Bus::addSignalWatch() { Private::s_watchManager()->addWatch(object<GstBus>()); } void Bus::removeSignalWatch() { Private::s_watchManager()->removeWatch(object<GstBus>()); } void Bus::enableSyncMessageEmission() { gst_bus_enable_sync_message_emission(object<GstBus>()); } void Bus::disableSyncMessageEmission() { gst_bus_disable_sync_message_emission(object<GstBus>()); } } //namespace QGst <|endoftext|>
<commit_before>#include <stdio.h> #include <iostream> #include <vector> // glm additional header to generate transformation matrices directly. #include <glm/gtc/matrix_transform.hpp> #include <cstring> // For memcopy depending on the platform. #include "helpers/ProgramUtilities.h" #include "Renderer.h" Renderer::Renderer(){} Renderer::~Renderer(){} void Renderer::init(int width, int height){ // Initialize the timer and pingpong. _timer = glfwGetTime(); _pingpong = 0; // Setup projection matrix. _camera.screen(width, height); // Setup the framebuffer. _lightFramebuffer = Framebuffer(1024, 1024); _lightFramebuffer.setup(GL_RG,GL_FLOAT,GL_LINEAR,GL_CLAMP_TO_BORDER); _blurFramebuffer = Framebuffer(1024, 1024); _blurFramebuffer.setup(GL_RG,GL_FLOAT,GL_LINEAR,GL_CLAMP_TO_BORDER); _sceneFramebuffer = Framebuffer(_camera._renderSize[0],_camera._renderSize[1]); _sceneFramebuffer.setup(GL_RGBA,GL_UNSIGNED_BYTE,GL_LINEAR,GL_CLAMP_TO_EDGE); _fxaaFramebuffer = Framebuffer(_camera._renderSize[0],_camera._renderSize[1]); _fxaaFramebuffer.setup(GL_RGBA,GL_UNSIGNED_BYTE,GL_LINEAR,GL_CLAMP_TO_EDGE); // Query the renderer identifier, and the supported OpenGL version. const GLubyte* renderer = glGetString(GL_RENDERER); const GLubyte* version = glGetString(GL_VERSION); std::cout << "Renderer: " << renderer << std::endl; std::cout << "OpenGL version supported: " << version << std::endl; checkGLError(); // GL options glEnable(GL_DEPTH_TEST); glEnable(GL_CULL_FACE); glFrontFace(GL_CCW); glCullFace(GL_BACK); checkGLError(); // Setup light _light = Light(glm::vec4(0.0f),glm::vec4(0.3f, 0.3f, 0.3f, 0.0f), glm::vec4(0.8f, 0.8f,0.8f, 0.0f), glm::vec4(1.0f, 1.0f, 1.0f, 0.0f), 25.0f, glm::ortho(-0.75f,0.75f,-0.75f,0.75f,2.0f,6.0f)); // position will be updated at each frame //glm::perspective(45.0f, 1.0f, 1.0f, 5.f); depending on the type of light, one might prefer to use one or the other matrix. // Generate the buffer. glGenBuffers(1, &_ubo); // Bind the buffer. glBindBuffer(GL_UNIFORM_BUFFER, _ubo); // We need to know the alignment size if we want to store two uniform blocks in the same uniform buffer. GLint uboAlignSize = 0; glGetIntegerv(GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT, &uboAlignSize); // Compute the padding for the second block, it needs to be a multiple of uboAlignSize (typically uboAlignSize will be 256.) GLuint lightSize = 4*sizeof(glm::vec4) + 1*sizeof(float); _padding = ((lightSize/uboAlignSize)+1)*uboAlignSize; // Allocate enough memory to hold two copies of the Light struct. glBufferData(GL_UNIFORM_BUFFER, _padding + lightSize, NULL, GL_DYNAMIC_DRAW); // Bind the range allocated to the first version of the light. glBindBufferRange(GL_UNIFORM_BUFFER, 0, _ubo, 0, lightSize); // Submit the data. glBufferSubData(GL_UNIFORM_BUFFER, 0, lightSize, _light.getStruct()); // Bind the range allocated to the second version of the light. glBindBufferRange(GL_UNIFORM_BUFFER, 1, _ubo, _padding, lightSize); // Submit the data. glBufferSubData(GL_UNIFORM_BUFFER, _padding, lightSize, _light.getStruct()); glBindBuffer(GL_UNIFORM_BUFFER,0); // Initialize objects. _suzanne.init(_blurFramebuffer.textureId()); _dragon.init(_blurFramebuffer.textureId()); _plane.init(_blurFramebuffer.textureId()); _skybox.init(); _blurScreen.init(_lightFramebuffer.textureId(), "ressources/shaders/boxblur"); _fxaaScreen.init(_sceneFramebuffer.textureId(), "ressources/shaders/fxaa"); _finalScreen.init(_fxaaFramebuffer.textureId(), "ressources/shaders/final_screenquad"); checkGLError(); } void Renderer::draw(){ // Compute the time elapsed since last frame float elapsed = glfwGetTime() - _timer; _timer = glfwGetTime(); // Physics simulation physics(elapsed); // Update the light position (in view space). // Bind the buffer. glBindBuffer(GL_UNIFORM_BUFFER, _ubo); // Obtain a handle to the underlying memory. // We force the GPU to consider the memory region as unsynchronized: // even if it is used, it will be overwritten. As we alternate between // two sub-buffers indices ("ping-ponging"), we won't risk writing over // a currently used value. GLvoid * ptr = glMapBufferRange(GL_UNIFORM_BUFFER,_pingpong*_padding,sizeof(glm::vec4),GL_MAP_WRITE_BIT | GL_MAP_UNSYNCHRONIZED_BIT); // Copy the light position. std::memcpy(ptr, _light.getStruct(), sizeof(glm::vec4)); // Unmap, unbind. glUnmapBuffer(GL_UNIFORM_BUFFER); glBindBuffer(GL_UNIFORM_BUFFER, 0); // --- Light pass ------- // Draw the scene inside the framebuffer. _lightFramebuffer.bind(); glViewport(0, 0, _lightFramebuffer._width, _lightFramebuffer._height); // Set the clear color to white. glClearColor(1.0f,1.0f,1.0f,0.0f); // Clear the color and depth buffers. glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Draw objects. _suzanne.drawDepth(elapsed, _light._mvp); _dragon.drawDepth(elapsed, _light._mvp); _plane.drawDepth(elapsed, _light._mvp); // Unbind the shadow map framebuffer. _lightFramebuffer.unbind(); // ---------------------- // --- Blur pass -------- glDisable(GL_DEPTH_TEST); // Bind the post-processing framebuffer. _blurFramebuffer.bind(); // Set screen viewport. glViewport(0,0,_blurFramebuffer._width, _blurFramebuffer._height); // Draw the fullscreen quad _blurScreen.draw( 1.0f / _camera._renderSize); _blurFramebuffer.unbind(); glEnable(GL_DEPTH_TEST); // ---------------------- // --- Scene pass ------- // Bind the full scene framebuffer. _sceneFramebuffer.bind(); // Set screen viewport glViewport(0,0,_sceneFramebuffer._width,_sceneFramebuffer._height); // Clear the depth buffer (we know we will draw everywhere, no need to clear color. glClear(GL_DEPTH_BUFFER_BIT); // Draw objects _suzanne.draw(elapsed, _camera._view, _camera._projection, _pingpong); _dragon.draw(elapsed, _camera._view, _camera._projection, _pingpong); _plane.draw(elapsed, _camera._view, _camera._projection, _pingpong); _skybox.draw(elapsed, _camera._view, _camera._projection); // Unbind the full scene framebuffer. _sceneFramebuffer.unbind(); // ---------------------- glDisable(GL_DEPTH_TEST); // --- FXAA pass ------- // Bind the post-processing framebuffer. _fxaaFramebuffer.bind(); // Set screen viewport. glViewport(0,0,_fxaaFramebuffer._width, _fxaaFramebuffer._height); // Draw the fullscreen quad _fxaaScreen.draw( 1.0f / _camera._renderSize); _fxaaFramebuffer.unbind(); // ---------------------- // --- Final pass ------- // We now render a full screen quad in the default framebuffer, using sRGB space. glEnable(GL_FRAMEBUFFER_SRGB); // Set screen viewport. glViewport(0,0,_camera._screenSize[0],_camera._screenSize[1]); // Draw the fullscreen quad _finalScreen.draw( 1.0f / _camera._screenSize); glDisable(GL_FRAMEBUFFER_SRGB); // ---------------------- glEnable(GL_DEPTH_TEST); // Update timer _timer = glfwGetTime(); // Update pingpong _pingpong = (_pingpong + 1)%2; } void Renderer::physics(float elapsedTime){ _camera.update(elapsedTime); _light.update(_timer, _camera._view); } void Renderer::clean(){ // Clean objects. _suzanne.clean(); _dragon.clean(); _plane.clean(); _skybox.clean(); _blurScreen.clean(); _fxaaScreen.clean(); _finalScreen.clean(); _lightFramebuffer.clean(); _blurFramebuffer.clean(); _sceneFramebuffer.clean(); _fxaaFramebuffer.clean(); } void Renderer::resize(int width, int height){ //Update the size of the viewport. glViewport(0, 0, width, height); // Update the projection matrix. _camera.screen(width, height); // Resize the framebuffer. _sceneFramebuffer.resize(_camera._renderSize); _fxaaFramebuffer.resize(_camera._renderSize); } void Renderer::keyPressed(int key, int action){ if(action == GLFW_PRESS){ _camera.key(key, true); } else if(action == GLFW_RELEASE) { _camera.key(key, false); } } void Renderer::buttonPressed(int button, int action, double x, double y){ if (button == GLFW_MOUSE_BUTTON_LEFT) { if (action == GLFW_PRESS) { _camera.mouse(MouseMode::Start,x, y); } else if (action == GLFW_RELEASE) { _camera.mouse(MouseMode::End, 0.0, 0.0); } } else { std::cout << "Button: " << button << ", action: " << action << std::endl; } } void Renderer::mousePosition(int x, int y, bool leftPress, bool rightPress){ if (leftPress){ _camera.mouse(MouseMode::Move, float(x), float(y)); } } <commit_msg>Use a smaller shadow map texture size.<commit_after>#include <stdio.h> #include <iostream> #include <vector> // glm additional header to generate transformation matrices directly. #include <glm/gtc/matrix_transform.hpp> #include <cstring> // For memcopy depending on the platform. #include "helpers/ProgramUtilities.h" #include "Renderer.h" Renderer::Renderer(){} Renderer::~Renderer(){} void Renderer::init(int width, int height){ // Initialize the timer and pingpong. _timer = glfwGetTime(); _pingpong = 0; // Setup projection matrix. _camera.screen(width, height); // Setup the framebuffer. _lightFramebuffer = Framebuffer(512, 512); _lightFramebuffer.setup(GL_RG,GL_FLOAT,GL_LINEAR,GL_CLAMP_TO_BORDER); _blurFramebuffer = Framebuffer(_lightFramebuffer._width, _lightFramebuffer._height); _blurFramebuffer.setup(GL_RG,GL_FLOAT,GL_LINEAR,GL_CLAMP_TO_BORDER); _sceneFramebuffer = Framebuffer(_camera._renderSize[0],_camera._renderSize[1]); _sceneFramebuffer.setup(GL_RGBA,GL_UNSIGNED_BYTE,GL_LINEAR,GL_CLAMP_TO_EDGE); _fxaaFramebuffer = Framebuffer(_camera._renderSize[0],_camera._renderSize[1]); _fxaaFramebuffer.setup(GL_RGBA,GL_UNSIGNED_BYTE,GL_LINEAR,GL_CLAMP_TO_EDGE); // Query the renderer identifier, and the supported OpenGL version. const GLubyte* renderer = glGetString(GL_RENDERER); const GLubyte* version = glGetString(GL_VERSION); std::cout << "Renderer: " << renderer << std::endl; std::cout << "OpenGL version supported: " << version << std::endl; checkGLError(); // GL options glEnable(GL_DEPTH_TEST); glEnable(GL_CULL_FACE); glFrontFace(GL_CCW); glCullFace(GL_BACK); checkGLError(); // Setup light _light = Light(glm::vec4(0.0f),glm::vec4(0.3f, 0.3f, 0.3f, 0.0f), glm::vec4(0.8f, 0.8f,0.8f, 0.0f), glm::vec4(1.0f, 1.0f, 1.0f, 0.0f), 25.0f, glm::ortho(-0.75f,0.75f,-0.75f,0.75f,2.0f,6.0f)); // position will be updated at each frame //glm::perspective(45.0f, 1.0f, 1.0f, 5.f); depending on the type of light, one might prefer to use one or the other matrix. // Generate the buffer. glGenBuffers(1, &_ubo); // Bind the buffer. glBindBuffer(GL_UNIFORM_BUFFER, _ubo); // We need to know the alignment size if we want to store two uniform blocks in the same uniform buffer. GLint uboAlignSize = 0; glGetIntegerv(GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT, &uboAlignSize); // Compute the padding for the second block, it needs to be a multiple of uboAlignSize (typically uboAlignSize will be 256.) GLuint lightSize = 4*sizeof(glm::vec4) + 1*sizeof(float); _padding = ((lightSize/uboAlignSize)+1)*uboAlignSize; // Allocate enough memory to hold two copies of the Light struct. glBufferData(GL_UNIFORM_BUFFER, _padding + lightSize, NULL, GL_DYNAMIC_DRAW); // Bind the range allocated to the first version of the light. glBindBufferRange(GL_UNIFORM_BUFFER, 0, _ubo, 0, lightSize); // Submit the data. glBufferSubData(GL_UNIFORM_BUFFER, 0, lightSize, _light.getStruct()); // Bind the range allocated to the second version of the light. glBindBufferRange(GL_UNIFORM_BUFFER, 1, _ubo, _padding, lightSize); // Submit the data. glBufferSubData(GL_UNIFORM_BUFFER, _padding, lightSize, _light.getStruct()); glBindBuffer(GL_UNIFORM_BUFFER,0); // Initialize objects. _suzanne.init(_blurFramebuffer.textureId()); _dragon.init(_blurFramebuffer.textureId()); _plane.init(_blurFramebuffer.textureId()); _skybox.init(); _blurScreen.init(_lightFramebuffer.textureId(), "ressources/shaders/boxblur"); _fxaaScreen.init(_sceneFramebuffer.textureId(), "ressources/shaders/fxaa"); _finalScreen.init(_fxaaFramebuffer.textureId(), "ressources/shaders/final_screenquad"); checkGLError(); } void Renderer::draw(){ // Compute the time elapsed since last frame float elapsed = glfwGetTime() - _timer; _timer = glfwGetTime(); // Physics simulation physics(elapsed); // Update the light position (in view space). // Bind the buffer. glBindBuffer(GL_UNIFORM_BUFFER, _ubo); // Obtain a handle to the underlying memory. // We force the GPU to consider the memory region as unsynchronized: // even if it is used, it will be overwritten. As we alternate between // two sub-buffers indices ("ping-ponging"), we won't risk writing over // a currently used value. GLvoid * ptr = glMapBufferRange(GL_UNIFORM_BUFFER,_pingpong*_padding,sizeof(glm::vec4),GL_MAP_WRITE_BIT | GL_MAP_UNSYNCHRONIZED_BIT); // Copy the light position. std::memcpy(ptr, _light.getStruct(), sizeof(glm::vec4)); // Unmap, unbind. glUnmapBuffer(GL_UNIFORM_BUFFER); glBindBuffer(GL_UNIFORM_BUFFER, 0); // --- Light pass ------- // Draw the scene inside the framebuffer. _lightFramebuffer.bind(); glViewport(0, 0, _lightFramebuffer._width, _lightFramebuffer._height); // Set the clear color to white. glClearColor(1.0f,1.0f,1.0f,0.0f); // Clear the color and depth buffers. glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Draw objects. _suzanne.drawDepth(elapsed, _light._mvp); _dragon.drawDepth(elapsed, _light._mvp); _plane.drawDepth(elapsed, _light._mvp); // Unbind the shadow map framebuffer. _lightFramebuffer.unbind(); // ---------------------- // --- Blur pass -------- glDisable(GL_DEPTH_TEST); // Bind the post-processing framebuffer. _blurFramebuffer.bind(); // Set screen viewport. glViewport(0,0,_blurFramebuffer._width, _blurFramebuffer._height); // Draw the fullscreen quad _blurScreen.draw( 1.0f / _camera._renderSize); _blurFramebuffer.unbind(); glEnable(GL_DEPTH_TEST); // ---------------------- // --- Scene pass ------- // Bind the full scene framebuffer. _sceneFramebuffer.bind(); // Set screen viewport glViewport(0,0,_sceneFramebuffer._width,_sceneFramebuffer._height); // Clear the depth buffer (we know we will draw everywhere, no need to clear color. glClear(GL_DEPTH_BUFFER_BIT); // Draw objects _suzanne.draw(elapsed, _camera._view, _camera._projection, _pingpong); _dragon.draw(elapsed, _camera._view, _camera._projection, _pingpong); _plane.draw(elapsed, _camera._view, _camera._projection, _pingpong); _skybox.draw(elapsed, _camera._view, _camera._projection); // Unbind the full scene framebuffer. _sceneFramebuffer.unbind(); // ---------------------- glDisable(GL_DEPTH_TEST); // --- FXAA pass ------- // Bind the post-processing framebuffer. _fxaaFramebuffer.bind(); // Set screen viewport. glViewport(0,0,_fxaaFramebuffer._width, _fxaaFramebuffer._height); // Draw the fullscreen quad _fxaaScreen.draw( 1.0f / _camera._renderSize); _fxaaFramebuffer.unbind(); // ---------------------- // --- Final pass ------- // We now render a full screen quad in the default framebuffer, using sRGB space. glEnable(GL_FRAMEBUFFER_SRGB); // Set screen viewport. glViewport(0,0,_camera._screenSize[0],_camera._screenSize[1]); // Draw the fullscreen quad _finalScreen.draw( 1.0f / _camera._screenSize); glDisable(GL_FRAMEBUFFER_SRGB); // ---------------------- glEnable(GL_DEPTH_TEST); // Update timer _timer = glfwGetTime(); // Update pingpong _pingpong = (_pingpong + 1)%2; } void Renderer::physics(float elapsedTime){ _camera.update(elapsedTime); _light.update(_timer, _camera._view); } void Renderer::clean(){ // Clean objects. _suzanne.clean(); _dragon.clean(); _plane.clean(); _skybox.clean(); _blurScreen.clean(); _fxaaScreen.clean(); _finalScreen.clean(); _lightFramebuffer.clean(); _blurFramebuffer.clean(); _sceneFramebuffer.clean(); _fxaaFramebuffer.clean(); } void Renderer::resize(int width, int height){ //Update the size of the viewport. glViewport(0, 0, width, height); // Update the projection matrix. _camera.screen(width, height); // Resize the framebuffer. _sceneFramebuffer.resize(_camera._renderSize); _fxaaFramebuffer.resize(_camera._renderSize); } void Renderer::keyPressed(int key, int action){ if(action == GLFW_PRESS){ _camera.key(key, true); } else if(action == GLFW_RELEASE) { _camera.key(key, false); } } void Renderer::buttonPressed(int button, int action, double x, double y){ if (button == GLFW_MOUSE_BUTTON_LEFT) { if (action == GLFW_PRESS) { _camera.mouse(MouseMode::Start,x, y); } else if (action == GLFW_RELEASE) { _camera.mouse(MouseMode::End, 0.0, 0.0); } } else { std::cout << "Button: " << button << ", action: " << action << std::endl; } } void Renderer::mousePosition(int x, int y, bool leftPress, bool rightPress){ if (leftPress){ _camera.mouse(MouseMode::Move, float(x), float(y)); } } <|endoftext|>
<commit_before>#include "Resolver.h" #include "Algorithm.h" #include "Exception.h" #include "Iterator.h" #include "Optional.h" #include "Requirement.h" #include "ToString.h" #include <algorithm> #include <cassert> #include <exception> #include <map> #include <set> #include <unordered_set> using namespace Arbiter; namespace { /** * Represents an acyclic dependency graph in which each project appears at most * once. * * Dependency graphs can exist in an incomplete state, but will never be * inconsistent (i.e., include versions that are known to be invalid given the * current graph). */ class DependencyGraph final { public: /** * Attempts to add the given node into the graph, as a dependency of * `dependent` if specified. * * If the given node refers to a project which already exists in the graph, * this method will attempt to intersect the version requirements of both. * * Throws an exception if this addition would make the graph inconsistent. */ void addNode (ArbiterResolvedDependency node, const ArbiterRequirement &initialRequirement, const Optional<ArbiterProjectIdentifier> &dependent) noexcept(false) { assert(initialRequirement.satisfiedBy(node._version)); const NodeKey &key = node._project; const auto it = _nodeMap.find(key); if (it != _nodeMap.end()) { NodeValue &value = it->second; // We need to unify our input with what was already there. if (auto newRequirement = initialRequirement.intersect(value.requirement())) { if (!newRequirement->satisfiedBy(value._version)) { throw Exception::UnsatisfiableConstraints("Cannot satisfy " + toString(*newRequirement) + " with " + toString(value._version)); } value.setRequirement(std::move(newRequirement)); } else { throw Exception::MutuallyExclusiveConstraints(toString(value.requirement()) + " and " + toString(initialRequirement) + " are mutually exclusive"); } } else { _nodeMap.emplace(std::make_pair(key, NodeValue(node._version, initialRequirement))); } if (dependent) { _edges[*dependent].insert(key); } else { _roots.insert(key); } } ArbiterResolvedDependencyGraph resolvedGraph () const { ArbiterResolvedDependencyGraph resolved; if (_nodeMap.empty()) { return resolved; } // Contains edges which still need to be added to the resolved graph. std::unordered_map<NodeKey, std::vector<NodeKey>> remainingEdges; // Contains dependencies without any dependencies themselves. ArbiterResolvedDependencyGraph::DepthSet leaves; for (const auto &pair : _nodeMap) { const NodeKey &key = pair.first; const auto it = _edges.find(key); if (it == _edges.end()) { leaves.emplace(resolveNode(key)); } else { std::vector<NodeKey> dependencies(it->second.begin(), it->second.end()); remainingEdges[key] = dependencies; dependencies.shrink_to_fit(); assert(std::is_sorted(dependencies.begin(), dependencies.end())); resolved._edges.emplace(std::make_pair(key, std::move(dependencies))); } } resolved._depths.emplace_back(std::move(leaves)); while (!remainingEdges.empty()) { ArbiterResolvedDependencyGraph::DepthSet thisDepth; for (auto edgeIt = remainingEdges.begin(); edgeIt != remainingEdges.end(); ) { const NodeKey &dependent = edgeIt->first; auto &dependencies = edgeIt->second; for (auto depIt = dependencies.begin(); depIt != dependencies.end(); ) { const NodeKey &dependency = *depIt; // If this dependency is in the graph already, it can be removed // from the list of remaining edges. if (resolved.contains(resolveNode(dependency))) { depIt = dependencies.erase(depIt); } else { ++depIt; } } // If all dependencies are now in the graph, we can add this node to // the current depth we're building. if (dependencies.empty()) { thisDepth.emplace(resolveNode(dependent)); edgeIt = remainingEdges.erase(edgeIt); } else { ++edgeIt; } } resolved._depths.emplace_back(std::move(thisDepth)); } assert(resolved.count() == _nodeMap.size()); return resolved; } std::ostream &describe (std::ostream &os) const { os << "Roots:"; for (const NodeKey &key : _roots) { os << "\n\t" << resolveNode(key); } os << "\n\nEdges"; for (const auto &pair : _edges) { const NodeKey &key = pair.first; os << "\n\t" << key << " ->"; for (const NodeKey &dependency : pair.second) { os << "\n\t\t" << resolveNode(dependency); } } return os; } private: using NodeKey = ArbiterProjectIdentifier; struct NodeValue final { public: const ArbiterSelectedVersion _version; NodeValue (ArbiterSelectedVersion version, const ArbiterRequirement &requirement) : _version(std::move(version)) { setRequirement(requirement); } const ArbiterRequirement &requirement () const { return *_requirement; } void setRequirement (const ArbiterRequirement &requirement) { setRequirement(requirement.cloneRequirement()); } void setRequirement (std::unique_ptr<ArbiterRequirement> requirement) { assert(requirement->satisfiedBy(_version)); _requirement = std::move(requirement); } private: std::shared_ptr<ArbiterRequirement> _requirement; }; static ArbiterResolvedDependency resolveNode (const NodeKey &key, const NodeValue &value) { return ArbiterResolvedDependency(key, value._version); } ArbiterResolvedDependency resolveNode (const NodeKey &key) const { return resolveNode(key, _nodeMap.at(key)); } // TODO: Should these be unordered, with ordering instead applied in // resolvedGraph? std::set<NodeKey> _roots; std::unordered_map<NodeKey, std::set<NodeKey>> _edges; std::unordered_map<NodeKey, NodeValue> _nodeMap; }; DependencyGraph resolveDependencies (ArbiterResolver &resolver, const DependencyGraph &baseGraph, std::set<ArbiterDependency> dependencySet, const std::unordered_map<ArbiterProjectIdentifier, ArbiterProjectIdentifier> &dependentsByProject) noexcept(false) { if (dependencySet.empty()) { return baseGraph; } // This collection is reused when actually building the new dependency graph // below. std::map<ArbiterProjectIdentifier, std::unique_ptr<ArbiterRequirement>> requirementsByProject; for (const ArbiterDependency &dependency : dependencySet) { requirementsByProject[dependency._projectIdentifier] = dependency.requirement().cloneRequirement(); } assert(requirementsByProject.size() == dependencySet.size()); // Free the dependencySet, as it will no longer be used. reset(dependencySet); // This collection needs to exist for as long as the permuted iterators do below. std::map<ArbiterProjectIdentifier, std::vector<ArbiterResolvedDependency>> possibilities; for (const auto &pair : requirementsByProject) { const ArbiterProjectIdentifier &project = pair.first; const ArbiterRequirement &requirement = *pair.second; std::vector<ArbiterSelectedVersion> versions = resolver.availableVersionsSatisfying(project, requirement); if (versions.empty()) { throw Exception::UnsatisfiableConstraints("Cannot satisfy " + toString(requirement) + " from available versions of " + toString(project)); } // Sort the version list with highest precedence first, so we try the newest // possible versions first. std::sort(versions.begin(), versions.end(), std::greater<ArbiterSelectedVersion>()); std::vector<ArbiterResolvedDependency> resolutions; resolutions.reserve(versions.size()); for (ArbiterSelectedVersion &version : versions) { resolutions.emplace_back(project, std::move(version)); } possibilities[project] = std::move(resolutions); } assert(possibilities.size() == requirementsByProject.size()); using Iterator = std::vector<ArbiterResolvedDependency>::const_iterator; std::vector<IteratorRange<Iterator>> ranges; for (const auto &pair : possibilities) { const std::vector<ArbiterResolvedDependency> &dependencies = pair.second; ranges.emplace_back(dependencies.cbegin(), dependencies.cend()); } assert(ranges.size() == possibilities.size()); std::exception_ptr lastException = std::make_exception_ptr(Exception::UnsatisfiableConstraints("No further combinations to attempt")); for (PermutationIterator<Iterator> permuter(std::move(ranges)); permuter; ++permuter) { try { std::vector<ArbiterResolvedDependency> choices = *permuter; DependencyGraph candidate = baseGraph; // Add everything to the graph first, to throw any exceptions that would // occur before we perform the computation- and memory-expensive stuff for // transitive dependencies. for (ArbiterResolvedDependency &dependency : choices) { const ArbiterRequirement &requirement = *requirementsByProject.at(dependency._project); candidate.addNode(dependency, requirement, maybeAt(dependentsByProject, dependency._project)); } // Collect immediate children for the next phase of dependency resolution, // so we can permute their versions as a group (for something // approximating breadth-first search). std::set<ArbiterDependency> collectedTransitives; std::unordered_map<ArbiterProjectIdentifier, ArbiterProjectIdentifier> dependentsByTransitive; for (ArbiterResolvedDependency &dependency : choices) { std::vector<ArbiterDependency> transitives = resolver.fetchDependencies(dependency._project, dependency._version)._dependencies; for (const ArbiterDependency &transitive : transitives) { dependentsByTransitive[transitive._projectIdentifier] = dependency._project; } collectedTransitives.insert(transitives.begin(), transitives.end()); } reset(choices); return resolveDependencies(resolver, candidate, std::move(collectedTransitives), std::move(dependentsByTransitive)); } catch (Arbiter::Exception::Base &ex) { lastException = std::current_exception(); } } std::rethrow_exception(lastException); } class UnversionedRequirementVisitor final : public Requirement::Visitor { public: std::vector<Requirement::Unversioned::Metadata> _allMetadata; void operator() (const ArbiterRequirement &requirement) override { if (const auto *ptr = dynamic_cast<const Requirement::Unversioned *>(&requirement)) { _allMetadata.emplace_back(ptr->_metadata); } } }; } // namespace ArbiterResolver *ArbiterCreateResolver (ArbiterResolverBehaviors behaviors, const ArbiterDependencyList *dependencyList, const void *context) { return new ArbiterResolver(std::move(behaviors), *dependencyList, context); } const void *ArbiterResolverContext (const ArbiterResolver *resolver) { return resolver->_context; } ArbiterResolvedDependencyGraph *ArbiterResolverCreateResolvedDependencyGraph (ArbiterResolver *resolver, char **error) { Optional<ArbiterResolvedDependencyGraph> dependencies; try { dependencies = resolver->resolve(); } catch (const std::exception &ex) { if (error) { *error = copyCString(ex.what()).release(); } return nullptr; } return new ArbiterResolvedDependencyGraph(std::move(*dependencies)); } void ArbiterFreeResolver (ArbiterResolver *resolver) { delete resolver; } ArbiterDependencyList ArbiterResolver::fetchDependencies (const ArbiterProjectIdentifier &project, const ArbiterSelectedVersion &version) noexcept(false) { ArbiterResolvedDependency resolved(project, version); if (auto list = maybeAt(_cachedDependencies, resolved)) { return *list; } char *error = nullptr; std::unique_ptr<ArbiterDependencyList> dependencyList(_behaviors.createDependencyList(this, &project, &version, &error)); if (dependencyList) { assert(!error); _cachedDependencies[resolved] = *dependencyList; return std::move(*dependencyList); } else if (error) { throw Exception::UserError(copyAcquireCString(error)); } else { throw Exception::UserError(); } } ArbiterSelectedVersionList ArbiterResolver::fetchAvailableVersions (const ArbiterProjectIdentifier &project) noexcept(false) { if (auto list = maybeAt(_cachedAvailableVersions, project)) { return *list; } char *error = nullptr; std::unique_ptr<ArbiterSelectedVersionList> versionList(_behaviors.createAvailableVersionsList(this, &project, &error)); if (versionList) { assert(!error); _cachedAvailableVersions[project] = *versionList; return std::move(*versionList); } else if (error) { throw Exception::UserError(copyAcquireCString(error)); } else { throw Exception::UserError(); } } Optional<ArbiterSelectedVersion> ArbiterResolver::fetchSelectedVersionForMetadata (const Arbiter::SharedUserValue<ArbiterSelectedVersion> &metadata) { const auto behavior = _behaviors.createSelectedVersionForMetadata; if (!behavior) { return None(); } std::unique_ptr<ArbiterSelectedVersion> version(behavior(this, metadata.data())); if (version) { return makeOptional(std::move(*version)); } else { return None(); } } ArbiterResolvedDependencyGraph ArbiterResolver::resolve () noexcept(false) { std::set<ArbiterDependency> dependencySet(_dependencyList._dependencies.begin(), _dependencyList._dependencies.end()); DependencyGraph graph = resolveDependencies(*this, DependencyGraph(), std::move(dependencySet), std::unordered_map<ArbiterProjectIdentifier, ArbiterProjectIdentifier>()); return graph.resolvedGraph(); } std::unique_ptr<Arbiter::Base> ArbiterResolver::clone () const { return std::make_unique<ArbiterResolver>(_behaviors, _dependencyList, _context); } std::ostream &ArbiterResolver::describe (std::ostream &os) const { return os << "ArbiterResolver: " << _dependencyList; } bool ArbiterResolver::operator== (const Arbiter::Base &other) const { return this == &other; } std::vector<ArbiterSelectedVersion> ArbiterResolver::availableVersionsSatisfying (const ArbiterProjectIdentifier &project, const ArbiterRequirement &requirement) noexcept(false) { std::vector<ArbiterSelectedVersion> versions; if (_behaviors.createSelectedVersionForMetadata) { UnversionedRequirementVisitor visitor; requirement.visit(visitor); for (const auto &metadata : visitor._allMetadata) { Optional<ArbiterSelectedVersion> version = fetchSelectedVersionForMetadata(metadata); if (version) { versions.emplace_back(std::move(*version)); } } } std::vector<ArbiterSelectedVersion> fetchedVersions = fetchAvailableVersions(project)._versions; versions.insert(versions.end(), std::make_move_iterator(fetchedVersions.begin()), std::make_move_iterator(fetchedVersions.end())); auto removeStart = std::remove_if(versions.begin(), versions.end(), [&requirement](const ArbiterSelectedVersion &version) { return !requirement.satisfiedBy(version); }); versions.erase(removeStart, versions.end()); return versions; } <commit_msg>Use a move iterator when collecting transitive dependencies<commit_after>#include "Resolver.h" #include "Algorithm.h" #include "Exception.h" #include "Iterator.h" #include "Optional.h" #include "Requirement.h" #include "ToString.h" #include <algorithm> #include <cassert> #include <exception> #include <map> #include <set> #include <unordered_set> using namespace Arbiter; namespace { /** * Represents an acyclic dependency graph in which each project appears at most * once. * * Dependency graphs can exist in an incomplete state, but will never be * inconsistent (i.e., include versions that are known to be invalid given the * current graph). */ class DependencyGraph final { public: /** * Attempts to add the given node into the graph, as a dependency of * `dependent` if specified. * * If the given node refers to a project which already exists in the graph, * this method will attempt to intersect the version requirements of both. * * Throws an exception if this addition would make the graph inconsistent. */ void addNode (ArbiterResolvedDependency node, const ArbiterRequirement &initialRequirement, const Optional<ArbiterProjectIdentifier> &dependent) noexcept(false) { assert(initialRequirement.satisfiedBy(node._version)); const NodeKey &key = node._project; const auto it = _nodeMap.find(key); if (it != _nodeMap.end()) { NodeValue &value = it->second; // We need to unify our input with what was already there. if (auto newRequirement = initialRequirement.intersect(value.requirement())) { if (!newRequirement->satisfiedBy(value._version)) { throw Exception::UnsatisfiableConstraints("Cannot satisfy " + toString(*newRequirement) + " with " + toString(value._version)); } value.setRequirement(std::move(newRequirement)); } else { throw Exception::MutuallyExclusiveConstraints(toString(value.requirement()) + " and " + toString(initialRequirement) + " are mutually exclusive"); } } else { _nodeMap.emplace(std::make_pair(key, NodeValue(node._version, initialRequirement))); } if (dependent) { _edges[*dependent].insert(key); } else { _roots.insert(key); } } ArbiterResolvedDependencyGraph resolvedGraph () const { ArbiterResolvedDependencyGraph resolved; if (_nodeMap.empty()) { return resolved; } // Contains edges which still need to be added to the resolved graph. std::unordered_map<NodeKey, std::vector<NodeKey>> remainingEdges; // Contains dependencies without any dependencies themselves. ArbiterResolvedDependencyGraph::DepthSet leaves; for (const auto &pair : _nodeMap) { const NodeKey &key = pair.first; const auto it = _edges.find(key); if (it == _edges.end()) { leaves.emplace(resolveNode(key)); } else { std::vector<NodeKey> dependencies(it->second.begin(), it->second.end()); remainingEdges[key] = dependencies; dependencies.shrink_to_fit(); assert(std::is_sorted(dependencies.begin(), dependencies.end())); resolved._edges.emplace(std::make_pair(key, std::move(dependencies))); } } resolved._depths.emplace_back(std::move(leaves)); while (!remainingEdges.empty()) { ArbiterResolvedDependencyGraph::DepthSet thisDepth; for (auto edgeIt = remainingEdges.begin(); edgeIt != remainingEdges.end(); ) { const NodeKey &dependent = edgeIt->first; auto &dependencies = edgeIt->second; for (auto depIt = dependencies.begin(); depIt != dependencies.end(); ) { const NodeKey &dependency = *depIt; // If this dependency is in the graph already, it can be removed // from the list of remaining edges. if (resolved.contains(resolveNode(dependency))) { depIt = dependencies.erase(depIt); } else { ++depIt; } } // If all dependencies are now in the graph, we can add this node to // the current depth we're building. if (dependencies.empty()) { thisDepth.emplace(resolveNode(dependent)); edgeIt = remainingEdges.erase(edgeIt); } else { ++edgeIt; } } resolved._depths.emplace_back(std::move(thisDepth)); } assert(resolved.count() == _nodeMap.size()); return resolved; } std::ostream &describe (std::ostream &os) const { os << "Roots:"; for (const NodeKey &key : _roots) { os << "\n\t" << resolveNode(key); } os << "\n\nEdges"; for (const auto &pair : _edges) { const NodeKey &key = pair.first; os << "\n\t" << key << " ->"; for (const NodeKey &dependency : pair.second) { os << "\n\t\t" << resolveNode(dependency); } } return os; } private: using NodeKey = ArbiterProjectIdentifier; struct NodeValue final { public: const ArbiterSelectedVersion _version; NodeValue (ArbiterSelectedVersion version, const ArbiterRequirement &requirement) : _version(std::move(version)) { setRequirement(requirement); } const ArbiterRequirement &requirement () const { return *_requirement; } void setRequirement (const ArbiterRequirement &requirement) { setRequirement(requirement.cloneRequirement()); } void setRequirement (std::unique_ptr<ArbiterRequirement> requirement) { assert(requirement->satisfiedBy(_version)); _requirement = std::move(requirement); } private: std::shared_ptr<ArbiterRequirement> _requirement; }; static ArbiterResolvedDependency resolveNode (const NodeKey &key, const NodeValue &value) { return ArbiterResolvedDependency(key, value._version); } ArbiterResolvedDependency resolveNode (const NodeKey &key) const { return resolveNode(key, _nodeMap.at(key)); } // TODO: Should these be unordered, with ordering instead applied in // resolvedGraph? std::set<NodeKey> _roots; std::unordered_map<NodeKey, std::set<NodeKey>> _edges; std::unordered_map<NodeKey, NodeValue> _nodeMap; }; DependencyGraph resolveDependencies (ArbiterResolver &resolver, const DependencyGraph &baseGraph, std::set<ArbiterDependency> dependencySet, const std::unordered_map<ArbiterProjectIdentifier, ArbiterProjectIdentifier> &dependentsByProject) noexcept(false) { if (dependencySet.empty()) { return baseGraph; } // This collection is reused when actually building the new dependency graph // below. std::map<ArbiterProjectIdentifier, std::unique_ptr<ArbiterRequirement>> requirementsByProject; for (const ArbiterDependency &dependency : dependencySet) { requirementsByProject[dependency._projectIdentifier] = dependency.requirement().cloneRequirement(); } assert(requirementsByProject.size() == dependencySet.size()); // Free the dependencySet, as it will no longer be used. reset(dependencySet); // This collection needs to exist for as long as the permuted iterators do below. std::map<ArbiterProjectIdentifier, std::vector<ArbiterResolvedDependency>> possibilities; for (const auto &pair : requirementsByProject) { const ArbiterProjectIdentifier &project = pair.first; const ArbiterRequirement &requirement = *pair.second; std::vector<ArbiterSelectedVersion> versions = resolver.availableVersionsSatisfying(project, requirement); if (versions.empty()) { throw Exception::UnsatisfiableConstraints("Cannot satisfy " + toString(requirement) + " from available versions of " + toString(project)); } // Sort the version list with highest precedence first, so we try the newest // possible versions first. std::sort(versions.begin(), versions.end(), std::greater<ArbiterSelectedVersion>()); std::vector<ArbiterResolvedDependency> resolutions; resolutions.reserve(versions.size()); for (ArbiterSelectedVersion &version : versions) { resolutions.emplace_back(project, std::move(version)); } possibilities[project] = std::move(resolutions); } assert(possibilities.size() == requirementsByProject.size()); using Iterator = std::vector<ArbiterResolvedDependency>::const_iterator; std::vector<IteratorRange<Iterator>> ranges; for (const auto &pair : possibilities) { const std::vector<ArbiterResolvedDependency> &dependencies = pair.second; ranges.emplace_back(dependencies.cbegin(), dependencies.cend()); } assert(ranges.size() == possibilities.size()); std::exception_ptr lastException = std::make_exception_ptr(Exception::UnsatisfiableConstraints("No further combinations to attempt")); for (PermutationIterator<Iterator> permuter(std::move(ranges)); permuter; ++permuter) { try { std::vector<ArbiterResolvedDependency> choices = *permuter; DependencyGraph candidate = baseGraph; // Add everything to the graph first, to throw any exceptions that would // occur before we perform the computation- and memory-expensive stuff for // transitive dependencies. for (ArbiterResolvedDependency &dependency : choices) { const ArbiterRequirement &requirement = *requirementsByProject.at(dependency._project); candidate.addNode(dependency, requirement, maybeAt(dependentsByProject, dependency._project)); } // Collect immediate children for the next phase of dependency resolution, // so we can permute their versions as a group (for something // approximating breadth-first search). std::set<ArbiterDependency> collectedTransitives; std::unordered_map<ArbiterProjectIdentifier, ArbiterProjectIdentifier> dependentsByTransitive; for (ArbiterResolvedDependency &dependency : choices) { std::vector<ArbiterDependency> transitives = resolver.fetchDependencies(dependency._project, dependency._version)._dependencies; for (const ArbiterDependency &transitive : transitives) { dependentsByTransitive[transitive._projectIdentifier] = dependency._project; } collectedTransitives.insert(std::make_move_iterator(transitives.begin()), std::make_move_iterator(transitives.end())); } reset(choices); return resolveDependencies(resolver, candidate, std::move(collectedTransitives), std::move(dependentsByTransitive)); } catch (Arbiter::Exception::Base &ex) { lastException = std::current_exception(); } } std::rethrow_exception(lastException); } class UnversionedRequirementVisitor final : public Requirement::Visitor { public: std::vector<Requirement::Unversioned::Metadata> _allMetadata; void operator() (const ArbiterRequirement &requirement) override { if (const auto *ptr = dynamic_cast<const Requirement::Unversioned *>(&requirement)) { _allMetadata.emplace_back(ptr->_metadata); } } }; } // namespace ArbiterResolver *ArbiterCreateResolver (ArbiterResolverBehaviors behaviors, const ArbiterDependencyList *dependencyList, const void *context) { return new ArbiterResolver(std::move(behaviors), *dependencyList, context); } const void *ArbiterResolverContext (const ArbiterResolver *resolver) { return resolver->_context; } ArbiterResolvedDependencyGraph *ArbiterResolverCreateResolvedDependencyGraph (ArbiterResolver *resolver, char **error) { Optional<ArbiterResolvedDependencyGraph> dependencies; try { dependencies = resolver->resolve(); } catch (const std::exception &ex) { if (error) { *error = copyCString(ex.what()).release(); } return nullptr; } return new ArbiterResolvedDependencyGraph(std::move(*dependencies)); } void ArbiterFreeResolver (ArbiterResolver *resolver) { delete resolver; } ArbiterDependencyList ArbiterResolver::fetchDependencies (const ArbiterProjectIdentifier &project, const ArbiterSelectedVersion &version) noexcept(false) { ArbiterResolvedDependency resolved(project, version); if (auto list = maybeAt(_cachedDependencies, resolved)) { return *list; } char *error = nullptr; std::unique_ptr<ArbiterDependencyList> dependencyList(_behaviors.createDependencyList(this, &project, &version, &error)); if (dependencyList) { assert(!error); _cachedDependencies[resolved] = *dependencyList; return std::move(*dependencyList); } else if (error) { throw Exception::UserError(copyAcquireCString(error)); } else { throw Exception::UserError(); } } ArbiterSelectedVersionList ArbiterResolver::fetchAvailableVersions (const ArbiterProjectIdentifier &project) noexcept(false) { if (auto list = maybeAt(_cachedAvailableVersions, project)) { return *list; } char *error = nullptr; std::unique_ptr<ArbiterSelectedVersionList> versionList(_behaviors.createAvailableVersionsList(this, &project, &error)); if (versionList) { assert(!error); _cachedAvailableVersions[project] = *versionList; return std::move(*versionList); } else if (error) { throw Exception::UserError(copyAcquireCString(error)); } else { throw Exception::UserError(); } } Optional<ArbiterSelectedVersion> ArbiterResolver::fetchSelectedVersionForMetadata (const Arbiter::SharedUserValue<ArbiterSelectedVersion> &metadata) { const auto behavior = _behaviors.createSelectedVersionForMetadata; if (!behavior) { return None(); } std::unique_ptr<ArbiterSelectedVersion> version(behavior(this, metadata.data())); if (version) { return makeOptional(std::move(*version)); } else { return None(); } } ArbiterResolvedDependencyGraph ArbiterResolver::resolve () noexcept(false) { std::set<ArbiterDependency> dependencySet(_dependencyList._dependencies.begin(), _dependencyList._dependencies.end()); DependencyGraph graph = resolveDependencies(*this, DependencyGraph(), std::move(dependencySet), std::unordered_map<ArbiterProjectIdentifier, ArbiterProjectIdentifier>()); return graph.resolvedGraph(); } std::unique_ptr<Arbiter::Base> ArbiterResolver::clone () const { return std::make_unique<ArbiterResolver>(_behaviors, _dependencyList, _context); } std::ostream &ArbiterResolver::describe (std::ostream &os) const { return os << "ArbiterResolver: " << _dependencyList; } bool ArbiterResolver::operator== (const Arbiter::Base &other) const { return this == &other; } std::vector<ArbiterSelectedVersion> ArbiterResolver::availableVersionsSatisfying (const ArbiterProjectIdentifier &project, const ArbiterRequirement &requirement) noexcept(false) { std::vector<ArbiterSelectedVersion> versions; if (_behaviors.createSelectedVersionForMetadata) { UnversionedRequirementVisitor visitor; requirement.visit(visitor); for (const auto &metadata : visitor._allMetadata) { Optional<ArbiterSelectedVersion> version = fetchSelectedVersionForMetadata(metadata); if (version) { versions.emplace_back(std::move(*version)); } } } std::vector<ArbiterSelectedVersion> fetchedVersions = fetchAvailableVersions(project)._versions; versions.insert(versions.end(), std::make_move_iterator(fetchedVersions.begin()), std::make_move_iterator(fetchedVersions.end())); auto removeStart = std::remove_if(versions.begin(), versions.end(), [&requirement](const ArbiterSelectedVersion &version) { return !requirement.satisfiedBy(version); }); versions.erase(removeStart, versions.end()); return versions; } <|endoftext|>
<commit_before>/* * Copyright (C) 2012 Kolibre * * This file is part of kolibre-clientcore. * * Kolibre-clientcore 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. * * Kolibre-clientcore 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 kolibre-clientcore. If not, see <http://www.gnu.org/licenses/>. */ #include "RootNode.h" #include "DaisyOnlineNode.h" #include "FileSystemNode.h" #include "Defines.h" #include "config.h" #include "CommandQueue2/CommandQueue.h" #include "Commands/InternalCommands.h" #include "MediaSourceManager.h" #include "Settings/Settings.h" #include "Utils.h" #include <Narrator.h> #include <NaviEngine.h> #include <log4cxx/logger.h> // create logger which will become a child to logger kolibre.clientcore log4cxx::LoggerPtr rootNodeLog(log4cxx::Logger::getLogger("kolibre.clientcore.rootnode")); using namespace naviengine; RootNode::RootNode(const std::string useragent) { LOG4CXX_TRACE(rootNodeLog, "Constructor"); userAgent_ = useragent; name_ = "Root"; openFirstChild_ = true; } RootNode::~RootNode() { LOG4CXX_TRACE(rootNodeLog, "Destructor"); } // NaviEngine functions bool RootNode::next(NaviEngine& navi) { bool ret = MenuNode::next(navi); currentChild_ = navi.getCurrentChoice(); announceSelection(); return ret; } bool RootNode::prev(NaviEngine& navi) { bool ret = MenuNode::prev(navi); currentChild_ = navi.getCurrentChoice(); announceSelection(); return ret; } bool RootNode::menu(NaviEngine& navi) { return navi.openMenu(navi.buildContextMenu()); } bool RootNode::up(NaviEngine& navi) { bool ret = MenuNode::up(navi); return ret; } bool RootNode::onOpen(NaviEngine& navi) { navi.setCurrentChoice(NULL); clearNodes(); navilist_.items.clear(); // Create sources defined in MediaSourceManager LOG4CXX_INFO(rootNodeLog, "Creating children for root"); int daisyOnlineServices = MediaSourceManager::Instance()->getDaisyOnlineServices(); for (int i = 0; i < daisyOnlineServices; i++) { std::string name = MediaSourceManager::Instance()->getDOSname(i); std::string url = MediaSourceManager::Instance()->getDOSurl(i); std::string username = MediaSourceManager::Instance()->getDOSusername(i); std::string password = MediaSourceManager::Instance()->getDOSpassword(i); // Create a DaisyOnlineNode DaisyOnlineNode* daisyOnlineNode = new DaisyOnlineNode(name, url, username, password, userAgent_, openFirstChild_); if (daisyOnlineNode->good()) { // Split userAgent into model/version std::string::size_type slashpos = userAgent_.find('/'); if (slashpos != std::string::npos) { std::string model = userAgent_.substr(0, slashpos); std::string version = userAgent_.substr(slashpos + 1); if (not model.empty() && not version.empty()) { daisyOnlineNode->setModel(model); daisyOnlineNode->setVersion(version); } } daisyOnlineNode->setLanguage(Settings::Instance()->read<std::string>("language", "sv")); LOG4CXX_INFO(rootNodeLog, "Adding DaisyOnlineService '" << name << "'"); addNode(daisyOnlineNode); // create a NaviListItem and store it in list for the NaviList signal NaviListItem item(daisyOnlineNode->uri_, name); navilist_.items.push_back(item); } else { LOG4CXX_ERROR(rootNodeLog, "DaisyOnlineNode failed to initialize"); } } int fileSystemPaths = MediaSourceManager::Instance()->getFileSystemPaths(); for (int i = 0; i < fileSystemPaths; i++) { std::string name = MediaSourceManager::Instance()->getFSPname(i); std::string path = MediaSourceManager::Instance()->getFSPpath(i); if (Utils::isDir(path)) { LOG4CXX_INFO(rootNodeLog, "Adding FileSystemNode '" << name << "'"); FileSystemNode *fileSystemNode = new FileSystemNode(name, path, openFirstChild_); addNode(fileSystemNode); // create a NaviListItem and store it in list for the NaviList signal NaviListItem item(fileSystemNode->uri_, name); navilist_.items.push_back(item); } } if (navi.getCurrentChoice() == NULL && numberOfChildren() > 0) { navi.setCurrentChoice(firstChild()); currentChild_ = firstChild(); } currentChild_ = navi.getCurrentChoice(); announce(); bool autoPlay = Settings::Instance()->read<bool>("autoplay", true); if (autoPlay && openFirstChild_) { narratorDoneConnection = Narrator::Instance()->connectAudioFinished(boost::bind(&RootNode::onNarratorDone, this)); Narrator::Instance()->setPushCommandFinished(true); } return true; } bool RootNode::process(NaviEngine& navi, int command, void* data) { return false; } bool RootNode::narrateInfo() { const bool isSelfNarrated = true; Narrator::Instance()->play(_N("choose option using left and right arrows, open using play button")); Narrator::Instance()->playLongpause(); announceSelection(); return isSelfNarrated; } bool RootNode::onNarrate() { const bool isSelfNarrated = true; return isSelfNarrated; } bool RootNode::onRender() { const bool isSelfRendered = true; return isSelfRendered; } bool RootNode::abort() { if (openFirstChild_) { openFirstChild_ = false; Narrator::Instance()->setPushCommandFinished(false); narratorDoneConnection.disconnect(); // abort auto open in children if (numberOfChildren() >= 1) { AnyNode* current = firstChild(); for (int i=0; i<numberOfChildren(); i++) { current->abort(); current = current->next_; } } } return true; } void RootNode::onNarratorDone() { bool autoPlay = Settings::Instance()->read<bool>("autoplay", true); if (autoPlay && openFirstChild_ && numberOfChildren() >= 1) { openFirstChild_ = false; Narrator::Instance()->setPushCommandFinished(false); narratorDoneConnection.disconnect(); LOG4CXX_INFO(rootNodeLog, "auto open first child"); cq2::Command<INTERNAL_COMMAND> c(COMMAND_DOWN); c(); } } void RootNode::announce() { cq2::Command<NaviList> naviList(navilist_); naviList(); int numItems = numberOfChildren(); if (numItems == 0) { Narrator::Instance()->play(_N("home contains no sources")); } else if (numItems == 1) { Narrator::Instance()->setParameter("1", numItems); Narrator::Instance()->play(_N("home contains {1} source")); } else if (numItems > 1) { Narrator::Instance()->setParameter("2", numItems); Narrator::Instance()->play(_N("home contains {2} sources")); } Narrator::Instance()->playLongpause(); announceSelection(); } void RootNode::announceSelection() { int currentChoice = 0; AnyNode* current = currentChild_; if ((firstChild() != NULL) && (current != NULL)) { while (firstChild() != current) { currentChoice++; current = current->prev_; } Narrator::Instance()->setParameter("1", currentChoice + 1); Narrator::Instance()->play(_N("source no. {1}")); currentChild_->narrateName(); NaviListItem item = navilist_.items[currentChoice]; cq2::Command<NaviListItem> naviItem(item); naviItem(); } } <commit_msg>Split userAgent string only once<commit_after>/* * Copyright (C) 2012 Kolibre * * This file is part of kolibre-clientcore. * * Kolibre-clientcore 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. * * Kolibre-clientcore 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 kolibre-clientcore. If not, see <http://www.gnu.org/licenses/>. */ #include "RootNode.h" #include "DaisyOnlineNode.h" #include "FileSystemNode.h" #include "Defines.h" #include "config.h" #include "CommandQueue2/CommandQueue.h" #include "Commands/InternalCommands.h" #include "MediaSourceManager.h" #include "Settings/Settings.h" #include "Utils.h" #include <Narrator.h> #include <NaviEngine.h> #include <log4cxx/logger.h> // create logger which will become a child to logger kolibre.clientcore log4cxx::LoggerPtr rootNodeLog(log4cxx::Logger::getLogger("kolibre.clientcore.rootnode")); using namespace naviengine; RootNode::RootNode(const std::string useragent) { LOG4CXX_TRACE(rootNodeLog, "Constructor"); userAgent_ = useragent; name_ = "Root"; openFirstChild_ = true; } RootNode::~RootNode() { LOG4CXX_TRACE(rootNodeLog, "Destructor"); } // NaviEngine functions bool RootNode::next(NaviEngine& navi) { bool ret = MenuNode::next(navi); currentChild_ = navi.getCurrentChoice(); announceSelection(); return ret; } bool RootNode::prev(NaviEngine& navi) { bool ret = MenuNode::prev(navi); currentChild_ = navi.getCurrentChoice(); announceSelection(); return ret; } bool RootNode::menu(NaviEngine& navi) { return navi.openMenu(navi.buildContextMenu()); } bool RootNode::up(NaviEngine& navi) { bool ret = MenuNode::up(navi); return ret; } bool RootNode::onOpen(NaviEngine& navi) { navi.setCurrentChoice(NULL); clearNodes(); navilist_.items.clear(); // Create sources defined in MediaSourceManager LOG4CXX_INFO(rootNodeLog, "Creating children for root"); // Split userAgent into model/version std::string model = ""; std::string version = ""; std::string::size_type slashpos = userAgent_.find('/'); if (slashpos != std::string::npos) { model = userAgent_.substr(0, slashpos); version = userAgent_.substr(slashpos + 1); } int daisyOnlineServices = MediaSourceManager::Instance()->getDaisyOnlineServices(); for (int i = 0; i < daisyOnlineServices; i++) { std::string name = MediaSourceManager::Instance()->getDOSname(i); std::string url = MediaSourceManager::Instance()->getDOSurl(i); std::string username = MediaSourceManager::Instance()->getDOSusername(i); std::string password = MediaSourceManager::Instance()->getDOSpassword(i); // Create a DaisyOnlineNode DaisyOnlineNode* daisyOnlineNode = new DaisyOnlineNode(name, url, username, password, userAgent_, openFirstChild_); if (daisyOnlineNode->good()) { if (not model.empty() && not version.empty()) { daisyOnlineNode->setModel(model); daisyOnlineNode->setVersion(version); } daisyOnlineNode->setLanguage(Settings::Instance()->read<std::string>("language", "sv")); LOG4CXX_INFO(rootNodeLog, "Adding DaisyOnlineService '" << name << "'"); addNode(daisyOnlineNode); // create a NaviListItem and store it in list for the NaviList signal NaviListItem item(daisyOnlineNode->uri_, name); navilist_.items.push_back(item); } else { LOG4CXX_ERROR(rootNodeLog, "DaisyOnlineNode failed to initialize"); } } int fileSystemPaths = MediaSourceManager::Instance()->getFileSystemPaths(); for (int i = 0; i < fileSystemPaths; i++) { std::string name = MediaSourceManager::Instance()->getFSPname(i); std::string path = MediaSourceManager::Instance()->getFSPpath(i); if (Utils::isDir(path)) { LOG4CXX_INFO(rootNodeLog, "Adding FileSystemNode '" << name << "'"); FileSystemNode *fileSystemNode = new FileSystemNode(name, path, openFirstChild_); addNode(fileSystemNode); // create a NaviListItem and store it in list for the NaviList signal NaviListItem item(fileSystemNode->uri_, name); navilist_.items.push_back(item); } } if (navi.getCurrentChoice() == NULL && numberOfChildren() > 0) { navi.setCurrentChoice(firstChild()); currentChild_ = firstChild(); } currentChild_ = navi.getCurrentChoice(); announce(); bool autoPlay = Settings::Instance()->read<bool>("autoplay", true); if (autoPlay && openFirstChild_) { narratorDoneConnection = Narrator::Instance()->connectAudioFinished(boost::bind(&RootNode::onNarratorDone, this)); Narrator::Instance()->setPushCommandFinished(true); } return true; } bool RootNode::process(NaviEngine& navi, int command, void* data) { return false; } bool RootNode::narrateInfo() { const bool isSelfNarrated = true; Narrator::Instance()->play(_N("choose option using left and right arrows, open using play button")); Narrator::Instance()->playLongpause(); announceSelection(); return isSelfNarrated; } bool RootNode::onNarrate() { const bool isSelfNarrated = true; return isSelfNarrated; } bool RootNode::onRender() { const bool isSelfRendered = true; return isSelfRendered; } bool RootNode::abort() { if (openFirstChild_) { openFirstChild_ = false; Narrator::Instance()->setPushCommandFinished(false); narratorDoneConnection.disconnect(); // abort auto open in children if (numberOfChildren() >= 1) { AnyNode* current = firstChild(); for (int i=0; i<numberOfChildren(); i++) { current->abort(); current = current->next_; } } } return true; } void RootNode::onNarratorDone() { bool autoPlay = Settings::Instance()->read<bool>("autoplay", true); if (autoPlay && openFirstChild_ && numberOfChildren() >= 1) { openFirstChild_ = false; Narrator::Instance()->setPushCommandFinished(false); narratorDoneConnection.disconnect(); LOG4CXX_INFO(rootNodeLog, "auto open first child"); cq2::Command<INTERNAL_COMMAND> c(COMMAND_DOWN); c(); } } void RootNode::announce() { cq2::Command<NaviList> naviList(navilist_); naviList(); int numItems = numberOfChildren(); if (numItems == 0) { Narrator::Instance()->play(_N("home contains no sources")); } else if (numItems == 1) { Narrator::Instance()->setParameter("1", numItems); Narrator::Instance()->play(_N("home contains {1} source")); } else if (numItems > 1) { Narrator::Instance()->setParameter("2", numItems); Narrator::Instance()->play(_N("home contains {2} sources")); } Narrator::Instance()->playLongpause(); announceSelection(); } void RootNode::announceSelection() { int currentChoice = 0; AnyNode* current = currentChild_; if ((firstChild() != NULL) && (current != NULL)) { while (firstChild() != current) { currentChoice++; current = current->prev_; } Narrator::Instance()->setParameter("1", currentChoice + 1); Narrator::Instance()->play(_N("source no. {1}")); currentChild_->narrateName(); NaviListItem item = navilist_.items[currentChoice]; cq2::Command<NaviListItem> naviItem(item); naviItem(); } } <|endoftext|>
<commit_before>#ifndef CV_ADAPTERS_ROWRANGE_HPP #define CV_ADAPTERS_ROWRANGE_HPP #include <iterator> #include <opencv2/core/core.hpp> template <typename T> class RowRangeConstIterator : public std::iterator<std::forward_iterator_tag, T> { public: RowRangeConstIterator() : data() , row() , position() {} RowRangeConstIterator(const cv::Mat_<T>& m, int index) : data(m) , position(index) { CV_DbgAssert(position >= 0 && position <= data.rows + 1); if (index != data.rows + 1) { row = m.row(index); } } // Dereference const cv::Mat_<T>& operator*() const { return row; } const cv::Mat_<T>* operator->() const { return &row; } // Logical comparison bool operator==(const RowRangeConstIterator& that) const { return this->position == that.position; } bool operator!=(const RowRangeConstIterator& that) const { return !(*this == that); } bool operator<(const RowRangeConstIterator& that) const { return this->position < that.position; } bool operator>(const RowRangeConstIterator& that) const { return this->position > that.position; } bool operator<=(const RowRangeConstIterator& that) const { return !(*this > that); } bool operator>=(const RowRangeConstIterator& that) const { return !(*this < that); } // Increment RowRangeConstIterator& operator++() { ++position; return *this; } RowRangeConstIterator operator++(int) const { RowRangeConstIterator tmp(*this); ++(*this); return tmp; } private: cv::Mat_<T> data; mutable cv::Mat_<T> row; int position; }; template <typename T> class RowRangeIterator : public RowRangeConstIterator<T> { public: RowRangeIterator() : data() , row() , position() {} RowRangeIterator(const cv::Mat_<T>& m, int index) : data(m) , position(index) { CV_DbgAssert(position >= 0 && position <= data.rows + 1); if (index != data.rows + 1) { row = m.row(index); } } // Dereference cv::Mat_<T>& operator*() const { return row; } cv::Mat_<T>* operator->() const { return &row; } private: cv::Mat_<T> data; mutable cv::Mat_<T> row; int position; }; template <typename T> class RowRange { public: typedef RowRangeConstIterator<T> const_iterator; typedef RowRangeIterator<T> iterator; typedef std::reverse_iterator<const_iterator> const_reverse_iterator; typedef std::reverse_iterator<iterator> reverse_iterator; RowRange(cv::Mat m) : data(m) { CV_Assert(m.type() == cv::DataType<T>::type); } RowRange(cv::Mat_<T> m) : data(m) {} const_iterator begin() const { return const_iterator(data, 0); } iterator begin() { return iterator(data, 0); } const_iterator end() const { return const_iterator(data, data.rows + 1); } iterator end() { return iterator(data, data.rows + 1); } const_iterator cbegin() const { return begin(); } const_iterator cend() const { return end(); } private: cv::Mat_<T> data; }; template <typename T> RowRange<T> make_RowRange(cv::Mat_<T> m) { return RowRange<T>(m); } #endif /* CV_ADAPTERS_ROWRANGE_HPP */ <commit_msg>Fixing incorrect equality comparisons.<commit_after>#ifndef CV_ADAPTERS_ROWRANGE_HPP #define CV_ADAPTERS_ROWRANGE_HPP #include <iterator> #include <opencv2/core/core.hpp> template <typename T> class RowRangeConstIterator : public std::iterator<std::forward_iterator_tag, T> { public: RowRangeConstIterator() : data() , row() , position() {} RowRangeConstIterator(const cv::Mat_<T>& m, int index) : data(m) , position(index) { CV_DbgAssert(position >= 0 && position <= data.rows + 1); if (index != data.rows + 1) { row = m.row(index); } } // Dereference const cv::Mat_<T>& operator*() const { return row; } const cv::Mat_<T>* operator->() const { return &row; } // Logical comparison bool operator==(const RowRangeConstIterator& that) const { return this->position == that.position; } bool operator!=(const RowRangeConstIterator& that) const { return !(*this == that); } bool operator<(const RowRangeConstIterator& that) const { return this->position < that.position; } bool operator>(const RowRangeConstIterator& that) const { return this->position > that.position; } bool operator<=(const RowRangeConstIterator& that) const { return !(*this > that); } bool operator>=(const RowRangeConstIterator& that) const { return !(*this < that); } // Increment RowRangeConstIterator& operator++() { ++position; return *this; } RowRangeConstIterator operator++(int) const { RowRangeConstIterator tmp(*this); ++(*this); return tmp; } protected: cv::Mat_<T> data; mutable cv::Mat_<T> row; int position; }; template <typename T> class RowRangeIterator : public RowRangeConstIterator<T> { public: RowRangeIterator() : RowRangeConstIterator<T>() {} RowRangeIterator(const cv::Mat_<T>& m, int index) : RowRangeConstIterator<T>(m, index) {} // Dereference cv::Mat_<T>& operator*() const { return RowRangeConstIterator<T>::row; } cv::Mat_<T>* operator->() const { return &RowRangeConstIterator<T>::row; } }; template <typename T> class RowRange { public: typedef RowRangeConstIterator<T> const_iterator; typedef RowRangeIterator<T> iterator; typedef std::reverse_iterator<const_iterator> const_reverse_iterator; typedef std::reverse_iterator<iterator> reverse_iterator; RowRange(cv::Mat m) : data(m) { CV_Assert(m.type() == cv::DataType<T>::type); } RowRange(cv::Mat_<T> m) : data(m) {} const_iterator begin() const { return const_iterator(data, 0); } iterator begin() { return iterator(data, 0); } const_iterator end() const { return const_iterator(data, data.rows + 1); } iterator end() { return iterator(data, data.rows + 1); } const_iterator cbegin() const { return begin(); } const_iterator cend() const { return end(); } private: cv::Mat_<T> data; }; template <typename T> RowRange<T> make_RowRange(cv::Mat_<T> m) { return RowRange<T>(m); } #endif /* CV_ADAPTERS_ROWRANGE_HPP */ <|endoftext|>
<commit_before>// Workspace.hh for Fluxbox // Copyright (c) 2002 - 2006 Henrik Kinnunen (fluxgen at fluxbox dot org) // // Workspace.hh for Blackbox - an X11 Window manager // Copyright (c) 1997 - 2000 Brad Hughes ([email protected]) // // 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 WORKSPACE_HH #define WORKSPACE_HH #include "FbMenu.hh" #include "FbTk/MultLayers.hh" #include "FbTk/Observer.hh" #include "FbTk/NotCopyable.hh" #include <string> #include <vector> #include <list> class BScreen; class FluxboxWindow; class WinClient; /** Handles a single workspace */ class Workspace:private FbTk::NotCopyable, private FbTk::Observer { public: typedef std::vector<FluxboxWindow *> Windows; Workspace(BScreen &screen, FbTk::MultLayers &layermanager, const std::string &name, unsigned int workspaceid = 0); ~Workspace(); void setLastFocusedWindow(FluxboxWindow *w); /// Set workspace name void setName(const std::string &name); void showAll(); void hideAll(bool interrupt_moving); void removeAll(); void reconfigure(); void shutdown(); void addWindow(FluxboxWindow &win, bool place = false); int removeWindow(FluxboxWindow *win, bool still_alive); void updateClientmenu(); BScreen &screen() { return m_screen; } const BScreen &screen() const { return m_screen; } FluxboxWindow *lastFocusedWindow() { return m_lastfocus; } const FluxboxWindow *lastFocusedWindow() const { return m_lastfocus; } inline FbTk::Menu &menu() { return m_clientmenu; } inline const FbTk::Menu &menu() const { return m_clientmenu; } /// name of this workspace inline const std::string &name() const { return m_name; } /** @return the number of this workspace, note: obsolete, should be in BScreen */ inline unsigned int workspaceID() const { return m_id; } const Windows &windowList() const { return m_windowlist; } Windows &windowList() { return m_windowlist; } int numberOfWindows() const; bool checkGrouping(FluxboxWindow &win); static bool loadGroups(const std::string &filename); private: void update(FbTk::Subject *subj); void placeWindow(FluxboxWindow &win); BScreen &m_screen; FluxboxWindow *m_lastfocus; FbMenu m_clientmenu; typedef std::vector<std::string> Group; typedef std::vector<Group> GroupList; static GroupList m_groups; ///< handle auto groupings FbTk::MultLayers &m_layermanager; Windows m_windowlist; std::string m_name; ///< name of this workspace unsigned int m_id; ///< id, obsolete, this should be in BScreen int *m_cascade_x; ///< need a cascade for each head (Xinerama) int *m_cascade_y; ///< need a cascade for each head (Xinerama) }; #endif // WORKSPACE_HH <commit_msg>moved placement strategies to different PlacementStrategy classes<commit_after>// Workspace.hh for Fluxbox // Copyright (c) 2002 - 2006 Henrik Kinnunen (fluxgen at fluxbox dot org) // // Workspace.hh for Blackbox - an X11 Window manager // Copyright (c) 1997 - 2000 Brad Hughes ([email protected]) // // 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 WORKSPACE_HH #define WORKSPACE_HH #include "FbMenu.hh" #include "FbTk/MultLayers.hh" #include "FbTk/Observer.hh" #include "FbTk/NotCopyable.hh" #include <string> #include <vector> #include <list> class BScreen; class FluxboxWindow; class WinClient; /** Handles a single workspace */ class Workspace:private FbTk::NotCopyable, private FbTk::Observer { public: typedef std::vector<FluxboxWindow *> Windows; Workspace(BScreen &screen, FbTk::MultLayers &layermanager, const std::string &name, unsigned int workspaceid = 0); ~Workspace(); void setLastFocusedWindow(FluxboxWindow *w); /// Set workspace name void setName(const std::string &name); void showAll(); void hideAll(bool interrupt_moving); void removeAll(); void reconfigure(); void shutdown(); void addWindow(FluxboxWindow &win, bool place = false); int removeWindow(FluxboxWindow *win, bool still_alive); void updateClientmenu(); BScreen &screen() { return m_screen; } const BScreen &screen() const { return m_screen; } FluxboxWindow *lastFocusedWindow() { return m_lastfocus; } const FluxboxWindow *lastFocusedWindow() const { return m_lastfocus; } inline FbTk::Menu &menu() { return m_clientmenu; } inline const FbTk::Menu &menu() const { return m_clientmenu; } /// name of this workspace inline const std::string &name() const { return m_name; } /** @return the number of this workspace, note: obsolete, should be in BScreen */ inline unsigned int workspaceID() const { return m_id; } const Windows &windowList() const { return m_windowlist; } Windows &windowList() { return m_windowlist; } int numberOfWindows() const; bool checkGrouping(FluxboxWindow &win); static bool loadGroups(const std::string &filename); private: void update(FbTk::Subject *subj); void placeWindow(FluxboxWindow &win); BScreen &m_screen; FluxboxWindow *m_lastfocus; FbMenu m_clientmenu; typedef std::vector<std::string> Group; typedef std::vector<Group> GroupList; static GroupList m_groups; ///< handle auto groupings FbTk::MultLayers &m_layermanager; Windows m_windowlist; std::string m_name; ///< name of this workspace unsigned int m_id; ///< id, obsolete, this should be in BScreen }; #endif // WORKSPACE_HH <|endoftext|>
<commit_before>#include <QApplication> #include <QVTKApplication.h> #include "ddMainWindow.h" #include "ddPythonManager.h" int main(int argc, char **argv) { QVTKApplication app(argc, argv); ddPythonManager* pythonManager = new ddPythonManager; ddMainWindow window; window.setPythonManager(pythonManager); window.resize(1800, 1000); window.show(); return app.exec(); } <commit_msg>add switch for using app to support 3Dconnexion devices<commit_after>#include <QApplication> #include "ddMainWindow.h" #include "ddPythonManager.h" #define USE_TDX 0 #if USE_TDX #include <QVTKApplication.h> #endif int main(int argc, char **argv) { #if USE_TDX QVTKApplication app(argc, argv); #else QApplication app(argc, argv); #endif ddPythonManager* pythonManager = new ddPythonManager; ddMainWindow window; window.setPythonManager(pythonManager); window.resize(1800, 1000); window.show(); return app.exec(); } <|endoftext|>
<commit_before>// Report data as I2C slave on address 0x70. #include "LPC8xx.h" #include "lpc_types.h" #include "romapi_8xx.h" #include "serial.h" #include <string.h> #define FIXED_CLOCK_RATE_HZ 10000000 #define FIXED_UART_BAUD_RATE 115200 uint32_t i2cBuffer[24]; // data area used by ROM-based I2C driver I2C_HANDLE_T* ih; // opaque handle used by ROM-based I2C driver I2C_PARAM_T i2cParam; // input parameters for pending I2C request I2C_RESULT_T i2cResult; // return values for pending I2C request uint8_t i2cRecvBuf[2]; // receive buffer: address + register number uint8_t i2cSendBuf[32]; // send buffer void timersInit() { LPC_SYSCON->SYSAHBCLKCTRL |= (1<<10); // enable MRT clock LPC_SYSCON->PRESETCTRL &= ~(1<<7); // reset MRT LPC_SYSCON->PRESETCTRL |= (1<<7); LPC_MRT->Channel[2].CTRL = (0x01 << 1); //MRT2 one-shot mode } void delayMs(int milliseconds) { LPC_MRT->Channel[2].INTVAL = (((FIXED_CLOCK_RATE_HZ / 250L) * milliseconds) >> 2) - 286; while (LPC_MRT->Channel[2].STAT & 0x02) ; //wait while running } void initMainClock() { LPC_SYSCON->PDRUNCFG &= ~(0x1 << 7); // Power up PLL LPC_SYSCON->SYSPLLCTRL = 0x24; // MSEL=4, PSEL=1 -> M=5, P=2 -> Fclkout = 60Mhz while (!(LPC_SYSCON->SYSPLLSTAT & 0x01)); // Wait for PLL lock LPC_SYSCON->MAINCLKSEL = 0x03; // Set main clock to PLL source and wait for update LPC_SYSCON->SYSAHBCLKDIV = 6; // Set divider to get final system clock of 10Mhz LPC_SYSCON->MAINCLKUEN = 0x00; LPC_SYSCON->MAINCLKUEN = 0x01; while (!(LPC_SYSCON->MAINCLKUEN & 0x01)); } void i2cSetupRecv (), i2cSetupSend (int); // forward void i2cSetup () { for (int i = 0; i < 3000000; ++i) __ASM(""); LPC_SWM->PINENABLE0 |= 3<<2; // disable SWCLK and SWDIO LPC_SWM->PINASSIGN7 = 0x02FFFFFF; // SDA on P2, pin 4 LPC_SWM->PINASSIGN8 = 0xFFFFFF03; // SCL on P3, pin 3 LPC_SYSCON->SYSAHBCLKCTRL |= 1<<5; // enable I2C clock ih = LPC_I2CD_API->i2c_setup(LPC_I2C_BASE, i2cBuffer); LPC_I2CD_API->i2c_set_slave_addr(ih, 0x70<<1, 0); NVIC_EnableIRQ(I2C_IRQn); } extern "C" void I2C0_IRQHandler () { LPC_I2CD_API->i2c_isr_handler(ih); } // called when I2C reception has been completed void i2cRecvDone (uint32_t err, uint32_t) { i2cSetupRecv(); if (err == 0) i2cSetupSend(i2cRecvBuf[1]); } // called when I2C transmission has been completed void i2cSendDone (uint32_t err, uint32_t) { i2cSetupRecv(); } // prepare to receive the register number void i2cSetupRecv () { i2cParam.func_pt = i2cRecvDone; i2cParam.num_bytes_send = 0; i2cParam.num_bytes_rec = 2; i2cParam.buffer_ptr_rec = i2cRecvBuf; LPC_I2CD_API->i2c_slave_receive_intr(ih, &i2cParam, &i2cResult); } // prepare to transmit either the byte count or the actual data void i2cSetupSend (int regNum) { i2cParam.func_pt = i2cSendDone; i2cParam.num_bytes_rec = 0; if (regNum == 0) { i2cParam.num_bytes_send = 1; i2cSendBuf[0] = 0xff; } else { i2cParam.num_bytes_send = 16; strcpy((char*)i2cSendBuf, "0123456789ABCDEF"); } i2cParam.buffer_ptr_send = i2cSendBuf; LPC_I2CD_API->i2c_slave_transmit_intr(ih, &i2cParam, &i2cResult); } int main () { initMainClock(); serial.init(LPC_USART0, FIXED_UART_BAUD_RATE); delayMs(100); puts("i2c-ir started"); i2cSetup(); i2cSetupRecv(); puts("Waiting..."); while (true) { __WFI(); puts("Msg received"); } } <commit_msg>Added SCT-driven square wave<commit_after>// Report data as I2C slave on address 0x70. #include "LPC8xx.h" #include "lpc_types.h" #include "romapi_8xx.h" #include "serial.h" #include <string.h> #define FIXED_CLOCK_RATE_HZ 10000000 #define FIXED_UART_BAUD_RATE 115200 uint32_t i2cBuffer[24]; // data area used by ROM-based I2C driver I2C_HANDLE_T* ih; // opaque handle used by ROM-based I2C driver I2C_PARAM_T i2cParam; // input parameters for pending I2C request I2C_RESULT_T i2cResult; // return values for pending I2C request uint8_t i2cRecvBuf[2]; // receive buffer: address + register number uint8_t i2cSendBuf[32]; // send buffer void timersInit() { LPC_SYSCON->SYSAHBCLKCTRL |= (1<<10); // enable MRT clock LPC_SYSCON->PRESETCTRL &= ~(1<<7); // reset MRT LPC_SYSCON->PRESETCTRL |= (1<<7); LPC_MRT->Channel[2].CTRL = (0x01 << 1); //MRT2 one-shot mode } void delayMs(int milliseconds) { LPC_MRT->Channel[2].INTVAL = (((FIXED_CLOCK_RATE_HZ / 250L) * milliseconds) >> 2) - 286; while (LPC_MRT->Channel[2].STAT & 0x02) ; //wait while running } void initMainClock() { LPC_SYSCON->PDRUNCFG &= ~(0x1 << 7); // Power up PLL LPC_SYSCON->SYSPLLCTRL = 0x24; // MSEL=4, PSEL=1 -> M=5, P=2 -> Fclkout = 60Mhz while (!(LPC_SYSCON->SYSPLLSTAT & 0x01)); // Wait for PLL lock LPC_SYSCON->MAINCLKSEL = 0x03; // Set main clock to PLL source and wait for update LPC_SYSCON->SYSAHBCLKDIV = 6; // Set divider to get final system clock of 10Mhz LPC_SYSCON->MAINCLKUEN = 0x00; LPC_SYSCON->MAINCLKUEN = 0x01; while (!(LPC_SYSCON->MAINCLKUEN & 0x01)); } #define SW_FREQ 38000 #define SW_MATCH_PERIOD (FIXED_CLOCK_RATE_HZ / SW_FREQ) #define SW_MATCH_HALF_PERIOD (SW_MATCH_PERIOD / 2) void initSCTSquareWave() { // Turn on the clock to the SCT LPC_SYSCON->SYSAHBCLKCTRL |= (1 << 8); // Set up output pin - (ISP) LPC_SWM->PINASSIGN6 = 0x01FFFFFF; LPC_SCT->CONFIG = 0; // 16 bit counter timers // Set up two match events for halfway through and at the end LPC_SCT->REGMODE_L = 0; LPC_SCT->MATCH[0].L = SW_MATCH_PERIOD; LPC_SCT->MATCHREL[0].L = SW_MATCH_PERIOD; LPC_SCT->MATCH[1].L = SW_MATCH_HALF_PERIOD; LPC_SCT->MATCHREL[1].L = SW_MATCH_HALF_PERIOD; // Toggle output pin on events to generate square wave LPC_SCT->OUT[0].SET = 0x01; LPC_SCT->OUT[0].CLR = 0x02; // Set up event control to simply enable events 1 and 2, // and associate them with L counter, match registers 0 and 1. LPC_SCT->EVENT[0].CTRL = 0x5000; LPC_SCT->EVENT[0].STATE = 0x01; LPC_SCT->EVENT[1].CTRL = 0x5001; LPC_SCT->EVENT[1].STATE = 0x01; // Set up counter limit on event 1 to restart LPC_SCT->LIMIT_L = 0x01; } void sctSquareWaveOn() { LPC_SCT->CTRL_L &= ~(1<<2); } void sctSquareWaveOff() { LPC_SCT->CTRL_L |= (1<<2); // Stop LPC_SCT->CTRL_L |= (1<<3); // Clear counter LPC_SCT->OUTPUT = 0; // Clear output } void i2cSetupRecv (), i2cSetupSend (int); void i2cSetup () { for (int i = 0; i < 3000000; ++i) __ASM(""); LPC_SWM->PINENABLE0 |= 3<<2; // disable SWCLK and SWDIO LPC_SWM->PINASSIGN7 = 0x02FFFFFF; // SDA on P2, pin 4 LPC_SWM->PINASSIGN8 = 0xFFFFFF03; // SCL on P3, pin 3 LPC_SYSCON->SYSAHBCLKCTRL |= 1<<5; // enable I2C clock ih = LPC_I2CD_API->i2c_setup(LPC_I2C_BASE, i2cBuffer); LPC_I2CD_API->i2c_set_slave_addr(ih, 0x70<<1, 0); NVIC_EnableIRQ(I2C_IRQn); } extern "C" void I2C0_IRQHandler () { LPC_I2CD_API->i2c_isr_handler(ih); } void i2cRecvDone (uint32_t err, uint32_t) { i2cSetupRecv(); if (err == 0) i2cSetupSend(i2cRecvBuf[1]); } void i2cSendDone (uint32_t err, uint32_t) { i2cSetupRecv(); } void i2cSetupRecv () { i2cParam.func_pt = i2cRecvDone; i2cParam.num_bytes_send = 0; i2cParam.num_bytes_rec = 2; i2cParam.buffer_ptr_rec = i2cRecvBuf; LPC_I2CD_API->i2c_slave_receive_intr(ih, &i2cParam, &i2cResult); } void i2cSetupSend (int regNum) { i2cParam.func_pt = i2cSendDone; i2cParam.num_bytes_rec = 0; switch (regNum) { case 0: i2cParam.num_bytes_send = 1; i2cSendBuf[0] = 0xff; break; case 1: i2cParam.num_bytes_send = 16; strcpy((char*)i2cSendBuf, "0123456789ABCDEF"); break; case 2: i2cParam.num_bytes_send = 1; i2cSendBuf[0] = 0xfe; sctSquareWaveOn(); break; case 3: i2cParam.num_bytes_send = 1; i2cSendBuf[0] = 0xfd; sctSquareWaveOff(); break; } i2cParam.buffer_ptr_send = i2cSendBuf; LPC_I2CD_API->i2c_slave_transmit_intr(ih, &i2cParam, &i2cResult); } int main () { initMainClock(); serial.init(LPC_USART0, FIXED_UART_BAUD_RATE); delayMs(100); puts("i2c-ir started"); i2cSetup(); i2cSetupRecv(); initSCTSquareWave(); puts("Waiting..."); while (true) { __WFI(); puts("Msg received"); } } <|endoftext|>
<commit_before>#ifndef CAFFE_DATA_LAYERS_HPP_ #define CAFFE_DATA_LAYERS_HPP_ #include <string> #include <utility> #include <vector> #include "boost/scoped_ptr.hpp" #include "hdf5.h" #include "caffe/blob.hpp" #include "caffe/common.hpp" #include "caffe/data_transformer.hpp" #include "caffe/filler.hpp" #include "caffe/internal_thread.hpp" #include "caffe/layer.hpp" #include "caffe/net.hpp" #include "caffe/proto/caffe.pb.h" #include "caffe/util/db.hpp" namespace caffe { /** * @brief Provides base for data layers that feed blobs to the Net. * * TODO(dox): thorough documentation for Forward and proto params. */ template <typename Dtype> class BaseDataLayer : public Layer<Dtype> { public: explicit BaseDataLayer(const LayerParameter& param); virtual ~BaseDataLayer() {} // LayerSetUp: implements common data layer setup functionality, and calls // DataLayerSetUp to do special data layer setup for individual layer types. // This method may not be overridden except by the BasePrefetchingDataLayer. virtual void LayerSetUp(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual void DataLayerSetUp(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) {} // Data layers have no bottoms, so reshaping is trivial. virtual void Reshape(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) {} virtual void Backward_cpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom) {} virtual void Backward_gpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom) {} protected: TransformationParameter transform_param_; shared_ptr<DataTransformer<Dtype> > data_transformer_; bool output_labels_; }; template <typename Dtype> class BasePrefetchingDataLayer : public BaseDataLayer<Dtype>, public InternalThread { public: explicit BasePrefetchingDataLayer(const LayerParameter& param) : BaseDataLayer<Dtype>(param) {} virtual ~BasePrefetchingDataLayer() {} // LayerSetUp: implements common data layer setup functionality, and calls // DataLayerSetUp to do special data layer setup for individual layer types. // This method may not be overridden. void LayerSetUp(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual void CreatePrefetchThread(); virtual void JoinPrefetchThread(); // The thread's function virtual void InternalThreadEntry() {} protected: Blob<Dtype> prefetch_data_; Blob<Dtype> prefetch_label_; Blob<Dtype> transformed_data_; }; template <typename Dtype> class DataLayer : public BasePrefetchingDataLayer<Dtype> { public: explicit DataLayer(const LayerParameter& param) : BasePrefetchingDataLayer<Dtype>(param) {} virtual ~DataLayer(); virtual void DataLayerSetUp(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual inline const char* type() const { return "Data"; } virtual inline int ExactNumBottomBlobs() const { return 0; } virtual inline int MinTopBlobs() const { return 1; } virtual inline int MaxTopBlobs() const { return 2; } protected: virtual void InternalThreadEntry(); shared_ptr<db::DB> db_; shared_ptr<db::Cursor> cursor_; }; /** * @brief Provides data to the Net generated by a Filler. * * TODO(dox): thorough documentation for Forward and proto params. */ template <typename Dtype> class DummyDataLayer : public Layer<Dtype> { public: explicit DummyDataLayer(const LayerParameter& param) : Layer<Dtype>(param) {} virtual void LayerSetUp(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); // Data layers have no bottoms, so reshaping is trivial. virtual void Reshape(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) {} virtual inline const char* type() const { return "DummyData"; } virtual inline int ExactNumBottomBlobs() const { return 0; } virtual inline int MinTopBlobs() const { return 1; } protected: virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual void Backward_cpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom) {} virtual void Backward_gpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom) {} vector<shared_ptr<Filler<Dtype> > > fillers_; vector<bool> refill_; }; /** * @brief Provides data to the Net from HDF5 files. * * TODO(dox): thorough documentation for Forward and proto params. */ template <typename Dtype> class HDF5DataLayer : public Layer<Dtype> { public: explicit HDF5DataLayer(const LayerParameter& param) : Layer<Dtype>(param) {} virtual ~HDF5DataLayer(); virtual void LayerSetUp(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); // Data layers have no bottoms, so reshaping is trivial. virtual void Reshape(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) {} virtual inline const char* type() const { return "HDF5Data"; } virtual inline int ExactNumBottomBlobs() const { return 0; } virtual inline int MinTopBlobs() const { return 1; } protected: virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual void Backward_cpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom) {} virtual void Backward_gpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom) {} virtual void LoadHDF5FileData(const char* filename); std::vector<std::string> hdf_filenames_; unsigned int num_files_; unsigned int current_file_; hsize_t current_row_; std::vector<shared_ptr<Blob<Dtype> > > hdf_blobs_; std::vector<unsigned int> data_permutation_; std::vector<unsigned int> file_permutation_; }; /** * @brief Write blobs to disk as HDF5 files. * * TODO(dox): thorough documentation for Forward and proto params. */ template <typename Dtype> class HDF5OutputLayer : public Layer<Dtype> { public: explicit HDF5OutputLayer(const LayerParameter& param) : Layer<Dtype>(param), file_opened_(false) {} virtual ~HDF5OutputLayer(); virtual void LayerSetUp(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); // Data layers have no bottoms, so reshaping is trivial. virtual void Reshape(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) {} virtual inline const char* type() const { return "HDF5Output"; } // TODO: no limit on the number of blobs virtual inline int ExactNumBottomBlobs() const { return 2; } virtual inline int ExactNumTopBlobs() const { return 0; } inline std::string file_name() const { return file_name_; } protected: virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual void Backward_cpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom); virtual void Backward_gpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom); virtual void SaveBlobs(); bool file_opened_; std::string file_name_; hid_t file_id_; Blob<Dtype> data_blob_; Blob<Dtype> label_blob_; }; /** * @brief Provides data to the Net from image files. * * TODO(dox): thorough documentation for Forward and proto params. */ template <typename Dtype> class ImageDataLayer : public BasePrefetchingDataLayer<Dtype> { public: explicit ImageDataLayer(const LayerParameter& param) : BasePrefetchingDataLayer<Dtype>(param) {} virtual ~ImageDataLayer(); virtual void DataLayerSetUp(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual inline const char* type() const { return "ImageData"; } virtual inline int ExactNumBottomBlobs() const { return 0; } virtual inline int ExactNumTopBlobs() const { return 2; } protected: shared_ptr<Caffe::RNG> prefetch_rng_; virtual void ShuffleImages(); virtual void InternalThreadEntry(); vector<std::pair<std::string, int> > lines_; int lines_id_; }; /** * @brief Provides data to the Net from memory. * * TODO(dox): thorough documentation for Forward and proto params. */ template <typename Dtype> class MemoryDataLayer : public BaseDataLayer<Dtype> { public: explicit MemoryDataLayer(const LayerParameter& param) : BaseDataLayer<Dtype>(param), has_new_data_(false) {} virtual void DataLayerSetUp(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual inline const char* type() const { return "MemoryData"; } virtual inline int ExactNumBottomBlobs() const { return 0; } virtual inline int ExactNumTopBlobs() const { return 2; } virtual void AddDatumVector(const vector<Datum>& datum_vector); virtual void AddMatVector(const vector<cv::Mat>& mat_vector, const vector<int>& labels); // Reset should accept const pointers, but can't, because the memory // will be given to Blob, which is mutable void Reset(Dtype* data, Dtype* label, int n); void set_batch_size(int new_size); int batch_size() { return batch_size_; } int channels() { return channels_; } int height() { return height_; } int width() { return width_; } protected: virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); int batch_size_, channels_, height_, width_, size_; Dtype* data_; Dtype* labels_; int n_; size_t pos_; Blob<Dtype> added_data_; Blob<Dtype> added_label_; bool has_new_data_; }; /** * @brief Provides data to the Net from windows of images files, specified * by a window data file. * * TODO(dox): thorough documentation for Forward and proto params. */ template <typename Dtype> class WindowDataLayer : public BasePrefetchingDataLayer<Dtype> { public: explicit WindowDataLayer(const LayerParameter& param) : BasePrefetchingDataLayer<Dtype>(param) {} virtual ~WindowDataLayer(); virtual void DataLayerSetUp(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual inline const char* type() const { return "WindowData"; } virtual inline int ExactNumBottomBlobs() const { return 0; } virtual inline int ExactNumTopBlobs() const { return 2; } protected: virtual unsigned int PrefetchRand(); virtual void InternalThreadEntry(); shared_ptr<Caffe::RNG> prefetch_rng_; vector<std::pair<std::string, vector<int> > > image_database_; enum WindowField { IMAGE_INDEX, LABEL, OVERLAP, X1, Y1, X2, Y2, NUM }; vector<vector<float> > fg_windows_; vector<vector<float> > bg_windows_; Blob<Dtype> data_mean_; vector<Dtype> mean_values_; bool has_mean_file_; bool has_mean_values_; bool cache_images_; vector<std::pair<std::string, Datum > > image_database_cache_; }; } // namespace caffe #endif // CAFFE_DATA_LAYERS_HPP_ <commit_msg>remove superfluous empty destructors<commit_after>#ifndef CAFFE_DATA_LAYERS_HPP_ #define CAFFE_DATA_LAYERS_HPP_ #include <string> #include <utility> #include <vector> #include "boost/scoped_ptr.hpp" #include "hdf5.h" #include "caffe/blob.hpp" #include "caffe/common.hpp" #include "caffe/data_transformer.hpp" #include "caffe/filler.hpp" #include "caffe/internal_thread.hpp" #include "caffe/layer.hpp" #include "caffe/net.hpp" #include "caffe/proto/caffe.pb.h" #include "caffe/util/db.hpp" namespace caffe { /** * @brief Provides base for data layers that feed blobs to the Net. * * TODO(dox): thorough documentation for Forward and proto params. */ template <typename Dtype> class BaseDataLayer : public Layer<Dtype> { public: explicit BaseDataLayer(const LayerParameter& param); // LayerSetUp: implements common data layer setup functionality, and calls // DataLayerSetUp to do special data layer setup for individual layer types. // This method may not be overridden except by the BasePrefetchingDataLayer. virtual void LayerSetUp(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual void DataLayerSetUp(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) {} // Data layers have no bottoms, so reshaping is trivial. virtual void Reshape(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) {} virtual void Backward_cpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom) {} virtual void Backward_gpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom) {} protected: TransformationParameter transform_param_; shared_ptr<DataTransformer<Dtype> > data_transformer_; bool output_labels_; }; template <typename Dtype> class BasePrefetchingDataLayer : public BaseDataLayer<Dtype>, public InternalThread { public: explicit BasePrefetchingDataLayer(const LayerParameter& param) : BaseDataLayer<Dtype>(param) {} // LayerSetUp: implements common data layer setup functionality, and calls // DataLayerSetUp to do special data layer setup for individual layer types. // This method may not be overridden. void LayerSetUp(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual void CreatePrefetchThread(); virtual void JoinPrefetchThread(); // The thread's function virtual void InternalThreadEntry() {} protected: Blob<Dtype> prefetch_data_; Blob<Dtype> prefetch_label_; Blob<Dtype> transformed_data_; }; template <typename Dtype> class DataLayer : public BasePrefetchingDataLayer<Dtype> { public: explicit DataLayer(const LayerParameter& param) : BasePrefetchingDataLayer<Dtype>(param) {} virtual ~DataLayer(); virtual void DataLayerSetUp(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual inline const char* type() const { return "Data"; } virtual inline int ExactNumBottomBlobs() const { return 0; } virtual inline int MinTopBlobs() const { return 1; } virtual inline int MaxTopBlobs() const { return 2; } protected: virtual void InternalThreadEntry(); shared_ptr<db::DB> db_; shared_ptr<db::Cursor> cursor_; }; /** * @brief Provides data to the Net generated by a Filler. * * TODO(dox): thorough documentation for Forward and proto params. */ template <typename Dtype> class DummyDataLayer : public Layer<Dtype> { public: explicit DummyDataLayer(const LayerParameter& param) : Layer<Dtype>(param) {} virtual void LayerSetUp(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); // Data layers have no bottoms, so reshaping is trivial. virtual void Reshape(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) {} virtual inline const char* type() const { return "DummyData"; } virtual inline int ExactNumBottomBlobs() const { return 0; } virtual inline int MinTopBlobs() const { return 1; } protected: virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual void Backward_cpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom) {} virtual void Backward_gpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom) {} vector<shared_ptr<Filler<Dtype> > > fillers_; vector<bool> refill_; }; /** * @brief Provides data to the Net from HDF5 files. * * TODO(dox): thorough documentation for Forward and proto params. */ template <typename Dtype> class HDF5DataLayer : public Layer<Dtype> { public: explicit HDF5DataLayer(const LayerParameter& param) : Layer<Dtype>(param) {} virtual ~HDF5DataLayer(); virtual void LayerSetUp(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); // Data layers have no bottoms, so reshaping is trivial. virtual void Reshape(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) {} virtual inline const char* type() const { return "HDF5Data"; } virtual inline int ExactNumBottomBlobs() const { return 0; } virtual inline int MinTopBlobs() const { return 1; } protected: virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual void Backward_cpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom) {} virtual void Backward_gpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom) {} virtual void LoadHDF5FileData(const char* filename); std::vector<std::string> hdf_filenames_; unsigned int num_files_; unsigned int current_file_; hsize_t current_row_; std::vector<shared_ptr<Blob<Dtype> > > hdf_blobs_; std::vector<unsigned int> data_permutation_; std::vector<unsigned int> file_permutation_; }; /** * @brief Write blobs to disk as HDF5 files. * * TODO(dox): thorough documentation for Forward and proto params. */ template <typename Dtype> class HDF5OutputLayer : public Layer<Dtype> { public: explicit HDF5OutputLayer(const LayerParameter& param) : Layer<Dtype>(param), file_opened_(false) {} virtual ~HDF5OutputLayer(); virtual void LayerSetUp(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); // Data layers have no bottoms, so reshaping is trivial. virtual void Reshape(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) {} virtual inline const char* type() const { return "HDF5Output"; } // TODO: no limit on the number of blobs virtual inline int ExactNumBottomBlobs() const { return 2; } virtual inline int ExactNumTopBlobs() const { return 0; } inline std::string file_name() const { return file_name_; } protected: virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual void Backward_cpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom); virtual void Backward_gpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom); virtual void SaveBlobs(); bool file_opened_; std::string file_name_; hid_t file_id_; Blob<Dtype> data_blob_; Blob<Dtype> label_blob_; }; /** * @brief Provides data to the Net from image files. * * TODO(dox): thorough documentation for Forward and proto params. */ template <typename Dtype> class ImageDataLayer : public BasePrefetchingDataLayer<Dtype> { public: explicit ImageDataLayer(const LayerParameter& param) : BasePrefetchingDataLayer<Dtype>(param) {} virtual ~ImageDataLayer(); virtual void DataLayerSetUp(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual inline const char* type() const { return "ImageData"; } virtual inline int ExactNumBottomBlobs() const { return 0; } virtual inline int ExactNumTopBlobs() const { return 2; } protected: shared_ptr<Caffe::RNG> prefetch_rng_; virtual void ShuffleImages(); virtual void InternalThreadEntry(); vector<std::pair<std::string, int> > lines_; int lines_id_; }; /** * @brief Provides data to the Net from memory. * * TODO(dox): thorough documentation for Forward and proto params. */ template <typename Dtype> class MemoryDataLayer : public BaseDataLayer<Dtype> { public: explicit MemoryDataLayer(const LayerParameter& param) : BaseDataLayer<Dtype>(param), has_new_data_(false) {} virtual void DataLayerSetUp(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual inline const char* type() const { return "MemoryData"; } virtual inline int ExactNumBottomBlobs() const { return 0; } virtual inline int ExactNumTopBlobs() const { return 2; } virtual void AddDatumVector(const vector<Datum>& datum_vector); virtual void AddMatVector(const vector<cv::Mat>& mat_vector, const vector<int>& labels); // Reset should accept const pointers, but can't, because the memory // will be given to Blob, which is mutable void Reset(Dtype* data, Dtype* label, int n); void set_batch_size(int new_size); int batch_size() { return batch_size_; } int channels() { return channels_; } int height() { return height_; } int width() { return width_; } protected: virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); int batch_size_, channels_, height_, width_, size_; Dtype* data_; Dtype* labels_; int n_; size_t pos_; Blob<Dtype> added_data_; Blob<Dtype> added_label_; bool has_new_data_; }; /** * @brief Provides data to the Net from windows of images files, specified * by a window data file. * * TODO(dox): thorough documentation for Forward and proto params. */ template <typename Dtype> class WindowDataLayer : public BasePrefetchingDataLayer<Dtype> { public: explicit WindowDataLayer(const LayerParameter& param) : BasePrefetchingDataLayer<Dtype>(param) {} virtual ~WindowDataLayer(); virtual void DataLayerSetUp(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual inline const char* type() const { return "WindowData"; } virtual inline int ExactNumBottomBlobs() const { return 0; } virtual inline int ExactNumTopBlobs() const { return 2; } protected: virtual unsigned int PrefetchRand(); virtual void InternalThreadEntry(); shared_ptr<Caffe::RNG> prefetch_rng_; vector<std::pair<std::string, vector<int> > > image_database_; enum WindowField { IMAGE_INDEX, LABEL, OVERLAP, X1, Y1, X2, Y2, NUM }; vector<vector<float> > fg_windows_; vector<vector<float> > bg_windows_; Blob<Dtype> data_mean_; vector<Dtype> mean_values_; bool has_mean_file_; bool has_mean_values_; bool cache_images_; vector<std::pair<std::string, Datum > > image_database_cache_; }; } // namespace caffe #endif // CAFFE_DATA_LAYERS_HPP_ <|endoftext|>
<commit_before>#pragma once /* * Covariant Script Version Info * * 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. * * Copyright (C) 2018 Michael Lee(李登淳) * Email: [email protected] * Github: https://github.com/mikecovlee * * Version Format: * 1 . 0 . 0 [Version Code](Preview/Unstable/Stable) Build 1 * | | | | * | | Minor Status * | Major * Master * */ #define COVSCRIPT_VERSION_NUM 3,0,1,2 #define COVSCRIPT_VERSION_STR "3.0.1 Acipenser sinensis(Unstable) Build 2" #define COVSCRIPT_STD_VERSION 190101 #define COVSCRIPT_ABI_VERSION 190101 #if defined(_WIN32) || defined(WIN32) #define COVSCRIPT_PLATFORM_WIN32 #endif <commit_msg>Release: 3.0.1<commit_after>#pragma once /* * Covariant Script Version Info * * 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. * * Copyright (C) 2018 Michael Lee(李登淳) * Email: [email protected] * Github: https://github.com/mikecovlee * * Version Format: * 1 . 0 . 0 [Version Code](Preview/Unstable/Stable) Build 1 * | | | | * | | Minor Status * | Major * Master * */ #define COVSCRIPT_VERSION_NUM 3,0,1,2 #define COVSCRIPT_VERSION_STR "3.0.1 Acipenser sinensis(Stable) Build 2" #define COVSCRIPT_STD_VERSION 190101 #define COVSCRIPT_ABI_VERSION 190101 #if defined(_WIN32) || defined(WIN32) #define COVSCRIPT_PLATFORM_WIN32 #endif <|endoftext|>
<commit_before>/* Copyright (c) 2003, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TORRENT_SOCKET_WIN_HPP_INCLUDED #define TORRENT_SOCKET_WIN_HPP_INCLUDED // TODO: remove the dependency of // platform specific headers here. // sockaddr_in is hard to get rid of in a nice way #if defined(_WIN32) #include <winsock2.h> #else #include <unistd.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include <errno.h> #include <pthread.h> #include <fcntl.h> #include <arpa/inet.h> #endif #include <boost/smart_ptr.hpp> #include <boost/function.hpp> #include <boost/noncopyable.hpp> #include <vector> #include <exception> #include <string> namespace libtorrent { class network_error : public std::exception { public: network_error(int error_code): m_error_code(error_code) {} virtual const char* what() const throw(); private: int m_error_code; }; class socket; class address { friend class socket; public: address(); address(unsigned char a, unsigned char b, unsigned char c, unsigned char d, unsigned short port); address(unsigned int addr, unsigned short port); address(const std::string& addr, unsigned short port); address(const address& a); ~address(); std::string as_string() const; unsigned int ip() const { return m_sockaddr.sin_addr.s_addr; } unsigned short port() const { return htons(m_sockaddr.sin_port); } bool operator<(const address& a) const { if (ip() == a.ip()) return port() < a.port(); else return ip() < a.ip(); } bool operator!=(const address& a) const { return (ip() != a.ip()) || port() != a.port(); } bool operator==(const address& a) const { return (ip() == a.ip()) && port() == a.port(); } private: sockaddr_in m_sockaddr; }; class socket: public boost::noncopyable { friend class address; friend class selector; public: enum type { tcp = 0, udp }; socket(type t, bool blocking = true, unsigned short receive_port = 0); virtual ~socket(); void connect(const address& addr); void close(); void set_blocking(bool blocking); bool is_blocking() { return m_blocking; } const address& sender() const { return m_sender; } address name() const; void listen(unsigned short port, int queue); boost::shared_ptr<libtorrent::socket> accept(); template<class T> int send(const T& buffer); template<class T> int send_to(const address& addr, const T& buffer); template<class T> int receive(T& buf); int send(const char* buffer, int size); int send_to(const address& addr, const char* buffer, int size); int receive(char* buffer, int size); void set_receive_bufsize(int size); void set_send_bufsize(int size); bool is_readable() const; bool is_writable() const; enum error_code { netdown, fault, access, address_in_use, address_not_available, in_progress, interrupted, invalid, net_reset, not_connected, no_buffers, operation_not_supported, not_socket, shutdown, would_block, connection_reset, timed_out, connection_aborted, message_size, not_ready, no_support, connection_refused, is_connected, net_unreachable, not_initialized, unknown_error }; error_code last_error() const; private: socket(int sock, const address& sender); int m_socket; address m_sender; bool m_blocking; #ifndef NDEBUG bool m_connected; // indicates that this socket has been connected type m_type; #endif }; template<class T> inline int socket::send(const T& buf) { return send(reinterpret_cast<const char*>(&buf), sizeof(buf)); } template<class T> inline int socket::send_to(const address& addr, const T& buf) { return send_to(addr, reinterpret_cast<const unsigned char*>(&buf), sizeof(buf)); } template<class T> inline int socket::receive(T& buf) { return receive(reinterpret_cast<char*>(&buf), sizeof(T)); } // timeout is given in microseconds // modified is cleared and filled with the sockets that is ready for reading or writing // or have had an error class selector { public: void monitor_readability(boost::shared_ptr<socket> s) { m_readable.push_back(s); } void monitor_writability(boost::shared_ptr<socket> s) { m_writable.push_back(s); } void monitor_errors(boost::shared_ptr<socket> s) { m_error.push_back(s); } /* void clear_readable() { m_readable.clear(); } void clear_writable() { m_writable.clear(); } */ void remove(boost::shared_ptr<socket> s); void remove_writable(boost::shared_ptr<socket> s) { m_writable.erase(std::find(m_writable.begin(), m_writable.end(), s)); } bool is_writability_monitored(boost::shared_ptr<socket> s) { return std::find(m_writable.begin(), m_writable.end(), s) != m_writable.end(); } void wait(int timeout , std::vector<boost::shared_ptr<socket> >& readable , std::vector<boost::shared_ptr<socket> >& writable , std::vector<boost::shared_ptr<socket> >& error); int count_read_monitors() const { return m_readable.size(); } private: std::vector<boost::shared_ptr<socket> > m_readable; std::vector<boost::shared_ptr<socket> > m_writable; std::vector<boost::shared_ptr<socket> > m_error; }; } #endif // TORRENT_SOCKET_WIN_HPP_INCLUDED <commit_msg>Made the socket.hpp platform independent<commit_after>/* Copyright (c) 2003, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TORRENT_SOCKET_HPP_INCLUDED #define TORRENT_SOCKET_HPP_INCLUDED // TODO: remove the dependency of // platform specific headers here. // sockaddr_in is hard to get rid of in a nice way #if defined(_WIN32) #include <winsock2.h> #else #include <unistd.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include <errno.h> #include <pthread.h> #include <fcntl.h> #include <arpa/inet.h> #endif #include <boost/smart_ptr.hpp> #include <boost/function.hpp> #include <boost/noncopyable.hpp> #include <vector> #include <exception> #include <string> namespace libtorrent { class network_error : public std::exception { public: network_error(int error_code): m_error_code(error_code) {} virtual const char* what() const throw(); private: int m_error_code; }; class socket; class address { friend class socket; public: address(); address( unsigned char a , unsigned char b , unsigned char c , unsigned char d , unsigned short port); address(unsigned int addr, unsigned short port); address(const std::string& addr, unsigned short port); address(const address& a); ~address(); std::string as_string() const; unsigned int ip() const { return m_ip; } unsigned short port() const { return m_port; } bool operator<(const address& a) const { if (ip() == a.ip()) return port() < a.port(); else return ip() < a.ip(); } bool operator!=(const address& a) const { return (ip() != a.ip()) || port() != a.port(); } bool operator==(const address& a) const { return (ip() == a.ip()) && port() == a.port(); } private: unsigned int m_ip; unsigned short m_port; }; class socket: public boost::noncopyable { friend class address; friend class selector; public: enum type { tcp = 0, udp }; socket(type t, bool blocking = true, unsigned short receive_port = 0); virtual ~socket(); void connect(const address& addr); void close(); void set_blocking(bool blocking); bool is_blocking() { return m_blocking; } const address& sender() const { return m_sender; } address name() const; void listen(unsigned short port, int queue); boost::shared_ptr<libtorrent::socket> accept(); template<class T> int send(const T& buffer); template<class T> int send_to(const address& addr, const T& buffer); template<class T> int receive(T& buf); int send(const char* buffer, int size); int send_to(const address& addr, const char* buffer, int size); int receive(char* buffer, int size); void set_receive_bufsize(int size); void set_send_bufsize(int size); bool is_readable() const; bool is_writable() const; enum error_code { netdown, fault, access, address_in_use, address_not_available, in_progress, interrupted, invalid, net_reset, not_connected, no_buffers, operation_not_supported, not_socket, shutdown, would_block, connection_reset, timed_out, connection_aborted, message_size, not_ready, no_support, connection_refused, is_connected, net_unreachable, not_initialized, unknown_error }; error_code last_error() const; private: socket(int sock, const address& sender); int m_socket; address m_sender; bool m_blocking; #ifndef NDEBUG bool m_connected; // indicates that this socket has been connected type m_type; #endif }; template<class T> inline int socket::send(const T& buf) { return send(reinterpret_cast<const char*>(&buf), sizeof(buf)); } template<class T> inline int socket::send_to(const address& addr, const T& buf) { return send_to(addr, reinterpret_cast<const unsigned char*>(&buf), sizeof(buf)); } template<class T> inline int socket::receive(T& buf) { return receive(reinterpret_cast<char*>(&buf), sizeof(T)); } // timeout is given in microseconds // modified is cleared and filled with the sockets that is ready for reading or writing // or have had an error class selector { public: void monitor_readability(boost::shared_ptr<socket> s) { m_readable.push_back(s); } void monitor_writability(boost::shared_ptr<socket> s) { m_writable.push_back(s); } void monitor_errors(boost::shared_ptr<socket> s) { m_error.push_back(s); } /* void clear_readable() { m_readable.clear(); } void clear_writable() { m_writable.clear(); } */ void remove(boost::shared_ptr<socket> s); void remove_writable(boost::shared_ptr<socket> s) { m_writable.erase(std::find(m_writable.begin(), m_writable.end(), s)); } bool is_writability_monitored(boost::shared_ptr<socket> s) { return std::find(m_writable.begin(), m_writable.end(), s) != m_writable.end(); } void wait(int timeout , std::vector<boost::shared_ptr<socket> >& readable , std::vector<boost::shared_ptr<socket> >& writable , std::vector<boost::shared_ptr<socket> >& error); int count_read_monitors() const { return m_readable.size(); } private: std::vector<boost::shared_ptr<socket> > m_readable; std::vector<boost::shared_ptr<socket> > m_writable; std::vector<boost::shared_ptr<socket> > m_error; }; } #endif // TORRENT_SOCKET_WIN_INCLUDED <|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2006 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 * *****************************************************************************/ //$Id: datasource.hpp 43 2005-04-22 18:52:47Z pavlenko $ #ifndef DATASOURCE_HPP #define DATASOURCE_HPP // stl #include <map> #include <string> // boost #include <boost/utility.hpp> #include <boost/shared_ptr.hpp> // mapnik #include <mapnik/config.hpp> #include <mapnik/ctrans.hpp> #include <mapnik/params.hpp> #include <mapnik/feature.hpp> #include <mapnik/query.hpp> #include <mapnik/feature_layer_desc.hpp> namespace mapnik { typedef MAPNIK_DECL boost::shared_ptr<Feature> feature_ptr; struct MAPNIK_DECL Featureset { virtual feature_ptr next()=0; virtual ~Featureset() {}; }; typedef MAPNIK_DECL boost::shared_ptr<Featureset> featureset_ptr; class MAPNIK_DECL datasource_exception : public std::exception { private: const std::string message_; public: datasource_exception(const std::string& message=std::string()) :message_(message) {} ~datasource_exception() throw() {} virtual const char* what() const throw() { return message_.c_str(); } }; class MAPNIK_DECL datasource : private boost::noncopyable { parameters params_; public: enum { Vector, Raster }; datasource (parameters const& params) : params_(params) {} parameters const& params() const { return params_; } virtual int type() const=0; virtual featureset_ptr features(const query& q) const=0; virtual featureset_ptr features_at_point(coord2d const& pt) const=0; virtual Envelope<double> envelope() const=0; virtual layer_descriptor get_descriptor() const=0; virtual ~datasource() {}; }; typedef std::string datasource_name(); typedef datasource* create_ds(const parameters& params); typedef void destroy_ds(datasource *ds); class datasource_deleter { public: void operator() (datasource* ds) { delete ds; } }; typedef boost::shared_ptr<datasource> datasource_ptr; #define DATASOURCE_PLUGIN(classname) \ extern "C" MAPNIK_DECL std::string datasource_name() \ { \ return classname::name(); \ } \ extern "C" MAPNIK_DECL datasource* create(const parameters &params) \ { \ return new classname(params); \ } \ extern "C" MAPNIK_DECL void destroy(datasource *ds) \ { \ delete ds; \ } \ // } #endif //DATASOURCE_HPP <commit_msg>make params_ accessible from derived classes<commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2006 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 * *****************************************************************************/ //$Id: datasource.hpp 43 2005-04-22 18:52:47Z pavlenko $ #ifndef DATASOURCE_HPP #define DATASOURCE_HPP // stl #include <map> #include <string> // boost #include <boost/utility.hpp> #include <boost/shared_ptr.hpp> // mapnik #include <mapnik/config.hpp> #include <mapnik/ctrans.hpp> #include <mapnik/params.hpp> #include <mapnik/feature.hpp> #include <mapnik/query.hpp> #include <mapnik/feature_layer_desc.hpp> namespace mapnik { typedef MAPNIK_DECL boost::shared_ptr<Feature> feature_ptr; struct MAPNIK_DECL Featureset { virtual feature_ptr next()=0; virtual ~Featureset() {}; }; typedef MAPNIK_DECL boost::shared_ptr<Featureset> featureset_ptr; class MAPNIK_DECL datasource_exception : public std::exception { private: const std::string message_; public: datasource_exception(const std::string& message=std::string()) :message_(message) {} ~datasource_exception() throw() {} virtual const char* what() const throw() { return message_.c_str(); } }; class MAPNIK_DECL datasource : private boost::noncopyable { public: enum { Vector, Raster }; datasource (parameters const& params) : params_(params) {} parameters const& params() const { return params_; } virtual int type() const=0; virtual featureset_ptr features(const query& q) const=0; virtual featureset_ptr features_at_point(coord2d const& pt) const=0; virtual Envelope<double> envelope() const=0; virtual layer_descriptor get_descriptor() const=0; virtual ~datasource() {}; protected: parameters params_; }; typedef std::string datasource_name(); typedef datasource* create_ds(const parameters& params); typedef void destroy_ds(datasource *ds); class datasource_deleter { public: void operator() (datasource* ds) { delete ds; } }; typedef boost::shared_ptr<datasource> datasource_ptr; #define DATASOURCE_PLUGIN(classname) \ extern "C" MAPNIK_DECL std::string datasource_name() \ { \ return classname::name(); \ } \ extern "C" MAPNIK_DECL datasource* create(const parameters &params) \ { \ return new classname(params); \ } \ extern "C" MAPNIK_DECL void destroy(datasource *ds) \ { \ delete ds; \ } \ // } #endif //DATASOURCE_HPP <|endoftext|>
<commit_before>/* * Copyright (c) 2010-2013, Vrije Universiteit Brussel. * All rights reserved. */ #ifndef __SHARK_GLOBALARRAY_HPP #define __SHARK_GLOBALARRAY_HPP #include <array> // std::array #include <cstddef> // std::size_t #include <memory> // std::unique_ptr #include <cassert> // assert #include "common.hpp" #include "boundary.hpp" #include "coords.hpp" #include "coords_range.hpp" #include "future.hpp" //#include <mpi.h> namespace shark { namespace ndim { template<int> class GAImpl; template<int,typename> class GADest; template<int,typename> class GARef; /** * A global array that is partitioned across a process group according to a domain */ template<int ndim,typename T> class GlobalArray { friend class Access<ndim,T>; public: typedef GARef<ndim,T> storage; typedef Access<ndim,T> accessor; static const /*constexpr*/ int number_of_dimensions = ndim; typedef std::array<Boundary<ndim,T>,ndim> bounds; private: // before allocate const Domain<ndim>* dom; coords<ndim> gw; bool gc; bounds bd; // after allocate T* ptr; std::unique_ptr<GAImpl<ndim>> impl; coords<ndim+1> ld; std::array<coords_range<ndim>,ndim> ghost_back; std::array<coords_range<ndim>,ndim> ghost_front; // extra mutable int lc; void allocate(); void deallocate(); void reset(); INLINE T& da(coords<ndim> i) const; std::ostream& log_out() const; public: /** * The domain */ INLINE const Domain<ndim>& domain() const; /** * The number of ghost cells for each dimension. */ INLINE coords<ndim> ghost_width() const; /** * Whether corner ghost cells are maintained. */ INLINE bool ghost_corners() const; /** * Returns whether this global array is active. */ INLINE /*explicit*/ operator bool() const; /** * The total/inner/outer region of elements */ INLINE coords_range<ndim> region() const; INLINE coords_range<ndim> inner() const; INLINE coords_range<ndim> outer_front(int) const; INLINE coords_range<ndim> outer_back(int) const; INLINE std::vector<coords_range<ndim>> outer() const; /** * Select a region of elements as destination */ GADest<ndim,T> region(coords_range<ndim>); GADest<ndim,T> region(std::vector<coords_range<ndim>>); /** * Construct a GlobalArray (collective). * The global array will not be active until it is assigned. */ GlobalArray(); /** * Construct a GlobalArray (collective). * @param domain the domain for the distribution of data * @param ghost_width number of ghost cells for each dimension * @param ghost_corners whether to maintain the corner ghost cells */ GlobalArray(const Domain<ndim>& domain, coords<ndim> ghost_width = coords<ndim>(), bool ghost_corners = false, bounds bd = bounds()); GlobalArray(const GlobalArray<ndim,T>& other, bool copy); /** * Destruct a GlobalArray (collective). * If active, the memory of the global array is released */ ~GlobalArray(); // Move semantics GlobalArray(const GlobalArray<ndim,T>& other) = delete; GlobalArray(GlobalArray<ndim,T>&& other); GlobalArray<ndim,T>& operator=(GlobalArray<ndim,T>&& other); // Copy from source GlobalArray<ndim,T>& operator=(const GlobalArray<ndim,T>& other); template<typename S> GlobalArray<ndim,T>& operator=(const S&); /** * Redistribute the GlobalArray to have a Domain. * @param domain the new domain, \verbatim domain().equiv(domain) \enverbatim */ void reshape(const Domain<ndim>& domain); /** * Update the ghost cells with data from their original locations (collective). * RMA operations cannot overlap with local access. * * iupdate is a non-blocking variant if circumstances permit this (aync communication * support, no ghost corners) * * @param k update phase (only used for general boundaries) */ void update(long k=0) const; Future<void> iupdate(long k=0) const; /** * Get remote range (one-sided). * RMA operations cannot overlap with local access. * @param range the area of the global array to retrieve * @param ld the strides to use for buf (default: determined by range) * @param buf the target buffer */ void get(coords_range<ndim> range, T* buf) const; void get(coords_range<ndim> range, std::array<std::size_t,ndim-1> ld, T* buf) const; /** * Put remote range (one-sided). * RMA operations cannot overlap with local access. * @param range the area of the global array to retrieve * @param ld the strides to use for buf (default: determined by range) * @param buf the target buffer */ void put(coords_range<ndim> range, const T* buf); void put(coords_range<ndim> range, std::array<std::size_t,ndim-1> ld, const T* buf); /** * Increase remote range with local values (one-sided). * RMA operations cannot overlap with local access. * @param range the area of the global array to update * @param ld the strides to use for buf (default: determined by range) * @param buf the source buffer */ template<typename = void> void accumulate(coords_range<ndim> range, const T* buf); template<typename = void> void accumulate(coords_range<ndim> range, std::array<std::size_t,ndim-1> ld, const T* buf); /** * Selective gather of remote values (collective). This fills all available positions in a * local sparse array with their values from this global array. * RMA operations cannot overlap with local access. * @param sa the sparse array to fill * * igather is a non-blocking variant if circumstances permit this (aync communication * support) */ template<typename = void> void gather(SparseArray<ndim,T>& sa) const; template<typename = void> Future<void> igather(SparseArray<ndim,T>& sa) const; /** * Selective scatter to remote values (collective). This sends out all available values of a * local sparse array to the respective positions in this global array. The values are accumulated * with the original value at the destination. * RMA operations cannot overlap with local access. * @param sa the sparse array whose values to send out * * iscatterAcc is a non-blocking variant if circumstances permit this (aync communication * support) */ template<typename = void> void scatterAcc(const SparseArray<ndim,T>& sa); template<typename = void> Future<void> iscatterAcc(const SparseArray<ndim,T>& sa); /** * Dump values of global array to a file */ template<typename = void> void dump(coords_range<ndim> range, std::string filename); }; template<int ndim, typename T> class GADest { friend class GlobalArray<ndim,T>; GlobalArray<ndim,T>& ga; std::vector<coords_range<ndim>> regions; GADest(GlobalArray<ndim,T>& ga, std::vector<coords_range<ndim>> r); public: ~GADest(); GADest(const GADest<ndim,T>& gad); GADest& operator=(const GADest<ndim,T>& gad) = delete; template<typename S> GADest<ndim,T>& operator=(const S& src); }; template<int ndim, typename T> class GARef { const GlobalArray<ndim,T>& ga; public: GARef(const GlobalArray<ndim,T>& ga); ~GARef(); INLINE operator const GlobalArray<ndim,T>&() const; INLINE const Domain<ndim>& domain() const; INLINE coords_range<ndim> region() const; }; // Inline function implementations template<int ndim, typename T> inline const Domain<ndim>& GlobalArray<ndim,T>::domain() const { return *dom; } template<int ndim, typename T> inline coords<ndim> GlobalArray<ndim,T>::ghost_width() const { return gw; } template<int ndim, typename T> inline bool GlobalArray<ndim,T>::ghost_corners() const { return gc; } template<int ndim, typename T> inline GlobalArray<ndim,T>::operator bool() const { return dom != 0; } template<int ndim, typename T> inline coords_range<ndim> GlobalArray<ndim,T>::region() const { return domain().total(); } template<int ndim, typename T> inline coords_range<ndim> GlobalArray<ndim,T>::inner() const { auto r = domain().local(); r.lower += ghost_width(); r.upper -= ghost_width(); return r; } template<int ndim, typename T> inline coords_range<ndim> GlobalArray<ndim,T>::outer_front(int d) const { assert(d >= 0 && d < ndim); auto r = domain().local(); r.upper[d] = r.lower[d] + ghost_width()[d]; return r; } template<int ndim, typename T> inline coords_range<ndim> GlobalArray<ndim,T>::outer_back(int d) const { assert(d >= 0 && d < ndim); auto r = domain().local(); r.lower[d] = r.upper[d] - ghost_width()[d]; return r; } template<int ndim, typename T> inline std::vector<coords_range<ndim>> GlobalArray<ndim,T>::outer() const { auto r = std::vector<coords_range<ndim>>(2*ndim); seq<0,ndim>::for_each([this,&r](int d) { r[2*d ] = outer_front(d); r[2*d+1] = outer_back(d); }); return r; } template<int ndim, typename T> inline T& GlobalArray<ndim,T>::da(coords<ndim> i) const { return ptr[(i + gw).offset(ld)]; } template<int ndim, typename T> inline GARef<ndim,T>::operator const GlobalArray<ndim,T>&() const { return ga; } template<int ndim, typename T> inline const Domain<ndim>& GARef<ndim,T>::domain() const { return ga.domain(); } template<int ndim, typename T> inline coords_range<ndim> GARef<ndim,T>::region() const { return ga.region(); } // Generic members template<int ndim, typename T> template<typename S> GlobalArray<ndim,T>& GlobalArray<ndim,T>::operator=(const S& src) { region(domain().total()) = src; return *this; } template<int ndim, typename T> template<typename S> GADest<ndim,T>& GADest<ndim,T>::operator=(const S& src) { static_assert(S::number_of_dimensions == ndim, "source dimensionality"); assert(ga.domain() == src.domain()); Access<ndim,T> d(ga); const typename S::accessor s(src); for(auto r : regions) { ga.domain().for_each(r, [&d, &s](coords<ndim> i){ assert(src.region().contains(r)); d(i) = s(i); }); } return *this; } } } #endif <commit_msg>shark: move assertion to correct spot<commit_after>/* * Copyright (c) 2010-2013, Vrije Universiteit Brussel. * All rights reserved. */ #ifndef __SHARK_GLOBALARRAY_HPP #define __SHARK_GLOBALARRAY_HPP #include <array> // std::array #include <cstddef> // std::size_t #include <memory> // std::unique_ptr #include <cassert> // assert #include "common.hpp" #include "boundary.hpp" #include "coords.hpp" #include "coords_range.hpp" #include "future.hpp" //#include <mpi.h> namespace shark { namespace ndim { template<int> class GAImpl; template<int,typename> class GADest; template<int,typename> class GARef; /** * A global array that is partitioned across a process group according to a domain */ template<int ndim,typename T> class GlobalArray { friend class Access<ndim,T>; public: typedef GARef<ndim,T> storage; typedef Access<ndim,T> accessor; static const /*constexpr*/ int number_of_dimensions = ndim; typedef std::array<Boundary<ndim,T>,ndim> bounds; private: // before allocate const Domain<ndim>* dom; coords<ndim> gw; bool gc; bounds bd; // after allocate T* ptr; std::unique_ptr<GAImpl<ndim>> impl; coords<ndim+1> ld; std::array<coords_range<ndim>,ndim> ghost_back; std::array<coords_range<ndim>,ndim> ghost_front; // extra mutable int lc; void allocate(); void deallocate(); void reset(); INLINE T& da(coords<ndim> i) const; std::ostream& log_out() const; public: /** * The domain */ INLINE const Domain<ndim>& domain() const; /** * The number of ghost cells for each dimension. */ INLINE coords<ndim> ghost_width() const; /** * Whether corner ghost cells are maintained. */ INLINE bool ghost_corners() const; /** * Returns whether this global array is active. */ INLINE /*explicit*/ operator bool() const; /** * The total/inner/outer region of elements */ INLINE coords_range<ndim> region() const; INLINE coords_range<ndim> inner() const; INLINE coords_range<ndim> outer_front(int) const; INLINE coords_range<ndim> outer_back(int) const; INLINE std::vector<coords_range<ndim>> outer() const; /** * Select a region of elements as destination */ GADest<ndim,T> region(coords_range<ndim>); GADest<ndim,T> region(std::vector<coords_range<ndim>>); /** * Construct a GlobalArray (collective). * The global array will not be active until it is assigned. */ GlobalArray(); /** * Construct a GlobalArray (collective). * @param domain the domain for the distribution of data * @param ghost_width number of ghost cells for each dimension * @param ghost_corners whether to maintain the corner ghost cells */ GlobalArray(const Domain<ndim>& domain, coords<ndim> ghost_width = coords<ndim>(), bool ghost_corners = false, bounds bd = bounds()); GlobalArray(const GlobalArray<ndim,T>& other, bool copy); /** * Destruct a GlobalArray (collective). * If active, the memory of the global array is released */ ~GlobalArray(); // Move semantics GlobalArray(const GlobalArray<ndim,T>& other) = delete; GlobalArray(GlobalArray<ndim,T>&& other); GlobalArray<ndim,T>& operator=(GlobalArray<ndim,T>&& other); // Copy from source GlobalArray<ndim,T>& operator=(const GlobalArray<ndim,T>& other); template<typename S> GlobalArray<ndim,T>& operator=(const S&); /** * Redistribute the GlobalArray to have a Domain. * @param domain the new domain, \verbatim domain().equiv(domain) \enverbatim */ void reshape(const Domain<ndim>& domain); /** * Update the ghost cells with data from their original locations (collective). * RMA operations cannot overlap with local access. * * iupdate is a non-blocking variant if circumstances permit this (aync communication * support, no ghost corners) * * @param k update phase (only used for general boundaries) */ void update(long k=0) const; Future<void> iupdate(long k=0) const; /** * Get remote range (one-sided). * RMA operations cannot overlap with local access. * @param range the area of the global array to retrieve * @param ld the strides to use for buf (default: determined by range) * @param buf the target buffer */ void get(coords_range<ndim> range, T* buf) const; void get(coords_range<ndim> range, std::array<std::size_t,ndim-1> ld, T* buf) const; /** * Put remote range (one-sided). * RMA operations cannot overlap with local access. * @param range the area of the global array to retrieve * @param ld the strides to use for buf (default: determined by range) * @param buf the target buffer */ void put(coords_range<ndim> range, const T* buf); void put(coords_range<ndim> range, std::array<std::size_t,ndim-1> ld, const T* buf); /** * Increase remote range with local values (one-sided). * RMA operations cannot overlap with local access. * @param range the area of the global array to update * @param ld the strides to use for buf (default: determined by range) * @param buf the source buffer */ template<typename = void> void accumulate(coords_range<ndim> range, const T* buf); template<typename = void> void accumulate(coords_range<ndim> range, std::array<std::size_t,ndim-1> ld, const T* buf); /** * Selective gather of remote values (collective). This fills all available positions in a * local sparse array with their values from this global array. * RMA operations cannot overlap with local access. * @param sa the sparse array to fill * * igather is a non-blocking variant if circumstances permit this (aync communication * support) */ template<typename = void> void gather(SparseArray<ndim,T>& sa) const; template<typename = void> Future<void> igather(SparseArray<ndim,T>& sa) const; /** * Selective scatter to remote values (collective). This sends out all available values of a * local sparse array to the respective positions in this global array. The values are accumulated * with the original value at the destination. * RMA operations cannot overlap with local access. * @param sa the sparse array whose values to send out * * iscatterAcc is a non-blocking variant if circumstances permit this (aync communication * support) */ template<typename = void> void scatterAcc(const SparseArray<ndim,T>& sa); template<typename = void> Future<void> iscatterAcc(const SparseArray<ndim,T>& sa); /** * Dump values of global array to a file */ template<typename = void> void dump(coords_range<ndim> range, std::string filename); }; template<int ndim, typename T> class GADest { friend class GlobalArray<ndim,T>; GlobalArray<ndim,T>& ga; std::vector<coords_range<ndim>> regions; GADest(GlobalArray<ndim,T>& ga, std::vector<coords_range<ndim>> r); public: ~GADest(); GADest(const GADest<ndim,T>& gad); GADest& operator=(const GADest<ndim,T>& gad) = delete; template<typename S> GADest<ndim,T>& operator=(const S& src); }; template<int ndim, typename T> class GARef { const GlobalArray<ndim,T>& ga; public: GARef(const GlobalArray<ndim,T>& ga); ~GARef(); INLINE operator const GlobalArray<ndim,T>&() const; INLINE const Domain<ndim>& domain() const; INLINE coords_range<ndim> region() const; }; // Inline function implementations template<int ndim, typename T> inline const Domain<ndim>& GlobalArray<ndim,T>::domain() const { return *dom; } template<int ndim, typename T> inline coords<ndim> GlobalArray<ndim,T>::ghost_width() const { return gw; } template<int ndim, typename T> inline bool GlobalArray<ndim,T>::ghost_corners() const { return gc; } template<int ndim, typename T> inline GlobalArray<ndim,T>::operator bool() const { return dom != 0; } template<int ndim, typename T> inline coords_range<ndim> GlobalArray<ndim,T>::region() const { return domain().total(); } template<int ndim, typename T> inline coords_range<ndim> GlobalArray<ndim,T>::inner() const { auto r = domain().local(); r.lower += ghost_width(); r.upper -= ghost_width(); return r; } template<int ndim, typename T> inline coords_range<ndim> GlobalArray<ndim,T>::outer_front(int d) const { assert(d >= 0 && d < ndim); auto r = domain().local(); r.upper[d] = r.lower[d] + ghost_width()[d]; return r; } template<int ndim, typename T> inline coords_range<ndim> GlobalArray<ndim,T>::outer_back(int d) const { assert(d >= 0 && d < ndim); auto r = domain().local(); r.lower[d] = r.upper[d] - ghost_width()[d]; return r; } template<int ndim, typename T> inline std::vector<coords_range<ndim>> GlobalArray<ndim,T>::outer() const { auto r = std::vector<coords_range<ndim>>(2*ndim); seq<0,ndim>::for_each([this,&r](int d) { r[2*d ] = outer_front(d); r[2*d+1] = outer_back(d); }); return r; } template<int ndim, typename T> inline T& GlobalArray<ndim,T>::da(coords<ndim> i) const { return ptr[(i + gw).offset(ld)]; } template<int ndim, typename T> inline GARef<ndim,T>::operator const GlobalArray<ndim,T>&() const { return ga; } template<int ndim, typename T> inline const Domain<ndim>& GARef<ndim,T>::domain() const { return ga.domain(); } template<int ndim, typename T> inline coords_range<ndim> GARef<ndim,T>::region() const { return ga.region(); } // Generic members template<int ndim, typename T> template<typename S> GlobalArray<ndim,T>& GlobalArray<ndim,T>::operator=(const S& src) { region(domain().total()) = src; return *this; } template<int ndim, typename T> template<typename S> GADest<ndim,T>& GADest<ndim,T>::operator=(const S& src) { static_assert(S::number_of_dimensions == ndim, "source dimensionality"); assert(ga.domain() == src.domain()); Access<ndim,T> d(ga); const typename S::accessor s(src); for(auto r : regions) { assert(src.region().contains(r)); ga.domain().for_each(r, [&d, &s](coords<ndim> i){ d(i) = s(i); }); } return *this; } } } #endif <|endoftext|>
<commit_before>#ifndef VSMC_CXX11_RANDOM_HPP #define VSMC_CXX11_RANDOM_HPP #include <vsmc/internal/config.hpp> #if VSMC_HAS_CXX11LIB_RANDOM #include <random> namespace vsmc { namespace cxx11 { using std::minstd_rand0; using std::minstd_rand; using std::mt19937; using std::mt19937_64; using std::ranlux24_base; using std::ranlux48_base; using std::ranlux24; using std::ranlux48; using std::knuth_b; using std::uniform_int_distribution; using std::uniform_real_distribution; using std::bernoulli_distribution; using std::binomial_distribution; using std::geometric_distribution; using std::negative_binomial_distribution; using std::exponential_distribution; using std::extreme_value_distribution; using std::gamma_distribution; using std::poisson_distribution; using std::weibull_distribution; using std::cauchy_distribution; using std::chi_squared_distribution; using std::fisher_f_distribution; using std::lognormal_distribution; using std::normal_distribution; using std::student_t_distribution; using std::discrete_distribution; using std::piecewise_constant_distribution; using std::piecewise_linear_distribution; } } #else // VSMC_HAS_CXX11LIB_RANDOM #include <boost/random.hpp> namespace vsmc { namespace cxx11 { using boost::random::minstd_rand0; using boost::random::minstd_rand; using boost::random::mt19937; using boost::random::mt19937_64; using boost::random::ranlux24_base; using boost::random::ranlux48_base; typedef boost::random::subtract_with_carry_engine<uint32_t, 24, 10, 24> ranlux24_base; typedef boost::random::subtract_with_carry_engine<uint64_t, 48, 5, 12> ranlux48_base; using boost::random::ranlux24; using boost::random::ranlux48; using boost::random::knuth_b; using boost::random::uniform_int_distribution; using boost::random::uniform_real_distribution; typedef boost::random::bernoulli_distribution<double> bernoulli_distribution; using boost::random::binomial_distribution; using boost::random::geometric_distribution; using boost::random::negative_binomial_distribution; using boost::random::exponential_distribution; using boost::random::extreme_value_distribution; using boost::random::gamma_distribution; using boost::random::poisson_distribution; using boost::random::weibull_distribution; using boost::random::cauchy_distribution; using boost::random::chi_squared_distribution; using boost::random::fisher_f_distribution; using boost::random::lognormal_distribution; using boost::random::normal_distribution; using boost::random::student_t_distribution; using boost::random::discrete_distribution; using boost::random::piecewise_constant_distribution; using boost::random::piecewise_linear_distribution; } } #endif // VSMC_HAS_CXX11LIB_RANDOM #endif // VSMC_CXX11_RANDOM_HPP <commit_msg>update random.hpp to include all C++11 names<commit_after>#ifndef VSMC_CXX11_RANDOM_HPP #define VSMC_CXX11_RANDOM_HPP #include <vsmc/internal/config.hpp> #if VSMC_HAS_CXX11LIB_RANDOM #include <random> namespace vsmc { namespace cxx11 { using std::linear_congruential_engine; using std::mersenne_twister_engine; using std::subtract_with_carry_engine; using std::discard_block_engine; using std::independent_bits_engine; using std::shuffle_order_engine; using std::minstd_rand0; using std::minstd_rand; using std::mt19937; using std::mt19937_64; using std::ranlux24_base; using std::ranlux48_base; using std::ranlux24; using std::ranlux48; using std::knuth_b; using std::default_random_engine; // using std::random_device; using std::seed_seq; using std::generate_canonical; using std::uniform_int_distribution; using std::uniform_real_distribution; using std::bernoulli_distribution; using std::binomial_distribution; using std::geometric_distribution; using std::negative_binomial_distribution; using std::poisson_distribution; using std::exponential_distribution; using std::gamma_distribution; using std::weibull_distribution; using std::extreme_value_distribution; using std::normal_distribution; using std::lognormal_distribution; using std::chi_squared_distribution; using std::cauchy_distribution; using std::fisher_f_distribution; using std::student_t_distribution; using std::discrete_distribution; using std::piecewise_constant_distribution; using std::piecewise_linear_distribution; } } #else // VSMC_HAS_CXX11LIB_RANDOM #include <boost/random.hpp> namespace vsmc { namespace cxx11 { using boost::random::linear_congruential_engine; using boost::random::mersenne_twister_engine; using boost::random::subtract_with_carry_engine; using boost::random::discard_block_engine; using boost::random::independent_bits_engine; using boost::random::shuffle_order_engine; using boost::random::minstd_rand0; using boost::random::minstd_rand; using boost::random::mt19937; using boost::random::mt19937_64; // using boost::random::ranlux24_base; typedef boost::random::subtract_with_carry_engine<uint32_t, 24, 10, 24> ranlux24_base; // using boost::random::ranlux48_base; typedef boost::random::subtract_with_carry_engine<uint64_t, 48, 5, 12> ranlux48_base; using boost::random::ranlux24; using boost::random::ranlux48; using boost::random::knuth_b; // using boost::random::default_random_engine; typedef boost::random::mt19937 default_random_engine; // using boost::random::random_device; using boost::random::seed_seq; using boost::random::generate_canonical; using boost::random::uniform_int_distribution; using boost::random::uniform_real_distribution; // using boost::random::bernoulli_distribution; typedef boost::random::bernoulli_distribution<double> bernoulli_distribution; using boost::random::binomial_distribution; using boost::random::geometric_distribution; using boost::random::negative_binomial_distribution; using boost::random::poisson_distribution; using boost::random::exponential_distribution; using boost::random::gamma_distribution; using boost::random::weibull_distribution; using boost::random::extreme_value_distribution; using boost::random::normal_distribution; using boost::random::lognormal_distribution; using boost::random::chi_squared_distribution; using boost::random::cauchy_distribution; using boost::random::fisher_f_distribution; using boost::random::student_t_distribution; using boost::random::discrete_distribution; using boost::random::piecewise_constant_distribution; using boost::random::piecewise_linear_distribution; } } #endif // VSMC_HAS_CXX11LIB_RANDOM #endif // VSMC_CXX11_RANDOM_HPP <|endoftext|>
<commit_before>#ifndef __NESTED_COMPILER__ #define __NESTED_COMPILER__ #include <map> #include <vector> #include <type_traits> #include <sstream> #include <utility> namespace nested_container { // boost lexical cast, simple non-throwing version template<typename Target, typename Source> Target lexical_cast(Source arg) { std::stringstream interpreter; Target result; if(!(interpreter << arg) || !(interpreter >> result) || !(interpreter >> std::ws).eof()) return Target(); return result; } template <typename key_type, typename value_type> using std_map_default_allocators = std::map<key_type, value_type>; template <typename value_type> using std_vector_default_allocators = std::vector<value_type>; template < class Key = std::string , class String = std::string , typename Int = int , typename UInt = unsigned int , typename Float = float , template <typename InnerKey, class This> class MapTemplate = std_map_default_allocators , template <typename This> class ArrayTemplate = std_vector_default_allocators > class basic_container final { public: // Public type declarations using key_type = Key; using str_type = String; using int_type = Int; using uint_type = UInt; using float_type = Float; using map_type = MapTemplate<key_type, basic_container>; using array_type = ArrayTemplate<basic_container>; private: using Map = map_type; using Array = array_type; enum class value_type : unsigned char { null = '0' , dictionary , array , string , floating , integer , unsigned_integer , boolean }; union value final { value() {} ~value() {} Map* dict_; Array* array_; String str_; Float float_; Int int_; UInt uint_; }; template<typename A, typename B> using eq = std::is_same<A,B>; template <typename T> struct type_proxy {}; template <typename T> struct is_from_container { static bool constexpr value = eq<Int, T>::value || eq<UInt, T>::value || eq<Float, T>::value || eq<String, T>::value || eq<Array, T>::value || eq<Map, T>::value || eq<std::nullptr_t, T>::value; }; template <typename Member> struct type_traits { using T = typename std::remove_cv<typename std::remove_reference<Member>::type>::type; using pure_type = T; static_assert(is_from_container<T>::value, "Type must be one of container's internal types"); static constexpr value_type type_value() { return eq<Int, T>::value ? value_type::integer : eq<UInt, T>::value ? value_type::unsigned_integer : eq<Float, T>::value ? value_type::floating : eq<String, T>::value ? value_type::string : eq<Array, T>::value ? value_type::array : eq<Map, T>::value ? value_type::dictionary : value_type::null; } }; value_type type_ = value_type::null; value value_; void clear() { switch (type_) { case value_type::null: break; case value_type::dictionary: delete value_.dict_; break; case value_type::array: delete value_.array_; break; case value_type::string: value_.str_.~str_type(); break; case value_type::floating: break; case value_type::integer: break; case value_type::unsigned_integer: break; default: break; } } // Compile tume initializers template <typename T> void init_member() { init_member(type_proxy<T>()); } void init_member(type_proxy<std::nullptr_t>) {} void init_member(type_proxy<Map>) { value_.dict_ = new Map; } void init_member(type_proxy<Array>) { value_.array_ = new Array; } void init_member(type_proxy<String>) { new (&value_.str_) String; } void init_member(type_proxy<Float>) { value_.float_ = 0.f; } void init_member(type_proxy<Int>) { value_.int_ = 0; } void init_member(type_proxy<UInt>) { value_.uint_ = 0u; } // Init with value - move void init_member(std::nullptr_t&&) {} void init_member(Map&& v) { value_.dict_ = new Map(std::move(v)); } void init_member(Array&& v) { value_.array_ = new Array(std::move(v)); } void init_member(String&& v) { new (&value_.str_) String(std::move(v)); } void init_member(Float&& v) { value_.float_ = v; } void init_member(Int&& v) { value_.int_ = v; } void init_member(UInt&& v) { value_.uint_ = v; } // Init with value - copy void init_member(std::nullptr_t const&) {} void init_member(Map const& v) { value_.dict_ = new Map(v); } void init_member(Array const& v) { value_.array_ = new Array(v); } void init_member(String const& v) { new (&value_.str_) String(v); } void init_member(Float const& v) { value_.float_ = v; } void init_member(Int const& v) { value_.int_ = v; } void init_member(UInt const& v) { value_.uint_ = v; } // Runtime version void init_member(value_type target_type) { switch (type_) { case value_type::null: break; case value_type::dictionary: init_member<Map>(); break; case value_type::array: init_member<Array>(); break; case value_type::string: init_member<String>(); break; case value_type::floating: init_member<Float>(); break; case value_type::integer: init_member<Int>(); break; case value_type::unsigned_integer: init_member<UInt>(); break; default: break; } } // When target time is known at compilation template <typename T> void switch_to_type() { value_type constexpr target_type = type_traits<T>::value_type; if (target_type == type_) return; clear(); init_member<T>(); type_ = target_type; } // When target type is known at runtime only void switch_to_type(value_type target_type) { if (target_type == type_) return; clear(); init_member(target_type); type_ = target_type; } template <typename T> basic_container(type_proxy<T>) : type_(type_traits<T>::type_value()) { init_member(type_proxy<T>()); } template <typename T> basic_container(type_proxy<typename type_traits<T>::pure_type>, T&& arg) : type_(type_traits<T>::type_value()) { init_member(std::forward<T>(arg)); } public: basic_container() {}; basic_container(basic_container const& c) { *this = c; } basic_container(basic_container&& c) { c = std::move(c); } basic_container& operator= (basic_container const& c) { switch_to_type(c.type_); switch (type_) { case value_type::null: break; case value_type::dictionary: *value_.dict_ = *c.value_.dict_; break; case value_type::array: *value_.array_ = *c.value_.array_; break; case value_type::string: value_.str_ = c.value_.str_; break; case value_type::floating: value_.float_ = c.value_.float_; break; case value_type::integer: value_.int_ = c.value_.int_; break; case value_type::unsigned_integer: value_.uint_ = c.value_.uint_; break; default: break; } return *this; } basic_container& operator= (basic_container&& c) { switch_to_type(c.type_); switch (type_) { case value_type::null: break; case value_type::dictionary: *value_.dict_ = std::move(*c.value_.dict_); break; case value_type::array: *value_.array_ = std::move(*c.value_.array_); break; case value_type::string: value_.str_ = std::move(c.value_.str_); break; case value_type::floating: value_.float_ = c.value_.float_; break; case value_type::integer: value_.int_ = c.value_.int_; break; case value_type::unsigned_integer: value_.uint_ = c.value_.uint_; break; default: break; } return *this; } // Specifying those without a template is mandatory // All have the same code, only signature changes; basic_container(std::nullptr_t&& arg) : basic_container(type_proxy<typename type_traits<decltype(arg)>::pure_type>(), arg) {} basic_container(Map&& arg) : basic_container(type_proxy<typename type_traits<decltype(arg)>::pure_type>(), arg) {} basic_container(Array&& arg) : basic_container(type_proxy<typename type_traits<decltype(arg)>::pure_type>(), arg) {} basic_container(String&& arg) : basic_container(type_proxy<typename type_traits<decltype(arg)>::pure_type>(), arg) {} basic_container(Float&& arg) : basic_container(type_proxy<typename type_traits<decltype(arg)>::pure_type>(), arg) {} basic_container(Int&& arg) : basic_container(type_proxy<typename type_traits<decltype(arg)>::pure_type>(), arg) {} basic_container(UInt&& arg) : basic_container(type_proxy<typename type_traits<decltype(arg)>::pure_type>(), arg) {} basic_container(std::nullptr_t const& arg) : basic_container(type_proxy<typename type_traits<decltype(arg)>::pure_type>(), arg) {} basic_container(Map const& arg) : basic_container(type_proxy<typename type_traits<decltype(arg)>::pure_type>(), arg) {} basic_container(Array const& arg) : basic_container(type_proxy<typename type_traits<decltype(arg)>::pure_type>(), arg) {} basic_container(String const& arg) : basic_container(type_proxy<typename type_traits<decltype(arg)>::pure_type>(), arg) {} basic_container(Float const& arg) : basic_container(type_proxy<typename type_traits<decltype(arg)>::pure_type>(), arg) {} basic_container(Int const& arg) : basic_container(type_proxy<typename type_traits<decltype(arg)>::pure_type>(), arg) {} basic_container(UInt const& arg) : basic_container(type_proxy<typename type_traits<decltype(arg)>::pure_type>(), arg) {} ~basic_container() { clear(); } // virtual not needed, this class is final // Helper to initialize the container to a given type template <typename T> static basic_container init() { return basic_container(type_proxy<T>()); } template <typename T> T as() { static_assert(is_from_container<T>::value, "as() must be used with a type of the container."); } inline bool is_null() const { return value_type::null == type_; } inline bool is_dictionary() const { return value_type::dictionary == type_; } inline bool is_array() const { return value_type::array == type_; } inline bool is_string() const { return value_type::string == type_; } inline bool is_float() const { return value_type::floating == type_; } inline bool is_int() const { return value_type::integer == type_; } inline bool is_uint() const { return value_type::unsigned_integer == type_; } }; using container = basic_container<>; }; // namespace nested_container #endif // __NESTED_COMPILER__ <commit_msg>Clang crashes with this code.<commit_after>#ifndef __NESTED_COMPILER__ #define __NESTED_COMPILER__ #include <map> #include <vector> #include <type_traits> #include <sstream> #include <utility> namespace nested_container { // boost lexical cast, simple non-throwing version template<typename Target, typename Source> Target lexical_cast(Source arg) { std::stringstream interpreter; Target result; if(!(interpreter << arg) || !(interpreter >> result) || !(interpreter >> std::ws).eof()) return Target(); return result; } template <typename key_type, typename value_type> using std_map_default_allocators = std::map<key_type, value_type>; template <typename value_type> using std_vector_default_allocators = std::vector<value_type>; template < class Key = std::string , class String = std::string , typename Int = int , typename UInt = unsigned int , typename Float = float , template <typename InnerKey, class This> class MapTemplate = std_map_default_allocators , template <typename This> class ArrayTemplate = std_vector_default_allocators > class basic_container final { public: // Public type declarations using key_type = Key; using str_type = String; using int_type = Int; using uint_type = UInt; using float_type = Float; using map_type = MapTemplate<key_type, basic_container>; using array_type = ArrayTemplate<basic_container>; private: using Map = map_type; using Array = array_type; enum class value_type : unsigned char { null = '0' , dictionary , array , string , floating , integer , unsigned_integer , boolean }; union value final { value() {} ~value() {} Map* dict_; Array* array_; String str_; Float float_; Int int_; UInt uint_; }; template<typename A, typename B> using eq = std::is_same<A,B>; template <typename T> struct type_proxy {}; template <bool Value> struct bool_proxy {}; template <typename T> struct is_from_container { static bool constexpr value = eq<Int, T>::value || eq<UInt, T>::value || eq<Float, T>::value || eq<String, T>::value || eq<Array, T>::value || eq<Map, T>::value || eq<std::nullptr_t, T>::value; }; template <typename Member> struct type_traits { using T = typename std::remove_cv<typename std::remove_reference<Member>::type>::type; using pure_type = T; static_assert(is_from_container<T>::value, "Type must be one of container's internal types"); static constexpr value_type type_value() { return eq<Int, T>::value ? value_type::integer : eq<UInt, T>::value ? value_type::unsigned_integer : eq<Float, T>::value ? value_type::floating : eq<String, T>::value ? value_type::string : eq<Array, T>::value ? value_type::array : eq<Map, T>::value ? value_type::dictionary : value_type::null; } }; value_type type_ = value_type::null; value value_; void clear() { switch (type_) { case value_type::null: break; case value_type::dictionary: delete value_.dict_; break; case value_type::array: delete value_.array_; break; case value_type::string: value_.str_.~str_type(); break; case value_type::floating: break; case value_type::integer: break; case value_type::unsigned_integer: break; default: break; } } // Compile time initializers template <typename T> inline void init_member() { init_member(type_proxy<T>()); } inline void init_member(type_proxy<std::nullptr_t>) {} inline void init_member(type_proxy<Map>) { value_.dict_ = new Map; } inline void init_member(type_proxy<Array>) { value_.array_ = new Array; } inline void init_member(type_proxy<String>) { new (&value_.str_) String; } inline void init_member(type_proxy<Float>) { value_.float_ = 0.f; } inline void init_member(type_proxy<Int>) { value_.int_ = 0; } inline void init_member(type_proxy<UInt>) { value_.uint_ = 0u; } // Init with value - move inline void init_member(std::nullptr_t&&) {} inline void init_member(Map&& v) { value_.dict_ = new Map(std::move(v)); } inline void init_member(Array&& v) { value_.array_ = new Array(std::move(v)); } inline void init_member(String&& v) { new (&value_.str_) String(std::move(v)); } inline void init_member(Float&& v) { value_.float_ = v; } inline void init_member(Int&& v) { value_.int_ = v; } inline void init_member(UInt&& v) { value_.uint_ = v; } // Init with value - copy inline void init_member(std::nullptr_t const&) {} inline void init_member(Map const& v) { value_.dict_ = new Map(v); } inline void init_member(Array const& v) { value_.array_ = new Array(v); } inline void init_member(String const& v) { new (&value_.str_) String(v); } inline void init_member(Float const& v) { value_.float_ = v; } inline void init_member(Int const& v) { value_.int_ = v; } inline void init_member(UInt const& v) { value_.uint_ = v; } // Runtime version void init_member(value_type target_type) { switch (type_) { case value_type::null: break; case value_type::dictionary: init_member<Map>(); break; case value_type::array: init_member<Array>(); break; case value_type::string: init_member<String>(); break; case value_type::floating: init_member<Float>(); break; case value_type::integer: init_member<Int>(); break; case value_type::unsigned_integer: init_member<UInt>(); break; default: break; } } // When target type is known at compilation template <typename T> void switch_to_type() { value_type constexpr target_type = type_traits<T>::type_value(); if (target_type == type_) return; clear(); init_member<T>(); type_ = target_type; } // When target type is known at runtime only void switch_to_type(value_type target_type) { if (target_type == type_) return; clear(); init_member(target_type); type_ = target_type; } template <typename T> basic_container(type_proxy<T>) : type_(type_traits<T>::type_value()) { init_member(type_proxy<T>()); } template <typename T> basic_container(type_proxy<typename type_traits<T>::pure_type>, T&& arg) : type_(type_traits<T>::type_value()) { init_member(std::forward<T>(arg)); } // Accessors template <typename T> inline T* ptr_to() { return ptr_to(type_proxy<T>()); } inline Map* ptr_to(type_proxy<Map>) { return value_.dict_; } inline Array* ptr_to(type_proxy<Array>) { return value_.array_; } inline String* ptr_to(type_proxy<String>) { return &value_.str_; } inline Float* ptr_to(type_proxy<Float>) { return &value_.float_; } inline Int* ptr_to(type_proxy<Int>) { return &value_.int_; } inline UInt* ptr_to(type_proxy<UInt>) { return &value_.uint_; } template <typename T> inline T& ref_to() { return ref_to(type_proxy<T>()); } inline Map& ref_to(type_proxy<Map>) { return *value_.dict_; } inline Array& ref_to(type_proxy<Array>) { return *value_.array_; } inline String& ref_to(type_proxy<String>) { return value_.str_; } inline Float& ref_to(type_proxy<Float>) { return value_.float_; } inline Int& ref_to(type_proxy<Int>) { return value_.int_; } inline UInt& ref_to(type_proxy<UInt>) { return value_.uint_; } template <typename T> basic_container& private_at(bool_proxy<T>, Key const&); // Accessors for when Key != size_t template<> basic_container& private_at(bool_proxy<false>, typename std::enable_if<eq<Key,size_t>::value,Key const&>::type key) { if (value_type::dictionary != type_) switch_to_type<Map>(); return value_.dict_->operator[](key); } // Accessors for when Key == size_t template <> basic_container& private_at (bool_proxy<true>, typename std::enable_if<eq<Key,size_t>::value,Key const&>::type key) { if (value_type::dictionary != type_ && value_type::array != type_) switch_to_type<Map>(); if (value_type::array == type_) return value_.array_->operator[](key); return value_.dict_->operator[](key); } public: basic_container() {}; basic_container(basic_container const& c) { *this = c; } basic_container(basic_container&& c) { c = std::move(c); } basic_container& operator= (basic_container const& c) { switch_to_type(c.type_); switch (type_) { case value_type::null: break; case value_type::dictionary: *value_.dict_ = *c.value_.dict_; break; case value_type::array: *value_.array_ = *c.value_.array_; break; case value_type::string: value_.str_ = c.value_.str_; break; case value_type::floating: value_.float_ = c.value_.float_; break; case value_type::integer: value_.int_ = c.value_.int_; break; case value_type::unsigned_integer: value_.uint_ = c.value_.uint_; break; default: break; } return *this; } basic_container& operator= (basic_container&& c) { switch_to_type(c.type_); switch (type_) { case value_type::null: break; case value_type::dictionary: *value_.dict_ = std::move(*c.value_.dict_); break; case value_type::array: *value_.array_ = std::move(*c.value_.array_); break; case value_type::string: value_.str_ = std::move(c.value_.str_); break; case value_type::floating: value_.float_ = c.value_.float_; break; case value_type::integer: value_.int_ = c.value_.int_; break; case value_type::unsigned_integer: value_.uint_ = c.value_.uint_; break; default: break; } return *this; } // Specifying those without a template is mandatory // All have the same code, only signature changes; basic_container(std::nullptr_t&& arg) : basic_container(type_proxy<typename type_traits<decltype(arg)>::pure_type>(), arg) {} basic_container(Map&& arg) : basic_container(type_proxy<typename type_traits<decltype(arg)>::pure_type>(), arg) {} basic_container(Array&& arg) : basic_container(type_proxy<typename type_traits<decltype(arg)>::pure_type>(), arg) {} basic_container(String&& arg) : basic_container(type_proxy<typename type_traits<decltype(arg)>::pure_type>(), arg) {} basic_container(Float&& arg) : basic_container(type_proxy<typename type_traits<decltype(arg)>::pure_type>(), arg) {} basic_container(Int&& arg) : basic_container(type_proxy<typename type_traits<decltype(arg)>::pure_type>(), arg) {} basic_container(UInt&& arg) : basic_container(type_proxy<typename type_traits<decltype(arg)>::pure_type>(), arg) {} basic_container(std::nullptr_t const& arg) : basic_container(type_proxy<typename type_traits<decltype(arg)>::pure_type>(), arg) {} basic_container(Map const& arg) : basic_container(type_proxy<typename type_traits<decltype(arg)>::pure_type>(), arg) {} basic_container(Array const& arg) : basic_container(type_proxy<typename type_traits<decltype(arg)>::pure_type>(), arg) {} basic_container(String const& arg) : basic_container(type_proxy<typename type_traits<decltype(arg)>::pure_type>(), arg) {} basic_container(Float const& arg) : basic_container(type_proxy<typename type_traits<decltype(arg)>::pure_type>(), arg) {} basic_container(Int const& arg) : basic_container(type_proxy<typename type_traits<decltype(arg)>::pure_type>(), arg) {} basic_container(UInt const& arg) : basic_container(type_proxy<typename type_traits<decltype(arg)>::pure_type>(), arg) {} ~basic_container() { clear(); } // virtual not needed, this class is final // Helper to initialize the container to a given type template <typename T> static basic_container init() { return basic_container(type_proxy<T>()); } template <typename T> T as() { static_assert(is_from_container<T>::value, "as() must be used with a type of the container."); } inline bool is_null() const { return value_type::null == type_; } inline bool is_dictionary() const { return value_type::dictionary == type_; } inline bool is_array() const { return value_type::array == type_; } inline bool is_string() const { return value_type::string == type_; } inline bool is_float() const { return value_type::floating == type_; } inline bool is_int() const { return value_type::integer == type_; } inline bool is_uint() const { return value_type::unsigned_integer == type_; } template <typename T> T const* get() const { return type_traits<T>::type_value() == type_ ? ptr_to<T>() : nullptr; } basic_container& operator[] (Key const& key) { return private_at(bool_proxy<eq<Key,size_t>::value>(), key); } basic_container& operator[] (typename std::enable_if<!eq<Key,size_t>::value, size_t>::type index) { if (value_type::array != type_) switch_to_type<Array>(); return value_.array_->operator[](index); } }; using container = basic_container<>; }; // namespace nested_container #endif // __NESTED_COMPILER__ <|endoftext|>
<commit_before>/** @file Brackets processor unit test test. @author Emil Maskovsky */ #include <cstdlib> #include <iostream> int main() { return EXIT_SUCCESS; } /* EOF */ <commit_msg>Unit test output<commit_after>/** @file Brackets processor unit test test. @author Emil Maskovsky */ #include <cstdlib> #include <iostream> int main() { std::cout << "Running the [Bracket processor] unit test" << std::endl << "=========================================" << std::endl; return EXIT_SUCCESS; } /* EOF */ <|endoftext|>
<commit_before>#ifndef __BSE_COMBO_HH__ #define __BSE_COMBO_HH__ #include <bse/processor.hh> namespace Bse { namespace AudioSignal { // == Chain == /// Container for connecting multiple Processors in a chain. class Chain : public Processor, ProcessorManager { class Inlet; using InletP = std::shared_ptr<Inlet>; using ProcessorVec = vector<ProcessorP>; InletP inlet_; ProcessorP eproc_; ProcessorVec processors_mt_; // modifications guarded by mt_mutex_ Processor *last_output_ = nullptr; const SpeakerArrangement ispeakers_ = SpeakerArrangement (0); const SpeakerArrangement ospeakers_ = SpeakerArrangement (0); std::mutex mt_mutex_; protected: void initialize () override; void configure (uint n_ibusses, const SpeakerArrangement *ibusses, uint n_obusses, const SpeakerArrangement *obusses) override; void reset () override; void render (uint n_frames) override; uint chain_up (Processor &pfirst, Processor &psecond); void reconnect (size_t start); void enqueue_children () override; ProcessorImplP processor_interface () const override; public: explicit Chain (SpeakerArrangement iobuses = SpeakerArrangement::STEREO); virtual ~Chain (); void query_info (ProcessorInfo &info) const override; void insert (ProcessorP proc, size_t pos = ~size_t (0)); bool remove (Processor &proc); ProcessorP at (uint nth); size_t find_pos (Processor &proc); size_t size (); void set_event_source (ProcessorP eproc); ProcessorVec list_processors_mt () const; }; using ChainP = std::shared_ptr<Chain>; } // AudioSignal // == ComboImpl == class ComboImpl : public ProcessorImpl, public virtual ComboIface { std::shared_ptr<AudioSignal::Chain> combo_; protected: bool __access__ (const std::string &n, const PropertyAccessorPred &p) override { return ProcessorImpl::__access__ (n, p);} // TODO: remove public: explicit ComboImpl (AudioSignal::Chain &combo); ProcessorSeq list_processors () override; bool remove_processor (ProcessorIface &sub) override; ProcessorIfaceP create_processor (const std::string &uuiduri) override; ProcessorIfaceP create_processor_before (const std::string &uuiduri, ProcessorIface &sibling) override; DeviceInfoSeq list_processor_types () override; AudioSignal::ProcessorP const audio_signal_processor () const; }; using ComboImplP = std::shared_ptr<ComboImpl>; } // Bse #endif // __BSE_COMBO_HH__ <commit_msg>BSE: combo.hh: remove __access__()<commit_after>#ifndef __BSE_COMBO_HH__ #define __BSE_COMBO_HH__ #include <bse/processor.hh> namespace Bse { namespace AudioSignal { // == Chain == /// Container for connecting multiple Processors in a chain. class Chain : public Processor, ProcessorManager { class Inlet; using InletP = std::shared_ptr<Inlet>; using ProcessorVec = vector<ProcessorP>; InletP inlet_; ProcessorP eproc_; ProcessorVec processors_mt_; // modifications guarded by mt_mutex_ Processor *last_output_ = nullptr; const SpeakerArrangement ispeakers_ = SpeakerArrangement (0); const SpeakerArrangement ospeakers_ = SpeakerArrangement (0); std::mutex mt_mutex_; protected: void initialize () override; void configure (uint n_ibusses, const SpeakerArrangement *ibusses, uint n_obusses, const SpeakerArrangement *obusses) override; void reset () override; void render (uint n_frames) override; uint chain_up (Processor &pfirst, Processor &psecond); void reconnect (size_t start); void enqueue_children () override; ProcessorImplP processor_interface () const override; public: explicit Chain (SpeakerArrangement iobuses = SpeakerArrangement::STEREO); virtual ~Chain (); void query_info (ProcessorInfo &info) const override; void insert (ProcessorP proc, size_t pos = ~size_t (0)); bool remove (Processor &proc); ProcessorP at (uint nth); size_t find_pos (Processor &proc); size_t size (); void set_event_source (ProcessorP eproc); ProcessorVec list_processors_mt () const; }; using ChainP = std::shared_ptr<Chain>; } // AudioSignal // == ComboImpl == class ComboImpl : public ProcessorImpl, public virtual ComboIface { std::shared_ptr<AudioSignal::Chain> combo_; public: explicit ComboImpl (AudioSignal::Chain &combo); ProcessorSeq list_processors () override; bool remove_processor (ProcessorIface &sub) override; ProcessorIfaceP create_processor (const std::string &uuiduri) override; ProcessorIfaceP create_processor_before (const std::string &uuiduri, ProcessorIface &sibling) override; DeviceInfoSeq list_processor_types () override; AudioSignal::ProcessorP const audio_signal_processor () const; }; using ComboImplP = std::shared_ptr<ComboImpl>; } // Bse #endif // __BSE_COMBO_HH__ <|endoftext|>
<commit_before>/* * Copyright (C) 2010-2011 Dmitry Marakasov * * This file is part of glosm. * * glosm is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * glosm 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 glosm. If not, see <http://www.gnu.org/licenses/>. */ #include <err.h> #include <sys/time.h> #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <getopt.h> #if defined(__APPLE__) # include <OpenGL/gl.h> # include <GLUT/glut.h> #else # include <GL/gl.h> # include <GL/glut.h> #endif #include <vector> #include <map> #include <glosm/Math.hh> #include <glosm/SphericalProjection.hh> #include <glosm/MercatorProjection.hh> #include <glosm/PreloadedXmlDatasource.hh> #include <glosm/DefaultGeometryGenerator.hh> #include <glosm/FirstPersonViewer.hh> #include <glosm/GeometryLayer.hh> /* as glut has no OO concept and no feature like setUserData, * please forgive me using global variables pointing to * stack data for now */ FirstPersonViewer viewer; GeometryLayer* layer_p = NULL; int screenw = 1; int screenh = 1; int movementflags = 0; float speed = 200.0f; int lockheight = 0; struct timeval prevtime, curtime, fpstime; int nframes = 0; void Display(void) { /* update scene */ gettimeofday(&curtime, NULL); float dt = (float)(curtime.tv_sec - prevtime.tv_sec) + (float)(curtime.tv_usec - prevtime.tv_usec)/1000000.0f; /* render frame */ glClearColor(0.5, 0.5, 0.5, 0.0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); if (layer_p) { int radius = 5000000; layer_p->RequestVisible(BBoxi(viewer.GetPos(MercatorProjection()) - Vector2i(radius, radius), viewer.GetPos(MercatorProjection()) + Vector2i(radius, radius)), false); layer_p->GarbageCollect(); layer_p->Render(viewer); } glFlush(); glutSwapBuffers(); /* movement */ if (movementflags) { float myspeed = speed; float height = viewer.MutablePos().z / 1000.0; if (height > 100.0 && height < 100000.0) myspeed *= height / 100.0; else if (height >= 100000.0) myspeed *= 1000.0; viewer.Move(movementflags, myspeed, dt); } if (lockheight != 0) viewer.MutablePos().z = lockheight; /* update FPS */ float fpst = (float)(curtime.tv_sec - fpstime.tv_sec) + (float)(curtime.tv_usec - fpstime.tv_usec)/1000000.0f; if (fpst > 10.0) { fprintf(stderr, "FPS: %.3f\n", (float)nframes/fpst); fpstime = curtime; nframes = 0; } prevtime = curtime; nframes++; /* frame limiter */ usleep(10000); } void Reshape(int w, int h) { if (w <= 0) w = 1; if (h <= 0) h = 1; screenw = w; screenh = h; float wanted_fov = 70.0f/180.0f*M_PI; float wanted_aspect = 4.0f/3.0f; float fov, aspect; if ((float)w/(float)h > wanted_aspect) { // wider than wanted fov = wanted_fov; } else { // narrower than wanted float wanted_h = (float)w/wanted_aspect; fov = 2.0f*atanf((float)h / wanted_h * tanf(wanted_fov/2.0f)); } fov = wanted_fov; aspect = (float)w/(float)h; glViewport(0, 0, w, h); viewer.SetFov(fov); viewer.SetAspect(aspect); glutWarpPointer(screenw/2, screenh/2); } void Mouse(int x, int y) { int dx = x - screenw/2; int dy = y - screenh/2; float YawDelta = (float)dx / 500.0; float PitchDelta = -(float)dy / 500.0; viewer.HardRotate(YawDelta, PitchDelta); if (dx != 0 || dy != 0) glutWarpPointer(screenw/2, screenh/2); } void SpecialDown(int key, int, int) { switch (key) { case GLUT_KEY_UP: movementflags |= FirstPersonViewer::FORWARD; break; case GLUT_KEY_DOWN: movementflags |= FirstPersonViewer::BACKWARD; break; case GLUT_KEY_LEFT: movementflags |= FirstPersonViewer::LEFT; break; case GLUT_KEY_RIGHT: movementflags |= FirstPersonViewer::RIGHT; break; default: break; } } void SpecialUp(int key, int, int) { switch (key) { case GLUT_KEY_UP: movementflags &= ~FirstPersonViewer::FORWARD; break; case GLUT_KEY_DOWN: movementflags &= ~FirstPersonViewer::BACKWARD; break; case GLUT_KEY_LEFT: movementflags &= ~FirstPersonViewer::LEFT; break; case GLUT_KEY_RIGHT: movementflags &= ~FirstPersonViewer::RIGHT; break; default: break; } } void KeyDown(unsigned char key, int, int) { switch (key) { case 27: case 'q': exit(0); break; case 'w': movementflags |= FirstPersonViewer::FORWARD; break; case 's': movementflags |= FirstPersonViewer::BACKWARD; break; case 'a': movementflags |= FirstPersonViewer::LEFT; break; case 'd': movementflags |= FirstPersonViewer::RIGHT; break; case 'c': movementflags |= FirstPersonViewer::LOWER; break; case ' ': movementflags |= FirstPersonViewer::HIGHER; break; case 'l': lockheight = (lockheight == 0 ? viewer.MutablePos().z : 0); break; case 'h': lockheight = (lockheight == 0 ? 1750 : 0); break; case '+': speed *= 5.0f; break; case '-': speed /= 5.0f; break; default: break; } } void KeyUp(unsigned char key, int, int) { switch (key) { case 'w': movementflags &= ~FirstPersonViewer::FORWARD; break; case 's': movementflags &= ~FirstPersonViewer::BACKWARD; break; case 'a': movementflags &= ~FirstPersonViewer::LEFT; break; case 'd': movementflags &= ~FirstPersonViewer::RIGHT; break; case 'c': movementflags &= ~FirstPersonViewer::LOWER; break; case ' ': movementflags &= ~FirstPersonViewer::HIGHER; break; default: break; } } void usage(const char* progname) { fprintf(stderr, "Usage: %s [-s] file.osm\n", progname); exit(1); } int real_main(int argc, char** argv) { glutInit(&argc, argv); int c; const char* progname = argv[0]; Projection proj = MercatorProjection(); while ((c = getopt(argc, argv, "s")) != -1) { switch (c) { case 's': proj = SphericalProjection(); break; default: usage(progname); } } argc -= optind; argv += optind; if (argc != 1) usage(progname); /* load data */ fprintf(stderr, "Loading...\n"); PreloadedXmlDatasource osm_datasource; gettimeofday(&prevtime, NULL); osm_datasource.Load(argv[0]); gettimeofday(&curtime, NULL); fprintf(stderr, "Loaded XML in %.3f seconds\n", (float)(curtime.tv_sec - prevtime.tv_sec) + (float)(curtime.tv_usec - prevtime.tv_usec)/1000000.0f); prevtime = curtime; fpstime = curtime; /* glut init */ glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA | GLUT_MULTISAMPLE); glutInitWindowSize(800, 600); glutCreateWindow("glosm viewer"); glutIgnoreKeyRepeat(1); glutSetCursor(GLUT_CURSOR_NONE); glutDisplayFunc(Display); glutIdleFunc(Display); glutReshapeFunc(Reshape); glutPassiveMotionFunc(Mouse); glutKeyboardFunc(KeyDown); glutKeyboardUpFunc(KeyUp); glutSpecialFunc(SpecialDown); glutSpecialUpFunc(SpecialUp); /* glosm init */ DefaultGeometryGenerator geometry_generator(osm_datasource); GeometryLayer layer(proj, geometry_generator); layer_p = &layer; int height = fabs((float)geometry_generator.GetBBox().top - (float)geometry_generator.GetBBox().bottom)/3600000000.0*40000000.0/10.0*1000.0; viewer.SetPos(Vector3i(geometry_generator.GetCenter(), height)); /* main loop */ /* note that this never returns and objects created above * are never properly destroyed; should dump GLUT ASAP */ glutMainLoop(); return 0; } int main(int argc, char** argv) { try { return real_main(argc, argv); } catch (std::exception &e) { fprintf(stderr, "Exception: %s\n", e.what()); } catch (...) { fprintf(stderr, "Unknown exception\n"); } return 1; } <commit_msg>Don't limit speed on high altitudes<commit_after>/* * Copyright (C) 2010-2011 Dmitry Marakasov * * This file is part of glosm. * * glosm is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * glosm 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 glosm. If not, see <http://www.gnu.org/licenses/>. */ #include <err.h> #include <sys/time.h> #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <getopt.h> #if defined(__APPLE__) # include <OpenGL/gl.h> # include <GLUT/glut.h> #else # include <GL/gl.h> # include <GL/glut.h> #endif #include <vector> #include <map> #include <glosm/Math.hh> #include <glosm/SphericalProjection.hh> #include <glosm/MercatorProjection.hh> #include <glosm/PreloadedXmlDatasource.hh> #include <glosm/DefaultGeometryGenerator.hh> #include <glosm/FirstPersonViewer.hh> #include <glosm/GeometryLayer.hh> /* as glut has no OO concept and no feature like setUserData, * please forgive me using global variables pointing to * stack data for now */ FirstPersonViewer viewer; GeometryLayer* layer_p = NULL; int screenw = 1; int screenh = 1; int movementflags = 0; float speed = 200.0f; int lockheight = 0; struct timeval prevtime, curtime, fpstime; int nframes = 0; void Display(void) { /* update scene */ gettimeofday(&curtime, NULL); float dt = (float)(curtime.tv_sec - prevtime.tv_sec) + (float)(curtime.tv_usec - prevtime.tv_usec)/1000000.0f; /* render frame */ glClearColor(0.5, 0.5, 0.5, 0.0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); if (layer_p) { int radius = 5000000; layer_p->RequestVisible(BBoxi(viewer.GetPos(MercatorProjection()) - Vector2i(radius, radius), viewer.GetPos(MercatorProjection()) + Vector2i(radius, radius)), false); layer_p->GarbageCollect(); layer_p->Render(viewer); } glFlush(); glutSwapBuffers(); /* movement */ if (movementflags) { float myspeed = speed; float height = viewer.MutablePos().z / 1000.0; if (height > 100.0) myspeed *= height / 100.0; viewer.Move(movementflags, myspeed, dt); } if (lockheight != 0) viewer.MutablePos().z = lockheight; /* update FPS */ float fpst = (float)(curtime.tv_sec - fpstime.tv_sec) + (float)(curtime.tv_usec - fpstime.tv_usec)/1000000.0f; if (fpst > 10.0) { fprintf(stderr, "FPS: %.3f\n", (float)nframes/fpst); fpstime = curtime; nframes = 0; } prevtime = curtime; nframes++; /* frame limiter */ usleep(10000); } void Reshape(int w, int h) { if (w <= 0) w = 1; if (h <= 0) h = 1; screenw = w; screenh = h; float wanted_fov = 70.0f/180.0f*M_PI; float wanted_aspect = 4.0f/3.0f; float fov, aspect; if ((float)w/(float)h > wanted_aspect) { // wider than wanted fov = wanted_fov; } else { // narrower than wanted float wanted_h = (float)w/wanted_aspect; fov = 2.0f*atanf((float)h / wanted_h * tanf(wanted_fov/2.0f)); } fov = wanted_fov; aspect = (float)w/(float)h; glViewport(0, 0, w, h); viewer.SetFov(fov); viewer.SetAspect(aspect); glutWarpPointer(screenw/2, screenh/2); } void Mouse(int x, int y) { int dx = x - screenw/2; int dy = y - screenh/2; float YawDelta = (float)dx / 500.0; float PitchDelta = -(float)dy / 500.0; viewer.HardRotate(YawDelta, PitchDelta); if (dx != 0 || dy != 0) glutWarpPointer(screenw/2, screenh/2); } void SpecialDown(int key, int, int) { switch (key) { case GLUT_KEY_UP: movementflags |= FirstPersonViewer::FORWARD; break; case GLUT_KEY_DOWN: movementflags |= FirstPersonViewer::BACKWARD; break; case GLUT_KEY_LEFT: movementflags |= FirstPersonViewer::LEFT; break; case GLUT_KEY_RIGHT: movementflags |= FirstPersonViewer::RIGHT; break; default: break; } } void SpecialUp(int key, int, int) { switch (key) { case GLUT_KEY_UP: movementflags &= ~FirstPersonViewer::FORWARD; break; case GLUT_KEY_DOWN: movementflags &= ~FirstPersonViewer::BACKWARD; break; case GLUT_KEY_LEFT: movementflags &= ~FirstPersonViewer::LEFT; break; case GLUT_KEY_RIGHT: movementflags &= ~FirstPersonViewer::RIGHT; break; default: break; } } void KeyDown(unsigned char key, int, int) { switch (key) { case 27: case 'q': exit(0); break; case 'w': movementflags |= FirstPersonViewer::FORWARD; break; case 's': movementflags |= FirstPersonViewer::BACKWARD; break; case 'a': movementflags |= FirstPersonViewer::LEFT; break; case 'd': movementflags |= FirstPersonViewer::RIGHT; break; case 'c': movementflags |= FirstPersonViewer::LOWER; break; case ' ': movementflags |= FirstPersonViewer::HIGHER; break; case 'l': lockheight = (lockheight == 0 ? viewer.MutablePos().z : 0); break; case 'h': lockheight = (lockheight == 0 ? 1750 : 0); break; case '+': speed *= 5.0f; break; case '-': speed /= 5.0f; break; default: break; } } void KeyUp(unsigned char key, int, int) { switch (key) { case 'w': movementflags &= ~FirstPersonViewer::FORWARD; break; case 's': movementflags &= ~FirstPersonViewer::BACKWARD; break; case 'a': movementflags &= ~FirstPersonViewer::LEFT; break; case 'd': movementflags &= ~FirstPersonViewer::RIGHT; break; case 'c': movementflags &= ~FirstPersonViewer::LOWER; break; case ' ': movementflags &= ~FirstPersonViewer::HIGHER; break; default: break; } } void usage(const char* progname) { fprintf(stderr, "Usage: %s [-s] file.osm\n", progname); exit(1); } int real_main(int argc, char** argv) { glutInit(&argc, argv); int c; const char* progname = argv[0]; Projection proj = MercatorProjection(); while ((c = getopt(argc, argv, "s")) != -1) { switch (c) { case 's': proj = SphericalProjection(); break; default: usage(progname); } } argc -= optind; argv += optind; if (argc != 1) usage(progname); /* load data */ fprintf(stderr, "Loading...\n"); PreloadedXmlDatasource osm_datasource; gettimeofday(&prevtime, NULL); osm_datasource.Load(argv[0]); gettimeofday(&curtime, NULL); fprintf(stderr, "Loaded XML in %.3f seconds\n", (float)(curtime.tv_sec - prevtime.tv_sec) + (float)(curtime.tv_usec - prevtime.tv_usec)/1000000.0f); prevtime = curtime; fpstime = curtime; /* glut init */ glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA | GLUT_MULTISAMPLE); glutInitWindowSize(800, 600); glutCreateWindow("glosm viewer"); glutIgnoreKeyRepeat(1); glutSetCursor(GLUT_CURSOR_NONE); glutDisplayFunc(Display); glutIdleFunc(Display); glutReshapeFunc(Reshape); glutPassiveMotionFunc(Mouse); glutKeyboardFunc(KeyDown); glutKeyboardUpFunc(KeyUp); glutSpecialFunc(SpecialDown); glutSpecialUpFunc(SpecialUp); /* glosm init */ DefaultGeometryGenerator geometry_generator(osm_datasource); GeometryLayer layer(proj, geometry_generator); layer_p = &layer; int height = fabs((float)geometry_generator.GetBBox().top - (float)geometry_generator.GetBBox().bottom)/3600000000.0*40000000.0/10.0*1000.0; viewer.SetPos(Vector3i(geometry_generator.GetCenter(), height)); /* main loop */ /* note that this never returns and objects created above * are never properly destroyed; should dump GLUT ASAP */ glutMainLoop(); return 0; } int main(int argc, char** argv) { try { return real_main(argc, argv); } catch (std::exception &e) { fprintf(stderr, "Exception: %s\n", e.what()); } catch (...) { fprintf(stderr, "Unknown exception\n"); } return 1; } <|endoftext|>
<commit_before>// Copyright 2015 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 "flutter/shell/common/engine.h" #include <memory> #include <utility> #include "flutter/common/settings.h" #include "flutter/fml/eintr_wrapper.h" #include "flutter/fml/file.h" #include "flutter/fml/make_copyable.h" #include "flutter/fml/paths.h" #include "flutter/fml/trace_event.h" #include "flutter/fml/unique_fd.h" #include "flutter/lib/snapshot/snapshot.h" #include "flutter/lib/ui/text/font_collection.h" #include "flutter/shell/common/animator.h" #include "flutter/shell/common/platform_view.h" #include "flutter/shell/common/shell.h" #include "rapidjson/document.h" #include "third_party/skia/include/core/SkCanvas.h" #include "third_party/skia/include/core/SkPictureRecorder.h" #ifdef ERROR #undef ERROR #endif namespace shell { static constexpr char kAssetChannel[] = "flutter/assets"; static constexpr char kLifecycleChannel[] = "flutter/lifecycle"; static constexpr char kNavigationChannel[] = "flutter/navigation"; static constexpr char kLocalizationChannel[] = "flutter/localization"; static constexpr char kSettingsChannel[] = "flutter/settings"; Engine::Engine(Delegate& delegate, blink::DartVM& vm, fml::RefPtr<blink::DartSnapshot> isolate_snapshot, fml::RefPtr<blink::DartSnapshot> shared_snapshot, blink::TaskRunners task_runners, blink::Settings settings, std::unique_ptr<Animator> animator, fml::WeakPtr<GrContext> resource_context, fml::RefPtr<flow::SkiaUnrefQueue> unref_queue) : delegate_(delegate), settings_(std::move(settings)), animator_(std::move(animator)), activity_running_(false), have_surface_(false), weak_factory_(this) { // Runtime controller is initialized here because it takes a reference to this // object as its delegate. The delegate may be called in the constructor and // we want to be fully initilazed by that point. runtime_controller_ = std::make_unique<blink::RuntimeController>( *this, // runtime delegate &vm, // VM std::move(isolate_snapshot), // isolate snapshot std::move(shared_snapshot), // shared snapshot std::move(task_runners), // task runners std::move(resource_context), // resource context std::move(unref_queue), // skia unref queue settings_.advisory_script_uri, // advisory script uri settings_.advisory_script_entrypoint // advisory script entrypoint ); } Engine::~Engine() = default; fml::WeakPtr<Engine> Engine::GetWeakPtr() const { return weak_factory_.GetWeakPtr(); } bool Engine::UpdateAssetManager( fml::RefPtr<blink::AssetManager> new_asset_manager) { if (asset_manager_ == new_asset_manager) { return false; } asset_manager_ = new_asset_manager; if (!asset_manager_) { return false; } // Using libTXT as the text engine. if (settings_.use_test_fonts) { font_collection_.RegisterTestFonts(); } else { font_collection_.RegisterFonts(asset_manager_); } return true; } bool Engine::Restart(RunConfiguration configuration) { TRACE_EVENT0("flutter", "Engine::Restart"); if (!configuration.IsValid()) { FML_LOG(ERROR) << "Engine run configuration was invalid."; return false; } delegate_.OnPreEngineRestart(); runtime_controller_ = runtime_controller_->Clone(); UpdateAssetManager(nullptr); return Run(std::move(configuration)) == Engine::RunStatus::Success; } Engine::RunStatus Engine::Run(RunConfiguration configuration) { if (!configuration.IsValid()) { FML_LOG(ERROR) << "Engine run configuration was invalid."; return RunStatus::Failure; } auto isolate_launch_status = PrepareAndLaunchIsolate(std::move(configuration)); if (isolate_launch_status == Engine::RunStatus::Failure) { FML_LOG(ERROR) << "Engine not prepare and launch isolate."; return isolate_launch_status; } else if (isolate_launch_status == Engine::RunStatus::FailureAlreadyRunning) { return isolate_launch_status; } std::shared_ptr<blink::DartIsolate> isolate = runtime_controller_->GetRootIsolate().lock(); bool isolate_running = isolate && isolate->GetPhase() == blink::DartIsolate::Phase::Running; if (isolate_running) { tonic::DartState::Scope scope(isolate.get()); if (settings_.root_isolate_create_callback) { settings_.root_isolate_create_callback(); } if (settings_.root_isolate_shutdown_callback) { isolate->AddIsolateShutdownCallback( settings_.root_isolate_shutdown_callback); } } return isolate_running ? Engine::RunStatus::Success : Engine::RunStatus::Failure; } shell::Engine::RunStatus Engine::PrepareAndLaunchIsolate( RunConfiguration configuration) { TRACE_EVENT0("flutter", "Engine::PrepareAndLaunchIsolate"); UpdateAssetManager(configuration.GetAssetManager()); auto isolate_configuration = configuration.TakeIsolateConfiguration(); std::shared_ptr<blink::DartIsolate> isolate = runtime_controller_->GetRootIsolate().lock(); if (!isolate) { return RunStatus::Failure; } // This can happen on iOS after a plugin shows a native window and returns to // the Flutter ViewController. if (isolate->GetPhase() == blink::DartIsolate::Phase::Running) { FML_DLOG(WARNING) << "Isolate was already running!"; return RunStatus::FailureAlreadyRunning; } if (!isolate_configuration->PrepareIsolate(*isolate)) { FML_LOG(ERROR) << "Could not prepare to run the isolate."; return RunStatus::Failure; } if (configuration.GetEntrypointLibrary().empty()) { if (!isolate->Run(configuration.GetEntrypoint())) { FML_LOG(ERROR) << "Could not run the isolate."; return RunStatus::Failure; } } else { if (!isolate->RunFromLibrary(configuration.GetEntrypointLibrary(), configuration.GetEntrypoint())) { FML_LOG(ERROR) << "Could not run the isolate."; return RunStatus::Failure; } } return RunStatus::Success; } void Engine::BeginFrame(fml::TimePoint frame_time) { TRACE_EVENT0("flutter", "Engine::BeginFrame"); runtime_controller_->BeginFrame(frame_time); } void Engine::NotifyIdle(int64_t deadline) { TRACE_EVENT0("flutter", "Engine::NotifyIdle"); runtime_controller_->NotifyIdle(deadline); } std::pair<bool, uint32_t> Engine::GetUIIsolateReturnCode() { return runtime_controller_->GetRootIsolateReturnCode(); } Dart_Port Engine::GetUIIsolateMainPort() { return runtime_controller_->GetMainPort(); } std::string Engine::GetUIIsolateName() { return runtime_controller_->GetIsolateName(); } bool Engine::UIIsolateHasLivePorts() { return runtime_controller_->HasLivePorts(); } tonic::DartErrorHandleType Engine::GetUIIsolateLastError() { return runtime_controller_->GetLastError(); } void Engine::OnOutputSurfaceCreated() { have_surface_ = true; StartAnimatorIfPossible(); ScheduleFrame(); } void Engine::OnOutputSurfaceDestroyed() { have_surface_ = false; StopAnimator(); } void Engine::SetViewportMetrics(const blink::ViewportMetrics& metrics) { bool dimensions_changed = viewport_metrics_.physical_height != metrics.physical_height || viewport_metrics_.physical_width != metrics.physical_width; viewport_metrics_ = metrics; runtime_controller_->SetViewportMetrics(viewport_metrics_); if (animator_) { if (dimensions_changed) animator_->SetDimensionChangePending(); if (have_surface_) ScheduleFrame(); } } void Engine::DispatchPlatformMessage( fml::RefPtr<blink::PlatformMessage> message) { if (message->channel() == kLifecycleChannel) { if (HandleLifecyclePlatformMessage(message.get())) return; } else if (message->channel() == kLocalizationChannel) { if (HandleLocalizationPlatformMessage(message.get())) return; } else if (message->channel() == kSettingsChannel) { HandleSettingsPlatformMessage(message.get()); return; } if (runtime_controller_->IsRootIsolateRunning() && runtime_controller_->DispatchPlatformMessage(std::move(message))) { return; } // If there's no runtime_, we may still need to set the initial route. if (message->channel() == kNavigationChannel) HandleNavigationPlatformMessage(std::move(message)); } bool Engine::HandleLifecyclePlatformMessage(blink::PlatformMessage* message) { const auto& data = message->data(); std::string state(reinterpret_cast<const char*>(data.data()), data.size()); if (state == "AppLifecycleState.paused" || state == "AppLifecycleState.suspending") { activity_running_ = false; StopAnimator(); } else if (state == "AppLifecycleState.resumed" || state == "AppLifecycleState.inactive") { activity_running_ = true; StartAnimatorIfPossible(); } // Always schedule a frame when the app does become active as per API // recommendation // https://developer.apple.com/documentation/uikit/uiapplicationdelegate/1622956-applicationdidbecomeactive?language=objc if (state == "AppLifecycleState.resumed" && have_surface_) { ScheduleFrame(); } return false; } bool Engine::HandleNavigationPlatformMessage( fml::RefPtr<blink::PlatformMessage> message) { const auto& data = message->data(); rapidjson::Document document; document.Parse(reinterpret_cast<const char*>(data.data()), data.size()); if (document.HasParseError() || !document.IsObject()) return false; auto root = document.GetObject(); auto method = root.FindMember("method"); if (method->value != "setInitialRoute") return false; auto route = root.FindMember("args"); initial_route_ = std::move(route->value.GetString()); return true; } bool Engine::HandleLocalizationPlatformMessage( blink::PlatformMessage* message) { const auto& data = message->data(); rapidjson::Document document; document.Parse(reinterpret_cast<const char*>(data.data()), data.size()); if (document.HasParseError() || !document.IsObject()) return false; auto root = document.GetObject(); auto method = root.FindMember("method"); if (method == root.MemberEnd() || method->value != "setLocale") return false; auto args = root.FindMember("args"); if (args == root.MemberEnd() || !args->value.IsArray()) return false; const auto& language = args->value[0]; const auto& country = args->value[1]; if (!language.IsString() || !country.IsString()) return false; return runtime_controller_->SetLocale(language.GetString(), country.GetString()); } void Engine::HandleSettingsPlatformMessage(blink::PlatformMessage* message) { const auto& data = message->data(); std::string jsonData(reinterpret_cast<const char*>(data.data()), data.size()); if (runtime_controller_->SetUserSettingsData(std::move(jsonData)) && have_surface_) { ScheduleFrame(); } } void Engine::DispatchPointerDataPacket(const blink::PointerDataPacket& packet) { runtime_controller_->DispatchPointerDataPacket(packet); } void Engine::DispatchSemanticsAction(int id, blink::SemanticsAction action, std::vector<uint8_t> args) { runtime_controller_->DispatchSemanticsAction(id, action, std::move(args)); } void Engine::SetSemanticsEnabled(bool enabled) { runtime_controller_->SetSemanticsEnabled(enabled); } void Engine::SetAccessibilityFeatures(int32_t flags) { runtime_controller_->SetAccessibilityFeatures(flags); } void Engine::StopAnimator() { animator_->Stop(); } void Engine::StartAnimatorIfPossible() { if (activity_running_ && have_surface_) animator_->Start(); } std::string Engine::DefaultRouteName() { if (!initial_route_.empty()) { return initial_route_; } return "/"; } void Engine::ScheduleFrame(bool regenerate_layer_tree) { animator_->RequestFrame(regenerate_layer_tree); } void Engine::Render(std::unique_ptr<flow::LayerTree> layer_tree) { if (!layer_tree) return; SkISize frame_size = SkISize::Make(viewport_metrics_.physical_width, viewport_metrics_.physical_height); if (frame_size.isEmpty()) return; layer_tree->set_frame_size(frame_size); animator_->Render(std::move(layer_tree)); } void Engine::UpdateSemantics(blink::SemanticsNodeUpdates update, blink::CustomAccessibilityActionUpdates actions) { delegate_.OnEngineUpdateSemantics(std::move(update), std::move(actions)); } void Engine::HandlePlatformMessage( fml::RefPtr<blink::PlatformMessage> message) { if (message->channel() == kAssetChannel) { HandleAssetPlatformMessage(std::move(message)); } else { delegate_.OnEngineHandlePlatformMessage(std::move(message)); } } blink::FontCollection& Engine::GetFontCollection() { return font_collection_; } void Engine::HandleAssetPlatformMessage( fml::RefPtr<blink::PlatformMessage> message) { fml::RefPtr<blink::PlatformMessageResponse> response = message->response(); if (!response) { return; } const auto& data = message->data(); std::string asset_name(reinterpret_cast<const char*>(data.data()), data.size()); if (asset_manager_) { std::unique_ptr<fml::Mapping> asset_mapping = asset_manager_->GetAsMapping(asset_name); if (asset_mapping) { response->Complete(std::move(asset_mapping)); return; } } response->CompleteEmpty(); } } // namespace shell <commit_msg>Add deadline_now_delta argument to Engine::NotifyIdle's trace (#6419)<commit_after>// Copyright 2015 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 "flutter/shell/common/engine.h" #include <memory> #include <string> #include <utility> #include "flutter/common/settings.h" #include "flutter/fml/eintr_wrapper.h" #include "flutter/fml/file.h" #include "flutter/fml/make_copyable.h" #include "flutter/fml/paths.h" #include "flutter/fml/trace_event.h" #include "flutter/fml/unique_fd.h" #include "flutter/lib/snapshot/snapshot.h" #include "flutter/lib/ui/text/font_collection.h" #include "flutter/shell/common/animator.h" #include "flutter/shell/common/platform_view.h" #include "flutter/shell/common/shell.h" #include "rapidjson/document.h" #include "third_party/dart/runtime/include/dart_tools_api.h" #include "third_party/skia/include/core/SkCanvas.h" #include "third_party/skia/include/core/SkPictureRecorder.h" #ifdef ERROR #undef ERROR #endif namespace shell { static constexpr char kAssetChannel[] = "flutter/assets"; static constexpr char kLifecycleChannel[] = "flutter/lifecycle"; static constexpr char kNavigationChannel[] = "flutter/navigation"; static constexpr char kLocalizationChannel[] = "flutter/localization"; static constexpr char kSettingsChannel[] = "flutter/settings"; Engine::Engine(Delegate& delegate, blink::DartVM& vm, fml::RefPtr<blink::DartSnapshot> isolate_snapshot, fml::RefPtr<blink::DartSnapshot> shared_snapshot, blink::TaskRunners task_runners, blink::Settings settings, std::unique_ptr<Animator> animator, fml::WeakPtr<GrContext> resource_context, fml::RefPtr<flow::SkiaUnrefQueue> unref_queue) : delegate_(delegate), settings_(std::move(settings)), animator_(std::move(animator)), activity_running_(false), have_surface_(false), weak_factory_(this) { // Runtime controller is initialized here because it takes a reference to this // object as its delegate. The delegate may be called in the constructor and // we want to be fully initilazed by that point. runtime_controller_ = std::make_unique<blink::RuntimeController>( *this, // runtime delegate &vm, // VM std::move(isolate_snapshot), // isolate snapshot std::move(shared_snapshot), // shared snapshot std::move(task_runners), // task runners std::move(resource_context), // resource context std::move(unref_queue), // skia unref queue settings_.advisory_script_uri, // advisory script uri settings_.advisory_script_entrypoint // advisory script entrypoint ); } Engine::~Engine() = default; fml::WeakPtr<Engine> Engine::GetWeakPtr() const { return weak_factory_.GetWeakPtr(); } bool Engine::UpdateAssetManager( fml::RefPtr<blink::AssetManager> new_asset_manager) { if (asset_manager_ == new_asset_manager) { return false; } asset_manager_ = new_asset_manager; if (!asset_manager_) { return false; } // Using libTXT as the text engine. if (settings_.use_test_fonts) { font_collection_.RegisterTestFonts(); } else { font_collection_.RegisterFonts(asset_manager_); } return true; } bool Engine::Restart(RunConfiguration configuration) { TRACE_EVENT0("flutter", "Engine::Restart"); if (!configuration.IsValid()) { FML_LOG(ERROR) << "Engine run configuration was invalid."; return false; } delegate_.OnPreEngineRestart(); runtime_controller_ = runtime_controller_->Clone(); UpdateAssetManager(nullptr); return Run(std::move(configuration)) == Engine::RunStatus::Success; } Engine::RunStatus Engine::Run(RunConfiguration configuration) { if (!configuration.IsValid()) { FML_LOG(ERROR) << "Engine run configuration was invalid."; return RunStatus::Failure; } auto isolate_launch_status = PrepareAndLaunchIsolate(std::move(configuration)); if (isolate_launch_status == Engine::RunStatus::Failure) { FML_LOG(ERROR) << "Engine not prepare and launch isolate."; return isolate_launch_status; } else if (isolate_launch_status == Engine::RunStatus::FailureAlreadyRunning) { return isolate_launch_status; } std::shared_ptr<blink::DartIsolate> isolate = runtime_controller_->GetRootIsolate().lock(); bool isolate_running = isolate && isolate->GetPhase() == blink::DartIsolate::Phase::Running; if (isolate_running) { tonic::DartState::Scope scope(isolate.get()); if (settings_.root_isolate_create_callback) { settings_.root_isolate_create_callback(); } if (settings_.root_isolate_shutdown_callback) { isolate->AddIsolateShutdownCallback( settings_.root_isolate_shutdown_callback); } } return isolate_running ? Engine::RunStatus::Success : Engine::RunStatus::Failure; } shell::Engine::RunStatus Engine::PrepareAndLaunchIsolate( RunConfiguration configuration) { TRACE_EVENT0("flutter", "Engine::PrepareAndLaunchIsolate"); UpdateAssetManager(configuration.GetAssetManager()); auto isolate_configuration = configuration.TakeIsolateConfiguration(); std::shared_ptr<blink::DartIsolate> isolate = runtime_controller_->GetRootIsolate().lock(); if (!isolate) { return RunStatus::Failure; } // This can happen on iOS after a plugin shows a native window and returns to // the Flutter ViewController. if (isolate->GetPhase() == blink::DartIsolate::Phase::Running) { FML_DLOG(WARNING) << "Isolate was already running!"; return RunStatus::FailureAlreadyRunning; } if (!isolate_configuration->PrepareIsolate(*isolate)) { FML_LOG(ERROR) << "Could not prepare to run the isolate."; return RunStatus::Failure; } if (configuration.GetEntrypointLibrary().empty()) { if (!isolate->Run(configuration.GetEntrypoint())) { FML_LOG(ERROR) << "Could not run the isolate."; return RunStatus::Failure; } } else { if (!isolate->RunFromLibrary(configuration.GetEntrypointLibrary(), configuration.GetEntrypoint())) { FML_LOG(ERROR) << "Could not run the isolate."; return RunStatus::Failure; } } return RunStatus::Success; } void Engine::BeginFrame(fml::TimePoint frame_time) { TRACE_EVENT0("flutter", "Engine::BeginFrame"); runtime_controller_->BeginFrame(frame_time); } void Engine::NotifyIdle(int64_t deadline) { TRACE_EVENT1("flutter", "Engine::NotifyIdle", "deadline_now_delta", std::to_string(deadline - Dart_TimelineGetMicros()).c_str()); runtime_controller_->NotifyIdle(deadline); } std::pair<bool, uint32_t> Engine::GetUIIsolateReturnCode() { return runtime_controller_->GetRootIsolateReturnCode(); } Dart_Port Engine::GetUIIsolateMainPort() { return runtime_controller_->GetMainPort(); } std::string Engine::GetUIIsolateName() { return runtime_controller_->GetIsolateName(); } bool Engine::UIIsolateHasLivePorts() { return runtime_controller_->HasLivePorts(); } tonic::DartErrorHandleType Engine::GetUIIsolateLastError() { return runtime_controller_->GetLastError(); } void Engine::OnOutputSurfaceCreated() { have_surface_ = true; StartAnimatorIfPossible(); ScheduleFrame(); } void Engine::OnOutputSurfaceDestroyed() { have_surface_ = false; StopAnimator(); } void Engine::SetViewportMetrics(const blink::ViewportMetrics& metrics) { bool dimensions_changed = viewport_metrics_.physical_height != metrics.physical_height || viewport_metrics_.physical_width != metrics.physical_width; viewport_metrics_ = metrics; runtime_controller_->SetViewportMetrics(viewport_metrics_); if (animator_) { if (dimensions_changed) animator_->SetDimensionChangePending(); if (have_surface_) ScheduleFrame(); } } void Engine::DispatchPlatformMessage( fml::RefPtr<blink::PlatformMessage> message) { if (message->channel() == kLifecycleChannel) { if (HandleLifecyclePlatformMessage(message.get())) return; } else if (message->channel() == kLocalizationChannel) { if (HandleLocalizationPlatformMessage(message.get())) return; } else if (message->channel() == kSettingsChannel) { HandleSettingsPlatformMessage(message.get()); return; } if (runtime_controller_->IsRootIsolateRunning() && runtime_controller_->DispatchPlatformMessage(std::move(message))) { return; } // If there's no runtime_, we may still need to set the initial route. if (message->channel() == kNavigationChannel) HandleNavigationPlatformMessage(std::move(message)); } bool Engine::HandleLifecyclePlatformMessage(blink::PlatformMessage* message) { const auto& data = message->data(); std::string state(reinterpret_cast<const char*>(data.data()), data.size()); if (state == "AppLifecycleState.paused" || state == "AppLifecycleState.suspending") { activity_running_ = false; StopAnimator(); } else if (state == "AppLifecycleState.resumed" || state == "AppLifecycleState.inactive") { activity_running_ = true; StartAnimatorIfPossible(); } // Always schedule a frame when the app does become active as per API // recommendation // https://developer.apple.com/documentation/uikit/uiapplicationdelegate/1622956-applicationdidbecomeactive?language=objc if (state == "AppLifecycleState.resumed" && have_surface_) { ScheduleFrame(); } return false; } bool Engine::HandleNavigationPlatformMessage( fml::RefPtr<blink::PlatformMessage> message) { const auto& data = message->data(); rapidjson::Document document; document.Parse(reinterpret_cast<const char*>(data.data()), data.size()); if (document.HasParseError() || !document.IsObject()) return false; auto root = document.GetObject(); auto method = root.FindMember("method"); if (method->value != "setInitialRoute") return false; auto route = root.FindMember("args"); initial_route_ = std::move(route->value.GetString()); return true; } bool Engine::HandleLocalizationPlatformMessage( blink::PlatformMessage* message) { const auto& data = message->data(); rapidjson::Document document; document.Parse(reinterpret_cast<const char*>(data.data()), data.size()); if (document.HasParseError() || !document.IsObject()) return false; auto root = document.GetObject(); auto method = root.FindMember("method"); if (method == root.MemberEnd() || method->value != "setLocale") return false; auto args = root.FindMember("args"); if (args == root.MemberEnd() || !args->value.IsArray()) return false; const auto& language = args->value[0]; const auto& country = args->value[1]; if (!language.IsString() || !country.IsString()) return false; return runtime_controller_->SetLocale(language.GetString(), country.GetString()); } void Engine::HandleSettingsPlatformMessage(blink::PlatformMessage* message) { const auto& data = message->data(); std::string jsonData(reinterpret_cast<const char*>(data.data()), data.size()); if (runtime_controller_->SetUserSettingsData(std::move(jsonData)) && have_surface_) { ScheduleFrame(); } } void Engine::DispatchPointerDataPacket(const blink::PointerDataPacket& packet) { runtime_controller_->DispatchPointerDataPacket(packet); } void Engine::DispatchSemanticsAction(int id, blink::SemanticsAction action, std::vector<uint8_t> args) { runtime_controller_->DispatchSemanticsAction(id, action, std::move(args)); } void Engine::SetSemanticsEnabled(bool enabled) { runtime_controller_->SetSemanticsEnabled(enabled); } void Engine::SetAccessibilityFeatures(int32_t flags) { runtime_controller_->SetAccessibilityFeatures(flags); } void Engine::StopAnimator() { animator_->Stop(); } void Engine::StartAnimatorIfPossible() { if (activity_running_ && have_surface_) animator_->Start(); } std::string Engine::DefaultRouteName() { if (!initial_route_.empty()) { return initial_route_; } return "/"; } void Engine::ScheduleFrame(bool regenerate_layer_tree) { animator_->RequestFrame(regenerate_layer_tree); } void Engine::Render(std::unique_ptr<flow::LayerTree> layer_tree) { if (!layer_tree) return; SkISize frame_size = SkISize::Make(viewport_metrics_.physical_width, viewport_metrics_.physical_height); if (frame_size.isEmpty()) return; layer_tree->set_frame_size(frame_size); animator_->Render(std::move(layer_tree)); } void Engine::UpdateSemantics(blink::SemanticsNodeUpdates update, blink::CustomAccessibilityActionUpdates actions) { delegate_.OnEngineUpdateSemantics(std::move(update), std::move(actions)); } void Engine::HandlePlatformMessage( fml::RefPtr<blink::PlatformMessage> message) { if (message->channel() == kAssetChannel) { HandleAssetPlatformMessage(std::move(message)); } else { delegate_.OnEngineHandlePlatformMessage(std::move(message)); } } blink::FontCollection& Engine::GetFontCollection() { return font_collection_; } void Engine::HandleAssetPlatformMessage( fml::RefPtr<blink::PlatformMessage> message) { fml::RefPtr<blink::PlatformMessageResponse> response = message->response(); if (!response) { return; } const auto& data = message->data(); std::string asset_name(reinterpret_cast<const char*>(data.data()), data.size()); if (asset_manager_) { std::unique_ptr<fml::Mapping> asset_mapping = asset_manager_->GetAsMapping(asset_name); if (asset_mapping) { response->Complete(std::move(asset_mapping)); return; } } response->CompleteEmpty(); } } // namespace shell <|endoftext|>
<commit_before>/* * The Apache Software License, Version 1.1 * * * Copyright (c) 1999-2002 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xalan" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact [email protected]. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ #if !defined(XALAN_XALANTRANSFORMERPROBLEMLISTENER_HEADER_GUARD) #define XALAN_XALANTRANSFORMERPROBLEMLISTENER_HEADER_GUARD // Base include file. Must be first. #include "XalanTransformerDefinitions.hpp" // Xalan header files. #include <XSLT/ProblemListenerDefault.hpp> class XALAN_TRANSFORMER_EXPORT XalanTransformerProblemListener : public ProblemListener { public: XalanTransformerProblemListener( #if defined(XALAN_NO_NAMESPACES) ostream* theWarningStream, #else std::ostream* theWarningStream, #endif PrintWriter* thePrintWriter); virtual ~XalanTransformerProblemListener(); // These methods are inherited from ProblemListener ... virtual void setPrintWriter(PrintWriter* pw); virtual void problem( eProblemSource where, eClassification classification, const XalanNode* sourceNode, const XalanNode* styleNode, const XalanDOMString& msg, const XalanDOMChar* uri, int lineNo, int charOffset); private: ProblemListenerDefault m_problemListener; #if defined(XALAN_NO_NAMESPACES) ostream* m_warningStream; #else std::ostream* m_warningStream; #endif }; #endif // XALAN_XALANTRANSFORMERPROBLEMLISTENER_HEADER_GUARD <commit_msg>Fixed problem on HP 11 with -AA switch.<commit_after>/* * The Apache Software License, Version 1.1 * * * Copyright (c) 1999-2002 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xalan" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact [email protected]. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ #if !defined(XALAN_XALANTRANSFORMERPROBLEMLISTENER_HEADER_GUARD) #define XALAN_XALANTRANSFORMERPROBLEMLISTENER_HEADER_GUARD // Base include file. Must be first. #include "XalanTransformerDefinitions.hpp" #if defined(XALAN_OLD_STREAMS) class ostream; #else #include <iosfwd> #endif // Xalan header files. #include <XSLT/ProblemListenerDefault.hpp> class XALAN_TRANSFORMER_EXPORT XalanTransformerProblemListener : public ProblemListener { public: XalanTransformerProblemListener( #if defined(XALAN_NO_NAMESPACES) ostream* theWarningStream, #else std::ostream* theWarningStream, #endif PrintWriter* thePrintWriter); virtual ~XalanTransformerProblemListener(); // These methods are inherited from ProblemListener ... virtual void setPrintWriter(PrintWriter* pw); virtual void problem( eProblemSource where, eClassification classification, const XalanNode* sourceNode, const XalanNode* styleNode, const XalanDOMString& msg, const XalanDOMChar* uri, int lineNo, int charOffset); private: ProblemListenerDefault m_problemListener; #if defined(XALAN_NO_NAMESPACES) ostream* m_warningStream; #else std::ostream* m_warningStream; #endif }; #endif // XALAN_XALANTRANSFORMERPROBLEMLISTENER_HEADER_GUARD <|endoftext|>
<commit_before>/* * Copyright (C) 1999 Lars Knoll ([email protected]) * (C) 1999 Antti Koivisto ([email protected]) * (C) 2001 Dirk Mueller ([email protected]) * (C) 2006 Alexey Proskuryakov ([email protected]) * Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2012 Apple Inc. All rights reserved. * Copyright (C) 2008, 2009 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/) * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies) * Copyright (C) 2013 Google Inc. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "config.h" #include "core/dom/StyleSheetCollection.h" #include "core/css/CSSStyleSheet.h" #include "core/css/StyleInvalidationAnalysis.h" #include "core/css/StyleRuleImport.h" #include "core/css/StyleSheetContents.h" #include "core/css/resolver/StyleResolver.h" #include "core/dom/Document.h" #include "core/dom/Element.h" #include "core/dom/StyleEngine.h" #include "core/html/HTMLStyleElement.h" #include "core/page/Settings.h" namespace WebCore { StyleSheetCollectionBase::StyleSheetCollectionBase() { } StyleSheetCollectionBase::~StyleSheetCollectionBase() { } void StyleSheetCollectionBase::swap(StyleSheetCollectionBase& other) { m_styleSheetsForStyleSheetList.swap(other.m_styleSheetsForStyleSheetList); m_activeAuthorStyleSheets.swap(other.m_activeAuthorStyleSheets); } void StyleSheetCollectionBase::appendActiveStyleSheets(const Vector<RefPtr<CSSStyleSheet> >& sheets) { m_activeAuthorStyleSheets.append(sheets); } void StyleSheetCollectionBase::appendActiveStyleSheet(CSSStyleSheet* sheet) { m_activeAuthorStyleSheets.append(sheet); } void StyleSheetCollectionBase::appendSheetForList(StyleSheet* sheet) { m_styleSheetsForStyleSheetList.append(sheet); } StyleSheetCollection::StyleSheetCollection(TreeScope& treeScope) : m_treeScope(treeScope) , m_hadActiveLoadingStylesheet(false) , m_usesRemUnits(false) { } void StyleSheetCollection::addStyleSheetCandidateNode(Node* node, bool createdByParser) { if (!node->inDocument()) return; // Until the <body> exists, we have no choice but to compare document positions, // since styles outside of the body and head continue to be shunted into the head // (and thus can shift to end up before dynamically added DOM content that is also // outside the body). if (createdByParser && document()->body()) m_styleSheetCandidateNodes.parserAdd(node); else m_styleSheetCandidateNodes.add(node); if (!isHTMLStyleElement(node)) return; ContainerNode* scopingNode = toHTMLStyleElement(node)->scopingNode(); if (!isTreeScopeRoot(scopingNode)) m_scopingNodesForStyleScoped.add(scopingNode); } void StyleSheetCollection::removeStyleSheetCandidateNode(Node* node, ContainerNode* scopingNode) { m_styleSheetCandidateNodes.remove(node); if (!isTreeScopeRoot(scopingNode)) m_scopingNodesForStyleScoped.remove(scopingNode); } StyleSheetCollection::StyleResolverUpdateType StyleSheetCollection::compareStyleSheets(const Vector<RefPtr<CSSStyleSheet> >& oldStyleSheets, const Vector<RefPtr<CSSStyleSheet> >& newStylesheets, Vector<StyleSheetContents*>& addedSheets) { unsigned newStyleSheetCount = newStylesheets.size(); unsigned oldStyleSheetCount = oldStyleSheets.size(); ASSERT(newStyleSheetCount >= oldStyleSheetCount); if (!newStyleSheetCount) return Reconstruct; unsigned newIndex = 0; for (unsigned oldIndex = 0; oldIndex < oldStyleSheetCount; ++oldIndex) { while (oldStyleSheets[oldIndex] != newStylesheets[newIndex]) { addedSheets.append(newStylesheets[newIndex]->contents()); if (++newIndex == newStyleSheetCount) return Reconstruct; } if (++newIndex == newStyleSheetCount) return Reconstruct; } bool hasInsertions = !addedSheets.isEmpty(); while (newIndex < newStyleSheetCount) { addedSheets.append(newStylesheets[newIndex]->contents()); ++newIndex; } // If all new sheets were added at the end of the list we can just add them to existing StyleResolver. // If there were insertions we need to re-add all the stylesheets so rules are ordered correctly. return hasInsertions ? Reset : Additive; } bool StyleSheetCollection::activeLoadingStyleSheetLoaded(const Vector<RefPtr<CSSStyleSheet> >& newStyleSheets) { // StyleSheets of <style> elements that @import stylesheets are active but loading. We need to trigger a full recalc when such loads are done. bool hasActiveLoadingStylesheet = false; unsigned newStylesheetCount = newStyleSheets.size(); for (unsigned i = 0; i < newStylesheetCount; ++i) { if (newStyleSheets[i]->isLoading()) hasActiveLoadingStylesheet = true; } if (m_hadActiveLoadingStylesheet && !hasActiveLoadingStylesheet) { m_hadActiveLoadingStylesheet = false; return true; } m_hadActiveLoadingStylesheet = hasActiveLoadingStylesheet; return false; } static bool styleSheetContentsHasFontFaceRule(Vector<StyleSheetContents*> sheets) { for (unsigned i = 0; i < sheets.size(); ++i) { ASSERT(sheets[i]); if (sheets[i]->hasFontFaceRule()) return true; } return false; } static bool cssStyleSheetHasFontFaceRule(const Vector<RefPtr<CSSStyleSheet> > sheets) { for (unsigned i = 0; i < sheets.size(); ++i) { ASSERT(sheets[i]); if (sheets[i]->contents()->hasFontFaceRule()) return true; } return false; } void StyleSheetCollection::analyzeStyleSheetChange(StyleResolverUpdateMode updateMode, const StyleSheetCollectionBase& newCollection, StyleSheetChange& change) { if (activeLoadingStyleSheetLoaded(newCollection.activeAuthorStyleSheets())) return; if (updateMode != AnalyzedStyleUpdate) return; // Find out which stylesheets are new. Vector<StyleSheetContents*> addedSheets; if (m_activeAuthorStyleSheets.size() <= newCollection.activeAuthorStyleSheets().size()) { change.styleResolverUpdateType = compareStyleSheets(m_activeAuthorStyleSheets, newCollection.activeAuthorStyleSheets(), addedSheets); } else { StyleResolverUpdateType updateType = compareStyleSheets(newCollection.activeAuthorStyleSheets(), m_activeAuthorStyleSheets, addedSheets); if (updateType != Additive) { change.styleResolverUpdateType = updateType; } else { if (styleSheetContentsHasFontFaceRule(addedSheets)) { change.styleResolverUpdateType = ResetStyleResolverAndFontSelector; return; } // FIXME: since currently all stylesheets are re-added after reseting styleresolver, // fontSelector should be always reset. After creating RuleSet for each StyleSheetContents, // we can avoid appending all stylesheetcontents in reset case. // So we can remove "styleSheetContentsHasFontFaceRule(newSheets)". if (cssStyleSheetHasFontFaceRule(newCollection.activeAuthorStyleSheets())) change.styleResolverUpdateType = ResetStyleResolverAndFontSelector; else change.styleResolverUpdateType = Reset; } } // FIXME: If styleResolverUpdateType is Reconstruct, we should return early here since // we need to recalc the whole document. It's wrong to use StyleInvalidationAnalysis since // it only looks at the addedSheets. // If we are already parsing the body and so may have significant amount of elements, put some effort into trying to avoid style recalcs. if (!document()->body() || document()->hasNodesWithPlaceholderStyle()) return; StyleInvalidationAnalysis invalidationAnalysis(addedSheets); if (invalidationAnalysis.dirtiesAllStyle()) return; invalidationAnalysis.invalidateStyle(*document()); change.requiresFullStyleRecalc = false; return; } void StyleSheetCollection::clearMediaQueryRuleSetStyleSheets() { for (size_t i = 0; i < m_activeAuthorStyleSheets.size(); ++i) { StyleSheetContents* contents = m_activeAuthorStyleSheets[i]->contents(); if (contents->hasMediaQueries()) contents->clearRuleSet(); } } void StyleSheetCollection::resetAllRuleSetsInTreeScope(StyleResolver* styleResolver) { // FIXME: If many web developers use style scoped, implement reset RuleSets in per-scoping node manner. if (DocumentOrderedList* styleScopedScopingNodes = scopingNodesForStyleScoped()) { for (DocumentOrderedList::iterator it = styleScopedScopingNodes->begin(); it != styleScopedScopingNodes->end(); ++it) styleResolver->resetAuthorStyle(toContainerNode(*it)); } if (ListHashSet<Node*, 4>* removedNodes = scopingNodesRemoved()) { for (ListHashSet<Node*, 4>::iterator it = removedNodes->begin(); it != removedNodes->end(); ++it) styleResolver->resetAuthorStyle(toContainerNode(*it)); } styleResolver->resetAuthorStyle(toContainerNode(m_treeScope.rootNode())); } static bool styleSheetsUseRemUnits(const Vector<RefPtr<CSSStyleSheet> >& sheets) { for (unsigned i = 0; i < sheets.size(); ++i) { if (sheets[i]->contents()->usesRemUnits()) return true; } return false; } void StyleSheetCollection::updateUsesRemUnits() { m_usesRemUnits = styleSheetsUseRemUnits(m_activeAuthorStyleSheets); } } <commit_msg>Don't do StyleInvalidationAnalysis if we have a full document recalc pending.<commit_after>/* * Copyright (C) 1999 Lars Knoll ([email protected]) * (C) 1999 Antti Koivisto ([email protected]) * (C) 2001 Dirk Mueller ([email protected]) * (C) 2006 Alexey Proskuryakov ([email protected]) * Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2012 Apple Inc. All rights reserved. * Copyright (C) 2008, 2009 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/) * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies) * Copyright (C) 2013 Google Inc. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "config.h" #include "core/dom/StyleSheetCollection.h" #include "core/css/CSSStyleSheet.h" #include "core/css/StyleInvalidationAnalysis.h" #include "core/css/StyleRuleImport.h" #include "core/css/StyleSheetContents.h" #include "core/css/resolver/StyleResolver.h" #include "core/dom/Document.h" #include "core/dom/Element.h" #include "core/dom/StyleEngine.h" #include "core/html/HTMLStyleElement.h" #include "core/page/Settings.h" namespace WebCore { StyleSheetCollectionBase::StyleSheetCollectionBase() { } StyleSheetCollectionBase::~StyleSheetCollectionBase() { } void StyleSheetCollectionBase::swap(StyleSheetCollectionBase& other) { m_styleSheetsForStyleSheetList.swap(other.m_styleSheetsForStyleSheetList); m_activeAuthorStyleSheets.swap(other.m_activeAuthorStyleSheets); } void StyleSheetCollectionBase::appendActiveStyleSheets(const Vector<RefPtr<CSSStyleSheet> >& sheets) { m_activeAuthorStyleSheets.append(sheets); } void StyleSheetCollectionBase::appendActiveStyleSheet(CSSStyleSheet* sheet) { m_activeAuthorStyleSheets.append(sheet); } void StyleSheetCollectionBase::appendSheetForList(StyleSheet* sheet) { m_styleSheetsForStyleSheetList.append(sheet); } StyleSheetCollection::StyleSheetCollection(TreeScope& treeScope) : m_treeScope(treeScope) , m_hadActiveLoadingStylesheet(false) , m_usesRemUnits(false) { } void StyleSheetCollection::addStyleSheetCandidateNode(Node* node, bool createdByParser) { if (!node->inDocument()) return; // Until the <body> exists, we have no choice but to compare document positions, // since styles outside of the body and head continue to be shunted into the head // (and thus can shift to end up before dynamically added DOM content that is also // outside the body). if (createdByParser && document()->body()) m_styleSheetCandidateNodes.parserAdd(node); else m_styleSheetCandidateNodes.add(node); if (!isHTMLStyleElement(node)) return; ContainerNode* scopingNode = toHTMLStyleElement(node)->scopingNode(); if (!isTreeScopeRoot(scopingNode)) m_scopingNodesForStyleScoped.add(scopingNode); } void StyleSheetCollection::removeStyleSheetCandidateNode(Node* node, ContainerNode* scopingNode) { m_styleSheetCandidateNodes.remove(node); if (!isTreeScopeRoot(scopingNode)) m_scopingNodesForStyleScoped.remove(scopingNode); } StyleSheetCollection::StyleResolverUpdateType StyleSheetCollection::compareStyleSheets(const Vector<RefPtr<CSSStyleSheet> >& oldStyleSheets, const Vector<RefPtr<CSSStyleSheet> >& newStylesheets, Vector<StyleSheetContents*>& addedSheets) { unsigned newStyleSheetCount = newStylesheets.size(); unsigned oldStyleSheetCount = oldStyleSheets.size(); ASSERT(newStyleSheetCount >= oldStyleSheetCount); if (!newStyleSheetCount) return Reconstruct; unsigned newIndex = 0; for (unsigned oldIndex = 0; oldIndex < oldStyleSheetCount; ++oldIndex) { while (oldStyleSheets[oldIndex] != newStylesheets[newIndex]) { addedSheets.append(newStylesheets[newIndex]->contents()); if (++newIndex == newStyleSheetCount) return Reconstruct; } if (++newIndex == newStyleSheetCount) return Reconstruct; } bool hasInsertions = !addedSheets.isEmpty(); while (newIndex < newStyleSheetCount) { addedSheets.append(newStylesheets[newIndex]->contents()); ++newIndex; } // If all new sheets were added at the end of the list we can just add them to existing StyleResolver. // If there were insertions we need to re-add all the stylesheets so rules are ordered correctly. return hasInsertions ? Reset : Additive; } bool StyleSheetCollection::activeLoadingStyleSheetLoaded(const Vector<RefPtr<CSSStyleSheet> >& newStyleSheets) { // StyleSheets of <style> elements that @import stylesheets are active but loading. We need to trigger a full recalc when such loads are done. bool hasActiveLoadingStylesheet = false; unsigned newStylesheetCount = newStyleSheets.size(); for (unsigned i = 0; i < newStylesheetCount; ++i) { if (newStyleSheets[i]->isLoading()) hasActiveLoadingStylesheet = true; } if (m_hadActiveLoadingStylesheet && !hasActiveLoadingStylesheet) { m_hadActiveLoadingStylesheet = false; return true; } m_hadActiveLoadingStylesheet = hasActiveLoadingStylesheet; return false; } static bool styleSheetContentsHasFontFaceRule(Vector<StyleSheetContents*> sheets) { for (unsigned i = 0; i < sheets.size(); ++i) { ASSERT(sheets[i]); if (sheets[i]->hasFontFaceRule()) return true; } return false; } static bool cssStyleSheetHasFontFaceRule(const Vector<RefPtr<CSSStyleSheet> > sheets) { for (unsigned i = 0; i < sheets.size(); ++i) { ASSERT(sheets[i]); if (sheets[i]->contents()->hasFontFaceRule()) return true; } return false; } void StyleSheetCollection::analyzeStyleSheetChange(StyleResolverUpdateMode updateMode, const StyleSheetCollectionBase& newCollection, StyleSheetChange& change) { // No point in doing the analysis work if we're just going to recalc the whole document anyways. if (document()->hasPendingForcedStyleRecalc()) return; if (activeLoadingStyleSheetLoaded(newCollection.activeAuthorStyleSheets())) return; if (updateMode != AnalyzedStyleUpdate) return; // Find out which stylesheets are new. Vector<StyleSheetContents*> addedSheets; if (m_activeAuthorStyleSheets.size() <= newCollection.activeAuthorStyleSheets().size()) { change.styleResolverUpdateType = compareStyleSheets(m_activeAuthorStyleSheets, newCollection.activeAuthorStyleSheets(), addedSheets); } else { StyleResolverUpdateType updateType = compareStyleSheets(newCollection.activeAuthorStyleSheets(), m_activeAuthorStyleSheets, addedSheets); if (updateType != Additive) { change.styleResolverUpdateType = updateType; } else { if (styleSheetContentsHasFontFaceRule(addedSheets)) { change.styleResolverUpdateType = ResetStyleResolverAndFontSelector; return; } // FIXME: since currently all stylesheets are re-added after reseting styleresolver, // fontSelector should be always reset. After creating RuleSet for each StyleSheetContents, // we can avoid appending all stylesheetcontents in reset case. // So we can remove "styleSheetContentsHasFontFaceRule(newSheets)". if (cssStyleSheetHasFontFaceRule(newCollection.activeAuthorStyleSheets())) change.styleResolverUpdateType = ResetStyleResolverAndFontSelector; else change.styleResolverUpdateType = Reset; } } // FIXME: If styleResolverUpdateType is Reconstruct, we should return early here since // we need to recalc the whole document. It's wrong to use StyleInvalidationAnalysis since // it only looks at the addedSheets. // If we are already parsing the body and so may have significant amount of elements, put some effort into trying to avoid style recalcs. if (!document()->body() || document()->hasNodesWithPlaceholderStyle()) return; StyleInvalidationAnalysis invalidationAnalysis(addedSheets); if (invalidationAnalysis.dirtiesAllStyle()) return; invalidationAnalysis.invalidateStyle(*document()); change.requiresFullStyleRecalc = false; return; } void StyleSheetCollection::clearMediaQueryRuleSetStyleSheets() { for (size_t i = 0; i < m_activeAuthorStyleSheets.size(); ++i) { StyleSheetContents* contents = m_activeAuthorStyleSheets[i]->contents(); if (contents->hasMediaQueries()) contents->clearRuleSet(); } } void StyleSheetCollection::resetAllRuleSetsInTreeScope(StyleResolver* styleResolver) { // FIXME: If many web developers use style scoped, implement reset RuleSets in per-scoping node manner. if (DocumentOrderedList* styleScopedScopingNodes = scopingNodesForStyleScoped()) { for (DocumentOrderedList::iterator it = styleScopedScopingNodes->begin(); it != styleScopedScopingNodes->end(); ++it) styleResolver->resetAuthorStyle(toContainerNode(*it)); } if (ListHashSet<Node*, 4>* removedNodes = scopingNodesRemoved()) { for (ListHashSet<Node*, 4>::iterator it = removedNodes->begin(); it != removedNodes->end(); ++it) styleResolver->resetAuthorStyle(toContainerNode(*it)); } styleResolver->resetAuthorStyle(toContainerNode(m_treeScope.rootNode())); } static bool styleSheetsUseRemUnits(const Vector<RefPtr<CSSStyleSheet> >& sheets) { for (unsigned i = 0; i < sheets.size(); ++i) { if (sheets[i]->contents()->usesRemUnits()) return true; } return false; } void StyleSheetCollection::updateUsesRemUnits() { m_usesRemUnits = styleSheetsUseRemUnits(m_activeAuthorStyleSheets); } } <|endoftext|>
<commit_before>/* * Jamoma TTNode Tree * Copyright © 2008, Tim Place * * License: This code is licensed under the terms of the GNU LGPL * http://www.gnu.org/licenses/lgpl.html */ #include "NodeLib.h" TTTreePtr jamoma_tree = NULL; /*********************************************************************************** * * C EXTERN METHODS * ************************************************************************************/ // Method to deal with the jamoma tree ///////////////////////////////////////// TTTreePtr jamoma_tree_init() { if(jamoma_tree) return jamoma_tree; // already have a tree, just return the pointer to the tree... jamoma_tree = new TTTree(TT("Jamoma")); return jamoma_tree; } JamomaError jamoma_tree_free(void) { if(jamoma_tree){ jamoma_tree->~TTTree(); return JAMOMA_ERR_NONE; } post("jamoma_tree_free : create a tree before"); return JAMOMA_ERR_GENERIC; } JamomaError jamoma_tree_dump(void) { unsigned int i; TTValue *hk; TTSymbolPtr key; if(jamoma_tree){ hk = new TTValue(); jamoma_tree->getDirectory()->getKeys(*hk); for(i=0; i<jamoma_tree->getDirectory()->getSize(); i++){ hk->get(i,(TTSymbol**)&key); post("%s",key->getCString()); } return JAMOMA_ERR_NONE; } post("jamoma_tree_dump : create a tree before"); return JAMOMA_ERR_GENERIC; } JamomaError jamoma_tree_register(t_symbol *OSCaddress, t_symbol *type, t_object *obj, TTNodePtr *newNode, bool *newInstanceCreated) { if(jamoma_tree){ jamoma_tree->NodeCreate(TT(OSCaddress->s_name), TT(type->s_name), obj, newNode, (TTBoolean *)newInstanceCreated); return JAMOMA_ERR_NONE; } post("jamoma_tree_register %s : create a tree before", OSCaddress->s_name); return JAMOMA_ERR_GENERIC; } JamomaError jamoma_tree_unregister(t_symbol *OSCaddress) { TTNodePtr node = NULL; if(jamoma_tree){ jamoma_tree->getNodeForOSC(OSCaddress->s_name, &node); } else{ post("jamoma_tree_unregister %s : create a tree before", OSCaddress->s_name); return JAMOMA_ERR_GENERIC; } if(node){ node->~TTNode(); return JAMOMA_ERR_NONE; } post("jamoma_tree_unregister %s : this address doesn't exist", OSCaddress->s_name); return JAMOMA_ERR_GENERIC; } JamomaError jamoma_tree_get_node(t_symbol *address, TTListPtr *returnedNodes, TTNodePtr *firstReturnedNode) { TTErr err; if(jamoma_tree){ err = jamoma_tree->Lookup(TT(address->s_name), returnedNodes, firstReturnedNode); if(err == kTTErrNone) return JAMOMA_ERR_NONE; else return JAMOMA_ERR_GENERIC; } post("jamoma_tree_get_node %s : create a tree before"); return JAMOMA_ERR_GENERIC; } // Method to deal with a node //////////////////////////////////// t_symbol * jamoma_node_name(TTNodePtr node) { return gensym((char*)node->getName()->getCString()); } t_symbol * jamoma_node_set_name(TTNodePtr node, t_symbol *name) { TTSymbolPtr newInstance; TTBoolean *newInstanceCreated = new TTBoolean(false); node->setName(TT(name->s_name), &newInstance, newInstanceCreated); if(*newInstanceCreated) return gensym((char*)newInstance->getCString()); return NULL; } t_symbol * jamoma_node_instance(TTNodePtr node) { return gensym((char*)node->getInstance()->getCString()); } t_symbol * jamoma_node_set_instance(TTNodePtr node, t_symbol *instance) { TTSymbolPtr newInstance; TTBoolean *newInstanceCreated = new TTBoolean(false); node->setInstance(TT(instance->s_name), &newInstance, newInstanceCreated); if(*newInstanceCreated) return gensym((char*)newInstance->getCString()); return NULL; } t_symbol * jamoma_node_type(TTNodePtr node) { return gensym((char*)node->getType()->getCString()); } TTListPtr jamoma_node_children(TTNodePtr node) { TTListPtr lk_children; TTErr err; err = node->getChildren(TT(S_WILDCARD),TT(S_WILDCARD), &lk_children); if(err == kTTErrNone) return lk_children; else return NULL; } t_object * jamoma_node_max_object(TTNodePtr node) { return (t_object*)node->getObject(); } TTListPtr jamoma_node_properties(TTNodePtr node) { uint i; TTValue *hk; TTSymbolPtr key; TTValue *c; TTListPtr lk_properties; // if there are properties if(node->getProperties()->getSize()){ hk = new TTValue(); c = new TTValue(); node->getProperties()->getKeys(*hk); lk_properties = new TTList(); // for each propertie for(i=0; i<node->getProperties()->getSize(); i++){ hk->get(i,(TTSymbol**)&key); // add the propertie to the linklist lk_properties->append(new TTValue((TTSymbolPtr)key)); } return lk_properties; } return NULL; } JamomaError jamoma_node_set_properties(TTNodePtr node, t_symbol *propertie) { TTErr err; err = node->setProperties(TT(propertie->s_name)); if(err == kTTErrNone) return JAMOMA_ERR_NONE; return JAMOMA_ERR_GENERIC; } <commit_msg>NodeLib: fixed memory leak in jamoma_tree_dump(). The 'new TTValue' was not matched by a 'delete TTValue'. I changed from allocating off the heap to allocating the TTValue on the stack, which consequently means we don't have to explicitly free it.<commit_after>/* * Jamoma TTNode Tree * Copyright © 2008, Tim Place * * License: This code is licensed under the terms of the GNU LGPL * http://www.gnu.org/licenses/lgpl.html */ #include "NodeLib.h" TTTreePtr jamoma_tree = NULL; /*********************************************************************************** * * C EXTERN METHODS * ************************************************************************************/ // Method to deal with the jamoma tree ///////////////////////////////////////// TTTreePtr jamoma_tree_init() { if(jamoma_tree) return jamoma_tree; // already have a tree, just return the pointer to the tree... jamoma_tree = new TTTree(TT("Jamoma")); return jamoma_tree; } JamomaError jamoma_tree_free(void) { if(jamoma_tree){ jamoma_tree->~TTTree(); return JAMOMA_ERR_NONE; } post("jamoma_tree_free : create a tree before"); return JAMOMA_ERR_GENERIC; } JamomaError jamoma_tree_dump(void) { unsigned int i; TTValue hk; TTSymbolPtr key; if(jamoma_tree){ jamoma_tree->getDirectory()->getKeys(hk); for(i=0; i<jamoma_tree->getDirectory()->getSize(); i++){ hk.get(i,(TTSymbol**)&key); post("%s",key->getCString()); } return JAMOMA_ERR_NONE; } post("jamoma_tree_dump : create a tree before"); return JAMOMA_ERR_GENERIC; } JamomaError jamoma_tree_register(t_symbol *OSCaddress, t_symbol *type, t_object *obj, TTNodePtr *newNode, bool *newInstanceCreated) { if(jamoma_tree){ jamoma_tree->NodeCreate(TT(OSCaddress->s_name), TT(type->s_name), obj, newNode, (TTBoolean *)newInstanceCreated); return JAMOMA_ERR_NONE; } post("jamoma_tree_register %s : create a tree before", OSCaddress->s_name); return JAMOMA_ERR_GENERIC; } JamomaError jamoma_tree_unregister(t_symbol *OSCaddress) { TTNodePtr node = NULL; if(jamoma_tree){ jamoma_tree->getNodeForOSC(OSCaddress->s_name, &node); } else{ post("jamoma_tree_unregister %s : create a tree before", OSCaddress->s_name); return JAMOMA_ERR_GENERIC; } if(node){ node->~TTNode(); return JAMOMA_ERR_NONE; } post("jamoma_tree_unregister %s : this address doesn't exist", OSCaddress->s_name); return JAMOMA_ERR_GENERIC; } JamomaError jamoma_tree_get_node(t_symbol *address, TTListPtr *returnedNodes, TTNodePtr *firstReturnedNode) { TTErr err; if(jamoma_tree){ err = jamoma_tree->Lookup(TT(address->s_name), returnedNodes, firstReturnedNode); if(err == kTTErrNone) return JAMOMA_ERR_NONE; else return JAMOMA_ERR_GENERIC; } post("jamoma_tree_get_node %s : create a tree before"); return JAMOMA_ERR_GENERIC; } // Method to deal with a node //////////////////////////////////// t_symbol * jamoma_node_name(TTNodePtr node) { return gensym((char*)node->getName()->getCString()); } t_symbol * jamoma_node_set_name(TTNodePtr node, t_symbol *name) { TTSymbolPtr newInstance; TTBoolean *newInstanceCreated = new TTBoolean(false); node->setName(TT(name->s_name), &newInstance, newInstanceCreated); if(*newInstanceCreated) return gensym((char*)newInstance->getCString()); return NULL; } t_symbol * jamoma_node_instance(TTNodePtr node) { return gensym((char*)node->getInstance()->getCString()); } t_symbol * jamoma_node_set_instance(TTNodePtr node, t_symbol *instance) { TTSymbolPtr newInstance; TTBoolean *newInstanceCreated = new TTBoolean(false); node->setInstance(TT(instance->s_name), &newInstance, newInstanceCreated); if(*newInstanceCreated) return gensym((char*)newInstance->getCString()); return NULL; } t_symbol * jamoma_node_type(TTNodePtr node) { return gensym((char*)node->getType()->getCString()); } TTListPtr jamoma_node_children(TTNodePtr node) { TTListPtr lk_children; TTErr err; err = node->getChildren(TT(S_WILDCARD),TT(S_WILDCARD), &lk_children); if(err == kTTErrNone) return lk_children; else return NULL; } t_object * jamoma_node_max_object(TTNodePtr node) { return (t_object*)node->getObject(); } TTListPtr jamoma_node_properties(TTNodePtr node) { uint i; TTValue *hk; TTSymbolPtr key; TTValue *c; TTListPtr lk_properties; // if there are properties if(node->getProperties()->getSize()){ hk = new TTValue(); c = new TTValue(); node->getProperties()->getKeys(*hk); lk_properties = new TTList(); // for each propertie for(i=0; i<node->getProperties()->getSize(); i++){ hk->get(i,(TTSymbol**)&key); // add the propertie to the linklist lk_properties->append(new TTValue((TTSymbolPtr)key)); } return lk_properties; } return NULL; } JamomaError jamoma_node_set_properties(TTNodePtr node, t_symbol *propertie) { TTErr err; err = node->setProperties(TT(propertie->s_name)); if(err == kTTErrNone) return JAMOMA_ERR_NONE; return JAMOMA_ERR_GENERIC; } <|endoftext|>
<commit_before>#include "stdafx.h" #include "Sprite.h" Sprite::Sprite(std::string resLocation) { } Sprite::Sprite() { sourceImage = nullptr; GenErrorImage(); } Sprite::~Sprite() { al_destroy_bitmap(sourceImage); } /* This makes a blue square with a yellow triangle inside that has an exclamation mark. This image is used anytime an image file on disk fails to load. --------------- | ^ | | / \ | | / ! \ | <- Kinda like this... | / \ | | ------- | --------------- */ bool Sprite::GenErrorImage() { sourceImage = al_create_bitmap(frameWidth, frameHeight); if (sourceImage == nullptr) return false; ALLEGRO_COLOR background = al_color_html("#3f51b5"); ALLEGRO_COLOR shadow = al_color_html("#1a237e"); ALLEGRO_COLOR sign = al_color_html("#ffeb3b"); float w = frameWidth; float h = frameHeight; al_set_target_bitmap(sourceImage); al_clear_to_color(background); // Shadow (3 triangles) al_draw_filled_triangle(w / 2.0, h / 4.0, w, (h * 3.0) / 4.0, w / 2.0, h, shadow); al_draw_filled_triangle(w, (h * 3.0) / 4.0, w, h, w / 2.0, h, shadow); al_draw_filled_triangle(w / 2.0, h / 4.0, w / 2.0, h, w / 4.0, (h * 3.0) / 4.0, shadow); // Alert sign triangle al_draw_filled_triangle(w / 2.0, h / 4.0, ((w * 3.0) / 4), ((h * 3.0) / 4.0), w / 4.0, ((h * 3.0) / 4.0), sign); // Exclamation point al_draw_filled_rectangle((w * 15.0) / 32.0, ((h * 14.0) / 32.0), ((w * 17.0) / 32.0), ((h * 19.0) / 32.0), background); al_draw_filled_rectangle((w * 15.0) / 32.0, (h * 5.0) / 8, (w * 17.0) / 32.0, (h * 11.0) / 16.0, background); al_set_target_backbuffer(al_get_current_display()); return true; } void Sprite::fallbackToDefaultADF(std::string resLoc) { std::cerr << "Error: ADF file " << resLoc << " not found!, fallback to errorImage" << std::endl; frameWidth = 30; frameHeight = 30; frameDelay = 1; GenErrorImage(); rows = 30 / frameHeight; columns = 30 / frameWidth; frames = rows * columns; animList.emplace_front(AnimState::IDLE, 0, 1); return; } void Sprite::parseADF(std::string resLoc) { const std::string sections [] = { "", "IDLE", "MOVE", "ATTACK0", "ATTACK1", "HARMED", "SPECIAL0", "SPECIAL1" }; const std::string entries [] = { "resPath", "frameWidth", "frameHeight", "frameDelay", "startCol", "sides" }; ALLEGRO_CONFIG *file = al_load_config_file(resLoc.c_str()); if (file == nullptr) { fallbackToDefaultADF(resLoc); return; } ALLEGRO_CONFIG_SECTION *section = nullptr; ALLEGRO_CONFIG_ENTRY *entry = nullptr; const char *sectionName = nullptr; const char *entryName = nullptr; sectionName = al_get_first_config_section(file, &section); while (section != nullptr) { entryName = al_get_first_config_entry(file, sectionName, &entry); while (entry != nullptr) { if (sectionName == sections[0]) // Global section { if (entryName == entries[0]) { sourceImgPath = al_get_config_value(file, sectionName, entryName); } else if (entryName == entries[1]) { frameWidth = std::atoi(al_get_config_value(file, sectionName, entryName)); } else if (entryName == entries[2]) { frameHeight = std::atoi(al_get_config_value(file, sectionName, entryName)); } else if (entryName == entries[3]) { frameDelay = std::atoi(al_get_config_value(file, sectionName, entryName)); } else { std::cerr << "Warning: Unknown key-pair value: " << sectionName << "=" << entryName << std::endl; } } entryName = al_get_next_config_entry(&entry); } sectionName = al_get_next_config_section(&section); } } <commit_msg>Partial ADF file parser<commit_after>#include "stdafx.h" #include "Sprite.h" Sprite::Sprite(std::string resLocation) { } Sprite::Sprite() { sourceImage = nullptr; GenErrorImage(); } Sprite::~Sprite() { al_destroy_bitmap(sourceImage); } /* This makes a blue square with a yellow triangle inside that has an exclamation mark. This image is used anytime an image file on disk fails to load. --------------- | ^ | | / \ | | / ! \ | <- Kinda like this... | / \ | | ------- | --------------- */ bool Sprite::GenErrorImage() { sourceImage = al_create_bitmap(frameWidth, frameHeight); if (sourceImage == nullptr) return false; ALLEGRO_COLOR background = al_color_html("#3f51b5"); ALLEGRO_COLOR shadow = al_color_html("#1a237e"); ALLEGRO_COLOR sign = al_color_html("#ffeb3b"); float w = frameWidth; float h = frameHeight; al_set_target_bitmap(sourceImage); al_clear_to_color(background); // Shadow (3 triangles) al_draw_filled_triangle(w / 2.0, h / 4.0, w, (h * 3.0) / 4.0, w / 2.0, h, shadow); al_draw_filled_triangle(w, (h * 3.0) / 4.0, w, h, w / 2.0, h, shadow); al_draw_filled_triangle(w / 2.0, h / 4.0, w / 2.0, h, w / 4.0, (h * 3.0) / 4.0, shadow); // Alert sign triangle al_draw_filled_triangle(w / 2.0, h / 4.0, ((w * 3.0) / 4), ((h * 3.0) / 4.0), w / 4.0, ((h * 3.0) / 4.0), sign); // Exclamation point al_draw_filled_rectangle((w * 15.0) / 32.0, ((h * 14.0) / 32.0), ((w * 17.0) / 32.0), ((h * 19.0) / 32.0), background); al_draw_filled_rectangle((w * 15.0) / 32.0, (h * 5.0) / 8, (w * 17.0) / 32.0, (h * 11.0) / 16.0, background); al_set_target_backbuffer(al_get_current_display()); return true; } void Sprite::fallbackToDefaultADF(std::string resLoc) { std::cerr << "Error: ADF file " << resLoc << " not found!, fallback to errorImage" << std::endl; frameWidth = 30; frameHeight = 30; frameDelay = 1; GenErrorImage(); rows = 30 / frameHeight; columns = 30 / frameWidth; frames = rows * columns; animList.emplace_front(AnimState::IDLE, 0, 1); return; } void Sprite::parseADF(std::string resLoc) { const std::string sections [] = { "", "IDLE", "MOVE", "ATTACK0", "ATTACK1", "HARMED", "SPECIAL0", "SPECIAL1" }; const std::string entries [] = { "resPath", "frameWidth", "frameHeight", "frameDelay", "startCol", "sides" }; ALLEGRO_CONFIG *file = al_load_config_file(resLoc.c_str()); if (file == nullptr) { fallbackToDefaultADF(resLoc); return; } ALLEGRO_CONFIG_SECTION *section = nullptr; ALLEGRO_CONFIG_ENTRY *entry = nullptr; const char *sectionName = nullptr; const char *entryName = nullptr; sectionName = al_get_first_config_section(file, &section); while (section != nullptr) { entryName = al_get_first_config_entry(file, sectionName, &entry); while (entry != nullptr) { if (sectionName == sections[0]) // Global section { if (entryName == entries[0]) { sourceImgPath = al_get_config_value(file, sectionName, entryName); } else if (entryName == entries[1]) { frameWidth = std::atoi(al_get_config_value(file, sectionName, entryName)); } else if (entryName == entries[2]) { frameHeight = std::atoi(al_get_config_value(file, sectionName, entryName)); } else if (entryName == entries[3]) { frameDelay = std::atoi(al_get_config_value(file, sectionName, entryName)); } else { std::cerr << "Warning: Unknown key-pair value: " << sectionName << "=" << entryName << std::endl; } entryName = al_get_next_config_entry(&entry); continue; } else // All other sections { entryName = al_get_next_config_entry(&entry); continue; } } sectionName = al_get_next_config_section(&section); } } <|endoftext|>
<commit_before>#include "android_vulkan_context_factory.hpp" #include "com/mapswithme/platform/Platform.hpp" #include "drape/drape_diagnostics.hpp" #include "drape/vulkan/vulkan_pipeline.hpp" #include "drape/vulkan/vulkan_utils.hpp" #include "base/assert.hpp" #include "base/logging.hpp" #include "base/macros.hpp" #include "base/src_point.hpp" #include <array> #include <vector> namespace android { namespace { class DrawVulkanContext : public dp::vulkan::VulkanBaseContext { public: DrawVulkanContext(VkInstance vulkanInstance, VkPhysicalDevice gpu, VkPhysicalDeviceProperties const & gpuProperties, VkDevice device, uint32_t renderingQueueFamilyIndex, ref_ptr<dp::vulkan::VulkanObjectManager> objectManager, int appVersionCode) : dp::vulkan::VulkanBaseContext(vulkanInstance, gpu, gpuProperties, device, renderingQueueFamilyIndex, objectManager, make_unique_dp<dp::vulkan::VulkanPipeline>( device, appVersionCode)) { VkQueue queue; vkGetDeviceQueue(device, renderingQueueFamilyIndex, 0, &queue); SetRenderingQueue(queue); CreateCommandPool(); } void MakeCurrent() override { m_objectManager->RegisterThread(dp::vulkan::VulkanObjectManager::Frontend); } }; class UploadVulkanContext : public dp::vulkan::VulkanBaseContext { public: UploadVulkanContext(VkInstance vulkanInstance, VkPhysicalDevice gpu, VkPhysicalDeviceProperties const & gpuProperties, VkDevice device, uint32_t renderingQueueFamilyIndex, ref_ptr<dp::vulkan::VulkanObjectManager> objectManager) : dp::vulkan::VulkanBaseContext(vulkanInstance, gpu, gpuProperties, device, renderingQueueFamilyIndex, objectManager, nullptr /* pipeline */) {} void MakeCurrent() override { m_objectManager->RegisterThread(dp::vulkan::VulkanObjectManager::Backend); } void Present() override {} void Resize(int w, int h) override {} void SetFramebuffer(ref_ptr<dp::BaseFramebuffer> framebuffer) override {} void Init(dp::ApiVersion apiVersion) override { CHECK_EQUAL(apiVersion, dp::ApiVersion::Vulkan, ()); } void SetClearColor(dp::Color const & color) override {} void Clear(uint32_t clearBits, uint32_t storeBits) override {} void Flush() override {} void SetDepthTestEnabled(bool enabled) override {} void SetDepthTestFunction(dp::TestFunction depthFunction) override {} void SetStencilTestEnabled(bool enabled) override {} void SetStencilFunction(dp::StencilFace face, dp::TestFunction stencilFunction) override {} void SetStencilActions(dp::StencilFace face, dp::StencilAction stencilFailAction, dp::StencilAction depthFailAction, dp::StencilAction passAction) override {} }; } // namespace AndroidVulkanContextFactory::AndroidVulkanContextFactory(int appVersionCode) { if (InitVulkan() == 0) { LOG_ERROR_VK("Could not initialize Vulkan library."); return; } VkApplicationInfo appInfo = {}; appInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO; appInfo.pNext = nullptr; appInfo.apiVersion = VK_MAKE_VERSION(1, 0, 0); appInfo.applicationVersion = static_cast<uint32_t>(appVersionCode); appInfo.engineVersion = static_cast<uint32_t>(appVersionCode); appInfo.pApplicationName = "MAPS.ME"; appInfo.pEngineName = "Drape Engine"; bool enableDiagnostics = false; #ifdef ENABLE_VULKAN_DIAGNOSTICS enableDiagnostics = true; #endif m_layers = make_unique_dp<dp::vulkan::Layers>(enableDiagnostics); VkInstanceCreateInfo instanceCreateInfo = {}; instanceCreateInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO; instanceCreateInfo.pNext = nullptr; instanceCreateInfo.pApplicationInfo = &appInfo; instanceCreateInfo.enabledExtensionCount = m_layers->GetInstanceExtensionsCount(); instanceCreateInfo.ppEnabledExtensionNames = m_layers->GetInstanceExtensions(); instanceCreateInfo.enabledLayerCount = m_layers->GetInstanceLayersCount(); instanceCreateInfo.ppEnabledLayerNames = m_layers->GetInstanceLayers(); VkResult statusCode; statusCode = vkCreateInstance(&instanceCreateInfo, nullptr, &m_vulkanInstance); if (statusCode != VK_SUCCESS) { LOG_ERROR_VK_CALL(vkCreateInstance, statusCode); return; } uint32_t gpuCount = 0; statusCode = vkEnumeratePhysicalDevices(m_vulkanInstance, &gpuCount, nullptr); if (statusCode != VK_SUCCESS || gpuCount == 0) { LOG_ERROR_VK_CALL(vkEnumeratePhysicalDevices, statusCode); return; } VkPhysicalDevice tmpGpus[gpuCount]; statusCode = vkEnumeratePhysicalDevices(m_vulkanInstance, &gpuCount, tmpGpus); if (statusCode != VK_SUCCESS) { LOG_ERROR_VK_CALL(vkEnumeratePhysicalDevices, statusCode); return; } m_gpu = tmpGpus[0]; uint32_t queueFamilyCount; vkGetPhysicalDeviceQueueFamilyProperties(m_gpu, &queueFamilyCount, nullptr); if (queueFamilyCount == 0) { LOG_ERROR_VK("Any queue family wasn't found."); return; } std::vector<VkQueueFamilyProperties> queueFamilyProperties(queueFamilyCount); vkGetPhysicalDeviceQueueFamilyProperties(m_gpu, &queueFamilyCount, queueFamilyProperties.data()); uint32_t renderingQueueFamilyIndex = 0; for (; renderingQueueFamilyIndex < queueFamilyCount; ++renderingQueueFamilyIndex) { if (queueFamilyProperties[renderingQueueFamilyIndex].queueFlags & VK_QUEUE_GRAPHICS_BIT) break; } if (renderingQueueFamilyIndex == queueFamilyCount) { LOG_ERROR_VK("Any queue family with VK_QUEUE_GRAPHICS_BIT wasn't found."); return; } if (!dp::vulkan::VulkanFormatUnpacker::Init(m_gpu)) return; if (!m_layers->Initialize(m_vulkanInstance, m_gpu)) return; float priorities[] = {1.0f}; VkDeviceQueueCreateInfo queueCreateInfo = {}; queueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO; queueCreateInfo.pNext = nullptr; queueCreateInfo.flags = 0; queueCreateInfo.queueCount = 1; queueCreateInfo.queueFamilyIndex = renderingQueueFamilyIndex; queueCreateInfo.pQueuePriorities = priorities; VkDeviceCreateInfo deviceCreateInfo = {}; VkPhysicalDeviceFeatures enabledFeatures = {}; deviceCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO; deviceCreateInfo.pNext = nullptr; deviceCreateInfo.queueCreateInfoCount = 1; deviceCreateInfo.pQueueCreateInfos = &queueCreateInfo; deviceCreateInfo.enabledLayerCount = m_layers->GetDeviceLayersCount(); deviceCreateInfo.ppEnabledLayerNames = m_layers->GetDeviceLayers(); deviceCreateInfo.enabledExtensionCount = m_layers->GetDeviceExtensionsCount(); deviceCreateInfo.ppEnabledExtensionNames = m_layers->GetDeviceExtensions(); deviceCreateInfo.pEnabledFeatures = nullptr; if (enableDiagnostics) { enabledFeatures.robustBufferAccess = VK_TRUE; deviceCreateInfo.pEnabledFeatures = &enabledFeatures; } statusCode = vkCreateDevice(m_gpu, &deviceCreateInfo, nullptr, &m_device); if (statusCode != VK_SUCCESS) { LOG_ERROR_VK_CALL(vkCreateDevice, statusCode); return; } VkPhysicalDeviceProperties gpuProperties; vkGetPhysicalDeviceProperties(m_gpu, &gpuProperties); VkPhysicalDeviceMemoryProperties memoryProperties; vkGetPhysicalDeviceMemoryProperties(m_gpu, &memoryProperties); m_objectManager = make_unique_dp<dp::vulkan::VulkanObjectManager>(m_device, gpuProperties.limits, memoryProperties, renderingQueueFamilyIndex); m_drawContext = make_unique_dp<DrawVulkanContext>(m_vulkanInstance, m_gpu, gpuProperties, m_device, renderingQueueFamilyIndex, make_ref(m_objectManager), appVersionCode); m_uploadContext = make_unique_dp<UploadVulkanContext>(m_vulkanInstance, m_gpu, gpuProperties, m_device, renderingQueueFamilyIndex, make_ref(m_objectManager)); } AndroidVulkanContextFactory::~AndroidVulkanContextFactory() { m_drawContext.reset(); m_uploadContext.reset(); m_objectManager.reset(); if (m_device != nullptr) { vkDeviceWaitIdle(m_device); vkDestroyDevice(m_device, nullptr); } if (m_vulkanInstance != nullptr) { m_layers->Uninitialize(m_vulkanInstance); vkDestroyInstance(m_vulkanInstance, nullptr); } } void AndroidVulkanContextFactory::SetSurface(JNIEnv * env, jobject jsurface) { if (!jsurface) { LOG_ERROR_VK("Java surface is not found."); return; } m_nativeWindow = ANativeWindow_fromSurface(env, jsurface); if (!m_nativeWindow) { LOG_ERROR_VK("Can't get native window from Java surface."); return; } SetVulkanSurface(); } void AndroidVulkanContextFactory::SetVulkanSurface() { if (m_windowSurfaceValid) return; VkAndroidSurfaceCreateInfoKHR createInfo = {}; createInfo.sType = VK_STRUCTURE_TYPE_ANDROID_SURFACE_CREATE_INFO_KHR; createInfo.pNext = nullptr; createInfo.flags = 0; createInfo.window = m_nativeWindow; VkResult statusCode; statusCode = vkCreateAndroidSurfaceKHR(m_vulkanInstance, &createInfo, nullptr, &m_surface); if (statusCode != VK_SUCCESS) { LOG_ERROR_VK_CALL(vkCreateAndroidSurfaceKHR, statusCode); return; } uint32_t const renderingQueueIndex = m_drawContext->GetRenderingQueueFamilyIndex(); VkBool32 supportsPresent; statusCode = vkGetPhysicalDeviceSurfaceSupportKHR(m_gpu, renderingQueueIndex, m_surface, &supportsPresent); if (statusCode != VK_SUCCESS) { LOG_ERROR_VK_CALL(vkGetPhysicalDeviceSurfaceSupportKHR, statusCode); return; } CHECK_EQUAL(supportsPresent, VK_TRUE, ()); CHECK(QuerySurfaceSize(), ()); if (m_drawContext) m_drawContext->SetSurface(m_surface, m_surfaceFormat, m_surfaceCapabilities); m_windowSurfaceValid = true; } bool AndroidVulkanContextFactory::QuerySurfaceSize() { auto statusCode = vkGetPhysicalDeviceSurfaceCapabilitiesKHR(m_gpu, m_surface, &m_surfaceCapabilities); if (statusCode != VK_SUCCESS) { LOG_ERROR_VK_CALL(vkGetPhysicalDeviceSurfaceCapabilitiesKHR, statusCode); return false; } uint32_t formatCount = 0; statusCode = vkGetPhysicalDeviceSurfaceFormatsKHR(m_gpu, m_surface, &formatCount, nullptr); if (statusCode != VK_SUCCESS) { LOG_ERROR_VK_CALL(vkGetPhysicalDeviceSurfaceFormatsKHR, statusCode); return false; } std::vector<VkSurfaceFormatKHR> formats(formatCount); statusCode = vkGetPhysicalDeviceSurfaceFormatsKHR(m_gpu, m_surface, &formatCount, formats.data()); if (statusCode != VK_SUCCESS) { LOG_ERROR_VK_CALL(vkGetPhysicalDeviceSurfaceFormatsKHR, statusCode); return false; } uint32_t chosenFormat; for (chosenFormat = 0; chosenFormat < formatCount; chosenFormat++) { if (formats[chosenFormat].format == VK_FORMAT_R8G8B8A8_UNORM) break; } if (chosenFormat == formatCount) { LOG_ERROR_VK("Any supported surface format wasn't found."); return false; } if (!(m_surfaceCapabilities.supportedCompositeAlpha & VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR)) { LOG_ERROR_VK("Alpha channel is not supported."); return false; } m_surfaceFormat = formats[chosenFormat]; m_surfaceWidth = static_cast<int>(m_surfaceCapabilities.currentExtent.width); m_surfaceHeight = static_cast<int>(m_surfaceCapabilities.currentExtent.height); return true; } void AndroidVulkanContextFactory::ResetSurface(bool allowPipelineDump) { ResetVulkanSurface(allowPipelineDump); if (m_nativeWindow != nullptr) { ANativeWindow_release(m_nativeWindow); m_nativeWindow = nullptr; } } void AndroidVulkanContextFactory::ResetVulkanSurface(bool allowPipelineDump) { if (!m_windowSurfaceValid) return; if (m_drawContext) m_drawContext->ResetSurface(allowPipelineDump); vkDestroySurfaceKHR(m_vulkanInstance, m_surface, nullptr); m_surface = 0; m_windowSurfaceValid = false; } void AndroidVulkanContextFactory::ChangeSurface(JNIEnv * env, jobject jsurface, int w, int h) { if (w == m_surfaceWidth && m_surfaceHeight == h) return; auto nativeWindow = ANativeWindow_fromSurface(env, jsurface); CHECK(nativeWindow == m_nativeWindow, ("Native window changing is not supported.")); ResetVulkanSurface(false /* allowPipelineDump */); SetVulkanSurface(); LOG(LINFO, ("Surface changed", m_surfaceWidth, m_surfaceHeight)); } bool AndroidVulkanContextFactory::IsVulkanSupported() const { return m_vulkanInstance != nullptr && m_gpu != nullptr && m_device != nullptr; } bool AndroidVulkanContextFactory::IsValid() const { return IsVulkanSupported() && m_windowSurfaceValid; } int AndroidVulkanContextFactory::GetWidth() const { ASSERT(IsValid(), ()); return m_surfaceWidth; } int AndroidVulkanContextFactory::GetHeight() const { ASSERT(IsValid(), ()); return m_surfaceHeight; } dp::GraphicsContext * AndroidVulkanContextFactory::GetDrawContext() { return m_drawContext.get(); } dp::GraphicsContext * AndroidVulkanContextFactory::GetResourcesUploadContext() { return m_uploadContext.get(); } bool AndroidVulkanContextFactory::IsDrawContextCreated() const { return m_drawContext != nullptr; } bool AndroidVulkanContextFactory::IsUploadContextCreated() const { return m_uploadContext != nullptr; } void AndroidVulkanContextFactory::SetPresentAvailable(bool available) { if (m_drawContext) m_drawContext->SetPresentAvailable(available); } } // namespace android <commit_msg>[vulkan] Added changing native window support<commit_after>#include "android_vulkan_context_factory.hpp" #include "com/mapswithme/platform/Platform.hpp" #include "drape/drape_diagnostics.hpp" #include "drape/vulkan/vulkan_pipeline.hpp" #include "drape/vulkan/vulkan_utils.hpp" #include "base/assert.hpp" #include "base/logging.hpp" #include "base/macros.hpp" #include "base/src_point.hpp" #include <array> #include <vector> namespace android { namespace { class DrawVulkanContext : public dp::vulkan::VulkanBaseContext { public: DrawVulkanContext(VkInstance vulkanInstance, VkPhysicalDevice gpu, VkPhysicalDeviceProperties const & gpuProperties, VkDevice device, uint32_t renderingQueueFamilyIndex, ref_ptr<dp::vulkan::VulkanObjectManager> objectManager, int appVersionCode) : dp::vulkan::VulkanBaseContext(vulkanInstance, gpu, gpuProperties, device, renderingQueueFamilyIndex, objectManager, make_unique_dp<dp::vulkan::VulkanPipeline>( device, appVersionCode)) { VkQueue queue; vkGetDeviceQueue(device, renderingQueueFamilyIndex, 0, &queue); SetRenderingQueue(queue); CreateCommandPool(); } void MakeCurrent() override { m_objectManager->RegisterThread(dp::vulkan::VulkanObjectManager::Frontend); } }; class UploadVulkanContext : public dp::vulkan::VulkanBaseContext { public: UploadVulkanContext(VkInstance vulkanInstance, VkPhysicalDevice gpu, VkPhysicalDeviceProperties const & gpuProperties, VkDevice device, uint32_t renderingQueueFamilyIndex, ref_ptr<dp::vulkan::VulkanObjectManager> objectManager) : dp::vulkan::VulkanBaseContext(vulkanInstance, gpu, gpuProperties, device, renderingQueueFamilyIndex, objectManager, nullptr /* pipeline */) {} void MakeCurrent() override { m_objectManager->RegisterThread(dp::vulkan::VulkanObjectManager::Backend); } void Present() override {} void Resize(int w, int h) override {} void SetFramebuffer(ref_ptr<dp::BaseFramebuffer> framebuffer) override {} void Init(dp::ApiVersion apiVersion) override { CHECK_EQUAL(apiVersion, dp::ApiVersion::Vulkan, ()); } void SetClearColor(dp::Color const & color) override {} void Clear(uint32_t clearBits, uint32_t storeBits) override {} void Flush() override {} void SetDepthTestEnabled(bool enabled) override {} void SetDepthTestFunction(dp::TestFunction depthFunction) override {} void SetStencilTestEnabled(bool enabled) override {} void SetStencilFunction(dp::StencilFace face, dp::TestFunction stencilFunction) override {} void SetStencilActions(dp::StencilFace face, dp::StencilAction stencilFailAction, dp::StencilAction depthFailAction, dp::StencilAction passAction) override {} }; } // namespace AndroidVulkanContextFactory::AndroidVulkanContextFactory(int appVersionCode) { if (InitVulkan() == 0) { LOG_ERROR_VK("Could not initialize Vulkan library."); return; } VkApplicationInfo appInfo = {}; appInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO; appInfo.pNext = nullptr; appInfo.apiVersion = VK_MAKE_VERSION(1, 0, 0); appInfo.applicationVersion = static_cast<uint32_t>(appVersionCode); appInfo.engineVersion = static_cast<uint32_t>(appVersionCode); appInfo.pApplicationName = "MAPS.ME"; appInfo.pEngineName = "Drape Engine"; bool enableDiagnostics = false; #ifdef ENABLE_VULKAN_DIAGNOSTICS enableDiagnostics = true; #endif m_layers = make_unique_dp<dp::vulkan::Layers>(enableDiagnostics); VkInstanceCreateInfo instanceCreateInfo = {}; instanceCreateInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO; instanceCreateInfo.pNext = nullptr; instanceCreateInfo.pApplicationInfo = &appInfo; instanceCreateInfo.enabledExtensionCount = m_layers->GetInstanceExtensionsCount(); instanceCreateInfo.ppEnabledExtensionNames = m_layers->GetInstanceExtensions(); instanceCreateInfo.enabledLayerCount = m_layers->GetInstanceLayersCount(); instanceCreateInfo.ppEnabledLayerNames = m_layers->GetInstanceLayers(); VkResult statusCode; statusCode = vkCreateInstance(&instanceCreateInfo, nullptr, &m_vulkanInstance); if (statusCode != VK_SUCCESS) { LOG_ERROR_VK_CALL(vkCreateInstance, statusCode); return; } uint32_t gpuCount = 0; statusCode = vkEnumeratePhysicalDevices(m_vulkanInstance, &gpuCount, nullptr); if (statusCode != VK_SUCCESS || gpuCount == 0) { LOG_ERROR_VK_CALL(vkEnumeratePhysicalDevices, statusCode); return; } VkPhysicalDevice tmpGpus[gpuCount]; statusCode = vkEnumeratePhysicalDevices(m_vulkanInstance, &gpuCount, tmpGpus); if (statusCode != VK_SUCCESS) { LOG_ERROR_VK_CALL(vkEnumeratePhysicalDevices, statusCode); return; } m_gpu = tmpGpus[0]; uint32_t queueFamilyCount; vkGetPhysicalDeviceQueueFamilyProperties(m_gpu, &queueFamilyCount, nullptr); if (queueFamilyCount == 0) { LOG_ERROR_VK("Any queue family wasn't found."); return; } std::vector<VkQueueFamilyProperties> queueFamilyProperties(queueFamilyCount); vkGetPhysicalDeviceQueueFamilyProperties(m_gpu, &queueFamilyCount, queueFamilyProperties.data()); uint32_t renderingQueueFamilyIndex = 0; for (; renderingQueueFamilyIndex < queueFamilyCount; ++renderingQueueFamilyIndex) { if (queueFamilyProperties[renderingQueueFamilyIndex].queueFlags & VK_QUEUE_GRAPHICS_BIT) break; } if (renderingQueueFamilyIndex == queueFamilyCount) { LOG_ERROR_VK("Any queue family with VK_QUEUE_GRAPHICS_BIT wasn't found."); return; } if (!dp::vulkan::VulkanFormatUnpacker::Init(m_gpu)) return; if (!m_layers->Initialize(m_vulkanInstance, m_gpu)) return; float priorities[] = {1.0f}; VkDeviceQueueCreateInfo queueCreateInfo = {}; queueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO; queueCreateInfo.pNext = nullptr; queueCreateInfo.flags = 0; queueCreateInfo.queueCount = 1; queueCreateInfo.queueFamilyIndex = renderingQueueFamilyIndex; queueCreateInfo.pQueuePriorities = priorities; VkDeviceCreateInfo deviceCreateInfo = {}; VkPhysicalDeviceFeatures enabledFeatures = {}; deviceCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO; deviceCreateInfo.pNext = nullptr; deviceCreateInfo.queueCreateInfoCount = 1; deviceCreateInfo.pQueueCreateInfos = &queueCreateInfo; deviceCreateInfo.enabledLayerCount = m_layers->GetDeviceLayersCount(); deviceCreateInfo.ppEnabledLayerNames = m_layers->GetDeviceLayers(); deviceCreateInfo.enabledExtensionCount = m_layers->GetDeviceExtensionsCount(); deviceCreateInfo.ppEnabledExtensionNames = m_layers->GetDeviceExtensions(); deviceCreateInfo.pEnabledFeatures = nullptr; if (enableDiagnostics) { enabledFeatures.robustBufferAccess = VK_TRUE; deviceCreateInfo.pEnabledFeatures = &enabledFeatures; } statusCode = vkCreateDevice(m_gpu, &deviceCreateInfo, nullptr, &m_device); if (statusCode != VK_SUCCESS) { LOG_ERROR_VK_CALL(vkCreateDevice, statusCode); return; } VkPhysicalDeviceProperties gpuProperties; vkGetPhysicalDeviceProperties(m_gpu, &gpuProperties); VkPhysicalDeviceMemoryProperties memoryProperties; vkGetPhysicalDeviceMemoryProperties(m_gpu, &memoryProperties); m_objectManager = make_unique_dp<dp::vulkan::VulkanObjectManager>(m_device, gpuProperties.limits, memoryProperties, renderingQueueFamilyIndex); m_drawContext = make_unique_dp<DrawVulkanContext>(m_vulkanInstance, m_gpu, gpuProperties, m_device, renderingQueueFamilyIndex, make_ref(m_objectManager), appVersionCode); m_uploadContext = make_unique_dp<UploadVulkanContext>(m_vulkanInstance, m_gpu, gpuProperties, m_device, renderingQueueFamilyIndex, make_ref(m_objectManager)); } AndroidVulkanContextFactory::~AndroidVulkanContextFactory() { m_drawContext.reset(); m_uploadContext.reset(); m_objectManager.reset(); if (m_device != nullptr) { vkDeviceWaitIdle(m_device); vkDestroyDevice(m_device, nullptr); } if (m_vulkanInstance != nullptr) { m_layers->Uninitialize(m_vulkanInstance); vkDestroyInstance(m_vulkanInstance, nullptr); } } void AndroidVulkanContextFactory::SetSurface(JNIEnv * env, jobject jsurface) { if (!jsurface) { LOG_ERROR_VK("Java surface is not found."); return; } m_nativeWindow = ANativeWindow_fromSurface(env, jsurface); if (!m_nativeWindow) { LOG_ERROR_VK("Can't get native window from Java surface."); return; } SetVulkanSurface(); } void AndroidVulkanContextFactory::SetVulkanSurface() { if (m_windowSurfaceValid) return; VkAndroidSurfaceCreateInfoKHR createInfo = {}; createInfo.sType = VK_STRUCTURE_TYPE_ANDROID_SURFACE_CREATE_INFO_KHR; createInfo.pNext = nullptr; createInfo.flags = 0; createInfo.window = m_nativeWindow; VkResult statusCode; statusCode = vkCreateAndroidSurfaceKHR(m_vulkanInstance, &createInfo, nullptr, &m_surface); if (statusCode != VK_SUCCESS) { LOG_ERROR_VK_CALL(vkCreateAndroidSurfaceKHR, statusCode); return; } uint32_t const renderingQueueIndex = m_drawContext->GetRenderingQueueFamilyIndex(); VkBool32 supportsPresent; statusCode = vkGetPhysicalDeviceSurfaceSupportKHR(m_gpu, renderingQueueIndex, m_surface, &supportsPresent); if (statusCode != VK_SUCCESS) { LOG_ERROR_VK_CALL(vkGetPhysicalDeviceSurfaceSupportKHR, statusCode); return; } CHECK_EQUAL(supportsPresent, VK_TRUE, ()); CHECK(QuerySurfaceSize(), ()); if (m_drawContext) m_drawContext->SetSurface(m_surface, m_surfaceFormat, m_surfaceCapabilities); m_windowSurfaceValid = true; } bool AndroidVulkanContextFactory::QuerySurfaceSize() { auto statusCode = vkGetPhysicalDeviceSurfaceCapabilitiesKHR(m_gpu, m_surface, &m_surfaceCapabilities); if (statusCode != VK_SUCCESS) { LOG_ERROR_VK_CALL(vkGetPhysicalDeviceSurfaceCapabilitiesKHR, statusCode); return false; } uint32_t formatCount = 0; statusCode = vkGetPhysicalDeviceSurfaceFormatsKHR(m_gpu, m_surface, &formatCount, nullptr); if (statusCode != VK_SUCCESS) { LOG_ERROR_VK_CALL(vkGetPhysicalDeviceSurfaceFormatsKHR, statusCode); return false; } std::vector<VkSurfaceFormatKHR> formats(formatCount); statusCode = vkGetPhysicalDeviceSurfaceFormatsKHR(m_gpu, m_surface, &formatCount, formats.data()); if (statusCode != VK_SUCCESS) { LOG_ERROR_VK_CALL(vkGetPhysicalDeviceSurfaceFormatsKHR, statusCode); return false; } uint32_t chosenFormat; for (chosenFormat = 0; chosenFormat < formatCount; chosenFormat++) { if (formats[chosenFormat].format == VK_FORMAT_R8G8B8A8_UNORM) break; } if (chosenFormat == formatCount) { LOG_ERROR_VK("Any supported surface format wasn't found."); return false; } if (!(m_surfaceCapabilities.supportedCompositeAlpha & VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR)) { LOG_ERROR_VK("Alpha channel is not supported."); return false; } m_surfaceFormat = formats[chosenFormat]; m_surfaceWidth = static_cast<int>(m_surfaceCapabilities.currentExtent.width); m_surfaceHeight = static_cast<int>(m_surfaceCapabilities.currentExtent.height); return true; } void AndroidVulkanContextFactory::ResetSurface(bool allowPipelineDump) { ResetVulkanSurface(allowPipelineDump); if (m_nativeWindow != nullptr) { ANativeWindow_release(m_nativeWindow); m_nativeWindow = nullptr; } } void AndroidVulkanContextFactory::ResetVulkanSurface(bool allowPipelineDump) { if (!m_windowSurfaceValid) return; if (m_drawContext) m_drawContext->ResetSurface(allowPipelineDump); vkDestroySurfaceKHR(m_vulkanInstance, m_surface, nullptr); m_surface = 0; m_windowSurfaceValid = false; } void AndroidVulkanContextFactory::ChangeSurface(JNIEnv * env, jobject jsurface, int w, int h) { if (w == m_surfaceWidth && m_surfaceHeight == h) return; auto nativeWindow = ANativeWindow_fromSurface(env, jsurface); if (m_nativeWindow == nullptr) { CHECK(!m_windowSurfaceValid, ()); m_nativeWindow = nativeWindow; } else { ResetVulkanSurface(false /* allowPipelineDump */); if (nativeWindow != m_nativeWindow) { ANativeWindow_release(m_nativeWindow); m_nativeWindow = nativeWindow; } } SetVulkanSurface(); LOG(LINFO, ("Surface changed", m_surfaceWidth, m_surfaceHeight)); } bool AndroidVulkanContextFactory::IsVulkanSupported() const { return m_vulkanInstance != nullptr && m_gpu != nullptr && m_device != nullptr; } bool AndroidVulkanContextFactory::IsValid() const { return IsVulkanSupported() && m_windowSurfaceValid; } int AndroidVulkanContextFactory::GetWidth() const { ASSERT(IsValid(), ()); return m_surfaceWidth; } int AndroidVulkanContextFactory::GetHeight() const { ASSERT(IsValid(), ()); return m_surfaceHeight; } dp::GraphicsContext * AndroidVulkanContextFactory::GetDrawContext() { return m_drawContext.get(); } dp::GraphicsContext * AndroidVulkanContextFactory::GetResourcesUploadContext() { return m_uploadContext.get(); } bool AndroidVulkanContextFactory::IsDrawContextCreated() const { return m_drawContext != nullptr; } bool AndroidVulkanContextFactory::IsUploadContextCreated() const { return m_uploadContext != nullptr; } void AndroidVulkanContextFactory::SetPresentAvailable(bool available) { if (m_drawContext) m_drawContext->SetPresentAvailable(available); } } // namespace android <|endoftext|>
<commit_before>#include "master.hpp" namespace factor { void factor_vm::dispatch_signal_handler(cell* sp, cell* pc, cell handler) { if (!code->seg->in_segment_p(*pc) || *sp < ctx->callstack_seg->start + stack_reserved) { /* Fault came from the VM, foreign code, a callstack overflow, or we don't have enough callstack room to try the resumable handler. Cut the callstack down to the shallowest Factor stack frame that leaves room for the signal handler to do its thing, and launch the handler without going through the resumable subprimitive. */ signal_resumable = false; void* frame_top = (void*)ctx->callstack_top; while (frame_top < ctx->callstack_bottom && (cell)frame_top < ctx->callstack_seg->start + stack_reserved) { frame_top = frame_predecessor(frame_top); } *sp = (cell)frame_top; ctx->callstack_top = frame_top; *pc = handler; } else { signal_resumable = true; /* Fault came from Factor, and we've got a good callstack. Route the signal handler through the resumable signal handler subprimitive. */ cell offset = *sp % 16; signal_handler_addr = handler; tagged<word> handler_word = tagged<word>(special_objects[SIGNAL_HANDLER_WORD]); /* True stack frames are always 16-byte aligned. Leaf procedures that don't create a stack frame will be out of alignment by sizeof(cell) bytes. */ /* On architectures with a link register we would have to check for leafness by matching the PC to a word. We should also use FRAME_RETURN_ADDRESS instead of assuming the stack pointer is the right place to put the resume address. */ if (offset == 0) { cell newsp = *sp - sizeof(cell); *sp = newsp; *(cell*)newsp = *pc; } else if (offset == 16 - sizeof(cell)) { /* Make a fake frame for the leaf procedure */ FACTOR_ASSERT(code->code_block_for_address(*pc) != NULL); cell newsp = *sp - LEAF_FRAME_SIZE; *(cell*)newsp = *pc; *sp = newsp; handler_word = tagged<word>(special_objects[LEAF_SIGNAL_HANDLER_WORD]); } else FACTOR_ASSERT(false); *pc = (cell)handler_word->entry_point; } /* Poking with the stack pointer, which the above code does, means that pointers to stack-allocated objects will become corrupted. Therefore the root vectors needs to be cleared because their pointers to stack variables are now garbage. */ data_roots.clear(); bignum_roots.clear(); code_roots.clear(); } } <commit_msg>VM: remove bignum_roots.clear() (snuck in during rebase)<commit_after>#include "master.hpp" namespace factor { void factor_vm::dispatch_signal_handler(cell* sp, cell* pc, cell handler) { if (!code->seg->in_segment_p(*pc) || *sp < ctx->callstack_seg->start + stack_reserved) { /* Fault came from the VM, foreign code, a callstack overflow, or we don't have enough callstack room to try the resumable handler. Cut the callstack down to the shallowest Factor stack frame that leaves room for the signal handler to do its thing, and launch the handler without going through the resumable subprimitive. */ signal_resumable = false; void* frame_top = (void*)ctx->callstack_top; while (frame_top < ctx->callstack_bottom && (cell)frame_top < ctx->callstack_seg->start + stack_reserved) { frame_top = frame_predecessor(frame_top); } *sp = (cell)frame_top; ctx->callstack_top = frame_top; *pc = handler; } else { signal_resumable = true; /* Fault came from Factor, and we've got a good callstack. Route the signal handler through the resumable signal handler subprimitive. */ cell offset = *sp % 16; signal_handler_addr = handler; tagged<word> handler_word = tagged<word>(special_objects[SIGNAL_HANDLER_WORD]); /* True stack frames are always 16-byte aligned. Leaf procedures that don't create a stack frame will be out of alignment by sizeof(cell) bytes. */ /* On architectures with a link register we would have to check for leafness by matching the PC to a word. We should also use FRAME_RETURN_ADDRESS instead of assuming the stack pointer is the right place to put the resume address. */ if (offset == 0) { cell newsp = *sp - sizeof(cell); *sp = newsp; *(cell*)newsp = *pc; } else if (offset == 16 - sizeof(cell)) { /* Make a fake frame for the leaf procedure */ FACTOR_ASSERT(code->code_block_for_address(*pc) != NULL); cell newsp = *sp - LEAF_FRAME_SIZE; *(cell*)newsp = *pc; *sp = newsp; handler_word = tagged<word>(special_objects[LEAF_SIGNAL_HANDLER_WORD]); } else FACTOR_ASSERT(false); *pc = (cell)handler_word->entry_point; } /* Poking with the stack pointer, which the above code does, means that pointers to stack-allocated objects will become corrupted. Therefore the root vectors needs to be cleared because their pointers to stack variables are now garbage. */ data_roots.clear(); code_roots.clear(); } } <|endoftext|>
<commit_before>#include <cctype> #include <cstring> #include <cmath> #include <iomanip> #include "objectmemory.hpp" #include "marshal.hpp" #include "object_utils.hpp" #include "strtod.hpp" #include "builtin/sendsite.hpp" #include "builtin/array.hpp" #include "builtin/compiledmethod.hpp" #include "builtin/fixnum.hpp" #include "builtin/float.hpp" #include "builtin/iseq.hpp" #include "builtin/string.hpp" #include "builtin/symbol.hpp" #include "builtin/tuple.hpp" namespace rubinius { using std::endl; void Marshaller::set_int(Object* obj) { stream << "I" << endl << as<Integer>(obj)->to_native() << endl; } void Marshaller::set_bignum(Bignum* big) { char buf[1024]; big->into_string(state, 10, buf, sizeof(buf)); stream << "I" << endl << buf << endl; } Object* UnMarshaller::get_int() { char data[1024]; std::memset(data, 0, 1024); stream >> data; return Bignum::from_string(state, data, 10); } void Marshaller::set_string(String* str) { stream << "s" << endl << str->size() << endl; stream.write(str->byte_address(), str->size()) << endl; } String* UnMarshaller::get_string() { size_t count; stream >> count; // String::create adds room for a trailing null on its own String* str = String::create(state, NULL, count); stream.get(); // read off newline stream.read(str->byte_address(), count); stream.get(); // read off newline return str; } void Marshaller::set_symbol(Symbol* sym) { String* str = sym->to_str(state); stream << "x" << endl << str->size() << endl; stream.write(str->byte_address(), str->size()) << endl; } Symbol* UnMarshaller::get_symbol() { char data[1024]; size_t count; stream >> count; stream.get(); stream.read(data, count + 1); data[count] = 0; // clamp return state->symbol(data); } void Marshaller::set_sendsite(SendSite* ss) { String* str = ss->name()->to_str(state); stream << "S" << endl << str->size() << endl; stream.write(str->c_str(), str->size()) << endl; } SendSite* UnMarshaller::get_sendsite() { char data[1024]; size_t count; stream >> count; stream.get(); stream.read(data, count + 1); data[count] = 0; // clamp Symbol* sym = state->symbol(data); return SendSite::create(state, sym); } void Marshaller::set_array(Array* ary) { size_t count = ary->size(); stream << "A" << endl << count << endl; for(size_t i = 0; i < count; i++) { marshal(ary->get(state, i)); } } Array* UnMarshaller::get_array() { size_t count; stream >> count; Array* ary = Array::create(state, count); for(size_t i = 0; i < count; i++) { ary->set(state, i, unmarshal()); } return ary; } void Marshaller::set_tuple(Tuple* tup) { stream << "p" << endl << tup->num_fields() << endl; for(size_t i = 0; i < tup->num_fields(); i++) { marshal(tup->at(state, i)); } } Tuple* UnMarshaller::get_tuple() { size_t count; stream >> count; Tuple* tup = Tuple::create(state, count); for(size_t i = 0; i < count; i++) { tup->put(state, i, unmarshal()); } return tup; } #define FLOAT_EXP_OFFSET 58 #define FLOAT_MAX_BUFFER 65 void Marshaller::set_float(Float* flt) { double val = flt->val; stream << "d" << endl; if(std::isinf(val)) { if(val < 0.0) stream << "-"; stream << "Infinity"; } else if(std::isnan(val)) { stream << "NaN"; } else { char data[FLOAT_MAX_BUFFER]; double x; int e; x = ::frexp(val, &e); snprintf(data, FLOAT_MAX_BUFFER, " %+.54f %5d", x, e); stream << data; } stream << endl; } Float* UnMarshaller::get_float() { char data[1024]; // discard the delimiter stream.get(); stream.getline(data, 1024); if(stream.fail()) { Exception::type_error(state, "Unable to unmarshal Float: failed to read value"); } if(data[0] == ' ') { double x; long e; x = strtod(data, NULL); e = strtol(data+FLOAT_EXP_OFFSET, NULL, 10); // This is necessary because exp2(1024) yields inf if(e == 1024) { double root_exp = ::exp2(512); return Float::create(state, x * root_exp * root_exp); } else { return Float::create(state, x * ::exp2(e)); } } else { // avoid compiler warning double zero = 0.0; double val = 0.0; if(!strncasecmp(data, "Infinity", 8U)) { val = 1.0; } else if(!strncasecmp(data, "-Infinity", 9U)) { val = -1.0; } else if(!strncasecmp(data, "NaN", 3U)) { val = zero; } else { Exception::type_error(state, "Unable to unmarshal Float: invalid format"); } return Float::create(state, val / zero); } } void Marshaller::set_iseq(InstructionSequence* iseq) { Tuple* ops = iseq->opcodes(); stream << "i" << endl << ops->num_fields() << endl; for(size_t i = 0; i < ops->num_fields(); i++) { stream << as<Fixnum>(ops->at(state, i))->to_native() << endl; } } InstructionSequence* UnMarshaller::get_iseq() { size_t count; long op; stream >> count; InstructionSequence* iseq = InstructionSequence::create(state, count); Tuple* ops = iseq->opcodes(); for(size_t i = 0; i < count; i++) { stream >> op; ops->put(state, i, Fixnum::from(op)); } iseq->post_marshal(state); return iseq; } void Marshaller::set_cmethod(CompiledMethod* cm) { assert(0); } CompiledMethod* UnMarshaller::get_cmethod() { size_t ver; stream >> ver; CompiledMethod* cm = CompiledMethod::create(state); cm->ivars(state, unmarshal()); cm->primitive(state, (Symbol*)unmarshal()); cm->name(state, (Symbol*)unmarshal()); cm->iseq(state, (InstructionSequence*)unmarshal()); cm->stack_size(state, (Fixnum*)unmarshal()); cm->local_count(state, (Fixnum*)unmarshal()); cm->required_args(state, (Fixnum*)unmarshal()); cm->total_args(state, (Fixnum*)unmarshal()); cm->splat(state, unmarshal()); cm->literals(state, (Tuple*)unmarshal()); cm->exceptions(state, (Tuple*)unmarshal()); cm->lines(state, (Tuple*)unmarshal()); cm->file(state, (Symbol*)unmarshal()); cm->local_names(state, (Tuple*)unmarshal()); cm->post_marshal(state); return cm; } Object* UnMarshaller::unmarshal() { char code; stream >> code; switch(code) { case 'n': return Qnil; case 't': return Qtrue; case 'f': return Qfalse; case 'I': return get_int(); case 's': return get_string(); case 'x': return get_symbol(); case 'S': return get_sendsite(); case 'A': return get_array(); case 'p': return get_tuple(); case 'd': return get_float(); case 'i': return get_iseq(); case 'M': return get_cmethod(); default: std::string str = "unknown marshal code: "; str.append( 1, code ); Exception::type_error(state, str.c_str()); return Qnil; // make compiler happy } } void Marshaller::marshal(Object* obj) { if(obj == Qnil) { stream << "n" << endl; } else if(obj == Qtrue) { stream << "t" << endl; } else if(obj == Qfalse) { stream << "f" << endl; } else if(obj->fixnum_p()) { set_int(obj); } else if(obj->symbol_p()) { set_symbol((Symbol*)obj); } else if(kind_of<Bignum>(obj)) { set_bignum(as<Bignum>(obj)); } else if(kind_of<String>(obj)) { set_string(as<String>(obj)); } else if(kind_of<SendSite>(obj)) { set_sendsite(as<SendSite>(obj)); } else if(kind_of<Array>(obj)) { set_array(as<Array>(obj)); } else if(kind_of<Tuple>(obj)) { set_tuple(as<Tuple>(obj)); } else if(kind_of<Float>(obj)) { set_float(as<Float>(obj)); } else if(kind_of<InstructionSequence>(obj)) { set_iseq(as<InstructionSequence>(obj)); } else if(kind_of<CompiledMethod>(obj)) { set_cmethod(as<CompiledMethod>(obj)); } else { Exception::type_error(state, "unknown object"); } } } <commit_msg>Don't zero the full buffer in UnMarshaller::get_int().<commit_after>#include <cctype> #include <cstring> #include <cmath> #include <iomanip> #include "objectmemory.hpp" #include "marshal.hpp" #include "object_utils.hpp" #include "strtod.hpp" #include "builtin/sendsite.hpp" #include "builtin/array.hpp" #include "builtin/compiledmethod.hpp" #include "builtin/fixnum.hpp" #include "builtin/float.hpp" #include "builtin/iseq.hpp" #include "builtin/string.hpp" #include "builtin/symbol.hpp" #include "builtin/tuple.hpp" namespace rubinius { using std::endl; void Marshaller::set_int(Object* obj) { stream << "I" << endl << as<Integer>(obj)->to_native() << endl; } void Marshaller::set_bignum(Bignum* big) { char buf[1024]; big->into_string(state, 10, buf, sizeof(buf)); stream << "I" << endl << buf << endl; } Object* UnMarshaller::get_int() { char data[1024]; stream >> data; data[sizeof(data) - 1] = '\0'; return Bignum::from_string(state, data, 10); } void Marshaller::set_string(String* str) { stream << "s" << endl << str->size() << endl; stream.write(str->byte_address(), str->size()) << endl; } String* UnMarshaller::get_string() { size_t count; stream >> count; // String::create adds room for a trailing null on its own String* str = String::create(state, NULL, count); stream.get(); // read off newline stream.read(str->byte_address(), count); stream.get(); // read off newline return str; } void Marshaller::set_symbol(Symbol* sym) { String* str = sym->to_str(state); stream << "x" << endl << str->size() << endl; stream.write(str->byte_address(), str->size()) << endl; } Symbol* UnMarshaller::get_symbol() { char data[1024]; size_t count; stream >> count; stream.get(); stream.read(data, count + 1); data[count] = 0; // clamp return state->symbol(data); } void Marshaller::set_sendsite(SendSite* ss) { String* str = ss->name()->to_str(state); stream << "S" << endl << str->size() << endl; stream.write(str->c_str(), str->size()) << endl; } SendSite* UnMarshaller::get_sendsite() { char data[1024]; size_t count; stream >> count; stream.get(); stream.read(data, count + 1); data[count] = 0; // clamp Symbol* sym = state->symbol(data); return SendSite::create(state, sym); } void Marshaller::set_array(Array* ary) { size_t count = ary->size(); stream << "A" << endl << count << endl; for(size_t i = 0; i < count; i++) { marshal(ary->get(state, i)); } } Array* UnMarshaller::get_array() { size_t count; stream >> count; Array* ary = Array::create(state, count); for(size_t i = 0; i < count; i++) { ary->set(state, i, unmarshal()); } return ary; } void Marshaller::set_tuple(Tuple* tup) { stream << "p" << endl << tup->num_fields() << endl; for(size_t i = 0; i < tup->num_fields(); i++) { marshal(tup->at(state, i)); } } Tuple* UnMarshaller::get_tuple() { size_t count; stream >> count; Tuple* tup = Tuple::create(state, count); for(size_t i = 0; i < count; i++) { tup->put(state, i, unmarshal()); } return tup; } #define FLOAT_EXP_OFFSET 58 #define FLOAT_MAX_BUFFER 65 void Marshaller::set_float(Float* flt) { double val = flt->val; stream << "d" << endl; if(std::isinf(val)) { if(val < 0.0) stream << "-"; stream << "Infinity"; } else if(std::isnan(val)) { stream << "NaN"; } else { char data[FLOAT_MAX_BUFFER]; double x; int e; x = ::frexp(val, &e); snprintf(data, FLOAT_MAX_BUFFER, " %+.54f %5d", x, e); stream << data; } stream << endl; } Float* UnMarshaller::get_float() { char data[1024]; // discard the delimiter stream.get(); stream.getline(data, 1024); if(stream.fail()) { Exception::type_error(state, "Unable to unmarshal Float: failed to read value"); } if(data[0] == ' ') { double x; long e; x = strtod(data, NULL); e = strtol(data+FLOAT_EXP_OFFSET, NULL, 10); // This is necessary because exp2(1024) yields inf if(e == 1024) { double root_exp = ::exp2(512); return Float::create(state, x * root_exp * root_exp); } else { return Float::create(state, x * ::exp2(e)); } } else { // avoid compiler warning double zero = 0.0; double val = 0.0; if(!strncasecmp(data, "Infinity", 8U)) { val = 1.0; } else if(!strncasecmp(data, "-Infinity", 9U)) { val = -1.0; } else if(!strncasecmp(data, "NaN", 3U)) { val = zero; } else { Exception::type_error(state, "Unable to unmarshal Float: invalid format"); } return Float::create(state, val / zero); } } void Marshaller::set_iseq(InstructionSequence* iseq) { Tuple* ops = iseq->opcodes(); stream << "i" << endl << ops->num_fields() << endl; for(size_t i = 0; i < ops->num_fields(); i++) { stream << as<Fixnum>(ops->at(state, i))->to_native() << endl; } } InstructionSequence* UnMarshaller::get_iseq() { size_t count; long op; stream >> count; InstructionSequence* iseq = InstructionSequence::create(state, count); Tuple* ops = iseq->opcodes(); for(size_t i = 0; i < count; i++) { stream >> op; ops->put(state, i, Fixnum::from(op)); } iseq->post_marshal(state); return iseq; } void Marshaller::set_cmethod(CompiledMethod* cm) { assert(0); } CompiledMethod* UnMarshaller::get_cmethod() { size_t ver; stream >> ver; CompiledMethod* cm = CompiledMethod::create(state); cm->ivars(state, unmarshal()); cm->primitive(state, (Symbol*)unmarshal()); cm->name(state, (Symbol*)unmarshal()); cm->iseq(state, (InstructionSequence*)unmarshal()); cm->stack_size(state, (Fixnum*)unmarshal()); cm->local_count(state, (Fixnum*)unmarshal()); cm->required_args(state, (Fixnum*)unmarshal()); cm->total_args(state, (Fixnum*)unmarshal()); cm->splat(state, unmarshal()); cm->literals(state, (Tuple*)unmarshal()); cm->exceptions(state, (Tuple*)unmarshal()); cm->lines(state, (Tuple*)unmarshal()); cm->file(state, (Symbol*)unmarshal()); cm->local_names(state, (Tuple*)unmarshal()); cm->post_marshal(state); return cm; } Object* UnMarshaller::unmarshal() { char code; stream >> code; switch(code) { case 'n': return Qnil; case 't': return Qtrue; case 'f': return Qfalse; case 'I': return get_int(); case 's': return get_string(); case 'x': return get_symbol(); case 'S': return get_sendsite(); case 'A': return get_array(); case 'p': return get_tuple(); case 'd': return get_float(); case 'i': return get_iseq(); case 'M': return get_cmethod(); default: std::string str = "unknown marshal code: "; str.append( 1, code ); Exception::type_error(state, str.c_str()); return Qnil; // make compiler happy } } void Marshaller::marshal(Object* obj) { if(obj == Qnil) { stream << "n" << endl; } else if(obj == Qtrue) { stream << "t" << endl; } else if(obj == Qfalse) { stream << "f" << endl; } else if(obj->fixnum_p()) { set_int(obj); } else if(obj->symbol_p()) { set_symbol((Symbol*)obj); } else if(kind_of<Bignum>(obj)) { set_bignum(as<Bignum>(obj)); } else if(kind_of<String>(obj)) { set_string(as<String>(obj)); } else if(kind_of<SendSite>(obj)) { set_sendsite(as<SendSite>(obj)); } else if(kind_of<Array>(obj)) { set_array(as<Array>(obj)); } else if(kind_of<Tuple>(obj)) { set_tuple(as<Tuple>(obj)); } else if(kind_of<Float>(obj)) { set_float(as<Float>(obj)); } else if(kind_of<InstructionSequence>(obj)) { set_iseq(as<InstructionSequence>(obj)); } else if(kind_of<CompiledMethod>(obj)) { set_cmethod(as<CompiledMethod>(obj)); } else { Exception::type_error(state, "unknown object"); } } } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: viewcontext.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: hr $ $Date: 2007-06-27 15:07:32 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _SD_XMLVIEWSETTINGSCONTEXT_HXX #define _SD_XMLVIEWSETTINGSCONTEXT_HXX #ifndef _COM_SUN_STAR_AWT_RECTANGLE_HPP_ #include <com/sun/star/awt/Rectangle.hpp> #endif #ifndef _XMLOFF_XMLICTXT_HXX #include <xmloff/xmlictxt.hxx> #endif class SdXMLImport; class SdXMLViewSettingsContext : public SvXMLImportContext { ::com::sun::star::awt::Rectangle maVisArea; public: SdXMLViewSettingsContext( SdXMLImport& rImport, USHORT nPrfx, const rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList); virtual ~SdXMLViewSettingsContext(); virtual SvXMLImportContext *CreateChildContext( USHORT nPrefix, const rtl::OUString& rLocalName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList ); virtual void EndElement(); }; #endif <commit_msg>INTEGRATION: CWS changefileheader (1.3.162); FILE MERGED 2008/04/01 13:04:45 thb 1.3.162.2: #i85898# Stripping all external header guards 2008/03/31 16:28:08 rt 1.3.162.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: viewcontext.hxx,v $ * $Revision: 1.4 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef _SD_XMLVIEWSETTINGSCONTEXT_HXX #define _SD_XMLVIEWSETTINGSCONTEXT_HXX #include <com/sun/star/awt/Rectangle.hpp> #include <xmloff/xmlictxt.hxx> class SdXMLImport; class SdXMLViewSettingsContext : public SvXMLImportContext { ::com::sun::star::awt::Rectangle maVisArea; public: SdXMLViewSettingsContext( SdXMLImport& rImport, USHORT nPrfx, const rtl::OUString& rLName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList); virtual ~SdXMLViewSettingsContext(); virtual SvXMLImportContext *CreateChildContext( USHORT nPrefix, const rtl::OUString& rLocalName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList>& xAttrList ); virtual void EndElement(); }; #endif <|endoftext|>
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/printing/print_preview_message_handler.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/printing/print_job_manager.h" #include "chrome/browser/printing/print_preview_tab_controller.h" #include "chrome/browser/printing/printer_query.h" #include "chrome/browser/ui/webui/print_preview_handler.h" #include "chrome/browser/ui/webui/print_preview_ui.h" #include "chrome/browser/ui/webui/print_preview_ui_html_source.h" #include "chrome/common/content_restriction.h" #include "chrome/common/print_messages.h" #include "content/browser/browser_thread.h" #include "content/browser/renderer_host/render_view_host.h" #include "content/browser/tab_contents/tab_contents.h" namespace printing { PrintPreviewMessageHandler::PrintPreviewMessageHandler( TabContents* tab_contents) : TabContentsObserver(tab_contents) { DCHECK(tab_contents); } PrintPreviewMessageHandler::~PrintPreviewMessageHandler() { } TabContents* PrintPreviewMessageHandler::GetPrintPreviewTab() { // Get/Create preview tab for initiator tab. printing::PrintPreviewTabController* tab_controller = printing::PrintPreviewTabController::GetInstance(); if (!tab_controller) return NULL; return tab_controller->GetPrintPreviewForTab(tab_contents()); } void PrintPreviewMessageHandler::OnPagesReadyForPreview( const PrintHostMsg_DidPreviewDocument_Params& params) { // Always need to stop the worker and send PrintMsg_PrintingDone. PrintJobManager* print_job_manager = g_browser_process->print_job_manager(); scoped_refptr<printing::PrinterQuery> printer_query; print_job_manager->PopPrinterQuery(params.document_cookie, &printer_query); if (printer_query.get()) { BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, NewRunnableMethod(printer_query.get(), &printing::PrinterQuery::StopWorker)); } RenderViewHost* rvh = tab_contents()->render_view_host(); rvh->Send(new PrintMsg_PrintingDone(rvh->routing_id(), params.document_cookie, true)); // Get the print preview tab. TabContents* print_preview_tab = GetPrintPreviewTab(); // User might have closed it already. if (!print_preview_tab) return; #if defined(OS_POSIX) base::SharedMemory* shared_buf = new base::SharedMemory(params.metafile_data_handle, true); if (!shared_buf->Map(params.data_size)) { NOTREACHED(); delete shared_buf; return; } PrintPreviewUI* print_preview_ui = static_cast<PrintPreviewUI*>(print_preview_tab->web_ui()); PrintPreviewUIHTMLSource* html_source = print_preview_ui->html_source(); html_source->SetPrintPreviewData( std::make_pair(shared_buf, params.data_size)); print_preview_ui->PreviewDataIsAvailable(params.expected_pages_count, tab_contents()->GetTitle()); #endif // defined(OS_POSIX) } void PrintPreviewMessageHandler::OnPrintPreviewNodeUnderContextMenu() { PrintPreviewTabController::PrintPreview(tab_contents()); } void PrintPreviewMessageHandler::OnScriptInitiatedPrintPreview() { PrintPreviewTabController::PrintPreview(tab_contents()); } bool PrintPreviewMessageHandler::OnMessageReceived( const IPC::Message& message) { bool handled = true; IPC_BEGIN_MESSAGE_MAP(PrintPreviewMessageHandler, message) IPC_MESSAGE_HANDLER(PrintHostMsg_PagesReadyForPreview, OnPagesReadyForPreview) IPC_MESSAGE_HANDLER(PrintHostMsg_PrintPreviewNodeUnderContextMenu, OnPrintPreviewNodeUnderContextMenu) IPC_MESSAGE_HANDLER(PrintHostMsg_ScriptInitiatedPrintPreview, OnScriptInitiatedPrintPreview) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() return handled; } void PrintPreviewMessageHandler::DidStartLoading() { if (tab_contents()->delegate() && printing::PrintPreviewTabController::IsPrintPreviewTab(tab_contents())) { tab_contents()->SetContentRestrictions(CONTENT_RESTRICTION_PRINT); } } } // namespace printing <commit_msg>Remove #if defined(OS_POSIX) so code can be used in windows print preview.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/printing/print_preview_message_handler.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/printing/print_job_manager.h" #include "chrome/browser/printing/print_preview_tab_controller.h" #include "chrome/browser/printing/printer_query.h" #include "chrome/browser/ui/webui/print_preview_handler.h" #include "chrome/browser/ui/webui/print_preview_ui.h" #include "chrome/browser/ui/webui/print_preview_ui_html_source.h" #include "chrome/common/content_restriction.h" #include "chrome/common/print_messages.h" #include "content/browser/browser_thread.h" #include "content/browser/renderer_host/render_view_host.h" #include "content/browser/tab_contents/tab_contents.h" namespace printing { PrintPreviewMessageHandler::PrintPreviewMessageHandler( TabContents* tab_contents) : TabContentsObserver(tab_contents) { DCHECK(tab_contents); } PrintPreviewMessageHandler::~PrintPreviewMessageHandler() { } TabContents* PrintPreviewMessageHandler::GetPrintPreviewTab() { // Get/Create preview tab for initiator tab. printing::PrintPreviewTabController* tab_controller = printing::PrintPreviewTabController::GetInstance(); if (!tab_controller) return NULL; return tab_controller->GetPrintPreviewForTab(tab_contents()); } void PrintPreviewMessageHandler::OnPagesReadyForPreview( const PrintHostMsg_DidPreviewDocument_Params& params) { // Always need to stop the worker and send PrintMsg_PrintingDone. PrintJobManager* print_job_manager = g_browser_process->print_job_manager(); scoped_refptr<printing::PrinterQuery> printer_query; print_job_manager->PopPrinterQuery(params.document_cookie, &printer_query); if (printer_query.get()) { BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, NewRunnableMethod(printer_query.get(), &printing::PrinterQuery::StopWorker)); } RenderViewHost* rvh = tab_contents()->render_view_host(); rvh->Send(new PrintMsg_PrintingDone(rvh->routing_id(), params.document_cookie, true)); // Get the print preview tab. TabContents* print_preview_tab = GetPrintPreviewTab(); // User might have closed it already. if (!print_preview_tab) return; base::SharedMemory* shared_buf = new base::SharedMemory(params.metafile_data_handle, true); if (!shared_buf->Map(params.data_size)) { NOTREACHED(); delete shared_buf; return; } PrintPreviewUI* print_preview_ui = static_cast<PrintPreviewUI*>(print_preview_tab->web_ui()); PrintPreviewUIHTMLSource* html_source = print_preview_ui->html_source(); html_source->SetPrintPreviewData( std::make_pair(shared_buf, params.data_size)); print_preview_ui->PreviewDataIsAvailable(params.expected_pages_count, tab_contents()->GetTitle()); } void PrintPreviewMessageHandler::OnPrintPreviewNodeUnderContextMenu() { PrintPreviewTabController::PrintPreview(tab_contents()); } void PrintPreviewMessageHandler::OnScriptInitiatedPrintPreview() { PrintPreviewTabController::PrintPreview(tab_contents()); } bool PrintPreviewMessageHandler::OnMessageReceived( const IPC::Message& message) { bool handled = true; IPC_BEGIN_MESSAGE_MAP(PrintPreviewMessageHandler, message) IPC_MESSAGE_HANDLER(PrintHostMsg_PagesReadyForPreview, OnPagesReadyForPreview) IPC_MESSAGE_HANDLER(PrintHostMsg_PrintPreviewNodeUnderContextMenu, OnPrintPreviewNodeUnderContextMenu) IPC_MESSAGE_HANDLER(PrintHostMsg_ScriptInitiatedPrintPreview, OnScriptInitiatedPrintPreview) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() return handled; } void PrintPreviewMessageHandler::DidStartLoading() { if (tab_contents()->delegate() && printing::PrintPreviewTabController::IsPrintPreviewTab(tab_contents())) { tab_contents()->SetContentRestrictions(CONTENT_RESTRICTION_PRINT); } } } // namespace printing <|endoftext|>
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/app/chrome_dll_resource.h" #include "chrome/test/automated_ui_tests/automated_ui_test_base.h" #include "chrome/test/automation/browser_proxy.h" #include "chrome/test/automation/tab_proxy.h" #include "chrome/test/ui/ui_test.h" #include "googleurl/src/gurl.h" #include "net/base/net_util.h" TEST_F(AutomatedUITestBase, NewTab) { int tab_count; active_browser()->GetTabCount(&tab_count); ASSERT_EQ(1, tab_count); NewTab(); active_browser()->GetTabCount(&tab_count); ASSERT_EQ(2, tab_count); NewTab(); active_browser()->GetTabCount(&tab_count); ASSERT_EQ(3, tab_count); } TEST_F(AutomatedUITestBase, DuplicateTab) { int tab_count; active_browser()->GetTabCount(&tab_count); ASSERT_EQ(1, tab_count); DuplicateTab(); active_browser()->GetTabCount(&tab_count); ASSERT_EQ(2, tab_count); DuplicateTab(); active_browser()->GetTabCount(&tab_count); ASSERT_EQ(3, tab_count); } TEST_F(AutomatedUITestBase, RestoreTab) { int tab_count; active_browser()->GetTabCount(&tab_count); ASSERT_EQ(1, tab_count); NewTab(); active_browser()->GetTabCount(&tab_count); ASSERT_EQ(2, tab_count); GURL test_url("about:blank"); GetActiveTab()->NavigateToURL(test_url); CloseActiveTab(); active_browser()->GetTabCount(&tab_count); ASSERT_EQ(1, tab_count); RestoreTab(); active_browser()->GetTabCount(&tab_count); ASSERT_EQ(2, tab_count); } TEST_F(AutomatedUITestBase, CloseTab) { int num_browser_windows; int tab_count; NewTab(); automation()->GetBrowserWindowCount(&num_browser_windows); ASSERT_EQ(1, num_browser_windows); active_browser()->GetTabCount(&tab_count); ASSERT_EQ(2, tab_count); ASSERT_TRUE(OpenAndActivateNewBrowserWindow(NULL)); NewTab(); NewTab(); active_browser()->GetTabCount(&tab_count); ASSERT_EQ(3, tab_count); automation()->GetBrowserWindowCount(&num_browser_windows); ASSERT_EQ(2, num_browser_windows); ASSERT_TRUE(CloseActiveTab()); active_browser()->GetTabCount(&tab_count); ASSERT_EQ(2, tab_count); ASSERT_TRUE(CloseActiveTab()); active_browser()->GetTabCount(&tab_count); ASSERT_EQ(1, tab_count); num_browser_windows = 0; automation()->GetBrowserWindowCount(&num_browser_windows); ASSERT_EQ(2, num_browser_windows); // The browser window is closed by closing this tab. ASSERT_TRUE(CloseActiveTab()); automation()->GetBrowserWindowCount(&num_browser_windows); ASSERT_EQ(1, num_browser_windows); // Active_browser_ is now the first created window. active_browser()->GetTabCount(&tab_count); ASSERT_EQ(2, tab_count); ASSERT_TRUE(CloseActiveTab()); active_browser()->GetTabCount(&tab_count); ASSERT_EQ(1, tab_count); // The last tab should not be closed. ASSERT_FALSE(CloseActiveTab()); active_browser()->GetTabCount(&tab_count); ASSERT_EQ(1, tab_count); } TEST_F(AutomatedUITestBase, OpenBrowserWindow) { int num_browser_windows; int tab_count; automation()->GetBrowserWindowCount(&num_browser_windows); ASSERT_EQ(1, num_browser_windows); active_browser()->GetTabCount(&tab_count); ASSERT_EQ(1, tab_count); BrowserProxy* previous_browser; ASSERT_TRUE(OpenAndActivateNewBrowserWindow(&previous_browser)); scoped_ptr<BrowserProxy>browser_1(previous_browser); automation()->GetBrowserWindowCount(&num_browser_windows); ASSERT_EQ(2, num_browser_windows); active_browser()->GetTabCount(&tab_count); ASSERT_EQ(1, tab_count); NewTab(); browser_1->GetTabCount(&tab_count); ASSERT_EQ(1, tab_count); active_browser()->GetTabCount(&tab_count); ASSERT_EQ(2, tab_count); ASSERT_TRUE(OpenAndActivateNewBrowserWindow(&previous_browser)); scoped_ptr<BrowserProxy>browser_2(previous_browser); automation()->GetBrowserWindowCount(&num_browser_windows); ASSERT_EQ(3, num_browser_windows); active_browser()->GetTabCount(&tab_count); ASSERT_EQ(1, tab_count); NewTab(); NewTab(); browser_1->GetTabCount(&tab_count); ASSERT_EQ(1, tab_count); browser_2->GetTabCount(&tab_count); ASSERT_EQ(2, tab_count); active_browser()->GetTabCount(&tab_count); ASSERT_EQ(3, tab_count); bool application_closed; CloseBrowser(browser_1.get(), &application_closed); ASSERT_FALSE(application_closed); automation()->GetBrowserWindowCount(&num_browser_windows); ASSERT_EQ(2, num_browser_windows); CloseBrowser(browser_2.get(), &application_closed); ASSERT_FALSE(application_closed); automation()->GetBrowserWindowCount(&num_browser_windows); ASSERT_EQ(1, num_browser_windows); } TEST_F(AutomatedUITestBase, CloseBrowserWindow) { int tab_count; NewTab(); active_browser()->GetTabCount(&tab_count); ASSERT_EQ(2, tab_count); ASSERT_TRUE(OpenAndActivateNewBrowserWindow(NULL)); NewTab(); NewTab(); active_browser()->GetTabCount(&tab_count); ASSERT_EQ(3, tab_count); ASSERT_TRUE(OpenAndActivateNewBrowserWindow(NULL)); NewTab(); NewTab(); NewTab(); active_browser()->GetTabCount(&tab_count); ASSERT_EQ(4, tab_count); ASSERT_TRUE(CloseActiveWindow()); active_browser()->GetTabCount(&tab_count); if (tab_count == 2) { ASSERT_TRUE(CloseActiveWindow()); active_browser()->GetTabCount(&tab_count); ASSERT_EQ(3, tab_count); } else { ASSERT_EQ(3, tab_count); ASSERT_TRUE(CloseActiveWindow()); active_browser()->GetTabCount(&tab_count); ASSERT_EQ(2, tab_count); } ASSERT_FALSE(CloseActiveWindow()); } TEST_F(AutomatedUITestBase, IncognitoWindow) { int num_browser_windows; int num_normal_browser_windows; automation()->GetBrowserWindowCount(&num_browser_windows); ASSERT_EQ(1, num_browser_windows); automation()->GetNormalBrowserWindowCount(&num_normal_browser_windows); ASSERT_EQ(1, num_normal_browser_windows); ASSERT_TRUE(GoOffTheRecord()); ASSERT_TRUE(GoOffTheRecord()); automation()->GetBrowserWindowCount(&num_browser_windows); ASSERT_EQ(3, num_browser_windows); automation()->GetNormalBrowserWindowCount(&num_normal_browser_windows); ASSERT_EQ(1, num_normal_browser_windows); // There is only one normal window so it will not be closed. ASSERT_FALSE(CloseActiveWindow()); automation()->GetBrowserWindowCount(&num_browser_windows); ASSERT_EQ(3, num_browser_windows); automation()->GetNormalBrowserWindowCount(&num_normal_browser_windows); ASSERT_EQ(1, num_normal_browser_windows); set_active_browser(automation()->GetBrowserWindow(0)); ASSERT_TRUE(RunCommand(IDC_CLOSE_WINDOW)); set_active_browser(automation()->GetBrowserWindow(0)); ASSERT_TRUE(RunCommand(IDC_CLOSE_WINDOW)); automation()->GetBrowserWindowCount(&num_browser_windows); ASSERT_EQ(1, num_browser_windows); } TEST_F(AutomatedUITestBase, OpenCloseBrowserWindowWithAccelerator) { // Note: we don't use RunCommand(IDC_OPEN/CLOSE_WINDOW) to open/close // browser window in automated ui tests. Instead we use // OpenAndActivateNewBrowserWindow and CloseActiveWindow. // There are other parts of UI test that use the accelerators. This is // a unit test for those usage. ASSERT_TRUE(RunCommand(IDC_NEW_WINDOW)); int num_browser_windows; automation()->GetBrowserWindowCount(&num_browser_windows); ASSERT_EQ(2, num_browser_windows); ASSERT_TRUE(RunCommand(IDC_NEW_WINDOW)); ASSERT_TRUE(RunCommand(IDC_NEW_WINDOW)); ASSERT_TRUE(RunCommand(IDC_NEW_WINDOW)); ASSERT_TRUE(RunCommand(IDC_NEW_WINDOW)); ASSERT_TRUE(RunCommand(IDC_NEW_WINDOW)); automation()->GetBrowserWindowCount(&num_browser_windows); ASSERT_EQ(7, num_browser_windows); set_active_browser(automation()->GetBrowserWindow(0)); ASSERT_TRUE(RunCommand(IDC_CLOSE_WINDOW)); automation()->GetBrowserWindowCount(&num_browser_windows); ASSERT_EQ(6, num_browser_windows); set_active_browser(automation()->GetBrowserWindow(0)); ASSERT_TRUE(RunCommand(IDC_CLOSE_WINDOW)); set_active_browser(automation()->GetBrowserWindow(0)); ASSERT_TRUE(RunCommand(IDC_CLOSE_WINDOW)); set_active_browser(automation()->GetBrowserWindow(0)); ASSERT_TRUE(RunCommand(IDC_CLOSE_WINDOW)); set_active_browser(automation()->GetBrowserWindow(0)); ASSERT_TRUE(RunCommand(IDC_CLOSE_WINDOW)); set_active_browser(automation()->GetBrowserWindow(0)); ASSERT_TRUE(RunCommand(IDC_CLOSE_WINDOW)); automation()->GetBrowserWindowCount(&num_browser_windows); ASSERT_EQ(1, num_browser_windows); } TEST_F(AutomatedUITestBase, Navigate) { FilePath path_prefix(test_data_directory_.AppendASCII("session_history")); GURL url1(net::FilePathToFileURL(path_prefix.AppendASCII("bot1.html"))); GURL url2(net::FilePathToFileURL(path_prefix.AppendASCII("bot2.html"))); GURL url3(net::FilePathToFileURL(path_prefix.AppendASCII("bot3.html"))); GURL url; ASSERT_TRUE(Navigate(url1)); ASSERT_TRUE(GetActiveTab()->GetCurrentURL(&url)); ASSERT_EQ(url1, url); ASSERT_TRUE(Navigate(url2)); ASSERT_TRUE(GetActiveTab()->GetCurrentURL(&url)); ASSERT_EQ(url2, url); ASSERT_TRUE(Navigate(url3)); ASSERT_TRUE(GetActiveTab()->GetCurrentURL(&url)); ASSERT_EQ(url3, url); ASSERT_TRUE(BackButton()); ASSERT_TRUE(GetActiveTab()->GetCurrentURL(&url)); ASSERT_EQ(url2, url); ASSERT_TRUE(BackButton()); ASSERT_TRUE(GetActiveTab()->GetCurrentURL(&url)); ASSERT_EQ(url1, url); ASSERT_TRUE(ForwardButton()); ASSERT_TRUE(GetActiveTab()->GetCurrentURL(&url)); ASSERT_EQ(url2, url); ASSERT_TRUE(ReloadPage()); ASSERT_TRUE(GetActiveTab()->GetCurrentURL(&url)); ASSERT_EQ(url2, url); } <commit_msg>Try fix the flakey AutomatedUITestBase.RestoreTab.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/app/chrome_dll_resource.h" #include "chrome/test/automated_ui_tests/automated_ui_test_base.h" #include "chrome/test/automation/browser_proxy.h" #include "chrome/test/automation/tab_proxy.h" #include "chrome/test/ui/ui_test.h" #include "googleurl/src/gurl.h" #include "net/base/net_util.h" TEST_F(AutomatedUITestBase, NewTab) { int tab_count; active_browser()->GetTabCount(&tab_count); ASSERT_EQ(1, tab_count); NewTab(); active_browser()->GetTabCount(&tab_count); ASSERT_EQ(2, tab_count); NewTab(); active_browser()->GetTabCount(&tab_count); ASSERT_EQ(3, tab_count); } TEST_F(AutomatedUITestBase, DuplicateTab) { int tab_count; active_browser()->GetTabCount(&tab_count); ASSERT_EQ(1, tab_count); DuplicateTab(); active_browser()->GetTabCount(&tab_count); ASSERT_EQ(2, tab_count); DuplicateTab(); active_browser()->GetTabCount(&tab_count); ASSERT_EQ(3, tab_count); } TEST_F(AutomatedUITestBase, RestoreTab) { int tab_count; active_browser()->GetTabCount(&tab_count); ASSERT_EQ(1, tab_count); NewTab(); active_browser()->GetTabCount(&tab_count); ASSERT_EQ(2, tab_count); FilePath path_prefix(test_data_directory_.AppendASCII("session_history")); GURL test_url = net::FilePathToFileURL(path_prefix.AppendASCII("bot1.html")); GetActiveTab()->NavigateToURL(test_url); CloseActiveTab(); active_browser()->GetTabCount(&tab_count); ASSERT_EQ(1, tab_count); RestoreTab(); active_browser()->GetTabCount(&tab_count); ASSERT_EQ(2, tab_count); } TEST_F(AutomatedUITestBase, CloseTab) { int num_browser_windows; int tab_count; NewTab(); automation()->GetBrowserWindowCount(&num_browser_windows); ASSERT_EQ(1, num_browser_windows); active_browser()->GetTabCount(&tab_count); ASSERT_EQ(2, tab_count); ASSERT_TRUE(OpenAndActivateNewBrowserWindow(NULL)); NewTab(); NewTab(); active_browser()->GetTabCount(&tab_count); ASSERT_EQ(3, tab_count); automation()->GetBrowserWindowCount(&num_browser_windows); ASSERT_EQ(2, num_browser_windows); ASSERT_TRUE(CloseActiveTab()); active_browser()->GetTabCount(&tab_count); ASSERT_EQ(2, tab_count); ASSERT_TRUE(CloseActiveTab()); active_browser()->GetTabCount(&tab_count); ASSERT_EQ(1, tab_count); num_browser_windows = 0; automation()->GetBrowserWindowCount(&num_browser_windows); ASSERT_EQ(2, num_browser_windows); // The browser window is closed by closing this tab. ASSERT_TRUE(CloseActiveTab()); automation()->GetBrowserWindowCount(&num_browser_windows); ASSERT_EQ(1, num_browser_windows); // Active_browser_ is now the first created window. active_browser()->GetTabCount(&tab_count); ASSERT_EQ(2, tab_count); ASSERT_TRUE(CloseActiveTab()); active_browser()->GetTabCount(&tab_count); ASSERT_EQ(1, tab_count); // The last tab should not be closed. ASSERT_FALSE(CloseActiveTab()); active_browser()->GetTabCount(&tab_count); ASSERT_EQ(1, tab_count); } TEST_F(AutomatedUITestBase, OpenBrowserWindow) { int num_browser_windows; int tab_count; automation()->GetBrowserWindowCount(&num_browser_windows); ASSERT_EQ(1, num_browser_windows); active_browser()->GetTabCount(&tab_count); ASSERT_EQ(1, tab_count); BrowserProxy* previous_browser; ASSERT_TRUE(OpenAndActivateNewBrowserWindow(&previous_browser)); scoped_ptr<BrowserProxy>browser_1(previous_browser); automation()->GetBrowserWindowCount(&num_browser_windows); ASSERT_EQ(2, num_browser_windows); active_browser()->GetTabCount(&tab_count); ASSERT_EQ(1, tab_count); NewTab(); browser_1->GetTabCount(&tab_count); ASSERT_EQ(1, tab_count); active_browser()->GetTabCount(&tab_count); ASSERT_EQ(2, tab_count); ASSERT_TRUE(OpenAndActivateNewBrowserWindow(&previous_browser)); scoped_ptr<BrowserProxy>browser_2(previous_browser); automation()->GetBrowserWindowCount(&num_browser_windows); ASSERT_EQ(3, num_browser_windows); active_browser()->GetTabCount(&tab_count); ASSERT_EQ(1, tab_count); NewTab(); NewTab(); browser_1->GetTabCount(&tab_count); ASSERT_EQ(1, tab_count); browser_2->GetTabCount(&tab_count); ASSERT_EQ(2, tab_count); active_browser()->GetTabCount(&tab_count); ASSERT_EQ(3, tab_count); bool application_closed; CloseBrowser(browser_1.get(), &application_closed); ASSERT_FALSE(application_closed); automation()->GetBrowserWindowCount(&num_browser_windows); ASSERT_EQ(2, num_browser_windows); CloseBrowser(browser_2.get(), &application_closed); ASSERT_FALSE(application_closed); automation()->GetBrowserWindowCount(&num_browser_windows); ASSERT_EQ(1, num_browser_windows); } TEST_F(AutomatedUITestBase, CloseBrowserWindow) { int tab_count; NewTab(); active_browser()->GetTabCount(&tab_count); ASSERT_EQ(2, tab_count); ASSERT_TRUE(OpenAndActivateNewBrowserWindow(NULL)); NewTab(); NewTab(); active_browser()->GetTabCount(&tab_count); ASSERT_EQ(3, tab_count); ASSERT_TRUE(OpenAndActivateNewBrowserWindow(NULL)); NewTab(); NewTab(); NewTab(); active_browser()->GetTabCount(&tab_count); ASSERT_EQ(4, tab_count); ASSERT_TRUE(CloseActiveWindow()); active_browser()->GetTabCount(&tab_count); if (tab_count == 2) { ASSERT_TRUE(CloseActiveWindow()); active_browser()->GetTabCount(&tab_count); ASSERT_EQ(3, tab_count); } else { ASSERT_EQ(3, tab_count); ASSERT_TRUE(CloseActiveWindow()); active_browser()->GetTabCount(&tab_count); ASSERT_EQ(2, tab_count); } ASSERT_FALSE(CloseActiveWindow()); } TEST_F(AutomatedUITestBase, IncognitoWindow) { int num_browser_windows; int num_normal_browser_windows; automation()->GetBrowserWindowCount(&num_browser_windows); ASSERT_EQ(1, num_browser_windows); automation()->GetNormalBrowserWindowCount(&num_normal_browser_windows); ASSERT_EQ(1, num_normal_browser_windows); ASSERT_TRUE(GoOffTheRecord()); ASSERT_TRUE(GoOffTheRecord()); automation()->GetBrowserWindowCount(&num_browser_windows); ASSERT_EQ(3, num_browser_windows); automation()->GetNormalBrowserWindowCount(&num_normal_browser_windows); ASSERT_EQ(1, num_normal_browser_windows); // There is only one normal window so it will not be closed. ASSERT_FALSE(CloseActiveWindow()); automation()->GetBrowserWindowCount(&num_browser_windows); ASSERT_EQ(3, num_browser_windows); automation()->GetNormalBrowserWindowCount(&num_normal_browser_windows); ASSERT_EQ(1, num_normal_browser_windows); set_active_browser(automation()->GetBrowserWindow(0)); ASSERT_TRUE(RunCommand(IDC_CLOSE_WINDOW)); set_active_browser(automation()->GetBrowserWindow(0)); ASSERT_TRUE(RunCommand(IDC_CLOSE_WINDOW)); automation()->GetBrowserWindowCount(&num_browser_windows); ASSERT_EQ(1, num_browser_windows); } TEST_F(AutomatedUITestBase, OpenCloseBrowserWindowWithAccelerator) { // Note: we don't use RunCommand(IDC_OPEN/CLOSE_WINDOW) to open/close // browser window in automated ui tests. Instead we use // OpenAndActivateNewBrowserWindow and CloseActiveWindow. // There are other parts of UI test that use the accelerators. This is // a unit test for those usage. ASSERT_TRUE(RunCommand(IDC_NEW_WINDOW)); int num_browser_windows; automation()->GetBrowserWindowCount(&num_browser_windows); ASSERT_EQ(2, num_browser_windows); ASSERT_TRUE(RunCommand(IDC_NEW_WINDOW)); ASSERT_TRUE(RunCommand(IDC_NEW_WINDOW)); ASSERT_TRUE(RunCommand(IDC_NEW_WINDOW)); ASSERT_TRUE(RunCommand(IDC_NEW_WINDOW)); ASSERT_TRUE(RunCommand(IDC_NEW_WINDOW)); automation()->GetBrowserWindowCount(&num_browser_windows); ASSERT_EQ(7, num_browser_windows); set_active_browser(automation()->GetBrowserWindow(0)); ASSERT_TRUE(RunCommand(IDC_CLOSE_WINDOW)); automation()->GetBrowserWindowCount(&num_browser_windows); ASSERT_EQ(6, num_browser_windows); set_active_browser(automation()->GetBrowserWindow(0)); ASSERT_TRUE(RunCommand(IDC_CLOSE_WINDOW)); set_active_browser(automation()->GetBrowserWindow(0)); ASSERT_TRUE(RunCommand(IDC_CLOSE_WINDOW)); set_active_browser(automation()->GetBrowserWindow(0)); ASSERT_TRUE(RunCommand(IDC_CLOSE_WINDOW)); set_active_browser(automation()->GetBrowserWindow(0)); ASSERT_TRUE(RunCommand(IDC_CLOSE_WINDOW)); set_active_browser(automation()->GetBrowserWindow(0)); ASSERT_TRUE(RunCommand(IDC_CLOSE_WINDOW)); automation()->GetBrowserWindowCount(&num_browser_windows); ASSERT_EQ(1, num_browser_windows); } TEST_F(AutomatedUITestBase, Navigate) { FilePath path_prefix(test_data_directory_.AppendASCII("session_history")); GURL url1(net::FilePathToFileURL(path_prefix.AppendASCII("bot1.html"))); GURL url2(net::FilePathToFileURL(path_prefix.AppendASCII("bot2.html"))); GURL url3(net::FilePathToFileURL(path_prefix.AppendASCII("bot3.html"))); GURL url; ASSERT_TRUE(Navigate(url1)); ASSERT_TRUE(GetActiveTab()->GetCurrentURL(&url)); ASSERT_EQ(url1, url); ASSERT_TRUE(Navigate(url2)); ASSERT_TRUE(GetActiveTab()->GetCurrentURL(&url)); ASSERT_EQ(url2, url); ASSERT_TRUE(Navigate(url3)); ASSERT_TRUE(GetActiveTab()->GetCurrentURL(&url)); ASSERT_EQ(url3, url); ASSERT_TRUE(BackButton()); ASSERT_TRUE(GetActiveTab()->GetCurrentURL(&url)); ASSERT_EQ(url2, url); ASSERT_TRUE(BackButton()); ASSERT_TRUE(GetActiveTab()->GetCurrentURL(&url)); ASSERT_EQ(url1, url); ASSERT_TRUE(ForwardButton()); ASSERT_TRUE(GetActiveTab()->GetCurrentURL(&url)); ASSERT_EQ(url2, url); ASSERT_TRUE(ReloadPage()); ASSERT_TRUE(GetActiveTab()->GetCurrentURL(&url)); ASSERT_EQ(url2, url); } <|endoftext|>
<commit_before>#include "classes.h" #include "msvc.h" #include <sycl.hpp> #include <chrono> #include <iostream> #include <string> #include <vector> #include <memory> using std::string; extern void compute_org(void*, int w, int h, int samps, Ray& cam, Vec& cx, Vec& cy, Vec r, Vec* c); extern void compute_org_openmp(void*, int w, int h, int samps, Ray& cam, Vec& cx, Vec& cy, Vec r, Vec* c); extern void compute_org_sp(void*, int w, int h, int samps, Ray& cam, Vec& cx, Vec& cy, Vec r, Vec* c); extern void compute_org_sp_openmp(void*, int w, int h, int samps, Ray& cam, Vec& cx, Vec& cy, Vec r, Vec* c); extern void compute_sycl_gtx(void* dev, int w, int h, int samps, Ray& cam_, Vec& cx_, Vec& cy_, Vec r_, Vec* c_); inline double clamp(double x) { return x < 0 ? 0 : x>1 ? 1 : x; } inline int toInt(double x) { return int(pow(clamp(x), 1 / 2.2) * 255 + .5); } void to_file(int w, int h, Vec* c, string filename) { FILE* f = fopen(filename.c_str(), "w"); // Write image to PPM file. fprintf(f, "P3\n%d %d\n%d\n", w, h, 255); for(int i = 0; i < w*h; i++) { fprintf(f, "%d %d %d\n", toInt(c[i].x), toInt(c[i].y), toInt(c[i].z)); } fclose(f); } using time_point = std::chrono::high_resolution_clock::time_point; auto now = []() { return std::chrono::high_resolution_clock::now(); }; auto duration = [](time_point before) { static const float to_seconds = 1e-6f; return std::chrono::duration_cast<std::chrono::microseconds>(now() - before).count() * to_seconds; }; struct testInfo { using function_ptr = void(*)(void*, int, int, int, Ray&, Vec&, Vec&, Vec, Vec*); string name; function_ptr test; std::unique_ptr<cl::sycl::device> dev; float lastTime = 0; static decltype(now()) startTime; static float totalTime; testInfo(string name, function_ptr test, cl::sycl::device* dev = nullptr) : name(name), test(test), dev(dev) {} testInfo(const testInfo&) = delete; testInfo(testInfo&& move) : name(std::move(move.name)), test(move.test), dev(std::move(move.dev)) {} }; decltype(now()) testInfo::startTime = now(); float testInfo::totalTime = 0; static std::vector<const testInfo> tests; static Ray cam(Vec(50, 52, 295.6), Vec(0, -0.042612, -1).norm()); // cam pos, dir bool tester(int w, int h, int samples, Vec& cx, Vec& cy, int iterations, int from, int to) { using namespace std; cout << "samples per pixel: " << samples << endl; Vec r; vector<Vec> empty_vectors(w*h, 0); vector<Vec> vectors; float time; for(int ti = from; ti < to; ++ti) { auto& t = tests[ti]; // Quality of Service // Prevent the user from waiting too long if(t.lastTime > 80) { continue; } cout << "Running test: " << t.name << endl; ns_erand::reset(); try { auto start = now(); for(int i = 0; i < iterations; ++i) { vectors = empty_vectors; t.test(t.dev.get(), w, h, samples, cam, cx, cy, r, vectors.data()); } time = (duration(start) / (float)iterations); } catch(cl::sycl::exception& e) { cerr << "SYCL error while testing: " << e.what() << endl; continue; } catch(exception& e) { cerr << "error while testing: " << e.what() << endl; continue; } cout << "time: " << time << endl; //to_file(w, h, vectors.data(), string("image_") + t.name + ".ppm"); t.lastTime = time; testInfo::totalTime = duration(testInfo::startTime); if(testInfo::totalTime > 600) { cout << "exceeded 10 minute limit, stopping" << endl; return false; } } return true; } template <class T> void printInfo(string description, const T& data, int offset = 0) { string indent; for(int i = 0; i < offset; ++i) { indent += '\t'; } std::cout << indent << description << ": " << data << std::endl; } void getDevices() { using namespace std; try { using namespace cl::sycl; auto platforms = platform::get_platforms(); int pNum = 0; for(auto& p : platforms) { cout << "- OpenCL platform " << pNum << ':' << endl; ++pNum; auto openclVersion = p.get_info<info::platform::version>(); printInfo("name", p.get_info<info::platform::name>(), 1); printInfo("vendor", p.get_info<info::platform::vendor>(), 1); printInfo("version", openclVersion, 1); printInfo("profile", p.get_info<info::platform::profile>(), 1); printInfo("extensions", p.get_info<info::platform::extensions>(), 1); auto devices = p.get_devices(); int dNum = 0; for(auto& d : devices) { cout << "\t-- OpenCL device " << dNum << ':' << endl; auto name = d.get_info<info::device::name>(); printInfo("name", d.get_info<info::device::name>(), 2); printInfo("device_type", (cl_device_type)d.get_info<info::device::device_type>(), 2); printInfo("vendor", d.get_info<info::device::vendor>(), 2); printInfo("device_version", d.get_info<info::device::device_version>(), 2); printInfo("driver_version", d.get_info<info::device::driver_version>(), 2); printInfo("opencl_version", d.get_info<info::device::opencl_version>(), 2); printInfo("single_fp_config", d.get_info<info::device::single_fp_config>(), 2); printInfo("double_fp_config", d.get_info<info::device::double_fp_config>(), 2); printInfo("profile", d.get_info<info::device::profile>(), 2); printInfo("error_correction_support", d.get_info<info::device::error_correction_support>(), 2); printInfo("host_unified_memory", d.get_info<info::device::host_unified_memory>(), 2); printInfo("max_clock_frequency", d.get_info<info::device::max_clock_frequency>(), 2); printInfo("max_compute_units", d.get_info<info::device::max_compute_units>(), 2); printInfo("max_work_item_dimensions", d.get_info<info::device::max_work_item_dimensions>(), 2); printInfo("max_work_group_size", d.get_info<info::device::max_work_group_size>(), 2); printInfo("address_bits", d.get_info<info::device::address_bits>(), 2); printInfo("max_mem_alloc_size", d.get_info<info::device::max_mem_alloc_size>(), 2); printInfo("global_mem_cache_line_size", d.get_info<info::device::global_mem_cache_line_size>(), 2); printInfo("global_mem_cache_size", d.get_info<info::device::global_mem_cache_size>(), 2); printInfo("global_mem_size", d.get_info<info::device::global_mem_size>(), 2); printInfo("max_constant_buffer_size", d.get_info<info::device::max_constant_buffer_size>(), 2); printInfo("max_constant_args", d.get_info<info::device::max_constant_args>(), 2); printInfo("local_mem_size", d.get_info<info::device::local_mem_size>(), 2); printInfo("extensions", d.get_info<info::device::extensions>(), 2); tests.emplace_back(name + ' ' + openclVersion, compute_sycl_gtx, new device(std::move(d))); ++dNum; } } } catch(cl::sycl::exception& e) { // TODO cout << "OpenCL not available: " << e.what() << endl; } } int main(int argc, char *argv[]) { using namespace std; cout << "smallpt SYCL tester" << endl; tests.emplace_back("org_single", compute_org_sp); tests.emplace_back("openmp_single", compute_org_sp_openmp); tests.emplace_back("org", compute_org); tests.emplace_back("openmp", compute_org_openmp); getDevices(); int w = 1024; int h = 768; Vec cx = Vec(w*.5135 / h); Vec cy = (cx%cam.d).norm()*.5135; auto numTests = tests.size(); int from = 2; int to = numTests; if(argc > 1) { from = atoi(argv[1]); if(argc > 2) { to = atoi(argv[2]); } } cout << "Going through tests in range [" << from << ',' << to << ')' << endl; if(false) { tester(w, h, 1, cx, cy, 1, from, to); cout << "Press any key to exit" << endl; cin.get(); return 0; } // Test suite int iterations = 1; bool canContinue; for(int samples = 10; samples < 10000; samples *= 2) { canContinue = tester(w, h, samples, cx, cy, iterations, from, to); if(!canContinue) { break; } } auto time = duration(testInfo::startTime); cout << "total test suite duration: " << time << endl; //cout << "Press any key to exit" << endl; //cin.get(); return 0; } <commit_msg>smallpt - tweaked testing parameters<commit_after>#include "classes.h" #include "msvc.h" #include <sycl.hpp> #include <chrono> #include <iostream> #include <string> #include <vector> #include <memory> using std::string; extern void compute_org(void*, int w, int h, int samps, Ray& cam, Vec& cx, Vec& cy, Vec r, Vec* c); extern void compute_org_openmp(void*, int w, int h, int samps, Ray& cam, Vec& cx, Vec& cy, Vec r, Vec* c); extern void compute_org_sp(void*, int w, int h, int samps, Ray& cam, Vec& cx, Vec& cy, Vec r, Vec* c); extern void compute_org_sp_openmp(void*, int w, int h, int samps, Ray& cam, Vec& cx, Vec& cy, Vec r, Vec* c); extern void compute_sycl_gtx(void* dev, int w, int h, int samps, Ray& cam_, Vec& cx_, Vec& cy_, Vec r_, Vec* c_); inline double clamp(double x) { return x < 0 ? 0 : x>1 ? 1 : x; } inline int toInt(double x) { return int(pow(clamp(x), 1 / 2.2) * 255 + .5); } void to_file(int w, int h, Vec* c, string filename) { FILE* f = fopen(filename.c_str(), "w"); // Write image to PPM file. fprintf(f, "P3\n%d %d\n%d\n", w, h, 255); for(int i = 0; i < w*h; i++) { fprintf(f, "%d %d %d\n", toInt(c[i].x), toInt(c[i].y), toInt(c[i].z)); } fclose(f); } using time_point = std::chrono::high_resolution_clock::time_point; auto now = []() { return std::chrono::high_resolution_clock::now(); }; auto duration = [](time_point before) { static const float to_seconds = 1e-6f; return std::chrono::duration_cast<std::chrono::microseconds>(now() - before).count() * to_seconds; }; struct testInfo { using function_ptr = void(*)(void*, int, int, int, Ray&, Vec&, Vec&, Vec, Vec*); string name; function_ptr test; std::unique_ptr<cl::sycl::device> dev; float lastTime = 0; static decltype(now()) startTime; static float totalTime; testInfo(string name, function_ptr test, cl::sycl::device* dev = nullptr) : name(name), test(test), dev(dev) {} testInfo(const testInfo&) = delete; testInfo(testInfo&& move) : name(std::move(move.name)), test(move.test), dev(std::move(move.dev)) {} }; decltype(now()) testInfo::startTime = now(); float testInfo::totalTime = 0; static std::vector<const testInfo> tests; static Ray cam(Vec(50, 52, 295.6), Vec(0, -0.042612, -1).norm()); // cam pos, dir bool tester(int w, int h, int samples, Vec& cx, Vec& cy, int iterations, int from, int to) { using namespace std; cout << "samples per pixel: " << samples << endl; Vec r; vector<Vec> empty_vectors(w*h, 0); vector<Vec> vectors; float time; for(int ti = from; ti < to; ++ti) { auto& t = tests[ti]; // Quality of Service // Prevent the user from waiting too long if(t.lastTime > 40) { continue; } cout << "Running test: " << t.name << endl; ns_erand::reset(); try { auto start = now(); for(int i = 0; i < iterations; ++i) { vectors = empty_vectors; t.test(t.dev.get(), w, h, samples, cam, cx, cy, r, vectors.data()); } time = (duration(start) / (float)iterations); } catch(cl::sycl::exception& e) { cerr << "SYCL error while testing: " << e.what() << endl; continue; } catch(exception& e) { cerr << "error while testing: " << e.what() << endl; continue; } cout << "time: " << time << endl; //to_file(w, h, vectors.data(), string("image_") + t.name + ".ppm"); t.lastTime = time; testInfo::totalTime = duration(testInfo::startTime); if(testInfo::totalTime > 300) { cout << "exceeded 5 minute limit, stopping" << endl; return false; } } return true; } template <class T> void printInfo(string description, const T& data, int offset = 0) { string indent; for(int i = 0; i < offset; ++i) { indent += '\t'; } std::cout << indent << description << ": " << data << std::endl; } void getDevices() { using namespace std; try { using namespace cl::sycl; auto platforms = platform::get_platforms(); int pNum = 0; for(auto& p : platforms) { cout << "- OpenCL platform " << pNum << ':' << endl; ++pNum; auto openclVersion = p.get_info<info::platform::version>(); printInfo("name", p.get_info<info::platform::name>(), 1); printInfo("vendor", p.get_info<info::platform::vendor>(), 1); printInfo("version", openclVersion, 1); printInfo("profile", p.get_info<info::platform::profile>(), 1); printInfo("extensions", p.get_info<info::platform::extensions>(), 1); auto devices = p.get_devices(); int dNum = 0; for(auto& d : devices) { cout << "\t-- OpenCL device " << dNum << ':' << endl; auto name = d.get_info<info::device::name>(); printInfo("name", d.get_info<info::device::name>(), 2); printInfo("device_type", (cl_device_type)d.get_info<info::device::device_type>(), 2); printInfo("vendor", d.get_info<info::device::vendor>(), 2); printInfo("device_version", d.get_info<info::device::device_version>(), 2); printInfo("driver_version", d.get_info<info::device::driver_version>(), 2); printInfo("opencl_version", d.get_info<info::device::opencl_version>(), 2); printInfo("single_fp_config", d.get_info<info::device::single_fp_config>(), 2); printInfo("double_fp_config", d.get_info<info::device::double_fp_config>(), 2); printInfo("profile", d.get_info<info::device::profile>(), 2); printInfo("error_correction_support", d.get_info<info::device::error_correction_support>(), 2); printInfo("host_unified_memory", d.get_info<info::device::host_unified_memory>(), 2); printInfo("max_clock_frequency", d.get_info<info::device::max_clock_frequency>(), 2); printInfo("max_compute_units", d.get_info<info::device::max_compute_units>(), 2); printInfo("max_work_item_dimensions", d.get_info<info::device::max_work_item_dimensions>(), 2); printInfo("max_work_group_size", d.get_info<info::device::max_work_group_size>(), 2); printInfo("address_bits", d.get_info<info::device::address_bits>(), 2); printInfo("max_mem_alloc_size", d.get_info<info::device::max_mem_alloc_size>(), 2); printInfo("global_mem_cache_line_size", d.get_info<info::device::global_mem_cache_line_size>(), 2); printInfo("global_mem_cache_size", d.get_info<info::device::global_mem_cache_size>(), 2); printInfo("global_mem_size", d.get_info<info::device::global_mem_size>(), 2); printInfo("max_constant_buffer_size", d.get_info<info::device::max_constant_buffer_size>(), 2); printInfo("max_constant_args", d.get_info<info::device::max_constant_args>(), 2); printInfo("local_mem_size", d.get_info<info::device::local_mem_size>(), 2); printInfo("extensions", d.get_info<info::device::extensions>(), 2); tests.emplace_back(name + ' ' + openclVersion, compute_sycl_gtx, new device(std::move(d))); ++dNum; } } } catch(cl::sycl::exception& e) { // TODO cout << "OpenCL not available: " << e.what() << endl; } } int main(int argc, char *argv[]) { using namespace std; cout << "smallpt SYCL tester" << endl; tests.emplace_back("org_single", compute_org_sp); tests.emplace_back("openmp_single", compute_org_sp_openmp); tests.emplace_back("org", compute_org); tests.emplace_back("openmp", compute_org_openmp); getDevices(); int w = 1024; int h = 768; Vec cx = Vec(w*.5135 / h); Vec cy = (cx%cam.d).norm()*.5135; auto numTests = tests.size(); int from = 2; int to = numTests; if(argc > 1) { from = atoi(argv[1]); if(argc > 2) { to = atoi(argv[2]); } } cout << "Going through tests in range [" << from << ',' << to << ')' << endl; if(false) { tester(w, h, 1, cx, cy, 1, from, to); cout << "Press any key to exit" << endl; cin.get(); return 0; } // Test suite int iterations = 1; bool canContinue; for(int samples = 5; samples < 10000; samples *= 2) { canContinue = tester(w, h, samples, cx, cy, iterations, from, to); if(!canContinue) { break; } } auto time = duration(testInfo::startTime); cout << "total test suite duration: " << time << endl; //cout << "Press any key to exit" << endl; //cin.get(); return 0; } <|endoftext|>
<commit_before>// Shell program for running a sequential multi-stage DIFT #include <sys/time.h> #include <sys/types.h> #include <sys/socket.h> #include <sys/stat.h> #include <sys/wait.h> #include <sys/mman.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <fcntl.h> #include <netdb.h> #include <errno.h> #include <pthread.h> #include <atomic> using namespace std; #include "util.h" #include "streamserver.h" //#define DETAILS #define STATUS_INIT 0 #define STATUS_STARTING 1 #define STATUS_EXECUTING 2 #define STATUS_STREAM 3 #define STATUS_DONE 4 struct epoch_ctl { int status; char inputqname[256]; pid_t cpid; pid_t spid; // For timings struct timeval tv_start; struct timeval tv_start_dift; struct timeval tv_start_stream; struct timeval tv_done; }; int fd; // Persistent descriptor for replay device // May eventually want to support >1 taint tracking at the same time, but not for now. void* do_stream (void* arg) { int s = (int) arg; int rc; struct timeval tv_start, tv_done; gettimeofday (&tv_start, NULL); // Receive control data struct epoch_hdr ehdr; rc = read (s, &ehdr, sizeof(ehdr)); if (rc != sizeof(ehdr)) { fprintf (stderr, "Cannot recieve header,rc=%d\n", rc); return NULL; } u_long epochs = ehdr.epochs; struct epoch_data edata[epochs]; struct epoch_ctl ectl[epochs]; rc = read (s, edata, sizeof(struct epoch_data)*epochs); if (rc != sizeof(struct epoch_data)*epochs) { fprintf (stderr, "Cannot recieve epochs,rc=%d\n", rc); return NULL; } // Set up shared memory regions for queues u_long qcnt = epochs+1; if (ehdr.finish_flag) qcnt--; for (u_long i = 0; i < qcnt; i++) { if (i == 0 && ehdr.start_flag) continue; // No queue needed sprintf(ectl[i].inputqname, "/input_queue%lu", i); int iqfd = shm_open (ectl[i].inputqname, O_CREAT|O_RDWR|O_TRUNC, 0644); if (iqfd < 0) { fprintf (stderr, "Cannot create input queue %s,errno=%d\n", ectl[i].inputqname, errno); return NULL; } rc = ftruncate(iqfd, TAINTQSIZE); if (rc < 0) { fprintf (stderr, "Cannot truncate input queue %s,errno=%d\n", ectl[i].inputqname, errno); return NULL; } close (iqfd); } // Start all the epochs at once for (u_long i = 0; i < epochs; i++) { ectl[i].cpid = fork (); if (ectl[i].cpid == 0) { if (i > 0) { char attach[80]; sprintf (attach, "--attach_offset=%d,%lu", edata[i].start_pid, edata[i].start_syscall); rc = execl("./resume", "resume", "-p", ehdr.dirname, "--pthread", "../eglibc-2.15/prefix/lib", attach, NULL); } else { rc = execl("./resume", "resume", "-p", ehdr.dirname, "--pthread", "../eglibc-2.15/prefix/lib", NULL); } fprintf (stderr, "execl of resume failed, rc=%d, errno=%d\n", rc, errno); return NULL; } else { gettimeofday (&ectl[i].tv_start, NULL); ectl[i].status = STATUS_STARTING; } } // Now attach pin to all of the epoch processes u_long executing = 0; do { for (u_long i = 0; i < epochs; i++) { if (ectl[i].status == STATUS_STARTING) { rc = get_attach_status (fd, ectl[i].cpid); if (rc == 1) { pid_t mpid = fork(); if (mpid == 0) { char cpids[80], syscalls[80], output_filter[80]; const char* args[256]; int argcnt = 0; args[argcnt++] = "pin"; args[argcnt++] = "-pid"; sprintf (cpids, "%d", ectl[i].cpid); args[argcnt++] = cpids; args[argcnt++] = "-t"; args[argcnt++] = "../dift/obj-ia32/linkage_data.so"; if (i < epochs-1) { if (i == 0) { sprintf (syscalls, "%ld", edata[i].stop_syscall); } else { sprintf (syscalls, "%ld", edata[i].stop_syscall-edata[i].start_syscall+1); } args[argcnt++] = "-l"; args[argcnt++] = syscalls; args[argcnt++] = "-ao"; // Last epoch does not need to trace to final addresses } if (i > 0) { args[argcnt++] = "-so"; } if (edata[i].filter_syscall) { sprintf (output_filter, "%lu", edata[i].filter_syscall); args[argcnt++] = "-ofs"; args[argcnt++] = output_filter; } args[argcnt++] = NULL; rc = execv ("../../../pin/pin", (char **) args); fprintf (stderr, "execv of pin tool failed, rc=%d, errno=%d\n", rc, errno); return NULL; } else { gettimeofday (&ectl[i].tv_start_dift, NULL); ectl[i].status = STATUS_EXECUTING; executing++; #ifdef DETAILS printf ("%lu/%lu epochs executing\n", executing, epochs); #endif } } } } } while (executing < epochs); // Wait for children to complete u_long epochs_done = 0; do { int status; pid_t wpid = waitpid (-1, &status, 0); if (wpid < 0) { fprintf (stderr, "waitpid returns %d, errno %d\n", rc, errno); return NULL; } else { for (u_long i = 0; i < epochs; i++) { if (wpid == ectl[i].cpid) { #ifdef DETAILS printf ("DIFT of epoch %lu is done\n", i); #endif ectl[i].spid = fork (); if (ectl[i].spid == 0) { // Now start up a stream processor for this epoch const char* args[256]; char dirname[80]; int argcnt = 0; args[argcnt++] = "stream"; sprintf (dirname, "/tmp/%d", ectl[i].cpid); args[argcnt++] = dirname; if (i < epochs-1 || !ehdr.finish_flag) { args[argcnt++] = "-iq"; args[argcnt++] = ectl[i+1].inputqname; } if (i == epochs-1 && !ehdr.finish_flag) { args[argcnt++] = "-ih"; } if (i > 0 || !ehdr.start_flag) { args[argcnt++] = "-oq"; args[argcnt++] = ectl[i].inputqname; } if (i == 0 && !ehdr.start_flag) { args[argcnt++] = "-oh"; args[argcnt++] = ehdr.next_host; } args[argcnt++] = NULL; rc = execv ("../dift/obj-ia32/stream", (char **) args); fprintf (stderr, "execv of stream failed, rc=%d, errno=%d\n", rc, errno); return NULL; } else { gettimeofday (&ectl[i].tv_start_stream, NULL); ectl[i].status = STATUS_STREAM; } } else if (wpid == ectl[i].spid) { gettimeofday (&ectl[i].tv_done, NULL); ectl[i].status = STATUS_DONE; epochs_done++; } } } } while (epochs_done < epochs); gettimeofday (&tv_done, NULL); // Clean up shared memory regions for queues for (u_long i = 0; i < qcnt; i++) { if (i == 0 && ehdr.start_flag) continue; // No queue needed rc = shm_unlink (ectl[i].inputqname); if (rc < 0) { fprintf (stderr, "Cannot unlink input queue %s,errno=%d\n", ectl[i].inputqname, errno); return NULL; } } printf ("Overall:\n"); printf ("\tStart time: %ld.%06ld\n", tv_start.tv_sec, tv_start.tv_usec); printf ("\tEnd time: %ld.%06ld\n", tv_done.tv_sec, tv_done.tv_usec); for (u_long i = 0; i < epochs; i++) { printf ("Epoch %lu:\n", i); printf ("\tEpoch start time: %ld.%06ld\n", ectl[i].tv_start.tv_sec, ectl[i].tv_start.tv_usec); printf ("\tDIFT start time: %ld.%06ld\n", ectl[i].tv_start_dift.tv_sec, ectl[i].tv_start_dift.tv_usec); printf ("\tStream start time: %ld.%06ld\n", ectl[i].tv_start_stream.tv_sec, ectl[i].tv_start_stream.tv_usec); printf ("\tEpoch end time: %ld.%06ld\n", ectl[i].tv_done.tv_sec, ectl[i].tv_done.tv_usec); } return NULL; } int main (int argc, char* argv[]) { struct timeval tv_start, tv_start_merge, tv_done; char dirname[80]; int rc, status, epochs, gstart, gend, i, executing, epochs_done; struct epoch* epoch; pid_t ppid; u_long merge_entries = 0; int group_by = 0; fd = open ("/dev/spec0", O_RDWR); if (fd < 0) { perror("open /dev/spec0"); return fd; } // Listen for incoming commands int c = socket (AF_INET, SOCK_STREAM, 0); if (c < 0) { fprintf (stderr, "Cannot create listening socket, errno=%d\n", errno); return c; } struct sockaddr_in addr; addr.sin_family = AF_INET; addr.sin_port = htons(STREAMSERVER_PORT); addr.sin_addr.s_addr = INADDR_ANY; rc = bind (c, (struct sockaddr *) &addr, sizeof(addr)); if (rc < 0) { fprintf (stderr, "Cannot bind socket, errno=%d\n", errno); return rc; } rc = listen (c, 5); if (rc < 0) { fprintf (stderr, "Cannot listen on socket, errno=%d\n", errno); return rc; } while (1) { int s = accept (c, NULL, NULL); if (s < 0) { fprintf (stderr, "Cannot accept connection, errno=%d\n", errno); return s; } // Spawn a thread to handle this request pthread_t tid; rc = pthread_create (&tid, NULL, do_stream, (void *) s); if (rc < 0) { fprintf (stderr, "Cannot spawn stream thread,rc=%d\n", rc); } } return 0; } <commit_msg>Fixed up DIFT params<commit_after>// Shell program for running a sequential multi-stage DIFT #include <sys/time.h> #include <sys/types.h> #include <sys/socket.h> #include <sys/stat.h> #include <sys/wait.h> #include <sys/mman.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <fcntl.h> #include <netdb.h> #include <errno.h> #include <pthread.h> #include <atomic> using namespace std; #include "util.h" #include "streamserver.h" //#define DETAILS #define STATUS_INIT 0 #define STATUS_STARTING 1 #define STATUS_EXECUTING 2 #define STATUS_STREAM 3 #define STATUS_DONE 4 struct epoch_ctl { int status; char inputqname[256]; pid_t cpid; pid_t spid; // For timings struct timeval tv_start; struct timeval tv_start_dift; struct timeval tv_start_stream; struct timeval tv_done; }; int fd; // Persistent descriptor for replay device // May eventually want to support >1 taint tracking at the same time, but not for now. void* do_stream (void* arg) { int s = (int) arg; int rc; struct timeval tv_start, tv_done; gettimeofday (&tv_start, NULL); // Receive control data struct epoch_hdr ehdr; rc = read (s, &ehdr, sizeof(ehdr)); if (rc != sizeof(ehdr)) { fprintf (stderr, "Cannot recieve header,rc=%d\n", rc); return NULL; } u_long epochs = ehdr.epochs; struct epoch_data edata[epochs]; struct epoch_ctl ectl[epochs]; rc = read (s, edata, sizeof(struct epoch_data)*epochs); if (rc != sizeof(struct epoch_data)*epochs) { fprintf (stderr, "Cannot recieve epochs,rc=%d\n", rc); return NULL; } // Set up shared memory regions for queues u_long qcnt = epochs+1; if (ehdr.finish_flag) qcnt--; for (u_long i = 0; i < qcnt; i++) { if (i == 0 && ehdr.start_flag) continue; // No queue needed sprintf(ectl[i].inputqname, "/input_queue%lu", i); int iqfd = shm_open (ectl[i].inputqname, O_CREAT|O_RDWR|O_TRUNC, 0644); if (iqfd < 0) { fprintf (stderr, "Cannot create input queue %s,errno=%d\n", ectl[i].inputqname, errno); return NULL; } rc = ftruncate(iqfd, TAINTQSIZE); if (rc < 0) { fprintf (stderr, "Cannot truncate input queue %s,errno=%d\n", ectl[i].inputqname, errno); return NULL; } close (iqfd); } // Start all the epochs at once for (u_long i = 0; i < epochs; i++) { ectl[i].cpid = fork (); if (ectl[i].cpid == 0) { if (i > 0) { char attach[80]; sprintf (attach, "--attach_offset=%d,%lu", edata[i].start_pid, edata[i].start_syscall); rc = execl("./resume", "resume", "-p", ehdr.dirname, "--pthread", "../eglibc-2.15/prefix/lib", attach, NULL); } else { rc = execl("./resume", "resume", "-p", ehdr.dirname, "--pthread", "../eglibc-2.15/prefix/lib", NULL); } fprintf (stderr, "execl of resume failed, rc=%d, errno=%d\n", rc, errno); return NULL; } else { gettimeofday (&ectl[i].tv_start, NULL); ectl[i].status = STATUS_STARTING; } } // Now attach pin to all of the epoch processes u_long executing = 0; do { for (u_long i = 0; i < epochs; i++) { if (ectl[i].status == STATUS_STARTING) { rc = get_attach_status (fd, ectl[i].cpid); if (rc == 1) { pid_t mpid = fork(); if (mpid == 0) { char cpids[80], syscalls[80], output_filter[80]; const char* args[256]; int argcnt = 0; args[argcnt++] = "pin"; args[argcnt++] = "-pid"; sprintf (cpids, "%d", ectl[i].cpid); args[argcnt++] = cpids; args[argcnt++] = "-t"; args[argcnt++] = "../dift/obj-ia32/linkage_data.so"; if (i < epochs-1 || !ehdr.finish_flag) { if (i == 0 && ehdr.start_flag) { sprintf (syscalls, "%ld", edata[i].stop_syscall); } else { sprintf (syscalls, "%ld", edata[i].stop_syscall-edata[i].start_syscall+1); } args[argcnt++] = "-l"; args[argcnt++] = syscalls; args[argcnt++] = "-ao"; // Last epoch does not need to trace to final addresses } if (i > 0 || !ehdr.start_flag) { args[argcnt++] = "-so"; } if (edata[i].filter_syscall) { sprintf (output_filter, "%lu", edata[i].filter_syscall); args[argcnt++] = "-ofs"; args[argcnt++] = output_filter; } args[argcnt++] = NULL; rc = execv ("../../../pin/pin", (char **) args); fprintf (stderr, "execv of pin tool failed, rc=%d, errno=%d\n", rc, errno); return NULL; } else { gettimeofday (&ectl[i].tv_start_dift, NULL); ectl[i].status = STATUS_EXECUTING; executing++; #ifdef DETAILS printf ("%lu/%lu epochs executing\n", executing, epochs); #endif } } } } } while (executing < epochs); // Wait for children to complete u_long epochs_done = 0; do { int status; pid_t wpid = waitpid (-1, &status, 0); if (wpid < 0) { fprintf (stderr, "waitpid returns %d, errno %d\n", rc, errno); return NULL; } else { for (u_long i = 0; i < epochs; i++) { if (wpid == ectl[i].cpid) { #ifdef DETAILS printf ("DIFT of epoch %lu is done\n", i); #endif ectl[i].spid = fork (); if (ectl[i].spid == 0) { // Now start up a stream processor for this epoch const char* args[256]; char dirname[80]; int argcnt = 0; args[argcnt++] = "stream"; sprintf (dirname, "/tmp/%d", ectl[i].cpid); args[argcnt++] = dirname; if (i < epochs-1 || !ehdr.finish_flag) { args[argcnt++] = "-iq"; args[argcnt++] = ectl[i+1].inputqname; } if (i == epochs-1 && !ehdr.finish_flag) { args[argcnt++] = "-ih"; } if (i > 0 || !ehdr.start_flag) { args[argcnt++] = "-oq"; args[argcnt++] = ectl[i].inputqname; } if (i == 0 && !ehdr.start_flag) { args[argcnt++] = "-oh"; args[argcnt++] = ehdr.next_host; } args[argcnt++] = NULL; rc = execv ("../dift/obj-ia32/stream", (char **) args); fprintf (stderr, "execv of stream failed, rc=%d, errno=%d\n", rc, errno); return NULL; } else { gettimeofday (&ectl[i].tv_start_stream, NULL); ectl[i].status = STATUS_STREAM; } } else if (wpid == ectl[i].spid) { gettimeofday (&ectl[i].tv_done, NULL); ectl[i].status = STATUS_DONE; epochs_done++; } } } } while (epochs_done < epochs); gettimeofday (&tv_done, NULL); // Clean up shared memory regions for queues for (u_long i = 0; i < qcnt; i++) { if (i == 0 && ehdr.start_flag) continue; // No queue needed rc = shm_unlink (ectl[i].inputqname); if (rc < 0) { fprintf (stderr, "Cannot unlink input queue %s,errno=%d\n", ectl[i].inputqname, errno); return NULL; } } printf ("Overall:\n"); printf ("\tStart time: %ld.%06ld\n", tv_start.tv_sec, tv_start.tv_usec); printf ("\tEnd time: %ld.%06ld\n", tv_done.tv_sec, tv_done.tv_usec); for (u_long i = 0; i < epochs; i++) { printf ("Epoch %lu:\n", i); printf ("\tEpoch start time: %ld.%06ld\n", ectl[i].tv_start.tv_sec, ectl[i].tv_start.tv_usec); printf ("\tDIFT start time: %ld.%06ld\n", ectl[i].tv_start_dift.tv_sec, ectl[i].tv_start_dift.tv_usec); printf ("\tStream start time: %ld.%06ld\n", ectl[i].tv_start_stream.tv_sec, ectl[i].tv_start_stream.tv_usec); printf ("\tEpoch end time: %ld.%06ld\n", ectl[i].tv_done.tv_sec, ectl[i].tv_done.tv_usec); } return NULL; } int main (int argc, char* argv[]) { struct timeval tv_start, tv_start_merge, tv_done; char dirname[80]; int rc, status, epochs, gstart, gend, i, executing, epochs_done; struct epoch* epoch; pid_t ppid; u_long merge_entries = 0; int group_by = 0; fd = open ("/dev/spec0", O_RDWR); if (fd < 0) { perror("open /dev/spec0"); return fd; } // Listen for incoming commands int c = socket (AF_INET, SOCK_STREAM, 0); if (c < 0) { fprintf (stderr, "Cannot create listening socket, errno=%d\n", errno); return c; } struct sockaddr_in addr; addr.sin_family = AF_INET; addr.sin_port = htons(STREAMSERVER_PORT); addr.sin_addr.s_addr = INADDR_ANY; rc = bind (c, (struct sockaddr *) &addr, sizeof(addr)); if (rc < 0) { fprintf (stderr, "Cannot bind socket, errno=%d\n", errno); return rc; } rc = listen (c, 5); if (rc < 0) { fprintf (stderr, "Cannot listen on socket, errno=%d\n", errno); return rc; } while (1) { int s = accept (c, NULL, NULL); if (s < 0) { fprintf (stderr, "Cannot accept connection, errno=%d\n", errno); return s; } // Spawn a thread to handle this request pthread_t tid; rc = pthread_create (&tid, NULL, do_stream, (void *) s); if (rc < 0) { fprintf (stderr, "Cannot spawn stream thread,rc=%d\n", rc); } } return 0; } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: ignoreKiKuFollowedBySa_ja_JP.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: rt $ $Date: 2003-04-08 16:02:55 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ // prevent internal compiler error with MSVC6SP3 #include <stl/utility> #define TRANSLITERATION_KiKuFollowedBySa_ja_JP #include <transliteration_Ignore.hxx> using namespace com::sun::star::uno; using namespace com::sun::star::lang; using namespace rtl; namespace com { namespace sun { namespace star { namespace i18n { OUString SAL_CALL ignoreKiKuFollowedBySa_ja_JP::folding( const OUString& inStr, sal_Int32 startPos, sal_Int32 nCount, Sequence< sal_Int32 >& offset ) throw(RuntimeException) { // Create a string buffer which can hold nCount + 1 characters. // The reference count is 0 now. rtl_uString * newStr = x_rtl_uString_new_WithLength( nCount ); // defined in x_rtl_ustring.h sal_Unicode * dst = newStr->buffer; const sal_Unicode * src = inStr.getStr() + startPos; sal_Int32 *p, position; if (useOffset) { // Allocate nCount length to offset argument. offset.realloc( nCount ); p = offset.getArray(); position = startPos; } // sal_Unicode previousChar = *src ++; sal_Unicode currentChar; // Translation while (-- nCount > 0) { currentChar = *src ++; // KU + Sa-So --> KI + Sa-So if (previousChar == 0x30AF ) { // KATAKANA LETTER KU if (0x30B5 <= currentChar && // KATAKANA LETTER SA currentChar <= 0x30BE) { // KATAKANA LETTER ZO if (useOffset) { *p ++ = position++; *p ++ = position++; } *dst ++ = 0x30AD; // KATAKANA LETTER KI *dst ++ = currentChar; previousChar = *src ++; nCount --; continue; } } if (useOffset) *p ++ = position++; *dst ++ = previousChar; previousChar = currentChar; } if (nCount == 0) { if (useOffset) *p = position; *dst ++ = previousChar; } *dst = (sal_Unicode) 0; newStr->length = sal_Int32(dst - newStr->buffer); if (useOffset) offset.realloc(newStr->length); return OUString( newStr ); // defined in rtl/usrting. The reference count is increased from 0 to 1. } } } } } <commit_msg>INTEGRATION: CWS ooo20030412 (1.2.44); FILE MERGED 2003/04/12 22:31:26 mh 1.2.44.2: RESYNC: (1.2-1.5); FILE MERGED 2003/04/11 11:38:38 mh 1.2.44.1: join: from ooo11beta<commit_after>/************************************************************************* * * $RCSfile: ignoreKiKuFollowedBySa_ja_JP.cxx,v $ * * $Revision: 1.6 $ * * last change: $Author: hr $ $Date: 2003-04-28 16:51:19 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ // prevent internal compiler error with MSVC6SP3 #include <utility> #define TRANSLITERATION_KiKuFollowedBySa_ja_JP #include <transliteration_Ignore.hxx> using namespace com::sun::star::uno; using namespace com::sun::star::lang; using namespace rtl; namespace com { namespace sun { namespace star { namespace i18n { OUString SAL_CALL ignoreKiKuFollowedBySa_ja_JP::folding( const OUString& inStr, sal_Int32 startPos, sal_Int32 nCount, Sequence< sal_Int32 >& offset ) throw(RuntimeException) { // Create a string buffer which can hold nCount + 1 characters. // The reference count is 0 now. rtl_uString * newStr = x_rtl_uString_new_WithLength( nCount ); // defined in x_rtl_ustring.h sal_Unicode * dst = newStr->buffer; const sal_Unicode * src = inStr.getStr() + startPos; sal_Int32 *p, position; if (useOffset) { // Allocate nCount length to offset argument. offset.realloc( nCount ); p = offset.getArray(); position = startPos; } // sal_Unicode previousChar = *src ++; sal_Unicode currentChar; // Translation while (-- nCount > 0) { currentChar = *src ++; // KU + Sa-So --> KI + Sa-So if (previousChar == 0x30AF ) { // KATAKANA LETTER KU if (0x30B5 <= currentChar && // KATAKANA LETTER SA currentChar <= 0x30BE) { // KATAKANA LETTER ZO if (useOffset) { *p ++ = position++; *p ++ = position++; } *dst ++ = 0x30AD; // KATAKANA LETTER KI *dst ++ = currentChar; previousChar = *src ++; nCount --; continue; } } if (useOffset) *p ++ = position++; *dst ++ = previousChar; previousChar = currentChar; } if (nCount == 0) { if (useOffset) *p = position; *dst ++ = previousChar; } *dst = (sal_Unicode) 0; newStr->length = sal_Int32(dst - newStr->buffer); if (useOffset) offset.realloc(newStr->length); return OUString( newStr ); // defined in rtl/usrting. The reference count is increased from 0 to 1. } } } } } <|endoftext|>
<commit_before> // Simple macro showing capabilities of TGSpeedo widget. #include "TSystem.h" #include "TGFrame.h" #include "TGWindow.h" #include "TGSpeedo.h" class TGShapedMain : public TGMainFrame { protected: TGSpeedo *fSpeedo; // analog meter Int_t fActInfo; // actual information value Bool_t fRunning; // kTRUE while updating infos public: TGShapedMain(const TGWindow *p, int w, int h); virtual ~TGShapedMain(); void CloseWindow(); TGSpeedo *GetSpeedo() const { return fSpeedo; } Int_t GetActInfo() const { return fActInfo; } Bool_t IsRunning() const { return fRunning; } void ToggleInfos(); }; //______________________________________________________________________________ TGShapedMain::TGShapedMain(const TGWindow *p, int w, int h) : TGMainFrame(p, w, h) { // Constructor. fActInfo = 1; fRunning = kTRUE; fSpeedo = new TGSpeedo(this, 0.0, 100.0, "CPU", "[%]"); fSpeedo->Connect("OdoClicked()", "TGShapedMain", this, "ToggleInfos()"); fSpeedo->Connect("LedClicked()", "TGShapedMain", this, "CloseWindow()"); TGMainFrame::Connect("CloseWindow()", "TGShapedMain", this, "CloseWindow()"); AddFrame(fSpeedo, new TGLayoutHints(kLHintsCenterX | kLHintsCenterX, 0, 0, 0, 0)); fSpeedo->SetDisplayText("Used RAM", "[MB]"); MapSubwindows(); MapWindow(); // To avoid closing the window while TGSpeedo is drawing DontCallClose(); Resize(GetDefaultSize()); // Set fixed size SetWMSizeHints(GetDefaultWidth(), GetDefaultHeight(), GetDefaultWidth(), GetDefaultHeight(), 1, 1); SetWindowName("ROOT CPU Load Meter"); } //______________________________________________________________________________ void TGShapedMain::ToggleInfos() { // Toggle information displayed in Analog Meter if (fActInfo < 2) fActInfo++; else fActInfo = 0; if (fActInfo == 0) fSpeedo->SetDisplayText("Total RAM", "[MB]"); else if (fActInfo == 1) fSpeedo->SetDisplayText("Used RAM", "[MB]"); else if (fActInfo == 2) fSpeedo->SetDisplayText("Free RAM", "[MB]"); } //______________________________________________________________________________ TGShapedMain::~TGShapedMain() { // Destructor. } //______________________________________________________________________________ void TGShapedMain::CloseWindow() { // Close Window. // stop updating fRunning = kFALSE; // reset kDontCallClose bit to be able to really close the window ResetBit(kDontCallClose); } //______________________________________________________________________________ void CPUMeter() { // Main application. MemInfo_t memInfo; CpuInfo_t cpuInfo; Float_t act_load, prev_load = 0.0; Int_t i, memUsage, old_memUsage = 0; TGShapedMain *mainWindow = new TGShapedMain(gClient->GetRoot(), 500, 200); TGSpeedo *speedo = mainWindow->GetSpeedo(); // set threshold values speedo->SetThresholds(12.5, 50.0, 87.5); // set threshold colors speedo->SetThresholdColors(TGSpeedo::kGreen, TGSpeedo::kOrange, TGSpeedo::kRed); // enable threshold speedo->EnableThreshold(); speedo->SetScaleValue(0.0, 5); // enable peak marker speedo->EnablePeakMark(); // update the TGSpeedo widget gSystem->GetCpuInfo(&cpuInfo); gSystem->GetMemInfo(&memInfo); gSystem->ProcessEvents(); while (mainWindow->IsRunning() && mainWindow->IsMapped()) { // Get CPU informations gSystem->GetCpuInfo(&cpuInfo); // actual CPU load act_load = cpuInfo.fTotal; // Get Memory informations gSystem->GetMemInfo(&memInfo); // choose which value to display if (mainWindow->GetActInfo() == 0) memUsage = memInfo.fMemTotal; else if (mainWindow->GetActInfo() == 1) memUsage = memInfo.fMemUsed; else if (mainWindow->GetActInfo() == 2) memUsage = memInfo.fMemFree; // small threshold to avoid "trembling" needle if (fabs(act_load-prev_load) > 0.9) { speedo->SetScaleValue(act_load, 5); prev_load = act_load; } // update only if value has changed if (memUsage != old_memUsage) { speedo->SetOdoValue(memUsage); old_memUsage = memUsage; } // sleep a bit gSystem->ProcessEvents(); gSystem->Sleep(250); } mainWindow->CloseWindow(); } <commit_msg>From Bertrand: Modified CPUMeter.C macro accordingly to the latest changes in TSystem.<commit_after> // Simple macro showing capabilities of TGSpeedo widget. #include "TSystem.h" #include "TGFrame.h" #include "TGWindow.h" #include "TGSpeedo.h" class TGShapedMain : public TGMainFrame { protected: TGSpeedo *fSpeedo; // analog meter Int_t fActInfo; // actual information value Bool_t fRunning; // kTRUE while updating infos public: TGShapedMain(const TGWindow *p, int w, int h); virtual ~TGShapedMain(); void CloseWindow(); TGSpeedo *GetSpeedo() const { return fSpeedo; } Int_t GetActInfo() const { return fActInfo; } Bool_t IsRunning() const { return fRunning; } void ToggleInfos(); }; //______________________________________________________________________________ TGShapedMain::TGShapedMain(const TGWindow *p, int w, int h) : TGMainFrame(p, w, h) { // Constructor. fActInfo = 1; fRunning = kTRUE; fSpeedo = new TGSpeedo(this, 0.0, 100.0, "CPU", "[%]"); fSpeedo->Connect("OdoClicked()", "TGShapedMain", this, "ToggleInfos()"); fSpeedo->Connect("LedClicked()", "TGShapedMain", this, "CloseWindow()"); TGMainFrame::Connect("CloseWindow()", "TGShapedMain", this, "CloseWindow()"); AddFrame(fSpeedo, new TGLayoutHints(kLHintsCenterX | kLHintsCenterX, 0, 0, 0, 0)); fSpeedo->SetDisplayText("Used RAM", "[MB]"); MapSubwindows(); MapWindow(); // To avoid closing the window while TGSpeedo is drawing DontCallClose(); Resize(GetDefaultSize()); // Set fixed size SetWMSizeHints(GetDefaultWidth(), GetDefaultHeight(), GetDefaultWidth(), GetDefaultHeight(), 1, 1); SetWindowName("ROOT CPU Load Meter"); } //______________________________________________________________________________ void TGShapedMain::ToggleInfos() { // Toggle information displayed in Analog Meter if (fActInfo < 2) fActInfo++; else fActInfo = 0; if (fActInfo == 0) fSpeedo->SetDisplayText("Total RAM", "[MB]"); else if (fActInfo == 1) fSpeedo->SetDisplayText("Used RAM", "[MB]"); else if (fActInfo == 2) fSpeedo->SetDisplayText("Free RAM", "[MB]"); } //______________________________________________________________________________ TGShapedMain::~TGShapedMain() { // Destructor. } //______________________________________________________________________________ void TGShapedMain::CloseWindow() { // Close Window. // stop updating fRunning = kFALSE; // reset kDontCallClose bit to be able to really close the window ResetBit(kDontCallClose); } //______________________________________________________________________________ void CPUMeter() { // Main application. MemInfo_t memInfo; CpuInfo_t cpuInfo; Float_t act_load, prev_load = 0.0; Int_t i, memUsage, old_memUsage = 0; TGShapedMain *mainWindow = new TGShapedMain(gClient->GetRoot(), 500, 200); TGSpeedo *speedo = mainWindow->GetSpeedo(); // set threshold values speedo->SetThresholds(12.5, 50.0, 87.5); // set threshold colors speedo->SetThresholdColors(TGSpeedo::kGreen, TGSpeedo::kOrange, TGSpeedo::kRed); // enable threshold speedo->EnableThreshold(); speedo->SetScaleValue(0.0, 5); // enable peak marker speedo->EnablePeakMark(); // update the TGSpeedo widget gSystem->GetCpuInfo(&cpuInfo); gSystem->GetMemInfo(&memInfo); gSystem->ProcessEvents(); while (mainWindow->IsRunning() && mainWindow->IsMapped()) { // Get CPU informations gSystem->GetCpuInfo(&cpuInfo, 100); // actual CPU load act_load = cpuInfo.fTotal; // Get Memory informations gSystem->GetMemInfo(&memInfo); // choose which value to display if (mainWindow->GetActInfo() == 0) memUsage = memInfo.fMemTotal; else if (mainWindow->GetActInfo() == 1) memUsage = memInfo.fMemUsed; else if (mainWindow->GetActInfo() == 2) memUsage = memInfo.fMemFree; // small threshold to avoid "trembling" needle if (fabs(act_load-prev_load) > 0.9) { speedo->SetScaleValue(act_load, 10); prev_load = act_load; } // update only if value has changed if (memUsage != old_memUsage) { speedo->SetOdoValue(memUsage); old_memUsage = memUsage; } // sleep a bit gSystem->ProcessEvents(); gSystem->Sleep(250); } mainWindow->CloseWindow(); } <|endoftext|>
<commit_before>/*********************************************************************** created: Fri, 4th July 2014 author: Henri I Hyyryläinen *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2014 Paul D Turner & The CEGUI Development Team * * 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 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 "CEGUI/RendererModules/Ogre/ShaderWrapper.h" #include "CEGUI/RendererModules/Ogre/Texture.h" #include "CEGUI/ShaderParameterBindings.h" #include "CEGUI/Exceptions.h" #include <glm/gtc/type_ptr.hpp> #include "OgreRenderSystem.h" #include "CEGUI/Logger.h" // Start of CEGUI namespace section namespace CEGUI { //----------------------------------------------------------------------------// OgreShaderWrapper::OgreShaderWrapper(OgreRenderer& owner, Ogre::RenderSystem& rs, Ogre::HighLevelGpuProgramPtr vs, Ogre::HighLevelGpuProgramPtr ps) : d_vertexShader(vs), d_pixelShader(ps), d_owner(owner), d_renderSystem(rs), d_lastMatrix(), d_previousAlpha(-1.f) { d_vertexParameters = d_vertexShader->createParameters(); d_pixelParameters = d_pixelShader->createParameters(); const Ogre::GpuConstantDefinitionMap& vertex_map = d_vertexShader->getConstantDefinitions().map; Ogre::GpuConstantDefinitionMap::const_iterator target = vertex_map.find("modelViewProjMatrix"); const Ogre::GpuConstantDefinitionMap& pixel_map = d_pixelShader->getConstantDefinitions().map; Ogre::GpuConstantDefinitionMap::const_iterator target2 = pixel_map.find("alphaPercentage"); // This will only be true when the shaders/parameter names are invalid if (target == vertex_map.end() || target2 == pixel_map.end()) { CEGUI_THROW(RendererException("Ogre renderer couldn't find an index for" " the shader data.")); // Don't want to fall through, ever return; } d_paramTypeToIndex[SPT_MATRIX_4X4] = target->second.physicalIndex; d_paramTypeToIndex[SPT_FLOAT] = target2->second.physicalIndex; d_paramTypeToIndex[SPT_TEXTURE] = 0; } //----------------------------------------------------------------------------// OgreShaderWrapper::~OgreShaderWrapper() { d_pixelParameters.setNull(); d_vertexParameters.setNull(); d_vertexShader.setNull(); d_pixelShader.setNull(); } //----------------------------------------------------------------------------// Ogre::GpuProgramParametersSharedPtr OgreShaderWrapper::getVertexParameters() const { return d_vertexParameters; } //----------------------------------------------------------------------------// void OgreShaderWrapper::prepareForRendering(const ShaderParameterBindings* shaderParameterBindings) { Ogre::GpuProgram* vs = d_vertexShader->_getBindingDelegate(); d_renderSystem.bindGpuProgram(vs); Ogre::GpuProgram* ps = d_pixelShader->_getBindingDelegate(); d_renderSystem.bindGpuProgram(ps); const ShaderParameterBindings::ShaderParameterBindingsMap& shader_parameter_bindings = shaderParameterBindings-> getShaderParameterBindings(); ShaderParameterBindings::ShaderParameterBindingsMap::const_iterator iter = shader_parameter_bindings.begin(); ShaderParameterBindings::ShaderParameterBindingsMap::const_iterator end = shader_parameter_bindings.end(); for (; iter != end; ++iter) { const CEGUI::ShaderParameter* parameter = iter->second; const ShaderParamType parameterType = parameter->getType(); std::map<int, size_t>::const_iterator find_iter = d_paramTypeToIndex. find(parameterType); if (find_iter == d_paramTypeToIndex.end()) { std::string errorMessage = std::string("Unknown variable name: \"")+ iter->first + "\""; CEGUI_THROW(RendererException(errorMessage)); } size_t target_index = find_iter->second; switch (parameterType) { case SPT_TEXTURE: { const CEGUI::ShaderParameterTexture* parameterTexture = static_cast<const CEGUI::ShaderParameterTexture*>(parameter); const CEGUI::OgreTexture* texture = static_cast<const CEGUI::OgreTexture*>(parameterTexture->d_parameterValue); Ogre::TexturePtr actual_texture = texture->getOgreTexture(); if (actual_texture.isNull()) { CEGUI_THROW(RendererException("Ogre texture ptr is empty")); } d_renderSystem._setTexture(0, true, actual_texture); d_owner.initialiseTextureStates(); break; } case SPT_MATRIX_4X4: { // This is the "modelViewProjMatrix" const CEGUI::ShaderParameterMatrix* mat = static_cast<const CEGUI::ShaderParameterMatrix*>(parameter); if (d_lastMatrix != mat->d_parameterValue) { d_vertexParameters->_writeRawConstants(target_index, glm::value_ptr(mat->d_parameterValue), 16); d_lastMatrix = mat->d_parameterValue; } break; } case SPT_FLOAT: { // This is the alpha value const CEGUI::ShaderParameterFloat* new_alpha = static_cast<const CEGUI::ShaderParameterFloat*>(parameter); if (d_previousAlpha != new_alpha->d_parameterValue) { d_previousAlpha = new_alpha->d_parameterValue; d_pixelParameters->_writeRawConstants(target_index, &d_previousAlpha, 1); } break; } default: CEGUI_THROW(RendererException("Invalid parameter type")); } } // Pass the finalized parameters to Ogre d_renderSystem.bindGpuProgramParameters(Ogre::GPT_VERTEX_PROGRAM, d_vertexParameters, Ogre::GPV_ALL); d_renderSystem.bindGpuProgramParameters(Ogre::GPT_FRAGMENT_PROGRAM, d_pixelParameters, Ogre::GPV_ALL); } //----------------------------------------------------------------------------// } <commit_msg>MOD: Minor docu change<commit_after>/*********************************************************************** created: Fri, 4th July 2014 author: Henri I Hyyryläinen *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2014 Paul D Turner & The CEGUI Development Team * * 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 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 "CEGUI/RendererModules/Ogre/ShaderWrapper.h" #include "CEGUI/RendererModules/Ogre/Texture.h" #include "CEGUI/ShaderParameterBindings.h" #include "CEGUI/Exceptions.h" #include <glm/gtc/type_ptr.hpp> #include "OgreRenderSystem.h" #include "CEGUI/Logger.h" // Start of CEGUI namespace section namespace CEGUI { //----------------------------------------------------------------------------// OgreShaderWrapper::OgreShaderWrapper(OgreRenderer& owner, Ogre::RenderSystem& rs, Ogre::HighLevelGpuProgramPtr vs, Ogre::HighLevelGpuProgramPtr ps) : d_vertexShader(vs), d_pixelShader(ps), d_owner(owner), d_renderSystem(rs), d_lastMatrix(), d_previousAlpha(-1.f) { d_vertexParameters = d_vertexShader->createParameters(); d_pixelParameters = d_pixelShader->createParameters(); const Ogre::GpuConstantDefinitionMap& vertex_map = d_vertexShader->getConstantDefinitions().map; Ogre::GpuConstantDefinitionMap::const_iterator target = vertex_map.find("modelViewProjMatrix"); const Ogre::GpuConstantDefinitionMap& pixel_map = d_pixelShader->getConstantDefinitions().map; Ogre::GpuConstantDefinitionMap::const_iterator target2 = pixel_map.find("alphaPercentage"); // We will throw an error if shaders/parameter names are invalid if (target == vertex_map.end() || target2 == pixel_map.end()) { CEGUI_THROW(RendererException("Ogre renderer couldn't find an index for" " the shader data.")); return; } d_paramTypeToIndex[SPT_MATRIX_4X4] = target->second.physicalIndex; d_paramTypeToIndex[SPT_FLOAT] = target2->second.physicalIndex; d_paramTypeToIndex[SPT_TEXTURE] = 0; } //----------------------------------------------------------------------------// OgreShaderWrapper::~OgreShaderWrapper() { d_pixelParameters.setNull(); d_vertexParameters.setNull(); d_vertexShader.setNull(); d_pixelShader.setNull(); } //----------------------------------------------------------------------------// Ogre::GpuProgramParametersSharedPtr OgreShaderWrapper::getVertexParameters() const { return d_vertexParameters; } //----------------------------------------------------------------------------// void OgreShaderWrapper::prepareForRendering(const ShaderParameterBindings* shaderParameterBindings) { Ogre::GpuProgram* vs = d_vertexShader->_getBindingDelegate(); d_renderSystem.bindGpuProgram(vs); Ogre::GpuProgram* ps = d_pixelShader->_getBindingDelegate(); d_renderSystem.bindGpuProgram(ps); const ShaderParameterBindings::ShaderParameterBindingsMap& shader_parameter_bindings = shaderParameterBindings-> getShaderParameterBindings(); ShaderParameterBindings::ShaderParameterBindingsMap::const_iterator iter = shader_parameter_bindings.begin(); ShaderParameterBindings::ShaderParameterBindingsMap::const_iterator end = shader_parameter_bindings.end(); for (; iter != end; ++iter) { const CEGUI::ShaderParameter* parameter = iter->second; const ShaderParamType parameterType = parameter->getType(); std::map<int, size_t>::const_iterator find_iter = d_paramTypeToIndex. find(parameterType); if (find_iter == d_paramTypeToIndex.end()) { std::string errorMessage = std::string("Unknown variable name: \"")+ iter->first + "\""; CEGUI_THROW(RendererException(errorMessage)); } size_t target_index = find_iter->second; switch (parameterType) { case SPT_TEXTURE: { const CEGUI::ShaderParameterTexture* parameterTexture = static_cast<const CEGUI::ShaderParameterTexture*>(parameter); const CEGUI::OgreTexture* texture = static_cast<const CEGUI::OgreTexture*>(parameterTexture->d_parameterValue); Ogre::TexturePtr actual_texture = texture->getOgreTexture(); if (actual_texture.isNull()) { CEGUI_THROW(RendererException("Ogre texture ptr is empty")); } d_renderSystem._setTexture(0, true, actual_texture); d_owner.initialiseTextureStates(); break; } case SPT_MATRIX_4X4: { // This is the "modelViewProjMatrix" const CEGUI::ShaderParameterMatrix* mat = static_cast<const CEGUI::ShaderParameterMatrix*>(parameter); if (d_lastMatrix != mat->d_parameterValue) { d_vertexParameters->_writeRawConstants(target_index, glm::value_ptr(mat->d_parameterValue), 16); d_lastMatrix = mat->d_parameterValue; } break; } case SPT_FLOAT: { // This is the alpha value const CEGUI::ShaderParameterFloat* new_alpha = static_cast<const CEGUI::ShaderParameterFloat*>(parameter); if (d_previousAlpha != new_alpha->d_parameterValue) { d_previousAlpha = new_alpha->d_parameterValue; d_pixelParameters->_writeRawConstants(target_index, &d_previousAlpha, 1); } break; } default: CEGUI_THROW(RendererException("Invalid parameter type")); } } // Pass the finalized parameters to Ogre d_renderSystem.bindGpuProgramParameters(Ogre::GPT_VERTEX_PROGRAM, d_vertexParameters, Ogre::GPV_ALL); d_renderSystem.bindGpuProgramParameters(Ogre::GPT_FRAGMENT_PROGRAM, d_pixelParameters, Ogre::GPV_ALL); } //----------------------------------------------------------------------------// } <|endoftext|>
<commit_before>/* * This file is part of the CN24 semantic segmentation software, * copyright (C) 2015 Clemens-Alexander Brust (ikosa dot de at gmail dot com). * * For licensing information, see the LICENSE file included with this project. */ /** * @file classifyImage.cpp * @brief Application that uses a pretrained net to segment images. * * @author Clemens-Alexander Brust (ikosa dot de at gmail dot com) */ #include <iostream> #include <fstream> #include <cstring> #include <sstream> #include <cn24.h> int main (int argc, char* argv[]) { if (argc < 6) { LOGERROR << "USAGE: " << argv[0] << " <dataset config file> <net config file> <net parameter tensor> <input image file> <output image file>"; LOGEND; return -1; } // Capture command line arguments std::string output_image_fname (argv[5]); std::string input_image_fname (argv[4]); std::string param_tensor_fname (argv[3]); std::string net_config_fname (argv[2]); std::string dataset_config_fname (argv[1]); // Initialize CN24 Conv::System::Init(); // Open network and dataset configuration files std::ifstream param_tensor_file(param_tensor_fname,std::ios::in | std::ios::binary); std::ifstream net_config_file(net_config_fname,std::ios::in); std::ifstream dataset_config_file(dataset_config_fname,std::ios::in); if(!param_tensor_file.good()) { FATAL("Cannot open param tensor file!"); } if(!net_config_file.good()) { FATAL("Cannot open net configuration file!"); } if(!dataset_config_file.good()) { FATAL("Cannot open dataset configuration file!"); } // Parse network configuration file Conv::ConfigurableFactory* factory = new Conv::ConfigurableFactory(net_config_file, 238238, false); // Parse dataset configuration file Conv::TensorStreamDataset* dataset = Conv::TensorStreamDataset::CreateFromConfiguration(dataset_config_file, true); unsigned int CLASSES = dataset->GetClasses(); // Load image Conv::Tensor original_data_tensor(input_image_fname); // Rescale image unsigned int width = original_data_tensor.width(); unsigned int height = original_data_tensor.height(); if(width & 1) width++; if(height & 1) height++; Conv::Tensor data_tensor(1, width, height, original_data_tensor.maps()); data_tensor.Clear(); Conv::Tensor::CopySample(original_data_tensor, 0, data_tensor, 0); // Assemble net Conv::Net net; Conv::InputLayer input_layer(data_tensor); int data_layer_id = net.AddLayer(&input_layer); int output_layer_id = factory->AddLayers (net, Conv::Connection (data_layer_id), CLASSES); // Load network parameters net.DeserializeParameters(param_tensor_file); net.SetIsTesting(true); LOGINFO << "Classifying..." << std::flush; net.FeedForward(); Conv::Tensor* net_output_tensor = &net.buffer(output_layer_id)->data; Conv::Tensor image_output_tensor(1, net_output_tensor->width(), net_output_tensor->height(), 3); LOGINFO << "Colorizing..." << std::flush; dataset->Colorize(*net_output_tensor, image_output_tensor); // Recrop image down Conv::Tensor small(1, original_data_tensor.width(), original_data_tensor.height(), 3); for(unsigned int m = 0; m < 3; m++) for(unsigned int y = 0; y < small.height(); y++) for(unsigned int x = 0; x < small.width(); x++) *small.data_ptr(x,y,m,0) = *image_output_tensor.data_ptr_const(x,y,m,0); small.WriteToFile(output_image_fname); LOGINFO << "DONE!"; LOGEND; return 0; } <commit_msg>Added max-pooling size heuristic from TensorStreamDataset to classifyImage for more consistency<commit_after>/* * This file is part of the CN24 semantic segmentation software, * copyright (C) 2015 Clemens-Alexander Brust (ikosa dot de at gmail dot com). * * For licensing information, see the LICENSE file included with this project. */ /** * @file classifyImage.cpp * @brief Application that uses a pretrained net to segment images. * * @author Clemens-Alexander Brust (ikosa dot de at gmail dot com) */ #include <iostream> #include <fstream> #include <cstring> #include <sstream> #include <cn24.h> int main (int argc, char* argv[]) { if (argc < 6) { LOGERROR << "USAGE: " << argv[0] << " <dataset config file> <net config file> <net parameter tensor> <input image file> <output image file>"; LOGEND; return -1; } // Capture command line arguments std::string output_image_fname (argv[5]); std::string input_image_fname (argv[4]); std::string param_tensor_fname (argv[3]); std::string net_config_fname (argv[2]); std::string dataset_config_fname (argv[1]); // Initialize CN24 Conv::System::Init(); // Open network and dataset configuration files std::ifstream param_tensor_file(param_tensor_fname,std::ios::in | std::ios::binary); std::ifstream net_config_file(net_config_fname,std::ios::in); std::ifstream dataset_config_file(dataset_config_fname,std::ios::in); if(!param_tensor_file.good()) { FATAL("Cannot open param tensor file!"); } if(!net_config_file.good()) { FATAL("Cannot open net configuration file!"); } if(!dataset_config_file.good()) { FATAL("Cannot open dataset configuration file!"); } // Parse network configuration file Conv::ConfigurableFactory* factory = new Conv::ConfigurableFactory(net_config_file, 238238, false); // Parse dataset configuration file Conv::TensorStreamDataset* dataset = Conv::TensorStreamDataset::CreateFromConfiguration(dataset_config_file, true); unsigned int CLASSES = dataset->GetClasses(); // Load image Conv::Tensor original_data_tensor(input_image_fname); // Rescale image unsigned int width = original_data_tensor.width(); unsigned int height = original_data_tensor.height(); if(width & 1) width++; if(height & 1) height++; if(width & 2) width+=2; if(height & 2) height+=2; if(width & 4) width+=4; if(height & 4) height+=4; Conv::Tensor data_tensor(1, width, height, original_data_tensor.maps()); data_tensor.Clear(); Conv::Tensor::CopySample(original_data_tensor, 0, data_tensor, 0); // Assemble net Conv::Net net; Conv::InputLayer input_layer(data_tensor); int data_layer_id = net.AddLayer(&input_layer); int output_layer_id = factory->AddLayers (net, Conv::Connection (data_layer_id), CLASSES); // Load network parameters net.DeserializeParameters(param_tensor_file); net.SetIsTesting(true); LOGINFO << "Classifying..." << std::flush; net.FeedForward(); Conv::Tensor* net_output_tensor = &net.buffer(output_layer_id)->data; Conv::Tensor image_output_tensor(1, net_output_tensor->width(), net_output_tensor->height(), 3); LOGINFO << "Colorizing..." << std::flush; dataset->Colorize(*net_output_tensor, image_output_tensor); // Recrop image down Conv::Tensor small(1, original_data_tensor.width(), original_data_tensor.height(), 3); for(unsigned int m = 0; m < 3; m++) for(unsigned int y = 0; y < small.height(); y++) for(unsigned int x = 0; x < small.width(); x++) *small.data_ptr(x,y,m,0) = *image_output_tensor.data_ptr_const(x,y,m,0); small.WriteToFile(output_image_fname); LOGINFO << "DONE!"; LOGEND; return 0; } <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/dom_ui/chrome_url_data_manager.h" #include "app/l10n_util.h" #include "base/file_util.h" #include "base/i18n/rtl.h" #include "base/message_loop.h" #include "base/path_service.h" #include "base/singleton.h" #include "base/string_util.h" #include "base/thread.h" #include "base/values.h" #if defined(OS_WIN) #include "base/win_util.h" #endif #include "chrome/browser/appcache/view_appcache_internals_job_factory.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/chrome_thread.h" #include "chrome/browser/dom_ui/shared_resources_data_source.h" #include "chrome/browser/net/chrome_url_request_context.h" #include "chrome/browser/net/view_http_cache_job_factory.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/ref_counted_util.h" #include "chrome/common/url_constants.h" #include "googleurl/src/url_util.h" #include "grit/platform_locale_settings.h" #include "net/base/io_buffer.h" #include "net/base/net_errors.h" #include "net/url_request/url_request.h" #include "net/url_request/url_request_file_job.h" #include "net/url_request/url_request_job.h" // URLRequestChromeJob is a URLRequestJob that manages running chrome-internal // resource requests asynchronously. // It hands off URL requests to ChromeURLDataManager, which asynchronously // calls back once the data is available. class URLRequestChromeJob : public URLRequestJob { public: explicit URLRequestChromeJob(URLRequest* request); // URLRequestJob implementation. virtual void Start(); virtual void Kill(); virtual bool ReadRawData(net::IOBuffer* buf, int buf_size, int *bytes_read); virtual bool GetMimeType(std::string* mime_type) const; // Called by ChromeURLDataManager to notify us that the data blob is ready // for us. void DataAvailable(RefCountedMemory* bytes); void SetMimeType(const std::string& mime_type) { mime_type_ = mime_type; } private: virtual ~URLRequestChromeJob(); // Helper for Start(), to let us start asynchronously. // (This pattern is shared by most URLRequestJob implementations.) void StartAsync(); // Do the actual copy from data_ (the data we're serving) into |buf|. // Separate from ReadRawData so we can handle async I/O. void CompleteRead(net::IOBuffer* buf, int buf_size, int* bytes_read); // The actual data we're serving. NULL until it's been fetched. scoped_refptr<RefCountedMemory> data_; // The current offset into the data that we're handing off to our // callers via the Read interfaces. int data_offset_; // For async reads, we keep around a pointer to the buffer that // we're reading into. scoped_refptr<net::IOBuffer> pending_buf_; int pending_buf_size_; std::string mime_type_; DISALLOW_COPY_AND_ASSIGN(URLRequestChromeJob); }; // URLRequestChromeFileJob is a URLRequestJob that acts like a file:// URL class URLRequestChromeFileJob : public URLRequestFileJob { public: URLRequestChromeFileJob(URLRequest* request, const FilePath& path); private: virtual ~URLRequestChromeFileJob(); DISALLOW_COPY_AND_ASSIGN(URLRequestChromeFileJob); }; void RegisterURLRequestChromeJob() { FilePath inspector_dir; if (PathService::Get(chrome::DIR_INSPECTOR, &inspector_dir)) { Singleton<ChromeURLDataManager>()->AddFileSource( chrome::kChromeUIDevToolsHost, inspector_dir); } SharedResourcesDataSource::Register(); URLRequest::RegisterProtocolFactory(chrome::kChromeUIScheme, &ChromeURLDataManager::Factory); } void UnregisterURLRequestChromeJob() { FilePath inspector_dir; if (PathService::Get(chrome::DIR_INSPECTOR, &inspector_dir)) { Singleton<ChromeURLDataManager>()->RemoveFileSource( chrome::kChromeUIDevToolsHost); } } // static void ChromeURLDataManager::URLToRequest(const GURL& url, std::string* source_name, std::string* path) { DCHECK(url.SchemeIs(chrome::kChromeUIScheme)); if (!url.is_valid()) { NOTREACHED(); return; } // Our input looks like: chrome://source_name/extra_bits?foo . // So the url's "host" is our source, and everything after the host is // the path. source_name->assign(url.host()); const std::string& spec = url.possibly_invalid_spec(); const url_parse::Parsed& parsed = url.parsed_for_possibly_invalid_spec(); // + 1 to skip the slash at the beginning of the path. int offset = parsed.CountCharactersBefore(url_parse::Parsed::PATH, false) + 1; if (offset < static_cast<int>(spec.size())) path->assign(spec.substr(offset)); } // static bool ChromeURLDataManager::URLToFilePath(const GURL& url, FilePath* file_path) { // Parse the URL into a request for a source and path. std::string source_name; std::string relative_path; // Remove Query and Ref from URL. GURL stripped_url; GURL::Replacements replacements; replacements.ClearQuery(); replacements.ClearRef(); stripped_url = url.ReplaceComponents(replacements); URLToRequest(stripped_url, &source_name, &relative_path); FileSourceMap::const_iterator i( Singleton<ChromeURLDataManager>()->file_sources_.find(source_name)); if (i == Singleton<ChromeURLDataManager>()->file_sources_.end()) return false; *file_path = i->second.AppendASCII(relative_path); return true; } ChromeURLDataManager::ChromeURLDataManager() : next_request_id_(0) { } ChromeURLDataManager::~ChromeURLDataManager() { } void ChromeURLDataManager::AddDataSource(scoped_refptr<DataSource> source) { // TODO(jackson): A new data source with same name should not clobber the // existing one. data_sources_[source->source_name()] = source; } void ChromeURLDataManager::AddFileSource(const std::string& source_name, const FilePath& file_path) { DCHECK(file_sources_.count(source_name) == 0); file_sources_[source_name] = file_path; } void ChromeURLDataManager::RemoveFileSource(const std::string& source_name) { DCHECK(file_sources_.count(source_name) == 1); file_sources_.erase(source_name); } bool ChromeURLDataManager::HasPendingJob(URLRequestChromeJob* job) const { for (PendingRequestMap::const_iterator i = pending_requests_.begin(); i != pending_requests_.end(); ++i) { if (i->second == job) return true; } return false; } bool ChromeURLDataManager::StartRequest(const GURL& url, URLRequestChromeJob* job) { // Parse the URL into a request for a source and path. std::string source_name; std::string path; URLToRequest(url, &source_name, &path); // Look up the data source for the request. DataSourceMap::iterator i = data_sources_.find(source_name); if (i == data_sources_.end()) return false; DataSource* source = i->second; // Save this request so we know where to send the data. RequestID request_id = next_request_id_++; pending_requests_.insert(std::make_pair(request_id, job)); // TODO(eroman): would be nicer if the mimetype were set at the same time // as the data blob. For now do it here, since NotifyHeadersComplete() is // going to get called once we return. job->SetMimeType(source->GetMimeType(path)); ChromeURLRequestContext* context = static_cast<ChromeURLRequestContext*>( job->request()->context()); // Forward along the request to the data source. MessageLoop* target_message_loop = source->MessageLoopForRequestPath(path); if (!target_message_loop) { // The DataSource is agnostic to which thread StartDataRequest is called // on for this path. Call directly into it from this thread, the IO // thread. source->StartDataRequest(path, context->is_off_the_record(), request_id); } else { // The DataSource wants StartDataRequest to be called on a specific thread, // usually the UI thread, for this path. target_message_loop->PostTask(FROM_HERE, NewRunnableMethod(source, &DataSource::StartDataRequest, path, context->is_off_the_record(), request_id)); } return true; } void ChromeURLDataManager::RemoveRequest(URLRequestChromeJob* job) { // Remove the request from our list of pending requests. // If/when the source sends the data that was requested, the data will just // be thrown away. for (PendingRequestMap::iterator i = pending_requests_.begin(); i != pending_requests_.end(); ++i) { if (i->second == job) { pending_requests_.erase(i); return; } } } void ChromeURLDataManager::DataAvailable( RequestID request_id, scoped_refptr<RefCountedMemory> bytes) { // Forward this data on to the pending URLRequest, if it exists. PendingRequestMap::iterator i = pending_requests_.find(request_id); if (i != pending_requests_.end()) { // We acquire a reference to the job so that it doesn't disappear under the // feet of any method invoked here (we could trigger a callback). scoped_refptr<URLRequestChromeJob> job = i->second; pending_requests_.erase(i); job->DataAvailable(bytes); } } void ChromeURLDataManager::DataSource::SendResponse( RequestID request_id, RefCountedMemory* bytes) { ChromeThread::PostTask( ChromeThread::IO, FROM_HERE, NewRunnableMethod(Singleton<ChromeURLDataManager>::get(), &ChromeURLDataManager::DataAvailable, request_id, scoped_refptr<RefCountedMemory>(bytes))); } MessageLoop* ChromeURLDataManager::DataSource::MessageLoopForRequestPath( const std::string& path) const { return message_loop_; } // static void ChromeURLDataManager::DataSource::SetFontAndTextDirection( DictionaryValue* localized_strings) { localized_strings->SetString(L"fontfamily", l10n_util::GetString(IDS_WEB_FONT_FAMILY)); int web_font_size_id = IDS_WEB_FONT_SIZE; #if defined(OS_WIN) // Some fonts used for some languages changed a lot in terms of the font // metric in Vista. So, we need to use different size before Vista. if (win_util::GetWinVersion() < win_util::WINVERSION_VISTA) web_font_size_id = IDS_WEB_FONT_SIZE_XP; #endif localized_strings->SetString(L"fontsize", l10n_util::GetString(web_font_size_id)); localized_strings->SetString(L"textdirection", base::i18n::IsRTL() ? L"rtl" : L"ltr"); } URLRequestJob* ChromeURLDataManager::Factory(URLRequest* request, const std::string& scheme) { // Try first with a file handler FilePath path; if (ChromeURLDataManager::URLToFilePath(request->url(), &path)) return new URLRequestChromeFileJob(request, path); // Next check for chrome://view-http-cache/*, which uses its own job type. if (ViewHttpCacheJobFactory::IsSupportedURL(request->url())) return ViewHttpCacheJobFactory::CreateJobForRequest(request); // Next check for chrome://appcache-internals/, which uses its own job type. if (ViewAppCacheInternalsJobFactory::IsSupportedURL(request->url())) return ViewAppCacheInternalsJobFactory::CreateJobForRequest(request); // Fall back to using a custom handler return new URLRequestChromeJob(request); } URLRequestChromeJob::URLRequestChromeJob(URLRequest* request) : URLRequestJob(request), data_offset_(0), pending_buf_size_(0) { } URLRequestChromeJob::~URLRequestChromeJob() { CHECK(!Singleton<ChromeURLDataManager>()->HasPendingJob(this)); } void URLRequestChromeJob::Start() { // Start reading asynchronously so that all error reporting and data // callbacks happen as they would for network requests. MessageLoop::current()->PostTask(FROM_HERE, NewRunnableMethod( this, &URLRequestChromeJob::StartAsync)); } void URLRequestChromeJob::Kill() { Singleton<ChromeURLDataManager>()->RemoveRequest(this); } bool URLRequestChromeJob::GetMimeType(std::string* mime_type) const { *mime_type = mime_type_; return !mime_type_.empty(); } void URLRequestChromeJob::DataAvailable(RefCountedMemory* bytes) { if (bytes) { // The request completed, and we have all the data. // Clear any IO pending status. SetStatus(URLRequestStatus()); data_ = bytes; int bytes_read; if (pending_buf_.get()) { CHECK(pending_buf_->data()); CompleteRead(pending_buf_, pending_buf_size_, &bytes_read); pending_buf_ = NULL; NotifyReadComplete(bytes_read); } } else { // The request failed. NotifyDone(URLRequestStatus(URLRequestStatus::FAILED, net::ERR_FAILED)); } } bool URLRequestChromeJob::ReadRawData(net::IOBuffer* buf, int buf_size, int* bytes_read) { if (!data_.get()) { SetStatus(URLRequestStatus(URLRequestStatus::IO_PENDING, 0)); DCHECK(!pending_buf_.get()); CHECK(buf->data()); pending_buf_ = buf; pending_buf_size_ = buf_size; return false; // Tell the caller we're still waiting for data. } // Otherwise, the data is available. CompleteRead(buf, buf_size, bytes_read); return true; } void URLRequestChromeJob::CompleteRead(net::IOBuffer* buf, int buf_size, int* bytes_read) { int remaining = static_cast<int>(data_->size()) - data_offset_; if (buf_size > remaining) buf_size = remaining; if (buf_size > 0) { memcpy(buf->data(), data_->front() + data_offset_, buf_size); data_offset_ += buf_size; } *bytes_read = buf_size; } void URLRequestChromeJob::StartAsync() { if (!request_) return; if (Singleton<ChromeURLDataManager>()->StartRequest(request_->url(), this)) { NotifyHeadersComplete(); } else { NotifyStartError(URLRequestStatus(URLRequestStatus::FAILED, net::ERR_INVALID_URL)); } } URLRequestChromeFileJob::URLRequestChromeFileJob(URLRequest* request, const FilePath& path) : URLRequestFileJob(request, path) { } URLRequestChromeFileJob::~URLRequestChromeFileJob() { } <commit_msg>Prevent hitting DCHECK when multiple slashes are specified in chrome://devtools///.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/dom_ui/chrome_url_data_manager.h" #include "app/l10n_util.h" #include "base/file_util.h" #include "base/i18n/rtl.h" #include "base/message_loop.h" #include "base/path_service.h" #include "base/singleton.h" #include "base/string_util.h" #include "base/thread.h" #include "base/values.h" #if defined(OS_WIN) #include "base/win_util.h" #endif #include "chrome/browser/appcache/view_appcache_internals_job_factory.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/chrome_thread.h" #include "chrome/browser/dom_ui/shared_resources_data_source.h" #include "chrome/browser/net/chrome_url_request_context.h" #include "chrome/browser/net/view_http_cache_job_factory.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/ref_counted_util.h" #include "chrome/common/url_constants.h" #include "googleurl/src/url_util.h" #include "grit/platform_locale_settings.h" #include "net/base/io_buffer.h" #include "net/base/net_errors.h" #include "net/url_request/url_request.h" #include "net/url_request/url_request_file_job.h" #include "net/url_request/url_request_job.h" // URLRequestChromeJob is a URLRequestJob that manages running chrome-internal // resource requests asynchronously. // It hands off URL requests to ChromeURLDataManager, which asynchronously // calls back once the data is available. class URLRequestChromeJob : public URLRequestJob { public: explicit URLRequestChromeJob(URLRequest* request); // URLRequestJob implementation. virtual void Start(); virtual void Kill(); virtual bool ReadRawData(net::IOBuffer* buf, int buf_size, int *bytes_read); virtual bool GetMimeType(std::string* mime_type) const; // Called by ChromeURLDataManager to notify us that the data blob is ready // for us. void DataAvailable(RefCountedMemory* bytes); void SetMimeType(const std::string& mime_type) { mime_type_ = mime_type; } private: virtual ~URLRequestChromeJob(); // Helper for Start(), to let us start asynchronously. // (This pattern is shared by most URLRequestJob implementations.) void StartAsync(); // Do the actual copy from data_ (the data we're serving) into |buf|. // Separate from ReadRawData so we can handle async I/O. void CompleteRead(net::IOBuffer* buf, int buf_size, int* bytes_read); // The actual data we're serving. NULL until it's been fetched. scoped_refptr<RefCountedMemory> data_; // The current offset into the data that we're handing off to our // callers via the Read interfaces. int data_offset_; // For async reads, we keep around a pointer to the buffer that // we're reading into. scoped_refptr<net::IOBuffer> pending_buf_; int pending_buf_size_; std::string mime_type_; DISALLOW_COPY_AND_ASSIGN(URLRequestChromeJob); }; // URLRequestChromeFileJob is a URLRequestJob that acts like a file:// URL class URLRequestChromeFileJob : public URLRequestFileJob { public: URLRequestChromeFileJob(URLRequest* request, const FilePath& path); private: virtual ~URLRequestChromeFileJob(); DISALLOW_COPY_AND_ASSIGN(URLRequestChromeFileJob); }; void RegisterURLRequestChromeJob() { FilePath inspector_dir; if (PathService::Get(chrome::DIR_INSPECTOR, &inspector_dir)) { Singleton<ChromeURLDataManager>()->AddFileSource( chrome::kChromeUIDevToolsHost, inspector_dir); } SharedResourcesDataSource::Register(); URLRequest::RegisterProtocolFactory(chrome::kChromeUIScheme, &ChromeURLDataManager::Factory); } void UnregisterURLRequestChromeJob() { FilePath inspector_dir; if (PathService::Get(chrome::DIR_INSPECTOR, &inspector_dir)) { Singleton<ChromeURLDataManager>()->RemoveFileSource( chrome::kChromeUIDevToolsHost); } } // static void ChromeURLDataManager::URLToRequest(const GURL& url, std::string* source_name, std::string* path) { DCHECK(url.SchemeIs(chrome::kChromeUIScheme)); if (!url.is_valid()) { NOTREACHED(); return; } // Our input looks like: chrome://source_name/extra_bits?foo . // So the url's "host" is our source, and everything after the host is // the path. source_name->assign(url.host()); const std::string& spec = url.possibly_invalid_spec(); const url_parse::Parsed& parsed = url.parsed_for_possibly_invalid_spec(); // + 1 to skip the slash at the beginning of the path. int offset = parsed.CountCharactersBefore(url_parse::Parsed::PATH, false) + 1; if (offset < static_cast<int>(spec.size())) path->assign(spec.substr(offset)); } // static bool ChromeURLDataManager::URLToFilePath(const GURL& url, FilePath* file_path) { // Parse the URL into a request for a source and path. std::string source_name; std::string relative_path; // Remove Query and Ref from URL. GURL stripped_url; GURL::Replacements replacements; replacements.ClearQuery(); replacements.ClearRef(); stripped_url = url.ReplaceComponents(replacements); URLToRequest(stripped_url, &source_name, &relative_path); FileSourceMap::const_iterator i( Singleton<ChromeURLDataManager>()->file_sources_.find(source_name)); if (i == Singleton<ChromeURLDataManager>()->file_sources_.end()) return false; // Check that |relative_path| is not an absolute path (otherwise AppendASCII() // will DCHECK). The awkward use of StringType is because on some systems // FilePath expects a std::string, but on others a std::wstring. FilePath p(FilePath::StringType(relative_path.begin(), relative_path.end())); if (p.IsAbsolute()) return false; *file_path = i->second.AppendASCII(relative_path); return true; } ChromeURLDataManager::ChromeURLDataManager() : next_request_id_(0) { } ChromeURLDataManager::~ChromeURLDataManager() { } void ChromeURLDataManager::AddDataSource(scoped_refptr<DataSource> source) { // TODO(jackson): A new data source with same name should not clobber the // existing one. data_sources_[source->source_name()] = source; } void ChromeURLDataManager::AddFileSource(const std::string& source_name, const FilePath& file_path) { DCHECK(file_sources_.count(source_name) == 0); file_sources_[source_name] = file_path; } void ChromeURLDataManager::RemoveFileSource(const std::string& source_name) { DCHECK(file_sources_.count(source_name) == 1); file_sources_.erase(source_name); } bool ChromeURLDataManager::HasPendingJob(URLRequestChromeJob* job) const { for (PendingRequestMap::const_iterator i = pending_requests_.begin(); i != pending_requests_.end(); ++i) { if (i->second == job) return true; } return false; } bool ChromeURLDataManager::StartRequest(const GURL& url, URLRequestChromeJob* job) { // Parse the URL into a request for a source and path. std::string source_name; std::string path; URLToRequest(url, &source_name, &path); // Look up the data source for the request. DataSourceMap::iterator i = data_sources_.find(source_name); if (i == data_sources_.end()) return false; DataSource* source = i->second; // Save this request so we know where to send the data. RequestID request_id = next_request_id_++; pending_requests_.insert(std::make_pair(request_id, job)); // TODO(eroman): would be nicer if the mimetype were set at the same time // as the data blob. For now do it here, since NotifyHeadersComplete() is // going to get called once we return. job->SetMimeType(source->GetMimeType(path)); ChromeURLRequestContext* context = static_cast<ChromeURLRequestContext*>( job->request()->context()); // Forward along the request to the data source. MessageLoop* target_message_loop = source->MessageLoopForRequestPath(path); if (!target_message_loop) { // The DataSource is agnostic to which thread StartDataRequest is called // on for this path. Call directly into it from this thread, the IO // thread. source->StartDataRequest(path, context->is_off_the_record(), request_id); } else { // The DataSource wants StartDataRequest to be called on a specific thread, // usually the UI thread, for this path. target_message_loop->PostTask(FROM_HERE, NewRunnableMethod(source, &DataSource::StartDataRequest, path, context->is_off_the_record(), request_id)); } return true; } void ChromeURLDataManager::RemoveRequest(URLRequestChromeJob* job) { // Remove the request from our list of pending requests. // If/when the source sends the data that was requested, the data will just // be thrown away. for (PendingRequestMap::iterator i = pending_requests_.begin(); i != pending_requests_.end(); ++i) { if (i->second == job) { pending_requests_.erase(i); return; } } } void ChromeURLDataManager::DataAvailable( RequestID request_id, scoped_refptr<RefCountedMemory> bytes) { // Forward this data on to the pending URLRequest, if it exists. PendingRequestMap::iterator i = pending_requests_.find(request_id); if (i != pending_requests_.end()) { // We acquire a reference to the job so that it doesn't disappear under the // feet of any method invoked here (we could trigger a callback). scoped_refptr<URLRequestChromeJob> job = i->second; pending_requests_.erase(i); job->DataAvailable(bytes); } } void ChromeURLDataManager::DataSource::SendResponse( RequestID request_id, RefCountedMemory* bytes) { ChromeThread::PostTask( ChromeThread::IO, FROM_HERE, NewRunnableMethod(Singleton<ChromeURLDataManager>::get(), &ChromeURLDataManager::DataAvailable, request_id, scoped_refptr<RefCountedMemory>(bytes))); } MessageLoop* ChromeURLDataManager::DataSource::MessageLoopForRequestPath( const std::string& path) const { return message_loop_; } // static void ChromeURLDataManager::DataSource::SetFontAndTextDirection( DictionaryValue* localized_strings) { localized_strings->SetString(L"fontfamily", l10n_util::GetString(IDS_WEB_FONT_FAMILY)); int web_font_size_id = IDS_WEB_FONT_SIZE; #if defined(OS_WIN) // Some fonts used for some languages changed a lot in terms of the font // metric in Vista. So, we need to use different size before Vista. if (win_util::GetWinVersion() < win_util::WINVERSION_VISTA) web_font_size_id = IDS_WEB_FONT_SIZE_XP; #endif localized_strings->SetString(L"fontsize", l10n_util::GetString(web_font_size_id)); localized_strings->SetString(L"textdirection", base::i18n::IsRTL() ? L"rtl" : L"ltr"); } URLRequestJob* ChromeURLDataManager::Factory(URLRequest* request, const std::string& scheme) { // Try first with a file handler FilePath path; if (ChromeURLDataManager::URLToFilePath(request->url(), &path)) return new URLRequestChromeFileJob(request, path); // Next check for chrome://view-http-cache/*, which uses its own job type. if (ViewHttpCacheJobFactory::IsSupportedURL(request->url())) return ViewHttpCacheJobFactory::CreateJobForRequest(request); // Next check for chrome://appcache-internals/, which uses its own job type. if (ViewAppCacheInternalsJobFactory::IsSupportedURL(request->url())) return ViewAppCacheInternalsJobFactory::CreateJobForRequest(request); // Fall back to using a custom handler return new URLRequestChromeJob(request); } URLRequestChromeJob::URLRequestChromeJob(URLRequest* request) : URLRequestJob(request), data_offset_(0), pending_buf_size_(0) { } URLRequestChromeJob::~URLRequestChromeJob() { CHECK(!Singleton<ChromeURLDataManager>()->HasPendingJob(this)); } void URLRequestChromeJob::Start() { // Start reading asynchronously so that all error reporting and data // callbacks happen as they would for network requests. MessageLoop::current()->PostTask(FROM_HERE, NewRunnableMethod( this, &URLRequestChromeJob::StartAsync)); } void URLRequestChromeJob::Kill() { Singleton<ChromeURLDataManager>()->RemoveRequest(this); } bool URLRequestChromeJob::GetMimeType(std::string* mime_type) const { *mime_type = mime_type_; return !mime_type_.empty(); } void URLRequestChromeJob::DataAvailable(RefCountedMemory* bytes) { if (bytes) { // The request completed, and we have all the data. // Clear any IO pending status. SetStatus(URLRequestStatus()); data_ = bytes; int bytes_read; if (pending_buf_.get()) { CHECK(pending_buf_->data()); CompleteRead(pending_buf_, pending_buf_size_, &bytes_read); pending_buf_ = NULL; NotifyReadComplete(bytes_read); } } else { // The request failed. NotifyDone(URLRequestStatus(URLRequestStatus::FAILED, net::ERR_FAILED)); } } bool URLRequestChromeJob::ReadRawData(net::IOBuffer* buf, int buf_size, int* bytes_read) { if (!data_.get()) { SetStatus(URLRequestStatus(URLRequestStatus::IO_PENDING, 0)); DCHECK(!pending_buf_.get()); CHECK(buf->data()); pending_buf_ = buf; pending_buf_size_ = buf_size; return false; // Tell the caller we're still waiting for data. } // Otherwise, the data is available. CompleteRead(buf, buf_size, bytes_read); return true; } void URLRequestChromeJob::CompleteRead(net::IOBuffer* buf, int buf_size, int* bytes_read) { int remaining = static_cast<int>(data_->size()) - data_offset_; if (buf_size > remaining) buf_size = remaining; if (buf_size > 0) { memcpy(buf->data(), data_->front() + data_offset_, buf_size); data_offset_ += buf_size; } *bytes_read = buf_size; } void URLRequestChromeJob::StartAsync() { if (!request_) return; if (Singleton<ChromeURLDataManager>()->StartRequest(request_->url(), this)) { NotifyHeadersComplete(); } else { NotifyStartError(URLRequestStatus(URLRequestStatus::FAILED, net::ERR_INVALID_URL)); } } URLRequestChromeFileJob::URLRequestChromeFileJob(URLRequest* request, const FilePath& path) : URLRequestFileJob(request, path) { } URLRequestChromeFileJob::~URLRequestChromeFileJob() { } <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/browser.h" #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/browser/extensions/extension_host.h" #include "chrome/browser/extensions/extension_process_manager.h" #include "chrome/browser/profile.h" #include "chrome/browser/renderer_host/render_view_host.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/common/chrome_switches.h" #include "chrome/test/ui_test_utils.h" #include "net/base/mock_host_resolver.h" class AppApiTest : public ExtensionApiTest { public: void SetUpCommandLine(CommandLine* command_line) { ExtensionApiTest::SetUpCommandLine(command_line); command_line->AppendSwitch(switches::kEnableExtensionApps); } }; // Simulates a page calling window.open on an URL, and waits for the navigation. static void WindowOpenHelper(Browser* browser, RenderViewHost* opener_host, const GURL& url) { bool result = false; ui_test_utils::ExecuteJavaScriptAndExtractBool( opener_host, L"", L"window.open('" + UTF8ToWide(url.spec()) + L"');" L"window.domAutomationController.send(true);", &result); ASSERT_TRUE(result); // Now the current tab should be the new tab. TabContents* newtab = browser->GetSelectedTabContents(); if (!newtab->controller().GetLastCommittedEntry() || newtab->controller().GetLastCommittedEntry()->url() != url) ui_test_utils::WaitForNavigation(&newtab->controller()); EXPECT_EQ(url, newtab->controller().GetLastCommittedEntry()->url()); } // Simulates a page navigating itself to an URL, and waits for the navigation. static void NavigateTabHelper(TabContents* contents, const GURL& url) { bool result = false; ui_test_utils::ExecuteJavaScriptAndExtractBool( contents->render_view_host(), L"", L"window.location = '" + UTF8ToWide(url.spec()) + L"';" L"window.domAutomationController.send(true);", &result); ASSERT_TRUE(result); if (contents->controller().GetLastCommittedEntry() || contents->controller().GetLastCommittedEntry()->url() != url) ui_test_utils::WaitForNavigation(&contents->controller()); EXPECT_EQ(url, contents->controller().GetLastCommittedEntry()->url()); } IN_PROC_BROWSER_TEST_F(AppApiTest, AppProcess) { host_resolver()->AddRule("*", "127.0.0.1"); StartHTTPServer(); ASSERT_TRUE(RunExtensionTest("app_process")) << message_; Extension* extension = GetSingleLoadedExtension(); ExtensionHost* host = browser()->profile()->GetExtensionProcessManager()-> GetBackgroundHostForExtension(extension); ASSERT_TRUE(host); // The extension should have opened 3 new tabs. Including the original blank // tab, we now have 4 tabs. Two should be part of the extension app, and // grouped in the extension process. ASSERT_EQ(4, browser()->tab_count()); EXPECT_EQ(host->render_process_host(), browser()->GetTabContentsAt(1)->render_view_host()->process()); EXPECT_EQ(host->render_process_host(), browser()->GetTabContentsAt(2)->render_view_host()->process()); EXPECT_NE(host->render_process_host(), browser()->GetTabContentsAt(3)->render_view_host()->process()); // Now let's do the same using window.open. The same should happen. WindowOpenHelper(browser(), host->render_view_host(), browser()->GetTabContentsAt(1)->GetURL()); WindowOpenHelper(browser(), host->render_view_host(), browser()->GetTabContentsAt(2)->GetURL()); WindowOpenHelper(browser(), host->render_view_host(), browser()->GetTabContentsAt(3)->GetURL()); ASSERT_EQ(7, browser()->tab_count()); EXPECT_EQ(host->render_process_host(), browser()->GetTabContentsAt(4)->render_view_host()->process()); EXPECT_EQ(host->render_process_host(), browser()->GetTabContentsAt(5)->render_view_host()->process()); EXPECT_NE(host->render_process_host(), browser()->GetTabContentsAt(6)->render_view_host()->process()); // Now let's have these pages navigate, into or out of the extension web // extent. They should switch processes. const GURL& app_url(browser()->GetTabContentsAt(1)->GetURL()); const GURL& non_app_url(browser()->GetTabContentsAt(3)->GetURL()); NavigateTabHelper(browser()->GetTabContentsAt(1), non_app_url); NavigateTabHelper(browser()->GetTabContentsAt(3), app_url); EXPECT_NE(host->render_process_host(), browser()->GetTabContentsAt(1)->render_view_host()->process()); EXPECT_EQ(host->render_process_host(), browser()->GetTabContentsAt(3)->render_view_host()->process()); } <commit_msg>mark AppApiTest.AppProcess as flaky<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/browser.h" #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/browser/extensions/extension_host.h" #include "chrome/browser/extensions/extension_process_manager.h" #include "chrome/browser/profile.h" #include "chrome/browser/renderer_host/render_view_host.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/common/chrome_switches.h" #include "chrome/test/ui_test_utils.h" #include "net/base/mock_host_resolver.h" class AppApiTest : public ExtensionApiTest { public: void SetUpCommandLine(CommandLine* command_line) { ExtensionApiTest::SetUpCommandLine(command_line); command_line->AppendSwitch(switches::kEnableExtensionApps); } }; // Simulates a page calling window.open on an URL, and waits for the navigation. static void WindowOpenHelper(Browser* browser, RenderViewHost* opener_host, const GURL& url) { bool result = false; ui_test_utils::ExecuteJavaScriptAndExtractBool( opener_host, L"", L"window.open('" + UTF8ToWide(url.spec()) + L"');" L"window.domAutomationController.send(true);", &result); ASSERT_TRUE(result); // Now the current tab should be the new tab. TabContents* newtab = browser->GetSelectedTabContents(); if (!newtab->controller().GetLastCommittedEntry() || newtab->controller().GetLastCommittedEntry()->url() != url) ui_test_utils::WaitForNavigation(&newtab->controller()); EXPECT_EQ(url, newtab->controller().GetLastCommittedEntry()->url()); } // Simulates a page navigating itself to an URL, and waits for the navigation. static void NavigateTabHelper(TabContents* contents, const GURL& url) { bool result = false; ui_test_utils::ExecuteJavaScriptAndExtractBool( contents->render_view_host(), L"", L"window.location = '" + UTF8ToWide(url.spec()) + L"';" L"window.domAutomationController.send(true);", &result); ASSERT_TRUE(result); if (contents->controller().GetLastCommittedEntry() || contents->controller().GetLastCommittedEntry()->url() != url) ui_test_utils::WaitForNavigation(&contents->controller()); EXPECT_EQ(url, contents->controller().GetLastCommittedEntry()->url()); } // This test is flaky, see bug 42497. IN_PROC_BROWSER_TEST_F(AppApiTest, FLAKY_AppProcess) { host_resolver()->AddRule("*", "127.0.0.1"); StartHTTPServer(); ASSERT_TRUE(RunExtensionTest("app_process")) << message_; Extension* extension = GetSingleLoadedExtension(); ExtensionHost* host = browser()->profile()->GetExtensionProcessManager()-> GetBackgroundHostForExtension(extension); ASSERT_TRUE(host); // The extension should have opened 3 new tabs. Including the original blank // tab, we now have 4 tabs. Two should be part of the extension app, and // grouped in the extension process. ASSERT_EQ(4, browser()->tab_count()); EXPECT_EQ(host->render_process_host(), browser()->GetTabContentsAt(1)->render_view_host()->process()); EXPECT_EQ(host->render_process_host(), browser()->GetTabContentsAt(2)->render_view_host()->process()); EXPECT_NE(host->render_process_host(), browser()->GetTabContentsAt(3)->render_view_host()->process()); // Now let's do the same using window.open. The same should happen. WindowOpenHelper(browser(), host->render_view_host(), browser()->GetTabContentsAt(1)->GetURL()); WindowOpenHelper(browser(), host->render_view_host(), browser()->GetTabContentsAt(2)->GetURL()); WindowOpenHelper(browser(), host->render_view_host(), browser()->GetTabContentsAt(3)->GetURL()); ASSERT_EQ(7, browser()->tab_count()); EXPECT_EQ(host->render_process_host(), browser()->GetTabContentsAt(4)->render_view_host()->process()); EXPECT_EQ(host->render_process_host(), browser()->GetTabContentsAt(5)->render_view_host()->process()); EXPECT_NE(host->render_process_host(), browser()->GetTabContentsAt(6)->render_view_host()->process()); // Now let's have these pages navigate, into or out of the extension web // extent. They should switch processes. const GURL& app_url(browser()->GetTabContentsAt(1)->GetURL()); const GURL& non_app_url(browser()->GetTabContentsAt(3)->GetURL()); NavigateTabHelper(browser()->GetTabContentsAt(1), non_app_url); NavigateTabHelper(browser()->GetTabContentsAt(3), app_url); EXPECT_NE(host->render_process_host(), browser()->GetTabContentsAt(1)->render_view_host()->process()); EXPECT_EQ(host->render_process_host(), browser()->GetTabContentsAt(3)->render_view_host()->process()); } <|endoftext|>
<commit_before>#include <iostream> #include <stdexcept> #include <pqxx/pqxx> namespace pqxx { namespace test { class test_failure : public PGSTD::logic_error { const PGSTD::string m_file; int m_line; public: test_failure( const PGSTD::string &ffile, int fline, const PGSTD::string &desc) : logic_error(desc), m_file(ffile), m_line(fline) {} ~test_failure() throw () {} const PGSTD::string &file() const throw () { return m_file; } int line() const throw () { return m_line; } }; // Run a libpqxx test function. template<typename TESTFUNC> inline int pqxxtest(TESTFUNC &func) { try { func(); } catch (const test_failure &e) { PGSTD::cerr << "Test failure in " + e.file() + " line " + to_string(e.line()) << ": " << e.what() << PGSTD::endl; return 1; } catch (const sql_error &e) { PGSTD::cerr << "SQL error: " << e.what() << PGSTD::endl << "Query was: " << e.query() << PGSTD::endl; return 1; } catch (const PGSTD::exception &e) { PGSTD::cerr << "Exception: " << e.what() << PGSTD::endl; return 2; } catch (...) { PGSTD::cerr << "Unknown exception" << PGSTD::endl; return 100; } return 0; } // pqxxtest() /// Does this backend have generate_series()? inline bool have_generate_series(const connection_base &c) { return c.server_version() >= 80000; } /// For backends that don't have generate_series(): sequence of ints /** If the backend lacks generate_series(), prepares a temp table called * series" containing given range of numbers (including lowest and highest). * * Use select_series() to construct a query selecting a range of numbers. For * the workaround on older backends to work, the ranges of numbers passed to * select_series() must be subsets of the range passed here. */ inline void prepare_series(transaction_base &t, int lowest, int highest) { if (!have_generate_series(t.conn())) { t.exec("CREATE TEMP TABLE series(x integer)"); for (int x=lowest; x <= highest; ++x) t.exec("INSERT INTO series(x) VALUES (" + to_string(x) + ")"); } } /// Generate query selecting series of numbers from lowest to highest, inclusive /** Needs to see connection object to determine whether the backend supports * generate_series(). */ inline PGSTD::string select_series(connection_base &conn, int lowest, int highest) { if (pqxx::test::have_generate_series(conn)) return "SELECT generate_series(" + to_string(lowest) + ", " + to_string(highest) + ")"; return "SELECT x FROM series " "WHERE " "x >= " + to_string(lowest) + " AND " "x <= " + to_string(highest) + " " "ORDER BY x"; } /// Base class for libpqxx tests. Sets up a connection and transaction. template<typename CONNECTION=connection, typename TRANSACTION=work> class TestCase { public: typedef void (*testfunc)(connection_base &, transaction_base &); // func takes connection and transaction as arguments. TestCase(const PGSTD::string &name, testfunc func) : m_conn(), m_trans(m_conn, name), m_func(func) { // Workaround for older backend versions that lack generate_series(). prepare_series(m_trans, 0, 100); } void operator()() { m_func(m_conn, m_trans); } private: CONNECTION m_conn; TRANSACTION m_trans; testfunc m_func; }; // Verify that variable has the expected value. #define PQXX_CHECK_EQUAL(actual, expected, desc) \ if (!(expected == actual)) throw pqxx::test::test_failure( \ __FILE__, \ __LINE__, \ PGSTD::string(desc) + " " \ "(" #actual " <> " #expected ": " + \ "expected=" + to_string(expected) + ", " \ "actual=" + to_string(actual) + ")"); // Verify that "action" throws "exception_type." #define PQXX_CHECK_THROWS(action, exception_type, desc) \ { \ bool pqxx_check_throws_failed = true; \ try \ { \ action ; \ pqxx_check_throws_failed = false; \ } \ catch (const exception_type &) {} \ catch (const PGSTD::exception &e) \ { \ throw pqxx::test::test_failure( \ __FILE__, \ __LINE__, \ PGSTD::string(desc) + " " \ "(" #action ": " \ "expected=" #exception_type ", " \ "threw='" + e.what() + ")"); \ } \ catch (...) \ { \ throw pqxx::test::test_failure( \ __FILE__, \ __LINE__, \ PGSTD::string(desc) + " " \ "(" #action ": " "unexpected exception)"); \ } \ if (!pqxx_check_throws_failed) throw pqxx::test::test_failure( \ __FILE__, \ __LINE__, \ PGSTD::string(desc) + " " \ "(" #action ": " \ "expected=" #exception_type ", " \ "did not throw)"); \ } } // namespace test } // namespace pqxx <commit_msg>Missing quote in exception message.<commit_after>#include <iostream> #include <stdexcept> #include <pqxx/pqxx> namespace pqxx { namespace test { class test_failure : public PGSTD::logic_error { const PGSTD::string m_file; int m_line; public: test_failure( const PGSTD::string &ffile, int fline, const PGSTD::string &desc) : logic_error(desc), m_file(ffile), m_line(fline) {} ~test_failure() throw () {} const PGSTD::string &file() const throw () { return m_file; } int line() const throw () { return m_line; } }; // Run a libpqxx test function. template<typename TESTFUNC> inline int pqxxtest(TESTFUNC &func) { try { func(); } catch (const test_failure &e) { PGSTD::cerr << "Test failure in " + e.file() + " line " + to_string(e.line()) << ": " << e.what() << PGSTD::endl; return 1; } catch (const sql_error &e) { PGSTD::cerr << "SQL error: " << e.what() << PGSTD::endl << "Query was: " << e.query() << PGSTD::endl; return 1; } catch (const PGSTD::exception &e) { PGSTD::cerr << "Exception: " << e.what() << PGSTD::endl; return 2; } catch (...) { PGSTD::cerr << "Unknown exception" << PGSTD::endl; return 100; } return 0; } // pqxxtest() /// Does this backend have generate_series()? inline bool have_generate_series(const connection_base &c) { return c.server_version() >= 80000; } /// For backends that don't have generate_series(): sequence of ints /** If the backend lacks generate_series(), prepares a temp table called * series" containing given range of numbers (including lowest and highest). * * Use select_series() to construct a query selecting a range of numbers. For * the workaround on older backends to work, the ranges of numbers passed to * select_series() must be subsets of the range passed here. */ inline void prepare_series(transaction_base &t, int lowest, int highest) { if (!have_generate_series(t.conn())) { t.exec("CREATE TEMP TABLE series(x integer)"); for (int x=lowest; x <= highest; ++x) t.exec("INSERT INTO series(x) VALUES (" + to_string(x) + ")"); } } /// Generate query selecting series of numbers from lowest to highest, inclusive /** Needs to see connection object to determine whether the backend supports * generate_series(). */ inline PGSTD::string select_series(connection_base &conn, int lowest, int highest) { if (pqxx::test::have_generate_series(conn)) return "SELECT generate_series(" + to_string(lowest) + ", " + to_string(highest) + ")"; return "SELECT x FROM series " "WHERE " "x >= " + to_string(lowest) + " AND " "x <= " + to_string(highest) + " " "ORDER BY x"; } /// Base class for libpqxx tests. Sets up a connection and transaction. template<typename CONNECTION=connection, typename TRANSACTION=work> class TestCase { public: typedef void (*testfunc)(connection_base &, transaction_base &); // func takes connection and transaction as arguments. TestCase(const PGSTD::string &name, testfunc func) : m_conn(), m_trans(m_conn, name), m_func(func) { // Workaround for older backend versions that lack generate_series(). prepare_series(m_trans, 0, 100); } void operator()() { m_func(m_conn, m_trans); } private: CONNECTION m_conn; TRANSACTION m_trans; testfunc m_func; }; // Verify that variable has the expected value. #define PQXX_CHECK_EQUAL(actual, expected, desc) \ if (!(expected == actual)) throw pqxx::test::test_failure( \ __FILE__, \ __LINE__, \ PGSTD::string(desc) + " " \ "(" #actual " <> " #expected ": " + \ "expected=" + to_string(expected) + ", " \ "actual=" + to_string(actual) + ")"); // Verify that "action" throws "exception_type." #define PQXX_CHECK_THROWS(action, exception_type, desc) \ { \ bool pqxx_check_throws_failed = true; \ try \ { \ action ; \ pqxx_check_throws_failed = false; \ } \ catch (const exception_type &) {} \ catch (const PGSTD::exception &e) \ { \ throw pqxx::test::test_failure( \ __FILE__, \ __LINE__, \ PGSTD::string(desc) + " " \ "(" #action ": " \ "expected=" #exception_type ", " \ "threw='" + e.what() + "')"); \ } \ catch (...) \ { \ throw pqxx::test::test_failure( \ __FILE__, \ __LINE__, \ PGSTD::string(desc) + " " \ "(" #action ": " "unexpected exception)"); \ } \ if (!pqxx_check_throws_failed) throw pqxx::test::test_failure( \ __FILE__, \ __LINE__, \ PGSTD::string(desc) + " " \ "(" #action ": " \ "expected=" #exception_type ", " \ "did not throw)"); \ } } // namespace test } // namespace pqxx <|endoftext|>
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/webui/print_preview_handler.h" #include <string> #include "base/i18n/file_util_icu.h" #include "base/json/json_reader.h" #include "base/path_service.h" #include "base/threading/thread.h" #include "base/threading/thread_restrictions.h" #include "base/utf_string_conversions.h" #include "base/values.h" #include "chrome/browser/platform_util.h" #include "chrome/browser/printing/print_preview_tab_controller.h" #include "chrome/browser/ui/tab_contents/tab_contents_wrapper.h" #include "chrome/browser/ui/webui/print_preview_ui_html_source.h" #include "chrome/browser/ui/webui/print_preview_ui.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/print_messages.h" #include "content/browser/browser_thread.h" #include "content/browser/renderer_host/render_view_host.h" #include "content/browser/tab_contents/tab_contents.h" #include "printing/backend/print_backend.h" #include "printing/metafile.h" #include "printing/metafile_impl.h" #include "printing/print_job_constants.h" #if defined(OS_POSIX) && !defined(OS_CHROMEOS) #include <cups/cups.h> #include "base/file_util.h" #endif namespace { const bool kColorDefaultValue = false; const bool kLandscapeDefaultValue = false; const char kDisableColorOption[] = "disableColorOption"; const char kSetColorAsDefault[] = "setColorAsDefault"; #if defined(OS_POSIX) && !defined(OS_CHROMEOS) const char kColorDevice[] = "ColorDevice"; #endif TabContents* GetInitiatorTab(TabContents* preview_tab) { printing::PrintPreviewTabController* tab_controller = printing::PrintPreviewTabController::GetInstance(); if (!tab_controller) return NULL; return tab_controller->GetInitiatorTab(preview_tab); } // Get the print job settings dictionary from |args|. The caller takes // ownership of the returned DictionaryValue. Returns NULL on failure. DictionaryValue* GetSettingsDictionary(const ListValue* args) { std::string json_str; if (!args->GetString(0, &json_str)) { NOTREACHED() << "Could not read JSON argument"; return NULL; } if (json_str.empty()) { NOTREACHED() << "Empty print job settings"; return NULL; } scoped_ptr<DictionaryValue> settings(static_cast<DictionaryValue*>( base::JSONReader::Read(json_str, false))); if (!settings.get() || !settings->IsType(Value::TYPE_DICTIONARY)) { NOTREACHED() << "Print job settings must be a dictionary."; return NULL; } if (settings->empty()) { NOTREACHED() << "Print job settings dictionary is empty"; return NULL; } return settings.release(); } } // namespace class PrintSystemTaskProxy : public base::RefCountedThreadSafe<PrintSystemTaskProxy, BrowserThread::DeleteOnUIThread> { public: PrintSystemTaskProxy(const base::WeakPtr<PrintPreviewHandler>& handler, printing::PrintBackend* print_backend) : handler_(handler), print_backend_(print_backend) { } void EnumeratePrinters() { ListValue* printers = new ListValue; int default_printer_index = -1; printing::PrinterList printer_list; print_backend_->EnumeratePrinters(&printer_list); int i = 0; for (printing::PrinterList::iterator index = printer_list.begin(); index != printer_list.end(); ++index, ++i) { printers->Append(new StringValue(index->printer_name)); if (index->is_default) default_printer_index = i; } BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, NewRunnableMethod(this, &PrintSystemTaskProxy::SendPrinterList, printers, new FundamentalValue(default_printer_index))); } void SendPrinterList(ListValue* printers, FundamentalValue* default_printer_index) { if (handler_) handler_->SendPrinterList(*printers, *default_printer_index); delete printers; delete default_printer_index; } void GetPrinterCapabilities(const std::string& printer_name) { printing::PrinterCapsAndDefaults printer_info; bool supports_color = true; if (!print_backend_->GetPrinterCapsAndDefaults(printer_name, &printer_info)) { return; } #if defined(OS_POSIX) && !defined(OS_CHROMEOS) FilePath ppd_file_path; if (!file_util::CreateTemporaryFile(&ppd_file_path)) return; int data_size = printer_info.printer_capabilities.length(); if (data_size != file_util::WriteFile( ppd_file_path, printer_info.printer_capabilities.data(), data_size)) { file_util::Delete(ppd_file_path, false); return; } ppd_file_t* ppd = ppdOpenFile(ppd_file_path.value().c_str()); if (ppd) { ppd_attr_t* attr = ppdFindAttr(ppd, kColorDevice, NULL); if (attr && attr->value) supports_color = ppd->color_device; ppdClose(ppd); } file_util::Delete(ppd_file_path, false); #elif defined(OS_WIN) || defined(OS_CHROMEOS) NOTIMPLEMENTED(); #endif DictionaryValue settings_info; settings_info.SetBoolean(kDisableColorOption, !supports_color); settings_info.SetBoolean(kSetColorAsDefault, false); BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, NewRunnableMethod(this, &PrintSystemTaskProxy::SendPrinterCapabilities, settings_info.DeepCopy())); } void SendPrinterCapabilities(DictionaryValue* settings_info) { if (handler_) handler_->SendPrinterCapabilities(*settings_info); delete settings_info; } private: friend struct BrowserThread::DeleteOnThread<BrowserThread::UI>; friend class DeleteTask<PrintSystemTaskProxy>; ~PrintSystemTaskProxy() {} base::WeakPtr<PrintPreviewHandler> handler_; scoped_refptr<printing::PrintBackend> print_backend_; DISALLOW_COPY_AND_ASSIGN(PrintSystemTaskProxy); }; // A Task implementation that stores a PDF file on disk. class PrintToPdfTask : public Task { public: // Takes ownership of |metafile|. PrintToPdfTask(printing::Metafile* metafile, const FilePath& path) : metafile_(metafile), path_(path) { } ~PrintToPdfTask() {} // Task implementation virtual void Run() { metafile_->SaveTo(path_); } private: // The metafile holding the PDF data. scoped_ptr<printing::Metafile> metafile_; // The absolute path where the file will be saved. FilePath path_; }; // static FilePath* PrintPreviewHandler::last_saved_path_ = NULL; PrintPreviewHandler::PrintPreviewHandler() : print_backend_(printing::PrintBackend::CreateInstance(NULL)) { } PrintPreviewHandler::~PrintPreviewHandler() { if (select_file_dialog_.get()) select_file_dialog_->ListenerDestroyed(); } void PrintPreviewHandler::RegisterMessages() { web_ui_->RegisterMessageCallback("getPrinters", NewCallback(this, &PrintPreviewHandler::HandleGetPrinters)); web_ui_->RegisterMessageCallback("getPreview", NewCallback(this, &PrintPreviewHandler::HandleGetPreview)); web_ui_->RegisterMessageCallback("print", NewCallback(this, &PrintPreviewHandler::HandlePrint)); web_ui_->RegisterMessageCallback("getPrinterCapabilities", NewCallback(this, &PrintPreviewHandler::HandleGetPrinterCapabilities)); } void PrintPreviewHandler::HandleGetPrinters(const ListValue*) { scoped_refptr<PrintSystemTaskProxy> task = new PrintSystemTaskProxy(AsWeakPtr(), print_backend_.get()); BrowserThread::PostTask( BrowserThread::FILE, FROM_HERE, NewRunnableMethod(task.get(), &PrintSystemTaskProxy::EnumeratePrinters)); } void PrintPreviewHandler::HandleGetPreview(const ListValue* args) { TabContents* initiator_tab = GetInitiatorTab(web_ui_->tab_contents()); if (!initiator_tab) return; scoped_ptr<DictionaryValue> settings(GetSettingsDictionary(args)); if (!settings.get()) return; RenderViewHost* rvh = initiator_tab->render_view_host(); rvh->Send(new PrintMsg_PrintPreview(rvh->routing_id(), *settings)); } void PrintPreviewHandler::HandlePrint(const ListValue* args) { TabContents* initiator_tab = GetInitiatorTab(web_ui_->tab_contents()); if (initiator_tab) { RenderViewHost* rvh = initiator_tab->render_view_host(); rvh->Send(new PrintMsg_ResetScriptedPrintCount(rvh->routing_id())); } scoped_ptr<DictionaryValue> settings(GetSettingsDictionary(args)); if (!settings.get()) return; bool print_to_pdf = false; settings->GetBoolean(printing::kSettingPrintToPDF, &print_to_pdf); if (print_to_pdf) { // Pre-populating select file dialog with print job title. TabContentsWrapper* wrapper = TabContentsWrapper::GetCurrentWrapperForContents( web_ui_->tab_contents()); string16 print_job_title_utf16 = wrapper->print_view_manager()->RenderSourceName(); #if defined(OS_WIN) FilePath::StringType print_job_title(print_job_title_utf16); #elif defined(OS_POSIX) FilePath::StringType print_job_title = UTF16ToUTF8(print_job_title_utf16); #endif file_util::ReplaceIllegalCharactersInPath(&print_job_title, '_'); FilePath default_filename(print_job_title); default_filename = default_filename.ReplaceExtension(FILE_PATH_LITERAL("pdf")); SelectFile(default_filename); } else { // The PDF being printed contains only the pages that the user selected, // so ignore the page range and print all pages. settings->Remove(printing::kSettingPageRange, NULL); RenderViewHost* rvh = web_ui_->GetRenderViewHost(); rvh->Send(new PrintMsg_PrintForPrintPreview(rvh->routing_id(), *settings)); } } void PrintPreviewHandler::HandleGetPrinterCapabilities( const ListValue* args) { std::string printer_name; bool ret = args->GetString(0, &printer_name); if (!ret || printer_name.empty()) return; scoped_refptr<PrintSystemTaskProxy> task = new PrintSystemTaskProxy(AsWeakPtr(), print_backend_.get()); BrowserThread::PostTask( BrowserThread::FILE, FROM_HERE, NewRunnableMethod(task.get(), &PrintSystemTaskProxy::GetPrinterCapabilities, printer_name)); } void PrintPreviewHandler::SendPrinterCapabilities( const DictionaryValue& settings_info) { web_ui_->CallJavascriptFunction("updateWithPrinterCapabilities", settings_info); } void PrintPreviewHandler::SendPrinterList( const ListValue& printers, const FundamentalValue& default_printer_index) { web_ui_->CallJavascriptFunction("setPrinters", printers, default_printer_index); } void PrintPreviewHandler::SelectFile(const FilePath& default_filename) { SelectFileDialog::FileTypeInfo file_type_info; file_type_info.extensions.resize(1); file_type_info.extensions[0].push_back(FILE_PATH_LITERAL("pdf")); // Initializing last_saved_path_ if it is not already initialized. if (!last_saved_path_) { last_saved_path_ = new FilePath(); // Allowing IO operation temporarily. It is ok to do so here because // the select file dialog performs IO anyway in order to display the // folders and also it is modal. base::ThreadRestrictions::ScopedAllowIO allow_io; PathService::Get(chrome::DIR_USER_DOCUMENTS, last_saved_path_); } if (!select_file_dialog_.get()) select_file_dialog_ = SelectFileDialog::Create(this); select_file_dialog_->SelectFile( SelectFileDialog::SELECT_SAVEAS_FILE, string16(), last_saved_path_->Append(default_filename), &file_type_info, 0, FILE_PATH_LITERAL(""), web_ui_->tab_contents(), platform_util::GetTopLevel( web_ui_->tab_contents()->GetNativeView()), NULL); } void PrintPreviewHandler::FileSelected(const FilePath& path, int index, void* params) { PrintPreviewUIHTMLSource::PrintPreviewData data; PrintPreviewUI* print_preview_ui = static_cast<PrintPreviewUI*>(web_ui_); print_preview_ui->html_source()->GetPrintPreviewData(&data); DCHECK(data.first); DCHECK_GT(data.second, 0U); printing::PreviewMetafile* metafile = new printing::PreviewMetafile; metafile->InitFromData(data.first->memory(), data.second); // Updating last_saved_path_ to the newly selected folder. *last_saved_path_ = path.DirName(); PrintToPdfTask* task = new PrintToPdfTask(metafile, path); BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE, task); } <commit_msg>Detect if printer is capable of printing color<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/webui/print_preview_handler.h" #include <string> #include "base/i18n/file_util_icu.h" #include "base/json/json_reader.h" #include "base/path_service.h" #include "base/threading/thread.h" #include "base/threading/thread_restrictions.h" #include "base/utf_string_conversions.h" #include "base/values.h" #include "chrome/browser/platform_util.h" #include "chrome/browser/printing/print_preview_tab_controller.h" #include "chrome/browser/ui/tab_contents/tab_contents_wrapper.h" #include "chrome/browser/ui/webui/print_preview_ui_html_source.h" #include "chrome/browser/ui/webui/print_preview_ui.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/print_messages.h" #include "content/browser/browser_thread.h" #include "content/browser/renderer_host/render_view_host.h" #include "content/browser/tab_contents/tab_contents.h" #include "printing/backend/print_backend.h" #include "printing/metafile.h" #include "printing/metafile_impl.h" #include "printing/print_job_constants.h" #if defined(OS_POSIX) && !defined(OS_CHROMEOS) #include <cups/cups.h> #include "base/file_util.h" #endif namespace { const bool kColorDefaultValue = false; const bool kLandscapeDefaultValue = false; const char kDisableColorOption[] = "disableColorOption"; const char kSetColorAsDefault[] = "setColorAsDefault"; #if defined(OS_POSIX) && !defined(OS_CHROMEOS) const char kColorDevice[] = "ColorDevice"; #elif defined(OS_WIN) const char kPskColor[] = "psk:Color"; #endif TabContents* GetInitiatorTab(TabContents* preview_tab) { printing::PrintPreviewTabController* tab_controller = printing::PrintPreviewTabController::GetInstance(); if (!tab_controller) return NULL; return tab_controller->GetInitiatorTab(preview_tab); } // Get the print job settings dictionary from |args|. The caller takes // ownership of the returned DictionaryValue. Returns NULL on failure. DictionaryValue* GetSettingsDictionary(const ListValue* args) { std::string json_str; if (!args->GetString(0, &json_str)) { NOTREACHED() << "Could not read JSON argument"; return NULL; } if (json_str.empty()) { NOTREACHED() << "Empty print job settings"; return NULL; } scoped_ptr<DictionaryValue> settings(static_cast<DictionaryValue*>( base::JSONReader::Read(json_str, false))); if (!settings.get() || !settings->IsType(Value::TYPE_DICTIONARY)) { NOTREACHED() << "Print job settings must be a dictionary."; return NULL; } if (settings->empty()) { NOTREACHED() << "Print job settings dictionary is empty"; return NULL; } return settings.release(); } } // namespace class PrintSystemTaskProxy : public base::RefCountedThreadSafe<PrintSystemTaskProxy, BrowserThread::DeleteOnUIThread> { public: PrintSystemTaskProxy(const base::WeakPtr<PrintPreviewHandler>& handler, printing::PrintBackend* print_backend) : handler_(handler), print_backend_(print_backend) { } void EnumeratePrinters() { ListValue* printers = new ListValue; int default_printer_index = -1; printing::PrinterList printer_list; print_backend_->EnumeratePrinters(&printer_list); int i = 0; for (printing::PrinterList::iterator index = printer_list.begin(); index != printer_list.end(); ++index, ++i) { printers->Append(new StringValue(index->printer_name)); if (index->is_default) default_printer_index = i; } BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, NewRunnableMethod(this, &PrintSystemTaskProxy::SendPrinterList, printers, new FundamentalValue(default_printer_index))); } void SendPrinterList(ListValue* printers, FundamentalValue* default_printer_index) { if (handler_) handler_->SendPrinterList(*printers, *default_printer_index); delete printers; delete default_printer_index; } void GetPrinterCapabilities(const std::string& printer_name) { printing::PrinterCapsAndDefaults printer_info; bool supports_color = true; if (!print_backend_->GetPrinterCapsAndDefaults(printer_name, &printer_info)) { return; } #if defined(OS_POSIX) && !defined(OS_CHROMEOS) FilePath ppd_file_path; if (!file_util::CreateTemporaryFile(&ppd_file_path)) return; int data_size = printer_info.printer_capabilities.length(); if (data_size != file_util::WriteFile( ppd_file_path, printer_info.printer_capabilities.data(), data_size)) { file_util::Delete(ppd_file_path, false); return; } ppd_file_t* ppd = ppdOpenFile(ppd_file_path.value().c_str()); if (ppd) { ppd_attr_t* attr = ppdFindAttr(ppd, kColorDevice, NULL); if (attr && attr->value) supports_color = ppd->color_device; ppdClose(ppd); } file_util::Delete(ppd_file_path, false); #elif defined(OS_WIN) // According to XPS 1.0 spec, only color printers have psk:Color. // Therefore we don't need to parse the whole XML file, we just need to // search the string. The spec can be found at: // http://msdn.microsoft.com/en-us/windows/hardware/gg463431. supports_color = (printer_info.printer_capabilities.find(kPskColor) != std::string::npos); #elif defined(OS_CHROMEOS) NOTIMPLEMENTED(); #endif DictionaryValue settings_info; settings_info.SetBoolean(kDisableColorOption, !supports_color); settings_info.SetBoolean(kSetColorAsDefault, false); BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, NewRunnableMethod(this, &PrintSystemTaskProxy::SendPrinterCapabilities, settings_info.DeepCopy())); } void SendPrinterCapabilities(DictionaryValue* settings_info) { if (handler_) handler_->SendPrinterCapabilities(*settings_info); delete settings_info; } private: friend struct BrowserThread::DeleteOnThread<BrowserThread::UI>; friend class DeleteTask<PrintSystemTaskProxy>; ~PrintSystemTaskProxy() {} base::WeakPtr<PrintPreviewHandler> handler_; scoped_refptr<printing::PrintBackend> print_backend_; DISALLOW_COPY_AND_ASSIGN(PrintSystemTaskProxy); }; // A Task implementation that stores a PDF file on disk. class PrintToPdfTask : public Task { public: // Takes ownership of |metafile|. PrintToPdfTask(printing::Metafile* metafile, const FilePath& path) : metafile_(metafile), path_(path) { } ~PrintToPdfTask() {} // Task implementation virtual void Run() { metafile_->SaveTo(path_); } private: // The metafile holding the PDF data. scoped_ptr<printing::Metafile> metafile_; // The absolute path where the file will be saved. FilePath path_; }; // static FilePath* PrintPreviewHandler::last_saved_path_ = NULL; PrintPreviewHandler::PrintPreviewHandler() : print_backend_(printing::PrintBackend::CreateInstance(NULL)) { } PrintPreviewHandler::~PrintPreviewHandler() { if (select_file_dialog_.get()) select_file_dialog_->ListenerDestroyed(); } void PrintPreviewHandler::RegisterMessages() { web_ui_->RegisterMessageCallback("getPrinters", NewCallback(this, &PrintPreviewHandler::HandleGetPrinters)); web_ui_->RegisterMessageCallback("getPreview", NewCallback(this, &PrintPreviewHandler::HandleGetPreview)); web_ui_->RegisterMessageCallback("print", NewCallback(this, &PrintPreviewHandler::HandlePrint)); web_ui_->RegisterMessageCallback("getPrinterCapabilities", NewCallback(this, &PrintPreviewHandler::HandleGetPrinterCapabilities)); } void PrintPreviewHandler::HandleGetPrinters(const ListValue*) { scoped_refptr<PrintSystemTaskProxy> task = new PrintSystemTaskProxy(AsWeakPtr(), print_backend_.get()); BrowserThread::PostTask( BrowserThread::FILE, FROM_HERE, NewRunnableMethod(task.get(), &PrintSystemTaskProxy::EnumeratePrinters)); } void PrintPreviewHandler::HandleGetPreview(const ListValue* args) { TabContents* initiator_tab = GetInitiatorTab(web_ui_->tab_contents()); if (!initiator_tab) return; scoped_ptr<DictionaryValue> settings(GetSettingsDictionary(args)); if (!settings.get()) return; RenderViewHost* rvh = initiator_tab->render_view_host(); rvh->Send(new PrintMsg_PrintPreview(rvh->routing_id(), *settings)); } void PrintPreviewHandler::HandlePrint(const ListValue* args) { TabContents* initiator_tab = GetInitiatorTab(web_ui_->tab_contents()); if (initiator_tab) { RenderViewHost* rvh = initiator_tab->render_view_host(); rvh->Send(new PrintMsg_ResetScriptedPrintCount(rvh->routing_id())); } scoped_ptr<DictionaryValue> settings(GetSettingsDictionary(args)); if (!settings.get()) return; bool print_to_pdf = false; settings->GetBoolean(printing::kSettingPrintToPDF, &print_to_pdf); if (print_to_pdf) { // Pre-populating select file dialog with print job title. TabContentsWrapper* wrapper = TabContentsWrapper::GetCurrentWrapperForContents( web_ui_->tab_contents()); string16 print_job_title_utf16 = wrapper->print_view_manager()->RenderSourceName(); #if defined(OS_WIN) FilePath::StringType print_job_title(print_job_title_utf16); #elif defined(OS_POSIX) FilePath::StringType print_job_title = UTF16ToUTF8(print_job_title_utf16); #endif file_util::ReplaceIllegalCharactersInPath(&print_job_title, '_'); FilePath default_filename(print_job_title); default_filename = default_filename.ReplaceExtension(FILE_PATH_LITERAL("pdf")); SelectFile(default_filename); } else { // The PDF being printed contains only the pages that the user selected, // so ignore the page range and print all pages. settings->Remove(printing::kSettingPageRange, NULL); RenderViewHost* rvh = web_ui_->GetRenderViewHost(); rvh->Send(new PrintMsg_PrintForPrintPreview(rvh->routing_id(), *settings)); } } void PrintPreviewHandler::HandleGetPrinterCapabilities( const ListValue* args) { std::string printer_name; bool ret = args->GetString(0, &printer_name); if (!ret || printer_name.empty()) return; scoped_refptr<PrintSystemTaskProxy> task = new PrintSystemTaskProxy(AsWeakPtr(), print_backend_.get()); BrowserThread::PostTask( BrowserThread::FILE, FROM_HERE, NewRunnableMethod(task.get(), &PrintSystemTaskProxy::GetPrinterCapabilities, printer_name)); } void PrintPreviewHandler::SendPrinterCapabilities( const DictionaryValue& settings_info) { web_ui_->CallJavascriptFunction("updateWithPrinterCapabilities", settings_info); } void PrintPreviewHandler::SendPrinterList( const ListValue& printers, const FundamentalValue& default_printer_index) { web_ui_->CallJavascriptFunction("setPrinters", printers, default_printer_index); } void PrintPreviewHandler::SelectFile(const FilePath& default_filename) { SelectFileDialog::FileTypeInfo file_type_info; file_type_info.extensions.resize(1); file_type_info.extensions[0].push_back(FILE_PATH_LITERAL("pdf")); // Initializing last_saved_path_ if it is not already initialized. if (!last_saved_path_) { last_saved_path_ = new FilePath(); // Allowing IO operation temporarily. It is ok to do so here because // the select file dialog performs IO anyway in order to display the // folders and also it is modal. base::ThreadRestrictions::ScopedAllowIO allow_io; PathService::Get(chrome::DIR_USER_DOCUMENTS, last_saved_path_); } if (!select_file_dialog_.get()) select_file_dialog_ = SelectFileDialog::Create(this); select_file_dialog_->SelectFile( SelectFileDialog::SELECT_SAVEAS_FILE, string16(), last_saved_path_->Append(default_filename), &file_type_info, 0, FILE_PATH_LITERAL(""), web_ui_->tab_contents(), platform_util::GetTopLevel( web_ui_->tab_contents()->GetNativeView()), NULL); } void PrintPreviewHandler::FileSelected(const FilePath& path, int index, void* params) { PrintPreviewUIHTMLSource::PrintPreviewData data; PrintPreviewUI* print_preview_ui = static_cast<PrintPreviewUI*>(web_ui_); print_preview_ui->html_source()->GetPrintPreviewData(&data); DCHECK(data.first); DCHECK_GT(data.second, 0U); printing::PreviewMetafile* metafile = new printing::PreviewMetafile; metafile->InitFromData(data.first->memory(), data.second); // Updating last_saved_path_ to the newly selected folder. *last_saved_path_ = path.DirName(); PrintToPdfTask* task = new PrintToPdfTask(metafile, path); BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE, task); } <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Constant defines used in the cloud print proxy code #include "chrome/service/cloud_print/cloud_print_consts.h" const char kProxyIdValue[] = "proxy"; const char kPrinterNameValue[] = "printer"; const char kPrinterDescValue[] = "description"; const char kPrinterCapsValue[] = "capabilities"; const char kPrinterDefaultsValue[] = "defaults"; const char kPrinterStatusValue[] = "status"; const char kPrinterTagValue[] = "tag"; // Values in the respone JSON from the cloud print server const wchar_t kPrinterListValue[] = L"printers"; const wchar_t kSuccessValue[] = L"success"; const wchar_t kNameValue[] = L"name"; const wchar_t kIdValue[] = L"id"; const wchar_t kTicketUrlValue[] = L"ticketUrl"; const wchar_t kFileUrlValue[] = L"fileUrl"; const wchar_t kJobListValue[] = L"jobs"; const wchar_t kTitleValue[] = L"title"; const wchar_t kPrinterCapsHashValue[] = L"capsHash"; const char kDefaultCloudPrintServerUrl[] = "https://www.google.com/cloudprint"; // TODO(sanjeevr): Change this to a real one. const char kCloudPrintTalkServiceUrl[] = "http://www.google.com/printing"; const char kGaiaUrl[] = "https://www.google.com/accounts/ClientLogin"; // TODO(sanjeevr): Change this to a real one once we get a GAIA service id. const char kCloudPrintGaiaServiceId[] = "print"; const char kSyncGaiaServiceId[] = "chromiumsync"; <commit_msg>Changed values of Cloud Print GAIA service id and Talk service URL to production values. BUG=None. TEST=Test with production cloudprint service. Review URL: http://codereview.chromium.org/2254003<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Constant defines used in the cloud print proxy code #include "chrome/service/cloud_print/cloud_print_consts.h" const char kProxyIdValue[] = "proxy"; const char kPrinterNameValue[] = "printer"; const char kPrinterDescValue[] = "description"; const char kPrinterCapsValue[] = "capabilities"; const char kPrinterDefaultsValue[] = "defaults"; const char kPrinterStatusValue[] = "status"; const char kPrinterTagValue[] = "tag"; // Values in the respone JSON from the cloud print server const wchar_t kPrinterListValue[] = L"printers"; const wchar_t kSuccessValue[] = L"success"; const wchar_t kNameValue[] = L"name"; const wchar_t kIdValue[] = L"id"; const wchar_t kTicketUrlValue[] = L"ticketUrl"; const wchar_t kFileUrlValue[] = L"fileUrl"; const wchar_t kJobListValue[] = L"jobs"; const wchar_t kTitleValue[] = L"title"; const wchar_t kPrinterCapsHashValue[] = L"capsHash"; const char kDefaultCloudPrintServerUrl[] = "https://www.google.com/cloudprint"; const char kCloudPrintTalkServiceUrl[] = "http://www.google.com/cloudprint"; const char kGaiaUrl[] = "https://www.google.com/accounts/ClientLogin"; const char kCloudPrintGaiaServiceId[] = "cloudprint"; const char kSyncGaiaServiceId[] = "chromiumsync"; <|endoftext|>
<commit_before><commit_msg>ENH: Make test usable from command line<commit_after><|endoftext|>
<commit_before>/*! \file NotificationManager.cpp \author Dane Gardner <[email protected]> \section LICENSE This file is part of the Parallel Tools GUI Framework (PTGF) Copyright (C) 2010-2013 Argo Navis Technologies, LLC This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "NotificationManagerPrivate.h" #if QT_VERSION >= 0x050000 # include <QStandardPaths> #else # include <QDesktopServices> #endif #include <QDockWidget> #include <QMenuBar> #include <QDateTime> #include <QDebug> #include <CoreWindow/CoreWindow.h> #include <PluginManager/PluginManager.h> #include <PrettyWidgets/ConsoleWidget.h> #include <ActionManager/ActionManager.h> namespace Core { namespace NotificationManager { /***** PUBLIC IMPLEMENTATION *****/ /*! \class NotificationManager \brief Manages notifications displayed in the CoreWindow and logged events \todo better documentation */ /*! \fn NotificationManager::instance() \brief Accessor to singleton instance \todo better documentation */ NotificationManager &NotificationManager::instance() { static NotificationManager m_Instance; return m_Instance; } /*! \internal \brief NotificationManager::NotificationManager */ NotificationManager::NotificationManager() : d(new NotificationManagerPrivate) { d->q = this; } /*! \internal \brief NotificationManager::~NotificationManager */ NotificationManager::~NotificationManager() { } /*! \internal \brief NotificationManager::initialize \return */ bool NotificationManager::initialize() { if(d->m_Initialized) { return false; } try { CoreWindow::CoreWindow &coreWindow = CoreWindow::CoreWindow::instance(); // Setup dock widget for message console QDockWidget *dockWidget = new QDockWidget(tr("Message Console"), &coreWindow); dockWidget->setObjectName("MessageConsoleDockWidget"); dockWidget->hide(); d->m_ConsoleWidget = new ConsoleWidget(dockWidget); d->m_ConsoleWidget->setEventLevelColor((int)QtDebugMsg, Qt::darkGreen); d->m_ConsoleWidget->setEventLevelColor((int)QtWarningMsg, Qt::darkYellow); d->m_ConsoleWidget->setEventLevelColor((int)QtCriticalMsg, Qt::darkRed); d->m_ConsoleWidget->setEventLevelColor((int)QtFatalMsg, Qt::darkRed); dockWidget->setWidget(d->m_ConsoleWidget); coreWindow.addDockWidget(Qt::BottomDockWidgetArea, dockWidget); ActionManager::ActionManager &actionManager = ActionManager::ActionManager::instance(); ActionManager::MenuPath path("Window"); actionManager.registerAction(path, dockWidget->toggleViewAction()); // Create log file and register handler for qDebug() messages #if QT_VERSION >= 0x050000 d->m_LogFile.setFileName(QString("%1/%2.txt") .arg(QStandardPaths::writableLocation(QStandardPaths::DataLocation)) .arg(QDateTime::currentDateTime().toUTC().toString(QString("yyyyMMddhhmmsszzz")))); #else d->m_LogFile.setFileName(QString("%1/%2.txt") .arg(QDesktopServices::storageLocation(QDesktopServices::DataLocation)) .arg(QDateTime::currentDateTime().toUTC().toString(QString("yyyyMMddhhmmsszzz")))); #endif #if QT_VERSION >= 0x050000 qInstallMessageHandler(d->qMessageHandler); #else qInstallMsgHandler(d->qMessageHandler); #endif Core::PluginManager::PluginManager::instance().addObject(this); } catch(...) { return false; } return d->m_Initialized = true; } /*! \internal \brief NotificationManager::shutdown */ void NotificationManager::shutdown() { if(!d->m_Initialized) { return; } #if QT_VERSION >= 0x050000 qInstallMessageHandler(0); #else qInstallMsgHandler(0); #endif if(d->m_LogFile.isOpen()) { d->m_LogFile.close(); } } /*! \fn NotificationManager::writeToLogFile() \brief Writes message to log file \todo better documentation */ void NotificationManager::writeToLogFile(const int &level, QString message) { d->writeToLogFile(level, message); } /*! \fn NotificationManager::notify() \brief Notification of event displayed in CoreWindow If an identical notification already exists, it will be returned. This means that the same NotificationWidget can be returned under different calls to this function. Do not take ownership, or delete the widget manually, it will screw things up! If the same widget is returned, and a timeout has been set, the timer will be restarted. \returns NotificationWidget, which is owned and destroyed by CoreWindow \todo better documentation */ NotificationWidget *NotificationManager::notify(const QString &text, NotificationWidget::Icon icon, NotificationWidget::StandardButtons buttons, const QObject *receiver, const char *member) { return d->notify(text, icon, buttons, receiver, member); } /***** PRIVATE IMPLEMENTATION *****/ NotificationManagerPrivate::NotificationManagerPrivate() : q(NULL), m_Initialized(false), m_StdOut(stdout, QIODevice::WriteOnly), m_StdError(stderr, QIODevice::WriteOnly), m_ConsoleWidget(NULL) { } NotificationManagerPrivate::~NotificationManagerPrivate() { if(m_LogFile.isOpen()) { m_LogFile.close(); } } void NotificationManagerPrivate::writeToLogFile(const int &level, QString message) { if(!m_LogFile.isOpen()) { m_LogFile.open(QIODevice::Append | QIODevice::Text); m_LogFileStream.setDevice(&m_LogFile); } QDateTime currentTime = QDateTime::currentDateTime().toUTC(); if(m_LogFile.isOpen()) { QString outputString = QString("%1 - %2") .arg(currentTime.toString("yyyy-MM-dd hh:mm:ss.zzz")) .arg(message); m_LogFileStream << outputString << endl; m_StdError << outputString << endl; m_ConsoleWidget->messageEvent(level, outputString); } } #if QT_VERSION >= 0x050000 void NotificationManagerPrivate::qMessageHandler(QtMsgType type, const QMessageLogContext &context, const QString &message) #else void NotificationManagerPrivate::qMessageHandler(QtMsgType type, const char *message) #endif { #if QT_VERSION >= 0x050000 Q_UNUSED(context) #endif QString msg; int level = 0; // Static member function requires that we get the singleton pointer directly NotificationManager *q = &NotificationManager::instance(); switch (type) { case QtDebugMsg: msg = q->tr("Debug: %1").arg(message); level = (int)QtDebugMsg; break; case QtWarningMsg: msg = q->tr("Warning: %1").arg(message); level = (int)QtWarningMsg; q->notify(msg, NotificationWidget::Warning)->setTimeoutInterval(5000); break; case QtCriticalMsg: msg = q->tr("Critical: %1").arg(message); level = (int)QtCriticalMsg; q->notify(msg, NotificationWidget::Critical); break; case QtFatalMsg: msg = q->tr("Fatal: %1").arg(message); level = (int)QtFatalMsg; break; default: msg = q->tr("Unknown: %1").arg(message); break; } q->writeToLogFile(level, msg); if(type == QtFatalMsg) { abort(); } } void NotificationManagerPrivate::removeNotificationWidget() { if(NotificationWidget *nw = qobject_cast<NotificationWidget *>(sender())) { m_NotificationWidgets.removeAll(nw); } } NotificationWidget *NotificationManagerPrivate::notify(const QString &text, NotificationWidget::Icon icon, NotificationWidget::StandardButtons buttons, const QObject *receiver, const char *member) { CoreWindow::CoreWindow &coreWindow = CoreWindow::CoreWindow::instance(); foreach(NotificationWidget *nw, m_NotificationWidgets) { if( nw->text().compare(text, Qt::CaseInsensitive) == 0 && nw->icon() == icon && nw->standardButtons() == buttons ) { if(nw->timeoutInterval() > 0) { // Reset the timer if necessary nw->setTimeoutInterval(nw->timeoutInterval()); } if(receiver && member) { connect(nw, SIGNAL(buttonClicked(NotificationWidget::StandardButton)), receiver, member); } return nw; } } NotificationWidget *notificationWidget = new NotificationWidget(text, icon, buttons, receiver, member, &coreWindow); m_NotificationWidgets.append(notificationWidget); connect(notificationWidget, SIGNAL(closing()), this, SLOT(removeNotificationWidget())); connect(notificationWidget, SIGNAL(destroyed()), this, SLOT(removeNotificationWidget())); coreWindow.addNotificationWidget(notificationWidget); notificationWidget->setFocus(); return notificationWidget; } } // namespace NotificationManager } // namespace Core <commit_msg>Fixed Linux issues with NotificationManager; creating logfile path before tyring to write to logfile<commit_after>/*! \file NotificationManager.cpp \author Dane Gardner <[email protected]> \section LICENSE This file is part of the Parallel Tools GUI Framework (PTGF) Copyright (C) 2010-2013 Argo Navis Technologies, LLC This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "NotificationManagerPrivate.h" #if QT_VERSION >= 0x050000 # include <QStandardPaths> #else # include <QDesktopServices> #endif #include <QDockWidget> #include <QMenuBar> #include <QDateTime> #include <QDebug> #include <QDir> #include <CoreWindow/CoreWindow.h> #include <PluginManager/PluginManager.h> #include <PrettyWidgets/ConsoleWidget.h> #include <ActionManager/ActionManager.h> namespace Core { namespace NotificationManager { /***** PUBLIC IMPLEMENTATION *****/ /*! \class NotificationManager \brief Manages notifications displayed in the CoreWindow and logged events \todo better documentation */ /*! \fn NotificationManager::instance() \brief Accessor to singleton instance \todo better documentation */ NotificationManager &NotificationManager::instance() { static NotificationManager m_Instance; return m_Instance; } /*! \internal \brief NotificationManager::NotificationManager */ NotificationManager::NotificationManager() : d(new NotificationManagerPrivate) { d->q = this; } /*! \internal \brief NotificationManager::~NotificationManager */ NotificationManager::~NotificationManager() { } /*! \internal \brief NotificationManager::initialize \return */ bool NotificationManager::initialize() { if(d->m_Initialized) { return false; } try { CoreWindow::CoreWindow &coreWindow = CoreWindow::CoreWindow::instance(); // Setup dock widget for message console QDockWidget *dockWidget = new QDockWidget(tr("Message Console"), &coreWindow); dockWidget->setObjectName("MessageConsoleDockWidget"); dockWidget->hide(); d->m_ConsoleWidget = new ConsoleWidget(dockWidget); d->m_ConsoleWidget->setEventLevelColor((int)QtDebugMsg, Qt::darkGreen); d->m_ConsoleWidget->setEventLevelColor((int)QtWarningMsg, Qt::darkYellow); d->m_ConsoleWidget->setEventLevelColor((int)QtCriticalMsg, Qt::darkRed); d->m_ConsoleWidget->setEventLevelColor((int)QtFatalMsg, Qt::darkRed); dockWidget->setWidget(d->m_ConsoleWidget); coreWindow.addDockWidget(Qt::BottomDockWidgetArea, dockWidget); ActionManager::ActionManager &actionManager = ActionManager::ActionManager::instance(); ActionManager::MenuPath menuPath("Window"); actionManager.registerAction(menuPath, dockWidget->toggleViewAction()); // // Create log file and register handler for qDebug() messages // QDir path; #if QT_VERSION >= 0x050000 path.setPath(QStandardPaths::writableLocation(QStandardPaths::DataLocation)); #else path.setPath(QDesktopServices::storageLocation(QDesktopServices::DataLocation)); #endif // Create the logfile path if need be if(!path.exists()) { if(!path.mkpath(path.path())) { qCritical() << tr("Unable to create path for log files at: \"%1\"").arg(path.path()); return false; } } // Set the logfile name d->m_LogFile.setFileName(QString("%1/%2.txt") .arg(path.path()) .arg(QDateTime::currentDateTime().toUTC().toString(QString("yyyyMMddhhmmsszzz")))); // Register with the debugging system #if QT_VERSION >= 0x050000 qInstallMessageHandler(d->qMessageHandler); #else qInstallMsgHandler(d->qMessageHandler); #endif Core::PluginManager::PluginManager::instance().addObject(this); } catch(...) { return false; } return d->m_Initialized = true; } /*! \internal \brief NotificationManager::shutdown */ void NotificationManager::shutdown() { if(!d->m_Initialized) { return; } #if QT_VERSION >= 0x050000 qInstallMessageHandler(0); #else qInstallMsgHandler(0); #endif if(d->m_LogFile.isOpen()) { d->m_LogFile.close(); } } /*! \fn NotificationManager::writeToLogFile() \brief Writes message to log file \todo better documentation */ void NotificationManager::writeToLogFile(const int &level, QString message) { d->writeToLogFile(level, message); } /*! \fn NotificationManager::notify() \brief Notification of event displayed in CoreWindow If an identical notification already exists, it will be returned. This means that the same NotificationWidget can be returned under different calls to this function. Do not take ownership, or delete the widget manually, it will screw things up! If the same widget is returned, and a timeout has been set, the timer will be restarted. \returns NotificationWidget, which is owned and destroyed by CoreWindow \todo better documentation */ NotificationWidget *NotificationManager::notify(const QString &text, NotificationWidget::Icon icon, NotificationWidget::StandardButtons buttons, const QObject *receiver, const char *member) { return d->notify(text, icon, buttons, receiver, member); } /***** PRIVATE IMPLEMENTATION *****/ NotificationManagerPrivate::NotificationManagerPrivate() : q(NULL), m_Initialized(false), m_StdOut(stdout, QIODevice::WriteOnly), m_StdError(stderr, QIODevice::WriteOnly), m_ConsoleWidget(NULL) { } NotificationManagerPrivate::~NotificationManagerPrivate() { if(m_LogFile.isOpen()) { m_LogFile.close(); } } void NotificationManagerPrivate::writeToLogFile(const int &level, QString message) { if(!m_LogFile.isOpen()) { if(!m_LogFile.open(QIODevice::Append | QIODevice::Text)) { QString logFileFailMsg = tr("Failed to open log file: %1").arg(m_LogFile.fileName()); q->notify(logFileFailMsg, NotificationWidget::Critical); m_StdError << Q_FUNC_INFO << logFileFailMsg; } m_LogFileStream.setDevice(&m_LogFile); } QDateTime currentTime = QDateTime::currentDateTime().toUTC(); QString outputString = QString("%1 - %2") .arg(currentTime.toString("yyyy-MM-dd hh:mm:ss.zzz")) .arg(message); if(m_LogFile.isOpen()) { m_LogFileStream << outputString << endl; } m_ConsoleWidget->messageEvent(level, outputString); m_StdError << outputString << endl; } #if QT_VERSION >= 0x050000 void NotificationManagerPrivate::qMessageHandler(QtMsgType type, const QMessageLogContext &context, const QString &message) #else void NotificationManagerPrivate::qMessageHandler(QtMsgType type, const char *message) #endif { #if QT_VERSION >= 0x050000 Q_UNUSED(context) #endif QString msg; int level = 0; // Static member function requires that we get the singleton pointer directly NotificationManager *q = &NotificationManager::instance(); switch (type) { case QtDebugMsg: msg = q->tr("Debug: %1").arg(message); level = (int)QtDebugMsg; break; case QtWarningMsg: msg = q->tr("Warning: %1").arg(message); level = (int)QtWarningMsg; q->notify(msg, NotificationWidget::Warning)->setTimeoutInterval(10 * 1000); break; case QtCriticalMsg: msg = q->tr("Critical: %1").arg(message); level = (int)QtCriticalMsg; q->notify(msg, NotificationWidget::Critical); break; case QtFatalMsg: msg = q->tr("Fatal: %1").arg(message); level = (int)QtFatalMsg; break; default: msg = q->tr("Unknown: %1").arg(message); break; } q->writeToLogFile(level, msg); if(type == QtFatalMsg) { abort(); } } void NotificationManagerPrivate::removeNotificationWidget() { if(NotificationWidget *nw = qobject_cast<NotificationWidget *>(sender())) { m_NotificationWidgets.removeAll(nw); } } NotificationWidget *NotificationManagerPrivate::notify(const QString &text, NotificationWidget::Icon icon, NotificationWidget::StandardButtons buttons, const QObject *receiver, const char *member) { CoreWindow::CoreWindow &coreWindow = CoreWindow::CoreWindow::instance(); foreach(NotificationWidget *nw, m_NotificationWidgets) { if( nw->text().compare(text, Qt::CaseInsensitive) == 0 && nw->icon() == icon && nw->standardButtons() == buttons ) { if(nw->timeoutInterval() > 0) { // Reset the timer if necessary nw->setTimeoutInterval(nw->timeoutInterval()); } if(receiver && member) { connect(nw, SIGNAL(buttonClicked(NotificationWidget::StandardButton)), receiver, member); } return nw; } } NotificationWidget *notificationWidget = new NotificationWidget(text, icon, buttons, receiver, member, &coreWindow); m_NotificationWidgets.append(notificationWidget); connect(notificationWidget, SIGNAL(closing()), this, SLOT(removeNotificationWidget())); connect(notificationWidget, SIGNAL(destroyed()), this, SLOT(removeNotificationWidget())); coreWindow.addNotificationWidget(notificationWidget); notificationWidget->setFocus(); return notificationWidget; } } // namespace NotificationManager } // namespace Core <|endoftext|>
<commit_before><commit_msg>Created a unit test to ensure invalidation of gdr_map after fork<commit_after><|endoftext|>
<commit_before><commit_msg>test a greater numeric range for divisions<commit_after><|endoftext|>
<commit_before>/****************************************************************************** This source file is part of the MoleQueue project. Copyright 2011 Kitware, Inc. This source code is released under the New BSD License, (the "License"). Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ******************************************************************************/ #include "mainwindow.h" #include "ui_mainwindow.h" #include "terminalprocess.h" #include "sshcommand.h" #include "ProgramItemModel.h" #include "program.h" #include <QtCore/QProcess> #include <QtCore/QProcessEnvironment> #include <QtCore/QTimer> #include <QtGui/QMessageBox> #include <QtGui/QCloseEvent> #include <QtNetwork/QLocalServer> #include <QtNetwork/QLocalSocket> namespace MoleQueue { MainWindow::MainWindow() : m_removeServer(false) { m_ui = new Ui::MainWindow; m_ui->setupUi(this); createActions(); createMainMenu(); createTrayIcon(); createJobModel(); m_trayIcon->show(); setWindowTitle(tr("MoleQueue")); resize(400, 300); // Start up our local socket server m_server = new QLocalServer(this); if (!m_server->listen("MoleQueue")) { QMessageBox::critical(this, tr("MoleQueue Server"), tr("Unable to start the server: %1.") .arg(m_server->errorString())); //m_server->removeServer("MoleQueue"); m_server->close(); m_removeServer = true; qDebug() << "Creating a client connection..."; // Create a test connection to the other server. QLocalSocket *socket = new QLocalSocket(this); socket->connectToServer("MoleQueue"); connect(socket, SIGNAL(readyRead()), this, SLOT(socketReadyRead())); connect(socket, SIGNAL(error(QLocalSocket::LocalSocketError)), this, SLOT(socketError(QLocalSocket::LocalSocketError))); connect(socket, SIGNAL(connected()), this, SLOT(socketConnected())); QTimer::singleShot(1000, this, SLOT(removeServer())); // close(); return; } else { qDebug() << "Connecting server new connection up..." << m_server->fullServerName(); connect(m_server, SIGNAL(newConnection()), this, SLOT(newConnection())); } } MainWindow::~MainWindow() { delete m_ui; m_ui = 0; } void MainWindow::setVisible(bool visible) { m_minimizeAction->setEnabled(visible); m_maximizeAction->setEnabled(!isMaximized()); m_restoreAction->setEnabled(isMaximized() || !visible); QMainWindow::setVisible(visible); } void MainWindow::closeEvent(QCloseEvent *event) { if (m_trayIcon->isVisible()) { QMessageBox::information(this, tr("Systray"), tr("The program will keep running in the " "system tray. To terminate the program, " "choose <b>Quit</b> in the context menu " "of the system tray entry.")); hide(); event->ignore(); } } void MainWindow::setIcon(int index) { } void MainWindow::iconActivated(QSystemTrayIcon::ActivationReason reason) { } void MainWindow::showMessage() { m_trayIcon->showMessage("Info", "System tray resident queue manager initialized.", QSystemTrayIcon::MessageIcon(0), 5000); } void MainWindow::messageClicked() { QMessageBox::information(0, tr("Systray"), tr("Sorry, I already gave what help I could.\n" "Maybe you should try asking a human?")); createMessageGroupBox(); } void MainWindow::newConnection() { m_trayIcon->showMessage("Info", tr("Client connected to us!"), QSystemTrayIcon::MessageIcon(0), 5000); QLocalSocket *clientSocket = m_server->nextPendingConnection(); if (!clientSocket) { qDebug() << "Erorr, invalid socket."; return; } connect(clientSocket, SIGNAL(disconnected()), clientSocket, SLOT(deleteLater())); clientSocket->write("Hello"); clientSocket->flush(); clientSocket->disconnectFromServer(); // Experimental QProcess for ssh qDebug() << "Calling SSH..."; TerminalProcess ssh; QProcessEnvironment env = QProcessEnvironment::systemEnvironment(); QProcessEnvironment sshEnv; if (env.contains("DISPLAY")) sshEnv.insert("DISPLAY", env.value("DISPLAY")); if (env.contains("EDITOR")) sshEnv.insert("EDITOR", env.value("EDITOR")); if (env.contains("SSH_AUTH_SOCK")) sshEnv.insert("SSH_AUTH_SOCK", env.value("SSH_AUTH_SOCK")); sshEnv.insert("SSH_ASKPASS", "/usr/bin/pinentry-qt4"); ssh.setProcessEnvironment(sshEnv); ssh.setProcessChannelMode(QProcess::MergedChannels); //ssh.start("env"); ssh.start("ssh", QStringList() << "unobtanium");// << "ls"); if (!ssh.waitForStarted()) { qDebug() << "Failed to start SSH..."; return; } ssh.waitForReadyRead(); ssh.write("ls ~/\n"); ssh.waitForBytesWritten(); ssh.waitForReadyRead(); QByteArray res = ssh.readAll(); qDebug() << "ls:" << res; ssh.write("env\nexit\n"); ssh.closeWriteChannel(); if (!ssh.waitForFinished()) { ssh.close(); qDebug() << "Failed to exit."; } QByteArray result = ssh.readAll(); qDebug() << "Output:" << result; } void MainWindow::socketReadyRead() { m_trayIcon->showMessage("Info", tr("Client connected to us!"), QSystemTrayIcon::MessageIcon(0), 5000); qDebug() << "Ready to read..."; m_removeServer = false; } void MainWindow::socketError(QLocalSocket::LocalSocketError socketError) { switch (socketError) { case QLocalSocket::ServerNotFoundError: QMessageBox::information(this, tr("MoleQueue Client"), tr("The pipe was not found. Please check the " "local pipe name.")); break; case QLocalSocket::ConnectionRefusedError: QMessageBox::information(this, tr("MoleQueue Client"), tr("The connection was refused by the server. " "Make sure the MoleQueue server is running, " "and check that the local pipe name " "is correct.")); break; case QLocalSocket::PeerClosedError: break; default: QMessageBox::information(this, tr("MoleQueue Client"), tr("The following error occurred: .")); //.arg(socket->errorString())); } qDebug() << "Hit the soccket error!"; } void MainWindow::socketConnected() { qDebug() << "Socket connected..."; m_removeServer = false; } void MainWindow::removeServer() { if (m_removeServer) { qDebug() << "Removing the server, as it looks like there was a timeout."; m_server->removeServer("MoleQueue"); } else { qDebug() << "Server not removed, client received response."; } } void MainWindow::moveFile() { qDebug() << "Calling SSH..."; TerminalProcess ssh; QProcessEnvironment env = QProcessEnvironment::systemEnvironment(); QProcessEnvironment sshEnv; if (env.contains("DISPLAY")) sshEnv.insert("DISPLAY", env.value("DISPLAY")); if (env.contains("EDITOR")) sshEnv.insert("EDITOR", env.value("EDITOR")); if (env.contains("SSH_AUTH_SOCK")) sshEnv.insert("SSH_AUTH_SOCK", env.value("SSH_AUTH_SOCK")); sshEnv.insert("SSH_ASKPASS", "/usr/bin/pinentry-qt4"); ssh.setProcessEnvironment(sshEnv); ssh.setProcessChannelMode(QProcess::MergedChannels); //ssh.start("env"); ssh.start("scp", QStringList() << "MoleQueue.cbp" << "unobtanium:");// << "ls"); if (!ssh.waitForStarted()) { qDebug() << "Failed to start SSH..."; return; } ssh.closeWriteChannel(); if (!ssh.waitForFinished()) { ssh.close(); qDebug() << "Failed to exit."; } QByteArray result = ssh.readAll(); qDebug() << "scp output:" << result << "Return code:" << ssh.exitCode(); SshCommand command(this); command.setHostName("unobtanium"); QString out; int exitCode = -1; bool success = command.execute("ls -la", out, exitCode); success = command.copyTo("MoleQueue.cbp", "MoleQueue666.cbp"); success = command.copyDirTo("bin", "MoleQueueBin"); // Now try copying some files over here! success = command.copyFrom("test.py", "test.py"); success = command.copyDirFrom("src/cml-reader", "cml-reader"); } void MainWindow::createIconGroupBox() { } void MainWindow::createMessageGroupBox() { m_trayIcon->showMessage("Info", "System tray resident queue manager initialized.", QSystemTrayIcon::MessageIcon(0), 15000); } void MainWindow::createActions() { m_minimizeAction = new QAction(tr("Mi&nimize"), this); connect(m_minimizeAction, SIGNAL(triggered()), this, SLOT(hide())); m_maximizeAction = new QAction(tr("Ma&ximize"), this); connect(m_maximizeAction, SIGNAL(triggered()), this, SLOT(showMaximized())); m_restoreAction = new QAction(tr("&Restore"), this); connect(m_restoreAction, SIGNAL(triggered()), this, SLOT(showNormal())); m_quitAction = new QAction(tr("&Quit"), this); connect(m_quitAction, SIGNAL(triggered()), qApp, SLOT(quit())); } void MainWindow::createMainMenu() { QMenu *file = new QMenu(tr("&File"), m_ui->menubar); QAction *test = new QAction(tr("&Test"), this); connect(test, SIGNAL(triggered()), this, SLOT(showMessage())); file->addAction(test); QAction *move = new QAction(tr("&Move"), this); connect(move, SIGNAL(triggered()), this, SLOT(moveFile())); file->addAction(move); file->addAction(m_quitAction); m_ui->menubar->addMenu(file); } void MainWindow::createTrayIcon() { m_trayIconMenu = new QMenu(this); m_trayIconMenu->addAction(m_minimizeAction); m_trayIconMenu->addAction(m_maximizeAction); m_trayIconMenu->addAction(m_restoreAction); m_trayIconMenu->addSeparator(); m_trayIconMenu->addAction(m_quitAction); m_trayIcon = new QSystemTrayIcon(this); m_trayIcon->setContextMenu(m_trayIconMenu); m_icon = new QIcon(":/icons/avogadro.png"); m_trayIcon->setIcon(*m_icon); if (m_trayIcon->supportsMessages()) m_trayIcon->setToolTip("Queue manager..."); else m_trayIcon->setToolTip("Queue manager (no message support)..."); } void MainWindow::createJobModel() { m_jobModel = new ProgramItemModel(&m_jobs, this); m_ui->jobView->setModel(m_jobModel); m_ui->jobView->setAlternatingRowColors(true); m_ui->jobView->setSelectionBehavior(QAbstractItemView::SelectRows); m_ui->jobView->setRootIsDecorated(false); m_ui->jobView->header()->setStretchLastSection(false); m_ui->jobView->header()->setResizeMode(0, QHeaderView::Stretch); //m_ui->jobView->header()->setResizeMode(0, QHeaderView::Stretch); Program *job = new Program; job->setName("Test job..."); m_jobModel->add(job); job = new Program; job->setName("My GAMESS job..."); m_jobModel->add(job); } } // End namespace <commit_msg>Switch to use a binary data stream.<commit_after>/****************************************************************************** This source file is part of the MoleQueue project. Copyright 2011 Kitware, Inc. This source code is released under the New BSD License, (the "License"). Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ******************************************************************************/ #include "mainwindow.h" #include "ui_mainwindow.h" #include "terminalprocess.h" #include "sshcommand.h" #include "ProgramItemModel.h" #include "program.h" #include <QtCore/QProcess> #include <QtCore/QProcessEnvironment> #include <QtCore/QTimer> #include <QtCore/QDataStream> #include <QtGui/QMessageBox> #include <QtGui/QCloseEvent> #include <QtNetwork/QLocalServer> #include <QtNetwork/QLocalSocket> namespace MoleQueue { MainWindow::MainWindow() : m_removeServer(false) { m_ui = new Ui::MainWindow; m_ui->setupUi(this); createActions(); createMainMenu(); createTrayIcon(); createJobModel(); m_trayIcon->show(); setWindowTitle(tr("MoleQueue")); resize(400, 300); // Start up our local socket server m_server = new QLocalServer(this); if (!m_server->listen("MoleQueue")) { QMessageBox::critical(this, tr("MoleQueue Server"), tr("Unable to start the server: %1.") .arg(m_server->errorString())); //m_server->removeServer("MoleQueue"); m_server->close(); m_removeServer = true; qDebug() << "Creating a client connection..."; // Create a test connection to the other server. QLocalSocket *socket = new QLocalSocket(this); socket->connectToServer("MoleQueue"); connect(socket, SIGNAL(readyRead()), this, SLOT(socketReadyRead())); connect(socket, SIGNAL(error(QLocalSocket::LocalSocketError)), this, SLOT(socketError(QLocalSocket::LocalSocketError))); connect(socket, SIGNAL(connected()), this, SLOT(socketConnected())); QTimer::singleShot(1000, this, SLOT(removeServer())); // close(); return; } else { qDebug() << "Connecting server new connection up..." << m_server->fullServerName(); connect(m_server, SIGNAL(newConnection()), this, SLOT(newConnection())); } } MainWindow::~MainWindow() { delete m_ui; m_ui = 0; } void MainWindow::setVisible(bool visible) { m_minimizeAction->setEnabled(visible); m_maximizeAction->setEnabled(!isMaximized()); m_restoreAction->setEnabled(isMaximized() || !visible); QMainWindow::setVisible(visible); } void MainWindow::closeEvent(QCloseEvent *event) { if (m_trayIcon->isVisible()) { QMessageBox::information(this, tr("Systray"), tr("The program will keep running in the " "system tray. To terminate the program, " "choose <b>Quit</b> in the context menu " "of the system tray entry.")); hide(); event->ignore(); } } void MainWindow::setIcon(int index) { } void MainWindow::iconActivated(QSystemTrayIcon::ActivationReason reason) { } void MainWindow::showMessage() { m_trayIcon->showMessage("Info", "System tray resident queue manager initialized.", QSystemTrayIcon::MessageIcon(0), 5000); } void MainWindow::messageClicked() { QMessageBox::information(0, tr("Systray"), tr("Sorry, I already gave what help I could.\n" "Maybe you should try asking a human?")); createMessageGroupBox(); } void MainWindow::newConnection() { m_trayIcon->showMessage("Info", tr("Client connected to us!"), QSystemTrayIcon::MessageIcon(0), 5000); QLocalSocket *clientSocket = m_server->nextPendingConnection(); if (!clientSocket) { qDebug() << "Erorr, invalid socket."; return; } connect(clientSocket, SIGNAL(disconnected()), clientSocket, SLOT(deleteLater())); QByteArray block; QDataStream out(&block, QIODevice::WriteOnly); out.setVersion(QDataStream::Qt_4_7); out << static_cast<quint16>(0); out << QString("Hello from the server..."); QList<QString> list; list << "GAMESS" << "MOPAC"; out << list; out.device()->seek(0); out << static_cast<quint16>(block.size() - sizeof(quint16)); qDebug() << "size:" << block.size() << sizeof(quint16) << "message:" << block; clientSocket->write(block); clientSocket->flush(); clientSocket->disconnectFromServer(); // Experimental QProcess for ssh qDebug() << "Calling SSH..."; TerminalProcess ssh; QProcessEnvironment env = QProcessEnvironment::systemEnvironment(); QProcessEnvironment sshEnv; if (env.contains("DISPLAY")) sshEnv.insert("DISPLAY", env.value("DISPLAY")); if (env.contains("EDITOR")) sshEnv.insert("EDITOR", env.value("EDITOR")); if (env.contains("SSH_AUTH_SOCK")) sshEnv.insert("SSH_AUTH_SOCK", env.value("SSH_AUTH_SOCK")); sshEnv.insert("SSH_ASKPASS", "/usr/bin/pinentry-qt4"); ssh.setProcessEnvironment(sshEnv); ssh.setProcessChannelMode(QProcess::MergedChannels); //ssh.start("env"); ssh.start("ssh", QStringList() << "unobtanium");// << "ls"); if (!ssh.waitForStarted()) { qDebug() << "Failed to start SSH..."; return; } ssh.waitForReadyRead(); ssh.write("ls ~/\n"); ssh.waitForBytesWritten(); ssh.waitForReadyRead(); QByteArray res = ssh.readAll(); qDebug() << "ls:" << res; ssh.write("env\nexit\n"); ssh.closeWriteChannel(); if (!ssh.waitForFinished()) { ssh.close(); qDebug() << "Failed to exit."; } QByteArray result = ssh.readAll(); qDebug() << "Output:" << result; } void MainWindow::socketReadyRead() { m_trayIcon->showMessage("Info", tr("Client connected to us!"), QSystemTrayIcon::MessageIcon(0), 5000); qDebug() << "Ready to read..."; m_removeServer = false; } void MainWindow::socketError(QLocalSocket::LocalSocketError socketError) { switch (socketError) { case QLocalSocket::ServerNotFoundError: QMessageBox::information(this, tr("MoleQueue Client"), tr("The pipe was not found. Please check the " "local pipe name.")); break; case QLocalSocket::ConnectionRefusedError: QMessageBox::information(this, tr("MoleQueue Client"), tr("The connection was refused by the server. " "Make sure the MoleQueue server is running, " "and check that the local pipe name " "is correct.")); break; case QLocalSocket::PeerClosedError: break; default: QMessageBox::information(this, tr("MoleQueue Client"), tr("The following error occurred: .")); //.arg(socket->errorString())); } qDebug() << "Hit the soccket error!"; } void MainWindow::socketConnected() { qDebug() << "Socket connected..."; m_removeServer = false; } void MainWindow::removeServer() { if (m_removeServer) { qDebug() << "Removing the server, as it looks like there was a timeout."; m_server->removeServer("MoleQueue"); } else { qDebug() << "Server not removed, client received response."; } } void MainWindow::moveFile() { qDebug() << "Calling SSH..."; TerminalProcess ssh; QProcessEnvironment env = QProcessEnvironment::systemEnvironment(); QProcessEnvironment sshEnv; if (env.contains("DISPLAY")) sshEnv.insert("DISPLAY", env.value("DISPLAY")); if (env.contains("EDITOR")) sshEnv.insert("EDITOR", env.value("EDITOR")); if (env.contains("SSH_AUTH_SOCK")) sshEnv.insert("SSH_AUTH_SOCK", env.value("SSH_AUTH_SOCK")); sshEnv.insert("SSH_ASKPASS", "/usr/bin/pinentry-qt4"); ssh.setProcessEnvironment(sshEnv); ssh.setProcessChannelMode(QProcess::MergedChannels); //ssh.start("env"); ssh.start("scp", QStringList() << "MoleQueue.cbp" << "unobtanium:");// << "ls"); if (!ssh.waitForStarted()) { qDebug() << "Failed to start SSH..."; return; } ssh.closeWriteChannel(); if (!ssh.waitForFinished()) { ssh.close(); qDebug() << "Failed to exit."; } QByteArray result = ssh.readAll(); qDebug() << "scp output:" << result << "Return code:" << ssh.exitCode(); SshCommand command(this); command.setHostName("unobtanium"); QString out; int exitCode = -1; bool success = command.execute("ls -la", out, exitCode); success = command.copyTo("MoleQueue.cbp", "MoleQueue666.cbp"); success = command.copyDirTo("bin", "MoleQueueBin"); // Now try copying some files over here! success = command.copyFrom("test.py", "test.py"); success = command.copyDirFrom("src/cml-reader", "cml-reader"); } void MainWindow::createIconGroupBox() { } void MainWindow::createMessageGroupBox() { m_trayIcon->showMessage("Info", "System tray resident queue manager initialized.", QSystemTrayIcon::MessageIcon(0), 15000); } void MainWindow::createActions() { m_minimizeAction = new QAction(tr("Mi&nimize"), this); connect(m_minimizeAction, SIGNAL(triggered()), this, SLOT(hide())); m_maximizeAction = new QAction(tr("Ma&ximize"), this); connect(m_maximizeAction, SIGNAL(triggered()), this, SLOT(showMaximized())); m_restoreAction = new QAction(tr("&Restore"), this); connect(m_restoreAction, SIGNAL(triggered()), this, SLOT(showNormal())); m_quitAction = new QAction(tr("&Quit"), this); connect(m_quitAction, SIGNAL(triggered()), qApp, SLOT(quit())); } void MainWindow::createMainMenu() { QMenu *file = new QMenu(tr("&File"), m_ui->menubar); QAction *test = new QAction(tr("&Test"), this); connect(test, SIGNAL(triggered()), this, SLOT(showMessage())); file->addAction(test); QAction *move = new QAction(tr("&Move"), this); connect(move, SIGNAL(triggered()), this, SLOT(moveFile())); file->addAction(move); file->addAction(m_quitAction); m_ui->menubar->addMenu(file); } void MainWindow::createTrayIcon() { m_trayIconMenu = new QMenu(this); m_trayIconMenu->addAction(m_minimizeAction); m_trayIconMenu->addAction(m_maximizeAction); m_trayIconMenu->addAction(m_restoreAction); m_trayIconMenu->addSeparator(); m_trayIconMenu->addAction(m_quitAction); m_trayIcon = new QSystemTrayIcon(this); m_trayIcon->setContextMenu(m_trayIconMenu); m_icon = new QIcon(":/icons/avogadro.png"); m_trayIcon->setIcon(*m_icon); if (m_trayIcon->supportsMessages()) m_trayIcon->setToolTip("Queue manager..."); else m_trayIcon->setToolTip("Queue manager (no message support)..."); } void MainWindow::createJobModel() { m_jobModel = new ProgramItemModel(&m_jobs, this); m_ui->jobView->setModel(m_jobModel); m_ui->jobView->setAlternatingRowColors(true); m_ui->jobView->setSelectionBehavior(QAbstractItemView::SelectRows); m_ui->jobView->setRootIsDecorated(false); m_ui->jobView->header()->setStretchLastSection(false); m_ui->jobView->header()->setResizeMode(0, QHeaderView::Stretch); //m_ui->jobView->header()->setResizeMode(0, QHeaderView::Stretch); Program *job = new Program; job->setName("Test job..."); m_jobModel->add(job); job = new Program; job->setName("My GAMESS job..."); m_jobModel->add(job); } } // End namespace <|endoftext|>
<commit_before>/* * Copyright 2014 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkTypes.h" #if defined(SK_BUILD_FOR_ANDROID) #include "gl/GrGLInterface.h" #include "gl/GrGLAssembleInterface.h" #include "gl/GrGLUtil.h" #include <EGL/egl.h> #include <GLES2/gl2.h> static GrGLFuncPtr android_get_gl_proc(void* ctx, const char name[]) { SkASSERT(nullptr == ctx); // Some older drivers on Android have busted eglGetProcAdddress Functions that // will return the wrong pointer for built in GLES2 functions. This set of functions // was generated on a Xoom by finding mismatches between the function pulled in via gl2.h and // the address returned by eglGetProcAddress. if (0 == strcmp("glActiveTexture", name)) { return (GrGLFuncPtr) glActiveTexture; } else if (0 == strcmp("glAttachShader", name)) { return (GrGLFuncPtr) glAttachShader; } else if (0 == strcmp("glBindAttribLocation", name)) { return (GrGLFuncPtr) glBindAttribLocation; } else if (0 == strcmp("glBindBuffer", name)) { return (GrGLFuncPtr) glBindBuffer; } else if (0 == strcmp("glBindTexture", name)) { return (GrGLFuncPtr) glBindTexture; } else if (0 == strcmp("glBlendColor", name)) { return (GrGLFuncPtr) glBlendColor; } else if (0 == strcmp("glBlendEquation", name)) { return (GrGLFuncPtr) glBlendEquation; } else if (0 == strcmp("glBlendFunc", name)) { return (GrGLFuncPtr) glBlendFunc; } else if (0 == strcmp("glBufferData", name)) { return (GrGLFuncPtr) glBufferData; } else if (0 == strcmp("glBufferSubData", name)) { return (GrGLFuncPtr) glBufferSubData; } else if (0 == strcmp("glClear", name)) { return (GrGLFuncPtr) glClear; } else if (0 == strcmp("glClearColor", name)) { return (GrGLFuncPtr) glClearColor; } else if (0 == strcmp("glClearStencil", name)) { return (GrGLFuncPtr) glClearStencil; } else if (0 == strcmp("glColorMask", name)) { return (GrGLFuncPtr) glColorMask; } else if (0 == strcmp("glCompileShader", name)) { return (GrGLFuncPtr) glCompileShader; } else if (0 == strcmp("glCompressedTexImage2D", name)) { return (GrGLFuncPtr) glCompressedTexImage2D; } else if (0 == strcmp("glCompressedTexSubImage2D", name)) { return (GrGLFuncPtr) glCompressedTexSubImage2D; } else if (0 == strcmp("glCopyTexSubImage2D", name)) { return (GrGLFuncPtr) glCopyTexSubImage2D; } else if (0 == strcmp("glCreateProgram", name)) { return (GrGLFuncPtr) glCreateProgram; } else if (0 == strcmp("glCreateShader", name)) { return (GrGLFuncPtr) glCreateShader; } else if (0 == strcmp("glCullFace", name)) { return (GrGLFuncPtr) glCullFace; } else if (0 == strcmp("glDeleteBuffers", name)) { return (GrGLFuncPtr) glDeleteBuffers; } else if (0 == strcmp("glDeleteProgram", name)) { return (GrGLFuncPtr) glDeleteProgram; } else if (0 == strcmp("glDeleteShader", name)) { return (GrGLFuncPtr) glDeleteShader; } else if (0 == strcmp("glDeleteTextures", name)) { return (GrGLFuncPtr) glDeleteTextures; } else if (0 == strcmp("glDepthMask", name)) { return (GrGLFuncPtr) glDepthMask; } else if (0 == strcmp("glDisable", name)) { return (GrGLFuncPtr) glDisable; } else if (0 == strcmp("glDisableVertexAttribArray", name)) { return (GrGLFuncPtr) glDisableVertexAttribArray; } else if (0 == strcmp("glDrawArrays", name)) { return (GrGLFuncPtr) glDrawArrays; } else if (0 == strcmp("glDrawElements", name)) { return (GrGLFuncPtr) glDrawElements; } else if (0 == strcmp("glEnable", name)) { return (GrGLFuncPtr) glEnable; } else if (0 == strcmp("glEnableVertexAttribArray", name)) { return (GrGLFuncPtr) glEnableVertexAttribArray; } else if (0 == strcmp("glFinish", name)) { return (GrGLFuncPtr) glFinish; } else if (0 == strcmp("glFlush", name)) { return (GrGLFuncPtr) glFlush; } else if (0 == strcmp("glFrontFace", name)) { return (GrGLFuncPtr) glFrontFace; } else if (0 == strcmp("glGenBuffers", name)) { return (GrGLFuncPtr) glGenBuffers; } else if (0 == strcmp("glGenerateMipmap", name)) { return (GrGLFuncPtr) glGenerateMipmap; } else if (0 == strcmp("glGenTextures", name)) { return (GrGLFuncPtr) glGenTextures; } else if (0 == strcmp("glGetBufferParameteriv", name)) { return (GrGLFuncPtr) glGetBufferParameteriv; } else if (0 == strcmp("glGetError", name)) { return (GrGLFuncPtr) glGetError; } else if (0 == strcmp("glGetIntegerv", name)) { return (GrGLFuncPtr) glGetIntegerv; } else if (0 == strcmp("glGetProgramInfoLog", name)) { return (GrGLFuncPtr) glGetProgramInfoLog; } else if (0 == strcmp("glGetProgramiv", name)) { return (GrGLFuncPtr) glGetProgramiv; } else if (0 == strcmp("glGetShaderInfoLog", name)) { return (GrGLFuncPtr) glGetShaderInfoLog; } else if (0 == strcmp("glGetShaderiv", name)) { return (GrGLFuncPtr) glGetShaderiv; } else if (0 == strcmp("glGetString", name)) { return (GrGLFuncPtr) glGetString; } else if (0 == strcmp("glGetUniformLocation", name)) { return (GrGLFuncPtr) glGetUniformLocation; } else if (0 == strcmp("glLineWidth", name)) { return (GrGLFuncPtr) glLineWidth; } else if (0 == strcmp("glLinkProgram", name)) { return (GrGLFuncPtr) glLinkProgram; } else if (0 == strcmp("glPixelStorei", name)) { return (GrGLFuncPtr) glPixelStorei; } else if (0 == strcmp("glReadPixels", name)) { return (GrGLFuncPtr) glReadPixels; } else if (0 == strcmp("glScissor", name)) { return (GrGLFuncPtr) glScissor; } else if (0 == strcmp("glShaderSource", name)) { return (GrGLFuncPtr) glShaderSource; } else if (0 == strcmp("glStencilFunc", name)) { return (GrGLFuncPtr) glStencilFunc; } else if (0 == strcmp("glStencilFuncSeparate", name)) { return (GrGLFuncPtr) glStencilFuncSeparate; } else if (0 == strcmp("glStencilMask", name)) { return (GrGLFuncPtr) glStencilMask; } else if (0 == strcmp("glStencilMaskSeparate", name)) { return (GrGLFuncPtr) glStencilMaskSeparate; } else if (0 == strcmp("glStencilOp", name)) { return (GrGLFuncPtr) glStencilOp; } else if (0 == strcmp("glStencilOpSeparate", name)) { return (GrGLFuncPtr) glStencilOpSeparate; } else if (0 == strcmp("glTexImage2D", name)) { return (GrGLFuncPtr) glTexImage2D; } else if (0 == strcmp("glTexParameteri", name)) { return (GrGLFuncPtr) glTexParameteri; } else if (0 == strcmp("glTexParameteriv", name)) { return (GrGLFuncPtr) glTexParameteriv; } else if (0 == strcmp("glTexSubImage2D", name)) { return (GrGLFuncPtr) glTexSubImage2D; } else if (0 == strcmp("glUniform1f", name)) { return (GrGLFuncPtr) glUniform1f; } else if (0 == strcmp("glUniform1i", name)) { return (GrGLFuncPtr) glUniform1i; } else if (0 == strcmp("glUniform1fv", name)) { return (GrGLFuncPtr) glUniform1fv; } else if (0 == strcmp("glUniform1iv", name)) { return (GrGLFuncPtr) glUniform1iv; } else if (0 == strcmp("glUniform2f", name)) { return (GrGLFuncPtr) glUniform2f; } else if (0 == strcmp("glUniform2i", name)) { return (GrGLFuncPtr) glUniform2i; } else if (0 == strcmp("glUniform2fv", name)) { return (GrGLFuncPtr) glUniform2fv; } else if (0 == strcmp("glUniform2iv", name)) { return (GrGLFuncPtr) glUniform2iv; } else if (0 == strcmp("glUniform3f", name)) { return (GrGLFuncPtr) glUniform3f; } else if (0 == strcmp("glUniform3i", name)) { return (GrGLFuncPtr) glUniform3i; } else if (0 == strcmp("glUniform3fv", name)) { return (GrGLFuncPtr) glUniform3fv; } else if (0 == strcmp("glUniform3iv", name)) { return (GrGLFuncPtr) glUniform3iv; } else if (0 == strcmp("glUniform4f", name)) { return (GrGLFuncPtr) glUniform4f; } else if (0 == strcmp("glUniform4i", name)) { return (GrGLFuncPtr) glUniform4i; } else if (0 == strcmp("glUniform4fv", name)) { return (GrGLFuncPtr) glUniform4fv; } else if (0 == strcmp("glUniform4iv", name)) { return (GrGLFuncPtr) glUniform4iv; } else if (0 == strcmp("glUniformMatrix2fv", name)) { return (GrGLFuncPtr) glUniformMatrix2fv; } else if (0 == strcmp("glUniformMatrix3fv", name)) { return (GrGLFuncPtr) glUniformMatrix3fv; } else if (0 == strcmp("glUniformMatrix4fv", name)) { return (GrGLFuncPtr) glUniformMatrix4fv; } else if (0 == strcmp("glUseProgram", name)) { return (GrGLFuncPtr) glUseProgram; } else if (0 == strcmp("glVertexAttrib1f", name)) { return (GrGLFuncPtr) glVertexAttrib1f; } else if (0 == strcmp("glVertexAttrib2fv", name)) { return (GrGLFuncPtr) glVertexAttrib2fv; } else if (0 == strcmp("glVertexAttrib3fv", name)) { return (GrGLFuncPtr) glVertexAttrib3fv; } else if (0 == strcmp("glVertexAttrib4fv", name)) { return (GrGLFuncPtr) glVertexAttrib4fv; } else if (0 == strcmp("glVertexAttribPointer", name)) { return (GrGLFuncPtr) glVertexAttribPointer; } else if (0 == strcmp("glViewport", name)) { return (GrGLFuncPtr) glViewport; } else if (0 == strcmp("glBindFramebuffer", name)) { return (GrGLFuncPtr) glBindFramebuffer; } else if (0 == strcmp("glBindRenderbuffer", name)) { return (GrGLFuncPtr) glBindRenderbuffer; } else if (0 == strcmp("glCheckFramebufferStatus", name)) { return (GrGLFuncPtr) glCheckFramebufferStatus; } else if (0 == strcmp("glDeleteFramebuffers", name)) { return (GrGLFuncPtr) glDeleteFramebuffers; } else if (0 == strcmp("glDeleteRenderbuffers", name)) { return (GrGLFuncPtr) glDeleteRenderbuffers; } else if (0 == strcmp("glFramebufferRenderbuffer", name)) { return (GrGLFuncPtr) glFramebufferRenderbuffer; } else if (0 == strcmp("glFramebufferTexture2D", name)) { return (GrGLFuncPtr) glFramebufferTexture2D; } else if (0 == strcmp("glGenFramebuffers", name)) { return (GrGLFuncPtr) glGenFramebuffers; } else if (0 == strcmp("glGenRenderbuffers", name)) { return (GrGLFuncPtr) glGenRenderbuffers; } else if (0 == strcmp("glGetFramebufferAttachmentParameteriv", name)) { return (GrGLFuncPtr) glGetFramebufferAttachmentParameteriv; } else if (0 == strcmp("glGetRenderbufferParameteriv", name)) { return (GrGLFuncPtr) glGetRenderbufferParameteriv; } else if (0 == strcmp("glRenderbufferStorage", name)) { return (GrGLFuncPtr) glRenderbufferStorage; } else if (0 == strcmp("eglQueryString", name)) { return (GrGLFuncPtr) eglQueryString; } else if (0 == strcmp("eglGetCurrentDisplay", name)) { return (GrGLFuncPtr) eglGetCurrentDisplay; } return eglGetProcAddress(name); } const GrGLInterface* GrGLCreateNativeInterface() { return GrGLAssembleInterface(nullptr, android_get_gl_proc); } #endif//defined(SK_BUILD_FOR_ANDROID) <commit_msg>use statically linked glGetShaderPrecisionFormat on Android<commit_after>/* * Copyright 2014 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkTypes.h" #if defined(SK_BUILD_FOR_ANDROID) #include "gl/GrGLInterface.h" #include "gl/GrGLAssembleInterface.h" #include "gl/GrGLUtil.h" #include <EGL/egl.h> #include <GLES2/gl2.h> static GrGLFuncPtr android_get_gl_proc(void* ctx, const char name[]) { SkASSERT(nullptr == ctx); // Some older drivers on Android have busted eglGetProcAdddress Functions that // will return the wrong pointer for built in GLES2 functions. This set of functions // was generated on a Xoom by finding mismatches between the function pulled in via gl2.h and // the address returned by eglGetProcAddress. if (0 == strcmp("glActiveTexture", name)) { return (GrGLFuncPtr) glActiveTexture; } else if (0 == strcmp("glAttachShader", name)) { return (GrGLFuncPtr) glAttachShader; } else if (0 == strcmp("glBindAttribLocation", name)) { return (GrGLFuncPtr) glBindAttribLocation; } else if (0 == strcmp("glBindBuffer", name)) { return (GrGLFuncPtr) glBindBuffer; } else if (0 == strcmp("glBindTexture", name)) { return (GrGLFuncPtr) glBindTexture; } else if (0 == strcmp("glBlendColor", name)) { return (GrGLFuncPtr) glBlendColor; } else if (0 == strcmp("glBlendEquation", name)) { return (GrGLFuncPtr) glBlendEquation; } else if (0 == strcmp("glBlendFunc", name)) { return (GrGLFuncPtr) glBlendFunc; } else if (0 == strcmp("glBufferData", name)) { return (GrGLFuncPtr) glBufferData; } else if (0 == strcmp("glBufferSubData", name)) { return (GrGLFuncPtr) glBufferSubData; } else if (0 == strcmp("glClear", name)) { return (GrGLFuncPtr) glClear; } else if (0 == strcmp("glClearColor", name)) { return (GrGLFuncPtr) glClearColor; } else if (0 == strcmp("glClearStencil", name)) { return (GrGLFuncPtr) glClearStencil; } else if (0 == strcmp("glColorMask", name)) { return (GrGLFuncPtr) glColorMask; } else if (0 == strcmp("glCompileShader", name)) { return (GrGLFuncPtr) glCompileShader; } else if (0 == strcmp("glCompressedTexImage2D", name)) { return (GrGLFuncPtr) glCompressedTexImage2D; } else if (0 == strcmp("glCompressedTexSubImage2D", name)) { return (GrGLFuncPtr) glCompressedTexSubImage2D; } else if (0 == strcmp("glCopyTexSubImage2D", name)) { return (GrGLFuncPtr) glCopyTexSubImage2D; } else if (0 == strcmp("glCreateProgram", name)) { return (GrGLFuncPtr) glCreateProgram; } else if (0 == strcmp("glCreateShader", name)) { return (GrGLFuncPtr) glCreateShader; } else if (0 == strcmp("glCullFace", name)) { return (GrGLFuncPtr) glCullFace; } else if (0 == strcmp("glDeleteBuffers", name)) { return (GrGLFuncPtr) glDeleteBuffers; } else if (0 == strcmp("glDeleteProgram", name)) { return (GrGLFuncPtr) glDeleteProgram; } else if (0 == strcmp("glDeleteShader", name)) { return (GrGLFuncPtr) glDeleteShader; } else if (0 == strcmp("glDeleteTextures", name)) { return (GrGLFuncPtr) glDeleteTextures; } else if (0 == strcmp("glDepthMask", name)) { return (GrGLFuncPtr) glDepthMask; } else if (0 == strcmp("glDisable", name)) { return (GrGLFuncPtr) glDisable; } else if (0 == strcmp("glDisableVertexAttribArray", name)) { return (GrGLFuncPtr) glDisableVertexAttribArray; } else if (0 == strcmp("glDrawArrays", name)) { return (GrGLFuncPtr) glDrawArrays; } else if (0 == strcmp("glDrawElements", name)) { return (GrGLFuncPtr) glDrawElements; } else if (0 == strcmp("glEnable", name)) { return (GrGLFuncPtr) glEnable; } else if (0 == strcmp("glEnableVertexAttribArray", name)) { return (GrGLFuncPtr) glEnableVertexAttribArray; } else if (0 == strcmp("glFinish", name)) { return (GrGLFuncPtr) glFinish; } else if (0 == strcmp("glFlush", name)) { return (GrGLFuncPtr) glFlush; } else if (0 == strcmp("glFrontFace", name)) { return (GrGLFuncPtr) glFrontFace; } else if (0 == strcmp("glGenBuffers", name)) { return (GrGLFuncPtr) glGenBuffers; } else if (0 == strcmp("glGenerateMipmap", name)) { return (GrGLFuncPtr) glGenerateMipmap; } else if (0 == strcmp("glGenTextures", name)) { return (GrGLFuncPtr) glGenTextures; } else if (0 == strcmp("glGetBufferParameteriv", name)) { return (GrGLFuncPtr) glGetBufferParameteriv; } else if (0 == strcmp("glGetError", name)) { return (GrGLFuncPtr) glGetError; } else if (0 == strcmp("glGetIntegerv", name)) { return (GrGLFuncPtr) glGetIntegerv; } else if (0 == strcmp("glGetProgramInfoLog", name)) { return (GrGLFuncPtr) glGetProgramInfoLog; } else if (0 == strcmp("glGetProgramiv", name)) { return (GrGLFuncPtr) glGetProgramiv; } else if (0 == strcmp("glGetShaderInfoLog", name)) { return (GrGLFuncPtr) glGetShaderInfoLog; } else if (0 == strcmp("glGetShaderiv", name)) { return (GrGLFuncPtr) glGetShaderiv; } else if (0 == strcmp("glGetShaderPrecisionFormat", name)) { return (GrGLFuncPtr) glGetShaderPrecisionFormat; } else if (0 == strcmp("glGetString", name)) { return (GrGLFuncPtr) glGetString; } else if (0 == strcmp("glGetUniformLocation", name)) { return (GrGLFuncPtr) glGetUniformLocation; } else if (0 == strcmp("glLineWidth", name)) { return (GrGLFuncPtr) glLineWidth; } else if (0 == strcmp("glLinkProgram", name)) { return (GrGLFuncPtr) glLinkProgram; } else if (0 == strcmp("glPixelStorei", name)) { return (GrGLFuncPtr) glPixelStorei; } else if (0 == strcmp("glReadPixels", name)) { return (GrGLFuncPtr) glReadPixels; } else if (0 == strcmp("glScissor", name)) { return (GrGLFuncPtr) glScissor; } else if (0 == strcmp("glShaderSource", name)) { return (GrGLFuncPtr) glShaderSource; } else if (0 == strcmp("glStencilFunc", name)) { return (GrGLFuncPtr) glStencilFunc; } else if (0 == strcmp("glStencilFuncSeparate", name)) { return (GrGLFuncPtr) glStencilFuncSeparate; } else if (0 == strcmp("glStencilMask", name)) { return (GrGLFuncPtr) glStencilMask; } else if (0 == strcmp("glStencilMaskSeparate", name)) { return (GrGLFuncPtr) glStencilMaskSeparate; } else if (0 == strcmp("glStencilOp", name)) { return (GrGLFuncPtr) glStencilOp; } else if (0 == strcmp("glStencilOpSeparate", name)) { return (GrGLFuncPtr) glStencilOpSeparate; } else if (0 == strcmp("glTexImage2D", name)) { return (GrGLFuncPtr) glTexImage2D; } else if (0 == strcmp("glTexParameteri", name)) { return (GrGLFuncPtr) glTexParameteri; } else if (0 == strcmp("glTexParameteriv", name)) { return (GrGLFuncPtr) glTexParameteriv; } else if (0 == strcmp("glTexSubImage2D", name)) { return (GrGLFuncPtr) glTexSubImage2D; } else if (0 == strcmp("glUniform1f", name)) { return (GrGLFuncPtr) glUniform1f; } else if (0 == strcmp("glUniform1i", name)) { return (GrGLFuncPtr) glUniform1i; } else if (0 == strcmp("glUniform1fv", name)) { return (GrGLFuncPtr) glUniform1fv; } else if (0 == strcmp("glUniform1iv", name)) { return (GrGLFuncPtr) glUniform1iv; } else if (0 == strcmp("glUniform2f", name)) { return (GrGLFuncPtr) glUniform2f; } else if (0 == strcmp("glUniform2i", name)) { return (GrGLFuncPtr) glUniform2i; } else if (0 == strcmp("glUniform2fv", name)) { return (GrGLFuncPtr) glUniform2fv; } else if (0 == strcmp("glUniform2iv", name)) { return (GrGLFuncPtr) glUniform2iv; } else if (0 == strcmp("glUniform3f", name)) { return (GrGLFuncPtr) glUniform3f; } else if (0 == strcmp("glUniform3i", name)) { return (GrGLFuncPtr) glUniform3i; } else if (0 == strcmp("glUniform3fv", name)) { return (GrGLFuncPtr) glUniform3fv; } else if (0 == strcmp("glUniform3iv", name)) { return (GrGLFuncPtr) glUniform3iv; } else if (0 == strcmp("glUniform4f", name)) { return (GrGLFuncPtr) glUniform4f; } else if (0 == strcmp("glUniform4i", name)) { return (GrGLFuncPtr) glUniform4i; } else if (0 == strcmp("glUniform4fv", name)) { return (GrGLFuncPtr) glUniform4fv; } else if (0 == strcmp("glUniform4iv", name)) { return (GrGLFuncPtr) glUniform4iv; } else if (0 == strcmp("glUniformMatrix2fv", name)) { return (GrGLFuncPtr) glUniformMatrix2fv; } else if (0 == strcmp("glUniformMatrix3fv", name)) { return (GrGLFuncPtr) glUniformMatrix3fv; } else if (0 == strcmp("glUniformMatrix4fv", name)) { return (GrGLFuncPtr) glUniformMatrix4fv; } else if (0 == strcmp("glUseProgram", name)) { return (GrGLFuncPtr) glUseProgram; } else if (0 == strcmp("glVertexAttrib1f", name)) { return (GrGLFuncPtr) glVertexAttrib1f; } else if (0 == strcmp("glVertexAttrib2fv", name)) { return (GrGLFuncPtr) glVertexAttrib2fv; } else if (0 == strcmp("glVertexAttrib3fv", name)) { return (GrGLFuncPtr) glVertexAttrib3fv; } else if (0 == strcmp("glVertexAttrib4fv", name)) { return (GrGLFuncPtr) glVertexAttrib4fv; } else if (0 == strcmp("glVertexAttribPointer", name)) { return (GrGLFuncPtr) glVertexAttribPointer; } else if (0 == strcmp("glViewport", name)) { return (GrGLFuncPtr) glViewport; } else if (0 == strcmp("glBindFramebuffer", name)) { return (GrGLFuncPtr) glBindFramebuffer; } else if (0 == strcmp("glBindRenderbuffer", name)) { return (GrGLFuncPtr) glBindRenderbuffer; } else if (0 == strcmp("glCheckFramebufferStatus", name)) { return (GrGLFuncPtr) glCheckFramebufferStatus; } else if (0 == strcmp("glDeleteFramebuffers", name)) { return (GrGLFuncPtr) glDeleteFramebuffers; } else if (0 == strcmp("glDeleteRenderbuffers", name)) { return (GrGLFuncPtr) glDeleteRenderbuffers; } else if (0 == strcmp("glFramebufferRenderbuffer", name)) { return (GrGLFuncPtr) glFramebufferRenderbuffer; } else if (0 == strcmp("glFramebufferTexture2D", name)) { return (GrGLFuncPtr) glFramebufferTexture2D; } else if (0 == strcmp("glGenFramebuffers", name)) { return (GrGLFuncPtr) glGenFramebuffers; } else if (0 == strcmp("glGenRenderbuffers", name)) { return (GrGLFuncPtr) glGenRenderbuffers; } else if (0 == strcmp("glGetFramebufferAttachmentParameteriv", name)) { return (GrGLFuncPtr) glGetFramebufferAttachmentParameteriv; } else if (0 == strcmp("glGetRenderbufferParameteriv", name)) { return (GrGLFuncPtr) glGetRenderbufferParameteriv; } else if (0 == strcmp("glRenderbufferStorage", name)) { return (GrGLFuncPtr) glRenderbufferStorage; } else if (0 == strcmp("eglQueryString", name)) { return (GrGLFuncPtr) eglQueryString; } else if (0 == strcmp("eglGetCurrentDisplay", name)) { return (GrGLFuncPtr) eglGetCurrentDisplay; } return eglGetProcAddress(name); } const GrGLInterface* GrGLCreateNativeInterface() { return GrGLAssembleInterface(nullptr, android_get_gl_proc); } #endif//defined(SK_BUILD_FOR_ANDROID) <|endoftext|>
<commit_before>#include <ros/ros.h> #include <dynamic_reconfigure/server.h> #include <mantis_description/se_tools.h> #include <mantis_router_base/mantis_router_base.h> #include <mantis_router_base/ControlParamsConfig.h> #include <mavros_msgs/PositionTarget.h> #include <nav_msgs/Odometry.h> #include <geometry_msgs/PoseStamped.h> #include <eigen3/Eigen/Dense> #include <math.h> #include <iostream> #include <vector> MantisRouterBase::MantisRouterBase() : nh_(), nhp_("~"), p_(nh_), s_(nh_, p_), solver_(p_, s_), contrail_(nhp_), param_frame_id_("map"), param_model_id_("mantis_uav"), param_path_rate_(50.0), dyncfg_control_settings_(ros::NodeHandle(nhp_, "control_settings")) { nhp_.param("frame_id", param_frame_id_, param_frame_id_); nhp_.param("model_id", param_model_id_, param_model_id_); nhp_.param("path_rate", param_path_rate_, param_path_rate_); dyncfg_control_settings_.setCallback(boost::bind(&MantisRouterBase::callback_cfg_control_settings, this, _1, _2)); vbe_last_ = Eigen::Matrix<double,6,1>::Zero(); if( p_.wait_for_params() && s_.wait_for_state() ) { pub_tri_ = nhp_.advertise<mavros_msgs::PositionTarget>("output/triplet", 10); pub_pose_base_ = nhp_.advertise<geometry_msgs::PoseStamped>("feedback/base", 10); pub_pose_track_ = nhp_.advertise<geometry_msgs::PoseStamped>("feedback/track", 10); timer_ = nhp_.createTimer(ros::Duration(1.0/param_path_rate_), &MantisRouterBase::callback_timer, this ); ROS_INFO_ONCE("Augmented path control loaded!"); } else { ROS_WARN("Augmented path control shutting down."); ros::shutdown(); } } MantisRouterBase::~MantisRouterBase() { } void MantisRouterBase::callback_cfg_control_settings(mantis_router_base::ControlParamsConfig &config, uint32_t level) { param_tracked_frame_ = config.tracked_frame; param_manipulator_jacobian_a_ = config.manipulator_jacobian_alpha; param_send_reference_feedback_ = config.reference_feedback; } Eigen::Affine3d MantisRouterBase::calc_goal_base_transform(const Eigen::Affine3d &ge_sp, const Eigen::Affine3d &gbe) { //Use this yaw only rotation to set the direction of the base (and thus end effector) Eigen::Matrix3d br_sp = MDTools::extract_yaw_matrix(ge_sp.linear()); //Construct the true end effector Eigen::Affine3d sp = Eigen::Affine3d::Identity(); sp.linear() = br_sp*gbe.linear(); sp.translation() = ge_sp.translation(); //Use the inverse transform to get the true base transform return sp*gbe.inverse(); } Eigen::Vector3d MantisRouterBase::calc_goal_base_velocity(const Eigen::Vector3d &gev_sp, const Eigen::Matrix3d &Re, const Eigen::VectorXd &vbe) { //Velocity of the end effector in the end effector frame //Eigen::VectorXd vbe = Je*rd; //Eigen::Affine3d Vbe; //Vbe.translation() << vbe.segment(0,3); //Vbe.linear() << vee_up(vbe.segment(3,3)); //Get linear velocity in the world frame Eigen::Vector3d Ve = Re*vbe.segment(0,3); //Only care about the translation movements return gev_sp - Ve; } void MantisRouterBase::callback_timer(const ros::TimerEvent& e) { double dt = (e.current_real - e.last_real).toSec(); bool success = false; if( ( p_.ok() ) && ( s_.ok() ) && ( contrail_.has_reference(e.current_real) ) ) { Eigen::Affine3d g_sp = Eigen::Affine3d::Identity(); Eigen::Vector3d gv_sp = Eigen::Vector3d::Zero(); Eigen::Affine3d ge_sp = Eigen::Affine3d::Identity(); Eigen::Vector3d gev_sp = Eigen::Vector3d::Zero(); Eigen::Affine3d gbe = Eigen::Affine3d::Identity(); bool ksolver_success = false; bool track_alter_success = false; if(param_tracked_frame_ == 0) { //Just track the base ksolver_success = true; } else if(param_tracked_frame_ == -1) { //Compute transform for all joints in the chain to get base to end effector track_alter_success = solver_.calculate_gbe( gbe ); ksolver_success = track_alter_success; } else if(param_tracked_frame_ > 0) { //Compute transform for all joints in the chain to get base to specified joint track_alter_success = solver_.calculate_gxy( gbe, 0, param_tracked_frame_ ); ksolver_success = track_alter_success; } Eigen::Vector3d ref_pos; Eigen::Vector3d ref_vel; double ref_rpos; double ref_rvel; //Make certain we have a valid reference if(ksolver_success && contrail_.get_reference(ref_pos, ref_vel, ref_rpos, ref_rvel, e.current_real ) ) { //Fill in the current goals ge_sp.translation() = ref_pos; ge_sp.linear() = Eigen::AngleAxisd(ref_rpos, Eigen::Vector3d::UnitZ()).toRotationMatrix(); gev_sp = ref_vel; if( track_alter_success ) { //Calculate the tracking offset for the base g_sp = calc_goal_base_transform(ge_sp, gbe); //Compensate for velocity terms in manipulator movement //This is more accurate, but can make things more unstable if(param_manipulator_jacobian_a_ > 0.0) { bool calc_manip_velocity = false; Eigen::VectorXd vbe; if(param_tracked_frame_ == -1) calc_manip_velocity = solver_.calculate_vbe( vbe ); if(param_tracked_frame_ > 0) calc_manip_velocity = solver_.calculate_vbx( vbe, param_tracked_frame_ ); if( calc_manip_velocity ) { vbe_last_ =((1.0 - param_manipulator_jacobian_a_) * vbe_last_) + (param_manipulator_jacobian_a_ * vbe); //Manipulator velocity in the world frame Eigen::Matrix3d br_sp = MDTools::extract_yaw_matrix(g_sp.linear()); Eigen::Vector3d Ve = br_sp*vbe_last_.segment(0,3); //Subtract from setpoint to compensate base movements gv_sp = gev_sp - Ve; } else { ROS_ERROR_THROTTLE(2.0, "Unable to use manipulator Jacobian"); gv_sp = gev_sp; vbe_last_ = Eigen::Matrix<double,6,1>::Zero(); } } else { gv_sp = gev_sp; vbe_last_ = Eigen::Matrix<double,6,1>::Zero(); } } else { //Just track the robot base g_sp = ge_sp; gv_sp = gev_sp; vbe_last_ = Eigen::Matrix<double,6,1>::Zero(); } Eigen::Vector3d gv_sp_b = g_sp.linear()*gv_sp; success = true; contrail_.check_end_reached(s_.g()); mavros_msgs::PositionTarget msg_tri_out; msg_tri_out.header.stamp = e.current_real; msg_tri_out.header.frame_id = param_frame_id_; msg_tri_out.coordinate_frame = msg_tri_out.FRAME_LOCAL_NED; msg_tri_out.type_mask = msg_tri_out.IGNORE_AFX | msg_tri_out.IGNORE_AFY | msg_tri_out.IGNORE_AFZ | msg_tri_out.FORCE; msg_tri_out.position = MDTools::point_from_eig(g_sp.translation()); msg_tri_out.velocity = MDTools::vector_from_eig(gv_sp); //Eigen::Vector3d ea = g_sp.linear().eulerAngles(2,1,0); msg_tri_out.yaw = MDTools::extract_yaw(Eigen::Quaterniond(g_sp.linear())); msg_tri_out.yaw_rate = ref_rvel; pub_tri_.publish(msg_tri_out); if(param_send_reference_feedback_) { geometry_msgs::PoseStamped msg_base_out; geometry_msgs::PoseStamped msg_track_out; msg_base_out.header.stamp = e.current_real; msg_base_out.header.frame_id = param_frame_id_; msg_track_out.header = msg_base_out.header; msg_base_out.pose = MDTools::pose_from_eig(g_sp); msg_track_out.pose = MDTools::pose_from_eig(ge_sp); pub_pose_base_.publish(msg_base_out); pub_pose_track_.publish(msg_track_out); } } } //Reset some values if we had an failed calc if(!success) { vbe_last_ = Eigen::Matrix<double,6,1>::Zero(); } } <commit_msg>Tracking dynamic end effector should work now<commit_after>#include <ros/ros.h> #include <dynamic_reconfigure/server.h> #include <mantis_description/se_tools.h> #include <mantis_router_base/mantis_router_base.h> #include <mantis_router_base/ControlParamsConfig.h> #include <mavros_msgs/PositionTarget.h> #include <nav_msgs/Odometry.h> #include <geometry_msgs/PoseStamped.h> #include <eigen3/Eigen/Dense> #include <math.h> #include <iostream> #include <vector> MantisRouterBase::MantisRouterBase() : nh_(), nhp_("~"), p_(nh_), s_(nh_, p_), solver_(p_, s_), contrail_(nhp_), param_frame_id_("map"), param_model_id_("mantis_uav"), param_path_rate_(50.0), dyncfg_control_settings_(ros::NodeHandle(nhp_, "control_settings")) { nhp_.param("frame_id", param_frame_id_, param_frame_id_); nhp_.param("model_id", param_model_id_, param_model_id_); nhp_.param("path_rate", param_path_rate_, param_path_rate_); dyncfg_control_settings_.setCallback(boost::bind(&MantisRouterBase::callback_cfg_control_settings, this, _1, _2)); vbe_last_ = Eigen::Matrix<double,6,1>::Zero(); if( p_.wait_for_params() && s_.wait_for_state() ) { pub_tri_ = nhp_.advertise<mavros_msgs::PositionTarget>("output/triplet", 10); pub_pose_base_ = nhp_.advertise<geometry_msgs::PoseStamped>("feedback/base", 10); pub_pose_track_ = nhp_.advertise<geometry_msgs::PoseStamped>("feedback/track", 10); timer_ = nhp_.createTimer(ros::Duration(1.0/param_path_rate_), &MantisRouterBase::callback_timer, this ); ROS_INFO_ONCE("Augmented path control loaded!"); } else { ROS_WARN("Augmented path control shutting down."); ros::shutdown(); } } MantisRouterBase::~MantisRouterBase() { } void MantisRouterBase::callback_cfg_control_settings(mantis_router_base::ControlParamsConfig &config, uint32_t level) { param_tracked_frame_ = config.tracked_frame; param_manipulator_jacobian_a_ = config.manipulator_jacobian_alpha; param_send_reference_feedback_ = config.reference_feedback; } Eigen::Affine3d MantisRouterBase::calc_goal_base_transform(const Eigen::Affine3d &ge_sp, const Eigen::Affine3d &gbe) { //Use this yaw only rotation to set the direction of the base (and thus end effector) Eigen::Matrix3d br_sp = MDTools::extract_yaw_matrix(ge_sp.linear()); //Construct the true end effector Eigen::Affine3d sp = Eigen::Affine3d::Identity(); sp.linear() = br_sp*gbe.linear(); sp.translation() = ge_sp.translation(); //Use the inverse transform to get the true base transform return sp*gbe.inverse(); } Eigen::Vector3d MantisRouterBase::calc_goal_base_velocity(const Eigen::Vector3d &gev_sp, const Eigen::Matrix3d &Re, const Eigen::VectorXd &vbe) { //Velocity of the end effector in the end effector frame //Eigen::VectorXd vbe = Je*rd; //Eigen::Affine3d Vbe; //Vbe.translation() << vbe.segment(0,3); //Vbe.linear() << vee_up(vbe.segment(3,3)); //Get linear velocity in the world frame Eigen::Vector3d Ve = Re*vbe.segment(0,3); //Only care about the translation movements return gev_sp - Ve; } void MantisRouterBase::callback_timer(const ros::TimerEvent& e) { double dt = (e.current_real - e.last_real).toSec(); bool success = false; if( ( p_.ok() ) && ( s_.ok() ) && ( contrail_.has_reference(e.current_real) ) ) { Eigen::Affine3d g_sp = Eigen::Affine3d::Identity(); Eigen::Vector3d gv_sp = Eigen::Vector3d::Zero(); Eigen::Affine3d ge_sp = Eigen::Affine3d::Identity(); Eigen::Vector3d gev_sp = Eigen::Vector3d::Zero(); Eigen::Affine3d gbe = Eigen::Affine3d::Identity(); bool ksolver_success = false; bool track_alter_success = false; if(param_tracked_frame_ == 0) { //Just track the base ksolver_success = true; } else if(param_tracked_frame_ == -1) { //Compute transform for all joints in the chain to get base to end effector track_alter_success = solver_.calculate_gbe( gbe ); ksolver_success = track_alter_success; } else if(param_tracked_frame_ > 0) { //Compute transform for all joints in the chain to get base to specified joint track_alter_success = solver_.calculate_gxy( gbe, 0, param_tracked_frame_ ); ksolver_success = track_alter_success; } Eigen::Vector3d ref_pos; Eigen::Vector3d ref_vel; double ref_rpos; double ref_rvel; //Make certain we have a valid reference if(ksolver_success && contrail_.get_reference(ref_pos, ref_vel, ref_rpos, ref_rvel, e.current_real ) ) { //Fill in the current goals ge_sp.translation() = ref_pos; ge_sp.linear() = Eigen::AngleAxisd(ref_rpos, Eigen::Vector3d::UnitZ()).toRotationMatrix(); gev_sp = ref_vel; if( track_alter_success ) { //Calculate the tracking offset for the base g_sp = calc_goal_base_transform(ge_sp, gbe); //Compensate for velocity terms in manipulator movement //This is more accurate, but can make things more unstable if(param_manipulator_jacobian_a_ > 0.0) { bool calc_manip_velocity = false; Eigen::VectorXd vbe; if(param_tracked_frame_ == -1) calc_manip_velocity = solver_.calculate_vbe( vbe ); if(param_tracked_frame_ > 0) calc_manip_velocity = solver_.calculate_vbx( vbe, param_tracked_frame_ ); if( calc_manip_velocity ) { vbe_last_ =((1.0 - param_manipulator_jacobian_a_) * vbe_last_) + (param_manipulator_jacobian_a_ * vbe); //Manipulator velocity in the world frame Eigen::Matrix3d br_sp = MDTools::extract_yaw_matrix(g_sp.linear()); Eigen::Vector3d Ve = br_sp*vbe_last_.segment(0,3); //Subtract from setpoint to compensate base movements gv_sp = gev_sp - Ve; } else { ROS_ERROR_THROTTLE(2.0, "Unable to use manipulator Jacobian"); gv_sp = gev_sp; vbe_last_ = Eigen::Matrix<double,6,1>::Zero(); } } else { gv_sp = gev_sp; vbe_last_ = Eigen::Matrix<double,6,1>::Zero(); } } else { //Just track the robot base g_sp = ge_sp; gv_sp = gev_sp; gbe = Eigen::Affine3d::Identity(); vbe_last_ = Eigen::Matrix<double,6,1>::Zero(); } Eigen::Vector3d gv_sp_b = g_sp.linear()*gv_sp; success = true; contrail_.check_end_reached(s_.g()*gbe); mavros_msgs::PositionTarget msg_tri_out; msg_tri_out.header.stamp = e.current_real; msg_tri_out.header.frame_id = param_frame_id_; msg_tri_out.coordinate_frame = msg_tri_out.FRAME_LOCAL_NED; msg_tri_out.type_mask = msg_tri_out.IGNORE_AFX | msg_tri_out.IGNORE_AFY | msg_tri_out.IGNORE_AFZ | msg_tri_out.FORCE; msg_tri_out.position = MDTools::point_from_eig(g_sp.translation()); msg_tri_out.velocity = MDTools::vector_from_eig(gv_sp); //Eigen::Vector3d ea = g_sp.linear().eulerAngles(2,1,0); msg_tri_out.yaw = MDTools::extract_yaw(Eigen::Quaterniond(g_sp.linear())); msg_tri_out.yaw_rate = ref_rvel; pub_tri_.publish(msg_tri_out); if(param_send_reference_feedback_) { geometry_msgs::PoseStamped msg_base_out; geometry_msgs::PoseStamped msg_track_out; msg_base_out.header.stamp = e.current_real; msg_base_out.header.frame_id = param_frame_id_; msg_track_out.header = msg_base_out.header; msg_base_out.pose = MDTools::pose_from_eig(g_sp); msg_track_out.pose = MDTools::pose_from_eig(ge_sp); pub_pose_base_.publish(msg_base_out); pub_pose_track_.publish(msg_track_out); } } } //Reset some values if we had an failed calc if(!success) { vbe_last_ = Eigen::Matrix<double,6,1>::Zero(); } } <|endoftext|>
<commit_before><commit_msg>Create acm_1025.cpp<commit_after><|endoftext|>