commit
stringlengths
40
40
old_file
stringlengths
2
205
new_file
stringlengths
2
205
old_contents
stringlengths
0
32.9k
new_contents
stringlengths
1
38.9k
subject
stringlengths
3
9.4k
message
stringlengths
6
9.84k
lang
stringlengths
3
13
license
stringclasses
13 values
repos
stringlengths
6
115k
2f82a5070e0144a3327140edfa317e391e955db5
include/tao/seq/config.hpp
include/tao/seq/config.hpp
// Copyright (c) 2015-2017 Daniel Frey // Please see LICENSE for license or visit https://github.com/taocpp/sequences/ #ifndef TAOCPP_SEQUENCES_INCLUDE_CONFIG_HPP #define TAOCPP_SEQUENCES_INCLUDE_CONFIG_HPP #if __cplusplus >= 201402L #define TAOCPP_USE_STD_INTEGER_SEQUENCE #if defined( _LIBCPP_VERSION ) #define TAOCPP_USE_STD_MAKE_INTEGER_SEQUENCE #elif defined( _GLIBCXX_RELEASE ) && ( _GLIBCXX_RELEASE >= 8 ) #define TAOCPP_USE_STD_MAKE_INTEGER_SEQUENCE #elif defined( _MSC_VER ) && ( _MSC_VER >= 190023918 ) #define TAOCPP_USE_STD_MAKE_INTEGER_SEQUENCE #endif #endif // __cplusplus >= 201402L #if defined( __cpp_fold_expressions ) #define TAOCPP_FOLD_EXPRESSIONS #endif #endif // TAOCPP_SEQUENCES_INCLUDE_CONFIG_HPP
// Copyright (c) 2015-2018 Daniel Frey // Please see LICENSE for license or visit https://github.com/taocpp/sequences/ #ifndef TAOCPP_SEQUENCES_INCLUDE_CONFIG_HPP #define TAOCPP_SEQUENCES_INCLUDE_CONFIG_HPP #include <utility> #ifndef TAOCPP_USE_STD_INTEGER_SEQUENCE #if defined( __cpp_lib_integer_sequence ) || ( defined( _LIBCPP_VERSION ) && ( __cplusplus >= 201402L ) ) #define TAOCPP_USE_STD_INTEGER_SEQUENCE #endif #endif #ifndef TAOCPP_USE_STD_MAKE_INTEGER_SEQUENCE #if defined( _LIBCPP_VERSION ) && ( __cplusplus >= 201402L ) #define TAOCPP_USE_STD_MAKE_INTEGER_SEQUENCE #elif defined( _GLIBCXX_RELEASE ) && ( _GLIBCXX_RELEASE >= 8 ) && ( __cplusplus >= 201402L ) #define TAOCPP_USE_STD_MAKE_INTEGER_SEQUENCE #elif defined( _MSC_VER ) && ( _MSC_FULL_VER >= 190023918 ) #define TAOCPP_USE_STD_MAKE_INTEGER_SEQUENCE #endif #endif #if defined( __cpp_fold_expressions ) #define TAOCPP_FOLD_EXPRESSIONS #endif #endif // TAOCPP_SEQUENCES_INCLUDE_CONFIG_HPP
Improve detection for integer_sequence
Improve detection for integer_sequence
C++
mit
taocpp/sequences,taocpp/sequences
19403026f36144e16eb4ad832d046ecc73ee2bf1
include/zmsg/zmsg_heat.hpp
include/zmsg/zmsg_heat.hpp
#pragma once #include "zmsg_types.hpp" namespace zmsg { template<> struct zmsg<mid_t::heat_start> { public: uint32_t Material; shrink_tube_t Fiberlen; bool Heatctl; uint16_t heat_time; /// unit: second int16_t heat_temp; /// unit: degree Celsius int16_t finish_temp; /// unit: degree Celsius bool fast_heat; public: ZMSG_PU(Material,Fiberlen,Heatctl,heat_time,heat_temp,finish_temp) }; template<> struct zmsg<mid_t::heat_result> { fs_err_t code; public: ZMSG_PU(code) }; }
#pragma once #include "zmsg_types.hpp" namespace zmsg { template<> struct zmsg<mid_t::heat_start> { public: uint32_t Material; shrink_tube_t Fiberlen; bool Heatctl; uint16_t heat_time; /// unit: second int16_t heat_temp; /// unit: degree Celsius int16_t finish_temp; /// unit: degree Celsius bool fast_heat; public: ZMSG_PU(Material,Fiberlen,Heatctl,heat_time,heat_temp,finish_temp,fast_heat) }; template<> struct zmsg<mid_t::heat_result> { fs_err_t code; public: ZMSG_PU(code) }; }
modify zmsg heat_start
modify zmsg heat_start
C++
apache-2.0
walkthetalk/libem,walkthetalk/libem,walkthetalk/libem
1d586fb5ab7fdf776423d8da27ee6bdb6da04ef8
src/json_writer.cpp
src/json_writer.cpp
#include "json_writer.hpp" #include <limits> #include <cmath> // TODO: test putc_unlocked (EOF) and snprintf (length if unlimited) output namespace zizany { static void fputs_unlocked(const char *str, FILE *output) { while (*str != 0) putc_unlocked(*str++, output); } json_writer::json_writer(FILE *output_, const int indent_width_) : output(output_), indent_width(indent_width_), indent_level(0), inline_level(std::numeric_limits<int>::max()), state(state::after_start) { } void json_writer::add_string(const std::string &value) { insert_separator_if_needed(); print_quoted_string(value); state = state::after_value; } void json_writer::add_string(const char *chars, const std::size_t length) { insert_separator_if_needed(); print_quoted_string(chars, length); state = state::after_value; } void json_writer::add_number(std::int32_t value) { insert_separator_if_needed(); char buffer[64]; snprintf(buffer, 64, "%i", value); fputs_unlocked(buffer, output); state = state::after_value; } void json_writer::add_number(std::uint32_t value) { insert_separator_if_needed(); char buffer[64]; snprintf(buffer, 64, "%u", value); fputs_unlocked(buffer, output); state = state::after_value; } void json_writer::add_number(std::int64_t value) { insert_separator_if_needed(); char buffer[64]; snprintf(buffer, 64, "%lli", value); fputs_unlocked(buffer, output); state = state::after_value; } void json_writer::add_number(std::uint64_t value) { insert_separator_if_needed(); char buffer[64]; snprintf(buffer, 64, "%llu", value); fputs_unlocked(buffer, output); state = state::after_value; } void json_writer::add_number(float value) { insert_separator_if_needed(); if (std::isnan(value) || std::isinf(value)) fputs_unlocked("null", output); else { char buffer[64]; snprintf(buffer, 64, "%f", value); fputs_unlocked(buffer, output); } state = state::after_value; } void json_writer::add_number(double value) { insert_separator_if_needed(); if (std::isnan(value) || std::isinf(value)) fputs_unlocked("null", output); else { char buffer[64]; snprintf(buffer, 64, "%lf", value); fputs_unlocked(buffer, output); } state = state::after_value; } void json_writer::add_bool(bool value) { insert_separator_if_needed(); fputs_unlocked(value ? "true" : "false", output); state = state::after_value; } void json_writer::add_null() { insert_separator_if_needed(); fputs_unlocked("null", output); state = state::after_value; } void json_writer::start_object(bool force_inline) { start_composite('{', force_inline); } void json_writer::add_key(const char *key) { insert_separator_if_needed(); print_quoted_string(key); fputs_unlocked(": ", output); state = state::after_key; } void json_writer::add_key(const std::string &key) { insert_separator_if_needed(); print_quoted_string(key); fputs_unlocked(": ", output); state = state::after_key; } void json_writer::end_object() { end_composite('}'); } void json_writer::start_array(bool force_inline) { start_composite('[', force_inline); } void json_writer::end_array() { end_composite(']'); } void json_writer::reset() { indent_level = 0; state = state::after_start; } void json_writer::start_composite(char marker, bool force_inline) { insert_separator_if_needed(); putc_unlocked(marker, output); if (force_inline) inline_level = std::min(inline_level, indent_level); indent_level += 1; state = state::after_composite_start; } void json_writer::end_composite(char marker) { indent_level -= 1; if (state == state::after_value && indent_level < inline_level) insert_newline(); putc_unlocked(marker, output); state = state::after_value; if (indent_level == inline_level) inline_level = std::numeric_limits<int>::max(); } void json_writer::insert_separator_if_needed() { if (state == state::after_value) putc_unlocked(',', output); if (state != state::after_key) { if (state != state::after_start && indent_level < inline_level) insert_newline(); else if (state == state::after_value) putc_unlocked(' ', output); } } void json_writer::insert_newline() { putc_unlocked('\n', output); for (int i = 0; i < indent_width * indent_level; ++i) putc_unlocked(' ', output); } inline void print_quoted_character(FILE *output, const char character) { const char hex[16] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; switch (character) { case '\b': putc_unlocked('\\', output); putc_unlocked('b', output); break; case '\f': putc_unlocked('\\', output); putc_unlocked('f', output); break; case '\n': putc_unlocked('\\', output); putc_unlocked('n', output); break; case '\r': putc_unlocked('\\', output); putc_unlocked('r', output); break; case '\t': putc_unlocked('\\', output); putc_unlocked('t', output); break; case '\\': putc_unlocked('\\', output); putc_unlocked('\\', output); break; case '\"': putc_unlocked('\\', output); putc_unlocked('"', output); break; default: if (character > 0 && character < 32) { putc_unlocked('\\', output); putc_unlocked('u', output); putc_unlocked('0', output); putc_unlocked('0', output); putc_unlocked(hex[character >> 4], output); putc_unlocked(hex[character & 0xf], output); } else { putc_unlocked(character, output); } } } void json_writer::print_quoted_string(const std::string &string) { putc_unlocked('"', output); for (std::size_t index = 0; index < string.size(); ++index) print_quoted_character(output, string[index]); putc_unlocked('"', output); } void json_writer::print_quoted_string(const char *string) { putc_unlocked('"', output); while (*string != 0) print_quoted_character(output, *string++); putc_unlocked('"', output); } void json_writer::print_quoted_string(const char *string, const std::size_t length) { putc_unlocked('"', output); for (std::size_t index = 0; index < length; ++index) print_quoted_character(output, string[index]); putc_unlocked('"', output); } }
#include "json_writer.hpp" #include <limits> #include <cmath> // TODO: test putc_unlocked (EOF) and snprintf (length if unlimited) output namespace zizany { static void fputs_unlocked_(const char *str, FILE *output) { while (*str != 0) putc_unlocked(*str++, output); } json_writer::json_writer(FILE *output_, const int indent_width_) : output(output_), indent_width(indent_width_), indent_level(0), inline_level(std::numeric_limits<int>::max()), state(state::after_start) { } void json_writer::add_string(const std::string &value) { insert_separator_if_needed(); print_quoted_string(value); state = state::after_value; } void json_writer::add_string(const char *chars, const std::size_t length) { insert_separator_if_needed(); print_quoted_string(chars, length); state = state::after_value; } void json_writer::add_number(std::int32_t value) { insert_separator_if_needed(); char buffer[64]; snprintf(buffer, 64, "%i", value); fputs_unlocked_(buffer, output); state = state::after_value; } void json_writer::add_number(std::uint32_t value) { insert_separator_if_needed(); char buffer[64]; snprintf(buffer, 64, "%u", value); fputs_unlocked_(buffer, output); state = state::after_value; } void json_writer::add_number(std::int64_t value) { insert_separator_if_needed(); char buffer[64]; snprintf(buffer, 64, "%lli", value); fputs_unlocked_(buffer, output); state = state::after_value; } void json_writer::add_number(std::uint64_t value) { insert_separator_if_needed(); char buffer[64]; snprintf(buffer, 64, "%llu", value); fputs_unlocked_(buffer, output); state = state::after_value; } void json_writer::add_number(float value) { insert_separator_if_needed(); if (std::isnan(value) || std::isinf(value)) fputs_unlocked_("null", output); else { char buffer[64]; snprintf(buffer, 64, "%f", value); fputs_unlocked_(buffer, output); } state = state::after_value; } void json_writer::add_number(double value) { insert_separator_if_needed(); if (std::isnan(value) || std::isinf(value)) fputs_unlocked_("null", output); else { char buffer[64]; snprintf(buffer, 64, "%lf", value); fputs_unlocked_(buffer, output); } state = state::after_value; } void json_writer::add_bool(bool value) { insert_separator_if_needed(); fputs_unlocked_(value ? "true" : "false", output); state = state::after_value; } void json_writer::add_null() { insert_separator_if_needed(); fputs_unlocked_("null", output); state = state::after_value; } void json_writer::start_object(bool force_inline) { start_composite('{', force_inline); } void json_writer::add_key(const char *key) { insert_separator_if_needed(); print_quoted_string(key); fputs_unlocked_(": ", output); state = state::after_key; } void json_writer::add_key(const std::string &key) { insert_separator_if_needed(); print_quoted_string(key); fputs_unlocked_(": ", output); state = state::after_key; } void json_writer::end_object() { end_composite('}'); } void json_writer::start_array(bool force_inline) { start_composite('[', force_inline); } void json_writer::end_array() { end_composite(']'); } void json_writer::reset() { indent_level = 0; state = state::after_start; } void json_writer::start_composite(char marker, bool force_inline) { insert_separator_if_needed(); putc_unlocked(marker, output); if (force_inline) inline_level = std::min(inline_level, indent_level); indent_level += 1; state = state::after_composite_start; } void json_writer::end_composite(char marker) { indent_level -= 1; if (state == state::after_value && indent_level < inline_level) insert_newline(); putc_unlocked(marker, output); state = state::after_value; if (indent_level == inline_level) inline_level = std::numeric_limits<int>::max(); } void json_writer::insert_separator_if_needed() { if (state == state::after_value) putc_unlocked(',', output); if (state != state::after_key) { if (state != state::after_start && indent_level < inline_level) insert_newline(); else if (state == state::after_value) putc_unlocked(' ', output); } } void json_writer::insert_newline() { putc_unlocked('\n', output); for (int i = 0; i < indent_width * indent_level; ++i) putc_unlocked(' ', output); } inline void print_quoted_character(FILE *output, const char character) { const char hex[16] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; switch (character) { case '\b': putc_unlocked('\\', output); putc_unlocked('b', output); break; case '\f': putc_unlocked('\\', output); putc_unlocked('f', output); break; case '\n': putc_unlocked('\\', output); putc_unlocked('n', output); break; case '\r': putc_unlocked('\\', output); putc_unlocked('r', output); break; case '\t': putc_unlocked('\\', output); putc_unlocked('t', output); break; case '\\': putc_unlocked('\\', output); putc_unlocked('\\', output); break; case '\"': putc_unlocked('\\', output); putc_unlocked('"', output); break; default: if (character > 0 && character < 32) { putc_unlocked('\\', output); putc_unlocked('u', output); putc_unlocked('0', output); putc_unlocked('0', output); putc_unlocked(hex[character >> 4], output); putc_unlocked(hex[character & 0xf], output); } else { putc_unlocked(character, output); } } } void json_writer::print_quoted_string(const std::string &string) { putc_unlocked('"', output); for (std::size_t index = 0; index < string.size(); ++index) print_quoted_character(output, string[index]); putc_unlocked('"', output); } void json_writer::print_quoted_string(const char *string) { putc_unlocked('"', output); while (*string != 0) print_quoted_character(output, *string++); putc_unlocked('"', output); } void json_writer::print_quoted_string(const char *string, const std::size_t length) { putc_unlocked('"', output); for (std::size_t index = 0; index < length; ++index) print_quoted_character(output, string[index]); putc_unlocked('"', output); } }
Rename fputs_unlocked because of conflict with gnu stdio.h
Rename fputs_unlocked because of conflict with gnu stdio.h
C++
mit
kmichel/zizany,kmichel/zizany
7f381db4513daba8fcd380084db97906915e9fb9
src/node-midi.cpp
src/node-midi.cpp
#include <nan.h> #include <queue> #include <uv.h> #include "lib/RtMidi/RtMidi.h" #include "lib/RtMidi/RtMidi.cpp" class NodeMidiOutput : public Nan::ObjectWrap { private: RtMidiOut* out; public: static Nan::Persistent<v8::FunctionTemplate> s_ct; static void Init(v8::Handle<v8::Object> target) { Nan::HandleScope scope; v8::Local<v8::FunctionTemplate> t = Nan::New<v8::FunctionTemplate>(NodeMidiOutput::New); s_ct.Reset(t); t->SetClassName(Nan::New<v8::String>("NodeMidiOutput").ToLocalChecked()); t->InstanceTemplate()->SetInternalFieldCount(1); Nan::SetPrototypeMethod(t, "getPortCount", GetPortCount); Nan::SetPrototypeMethod(t, "getPortName", GetPortName); Nan::SetPrototypeMethod(t, "openPort", OpenPort); Nan::SetPrototypeMethod(t, "openVirtualPort", OpenVirtualPort); Nan::SetPrototypeMethod(t, "closePort", ClosePort); Nan::SetPrototypeMethod(t, "isPortOpen", IsPortOpen); Nan::SetPrototypeMethod(t, "sendMessage", SendMessage); target->Set(Nan::New<v8::String>("output").ToLocalChecked(), t->GetFunction()); } NodeMidiOutput() { out = new RtMidiOut(); } ~NodeMidiOutput() { delete out; } static NAN_METHOD(New) { Nan::HandleScope scope; if (!info.IsConstructCall()) { return Nan::ThrowTypeError("Use the new operator to create instances of this object."); } NodeMidiOutput* output = new NodeMidiOutput(); output->Wrap(info.This()); info.GetReturnValue().Set(info.This()); } static NAN_METHOD(GetPortCount) { Nan::HandleScope scope; NodeMidiOutput* output = Nan::ObjectWrap::Unwrap<NodeMidiOutput>(info.This()); v8::Local<v8::Integer> result = Nan::New<v8::Uint32>(output->out->getPortCount()); info.GetReturnValue().Set(result); } static NAN_METHOD(GetPortName) { Nan::HandleScope scope; NodeMidiOutput* output = Nan::ObjectWrap::Unwrap<NodeMidiOutput>(info.This()); if (info.Length() == 0 || !info[0]->IsUint32()) { return Nan::ThrowTypeError("First argument must be an integer"); } unsigned int portNumber = Nan::To<unsigned int>(info[0]).FromJust(); v8::Local<v8::String> result = Nan::New<v8::String>(output->out->getPortName(portNumber).c_str()).ToLocalChecked(); info.GetReturnValue().Set(result); } static NAN_METHOD(OpenPort) { Nan::HandleScope scope; NodeMidiOutput* output = Nan::ObjectWrap::Unwrap<NodeMidiOutput>(info.This()); if (info.Length() == 0 || !info[0]->IsUint32()) { return Nan::ThrowTypeError("First argument must be an integer"); } unsigned int portNumber = Nan::To<unsigned int>(info[0]).FromJust(); if (portNumber >= output->out->getPortCount()) { return Nan::ThrowRangeError("Invalid MIDI port number"); } output->out->openPort(portNumber); return; } static NAN_METHOD(OpenVirtualPort) { Nan::HandleScope scope; NodeMidiOutput* output = Nan::ObjectWrap::Unwrap<NodeMidiOutput>(info.This()); if (info.Length() == 0 || !info[0]->IsString()) { return Nan::ThrowTypeError("First argument must be a string"); } std::string name(*Nan::Utf8String(info[0])); output->out->openVirtualPort(name); return; } static NAN_METHOD(ClosePort) { Nan::HandleScope scope; NodeMidiOutput* output = Nan::ObjectWrap::Unwrap<NodeMidiOutput>(info.This()); output->out->closePort(); return; } static NAN_METHOD(IsPortOpen) { Nan::HandleScope scope; NodeMidiOutput* output = Nan::ObjectWrap::Unwrap<NodeMidiOutput>(info.This()); v8::Local<v8::Boolean> result = Nan::New<v8::Boolean>(output->out->isPortOpen()); info.GetReturnValue().Set(result); } static NAN_METHOD(SendMessage) { Nan::HandleScope scope; NodeMidiOutput* output = Nan::ObjectWrap::Unwrap<NodeMidiOutput>(info.This()); if (info.Length() == 0 || !info[0]->IsArray()) { return Nan::ThrowTypeError("First argument must be an array"); } v8::Local<v8::Object> message = Nan::To<v8::Object>(info[0]).ToLocalChecked(); int32_t messageLength = Nan::To<int32_t>(message->Get(Nan::New<v8::String>("length").ToLocalChecked())).FromJust(); std::vector<unsigned char> messageOutput; for (int32_t i = 0; i != messageLength; ++i) { messageOutput.push_back(Nan::To<unsigned int>(message->Get(Nan::New<v8::Integer>(i))).FromJust()); } output->out->sendMessage(&messageOutput); return; } }; const char* symbol_emit = "emit"; const char* symbol_message = "message"; class NodeMidiInput : public Nan::ObjectWrap { private: RtMidiIn* in; public: uv_async_t message_async; uv_mutex_t message_mutex; struct MidiMessage { double deltaTime; std::vector<unsigned char> message; }; std::queue<MidiMessage*> message_queue; static Nan::Persistent<v8::FunctionTemplate> s_ct; static void Init(v8::Handle<v8::Object> target) { Nan::HandleScope scope; v8::Local<v8::FunctionTemplate> t = Nan::New<v8::FunctionTemplate>(NodeMidiInput::New); s_ct.Reset(t); t->SetClassName(Nan::New<v8::String>("NodeMidiInput").ToLocalChecked()); t->InstanceTemplate()->SetInternalFieldCount(1); Nan::SetPrototypeMethod(t, "getPortCount", GetPortCount); Nan::SetPrototypeMethod(t, "getPortName", GetPortName); Nan::SetPrototypeMethod(t, "openPort", OpenPort); Nan::SetPrototypeMethod(t, "openVirtualPort", OpenVirtualPort); Nan::SetPrototypeMethod(t, "closePort", ClosePort); Nan::SetPrototypeMethod(t, "isPortOpen", IsPortOpen); Nan::SetPrototypeMethod(t, "ignoreTypes", IgnoreTypes); target->Set(Nan::New<v8::String>("input").ToLocalChecked(), t->GetFunction()); } NodeMidiInput() { in = new RtMidiIn(); uv_mutex_init(&message_mutex); } ~NodeMidiInput() { in->closePort(); delete in; uv_mutex_destroy(&message_mutex); } static NAUV_WORK_CB(EmitMessage) { Nan::HandleScope scope; NodeMidiInput *input = static_cast<NodeMidiInput*>(async->data); uv_mutex_lock(&input->message_mutex); v8::Local<v8::Function> emitFunction = input->handle()->Get(Nan::New<v8::String>(symbol_emit).ToLocalChecked()).As<v8::Function>(); while (!input->message_queue.empty()) { MidiMessage* message = input->message_queue.front(); v8::Local<v8::Value> info[3]; info[0] = Nan::New<v8::String>(symbol_message).ToLocalChecked(); info[1] = Nan::New<v8::Number>(message->deltaTime); int32_t count = (int32_t)message->message.size(); v8::Local<v8::Array> data = Nan::New<v8::Array>(count); for (int32_t i = 0; i < count; ++i) { data->Set(Nan::New<v8::Number>(i), Nan::New<v8::Integer>(message->message[i])); } info[2] = data; Nan::Call(emitFunction, input->handle(), 3, info); input->message_queue.pop(); delete message; } uv_mutex_unlock(&input->message_mutex); } static void Callback(double deltaTime, std::vector<unsigned char> *message, void *userData) { NodeMidiInput *input = static_cast<NodeMidiInput*>(userData); MidiMessage* data = new MidiMessage(); data->deltaTime = deltaTime; data->message = *message; uv_mutex_lock(&input->message_mutex); input->message_queue.push(data); uv_mutex_unlock(&input->message_mutex); uv_async_send(&input->message_async); } static NAN_METHOD(New) { Nan::HandleScope scope; if (!info.IsConstructCall()) { return Nan::ThrowTypeError("Use the new operator to create instances of this object."); } NodeMidiInput* input = new NodeMidiInput(); input->message_async.data = input; uv_async_init(uv_default_loop(), &input->message_async, NodeMidiInput::EmitMessage); input->Wrap(info.This()); info.GetReturnValue().Set(info.This()); } static NAN_METHOD(GetPortCount) { Nan::HandleScope scope; NodeMidiInput* input = Nan::ObjectWrap::Unwrap<NodeMidiInput>(info.This()); v8::Local<v8::Integer> result = Nan::New<v8::Uint32>(input->in->getPortCount()); info.GetReturnValue().Set(result); } static NAN_METHOD(GetPortName) { Nan::HandleScope scope; NodeMidiInput* input = Nan::ObjectWrap::Unwrap<NodeMidiInput>(info.This()); if (info.Length() == 0 || !info[0]->IsUint32()) { return Nan::ThrowTypeError("First argument must be an integer"); } unsigned int portNumber = Nan::To<unsigned int>(info[0]).FromJust(); v8::Local<v8::String> result = Nan::New<v8::String>(input->in->getPortName(portNumber).c_str()).ToLocalChecked(); info.GetReturnValue().Set(result); } static NAN_METHOD(OpenPort) { Nan::HandleScope scope; NodeMidiInput* input = Nan::ObjectWrap::Unwrap<NodeMidiInput>(info.This()); if (info.Length() == 0 || !info[0]->IsUint32()) { return Nan::ThrowTypeError("First argument must be an integer"); } unsigned int portNumber = Nan::To<unsigned int>(info[0]).FromJust(); if (portNumber >= input->in->getPortCount()) { return Nan::ThrowRangeError("Invalid MIDI port number"); } input->Ref(); input->in->setCallback(&NodeMidiInput::Callback, Nan::ObjectWrap::Unwrap<NodeMidiInput>(info.This())); input->in->openPort(portNumber); return; } static NAN_METHOD(OpenVirtualPort) { Nan::HandleScope scope; NodeMidiInput* input = Nan::ObjectWrap::Unwrap<NodeMidiInput>(info.This()); if (info.Length() == 0 || !info[0]->IsString()) { return Nan::ThrowTypeError("First argument must be a string"); } std::string name(*Nan::Utf8String(info[0])); input->Ref(); input->in->setCallback(&NodeMidiInput::Callback, Nan::ObjectWrap::Unwrap<NodeMidiInput>(info.This())); input->in->openVirtualPort(name); return; } static NAN_METHOD(ClosePort) { Nan::HandleScope scope; NodeMidiInput* input = Nan::ObjectWrap::Unwrap<NodeMidiInput>(info.This()); if (input->in->isPortOpen()) { input->Unref(); } input->in->cancelCallback(); input->in->closePort(); uv_close((uv_handle_t*)&input->message_async, NULL); return; } static NAN_METHOD(IsPortOpen) { Nan::HandleScope scope; NodeMidiInput* input = Nan::ObjectWrap::Unwrap<NodeMidiInput>(info.This()); v8::Local<v8::Boolean> result = Nan::New<v8::Boolean>(input->in->isPortOpen()); info.GetReturnValue().Set(result); } static NAN_METHOD(IgnoreTypes) { Nan::HandleScope scope; NodeMidiInput* input = Nan::ObjectWrap::Unwrap<NodeMidiInput>(info.This()); if (info.Length() != 3 || !info[0]->IsBoolean() || !info[1]->IsBoolean() || !info[2]->IsBoolean()) { return Nan::ThrowTypeError("Arguments must be boolean"); } bool filter_sysex = Nan::To<bool>(info[0]).FromJust(); bool filter_timing = Nan::To<bool>(info[1]).FromJust(); bool filter_sensing = Nan::To<bool>(info[2]).FromJust(); input->in->ignoreTypes(filter_sysex, filter_timing, filter_sensing); return; } }; Nan::Persistent<v8::FunctionTemplate> NodeMidiOutput::s_ct; Nan::Persistent<v8::FunctionTemplate> NodeMidiInput::s_ct; extern "C" { void init (v8::Handle<v8::Object> target) { NodeMidiOutput::Init(target); NodeMidiInput::Init(target); } NODE_MODULE(midi, init) }
#include <nan.h> #include <queue> #include <uv.h> #include "lib/RtMidi/RtMidi.h" #include "lib/RtMidi/RtMidi.cpp" class NodeMidiOutput : public Nan::ObjectWrap { private: RtMidiOut* out; public: static Nan::Persistent<v8::FunctionTemplate> s_ct; static void Init(v8::Local<v8::Object> target) { Nan::HandleScope scope; v8::Local<v8::FunctionTemplate> t = Nan::New<v8::FunctionTemplate>(NodeMidiOutput::New); s_ct.Reset(t); t->SetClassName(Nan::New<v8::String>("NodeMidiOutput").ToLocalChecked()); t->InstanceTemplate()->SetInternalFieldCount(1); Nan::SetPrototypeMethod(t, "getPortCount", GetPortCount); Nan::SetPrototypeMethod(t, "getPortName", GetPortName); Nan::SetPrototypeMethod(t, "openPort", OpenPort); Nan::SetPrototypeMethod(t, "openVirtualPort", OpenVirtualPort); Nan::SetPrototypeMethod(t, "closePort", ClosePort); Nan::SetPrototypeMethod(t, "isPortOpen", IsPortOpen); Nan::SetPrototypeMethod(t, "sendMessage", SendMessage); Nan::Set(target, Nan::New<v8::String>("output").ToLocalChecked(), Nan::GetFunction(t).ToLocalChecked()); } NodeMidiOutput() { out = new RtMidiOut(); } ~NodeMidiOutput() { delete out; } static NAN_METHOD(New) { Nan::HandleScope scope; if (!info.IsConstructCall()) { return Nan::ThrowTypeError("Use the new operator to create instances of this object."); } NodeMidiOutput* output = new NodeMidiOutput(); output->Wrap(info.This()); info.GetReturnValue().Set(info.This()); } static NAN_METHOD(GetPortCount) { Nan::HandleScope scope; NodeMidiOutput* output = Nan::ObjectWrap::Unwrap<NodeMidiOutput>(info.This()); v8::Local<v8::Integer> result = Nan::New<v8::Uint32>(output->out->getPortCount()); info.GetReturnValue().Set(result); } static NAN_METHOD(GetPortName) { Nan::HandleScope scope; NodeMidiOutput* output = Nan::ObjectWrap::Unwrap<NodeMidiOutput>(info.This()); if (info.Length() == 0 || !info[0]->IsUint32()) { return Nan::ThrowTypeError("First argument must be an integer"); } unsigned int portNumber = Nan::To<unsigned int>(info[0]).FromJust(); v8::Local<v8::String> result = Nan::New<v8::String>(output->out->getPortName(portNumber).c_str()).ToLocalChecked(); info.GetReturnValue().Set(result); } static NAN_METHOD(OpenPort) { Nan::HandleScope scope; NodeMidiOutput* output = Nan::ObjectWrap::Unwrap<NodeMidiOutput>(info.This()); if (info.Length() == 0 || !info[0]->IsUint32()) { return Nan::ThrowTypeError("First argument must be an integer"); } unsigned int portNumber = Nan::To<unsigned int>(info[0]).FromJust(); if (portNumber >= output->out->getPortCount()) { return Nan::ThrowRangeError("Invalid MIDI port number"); } output->out->openPort(portNumber); return; } static NAN_METHOD(OpenVirtualPort) { Nan::HandleScope scope; NodeMidiOutput* output = Nan::ObjectWrap::Unwrap<NodeMidiOutput>(info.This()); if (info.Length() == 0 || !info[0]->IsString()) { return Nan::ThrowTypeError("First argument must be a string"); } std::string name(*Nan::Utf8String(info[0])); output->out->openVirtualPort(name); return; } static NAN_METHOD(ClosePort) { Nan::HandleScope scope; NodeMidiOutput* output = Nan::ObjectWrap::Unwrap<NodeMidiOutput>(info.This()); output->out->closePort(); return; } static NAN_METHOD(IsPortOpen) { Nan::HandleScope scope; NodeMidiOutput* output = Nan::ObjectWrap::Unwrap<NodeMidiOutput>(info.This()); v8::Local<v8::Boolean> result = Nan::New<v8::Boolean>(output->out->isPortOpen()); info.GetReturnValue().Set(result); } static NAN_METHOD(SendMessage) { Nan::HandleScope scope; NodeMidiOutput* output = Nan::ObjectWrap::Unwrap<NodeMidiOutput>(info.This()); if (info.Length() == 0 || !info[0]->IsArray()) { return Nan::ThrowTypeError("First argument must be an array"); } v8::Local<v8::Object> message = Nan::To<v8::Object>(info[0]).ToLocalChecked(); int32_t messageLength = Nan::To<int32_t>(Nan::Get(message, Nan::New<v8::String>("length").ToLocalChecked()).ToLocalChecked()).FromJust(); std::vector<unsigned char> messageOutput; for (int32_t i = 0; i != messageLength; ++i) { messageOutput.push_back(Nan::To<unsigned int>(Nan::Get(message, Nan::New<v8::Integer>(i)).ToLocalChecked()).FromJust()); } output->out->sendMessage(&messageOutput); return; } }; const char* symbol_emit = "emit"; const char* symbol_message = "message"; class NodeMidiInput : public Nan::ObjectWrap { private: RtMidiIn* in; public: uv_async_t message_async; uv_mutex_t message_mutex; struct MidiMessage { double deltaTime; std::vector<unsigned char> message; }; std::queue<MidiMessage*> message_queue; static Nan::Persistent<v8::FunctionTemplate> s_ct; static void Init(v8::Local<v8::Object> target) { Nan::HandleScope scope; v8::Local<v8::FunctionTemplate> t = Nan::New<v8::FunctionTemplate>(NodeMidiInput::New); s_ct.Reset(t); t->SetClassName(Nan::New<v8::String>("NodeMidiInput").ToLocalChecked()); t->InstanceTemplate()->SetInternalFieldCount(1); Nan::SetPrototypeMethod(t, "getPortCount", GetPortCount); Nan::SetPrototypeMethod(t, "getPortName", GetPortName); Nan::SetPrototypeMethod(t, "openPort", OpenPort); Nan::SetPrototypeMethod(t, "openVirtualPort", OpenVirtualPort); Nan::SetPrototypeMethod(t, "closePort", ClosePort); Nan::SetPrototypeMethod(t, "isPortOpen", IsPortOpen); Nan::SetPrototypeMethod(t, "ignoreTypes", IgnoreTypes); Nan::Set(target, Nan::New<v8::String>("input").ToLocalChecked(), Nan::GetFunction(t).ToLocalChecked()); } NodeMidiInput() { in = new RtMidiIn(); uv_mutex_init(&message_mutex); } ~NodeMidiInput() { in->closePort(); delete in; uv_mutex_destroy(&message_mutex); } static NAUV_WORK_CB(EmitMessage) { Nan::HandleScope scope; NodeMidiInput *input = static_cast<NodeMidiInput*>(async->data); uv_mutex_lock(&input->message_mutex); v8::Local<v8::Function> emitFunction = Nan::Get(input->handle(), Nan::New<v8::String>(symbol_emit).ToLocalChecked()).ToLocalChecked().As<v8::Function>(); while (!input->message_queue.empty()) { MidiMessage* message = input->message_queue.front(); v8::Local<v8::Value> info[3]; info[0] = Nan::New<v8::String>(symbol_message).ToLocalChecked(); info[1] = Nan::New<v8::Number>(message->deltaTime); int32_t count = (int32_t)message->message.size(); v8::Local<v8::Array> data = Nan::New<v8::Array>(count); for (int32_t i = 0; i < count; ++i) { Nan::Set(data, Nan::New<v8::Number>(i), Nan::New<v8::Integer>(message->message[i])); } info[2] = data; Nan::Call(emitFunction, input->handle(), 3, info); input->message_queue.pop(); delete message; } uv_mutex_unlock(&input->message_mutex); } static void Callback(double deltaTime, std::vector<unsigned char> *message, void *userData) { NodeMidiInput *input = static_cast<NodeMidiInput*>(userData); MidiMessage* data = new MidiMessage(); data->deltaTime = deltaTime; data->message = *message; uv_mutex_lock(&input->message_mutex); input->message_queue.push(data); uv_mutex_unlock(&input->message_mutex); uv_async_send(&input->message_async); } static NAN_METHOD(New) { Nan::HandleScope scope; if (!info.IsConstructCall()) { return Nan::ThrowTypeError("Use the new operator to create instances of this object."); } NodeMidiInput* input = new NodeMidiInput(); input->message_async.data = input; uv_async_init(uv_default_loop(), &input->message_async, NodeMidiInput::EmitMessage); input->Wrap(info.This()); info.GetReturnValue().Set(info.This()); } static NAN_METHOD(GetPortCount) { Nan::HandleScope scope; NodeMidiInput* input = Nan::ObjectWrap::Unwrap<NodeMidiInput>(info.This()); v8::Local<v8::Integer> result = Nan::New<v8::Uint32>(input->in->getPortCount()); info.GetReturnValue().Set(result); } static NAN_METHOD(GetPortName) { Nan::HandleScope scope; NodeMidiInput* input = Nan::ObjectWrap::Unwrap<NodeMidiInput>(info.This()); if (info.Length() == 0 || !info[0]->IsUint32()) { return Nan::ThrowTypeError("First argument must be an integer"); } unsigned int portNumber = Nan::To<unsigned int>(info[0]).FromJust(); v8::Local<v8::String> result = Nan::New<v8::String>(input->in->getPortName(portNumber).c_str()).ToLocalChecked(); info.GetReturnValue().Set(result); } static NAN_METHOD(OpenPort) { Nan::HandleScope scope; NodeMidiInput* input = Nan::ObjectWrap::Unwrap<NodeMidiInput>(info.This()); if (info.Length() == 0 || !info[0]->IsUint32()) { return Nan::ThrowTypeError("First argument must be an integer"); } unsigned int portNumber = Nan::To<unsigned int>(info[0]).FromJust(); if (portNumber >= input->in->getPortCount()) { return Nan::ThrowRangeError("Invalid MIDI port number"); } input->Ref(); input->in->setCallback(&NodeMidiInput::Callback, Nan::ObjectWrap::Unwrap<NodeMidiInput>(info.This())); input->in->openPort(portNumber); return; } static NAN_METHOD(OpenVirtualPort) { Nan::HandleScope scope; NodeMidiInput* input = Nan::ObjectWrap::Unwrap<NodeMidiInput>(info.This()); if (info.Length() == 0 || !info[0]->IsString()) { return Nan::ThrowTypeError("First argument must be a string"); } std::string name(*Nan::Utf8String(info[0])); input->Ref(); input->in->setCallback(&NodeMidiInput::Callback, Nan::ObjectWrap::Unwrap<NodeMidiInput>(info.This())); input->in->openVirtualPort(name); return; } static NAN_METHOD(ClosePort) { Nan::HandleScope scope; NodeMidiInput* input = Nan::ObjectWrap::Unwrap<NodeMidiInput>(info.This()); if (input->in->isPortOpen()) { input->Unref(); } input->in->cancelCallback(); input->in->closePort(); uv_close((uv_handle_t*)&input->message_async, NULL); return; } static NAN_METHOD(IsPortOpen) { Nan::HandleScope scope; NodeMidiInput* input = Nan::ObjectWrap::Unwrap<NodeMidiInput>(info.This()); v8::Local<v8::Boolean> result = Nan::New<v8::Boolean>(input->in->isPortOpen()); info.GetReturnValue().Set(result); } static NAN_METHOD(IgnoreTypes) { Nan::HandleScope scope; NodeMidiInput* input = Nan::ObjectWrap::Unwrap<NodeMidiInput>(info.This()); if (info.Length() != 3 || !info[0]->IsBoolean() || !info[1]->IsBoolean() || !info[2]->IsBoolean()) { return Nan::ThrowTypeError("Arguments must be boolean"); } bool filter_sysex = Nan::To<bool>(info[0]).FromJust(); bool filter_timing = Nan::To<bool>(info[1]).FromJust(); bool filter_sensing = Nan::To<bool>(info[2]).FromJust(); input->in->ignoreTypes(filter_sysex, filter_timing, filter_sensing); return; } }; Nan::Persistent<v8::FunctionTemplate> NodeMidiOutput::s_ct; Nan::Persistent<v8::FunctionTemplate> NodeMidiInput::s_ct; extern "C" { void init (v8::Local<v8::Object> target) { NodeMidiOutput::Init(target); NodeMidiInput::Init(target); } NODE_MODULE(midi, init) }
Fix errors and deprecations for node 12.
Fix errors and deprecations for node 12.
C++
mit
Cycling74/node-midi,Cycling74/node-midi,justinlatimer/node-midi,Cycling74/node-midi,justinlatimer/node-midi,justinlatimer/node-midi,Cycling74/node-midi,Cycling74/node-midi,Cycling74/node-midi
076851b74bee39d0c911a344063f5e4731dda28a
modules/gui/skins2/utils/var_tree.cpp
modules/gui/skins2/utils/var_tree.cpp
/***************************************************************************** * var_tree.cpp ***************************************************************************** * Copyright (C) 2005 the VideoLAN team * $Id$ * * Authors: Antoine Cellerier <[email protected]> * Clément Stenac <[email protected]> * Erwan Tulou <[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 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ #include "var_tree.hpp" #include <math.h> const string VarTree::m_type = "tree"; VarTree::VarTree( intf_thread_t *pIntf ) : Variable( pIntf ), m_pParent( NULL ), m_id( 0 ), m_readonly( false ), m_selected( false ), m_playing( false ), m_expanded( false ), m_flat( false ), m_dontMove( false ) { // Create the position variable m_cPosition = VariablePtr( new VarPercent( pIntf ) ); getPositionVar().set( 1.0 ); getPositionVar().addObserver( this ); } VarTree::VarTree( intf_thread_t *pIntf, VarTree *pParent, int id, const UStringPtr &rcString, bool selected, bool playing, bool expanded, bool readonly ) : Variable( pIntf ), m_pParent( pParent ), m_id( id ), m_cString( rcString ), m_readonly( readonly ), m_selected( selected ), m_playing( playing ), m_expanded( expanded ), m_flat( false ), m_dontMove( false ) { // Create the position variable m_cPosition = VariablePtr( new VarPercent( pIntf ) ); getPositionVar().set( 1.0 ); getPositionVar().addObserver( this ); } VarTree::VarTree( const VarTree& v ) : Variable( v.getIntf() ), m_pParent( v.m_pParent ), m_id( v.m_id ), m_cString( v.m_cString ), m_readonly( v.m_readonly ), m_selected( v.m_selected ), m_playing( v.m_playing ), m_expanded( v.m_expanded ), m_flat( false ), m_dontMove( false ) { // Create the position variable m_cPosition = VariablePtr( new VarPercent( getIntf() ) ); getPositionVar().set( 1.0 ); getPositionVar().addObserver( this ); } VarTree::~VarTree() { getPositionVar().delObserver( this ); } VarTree::Iterator VarTree::add( int id, const UStringPtr &rcString, bool selected, bool playing, bool expanded, bool readonly, int pos ) { Iterator it; if( pos == -1 ) { it = m_children.end(); } else { it = m_children.begin(); for( int i = 0; i < pos && it != m_children.end(); ++it, i++ ); } return m_children.insert( it, VarTree( getIntf(), this, id, rcString, selected, playing, expanded, readonly ) ); } void VarTree::delSelected() { for( Iterator it = m_children.begin(); it != m_children.end(); ) { if( it->m_selected ) { Iterator oldIt = it; ++it; m_children.erase( oldIt ); } } } void VarTree::clear() { m_children.clear(); } VarTree::Iterator VarTree::getNextSiblingOrUncle() { VarTree *p_parent = parent(); if( p_parent ) { Iterator it = ++(getSelf()); if( it != p_parent->m_children.end() ) return it; else return next_uncle(); } return root()->m_children.end(); } VarTree::Iterator VarTree::getPrevSiblingOrUncle() { VarTree *p_parent = parent(); if( p_parent ) { Iterator it = getSelf(); if( it != p_parent->m_children.begin() ) return --it; else return prev_uncle(); } return root()->m_children.end(); } /* find iterator to next ancestor * ... which means parent++ or grandparent++ or grandgrandparent++ ... */ VarTree::Iterator VarTree::next_uncle() { VarTree *p_parent = parent(); if( p_parent ) { VarTree *p_grandparent = p_parent->parent(); while( p_grandparent ) { Iterator it = ++(p_parent->getSelf()); if( it != p_grandparent->m_children.end() ) return it; p_parent = p_grandparent; p_grandparent = p_parent->parent(); } } /* if we didn't return before, it means that we've reached the end */ return root()->m_children.end(); } VarTree::Iterator VarTree::prev_uncle() { VarTree *p_parent = parent(); if( p_parent ) { VarTree *p_grandparent = p_parent->parent(); while( p_grandparent ) { Iterator it = p_parent->getSelf(); if( it != p_grandparent->m_children.begin() ) return --it; p_parent = p_grandparent; p_grandparent = p_parent->parent(); } } /* if we didn't return before, it means that we've reached the end */ return root()->m_children.end(); } int VarTree::visibleItems() { int i_count = size(); for( Iterator it = m_children.begin(); it != m_children.end(); ++it ) { if( it->m_expanded ) { i_count += it->visibleItems(); } } return i_count; } VarTree::Iterator VarTree::getVisibleItem( int n ) { Iterator it = m_children.begin(); while( it != m_children.end() ) { n--; if( n <= 0 ) return it; if( it->m_expanded ) { int i; i = n - it->visibleItems(); if( i <= 0 ) return it->getVisibleItem( n ); n = i; } ++it; } return m_children.end(); } VarTree::Iterator VarTree::getLeaf( int n ) { Iterator it = m_children.begin(); while( it != m_children.end() ) { if( it->size() ) { int i; i = n - it->countLeafs(); if( i <= 0 ) return it->getLeaf( n ); n = i; } else { n--; if( n <= 0 ) return it; } ++it; } return m_children.end(); } VarTree::Iterator VarTree::getNextVisibleItem( Iterator it ) { if( it->m_expanded && it->size() ) { it = it->m_children.begin(); } else { Iterator it_old = it; ++it; // Was 'it' the last brother? If so, look for uncles if( it_old->parent() && it_old->parent()->m_children.end() == it ) { it = it_old->next_uncle(); } } return it; } VarTree::Iterator VarTree::getPrevVisibleItem( Iterator it ) { if( it == root()->m_children.begin() ) return it; if( it == root()->m_children.end() ) { --it; while( it->size() && it->m_expanded ) it = --(it->m_children.end()); return it; } /* Was it the first child of its parent ? */ VarTree *p_parent = it->parent(); if( it == p_parent->m_children.begin() ) { /* Yes, get its parent's it */ it = p_parent->getSelf(); } else { --it; /* We have found an older brother, take its last visible child */ while( it->size() && it->m_expanded ) it = --(it->m_children.end()); } return it; } VarTree::Iterator VarTree::getNextItem( Iterator it ) { if( it->size() ) { it = it->m_children.begin(); } else { Iterator it_old = it; ++it; // Was 'it' the last brother? If so, look for uncles if( it_old->parent() && it_old->parent()->m_children.end() == it ) { it = it_old->next_uncle(); } } return it; } VarTree::Iterator VarTree::getPrevItem( Iterator it ) { if( it == root()->m_children.begin() ) return it; if( it == root()->m_children.end() ) { --it; while( it->size() ) it = --(it->m_children.end()); return it; } /* Was it the first child of its parent ? */ VarTree *p_parent = it->parent(); if( it == p_parent->m_children.begin() ) { /* Yes, get its parent's it */ it = p_parent->getSelf(); } else { --it; /* We have found an older brother, take its last child */ while( it->size() ) it = --(it->m_children.end()); } return it; } VarTree::Iterator VarTree::getNextLeaf( Iterator it ) { do { it = getNextItem( it ); } while( it != root()->m_children.end() && it->size() ); return it; } VarTree::Iterator VarTree::getPrevLeaf( Iterator it ) { Iterator it_new = it->getPrevSiblingOrUncle(); if( it_new == root()->end() ) return it_new; while( it_new->size() ) it_new = --(it_new->m_children.end()); return it_new; } VarTree::Iterator VarTree::getParent( Iterator it ) { if( it->parent() ) { return it->parent()->getSelf(); } return m_children.end(); } void VarTree::ensureExpanded( const Iterator& it ) { /// Don't expand ourselves, only our parents VarTree *current = &(*it); current = current->parent(); while( current->parent() ) { current->m_expanded = true; current = current->parent(); } } int VarTree::countLeafs() { if( size() == 0 ) return 1; int i_count = 0; for( Iterator it = m_children.begin(); it != m_children.end(); ++it ) { i_count += it->countLeafs(); } return i_count; } VarTree::Iterator VarTree::firstLeaf() { Iterator b = root()->m_children.begin(); if( b->size() ) return getNextLeaf( b ); return b; } int VarTree::getIndex( const Iterator& item ) { int index = 0; Iterator it; for( it = m_flat ? firstLeaf() : m_children.begin(); it != m_children.end(); it = m_flat ? getNextLeaf( it ) : getNextVisibleItem( it ) ) { if( it == item ) break; index++; } return (it == item) ? index : -1; } VarTree::Iterator VarTree::getItemFromSlider() { // a simple (int)(...) causes rounding errors ! #ifdef _MSC_VER # define lrint (int) #endif VarPercent &rVarPos = getPositionVar(); double percentage = rVarPos.get(); int indexMax = m_flat ? (countLeafs() - 1) : (visibleItems() - 1); int index = lrint( (1.0 - percentage)*(double)indexMax ); Iterator it_first = m_flat ? getLeaf( index + 1 ) : getVisibleItem( index + 1 ); return it_first; } void VarTree::setSliderFromItem( const Iterator& it ) { VarPercent &rVarPos = getPositionVar(); int indexMax = m_flat ? (countLeafs() - 1) : (visibleItems() - 1); int index = getIndex( it ); double percentage = (1.0 - (double)index/(double)indexMax); m_dontMove = true; rVarPos.set( (float)percentage ); m_dontMove = false; } void VarTree::onUpdate( Subject<VarPercent> &rPercent, void* arg ) { (void)rPercent; (void)arg; onUpdateSlider(); } void VarTree::unselectTree() { m_selected = false; for( Iterator it = m_children.begin(); it != m_children.end(); ++it ) it->unselectTree(); } VarTree::IteratorVisible VarTree::getItem( int index ) { Iterator it = m_flat ? getLeaf( index + 1 ) : getVisibleItem( index + 1 ); return IteratorVisible( it, this ); }
/***************************************************************************** * var_tree.cpp ***************************************************************************** * Copyright (C) 2005 the VideoLAN team * $Id$ * * Authors: Antoine Cellerier <[email protected]> * Clément Stenac <[email protected]> * Erwan Tulou <[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 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ #include "var_tree.hpp" #include <math.h> const string VarTree::m_type = "tree"; VarTree::VarTree( intf_thread_t *pIntf ) : Variable( pIntf ), m_pParent( NULL ), m_id( 0 ), m_readonly( false ), m_selected( false ), m_playing( false ), m_expanded( false ), m_flat( false ), m_dontMove( false ) { // Create the position variable m_cPosition = VariablePtr( new VarPercent( pIntf ) ); getPositionVar().set( 1.0 ); getPositionVar().addObserver( this ); } VarTree::VarTree( intf_thread_t *pIntf, VarTree *pParent, int id, const UStringPtr &rcString, bool selected, bool playing, bool expanded, bool readonly ) : Variable( pIntf ), m_pParent( pParent ), m_id( id ), m_cString( rcString ), m_readonly( readonly ), m_selected( selected ), m_playing( playing ), m_expanded( expanded ), m_flat( false ), m_dontMove( false ) { // Create the position variable m_cPosition = VariablePtr( new VarPercent( pIntf ) ); getPositionVar().set( 1.0 ); getPositionVar().addObserver( this ); } VarTree::VarTree( const VarTree& v ) : Variable( v.getIntf() ), m_children( v.m_children), m_pParent( v.m_pParent ), m_id( v.m_id ), m_cString( v.m_cString ), m_readonly( v.m_readonly ), m_selected( v.m_selected ), m_playing( v.m_playing ), m_expanded( v.m_expanded ), m_flat( false ), m_dontMove( false ) { // Create the position variable m_cPosition = VariablePtr( new VarPercent( getIntf() ) ); getPositionVar().set( 1.0 ); getPositionVar().addObserver( this ); } VarTree::~VarTree() { getPositionVar().delObserver( this ); } VarTree::Iterator VarTree::add( int id, const UStringPtr &rcString, bool selected, bool playing, bool expanded, bool readonly, int pos ) { Iterator it; if( pos == -1 ) { it = m_children.end(); } else { it = m_children.begin(); for( int i = 0; i < pos && it != m_children.end(); ++it, i++ ); } return m_children.insert( it, VarTree( getIntf(), this, id, rcString, selected, playing, expanded, readonly ) ); } void VarTree::delSelected() { for( Iterator it = m_children.begin(); it != m_children.end(); ) { if( it->m_selected ) { Iterator oldIt = it; ++it; m_children.erase( oldIt ); } } } void VarTree::clear() { m_children.clear(); } VarTree::Iterator VarTree::getNextSiblingOrUncle() { VarTree *p_parent = parent(); if( p_parent ) { Iterator it = ++(getSelf()); if( it != p_parent->m_children.end() ) return it; else return next_uncle(); } return root()->m_children.end(); } VarTree::Iterator VarTree::getPrevSiblingOrUncle() { VarTree *p_parent = parent(); if( p_parent ) { Iterator it = getSelf(); if( it != p_parent->m_children.begin() ) return --it; else return prev_uncle(); } return root()->m_children.end(); } /* find iterator to next ancestor * ... which means parent++ or grandparent++ or grandgrandparent++ ... */ VarTree::Iterator VarTree::next_uncle() { VarTree *p_parent = parent(); if( p_parent ) { VarTree *p_grandparent = p_parent->parent(); while( p_grandparent ) { Iterator it = ++(p_parent->getSelf()); if( it != p_grandparent->m_children.end() ) return it; p_parent = p_grandparent; p_grandparent = p_parent->parent(); } } /* if we didn't return before, it means that we've reached the end */ return root()->m_children.end(); } VarTree::Iterator VarTree::prev_uncle() { VarTree *p_parent = parent(); if( p_parent ) { VarTree *p_grandparent = p_parent->parent(); while( p_grandparent ) { Iterator it = p_parent->getSelf(); if( it != p_grandparent->m_children.begin() ) return --it; p_parent = p_grandparent; p_grandparent = p_parent->parent(); } } /* if we didn't return before, it means that we've reached the end */ return root()->m_children.end(); } int VarTree::visibleItems() { int i_count = size(); for( Iterator it = m_children.begin(); it != m_children.end(); ++it ) { if( it->m_expanded ) { i_count += it->visibleItems(); } } return i_count; } VarTree::Iterator VarTree::getVisibleItem( int n ) { Iterator it = m_children.begin(); while( it != m_children.end() ) { n--; if( n <= 0 ) return it; if( it->m_expanded ) { int i; i = n - it->visibleItems(); if( i <= 0 ) return it->getVisibleItem( n ); n = i; } ++it; } return m_children.end(); } VarTree::Iterator VarTree::getLeaf( int n ) { Iterator it = m_children.begin(); while( it != m_children.end() ) { if( it->size() ) { int i; i = n - it->countLeafs(); if( i <= 0 ) return it->getLeaf( n ); n = i; } else { n--; if( n <= 0 ) return it; } ++it; } return m_children.end(); } VarTree::Iterator VarTree::getNextVisibleItem( Iterator it ) { if( it->m_expanded && it->size() ) { it = it->m_children.begin(); } else { Iterator it_old = it; ++it; // Was 'it' the last brother? If so, look for uncles if( it_old->parent() && it_old->parent()->m_children.end() == it ) { it = it_old->next_uncle(); } } return it; } VarTree::Iterator VarTree::getPrevVisibleItem( Iterator it ) { if( it == root()->m_children.begin() ) return it; if( it == root()->m_children.end() ) { --it; while( it->size() && it->m_expanded ) it = --(it->m_children.end()); return it; } /* Was it the first child of its parent ? */ VarTree *p_parent = it->parent(); if( it == p_parent->m_children.begin() ) { /* Yes, get its parent's it */ it = p_parent->getSelf(); } else { --it; /* We have found an older brother, take its last visible child */ while( it->size() && it->m_expanded ) it = --(it->m_children.end()); } return it; } VarTree::Iterator VarTree::getNextItem( Iterator it ) { if( it->size() ) { it = it->m_children.begin(); } else { Iterator it_old = it; ++it; // Was 'it' the last brother? If so, look for uncles if( it_old->parent() && it_old->parent()->m_children.end() == it ) { it = it_old->next_uncle(); } } return it; } VarTree::Iterator VarTree::getPrevItem( Iterator it ) { if( it == root()->m_children.begin() ) return it; if( it == root()->m_children.end() ) { --it; while( it->size() ) it = --(it->m_children.end()); return it; } /* Was it the first child of its parent ? */ VarTree *p_parent = it->parent(); if( it == p_parent->m_children.begin() ) { /* Yes, get its parent's it */ it = p_parent->getSelf(); } else { --it; /* We have found an older brother, take its last child */ while( it->size() ) it = --(it->m_children.end()); } return it; } VarTree::Iterator VarTree::getNextLeaf( Iterator it ) { do { it = getNextItem( it ); } while( it != root()->m_children.end() && it->size() ); return it; } VarTree::Iterator VarTree::getPrevLeaf( Iterator it ) { Iterator it_new = it->getPrevSiblingOrUncle(); if( it_new == root()->end() ) return it_new; while( it_new->size() ) it_new = --(it_new->m_children.end()); return it_new; } VarTree::Iterator VarTree::getParent( Iterator it ) { if( it->parent() ) { return it->parent()->getSelf(); } return m_children.end(); } void VarTree::ensureExpanded( const Iterator& it ) { /// Don't expand ourselves, only our parents VarTree *current = &(*it); current = current->parent(); while( current->parent() ) { current->m_expanded = true; current = current->parent(); } } int VarTree::countLeafs() { if( size() == 0 ) return 1; int i_count = 0; for( Iterator it = m_children.begin(); it != m_children.end(); ++it ) { i_count += it->countLeafs(); } return i_count; } VarTree::Iterator VarTree::firstLeaf() { Iterator b = root()->m_children.begin(); if( b->size() ) return getNextLeaf( b ); return b; } int VarTree::getIndex( const Iterator& item ) { int index = 0; Iterator it; for( it = m_flat ? firstLeaf() : m_children.begin(); it != m_children.end(); it = m_flat ? getNextLeaf( it ) : getNextVisibleItem( it ) ) { if( it == item ) break; index++; } return (it == item) ? index : -1; } VarTree::Iterator VarTree::getItemFromSlider() { // a simple (int)(...) causes rounding errors ! #ifdef _MSC_VER # define lrint (int) #endif VarPercent &rVarPos = getPositionVar(); double percentage = rVarPos.get(); int indexMax = m_flat ? (countLeafs() - 1) : (visibleItems() - 1); int index = lrint( (1.0 - percentage)*(double)indexMax ); Iterator it_first = m_flat ? getLeaf( index + 1 ) : getVisibleItem( index + 1 ); return it_first; } void VarTree::setSliderFromItem( const Iterator& it ) { VarPercent &rVarPos = getPositionVar(); int indexMax = m_flat ? (countLeafs() - 1) : (visibleItems() - 1); int index = getIndex( it ); double percentage = (1.0 - (double)index/(double)indexMax); m_dontMove = true; rVarPos.set( (float)percentage ); m_dontMove = false; } void VarTree::onUpdate( Subject<VarPercent> &rPercent, void* arg ) { (void)rPercent; (void)arg; onUpdateSlider(); } void VarTree::unselectTree() { m_selected = false; for( Iterator it = m_children.begin(); it != m_children.end(); ++it ) it->unselectTree(); } VarTree::IteratorVisible VarTree::getItem( int index ) { Iterator it = m_flat ? getLeaf( index + 1 ) : getVisibleItem( index + 1 ); return IteratorVisible( it, this ); }
fix forgotten initialization in copy constructor
skins2: fix forgotten initialization in copy constructor This bug was unnoticed because this constructor is only called in a situation where really copying from origin or leaving it to the compiler to set it via the default constructor leads to the same result (an empty list). Yet, this was a bug. It may solve trac #6599 though, (a Linux port where there is a real initialization issue)
C++
lgpl-2.1
vlc-mirror/vlc-2.1,xkfz007/vlc,shyamalschandra/vlc,shyamalschandra/vlc,krichter722/vlc,vlc-mirror/vlc,vlc-mirror/vlc,jomanmuk/vlc-2.2,jomanmuk/vlc-2.2,jomanmuk/vlc-2.1,xkfz007/vlc,krichter722/vlc,vlc-mirror/vlc-2.1,xkfz007/vlc,krichter722/vlc,shyamalschandra/vlc,vlc-mirror/vlc,jomanmuk/vlc-2.2,krichter722/vlc,vlc-mirror/vlc,shyamalschandra/vlc,xkfz007/vlc,shyamalschandra/vlc,jomanmuk/vlc-2.2,vlc-mirror/vlc-2.1,shyamalschandra/vlc,vlc-mirror/vlc-2.1,vlc-mirror/vlc,xkfz007/vlc,vlc-mirror/vlc,jomanmuk/vlc-2.1,jomanmuk/vlc-2.1,jomanmuk/vlc-2.1,jomanmuk/vlc-2.1,xkfz007/vlc,krichter722/vlc,jomanmuk/vlc-2.1,vlc-mirror/vlc-2.1,jomanmuk/vlc-2.2,krichter722/vlc,krichter722/vlc,jomanmuk/vlc-2.2,shyamalschandra/vlc,jomanmuk/vlc-2.1,xkfz007/vlc,vlc-mirror/vlc-2.1,vlc-mirror/vlc-2.1,jomanmuk/vlc-2.2,vlc-mirror/vlc
bcd15752e30f713525614cec7fc3cabbb250319d
src/child_manager.cxx
src/child_manager.cxx
/* * Central manager for child processes. * * author: Max Kellermann <[email protected]> */ #include "child_manager.hxx" #include "crash.hxx" #include "pool.hxx" #include "spawn/ExitListener.hxx" #include "event/TimerEvent.hxx" #include "event/DeferEvent.hxx" #include "event/SignalEvent.hxx" #include "event/Callback.hxx" #include "system/clock.h" #include "util/DeleteDisposer.hxx" #include <daemon/log.h> #include <daemon/daemonize.h> #include <boost/intrusive/set.hpp> #include <string> #include <assert.h> #include <errno.h> #include <string.h> #include <sys/wait.h> #include <sys/resource.h> struct ChildProcess : boost::intrusive::set_base_hook<boost::intrusive::link_mode<boost::intrusive::normal_link>> { const pid_t pid; const std::string name; /** * The monotonic clock when this child process was started * (registered in this library). */ const uint64_t start_us; ExitListener *listener; /** * This timer is set up by child_kill_signal(). If the child * process hasn't exited after a certain amount of time, we send * SIGKILL. */ TimerEvent kill_timeout_event; ChildProcess(pid_t _pid, const char *_name, ExitListener *_listener) :pid(_pid), name(_name), start_us(now_us()), listener(_listener), kill_timeout_event(MakeSimpleEventCallback(ChildProcess, KillTimeoutCallback), this) {} void OnExit(int status, const struct rusage &rusage); void KillTimeoutCallback(); struct Compare { bool operator()(const ChildProcess &a, const ChildProcess &b) const { return a.pid < b.pid; } bool operator()(const ChildProcess &a, pid_t b) const { return a.pid < b; } bool operator()(pid_t a, const ChildProcess &b) const { return a < b.pid; } }; }; static const struct timeval child_kill_timeout = { .tv_sec = 60, .tv_usec = 0, }; static bool shutdown_flag = false; static boost::intrusive::set<ChildProcess, boost::intrusive::compare<ChildProcess::Compare>, boost::intrusive::constant_time_size<true>> children; static SignalEvent sigchld_event; /** * This event is used by children_event_add() to invoke * child_event_callback() as soon as possible. It is necessary to * catch up with SIGCHLDs that may have been lost while the SIGCHLD * handler was disabled. */ static DeferEvent defer_event; static ChildProcess * find_child_by_pid(pid_t pid) { auto i = children.find(pid, ChildProcess::Compare()); if (i == children.end()) return nullptr; return &*i; } static void child_remove(ChildProcess &child) { assert(!children.empty()); child.kill_timeout_event.Cancel(); children.erase(children.iterator_to(child)); if (shutdown_flag && children.empty()) children_event_del(); } static void child_abandon(ChildProcess &child) { child_remove(child); delete &child; } gcc_pure static double timeval_to_double(const struct timeval *tv) { return tv->tv_sec + tv->tv_usec / 1000000.; } inline void ChildProcess::OnExit(int status, const struct rusage &rusage) { const int exit_status = WEXITSTATUS(status); if (WIFSIGNALED(status)) { int level = 1; if (!WCOREDUMP(status) && WTERMSIG(status) == SIGTERM) level = 4; daemon_log(level, "child process '%s' (pid %d) died from signal %d%s\n", name.c_str(), (int)pid, WTERMSIG(status), WCOREDUMP(status) ? " (core dumped)" : ""); } else if (exit_status == 0) daemon_log(5, "child process '%s' (pid %d) exited with success\n", name.c_str(), (int)pid); else daemon_log(2, "child process '%s' (pid %d) exited with status %d\n", name.c_str(), (int)pid, exit_status); daemon_log(6, "stats on '%s' (pid %d): %1.3fs elapsed, %1.3fs user, %1.3fs sys, %ld/%ld faults, %ld/%ld switches\n", name.c_str(), (int)pid, (now_us() - start_us) / 1000000., timeval_to_double(&rusage.ru_utime), timeval_to_double(&rusage.ru_stime), rusage.ru_minflt, rusage.ru_majflt, rusage.ru_nvcsw, rusage.ru_nivcsw); if (listener != nullptr) listener->OnChildProcessExit(status); } inline void ChildProcess::KillTimeoutCallback() { daemon_log(3, "sending SIGKILL to child process '%s' (pid %d) due to timeout\n", name.c_str(), (int)pid); if (kill(pid, SIGKILL) < 0) daemon_log(1, "failed to kill child process '%s' (pid %d): %s\n", name.c_str(), (int)pid, strerror(errno)); } static void child_event_callback(int fd gcc_unused, short event gcc_unused, void *ctx gcc_unused) { pid_t pid; int status; struct rusage rusage; while ((pid = wait4(-1, &status, WNOHANG, &rusage)) > 0) { if (daemonize_child_exited(pid, status)) continue; ChildProcess *child = find_child_by_pid(pid); if (child != nullptr) { child_remove(*child); child->OnExit(status, rusage); delete child; } } pool_commit(); } void children_init() { assert(!shutdown_flag); defer_event.Init(child_event_callback, nullptr); children_event_add(); } void children_deinit() { children_event_del(); shutdown_flag = false; } void children_clear() { children.clear_and_dispose(DeleteDisposer()); } void children_shutdown(void) { defer_event.Deinit(); shutdown_flag = true; if (children.empty()) children_event_del(); } void children_event_add(void) { assert(!shutdown_flag); sigchld_event.Set(SIGCHLD, child_event_callback, nullptr); sigchld_event.Add(); /* schedule an immediate waitpid() run, just in case we lost a SIGCHLD */ defer_event.Add(); } void children_event_del(void) { sigchld_event.Delete(); defer_event.Cancel(); } void child_register(pid_t pid, const char *name, ExitListener *listener) { assert(!shutdown_flag); assert(name != nullptr); daemon_log(5, "added child process '%s' (pid %d)\n", name, (int)pid); auto child = new ChildProcess(pid, name, listener); children.insert(*child); } void child_kill_signal(pid_t pid, int signo) { ChildProcess *child = find_child_by_pid(pid); assert(child != nullptr); assert(child->listener != nullptr); daemon_log(5, "sending %s to child process '%s' (pid %d)\n", strsignal(signo), child->name.c_str(), (int)pid); child->listener = nullptr; if (kill(pid, signo) < 0) { daemon_log(1, "failed to kill child process '%s' (pid %d): %s\n", child->name.c_str(), (int)pid, strerror(errno)); /* if we can't kill the process, we can't do much, so let's just ignore the process from now on and don't let it delay the shutdown */ child_abandon(*child); return; } child->kill_timeout_event.Add(child_kill_timeout); } void child_kill(pid_t pid) { child_kill_signal(pid, SIGTERM); } unsigned child_get_count(void) { return children.size(); }
/* * Central manager for child processes. * * author: Max Kellermann <[email protected]> */ #include "child_manager.hxx" #include "crash.hxx" #include "pool.hxx" #include "spawn/ExitListener.hxx" #include "event/TimerEvent.hxx" #include "event/SignalEvent.hxx" #include "event/Callback.hxx" #include "system/clock.h" #include "util/DeleteDisposer.hxx" #include <daemon/log.h> #include <daemon/daemonize.h> #include <boost/intrusive/set.hpp> #include <string> #include <assert.h> #include <errno.h> #include <string.h> #include <sys/wait.h> #include <sys/resource.h> struct ChildProcess : boost::intrusive::set_base_hook<boost::intrusive::link_mode<boost::intrusive::normal_link>> { const pid_t pid; const std::string name; /** * The monotonic clock when this child process was started * (registered in this library). */ const uint64_t start_us; ExitListener *listener; /** * This timer is set up by child_kill_signal(). If the child * process hasn't exited after a certain amount of time, we send * SIGKILL. */ TimerEvent kill_timeout_event; ChildProcess(pid_t _pid, const char *_name, ExitListener *_listener) :pid(_pid), name(_name), start_us(now_us()), listener(_listener), kill_timeout_event(MakeSimpleEventCallback(ChildProcess, KillTimeoutCallback), this) {} void OnExit(int status, const struct rusage &rusage); void KillTimeoutCallback(); struct Compare { bool operator()(const ChildProcess &a, const ChildProcess &b) const { return a.pid < b.pid; } bool operator()(const ChildProcess &a, pid_t b) const { return a.pid < b; } bool operator()(pid_t a, const ChildProcess &b) const { return a < b.pid; } }; }; static const struct timeval child_kill_timeout = { .tv_sec = 60, .tv_usec = 0, }; static bool shutdown_flag = false; static boost::intrusive::set<ChildProcess, boost::intrusive::compare<ChildProcess::Compare>, boost::intrusive::constant_time_size<true>> children; static SignalEvent sigchld_event; static ChildProcess * find_child_by_pid(pid_t pid) { auto i = children.find(pid, ChildProcess::Compare()); if (i == children.end()) return nullptr; return &*i; } static void child_remove(ChildProcess &child) { assert(!children.empty()); child.kill_timeout_event.Cancel(); children.erase(children.iterator_to(child)); if (shutdown_flag && children.empty()) children_event_del(); } static void child_abandon(ChildProcess &child) { child_remove(child); delete &child; } gcc_pure static double timeval_to_double(const struct timeval *tv) { return tv->tv_sec + tv->tv_usec / 1000000.; } inline void ChildProcess::OnExit(int status, const struct rusage &rusage) { const int exit_status = WEXITSTATUS(status); if (WIFSIGNALED(status)) { int level = 1; if (!WCOREDUMP(status) && WTERMSIG(status) == SIGTERM) level = 4; daemon_log(level, "child process '%s' (pid %d) died from signal %d%s\n", name.c_str(), (int)pid, WTERMSIG(status), WCOREDUMP(status) ? " (core dumped)" : ""); } else if (exit_status == 0) daemon_log(5, "child process '%s' (pid %d) exited with success\n", name.c_str(), (int)pid); else daemon_log(2, "child process '%s' (pid %d) exited with status %d\n", name.c_str(), (int)pid, exit_status); daemon_log(6, "stats on '%s' (pid %d): %1.3fs elapsed, %1.3fs user, %1.3fs sys, %ld/%ld faults, %ld/%ld switches\n", name.c_str(), (int)pid, (now_us() - start_us) / 1000000., timeval_to_double(&rusage.ru_utime), timeval_to_double(&rusage.ru_stime), rusage.ru_minflt, rusage.ru_majflt, rusage.ru_nvcsw, rusage.ru_nivcsw); if (listener != nullptr) listener->OnChildProcessExit(status); } inline void ChildProcess::KillTimeoutCallback() { daemon_log(3, "sending SIGKILL to child process '%s' (pid %d) due to timeout\n", name.c_str(), (int)pid); if (kill(pid, SIGKILL) < 0) daemon_log(1, "failed to kill child process '%s' (pid %d): %s\n", name.c_str(), (int)pid, strerror(errno)); } static void child_event_callback(int fd gcc_unused, short event gcc_unused, void *ctx gcc_unused) { pid_t pid; int status; struct rusage rusage; while ((pid = wait4(-1, &status, WNOHANG, &rusage)) > 0) { if (daemonize_child_exited(pid, status)) continue; ChildProcess *child = find_child_by_pid(pid); if (child != nullptr) { child_remove(*child); child->OnExit(status, rusage); delete child; } } pool_commit(); } void children_init() { assert(!shutdown_flag); children_event_add(); } void children_deinit() { children_event_del(); shutdown_flag = false; } void children_clear() { children.clear_and_dispose(DeleteDisposer()); } void children_shutdown(void) { shutdown_flag = true; if (children.empty()) children_event_del(); } void children_event_add(void) { assert(!shutdown_flag); sigchld_event.Set(SIGCHLD, child_event_callback, nullptr); sigchld_event.Add(); } void children_event_del(void) { sigchld_event.Delete(); } void child_register(pid_t pid, const char *name, ExitListener *listener) { assert(!shutdown_flag); assert(name != nullptr); daemon_log(5, "added child process '%s' (pid %d)\n", name, (int)pid); auto child = new ChildProcess(pid, name, listener); children.insert(*child); } void child_kill_signal(pid_t pid, int signo) { ChildProcess *child = find_child_by_pid(pid); assert(child != nullptr); assert(child->listener != nullptr); daemon_log(5, "sending %s to child process '%s' (pid %d)\n", strsignal(signo), child->name.c_str(), (int)pid); child->listener = nullptr; if (kill(pid, signo) < 0) { daemon_log(1, "failed to kill child process '%s' (pid %d): %s\n", child->name.c_str(), (int)pid, strerror(errno)); /* if we can't kill the process, we can't do much, so let's just ignore the process from now on and don't let it delay the shutdown */ child_abandon(*child); return; } child->kill_timeout_event.Add(child_kill_timeout); } void child_kill(pid_t pid) { child_kill_signal(pid, SIGTERM); } unsigned child_get_count(void) { return children.size(); }
remove defer_event, obsolete
child_manager: remove defer_event, obsolete
C++
bsd-2-clause
CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy
2e393ab83362743ba1825ad4b31d4a2925c606b4
modules/superres/src/frame_source.cpp
modules/superres/src/frame_source.cpp
/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) however caused // and on any theory of liability, whether in contract, strict liability, // or tort (including negligence or otherwise) arising in any way out of // the use of this software, even if advised of the possibility of such damage. // //M*/ #include "precomp.hpp" using namespace std; using namespace cv; using namespace cv::gpu; using namespace cv::superres; using namespace cv::superres::detail; cv::superres::FrameSource::~FrameSource() { } ////////////////////////////////////////////////////// // EmptyFrameSource namespace { class EmptyFrameSource : public FrameSource { public: void nextFrame(OutputArray frame); void reset(); }; void EmptyFrameSource::nextFrame(OutputArray frame) { frame.release(); } void EmptyFrameSource::reset() { } } Ptr<FrameSource> cv::superres::createFrameSource_Empty() { return new EmptyFrameSource; } ////////////////////////////////////////////////////// // VideoFrameSource & CameraFrameSource #ifndef HAVE_OPENCV_HIGHGUI Ptr<FrameSource> cv::superres::createFrameSource_Video(const string& fileName) { (void) fileName; CV_Error(CV_StsNotImplemented, "The called functionality is disabled for current build or platform"); return Ptr<FrameSource>(); } Ptr<FrameSource> cv::superres::createFrameSource_Camera(int deviceId) { (void) deviceId; CV_Error(CV_StsNotImplemented, "The called functionality is disabled for current build or platform"); return Ptr<FrameSource>(); } #else // HAVE_OPENCV_HIGHGUI namespace { class CaptureFrameSource : public FrameSource { public: void nextFrame(OutputArray frame); protected: VideoCapture vc_; private: Mat frame_; }; void CaptureFrameSource::nextFrame(OutputArray _frame) { if (_frame.kind() == _InputArray::MAT) { vc_ >> _frame.getMatRef(); } else if(_frame.kind() == _InputArray::GPU_MAT) { vc_ >> frame_; arrCopy(frame_, _frame); } else if(_frame.kind() == _InputArray::OCL_MAT) { vc_ >> frame_; if(!frame_.empty()) { arrCopy(frame_, _frame); } } else { //should never get here } } class VideoFrameSource : public CaptureFrameSource { public: VideoFrameSource(const string& fileName); void reset(); private: string fileName_; }; VideoFrameSource::VideoFrameSource(const string& fileName) : fileName_(fileName) { reset(); } void VideoFrameSource::reset() { vc_.release(); vc_.open(fileName_); CV_Assert( vc_.isOpened() ); } class CameraFrameSource : public CaptureFrameSource { public: CameraFrameSource(int deviceId); void reset(); private: int deviceId_; }; CameraFrameSource::CameraFrameSource(int deviceId) : deviceId_(deviceId) { reset(); } void CameraFrameSource::reset() { vc_.release(); vc_.open(deviceId_); CV_Assert( vc_.isOpened() ); } } Ptr<FrameSource> cv::superres::createFrameSource_Video(const string& fileName) { return new VideoFrameSource(fileName); } Ptr<FrameSource> cv::superres::createFrameSource_Camera(int deviceId) { return new CameraFrameSource(deviceId); } #endif // HAVE_OPENCV_HIGHGUI ////////////////////////////////////////////////////// // VideoFrameSource_GPU #if !defined(HAVE_OPENCV_GPU) || defined(DYNAMIC_CUDA_SUPPORT) Ptr<FrameSource> cv::superres::createFrameSource_Video_GPU(const string& fileName) { (void) fileName; CV_Error(CV_StsNotImplemented, "The called functionality is disabled for current build or platform"); return Ptr<FrameSource>(); } #else // HAVE_OPENCV_GPU namespace { class VideoFrameSource_GPU : public FrameSource { public: VideoFrameSource_GPU(const string& fileName); void nextFrame(OutputArray frame); void reset(); private: string fileName_; VideoReader_GPU reader_; GpuMat frame_; }; VideoFrameSource_GPU::VideoFrameSource_GPU(const string& fileName) : fileName_(fileName) { reset(); } void VideoFrameSource_GPU::nextFrame(OutputArray _frame) { if (_frame.kind() == _InputArray::GPU_MAT) { bool res = reader_.read(_frame.getGpuMatRef()); if (!res) _frame.release(); } else { bool res = reader_.read(frame_); if (!res) _frame.release(); else arrCopy(frame_, _frame); } } void VideoFrameSource_GPU::reset() { reader_.close(); reader_.open(fileName_); CV_Assert( reader_.isOpened() ); } } Ptr<FrameSource> cv::superres::createFrameSource_Video_GPU(const string& fileName) { return new VideoFrameSource(fileName); } #endif // HAVE_OPENCV_GPU
/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) however caused // and on any theory of liability, whether in contract, strict liability, // or tort (including negligence or otherwise) arising in any way out of // the use of this software, even if advised of the possibility of such damage. // //M*/ #include "precomp.hpp" using namespace std; using namespace cv; using namespace cv::gpu; using namespace cv::superres; using namespace cv::superres::detail; cv::superres::FrameSource::~FrameSource() { } ////////////////////////////////////////////////////// // EmptyFrameSource namespace { class EmptyFrameSource : public FrameSource { public: void nextFrame(OutputArray frame); void reset(); }; void EmptyFrameSource::nextFrame(OutputArray frame) { frame.release(); } void EmptyFrameSource::reset() { } } Ptr<FrameSource> cv::superres::createFrameSource_Empty() { return new EmptyFrameSource; } ////////////////////////////////////////////////////// // VideoFrameSource & CameraFrameSource #ifndef HAVE_OPENCV_HIGHGUI Ptr<FrameSource> cv::superres::createFrameSource_Video(const string& fileName) { (void) fileName; CV_Error(CV_StsNotImplemented, "The called functionality is disabled for current build or platform"); return Ptr<FrameSource>(); } Ptr<FrameSource> cv::superres::createFrameSource_Camera(int deviceId) { (void) deviceId; CV_Error(CV_StsNotImplemented, "The called functionality is disabled for current build or platform"); return Ptr<FrameSource>(); } #else // HAVE_OPENCV_HIGHGUI namespace { class CaptureFrameSource : public FrameSource { public: void nextFrame(OutputArray frame); protected: VideoCapture vc_; private: Mat frame_; }; void CaptureFrameSource::nextFrame(OutputArray _frame) { if (_frame.kind() == _InputArray::MAT) { vc_ >> _frame.getMatRef(); } else if(_frame.kind() == _InputArray::GPU_MAT) { vc_ >> frame_; arrCopy(frame_, _frame); } else if(_frame.kind() == _InputArray::OCL_MAT) { vc_ >> frame_; if(!frame_.empty()) { arrCopy(frame_, _frame); } } else { //should never get here } } class VideoFrameSource : public CaptureFrameSource { public: VideoFrameSource(const string& fileName); void reset(); private: string fileName_; }; VideoFrameSource::VideoFrameSource(const string& fileName) : fileName_(fileName) { reset(); } void VideoFrameSource::reset() { vc_.release(); vc_.open(fileName_); CV_Assert( vc_.isOpened() ); } class CameraFrameSource : public CaptureFrameSource { public: CameraFrameSource(int deviceId); void reset(); private: int deviceId_; }; CameraFrameSource::CameraFrameSource(int deviceId) : deviceId_(deviceId) { reset(); } void CameraFrameSource::reset() { vc_.release(); vc_.open(deviceId_); CV_Assert( vc_.isOpened() ); } } Ptr<FrameSource> cv::superres::createFrameSource_Video(const string& fileName) { return new VideoFrameSource(fileName); } Ptr<FrameSource> cv::superres::createFrameSource_Camera(int deviceId) { return new CameraFrameSource(deviceId); } #endif // HAVE_OPENCV_HIGHGUI ////////////////////////////////////////////////////// // VideoFrameSource_GPU #if !defined(HAVE_OPENCV_GPU) || defined(DYNAMIC_CUDA_SUPPORT) Ptr<FrameSource> cv::superres::createFrameSource_Video_GPU(const string& fileName) { (void) fileName; CV_Error(CV_StsNotImplemented, "The called functionality is disabled for current build or platform"); return Ptr<FrameSource>(); } #else // HAVE_OPENCV_GPU namespace { class VideoFrameSource_GPU : public FrameSource { public: VideoFrameSource_GPU(const string& fileName); void nextFrame(OutputArray frame); void reset(); private: string fileName_; VideoReader_GPU reader_; GpuMat frame_; }; VideoFrameSource_GPU::VideoFrameSource_GPU(const string& fileName) : fileName_(fileName) { reset(); } void VideoFrameSource_GPU::nextFrame(OutputArray _frame) { if (_frame.kind() == _InputArray::GPU_MAT) { bool res = reader_.read(_frame.getGpuMatRef()); if (!res) _frame.release(); } else { bool res = reader_.read(frame_); if (!res) _frame.release(); else arrCopy(frame_, _frame); } } void VideoFrameSource_GPU::reset() { reader_.close(); reader_.open(fileName_); CV_Assert( reader_.isOpened() ); } } Ptr<FrameSource> cv::superres::createFrameSource_Video_GPU(const string& fileName) { return new VideoFrameSource_GPU(fileName); } #endif // HAVE_OPENCV_GPU
Fix return value VideoFrameSource_GPU
superres: Fix return value VideoFrameSource_GPU superres module fails to compile with the following error messages: [100%] Building CXX object modules/superres/CMakeFiles/opencv_superres.dir/src/super_resolution.cpp.o /opencv-2.4.10/modules/superres/src/frame_source.cpp: In function 'cv::Ptr<cv::superres::FrameSource> cv::superres::createFrameSource_Video_GPU(const string&)': /opencv-2.4.10/modules/superres/src/frame_source.cpp:263:16: error: expected type-specifier before 'VideoFrameSource' /opencv-2.4.10/modules/superres/src/frame_source.cpp:263:16: error: could not convert '(int*)operator new(4ul)' from 'int*' to 'cv::Ptr<cv::superres::FrameSource>' /opencv-2.4.10/modules/superres/src/frame_source.cpp:263:16: error: expected ';' before 'VideoFrameSource' /opencv-2.4.10/modules/superres/src/frame_source.cpp:263:41: error: 'VideoFrameSource' was not declared in this scope /opencv-2.4.10/modules/superres/src/frame_source.cpp:264:1: error: control reaches end of non-void function [-Werror=return-type] cc1plus: some warnings being treated as errors make[3]: *** [modules/superres/CMakeFiles/opencv_superres.dir/src/frame_source.cpp.o] Error 1 make[3]: *** Waiting for unfinished jobs.... This is caused because the return value of the createFrameSource_Video_GPU function should be a VideoFrameSource_GPU object.
C++
apache-2.0
opencv/opencv,opencv/opencv,opencv/opencv,opencv/opencv,opencv/opencv,opencv/opencv,opencv/opencv,opencv/opencv,opencv/opencv,opencv/opencv
c9953e57301ed46b5082e1170e6609c8d7c1d5d5
src/osuar_ground_station/osuar_vision/src/squares.cpp
src/osuar_ground_station/osuar_vision/src/squares.cpp
// The "Square Detector" program. // It loads several images sequentially and tries to find squares in // each image #include "opencv2/core/core.hpp" #include "opencv2/imgproc/imgproc.hpp" #include "opencv2/highgui/highgui.hpp" #include <iostream> #include <math.h> #include <string.h> #include <stdio.h> #include <ros/ros.h> #include <osuar_vision/windowCoordinates.h> using namespace cv; int thresh = 50, N = 11; // Threshold for maximum cosine between angles (x100). int maxCosineThresh = 25; // Threshold for ratio of shortest side / longest side (x100). int sideRatioThresh = 75; // Find colors of any hue... int wallHueLow = 0; int wallHueHigh = 179; // ...of low saturation... int wallSatLow = 0; int wallSatHigh = 40; // ...ranging down to gray, but not completely dark. That is to say, white. int wallValLow = 50; int wallValHigh = 255; ros::Publisher visPub; osuar_vision::windowCoordinates winCoords; // helper function: // finds a cosine of angle between vectors // from pt0->pt1 and from pt0->pt2 static double angle( Point pt1, Point pt2, Point pt0 ) { double dx1 = pt1.x - pt0.x; double dy1 = pt1.y - pt0.y; double dx2 = pt2.x - pt0.x; double dy2 = pt2.y - pt0.y; return (dx1*dx2 + dy1*dy2)/sqrt((dx1*dx1 + dy1*dy1)*(dx2*dx2 + dy2*dy2) + 1e-10); } // returns sequence of squares detected on the image. // the sequence is stored in the specified memory storage static void findSquares( const Mat& image, vector<vector<Point> >& squares ) { squares.clear(); Mat pyr, timg, gray0(image.size(), CV_8U), gray; // down-scale and upscale the image to filter out the noise pyrDown(image, pyr, Size(image.cols/2, image.rows/2)); pyrUp(pyr, timg, image.size()); vector<vector<Point> > contours; // find squares in every color plane of the image //for( int c = 0; c < 3; c++ ) //{ //int ch[] = {c, 0}; //mixChannels(&timg, 1, &gray0, 1, ch, 1); // try several threshold levels for( int l = 0; l < N; l++ ) { // hack: use Canny instead of zero threshold level. // Canny helps to catch squares with gradient shading if( l == 0 ) { // apply Canny. Take the upper threshold from slider // and set the lower to 0 (which forces edges merging) Canny(image, gray, 0, thresh, 5); // dilate canny output to remove potential // holes between edge segments dilate(gray, gray, Mat(), Point(-1,-1)); } else { // apply threshold if l!=0: // tgray(x,y) = gray(x,y) < (l+1)*255/N ? 255 : 0 gray = image >= (l+1)*255/N; } // find contours and store them all as a list findContours(gray, contours, CV_RETR_LIST, CV_CHAIN_APPROX_SIMPLE); vector<Point> approx; // test each contour for( size_t i = 0; i < contours.size(); i++ ) { // approximate contour with accuracy proportional // to the contour perimeter approxPolyDP(Mat(contours[i]), approx, arcLength(Mat(contours[i]), true)*0.02, true); // square contours should have 4 vertices after approximation // relatively large area (to filter out noisy contours) // and be convex. // Note: absolute value of an area is used because // area may be positive or negative - in accordance with the // contour orientation if( approx.size() == 4 && fabs(contourArea(Mat(approx))) > 1000 && isContourConvex(Mat(approx)) ) { double maxCosine = 0; double minSideLen = 100000; double maxSideLen = 0; double sideRatio = 0; for( int j = 2; j < 5; j++ ) { // find the maximum cosine of the angle between joint edges double cosine = fabs(angle(approx[j%4], approx[j-2], approx[j-1])); maxCosine = MAX(maxCosine, cosine); // Find the maximum difference in length of adjacent // sides double sideLen = sqrt(pow((approx[j%4].x - approx[(j+1)%4].x), 2) + pow((approx[j%4].y - approx[(j+1)%4].y), 2)); minSideLen = MIN(minSideLen, sideLen); maxSideLen = MAX(maxSideLen, sideLen); } sideRatio = minSideLen / maxSideLen; std::cout << minSideLen << " " << maxSideLen << "\n"; // if cosines of all angles are small // (all angles are ~90 degree) then write quandrange // vertices to resultant sequence if( maxCosine < ((double) maxCosineThresh)/100 && sideRatio >= (double) sideRatioThresh/100 ) squares.push_back(approx); } } } //} } // the function draws all the squares in the image static void drawSquares( Mat& image, const vector<vector<Point> >& squares ) { for( size_t i = 0; i < squares.size(); i++ ) { const Point* p = &squares[i][0]; int n = (int)squares[i].size(); polylines(image, &p, &n, 1, true, Scalar(0,255,0), 3, CV_AA); std::cout << "x: " << squares[i][0].x << " y: " << squares[i][0].y << "\n"; // Only publish coordinates for one of the squares. Coordinates are // shifted over by half the camera resolution (which itself is scaled // down by a factor of two!) on each axis. The y coordinate is inverted // so up is positive. if (i == 0) { putText(image, "0", squares[0][0], FONT_HERSHEY_SIMPLEX, 0.5, Scalar(255,0,0)); putText(image, "1", squares[0][1], FONT_HERSHEY_SIMPLEX, 0.5, Scalar(255,0,0)); putText(image, "2", squares[0][2], FONT_HERSHEY_SIMPLEX, 0.5, Scalar(255,0,0)); putText(image, "3", squares[0][3], FONT_HERSHEY_SIMPLEX, 0.5, Scalar(255,0,0)); winCoords.x = (squares[0][0].x + squares[0][2].x)/2 - 180; winCoords.y = -((squares[0][0].y + squares[0][2].y)/2 - 120); visPub.publish(winCoords); } } } int main(int argc, char** argv) { ros::init(argc, argv, "vision"); ros::NodeHandle nh; visPub = nh.advertise<osuar_vision::windowCoordinates>("window_coordinates", 1); // Instantiate VideoCapture object. See here for details: // http://opencv.willowgarage.com/documentation/cpp/reading_and_writing_images_and_video.html VideoCapture cap(1); // Configure video. Our camera NEEDS the frame width to be set to 720 // pixels. cap.set(CV_CAP_PROP_FRAME_WIDTH, 720); cap.set(CV_CAP_PROP_FRAME_HEIGHT, 480); //cap.set(CV_CAP_PROP_FPS, 20); // Instantiate a Mat in which to store each video frame. Mat origFrame; Mat resizedFrame; // Scaled-down from origFrame by factor of 2. Mat hsvFrame; // Converted to HSV space from resizedFrame. Mat bwFrame; // Black/white image after thresholding hsvFrame. namedWindow("origImage", 1); namedWindow("hsvImage", 1); namedWindow("bwImage", 1); cvNamedWindow("control panel"); cvCreateTrackbar("threshold", "control panel", &thresh, 300, NULL); cvCreateTrackbar("maxCosineThresh (x100)", "control panel", &maxCosineThresh, 100, NULL); cvCreateTrackbar("sideRatioThresh (x100)", "control panel", &sideRatioThresh, 100, NULL); cvCreateTrackbar("wallHueLow", "control panel", &wallHueLow, 179, NULL); cvCreateTrackbar("wallHueHigh", "control panel", &wallHueHigh, 179, NULL); cvCreateTrackbar("wallSatLow", "control panel", &wallSatLow, 255, NULL); cvCreateTrackbar("wallSatHigh", "control panel", &wallSatHigh, 255, NULL); cvCreateTrackbar("wallValLow", "control panel", &wallValLow, 255, NULL); cvCreateTrackbar("wallValHigh", "control panel", &wallValHigh, 255, NULL); vector<vector<Point> > squares; while (true) { // Capture image. cap >> origFrame; // Resize the image to increase processing rate. See here for details: // http://opencv.willowgarage.com/documentation/cpp/image_filtering.html pyrDown(origFrame, resizedFrame, Size(origFrame.cols/2, origFrame.rows/2)); // Convert the frame to HSV. TODO: combine this with more filtering and // turn into function. cvtColor(resizedFrame, hsvFrame, CV_BGR2HSV); // Threshold hsvFrame for color of maze walls. inRange(hsvFrame, Scalar(wallHueLow, wallSatLow, wallValLow), Scalar(wallHueHigh, wallSatHigh, wallValHigh), bwFrame); // Find and draw squares. findSquares(bwFrame, squares); drawSquares(resizedFrame, squares); // Show the image, with the squares overlaid. imshow("origImage", resizedFrame); imshow("hsvImage", hsvFrame); imshow("bwImage", bwFrame); // Wait 5 milliseconds for a keypress. int c = waitKey(5); // Exit if the spacebar is pressed. NOTE: killing the program with // Ctrl+C sometimes stops OpenCV at a bad place and effects a kernel // panic! If you really like Ctrl+C, do so at your own risk! if ((char) c == 32) { return 0; } } return 0; }
// The "Square Detector" program. // It loads several images sequentially and tries to find squares in // each image #include "opencv2/core/core.hpp" #include "opencv2/imgproc/imgproc.hpp" #include "opencv2/highgui/highgui.hpp" #include <iostream> #include <math.h> #include <string.h> #include <stdio.h> #include <ros/ros.h> #include <osuar_vision/windowCoordinates.h> using namespace cv; int thresh = 50, N = 11; // Threshold for maximum cosine between angles (x100). int maxCosineThresh = 25; // Threshold for ratio of shortest side / longest side (x100). int sideRatioThresh = 85; // Maximum square area. int maxSquareArea = 41000; // Find colors of any hue... int wallHueLow = 0; int wallHueHigh = 179; // ...of low saturation... int wallSatLow = 0; int wallSatHigh = 40; // ...ranging down to gray, but not completely dark. That is to say, white. int wallValLow = 50; int wallValHigh = 255; ros::Publisher visPub; osuar_vision::windowCoordinates winCoords; // helper function: // finds a cosine of angle between vectors // from pt0->pt1 and from pt0->pt2 static double angle( Point pt1, Point pt2, Point pt0 ) { double dx1 = pt1.x - pt0.x; double dy1 = pt1.y - pt0.y; double dx2 = pt2.x - pt0.x; double dy2 = pt2.y - pt0.y; return (dx1*dx2 + dy1*dy2)/sqrt((dx1*dx1 + dy1*dy1)*(dx2*dx2 + dy2*dy2) + 1e-10); } // returns sequence of squares detected on the image. // the sequence is stored in the specified memory storage static void findSquares( const Mat& image, vector<vector<Point> >& squares ) { squares.clear(); Mat pyr, timg, gray0(image.size(), CV_8U), gray; // down-scale and upscale the image to filter out the noise pyrDown(image, pyr, Size(image.cols/2, image.rows/2)); pyrUp(pyr, timg, image.size()); vector<vector<Point> > contours; // find squares in every color plane of the image //for( int c = 0; c < 3; c++ ) //{ //int ch[] = {c, 0}; //mixChannels(&timg, 1, &gray0, 1, ch, 1); // try several threshold levels for( int l = 0; l < N; l++ ) { // hack: use Canny instead of zero threshold level. // Canny helps to catch squares with gradient shading if( l == 0 ) { // apply Canny. Take the upper threshold from slider // and set the lower to 0 (which forces edges merging) Canny(image, gray, 0, thresh, 5); // dilate canny output to remove potential // holes between edge segments dilate(gray, gray, Mat(), Point(-1,-1)); } else { // apply threshold if l!=0: // tgray(x,y) = gray(x,y) < (l+1)*255/N ? 255 : 0 gray = image >= (l+1)*255/N; } // find contours and store them all as a list findContours(gray, contours, CV_RETR_LIST, CV_CHAIN_APPROX_SIMPLE); vector<Point> approx; // test each contour for( size_t i = 0; i < contours.size(); i++ ) { // approximate contour with accuracy proportional // to the contour perimeter approxPolyDP(Mat(contours[i]), approx, arcLength(Mat(contours[i]), true)*0.02, true); // square contours should have 4 vertices after approximation // relatively large area (to filter out noisy contours) // and be convex. // Note: absolute value of an area is used because // area may be positive or negative - in accordance with the // contour orientation if( approx.size() == 4 && fabs(contourArea(Mat(approx))) > 1000 && fabs(contourArea(Mat(approx))) < maxSquareArea && isContourConvex(Mat(approx)) ) { double maxCosine = 0; double minSideLen = 100000; double maxSideLen = 0; double sideRatio = 0; for( int j = 2; j < 5; j++ ) { // find the maximum cosine of the angle between joint edges double cosine = fabs(angle(approx[j%4], approx[j-2], approx[j-1])); maxCosine = MAX(maxCosine, cosine); // Find the maximum difference in length of adjacent // sides double sideLen = sqrt(pow((approx[j%4].x - approx[(j+1)%4].x), 2) + pow((approx[j%4].y - approx[(j+1)%4].y), 2)); minSideLen = MIN(minSideLen, sideLen); maxSideLen = MAX(maxSideLen, sideLen); } sideRatio = minSideLen / maxSideLen; std::cout << minSideLen << " " << maxSideLen << "\n"; // if cosines of all angles are small // (all angles are ~90 degree) then write quandrange // vertices to resultant sequence if( maxCosine < ((double) maxCosineThresh)/100 && sideRatio >= (double) sideRatioThresh/100 ) squares.push_back(approx); } } } //} } // the function draws all the squares in the image static void drawSquares( Mat& image, const vector<vector<Point> >& squares ) { for( size_t i = 0; i < squares.size(); i++ ) { const Point* p = &squares[i][0]; int n = (int)squares[i].size(); polylines(image, &p, &n, 1, true, Scalar(0,255,0), 3, CV_AA); std::cout << "x: " << squares[i][0].x << " y: " << squares[i][0].y << "\n"; // Only publish coordinates for one of the squares. Coordinates are // shifted over by half the camera resolution (which itself is scaled // down by a factor of two!) on each axis. The y coordinate is inverted // so up is positive. if (i == 0) { putText(image, "0", squares[0][0], FONT_HERSHEY_SIMPLEX, 0.5, Scalar(255,0,0)); putText(image, "1", squares[0][1], FONT_HERSHEY_SIMPLEX, 0.5, Scalar(255,0,0)); putText(image, "2", squares[0][2], FONT_HERSHEY_SIMPLEX, 0.5, Scalar(255,0,0)); putText(image, "3", squares[0][3], FONT_HERSHEY_SIMPLEX, 0.5, Scalar(255,0,0)); winCoords.x = (squares[0][0].x + squares[0][2].x)/2 - 180; winCoords.y = -((squares[0][0].y + squares[0][2].y)/2 - 120); visPub.publish(winCoords); } } } int main(int argc, char** argv) { ros::init(argc, argv, "vision"); ros::NodeHandle nh; visPub = nh.advertise<osuar_vision::windowCoordinates>("window_coordinates", 1); // Instantiate VideoCapture object. See here for details: // http://opencv.willowgarage.com/documentation/cpp/reading_and_writing_images_and_video.html VideoCapture cap(1); // Configure video. Our camera NEEDS the frame width to be set to 720 // pixels. cap.set(CV_CAP_PROP_FRAME_WIDTH, 720); cap.set(CV_CAP_PROP_FRAME_HEIGHT, 480); //cap.set(CV_CAP_PROP_FPS, 20); // Instantiate a Mat in which to store each video frame. Mat origFrame; Mat resizedFrame; // Scaled-down from origFrame by factor of 2. Mat hsvFrame; // Converted to HSV space from resizedFrame. Mat bwFrame; // Black/white image after thresholding hsvFrame. namedWindow("origImage", 1); namedWindow("hsvImage", 1); namedWindow("bwImage", 1); cvNamedWindow("control panel"); cvCreateTrackbar("threshold", "control panel", &thresh, 300, NULL); cvCreateTrackbar("maxCosineThresh (x100)", "control panel", &maxCosineThresh, 100, NULL); cvCreateTrackbar("sideRatioThresh (x100)", "control panel", &sideRatioThresh, 100, NULL); cvCreateTrackbar("maxSquareArea", "control panel", &maxSquareArea, 100000, NULL); cvCreateTrackbar("wallHueLow", "control panel", &wallHueLow, 179, NULL); cvCreateTrackbar("wallHueHigh", "control panel", &wallHueHigh, 179, NULL); cvCreateTrackbar("wallSatLow", "control panel", &wallSatLow, 255, NULL); cvCreateTrackbar("wallSatHigh", "control panel", &wallSatHigh, 255, NULL); cvCreateTrackbar("wallValLow", "control panel", &wallValLow, 255, NULL); cvCreateTrackbar("wallValHigh", "control panel", &wallValHigh, 255, NULL); vector<vector<Point> > squares; while (true) { // Capture image. cap >> origFrame; // Resize the image to increase processing rate. See here for details: // http://opencv.willowgarage.com/documentation/cpp/image_filtering.html pyrDown(origFrame, resizedFrame, Size(origFrame.cols/2, origFrame.rows/2)); // Convert the frame to HSV. TODO: combine this with more filtering and // turn into function. cvtColor(resizedFrame, hsvFrame, CV_BGR2HSV); // Threshold hsvFrame for color of maze walls. inRange(hsvFrame, Scalar(wallHueLow, wallSatLow, wallValLow), Scalar(wallHueHigh, wallSatHigh, wallValHigh), bwFrame); // Find and draw squares. findSquares(bwFrame, squares); drawSquares(resizedFrame, squares); // Show the image, with the squares overlaid. imshow("origImage", resizedFrame); imshow("hsvImage", hsvFrame); imshow("bwImage", bwFrame); // Wait 5 milliseconds for a keypress. int c = waitKey(5); // Exit if the spacebar is pressed. NOTE: killing the program with // Ctrl+C sometimes stops OpenCV at a bad place and effects a kernel // panic! If you really like Ctrl+C, do so at your own risk! if ((char) c == 32) { return 0; } } return 0; }
Add maximum square area threshold.
Add maximum square area threshold.
C++
lgpl-2.1
osuar/iarc,osuar/iarc,osuar/iarc,osuar/iarc,osuar/iarc,osuar/iarc
077fc1dfa8cf5712b9e5c1a5a92e62cc9f208dcd
chrome/browser/extensions/extension_bookmark_manager_apitest.cc
chrome/browser/extensions/extension_bookmark_manager_apitest.cc
// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/command_line.h" #include "base/utf_string_conversions.h" #include "chrome/browser/bookmarks/bookmark_model.h" #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/browser/extensions/extension_bookmark_manager_api.h" #include "chrome/browser/prefs/pref_service.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/pref_names.h" IN_PROC_BROWSER_TEST_F(ExtensionApiTest, BookmarkManager) { CommandLine::ForCurrentProcess()->AppendSwitch( switches::kEnableExperimentalExtensionApis); ASSERT_TRUE(RunExtensionTest("bookmark_manager/standard")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, BookmarkManagerEditDisabled) { CommandLine::ForCurrentProcess()->AppendSwitch( switches::kEnableExperimentalExtensionApis); Profile* profile = browser()->profile(); // Provide some testing data here, since bookmark editing will be disabled // within the extension. BookmarkModel* model = profile->GetBookmarkModel(); const BookmarkNode* bar = model->GetBookmarkBarNode(); const BookmarkNode* folder = model->AddFolder(bar, 0, ASCIIToUTF16("Folder")); const BookmarkNode* node = model->AddURL(bar, 1, ASCIIToUTF16("AAA"), GURL("http://aaa.example.com")); node = model->AddURL(folder, 0, ASCIIToUTF16("BBB"), GURL("http://bbb.example.com")); profile->GetPrefs()->SetBoolean(prefs::kEditBookmarksEnabled, false); ASSERT_TRUE(RunExtensionTest("bookmark_manager/edit_disabled")) << message_; }
// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/command_line.h" #include "base/utf_string_conversions.h" #include "chrome/browser/bookmarks/bookmark_model.h" #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/browser/extensions/extension_bookmark_manager_api.h" #include "chrome/browser/prefs/pref_service.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/pref_names.h" IN_PROC_BROWSER_TEST_F(ExtensionApiTest, BookmarkManager) { CommandLine::ForCurrentProcess()->AppendSwitch( switches::kEnableExperimentalExtensionApis); ASSERT_TRUE(RunExtensionTest("bookmark_manager/standard")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, FLAKY_BookmarkManagerEditDisabled) { CommandLine::ForCurrentProcess()->AppendSwitch( switches::kEnableExperimentalExtensionApis); Profile* profile = browser()->profile(); // Provide some testing data here, since bookmark editing will be disabled // within the extension. BookmarkModel* model = profile->GetBookmarkModel(); const BookmarkNode* bar = model->GetBookmarkBarNode(); const BookmarkNode* folder = model->AddFolder(bar, 0, ASCIIToUTF16("Folder")); const BookmarkNode* node = model->AddURL(bar, 1, ASCIIToUTF16("AAA"), GURL("http://aaa.example.com")); node = model->AddURL(folder, 0, ASCIIToUTF16("BBB"), GURL("http://bbb.example.com")); profile->GetPrefs()->SetBoolean(prefs::kEditBookmarksEnabled, false); ASSERT_TRUE(RunExtensionTest("bookmark_manager/edit_disabled")) << message_; }
Tag ExtensionApiTest.BookmarkManagerEditDisabled flaky.
Tag ExtensionApiTest.BookmarkManagerEditDisabled flaky. [email protected] BUG=79335 TEST=none Review URL: http://codereview.chromium.org/6836012 git-svn-id: dd90618784b6a4b323ea0c23a071cb1c9e6f2ac7@81417 4ff67af0-8c30-449e-8e8b-ad334ec8d88c
C++
bsd-3-clause
wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser
891f4c265344b4ac56803544eca3ef59892f24ae
cccallcc.hpp
cccallcc.hpp
#ifndef __CCCALLCC_HPP__ #define __CCCALLCC_HPP__ #include <functional> #include <memory> #include <unistd.h> template <typename T> class cont { public: typedef std::function<T (cont<T>)> call_cc_arg; static T call_cc(call_cc_arg f); void operator()(const T &x) { m_impl_ptr->invoke(x); } private: class impl { public: impl(int pipe) : m_pipe(pipe) { } ~impl() { close(m_pipe); } void invoke(const T &x) { write(m_pipe, &x, sizeof(T)); exit(0); } private: int m_pipe; }; cont(int pipe) : m_impl_ptr(new impl(pipe)) { } std::shared_ptr<impl> m_impl_ptr; }; template <typename T> T cont<T>::call_cc(call_cc_arg f) { int fd[2]; pipe(fd); int read_fd = fd[0]; int write_fd = fd[1]; pid_t pid = fork(); if (pid) { // parent close(read_fd); return f( cont<T>(write_fd) ); } else { // child close(write_fd); char buf[sizeof(T)]; if (read(read_fd, buf, sizeof(T)) < sizeof(T)) exit(0); close(read_fd); return *reinterpret_cast<T*>(buf); } } template <typename T> static inline T call_cc(typename cont<T>::call_cc_arg f) { return cont<T>::call_cc(f); } #endif // !defined(__CCALLCC_HPP__)
#ifndef __CCCALLCC_HPP__ #define __CCCALLCC_HPP__ #include <functional> #include <memory> #include <unistd.h> template <typename T> class cont { public: typedef std::function<T (cont<T>)> call_cc_arg; static T call_cc(call_cc_arg f); void operator()(const T &x) { m_impl_ptr->invoke(x); } private: class impl { public: impl(int pipe) : m_pipe(pipe) { } ~impl() { close(m_pipe); } void invoke(const T &x) { write(m_pipe, &x, sizeof(T)); exit(0); } private: int m_pipe; }; cont(int pipe) : m_impl_ptr(new impl(pipe)) { } std::shared_ptr<impl> m_impl_ptr; }; template <typename T> T cont<T>::call_cc(call_cc_arg f) { int fd[2]; pipe(fd); int read_fd = fd[0]; int write_fd = fd[1]; pid_t pid = fork(); if (pid) { // parent close(read_fd); return f( cont<T>(write_fd) ); } else { // child close(write_fd); char buf[sizeof(T)]; if (read(read_fd, buf, sizeof(T)) < ssize_t(sizeof(T))) exit(0); close(read_fd); return *reinterpret_cast<T*>(buf); } } template <typename T> static inline T call_cc(typename cont<T>::call_cc_arg f) { return cont<T>::call_cc(f); } #endif // !defined(__CCALLCC_HPP__)
deal with comparison signedness
deal with comparison signedness If sizeof(T) is more than the max ssize_t then we have other problems, like the stack-allocated buffer.
C++
bsd-3-clause
kmcallister/cccallcc,kmcallister/cccallcc
682cdd2ccfe630491b15855b280dadcbd4b5a6c1
src/numerics/distributed_vector.C
src/numerics/distributed_vector.C
// $Id$ // The libMesh Finite Element Library. // Copyright (C) 2002-2007 Benjamin S. Kirk, John W. Peterson // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #include "libmesh_common.h" // C++ includes #include <cmath> // for std::abs // Local Includes #include "distributed_vector.h" #include "dense_vector.h" #include "parallel.h" //-------------------------------------------------------------------------- // DistributedVector methods template <typename T> T DistributedVector<T>::sum () const { // This function must be run on all processors at once parallel_only(); assert (this->initialized()); assert (_values.size() == _local_size); assert ((_last_local_index - _first_local_index) == _local_size); T local_sum = 0.; for (unsigned int i=0; i<local_size(); i++) local_sum += _values[i]; Parallel::sum(local_sum); return local_sum; } template <typename T> Real DistributedVector<T>::l1_norm () const { // This function must be run on all processors at once parallel_only(); assert (this->initialized()); assert (_values.size() == _local_size); assert ((_last_local_index - _first_local_index) == _local_size); double local_l1 = 0.; for (unsigned int i=0; i<local_size(); i++) local_l1 += std::abs(_values[i]); Parallel::sum(local_l1); return local_l1; } template <typename T> Real DistributedVector<T>::l2_norm () const { // This function must be run on all processors at once parallel_only(); assert (this->initialized()); assert (_values.size() == _local_size); assert ((_last_local_index - _first_local_index) == _local_size); double local_l2 = 0.; for (unsigned int i=0; i<local_size(); i++) local_l2 += libmesh_norm(_values[i]); Parallel::sum(local_l2); return std::sqrt(local_l2); } template <typename T> Real DistributedVector<T>::linfty_norm () const { // This function must be run on all processors at once parallel_only(); assert (this->initialized()); assert (_values.size() == _local_size); assert ((_last_local_index - _first_local_index) == _local_size); double local_linfty = 0.; for (unsigned int i=0; i<local_size(); i++) local_linfty = std::max(local_linfty, static_cast<double>(std::abs(_values[i])) ); // Note we static_cast so that both // types are the same, as required // by std::max Parallel::max(local_linfty); return local_linfty; } template <typename T> NumericVector<T>& DistributedVector<T>::operator += (const NumericVector<T>& v) { assert (this->closed()); assert (this->initialized()); assert (_values.size() == _local_size); assert ((_last_local_index - _first_local_index) == _local_size); add(1., v); return *this; } template <typename T> NumericVector<T>& DistributedVector<T>::operator -= (const NumericVector<T>& v) { assert (this->closed()); assert (this->initialized()); assert (_values.size() == _local_size); assert ((_last_local_index - _first_local_index) == _local_size); add(-1., v); return *this; } template <typename T> void DistributedVector<T>::add_vector (const std::vector<T>& v, const std::vector<unsigned int>& dof_indices) { assert (!v.empty()); assert (v.size() == dof_indices.size()); assert (this->initialized()); assert (_values.size() == _local_size); assert ((_last_local_index - _first_local_index) == _local_size); for (unsigned int i=0; i<v.size(); i++) add (dof_indices[i], v[i]); } template <typename T> void DistributedVector<T>::add_vector (const NumericVector<T>& V, const std::vector<unsigned int>& dof_indices) { assert (V.size() == dof_indices.size()); assert (this->initialized()); assert (_values.size() == _local_size); assert ((_last_local_index - _first_local_index) == _local_size); for (unsigned int i=0; i<V.size(); i++) add (dof_indices[i], V(i)); } template <typename T> void DistributedVector<T>::add_vector (const DenseVector<T>& V, const std::vector<unsigned int>& dof_indices) { assert (V.size() == dof_indices.size()); assert (this->initialized()); assert (_values.size() == _local_size); assert ((_last_local_index - _first_local_index) == _local_size); for (unsigned int i=0; i<V.size(); i++) add (dof_indices[i], V(i)); } template <typename T> void DistributedVector<T>::add (const T v) { assert (this->initialized()); assert (_values.size() == _local_size); assert ((_last_local_index - _first_local_index) == _local_size); for (unsigned int i=0; i<local_size(); i++) _values[i] += v; } template <typename T> void DistributedVector<T>::add (const NumericVector<T>& v) { assert (this->initialized()); assert (_values.size() == _local_size); assert ((_last_local_index - _first_local_index) == _local_size); add (1., v); } template <typename T> void DistributedVector<T>::add (const T a, const NumericVector<T>& v) { assert (this->initialized()); assert (_values.size() == _local_size); assert ((_last_local_index - _first_local_index) == _local_size); add(a, v); } template <typename T> void DistributedVector<T>::insert (const std::vector<T>& v, const std::vector<unsigned int>& dof_indices) { assert (!v.empty()); assert (v.size() == dof_indices.size()); assert (this->initialized()); assert (_values.size() == _local_size); assert ((_last_local_index - _first_local_index) == _local_size); for (unsigned int i=0; i<v.size(); i++) this->set (dof_indices[i], v[i]); } template <typename T> void DistributedVector<T>::insert (const NumericVector<T>& V, const std::vector<unsigned int>& dof_indices) { assert (V.size() == dof_indices.size()); assert (this->initialized()); assert (_values.size() == _local_size); assert ((_last_local_index - _first_local_index) == _local_size); for (unsigned int i=0; i<V.size(); i++) this->set (dof_indices[i], V(i)); } template <typename T> void DistributedVector<T>::insert (const DenseVector<T>& V, const std::vector<unsigned int>& dof_indices) { assert (V.size() == dof_indices.size()); assert (this->initialized()); assert (_values.size() == _local_size); assert ((_last_local_index - _first_local_index) == _local_size); for (unsigned int i=0; i<V.size(); i++) this->set (dof_indices[i], V(i)); } template <typename T> void DistributedVector<T>::scale (const T factor) { assert (this->initialized()); assert (_values.size() == _local_size); assert ((_last_local_index - _first_local_index) == _local_size); for (unsigned int i=0; i<local_size(); i++) _values[i] *= factor; } template <typename T> T DistributedVector<T>::dot (const NumericVector<T>& V) const { // This function must be run on all processors at once parallel_only(); // Make sure the NumericVector passed in is really a DistributedVector const DistributedVector<T>* v = dynamic_cast<const DistributedVector<T>*>(&V); assert (v != NULL); // Make sure that the two vectors are distributed in the same way. assert ( this->first_local_index() == v->first_local_index() ); assert ( this->last_local_index() == v->last_local_index() ); // The result of dotting together the local parts of the vector. T local_dot = 0; for (unsigned int i=0; i<this->local_size(); i++) local_dot += this->_values[i] * v->_values[i]; // The local dot products are now summed via MPI Parallel::sum(local_dot); return local_dot; } template <typename T> NumericVector<T>& DistributedVector<T>::operator = (const T s) { assert (this->initialized()); assert (_values.size() == _local_size); assert ((_last_local_index - _first_local_index) == _local_size); for (unsigned int i=0; i<local_size(); i++) _values[i] = s; return *this; } template <typename T> NumericVector<T>& DistributedVector<T>::operator = (const NumericVector<T>& v_in) { const DistributedVector<T>* v = dynamic_cast<const DistributedVector<T>*>(&v_in); assert (v != NULL); *this = *v; return *this; } template <typename T> DistributedVector<T>& DistributedVector<T>::operator = (const DistributedVector<T>& v) { this->_is_initialized = v._is_initialized; this->_is_closed = v._is_closed; _global_size = v._global_size; _local_size = v._local_size; _first_local_index = v._first_local_index; _last_local_index = v._last_local_index; if (v.local_size() == this->local_size()) { _values = v._values; } else { error(); } return *this; } template <typename T> NumericVector<T>& DistributedVector<T>::operator = (const std::vector<T>& v) { assert (this->initialized()); assert (_values.size() == _local_size); assert ((_last_local_index - _first_local_index) == _local_size); if (v.size() == local_size()) _values = v; else if (v.size() == size()) for (unsigned int i=first_local_index(); i<last_local_index(); i++) _values[i-first_local_index()] = v[i]; else { error(); } return *this; } template <typename T> void DistributedVector<T>::localize (NumericVector<T>& v_local_in) const { assert (this->initialized()); assert (_values.size() == _local_size); assert ((_last_local_index - _first_local_index) == _local_size); DistributedVector<T>* v_local = dynamic_cast<DistributedVector<T>*>(&v_local_in); assert (v_local != NULL); v_local->_first_local_index = 0; v_local->_global_size = v_local->_local_size = v_local->_last_local_index = size(); v_local->_is_initialized = v_local->_is_closed = true; // Call localize on the vector's values. This will help // prevent code duplication localize (v_local->_values); #ifndef HAVE_MPI assert (local_size() == size()); #endif } template <typename T> void DistributedVector<T>::localize (NumericVector<T>& v_local_in, const std::vector<unsigned int>&) const { assert (this->initialized()); assert (_values.size() == _local_size); assert ((_last_local_index - _first_local_index) == _local_size); // We don't support the send list. Call the less efficient localize(v_local_in) localize (v_local_in); } template <typename T> void DistributedVector<T>::localize (const unsigned int first_local_idx, const unsigned int last_local_idx, const std::vector<unsigned int>& send_list) { // Only good for serial vectors assert (this->size() == this->local_size()); assert (last_local_idx > first_local_idx); assert (send_list.size() <= this->size()); assert (last_local_idx < this->size()); const unsigned int size = this->size(); const unsigned int local_size = (last_local_idx - first_local_idx + 1); // Don't bother for serial cases if ((first_local_idx == 0) && (local_size == size)) return; // Build a parallel vector, initialize it with the local // parts of (*this) DistributedVector<T> parallel_vec; parallel_vec.init (size, local_size); // Copy part of *this into the parallel_vec for (unsigned int i=first_local_idx; i<=last_local_idx; i++) parallel_vec._values[i-first_local_idx] = _values[i]; // localize like normal parallel_vec.localize (*this, send_list); } template <typename T> void DistributedVector<T>::localize (std::vector<T>& v_local) const { // This function must be run on all processors at once parallel_only(); assert (this->initialized()); assert (_values.size() == _local_size); assert ((_last_local_index - _first_local_index) == _local_size); v_local = this->_values; Parallel::allgather (v_local); #ifndef HAVE_MPI assert (local_size() == size()); #endif } template <typename T> void DistributedVector<T>::localize_to_one (std::vector<T>& v_local, const unsigned int pid) const { // This function must be run on all processors at once parallel_only(); assert (this->initialized()); assert (_values.size() == _local_size); assert ((_last_local_index - _first_local_index) == _local_size); v_local = this->_values; Parallel::gather (pid, v_local); #ifndef HAVE_MPI assert (local_size() == size()); #endif } //-------------------------------------------------------------- // Explicit instantiations template class DistributedVector<Number>;
// $Id$ // The libMesh Finite Element Library. // Copyright (C) 2002-2007 Benjamin S. Kirk, John W. Peterson // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #include "libmesh_common.h" // C++ includes #include <cmath> // for std::abs // Local Includes #include "distributed_vector.h" #include "dense_vector.h" #include "parallel.h" //-------------------------------------------------------------------------- // DistributedVector methods template <typename T> T DistributedVector<T>::sum () const { // This function must be run on all processors at once parallel_only(); assert (this->initialized()); assert (_values.size() == _local_size); assert ((_last_local_index - _first_local_index) == _local_size); T local_sum = 0.; for (unsigned int i=0; i<local_size(); i++) local_sum += _values[i]; Parallel::sum(local_sum); return local_sum; } template <typename T> Real DistributedVector<T>::l1_norm () const { // This function must be run on all processors at once parallel_only(); assert (this->initialized()); assert (_values.size() == _local_size); assert ((_last_local_index - _first_local_index) == _local_size); double local_l1 = 0.; for (unsigned int i=0; i<local_size(); i++) local_l1 += std::abs(_values[i]); Parallel::sum(local_l1); return local_l1; } template <typename T> Real DistributedVector<T>::l2_norm () const { // This function must be run on all processors at once parallel_only(); assert (this->initialized()); assert (_values.size() == _local_size); assert ((_last_local_index - _first_local_index) == _local_size); double local_l2 = 0.; for (unsigned int i=0; i<local_size(); i++) local_l2 += libmesh_norm(_values[i]); Parallel::sum(local_l2); return std::sqrt(local_l2); } template <typename T> Real DistributedVector<T>::linfty_norm () const { // This function must be run on all processors at once parallel_only(); assert (this->initialized()); assert (_values.size() == _local_size); assert ((_last_local_index - _first_local_index) == _local_size); Real local_linfty = 0.; for (unsigned int i=0; i<local_size(); i++) local_linfty = std::max(local_linfty, static_cast<Real>(std::abs(_values[i])) ); // Note we static_cast so that both // types are the same, as required // by std::max Parallel::max(local_linfty); return local_linfty; } template <typename T> NumericVector<T>& DistributedVector<T>::operator += (const NumericVector<T>& v) { assert (this->closed()); assert (this->initialized()); assert (_values.size() == _local_size); assert ((_last_local_index - _first_local_index) == _local_size); add(1., v); return *this; } template <typename T> NumericVector<T>& DistributedVector<T>::operator -= (const NumericVector<T>& v) { assert (this->closed()); assert (this->initialized()); assert (_values.size() == _local_size); assert ((_last_local_index - _first_local_index) == _local_size); add(-1., v); return *this; } template <typename T> void DistributedVector<T>::add_vector (const std::vector<T>& v, const std::vector<unsigned int>& dof_indices) { assert (!v.empty()); assert (v.size() == dof_indices.size()); assert (this->initialized()); assert (_values.size() == _local_size); assert ((_last_local_index - _first_local_index) == _local_size); for (unsigned int i=0; i<v.size(); i++) add (dof_indices[i], v[i]); } template <typename T> void DistributedVector<T>::add_vector (const NumericVector<T>& V, const std::vector<unsigned int>& dof_indices) { assert (V.size() == dof_indices.size()); assert (this->initialized()); assert (_values.size() == _local_size); assert ((_last_local_index - _first_local_index) == _local_size); for (unsigned int i=0; i<V.size(); i++) add (dof_indices[i], V(i)); } template <typename T> void DistributedVector<T>::add_vector (const DenseVector<T>& V, const std::vector<unsigned int>& dof_indices) { assert (V.size() == dof_indices.size()); assert (this->initialized()); assert (_values.size() == _local_size); assert ((_last_local_index - _first_local_index) == _local_size); for (unsigned int i=0; i<V.size(); i++) add (dof_indices[i], V(i)); } template <typename T> void DistributedVector<T>::add (const T v) { assert (this->initialized()); assert (_values.size() == _local_size); assert ((_last_local_index - _first_local_index) == _local_size); for (unsigned int i=0; i<local_size(); i++) _values[i] += v; } template <typename T> void DistributedVector<T>::add (const NumericVector<T>& v) { assert (this->initialized()); assert (_values.size() == _local_size); assert ((_last_local_index - _first_local_index) == _local_size); add (1., v); } template <typename T> void DistributedVector<T>::add (const T a, const NumericVector<T>& v) { assert (this->initialized()); assert (_values.size() == _local_size); assert ((_last_local_index - _first_local_index) == _local_size); add(a, v); } template <typename T> void DistributedVector<T>::insert (const std::vector<T>& v, const std::vector<unsigned int>& dof_indices) { assert (!v.empty()); assert (v.size() == dof_indices.size()); assert (this->initialized()); assert (_values.size() == _local_size); assert ((_last_local_index - _first_local_index) == _local_size); for (unsigned int i=0; i<v.size(); i++) this->set (dof_indices[i], v[i]); } template <typename T> void DistributedVector<T>::insert (const NumericVector<T>& V, const std::vector<unsigned int>& dof_indices) { assert (V.size() == dof_indices.size()); assert (this->initialized()); assert (_values.size() == _local_size); assert ((_last_local_index - _first_local_index) == _local_size); for (unsigned int i=0; i<V.size(); i++) this->set (dof_indices[i], V(i)); } template <typename T> void DistributedVector<T>::insert (const DenseVector<T>& V, const std::vector<unsigned int>& dof_indices) { assert (V.size() == dof_indices.size()); assert (this->initialized()); assert (_values.size() == _local_size); assert ((_last_local_index - _first_local_index) == _local_size); for (unsigned int i=0; i<V.size(); i++) this->set (dof_indices[i], V(i)); } template <typename T> void DistributedVector<T>::scale (const T factor) { assert (this->initialized()); assert (_values.size() == _local_size); assert ((_last_local_index - _first_local_index) == _local_size); for (unsigned int i=0; i<local_size(); i++) _values[i] *= factor; } template <typename T> T DistributedVector<T>::dot (const NumericVector<T>& V) const { // This function must be run on all processors at once parallel_only(); // Make sure the NumericVector passed in is really a DistributedVector const DistributedVector<T>* v = dynamic_cast<const DistributedVector<T>*>(&V); assert (v != NULL); // Make sure that the two vectors are distributed in the same way. assert ( this->first_local_index() == v->first_local_index() ); assert ( this->last_local_index() == v->last_local_index() ); // The result of dotting together the local parts of the vector. T local_dot = 0; for (unsigned int i=0; i<this->local_size(); i++) local_dot += this->_values[i] * v->_values[i]; // The local dot products are now summed via MPI Parallel::sum(local_dot); return local_dot; } template <typename T> NumericVector<T>& DistributedVector<T>::operator = (const T s) { assert (this->initialized()); assert (_values.size() == _local_size); assert ((_last_local_index - _first_local_index) == _local_size); for (unsigned int i=0; i<local_size(); i++) _values[i] = s; return *this; } template <typename T> NumericVector<T>& DistributedVector<T>::operator = (const NumericVector<T>& v_in) { const DistributedVector<T>* v = dynamic_cast<const DistributedVector<T>*>(&v_in); assert (v != NULL); *this = *v; return *this; } template <typename T> DistributedVector<T>& DistributedVector<T>::operator = (const DistributedVector<T>& v) { this->_is_initialized = v._is_initialized; this->_is_closed = v._is_closed; _global_size = v._global_size; _local_size = v._local_size; _first_local_index = v._first_local_index; _last_local_index = v._last_local_index; if (v.local_size() == this->local_size()) { _values = v._values; } else { error(); } return *this; } template <typename T> NumericVector<T>& DistributedVector<T>::operator = (const std::vector<T>& v) { assert (this->initialized()); assert (_values.size() == _local_size); assert ((_last_local_index - _first_local_index) == _local_size); if (v.size() == local_size()) _values = v; else if (v.size() == size()) for (unsigned int i=first_local_index(); i<last_local_index(); i++) _values[i-first_local_index()] = v[i]; else { error(); } return *this; } template <typename T> void DistributedVector<T>::localize (NumericVector<T>& v_local_in) const { assert (this->initialized()); assert (_values.size() == _local_size); assert ((_last_local_index - _first_local_index) == _local_size); DistributedVector<T>* v_local = dynamic_cast<DistributedVector<T>*>(&v_local_in); assert (v_local != NULL); v_local->_first_local_index = 0; v_local->_global_size = v_local->_local_size = v_local->_last_local_index = size(); v_local->_is_initialized = v_local->_is_closed = true; // Call localize on the vector's values. This will help // prevent code duplication localize (v_local->_values); #ifndef HAVE_MPI assert (local_size() == size()); #endif } template <typename T> void DistributedVector<T>::localize (NumericVector<T>& v_local_in, const std::vector<unsigned int>&) const { assert (this->initialized()); assert (_values.size() == _local_size); assert ((_last_local_index - _first_local_index) == _local_size); // We don't support the send list. Call the less efficient localize(v_local_in) localize (v_local_in); } template <typename T> void DistributedVector<T>::localize (const unsigned int first_local_idx, const unsigned int last_local_idx, const std::vector<unsigned int>& send_list) { // Only good for serial vectors assert (this->size() == this->local_size()); assert (last_local_idx > first_local_idx); assert (send_list.size() <= this->size()); assert (last_local_idx < this->size()); const unsigned int size = this->size(); const unsigned int local_size = (last_local_idx - first_local_idx + 1); // Don't bother for serial cases if ((first_local_idx == 0) && (local_size == size)) return; // Build a parallel vector, initialize it with the local // parts of (*this) DistributedVector<T> parallel_vec; parallel_vec.init (size, local_size); // Copy part of *this into the parallel_vec for (unsigned int i=first_local_idx; i<=last_local_idx; i++) parallel_vec._values[i-first_local_idx] = _values[i]; // localize like normal parallel_vec.localize (*this, send_list); } template <typename T> void DistributedVector<T>::localize (std::vector<T>& v_local) const { // This function must be run on all processors at once parallel_only(); assert (this->initialized()); assert (_values.size() == _local_size); assert ((_last_local_index - _first_local_index) == _local_size); v_local = this->_values; Parallel::allgather (v_local); #ifndef HAVE_MPI assert (local_size() == size()); #endif } template <typename T> void DistributedVector<T>::localize_to_one (std::vector<T>& v_local, const unsigned int pid) const { // This function must be run on all processors at once parallel_only(); assert (this->initialized()); assert (_values.size() == _local_size); assert ((_last_local_index - _first_local_index) == _local_size); v_local = this->_values; Parallel::gather (pid, v_local); #ifndef HAVE_MPI assert (local_size() == size()); #endif } //-------------------------------------------------------------- // Explicit instantiations template class DistributedVector<Number>;
Use Real instead of double where appropriate
Use Real instead of double where appropriate git-svn-id: ffc1bc5b3feaf8644044862cc38c386ade156493@2613 434f946d-2f3d-0410-ba4c-cb9f52fb0dbf
C++
lgpl-2.1
certik/libmesh,certik/libmesh,certik/libmesh,certik/libmesh,certik/libmesh,certik/libmesh,certik/libmesh
f54a23364dc46cce010b3b694486605b83da98a5
src/common/id_gen.hpp
src/common/id_gen.hpp
/* * Copyright (C) 2015 Luke San Antonio * All rights reserved. */ #pragma once #include <queue> namespace redc { template <typename id_type> struct ID_Gen { using queue_type = std::queue<id_type>; id_type count = 0; queue_type removed_id_queue; inline id_type get(); inline void remove(id_type id); }; /*! * \brief Returns some valid which can be used on a new Object. * * \returns 0 if there are no ids available. */ template <typename id_type> id_type ID_Gen<id_type>::get() { if(!removed_id_queue.empty()) { id_type id = 0; id = removed_id_queue.front(); removed_id_queue.pop(); return id; } // What do we do on integer overflow? if(++this->count == 0) { // If we subtract one from it, this case will continue forever, the only // way to get ids back is of course to remove them. --this->count; // Return zero, signifying a bad id return 0; } return this->count; } template <typename id_type> void ID_Gen<id_type>::remove(id_type id) { this->removed_id_queue.push(id); } }
/* * Copyright (C) 2015 Luke San Antonio * All rights reserved. */ #pragma once #include <vector> namespace redc { template <typename id_type> struct ID_Gen { id_type get(); id_type peek(); void remove(id_type id); bool is_removed(id_type id); bool is_valid(id_type id); id_type reserved(); private: id_type count_ = 0; // We could technically use a set here, but the performance is never going // to be better than the vector for the amount of ids that we are going to // actually need in practice. std::vector<id_type> removed_id_queue_; }; /*! * \brief Returns some valid which can be used on a new Object. * * \returns 0 if there are no ids available. */ template <typename id_type> id_type ID_Gen<id_type>::get() { // If we have ids to use if(!removed_id_queue_.empty()) { auto id = removed_id_queue_.back(); removed_id_queue_.pop_back(); return id; } // What do we do on integer overflow? id_type ret = ++count_; // If there was an overflow, go back one so this happens every time from // now on. Also zero is a bad id so it works. Remember ret will still be // zero once we decrement count. if(ret == 0) --count_; return ret; } template <typename id_type> id_type ID_Gen<id_type>::peek() { if(!removed_id_queue_.empty()) { return removed_id_queue_.front(); } else { // If this overflows it will be zero, we're good. return count_ + 1; } } template <typename id_type> void ID_Gen<id_type>::remove(id_type id) { // This is a bad id, ignore it or we may just go about returning them // erroneously. if(id == 0) return; // The id can't be bigger than count, because count is the last id that was // returned. In fact, if we end up overflowing it will always be that one // number right before overflow so everything will work out. if(id <= count_) { // Make sure it isn't already in the vector. if(!is_removed(id)) { // We don't particularly care when this id is used, but at the moment // it will be the next one to be used, ie the result of peek(). removed_id_queue_.push_back(id); } // else the id was found, we don't need to remove it again. } } template <class id_type> bool ID_Gen<id_type>::is_removed(id_type id) { auto it = std::find(begin(removed_id_queue_), end(removed_id_queue_), id); return it != end(removed_id_queue_); } template <class id_type> bool ID_Gen<id_type>::is_valid(id_type id) { // A valid id can't be removed and must be below/equal to count_ return !is_removed(id) && id <= count_; } template <typename id_type> id_type ID_Gen<id_type>::reserved() { return count_ - removed_id_queue_.size(); } }
Clean up ID_Gen
Clean up ID_Gen It is no longer mostly inline and no longer publicly flaunting its implementation. It is being used in the Scene struct to manage the indices of objects currently valid in a pre-allocated contiguous array of them.
C++
bsd-3-clause
RedCraneStudio/redcrane-engine,RedCraneStudio/redcrane-engine,RedCraneStudio/redcrane-engine,RedCraneStudio/redcrane-engine
5739d78831e56bb908335fd9a91da758f60b836e
Rendering/Testing/Cxx/TestScenePicker.cxx
Rendering/Testing/Cxx/TestScenePicker.cxx
/*========================================================================= Program: Visualization Toolkit Module: TestScenePicker.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ // // Test class vtkScenePicker. // Move your mouse around the scene and the underlying actor should be // printed on standard output. // #include "vtkSphereSource.h" #include "vtkPolyDataMapper.h" #include "vtkActor.h" #include "vtkRenderer.h" #include "vtkRenderWindow.h" #include "vtkRenderWindowInteractor.h" #include "vtkCommand.h" #include "vtkTestUtilities.h" #include "vtkRegressionTestImage.h" #include "vtkScenePicker.h" #include "vtkVolume16Reader.h" #include "vtkProperty.h" #include "vtkPolyDataNormals.h" #include "vtkContourFilter.h" #include <vtkstd/map> #include <vtkstd/string> //----------------------------------------------------------------------------- // Create a few actors first vtkActor *CreateActor1( int argc, char *argv[], vtkRenderer * aRenderer ) { char* fname2 = vtkTestUtilities::ExpandDataFileName( argc, argv, "Data/headsq/quarter"); vtkVolume16Reader *v16 = vtkVolume16Reader::New(); v16->SetDataDimensions (64,64); v16->SetImageRange (1,93); v16->SetDataByteOrderToLittleEndian(); v16->SetFilePrefix (fname2); v16->SetDataSpacing (3.2, 3.2, 1.5); // An isosurface, or contour value of 500 is known to correspond to the // skin of the patient. Once generated, a vtkPolyDataNormals filter is // is used to create normals for smooth surface shading during rendering. vtkContourFilter *skinExtractor = vtkContourFilter::New(); skinExtractor->SetInputConnection(v16->GetOutputPort()); skinExtractor->SetValue(0, 500); vtkPolyDataNormals *skinNormals = vtkPolyDataNormals::New(); skinNormals->SetInputConnection(skinExtractor->GetOutputPort()); skinNormals->SetFeatureAngle(60.0); vtkPolyDataMapper *skinMapper = vtkPolyDataMapper::New(); skinMapper->SetInputConnection(skinNormals->GetOutputPort()); skinMapper->ScalarVisibilityOff(); vtkActor *skin = vtkActor::New(); skin->SetMapper(skinMapper); skin->GetProperty()->SetColor(0.95,0.75,0.75); aRenderer->AddActor(skin); v16->Delete(); skinExtractor->Delete(); skinNormals->Delete(); skinMapper->Delete(); skin->Delete(); delete [] fname2; return skin; } //----------------------------------------------------------------------------- // Create a few actors first vtkActor * CreateActor2( int vtkNotUsed(argc), char **vtkNotUsed(argv), vtkRenderer * ren ) { vtkSphereSource *ss = vtkSphereSource::New(); ss->SetThetaResolution(30); ss->SetPhiResolution(30); ss->SetRadius(150.0); vtkPolyDataMapper *mapper = vtkPolyDataMapper::New(); mapper->SetInput(ss->GetOutput()); vtkActor *actor = vtkActor::New(); actor->SetMapper(mapper); actor->GetProperty()->SetColor(0.0,1.0,0.0); ren->AddActor(actor); ss->Delete(); mapper->Delete(); actor->Delete(); return actor; } //----------------------------------------------------------------------------- // Command to write out picked actors during mouse over. class TestScenePickerCommand : public vtkCommand { public: vtkScenePicker * m_Picker; static TestScenePickerCommand *New() { return new TestScenePickerCommand; } virtual void Execute(vtkObject *caller, unsigned long vtkNotUsed(eventId), void* vtkNotUsed(callData)) { vtkRenderWindowInteractor * iren = reinterpret_cast< vtkRenderWindowInteractor *>(caller); int e[2]; iren->GetEventPosition(e); cout << "DisplayPosition : (" << e[0] << "," << e[1] << ")" << " Prop: " << m_ActorDescription[m_Picker->GetViewProp(e)].c_str() << " CellId: " << m_Picker->GetCellId(e) << " VertexId: " << m_Picker->GetVertexId(e) << endl; } void SetActorDescription( vtkProp *a, vtkstd::string s ) { this->m_ActorDescription[a] = s; } vtkstd::map< vtkProp *, vtkstd::string > m_ActorDescription; protected: TestScenePickerCommand() { this->SetActorDescription(static_cast<vtkActor*>(NULL), "None"); } virtual ~TestScenePickerCommand() {} }; //----------------------------------------------------------------------------- int TestScenePicker(int argc, char* argv[]) { vtkRenderer *ren = vtkRenderer::New(); vtkRenderWindow *renWin = vtkRenderWindow::New(); vtkRenderWindowInteractor *iren = vtkRenderWindowInteractor::New(); renWin->AddRenderer(ren); iren->SetRenderWindow(renWin); ren->SetBackground(0.0, 0.0, 0.0); renWin->SetSize(300, 300); // Here comes the scene picker stuff. [ Just 2 lines ] vtkScenePicker * picker = vtkScenePicker::New(); picker->SetRenderer(ren); // Write some stuff for interactive stuff. TestScenePickerCommand * command = TestScenePickerCommand::New(); command->m_Picker = picker; command->SetActorDescription( CreateActor1( argc, argv, ren ), "Head" ); command->SetActorDescription( CreateActor2( argc, argv, ren ), "Sphere" ); iren->AddObserver(vtkCommand::MouseMoveEvent, command); renWin->Render(); iren->Initialize(); // Check if scene picking works. int retVal = EXIT_SUCCESS; int e[2] = {175, 215}; if (command->m_ActorDescription[picker->GetViewProp(e)] != "Head" || picker->GetCellId(e) != 50992) { retVal = EXIT_FAILURE; } for ( int i = 0; i < argc; ++i ) { if ( ! strcmp( argv[i], "-I" ) ) { iren->Start(); } } // Cleanups command->Delete(); picker->Delete(); ren->Delete(); renWin->Delete(); iren->Delete(); return retVal; }
/*========================================================================= Program: Visualization Toolkit Module: TestScenePicker.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ // // Test class vtkScenePicker. // Move your mouse around the scene and the underlying actor should be // printed on standard output. // #include "vtkSphereSource.h" #include "vtkPolyDataMapper.h" #include "vtkActor.h" #include "vtkRenderer.h" #include "vtkRenderWindow.h" #include "vtkRenderWindowInteractor.h" #include "vtkCommand.h" #include "vtkTestUtilities.h" #include "vtkRegressionTestImage.h" #include "vtkScenePicker.h" #include "vtkVolume16Reader.h" #include "vtkProperty.h" #include "vtkPolyDataNormals.h" #include "vtkContourFilter.h" #include <vtkstd/map> #include <vtkstd/string> //----------------------------------------------------------------------------- // Create a few actors first vtkActor *CreateActor1( int argc, char *argv[], vtkRenderer * aRenderer ) { char* fname2 = vtkTestUtilities::ExpandDataFileName( argc, argv, "Data/headsq/quarter"); vtkVolume16Reader *v16 = vtkVolume16Reader::New(); v16->SetDataDimensions (64,64); v16->SetImageRange (1,93); v16->SetDataByteOrderToLittleEndian(); v16->SetFilePrefix (fname2); v16->SetDataSpacing (3.2, 3.2, 1.5); // An isosurface, or contour value of 500 is known to correspond to the // skin of the patient. Once generated, a vtkPolyDataNormals filter is // is used to create normals for smooth surface shading during rendering. vtkContourFilter *skinExtractor = vtkContourFilter::New(); skinExtractor->SetInputConnection(v16->GetOutputPort()); skinExtractor->SetValue(0, 500); vtkPolyDataNormals *skinNormals = vtkPolyDataNormals::New(); skinNormals->SetInputConnection(skinExtractor->GetOutputPort()); skinNormals->SetFeatureAngle(60.0); vtkPolyDataMapper *skinMapper = vtkPolyDataMapper::New(); skinMapper->SetInputConnection(skinNormals->GetOutputPort()); skinMapper->ScalarVisibilityOff(); vtkActor *skin = vtkActor::New(); skin->SetMapper(skinMapper); skin->GetProperty()->SetColor(0.95,0.75,0.75); aRenderer->AddActor(skin); v16->Delete(); skinExtractor->Delete(); skinNormals->Delete(); skinMapper->Delete(); skin->Delete(); delete [] fname2; return skin; } //----------------------------------------------------------------------------- // Create a few actors first vtkActor * CreateActor2( int vtkNotUsed(argc), char **vtkNotUsed(argv), vtkRenderer * ren ) { vtkSphereSource *ss = vtkSphereSource::New(); ss->SetThetaResolution(30); ss->SetPhiResolution(30); ss->SetRadius(150.0); vtkPolyDataMapper *mapper = vtkPolyDataMapper::New(); mapper->SetInput(ss->GetOutput()); vtkActor *actor = vtkActor::New(); actor->SetMapper(mapper); actor->GetProperty()->SetColor(0.0,1.0,0.0); ren->AddActor(actor); ss->Delete(); mapper->Delete(); actor->Delete(); return actor; } //----------------------------------------------------------------------------- // Command to write out picked actors during mouse over. class TestScenePickerCommand : public vtkCommand { public: vtkScenePicker * m_Picker; static TestScenePickerCommand *New() { return new TestScenePickerCommand; } virtual void Execute(vtkObject *caller, unsigned long vtkNotUsed(eventId), void* vtkNotUsed(callData)) { vtkRenderWindowInteractor * iren = reinterpret_cast< vtkRenderWindowInteractor *>(caller); int e[2]; iren->GetEventPosition(e); cout << "DisplayPosition : (" << e[0] << "," << e[1] << ")" << " Prop: " << m_ActorDescription[m_Picker->GetViewProp(e)].c_str() << " CellId: " << m_Picker->GetCellId(e) << " VertexId: " << m_Picker->GetVertexId(e) << endl; } void SetActorDescription( vtkProp *a, vtkstd::string s ) { this->m_ActorDescription[a] = s; } vtkstd::map< vtkProp *, vtkstd::string > m_ActorDescription; protected: TestScenePickerCommand() { this->SetActorDescription(static_cast<vtkActor*>(NULL), "None"); } virtual ~TestScenePickerCommand() {} }; //----------------------------------------------------------------------------- int TestScenePicker(int argc, char* argv[]) { vtkRenderer *ren = vtkRenderer::New(); vtkRenderWindow *renWin = vtkRenderWindow::New(); renWin->SetStencilCapable(1); vtkRenderWindowInteractor *iren = vtkRenderWindowInteractor::New(); renWin->AddRenderer(ren); iren->SetRenderWindow(renWin); ren->SetBackground(0.0, 0.0, 0.0); renWin->SetSize(300, 300); // Here comes the scene picker stuff. [ Just 2 lines ] vtkScenePicker * picker = vtkScenePicker::New(); picker->SetRenderer(ren); // Write some stuff for interactive stuff. TestScenePickerCommand * command = TestScenePickerCommand::New(); command->m_Picker = picker; command->SetActorDescription( CreateActor1( argc, argv, ren ), "Head" ); command->SetActorDescription( CreateActor2( argc, argv, ren ), "Sphere" ); iren->AddObserver(vtkCommand::MouseMoveEvent, command); renWin->Render(); int retVal = EXIT_SUCCESS; int tryit = 1; int rgba[4]; int e[2] = {175, 215}; renWin->GetColorBufferSizes(rgba); if (rgba[0] < 8 || rgba[1] < 8 || rgba[2] < 8) { cerr << "Must have at least 24 bit color depth for cell selection." << endl; tryit = 0; } if (!renWin->GetStencilCapable()) { cerr << "Vertex selection will not work without stencil capable rendering." << endl; //tryit = 0; //test doesn't exercise vertex selection } iren->Initialize(); if (tryit) { // Check if scene picking works. if (command->m_ActorDescription[picker->GetViewProp(e)] != "Head" || picker->GetCellId(e) != 50992) { retVal = EXIT_FAILURE; } } for ( int i = 0; i < argc; ++i ) { if ( ! strcmp( argv[i], "-I" ) ) { iren->Start(); } } // Cleanups command->Delete(); picker->Delete(); ren->Delete(); renWin->Delete(); iren->Delete(); return retVal; }
Check and warn when renderwindow is not capable of doing visible cell/point selection.
BUG: Check and warn when renderwindow is not capable of doing visible cell/point selection.
C++
bsd-3-clause
sankhesh/VTK,berendkleinhaneveld/VTK,biddisco/VTK,arnaudgelas/VTK,berendkleinhaneveld/VTK,cjh1/VTK,msmolens/VTK,Wuteyan/VTK,biddisco/VTK,cjh1/VTK,daviddoria/PointGraphsPhase1,demarle/VTK,spthaolt/VTK,aashish24/VTK-old,aashish24/VTK-old,Wuteyan/VTK,mspark93/VTK,hendradarwin/VTK,gram526/VTK,ashray/VTK-EVM,candy7393/VTK,keithroe/vtkoptix,sankhesh/VTK,jeffbaumes/jeffbaumes-vtk,jeffbaumes/jeffbaumes-vtk,mspark93/VTK,johnkit/vtk-dev,aashish24/VTK-old,ashray/VTK-EVM,johnkit/vtk-dev,biddisco/VTK,biddisco/VTK,keithroe/vtkoptix,jmerkow/VTK,mspark93/VTK,jmerkow/VTK,naucoin/VTKSlicerWidgets,spthaolt/VTK,johnkit/vtk-dev,Wuteyan/VTK,sumedhasingla/VTK,sumedhasingla/VTK,sumedhasingla/VTK,msmolens/VTK,mspark93/VTK,jmerkow/VTK,ashray/VTK-EVM,arnaudgelas/VTK,biddisco/VTK,demarle/VTK,ashray/VTK-EVM,hendradarwin/VTK,arnaudgelas/VTK,sankhesh/VTK,SimVascular/VTK,jeffbaumes/jeffbaumes-vtk,mspark93/VTK,sumedhasingla/VTK,sumedhasingla/VTK,Wuteyan/VTK,daviddoria/PointGraphsPhase1,jmerkow/VTK,SimVascular/VTK,ashray/VTK-EVM,hendradarwin/VTK,candy7393/VTK,hendradarwin/VTK,sumedhasingla/VTK,demarle/VTK,berendkleinhaneveld/VTK,Wuteyan/VTK,cjh1/VTK,johnkit/vtk-dev,collects/VTK,sumedhasingla/VTK,collects/VTK,mspark93/VTK,cjh1/VTK,arnaudgelas/VTK,cjh1/VTK,msmolens/VTK,keithroe/vtkoptix,gram526/VTK,sankhesh/VTK,johnkit/vtk-dev,biddisco/VTK,sumedhasingla/VTK,berendkleinhaneveld/VTK,demarle/VTK,gram526/VTK,daviddoria/PointGraphsPhase1,berendkleinhaneveld/VTK,arnaudgelas/VTK,SimVascular/VTK,SimVascular/VTK,candy7393/VTK,sankhesh/VTK,cjh1/VTK,collects/VTK,candy7393/VTK,naucoin/VTKSlicerWidgets,jeffbaumes/jeffbaumes-vtk,jeffbaumes/jeffbaumes-vtk,mspark93/VTK,candy7393/VTK,msmolens/VTK,jeffbaumes/jeffbaumes-vtk,demarle/VTK,naucoin/VTKSlicerWidgets,SimVascular/VTK,keithroe/vtkoptix,biddisco/VTK,SimVascular/VTK,msmolens/VTK,demarle/VTK,naucoin/VTKSlicerWidgets,candy7393/VTK,naucoin/VTKSlicerWidgets,spthaolt/VTK,hendradarwin/VTK,keithroe/vtkoptix,gram526/VTK,ashray/VTK-EVM,jmerkow/VTK,berendkleinhaneveld/VTK,spthaolt/VTK,SimVascular/VTK,collects/VTK,berendkleinhaneveld/VTK,gram526/VTK,keithroe/vtkoptix,daviddoria/PointGraphsPhase1,Wuteyan/VTK,sankhesh/VTK,johnkit/vtk-dev,collects/VTK,jmerkow/VTK,SimVascular/VTK,gram526/VTK,mspark93/VTK,naucoin/VTKSlicerWidgets,Wuteyan/VTK,sankhesh/VTK,ashray/VTK-EVM,keithroe/vtkoptix,spthaolt/VTK,hendradarwin/VTK,ashray/VTK-EVM,daviddoria/PointGraphsPhase1,demarle/VTK,candy7393/VTK,spthaolt/VTK,johnkit/vtk-dev,collects/VTK,keithroe/vtkoptix,jmerkow/VTK,sankhesh/VTK,candy7393/VTK,aashish24/VTK-old,msmolens/VTK,msmolens/VTK,daviddoria/PointGraphsPhase1,demarle/VTK,spthaolt/VTK,aashish24/VTK-old,hendradarwin/VTK,arnaudgelas/VTK,aashish24/VTK-old,msmolens/VTK,gram526/VTK,gram526/VTK,jmerkow/VTK
b682adaee9fa9e360e428db2d71328c2d8d7fbed
src/tools/qtcreatorcrashhandler/crashhandlersetup.cpp
src/tools/qtcreatorcrashhandler/crashhandlersetup.cpp
/************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "crashhandlersetup.h" #include <QtGlobal> #if !defined(QT_NO_DEBUG) && defined(Q_OS_LINUX) #define BUILD_CRASH_HANDLER #endif #ifdef BUILD_CRASH_HANDLER #include <QApplication> #include <QDebug> #include <QString> #include <stdlib.h> #include <errno.h> #include <signal.h> #include <string.h> #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> #ifdef Q_WS_X11 #include <qx11info_x11.h> #include <X11/Xlib.h> #endif static const char *crashHandlerPathC; static void *signalHandlerStack; extern "C" void signalHandler(int signal) { #ifdef Q_WS_X11 // Kill window since it's frozen anyway. if (QX11Info::display()) close(ConnectionNumber(QX11Info::display())); #endif pid_t pid = fork(); switch (pid) { case -1: // error break; case 0: // child execl(crashHandlerPathC, crashHandlerPathC, strsignal(signal), (char *) 0); _exit(EXIT_FAILURE); default: // parent waitpid(pid, 0, 0); _exit(EXIT_FAILURE); break; } } #endif // BUILD_CRASH_HANDLER void setupCrashHandler() { #ifdef BUILD_CRASH_HANDLER const QString crashHandlerPath = qApp->applicationDirPath() + QLatin1String("/qtcreator_crash_handler"); crashHandlerPathC = qstrdup(qPrintable(crashHandlerPath)); // Setup an alternative stack for the signal handler. This way we are able to handle SIGSEGV // even if the normal process stack is exhausted. stack_t ss; ss.ss_sp = signalHandlerStack = malloc(SIGSTKSZ); // Usual requirements for alternative signal stack. if (ss.ss_sp == 0) { qWarning("Warning: Could not allocate space for alternative signal stack (%s).", Q_FUNC_INFO); return; } ss.ss_size = SIGSTKSZ; ss.ss_flags = 0; if (sigaltstack(&ss, 0) == -1) { qWarning("Warning: Failed to set alternative signal stack (%s).", Q_FUNC_INFO); return; } // Install signal handler for calling the crash handler. struct sigaction sa; if (sigemptyset(&sa.sa_mask) == -1) { qWarning("Warning: Failed to empty signal set (%s).", Q_FUNC_INFO); return; } sa.sa_handler = &signalHandler; // SA_RESETHAND - Restore signal action to default after signal handler has been called. // SA_NODEFER - Don't block the signal after it was triggered (otherwise blocked signals get // inherited via fork() and execve()). Without this the signal will not be delivered to the // restarted Qt Creator. // SA_ONSTACK - Use alternative stack. sa.sa_flags = SA_RESETHAND | SA_NODEFER | SA_ONSTACK; const int signalsToHandle[] = { SIGILL, SIGFPE, SIGSEGV, SIGBUS, 0 }; for (int i = 0; signalsToHandle[i]; ++i) { if (sigaction(signalsToHandle[i], &sa, 0) == -1 ) { qWarning("Warning: Failed to install signal handler for signal \"%s\" (%s).", strsignal(signalsToHandle[i]), Q_FUNC_INFO); } } #endif // BUILD_CRASH_HANDLER } void cleanupCrashHandler() { #ifdef BUILD_CRASH_HANDLER delete[] crashHandlerPathC; free(signalHandlerStack); #endif }
/************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "crashhandlersetup.h" #include <QtGlobal> #if !defined(QT_NO_DEBUG) && defined(Q_OS_LINUX) #define BUILD_CRASH_HANDLER #endif #ifdef BUILD_CRASH_HANDLER #include <QApplication> #include <QDebug> #include <QString> #include <stdlib.h> #include <errno.h> #include <signal.h> #include <string.h> #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> #ifdef Q_WS_X11 #include <qx11info_x11.h> #include <X11/Xlib.h> #endif static const char *crashHandlerPathC; static void *signalHandlerStack; extern "C" void signalHandler(int signal) { #ifdef Q_WS_X11 // Kill window since it's frozen anyway. if (QX11Info::display()) close(ConnectionNumber(QX11Info::display())); #endif pid_t pid = fork(); switch (pid) { case -1: // error break; case 0: // child execl(crashHandlerPathC, crashHandlerPathC, strsignal(signal), (char *) 0); _exit(EXIT_FAILURE); default: // parent waitpid(pid, 0, 0); _exit(EXIT_FAILURE); break; } } #endif // BUILD_CRASH_HANDLER void setupCrashHandler() { #ifdef BUILD_CRASH_HANDLER const QString crashHandlerPath = qApp->applicationDirPath() + QLatin1String("/qtcreator_crash_handler"); crashHandlerPathC = qstrdup(qPrintable(crashHandlerPath)); // Setup an alternative stack for the signal handler. This way we are able to handle SIGSEGV // even if the normal process stack is exhausted. stack_t ss; ss.ss_sp = signalHandlerStack = malloc(SIGSTKSZ); // Usual requirements for alternative signal stack. if (ss.ss_sp == 0) { qWarning("Warning: Could not allocate space for alternative signal stack (%s).", Q_FUNC_INFO); return; } ss.ss_size = SIGSTKSZ; ss.ss_flags = 0; if (sigaltstack(&ss, 0) == -1) { qWarning("Warning: Failed to set alternative signal stack (%s).", Q_FUNC_INFO); return; } // Install signal handler for calling the crash handler. struct sigaction sa; if (sigemptyset(&sa.sa_mask) == -1) { qWarning("Warning: Failed to empty signal set (%s).", Q_FUNC_INFO); return; } sa.sa_handler = &signalHandler; // SA_RESETHAND - Restore signal action to default after signal handler has been called. // SA_NODEFER - Don't block the signal after it was triggered (otherwise blocked signals get // inherited via fork() and execve()). Without this the signal will not be delivered to the // restarted Qt Creator. // SA_ONSTACK - Use alternative stack. sa.sa_flags = SA_RESETHAND | SA_NODEFER | SA_ONSTACK; // See "man 7 signal" for an overview of signals. // Do not add SIGPIPE here, QProcess and QTcpSocket use it. const int signalsToHandle[] = { SIGILL, SIGABRT, SIGFPE, SIGSEGV, SIGBUS, 0 }; for (int i = 0; signalsToHandle[i]; ++i) { if (sigaction(signalsToHandle[i], &sa, 0) == -1 ) { qWarning("Warning: Failed to install signal handler for signal \"%s\" (%s).", strsignal(signalsToHandle[i]), Q_FUNC_INFO); } } #endif // BUILD_CRASH_HANDLER } void cleanupCrashHandler() { #ifdef BUILD_CRASH_HANDLER delete[] crashHandlerPathC; free(signalHandlerStack); #endif }
Handle signal SIGABRT
CrashHandler: Handle signal SIGABRT This signal is generated if abort() is called. This happens e.g. 1. if there is an attempt to call a pure virtual method 2. if Qt detects an uncaught exception or printing a message fails (qlogging.cpp, qt_message()) Change-Id: I6a1d8f094a884ebc6bfc6a1fc168aea8afe825b5 Reviewed-by: Christian Kandeler <[email protected]>
C++
lgpl-2.1
kuba1/qtcreator,xianian/qt-creator,malikcjm/qtcreator,kuba1/qtcreator,AltarBeastiful/qt-creator,maui-packages/qt-creator,kuba1/qtcreator,darksylinc/qt-creator,omniacreator/qtcreator,maui-packages/qt-creator,xianian/qt-creator,farseerri/git_code,AltarBeastiful/qt-creator,farseerri/git_code,xianian/qt-creator,martyone/sailfish-qtcreator,richardmg/qtcreator,colede/qtcreator,colede/qtcreator,omniacreator/qtcreator,malikcjm/qtcreator,danimo/qt-creator,amyvmiwei/qt-creator,darksylinc/qt-creator,omniacreator/qtcreator,amyvmiwei/qt-creator,Distrotech/qtcreator,farseerri/git_code,duythanhphan/qt-creator,malikcjm/qtcreator,malikcjm/qtcreator,farseerri/git_code,xianian/qt-creator,maui-packages/qt-creator,AltarBeastiful/qt-creator,xianian/qt-creator,malikcjm/qtcreator,xianian/qt-creator,colede/qtcreator,danimo/qt-creator,amyvmiwei/qt-creator,martyone/sailfish-qtcreator,malikcjm/qtcreator,kuba1/qtcreator,AltarBeastiful/qt-creator,colede/qtcreator,danimo/qt-creator,darksylinc/qt-creator,duythanhphan/qt-creator,martyone/sailfish-qtcreator,colede/qtcreator,martyone/sailfish-qtcreator,maui-packages/qt-creator,danimo/qt-creator,amyvmiwei/qt-creator,AltarBeastiful/qt-creator,richardmg/qtcreator,colede/qtcreator,omniacreator/qtcreator,duythanhphan/qt-creator,AltarBeastiful/qt-creator,danimo/qt-creator,maui-packages/qt-creator,martyone/sailfish-qtcreator,darksylinc/qt-creator,richardmg/qtcreator,omniacreator/qtcreator,farseerri/git_code,richardmg/qtcreator,duythanhphan/qt-creator,maui-packages/qt-creator,danimo/qt-creator,Distrotech/qtcreator,danimo/qt-creator,AltarBeastiful/qt-creator,richardmg/qtcreator,farseerri/git_code,Distrotech/qtcreator,martyone/sailfish-qtcreator,darksylinc/qt-creator,martyone/sailfish-qtcreator,kuba1/qtcreator,omniacreator/qtcreator,darksylinc/qt-creator,duythanhphan/qt-creator,Distrotech/qtcreator,amyvmiwei/qt-creator,maui-packages/qt-creator,richardmg/qtcreator,richardmg/qtcreator,Distrotech/qtcreator,amyvmiwei/qt-creator,duythanhphan/qt-creator,danimo/qt-creator,martyone/sailfish-qtcreator,colede/qtcreator,AltarBeastiful/qt-creator,xianian/qt-creator,xianian/qt-creator,martyone/sailfish-qtcreator,xianian/qt-creator,kuba1/qtcreator,malikcjm/qtcreator,Distrotech/qtcreator,amyvmiwei/qt-creator,darksylinc/qt-creator,duythanhphan/qt-creator,kuba1/qtcreator,kuba1/qtcreator,kuba1/qtcreator,farseerri/git_code,amyvmiwei/qt-creator,omniacreator/qtcreator,Distrotech/qtcreator,danimo/qt-creator,darksylinc/qt-creator,farseerri/git_code
70f2a1f9850faac9cccca7083a7477e80c38d093
src/tracing/processors/timed_stream_vcd_processor.cpp
src/tracing/processors/timed_stream_vcd_processor.cpp
#include "tvs/tracing/processors/timed_stream_vcd_processor.h" #include "tvs/tracing/processors/timed_stream_processor_base.h" #include "tvs/utils/assert.h" #include "tvs/utils/report.h" #include "tvs/tracing/report_msgs.h" #include <cstdint> #include <map> namespace tracing { char const* vcd_stream_container_base::scope() const { #ifndef SYSX_NO_SYSTEMC if (scope_.empty()) { auto parent = this->reader().stream().get_parent_object(); if (parent != nullptr) return parent->name(); } #endif return scope_.c_str(); } timed_stream_vcd_processor::timed_stream_vcd_processor(char const* modscope, std::ostream& out) : named_object(modscope) , out_(out) {} timed_stream_vcd_processor::~timed_stream_vcd_processor() { out_ << "$vcdclose " << this->local_time() << " $end\n"; } std::string timed_stream_vcd_processor::next_identifier() { // ASCII start/end characters for encoding the wire ID char const first_id = '!'; char const last_id = '~'; int const range = last_id - first_id + 1; auto next = vcd_id_++; // produce an identifier in the range [first_id, last_id] with the necessary // amount of character symbols std::string id{}; do { int rem = next % range; id.insert(id.begin(), rem + first_id); next /= range; } while (next != 0); return id; } void timed_stream_vcd_processor::print_timestamp(time_type const& stamp) { using sysx::units::sc_time_cast; out_ << "#" << static_cast<uint64_t>(sc_time_cast<sysx::units::time_type>(stamp) / scale_) << "\n"; } void timed_stream_vcd_processor::write_header() { out_ << "$timescale " << sysx::units::engineering_prefix << scale_ << " $end\n"; out_ << "$scope module " << this->name() << " $end\n"; for (const auto& vcd : this->vcd_streams_) { if (vcd->scope() != std::string("")) { out_ << "$scope module " << vcd->scope() << " $end\n"; vcd->print_node_information(out_); out_ << "$upscope $end\n"; } else { vcd->print_node_information(out_); } } out_ << "$upscope $end\n"; out_ << "$enddefinitions $end\n" << "$dumpvars\n"; for (auto&& vcd : this->vcd_streams_) { vcd->print_default_value(out_); } out_ << "$end\n"; } void timed_stream_vcd_processor::notify(reader_base_type&) { if (!header_written_) { write_header(); header_written_ = true; } // find the minimum available time of all VCD input streams auto it = std::min_element(this->inputs().cbegin(), this->inputs().cend(), [](std::shared_ptr<timed_reader_base> const& lhs, std::shared_ptr<timed_reader_base> const& rhs) { return lhs->available_until() < rhs->available_until(); }); time_type until = (*it)->available_until(); if (until <= local_time()) { return; } // create a map of all tuples to order them std::multimap<time_type, std::string> ordered; for (auto&& vcd : this->vcd_streams_) { auto& rd = vcd->reader(); while (rd.available() && rd.local_time() <= until) { if (vcd->value_changed()) { vcd->print_front_value(temp_sstr_); ordered.insert(std::make_pair(rd.local_time(), temp_sstr_.str())); temp_sstr_.str(""); vcd->update_value(); } rd.pop(); } } // print the ordered tuples and the time stamp if necessary time_type stamp = duration_type::infinity(); for (auto&& o : ordered) { if (stamp != o.first) { print_timestamp(o.first); stamp = o.first; } out_ << o.second; } commit(until); } } // namespace tracing
#include "tvs/tracing/processors/timed_stream_vcd_processor.h" #include "tvs/tracing/processors/timed_stream_processor_base.h" #include "tvs/utils/assert.h" #include "tvs/utils/report.h" #include "tvs/tracing/report_msgs.h" #include <cstdint> #include <map> namespace tracing { char const* vcd_stream_container_base::scope() const { #ifndef SYSX_NO_SYSTEMC if (scope_.empty()) { auto parent = this->reader().stream().get_parent_object(); if (parent != nullptr) return parent->name(); } #endif return scope_.c_str(); } timed_stream_vcd_processor::timed_stream_vcd_processor(char const* modscope, std::ostream& out) : named_object(modscope) , out_(out) {} timed_stream_vcd_processor::~timed_stream_vcd_processor() { print_timestamp(this->local_time()); out_ << "$vcdclose " << this->local_time() << " $end\n"; } std::string timed_stream_vcd_processor::next_identifier() { // ASCII start/end characters for encoding the wire ID char const first_id = '!'; char const last_id = '~'; int const range = last_id - first_id + 1; auto next = vcd_id_++; // produce an identifier in the range [first_id, last_id] with the necessary // amount of character symbols std::string id{}; do { int rem = next % range; id.insert(id.begin(), rem + first_id); next /= range; } while (next != 0); return id; } void timed_stream_vcd_processor::print_timestamp(time_type const& stamp) { using sysx::units::sc_time_cast; out_ << "#" << static_cast<uint64_t>(sc_time_cast<sysx::units::time_type>(stamp) / scale_) << "\n"; } void timed_stream_vcd_processor::write_header() { out_ << "$timescale " << sysx::units::engineering_prefix << scale_ << " $end\n"; out_ << "$scope module " << this->name() << " $end\n"; for (const auto& vcd : this->vcd_streams_) { if (vcd->scope() != std::string("")) { out_ << "$scope module " << vcd->scope() << " $end\n"; vcd->print_node_information(out_); out_ << "$upscope $end\n"; } else { vcd->print_node_information(out_); } } out_ << "$upscope $end\n"; out_ << "$enddefinitions $end\n" << "$dumpvars\n"; for (auto&& vcd : this->vcd_streams_) { vcd->print_default_value(out_); } out_ << "$end\n"; } void timed_stream_vcd_processor::notify(reader_base_type&) { if (!header_written_) { write_header(); header_written_ = true; } // find the minimum available time of all VCD input streams auto it = std::min_element(this->inputs().cbegin(), this->inputs().cend(), [](std::shared_ptr<timed_reader_base> const& lhs, std::shared_ptr<timed_reader_base> const& rhs) { return lhs->available_until() < rhs->available_until(); }); time_type until = (*it)->available_until(); if (until <= local_time()) { return; } // create a map of all tuples to order them std::multimap<time_type, std::string> ordered; for (auto&& vcd : this->vcd_streams_) { auto& rd = vcd->reader(); while (rd.available() && rd.local_time() <= until) { if (vcd->value_changed()) { vcd->print_front_value(temp_sstr_); ordered.insert(std::make_pair(rd.local_time(), temp_sstr_.str())); temp_sstr_.str(""); vcd->update_value(); } rd.pop(); } } // print the ordered tuples and the time stamp if necessary time_type stamp = duration_type::infinity(); for (auto&& o : ordered) { if (stamp != o.first) { print_timestamp(o.first); stamp = o.first; } out_ << o.second; } commit(until); } } // namespace tracing
print final timestamp in VCD file
vcd: print final timestamp in VCD file
C++
apache-2.0
offis/libtvs,offis/libtvs
beb41cd5e257f2d2eb0cea64426c01fe21840b29
core/propertyBag/accountPropertyBag.cpp
core/propertyBag/accountPropertyBag.cpp
#include <core/stdafx.h> #include <core/propertyBag/accountPropertyBag.h> #include <core/mapi/mapiFunctions.h> #include <core/mapi/mapiMemory.h> #include <core/mapi/account/actMgmt.h> namespace propertybag { accountPropertyBag::accountPropertyBag(std::wstring lpwszProfile, LPOLKACCOUNT lpAccount) { m_lpwszProfile = lpwszProfile; m_lpAccount = mapi::safe_cast<LPOLKACCOUNT>(lpAccount); } accountPropertyBag ::~accountPropertyBag() { if (m_lpAccount) m_lpAccount->Release(); m_lpAccount = nullptr; } propBagFlags accountPropertyBag::GetFlags() const { auto ulFlags = propBagFlags::None; return ulFlags; } bool accountPropertyBag::IsEqual(const std::shared_ptr<IMAPIPropertyBag> lpPropBag) const { if (!lpPropBag) return false; if (GetType() != lpPropBag->GetType()) return false; // Two accounts are the same if their profile is the same const auto lpOther = std::dynamic_pointer_cast<accountPropertyBag>(lpPropBag); if (lpOther) { if (m_lpwszProfile != lpOther->m_lpwszProfile) return false; return true; } return false; } // Convert an ACCT_VARIANT to SPropValue allocated off of pParent // Frees any memory associated with the ACCT_VARIANT SPropValue accountPropertyBag::convertVarToMAPI(ULONG ulPropTag, ACCT_VARIANT var, _In_opt_ const VOID* pParent) { SPropValue sProp = {}; sProp.ulPropTag = ulPropTag; switch (PROP_TYPE(ulPropTag)) { case PT_LONG: sProp.Value.l = var.Val.dw; break; case PT_UNICODE: sProp.Value.lpszW = mapi::CopyStringW(var.Val.pwsz, pParent); (void) m_lpAccount->FreeMemory(reinterpret_cast<LPBYTE>(var.Val.pwsz)); break; case PT_BINARY: auto bin = SBinary{var.Val.bin.cb, var.Val.bin.pb}; sProp.Value.bin = mapi::CopySBinary(bin, pParent); (void) m_lpAccount->FreeMemory(reinterpret_cast<LPBYTE>(var.Val.bin.pb)); break; } return sProp; } _Check_return_ HRESULT accountPropertyBag::GetAllProps(ULONG FAR* lpcValues, LPSPropValue FAR* lppPropArray) { if (!lpcValues || !lppPropArray) return MAPI_E_INVALID_PARAMETER; if (!m_lpAccount) { *lpcValues = 0; *lppPropArray = nullptr; return S_OK; } // Just return what we have auto hRes = S_OK; ULONG i = 0; std::vector<std::pair<ULONG, ACCT_VARIANT>> props = {}; for (i = 0; i < 0x8000; i++) { ACCT_VARIANT pProp = {}; hRes = m_lpAccount->GetProp(PROP_TAG(PT_LONG, i), &pProp); if (SUCCEEDED(hRes)) { props.emplace_back(PROP_TAG(PT_LONG, i), pProp); } hRes = m_lpAccount->GetProp(PROP_TAG(PT_UNICODE, i), &pProp); if (SUCCEEDED(hRes)) { props.emplace_back(PROP_TAG(PT_UNICODE, i), pProp); } hRes = m_lpAccount->GetProp(PROP_TAG(PT_BINARY, i), &pProp); if (SUCCEEDED(hRes)) { props.emplace_back(PROP_TAG(PT_BINARY, i), pProp); } } if (props.size() > 0) { *lpcValues = props.size(); *lppPropArray = mapi::allocate<LPSPropValue>(props.size() * sizeof(SPropValue)); auto iProp = 0; for (const auto prop : props) { (*lppPropArray)[iProp] = convertVarToMAPI(prop.first, prop.second, *lppPropArray); iProp++; } } return S_OK; } _Check_return_ HRESULT accountPropertyBag::GetProps( LPSPropTagArray /*lpPropTagArray*/, ULONG /*ulFlags*/, ULONG FAR* /*lpcValues*/, LPSPropValue FAR* /*lppPropArray*/) { // TODO: See if accounts could support this // This is only called from the Extra Props code. We can't support Extra Props from a row // so we don't need to implement this. return E_NOTIMPL; } _Check_return_ HRESULT accountPropertyBag::GetProp(ULONG ulPropTag, LPSPropValue FAR* lppProp) { if (!lppProp) return MAPI_E_INVALID_PARAMETER; *lppProp = mapi::allocate<LPSPropValue>(sizeof(SPropValue)); auto pProp = ACCT_VARIANT{}; const auto hRes = m_lpAccount->GetProp(ulPropTag, &pProp); if (SUCCEEDED(hRes)) { (*lppProp)[0] = convertVarToMAPI(ulPropTag, pProp, *lppProp); } else { (*lppProp)->ulPropTag = CHANGE_PROP_TYPE(ulPropTag, PT_ERROR); (*lppProp)->Value.err = hRes; } return S_OK; } _Check_return_ HRESULT accountPropertyBag::SetProp(LPSPropValue lpProp) { return E_NOTIMPL; } } // namespace propertybag
#include <core/stdafx.h> #include <core/propertyBag/accountPropertyBag.h> #include <core/mapi/mapiFunctions.h> #include <core/mapi/mapiMemory.h> #include <core/mapi/account/actMgmt.h> namespace propertybag { accountPropertyBag::accountPropertyBag(std::wstring lpwszProfile, LPOLKACCOUNT lpAccount) { m_lpwszProfile = lpwszProfile; m_lpAccount = mapi::safe_cast<LPOLKACCOUNT>(lpAccount); } accountPropertyBag ::~accountPropertyBag() { if (m_lpAccount) m_lpAccount->Release(); m_lpAccount = nullptr; } propBagFlags accountPropertyBag::GetFlags() const { auto ulFlags = propBagFlags::None; return ulFlags; } bool accountPropertyBag::IsEqual(const std::shared_ptr<IMAPIPropertyBag> lpPropBag) const { if (!lpPropBag) return false; if (GetType() != lpPropBag->GetType()) return false; // Two accounts are the same if their profile is the same const auto lpOther = std::dynamic_pointer_cast<accountPropertyBag>(lpPropBag); if (lpOther) { if (m_lpwszProfile != lpOther->m_lpwszProfile) return false; return true; } return false; } // Convert an ACCT_VARIANT to SPropValue allocated off of pParent // Frees any memory associated with the ACCT_VARIANT SPropValue accountPropertyBag::convertVarToMAPI(ULONG ulPropTag, ACCT_VARIANT var, _In_opt_ const VOID* pParent) { SPropValue sProp = {}; sProp.ulPropTag = ulPropTag; switch (PROP_TYPE(ulPropTag)) { case PT_LONG: sProp.Value.l = var.Val.dw; break; case PT_UNICODE: sProp.Value.lpszW = mapi::CopyStringW(var.Val.pwsz, pParent); (void) m_lpAccount->FreeMemory(reinterpret_cast<LPBYTE>(var.Val.pwsz)); break; case PT_BINARY: auto bin = SBinary{var.Val.bin.cb, var.Val.bin.pb}; sProp.Value.bin = mapi::CopySBinary(bin, pParent); (void) m_lpAccount->FreeMemory(reinterpret_cast<LPBYTE>(var.Val.bin.pb)); break; } return sProp; } _Check_return_ HRESULT accountPropertyBag::GetAllProps(ULONG FAR* lpcValues, LPSPropValue FAR* lppPropArray) { if (!lpcValues || !lppPropArray) return MAPI_E_INVALID_PARAMETER; if (!m_lpAccount) { *lpcValues = 0; *lppPropArray = nullptr; return S_OK; } auto hRes = S_OK; ULONG i = 0; std::vector<std::pair<ULONG, ACCT_VARIANT>> props = {}; for (i = 0; i < 0x8000; i++) { ACCT_VARIANT pProp = {}; hRes = m_lpAccount->GetProp(PROP_TAG(PT_LONG, i), &pProp); if (SUCCEEDED(hRes)) { props.emplace_back(PROP_TAG(PT_LONG, i), pProp); } hRes = m_lpAccount->GetProp(PROP_TAG(PT_UNICODE, i), &pProp); if (SUCCEEDED(hRes)) { props.emplace_back(PROP_TAG(PT_UNICODE, i), pProp); } hRes = m_lpAccount->GetProp(PROP_TAG(PT_BINARY, i), &pProp); if (SUCCEEDED(hRes)) { props.emplace_back(PROP_TAG(PT_BINARY, i), pProp); } } if (props.size() > 0) { *lpcValues = props.size(); *lppPropArray = mapi::allocate<LPSPropValue>(props.size() * sizeof(SPropValue)); auto iProp = 0; for (const auto& prop : props) { (*lppPropArray)[iProp] = convertVarToMAPI(prop.first, prop.second, *lppPropArray); iProp++; } } return S_OK; } _Check_return_ HRESULT accountPropertyBag::GetProps( LPSPropTagArray lpPropTagArray, ULONG ulFlags, ULONG FAR* lpcValues, LPSPropValue FAR* lppPropArray) { if (!lpcValues || !lppPropArray) return MAPI_E_INVALID_PARAMETER; if (!m_lpAccount || !lpPropTagArray) { *lpcValues = 0; *lppPropArray = nullptr; return S_OK; } *lpcValues = lpPropTagArray->cValues; *lppPropArray = mapi::allocate<LPSPropValue>(lpPropTagArray->cValues * sizeof(SPropValue)); for (ULONG iProp = 0; iProp < lpPropTagArray->cValues; iProp++) { ACCT_VARIANT pProp = {}; const auto ulPropTag = lpPropTagArray->aulPropTag[iProp]; const auto hRes = m_lpAccount->GetProp(ulPropTag, &pProp); if (SUCCEEDED(hRes)) { (*lppPropArray)[iProp] = convertVarToMAPI(ulPropTag, pProp, *lppPropArray); } else { (*lppPropArray)[iProp].ulPropTag = CHANGE_PROP_TYPE(ulPropTag, PT_ERROR); (*lppPropArray)[iProp].Value.err = hRes; } } return S_OK; } _Check_return_ HRESULT accountPropertyBag::GetProp(ULONG ulPropTag, LPSPropValue FAR* lppProp) { if (!lppProp) return MAPI_E_INVALID_PARAMETER; *lppProp = mapi::allocate<LPSPropValue>(sizeof(SPropValue)); auto pProp = ACCT_VARIANT{}; const auto hRes = m_lpAccount->GetProp(ulPropTag, &pProp); if (SUCCEEDED(hRes)) { (*lppProp)[0] = convertVarToMAPI(ulPropTag, pProp, *lppProp); } else { (*lppProp)->ulPropTag = CHANGE_PROP_TYPE(ulPropTag, PT_ERROR); (*lppProp)->Value.err = hRes; } return S_OK; } _Check_return_ HRESULT accountPropertyBag::SetProp(LPSPropValue lpProp) { return E_NOTIMPL; } } // namespace propertybag
implement GetProps
implement GetProps
C++
mit
stephenegriffin/mfcmapi,stephenegriffin/mfcmapi,stephenegriffin/mfcmapi
0b78219cd31194d423d23d404c349a188b019d43
src/osvr/Common/ClientContext.cpp
src/osvr/Common/ClientContext.cpp
/** @file @brief Implementation @date 2014 @author Sensics, Inc. <http://sensics.com/osvr> */ // Copyright 2014 Sensics, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Internal Includes #include <osvr/Common/ClientContext.h> #include <osvr/Common/ClientInterface.h> #include <osvr/Util/Verbosity.h> #include "GetJSONStringFromTree.h" // Library/third-party includes #include <boost/assert.hpp> // Standard includes #include <algorithm> using ::osvr::common::ClientInterfacePtr; using ::osvr::common::ClientInterface; using ::osvr::make_shared; OSVR_ClientContextObject::OSVR_ClientContextObject(const char appId[]) : m_appId(appId) { OSVR_DEV_VERBOSE("Client context initialized for " << m_appId); } OSVR_ClientContextObject::~OSVR_ClientContextObject() {} std::string const &OSVR_ClientContextObject::getAppId() const { return m_appId; } void OSVR_ClientContextObject::update() { m_update(); for (auto const &iface : m_interfaces) { iface->update(); } } ClientInterfacePtr OSVR_ClientContextObject::getInterface(const char path[]) { ClientInterfacePtr ret; if (!path) { return ret; } std::string p(path); if (p.empty()) { return ret; } ret = make_shared<ClientInterface>(this, path, ClientInterface::PrivateConstructor()); m_handleNewInterface(ret); m_interfaces.push_back(ret); return ret; } ClientInterfacePtr OSVR_ClientContextObject::releaseInterface(ClientInterface *iface) { ClientInterfacePtr ret; if (!iface) { return ret; } InterfaceList::iterator it = std::find_if(begin(m_interfaces), end(m_interfaces), [&](ClientInterfacePtr const &ptr) { if (ptr.get() == iface) { ret = ptr; return true; } return false; }); BOOST_ASSERT_MSG( (it == end(m_interfaces)) == (!ret), "We should have a pointer if and only if we have the iterator"); if (ret) { // Erase it from our list m_interfaces.erase(it); // Notify the derived class if desired m_handleReleasingInterface(ret); } return ret; } std::string OSVR_ClientContextObject::getStringParameter(std::string const &path) const { return getJSONStringFromTree(getPathTree(), path); } osvr::common::PathTree const &OSVR_ClientContextObject::getPathTree() const { return m_getPathTree(); } void OSVR_ClientContextObject::sendRoute(std::string const &route) { m_sendRoute(route); } bool OSVR_ClientContextObject::releaseObject(void *obj) { return m_ownedObjects.release(obj); } void OSVR_ClientContextObject::m_handleNewInterface( ::osvr::common::ClientInterfacePtr const &) { // by default do nothing } void OSVR_ClientContextObject::m_handleReleasingInterface( ::osvr::common::ClientInterfacePtr const &) { // by default do nothing }
/** @file @brief Implementation @date 2014 @author Sensics, Inc. <http://sensics.com/osvr> */ // Copyright 2014 Sensics, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Internal Includes #include <osvr/Common/ClientContext.h> #include <osvr/Common/ClientInterface.h> #include <osvr/Util/Verbosity.h> #include "GetJSONStringFromTree.h" // Library/third-party includes #include <boost/assert.hpp> // Standard includes #include <algorithm> using ::osvr::common::ClientInterfacePtr; using ::osvr::common::ClientInterface; using ::osvr::make_shared; OSVR_ClientContextObject::OSVR_ClientContextObject(const char appId[]) : m_appId(appId) { OSVR_DEV_VERBOSE("Client context initialized for " << m_appId); } OSVR_ClientContextObject::~OSVR_ClientContextObject() { OSVR_DEV_VERBOSE("Client context shut down for " << m_appId); } std::string const &OSVR_ClientContextObject::getAppId() const { return m_appId; } void OSVR_ClientContextObject::update() { m_update(); for (auto const &iface : m_interfaces) { iface->update(); } } ClientInterfacePtr OSVR_ClientContextObject::getInterface(const char path[]) { ClientInterfacePtr ret; if (!path) { return ret; } std::string p(path); if (p.empty()) { return ret; } ret = make_shared<ClientInterface>(this, path, ClientInterface::PrivateConstructor()); m_handleNewInterface(ret); m_interfaces.push_back(ret); return ret; } ClientInterfacePtr OSVR_ClientContextObject::releaseInterface(ClientInterface *iface) { ClientInterfacePtr ret; if (!iface) { return ret; } InterfaceList::iterator it = std::find_if(begin(m_interfaces), end(m_interfaces), [&](ClientInterfacePtr const &ptr) { if (ptr.get() == iface) { ret = ptr; return true; } return false; }); BOOST_ASSERT_MSG( (it == end(m_interfaces)) == (!ret), "We should have a pointer if and only if we have the iterator"); if (ret) { // Erase it from our list m_interfaces.erase(it); // Notify the derived class if desired m_handleReleasingInterface(ret); } return ret; } std::string OSVR_ClientContextObject::getStringParameter(std::string const &path) const { return getJSONStringFromTree(getPathTree(), path); } osvr::common::PathTree const &OSVR_ClientContextObject::getPathTree() const { return m_getPathTree(); } void OSVR_ClientContextObject::sendRoute(std::string const &route) { m_sendRoute(route); } bool OSVR_ClientContextObject::releaseObject(void *obj) { return m_ownedObjects.release(obj); } void OSVR_ClientContextObject::m_handleNewInterface( ::osvr::common::ClientInterfacePtr const &) { // by default do nothing } void OSVR_ClientContextObject::m_handleReleasingInterface( ::osvr::common::ClientInterfacePtr const &) { // by default do nothing }
Add a context shut down message
Add a context shut down message
C++
apache-2.0
feilen/OSVR-Core,godbyk/OSVR-Core,leemichaelRazer/OSVR-Core,d235j/OSVR-Core,Armada651/OSVR-Core,godbyk/OSVR-Core,Armada651/OSVR-Core,OSVR/OSVR-Core,godbyk/OSVR-Core,OSVR/OSVR-Core,feilen/OSVR-Core,godbyk/OSVR-Core,feilen/OSVR-Core,OSVR/OSVR-Core,d235j/OSVR-Core,OSVR/OSVR-Core,Armada651/OSVR-Core,feilen/OSVR-Core,OSVR/OSVR-Core,feilen/OSVR-Core,Armada651/OSVR-Core,leemichaelRazer/OSVR-Core,Armada651/OSVR-Core,OSVR/OSVR-Core,leemichaelRazer/OSVR-Core,godbyk/OSVR-Core,d235j/OSVR-Core,leemichaelRazer/OSVR-Core,leemichaelRazer/OSVR-Core,d235j/OSVR-Core,godbyk/OSVR-Core,d235j/OSVR-Core
c345b192c37e897464bf65f04fe1f6837c3fb76d
src/curl.cpp
src/curl.cpp
/* * Copyright (C) 2009 Toni Gundogdu. * * This file is part of cclive. * * cclive 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. * * cclive is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ #include "config.h" #include <iostream> #include <iomanip> #include <sstream> #include <string> #include <cstdlib> #include <cstring> #include <curl/curl.h> #ifdef HAVE_UNISTD_H #include <unistd.h> #endif #include "except.h" #include "opts.h" #include "macros.h" #include "video.h" #include "progressbar.h" #include "log.h" #include "curl.h" #include "retry.h" static CURL *curl; static std::string formatError (const long& httpcode) { std::stringstream s; s << "server returned http/" << httpcode << ""; return s.str(); } static std::string formatError (const CURLcode& code) { std::stringstream s; s << curl_easy_strerror(code) << " (rc=" << code << ")"; return s.str(); } CurlMgr::CurlMgr() : httpcode(0) { curl = NULL; } // Keeps -Weffc++ happy. CurlMgr::CurlMgr(const CurlMgr& o) : httpcode(o.httpcode) { curl = NULL; } // Ditto. CurlMgr& CurlMgr::operator=(const CurlMgr&) { return *this; } CurlMgr::~CurlMgr() { curl_easy_cleanup(curl); curl = NULL; } void CurlMgr::init() { curl = curl_easy_init(); if (!curl) throw RuntimeException(CCLIVE_CURLINIT); const Options opts = optsmgr.getOptions(); curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1L); curl_easy_setopt(curl, CURLOPT_USERAGENT, opts.agent_arg); curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L); curl_easy_setopt(curl, CURLOPT_AUTOREFERER, 1L); curl_easy_setopt(curl, CURLOPT_NOBODY, 0L); curl_easy_setopt(curl, CURLOPT_VERBOSE, opts.debug_given); const char *proxy = opts.proxy_arg; if (opts.no_proxy_given) proxy = ""; curl_easy_setopt(curl, CURLOPT_PROXY, proxy); } static void * _realloc(void *p, const size_t size) { if (p) return realloc(p,size); return malloc(size); } struct mem_s { size_t size; char *p; }; static size_t callback_writemem(void *p, size_t size, size_t nmemb, void *data) { mem_s *m = reinterpret_cast<mem_s*>(data); const size_t rsize = size * nmemb; void *tmp = _realloc(m->p, m->size+rsize+1); if (tmp) { m->p = reinterpret_cast<char*>(tmp); memcpy(&(m->p[m->size]), p, rsize); m->size += rsize; m->p[m->size] = '\0'; } return rsize; } std::string CurlMgr::fetchToMem(const std::string& url, const std::string &what) { logmgr.cout() << "fetch "; if (what.empty()) logmgr.cout() << url; else logmgr.cout() << what; logmgr.cout() << " ..." << std::flush; curl_easy_setopt(curl, CURLOPT_URL, url.c_str()); curl_easy_setopt(curl, CURLOPT_ENCODING, ""); mem_s mem; memset(&mem, 0, sizeof(mem)); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &mem); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, callback_writemem); const Options opts = optsmgr.getOptions(); curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, opts.connect_timeout_arg); /* * http://curl.haxx.se/docs/knownbugs.html: * * "When connecting to a SOCKS proxy, the (connect) timeout is * not properly acknowledged after the actual TCP connect (during * the SOCKS 'negotiate' phase)." */ curl_easy_setopt(curl, CURLOPT_TIMEOUT, opts.connect_timeout_socks_arg); const CURLcode rc = curl_easy_perform(curl); curl_easy_setopt(curl, CURLOPT_TIMEOUT, 0L); std::string errmsg; httpcode = 0; if (CURLE_OK == rc) { curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &httpcode); if (200 == httpcode) logmgr.cout() << "done." << std::endl; else errmsg = formatError(httpcode); } else errmsg = formatError(rc); std::string content; if (NULL != mem.p) { content = mem.p; _FREE(mem.p); } if (!errmsg.empty()) throw FetchException(errmsg, httpcode); return content; } void CurlMgr::queryFileLength(VideoProperties& props) { FILE *f = tmpfile(); if (!f) { perror("tmpfile"); throw RuntimeException(CCLIVE_SYSTEM); } logmgr.cout() << "verify video link ..." << std::flush; const Options opts = optsmgr.getOptions(); curl_easy_setopt(curl, CURLOPT_URL, props.getLink().c_str()); curl_easy_setopt(curl, CURLOPT_NOBODY, 1L); // GET -> HEAD curl_easy_setopt(curl, CURLOPT_WRITEDATA, f); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, NULL); curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, opts.connect_timeout_arg); curl_easy_setopt(curl, CURLOPT_TIMEOUT, opts.connect_timeout_socks_arg); const CURLcode rc = curl_easy_perform(curl); curl_easy_setopt(curl, CURLOPT_TIMEOUT, 0L); curl_easy_setopt(curl, CURLOPT_HTTPGET, 1L); // reset HEAD -> GET fflush(f); fclose(f); std::string errmsg; httpcode = 0; if (CURLE_OK == rc) { curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &httpcode); if (200 == httpcode || 206 == httpcode) { const char *ct = NULL; curl_easy_getinfo(curl, CURLINFO_CONTENT_TYPE, &ct); double len = 0; curl_easy_getinfo(curl, CURLINFO_CONTENT_LENGTH_DOWNLOAD, &len); props.setLength(len); props.setContentType(ct); logmgr.cout() << "done." << std::endl; } else errmsg = formatError(httpcode); } else errmsg = formatError(rc); if (!errmsg.empty()) throw FetchException(errmsg, httpcode); props.formatOutputFilename(); } struct write_s { write_s() : filename(NULL), initial(0), file(NULL) { } char *filename; double initial; FILE *file; }; static size_t callback_writefile(void *data, size_t size, size_t nmemb, void *p) { write_s *w = reinterpret_cast<write_s*>(p); if (NULL != w && !w->file && NULL != w->filename) { const char *mode = w->initial > 0 ? "ab" : "wb"; w->file = fopen(w->filename, mode); if (!w->file) return -1; } return fwrite(data, size, nmemb, w->file); } int callback_progress( void *p, double total, double now, double utotal, double unow) { ProgressBar *pb = static_cast<ProgressBar*>(p); pb->update(now); return 0; } void CurlMgr::fetchToFile(const VideoProperties& props) { const Options opts = optsmgr.getOptions(); const double initial = props.getInitial(); bool continue_given = static_cast<bool>(opts.continue_given); if (retrymgr.getRetryUntilRetrievedFlag()) continue_given = true; if (continue_given && initial > 0) { double remaining = props.getLength() - initial; logmgr.cout() << "from: " << std::setprecision(0) << initial << " (" << std::setprecision(1) << _TOMB(initial) << "M) remaining: " << std::setprecision(0) << remaining << " (" << std::setprecision(1) << _TOMB(remaining) << "M)" << std::endl; } curl_easy_setopt(curl, CURLOPT_URL, props.getLink().c_str()); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, callback_writefile); write_s write; memset(&write, 0, sizeof(write)); write.initial = initial; write.filename = const_cast<char*>(props.getFilename().c_str()); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &write); curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0L); curl_easy_setopt(curl, CURLOPT_PROGRESSFUNCTION, &callback_progress); ProgressBar pb; pb.init(props); curl_easy_setopt(curl, CURLOPT_PROGRESSDATA, &pb); curl_easy_setopt(curl, CURLOPT_ENCODING, "identity"); curl_easy_setopt(curl, CURLOPT_HEADER, 0L); curl_easy_setopt(curl, CURLOPT_RESUME_FROM, (long)initial); curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, opts.connect_timeout_arg); curl_off_t limit_rate = opts.limit_rate_arg * 1024; curl_easy_setopt(curl, CURLOPT_MAX_RECV_SPEED_LARGE, limit_rate); const CURLcode rc = curl_easy_perform(curl); curl_easy_setopt(curl, CURLOPT_HEADER, 1L); curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 1L); curl_easy_setopt(curl, CURLOPT_RESUME_FROM, 0L); curl_easy_setopt(curl, CURLOPT_MAX_RECV_SPEED_LARGE, (curl_off_t) 0); if (NULL != write.file) { fflush(write.file); fclose(write.file); } httpcode = 0; curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &httpcode); if (CURLE_OK != rc) throw FetchException(curl_easy_strerror(rc), httpcode); pb.finish(); logmgr.cout() << std::endl; } const std::string& CurlMgr::unescape(std::string& url) const { char *p = curl_easy_unescape(curl, url.c_str(), 0, 0); url = p; curl_free(p); return url; } CurlMgr::FetchException::FetchException( const std::string& error, const long& httpcode) : RuntimeException(CCLIVE_FETCH, error), httpcode(httpcode) { } const long& CurlMgr::FetchException::getHTTPCode() const { return httpcode; }
/* * Copyright (C) 2009 Toni Gundogdu. * * This file is part of cclive. * * cclive 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. * * cclive is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ #include "config.h" #include <iostream> #include <iomanip> #include <sstream> #include <string> #include <cstdlib> #include <cstring> #include <curl/curl.h> #ifdef HAVE_UNISTD_H #include <unistd.h> #endif #include "except.h" #include "opts.h" #include "macros.h" #include "video.h" #include "progressbar.h" #include "log.h" #include "curl.h" #include "retry.h" static CURL *curl; static std::string formatError (const long& httpcode) { std::stringstream s; s << "server returned http/" << httpcode << ""; return s.str(); } static std::string formatError (const CURLcode& code) { std::stringstream s; s << curl_easy_strerror(code) << " (rc=" << code << ")"; return s.str(); } CurlMgr::CurlMgr() : httpcode(0) { curl = NULL; } // Keeps -Weffc++ happy. CurlMgr::CurlMgr(const CurlMgr& o) : httpcode(o.httpcode) { curl = NULL; } // Ditto. CurlMgr& CurlMgr::operator=(const CurlMgr&) { return *this; } CurlMgr::~CurlMgr() { curl_easy_cleanup(curl); curl = NULL; } void CurlMgr::init() { curl = curl_easy_init(); if (!curl) throw RuntimeException(CCLIVE_CURLINIT); const Options opts = optsmgr.getOptions(); curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1L); curl_easy_setopt(curl, CURLOPT_USERAGENT, opts.agent_arg); curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L); curl_easy_setopt(curl, CURLOPT_AUTOREFERER, 1L); curl_easy_setopt(curl, CURLOPT_NOBODY, 0L); curl_easy_setopt(curl, CURLOPT_VERBOSE, opts.debug_given); const char *proxy = opts.proxy_arg; if (opts.no_proxy_given) proxy = ""; curl_easy_setopt(curl, CURLOPT_PROXY, proxy); } static void * _realloc(void *p, const size_t size) { if (p) return realloc(p,size); return malloc(size); } struct mem_s { size_t size; char *p; }; static size_t callback_writemem(void *p, size_t size, size_t nmemb, void *data) { mem_s *m = reinterpret_cast<mem_s*>(data); const size_t rsize = size * nmemb; void *tmp = _realloc(m->p, m->size+rsize+1); if (tmp) { m->p = reinterpret_cast<char*>(tmp); memcpy(&(m->p[m->size]), p, rsize); m->size += rsize; m->p[m->size] = '\0'; } return rsize; } std::string CurlMgr::fetchToMem(const std::string& url, const std::string &what) { logmgr.cout() << "fetch "; if (what.empty()) logmgr.cout() << url; else logmgr.cout() << what; logmgr.cout() << " ..." << std::flush; curl_easy_setopt(curl, CURLOPT_URL, url.c_str()); curl_easy_setopt(curl, CURLOPT_ENCODING, ""); mem_s mem; memset(&mem, 0, sizeof(mem)); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &mem); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, callback_writemem); const Options opts = optsmgr.getOptions(); curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, opts.connect_timeout_arg); /* * http://curl.haxx.se/docs/knownbugs.html: * * "When connecting to a SOCKS proxy, the (connect) timeout is * not properly acknowledged after the actual TCP connect (during * the SOCKS 'negotiate' phase)." */ curl_easy_setopt(curl, CURLOPT_TIMEOUT, opts.connect_timeout_socks_arg); const CURLcode rc = curl_easy_perform(curl); curl_easy_setopt(curl, CURLOPT_TIMEOUT, 0L); std::string errmsg; httpcode = 0; if (CURLE_OK == rc) { curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &httpcode); if (200 == httpcode) logmgr.cout() << "done." << std::endl; else errmsg = formatError(httpcode); } else errmsg = formatError(rc); std::string content; if (NULL != mem.p) { content = mem.p; _FREE(mem.p); } if (!errmsg.empty()) throw FetchException(errmsg, httpcode); return content; } void CurlMgr::queryFileLength(VideoProperties& props) { FILE *f = tmpfile(); if (!f) { perror("tmpfile"); throw RuntimeException(CCLIVE_SYSTEM); } logmgr.cout() << "verify video link ..." << std::flush; const Options opts = optsmgr.getOptions(); curl_easy_setopt(curl, CURLOPT_URL, props.getLink().c_str()); curl_easy_setopt(curl, CURLOPT_NOBODY, 1L); // GET -> HEAD curl_easy_setopt(curl, CURLOPT_WRITEDATA, f); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, NULL); curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, opts.connect_timeout_arg); curl_easy_setopt(curl, CURLOPT_TIMEOUT, opts.connect_timeout_socks_arg); const CURLcode rc = curl_easy_perform(curl); curl_easy_setopt(curl, CURLOPT_TIMEOUT, 0L); curl_easy_setopt(curl, CURLOPT_HTTPGET, 1L); // reset HEAD -> GET fflush(f); fclose(f); std::string errmsg; httpcode = 0; if (CURLE_OK == rc) { curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &httpcode); if (200 == httpcode || 206 == httpcode) { const char *ct = NULL; curl_easy_getinfo(curl, CURLINFO_CONTENT_TYPE, &ct); double len = 0; curl_easy_getinfo(curl, CURLINFO_CONTENT_LENGTH_DOWNLOAD, &len); props.setLength(len); props.setContentType(ct); logmgr.cout() << "done." << std::endl; } else errmsg = formatError(httpcode); } else errmsg = formatError(rc); if (!errmsg.empty()) throw FetchException(errmsg, httpcode); props.formatOutputFilename(); } struct write_s { write_s() : filename(NULL), initial(0), file(NULL) { } char *filename; double initial; FILE *file; }; static size_t callback_writefile(void *data, size_t size, size_t nmemb, void *p) { write_s *w = reinterpret_cast<write_s*>(p); if (NULL != w && !w->file && NULL != w->filename) { const char *mode = w->initial > 0 ? "ab" : "wb"; w->file = fopen(w->filename, mode); if (!w->file) return -1; } return fwrite(data, size, nmemb, w->file); } int callback_progress( void *p, double total, double now, double utotal, double unow) { ProgressBar *pb = static_cast<ProgressBar*>(p); pb->update(now); return 0; } void CurlMgr::fetchToFile(const VideoProperties& props) { const Options opts = optsmgr.getOptions(); const double initial = props.getInitial(); bool continue_given = static_cast<bool>(opts.continue_given); if (retrymgr.getRetryUntilRetrievedFlag()) continue_given = true; if (continue_given && initial > 0) { const double remaining = props.getLength() - initial; logmgr.cout() << "from: " << std::setprecision(0) << initial << " (" << std::setprecision(1) << _TOMB(initial) << "M) remaining: " << std::setprecision(0) << remaining << " (" << std::setprecision(1) << _TOMB(remaining) << "M)" << std::endl; } curl_easy_setopt(curl, CURLOPT_URL, props.getLink().c_str()); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, callback_writefile); write_s write; memset(&write, 0, sizeof(write)); write.initial = initial; write.filename = const_cast<char*>(props.getFilename().c_str()); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &write); curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0L); curl_easy_setopt(curl, CURLOPT_PROGRESSFUNCTION, &callback_progress); ProgressBar pb; pb.init(props); curl_easy_setopt(curl, CURLOPT_PROGRESSDATA, &pb); curl_easy_setopt(curl, CURLOPT_ENCODING, "identity"); curl_easy_setopt(curl, CURLOPT_HEADER, 0L); curl_easy_setopt(curl, CURLOPT_RESUME_FROM, (long)initial); curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, opts.connect_timeout_arg); curl_off_t limit_rate = opts.limit_rate_arg * 1024; curl_easy_setopt(curl, CURLOPT_MAX_RECV_SPEED_LARGE, limit_rate); const CURLcode rc = curl_easy_perform(curl); curl_easy_setopt(curl, CURLOPT_HEADER, 1L); curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 1L); curl_easy_setopt(curl, CURLOPT_RESUME_FROM, 0L); curl_easy_setopt(curl, CURLOPT_MAX_RECV_SPEED_LARGE, (curl_off_t) 0); if (NULL != write.file) { fflush(write.file); fclose(write.file); } httpcode = 0; curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &httpcode); if (CURLE_OK != rc) throw FetchException(curl_easy_strerror(rc), httpcode); pb.finish(); logmgr.cout() << std::endl; } const std::string& CurlMgr::unescape(std::string& url) const { char *p = curl_easy_unescape(curl, url.c_str(), 0, 0); url = p; curl_free(p); return url; } CurlMgr::FetchException::FetchException( const std::string& error, const long& httpcode) : RuntimeException(CCLIVE_FETCH, error), httpcode(httpcode) { } const long& CurlMgr::FetchException::getHTTPCode() const { return httpcode; }
Make const.
Make const.
C++
agpl-3.0
legatvs/cclive,legatvs/cclive,legatvs/cclive
8f073382bb6a9b3998a74e6b58654476b77b4c86
src/core/SkShader.cpp
src/core/SkShader.cpp
/* libs/graphics/sgl/SkShader.cpp ** ** Copyright 2006, 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 "SkShader.h" #include "SkPaint.h" SkShader::SkShader() : fLocalMatrix(NULL) { SkDEBUGCODE(fInSession = false;) } SkShader::SkShader(SkFlattenableReadBuffer& buffer) : INHERITED(buffer), fLocalMatrix(NULL) { if (buffer.readBool()) { SkMatrix matrix; buffer.read(&matrix, sizeof(matrix)); setLocalMatrix(matrix); } SkDEBUGCODE(fInSession = false;) } SkShader::~SkShader() { SkASSERT(!fInSession); sk_free(fLocalMatrix); } void SkShader::beginSession() { SkASSERT(!fInSession); SkDEBUGCODE(fInSession = true;) } void SkShader::endSession() { SkASSERT(fInSession); SkDEBUGCODE(fInSession = false;) } void SkShader::flatten(SkFlattenableWriteBuffer& buffer) { this->INHERITED::flatten(buffer); buffer.writeBool(fLocalMatrix != NULL); if (fLocalMatrix) { buffer.writeMul4(fLocalMatrix, sizeof(SkMatrix)); } } bool SkShader::getLocalMatrix(SkMatrix* localM) const { if (fLocalMatrix) { if (localM) { *localM = *fLocalMatrix; } return true; } else { if (localM) { localM->reset(); } return false; } } void SkShader::setLocalMatrix(const SkMatrix& localM) { if (localM.isIdentity()) { this->resetLocalMatrix(); } else { if (fLocalMatrix == NULL) { fLocalMatrix = (SkMatrix*)sk_malloc_throw(sizeof(SkMatrix)); } *fLocalMatrix = localM; } } void SkShader::resetLocalMatrix() { if (fLocalMatrix) { sk_free(fLocalMatrix); fLocalMatrix = NULL; } } bool SkShader::setContext(const SkBitmap& device, const SkPaint& paint, const SkMatrix& matrix) { const SkMatrix* m = &matrix; SkMatrix total; fDeviceConfig = SkToU8(device.getConfig()); fPaintAlpha = paint.getAlpha(); if (fLocalMatrix) { total.setConcat(matrix, *fLocalMatrix); m = &total; } if (m->invert(&fTotalInverse)) { fTotalInverseClass = (uint8_t)ComputeMatrixClass(fTotalInverse); return true; } return false; } #include "SkColorPriv.h" void SkShader::shadeSpan16(int x, int y, uint16_t span16[], int count) { SkASSERT(span16); SkASSERT(count > 0); SkASSERT(this->canCallShadeSpan16()); // basically, if we get here, the subclass screwed up SkASSERT(!"kHasSpan16 flag is set, but shadeSpan16() not implemented"); } #define kTempColorQuadCount 6 // balance between speed (larger) and saving stack-space #define kTempColorCount (kTempColorQuadCount << 2) #ifdef SK_CPU_BENDIAN #define SkU32BitShiftToByteOffset(shift) (3 - ((shift) >> 3)) #else #define SkU32BitShiftToByteOffset(shift) ((shift) >> 3) #endif void SkShader::shadeSpanAlpha(int x, int y, uint8_t alpha[], int count) { SkASSERT(count > 0); SkPMColor colors[kTempColorCount]; while ((count -= kTempColorCount) >= 0) { this->shadeSpan(x, y, colors, kTempColorCount); x += kTempColorCount; const uint8_t* srcA = (const uint8_t*)colors + SkU32BitShiftToByteOffset(SK_A32_SHIFT); int quads = kTempColorQuadCount; do { U8CPU a0 = srcA[0]; U8CPU a1 = srcA[4]; U8CPU a2 = srcA[8]; U8CPU a3 = srcA[12]; srcA += 4*4; *alpha++ = SkToU8(a0); *alpha++ = SkToU8(a1); *alpha++ = SkToU8(a2); *alpha++ = SkToU8(a3); } while (--quads != 0); } SkASSERT(count < 0); SkASSERT(count + kTempColorCount >= 0); if (count += kTempColorCount) { this->shadeSpan(x, y, colors, count); const uint8_t* srcA = (const uint8_t*)colors + SkU32BitShiftToByteOffset(SK_A32_SHIFT); do { *alpha++ = *srcA; srcA += 4; } while (--count != 0); } #if 0 do { int n = count; if (n > kTempColorCount) n = kTempColorCount; SkASSERT(n > 0); this->shadeSpan(x, y, colors, n); x += n; count -= n; const uint8_t* srcA = (const uint8_t*)colors + SkU32BitShiftToByteOffset(SK_A32_SHIFT); do { *alpha++ = *srcA; srcA += 4; } while (--n != 0); } while (count > 0); #endif } SkShader::MatrixClass SkShader::ComputeMatrixClass(const SkMatrix& mat) { MatrixClass mc = kLinear_MatrixClass; if (mat.getType() & SkMatrix::kPerspective_Mask) { if (mat.fixedStepInX(0, NULL, NULL)) { mc = kFixedStepInX_MatrixClass; } else { mc = kPerspective_MatrixClass; } } return mc; } ////////////////////////////////////////////////////////////////////////////// bool SkShader::asABitmap(SkBitmap*, SkMatrix*, TileMode*) { return false; } SkShader* SkShader::CreateBitmapShader(const SkBitmap& src, TileMode tmx, TileMode tmy) { return SkShader::CreateBitmapShader(src, tmx, tmy, NULL, 0); } ////////////////////////////////////////////////////////////////////////////// #include "SkColorShader.h" #include "SkUtils.h" SkColorShader::SkColorShader(SkFlattenableReadBuffer& b) : INHERITED(b) { fFlags = 0; // computed in setContext fInheritColor = b.readU8(); if (fInheritColor) { return; } fColor = b.readU32(); } void SkColorShader::flatten(SkFlattenableWriteBuffer& buffer) { this->INHERITED::flatten(buffer); buffer.write8(fInheritColor); if (fInheritColor) { return; } buffer.write32(fColor); } uint8_t SkColorShader::getSpan16Alpha() const { return SkGetPackedA32(fPMColor); } bool SkColorShader::setContext(const SkBitmap& device, const SkPaint& paint, const SkMatrix& matrix) { if (!this->INHERITED::setContext(device, paint, matrix)) { return false; } SkColor c; unsigned a; if (fInheritColor) { c = paint.getColor(); a = SkColorGetA(c); } else { c = fColor; a = SkAlphaMul(SkColorGetA(c), SkAlpha255To256(paint.getAlpha())); } unsigned r = SkColorGetR(c); unsigned g = SkColorGetG(c); unsigned b = SkColorGetB(c); // we want this before we apply any alpha fColor16 = SkPack888ToRGB16(r, g, b); if (a != 255) { a = SkAlpha255To256(a); r = SkAlphaMul(r, a); g = SkAlphaMul(g, a); b = SkAlphaMul(b, a); } fPMColor = SkPackARGB32(a, r, g, b); fFlags = kHasSpan16_Flag | kConstInY32_Flag; if (SkGetPackedA32(fPMColor) == 255) { fFlags |= kOpaqueAlpha_Flag; } return true; } void SkColorShader::shadeSpan(int x, int y, SkPMColor span[], int count) { sk_memset32(span, fPMColor, count); } void SkColorShader::shadeSpan16(int x, int y, uint16_t span[], int count) { sk_memset16(span, fColor16, count); } void SkColorShader::shadeSpanAlpha(int x, int y, uint8_t alpha[], int count) { memset(alpha, SkGetPackedA32(fPMColor), count); }
/* libs/graphics/sgl/SkShader.cpp ** ** Copyright 2006, 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 "SkShader.h" #include "SkPaint.h" SkShader::SkShader() : fLocalMatrix(NULL) { SkDEBUGCODE(fInSession = false;) } SkShader::SkShader(SkFlattenableReadBuffer& buffer) : INHERITED(buffer), fLocalMatrix(NULL) { if (buffer.readBool()) { SkMatrix matrix; buffer.read(&matrix, sizeof(matrix)); setLocalMatrix(matrix); } SkDEBUGCODE(fInSession = false;) } SkShader::~SkShader() { SkASSERT(!fInSession); sk_free(fLocalMatrix); } void SkShader::beginSession() { SkASSERT(!fInSession); SkDEBUGCODE(fInSession = true;) } void SkShader::endSession() { SkASSERT(fInSession); SkDEBUGCODE(fInSession = false;) } void SkShader::flatten(SkFlattenableWriteBuffer& buffer) { this->INHERITED::flatten(buffer); buffer.writeBool(fLocalMatrix != NULL); if (fLocalMatrix) { buffer.writeMul4(fLocalMatrix, sizeof(SkMatrix)); } } bool SkShader::getLocalMatrix(SkMatrix* localM) const { if (fLocalMatrix) { if (localM) { *localM = *fLocalMatrix; } return true; } else { if (localM) { localM->reset(); } return false; } } void SkShader::setLocalMatrix(const SkMatrix& localM) { if (localM.isIdentity()) { this->resetLocalMatrix(); } else { if (fLocalMatrix == NULL) { fLocalMatrix = (SkMatrix*)sk_malloc_throw(sizeof(SkMatrix)); } *fLocalMatrix = localM; } } void SkShader::resetLocalMatrix() { if (fLocalMatrix) { sk_free(fLocalMatrix); fLocalMatrix = NULL; } } bool SkShader::setContext(const SkBitmap& device, const SkPaint& paint, const SkMatrix& matrix) { const SkMatrix* m = &matrix; SkMatrix total; fDeviceConfig = SkToU8(device.getConfig()); fPaintAlpha = paint.getAlpha(); if (fLocalMatrix) { total.setConcat(matrix, *fLocalMatrix); m = &total; } if (m->invert(&fTotalInverse)) { fTotalInverseClass = (uint8_t)ComputeMatrixClass(fTotalInverse); return true; } return false; } #include "SkColorPriv.h" void SkShader::shadeSpan16(int x, int y, uint16_t span16[], int count) { SkASSERT(span16); SkASSERT(count > 0); SkASSERT(this->canCallShadeSpan16()); // basically, if we get here, the subclass screwed up SkASSERT(!"kHasSpan16 flag is set, but shadeSpan16() not implemented"); } #define kTempColorQuadCount 6 // balance between speed (larger) and saving stack-space #define kTempColorCount (kTempColorQuadCount << 2) #ifdef SK_CPU_BENDIAN #define SkU32BitShiftToByteOffset(shift) (3 - ((shift) >> 3)) #else #define SkU32BitShiftToByteOffset(shift) ((shift) >> 3) #endif void SkShader::shadeSpanAlpha(int x, int y, uint8_t alpha[], int count) { SkASSERT(count > 0); SkPMColor colors[kTempColorCount]; while ((count -= kTempColorCount) >= 0) { this->shadeSpan(x, y, colors, kTempColorCount); x += kTempColorCount; const uint8_t* srcA = (const uint8_t*)colors + SkU32BitShiftToByteOffset(SK_A32_SHIFT); int quads = kTempColorQuadCount; do { U8CPU a0 = srcA[0]; U8CPU a1 = srcA[4]; U8CPU a2 = srcA[8]; U8CPU a3 = srcA[12]; srcA += 4*4; *alpha++ = SkToU8(a0); *alpha++ = SkToU8(a1); *alpha++ = SkToU8(a2); *alpha++ = SkToU8(a3); } while (--quads != 0); } SkASSERT(count < 0); SkASSERT(count + kTempColorCount >= 0); if (count += kTempColorCount) { this->shadeSpan(x, y, colors, count); const uint8_t* srcA = (const uint8_t*)colors + SkU32BitShiftToByteOffset(SK_A32_SHIFT); do { *alpha++ = *srcA; srcA += 4; } while (--count != 0); } #if 0 do { int n = count; if (n > kTempColorCount) n = kTempColorCount; SkASSERT(n > 0); this->shadeSpan(x, y, colors, n); x += n; count -= n; const uint8_t* srcA = (const uint8_t*)colors + SkU32BitShiftToByteOffset(SK_A32_SHIFT); do { *alpha++ = *srcA; srcA += 4; } while (--n != 0); } while (count > 0); #endif } SkShader::MatrixClass SkShader::ComputeMatrixClass(const SkMatrix& mat) { MatrixClass mc = kLinear_MatrixClass; if (mat.getType() & SkMatrix::kPerspective_Mask) { if (mat.fixedStepInX(0, NULL, NULL)) { mc = kFixedStepInX_MatrixClass; } else { mc = kPerspective_MatrixClass; } } return mc; } ////////////////////////////////////////////////////////////////////////////// bool SkShader::asABitmap(SkBitmap*, SkMatrix*, TileMode*) { return false; } SkShader* SkShader::CreateBitmapShader(const SkBitmap& src, TileMode tmx, TileMode tmy) { return SkShader::CreateBitmapShader(src, tmx, tmy, NULL, 0); } ////////////////////////////////////////////////////////////////////////////// #include "SkColorShader.h" #include "SkUtils.h" SkColorShader::SkColorShader(SkFlattenableReadBuffer& b) : INHERITED(b) { fFlags = 0; // computed in setContext fInheritColor = b.readU8(); if (fInheritColor) { return; } fColor = b.readU32(); } void SkColorShader::flatten(SkFlattenableWriteBuffer& buffer) { this->INHERITED::flatten(buffer); buffer.write8(fInheritColor); if (fInheritColor) { return; } buffer.write32(fColor); } uint8_t SkColorShader::getSpan16Alpha() const { return SkGetPackedA32(fPMColor); } bool SkColorShader::setContext(const SkBitmap& device, const SkPaint& paint, const SkMatrix& matrix) { if (!this->INHERITED::setContext(device, paint, matrix)) { return false; } SkColor c; unsigned a; if (fInheritColor) { c = paint.getColor(); a = SkColorGetA(c); } else { c = fColor; a = SkAlphaMul(SkColorGetA(c), SkAlpha255To256(paint.getAlpha())); } unsigned r = SkColorGetR(c); unsigned g = SkColorGetG(c); unsigned b = SkColorGetB(c); // we want this before we apply any alpha fColor16 = SkPack888ToRGB16(r, g, b); if (a != 255) { r = SkMulDiv255Round(r, a); g = SkMulDiv255Round(g, a); b = SkMulDiv255Round(b, a); } fPMColor = SkPackARGB32(a, r, g, b); fFlags = kConstInY32_Flag; if (paint.isDither() == false) { fFlags |= kHasSpan16_Flag; } if (SkGetPackedA32(fPMColor) == 255) { fFlags |= kOpaqueAlpha_Flag; } return true; } void SkColorShader::shadeSpan(int x, int y, SkPMColor span[], int count) { sk_memset32(span, fPMColor, count); } void SkColorShader::shadeSpan16(int x, int y, uint16_t span[], int count) { sk_memset16(span, fColor16, count); } void SkColorShader::shadeSpanAlpha(int x, int y, uint8_t alpha[], int count) { memset(alpha, SkGetPackedA32(fPMColor), count); }
fix off-by-1 in alpha in colorshader setup don't promise HasSpan16 if we're supposed to dither
fix off-by-1 in alpha in colorshader setup don't promise HasSpan16 if we're supposed to dither git-svn-id: e8541e15acce502a64c929015570ad1648e548cd@526 2bbb7eff-a529-9590-31e7-b0007b416f81
C++
bsd-3-clause
AsteroidOS/android_external_skia,Purity-Lollipop/platform_external_skia,OptiPop/external_skia,chenlian2015/skia_from_google,TeamEOS/external_chromium_org_third_party_skia,AOSP-YU/platform_external_skia,Fusion-Rom/android_external_skia,Fusion-Rom/external_chromium_org_third_party_skia,Fusion-Rom/external_chromium_org_third_party_skia,AndroidOpenDevelopment/android_external_skia,MinimalOS-AOSP/platform_external_skia,DiamondLovesYou/skia-sys,AOSPA-L/android_external_skia,TeamTwisted/external_skia,geekboxzone/lollipop_external_chromium_org_third_party_skia,timduru/platform-external-skia,timduru/platform-external-skia,sombree/android_external_skia,MyAOSP/external_chromium_org_third_party_skia,Infinitive-OS/platform_external_skia,vanish87/skia,TeslaOS/android_external_skia,AOSPU/external_chromium_org_third_party_skia,TeamEOS/external_chromium_org_third_party_skia,HealthyHoney/temasek_SKIA,pacerom/external_skia,geekboxzone/lollipop_external_skia,vvuk/skia,jtg-gg/skia,byterom/android_external_skia,wildermason/external_skia,android-ia/platform_external_chromium_org_third_party_skia,xin3liang/platform_external_chromium_org_third_party_skia,Asteroid-Project/android_external_skia,mydongistiny/external_chromium_org_third_party_skia,suyouxin/android_external_skia,AsteroidOS/android_external_skia,CyanogenMod/android_external_chromium_org_third_party_skia,VentureROM-L/android_external_skia,invisiblek/android_external_skia,YUPlayGodDev/platform_external_skia,aospo/platform_external_skia,TeamExodus/external_skia,Igalia/skia,aosp-mirror/platform_external_skia,DiamondLovesYou/skia-sys,UBERMALLOW/external_skia,rubenvb/skia,AOSPB/external_skia,OptiPop/external_chromium_org_third_party_skia,RadonX-ROM/external_skia,ominux/skia,MinimalOS-AOSP/platform_external_skia,PAC-ROM/android_external_skia,FusionSP/external_chromium_org_third_party_skia,samuelig/skia,noselhq/skia,google/skia,TeslaOS/android_external_skia,AsteroidOS/android_external_skia,wildermason/external_skia,nvoron23/skia,TeamEOS/external_skia,pacerom/external_skia,vvuk/skia,MIPS/external-chromium_org-third_party-skia,MonkeyZZZZ/platform_external_skia,geekboxzone/mmallow_external_skia,mydongistiny/android_external_skia,sombree/android_external_skia,TeamBliss-LP/android_external_skia,timduru/platform-external-skia,AOSP-YU/platform_external_skia,ench0/external_skia,MonkeyZZZZ/platform_external_skia,Infinitive-OS/platform_external_skia,aospo/platform_external_skia,TeamEOS/external_chromium_org_third_party_skia,mydongistiny/android_external_skia,TeamBliss-LP/android_external_skia,Khaon/android_external_skia,NamelessRom/android_external_skia,AOSPA-L/android_external_skia,xin3liang/platform_external_chromium_org_third_party_skia,Euphoria-OS-Legacy/android_external_skia,xzzz9097/android_external_skia,w3nd1go/android_external_skia,fire855/android_external_skia,w3nd1go/android_external_skia,Fusion-Rom/android_external_skia,android-ia/platform_external_skia,TeamExodus/external_skia,qrealka/skia-hc,Fusion-Rom/external_chromium_org_third_party_skia,FusionSP/external_chromium_org_third_party_skia,VRToxin-AOSP/android_external_skia,InfinitiveOS/external_skia,Omegaphora/external_skia,Hybrid-Rom/external_skia,OptiPop/external_skia,AOSP-YU/platform_external_skia,sombree/android_external_skia,xin3liang/platform_external_chromium_org_third_party_skia,YUPlayGodDev/platform_external_skia,NamelessRom/android_external_skia,Purity-Lollipop/platform_external_skia,tmpvar/skia.cc,Infusion-OS/android_external_skia,VRToxin-AOSP/android_external_skia,Fusion-Rom/android_external_skia,SlimSaber/android_external_skia,VentureROM-L/android_external_skia,byterom/android_external_skia,TeamEOS/external_skia,shahrzadmn/skia,F-AOSP/platform_external_skia,OptiPop/external_skia,xin3liang/platform_external_chromium_org_third_party_skia,Khaon/android_external_skia,HalCanary/skia-hc,Android-AOSP/external_skia,AOSPU/external_chromium_org_third_party_skia,akiss77/skia,mozilla-b2g/external_skia,mmatyas/skia,Purity-Lollipop/platform_external_skia,chenlian2015/skia_from_google,sudosurootdev/external_skia,chenlian2015/skia_from_google,DesolationStaging/android_external_skia,noselhq/skia,F-AOSP/platform_external_skia,DiamondLovesYou/skia-sys,SlimSaber/android_external_skia,MinimalOS/android_external_skia,Euphoria-OS-Legacy/android_external_skia,Android-AOSP/external_skia,jtg-gg/skia,mydongistiny/external_chromium_org_third_party_skia,Infinitive-OS/platform_external_skia,DiamondLovesYou/skia-sys,android-ia/platform_external_chromium_org_third_party_skia,pcwalton/skia,OneRom/external_skia,Android-AOSP/external_skia,mmatyas/skia,geekboxzone/lollipop_external_skia,fire855/android_external_skia,OneRom/external_skia,sombree/android_external_skia,samuelig/skia,Hybrid-Rom/external_skia,ominux/skia,nox/skia,codeaurora-unoffical/platform-external-skia,MIPS/external-chromium_org-third_party-skia,OneRom/external_skia,FusionSP/android_external_skia,google/skia,mydongistiny/android_external_skia,qrealka/skia-hc,TeamExodus/external_skia,ominux/skia,Euphoria-OS-Legacy/android_external_skia,MinimalOS/android_external_chromium_org_third_party_skia,MinimalOS/external_skia,mozilla-b2g/external_skia,android-ia/platform_external_skia,HealthyHoney/temasek_SKIA,houst0nn/external_skia,nox/skia,google/skia,OptiPop/external_skia,noselhq/skia,jtg-gg/skia,geekboxzone/lollipop_external_skia,Omegaphora/external_skia,Plain-Andy/android_platform_external_skia,MinimalOS-AOSP/platform_external_skia,AOSPB/external_skia,wildermason/external_skia,mmatyas/skia,NamelessRom/android_external_skia,OneRom/external_skia,shahrzadmn/skia,Euphoria-OS-Legacy/android_external_skia,Hikari-no-Tenshi/android_external_skia,Hybrid-Rom/external_skia,F-AOSP/platform_external_skia,Samsung/skia,boulzordev/android_external_skia,OptiPop/external_chromium_org_third_party_skia,vanish87/skia,TeamBliss-LP/android_external_skia,spezi77/android_external_skia,Infusion-OS/android_external_skia,TeamEOS/external_chromium_org_third_party_skia,zhaochengw/platform_external_skia,mydongistiny/external_chromium_org_third_party_skia,TeslaOS/android_external_skia,codeaurora-unoffical/platform-external-skia,ctiao/platform-external-skia,TeamExodus/external_skia,TeamExodus/external_skia,Khaon/android_external_skia,Omegaphora/external_chromium_org_third_party_skia,mozilla-b2g/external_skia,CyanogenMod/android_external_chromium_org_third_party_skia,VRToxin-AOSP/android_external_skia,nfxosp/platform_external_skia,TeamEOS/external_skia,BrokenROM/external_skia,TeamTwisted/external_skia,android-ia/platform_external_skia,geekboxzone/lollipop_external_skia,invisiblek/android_external_skia,TeamExodus/external_skia,MonkeyZZZZ/platform_external_skia,Asteroid-Project/android_external_skia,TeamTwisted/external_skia,ench0/external_chromium_org_third_party_skia,sombree/android_external_skia,Omegaphora/external_chromium_org_third_party_skia,NamelessRom/android_external_skia,UBERMALLOW/external_skia,Euphoria-OS-Legacy/android_external_skia,MarshedOut/android_external_skia,DesolationStaging/android_external_skia,mydongistiny/external_chromium_org_third_party_skia,PAC-ROM/android_external_skia,MinimalOS/external_skia,Infusion-OS/android_external_skia,Plain-Andy/android_platform_external_skia,timduru/platform-external-skia,google/skia,Infusion-OS/android_external_skia,MonkeyZZZZ/platform_external_skia,Hybrid-Rom/external_skia,MarshedOut/android_external_skia,VentureROM-L/android_external_skia,boulzordev/android_external_skia,Pure-Aosp/android_external_skia,MinimalOS/external_skia,CyanogenMod/android_external_chromium_org_third_party_skia,MIPS/external-chromium_org-third_party-skia,noselhq/skia,Plain-Andy/android_platform_external_skia,scroggo/skia,Omegaphora/external_chromium_org_third_party_skia,Infinitive-OS/platform_external_skia,AOSPB/external_skia,MinimalOS/android_external_chromium_org_third_party_skia,SlimSaber/android_external_skia,temasek/android_external_skia,AOSPA-L/android_external_skia,Hybrid-Rom/external_skia,BrokenROM/external_skia,noselhq/skia,invisiblek/android_external_skia,HealthyHoney/temasek_SKIA,geekboxzone/mmallow_external_skia,codeaurora-unoffical/platform-external-skia,UBERMALLOW/external_skia,chenlian2015/skia_from_google,FusionSP/external_chromium_org_third_party_skia,mydongistiny/external_chromium_org_third_party_skia,amyvmiwei/skia,MinimalOS/android_external_skia,AsteroidOS/android_external_skia,larsbergstrom/skia,scroggo/skia,pacerom/external_skia,Android-AOSP/external_skia,amyvmiwei/skia,sigysmund/platform_external_skia,larsbergstrom/skia,AsteroidOS/android_external_skia,Tesla-Redux/android_external_skia,vanish87/skia,ench0/external_chromium_org_third_party_skia,Purity-Lollipop/platform_external_skia,pcwalton/skia,DARKPOP/external_chromium_org_third_party_skia,Tesla-Redux/android_external_skia,Igalia/skia,rubenvb/skia,ench0/external_skia,VRToxin-AOSP/android_external_skia,FusionSP/android_external_skia,pacerom/external_skia,samuelig/skia,suyouxin/android_external_skia,timduru/platform-external-skia,tmpvar/skia.cc,sigysmund/platform_external_skia,mmatyas/skia,invisiblek/android_external_skia,YUPlayGodDev/platform_external_skia,ench0/external_skia,spezi77/android_external_skia,GladeRom/android_external_skia,DARKPOP/external_chromium_org_third_party_skia,OptiPop/external_chromium_org_third_party_skia,invisiblek/android_external_skia,houst0nn/external_skia,CyanogenMod/android_external_chromium_org_third_party_skia,Euphoria-OS-Legacy/android_external_skia,boulzordev/android_external_skia,Pure-Aosp/android_external_skia,invisiblek/android_external_skia,w3nd1go/android_external_skia,nox/skia,DARKPOP/external_chromium_org_third_party_skia,Pure-Aosp/android_external_skia,geekboxzone/mmallow_external_skia,PAC-ROM/android_external_skia,nox/skia,RadonX-ROM/external_skia,VentureROM-L/android_external_skia,AOSPU/external_chromium_org_third_party_skia,F-AOSP/platform_external_skia,xzzz9097/android_external_skia,MinimalOS/android_external_chromium_org_third_party_skia,VRToxin-AOSP/android_external_skia,todotodoo/skia,Infusion-OS/android_external_skia,timduru/platform-external-skia,HealthyHoney/temasek_SKIA,suyouxin/android_external_skia,MyAOSP/external_chromium_org_third_party_skia,AsteroidOS/android_external_skia,NamelessRom/android_external_skia,vvuk/skia,FusionSP/external_chromium_org_third_party_skia,akiss77/skia,mydongistiny/android_external_skia,TeslaProject/external_skia,CyanogenMod/android_external_chromium_org_third_party_skia,aosp-mirror/platform_external_skia,google/skia,Hybrid-Rom/external_skia,akiss77/skia,w3nd1go/android_external_skia,houst0nn/external_skia,TeamTwisted/external_skia,spezi77/android_external_skia,sombree/android_external_skia,MinimalOS/external_chromium_org_third_party_skia,aospo/platform_external_skia,spezi77/android_external_skia,MIPS/external-chromium_org-third_party-skia,larsbergstrom/skia,ench0/external_chromium_org_third_party_skia,rubenvb/skia,todotodoo/skia,ctiao/platform-external-skia,nvoron23/skia,Khaon/android_external_skia,sigysmund/platform_external_skia,OptiPop/external_chromium_org_third_party_skia,ench0/external_skia,TeamTwisted/external_skia,OptiPop/external_skia,Android-AOSP/external_skia,AOSP-YU/platform_external_skia,nox/skia,nvoron23/skia,MyAOSP/external_chromium_org_third_party_skia,xzzz9097/android_external_skia,Asteroid-Project/android_external_skia,larsbergstrom/skia,OptiPop/external_chromium_org_third_party_skia,Hikari-no-Tenshi/android_external_skia,AOSPB/external_skia,Samsung/skia,Fusion-Rom/android_external_skia,Infinitive-OS/platform_external_skia,MinimalOS/android_external_chromium_org_third_party_skia,akiss77/skia,pcwalton/skia,android-ia/platform_external_chromium_org_third_party_skia,YUPlayGodDev/platform_external_skia,vvuk/skia,F-AOSP/platform_external_skia,Omegaphora/external_chromium_org_third_party_skia,shahrzadmn/skia,Pure-Aosp/android_external_skia,MinimalOS-AOSP/platform_external_skia,Samsung/skia,BrokenROM/external_skia,tmpvar/skia.cc,BrokenROM/external_skia,HalCanary/skia-hc,samuelig/skia,akiss77/skia,akiss77/skia,Hikari-no-Tenshi/android_external_skia,xin3liang/platform_external_chromium_org_third_party_skia,DARKPOP/external_chromium_org_third_party_skia,MinimalOS-AOSP/platform_external_skia,mmatyas/skia,Khaon/android_external_skia,MonkeyZZZZ/platform_external_skia,geekboxzone/lollipop_external_skia,TeslaOS/android_external_skia,larsbergstrom/skia,nfxosp/platform_external_skia,shahrzadmn/skia,DiamondLovesYou/skia-sys,PAC-ROM/android_external_skia,DesolationStaging/android_external_skia,todotodoo/skia,ctiao/platform-external-skia,tmpvar/skia.cc,xzzz9097/android_external_skia,rubenvb/skia,qrealka/skia-hc,F-AOSP/platform_external_skia,HalCanary/skia-hc,temasek/android_external_skia,Plain-Andy/android_platform_external_skia,geekboxzone/mmallow_external_skia,FusionSP/android_external_skia,Infinitive-OS/platform_external_skia,YUPlayGodDev/platform_external_skia,MinimalOS/android_external_skia,DesolationStaging/android_external_skia,Omegaphora/external_skia,tmpvar/skia.cc,temasek/android_external_skia,ench0/external_skia,PAC-ROM/android_external_skia,CyanogenMod/android_external_chromium_org_third_party_skia,w3nd1go/android_external_skia,AOSPA-L/android_external_skia,OneRom/external_skia,geekboxzone/lollipop_external_skia,FusionSP/external_chromium_org_third_party_skia,FusionSP/android_external_skia,Hikari-no-Tenshi/android_external_skia,MinimalOS/android_external_skia,TeslaProject/external_skia,sigysmund/platform_external_skia,GladeRom/android_external_skia,NamelessRom/android_external_skia,Samsung/skia,MinimalOS/external_skia,shahrzadmn/skia,HealthyHoney/temasek_SKIA,HalCanary/skia-hc,RadonX-ROM/external_skia,byterom/android_external_skia,zhaochengw/platform_external_skia,Purity-Lollipop/platform_external_skia,HalCanary/skia-hc,OptiPop/external_skia,YUPlayGodDev/platform_external_skia,zhaochengw/platform_external_skia,TeamTwisted/external_skia,nfxosp/platform_external_skia,HalCanary/skia-hc,Hikari-no-Tenshi/android_external_skia,codeaurora-unoffical/platform-external-skia,Infusion-OS/android_external_skia,ench0/external_chromium_org_third_party_skia,suyouxin/android_external_skia,noselhq/skia,AOSPU/external_chromium_org_third_party_skia,MarshedOut/android_external_skia,fire855/android_external_skia,wildermason/external_skia,android-ia/platform_external_skia,byterom/android_external_skia,todotodoo/skia,AOSPB/external_skia,TeamEOS/external_chromium_org_third_party_skia,sigysmund/platform_external_skia,RadonX-ROM/external_skia,aosp-mirror/platform_external_skia,samuelig/skia,akiss77/skia,aospo/platform_external_skia,aosp-mirror/platform_external_skia,larsbergstrom/skia,Omegaphora/external_chromium_org_third_party_skia,scroggo/skia,InfinitiveOS/external_skia,nfxosp/platform_external_skia,ominux/skia,Fusion-Rom/external_chromium_org_third_party_skia,xzzz9097/android_external_skia,MinimalOS/android_external_chromium_org_third_party_skia,nvoron23/skia,Infusion-OS/android_external_skia,qrealka/skia-hc,MinimalOS/android_external_skia,TeamEOS/external_chromium_org_third_party_skia,Omegaphora/external_skia,vvuk/skia,AOSPA-L/android_external_skia,aosp-mirror/platform_external_skia,aosp-mirror/platform_external_skia,qrealka/skia-hc,google/skia,AndroidOpenDevelopment/android_external_skia,Purity-Lollipop/platform_external_skia,VentureROM-L/android_external_skia,nvoron23/skia,MinimalOS-AOSP/platform_external_skia,Jichao/skia,Hybrid-Rom/external_skia,Jichao/skia,boulzordev/android_external_skia,vanish87/skia,UBERMALLOW/external_skia,fire855/android_external_skia,Tesla-Redux/android_external_skia,chenlian2015/skia_from_google,DARKPOP/external_chromium_org_third_party_skia,Hikari-no-Tenshi/android_external_skia,MyAOSP/external_chromium_org_third_party_skia,TeslaProject/external_skia,temasek/android_external_skia,Purity-Lollipop/platform_external_skia,nvoron23/skia,mydongistiny/android_external_skia,aosp-mirror/platform_external_skia,Igalia/skia,FusionSP/android_external_skia,ench0/external_chromium_org_third_party_skia,android-ia/platform_external_chromium_org_third_party_skia,vanish87/skia,AOSP-YU/platform_external_skia,google/skia,vanish87/skia,TeamEOS/external_skia,suyouxin/android_external_skia,w3nd1go/android_external_skia,aospo/platform_external_skia,tmpvar/skia.cc,InfinitiveOS/external_skia,larsbergstrom/skia,w3nd1go/android_external_skia,MinimalOS-AOSP/platform_external_skia,Plain-Andy/android_platform_external_skia,Asteroid-Project/android_external_skia,Igalia/skia,MyAOSP/external_chromium_org_third_party_skia,TeamEOS/external_chromium_org_third_party_skia,Omegaphora/external_skia,nfxosp/platform_external_skia,VRToxin-AOSP/android_external_skia,geekboxzone/lollipop_external_chromium_org_third_party_skia,zhaochengw/platform_external_skia,GladeRom/android_external_skia,noselhq/skia,HalCanary/skia-hc,mmatyas/skia,MarshedOut/android_external_skia,OneRom/external_skia,geekboxzone/lollipop_external_chromium_org_third_party_skia,Infinitive-OS/platform_external_skia,F-AOSP/platform_external_skia,vvuk/skia,Asteroid-Project/android_external_skia,vvuk/skia,DiamondLovesYou/skia-sys,TeamExodus/external_skia,w3nd1go/android_external_skia,invisiblek/android_external_skia,amyvmiwei/skia,MinimalOS/external_chromium_org_third_party_skia,Tesla-Redux/android_external_skia,scroggo/skia,BrokenROM/external_skia,mydongistiny/external_chromium_org_third_party_skia,xin3liang/platform_external_chromium_org_third_party_skia,rubenvb/skia,android-ia/platform_external_chromium_org_third_party_skia,GladeRom/android_external_skia,ominux/skia,DARKPOP/external_chromium_org_third_party_skia,AOSPU/external_chromium_org_third_party_skia,pcwalton/skia,MarshedOut/android_external_skia,tmpvar/skia.cc,ctiao/platform-external-skia,PAC-ROM/android_external_skia,nfxosp/platform_external_skia,rubenvb/skia,TeamBliss-LP/android_external_skia,sombree/android_external_skia,suyouxin/android_external_skia,Jichao/skia,SlimSaber/android_external_skia,VentureROM-L/android_external_skia,ench0/external_chromium_org_third_party_skia,Igalia/skia,Pure-Aosp/android_external_skia,zhaochengw/platform_external_skia,InfinitiveOS/external_skia,sigysmund/platform_external_skia,ctiao/platform-external-skia,AOSPB/external_skia,MinimalOS/external_chromium_org_third_party_skia,MinimalOS/external_skia,CyanogenMod/android_external_chromium_org_third_party_skia,samuelig/skia,MinimalOS/external_skia,ominux/skia,MinimalOS/external_chromium_org_third_party_skia,ench0/external_skia,Pure-Aosp/android_external_skia,Fusion-Rom/android_external_skia,AOSPB/external_skia,AOSPU/external_chromium_org_third_party_skia,Tesla-Redux/android_external_skia,UBERMALLOW/external_skia,nfxosp/platform_external_skia,nox/skia,aosp-mirror/platform_external_skia,scroggo/skia,pcwalton/skia,todotodoo/skia,TeamBliss-LP/android_external_skia,vanish87/skia,qrealka/skia-hc,AndroidOpenDevelopment/android_external_skia,nfxosp/platform_external_skia,Asteroid-Project/android_external_skia,Khaon/android_external_skia,DesolationStaging/android_external_skia,ench0/external_skia,tmpvar/skia.cc,sudosurootdev/external_skia,Jichao/skia,mydongistiny/external_chromium_org_third_party_skia,boulzordev/android_external_skia,MinimalOS-AOSP/platform_external_skia,TeamEOS/external_skia,byterom/android_external_skia,android-ia/platform_external_skia,sigysmund/platform_external_skia,AsteroidOS/android_external_skia,TeslaProject/external_skia,OneRom/external_skia,Omegaphora/external_chromium_org_third_party_skia,YUPlayGodDev/platform_external_skia,MarshedOut/android_external_skia,YUPlayGodDev/platform_external_skia,DesolationStaging/android_external_skia,google/skia,Tesla-Redux/android_external_skia,TeamExodus/external_skia,Fusion-Rom/android_external_skia,MinimalOS/android_external_chromium_org_third_party_skia,OneRom/external_skia,vanish87/skia,Omegaphora/external_chromium_org_third_party_skia,pcwalton/skia,Samsung/skia,nox/skia,GladeRom/android_external_skia,boulzordev/android_external_skia,Samsung/skia,vvuk/skia,Samsung/skia,boulzordev/android_external_skia,houst0nn/external_skia,PAC-ROM/android_external_skia,codeaurora-unoffical/platform-external-skia,fire855/android_external_skia,Asteroid-Project/android_external_skia,aospo/platform_external_skia,qrealka/skia-hc,Fusion-Rom/android_external_skia,temasek/android_external_skia,MonkeyZZZZ/platform_external_skia,codeaurora-unoffical/platform-external-skia,houst0nn/external_skia,VRToxin-AOSP/android_external_skia,google/skia,MarshedOut/android_external_skia,xzzz9097/android_external_skia,MinimalOS/external_chromium_org_third_party_skia,scroggo/skia,Infusion-OS/android_external_skia,TeamTwisted/external_skia,InfinitiveOS/external_skia,TeamEOS/external_chromium_org_third_party_skia,geekboxzone/mmallow_external_skia,OptiPop/external_skia,Jichao/skia,geekboxzone/mmallow_external_skia,Omegaphora/external_chromium_org_third_party_skia,todotodoo/skia,DiamondLovesYou/skia-sys,scroggo/skia,PAC-ROM/android_external_skia,Igalia/skia,Tesla-Redux/android_external_skia,geekboxzone/lollipop_external_chromium_org_third_party_skia,android-ia/platform_external_skia,fire855/android_external_skia,TeslaProject/external_skia,houst0nn/external_skia,Android-AOSP/external_skia,jtg-gg/skia,TeamTwisted/external_skia,VentureROM-L/android_external_skia,OptiPop/external_chromium_org_third_party_skia,AndroidOpenDevelopment/android_external_skia,samuelig/skia,VRToxin-AOSP/android_external_skia,OptiPop/external_skia,MIPS/external-chromium_org-third_party-skia,geekboxzone/lollipop_external_skia,geekboxzone/mmallow_external_skia,MonkeyZZZZ/platform_external_skia,vanish87/skia,MinimalOS/external_chromium_org_third_party_skia,Infinitive-OS/platform_external_skia,houst0nn/external_skia,mydongistiny/android_external_skia,byterom/android_external_skia,MinimalOS/external_skia,sigysmund/platform_external_skia,amyvmiwei/skia,noselhq/skia,Euphoria-OS-Legacy/android_external_skia,AOSP-YU/platform_external_skia,GladeRom/android_external_skia,HalCanary/skia-hc,android-ia/platform_external_skia,MinimalOS/android_external_chromium_org_third_party_skia,BrokenROM/external_skia,xzzz9097/android_external_skia,MinimalOS/external_skia,FusionSP/android_external_skia,HealthyHoney/temasek_SKIA,FusionSP/android_external_skia,sudosurootdev/external_skia,ench0/external_chromium_org_third_party_skia,zhaochengw/platform_external_skia,spezi77/android_external_skia,wildermason/external_skia,Igalia/skia,noselhq/skia,Asteroid-Project/android_external_skia,rubenvb/skia,HealthyHoney/temasek_SKIA,ominux/skia,larsbergstrom/skia,HealthyHoney/temasek_SKIA,GladeRom/android_external_skia,DesolationStaging/android_external_skia,todotodoo/skia,GladeRom/android_external_skia,Infinitive-OS/platform_external_skia,nvoron23/skia,ctiao/platform-external-skia,Omegaphora/external_skia,qrealka/skia-hc,fire855/android_external_skia,SlimSaber/android_external_skia,sombree/android_external_skia,MarshedOut/android_external_skia,OptiPop/external_chromium_org_third_party_skia,AndroidOpenDevelopment/android_external_skia,AOSP-YU/platform_external_skia,codeaurora-unoffical/platform-external-skia,Android-AOSP/external_skia,Jichao/skia,ominux/skia,Khaon/android_external_skia,AndroidOpenDevelopment/android_external_skia,xzzz9097/android_external_skia,TeslaProject/external_skia,UBERMALLOW/external_skia,MinimalOS/external_chromium_org_third_party_skia,pacerom/external_skia,wildermason/external_skia,aospo/platform_external_skia,MyAOSP/external_chromium_org_third_party_skia,mmatyas/skia,MIPS/external-chromium_org-third_party-skia,Fusion-Rom/external_chromium_org_third_party_skia,DARKPOP/external_chromium_org_third_party_skia,fire855/android_external_skia,pcwalton/skia,mmatyas/skia,NamelessRom/android_external_skia,Purity-Lollipop/platform_external_skia,suyouxin/android_external_skia,geekboxzone/lollipop_external_chromium_org_third_party_skia,VentureROM-L/android_external_skia,HalCanary/skia-hc,sudosurootdev/external_skia,AOSPB/external_skia,OneRom/external_skia,Hikari-no-Tenshi/android_external_skia,SlimSaber/android_external_skia,AOSPU/external_chromium_org_third_party_skia,Hybrid-Rom/external_skia,YUPlayGodDev/platform_external_skia,Fusion-Rom/android_external_skia,AOSP-YU/platform_external_skia,amyvmiwei/skia,mozilla-b2g/external_skia,nfxosp/platform_external_skia,OptiPop/external_chromium_org_third_party_skia,zhaochengw/platform_external_skia,mozilla-b2g/external_skia,akiss77/skia,ctiao/platform-external-skia,TeamExodus/external_skia,Euphoria-OS-Legacy/android_external_skia,wildermason/external_skia,Khaon/android_external_skia,Samsung/skia,sudosurootdev/external_skia,rubenvb/skia,AsteroidOS/android_external_skia,AOSPA-L/android_external_skia,mozilla-b2g/external_skia,RadonX-ROM/external_skia,boulzordev/android_external_skia,AOSPA-L/android_external_skia,Plain-Andy/android_platform_external_skia,amyvmiwei/skia,TeslaOS/android_external_skia,MinimalOS/external_chromium_org_third_party_skia,InfinitiveOS/external_skia,google/skia,AndroidOpenDevelopment/android_external_skia,geekboxzone/lollipop_external_chromium_org_third_party_skia,android-ia/platform_external_chromium_org_third_party_skia,geekboxzone/mmallow_external_skia,sudosurootdev/external_skia,AOSPB/external_skia,MarshedOut/android_external_skia,Pure-Aosp/android_external_skia,mydongistiny/android_external_skia,jtg-gg/skia,pcwalton/skia,TeamEOS/external_skia,android-ia/platform_external_chromium_org_third_party_skia,sudosurootdev/external_skia,mozilla-b2g/external_skia,todotodoo/skia,pcwalton/skia,Tesla-Redux/android_external_skia,temasek/android_external_skia,nox/skia,mmatyas/skia,rubenvb/skia,nvoron23/skia,pacerom/external_skia,mydongistiny/external_chromium_org_third_party_skia,TeamTwisted/external_skia,xin3liang/platform_external_chromium_org_third_party_skia,boulzordev/android_external_skia,samuelig/skia,Fusion-Rom/external_chromium_org_third_party_skia,jtg-gg/skia,MinimalOS/android_external_skia,jtg-gg/skia,DARKPOP/external_chromium_org_third_party_skia,RadonX-ROM/external_skia,wildermason/external_skia,Pure-Aosp/android_external_skia,DesolationStaging/android_external_skia,invisiblek/android_external_skia,w3nd1go/android_external_skia,byterom/android_external_skia,Jichao/skia,F-AOSP/platform_external_skia,geekboxzone/lollipop_external_skia,AOSP-YU/platform_external_skia,nvoron23/skia,UBERMALLOW/external_skia,shahrzadmn/skia,MyAOSP/external_chromium_org_third_party_skia,FusionSP/external_chromium_org_third_party_skia,BrokenROM/external_skia,tmpvar/skia.cc,byterom/android_external_skia,shahrzadmn/skia,VRToxin-AOSP/android_external_skia,shahrzadmn/skia,MyAOSP/external_chromium_org_third_party_skia,InfinitiveOS/external_skia,NamelessRom/android_external_skia,TeslaProject/external_skia,rubenvb/skia,Fusion-Rom/external_chromium_org_third_party_skia,Hikari-no-Tenshi/android_external_skia,todotodoo/skia,ench0/external_skia,AOSPA-L/android_external_skia,chenlian2015/skia_from_google,ench0/external_chromium_org_third_party_skia,Fusion-Rom/external_chromium_org_third_party_skia,Igalia/skia,larsbergstrom/skia,HalCanary/skia-hc,timduru/platform-external-skia,aosp-mirror/platform_external_skia,spezi77/android_external_skia,Omegaphora/external_skia,codeaurora-unoffical/platform-external-skia,TeslaOS/android_external_skia,MonkeyZZZZ/platform_external_skia,MinimalOS/android_external_skia,akiss77/skia,TeslaOS/android_external_skia,vvuk/skia,aosp-mirror/platform_external_skia,nox/skia,MinimalOS/android_external_chromium_org_third_party_skia,TeamEOS/external_skia,geekboxzone/mmallow_external_skia,MIPS/external-chromium_org-third_party-skia,Jichao/skia,TeamBliss-LP/android_external_skia,scroggo/skia,PAC-ROM/android_external_skia,amyvmiwei/skia,geekboxzone/lollipop_external_chromium_org_third_party_skia,SlimSaber/android_external_skia,FusionSP/external_chromium_org_third_party_skia,ominux/skia,temasek/android_external_skia,temasek/android_external_skia,aospo/platform_external_skia,MIPS/external-chromium_org-third_party-skia,mozilla-b2g/external_skia,sudosurootdev/external_skia,UBERMALLOW/external_skia,android-ia/platform_external_skia,geekboxzone/lollipop_external_chromium_org_third_party_skia,android-ia/platform_external_chromium_org_third_party_skia,zhaochengw/platform_external_skia,TeslaProject/external_skia,MinimalOS-AOSP/platform_external_skia,mydongistiny/android_external_skia,chenlian2015/skia_from_google,amyvmiwei/skia,MinimalOS/android_external_skia,Plain-Andy/android_platform_external_skia,UBERMALLOW/external_skia,shahrzadmn/skia,Jichao/skia,TeslaOS/android_external_skia,FusionSP/external_chromium_org_third_party_skia,BrokenROM/external_skia,MonkeyZZZZ/platform_external_skia,TeamBliss-LP/android_external_skia,pacerom/external_skia,RadonX-ROM/external_skia,InfinitiveOS/external_skia,SlimSaber/android_external_skia,Omegaphora/external_skia,RadonX-ROM/external_skia
40e6f72c138755554e329cd36b2116aaf3f3d11c
atom/browser/atom_download_manager_delegate.cc
atom/browser/atom_download_manager_delegate.cc
// Copyright (c) 2015 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "atom/browser/atom_download_manager_delegate.h" #include <string> #include "atom/browser/api/atom_api_download_item.h" #include "atom/browser/atom_browser_context.h" #include "atom/browser/native_window.h" #include "atom/browser/ui/file_dialog.h" #include "base/bind.h" #include "base/files/file_util.h" #include "chrome/common/pref_names.h" #include "components/prefs/pref_service.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/download_manager.h" #include "net/base/filename_util.h" namespace atom { AtomDownloadManagerDelegate::AtomDownloadManagerDelegate( content::DownloadManager* manager) : download_manager_(manager), weak_ptr_factory_(this) {} AtomDownloadManagerDelegate::~AtomDownloadManagerDelegate() { if (download_manager_) { DCHECK_EQ(static_cast<content::DownloadManagerDelegate*>(this), download_manager_->GetDelegate()); download_manager_->SetDelegate(nullptr); download_manager_ = nullptr; } } void AtomDownloadManagerDelegate::GetItemSavePath(content::DownloadItem* item, base::FilePath* path) { v8::Isolate* isolate = v8::Isolate::GetCurrent(); v8::Locker locker(isolate); v8::HandleScope handle_scope(isolate); api::DownloadItem* download = api::DownloadItem::FromWrappedClass(isolate, item); if (download) *path = download->GetSavePath(); } void AtomDownloadManagerDelegate::CreateDownloadPath( const GURL& url, const std::string& content_disposition, const std::string& suggested_filename, const std::string& mime_type, const base::FilePath& default_download_path, const CreateDownloadPathCallback& callback) { DCHECK_CURRENTLY_ON(content::BrowserThread::FILE); auto generated_name = net::GenerateFileName(url, content_disposition, std::string(), suggested_filename, mime_type, std::string()); if (!base::PathExists(default_download_path)) base::CreateDirectory(default_download_path); base::FilePath path(default_download_path.Append(generated_name)); content::BrowserThread::PostTask(content::BrowserThread::UI, FROM_HERE, base::Bind(callback, path)); } void AtomDownloadManagerDelegate::OnDownloadPathGenerated( uint32_t download_id, const content::DownloadTargetCallback& callback, const base::FilePath& default_path) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); auto item = download_manager_->GetDownload(download_id); if (!item) return; NativeWindow* window = nullptr; content::WebContents* web_contents = item->GetWebContents(); auto relay = web_contents ? NativeWindowRelay::FromWebContents(web_contents) : nullptr; if (relay) window = relay->window.get(); base::FilePath path; GetItemSavePath(item, &path); // Show save dialog if save path was not set already on item if (path.empty() && file_dialog::ShowSaveDialog(window, item->GetURL().spec(), "", default_path, file_dialog::Filters(), &path)) { // Remember the last selected download directory. AtomBrowserContext* browser_context = static_cast<AtomBrowserContext*>( download_manager_->GetBrowserContext()); browser_context->prefs()->SetFilePath(prefs::kDownloadDefaultDirectory, path.DirName()); v8::Isolate* isolate = v8::Isolate::GetCurrent(); v8::Locker locker(isolate); v8::HandleScope handle_scope(isolate); api::DownloadItem* download_item = api::DownloadItem::FromWrappedClass( isolate, item); if (download_item) download_item->SetSavePath(path); } // Running the DownloadTargetCallback with an empty FilePath signals that the // download should be cancelled. // If user cancels the file save dialog, run the callback with empty FilePath. callback.Run(path, content::DownloadItem::TARGET_DISPOSITION_PROMPT, content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, path); } void AtomDownloadManagerDelegate::Shutdown() { weak_ptr_factory_.InvalidateWeakPtrs(); download_manager_ = nullptr; } bool AtomDownloadManagerDelegate::DetermineDownloadTarget( content::DownloadItem* download, const content::DownloadTargetCallback& callback) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); if (!download->GetForcedFilePath().empty()) { callback.Run(download->GetForcedFilePath(), content::DownloadItem::TARGET_DISPOSITION_OVERWRITE, content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, download->GetForcedFilePath()); return true; } // Try to get the save path from JS wrapper. base::FilePath save_path; GetItemSavePath(download, &save_path); if (!save_path.empty()) { callback.Run(save_path, content::DownloadItem::TARGET_DISPOSITION_OVERWRITE, content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, save_path); return true; } AtomBrowserContext* browser_context = static_cast<AtomBrowserContext*>( download_manager_->GetBrowserContext()); base::FilePath default_download_path = browser_context->prefs()->GetFilePath( prefs::kDownloadDefaultDirectory); CreateDownloadPathCallback download_path_callback = base::Bind(&AtomDownloadManagerDelegate::OnDownloadPathGenerated, weak_ptr_factory_.GetWeakPtr(), download->GetId(), callback); content::BrowserThread::PostTask( content::BrowserThread::FILE, FROM_HERE, base::Bind(&AtomDownloadManagerDelegate::CreateDownloadPath, weak_ptr_factory_.GetWeakPtr(), download->GetURL(), download->GetContentDisposition(), download->GetSuggestedFilename(), download->GetMimeType(), default_download_path, download_path_callback)); return true; } bool AtomDownloadManagerDelegate::ShouldOpenDownload( content::DownloadItem* download, const content::DownloadOpenDelayedCallback& callback) { return true; } void AtomDownloadManagerDelegate::GetNextId( const content::DownloadIdCallback& callback) { static uint32_t next_id = content::DownloadItem::kInvalidId + 1; callback.Run(next_id++); } } // namespace atom
// Copyright (c) 2015 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "atom/browser/atom_download_manager_delegate.h" #include <string> #include "atom/browser/api/atom_api_download_item.h" #include "atom/browser/atom_browser_context.h" #include "atom/browser/native_window.h" #include "atom/browser/ui/file_dialog.h" #include "base/bind.h" #include "base/files/file_util.h" #include "chrome/common/pref_names.h" #include "components/prefs/pref_service.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/download_manager.h" #include "net/base/filename_util.h" namespace atom { AtomDownloadManagerDelegate::AtomDownloadManagerDelegate( content::DownloadManager* manager) : download_manager_(manager), weak_ptr_factory_(this) {} AtomDownloadManagerDelegate::~AtomDownloadManagerDelegate() { if (download_manager_) { DCHECK_EQ(static_cast<content::DownloadManagerDelegate*>(this), download_manager_->GetDelegate()); download_manager_->SetDelegate(nullptr); download_manager_ = nullptr; } } void AtomDownloadManagerDelegate::GetItemSavePath(content::DownloadItem* item, base::FilePath* path) { v8::Isolate* isolate = v8::Isolate::GetCurrent(); v8::Locker locker(isolate); v8::HandleScope handle_scope(isolate); api::DownloadItem* download = api::DownloadItem::FromWrappedClass(isolate, item); if (download) *path = download->GetSavePath(); } void AtomDownloadManagerDelegate::CreateDownloadPath( const GURL& url, const std::string& content_disposition, const std::string& suggested_filename, const std::string& mime_type, const base::FilePath& default_download_path, const CreateDownloadPathCallback& callback) { DCHECK_CURRENTLY_ON(content::BrowserThread::FILE); auto generated_name = net::GenerateFileName(url, content_disposition, std::string(), suggested_filename, mime_type, std::string()); if (!base::PathExists(default_download_path)) base::CreateDirectory(default_download_path); base::FilePath path(default_download_path.Append(generated_name)); content::BrowserThread::PostTask(content::BrowserThread::UI, FROM_HERE, base::Bind(callback, path)); } void AtomDownloadManagerDelegate::OnDownloadPathGenerated( uint32_t download_id, const content::DownloadTargetCallback& callback, const base::FilePath& default_path) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); auto item = download_manager_->GetDownload(download_id); if (!item) return; NativeWindow* window = nullptr; content::WebContents* web_contents = item->GetWebContents(); auto relay = web_contents ? NativeWindowRelay::FromWebContents(web_contents) : nullptr; if (relay) window = relay->window.get(); base::FilePath path; GetItemSavePath(item, &path); // Show save dialog if save path was not set already on item if (path.empty() && file_dialog::ShowSaveDialog(window, item->GetURL().spec(), "", default_path, file_dialog::Filters(), &path)) { // Remember the last selected download directory. AtomBrowserContext* browser_context = static_cast<AtomBrowserContext*>( download_manager_->GetBrowserContext()); browser_context->prefs()->SetFilePath(prefs::kDownloadDefaultDirectory, path.DirName()); v8::Isolate* isolate = v8::Isolate::GetCurrent(); v8::Locker locker(isolate); v8::HandleScope handle_scope(isolate); api::DownloadItem* download_item = api::DownloadItem::FromWrappedClass( isolate, item); if (download_item) download_item->SetSavePath(path); } callback.Run(path, content::DownloadItem::TARGET_DISPOSITION_PROMPT, content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, path, path.empty() ? content::DOWNLOAD_INTERRUPT_REASON_USER_CANCELED : content::DOWNLOAD_INTERRUPT_REASON_NONE); } void AtomDownloadManagerDelegate::Shutdown() { weak_ptr_factory_.InvalidateWeakPtrs(); download_manager_ = nullptr; } bool AtomDownloadManagerDelegate::DetermineDownloadTarget( content::DownloadItem* download, const content::DownloadTargetCallback& callback) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); if (!download->GetForcedFilePath().empty()) { callback.Run(download->GetForcedFilePath(), content::DownloadItem::TARGET_DISPOSITION_OVERWRITE, content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, download->GetForcedFilePath(), content::DOWNLOAD_INTERRUPT_REASON_NONE); return true; } // Try to get the save path from JS wrapper. base::FilePath save_path; GetItemSavePath(download, &save_path); if (!save_path.empty()) { callback.Run(save_path, content::DownloadItem::TARGET_DISPOSITION_OVERWRITE, content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, save_path, content::DOWNLOAD_INTERRUPT_REASON_NONE); return true; } AtomBrowserContext* browser_context = static_cast<AtomBrowserContext*>( download_manager_->GetBrowserContext()); base::FilePath default_download_path = browser_context->prefs()->GetFilePath( prefs::kDownloadDefaultDirectory); CreateDownloadPathCallback download_path_callback = base::Bind(&AtomDownloadManagerDelegate::OnDownloadPathGenerated, weak_ptr_factory_.GetWeakPtr(), download->GetId(), callback); content::BrowserThread::PostTask( content::BrowserThread::FILE, FROM_HERE, base::Bind(&AtomDownloadManagerDelegate::CreateDownloadPath, weak_ptr_factory_.GetWeakPtr(), download->GetURL(), download->GetContentDisposition(), download->GetSuggestedFilename(), download->GetMimeType(), default_download_path, download_path_callback)); return true; } bool AtomDownloadManagerDelegate::ShouldOpenDownload( content::DownloadItem* download, const content::DownloadOpenDelayedCallback& callback) { return true; } void AtomDownloadManagerDelegate::GetNextId( const content::DownloadIdCallback& callback) { static uint32_t next_id = content::DownloadItem::kInvalidId + 1; callback.Run(next_id++); } } // namespace atom
Add DownloadInterruptReason param to DownloadTargetCallback
Add DownloadInterruptReason param to DownloadTargetCallback
C++
mit
brave/electron,brave/muon,brave/electron,brave/muon,brave/electron,brave/electron,brave/electron,brave/muon,brave/muon,brave/muon,brave/electron,brave/muon
f661a0013f73cb8d45c3f0999fea15686dcd2993
Samples/SSDPServer/Sources/SSDPServer.cpp
Samples/SSDPServer/Sources/SSDPServer.cpp
/* * Copyright(c) Sophist Solutions, Inc. 1990-2013. All rights reserved */ #include "Stroika/Frameworks/StroikaPreComp.h" #include <mutex> #include <iostream> #include "Stroika/Foundation/Characters/Format.h" #include "Stroika/Foundation/Execution/CommandLine.h" #include "Stroika/Foundation/Execution/Event.h" #include "Stroika/Foundation/Memory/Optional.h" #include "Stroika/Foundation/IO/Network/HTTP/Headers.h" #include "Stroika/Foundation/IO/Network/NetworkInterfaces.h" #include "Stroika/Foundation/IO/Network/Listener.h" #include "Stroika/Foundation/Streams/iostream/BinaryInputStreamFromIStreamAdapter.h" #include "Stroika/Frameworks/UPnP/SSDP/Server/BasicServer.h" #include "Stroika/Frameworks/WebServer/ConnectionManager.h" using namespace std; using namespace Stroika::Foundation; using namespace Stroika::Foundation::IO; using namespace Stroika::Foundation::IO::Network; using namespace Stroika::Frameworks; using namespace Stroika::Frameworks::UPnP; using namespace Stroika::Frameworks::UPnP::SSDP; using namespace Stroika::Frameworks::WebServer; using Characters::String; using Containers::Sequence; using Memory::Optional; using Server::BasicServer; namespace { struct WebServerForDeviceDescription_ { WebServerForDeviceDescription_ (uint16_t webServerPortNumber, Memory::BLOB deviceDescription) : fListener () { auto onConnect = [deviceDescription](Socket s) { Execution::Thread runConnectionOnAnotherThread ([s, deviceDescription]() { // now read Connection conn (s); conn.ReadHeaders (); // bad API. Must rethink... conn.GetResponse ().AddHeader (IO::Network::HTTP::HeaderName::kServer, L"stroika-ssdp-server-demo"); conn.GetResponse ().write (deviceDescription.begin (), deviceDescription.end ()); conn.GetResponse ().SetContentType (DataExchange::PredefinedInternetMediaType::XML_CT ()); conn.GetResponse ().End (); }); runConnectionOnAnotherThread.SetThreadName (L"Connection Thread"); // SHOULD use a fancier name (connection#) runConnectionOnAnotherThread.Start (); //runConnectionOnAnotherThread.WaitForDone (); // maybe save these in connection mgr so we can force them all shut down... }; //fListener = std::move (Listener (SocketAddress (Network::V4::kAddrAny, webServerPortNumber), onConnect)); fListener = shared_ptr<Listener> (new Listener (SocketAddress (Network::V4::kAddrAny, webServerPortNumber), onConnect)); } // @todo - FIX OPTIONAL (and related code) -so Optional<> works here - rvalue -references //Memory::Optional<Listener> fListener; shared_ptr<Listener> fListener; }; } int main (int argc, const char* argv[]) { try { uint16_t portForOurWS = 8080; Device d; d.fLocation = Characters::Format (L"http://%s:%d", IO::Network::GetPrimaryInternetAddress ().As<String> ().c_str (), portForOurWS); d.fServer = L"unix/5.1 UPnP/1.1 MyProduct/1.0"; // @todo wrong - to be fixed d.fDeviceID = L"315CAAE0-668D-47C7-A178-24C9EE756627"; DeviceDescription deviceInfo; deviceInfo.fPresentationURL = L"http://www.sophists.com/"; deviceInfo.fDeviceType = L"urn:sophists.com:device:deviceType:1.0"; deviceInfo.fManufactureName = L"Sophist Solutions, Inc."; deviceInfo.fFriendlyName = L"Sophist Solutions fake device"; deviceInfo.fManufacturingURL = L"http://www.sophists.com/"; deviceInfo.fModelDescription = L"long user-friendly title"; deviceInfo.fModelName = L"model name"; deviceInfo.fModelNumber = L"model number"; deviceInfo.fModelURL = L"http://www.sophists.com/"; deviceInfo.fSerialNumber = L"manufacturer's serial number"; WebServerForDeviceDescription_ deviceWS (portForOurWS, Stroika::Frameworks::UPnP::Serialize (d, deviceInfo)); BasicServer b (d, BasicServer::FrequencyInfo ()); Execution::Event ().Wait (); // wait forever - til user hits ctrl-c } catch (...) { cerr << "Exception - terminating..." << endl; return EXIT_FAILURE; } return EXIT_SUCCESS; }
/* * Copyright(c) Sophist Solutions, Inc. 1990-2013. All rights reserved */ #include "Stroika/Frameworks/StroikaPreComp.h" #include <mutex> #include <iostream> #include "Stroika/Foundation/Characters/Format.h" #include "Stroika/Foundation/Execution/CommandLine.h" #include "Stroika/Foundation/Execution/Event.h" #include "Stroika/Foundation/Memory/Optional.h" #include "Stroika/Foundation/IO/Network/HTTP/Headers.h" #include "Stroika/Foundation/IO/Network/NetworkInterfaces.h" #include "Stroika/Foundation/IO/Network/Listener.h" #include "Stroika/Foundation/Streams/iostream/BinaryInputStreamFromIStreamAdapter.h" #include "Stroika/Frameworks/UPnP/SSDP/Server/BasicServer.h" #include "Stroika/Frameworks/WebServer/ConnectionManager.h" using namespace std; using namespace Stroika::Foundation; using namespace Stroika::Foundation::IO; using namespace Stroika::Foundation::IO::Network; using namespace Stroika::Frameworks; using namespace Stroika::Frameworks::UPnP; using namespace Stroika::Frameworks::UPnP::SSDP; using namespace Stroika::Frameworks::WebServer; using Characters::String; using Containers::Sequence; using Memory::Optional; using Server::BasicServer; namespace { struct WebServerForDeviceDescription_ { WebServerForDeviceDescription_ (uint16_t webServerPortNumber, Memory::BLOB deviceDescription) : fListener () { auto onConnect = [deviceDescription](Socket s) { Execution::Thread runConnectionOnAnotherThread ([s, deviceDescription]() { // now read Connection conn (s); conn.ReadHeaders (); // bad API. Must rethink... conn.GetResponse ().AddHeader (IO::Network::HTTP::HeaderName::kServer, L"stroika-ssdp-server-demo"); conn.GetResponse ().write (deviceDescription.begin (), deviceDescription.end ()); conn.GetResponse ().SetContentType (DataExchange::PredefinedInternetMediaType::XML_CT ()); conn.GetResponse ().End (); }); runConnectionOnAnotherThread.SetThreadName (L"Connection Thread"); // SHOULD use a fancier name (connection#) runConnectionOnAnotherThread.Start (); //runConnectionOnAnotherThread.WaitForDone (); // maybe save these in connection mgr so we can force them all shut down... }; //fListener = std::move (Listener (SocketAddress (Network::V4::kAddrAny, webServerPortNumber), onConnect)); fListener = shared_ptr<Listener> (new Listener (SocketAddress (Network::V4::kAddrAny, webServerPortNumber), onConnect)); } // @todo - FIX OPTIONAL (and related code) -so Optional<> works here - rvalue -references //Memory::Optional<Listener> fListener; shared_ptr<Listener> fListener; }; } int main (int argc, const char* argv[]) { try { uint16_t portForOurWS = 8080; Device d; d.fLocation = Characters::Format (L"http://%s:%d", IO::Network::GetPrimaryInternetAddress ().As<String> ().c_str (), portForOurWS); d.fServer = L"unix/5.1 UPnP/1.1 MyProduct/1.0"; // @todo wrong - to be fixed d.fDeviceID = UPnP::MungePrimaryMacAddrIntoBaseDeviceID (L"315CAAE0-1335-57BF-A178-24C9EE756627"); DeviceDescription deviceInfo; deviceInfo.fPresentationURL = L"http://www.sophists.com/"; deviceInfo.fDeviceType = L"urn:sophists.com:device:deviceType:1.0"; deviceInfo.fManufactureName = L"Sophist Solutions, Inc."; deviceInfo.fFriendlyName = L"Sophist Solutions fake device"; deviceInfo.fManufacturingURL = L"http://www.sophists.com/"; deviceInfo.fModelDescription = L"long user-friendly title"; deviceInfo.fModelName = L"model name"; deviceInfo.fModelNumber = L"model number"; deviceInfo.fModelURL = L"http://www.sophists.com/"; deviceInfo.fSerialNumber = L"manufacturer's serial number"; WebServerForDeviceDescription_ deviceWS (portForOurWS, Stroika::Frameworks::UPnP::Serialize (d, deviceInfo)); BasicServer b (d, BasicServer::FrequencyInfo ()); Execution::Event ().Wait (); // wait forever - til user hits ctrl-c } catch (...) { cerr << "Exception - terminating..." << endl; return EXIT_FAILURE; } return EXIT_SUCCESS; }
use new UPnP::MungePrimaryMacAddrIntoBaseDeviceID () in SSDPServer Sample code so we get unique addrs in testing SSDPServer
use new UPnP::MungePrimaryMacAddrIntoBaseDeviceID () in SSDPServer Sample code so we get unique addrs in testing SSDPServer
C++
mit
SophistSolutions/Stroika,SophistSolutions/Stroika,SophistSolutions/Stroika,SophistSolutions/Stroika,SophistSolutions/Stroika
3dff7620355597df0ddad435869fe9f31784f7c4
Code/Numerics/itkSingleValuedVnlCostFunctionAdaptor.cxx
Code/Numerics/itkSingleValuedVnlCostFunctionAdaptor.cxx
/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkSingleValuedVnlCostFunctionAdaptor.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 2002 Insight Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "itkSingleValuedVnlCostFunctionAdaptor.h" #include "itkExceptionObject.h" namespace itk { /** Constructor. */ SingleValuedVnlCostFunctionAdaptor ::SingleValuedVnlCostFunctionAdaptor(unsigned int spaceDimension): vnl_cost_function(spaceDimension) { } /** Delegate computation of the value to the CostFunction. */ SingleValuedVnlCostFunctionAdaptor::InternalMeasureType SingleValuedVnlCostFunctionAdaptor ::f( const InternalParametersType & inparameters ) { if( !m_CostFunction ) { itkGenericExceptionMacro(<<"Attempt to use a SingleValuedVnlCostFunctionAdaptor without any CostFunction plugged in"); } ParametersType parameters( inparameters.size() ); ConvertInternalToExternalParameters( inparameters, parameters ); const InternalMeasureType value = static_cast<InternalMeasureType>( m_CostFunction->GetValue( parameters )); return value; } /** Delegate computation of the gradient to the costfunction. */ void SingleValuedVnlCostFunctionAdaptor ::gradf( const InternalParametersType & inparameters, InternalDerivativeType & gradient ) { if( !m_CostFunction ) { itkGenericExceptionMacro("Attempt to use a SingleValuedVnlCostFunctionAdaptor without any CostFunction plugged in"); } ParametersType parameters( inparameters.size() ); ConvertInternalToExternalParameters( inparameters, parameters ); DerivativeType externalGradient; m_CostFunction->GetDerivative( parameters, externalGradient ); ConvertExternalToInternalGradient( externalGradient, gradient); } /** Delegate computation of value and gradient to the costfunction. */ void SingleValuedVnlCostFunctionAdaptor ::compute( const InternalParametersType & x, InternalMeasureType * f, InternalDerivativeType * g ) { // delegate the computation to the CostFunction ParametersType parameters( x.size() ); ConvertInternalToExternalParameters( x, parameters ); *f = static_cast<InternalMeasureType>( m_CostFunction->GetValue( parameters ) ); DerivativeType externalGradient; m_CostFunction->GetDerivative( parameters, externalGradient ); ConvertExternalToInternalGradient( externalGradient, *g ); } /** Convert internal Parameters into external type. */ void SingleValuedVnlCostFunctionAdaptor ::ConvertInternalToExternalParameters( const InternalParametersType & input, ParametersType & output ) { const unsigned int size = input.size(); for( unsigned int i=0; i<size; i++ ) { output[i] = input[i]; } } /** Convert external Parameters into internal type */ void SingleValuedVnlCostFunctionAdaptor ::ConvertExternalToInternalParameters( const ParametersType & input, InternalParametersType & output ) { const unsigned int size = input.size(); for( unsigned int i=0; i<size; i++ ) { output[i] = input[i]; } } /** Convert external derviative measures into internal type */ void SingleValuedVnlCostFunctionAdaptor ::ConvertExternalToInternalGradient( const DerivativeType & input, InternalDerivativeType & output ) { const unsigned int size = input.size(); for( unsigned int i=0; i<size; i++ ) { output[i] = input[i]; } } } // end namespace itk
/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkSingleValuedVnlCostFunctionAdaptor.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 2002 Insight Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "itkSingleValuedVnlCostFunctionAdaptor.h" #include "itkExceptionObject.h" namespace itk { /** Constructor. */ SingleValuedVnlCostFunctionAdaptor ::SingleValuedVnlCostFunctionAdaptor(unsigned int spaceDimension): vnl_cost_function(spaceDimension) { } /** Delegate computation of the value to the CostFunction. */ SingleValuedVnlCostFunctionAdaptor::InternalMeasureType SingleValuedVnlCostFunctionAdaptor ::f( const InternalParametersType & inparameters ) { if( !m_CostFunction ) { itkGenericExceptionMacro(<<"Attempt to use a SingleValuedVnlCostFunctionAdaptor without any CostFunction plugged in"); } ParametersType parameters( inparameters.size() ); ConvertInternalToExternalParameters( inparameters, parameters ); const InternalMeasureType value = static_cast<InternalMeasureType>( m_CostFunction->GetValue( parameters )); return value; } /** Delegate computation of the gradient to the costfunction. */ void SingleValuedVnlCostFunctionAdaptor ::gradf( const InternalParametersType & inparameters, InternalDerivativeType & gradient ) { if( !m_CostFunction ) { itkGenericExceptionMacro("Attempt to use a SingleValuedVnlCostFunctionAdaptor without any CostFunction plugged in"); } ParametersType parameters( inparameters.size() ); ConvertInternalToExternalParameters( inparameters, parameters ); DerivativeType externalGradient; m_CostFunction->GetDerivative( parameters, externalGradient ); ConvertExternalToInternalGradient( externalGradient, gradient); } /** Delegate computation of value and gradient to the costfunction. */ void SingleValuedVnlCostFunctionAdaptor ::compute( const InternalParametersType & x, InternalMeasureType * f, InternalDerivativeType * g ) { // delegate the computation to the CostFunction ParametersType parameters( x.size() ); ConvertInternalToExternalParameters( x, parameters ); *f = static_cast<InternalMeasureType>( m_CostFunction->GetValue( parameters ) ); DerivativeType externalGradient; m_CostFunction->GetDerivative( parameters, externalGradient ); ConvertExternalToInternalGradient( externalGradient, *g ); } /** Convert internal Parameters into external type. */ void SingleValuedVnlCostFunctionAdaptor ::ConvertInternalToExternalParameters( const InternalParametersType & input, ParametersType & output ) { const unsigned int size = input.size(); output = ParametersType(size); for( unsigned int i=0; i<size; i++ ) { output[i] = input[i]; } } /** Convert external Parameters into internal type */ void SingleValuedVnlCostFunctionAdaptor ::ConvertExternalToInternalParameters( const ParametersType & input, InternalParametersType & output ) { const unsigned int size = input.size(); for( unsigned int i=0; i<size; i++ ) { output[i] = input[i]; } } /** Convert external derviative measures into internal type */ void SingleValuedVnlCostFunctionAdaptor ::ConvertExternalToInternalGradient( const DerivativeType & input, InternalDerivativeType & output ) { const unsigned int size = input.size(); output = InternalDerivativeType(size); for( unsigned int i=0; i<size; i++ ) { output[i] = input[i]; } } } // end namespace itk
fix crash
ENH: fix crash
C++
apache-2.0
hinerm/ITK,zachary-williamson/ITK,PlutoniumHeart/ITK,BlueBrain/ITK,msmolens/ITK,fuentesdt/InsightToolkit-dev,itkvideo/ITK,wkjeong/ITK,hjmjohnson/ITK,spinicist/ITK,BlueBrain/ITK,PlutoniumHeart/ITK,vfonov/ITK,LucasGandel/ITK,fedral/ITK,fuentesdt/InsightToolkit-dev,Kitware/ITK,Kitware/ITK,Kitware/ITK,GEHC-Surgery/ITK,hinerm/ITK,fedral/ITK,CapeDrew/DCMTK-ITK,hinerm/ITK,BRAINSia/ITK,jcfr/ITK,fedral/ITK,cpatrick/ITK-RemoteIO,stnava/ITK,zachary-williamson/ITK,malaterre/ITK,spinicist/ITK,jmerkow/ITK,blowekamp/ITK,itkvideo/ITK,fuentesdt/InsightToolkit-dev,jmerkow/ITK,stnava/ITK,vfonov/ITK,thewtex/ITK,heimdali/ITK,fbudin69500/ITK,CapeDrew/DITK,LucasGandel/ITK,PlutoniumHeart/ITK,hjmjohnson/ITK,msmolens/ITK,daviddoria/itkHoughTransform,richardbeare/ITK,zachary-williamson/ITK,LucasGandel/ITK,LucHermitte/ITK,malaterre/ITK,CapeDrew/DITK,LucHermitte/ITK,CapeDrew/DCMTK-ITK,fbudin69500/ITK,thewtex/ITK,BlueBrain/ITK,jmerkow/ITK,daviddoria/itkHoughTransform,hjmjohnson/ITK,ajjl/ITK,spinicist/ITK,PlutoniumHeart/ITK,wkjeong/ITK,GEHC-Surgery/ITK,eile/ITK,richardbeare/ITK,blowekamp/ITK,ajjl/ITK,biotrump/ITK,jcfr/ITK,richardbeare/ITK,fbudin69500/ITK,eile/ITK,itkvideo/ITK,malaterre/ITK,InsightSoftwareConsortium/ITK,malaterre/ITK,hinerm/ITK,fbudin69500/ITK,spinicist/ITK,BlueBrain/ITK,biotrump/ITK,wkjeong/ITK,PlutoniumHeart/ITK,BRAINSia/ITK,blowekamp/ITK,ajjl/ITK,fbudin69500/ITK,jcfr/ITK,daviddoria/itkHoughTransform,eile/ITK,hendradarwin/ITK,heimdali/ITK,atsnyder/ITK,atsnyder/ITK,CapeDrew/DCMTK-ITK,fuentesdt/InsightToolkit-dev,wkjeong/ITK,rhgong/itk-with-dom,jmerkow/ITK,fedral/ITK,atsnyder/ITK,zachary-williamson/ITK,cpatrick/ITK-RemoteIO,GEHC-Surgery/ITK,CapeDrew/DITK,msmolens/ITK,CapeDrew/DCMTK-ITK,cpatrick/ITK-RemoteIO,CapeDrew/DCMTK-ITK,jcfr/ITK,rhgong/itk-with-dom,rhgong/itk-with-dom,biotrump/ITK,heimdali/ITK,eile/ITK,blowekamp/ITK,paulnovo/ITK,ajjl/ITK,fbudin69500/ITK,biotrump/ITK,rhgong/itk-with-dom,daviddoria/itkHoughTransform,cpatrick/ITK-RemoteIO,CapeDrew/DITK,stnava/ITK,ajjl/ITK,eile/ITK,fbudin69500/ITK,BlueBrain/ITK,daviddoria/itkHoughTransform,daviddoria/itkHoughTransform,fedral/ITK,blowekamp/ITK,itkvideo/ITK,rhgong/itk-with-dom,hendradarwin/ITK,Kitware/ITK,rhgong/itk-with-dom,jmerkow/ITK,thewtex/ITK,stnava/ITK,LucasGandel/ITK,CapeDrew/DITK,fedral/ITK,hinerm/ITK,CapeDrew/DITK,malaterre/ITK,fedral/ITK,GEHC-Surgery/ITK,thewtex/ITK,biotrump/ITK,InsightSoftwareConsortium/ITK,biotrump/ITK,blowekamp/ITK,rhgong/itk-with-dom,blowekamp/ITK,BlueBrain/ITK,stnava/ITK,Kitware/ITK,hinerm/ITK,stnava/ITK,heimdali/ITK,thewtex/ITK,vfonov/ITK,PlutoniumHeart/ITK,richardbeare/ITK,fuentesdt/InsightToolkit-dev,vfonov/ITK,thewtex/ITK,hinerm/ITK,richardbeare/ITK,InsightSoftwareConsortium/ITK,stnava/ITK,vfonov/ITK,CapeDrew/DCMTK-ITK,hjmjohnson/ITK,cpatrick/ITK-RemoteIO,jmerkow/ITK,LucHermitte/ITK,jcfr/ITK,stnava/ITK,atsnyder/ITK,GEHC-Surgery/ITK,zachary-williamson/ITK,eile/ITK,LucasGandel/ITK,msmolens/ITK,malaterre/ITK,Kitware/ITK,hendradarwin/ITK,rhgong/itk-with-dom,InsightSoftwareConsortium/ITK,hjmjohnson/ITK,hendradarwin/ITK,paulnovo/ITK,fedral/ITK,atsnyder/ITK,fuentesdt/InsightToolkit-dev,LucHermitte/ITK,fuentesdt/InsightToolkit-dev,atsnyder/ITK,itkvideo/ITK,BRAINSia/ITK,richardbeare/ITK,spinicist/ITK,LucHermitte/ITK,BlueBrain/ITK,wkjeong/ITK,itkvideo/ITK,atsnyder/ITK,spinicist/ITK,paulnovo/ITK,richardbeare/ITK,malaterre/ITK,CapeDrew/DITK,CapeDrew/DITK,hendradarwin/ITK,GEHC-Surgery/ITK,hendradarwin/ITK,BRAINSia/ITK,msmolens/ITK,eile/ITK,biotrump/ITK,vfonov/ITK,wkjeong/ITK,Kitware/ITK,daviddoria/itkHoughTransform,LucasGandel/ITK,biotrump/ITK,heimdali/ITK,heimdali/ITK,LucHermitte/ITK,eile/ITK,spinicist/ITK,vfonov/ITK,CapeDrew/DITK,itkvideo/ITK,jmerkow/ITK,paulnovo/ITK,hjmjohnson/ITK,cpatrick/ITK-RemoteIO,jcfr/ITK,jcfr/ITK,paulnovo/ITK,jmerkow/ITK,PlutoniumHeart/ITK,atsnyder/ITK,ajjl/ITK,fuentesdt/InsightToolkit-dev,LucHermitte/ITK,heimdali/ITK,malaterre/ITK,stnava/ITK,hendradarwin/ITK,eile/ITK,thewtex/ITK,cpatrick/ITK-RemoteIO,hinerm/ITK,ajjl/ITK,atsnyder/ITK,spinicist/ITK,msmolens/ITK,paulnovo/ITK,InsightSoftwareConsortium/ITK,GEHC-Surgery/ITK,GEHC-Surgery/ITK,spinicist/ITK,fbudin69500/ITK,msmolens/ITK,CapeDrew/DCMTK-ITK,InsightSoftwareConsortium/ITK,itkvideo/ITK,wkjeong/ITK,heimdali/ITK,ajjl/ITK,CapeDrew/DCMTK-ITK,paulnovo/ITK,wkjeong/ITK,daviddoria/itkHoughTransform,zachary-williamson/ITK,BRAINSia/ITK,msmolens/ITK,LucasGandel/ITK,PlutoniumHeart/ITK,zachary-williamson/ITK,paulnovo/ITK,zachary-williamson/ITK,fuentesdt/InsightToolkit-dev,hjmjohnson/ITK,blowekamp/ITK,cpatrick/ITK-RemoteIO,CapeDrew/DCMTK-ITK,jcfr/ITK,BlueBrain/ITK,zachary-williamson/ITK,LucasGandel/ITK,InsightSoftwareConsortium/ITK,malaterre/ITK,LucHermitte/ITK,vfonov/ITK,hinerm/ITK,BRAINSia/ITK,hendradarwin/ITK,daviddoria/itkHoughTransform,BRAINSia/ITK,vfonov/ITK,itkvideo/ITK
0e0d716684f90e1ba5f34dc7ad961bc323b711ed
src/3rdparty/phonon/mmf/videoplayer.cpp
src/3rdparty/phonon/mmf/videoplayer.cpp
/* This file is part of the KDE project. Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). 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 or 3 of the License. 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, see <http://www.gnu.org/licenses/>. */ #include <QUrl> #include <QTimer> #include <QWidget> #include <coemain.h> // For CCoeEnv #include <coecntrl.h> #include "videoplayer.h" #include "utils.h" #ifdef _DEBUG #include "objectdump/objectdump.h" #endif QT_BEGIN_NAMESPACE using namespace Phonon; using namespace Phonon::MMF; //----------------------------------------------------------------------------- // Constructor / destructor //----------------------------------------------------------------------------- MMF::VideoPlayer::VideoPlayer() : m_wsSession(NULL) , m_screenDevice(NULL) , m_window(NULL) , m_totalTime(0) , m_mmfOutputChangePending(false) { construct(); } MMF::VideoPlayer::VideoPlayer(const AbstractPlayer& player) : AbstractMediaPlayer(player) , m_wsSession(NULL) , m_screenDevice(NULL) , m_window(NULL) , m_totalTime(0) , m_mmfOutputChangePending(false) { construct(); } void MMF::VideoPlayer::construct() { TRACE_CONTEXT(VideoPlayer::VideoPlayer, EVideoApi); TRACE_ENTRY_0(); if (!m_videoOutput) { m_dummyVideoOutput.reset(new VideoOutput(NULL)); } videoOutput().setObserver(this); const TInt priority = 0; const TMdaPriorityPreference preference = EMdaPriorityPreferenceNone; getNativeWindowSystemHandles(); // TODO: is this the correct way to handle errors which occur when // creating a Symbian object in the constructor of a Qt object? // TODO: check whether videoOutput is visible? If not, then the // corresponding window will not be active, meaning that the // clipping region will be set to empty and the video will not be // visible. If this is the case, we should set m_mmfOutputChangePending // and respond to future showEvents from the videoOutput widget. TRAPD(err, m_player.reset(CVideoPlayerUtility::NewL ( *this, priority, preference, *m_wsSession, *m_screenDevice, *m_window, m_windowRect, m_clipRect )) ); if (KErrNone != err) { changeState(ErrorState); } TRACE_EXIT_0(); } MMF::VideoPlayer::~VideoPlayer() { TRACE_CONTEXT(VideoPlayer::~VideoPlayer, EVideoApi); TRACE_ENTRY_0(); TRACE_EXIT_0(); } //----------------------------------------------------------------------------- // Public API //----------------------------------------------------------------------------- void MMF::VideoPlayer::doPlay() { TRACE_CONTEXT(VideoPlayer::doPlay, EVideoApi); // See comment in updateMmfOutput if(m_mmfOutputChangePending) { TRACE_0("MMF output change pending - pushing now"); updateMmfOutput(); } m_player->Play(); } void MMF::VideoPlayer::doPause() { TRACE_CONTEXT(VideoPlayer::doPause, EVideoApi); TRAPD(err, m_player->PauseL()); if (KErrNone != err) { TRACE("PauseL error %d", err); setError(NormalError); } } void MMF::VideoPlayer::doStop() { m_player->Stop(); } void MMF::VideoPlayer::doSeek(qint64 ms) { TRACE_CONTEXT(VideoPlayer::doSeek, EVideoApi); TRAPD(err, m_player->SetPositionL(TTimeIntervalMicroSeconds(ms * 1000))); if (KErrNone != err) { TRACE("SetPositionL error %d", err); setError(NormalError); } } int MMF::VideoPlayer::setDeviceVolume(int mmfVolume) { TRAPD(err, m_player->SetVolumeL(mmfVolume)); return err; } int MMF::VideoPlayer::openFile(RFile& file) { TRAPD(err, m_player->OpenFileL(file)); return err; } void MMF::VideoPlayer::close() { m_player->Close(); } bool MMF::VideoPlayer::hasVideo() const { return true; } qint64 MMF::VideoPlayer::currentTime() const { TRACE_CONTEXT(VideoPlayer::currentTime, EVideoApi); TTimeIntervalMicroSeconds us; TRAPD(err, us = m_player->PositionL()) qint64 result = 0; if (KErrNone == err) { result = toMilliSeconds(us); } else { TRACE("PositionL error %d", err); // If we don't cast away constness here, we simply have to ignore // the error. const_cast<VideoPlayer*>(this)->setError(NormalError); } return result; } qint64 MMF::VideoPlayer::totalTime() const { return m_totalTime; } //----------------------------------------------------------------------------- // MVideoPlayerUtilityObserver callbacks //----------------------------------------------------------------------------- void MMF::VideoPlayer::MvpuoOpenComplete(TInt aError) { TRACE_CONTEXT(VideoPlayer::MvpuoOpenComplete, EVideoApi); TRACE_ENTRY("state %d error %d", state(), aError); __ASSERT_ALWAYS(LoadingState == state(), Utils::panic(InvalidStatePanic)); if (KErrNone == aError) { m_player->Prepare(); } else { // TODO: set different error states according to value of aError? setError(NormalError); } TRACE_EXIT_0(); } void MMF::VideoPlayer::MvpuoPrepareComplete(TInt aError) { TRACE_CONTEXT(VideoPlayer::MvpuoPrepareComplete, EVideoApi); TRACE_ENTRY("state %d error %d", state(), aError); __ASSERT_ALWAYS(LoadingState == state(), Utils::panic(InvalidStatePanic)); TRAPD(err, doPrepareCompleteL(aError)); if (KErrNone == err) { maxVolumeChanged(m_player->MaxVolume()); videoOutput().setFrameSize(m_frameSize); // See comment in updateMmfOutput if(m_mmfOutputChangePending) { TRACE_0("MMF output change pending - pushing now"); updateMmfOutput(); } emit totalTimeChanged(totalTime()); changeState(StoppedState); } else { // TODO: set different error states according to value of aError? setError(NormalError); } TRACE_EXIT_0(); } void MMF::VideoPlayer::doPrepareCompleteL(TInt aError) { User::LeaveIfError(aError); // Get frame size TSize size; m_player->VideoFrameSizeL(size); m_frameSize = QSize(size.iWidth, size.iHeight); // Get duration m_totalTime = toMilliSeconds(m_player->DurationL()); } void MMF::VideoPlayer::MvpuoFrameReady(CFbsBitmap &aFrame, TInt aError) { TRACE_CONTEXT(VideoPlayer::MvpuoFrameReady, EVideoApi); TRACE_ENTRY("state %d error %d", state(), aError); // TODO Q_UNUSED(aFrame); Q_UNUSED(aError); // suppress warnings in release builds TRACE_EXIT_0(); } void MMF::VideoPlayer::MvpuoPlayComplete(TInt aError) { TRACE_CONTEXT(VideoPlayer::MvpuoPlayComplete, EVideoApi) TRACE_ENTRY("state %d error %d", state(), aError); // TODO Q_UNUSED(aError); // suppress warnings in release builds TRACE_EXIT_0(); } void MMF::VideoPlayer::MvpuoEvent(const TMMFEvent &aEvent) { TRACE_CONTEXT(VideoPlayer::MvpuoEvent, EVideoApi); TRACE_ENTRY("state %d", state()); // TODO Q_UNUSED(aEvent); TRACE_EXIT_0(); } //----------------------------------------------------------------------------- // VideoOutputObserver //----------------------------------------------------------------------------- void MMF::VideoPlayer::videoOutputRegionChanged() { TRACE_CONTEXT(VideoPlayer::videoOutputRegionChanged, EVideoInternal); TRACE_ENTRY("state %d", state()); getNativeWindowSystemHandles(); // See comment in updateMmfOutput if(state() == LoadingState) m_mmfOutputChangePending = true; else updateMmfOutput(); TRACE_EXIT_0(); } void MMF::VideoPlayer::updateMmfOutput() { TRACE_CONTEXT(VideoPlayer::updateMmfOutput, EVideoInternal); TRACE_ENTRY_0(); // Calling SetDisplayWindowL is a no-op unless the MMF controller has // been loaded, so we shouldn't do it. Instead, the // m_mmfOutputChangePending flag is used to record the fact that we // need to call SetDisplayWindowL, and this is checked in // MvpuoPrepareComplete, at which point the MMF controller has been // loaded. // TODO: check whether videoOutput is visible? If not, then the // corresponding window will not be active, meaning that the // clipping region will be set to empty and the video will not be // visible. If this is the case, we should set m_mmfOutputChangePending // and respond to future showEvents from the videoOutput widget. getNativeWindowSystemHandles(); TRAPD(err, m_player->SetDisplayWindowL ( *m_wsSession, *m_screenDevice, *m_window, m_windowRect, m_clipRect ) ); if (KErrNone != err) { TRACE("SetDisplayWindowL error %d", err); setError(NormalError); } m_mmfOutputChangePending = false; TRACE_EXIT_0(); } //----------------------------------------------------------------------------- // Private functions //----------------------------------------------------------------------------- VideoOutput& MMF::VideoPlayer::videoOutput() { TRACE_CONTEXT(VideoPlayer::videoOutput, EVideoInternal); TRACE("videoOutput 0x%08x dummy 0x%08x", m_videoOutput, m_dummyVideoOutput.data()); return m_videoOutput ? *m_videoOutput : *m_dummyVideoOutput; } void MMF::VideoPlayer::videoOutputChanged() { TRACE_CONTEXT(VideoPlayer::videoOutputChanged, EVideoInternal); TRACE_ENTRY_0(); // Lazily construct a dummy output if needed here if (!m_videoOutput and m_dummyVideoOutput.isNull()) { m_dummyVideoOutput.reset(new VideoOutput(NULL)); } videoOutput().setObserver(this); videoOutput().setFrameSize(m_frameSize); videoOutputRegionChanged(); TRACE_EXIT_0(); } void MMF::VideoPlayer::getNativeWindowSystemHandles() { TRACE_CONTEXT(VideoPlayer::getNativeWindowSystemHandles, EVideoInternal); TRACE_ENTRY_0(); VideoOutput& output = videoOutput(); CCoeControl* const control = output.winId(); CCoeEnv* const coeEnv = control->ControlEnv(); m_wsSession = &(coeEnv->WsSession()); m_screenDevice = coeEnv->ScreenDevice(); m_window = control->DrawableWindow(); #ifdef _DEBUG QScopedPointer<ObjectDump::QDumper> dumper(new ObjectDump::QDumper); dumper->setPrefix("Phonon::MMF"); // to aid searchability of logs ObjectDump::addDefaultAnnotators(*dumper); TRACE_0("Dumping VideoOutput:"); dumper->dumpObject(output); #endif #ifdef PHONON_MMF_HARD_CODE_VIDEO_RECT // HACK: why isn't control->Rect updated following a call to // updateGeometry on the parent widget? m_windowRect = TRect(0, 100, 320, 250); m_clipRect = m_windowRect; #else m_windowRect = TRect( control->DrawableWindow()->AbsPosition(), control->DrawableWindow()->Size()); m_clipRect = m_windowRect; #endif #ifdef PHONON_MMF_HARD_CODE_VIDEO_RECT_TO_EMPTY m_windowRect = TRect(0, 0, 0, 0); m_clipRect = m_windowRect; #endif TRACE("windowRect %d %d - %d %d", m_windowRect.iTl.iX, m_windowRect.iTl.iY, m_windowRect.iBr.iX, m_windowRect.iBr.iY); TRACE("clipRect %d %d - %d %d", m_clipRect.iTl.iX, m_clipRect.iTl.iY, m_clipRect.iBr.iX, m_clipRect.iBr.iY); TRACE_EXIT_0(); } QT_END_NAMESPACE
/* This file is part of the KDE project. Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). 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 or 3 of the License. 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, see <http://www.gnu.org/licenses/>. */ #include <QUrl> #include <QTimer> #include <QWidget> #include <coemain.h> // For CCoeEnv #include <coecntrl.h> #include "videoplayer.h" #include "utils.h" #ifdef _DEBUG #include "objectdump/objectdump.h" #endif QT_BEGIN_NAMESPACE using namespace Phonon; using namespace Phonon::MMF; //----------------------------------------------------------------------------- // Constructor / destructor //----------------------------------------------------------------------------- MMF::VideoPlayer::VideoPlayer() : m_wsSession(NULL) , m_screenDevice(NULL) , m_window(NULL) , m_totalTime(0) , m_mmfOutputChangePending(false) { construct(); } MMF::VideoPlayer::VideoPlayer(const AbstractPlayer& player) : AbstractMediaPlayer(player) , m_wsSession(NULL) , m_screenDevice(NULL) , m_window(NULL) , m_totalTime(0) , m_mmfOutputChangePending(false) { construct(); } void MMF::VideoPlayer::construct() { TRACE_CONTEXT(VideoPlayer::VideoPlayer, EVideoApi); TRACE_ENTRY_0(); if (!m_videoOutput) { m_dummyVideoOutput.reset(new VideoOutput(NULL)); } videoOutput().setObserver(this); const TInt priority = 0; const TMdaPriorityPreference preference = EMdaPriorityPreferenceNone; getNativeWindowSystemHandles(); // TODO: is this the correct way to handle errors which occur when // creating a Symbian object in the constructor of a Qt object? // TODO: check whether videoOutput is visible? If not, then the // corresponding window will not be active, meaning that the // clipping region will be set to empty and the video will not be // visible. If this is the case, we should set m_mmfOutputChangePending // and respond to future showEvents from the videoOutput widget. TRAPD(err, m_player.reset(CVideoPlayerUtility::NewL ( *this, priority, preference, *m_wsSession, *m_screenDevice, *m_window, m_windowRect, m_clipRect )) ); if (KErrNone != err) { changeState(ErrorState); } TRACE_EXIT_0(); } MMF::VideoPlayer::~VideoPlayer() { TRACE_CONTEXT(VideoPlayer::~VideoPlayer, EVideoApi); TRACE_ENTRY_0(); TRACE_EXIT_0(); } //----------------------------------------------------------------------------- // Public API //----------------------------------------------------------------------------- void MMF::VideoPlayer::doPlay() { TRACE_CONTEXT(VideoPlayer::doPlay, EVideoApi); // See comment in updateMmfOutput if(m_mmfOutputChangePending) { TRACE_0("MMF output change pending - pushing now"); updateMmfOutput(); } m_player->Play(); } void MMF::VideoPlayer::doPause() { TRACE_CONTEXT(VideoPlayer::doPause, EVideoApi); TRAPD(err, m_player->PauseL()); if (KErrNone != err) { TRACE("PauseL error %d", err); setError(NormalError); } } void MMF::VideoPlayer::doStop() { m_player->Stop(); } void MMF::VideoPlayer::doSeek(qint64 ms) { TRACE_CONTEXT(VideoPlayer::doSeek, EVideoApi); TRAPD(err, m_player->SetPositionL(TTimeIntervalMicroSeconds(ms * 1000))); if (KErrNone != err) { TRACE("SetPositionL error %d", err); setError(NormalError); } } int MMF::VideoPlayer::setDeviceVolume(int mmfVolume) { TRAPD(err, m_player->SetVolumeL(mmfVolume)); return err; } int MMF::VideoPlayer::openFile(RFile& file) { TRAPD(err, m_player->OpenFileL(file)); return err; } void MMF::VideoPlayer::close() { m_player->Close(); } bool MMF::VideoPlayer::hasVideo() const { return true; } qint64 MMF::VideoPlayer::currentTime() const { TRACE_CONTEXT(VideoPlayer::currentTime, EVideoApi); TTimeIntervalMicroSeconds us; TRAPD(err, us = m_player->PositionL()) qint64 result = 0; if (KErrNone == err) { result = toMilliSeconds(us); } else { TRACE("PositionL error %d", err); // If we don't cast away constness here, we simply have to ignore // the error. const_cast<VideoPlayer*>(this)->setError(NormalError); } return result; } qint64 MMF::VideoPlayer::totalTime() const { return m_totalTime; } //----------------------------------------------------------------------------- // MVideoPlayerUtilityObserver callbacks //----------------------------------------------------------------------------- void MMF::VideoPlayer::MvpuoOpenComplete(TInt aError) { TRACE_CONTEXT(VideoPlayer::MvpuoOpenComplete, EVideoApi); TRACE_ENTRY("state %d error %d", state(), aError); __ASSERT_ALWAYS(LoadingState == state(), Utils::panic(InvalidStatePanic)); if (KErrNone == aError) m_player->Prepare(); else setError(NormalError); TRACE_EXIT_0(); } void MMF::VideoPlayer::MvpuoPrepareComplete(TInt aError) { TRACE_CONTEXT(VideoPlayer::MvpuoPrepareComplete, EVideoApi); TRACE_ENTRY("state %d error %d", state(), aError); __ASSERT_ALWAYS(LoadingState == state(), Utils::panic(InvalidStatePanic)); TRAPD(err, doPrepareCompleteL(aError)); if (KErrNone == err) { maxVolumeChanged(m_player->MaxVolume()); videoOutput().setFrameSize(m_frameSize); // See comment in updateMmfOutput if(m_mmfOutputChangePending) { TRACE_0("MMF output change pending - pushing now"); updateMmfOutput(); } emit totalTimeChanged(totalTime()); changeState(StoppedState); } else { // TODO: set different error states according to value of aError? setError(NormalError); } TRACE_EXIT_0(); } void MMF::VideoPlayer::doPrepareCompleteL(TInt aError) { User::LeaveIfError(aError); // Get frame size TSize size; m_player->VideoFrameSizeL(size); m_frameSize = QSize(size.iWidth, size.iHeight); // Get duration m_totalTime = toMilliSeconds(m_player->DurationL()); } void MMF::VideoPlayer::MvpuoFrameReady(CFbsBitmap &aFrame, TInt aError) { TRACE_CONTEXT(VideoPlayer::MvpuoFrameReady, EVideoApi); TRACE_ENTRY("state %d error %d", state(), aError); // TODO Q_UNUSED(aFrame); Q_UNUSED(aError); // suppress warnings in release builds TRACE_EXIT_0(); } void MMF::VideoPlayer::MvpuoPlayComplete(TInt aError) { TRACE_CONTEXT(VideoPlayer::MvpuoPlayComplete, EVideoApi) TRACE_ENTRY("state %d error %d", state(), aError); // TODO Q_UNUSED(aError); // suppress warnings in release builds TRACE_EXIT_0(); } void MMF::VideoPlayer::MvpuoEvent(const TMMFEvent &aEvent) { TRACE_CONTEXT(VideoPlayer::MvpuoEvent, EVideoApi); TRACE_ENTRY("state %d", state()); // TODO Q_UNUSED(aEvent); TRACE_EXIT_0(); } //----------------------------------------------------------------------------- // VideoOutputObserver //----------------------------------------------------------------------------- void MMF::VideoPlayer::videoOutputRegionChanged() { TRACE_CONTEXT(VideoPlayer::videoOutputRegionChanged, EVideoInternal); TRACE_ENTRY("state %d", state()); getNativeWindowSystemHandles(); // See comment in updateMmfOutput if(state() == LoadingState) m_mmfOutputChangePending = true; else updateMmfOutput(); TRACE_EXIT_0(); } void MMF::VideoPlayer::updateMmfOutput() { TRACE_CONTEXT(VideoPlayer::updateMmfOutput, EVideoInternal); TRACE_ENTRY_0(); // Calling SetDisplayWindowL is a no-op unless the MMF controller has // been loaded, so we shouldn't do it. Instead, the // m_mmfOutputChangePending flag is used to record the fact that we // need to call SetDisplayWindowL, and this is checked in // MvpuoPrepareComplete, at which point the MMF controller has been // loaded. // TODO: check whether videoOutput is visible? If not, then the // corresponding window will not be active, meaning that the // clipping region will be set to empty and the video will not be // visible. If this is the case, we should set m_mmfOutputChangePending // and respond to future showEvents from the videoOutput widget. getNativeWindowSystemHandles(); TRAPD(err, m_player->SetDisplayWindowL ( *m_wsSession, *m_screenDevice, *m_window, m_windowRect, m_clipRect ) ); if (KErrNone != err) { TRACE("SetDisplayWindowL error %d", err); setError(NormalError); } m_mmfOutputChangePending = false; TRACE_EXIT_0(); } //----------------------------------------------------------------------------- // Private functions //----------------------------------------------------------------------------- VideoOutput& MMF::VideoPlayer::videoOutput() { TRACE_CONTEXT(VideoPlayer::videoOutput, EVideoInternal); TRACE("videoOutput 0x%08x dummy 0x%08x", m_videoOutput, m_dummyVideoOutput.data()); return m_videoOutput ? *m_videoOutput : *m_dummyVideoOutput; } void MMF::VideoPlayer::videoOutputChanged() { TRACE_CONTEXT(VideoPlayer::videoOutputChanged, EVideoInternal); TRACE_ENTRY_0(); // Lazily construct a dummy output if needed here if (!m_videoOutput and m_dummyVideoOutput.isNull()) { m_dummyVideoOutput.reset(new VideoOutput(NULL)); } videoOutput().setObserver(this); videoOutput().setFrameSize(m_frameSize); videoOutputRegionChanged(); TRACE_EXIT_0(); } void MMF::VideoPlayer::getNativeWindowSystemHandles() { TRACE_CONTEXT(VideoPlayer::getNativeWindowSystemHandles, EVideoInternal); TRACE_ENTRY_0(); VideoOutput& output = videoOutput(); CCoeControl* const control = output.winId(); CCoeEnv* const coeEnv = control->ControlEnv(); m_wsSession = &(coeEnv->WsSession()); m_screenDevice = coeEnv->ScreenDevice(); m_window = control->DrawableWindow(); #ifdef _DEBUG QScopedPointer<ObjectDump::QDumper> dumper(new ObjectDump::QDumper); dumper->setPrefix("Phonon::MMF"); // to aid searchability of logs ObjectDump::addDefaultAnnotators(*dumper); TRACE_0("Dumping VideoOutput:"); dumper->dumpObject(output); #endif #ifdef PHONON_MMF_HARD_CODE_VIDEO_RECT // HACK: why isn't control->Rect updated following a call to // updateGeometry on the parent widget? m_windowRect = TRect(0, 100, 320, 250); m_clipRect = m_windowRect; #else m_windowRect = TRect( control->DrawableWindow()->AbsPosition(), control->DrawableWindow()->Size()); m_clipRect = m_windowRect; #endif #ifdef PHONON_MMF_HARD_CODE_VIDEO_RECT_TO_EMPTY m_windowRect = TRect(0, 0, 0, 0); m_clipRect = m_windowRect; #endif TRACE("windowRect %d %d - %d %d", m_windowRect.iTl.iX, m_windowRect.iTl.iY, m_windowRect.iBr.iX, m_windowRect.iBr.iY); TRACE("clipRect %d %d - %d %d", m_clipRect.iTl.iX, m_clipRect.iTl.iY, m_clipRect.iBr.iX, m_clipRect.iBr.iY); TRACE_EXIT_0(); } QT_END_NAMESPACE
Remove an unimplementable TODO.
Remove an unimplementable TODO. MvpuoOpenComplete's TInt aError doesn't map to Phonon::ErrorType.
C++
lgpl-2.1
igor-sfdc/qt-wk,radekp/qt,igor-sfdc/qt-wk,igor-sfdc/qt-wk,radekp/qt,igor-sfdc/qt-wk,radekp/qt,igor-sfdc/qt-wk,pruiz/wkhtmltopdf-qt,pruiz/wkhtmltopdf-qt,radekp/qt,radekp/qt,igor-sfdc/qt-wk,pruiz/wkhtmltopdf-qt,radekp/qt,igor-sfdc/qt-wk,pruiz/wkhtmltopdf-qt,radekp/qt,pruiz/wkhtmltopdf-qt,pruiz/wkhtmltopdf-qt,radekp/qt,pruiz/wkhtmltopdf-qt,radekp/qt,pruiz/wkhtmltopdf-qt,pruiz/wkhtmltopdf-qt,igor-sfdc/qt-wk,igor-sfdc/qt-wk,igor-sfdc/qt-wk,pruiz/wkhtmltopdf-qt,pruiz/wkhtmltopdf-qt,radekp/qt,igor-sfdc/qt-wk
9325a42e23fb7decca2c70276b870f45a1ec76e8
elang/lir/transforms/register_allocation_pass.cc
elang/lir/transforms/register_allocation_pass.cc
// Copyright 2015 Project Vogue. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "elang/lir/transforms/register_allocation_pass.h" #include "elang/lir/editor.h" #include "elang/lir/instructions.h" #include "elang/lir/literals.h" #include "elang/lir/transforms/register_allocator.h" #include "elang/lir/transforms/register_assignments.h" #include "elang/lir/transforms/stack_allocator.h" #include "elang/lir/transforms/stack_assigner.h" #include "elang/lir/transforms/stack_assignments.h" #include "elang/lir/target.h" namespace elang { namespace lir { namespace { bool IsUselessInstruction(const Instruction* instr) { if (instr->is<CopyInstruction>()) return instr->output(0) == instr->input(0); return false; } } // namespace ////////////////////////////////////////////////////////////////////// // // RegisterAssignmentsPass // RegisterAssignmentsPass::RegisterAssignmentsPass(Editor* editor) : FunctionPass(editor), register_assignments_(new RegisterAssignments()), stack_assignments_(new StackAssignments()) { } RegisterAssignmentsPass::~RegisterAssignmentsPass() { } base::StringPiece RegisterAssignmentsPass::name() const { return "register_allocation"; } Value RegisterAssignmentsPass::AssignmentOf(Instruction* instr, Value operand) const { if (!operand.is_virtual()) return operand; auto const assignment = register_assignments_->AllocationOf(instr, operand); if (assignment.is_physical()) return assignment; if (assignment.is_spill_slot()) return stack_assignments_->StackSlotOf(operand); NOTREACHED() << "unexpected assignment for " << operand << " " << assignment; return Value(); } void RegisterAssignmentsPass::RunOnFunction() { { RegisterAllocator allocator(editor(), register_assignments_.get(), stack_assignments_.get()); allocator.Run(); } { StackAssigner stack_assigner(factory(), register_assignments_.get(), stack_assignments_.get()); stack_assigner.Run(); } // Insert prologue { auto const entry_block = editor()->entry_block(); auto const entry_instr = entry_block->first_instruction(); auto const ref_instr = entry_instr->next(); editor()->Edit(entry_block); for (auto const instr : stack_assignments_->prologue()) editor()->InsertBefore(instr, ref_instr); editor()->Commit(); } for (auto const block : function()->basic_blocks()) { Editor::ScopedEdit scope(editor()); editor()->Edit(block); WorkList<Instruction> action_owners; for (auto const instr : block->instructions()) { if (!register_assignments_->BeforeActionOf(instr).empty()) action_owners.Push(instr); ProcessInstruction(instr); } while (!action_owners.empty()) { auto const instr = action_owners.Pop(); for (auto const action : register_assignments_->BeforeActionOf(instr)) { editor()->InsertBefore(action, instr); ProcessInstruction(action); } if (!instr->is<PCopyInstruction>()) continue; editor()->Remove(instr); } auto const ret_instr = block->last_instruction()->as<RetInstruction>(); if (!ret_instr) continue; // Insert epilogue before 'ret' instruction. for (auto const instr : stack_assignments_->epilogue()) editor()->InsertBefore(instr, ret_instr); } editor()->BulkRemoveInstructions(&useless_instructions_); } void RegisterAssignmentsPass::ProcessInstruction(Instruction* instr) { auto output_position = 0; for (auto const output : instr->outputs()) { auto const assignment = AssignmentOf(instr, output); editor()->SetOutput(instr, output_position, assignment); ++output_position; } auto input_position = 0; for (auto const input : instr->inputs()) { auto const assignment = AssignmentOf(instr, input); editor()->SetInput(instr, input_position, assignment); ++input_position; } if (!IsUselessInstruction(instr)) return; useless_instructions_.Push(instr); } } // namespace lir } // namespace elang
// Copyright 2015 Project Vogue. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "elang/lir/transforms/register_allocation_pass.h" #include "elang/lir/editor.h" #include "elang/lir/instructions.h" #include "elang/lir/literals.h" #include "elang/lir/transforms/register_allocator.h" #include "elang/lir/transforms/register_assignments.h" #include "elang/lir/transforms/stack_allocator.h" #include "elang/lir/transforms/stack_assigner.h" #include "elang/lir/transforms/stack_assignments.h" #include "elang/lir/target.h" namespace elang { namespace lir { namespace { bool IsUselessInstruction(const Instruction* instr) { if (instr->is<CopyInstruction>()) return instr->output(0) == instr->input(0); return false; } } // namespace ////////////////////////////////////////////////////////////////////// // // RegisterAssignmentsPass // RegisterAssignmentsPass::RegisterAssignmentsPass(Editor* editor) : FunctionPass(editor), register_assignments_(new RegisterAssignments()), stack_assignments_(new StackAssignments()) { } RegisterAssignmentsPass::~RegisterAssignmentsPass() { } base::StringPiece RegisterAssignmentsPass::name() const { return "register_allocation"; } Value RegisterAssignmentsPass::AssignmentOf(Instruction* instr, Value operand) const { if (!operand.is_virtual()) return operand; auto const assignment = register_assignments_->AllocationOf(instr, operand); if (assignment.is_physical()) return assignment; if (assignment.is_spill_slot()) return stack_assignments_->StackSlotOf(operand); NOTREACHED() << "unexpected assignment for " << operand << " " << assignment; return Value(); } void RegisterAssignmentsPass::RunOnFunction() { { RegisterAllocator allocator(editor(), register_assignments_.get(), stack_assignments_.get()); allocator.Run(); } { StackAssigner stack_assigner(factory(), register_assignments_.get(), stack_assignments_.get()); stack_assigner.Run(); } // Insert prologue { auto const entry_block = editor()->entry_block(); auto const entry_instr = entry_block->first_instruction(); auto const ref_instr = entry_instr->next(); editor()->Edit(entry_block); for (auto const instr : stack_assignments_->prologue()) editor()->InsertBefore(instr, ref_instr); editor()->Commit(); } for (auto const block : function()->basic_blocks()) { Editor::ScopedEdit scope(editor()); editor()->Edit(block); editor()->DiscardPhiInstructions(); WorkList<Instruction> action_owners; for (auto const instr : block->instructions()) { if (!register_assignments_->BeforeActionOf(instr).empty()) action_owners.Push(instr); ProcessInstruction(instr); } while (!action_owners.empty()) { auto const instr = action_owners.Pop(); for (auto const action : register_assignments_->BeforeActionOf(instr)) { editor()->InsertBefore(action, instr); ProcessInstruction(action); } if (!instr->is<PCopyInstruction>()) continue; editor()->Remove(instr); } auto const ret_instr = block->last_instruction()->as<RetInstruction>(); if (!ret_instr) continue; // Insert epilogue before 'ret' instruction. for (auto const instr : stack_assignments_->epilogue()) editor()->InsertBefore(instr, ret_instr); } editor()->BulkRemoveInstructions(&useless_instructions_); } void RegisterAssignmentsPass::ProcessInstruction(Instruction* instr) { auto output_position = 0; for (auto const output : instr->outputs()) { auto const assignment = AssignmentOf(instr, output); editor()->SetOutput(instr, output_position, assignment); ++output_position; } auto input_position = 0; for (auto const input : instr->inputs()) { auto const assignment = AssignmentOf(instr, input); editor()->SetInput(instr, input_position, assignment); ++input_position; } if (!IsUselessInstruction(instr)) return; useless_instructions_.Push(instr); } } // namespace lir } // namespace elang
Make |RegisterAssignmentsPass| to discard phi-instructions after converting SSA form to normal form.
elang/lir/transforms: Make |RegisterAssignmentsPass| to discard phi-instructions after converting SSA form to normal form.
C++
apache-2.0
eval1749/elang,eval1749/elang,eval1749/elang,eval1749/elang,eval1749/elang
0ef1cc556ad75a0952ebf838fed629238715e6bf
src/Editor/GUI/VerticalScrollLayout.cpp
src/Editor/GUI/VerticalScrollLayout.cpp
#include "VerticalScrollLayout.hpp" #include <Engine/Geometry/Rectangle.hpp> #include <Engine/Manager/Managers.hpp> #include <Engine/Manager/ResourceManager.hpp> #include <Engine/Util/Input.hpp> using namespace GUI; VerticalScrollLayout::VerticalScrollLayout(Widget* parent) : Container(parent) { rectangle = Managers().resourceManager->CreateRectangle(); } VerticalScrollLayout::~VerticalScrollLayout() { Managers().resourceManager->FreeRectangle(); } void VerticalScrollLayout::Update() { Container::Update(); if (Input()->ScrollUp() && scrollPosition > 0U) { --scrollPosition; UpdatePositions(); } else if (Input()->ScrollDown() && scrollPosition < GetWidgets().size()) { ++scrollPosition; UpdatePositions(); } } void VerticalScrollLayout::Render() { // Set color. glm::vec3 color(0.06666666666f, 0.06274509803f, 0.08235294117f); rectangle->Render(GetPosition(), size, color); // Draw scrollbar. if (!GetWidgets().empty()) { color = glm::vec3(0.16078431372f, 0.15686274509f, 0.17647058823f); float yScrolled = 0.f; float yCovered = 0.f; float yTotal = 0.f; for (std::size_t i=0U; i < GetWidgets().size(); ++i) { yTotal += GetWidgets()[i]->GetSize().y; if (i < scrollPosition) { yScrolled += GetWidgets()[i]->GetSize().y; } else if (yTotal - yScrolled < size.y) { yCovered += GetWidgets()[i]->GetSize().y; } } rectangle->Render(GetPosition() + glm::vec2(size.x - 20.f, size.y * yScrolled / yTotal), glm::vec2(20.f, size.y * yCovered / yTotal), color); } for (Widget* widget : GetWidgets()) { if (widget->IsVisible() && widget->GetPosition().y - GetPosition().y + widget->GetSize().y <= size.y) widget->Render(); } } void VerticalScrollLayout::AddWidget(Widget* widget) { Container::AddWidget(widget); widget->SetPosition(GetPosition() + nextPosition); nextPosition.y += widget->GetSize().y; } void VerticalScrollLayout::ClearWidgets() { Container::ClearWidgets(); nextPosition = glm::vec2(0.f, 0.f); scrollPosition = 0U; } glm::vec2 VerticalScrollLayout::GetSize() const { return this->size; } void VerticalScrollLayout::SetSize(const glm::vec2& size) { this->size = size; } void VerticalScrollLayout::UpdatePositions() { glm::vec2 nextPosition(0.f, 0.f); for (std::size_t i=0U; i < GetWidgets().size(); ++i) { if (i >= scrollPosition) { GetWidgets()[i]->SetPosition(GetPosition() + nextPosition); nextPosition.y += GetWidgets()[i]->GetSize().y; } } }
#include "VerticalScrollLayout.hpp" #include <Engine/Geometry/Rectangle.hpp> #include <Engine/Manager/Managers.hpp> #include <Engine/Manager/ResourceManager.hpp> #include <Engine/Util/Input.hpp> using namespace GUI; VerticalScrollLayout::VerticalScrollLayout(Widget* parent) : Container(parent) { rectangle = Managers().resourceManager->CreateRectangle(); } VerticalScrollLayout::~VerticalScrollLayout() { Managers().resourceManager->FreeRectangle(); } void VerticalScrollLayout::Update() { if (Input()->ScrollUp() && scrollPosition > 0U) { --scrollPosition; UpdatePositions(); } else if (Input()->ScrollDown() && scrollPosition < GetWidgets().size() - 1) { ++scrollPosition; UpdatePositions(); } std::size_t i = 0U; for (Widget* widget : GetWidgets()) { if (widget->IsVisible() && i++ >= scrollPosition) { widget->Update(); } } } void VerticalScrollLayout::Render() { // Set color. glm::vec3 color(0.06666666666f, 0.06274509803f, 0.08235294117f); rectangle->Render(GetPosition(), size, color); // Draw scrollbar. if (!GetWidgets().empty()) { color = glm::vec3(0.16078431372f, 0.15686274509f, 0.17647058823f); float yScrolled = 0.f; float yCovered = 0.f; float yTotal = 0.f; for (std::size_t i=0U; i < GetWidgets().size(); ++i) { yTotal += GetWidgets()[i]->GetSize().y; if (i < scrollPosition) { yScrolled += GetWidgets()[i]->GetSize().y; } else if (yTotal - yScrolled < size.y) { yCovered += GetWidgets()[i]->GetSize().y; } } rectangle->Render(GetPosition() + glm::vec2(size.x - 20.f, size.y * yScrolled / yTotal), glm::vec2(20.f, size.y * yCovered / yTotal), color); } std::size_t i = 0U; for (Widget* widget : GetWidgets()) { if (widget->IsVisible() && i++ >= scrollPosition && widget->GetPosition().y - GetPosition().y + widget->GetSize().y <= size.y) widget->Render(); } } void VerticalScrollLayout::AddWidget(Widget* widget) { Container::AddWidget(widget); widget->SetPosition(GetPosition() + nextPosition); nextPosition.y += widget->GetSize().y; } void VerticalScrollLayout::ClearWidgets() { Container::ClearWidgets(); nextPosition = glm::vec2(0.f, 0.f); scrollPosition = 0U; } glm::vec2 VerticalScrollLayout::GetSize() const { return this->size; } void VerticalScrollLayout::SetSize(const glm::vec2& size) { this->size = size; } void VerticalScrollLayout::UpdatePositions() { glm::vec2 nextPosition(0.f, 0.f); std::size_t i = 0U; for (Widget* widget : GetWidgets()) { if (widget->IsVisible() && i++ >= scrollPosition) { nextPosition.y += widget->GetSize().y + 10.f; } } }
Fix vertical scroll layout
Fix vertical scroll layout
C++
mit
Chainsawkitten/LargeGameProjectEngine,Chainsawkitten/LargeGameProjectEngine,Chainsawkitten/HymnToBeauty,Chainsawkitten/HymnToBeauty
8d578e9f5a91aafcabebb2c5515012d62dfa1f7e
src/file.cpp
src/file.cpp
/* Copyright (c) 2003, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "libtorrent/pch.hpp" #include <boost/scoped_ptr.hpp> #ifdef _WIN32 // windows part #include "libtorrent/utf8.hpp" #include <io.h> #include <fcntl.h> #include <sys/stat.h> #include <sys/types.h> #ifndef _MODE_T_ typedef int mode_t; #endif #ifdef UNICODE #include "libtorrent/storage.hpp" #endif #else // unix part #define _FILE_OFFSET_BITS 64 #include <unistd.h> #include <fcntl.h> #include <sys/stat.h> #include <sys/types.h> #include <errno.h> #include <boost/static_assert.hpp> // make sure the _FILE_OFFSET_BITS define worked // on this platform BOOST_STATIC_ASSERT(sizeof(lseek(0, 0, 0)) >= 8); #endif #include <boost/filesystem/operations.hpp> #include "libtorrent/file.hpp" #include <sstream> #include <cstring> #include <vector> #ifndef O_BINARY #define O_BINARY 0 #endif #ifndef O_RANDOM #define O_RANDOM 0 #endif #ifdef UNICODE #include "libtorrent/storage.hpp" #endif #include "libtorrent/assert.hpp" namespace { enum { mode_in = 1, mode_out = 2 }; mode_t map_open_mode(int m) { if (m == (mode_in | mode_out)) return O_RDWR | O_CREAT | O_BINARY | O_RANDOM; if (m == mode_out) return O_WRONLY | O_CREAT | O_BINARY | O_RANDOM; if (m == mode_in) return O_RDONLY | O_BINARY | O_RANDOM; TORRENT_ASSERT(false); return 0; } #ifdef WIN32 std::string utf8_native(std::string const& s) { try { std::wstring ws; libtorrent::utf8_wchar(s, ws); std::size_t size = wcstombs(0, ws.c_str(), 0); if (size == std::size_t(-1)) return s; std::string ret; ret.resize(size); size = wcstombs(&ret[0], ws.c_str(), size + 1); if (size == wchar_t(-1)) return s; ret.resize(size); return ret; } catch(std::exception) { return s; } } #else std::string const& utf8_native(std::string const& s) { return s; } #endif } namespace libtorrent { namespace fs = boost::filesystem; const file::open_mode file::in(mode_in); const file::open_mode file::out(mode_out); const file::seek_mode file::begin(1); const file::seek_mode file::end(2); struct file::impl { impl() : m_fd(-1) , m_open_mode(0) {} impl(fs::path const& path, int mode, error_code& ec) : m_fd(-1) , m_open_mode(0) { open(path, mode, ec); } ~impl() { close(); } bool open(fs::path const& path, int mode, error_code& ec) { close(); #ifdef TORRENT_WINDOWS const int permissions = _S_IREAD | _S_IWRITE; #ifdef defined UNICODE #define open _wopen std::wstring file_path(safe_convert(path.native_file_string())); #else #define open _open std::string const& file_path = path.native_file_string(); #endif #else // if not windows const mode_t permissions = S_IRWXU | S_IRGRP | S_IROTH; std::string const& file_path = path.native_file_string(); #endif m_fd = ::open(file_path.c_str(), map_open_mode(mode), permissions); #ifdef TORRENT_WINDOWS #undef open #endif if (m_fd == -1) { ec = error_code(errno, get_posix_category()); return false; } m_open_mode = mode; return true; } void close() { if (m_fd == -1) return; #ifdef _WIN32 ::_close(m_fd); #else ::close(m_fd); #endif m_fd = -1; m_open_mode = 0; } size_type read(char* buf, size_type num_bytes, error_code& ec) { TORRENT_ASSERT(m_open_mode & mode_in); TORRENT_ASSERT(m_fd != -1); #ifdef _WIN32 size_type ret = ::_read(m_fd, buf, num_bytes); #else size_type ret = ::read(m_fd, buf, num_bytes); #endif if (ret == -1) ec = error_code(errno, get_posix_category()); return ret; } size_type write(const char* buf, size_type num_bytes, error_code& ec) { TORRENT_ASSERT(m_open_mode & mode_out); TORRENT_ASSERT(m_fd != -1); // TODO: Test this a bit more, what happens with random failures in // the files? // if ((rand() % 100) > 80) // throw file_error("debug"); #ifdef _WIN32 size_type ret = ::_write(m_fd, buf, num_bytes); #else size_type ret = ::write(m_fd, buf, num_bytes); #endif if (ret == -1) ec = error_code(errno, get_posix_category()); return ret; } bool set_size(size_type s, error_code& ec) { #ifdef _WIN32 #error file.cpp is for posix systems only. use file_win.cpp on windows #else if (ftruncate(m_fd, s) < 0) { ec = error_code(errno, get_posix_category()); return false; } return true; #endif } size_type seek(size_type offset, int m, error_code& ec) { TORRENT_ASSERT(m_open_mode); TORRENT_ASSERT(m_fd != -1); int seekdir = (m == 1)?SEEK_SET:SEEK_END; #ifdef _WIN32 size_type ret = _lseeki64(m_fd, offset, seekdir); #else size_type ret = lseek(m_fd, offset, seekdir); #endif // For some strange reason this fails // on win32. Use windows specific file // wrapper instead. if (ret < 0) ec = error_code(errno, get_posix_category()); return ret; } size_type tell(error_code& ec) { TORRENT_ASSERT(m_open_mode); TORRENT_ASSERT(m_fd != -1); size_type ret; #ifdef _WIN32 ret = _telli64(m_fd); #else ret = lseek(m_fd, 0, SEEK_CUR); #endif if (ret < 0) ec = error_code(errno, get_posix_category()); return ret; } int m_fd; int m_open_mode; }; // pimpl forwardings file::file() : m_impl(new impl()) {} file::file(fs::path const& p, file::open_mode m, error_code& ec) : m_impl(new impl(p, m.m_mask, ec)) {} file::~file() {} bool file::open(fs::path const& p, file::open_mode m, error_code& ec) { return m_impl->open(p, m.m_mask, ec); } void file::close() { m_impl->close(); } size_type file::write(const char* buf, size_type num_bytes, error_code& ec) { return m_impl->write(buf, num_bytes, ec); } size_type file::read(char* buf, size_type num_bytes, error_code& ec) { return m_impl->read(buf, num_bytes, ec); } bool file::set_size(size_type s, error_code& ec) { return m_impl->set_size(s, ec); } size_type file::seek(size_type pos, file::seek_mode m, error_code& ec) { return m_impl->seek(pos, m.m_val, ec); } size_type file::tell(error_code& ec) { return m_impl->tell(ec); } }
/* Copyright (c) 2003, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "libtorrent/pch.hpp" #include <boost/scoped_ptr.hpp> #ifdef _WIN32 // windows part #include "libtorrent/utf8.hpp" #include <io.h> #include <fcntl.h> #include <sys/stat.h> #include <sys/types.h> #ifndef _MODE_T_ typedef int mode_t; #endif #ifdef UNICODE #include "libtorrent/storage.hpp" #endif #else // unix part #define _FILE_OFFSET_BITS 64 #include <unistd.h> #include <fcntl.h> #include <sys/stat.h> #include <sys/types.h> #include <errno.h> #include <boost/static_assert.hpp> // make sure the _FILE_OFFSET_BITS define worked // on this platform BOOST_STATIC_ASSERT(sizeof(lseek(0, 0, 0)) >= 8); #endif #include <boost/filesystem/operations.hpp> #include "libtorrent/file.hpp" #include <sstream> #include <cstring> #include <vector> #ifndef O_BINARY #define O_BINARY 0 #endif #ifndef O_RANDOM #define O_RANDOM 0 #endif #ifdef UNICODE #include "libtorrent/storage.hpp" #endif #include "libtorrent/assert.hpp" namespace { enum { mode_in = 1, mode_out = 2 }; mode_t map_open_mode(int m) { if (m == (mode_in | mode_out)) return O_RDWR | O_CREAT | O_BINARY | O_RANDOM; if (m == mode_out) return O_WRONLY | O_CREAT | O_BINARY | O_RANDOM; if (m == mode_in) return O_RDONLY | O_BINARY | O_RANDOM; TORRENT_ASSERT(false); return 0; } #ifdef WIN32 std::string utf8_native(std::string const& s) { try { std::wstring ws; libtorrent::utf8_wchar(s, ws); std::size_t size = wcstombs(0, ws.c_str(), 0); if (size == std::size_t(-1)) return s; std::string ret; ret.resize(size); size = wcstombs(&ret[0], ws.c_str(), size + 1); if (size == wchar_t(-1)) return s; ret.resize(size); return ret; } catch(std::exception) { return s; } } #else std::string const& utf8_native(std::string const& s) { return s; } #endif } namespace libtorrent { namespace fs = boost::filesystem; const file::open_mode file::in(mode_in); const file::open_mode file::out(mode_out); const file::seek_mode file::begin(1); const file::seek_mode file::end(2); struct file::impl { impl() : m_fd(-1) , m_open_mode(0) {} impl(fs::path const& path, int mode, error_code& ec) : m_fd(-1) , m_open_mode(0) { open(path, mode, ec); } ~impl() { close(); } bool open(fs::path const& path, int mode, error_code& ec) { close(); #ifdef TORRENT_WINDOWS const int permissions = _S_IREAD | _S_IWRITE; #ifdef defined UNICODE #define open _wopen std::wstring file_path(safe_convert(path.native_file_string())); #else #define open _open std::string const& file_path = path.native_file_string(); #endif #else // if not windows // rely on default umask to filter x and w permissions // for group and others const mode_t permissions = S_IRWXU | S_IRWXG | S_IRWXO; std::string const& file_path = path.native_file_string(); #endif m_fd = ::open(file_path.c_str(), map_open_mode(mode), permissions); #ifdef TORRENT_WINDOWS #undef open #endif if (m_fd == -1) { ec = error_code(errno, get_posix_category()); return false; } m_open_mode = mode; return true; } void close() { if (m_fd == -1) return; #ifdef _WIN32 ::_close(m_fd); #else ::close(m_fd); #endif m_fd = -1; m_open_mode = 0; } size_type read(char* buf, size_type num_bytes, error_code& ec) { TORRENT_ASSERT(m_open_mode & mode_in); TORRENT_ASSERT(m_fd != -1); #ifdef _WIN32 size_type ret = ::_read(m_fd, buf, num_bytes); #else size_type ret = ::read(m_fd, buf, num_bytes); #endif if (ret == -1) ec = error_code(errno, get_posix_category()); return ret; } size_type write(const char* buf, size_type num_bytes, error_code& ec) { TORRENT_ASSERT(m_open_mode & mode_out); TORRENT_ASSERT(m_fd != -1); // TODO: Test this a bit more, what happens with random failures in // the files? // if ((rand() % 100) > 80) // throw file_error("debug"); #ifdef _WIN32 size_type ret = ::_write(m_fd, buf, num_bytes); #else size_type ret = ::write(m_fd, buf, num_bytes); #endif if (ret == -1) ec = error_code(errno, get_posix_category()); return ret; } bool set_size(size_type s, error_code& ec) { #ifdef _WIN32 #error file.cpp is for posix systems only. use file_win.cpp on windows #else if (ftruncate(m_fd, s) < 0) { ec = error_code(errno, get_posix_category()); return false; } return true; #endif } size_type seek(size_type offset, int m, error_code& ec) { TORRENT_ASSERT(m_open_mode); TORRENT_ASSERT(m_fd != -1); int seekdir = (m == 1)?SEEK_SET:SEEK_END; #ifdef _WIN32 size_type ret = _lseeki64(m_fd, offset, seekdir); #else size_type ret = lseek(m_fd, offset, seekdir); #endif // For some strange reason this fails // on win32. Use windows specific file // wrapper instead. if (ret < 0) ec = error_code(errno, get_posix_category()); return ret; } size_type tell(error_code& ec) { TORRENT_ASSERT(m_open_mode); TORRENT_ASSERT(m_fd != -1); size_type ret; #ifdef _WIN32 ret = _telli64(m_fd); #else ret = lseek(m_fd, 0, SEEK_CUR); #endif if (ret < 0) ec = error_code(errno, get_posix_category()); return ret; } int m_fd; int m_open_mode; }; // pimpl forwardings file::file() : m_impl(new impl()) {} file::file(fs::path const& p, file::open_mode m, error_code& ec) : m_impl(new impl(p, m.m_mask, ec)) {} file::~file() {} bool file::open(fs::path const& p, file::open_mode m, error_code& ec) { return m_impl->open(p, m.m_mask, ec); } void file::close() { m_impl->close(); } size_type file::write(const char* buf, size_type num_bytes, error_code& ec) { return m_impl->write(buf, num_bytes, ec); } size_type file::read(char* buf, size_type num_bytes, error_code& ec) { return m_impl->read(buf, num_bytes, ec); } bool file::set_size(size_type s, error_code& ec) { return m_impl->set_size(s, ec); } size_type file::seek(size_type pos, file::seek_mode m, error_code& ec) { return m_impl->seek(pos, m.m_val, ec); } size_type file::tell(error_code& ec) { return m_impl->tell(ec); } }
set all permission bits on files and let umask handle reducing permissions
set all permission bits on files and let umask handle reducing permissions git-svn-id: a9fe57c6430a6997a38eed96ede4af2f77d6b776@2553 a83610d8-ad2a-0410-a6ab-fc0612d85776
C++
bsd-3-clause
chongyc/libtorrent,chongyc/libtorrent,chongyc/libtorrent,chongyc/libtorrent
c7286e13e4489a1b2acb7be5d2832fba09d33c75
src/device/device.cpp
src/device/device.cpp
/* * Copyright 2011-2013 Blender Foundation * * 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 <stdlib.h> #include <string.h> #include "device.h" #include "device_intern.h" #include "util_debug.h" #include "util_foreach.h" #include "util_half.h" #include "util_math.h" #include "util_opengl.h" #include "util_time.h" #include "util_types.h" #include "util_vector.h" #include "util_string.h" CCL_NAMESPACE_BEGIN bool Device::need_types_update = true; bool Device::need_devices_update = true; /* Device Requested Features */ std::ostream& operator <<(std::ostream &os, const DeviceRequestedFeatures& requested_features) { os << "Experimental features: " << (requested_features.experimental ? "On" : "Off") << std::endl; os << "Max closure count: " << requested_features.max_closure << std::endl; os << "Max nodes group: " << requested_features.max_nodes_group << std::endl; /* TODO(sergey): Decode bitflag into list of names. */ os << "Nodes features: " << requested_features.nodes_features << std::endl; os << "Use hair: " << string_from_bool(requested_features.use_hair) << std::endl; os << "Use object motion: " << string_from_bool(requested_features.use_object_motion) << std::endl; os << "Use camera motion: " << string_from_bool(requested_features.use_camera_motion) << std::endl; os << "Use Baking: " << string_from_bool(requested_features.use_baking) << std::endl; return os; } /* Device */ Device::~Device() { if(!background && vertex_buffer != 0) { glDeleteBuffers(1, &vertex_buffer); } } void Device::pixels_alloc(device_memory& mem) { mem_alloc(mem, MEM_READ_WRITE); } void Device::pixels_copy_from(device_memory& mem, int y, int w, int h) { if(mem.data_type == TYPE_HALF) mem_copy_from(mem, y, w, h, sizeof(half4)); else mem_copy_from(mem, y, w, h, sizeof(uchar4)); } void Device::pixels_free(device_memory& mem) { mem_free(mem); } void Device::draw_pixels(device_memory& rgba, int y, int w, int h, int dx, int dy, int width, int height, bool transparent, const DeviceDrawParams &draw_params) { pixels_copy_from(rgba, y, w, h); if(transparent) { glEnable(GL_BLEND); glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA); } glColor3f(1.0f, 1.0f, 1.0f); if(rgba.data_type == TYPE_HALF) { /* for multi devices, this assumes the inefficient method that we allocate * all pixels on the device even though we only render to a subset */ GLhalf *data_pointer = (GLhalf*)rgba.data_pointer; float vbuffer[16], *basep; float *vp = NULL; data_pointer += 4*y*w; /* draw half float texture, GLSL shader for display transform assumed to be bound */ GLuint texid; glGenTextures(1, &texid); glBindTexture(GL_TEXTURE_2D, texid); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F_ARB, w, h, 0, GL_RGBA, GL_HALF_FLOAT, data_pointer); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glEnable(GL_TEXTURE_2D); if(draw_params.bind_display_space_shader_cb) { draw_params.bind_display_space_shader_cb(); } if(GLEW_VERSION_1_5) { if(!vertex_buffer) glGenBuffers(1, &vertex_buffer); glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer); /* invalidate old contents - avoids stalling if buffer is still waiting in queue to be rendered */ glBufferData(GL_ARRAY_BUFFER, 16 * sizeof(float), NULL, GL_STREAM_DRAW); vp = (float *)glMapBuffer(GL_ARRAY_BUFFER, GL_WRITE_ONLY); basep = NULL; } else { basep = vbuffer; vp = vbuffer; } if(vp) { /* texture coordinate - vertex pair */ vp[0] = 0.0f; vp[1] = 0.0f; vp[2] = dx; vp[3] = dy; vp[4] = 1.0f; vp[5] = 0.0f; vp[6] = (float)width + dx; vp[7] = dy; vp[8] = 1.0f; vp[9] = 1.0f; vp[10] = (float)width + dx; vp[11] = (float)height + dy; vp[12] = 0.0f; vp[13] = 1.0f; vp[14] = dx; vp[15] = (float)height + dy; if(vertex_buffer) glUnmapBuffer(GL_ARRAY_BUFFER); } glTexCoordPointer(2, GL_FLOAT, 4 * sizeof(float), basep); glVertexPointer(2, GL_FLOAT, 4 * sizeof(float), ((char *)basep) + 2 * sizeof(float)); glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_TEXTURE_COORD_ARRAY); glDrawArrays(GL_TRIANGLE_FAN, 0, 4); glDisableClientState(GL_TEXTURE_COORD_ARRAY); glDisableClientState(GL_VERTEX_ARRAY); if(vertex_buffer) { glBindBuffer(GL_ARRAY_BUFFER, 0); } if(draw_params.unbind_display_space_shader_cb) { draw_params.unbind_display_space_shader_cb(); } glBindTexture(GL_TEXTURE_2D, 0); glDisable(GL_TEXTURE_2D); glDeleteTextures(1, &texid); } else { /* fallback for old graphics cards that don't support GLSL, half float, * and non-power-of-two textures */ glPixelZoom((float)width/(float)w, (float)height/(float)h); glRasterPos2f(dx, dy); uint8_t *pixels = (uint8_t*)rgba.data_pointer; pixels += 4*y*w; glDrawPixels(w, h, GL_RGBA, GL_UNSIGNED_BYTE, pixels); glRasterPos2f(0.0f, 0.0f); glPixelZoom(1.0f, 1.0f); } if(transparent) glDisable(GL_BLEND); } Device *Device::create(DeviceInfo& info, Stats &stats, bool background) { Device *device; switch(info.type) { case DEVICE_CPU: device = device_cpu_create(info, stats, background); break; #ifdef WITH_CUDA case DEVICE_CUDA: if(device_cuda_init()) device = device_cuda_create(info, stats, background); else device = NULL; break; #endif #ifdef WITH_MULTI case DEVICE_MULTI: device = device_multi_create(info, stats, background); break; #endif #ifdef WITH_NETWORK case DEVICE_NETWORK: device = device_network_create(info, stats, "127.0.0.1"); break; #endif #ifdef WITH_OPENCL case DEVICE_OPENCL: if(device_opencl_init()) device = device_opencl_create(info, stats, background); else device = NULL; break; #endif default: return NULL; } return device; } DeviceType Device::type_from_string(const char *name) { if(strcmp(name, "cpu") == 0) return DEVICE_CPU; else if(strcmp(name, "cuda") == 0) return DEVICE_CUDA; else if(strcmp(name, "opencl") == 0) return DEVICE_OPENCL; else if(strcmp(name, "network") == 0) return DEVICE_NETWORK; else if(strcmp(name, "multi") == 0) return DEVICE_MULTI; return DEVICE_NONE; } string Device::string_from_type(DeviceType type) { if(type == DEVICE_CPU) return "cpu"; else if(type == DEVICE_CUDA) return "cuda"; else if(type == DEVICE_OPENCL) return "opencl"; else if(type == DEVICE_NETWORK) return "network"; else if(type == DEVICE_MULTI) return "multi"; return ""; } vector<DeviceType>& Device::available_types() { static vector<DeviceType> types; if(need_types_update) { types.clear(); types.push_back(DEVICE_CPU); #ifdef WITH_CUDA if(device_cuda_init()) types.push_back(DEVICE_CUDA); #endif #ifdef WITH_OPENCL if(device_opencl_init()) types.push_back(DEVICE_OPENCL); #endif #ifdef WITH_NETWORK types.push_back(DEVICE_NETWORK); #endif #ifdef WITH_MULTI types.push_back(DEVICE_MULTI); #endif need_types_update = false; } return types; } vector<DeviceInfo>& Device::available_devices() { static vector<DeviceInfo> devices; if(need_types_update) { devices.clear(); #ifdef WITH_CUDA if(device_cuda_init()) device_cuda_info(devices); #endif #ifdef WITH_OPENCL if(device_opencl_init()) device_opencl_info(devices); #endif #ifdef WITH_MULTI device_multi_info(devices); #endif device_cpu_info(devices); #ifdef WITH_NETWORK device_network_info(devices); #endif need_types_update = false; } return devices; } string Device::device_capabilities() { string capabilities = "CPU device capabilities: "; capabilities += device_cpu_capabilities() + "\n"; #ifdef WITH_CUDA if(device_cuda_init()) { capabilities += "\nCUDA device capabilities:\n"; capabilities += device_cuda_capabilities(); } #endif #ifdef WITH_OPENCL if(device_opencl_init()) { capabilities += "\nOpenCL device capabilities:\n"; capabilities += device_opencl_capabilities(); } #endif return capabilities; } void Device::tag_update() { need_types_update = true; need_devices_update = true; } CCL_NAMESPACE_END
/* * Copyright 2011-2013 Blender Foundation * * 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 <stdlib.h> #include <string.h> #include "device.h" #include "device_intern.h" #include "util_debug.h" #include "util_foreach.h" #include "util_half.h" #include "util_math.h" #include "util_opengl.h" #include "util_time.h" #include "util_types.h" #include "util_vector.h" #include "util_string.h" CCL_NAMESPACE_BEGIN bool Device::need_types_update = true; bool Device::need_devices_update = true; /* Device Requested Features */ std::ostream& operator <<(std::ostream &os, const DeviceRequestedFeatures& requested_features) { os << "Experimental features: " << (requested_features.experimental ? "On" : "Off") << std::endl; os << "Max closure count: " << requested_features.max_closure << std::endl; os << "Max nodes group: " << requested_features.max_nodes_group << std::endl; /* TODO(sergey): Decode bitflag into list of names. */ os << "Nodes features: " << requested_features.nodes_features << std::endl; os << "Use hair: " << string_from_bool(requested_features.use_hair) << std::endl; os << "Use object motion: " << string_from_bool(requested_features.use_object_motion) << std::endl; os << "Use camera motion: " << string_from_bool(requested_features.use_camera_motion) << std::endl; os << "Use Baking: " << string_from_bool(requested_features.use_baking) << std::endl; return os; } /* Device */ Device::~Device() { if(!background && vertex_buffer != 0) { glDeleteBuffers(1, &vertex_buffer); } } void Device::pixels_alloc(device_memory& mem) { mem_alloc(mem, MEM_READ_WRITE); } void Device::pixels_copy_from(device_memory& mem, int y, int w, int h) { if(mem.data_type == TYPE_HALF) mem_copy_from(mem, y, w, h, sizeof(half4)); else mem_copy_from(mem, y, w, h, sizeof(uchar4)); } void Device::pixels_free(device_memory& mem) { mem_free(mem); } void Device::draw_pixels(device_memory& rgba, int y, int w, int h, int dx, int dy, int width, int height, bool transparent, const DeviceDrawParams &draw_params) { pixels_copy_from(rgba, y, w, h); if(transparent) { glEnable(GL_BLEND); glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA); } glColor3f(1.0f, 1.0f, 1.0f); if(rgba.data_type == TYPE_HALF) { /* for multi devices, this assumes the inefficient method that we allocate * all pixels on the device even though we only render to a subset */ GLhalf *data_pointer = (GLhalf*)rgba.data_pointer; float vbuffer[16], *basep; float *vp = NULL; data_pointer += 4*y*w; /* draw half float texture, GLSL shader for display transform assumed to be bound */ GLuint texid; glGenTextures(1, &texid); glBindTexture(GL_TEXTURE_2D, texid); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F_ARB, w, h, 0, GL_RGBA, GL_HALF_FLOAT, data_pointer); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glEnable(GL_TEXTURE_2D); if(draw_params.bind_display_space_shader_cb) { draw_params.bind_display_space_shader_cb(); } if(GLEW_VERSION_1_5) { if(!vertex_buffer) glGenBuffers(1, &vertex_buffer); glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer); /* invalidate old contents - avoids stalling if buffer is still waiting in queue to be rendered */ glBufferData(GL_ARRAY_BUFFER, 16 * sizeof(float), NULL, GL_STREAM_DRAW); vp = (float *)glMapBuffer(GL_ARRAY_BUFFER, GL_WRITE_ONLY); basep = NULL; } else { basep = vbuffer; vp = vbuffer; } if(vp) { /* texture coordinate - vertex pair */ vp[0] = 0.0f; vp[1] = 0.0f; vp[2] = dx; vp[3] = dy; vp[4] = 1.0f; vp[5] = 0.0f; vp[6] = (float)width + dx; vp[7] = dy; vp[8] = 1.0f; vp[9] = 1.0f; vp[10] = (float)width + dx; vp[11] = (float)height + dy; vp[12] = 0.0f; vp[13] = 1.0f; vp[14] = dx; vp[15] = (float)height + dy; if(vertex_buffer) glUnmapBuffer(GL_ARRAY_BUFFER); } glTexCoordPointer(2, GL_FLOAT, 4 * sizeof(float), basep); glVertexPointer(2, GL_FLOAT, 4 * sizeof(float), ((char *)basep) + 2 * sizeof(float)); glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_TEXTURE_COORD_ARRAY); glDrawArrays(GL_TRIANGLE_FAN, 0, 4); glDisableClientState(GL_TEXTURE_COORD_ARRAY); glDisableClientState(GL_VERTEX_ARRAY); if(vertex_buffer) { glBindBuffer(GL_ARRAY_BUFFER, 0); } if(draw_params.unbind_display_space_shader_cb) { draw_params.unbind_display_space_shader_cb(); } glBindTexture(GL_TEXTURE_2D, 0); glDisable(GL_TEXTURE_2D); glDeleteTextures(1, &texid); } else { /* fallback for old graphics cards that don't support GLSL, half float, * and non-power-of-two textures */ glPixelZoom((float)width/(float)w, (float)height/(float)h); glRasterPos2f(dx, dy); uint8_t *pixels = (uint8_t*)rgba.data_pointer; pixels += 4*y*w; glDrawPixels(w, h, GL_RGBA, GL_UNSIGNED_BYTE, pixels); glRasterPos2f(0.0f, 0.0f); glPixelZoom(1.0f, 1.0f); } if(transparent) glDisable(GL_BLEND); } Device *Device::create(DeviceInfo& info, Stats &stats, bool background) { Device *device; switch(info.type) { case DEVICE_CPU: device = device_cpu_create(info, stats, background); break; #ifdef WITH_CUDA case DEVICE_CUDA: if(device_cuda_init()) device = device_cuda_create(info, stats, background); else device = NULL; break; #endif #ifdef WITH_MULTI case DEVICE_MULTI: device = device_multi_create(info, stats, background); break; #endif #ifdef WITH_NETWORK case DEVICE_NETWORK: device = device_network_create(info, stats, "127.0.0.1"); break; #endif #ifdef WITH_OPENCL case DEVICE_OPENCL: if(device_opencl_init()) device = device_opencl_create(info, stats, background); else device = NULL; break; #endif default: return NULL; } return device; } DeviceType Device::type_from_string(const char *name) { if(strcmp(name, "cpu") == 0) return DEVICE_CPU; else if(strcmp(name, "cuda") == 0) return DEVICE_CUDA; else if(strcmp(name, "opencl") == 0) return DEVICE_OPENCL; else if(strcmp(name, "network") == 0) return DEVICE_NETWORK; else if(strcmp(name, "multi") == 0) return DEVICE_MULTI; return DEVICE_NONE; } string Device::string_from_type(DeviceType type) { if(type == DEVICE_CPU) return "cpu"; else if(type == DEVICE_CUDA) return "cuda"; else if(type == DEVICE_OPENCL) return "opencl"; else if(type == DEVICE_NETWORK) return "network"; else if(type == DEVICE_MULTI) return "multi"; return ""; } vector<DeviceType>& Device::available_types() { static vector<DeviceType> types; if(need_types_update) { types.clear(); types.push_back(DEVICE_CPU); #ifdef WITH_CUDA if(device_cuda_init()) types.push_back(DEVICE_CUDA); #endif #ifdef WITH_OPENCL if(device_opencl_init()) types.push_back(DEVICE_OPENCL); #endif #ifdef WITH_NETWORK types.push_back(DEVICE_NETWORK); #endif #ifdef WITH_MULTI types.push_back(DEVICE_MULTI); #endif need_types_update = false; } return types; } vector<DeviceInfo>& Device::available_devices() { static vector<DeviceInfo> devices; if(need_devices_update) { devices.clear(); #ifdef WITH_CUDA if(device_cuda_init()) device_cuda_info(devices); #endif #ifdef WITH_OPENCL if(device_opencl_init()) device_opencl_info(devices); #endif #ifdef WITH_MULTI device_multi_info(devices); #endif device_cpu_info(devices); #ifdef WITH_NETWORK device_network_info(devices); #endif need_devices_update = false; } return devices; } string Device::device_capabilities() { string capabilities = "CPU device capabilities: "; capabilities += device_cpu_capabilities() + "\n"; #ifdef WITH_CUDA if(device_cuda_init()) { capabilities += "\nCUDA device capabilities:\n"; capabilities += device_cuda_capabilities(); } #endif #ifdef WITH_OPENCL if(device_opencl_init()) { capabilities += "\nOpenCL device capabilities:\n"; capabilities += device_opencl_capabilities(); } #endif return capabilities; } void Device::tag_update() { need_types_update = true; need_devices_update = true; } CCL_NAMESPACE_END
Fix typo in flags check
Fix typo in flags check
C++
apache-2.0
tangent-opensource/coreBlackbird,tangent-opensource/coreBlackbird,tangent-opensource/coreBlackbird
bb6a0a65a4eada4c148fe5fffe9b62fa8ef4ec7a
core/src/tangram.cpp
core/src/tangram.cpp
#include "tangram.h" #include "platform.h" #include "scene/scene.h" #include "scene/sceneLoader.h" #include "style/style.h" #include "text/fontContext.h" #include "labels/labels.h" #include "tile/tileManager.h" #include "tile/tile.h" #include "gl/error.h" #include "gl/shaderProgram.h" #include "scene/skybox.h" #include "view/view.h" #include "gl/renderState.h" #include "util/inputHandler.h" #include <memory> #include <cmath> namespace Tangram { std::unique_ptr<TileManager> m_tileManager; std::shared_ptr<Scene> m_scene; std::shared_ptr<View> m_view; std::shared_ptr<Labels> m_labels; std::shared_ptr<FontContext> m_ftContext; std::shared_ptr<Skybox> m_skybox; std::unique_ptr<InputHandler> m_inputHandler; static float g_time = 0.0; static unsigned long g_flags = 0; void initialize() { logMsg("initialize\n"); if (!m_tileManager) { // Create view m_view = std::make_shared<View>(); // Create a scene object m_scene = std::make_shared<Scene>(); // Input handler m_inputHandler = std::unique_ptr<InputHandler>(new InputHandler(m_view)); m_skybox = std::shared_ptr<Skybox>(new Skybox("cubemap.png")); m_skybox->init(); // Create a tileManager m_tileManager = TileManager::GetInstance(); // Pass references to the view and scene into the tile manager m_tileManager->setView(m_view); m_tileManager->setScene(m_scene); // Font and label setup m_ftContext = std::make_shared<FontContext>(); m_ftContext->addFont("FiraSans-Medium.ttf", "FiraSans"); m_labels = Labels::GetInstance(); m_labels->setFontContext(m_ftContext); m_labels->setView(m_view); SceneLoader loader; loader.loadScene("config.yaml", *m_scene, *m_tileManager, *m_view); } RenderState::configure(); while (Error::hadGlError("Tangram::initialize()")) {} logMsg("finish initialize\n"); } void resize(int _newWidth, int _newHeight) { logMsg("resize: %d x %d\n", _newWidth, _newHeight); glViewport(0, 0, _newWidth, _newHeight); if (m_view) { m_view->setSize(_newWidth, _newHeight); } if (m_ftContext) { m_ftContext->setScreenSize(m_view->getWidth(), m_view->getHeight()); m_labels->setScreenSize(m_view->getWidth(), m_view->getHeight()); } while (Error::hadGlError("Tangram::resize()")) {} } void update(float _dt) { g_time += _dt; if (m_view) { m_inputHandler->update(_dt); m_view->update(); m_tileManager->updateTileSet(); if(m_view->changedOnLastUpdate() || m_tileManager->hasTileSetChanged() || Label::s_needUpdate) { Label::s_needUpdate = false; for (const auto& mapIDandTile : m_tileManager->getVisibleTiles()) { const auto& tile = mapIDandTile.second; if (tile->isReady()) { tile->update(_dt, *m_view); } } // update labels for specific style for (const auto& style : m_scene->getStyles()) { for (const auto& mapIDandTile : m_tileManager->getVisibleTiles()) { const auto& tile = mapIDandTile.second; if (tile->isReady()) { tile->updateLabels(_dt, *style, *m_view); } } } // manage occlusions m_labels->updateOcclusions(); for (const auto& style : m_scene->getStyles()) { for (const auto& mapIDandTile : m_tileManager->getVisibleTiles()) { const auto& tile = mapIDandTile.second; if (tile->isReady()) { tile->pushLabelTransforms(*style, m_labels); } } } } if (Label::s_needUpdate) { requestRender(); } } if(m_scene) { // Update lights and styles } } void render() { // Set up openGL for new frame glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Loop over all styles for (const auto& style : m_scene->getStyles()) { style->onBeginDrawFrame(m_view, m_scene); // Loop over all tiles in m_tileSet for (const auto& mapIDandTile : m_tileManager->getVisibleTiles()) { const std::shared_ptr<Tile>& tile = mapIDandTile.second; if (tile->isReady()) { // Draw tile! tile->draw(*style, *m_view); } } style->onEndDrawFrame(); } m_skybox->draw(*m_view); m_labels->drawDebug(); while (Error::hadGlError("Tangram::render()")) {} } void setPosition(double _lon, double _lat) { glm::dvec2 meters = m_view->getMapProjection().LonLatToMeters({ _lon, _lat}); m_view->setPosition(meters.x, meters.y); requestRender(); } void getPosition(double& _lon, double& _lat) { glm::dvec2 meters(m_view->getPosition().x, m_view->getPosition().y); glm::dvec2 degrees = m_view->getMapProjection().MetersToLonLat(meters); _lon = degrees.x; _lat = degrees.y; } void setZoom(float _z) { m_view->setZoom(_z); requestRender(); } float getZoom() { return m_view->getZoom(); } void setRotation(float _radians) { m_view->setRoll(_radians); requestRender(); } float getRotation() { return m_view->getRoll(); } void setTilt(float _radians) { m_view->setPitch(_radians); requestRender(); } float getTilt() { return m_view->getPitch(); } void screenToWorldCoordinates(double& _x, double& _y) { float screenX = _x, screenY = _y; m_view->screenToGroundPlane(screenX, screenY); glm::dvec2 meters(screenX + m_view->getPosition().x, screenY + m_view->getPosition().y); glm::dvec2 lonLat = m_view->getMapProjection().MetersToLonLat(meters); _x = lonLat.x; _y = lonLat.y; } void setPixelScale(float _pixelsPerPoint) { if (m_view) { m_view->setPixelScale(_pixelsPerPoint); } for (auto& style : m_scene->getStyles()) { style->setPixelScale(_pixelsPerPoint); } } void handleTapGesture(float _posX, float _posY) { m_inputHandler->handleTapGesture(_posX, _posY); } void handleDoubleTapGesture(float _posX, float _posY) { m_inputHandler->handleDoubleTapGesture(_posX, _posY); } void handlePanGesture(float _startX, float _startY, float _endX, float _endY) { m_inputHandler->handlePanGesture(_startX, _startY, _endX, _endY); } void handlePinchGesture(float _posX, float _posY, float _scale, float _velocity) { m_inputHandler->handlePinchGesture(_posX, _posY, _scale, _velocity); } void handleRotateGesture(float _posX, float _posY, float _radians) { m_inputHandler->handleRotateGesture(_posX, _posY, _radians); } void handleShoveGesture(float _distance) { m_inputHandler->handleShoveGesture(_distance); } void setDebugFlag(DebugFlags _flag, bool _on) { if (_on) { g_flags |= (1 << _flag); // |ing with a bitfield that is 0 everywhere except index _flag; sets index _flag to 1 } else { g_flags &= ~(1 << _flag); // &ing with a bitfield that is 1 everywhere except index _flag; sets index _flag to 0 } m_view->setZoom(m_view->getZoom()); // Force the view to refresh } bool getDebugFlag(DebugFlags _flag) { return (g_flags & (1 << _flag)) != 0; // &ing with a bitfield that is 0 everywhere except index _flag will yield 0 iff index _flag is 0 } void onContextDestroyed() { logMsg("context destroyed\n"); // The OpenGL context has been destroyed since the last time resources were created, // so we invalidate all data that depends on OpenGL object handles. // ShaderPrograms are invalidated and immediately rebuilt ShaderProgram::invalidateAllPrograms(); // Buffer objects are invalidated and re-uploaded the next time they are used VboMesh::invalidateAllVBOs(); // Texture objects are invalidated and re-uploaded the next time they are updated Texture::invalidateAllTextures(); // Reconfigure the render states RenderState::configure(); } }
#include "tangram.h" #include "platform.h" #include "scene/scene.h" #include "scene/sceneLoader.h" #include "style/style.h" #include "text/fontContext.h" #include "labels/labels.h" #include "tile/tileManager.h" #include "tile/tile.h" #include "gl/error.h" #include "gl/shaderProgram.h" #include "scene/skybox.h" #include "view/view.h" #include "gl/renderState.h" #include "util/inputHandler.h" #include <memory> #include <cmath> #include <bitset> namespace Tangram { std::unique_ptr<TileManager> m_tileManager; std::shared_ptr<Scene> m_scene; std::shared_ptr<View> m_view; std::shared_ptr<Labels> m_labels; std::shared_ptr<FontContext> m_ftContext; std::shared_ptr<Skybox> m_skybox; std::unique_ptr<InputHandler> m_inputHandler; static float g_time = 0.0; static std::bitset<8> g_flags = 0; void initialize() { logMsg("initialize\n"); if (!m_tileManager) { // Create view m_view = std::make_shared<View>(); // Create a scene object m_scene = std::make_shared<Scene>(); // Input handler m_inputHandler = std::unique_ptr<InputHandler>(new InputHandler(m_view)); m_skybox = std::shared_ptr<Skybox>(new Skybox("cubemap.png")); m_skybox->init(); // Create a tileManager m_tileManager = TileManager::GetInstance(); // Pass references to the view and scene into the tile manager m_tileManager->setView(m_view); m_tileManager->setScene(m_scene); // Font and label setup m_ftContext = std::make_shared<FontContext>(); m_ftContext->addFont("FiraSans-Medium.ttf", "FiraSans"); m_labels = Labels::GetInstance(); m_labels->setFontContext(m_ftContext); m_labels->setView(m_view); SceneLoader loader; loader.loadScene("config.yaml", *m_scene, *m_tileManager, *m_view); } RenderState::configure(); while (Error::hadGlError("Tangram::initialize()")) {} logMsg("finish initialize\n"); } void resize(int _newWidth, int _newHeight) { logMsg("resize: %d x %d\n", _newWidth, _newHeight); glViewport(0, 0, _newWidth, _newHeight); if (m_view) { m_view->setSize(_newWidth, _newHeight); } if (m_ftContext) { m_ftContext->setScreenSize(m_view->getWidth(), m_view->getHeight()); m_labels->setScreenSize(m_view->getWidth(), m_view->getHeight()); } while (Error::hadGlError("Tangram::resize()")) {} } void update(float _dt) { g_time += _dt; if (m_view) { m_inputHandler->update(_dt); m_view->update(); m_tileManager->updateTileSet(); if(m_view->changedOnLastUpdate() || m_tileManager->hasTileSetChanged() || Label::s_needUpdate) { Label::s_needUpdate = false; for (const auto& mapIDandTile : m_tileManager->getVisibleTiles()) { const auto& tile = mapIDandTile.second; if (tile->isReady()) { tile->update(_dt, *m_view); } } // update labels for specific style for (const auto& style : m_scene->getStyles()) { for (const auto& mapIDandTile : m_tileManager->getVisibleTiles()) { const auto& tile = mapIDandTile.second; if (tile->isReady()) { tile->updateLabels(_dt, *style, *m_view); } } } // manage occlusions m_labels->updateOcclusions(); for (const auto& style : m_scene->getStyles()) { for (const auto& mapIDandTile : m_tileManager->getVisibleTiles()) { const auto& tile = mapIDandTile.second; if (tile->isReady()) { tile->pushLabelTransforms(*style, m_labels); } } } } if (Label::s_needUpdate) { requestRender(); } } if(m_scene) { // Update lights and styles } } void render() { // Set up openGL for new frame glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Loop over all styles for (const auto& style : m_scene->getStyles()) { style->onBeginDrawFrame(m_view, m_scene); // Loop over all tiles in m_tileSet for (const auto& mapIDandTile : m_tileManager->getVisibleTiles()) { const std::shared_ptr<Tile>& tile = mapIDandTile.second; if (tile->isReady()) { // Draw tile! tile->draw(*style, *m_view); } } style->onEndDrawFrame(); } m_skybox->draw(*m_view); m_labels->drawDebug(); while (Error::hadGlError("Tangram::render()")) {} } void setPosition(double _lon, double _lat) { glm::dvec2 meters = m_view->getMapProjection().LonLatToMeters({ _lon, _lat}); m_view->setPosition(meters.x, meters.y); requestRender(); } void getPosition(double& _lon, double& _lat) { glm::dvec2 meters(m_view->getPosition().x, m_view->getPosition().y); glm::dvec2 degrees = m_view->getMapProjection().MetersToLonLat(meters); _lon = degrees.x; _lat = degrees.y; } void setZoom(float _z) { m_view->setZoom(_z); requestRender(); } float getZoom() { return m_view->getZoom(); } void setRotation(float _radians) { m_view->setRoll(_radians); requestRender(); } float getRotation() { return m_view->getRoll(); } void setTilt(float _radians) { m_view->setPitch(_radians); requestRender(); } float getTilt() { return m_view->getPitch(); } void screenToWorldCoordinates(double& _x, double& _y) { float screenX = _x, screenY = _y; m_view->screenToGroundPlane(screenX, screenY); glm::dvec2 meters(screenX + m_view->getPosition().x, screenY + m_view->getPosition().y); glm::dvec2 lonLat = m_view->getMapProjection().MetersToLonLat(meters); _x = lonLat.x; _y = lonLat.y; } void setPixelScale(float _pixelsPerPoint) { if (m_view) { m_view->setPixelScale(_pixelsPerPoint); } for (auto& style : m_scene->getStyles()) { style->setPixelScale(_pixelsPerPoint); } } void handleTapGesture(float _posX, float _posY) { m_inputHandler->handleTapGesture(_posX, _posY); } void handleDoubleTapGesture(float _posX, float _posY) { m_inputHandler->handleDoubleTapGesture(_posX, _posY); } void handlePanGesture(float _startX, float _startY, float _endX, float _endY) { m_inputHandler->handlePanGesture(_startX, _startY, _endX, _endY); } void handlePinchGesture(float _posX, float _posY, float _scale, float _velocity) { m_inputHandler->handlePinchGesture(_posX, _posY, _scale, _velocity); } void handleRotateGesture(float _posX, float _posY, float _radians) { m_inputHandler->handleRotateGesture(_posX, _posY, _radians); } void handleShoveGesture(float _distance) { m_inputHandler->handleShoveGesture(_distance); } void setDebugFlag(DebugFlags _flag, bool _on) { g_flags.set(_flag, _on); m_view->setZoom(m_view->getZoom()); // Force the view to refresh } bool getDebugFlag(DebugFlags _flag) { return g_flags.test(_flag); } void onContextDestroyed() { logMsg("context destroyed\n"); // The OpenGL context has been destroyed since the last time resources were created, // so we invalidate all data that depends on OpenGL object handles. // ShaderPrograms are invalidated and immediately rebuilt ShaderProgram::invalidateAllPrograms(); // Buffer objects are invalidated and re-uploaded the next time they are used VboMesh::invalidateAllVBOs(); // Texture objects are invalidated and re-uploaded the next time they are updated Texture::invalidateAllTextures(); // Reconfigure the render states RenderState::configure(); } }
use std::bitset for Debug options
use std::bitset for Debug options - further reading for anyone missing the bit twiddling: https://graphics.stanford.edu/~seander/bithacks.html
C++
mit
tangrams/tangram-es,quitejonny/tangram-es,quitejonny/tangram-es,cleeus/tangram-es,xvilan/tangram-es,quitejonny/tangram-es,cleeus/tangram-es,xvilan/tangram-es,tangrams/tangram-es,tangrams/tangram-es,cleeus/tangram-es,tangrams/tangram-es,cleeus/tangram-es,quitejonny/tangram-es,cleeus/tangram-es,quitejonny/tangram-es,xvilan/tangram-es,cleeus/tangram-es,tangrams/tangram-es,tangrams/tangram-es,tangrams/tangram-es,xvilan/tangram-es,quitejonny/tangram-es
7f7f3688b86b8c9092f7a5b188b32a66e39e8b30
src/lb/ExpectMonitor.cxx
src/lb/ExpectMonitor.cxx
/* * Copyright 2007-2017 Content Management AG * All rights reserved. * * author: Max Kellermann <[email protected]> * * 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. * * 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 * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "ExpectMonitor.hxx" #include "Monitor.hxx" #include "MonitorConfig.hxx" #include "system/Error.hxx" #include "net/ConnectSocket.hxx" #include "net/UniqueSocketDescriptor.hxx" #include "net/SocketAddress.hxx" #include "event/SocketEvent.hxx" #include "event/TimerEvent.hxx" #include "event/Duration.hxx" #include "util/Cancellable.hxx" #include <unistd.h> #include <sys/socket.h> #include <string.h> #include <errno.h> class ExpectMonitor final : ConnectSocketHandler, Cancellable { const LbMonitorConfig &config; ConnectSocket connect; int fd = -1; SocketEvent event; /** * A timer which is used to delay the recv() call, just in case * the server sends the response in more than one packet. */ TimerEvent delay_event; LbMonitorHandler &handler; public: ExpectMonitor(EventLoop &event_loop, const LbMonitorConfig &_config, LbMonitorHandler &_handler) :config(_config), connect(event_loop, *this), event(event_loop, BIND_THIS_METHOD(EventCallback)), delay_event(event_loop, BIND_THIS_METHOD(DelayCallback)), handler(_handler) {} ExpectMonitor(const ExpectMonitor &other) = delete; void Start(SocketAddress address, CancellablePointer &cancel_ptr) { cancel_ptr = *this; const unsigned timeout = config.connect_timeout > 0 ? config.connect_timeout : (config.timeout > 0 ? config.timeout : 30); connect.Connect(address, ToEventDuration(std::chrono::seconds(timeout))); } private: /* virtual methods from class Cancellable */ void Cancel() override; /* virtual methods from class ConnectSocketHandler */ void OnSocketConnectSuccess(UniqueSocketDescriptor &&fd) override; void OnSocketConnectTimeout() override { handler.Timeout(); delete this; } void OnSocketConnectError(std::exception_ptr ep) override { handler.Error(ep); delete this; } private: void EventCallback(unsigned events); void DelayCallback(); }; static bool check_expectation(char *received, size_t received_length, const char *expect) { return memmem(received, received_length, expect, strlen(expect)) != nullptr; } /* * async operation * */ void ExpectMonitor::Cancel() { if (fd >= 0) { event.Delete(); delay_event.Cancel(); close(fd); } delete this; } /* * libevent callback * */ inline void ExpectMonitor::EventCallback(unsigned events) { if (events & SocketEvent::TIMEOUT) { close(fd); handler.Timeout(); } else { /* wait 10ms before we start reading */ delay_event.Add(EventDuration<0, 10000>::value); return; } delete this; } void ExpectMonitor::DelayCallback() { char buffer[1024]; ssize_t nbytes = recv(fd, buffer, sizeof(buffer), MSG_DONTWAIT); if (nbytes < 0) { auto e = MakeErrno("Failed to receive"); close(fd); handler.Error(std::make_exception_ptr(e)); } else if (!config.fade_expect.empty() && check_expectation(buffer, nbytes, config.fade_expect.c_str())) { close(fd); handler.Fade(); } else if (config.expect.empty() || check_expectation(buffer, nbytes, config.expect.c_str())) { close(fd); handler.Success(); } else { close(fd); handler.Error(std::make_exception_ptr(std::runtime_error("Expectation failed"))); } delete this; } /* * client_socket handler * */ void ExpectMonitor::OnSocketConnectSuccess(UniqueSocketDescriptor &&new_fd) { if (!config.send.empty()) { ssize_t nbytes = send(new_fd.Get(), config.send.data(), config.send.length(), MSG_DONTWAIT); if (nbytes < 0) { handler.Error(std::make_exception_ptr(MakeErrno("Failed to send"))); delete this; return; } } struct timeval expect_timeout = { time_t(config.timeout > 0 ? config.timeout : 10), 0, }; fd = new_fd.Steal(); event.Set(fd, SocketEvent::READ); event.Add(expect_timeout); } /* * lb_monitor_class * */ static void expect_monitor_run(EventLoop &event_loop, const LbMonitorConfig &config, SocketAddress address, LbMonitorHandler &handler, CancellablePointer &cancel_ptr) { ExpectMonitor *expect = new ExpectMonitor(event_loop, config, handler); expect->Start(address, cancel_ptr); } const LbMonitorClass expect_monitor_class = { .run = expect_monitor_run, };
/* * Copyright 2007-2017 Content Management AG * All rights reserved. * * author: Max Kellermann <[email protected]> * * 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. * * 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 * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "ExpectMonitor.hxx" #include "Monitor.hxx" #include "MonitorConfig.hxx" #include "system/Error.hxx" #include "net/ConnectSocket.hxx" #include "net/UniqueSocketDescriptor.hxx" #include "net/SocketAddress.hxx" #include "event/SocketEvent.hxx" #include "event/TimerEvent.hxx" #include "event/Duration.hxx" #include "util/Cancellable.hxx" #include <unistd.h> #include <sys/socket.h> #include <string.h> #include <errno.h> class ExpectMonitor final : ConnectSocketHandler, Cancellable { const LbMonitorConfig &config; ConnectSocket connect; SocketDescriptor fd = SocketDescriptor::Undefined(); SocketEvent event; /** * A timer which is used to delay the recv() call, just in case * the server sends the response in more than one packet. */ TimerEvent delay_event; LbMonitorHandler &handler; public: ExpectMonitor(EventLoop &event_loop, const LbMonitorConfig &_config, LbMonitorHandler &_handler) :config(_config), connect(event_loop, *this), event(event_loop, BIND_THIS_METHOD(EventCallback)), delay_event(event_loop, BIND_THIS_METHOD(DelayCallback)), handler(_handler) {} ExpectMonitor(const ExpectMonitor &other) = delete; void Start(SocketAddress address, CancellablePointer &cancel_ptr) { cancel_ptr = *this; const unsigned timeout = config.connect_timeout > 0 ? config.connect_timeout : (config.timeout > 0 ? config.timeout : 30); connect.Connect(address, ToEventDuration(std::chrono::seconds(timeout))); } private: /* virtual methods from class Cancellable */ void Cancel() override; /* virtual methods from class ConnectSocketHandler */ void OnSocketConnectSuccess(UniqueSocketDescriptor &&fd) override; void OnSocketConnectTimeout() override { handler.Timeout(); delete this; } void OnSocketConnectError(std::exception_ptr ep) override { handler.Error(ep); delete this; } private: void EventCallback(unsigned events); void DelayCallback(); }; static bool check_expectation(char *received, size_t received_length, const char *expect) { return memmem(received, received_length, expect, strlen(expect)) != nullptr; } /* * async operation * */ void ExpectMonitor::Cancel() { if (fd.IsDefined()) { event.Delete(); delay_event.Cancel(); fd.Close(); } delete this; } /* * libevent callback * */ inline void ExpectMonitor::EventCallback(unsigned events) { if (events & SocketEvent::TIMEOUT) { fd.Close(); handler.Timeout(); } else { /* wait 10ms before we start reading */ delay_event.Add(EventDuration<0, 10000>::value); return; } delete this; } void ExpectMonitor::DelayCallback() { char buffer[1024]; ssize_t nbytes = recv(fd.Get(), buffer, sizeof(buffer), MSG_DONTWAIT); if (nbytes < 0) { auto e = MakeErrno("Failed to receive"); fd.Close(); handler.Error(std::make_exception_ptr(e)); } else if (!config.fade_expect.empty() && check_expectation(buffer, nbytes, config.fade_expect.c_str())) { fd.Close(); handler.Fade(); } else if (config.expect.empty() || check_expectation(buffer, nbytes, config.expect.c_str())) { fd.Close(); handler.Success(); } else { fd.Close(); handler.Error(std::make_exception_ptr(std::runtime_error("Expectation failed"))); } delete this; } /* * client_socket handler * */ void ExpectMonitor::OnSocketConnectSuccess(UniqueSocketDescriptor &&new_fd) { if (!config.send.empty()) { ssize_t nbytes = send(new_fd.Get(), config.send.data(), config.send.length(), MSG_DONTWAIT); if (nbytes < 0) { handler.Error(std::make_exception_ptr(MakeErrno("Failed to send"))); delete this; return; } } struct timeval expect_timeout = { time_t(config.timeout > 0 ? config.timeout : 10), 0, }; fd = new_fd.Release(); event.Set(fd.Get(), SocketEvent::READ); event.Add(expect_timeout); } /* * lb_monitor_class * */ static void expect_monitor_run(EventLoop &event_loop, const LbMonitorConfig &config, SocketAddress address, LbMonitorHandler &handler, CancellablePointer &cancel_ptr) { ExpectMonitor *expect = new ExpectMonitor(event_loop, config, handler); expect->Start(address, cancel_ptr); } const LbMonitorClass expect_monitor_class = { .run = expect_monitor_run, };
use class SocketDescriptor
lb/ExpectMonitor: use class SocketDescriptor
C++
bsd-2-clause
CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy
37bcae036ed8cac947baf9334a565cc862d118b1
framework/src/utils/MonotoneCubicInterpolation.C
framework/src/utils/MonotoneCubicInterpolation.C
/****************************************************************/ /* DO NOT MODIFY THIS HEADER */ /* MOOSE - Multiphysics Object Oriented Simulation Environment */ /* */ /* (c) 2010 Battelle Energy Alliance, LLC */ /* ALL RIGHTS RESERVED */ /* */ /* Prepared by Battelle Energy Alliance, LLC */ /* Under Contract No. DE-AC07-05ID14517 */ /* With the U. S. Department of Energy */ /* */ /* See COPYRIGHT for full restrictions */ /****************************************************************/ #include "MonotoneCubicInterpolation.h" #include <fstream> #include <sstream> #include <string> #include <stdexcept> #include <cassert> #include <cmath> MonotoneCubicInterpolation::MonotoneCubicInterpolation() {} MonotoneCubicInterpolation::MonotoneCubicInterpolation(const std::vector<Real> & x, const std::vector<Real> & y): _x(x), _y(y) { errorCheck(); solve(); } void MonotoneCubicInterpolation::setData(const std::vector<Real> & x, const std::vector<Real> & y) { _x = x; _y = y; errorCheck(); solve(); } void MonotoneCubicInterpolation::errorCheck() { if (_x.size() != _y.size()) throw std::domain_error("MonotoneCubicInterpolation: x and y vectors are not the same length"); bool error = false; for (unsigned i = 0; !error && i + 1 < _x.size(); ++i) if (_x[i] >= _x[i+1]) error = true; if (error) throw std::domain_error("x-values are not strictly increasing"); checkMonotone(); if (_monotonic_status == monotonic_not) throw std::domain_error("Don't ask for a monotonic interpolation routine if your dependent variable data isn't monotonic."); } Real MonotoneCubicInterpolation::sign(const Real & x) const { if (x < 0) return -1; else if (x > 0) return 1; else return 0; } void MonotoneCubicInterpolation::checkMonotone() { Real y_diff = _y[1] - _y[0]; Real s = sign(y_diff); for (unsigned int i = 1; i < _y.size() - 1; ++i) { y_diff = _y[i+1] - _y[i]; if (s == 0) s = sign(y_diff); if (s * y_diff < 0) { _monotonic_status = monotonic_not; return; } } if (s > 0) _monotonic_status = monotonic_increase; else if (s < 0) _monotonic_status = monotonic_decrease; else _monotonic_status = monotonic_constant; } Real MonotoneCubicInterpolation::phi(const Real & t) const { return 3. * t * t - 2. * t * t * t; } Real MonotoneCubicInterpolation::phiPrime(const Real & t) const { return 6. * t - 6. * t * t; } Real MonotoneCubicInterpolation::phiDoublePrime(const Real & t) const { return 6. - 12. * t; } Real MonotoneCubicInterpolation::psi(const Real & t) const { return t * t * t - t * t; } Real MonotoneCubicInterpolation::psiPrime(const Real & t) const { return 3. * t * t - 2. * t; } Real MonotoneCubicInterpolation::psiDoublePrime(const Real & t) const { return 6. * t - 2.; } Real MonotoneCubicInterpolation::h1(const Real & xhi, const Real & xlo, const Real & x) const { Real h = xhi - xlo; Real t = (xhi - x) / h; return phi(t); } Real MonotoneCubicInterpolation::h1Prime(const Real & xhi, const Real & xlo, const Real & x) const { Real h = xhi - xlo; Real t = (xhi - x) / h; Real tPrime = -1. / h; return phiPrime(t) * tPrime; } Real MonotoneCubicInterpolation::h1DoublePrime(const Real & xhi, const Real & xlo, const Real & x) const { Real h = xhi - xlo; Real t = (xhi - x) / h; Real tPrime = -1. / h; return phiDoublePrime(t) * tPrime * tPrime; } Real MonotoneCubicInterpolation::h2(const Real & xhi, const Real & xlo, const Real & x) const { Real h = xhi - xlo; Real t = (x - xlo) / h; return phi(t); } Real MonotoneCubicInterpolation::h2Prime(const Real & xhi, const Real & xlo, const Real & x) const { Real h = xhi - xlo; Real t = (x - xlo) / h; Real tPrime = 1. / h; return phiPrime(t) * tPrime; } Real MonotoneCubicInterpolation::h2DoublePrime(const Real & xhi, const Real & xlo, const Real & x) const { Real h = xhi - xlo; Real t = (x - xlo) / h; Real tPrime = 1. / h; return phiDoublePrime(t) * tPrime * tPrime; } Real MonotoneCubicInterpolation::h3(const Real & xhi, const Real & xlo, const Real & x) const { Real h = xhi - xlo; Real t = (xhi - x) / h; return -h * psi(t); } Real MonotoneCubicInterpolation::h3Prime(const Real & xhi, const Real & xlo, const Real & x) const { Real h = xhi - xlo; Real t = (xhi - x) / h; Real tPrime = -1. / h; return -h * psiPrime(t) * tPrime; // psiPrime(t) } Real MonotoneCubicInterpolation::h3DoublePrime(const Real & xhi, const Real & xlo, const Real & x) const { Real h = xhi - xlo; Real t = (xhi - x) / h; Real tPrime = -1. / h; return psiDoublePrime(t) * tPrime; } Real MonotoneCubicInterpolation::h4(const Real & xhi, const Real & xlo, const Real & x) const { Real h = xhi - xlo; Real t = (x - xlo) / h; return h * psi(t); } Real MonotoneCubicInterpolation::h4Prime(const Real & xhi, const Real & xlo, const Real & x) const { Real h = xhi - xlo; Real t = (x - xlo) / h; Real tPrime = 1. / h; return h * psiPrime(t) * tPrime; // psiPrime(t) } Real MonotoneCubicInterpolation::h4DoublePrime(const Real & xhi, const Real & xlo, const Real & x) const { Real h = xhi - xlo; Real t = (x - xlo) / h; Real tPrime = 1. / h; return psiDoublePrime(t) * tPrime; } Real MonotoneCubicInterpolation::p(const Real & xhi, const Real & xlo, const Real & fhi, const Real & flo, const Real & dhi, const Real & dlo, const Real & x) const { return flo * h1(xhi, xlo, x) + fhi * h2(xhi, xlo, x) + dlo * h3(xhi, xlo, x) + dhi * h4(xhi, xlo, x); } Real MonotoneCubicInterpolation::pPrime(const Real & xhi, const Real & xlo, const Real & fhi, const Real & flo, const Real & dhi, const Real & dlo, const Real & x) const { return flo * h1Prime(xhi, xlo, x) + fhi * h2Prime(xhi, xlo, x) + dlo * h3Prime(xhi, xlo, x) + dhi * h4Prime(xhi, xlo, x); } Real MonotoneCubicInterpolation::pDoublePrime(const Real & xhi, const Real & xlo, const Real & fhi, const Real & flo, const Real & dhi, const Real & dlo, const Real & x) const { return flo * h1DoublePrime(xhi, xlo, x) + fhi * h2DoublePrime(xhi, xlo, x) + dlo * h3DoublePrime(xhi, xlo, x) + dhi * h4DoublePrime(xhi, xlo, x); } void MonotoneCubicInterpolation::initialize_derivs() { for (unsigned int i = 1; i < _n_knots - 1; ++i) _yp[i] = (std::pow(_h[i-1], 2) * _y[i+1] - std::pow(_h[i], 2) * _y[i-1] - _y[i] * (_h[i-1] - _h[i]) * (_h[i-1] + _h[i])) / (_h[i-1] * _h[i] * (_h[i-1] * _h[i])); _yp[0] = (-std::pow(_h[0], 2) * _y[2] - _h[1] * _y[0] * (2*_h[0] + _h[1]) + _y[1] * std::pow(_h[0] + _h[1], 2)) / (_h[0] * _h[1] * (_h[0] + _h[1])); Real hlast = _h[_n_intervals - 1]; Real hsecond = _h[_n_intervals - 2]; Real ylast = _y[_n_knots - 1]; Real ysecond = _y[_n_knots - 2]; Real ythird = _y[_n_knots - 3]; _yp[_n_knots - 1] = (hsecond * ylast * (hsecond + 2 * hlast) + std::pow(hlast, 2) * ythird - ysecond * std::pow(hsecond + hlast, 2)) / (hsecond * hlast * (hsecond + hlast)); } void MonotoneCubicInterpolation::modify_derivs(const Real & alpha, const Real & beta, const Real & delta, Real & yp_lo, Real & yp_hi) { Real tau = 3. / std::sqrt(std::pow(alpha, 2) + std::pow(beta, 2)); Real alpha_star = alpha * tau; Real beta_star = beta * tau; yp_lo = alpha_star * delta; yp_hi = beta_star * delta; } void MonotoneCubicInterpolation::solve() { _n_knots = _x.size(), _n_intervals = _x.size() - 1; _h.resize(_n_intervals); _yp.resize(_n_knots); _delta.resize(_n_intervals); _alpha.resize(_n_intervals); _beta.resize(_n_intervals); for (unsigned int i = 0; i < _n_intervals; ++i) _h[i] = _x[i+1] - _x[i]; initialize_derivs(); for (unsigned int i = 0; i < _n_intervals; ++i) _delta[i] = (_y[i+1] - _y[i]) / _h[i]; if (sign(_delta[0]) != sign(_yp[0])) _yp[0] = 0; if (sign(_delta[_n_intervals - 1]) != sign(_yp[_n_knots - 1])) _yp[_n_knots - 1] = 0; for (unsigned int i = 0; i < _n_intervals; ++i) { // Test for zero slope if (_yp[i] == 0 && _delta[i] == 0) _alpha[i] = 1; else if (_delta[i] == 0) _alpha[i] = 4; else _alpha[i] = _yp[i] / _delta[i]; // Test for zero slope if (_yp[i+1] == 0 && _delta[i] == 0) _beta[i] = 1; else if (_delta[i] == 0) _beta[i] = 4; else _beta[i] = _yp[i+1] / _delta[i]; // check if outside region of monotonicity if (std::pow(_alpha[i], 2) + std::pow(_beta[i], 2) > 9.) modify_derivs(_alpha[i], _beta[i], _delta[i], _yp[i], _yp[i+1]); } } void MonotoneCubicInterpolation::findInterval(const Real & x, unsigned int & klo, unsigned int & khi) const { klo = 0; khi = _n_knots - 1; while (khi - klo > 1) { unsigned int k = (khi + klo) >> 1; if (_x[k] > x) khi = k; else klo = k; } } Real MonotoneCubicInterpolation::sample(const Real & x) const { // sanity check (empty MontoneCubicInterpolations are constructable // so we cannot put this into the errorCheck) assert(_x.size() > 0); unsigned int klo, khi; findInterval(x, klo, khi); return p(_x[khi], _x[klo], _y[khi], _y[klo], _yp[khi], _yp[klo], x); } Real MonotoneCubicInterpolation::sampleDerivative(const Real & x) const { unsigned int klo, khi; findInterval(x, klo, khi); return pPrime(_x[khi], _x[klo], _y[khi], _y[klo], _yp[khi], _yp[klo], x); } Real MonotoneCubicInterpolation::sample2ndDerivative(const Real & x) const { unsigned int klo, khi; findInterval(x, klo, khi); return pDoublePrime(_x[khi], _x[klo], _y[khi], _y[klo], _yp[khi], _yp[klo], x); } void MonotoneCubicInterpolation::dumpCSV(std::string filename, const std::vector<Real> & xnew) { unsigned int n = xnew.size(); std::vector<Real> ynew(n), ypnew(n), yppnew(n); std::ofstream out(filename.c_str()); for (unsigned int i = 0; i < n; ++i) { ynew[i] = sample(xnew[i]); ypnew[i] = sampleDerivative(xnew[i]); yppnew[i] = sample2ndDerivative(xnew[i]); out << xnew[i] << ", " << ynew[i] << ", " << ypnew[i] << ", " << yppnew[i] << "\n"; } out.close(); } unsigned int MonotoneCubicInterpolation::getSampleSize() { return _x.size(); }
/****************************************************************/ /* DO NOT MODIFY THIS HEADER */ /* MOOSE - Multiphysics Object Oriented Simulation Environment */ /* */ /* (c) 2010 Battelle Energy Alliance, LLC */ /* ALL RIGHTS RESERVED */ /* */ /* Prepared by Battelle Energy Alliance, LLC */ /* Under Contract No. DE-AC07-05ID14517 */ /* With the U. S. Department of Energy */ /* */ /* See COPYRIGHT for full restrictions */ /****************************************************************/ #include "MonotoneCubicInterpolation.h" #include <fstream> #include <sstream> #include <string> #include <stdexcept> #include <cassert> #include <cmath> MonotoneCubicInterpolation::MonotoneCubicInterpolation() {} MonotoneCubicInterpolation::MonotoneCubicInterpolation(const std::vector<Real> & x, const std::vector<Real> & y) : _x(x), _y(y) { errorCheck(); solve(); } void MonotoneCubicInterpolation::setData(const std::vector<Real> & x, const std::vector<Real> & y) { _x = x; _y = y; errorCheck(); solve(); } void MonotoneCubicInterpolation::errorCheck() { if (_x.size() != _y.size()) throw std::domain_error("MonotoneCubicInterpolation: x and y vectors are not the same length"); bool error = false; for (unsigned i = 0; !error && i + 1 < _x.size(); ++i) if (_x[i] >= _x[i+1]) error = true; if (error) throw std::domain_error("x-values are not strictly increasing"); checkMonotone(); if (_monotonic_status == monotonic_not) throw std::domain_error("Don't ask for a monotonic interpolation routine if your dependent variable data isn't monotonic."); } Real MonotoneCubicInterpolation::sign(const Real & x) const { if (x < 0) return -1; else if (x > 0) return 1; else return 0; } void MonotoneCubicInterpolation::checkMonotone() { Real y_diff = _y[1] - _y[0]; Real s = sign(y_diff); for (unsigned int i = 1; i < _y.size() - 1; ++i) { y_diff = _y[i+1] - _y[i]; if (s == 0) s = sign(y_diff); if (s * y_diff < 0) { _monotonic_status = monotonic_not; return; } } if (s > 0) _monotonic_status = monotonic_increase; else if (s < 0) _monotonic_status = monotonic_decrease; else _monotonic_status = monotonic_constant; } Real MonotoneCubicInterpolation::phi(const Real & t) const { return 3. * t * t - 2. * t * t * t; } Real MonotoneCubicInterpolation::phiPrime(const Real & t) const { return 6. * t - 6. * t * t; } Real MonotoneCubicInterpolation::phiDoublePrime(const Real & t) const { return 6. - 12. * t; } Real MonotoneCubicInterpolation::psi(const Real & t) const { return t * t * t - t * t; } Real MonotoneCubicInterpolation::psiPrime(const Real & t) const { return 3. * t * t - 2. * t; } Real MonotoneCubicInterpolation::psiDoublePrime(const Real & t) const { return 6. * t - 2.; } Real MonotoneCubicInterpolation::h1(const Real & xhi, const Real & xlo, const Real & x) const { Real h = xhi - xlo; Real t = (xhi - x) / h; return phi(t); } Real MonotoneCubicInterpolation::h1Prime(const Real & xhi, const Real & xlo, const Real & x) const { Real h = xhi - xlo; Real t = (xhi - x) / h; Real tPrime = -1. / h; return phiPrime(t) * tPrime; } Real MonotoneCubicInterpolation::h1DoublePrime(const Real & xhi, const Real & xlo, const Real & x) const { Real h = xhi - xlo; Real t = (xhi - x) / h; Real tPrime = -1. / h; return phiDoublePrime(t) * tPrime * tPrime; } Real MonotoneCubicInterpolation::h2(const Real & xhi, const Real & xlo, const Real & x) const { Real h = xhi - xlo; Real t = (x - xlo) / h; return phi(t); } Real MonotoneCubicInterpolation::h2Prime(const Real & xhi, const Real & xlo, const Real & x) const { Real h = xhi - xlo; Real t = (x - xlo) / h; Real tPrime = 1. / h; return phiPrime(t) * tPrime; } Real MonotoneCubicInterpolation::h2DoublePrime(const Real & xhi, const Real & xlo, const Real & x) const { Real h = xhi - xlo; Real t = (x - xlo) / h; Real tPrime = 1. / h; return phiDoublePrime(t) * tPrime * tPrime; } Real MonotoneCubicInterpolation::h3(const Real & xhi, const Real & xlo, const Real & x) const { Real h = xhi - xlo; Real t = (xhi - x) / h; return -h * psi(t); } Real MonotoneCubicInterpolation::h3Prime(const Real & xhi, const Real & xlo, const Real & x) const { Real h = xhi - xlo; Real t = (xhi - x) / h; Real tPrime = -1. / h; return -h * psiPrime(t) * tPrime; // psiPrime(t) } Real MonotoneCubicInterpolation::h3DoublePrime(const Real & xhi, const Real & xlo, const Real & x) const { Real h = xhi - xlo; Real t = (xhi - x) / h; Real tPrime = -1. / h; return psiDoublePrime(t) * tPrime; } Real MonotoneCubicInterpolation::h4(const Real & xhi, const Real & xlo, const Real & x) const { Real h = xhi - xlo; Real t = (x - xlo) / h; return h * psi(t); } Real MonotoneCubicInterpolation::h4Prime(const Real & xhi, const Real & xlo, const Real & x) const { Real h = xhi - xlo; Real t = (x - xlo) / h; Real tPrime = 1. / h; return h * psiPrime(t) * tPrime; // psiPrime(t) } Real MonotoneCubicInterpolation::h4DoublePrime(const Real & xhi, const Real & xlo, const Real & x) const { Real h = xhi - xlo; Real t = (x - xlo) / h; Real tPrime = 1. / h; return psiDoublePrime(t) * tPrime; } Real MonotoneCubicInterpolation::p(const Real & xhi, const Real & xlo, const Real & fhi, const Real & flo, const Real & dhi, const Real & dlo, const Real & x) const { return flo * h1(xhi, xlo, x) + fhi * h2(xhi, xlo, x) + dlo * h3(xhi, xlo, x) + dhi * h4(xhi, xlo, x); } Real MonotoneCubicInterpolation::pPrime(const Real & xhi, const Real & xlo, const Real & fhi, const Real & flo, const Real & dhi, const Real & dlo, const Real & x) const { return flo * h1Prime(xhi, xlo, x) + fhi * h2Prime(xhi, xlo, x) + dlo * h3Prime(xhi, xlo, x) + dhi * h4Prime(xhi, xlo, x); } Real MonotoneCubicInterpolation::pDoublePrime(const Real & xhi, const Real & xlo, const Real & fhi, const Real & flo, const Real & dhi, const Real & dlo, const Real & x) const { return flo * h1DoublePrime(xhi, xlo, x) + fhi * h2DoublePrime(xhi, xlo, x) + dlo * h3DoublePrime(xhi, xlo, x) + dhi * h4DoublePrime(xhi, xlo, x); } void MonotoneCubicInterpolation::initialize_derivs() { for (unsigned int i = 1; i < _n_knots - 1; ++i) _yp[i] = (std::pow(_h[i-1], 2) * _y[i+1] - std::pow(_h[i], 2) * _y[i-1] - _y[i] * (_h[i-1] - _h[i]) * (_h[i-1] + _h[i])) / (_h[i-1] * _h[i] * (_h[i-1] * _h[i])); _yp[0] = (-std::pow(_h[0], 2) * _y[2] - _h[1] * _y[0] * (2*_h[0] + _h[1]) + _y[1] * std::pow(_h[0] + _h[1], 2)) / (_h[0] * _h[1] * (_h[0] + _h[1])); Real hlast = _h[_n_intervals - 1]; Real hsecond = _h[_n_intervals - 2]; Real ylast = _y[_n_knots - 1]; Real ysecond = _y[_n_knots - 2]; Real ythird = _y[_n_knots - 3]; _yp[_n_knots - 1] = (hsecond * ylast * (hsecond + 2 * hlast) + std::pow(hlast, 2) * ythird - ysecond * std::pow(hsecond + hlast, 2)) / (hsecond * hlast * (hsecond + hlast)); } void MonotoneCubicInterpolation::modify_derivs(const Real & alpha, const Real & beta, const Real & delta, Real & yp_lo, Real & yp_hi) { Real tau = 3. / std::sqrt(std::pow(alpha, 2) + std::pow(beta, 2)); Real alpha_star = alpha * tau; Real beta_star = beta * tau; yp_lo = alpha_star * delta; yp_hi = beta_star * delta; } void MonotoneCubicInterpolation::solve() { _n_knots = _x.size(), _n_intervals = _x.size() - 1; _h.resize(_n_intervals); _yp.resize(_n_knots); _delta.resize(_n_intervals); _alpha.resize(_n_intervals); _beta.resize(_n_intervals); for (unsigned int i = 0; i < _n_intervals; ++i) _h[i] = _x[i+1] - _x[i]; initialize_derivs(); for (unsigned int i = 0; i < _n_intervals; ++i) _delta[i] = (_y[i+1] - _y[i]) / _h[i]; if (sign(_delta[0]) != sign(_yp[0])) _yp[0] = 0; if (sign(_delta[_n_intervals - 1]) != sign(_yp[_n_knots - 1])) _yp[_n_knots - 1] = 0; for (unsigned int i = 0; i < _n_intervals; ++i) { // Test for zero slope if (_yp[i] == 0 && _delta[i] == 0) _alpha[i] = 1; else if (_delta[i] == 0) _alpha[i] = 4; else _alpha[i] = _yp[i] / _delta[i]; // Test for zero slope if (_yp[i+1] == 0 && _delta[i] == 0) _beta[i] = 1; else if (_delta[i] == 0) _beta[i] = 4; else _beta[i] = _yp[i+1] / _delta[i]; // check if outside region of monotonicity if (std::pow(_alpha[i], 2) + std::pow(_beta[i], 2) > 9.) modify_derivs(_alpha[i], _beta[i], _delta[i], _yp[i], _yp[i+1]); } } void MonotoneCubicInterpolation::findInterval(const Real & x, unsigned int & klo, unsigned int & khi) const { klo = 0; khi = _n_knots - 1; while (khi - klo > 1) { unsigned int k = (khi + klo) >> 1; if (_x[k] > x) khi = k; else klo = k; } } Real MonotoneCubicInterpolation::sample(const Real & x) const { // sanity check (empty MontoneCubicInterpolations are constructable // so we cannot put this into the errorCheck) assert(_x.size() > 0); unsigned int klo, khi; findInterval(x, klo, khi); return p(_x[khi], _x[klo], _y[khi], _y[klo], _yp[khi], _yp[klo], x); } Real MonotoneCubicInterpolation::sampleDerivative(const Real & x) const { unsigned int klo, khi; findInterval(x, klo, khi); return pPrime(_x[khi], _x[klo], _y[khi], _y[klo], _yp[khi], _yp[klo], x); } Real MonotoneCubicInterpolation::sample2ndDerivative(const Real & x) const { unsigned int klo, khi; findInterval(x, klo, khi); return pDoublePrime(_x[khi], _x[klo], _y[khi], _y[klo], _yp[khi], _yp[klo], x); } void MonotoneCubicInterpolation::dumpCSV(std::string filename, const std::vector<Real> & xnew) { unsigned int n = xnew.size(); std::vector<Real> ynew(n), ypnew(n), yppnew(n); std::ofstream out(filename.c_str()); for (unsigned int i = 0; i < n; ++i) { ynew[i] = sample(xnew[i]); ypnew[i] = sampleDerivative(xnew[i]); yppnew[i] = sample2ndDerivative(xnew[i]); out << xnew[i] << ", " << ynew[i] << ", " << ypnew[i] << ", " << yppnew[i] << "\n"; } out.close(); } unsigned int MonotoneCubicInterpolation::getSampleSize() { return _x.size(); }
Fix minor spacing issue in constructor.
Fix minor spacing issue in constructor.
C++
lgpl-2.1
yipenggao/moose,milljm/moose,yipenggao/moose,liuwenf/moose,harterj/moose,bwspenc/moose,stimpsonsg/moose,idaholab/moose,milljm/moose,yipenggao/moose,sapitts/moose,nuclear-wizard/moose,YaqiWang/moose,andrsd/moose,liuwenf/moose,backmari/moose,YaqiWang/moose,sapitts/moose,bwspenc/moose,idaholab/moose,andrsd/moose,laagesen/moose,Chuban/moose,backmari/moose,jessecarterMOOSE/moose,andrsd/moose,friedmud/moose,stimpsonsg/moose,bwspenc/moose,stimpsonsg/moose,dschwen/moose,nuclear-wizard/moose,lindsayad/moose,Chuban/moose,jessecarterMOOSE/moose,friedmud/moose,lindsayad/moose,SudiptaBiswas/moose,lindsayad/moose,YaqiWang/moose,andrsd/moose,SudiptaBiswas/moose,milljm/moose,permcody/moose,nuclear-wizard/moose,harterj/moose,Chuban/moose,dschwen/moose,sapitts/moose,liuwenf/moose,backmari/moose,andrsd/moose,liuwenf/moose,SudiptaBiswas/moose,idaholab/moose,jessecarterMOOSE/moose,laagesen/moose,permcody/moose,liuwenf/moose,lindsayad/moose,idaholab/moose,Chuban/moose,harterj/moose,laagesen/moose,idaholab/moose,laagesen/moose,dschwen/moose,jessecarterMOOSE/moose,permcody/moose,SudiptaBiswas/moose,bwspenc/moose,jessecarterMOOSE/moose,dschwen/moose,friedmud/moose,milljm/moose,SudiptaBiswas/moose,liuwenf/moose,laagesen/moose,stimpsonsg/moose,sapitts/moose,harterj/moose,harterj/moose,sapitts/moose,yipenggao/moose,YaqiWang/moose,lindsayad/moose,nuclear-wizard/moose,backmari/moose,dschwen/moose,milljm/moose,bwspenc/moose,permcody/moose,friedmud/moose
7142cebcdd7b0e63a5b567d7eda5a5cfe3d8ccc5
src/orbwordindex.cc
src/orbwordindex.cc
/***************************************************************************** * Copyright (C) 2014 Visualink * * Authors: Adrien Maglo <[email protected]> * * This file is part of Pastec. * * Pastec is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Pastec 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 Pastec. If not, see <http://www.gnu.org/licenses/>. *****************************************************************************/ #include <iostream> #include <fstream> #include "orbwordindex.h" using namespace cv; using namespace std; ORBWordIndex::ORBWordIndex() { words = new Mat(0, 32, CV_8U); // The matrix that stores the visual words. kdIndex = NULL; } ORBWordIndex::~ORBWordIndex() { delete words; if (kdIndex!=NULL) { delete kdIndex; } } bool ORBWordIndex::isTraining() { return training; } int ORBWordIndex::startTraining() { if (training) { return ALREADY_TRAINING; } // Release existing words delete words; // ..and create a new empty words list words = new Mat(0, 32, CV_8U); training = true; return SUCCESS; } bool ORBWordIndex::wordPresent(Mat word) { for (int word_idx = 0; word_idx<words->rows; word_idx++) { if ( cv::countNonZero(word!=words->row(word_idx)) == 0) { return true; } } return false; } u_int32_t ORBWordIndex::addTrainingFeatures(Mat training_features, unsigned min_distance) { // Lock for adding words to our vocabulary unique_lock<mutex> locker(trainingMutex); cv::Mat newDescriptors; if (words->rows==0) { newDescriptors = training_features; } else { cvflann::Matrix<unsigned char> m_features ((unsigned char*)words->ptr<unsigned char>(0), words->rows, words->cols); kdIndex = new cvflann::HierarchicalClusteringIndex<cvflann::Hamming<unsigned char> > (m_features,cvflann::HierarchicalClusteringIndexParams(10, cvflann::FLANN_CENTERS_RANDOM, 8, 100)); kdIndex->buildIndex(); for (int i = 0; i < training_features.rows; ++i) { std::vector<int> indices(1); std::vector<int> dists(1); knnSearch(training_features.row(i), indices, dists, 1); for (unsigned j = 0; j < indices.size(); ++j) { const unsigned i_distance = dists[j]; if ( i_distance > min_distance ) { newDescriptors.push_back(training_features.row(i)); } } } } int added_features = newDescriptors.rows; for (int feature_idx = 0; feature_idx<newDescriptors.rows; feature_idx++) { words->push_back(newDescriptors.row(feature_idx)); } locker.unlock(); return added_features; } int ORBWordIndex::endTraining(string visualWordsPath) { if (!training) { return NOT_TRAINING; } if (kdIndex!=NULL) { delete kdIndex; } // Make sure we wait for the last pending // training to be complete if one is pending unique_lock<mutex> locker(trainingMutex); cvflann::Matrix<unsigned char> m_features ((unsigned char*)words->ptr<unsigned char>(0), words->rows, words->cols); kdIndex = new cvflann::HierarchicalClusteringIndex<cvflann::Hamming<unsigned char> > (m_features,cvflann::HierarchicalClusteringIndexParams(10, cvflann::FLANN_CENTERS_RANDOM, 8, 100)); kdIndex->buildIndex(); training = false; if (!saveVisualWords(visualWordsPath)) { locker.unlock(); return SAVE_FAILED; } locker.unlock(); return SUCCESS; } int ORBWordIndex::initialize(string visualWordsPath, int numberOfWords) { if (!readVisualWords(visualWordsPath)) return WORD_DB_FILE_MISSING; if (numberOfWords>0 && words->rows != numberOfWords) { return WORD_DB_WRONG_ROW_SIZE; } cvflann::Matrix<unsigned char> m_features ((unsigned char*)words->ptr<unsigned char>(0), words->rows, words->cols); kdIndex = new cvflann::HierarchicalClusteringIndex<cvflann::Hamming<unsigned char> > (m_features,cvflann::HierarchicalClusteringIndexParams(10, cvflann::FLANN_CENTERS_RANDOM, 8, 100)); kdIndex->buildIndex(); return SUCCESS; } void ORBWordIndex::knnSearch(const Mat& query, vector<int>& indices, vector<int>& dists, int knn, u_int16_t search_params) { cvflann::KNNResultSet<int> m_indices(knn); m_indices.init(indices.data(), dists.data()); kdIndex->findNeighbors(m_indices, (unsigned char*)query.ptr<unsigned char>(0), cvflann::SearchParams(search_params)); } /** * @brief Read the list of visual words from an external file. * @param fileName the path of the input file name. * @param words a pointer to a matrix to store the words. * @return true on success else false. */ bool ORBWordIndex::readVisualWords(string fileName) { // Open the input file. ifstream ifs; ifs.open(fileName.c_str(), ios_base::binary); if (!ifs.good()) { cerr << "Could not open the input word index file." << endl; return false; } unsigned char c; while (ifs.good()) { Mat line(1, 32, CV_8U); for (unsigned i_col = 0; i_col < 32; ++i_col) { ifs.read((char*)&c, sizeof(unsigned char)); line.at<unsigned char>(0, i_col) = c; } if (!ifs.good()) break; words->push_back(line); } ifs.close(); return true; } /** * @brief Save the list of visual words to an external file. * @param fileName the path of the output file name. * @return true on success else false. */ bool ORBWordIndex::saveVisualWords(string fileName) { // Open the input file. ofstream ofs; ofs.open(fileName.c_str(), ios_base::binary); if (!ofs.good()) { cerr << "Could not open the output word index file." << endl; return false; } unsigned char c; for (int rowIdx = 0; rowIdx<words->rows; rowIdx++) { Mat line = words->row(rowIdx); for (unsigned i_col = 0; i_col < 32; ++i_col) { c = line.at<char>(0, i_col); ofs.write((char*)&c, sizeof(unsigned char)); } } ofs.close(); return true; } const char* ORBWordIndex::messages[] = { "Success", "Could not access word index DB file", "Word Index DB has the wrong number of rows", "Already training", "Detector is not being trained", "Failed to save Word Index DB" };
/***************************************************************************** * Copyright (C) 2014 Visualink * * Authors: Adrien Maglo <[email protected]> * * This file is part of Pastec. * * Pastec is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Pastec 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 Pastec. If not, see <http://www.gnu.org/licenses/>. *****************************************************************************/ #include <iostream> #include <fstream> #include "orbwordindex.h" using namespace cv; using namespace std; ORBWordIndex::ORBWordIndex() { words = new Mat(0, 32, CV_8U); // The matrix that stores the visual words. kdIndex = NULL; training = false; } ORBWordIndex::~ORBWordIndex() { delete words; if (kdIndex!=NULL) { delete kdIndex; } } bool ORBWordIndex::isTraining() { return training; } int ORBWordIndex::startTraining() { if (training) { return ALREADY_TRAINING; } // Release existing words delete words; // ..and create a new empty words list words = new Mat(0, 32, CV_8U); training = true; return SUCCESS; } bool ORBWordIndex::wordPresent(Mat word) { for (int word_idx = 0; word_idx<words->rows; word_idx++) { if ( cv::countNonZero(word!=words->row(word_idx)) == 0) { return true; } } return false; } u_int32_t ORBWordIndex::addTrainingFeatures(Mat training_features, unsigned min_distance) { // Lock for adding words to our vocabulary unique_lock<mutex> locker(trainingMutex); cv::Mat newDescriptors; if (words->rows==0) { newDescriptors = training_features; } else { cvflann::Matrix<unsigned char> m_features ((unsigned char*)words->ptr<unsigned char>(0), words->rows, words->cols); kdIndex = new cvflann::HierarchicalClusteringIndex<cvflann::Hamming<unsigned char> > (m_features,cvflann::HierarchicalClusteringIndexParams(10, cvflann::FLANN_CENTERS_RANDOM, 8, 100)); kdIndex->buildIndex(); for (int i = 0; i < training_features.rows; ++i) { std::vector<int> indices(1); std::vector<int> dists(1); knnSearch(training_features.row(i), indices, dists, 1); for (unsigned j = 0; j < indices.size(); ++j) { const unsigned i_distance = dists[j]; if ( i_distance > min_distance ) { newDescriptors.push_back(training_features.row(i)); } } } } int added_features = newDescriptors.rows; for (int feature_idx = 0; feature_idx<newDescriptors.rows; feature_idx++) { words->push_back(newDescriptors.row(feature_idx)); } locker.unlock(); return added_features; } int ORBWordIndex::endTraining(string visualWordsPath) { if (!training) { return NOT_TRAINING; } if (kdIndex!=NULL) { delete kdIndex; } // Make sure we wait for the last pending // training to be complete if one is pending unique_lock<mutex> locker(trainingMutex); cvflann::Matrix<unsigned char> m_features ((unsigned char*)words->ptr<unsigned char>(0), words->rows, words->cols); kdIndex = new cvflann::HierarchicalClusteringIndex<cvflann::Hamming<unsigned char> > (m_features,cvflann::HierarchicalClusteringIndexParams(10, cvflann::FLANN_CENTERS_RANDOM, 8, 100)); kdIndex->buildIndex(); training = false; if (!saveVisualWords(visualWordsPath)) { locker.unlock(); return SAVE_FAILED; } locker.unlock(); return SUCCESS; } int ORBWordIndex::initialize(string visualWordsPath, int numberOfWords) { if (!readVisualWords(visualWordsPath)) return WORD_DB_FILE_MISSING; if (numberOfWords>0 && words->rows != numberOfWords) { return WORD_DB_WRONG_ROW_SIZE; } cvflann::Matrix<unsigned char> m_features ((unsigned char*)words->ptr<unsigned char>(0), words->rows, words->cols); kdIndex = new cvflann::HierarchicalClusteringIndex<cvflann::Hamming<unsigned char> > (m_features,cvflann::HierarchicalClusteringIndexParams(10, cvflann::FLANN_CENTERS_RANDOM, 8, 100)); kdIndex->buildIndex(); return SUCCESS; } void ORBWordIndex::knnSearch(const Mat& query, vector<int>& indices, vector<int>& dists, int knn, u_int16_t search_params) { cvflann::KNNResultSet<int> m_indices(knn); m_indices.init(indices.data(), dists.data()); kdIndex->findNeighbors(m_indices, (unsigned char*)query.ptr<unsigned char>(0), cvflann::SearchParams(search_params)); } /** * @brief Read the list of visual words from an external file. * @param fileName the path of the input file name. * @param words a pointer to a matrix to store the words. * @return true on success else false. */ bool ORBWordIndex::readVisualWords(string fileName) { // Open the input file. ifstream ifs; ifs.open(fileName.c_str(), ios_base::binary); if (!ifs.good()) { cerr << "Could not open the input word index file." << endl; return false; } unsigned char c; while (ifs.good()) { Mat line(1, 32, CV_8U); for (unsigned i_col = 0; i_col < 32; ++i_col) { ifs.read((char*)&c, sizeof(unsigned char)); line.at<unsigned char>(0, i_col) = c; } if (!ifs.good()) break; words->push_back(line); } ifs.close(); return true; } /** * @brief Save the list of visual words to an external file. * @param fileName the path of the output file name. * @return true on success else false. */ bool ORBWordIndex::saveVisualWords(string fileName) { // Open the input file. ofstream ofs; ofs.open(fileName.c_str(), ios_base::binary); if (!ofs.good()) { cerr << "Could not open the output word index file." << endl; return false; } unsigned char c; for (int rowIdx = 0; rowIdx<words->rows; rowIdx++) { Mat line = words->row(rowIdx); for (unsigned i_col = 0; i_col < 32; ++i_col) { c = line.at<char>(0, i_col); ofs.write((char*)&c, sizeof(unsigned char)); } } ofs.close(); return true; } const char* ORBWordIndex::messages[] = { "Success", "Could not access word index DB file", "Word Index DB has the wrong number of rows", "Already training", "Detector is not being trained", "Failed to save Word Index DB" };
Make sure training is marked as not started when creating word indexer instance
Make sure training is marked as not started when creating word indexer instance
C++
apache-2.0
Wedjaa/node-orbidx,Wedjaa/node-orbidx,Wedjaa/node-orbidx,Wedjaa/node-orbidx
f08a56b16a6bdb5e143e99d82473bbd0347b2c0d
src/Platforms/Borland/UtestPlatform.cpp
src/Platforms/Borland/UtestPlatform.cpp
/* * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde * 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 <organization> 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 EARLIER MENTIONED AUTHORS ``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 <copyright holder> 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 DAMA */ #include <stdlib.h> #include "CppUTest/TestHarness.h" #undef malloc #undef free #undef calloc #undef realloc #undef strdup #undef strndup #ifdef CPPUTEST_HAVE_GETTIMEOFDAY #include <sys/time.h> #endif #if defined(CPPUTEST_HAVE_FORK) && defined(CPPUTEST_HAVE_WAITPID) #include <unistd.h> #include <sys/wait.h> #include <errno.h> #endif #include <time.h> #include <stdio.h> #include <stdarg.h> #include <setjmp.h> #include <string.h> #include <math.h> #include <ctype.h> #include <signal.h> #ifdef CPPUTEST_HAVE_PTHREAD_MUTEX_LOCK #include <pthread.h> #endif #include "CppUTest/PlatformSpecificFunctions.h" static jmp_buf test_exit_jmp_buf[10]; static int jmp_buf_index = 0; // There is a possibility that a compiler provides fork but not waitpid. #if !defined(CPPUTEST_HAVE_FORK) || !defined(CPPUTEST_HAVE_WAITPID) static void GccPlatformSpecificRunTestInASeperateProcess(UtestShell* shell, TestPlugin*, TestResult* result) { result->addFailure(TestFailure(shell, "-p doesn't work on this platform, as it is lacking fork.\b")); } static int PlatformSpecificForkImplementation(void) { return 0; } static int PlatformSpecificWaitPidImplementation(int, int*, int) { return 0; } #else static void SetTestFailureByStatusCode(UtestShell* shell, TestResult* result, int status) { if (WIFEXITED(status) && WEXITSTATUS(status) != 0) { result->addFailure(TestFailure(shell, "Failed in separate process")); } else if (WIFSIGNALED(status)) { SimpleString message("Failed in separate process - killed by signal "); message += StringFrom(WTERMSIG(status)); result->addFailure(TestFailure(shell, message)); } else if (WIFSTOPPED(status)) { result->addFailure(TestFailure(shell, "Stopped in separate process - continuing")); } } static void GccPlatformSpecificRunTestInASeperateProcess(UtestShell* shell, TestPlugin* plugin, TestResult* result) { const pid_t syscallError = -1; pid_t cpid; pid_t w; int status = 0; cpid = PlatformSpecificFork(); if (cpid == syscallError) { result->addFailure(TestFailure(shell, "Call to fork() failed")); return; } if (cpid == 0) { /* Code executed by child */ const size_t initialFailureCount = result->getFailureCount(); // LCOV_EXCL_LINE shell->runOneTestInCurrentProcess(plugin, *result); // LCOV_EXCL_LINE _exit(initialFailureCount < result->getFailureCount()); // LCOV_EXCL_LINE } else { /* Code executed by parent */ size_t amountOfRetries = 0; do { w = PlatformSpecificWaitPid(cpid, &status, WUNTRACED); if (w == syscallError) { // OS X debugger causes EINTR if (EINTR == errno) { if (amountOfRetries > 30) { result->addFailure(TestFailure(shell, "Call to waitpid() failed with EINTR. Tried 30 times and giving up! Sometimes happens in debugger")); return; } amountOfRetries++; } else { result->addFailure(TestFailure(shell, "Call to waitpid() failed")); return; } } else { SetTestFailureByStatusCode(shell, result, status); if (WIFSTOPPED(status)) kill(w, SIGCONT); } } while ((w == syscallError) || (!WIFEXITED(status) && !WIFSIGNALED(status))); } } static pid_t PlatformSpecificForkImplementation(void) { return fork(); } static pid_t PlatformSpecificWaitPidImplementation(int pid, int* status, int options) { return waitpid(pid, status, options); } #endif TestOutput::WorkingEnvironment PlatformSpecificGetWorkingEnvironment() { return TestOutput::eclipse; } void (*PlatformSpecificRunTestInASeperateProcess)(UtestShell* shell, TestPlugin* plugin, TestResult* result) = GccPlatformSpecificRunTestInASeperateProcess; int (*PlatformSpecificFork)(void) = PlatformSpecificForkImplementation; int (*PlatformSpecificWaitPid)(int, int*, int) = PlatformSpecificWaitPidImplementation; extern "C" { static int PlatformSpecificSetJmpImplementation(void (*function) (void* data), void* data) { if (0 == setjmp(test_exit_jmp_buf[jmp_buf_index])) { jmp_buf_index++; function(data); jmp_buf_index--; return 1; } return 0; } static void PlatformSpecificLongJmpImplementation() { jmp_buf_index--; longjmp(test_exit_jmp_buf[jmp_buf_index], 1); } static void PlatformSpecificRestoreJumpBufferImplementation() { jmp_buf_index--; } void (*PlatformSpecificLongJmp)() = PlatformSpecificLongJmpImplementation; int (*PlatformSpecificSetJmp)(void (*)(void*), void*) = PlatformSpecificSetJmpImplementation; void (*PlatformSpecificRestoreJumpBuffer)() = PlatformSpecificRestoreJumpBufferImplementation; ///////////// Time in millis static long TimeInMillisImplementation() { #ifdef CPPUTEST_HAVE_GETTIMEOFDAY struct timeval tv; struct timezone tz; gettimeofday(&tv, &tz); return (tv.tv_sec * 1000) + (long)((double)tv.tv_usec * 0.001); #else return 0; #endif } static const char* TimeStringImplementation() { time_t theTime = time(NULLPTR); static char dateTime[80]; #if defined(_WIN32) && defined(MINGW_HAS_SECURE_API) static struct tm lastlocaltime; localtime_s(&lastlocaltime, &theTime); struct tm *tmp = &lastlocaltime; #else struct tm *tmp = localtime(&theTime); #endif strftime(dateTime, 80, "%Y-%m-%dT%H:%M:%S", tmp); return dateTime; } long (*GetPlatformSpecificTimeInMillis)() = TimeInMillisImplementation; const char* (*GetPlatformSpecificTimeString)() = TimeStringImplementation; int (*PlatformSpecificVSNprintf)(char *str, size_t size, const char* format, va_list va_args_list) = vsnprintf; static PlatformSpecificFile PlatformSpecificFOpenImplementation(const char* filename, const char* flag) { #if defined(_WIN32) && defined(MINGW_HAS_SECURE_API) FILE* file; fopen_s(&file, filename, flag); return file; #else return fopen(filename, flag); #endif } static void PlatformSpecificFPutsImplementation(const char* str, PlatformSpecificFile file) { fputs(str, (FILE*)file); } static void PlatformSpecificFCloseImplementation(PlatformSpecificFile file) { fclose((FILE*)file); } static void PlatformSpecificFlushImplementation() { fflush(stdout); } PlatformSpecificFile (*PlatformSpecificFOpen)(const char*, const char*) = PlatformSpecificFOpenImplementation; void (*PlatformSpecificFPuts)(const char*, PlatformSpecificFile) = PlatformSpecificFPutsImplementation; void (*PlatformSpecificFClose)(PlatformSpecificFile) = PlatformSpecificFCloseImplementation; int (*PlatformSpecificPutchar)(int) = putchar; void (*PlatformSpecificFlush)() = PlatformSpecificFlushImplementation; void* (*PlatformSpecificMalloc)(size_t size) = malloc; void* (*PlatformSpecificRealloc)(void*, size_t) = realloc; void (*PlatformSpecificFree)(void* memory) = free; void* (*PlatformSpecificMemCpy)(void*, const void*, size_t) = memcpy; void* (*PlatformSpecificMemset)(void*, int, size_t) = memset; /* GCC 4.9.x introduces -Wfloat-conversion, which causes a warning / error * in GCC's own (macro) implementation of isnan() and isinf(). */ #if defined(__GNUC__) && (__GNUC__ >= 5 || (__GNUC__ == 4 && __GNUC_MINOR__ > 8)) #pragma GCC diagnostic ignored "-Wfloat-conversion" #endif static int IsNanImplementation(double d) { return isnan(d); } static int IsInfImplementation(double d) { return isinf(d); } double (*PlatformSpecificFabs)(double) = fabs; void (*PlatformSpecificSrand)(unsigned int) = srand; int (*PlatformSpecificRand)(void) = rand; int (*PlatformSpecificIsNan)(double) = IsNanImplementation; int (*PlatformSpecificIsInf)(double) = IsInfImplementation; int (*PlatformSpecificAtExit)(void(*func)(void)) = atexit; /// this was undefined before static PlatformSpecificMutex PThreadMutexCreate(void) { #ifdef CPPUTEST_HAVE_PTHREAD_MUTEX_LOCK pthread_mutex_t *mutex = new pthread_mutex_t; pthread_mutex_init(mutex, NULLPTR); return (PlatformSpecificMutex)mutex; #else return NULLPTR; #endif } #ifdef CPPUTEST_HAVE_PTHREAD_MUTEX_LOCK static void PThreadMutexLock(PlatformSpecificMutex mtx) { pthread_mutex_lock((pthread_mutex_t *)mtx); } #else static void PThreadMutexLock(PlatformSpecificMutex) { } #endif #ifdef CPPUTEST_HAVE_PTHREAD_MUTEX_LOCK static void PThreadMutexUnlock(PlatformSpecificMutex mtx) { pthread_mutex_unlock((pthread_mutex_t *)mtx); } #else static void PThreadMutexUnlock(PlatformSpecificMutex) { } #endif #ifdef CPPUTEST_HAVE_PTHREAD_MUTEX_LOCK static void PThreadMutexDestroy(PlatformSpecificMutex mtx) { pthread_mutex_t *mutex = (pthread_mutex_t *)mtx; pthread_mutex_destroy(mutex); delete mutex; } #else static void PThreadMutexDestroy(PlatformSpecificMutex) { } #endif PlatformSpecificMutex (*PlatformSpecificMutexCreate)(void) = PThreadMutexCreate; void (*PlatformSpecificMutexLock)(PlatformSpecificMutex) = PThreadMutexLock; void (*PlatformSpecificMutexUnlock)(PlatformSpecificMutex) = PThreadMutexUnlock; void (*PlatformSpecificMutexDestroy)(PlatformSpecificMutex) = PThreadMutexDestroy; }
/* * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde * 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 <organization> 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 EARLIER MENTIONED AUTHORS ``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 <copyright holder> 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 DAMA */ #include <stdlib.h> #include "CppUTest/TestHarness.h" #undef malloc #undef free #undef calloc #undef realloc #undef strdup #undef strndup #ifdef CPPUTEST_HAVE_GETTIMEOFDAY #include <sys/time.h> #endif #if defined(CPPUTEST_HAVE_FORK) && defined(CPPUTEST_HAVE_WAITPID) #include <unistd.h> #include <sys/wait.h> #include <errno.h> #endif #include <time.h> #include <stdio.h> #include <stdarg.h> #include <setjmp.h> #include <string.h> #include <math.h> #include <ctype.h> #include <signal.h> #ifdef CPPUTEST_HAVE_PTHREAD_MUTEX_LOCK #include <pthread.h> #endif #include "CppUTest/PlatformSpecificFunctions.h" static jmp_buf test_exit_jmp_buf[10]; static int jmp_buf_index = 0; // There is a possibility that a compiler provides fork but not waitpid. #if !defined(CPPUTEST_HAVE_FORK) || !defined(CPPUTEST_HAVE_WAITPID) static void GccPlatformSpecificRunTestInASeperateProcess(UtestShell* shell, TestPlugin*, TestResult* result) { result->addFailure(TestFailure(shell, "-p doesn't work on this platform, as it is lacking fork.\b")); } static int PlatformSpecificForkImplementation(void) { return 0; } static int PlatformSpecificWaitPidImplementation(int, int*, int) { return 0; } #else static void SetTestFailureByStatusCode(UtestShell* shell, TestResult* result, int status) { if (WIFEXITED(status) && WEXITSTATUS(status) != 0) { result->addFailure(TestFailure(shell, "Failed in separate process")); } else if (WIFSIGNALED(status)) { SimpleString message("Failed in separate process - killed by signal "); message += StringFrom(WTERMSIG(status)); result->addFailure(TestFailure(shell, message)); } else if (WIFSTOPPED(status)) { result->addFailure(TestFailure(shell, "Stopped in separate process - continuing")); } } static void GccPlatformSpecificRunTestInASeperateProcess(UtestShell* shell, TestPlugin* plugin, TestResult* result) { const pid_t syscallError = -1; pid_t cpid; pid_t w; int status = 0; cpid = PlatformSpecificFork(); if (cpid == syscallError) { result->addFailure(TestFailure(shell, "Call to fork() failed")); return; } if (cpid == 0) { /* Code executed by child */ const size_t initialFailureCount = result->getFailureCount(); // LCOV_EXCL_LINE shell->runOneTestInCurrentProcess(plugin, *result); // LCOV_EXCL_LINE _exit(initialFailureCount < result->getFailureCount()); // LCOV_EXCL_LINE } else { /* Code executed by parent */ size_t amountOfRetries = 0; do { w = PlatformSpecificWaitPid(cpid, &status, WUNTRACED); if (w == syscallError) { // OS X debugger causes EINTR if (EINTR == errno) { if (amountOfRetries > 30) { result->addFailure(TestFailure(shell, "Call to waitpid() failed with EINTR. Tried 30 times and giving up! Sometimes happens in debugger")); return; } amountOfRetries++; } else { result->addFailure(TestFailure(shell, "Call to waitpid() failed")); return; } } else { SetTestFailureByStatusCode(shell, result, status); if (WIFSTOPPED(status)) kill(w, SIGCONT); } } while ((w == syscallError) || (!WIFEXITED(status) && !WIFSIGNALED(status))); } } static pid_t PlatformSpecificForkImplementation(void) { return fork(); } static pid_t PlatformSpecificWaitPidImplementation(int pid, int* status, int options) { return waitpid(pid, status, options); } #endif TestOutput::WorkingEnvironment PlatformSpecificGetWorkingEnvironment() { return TestOutput::eclipse; } void (*PlatformSpecificRunTestInASeperateProcess)(UtestShell* shell, TestPlugin* plugin, TestResult* result) = GccPlatformSpecificRunTestInASeperateProcess; int (*PlatformSpecificFork)(void) = PlatformSpecificForkImplementation; int (*PlatformSpecificWaitPid)(int, int*, int) = PlatformSpecificWaitPidImplementation; extern "C" { static int PlatformSpecificSetJmpImplementation(void (*function) (void* data), void* data) { if (0 == setjmp(test_exit_jmp_buf[jmp_buf_index])) { jmp_buf_index++; function(data); jmp_buf_index--; return 1; } return 0; } static void PlatformSpecificLongJmpImplementation() { jmp_buf_index--; longjmp(test_exit_jmp_buf[jmp_buf_index], 1); } static void PlatformSpecificRestoreJumpBufferImplementation() { jmp_buf_index--; } void (*PlatformSpecificLongJmp)() = PlatformSpecificLongJmpImplementation; int (*PlatformSpecificSetJmp)(void (*)(void*), void*) = PlatformSpecificSetJmpImplementation; void (*PlatformSpecificRestoreJumpBuffer)() = PlatformSpecificRestoreJumpBufferImplementation; ///////////// Time in millis static long TimeInMillisImplementation() { #ifdef CPPUTEST_HAVE_GETTIMEOFDAY struct timeval tv; struct timezone tz; gettimeofday(&tv, &tz); return (tv.tv_sec * 1000) + (long)((double)tv.tv_usec * 0.001); #else return 0; #endif } static const char* TimeStringImplementation() { time_t theTime = time(NULLPTR); static char dateTime[80]; #if defined(_WIN32) && defined(MINGW_HAS_SECURE_API) static struct tm lastlocaltime; localtime_s(&lastlocaltime, &theTime); struct tm *tmp = &lastlocaltime; #else struct tm *tmp = localtime(&theTime); #endif strftime(dateTime, 80, "%Y-%m-%dT%H:%M:%S", tmp); return dateTime; } long (*GetPlatformSpecificTimeInMillis)() = TimeInMillisImplementation; const char* (*GetPlatformSpecificTimeString)() = TimeStringImplementation; int (*PlatformSpecificVSNprintf)(char *str, size_t size, const char* format, va_list va_args_list) = vsnprintf; static PlatformSpecificFile PlatformSpecificFOpenImplementation(const char* filename, const char* flag) { #if defined(_WIN32) && defined(MINGW_HAS_SECURE_API) FILE* file; fopen_s(&file, filename, flag); return file; #else return fopen(filename, flag); #endif } static void PlatformSpecificFPutsImplementation(const char* str, PlatformSpecificFile file) { fputs(str, (FILE*)file); } static void PlatformSpecificFCloseImplementation(PlatformSpecificFile file) { fclose((FILE*)file); } static void PlatformSpecificFlushImplementation() { fflush(stdout); } PlatformSpecificFile (*PlatformSpecificFOpen)(const char*, const char*) = PlatformSpecificFOpenImplementation; void (*PlatformSpecificFPuts)(const char*, PlatformSpecificFile) = PlatformSpecificFPutsImplementation; void (*PlatformSpecificFClose)(PlatformSpecificFile) = PlatformSpecificFCloseImplementation; int (*PlatformSpecificPutchar)(int) = putchar; void (*PlatformSpecificFlush)() = PlatformSpecificFlushImplementation; void* (*PlatformSpecificMalloc)(size_t size) = malloc; void* (*PlatformSpecificRealloc)(void*, size_t) = realloc; void (*PlatformSpecificFree)(void* memory) = free; void* (*PlatformSpecificMemCpy)(void*, const void*, size_t) = memcpy; void* (*PlatformSpecificMemset)(void*, int, size_t) = memset; static int IsNanImplementation(double d) { return isnan(d); } static int IsInfImplementation(double d) { return isinf(d); } double (*PlatformSpecificFabs)(double) = fabs; void (*PlatformSpecificSrand)(unsigned int) = srand; int (*PlatformSpecificRand)(void) = rand; int (*PlatformSpecificIsNan)(double) = IsNanImplementation; int (*PlatformSpecificIsInf)(double) = IsInfImplementation; int (*PlatformSpecificAtExit)(void(*func)(void)) = atexit; /// this was undefined before static PlatformSpecificMutex PThreadMutexCreate(void) { #ifdef CPPUTEST_HAVE_PTHREAD_MUTEX_LOCK pthread_mutex_t *mutex = new pthread_mutex_t; pthread_mutex_init(mutex, NULLPTR); return (PlatformSpecificMutex)mutex; #else return NULLPTR; #endif } #ifdef CPPUTEST_HAVE_PTHREAD_MUTEX_LOCK static void PThreadMutexLock(PlatformSpecificMutex mtx) { pthread_mutex_lock((pthread_mutex_t *)mtx); } #else static void PThreadMutexLock(PlatformSpecificMutex) { } #endif #ifdef CPPUTEST_HAVE_PTHREAD_MUTEX_LOCK static void PThreadMutexUnlock(PlatformSpecificMutex mtx) { pthread_mutex_unlock((pthread_mutex_t *)mtx); } #else static void PThreadMutexUnlock(PlatformSpecificMutex) { } #endif #ifdef CPPUTEST_HAVE_PTHREAD_MUTEX_LOCK static void PThreadMutexDestroy(PlatformSpecificMutex mtx) { pthread_mutex_t *mutex = (pthread_mutex_t *)mtx; pthread_mutex_destroy(mutex); delete mutex; } #else static void PThreadMutexDestroy(PlatformSpecificMutex) { } #endif PlatformSpecificMutex (*PlatformSpecificMutexCreate)(void) = PThreadMutexCreate; void (*PlatformSpecificMutexLock)(PlatformSpecificMutex) = PThreadMutexLock; void (*PlatformSpecificMutexUnlock)(PlatformSpecificMutex) = PThreadMutexUnlock; void (*PlatformSpecificMutexDestroy)(PlatformSpecificMutex) = PThreadMutexDestroy; }
Update UtestPlatform.cpp
Update UtestPlatform.cpp removed gcc pragma directive
C++
bsd-3-clause
basvodde/cpputest,offa/cpputest,basvodde/cpputest,basvodde/cpputest,cpputest/cpputest,offa/cpputest,offa/cpputest,cpputest/cpputest,offa/cpputest,cpputest/cpputest,cpputest/cpputest,basvodde/cpputest
08320755cc87236230927fc9abdbd513d00fe2be
src/game.cpp
src/game.cpp
#include "game.hpp" #include "exception.hpp" namespace Quoridor { // order in which pawns are adding // pawns rotates according to their indexes: 0 -> 1 -> 2 -> 3 -> 0 -> ... static const std::vector<int> pawn_idx_list = {0, 2, 1, 3}; Game::Game(int board_size) : board_size_(board_size), pawn_data_list_(), cur_pawn_idx_(-1), bg_(board_size_, board_size_), wg_(board_size_ + 1) { } Game::~Game() { } void Game::set_pawns(std::vector<std::shared_ptr<Pawn>> &pawn_list) { size_t pawn_num = pawn_list.size(); if ((pawn_num != 2) && (pawn_num != 4)) { throw Exception("Invalid number of players: " + std::to_string(pawn_num)); } for (size_t i = 0; i < pawn_list.size(); ++i) { pawn_data_t pawn_data; pawn_data.pawn = pawn_list[i]; pawn_data.idx = pawn_idx_list[i]; switch (pawn_data.idx) { case 0: pawn_data.node.set_row(0); pawn_data.node.set_col(board_size_ / 2); for (int j = 0; j < board_size_; ++j) { Node gn(board_size_ - 1, j); pawn_data.goal_nodes.insert(gn); } break; case 1: pawn_data.node.set_row(board_size_ / 2); pawn_data.node.set_col(0); for (int j = 0; j < board_size_; ++j) { Node gn(j, board_size_ - 1); pawn_data.goal_nodes.insert(gn); } break; case 2: pawn_data.node.set_row(board_size_ - 1); pawn_data.node.set_col(board_size_ / 2); for (int j = 0; j < board_size_; ++j) { Node gn(0, j); pawn_data.goal_nodes.insert(gn); } break; case 3: pawn_data.node.set_row(board_size_ / 2); pawn_data.node.set_col(board_size_ - 1); for (int j = 0; j < board_size_; ++j) { Node gn(j, 0); pawn_data.goal_nodes.insert(gn); } break; } pawn_data_list_.insert(pawn_data); } } void Game::switch_pawn() { auto it = pawn_data_list_.upper_bound(cur_pawn_idx_); if (it == pawn_data_list_.end()) { it = pawn_data_list_.begin(); } cur_pawn_idx_ = it->idx; } const pawn_data_t &Game::cur_pawn_data() const { return *pawn_data_list_.find(cur_pawn_idx_); } const pawn_data_list_t &Game::pawn_data_list() const { return pawn_data_list_; } const pawn_data_t &Game::pawn_data(std::shared_ptr<Pawn> &pawn) const { return *pawn_data_list_.get<by_pawn>().find(pawn); } int Game::move_pawn(const Node &node) { const Node &cur_node = pawn_data_list_.find(cur_pawn_idx_)->node; if (bg_.is_adjacent(cur_node, node)) { bg_.unblock_neighbours(cur_node); pawn_data_list_t::iterator it = pawn_data_list_.find(cur_pawn_idx_); pawn_data_list_.modify(it, [=](pawn_data_t &e){ e.node = node; }); bg_.block_neighbours(node); return 0; } else { return -1; } } int Game::add_wall(const Wall &wall) { std::vector<std::pair<Node, Node>> edges; if (try_add_wall(wall, &edges) < 0) { return -1; } wg_.apply_tmp_wall(); for (auto edge : edges) { bg_.remove_edges(edge.first, edge.second); } return 0; } bool Game::is_finished() const { Node cur_node = pawn_data_list_.find(cur_pawn_idx_)->node; if (pawn_data_list_.find(cur_pawn_idx_)->goal_nodes.count(cur_node) != 0) { return true; } return false; } bool Game::get_path(std::shared_ptr<Pawn> pawn, const Node &node, std::list<Node> *path) const { return bg_.find_path(pawn_data(pawn).node, node, path); } int Game::try_add_wall(const Wall &wall, std::vector<std::pair<Node, Node>> *edges) { if (wg_.add_tmp_wall(wall) < 0) { return -1; } bg_.reset_filters(); Node node1; Node node2; Node node_tmp; if (wall.orientation() == Wall::kHorizontal) { for (int i = 0; i < wall.cnt(); ++i) { node1 = Node(wall.row() - 1, wall.col() + i); node2 = Node(wall.row(), wall.col() + i); bg_.filter_edges(node1, node2); edges->push_back(std::make_pair(node1, node2)); node_tmp = Node(wall.row() + 1, wall.col() + i); if ((node_tmp.row() >= 0) && (node_tmp.row() < board_size_) && (node_tmp.col() >= 0) && (node_tmp.col() < board_size_)) { bg_.filter_edges(node1, node_tmp); edges->push_back(std::make_pair(node1, node_tmp)); } node_tmp = Node(wall.row() - 2, wall.col() + i); if ((node_tmp.row() >= 0) && (node_tmp.row() < board_size_) && (node_tmp.col() >= 0) && (node_tmp.col() < board_size_)) { bg_.filter_edges(node_tmp, node2); edges->push_back(std::make_pair(node_tmp, node2)); } for (int j = i - 1; j <= i + 1; j += 2) { node_tmp = Node(wall.row(), wall.col() + j); if ((node_tmp.row() >= 0) && (node_tmp.row() < board_size_) && (node_tmp.col() >= 0) && (node_tmp.col() < board_size_)) { bg_.filter_edges(node1, node_tmp); edges->push_back(std::make_pair(node1, node_tmp)); } node_tmp = Node(wall.row() - 1, wall.col() + j); if ((node_tmp.row() >= 0) && (node_tmp.row() < board_size_) && (node_tmp.col() >= 0) && (node_tmp.col() < board_size_)) { bg_.filter_edges(node_tmp, node2); edges->push_back(std::make_pair(node_tmp, node2)); } } } } else if (wall.orientation() == Wall::kVertical) { for (int i = 0; i < wall.cnt(); ++i) { node1 = Node(wall.row() + i, wall.col() - 1); node2 = Node(wall.row() + i, wall.col()); bg_.filter_edges(node1, node2); edges->push_back(std::make_pair(node1, node2)); node_tmp = Node(wall.row() + i, wall.col() + 1); if ((node_tmp.row() >= 0) && (node_tmp.row() < board_size_) && (node_tmp.col() >= 0) && (node_tmp.col() < board_size_)) { bg_.filter_edges(node1, node_tmp); edges->push_back(std::make_pair(node1, node_tmp)); } node_tmp = Node(wall.row() + i, wall.col() - 2); if ((node_tmp.row() >= 0) && (node_tmp.row() < board_size_) && (node_tmp.col() >= 0) && (node_tmp.col() < board_size_)) { bg_.filter_edges(node_tmp, node2); edges->push_back(std::make_pair(node_tmp, node2)); } for (int j = i - 1; j <= i + 1; j += 2) { node_tmp = Node(wall.row() + j, wall.col()); if ((node_tmp.row() >= 0) && (node_tmp.row() < board_size_) && (node_tmp.col() >= 0) && (node_tmp.col() < board_size_)) { bg_.filter_edges(node1, node_tmp); edges->push_back(std::make_pair(node1, node_tmp)); } node_tmp = Node(wall.row() + j, wall.col() - 1); if ((node_tmp.row() >= 0) && (node_tmp.row() < board_size_) && (node_tmp.col() >= 0) && (node_tmp.col() < board_size_)) { bg_.filter_edges(node_tmp, node2); edges->push_back(std::make_pair(node_tmp, node2)); } } } } else { return -1; } bool path_blocked = false; for (auto pawn_data : pawn_data_list_) { path_blocked = true; for (auto goal_node : pawn_data.goal_nodes) { if (bg_.is_path_exists(pawn_data.node, goal_node)) { path_blocked = false; break; } } // wall blocks all pathes to the opposite side for one of pawns if (path_blocked) { break; } } if (path_blocked) { return -1; } return 0; } } // namespace Quoridor
#include "game.hpp" #include "exception.hpp" namespace Quoridor { // order in which pawns are adding // pawns rotates according to their indexes: 0 -> 1 -> 2 -> 3 -> 0 -> ... static const std::vector<int> pawn_idx_list = {0, 2, 1, 3}; Game::Game(int board_size) : board_size_(board_size), pawn_data_list_(), cur_pawn_idx_(-1), bg_(board_size_, board_size_), wg_(board_size_ + 1) { } Game::~Game() { } void Game::set_pawns(std::vector<std::shared_ptr<Pawn>> &pawn_list) { size_t pawn_num = pawn_list.size(); if ((pawn_num != 2) && (pawn_num != 4)) { throw Exception("Invalid number of players: " + std::to_string(pawn_num)); } for (size_t i = 0; i < pawn_list.size(); ++i) { pawn_data_t pawn_data; pawn_data.pawn = pawn_list[i]; pawn_data.idx = pawn_idx_list[i]; switch (pawn_data.idx) { case 0: pawn_data.node.set_row(0); pawn_data.node.set_col(board_size_ / 2); bg_.block_neighbours(pawn_data.node); for (int j = 0; j < board_size_; ++j) { Node gn(board_size_ - 1, j); pawn_data.goal_nodes.insert(gn); } break; case 1: pawn_data.node.set_row(board_size_ / 2); pawn_data.node.set_col(0); bg_.block_neighbours(pawn_data.node); for (int j = 0; j < board_size_; ++j) { Node gn(j, board_size_ - 1); pawn_data.goal_nodes.insert(gn); } break; case 2: pawn_data.node.set_row(board_size_ - 1); pawn_data.node.set_col(board_size_ / 2); bg_.block_neighbours(pawn_data.node); for (int j = 0; j < board_size_; ++j) { Node gn(0, j); pawn_data.goal_nodes.insert(gn); } break; case 3: pawn_data.node.set_row(board_size_ / 2); pawn_data.node.set_col(board_size_ - 1); bg_.block_neighbours(pawn_data.node); for (int j = 0; j < board_size_; ++j) { Node gn(j, 0); pawn_data.goal_nodes.insert(gn); } break; } pawn_data_list_.insert(pawn_data); } } void Game::switch_pawn() { auto it = pawn_data_list_.upper_bound(cur_pawn_idx_); if (it == pawn_data_list_.end()) { it = pawn_data_list_.begin(); } cur_pawn_idx_ = it->idx; } const pawn_data_t &Game::cur_pawn_data() const { return *pawn_data_list_.find(cur_pawn_idx_); } const pawn_data_list_t &Game::pawn_data_list() const { return pawn_data_list_; } const pawn_data_t &Game::pawn_data(std::shared_ptr<Pawn> &pawn) const { return *pawn_data_list_.get<by_pawn>().find(pawn); } int Game::move_pawn(const Node &node) { const Node &cur_node = pawn_data_list_.find(cur_pawn_idx_)->node; if (bg_.is_adjacent(cur_node, node)) { bg_.unblock_neighbours(cur_node); pawn_data_list_t::iterator it = pawn_data_list_.find(cur_pawn_idx_); pawn_data_list_.modify(it, [=](pawn_data_t &e){ e.node = node; }); bg_.block_neighbours(node); return 0; } else { return -1; } } int Game::add_wall(const Wall &wall) { std::vector<std::pair<Node, Node>> edges; if (try_add_wall(wall, &edges) < 0) { return -1; } wg_.apply_tmp_wall(); for (auto edge : edges) { bg_.remove_edges(edge.first, edge.second); } return 0; } bool Game::is_finished() const { Node cur_node = pawn_data_list_.find(cur_pawn_idx_)->node; if (pawn_data_list_.find(cur_pawn_idx_)->goal_nodes.count(cur_node) != 0) { return true; } return false; } bool Game::get_path(std::shared_ptr<Pawn> pawn, const Node &node, std::list<Node> *path) const { return bg_.find_path(pawn_data(pawn).node, node, path); } int Game::try_add_wall(const Wall &wall, std::vector<std::pair<Node, Node>> *edges) { if (wg_.add_tmp_wall(wall) < 0) { return -1; } bg_.reset_filters(); Node node1; Node node2; Node node_tmp; if (wall.orientation() == Wall::kHorizontal) { for (int i = 0; i < wall.cnt(); ++i) { node1 = Node(wall.row() - 1, wall.col() + i); node2 = Node(wall.row(), wall.col() + i); bg_.filter_edges(node1, node2); edges->push_back(std::make_pair(node1, node2)); node_tmp = Node(wall.row() + 1, wall.col() + i); if ((node_tmp.row() >= 0) && (node_tmp.row() < board_size_) && (node_tmp.col() >= 0) && (node_tmp.col() < board_size_)) { bg_.filter_edges(node1, node_tmp); edges->push_back(std::make_pair(node1, node_tmp)); } node_tmp = Node(wall.row() - 2, wall.col() + i); if ((node_tmp.row() >= 0) && (node_tmp.row() < board_size_) && (node_tmp.col() >= 0) && (node_tmp.col() < board_size_)) { bg_.filter_edges(node_tmp, node2); edges->push_back(std::make_pair(node_tmp, node2)); } for (int j = i - 1; j <= i + 1; j += 2) { node_tmp = Node(wall.row(), wall.col() + j); if ((node_tmp.row() >= 0) && (node_tmp.row() < board_size_) && (node_tmp.col() >= 0) && (node_tmp.col() < board_size_)) { bg_.filter_edges(node1, node_tmp); edges->push_back(std::make_pair(node1, node_tmp)); } node_tmp = Node(wall.row() - 1, wall.col() + j); if ((node_tmp.row() >= 0) && (node_tmp.row() < board_size_) && (node_tmp.col() >= 0) && (node_tmp.col() < board_size_)) { bg_.filter_edges(node_tmp, node2); edges->push_back(std::make_pair(node_tmp, node2)); } } } } else if (wall.orientation() == Wall::kVertical) { for (int i = 0; i < wall.cnt(); ++i) { node1 = Node(wall.row() + i, wall.col() - 1); node2 = Node(wall.row() + i, wall.col()); bg_.filter_edges(node1, node2); edges->push_back(std::make_pair(node1, node2)); node_tmp = Node(wall.row() + i, wall.col() + 1); if ((node_tmp.row() >= 0) && (node_tmp.row() < board_size_) && (node_tmp.col() >= 0) && (node_tmp.col() < board_size_)) { bg_.filter_edges(node1, node_tmp); edges->push_back(std::make_pair(node1, node_tmp)); } node_tmp = Node(wall.row() + i, wall.col() - 2); if ((node_tmp.row() >= 0) && (node_tmp.row() < board_size_) && (node_tmp.col() >= 0) && (node_tmp.col() < board_size_)) { bg_.filter_edges(node_tmp, node2); edges->push_back(std::make_pair(node_tmp, node2)); } for (int j = i - 1; j <= i + 1; j += 2) { node_tmp = Node(wall.row() + j, wall.col()); if ((node_tmp.row() >= 0) && (node_tmp.row() < board_size_) && (node_tmp.col() >= 0) && (node_tmp.col() < board_size_)) { bg_.filter_edges(node1, node_tmp); edges->push_back(std::make_pair(node1, node_tmp)); } node_tmp = Node(wall.row() + j, wall.col() - 1); if ((node_tmp.row() >= 0) && (node_tmp.row() < board_size_) && (node_tmp.col() >= 0) && (node_tmp.col() < board_size_)) { bg_.filter_edges(node_tmp, node2); edges->push_back(std::make_pair(node_tmp, node2)); } } } } else { return -1; } bool path_blocked = false; for (auto pawn_data : pawn_data_list_) { path_blocked = true; for (auto goal_node : pawn_data.goal_nodes) { if (bg_.is_path_exists(pawn_data.node, goal_node)) { path_blocked = false; break; } } // wall blocks all pathes to the opposite side for one of pawns if (path_blocked) { break; } } if (path_blocked) { return -1; } return 0; } } // namespace Quoridor
Fix issue #13: pawn can move through the wall
Fix issue #13: pawn can move through the wall
C++
mit
sfod/quoridor
381b56cd572d3ca85efec4ddebea4af3953845a7
src/glob.cpp
src/glob.cpp
#include <cstring> #include <cstdlib> #include <iostream> #include <stdint.h> #include <string> #include "FS.hpp" #include "sass.h" #include <libgen.h> // return version of libsass we are linked against extern "C" const char* ADDCALL libsass_get_version() { return libsass_version(); } // create a custom importer to resolve glob-based includes Sass_Import_List glob_importer(const char* cur_path, Sass_Importer_Entry cb, struct Sass_Compiler* comp) { // get the base directory from previous import Sass_Import_Entry imp = sass_compiler_get_last_import(comp); char* prev = strdup(sass_import_get_abs_path(imp)); std::string pattern(dirname(prev)); std::free(prev); pattern += std::string("/") + cur_path; // instantiate the matcher instance FS::Match* matcher = new FS::Match(pattern); // get vector of matches (results are cached) const std::vector<FS::Entry*> matches = matcher->getMatches(); // propagate error back to libsass if (matches.empty()) return NULL; // get the cookie from importer descriptor // void* cookie = sass_importer_get_cookie(cb); // create a list to hold our import entries Sass_Import_List incs = sass_make_import_list(matches.size()); // iterate over the list and print out the results std::vector<FS::Entry*>::const_iterator it = matches.begin(); std::vector<FS::Entry*>::const_iterator end = matches.end(); // attach import entry for each match size_t i = 0; while (i < matches.size()) { // create intermediate string object std::string path(matches[i]->path()); // create the resolved import entries (paths to be loaded) incs[i ++ ] = sass_make_import(path.c_str(), path.c_str(), 0, 0); } // return imports return incs; } // entry point for libsass to request custom importers from plugin extern "C" Sass_Importer_List ADDCALL libsass_load_importers() { // allocate a custom function caller Sass_Importer_Entry c_header = sass_make_importer(glob_importer, 3000, (void*) 0); // create list of all custom functions Sass_Importer_List imp_list = sass_make_importer_list(1); // put the only function in this plugin to the list sass_importer_set_list_entry(imp_list, 0, c_header); // return the list return imp_list; }
#include <cstring> #include <cstdlib> #include <iostream> #include <stdint.h> #include <string> #include "FS.hpp" #include "sass.h" #include <libgen.h> // return version of libsass we are linked against extern "C" const char* ADDCALL libsass_get_version() { return libsass_version(); } // create a custom importer to resolve glob-based includes Sass_Import_List glob_importer(const char* cur_path, Sass_Importer_Entry cb, struct Sass_Compiler* comp) { // get the base directory from previous import Sass_Import_Entry imp = sass_compiler_get_last_import(comp); char* prev = strdup(sass_import_get_abs_path(imp)); std::string pattern(dirname(prev)); std::free(prev); pattern += std::string("/") + cur_path; // instantiate the matcher instance FS::Match matcher(pattern); // get vector of matches (results are cached) const std::vector<FS::Entry*> matches = matcher.getMatches(); // propagate error back to libsass if (matches.empty()) return NULL; // get the cookie from importer descriptor // void* cookie = sass_importer_get_cookie(cb); // create a list to hold our import entries Sass_Import_List incs = sass_make_import_list(matches.size()); // iterate over the list and print out the results std::vector<FS::Entry*>::const_iterator it = matches.begin(); std::vector<FS::Entry*>::const_iterator end = matches.end(); // attach import entry for each match size_t i = 0; while (i < matches.size()) { // create intermediate string object std::string path(matches[i]->path()); // create the resolved import entries (paths to be loaded) incs[i ++ ] = sass_make_import(path.c_str(), path.c_str(), 0, 0); } // return imports return incs; } // entry point for libsass to request custom importers from plugin extern "C" Sass_Importer_List ADDCALL libsass_load_importers() { // allocate a custom function caller Sass_Importer_Entry c_header = sass_make_importer(glob_importer, 3000, (void*) 0); // create list of all custom functions Sass_Importer_List imp_list = sass_make_importer_list(1); // put the only function in this plugin to the list sass_importer_set_list_entry(imp_list, 0, c_header); // return the list return imp_list; }
Fix memory leak in `glob_importer`
Fix memory leak in `glob_importer` The matcher was never deleted. Allocate it on stack instead.
C++
mit
mgreter/libsass-glob
dec78d58f49ed6f4e2975115ffd2c04c916d2fea
src/engine/Object.cpp
src/engine/Object.cpp
#include "Object.hpp" Object::Object() {} Object::Object(const Object::Type & type, const std::string& meshPath, const std::vector<std::pair<std::string, bool>>& texturesPaths, const std::vector<std::pair<std::string, bool>>& cubemapPaths, bool castShadows) { _material = static_cast<int>(type); _castShadow = castShadows; switch (_material) { case Object::Skybox: _program = Resources::manager().getProgram("skybox_gbuffer"); break; case Object::Parallax: _program = Resources::manager().getProgram("parallax_gbuffer"); break; case Object::Regular: default: _program = Resources::manager().getProgram("object_gbuffer"); break; } // Load geometry. _mesh = Resources::manager().getMesh(meshPath); // Load and upload the textures. for (unsigned int i = 0; i < texturesPaths.size(); ++i) { const auto & textureName = texturesPaths[i]; _textures.push_back(Resources::manager().getTexture(textureName.first, textureName.second)); } for (unsigned int i = 0; i < cubemapPaths.size(); ++i) { const auto & textureName = cubemapPaths[i]; _textures.push_back(Resources::manager().getCubemap(textureName.first, textureName.second)); } _model = glm::mat4(1.0f); checkGLError(); } Object::Object(std::shared_ptr<ProgramInfos> & program, const std::string& meshPath, const std::vector<std::pair<std::string, bool>>& texturesPaths, const std::vector<std::pair<std::string, bool>>& cubemapPaths) { _material = static_cast<int>(Object::Custom); _castShadow = false; // Load the shaders _program = program; // Load geometry. _mesh = Resources::manager().getMesh(meshPath); // Load and upload the textures. for (unsigned int i = 0; i < texturesPaths.size(); ++i) { const auto & textureName = texturesPaths[i]; _textures.push_back(Resources::manager().getTexture(textureName.first, textureName.second)); } for (unsigned int i = 0; i < cubemapPaths.size(); ++i) { const auto & textureName = cubemapPaths[i]; _textures.push_back(Resources::manager().getCubemap(textureName.first, textureName.second)); } _model = glm::mat4(1.0f); checkGLError(); } void Object::update(const glm::mat4& model) { _model = model; } void Object::draw(const glm::mat4& view, const glm::mat4& projection) const { // Combine the three matrices. glm::mat4 MV = view * _model; glm::mat4 MVP = projection * MV; // Compute the normal matrix glm::mat3 normalMatrix = glm::transpose(glm::inverse(glm::mat3(MV))); // Select the program (and shaders). glUseProgram(_program->id()); // Upload the MVP matrix. glUniformMatrix4fv(_program->uniform("mvp"), 1, GL_FALSE, &MVP[0][0]); switch (_material) { case Object::Parallax: // Upload the projection matrix. glUniformMatrix4fv(_program->uniform("p"), 1, GL_FALSE, &projection[0][0]); // Upload the MV matrix. glUniformMatrix4fv(_program->uniform("mv"), 1, GL_FALSE, &MV[0][0]); // Upload the normal matrix. glUniformMatrix3fv(_program->uniform("normalMatrix"), 1, GL_FALSE, &normalMatrix[0][0]); break; case Object::Regular: // Upload the normal matrix. glUniformMatrix3fv(_program->uniform("normalMatrix"), 1, GL_FALSE, &normalMatrix[0][0]); break; default: break; } // Bind the textures. for (unsigned int i = 0; i < _textures.size(); ++i){ glActiveTexture(GL_TEXTURE0 + i); glBindTexture(_textures[i].cubemap ? GL_TEXTURE_CUBE_MAP : GL_TEXTURE_2D, _textures[i].id); } drawGeometry(); glUseProgram(0); } void Object::drawGeometry() const { glBindVertexArray(_mesh.vId); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _mesh.eId); glDrawElements(GL_TRIANGLES, _mesh.count, GL_UNSIGNED_INT, (void*)0); glBindVertexArray(0); } void Object::clean() const { glDeleteVertexArrays(1, &_mesh.vId); for (auto & texture : _textures) { glDeleteTextures(1, &(texture.id)); } } BoundingBox Object::getBoundingBox() const { return _mesh.bbox.transformed(_model); }
#include "Object.hpp" Object::Object() {} Object::Object(const Object::Type & type, const std::string& meshPath, const std::vector<std::pair<std::string, bool>>& texturesPaths, const std::vector<std::pair<std::string, bool>>& cubemapPaths, bool castShadows) { _material = static_cast<int>(type); _castShadow = castShadows; switch (_material) { case Object::Skybox: _program = Resources::manager().getProgram("skybox_gbuffer"); break; case Object::Parallax: _program = Resources::manager().getProgram("parallax_gbuffer"); break; case Object::Regular: default: _program = Resources::manager().getProgram("object_gbuffer"); break; } // Load geometry. _mesh = Resources::manager().getMesh(meshPath); // Load and upload the textures. for (unsigned int i = 0; i < texturesPaths.size(); ++i) { const auto & textureName = texturesPaths[i]; _textures.push_back(Resources::manager().getTexture(textureName.first, textureName.second)); } for (unsigned int i = 0; i < cubemapPaths.size(); ++i) { const auto & textureName = cubemapPaths[i]; _textures.push_back(Resources::manager().getCubemap(textureName.first, textureName.second)); } _model = glm::mat4(1.0f); checkGLError(); } Object::Object(std::shared_ptr<ProgramInfos> & program, const std::string& meshPath, const std::vector<std::pair<std::string, bool>>& texturesPaths, const std::vector<std::pair<std::string, bool>>& cubemapPaths) { _material = static_cast<int>(Object::Custom); _castShadow = false; // Load the shaders _program = program; // Load geometry. _mesh = Resources::manager().getMesh(meshPath); // Load and upload the textures. for (unsigned int i = 0; i < texturesPaths.size(); ++i) { const auto & textureName = texturesPaths[i]; _textures.push_back(Resources::manager().getTexture(textureName.first, textureName.second)); } for (unsigned int i = 0; i < cubemapPaths.size(); ++i) { const auto & textureName = cubemapPaths[i]; _textures.push_back(Resources::manager().getCubemap(textureName.first, textureName.second)); } _model = glm::mat4(1.0f); checkGLError(); } void Object::update(const glm::mat4& model) { _model = model; } void Object::draw(const glm::mat4& view, const glm::mat4& projection) const { // Combine the three matrices. glm::mat4 MV = view * _model; glm::mat4 MVP = projection * MV; // Compute the normal matrix glm::mat3 normalMatrix = glm::transpose(glm::inverse(glm::mat3(MV))); // Select the program (and shaders). glUseProgram(_program->id()); // Upload the MVP matrix. glUniformMatrix4fv(_program->uniform("mvp"), 1, GL_FALSE, &MVP[0][0]); switch (_material) { case Object::Parallax: // Upload the projection matrix. glUniformMatrix4fv(_program->uniform("p"), 1, GL_FALSE, &projection[0][0]); // Upload the MV matrix. glUniformMatrix4fv(_program->uniform("mv"), 1, GL_FALSE, &MV[0][0]); // Upload the normal matrix. glUniformMatrix3fv(_program->uniform("normalMatrix"), 1, GL_FALSE, &normalMatrix[0][0]); break; case Object::Regular: // Upload the normal matrix. glUniformMatrix3fv(_program->uniform("normalMatrix"), 1, GL_FALSE, &normalMatrix[0][0]); break; default: break; } // Bind the textures. for (unsigned int i = 0; i < _textures.size(); ++i){ glActiveTexture(GL_TEXTURE0 + i); glBindTexture(_textures[i].cubemap ? GL_TEXTURE_CUBE_MAP : GL_TEXTURE_2D, _textures[i].id); } drawGeometry(); glUseProgram(0); } void Object::drawGeometry() const { glBindVertexArray(_mesh.vId); glDrawElements(GL_TRIANGLES, _mesh.count, GL_UNSIGNED_INT, (void*)0); glBindVertexArray(0); } void Object::clean() const { glDeleteVertexArrays(1, &_mesh.vId); for (auto & texture : _textures) { glDeleteTextures(1, &(texture.id)); } } BoundingBox Object::getBoundingBox() const { return _mesh.bbox.transformed(_model); }
remove uneeded element array buffer binding.
Object: remove uneeded element array buffer binding. Former-commit-id: 111ffd61291b8ac7015f86420ec672bec4e87804
C++
mit
kosua20/GL_Template,kosua20/GL_Template
6488b5749e45bbaef09480a636f184f59ad85057
src/gzip.cpp
src/gzip.cpp
/* Copyright (c) 2007-2014, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "libtorrent/assert.hpp" #include "libtorrent/puff.hpp" #include <vector> #include <string> namespace { enum { FTEXT = 0x01, FHCRC = 0x02, FEXTRA = 0x04, FNAME = 0x08, FCOMMENT = 0x10, FRESERVED = 0xe0, GZIP_MAGIC0 = 0x1f, GZIP_MAGIC1 = 0x8b }; } namespace libtorrent { // returns -1 if gzip header is invalid or the header size in bytes int gzip_header(const char* buf, int size) { TORRENT_ASSERT(buf != 0); const unsigned char* buffer = reinterpret_cast<const unsigned char*>(buf); const int total_size = size; // The zip header cannot be shorter than 10 bytes if (size < 10 || buf == 0) return -1; // check the magic header of gzip if ((buffer[0] != GZIP_MAGIC0) || (buffer[1] != GZIP_MAGIC1)) return -1; int method = buffer[2]; int flags = buffer[3]; // check for reserved flag and make sure it's compressed with the correct metod if (method != 8 || (flags & FRESERVED) != 0) return -1; // skip time, xflags, OS code size -= 10; buffer += 10; if (flags & FEXTRA) { int extra_len; if (size < 2) return -1; extra_len = (buffer[1] << 8) | buffer[0]; if (size < (extra_len+2)) return -1; size -= (extra_len + 2); buffer += (extra_len + 2); } if (flags & FNAME) { while (size && *buffer) { --size; ++buffer; } if (!size || *buffer) return -1; --size; ++buffer; } if (flags & FCOMMENT) { while (size && *buffer) { --size; ++buffer; } if (!size || *buffer) return -1; --size; ++buffer; } if (flags & FHCRC) { if (size < 2) return -1; size -= 2; // buffer += 2; } return total_size - size; } // TODO: 2 it would be nice to use proper error handling here bool inflate_gzip( char const* in , int size , std::vector<char>& buffer , int maximum_size , std::string& error) { TORRENT_ASSERT(maximum_size > 0); int header_len = gzip_header(in, size); if (header_len < 0) { error = "invalid gzip header"; return true; } // start off with 4 kilobytes and grow // if needed boost::uint32_t destlen = 4096; int ret = 0; boost::uint32_t srclen = size - header_len; in += header_len; do { TORRENT_TRY { buffer.resize(destlen); } TORRENT_CATCH(std::exception& e) { error = "out of memory"; return true; } ret = puff((unsigned char*)&buffer[0], &destlen, (unsigned char*)in, &srclen); // if the destination buffer wasn't large enough, double its // size and try again. Unless it's already at its max, in which // case we fail if (ret == 1) // 1: output space exhausted before completing inflate { if (destlen == maximum_size) { error = "inflated data too big"; return true; } destlen *= 2; if (destlen > maximum_size) destlen = maximum_size; } } while (ret == 1); if (ret != 0) { error = "error while inflating data"; return true; } if (destlen > buffer.size()) { error = "internal gzip error"; return true; } buffer.resize(destlen); return false; } }
/* Copyright (c) 2007-2014, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "libtorrent/assert.hpp" #include "libtorrent/puff.hpp" #include <vector> #include <string> namespace { enum { FTEXT = 0x01, FHCRC = 0x02, FEXTRA = 0x04, FNAME = 0x08, FCOMMENT = 0x10, FRESERVED = 0xe0, GZIP_MAGIC0 = 0x1f, GZIP_MAGIC1 = 0x8b }; } namespace libtorrent { // returns -1 if gzip header is invalid or the header size in bytes int gzip_header(const char* buf, int size) { TORRENT_ASSERT(buf != 0); const unsigned char* buffer = reinterpret_cast<const unsigned char*>(buf); const int total_size = size; // The zip header cannot be shorter than 10 bytes if (size < 10 || buf == 0) return -1; // check the magic header of gzip if ((buffer[0] != GZIP_MAGIC0) || (buffer[1] != GZIP_MAGIC1)) return -1; int method = buffer[2]; int flags = buffer[3]; // check for reserved flag and make sure it's compressed with the correct metod if (method != 8 || (flags & FRESERVED) != 0) return -1; // skip time, xflags, OS code size -= 10; buffer += 10; if (flags & FEXTRA) { int extra_len; if (size < 2) return -1; extra_len = (buffer[1] << 8) | buffer[0]; if (size < (extra_len+2)) return -1; size -= (extra_len + 2); buffer += (extra_len + 2); } if (flags & FNAME) { while (size && *buffer) { --size; ++buffer; } if (!size || *buffer) return -1; --size; ++buffer; } if (flags & FCOMMENT) { while (size && *buffer) { --size; ++buffer; } if (!size || *buffer) return -1; --size; ++buffer; } if (flags & FHCRC) { if (size < 2) return -1; size -= 2; // buffer += 2; } return total_size - size; } // TODO: 2 it would be nice to use proper error handling here TORRENT_EXTRA_EXPORT bool inflate_gzip( char const* in , int size , std::vector<char>& buffer , int maximum_size , std::string& error) { TORRENT_ASSERT(maximum_size > 0); int header_len = gzip_header(in, size); if (header_len < 0) { error = "invalid gzip header"; return true; } // start off with 4 kilobytes and grow // if needed boost::uint32_t destlen = 4096; int ret = 0; boost::uint32_t srclen = size - header_len; in += header_len; do { TORRENT_TRY { buffer.resize(destlen); } TORRENT_CATCH(std::exception& e) { error = "out of memory"; return true; } ret = puff((unsigned char*)&buffer[0], &destlen, (unsigned char*)in, &srclen); // if the destination buffer wasn't large enough, double its // size and try again. Unless it's already at its max, in which // case we fail if (ret == 1) // 1: output space exhausted before completing inflate { if (destlen == maximum_size) { error = "inflated data too big"; return true; } destlen *= 2; if (destlen > maximum_size) destlen = maximum_size; } } while (ret == 1); if (ret != 0) { error = "error while inflating data"; return true; } if (destlen > buffer.size()) { error = "internal gzip error"; return true; } buffer.resize(destlen); return false; } }
fix inflate_gzip export for unit test
fix inflate_gzip export for unit test git-svn-id: 4f0141143c3c635d33f1b9f02fcb2b6c73e45c89@9926 a83610d8-ad2a-0410-a6ab-fc0612d85776
C++
bsd-3-clause
svn2github/libtorrent-rasterbar-trunk,svn2github/libtorrent-rasterbar-trunk,svn2github/libtorrent-rasterbar-trunk,svn2github/libtorrent-rasterbar-trunk
9ef938362557eac870a57396f94b550b7a8534e1
src/ics3.cpp
src/ics3.cpp
#include"ics3/ics3.hpp" #include"core.hpp" #include"ics3/eeprom.hpp" #include"ics3/parameter.hpp" #include"ics3/id.hpp" inline uint16_t getReceiveAngle(const std::vector<uint8_t>& rx) noexcept { return static_cast<uint16_t>((rx[4] << 7) | rx[5]); } ics::ICS3::ICS3(const std::string& path, const Baudrate& baudrate) : core {Core::getCore(path, baudrate.getSpeed())} {} ics::Angle ics::ICS3::move(const ID& id, Angle angle) { static std::vector<uint8_t> tx(3), rx(6); const uint16_t send {angle.getRaw()}; tx[0] = 0x80 | id.get(); tx[1] = 0x7F & (send >> 7); tx[2] = 0x7F & send; core->communicate(tx, rx); // throw std::runtime_error angle.rawData = getReceiveAngle(rx); // avoid invalid check. need friend return angle; } ics::Angle ics::ICS3::free(const ID& id, Angle unit) { static std::vector<uint8_t> tx(3), rx(6); tx[0] = 0x80 | id.get(); // tx[1] == tx[2] == 0 core->communicate(tx, rx); // throw std::runtime_error unit.rawData = getReceiveAngle(rx); // avoid invalid check. need friend return unit; } ics::Parameter ics::ICS3::get(const ID& id, const Parameter& type) { static std::vector<uint8_t> tx(2), rx(5); tx[0] = 0xA0 | id.get(); tx[1] = type.getSubcommand(); core->communicate(tx, rx); // throw std::runtime_error return Parameter::newParameter(type, rx[4]); } void ics::ICS3::set(const ID& id, const Parameter& param) { static std::vector<uint8_t> tx(3), rx(6); tx[0] = 0xC0 | id.get(); tx[1] = param.getSubcommand(); tx[2] = param.get(); core->communicate(tx, rx); // throw std::runtime_error } ics::EepRom ics::ICS3::getRom(const ID& id) { static std::vector<uint8_t> tx(2), rx(68); tx[0] = 0xA0 | id.get(); // tx[1] == 0 core->communicate(tx, rx); // throw std::runtime_error std::array<uint8_t, 64> romData; std::copy(rx.begin() + 4, rx.end(), romData.begin()); return EepRom {romData}; // need friend } void ics::ICS3::setRom(const ID& id, const EepRom& rom) { static std::vector<uint8_t> tx(66), rx(68); tx[0] = 0xC0 | id.get(); // tx[1] == 0 rom.write(tx.begin() + 2); core->communicate(tx, rx); // throw std::runtime_error } ics::ID ics::ICS3::getID() { static const std::vector<uint8_t> tx {0xFF, 0x00, 0x00, 0x00}; static std::vector<uint8_t> rx(5); core->communicateID(tx, rx); return ID {static_cast<uint8_t>(0x1F & rx[4])}; } void ics::ICS3::setID(const ID& id) { static std::vector<uint8_t> tx(4, 1), rx(5); tx[0] = 0xE0 | id.get(); // tx[1] == tx[2] == tx[3] == 1 core->communicateID(tx, rx); }
#include"ics3/ics3.hpp" #include"core.hpp" #include"ics3/eeprom.hpp" #include"ics3/parameter.hpp" #include"ics3/id.hpp" inline uint16_t getReceiveAngle(const std::vector<uint8_t>& rx) noexcept { return static_cast<uint16_t>((rx[4] << 7) | rx[5]); } ics::ICS3::ICS3(const std::string& path, const Baudrate& baudrate) : core {Core::getCore(path, baudrate.getSpeed())} {} ics::Angle ics::ICS3::move(const ID& id, Angle angle) { static std::vector<uint8_t> tx(3), rx(6); // cache for runtime speed const uint16_t send {angle.getRaw()}; tx[0] = 0x80 | id.get(); tx[1] = 0x7F & (send >> 7); tx[2] = 0x7F & send; core->communicate(tx, rx); // throw std::runtime_error angle.rawData = getReceiveAngle(rx); // avoid invalid check. need friend return angle; } ics::Angle ics::ICS3::free(const ID& id, Angle unit) { static std::vector<uint8_t> tx(3), rx(6); // cache for runtime speed tx[0] = 0x80 | id.get(); // tx[1] == tx[2] == 0 core->communicate(tx, rx); // throw std::runtime_error unit.rawData = getReceiveAngle(rx); // avoid invalid check. need friend return unit; } ics::Parameter ics::ICS3::get(const ID& id, const Parameter& type) { std::vector<uint8_t> tx(2), rx(5); tx[0] = 0xA0 | id.get(); tx[1] = type.getSubcommand(); core->communicate(tx, rx); // throw std::runtime_error return Parameter::newParameter(type, rx[4]); } void ics::ICS3::set(const ID& id, const Parameter& param) { std::vector<uint8_t> tx(3), rx(6); tx[0] = 0xC0 | id.get(); tx[1] = param.getSubcommand(); tx[2] = param.get(); core->communicate(tx, rx); // throw std::runtime_error } ics::EepRom ics::ICS3::getRom(const ID& id) { std::vector<uint8_t> tx(2), rx(68); tx[0] = 0xA0 | id.get(); // tx[1] == 0 core->communicate(tx, rx); // throw std::runtime_error std::array<uint8_t, 64> romData; std::copy(rx.cbegin() + 4, rx.cend(), romData.begin()); return EepRom {romData}; // need friend } void ics::ICS3::setRom(const ID& id, const EepRom& rom) { std::vector<uint8_t> tx(66), rx(68); tx[0] = 0xC0 | id.get(); // tx[1] == 0 rom.write(tx.begin() + 2); core->communicate(tx, rx); // throw std::runtime_error } ics::ID ics::ICS3::getID() { const std::vector<uint8_t> tx {0xFF, 0x00, 0x00, 0x00}; std::vector<uint8_t> rx(5); core->communicateID(tx, rx); return ID {static_cast<uint8_t>(0x1F & rx[4])}; } void ics::ICS3::setID(const ID& id) { std::vector<uint8_t> tx(4, 1), rx(5); tx[0] = 0xE0 | id.get(); // tx[1] == tx[2] == tx[3] == 1 core->communicateID(tx, rx); }
Remove static of vector on ics methods for memory
Remove static of vector on ics methods for memory
C++
bsd-2-clause
forno/libics3,forno/libics3
04eb628fc631d456acca3da79c96a6e820afaf57
src/ifgt.hpp
src/ifgt.hpp
// fgt — fast Gauss transforms // Copyright (C) 2016 Peter J. Gadomski <[email protected]> // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA #include <cstddef> #include "fgt.hpp" namespace fgt { /// Tuning parameters for the IFGT. /// /// In general, you shouldn't need to create these yourself. struct IfgtParameters { /// The number of clusters that should be used for the IFGT. size_t nclusters; /// The cutoff radius. double cutoff_radius; }; /// Chooses appropriate parameters for an IFGT. IfgtParameters ifgt_choose_parameters(size_t cols, double bandwidth, double epsilon, size_t max_num_clusters, size_t truncation_number_ul); /// Chooses the appropriate truncation number for IFGT, given a max clustering /// radius. size_t ifgt_choose_truncation_number(size_t cols, double bandwidth, double epsilon, double max_radius, size_t truncation_number_ul); }
// fgt — fast Gauss transforms // Copyright (C) 2016 Peter J. Gadomski <[email protected]> // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA #pragma once #include <cstddef> #include "fgt.hpp" namespace fgt { /// Tuning parameters for the IFGT. /// /// In general, you shouldn't need to create these yourself. struct IfgtParameters { /// The number of clusters that should be used for the IFGT. size_t nclusters; /// The cutoff radius. double cutoff_radius; }; /// Chooses appropriate parameters for an IFGT. IfgtParameters ifgt_choose_parameters(size_t cols, double bandwidth, double epsilon, size_t max_num_clusters, size_t truncation_number_ul); /// Chooses the appropriate truncation number for IFGT, given a max clustering /// radius. size_t ifgt_choose_truncation_number(size_t cols, double bandwidth, double epsilon, double max_radius, size_t truncation_number_ul); }
Add pragma once to ifgt.hpp
Add pragma once to ifgt.hpp
C++
lgpl-2.1
gadomski/fgt,gadomski/fgt,gadomski/fgt
74e96c9e3f675685e289ecb7792dc39cf2da3944
src/eth/StratumEth.cc
src/eth/StratumEth.cc
/* The MIT License (MIT) Copyright (c) [2016] [BTC.COM] Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "StratumEth.h" #include "Utils.h" #include <glog/logging.h> #include "bitcoin/CommonBitcoin.h" #include <boost/endian/buffers.hpp> static const size_t ETH_HEADER_FIELDS = 13; ///////////////////////////////StratumJobEth/////////////////////////// StratumJobEth::StratumJobEth() : headerNoExtraData_{RLPValue::VARR} { } bool StratumJobEth::initFromGw( const RskWorkEth &work, EthConsensus::Chain chain, uint8_t serverId) { if (work.isInitialized()) { chain_ = chain; height_ = work.getHeight(); parent_ = work.getParent(); networkTarget_ = uint256S(work.getTarget()); headerHash_ = work.getBlockHash(); seedHash_ = work.getSeedHash(); uncles_ = work.getUncles(); transactions_ = work.getTransactions(); gasUsedPercent_ = work.getGasUsedPercent(); rpcAddress_ = work.getRpcAddress(); rpcUserPwd_ = work.getRpcUserPwd(); header_ = work.getHeader(); } return seedHash_.size() && headerHash_.size(); } string StratumJobEth::serializeToJson() const { return Strings::Format( "{\"jobId\":%u" ",\"chain\":\"%s\"" ",\"height\":%u" ",\"parent\":\"%s\"" ",\"networkTarget\":\"0x%s\"" ",\"headerHash\":\"%s\"" ",\"sHash\":\"%s\"" ",\"uncles\":%u" ",\"transactions\":%u" ",\"gasUsedPercent\":%f" "%s" ",\"rpcAddress\":\"%s\"" ",\"rpcUserPwd\":\"%s\"" // backward compatible ",\"rskNetworkTarget\":\"0x%s\"" ",\"rskBlockHashForMergedMining\":\"%s\"" ",\"rskFeesForMiner\":\"\"" ",\"rskdRpcAddress\":\"\"" ",\"rskdRpcUserPwd\":\"\"" ",\"isRskCleanJob\":false" "}", jobId_, EthConsensus::getChainStr(chain_), height_, parent_, networkTarget_.GetHex(), headerHash_, seedHash_, uncles_, transactions_, gasUsedPercent_, header_.empty() ? "" : Strings::Format(",\"header\":\"%s\"", header_), rpcAddress_, rpcUserPwd_, // backward compatible networkTarget_.GetHex(), headerHash_); } bool StratumJobEth::unserializeFromJson(const char *s, size_t len) { JsonNode j; if (!JsonNode::parse(s, s + len, j)) { return false; } if (j["jobId"].type() != Utilities::JS::type::Int || j["chain"].type() != Utilities::JS::type::Str || j["height"].type() != Utilities::JS::type::Int || j["networkTarget"].type() != Utilities::JS::type::Str || j["headerHash"].type() != Utilities::JS::type::Str || j["sHash"].type() != Utilities::JS::type::Str) { LOG(ERROR) << "parse eth stratum job failure: " << s; return false; } jobId_ = j["jobId"].uint64(); chain_ = EthConsensus::getChain(j["chain"].str()); height_ = j["height"].uint64(); networkTarget_ = uint256S(j["networkTarget"].str()); headerHash_ = j["headerHash"].str(); seedHash_ = j["sHash"].str(); if (j["parent"].type() == Utilities::JS::type::Str && j["uncles"].type() == Utilities::JS::type::Int && j["transactions"].type() == Utilities::JS::type::Int && j["gasUsedPercent"].type() == Utilities::JS::type::Real) { parent_ = j["parent"].str(); uncles_ = j["uncles"].uint32(); transactions_ = j["transactions"].uint32(); gasUsedPercent_ = j["gasUsedPercent"].real(); } if (j["header"].type() == Utilities::JS::type::Str) { header_ = HexStripPrefix(j["header"].str()); if (IsHex(header_)) { auto headerBin = ParseHex(header_); size_t consumed = 0; size_t wanted = 0; RLPValue headerValue; if (headerValue.read( &headerBin.front(), headerBin.size(), consumed, wanted) && headerValue.size() == ETH_HEADER_FIELDS && headerValue[ETH_HEADER_FIELDS - 1].type() == RLPValue::VBUF) { for (size_t i = 0; i < ETH_HEADER_FIELDS - 1; ++i) { headerNoExtraData_.push_back(headerValue[i]); } extraData_ = headerValue[ETH_HEADER_FIELDS - 1].get_str(); if (extraData_.size() >= 4 && extraData_.find_first_not_of('\0', extraData_.size() - 4) == std::string::npos) { // Remove the substitutable zeros extraData_ = extraData_.substr(0, extraData_.size() - 4); } } else { LOG(ERROR) << "Decoding RLP failed for block header"; } } else { header_.clear(); } } if (j["rpcAddress"].type() == Utilities::JS::type::Str && j["rpcUserPwd"].type() == Utilities::JS::type::Str) { rpcAddress_ = j["rpcAddress"].str(); rpcUserPwd_ = j["rpcUserPwd"].str(); } return true; } string StratumJobEth::getHeaderWithExtraNonce( uint32_t extraNonce1, const boost::optional<uint32_t> &extraNonce2) const { boost::endian::big_uint32_buf_t extraNonce1Buf{extraNonce1}; RLPValue headerValue{headerNoExtraData_}; std::string extraData{extraData_}; extraData.append(extraNonce1Buf.data(), 4); if (extraNonce2) { boost::endian::big_uint32_buf_t extraNonce2Buf{*extraNonce2}; extraData.append(extraNonce2Buf.data(), 4); } headerValue.push_back(RLPValue{extraData}); return headerValue.write(); } bool StratumJobEth::hasHeader() const { return !headerNoExtraData_.empty(); }
/* The MIT License (MIT) Copyright (c) [2016] [BTC.COM] Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "StratumEth.h" #include "Utils.h" #include <glog/logging.h> #include "bitcoin/CommonBitcoin.h" #include <boost/endian/buffers.hpp> static const size_t ETH_HEADER_FIELDS = 13; ///////////////////////////////StratumJobEth/////////////////////////// StratumJobEth::StratumJobEth() : headerNoExtraData_{RLPValue::VARR} { } bool StratumJobEth::initFromGw( const RskWorkEth &work, EthConsensus::Chain chain, uint8_t serverId) { if (work.isInitialized()) { chain_ = chain; height_ = work.getHeight(); parent_ = work.getParent(); networkTarget_ = uint256S(work.getTarget()); headerHash_ = work.getBlockHash(); seedHash_ = work.getSeedHash(); uncles_ = work.getUncles(); transactions_ = work.getTransactions(); gasUsedPercent_ = work.getGasUsedPercent(); rpcAddress_ = work.getRpcAddress(); rpcUserPwd_ = work.getRpcUserPwd(); header_ = work.getHeader(); } return seedHash_.size() && headerHash_.size(); } string StratumJobEth::serializeToJson() const { return Strings::Format( "{\"jobId\":%u" ",\"chain\":\"%s\"" ",\"height\":%u" ",\"parent\":\"%s\"" ",\"networkTarget\":\"0x%s\"" ",\"headerHash\":\"%s\"" ",\"sHash\":\"%s\"" ",\"uncles\":%u" ",\"transactions\":%u" ",\"gasUsedPercent\":%f" "%s" ",\"rpcAddress\":\"%s\"" ",\"rpcUserPwd\":\"%s\"" // backward compatible ",\"rskNetworkTarget\":\"0x%s\"" ",\"rskBlockHashForMergedMining\":\"%s\"" ",\"rskFeesForMiner\":\"\"" ",\"rskdRpcAddress\":\"\"" ",\"rskdRpcUserPwd\":\"\"" ",\"isRskCleanJob\":false" "}", jobId_, EthConsensus::getChainStr(chain_), height_, parent_, networkTarget_.GetHex(), headerHash_, seedHash_, uncles_, transactions_, gasUsedPercent_, header_.empty() ? "" : Strings::Format(",\"header\":\"%s\"", header_), rpcAddress_, rpcUserPwd_, // backward compatible networkTarget_.GetHex(), headerHash_); } bool StratumJobEth::unserializeFromJson(const char *s, size_t len) { JsonNode j; if (!JsonNode::parse(s, s + len, j)) { return false; } if (j["jobId"].type() != Utilities::JS::type::Int || j["chain"].type() != Utilities::JS::type::Str || j["height"].type() != Utilities::JS::type::Int || j["networkTarget"].type() != Utilities::JS::type::Str || j["headerHash"].type() != Utilities::JS::type::Str || j["sHash"].type() != Utilities::JS::type::Str) { LOG(ERROR) << "parse eth stratum job failure: " << s; return false; } jobId_ = j["jobId"].uint64(); chain_ = EthConsensus::getChain(j["chain"].str()); height_ = j["height"].uint64(); networkTarget_ = uint256S(j["networkTarget"].str()); headerHash_ = j["headerHash"].str(); seedHash_ = j["sHash"].str(); if (j["parent"].type() == Utilities::JS::type::Str && j["uncles"].type() == Utilities::JS::type::Int && j["transactions"].type() == Utilities::JS::type::Int && j["gasUsedPercent"].type() == Utilities::JS::type::Real) { parent_ = j["parent"].str(); uncles_ = j["uncles"].uint32(); transactions_ = j["transactions"].uint32(); gasUsedPercent_ = j["gasUsedPercent"].real(); } if (j["header"].type() == Utilities::JS::type::Str) { header_ = HexStripPrefix(j["header"].str()); if (IsHex(header_)) { auto headerBin = ParseHex(header_); size_t consumed = 0; size_t wanted = 0; RLPValue headerValue; if (headerValue.read( &headerBin.front(), headerBin.size(), consumed, wanted) && headerValue.size() == ETH_HEADER_FIELDS && headerValue[ETH_HEADER_FIELDS - 1].type() == RLPValue::VBUF) { for (size_t i = 0; i < ETH_HEADER_FIELDS - 1; ++i) { headerNoExtraData_.push_back(headerValue[i]); } extraData_ = headerValue[ETH_HEADER_FIELDS - 1].get_str(); if (extraData_.size() >= 4 && extraData_.find_first_not_of('\0', extraData_.size() - 4) == std::string::npos) { // Remove the substitutable zeros extraData_ = extraData_.substr(0, extraData_.size() - 4); } } else { LOG(ERROR) << "Decoding RLP failed for block header"; } } else { header_.clear(); } } if (j["rpcAddress"].type() == Utilities::JS::type::Str && j["rpcUserPwd"].type() == Utilities::JS::type::Str) { rpcAddress_ = j["rpcAddress"].str(); rpcUserPwd_ = j["rpcUserPwd"].str(); } return true; } string StratumJobEth::getHeaderWithExtraNonce( uint32_t extraNonce1, const boost::optional<uint32_t> &extraNonce2) const { boost::endian::big_uint32_buf_t extraNonce1Buf{extraNonce1}; RLPValue headerValue{headerNoExtraData_}; std::string extraData{extraData_}; extraData.append(reinterpret_cast<const char*>(extraNonce1Buf.data()), 4); if (extraNonce2) { boost::endian::big_uint32_buf_t extraNonce2Buf{*extraNonce2}; extraData.append(reinterpret_cast<const char*>(extraNonce2Buf.data()), 4); } headerValue.push_back(RLPValue{extraData}); return headerValue.write(); } bool StratumJobEth::hasHeader() const { return !headerNoExtraData_.empty(); }
Fix build errors with Boost 1.72
Fix build errors with Boost 1.72 Boost 1.72 changed return type of endian buffer data() method to unsigned char* so a cast is needed.
C++
mit
btccom/btcpool,btccom/btcpool,btccom/btcpool,btccom/btcpool,btccom/btcpool,btccom/btcpool,btccom/btcpool,btccom/btcpool
5b891894d7ca8396ee75eb909d2c08036363e18a
src/export_cfg_md.cpp
src/export_cfg_md.cpp
#include "export_cfg_md.h" #include "atoms_md.h" #include "elements.h" #include "print.h" using namespace MAPP_NS; /*-------------------------------------------- --------------------------------------------*/ ExportCFGMD::ExportCFGMD(const std::string& __pattern,int __nevery, std::string* user_vec_names,size_t nuservecs,bool __sort): ExportMD({"elem","x"},__nevery,user_vec_names,nuservecs), pattern(__pattern+".%09d.cfg"), sort(__sort) { if(sort) add_to_default("id"); } /*-------------------------------------------- --------------------------------------------*/ ExportCFGMD::~ExportCFGMD() { } /*-------------------------------------------- --------------------------------------------*/ void ExportCFGMD::write_header(FILE* fp) { if(atoms->comm_rank) return; fprintf(fp,"Number of particles = %d\n",atoms->natms); fprintf(fp,"A = %lf Angstrom (basic length-scale)\n",1.0); for(int i=0;i<__dim__;i++) for(int j=0;j<__dim__;j++) fprintf(fp,"H0(%d,%d) = %lf A\n",i+1,j+1,atoms->H[i][j]); if(x_d_inc) { fprintf(fp,"R = 1.0"); if(sort) fprintf(fp,"entry_count = %d\n",ndims-1); else fprintf(fp,"entry_count = %d\n",ndims-2); vec** usr_vecs=vecs+ndef_vecs; int icmp=0; for(int i=0;i<nusr_vecs;i++) { if(usr_vecs[i]==atoms->x_d) continue; int d=usr_vecs[i]->ndim_dump(); for(int j=0;j<d;j++) fprintf(fp,"auxiliary[%d] = %s_%d [reduced unit]\n",icmp++,usr_vecs[i]->name,j); } } else { fprintf(fp,".NO_VELOCITY.\n"); if(sort) fprintf(fp,"entry_count = %d\n",ndims-2); else fprintf(fp,"entry_count = %d\n",ndims-1); vec** usr_vecs=vecs+ndef_vecs; int icmp=0; for(int i=0;i<nusr_vecs;i++) { int d=usr_vecs[i]->ndim_dump(); for(int j=0;j<d;j++) fprintf(fp,"auxiliary[%d] = %s_%d [reduced unit]\n",icmp++,usr_vecs[i]->name,j); } } } /*-------------------------------------------- --------------------------------------------*/ void ExportCFGMD::write_body_sort(FILE* fp) { gather(vecs,nvecs); if(atoms->comm_rank==0) { atoms->x2s_dump(); if(x_d_inc) atoms->x_d2s_d_dump(); int natms=atoms->natms; unsigned int* id=atoms->id->begin_dump(); unsigned int* id_map=natms==0 ? NULL:new unsigned int[natms]; for(int i=0;i<natms;i++) id_map[id[i]]=i; char** elem_names=atoms->elements.names; type0* masses=atoms->elements.masses; elem_type* elem=atoms->elem->begin_dump(); int curr_elem=-1; int __curr_elem; unsigned int iatm; vec** usr_vecs=vecs+ndef_vecs; for(int i=0;i<natms;i++) { iatm=id_map[i]; __curr_elem=elem[iatm]; if(__curr_elem!=curr_elem) { curr_elem=__curr_elem; fprintf(fp,"%lf\n",masses[curr_elem]); fprintf(fp,"%s\n",elem_names[curr_elem]); } atoms->x->print(fp,iatm); for(int j=0;j<nusr_vecs;j++) usr_vecs[j]->print(fp,iatm); fprintf(fp,"\n"); } delete [] id_map; } release(vecs,nvecs); } /*-------------------------------------------- --------------------------------------------*/ void ExportCFGMD::write_body(FILE* fp) { gather(vecs,nvecs); if(atoms->comm_rank==0) { atoms->x2s_dump(); if(x_d_inc) atoms->x_d2s_d_dump(); int natms=atoms->natms; char** elem_names=atoms->elements.names; type0* masses=atoms->elements.masses; elem_type* elem=atoms->elem->begin_dump(); int curr_elem=-1; int __curr_elem; vec** usr_vecs=vecs+ndef_vecs; for(int i=0;i<natms;i++) { __curr_elem=elem[i]; if(__curr_elem!=curr_elem) { curr_elem=__curr_elem; fprintf(fp,"%lf\n",masses[curr_elem]); fprintf(fp,"%s\n",elem_names[curr_elem]); } atoms->x->print(fp,i); for(int j=0;j<nusr_vecs;j++) usr_vecs[j]->print(fp,i); fprintf(fp,"\n"); } } release(vecs,nvecs); } /*-------------------------------------------- --------------------------------------------*/ void ExportCFGMD::init() { try { find_vecs(atoms); } catch(std::string& err_msg) { throw err_msg; } x_d_inc=false; for(int i=0;i<nvecs && !x_d_inc;i++) if(std::strcmp(vec_names[i].c_str(),"x_d")==0) x_d_inc=true; } /*-------------------------------------------- --------------------------------------------*/ void ExportCFGMD::fin() { } /*-------------------------------------------- --------------------------------------------*/ void ExportCFGMD::write(int stps) { /* we have a list of vectors defaults user defined ones some vectors will just send their regular others will need preparing */ char* file_name=Print::vprintf(pattern.c_str(),stps); FILE* fp=NULL; if(atoms->comm_rank==0) fp=fopen(file_name,"w"); delete [] file_name; write_header(fp); if(sort) write_body_sort(fp); else write_body(fp); if(atoms->comm_rank==0) fclose(fp); } /*------------------------------------------------------------------------------------------------------------------------------------ ------------------------------------------------------------------------------------------------------------------------------------*/ PyObject* ExportCFGMD::__new__(PyTypeObject* type,PyObject* args,PyObject* kwds) { Object* __self=reinterpret_cast<Object*>(type->tp_alloc(type,0)); PyObject* self=reinterpret_cast<PyObject*>(__self); return self; } /*-------------------------------------------- --------------------------------------------*/ int ExportCFGMD::__init__(PyObject* self,PyObject* args,PyObject* kwds) { FuncAPI<std::string,int,std::string*,bool> f("__init__",{"file_pattern","nevery","extra_vecs","sort"}); f.noptionals=3; f.logics<1>()[0]=VLogics("gt",0); f.val<3>()=false; f.val<1>()=10000; if(f(args,kwds)==-1) return -1; Object* __self=reinterpret_cast<Object*>(self); __self->xprt=new ExportCFGMD(f.val<0>(),f.val<1>(),f.val<2>(),f.v<2>().size,f.val<3>()); return 0; } /*-------------------------------------------- --------------------------------------------*/ PyObject* ExportCFGMD::__alloc__(PyTypeObject* type,Py_ssize_t) { Object* __self=new Object; __self->ob_type=type; __self->ob_refcnt=1; __self->xprt=NULL; return reinterpret_cast<PyObject*>(__self); } /*-------------------------------------------- --------------------------------------------*/ void ExportCFGMD::__dealloc__(PyObject* self) { Object* __self=reinterpret_cast<Object*>(self); delete __self->xprt; __self->xprt=NULL; delete __self; } /*--------------------------------------------*/ PyTypeObject ExportCFGMD::TypeObject={PyObject_HEAD_INIT(NULL)}; /*--------------------------------------------*/ void ExportCFGMD::setup_tp() { TypeObject.tp_name="mapp.md.export_cfg"; TypeObject.tp_doc="export atomeye"; TypeObject.tp_flags=Py_TPFLAGS_DEFAULT; TypeObject.tp_basicsize=sizeof(Object); TypeObject.tp_new=__new__; TypeObject.tp_init=__init__; TypeObject.tp_alloc=__alloc__; TypeObject.tp_dealloc=__dealloc__; setup_tp_methods(); TypeObject.tp_methods=methods; setup_tp_getset(); TypeObject.tp_getset=getset; TypeObject.tp_base=&ExportMD::TypeObject; } /*--------------------------------------------*/ PyGetSetDef ExportCFGMD::getset[]={[0 ... 2]={NULL,NULL,NULL,NULL,NULL}}; /*--------------------------------------------*/ void ExportCFGMD::setup_tp_getset() { getset_deafult_vecs(getset[0]); getset_extra_vecs(getset[1]); } /*--------------------------------------------*/ PyMethodDef ExportCFGMD::methods[]={[0 ... 0]={NULL}}; /*--------------------------------------------*/ void ExportCFGMD::setup_tp_methods() { }
#include "export_cfg_md.h" #include "atoms_md.h" #include "elements.h" #include "print.h" using namespace MAPP_NS; /*-------------------------------------------- --------------------------------------------*/ ExportCFGMD::ExportCFGMD(const std::string& __pattern,int __nevery, std::string* user_vec_names,size_t nuservecs,bool __sort): ExportMD({"elem","x"},__nevery,user_vec_names,nuservecs), pattern(__pattern+".%09d.cfg"), sort(__sort) { if(sort) add_to_default("id"); } /*-------------------------------------------- --------------------------------------------*/ ExportCFGMD::~ExportCFGMD() { } /*-------------------------------------------- --------------------------------------------*/ void ExportCFGMD::write_header(FILE* fp) { if(atoms->comm_rank) return; fprintf(fp,"Number of particles = %d\n",atoms->natms); fprintf(fp,"A = %lf Angstrom (basic length-scale)\n",1.0); for(int i=0;i<__dim__;i++) for(int j=0;j<__dim__;j++) fprintf(fp,"H0(%d,%d) = %lf A\n",i+1,j+1,atoms->H[i][j]); if(x_d_inc) fprintf(fp,"R = 1.0"); else fprintf(fp,".NO_VELOCITY.\n"); if(sort) fprintf(fp,"entry_count = %d\n",ndims-1); else fprintf(fp,"entry_count = %d\n",ndims-2); vec** usr_vecs=vecs+ndef_vecs; int icmp=0; for(int i=0;i<nusr_vecs;i++) { if(usr_vecs[i]==atoms->x_d) continue; int d=usr_vecs[i]->ndim_dump(); for(int j=0;j<d;j++) fprintf(fp,"auxiliary[%d] = %s_%d [reduced unit]\n",icmp++,usr_vecs[i]->name,j); } } /*-------------------------------------------- --------------------------------------------*/ void ExportCFGMD::write_body_sort(FILE* fp) { gather(vecs,nvecs); if(atoms->comm_rank==0) { atoms->x2s_dump(); if(x_d_inc) atoms->x_d2s_d_dump(); int natms=atoms->natms; unsigned int* id=atoms->id->begin_dump(); unsigned int* id_map=natms==0 ? NULL:new unsigned int[natms]; for(int i=0;i<natms;i++) id_map[id[i]]=i; char** elem_names=atoms->elements.names; type0* masses=atoms->elements.masses; elem_type* elem=atoms->elem->begin_dump(); int curr_elem=-1; int __curr_elem; unsigned int iatm; vec** usr_vecs=vecs+ndef_vecs; for(int i=0;i<natms;i++) { iatm=id_map[i]; __curr_elem=elem[iatm]; if(__curr_elem!=curr_elem) { curr_elem=__curr_elem; fprintf(fp,"%lf\n",masses[curr_elem]); fprintf(fp,"%s\n",elem_names[curr_elem]); } atoms->x->print(fp,iatm); for(int j=0;j<nusr_vecs;j++) usr_vecs[j]->print(fp,iatm); fprintf(fp,"\n"); } delete [] id_map; } release(vecs,nvecs); } /*-------------------------------------------- --------------------------------------------*/ void ExportCFGMD::write_body(FILE* fp) { gather(vecs,nvecs); if(atoms->comm_rank==0) { atoms->x2s_dump(); if(x_d_inc) atoms->x_d2s_d_dump(); int natms=atoms->natms; char** elem_names=atoms->elements.names; type0* masses=atoms->elements.masses; elem_type* elem=atoms->elem->begin_dump(); int curr_elem=-1; int __curr_elem; vec** usr_vecs=vecs+ndef_vecs; for(int i=0;i<natms;i++) { __curr_elem=elem[i]; if(__curr_elem!=curr_elem) { curr_elem=__curr_elem; fprintf(fp,"%lf\n",masses[curr_elem]); fprintf(fp,"%s\n",elem_names[curr_elem]); } atoms->x->print(fp,i); for(int j=0;j<nusr_vecs;j++) usr_vecs[j]->print(fp,i); fprintf(fp,"\n"); } } release(vecs,nvecs); } /*-------------------------------------------- --------------------------------------------*/ void ExportCFGMD::init() { try { find_vecs(atoms); } catch(std::string& err_msg) { throw err_msg; } x_d_inc=false; for(int i=0;i<nvecs && !x_d_inc;i++) if(std::strcmp(vec_names[i].c_str(),"x_d")==0) x_d_inc=true; } /*-------------------------------------------- --------------------------------------------*/ void ExportCFGMD::fin() { } /*-------------------------------------------- --------------------------------------------*/ void ExportCFGMD::write(int stps) { /* we have a list of vectors defaults user defined ones some vectors will just send its regular content while others will need some preparing */ char* file_name=Print::vprintf(pattern.c_str(),stps); FILE* fp=NULL; if(atoms->comm_rank==0) fp=fopen(file_name,"w"); delete [] file_name; write_header(fp); if(sort) write_body_sort(fp); else write_body(fp); if(atoms->comm_rank==0) fclose(fp); } /*------------------------------------------------------------------------------------------------------------------------------------ ------------------------------------------------------------------------------------------------------------------------------------*/ PyObject* ExportCFGMD::__new__(PyTypeObject* type,PyObject* args,PyObject* kwds) { Object* __self=reinterpret_cast<Object*>(type->tp_alloc(type,0)); PyObject* self=reinterpret_cast<PyObject*>(__self); return self; } /*-------------------------------------------- --------------------------------------------*/ int ExportCFGMD::__init__(PyObject* self,PyObject* args,PyObject* kwds) { FuncAPI<std::string,int,std::string*,bool> f("__init__",{"file_pattern","nevery","extra_vecs","sort"}); f.noptionals=3; f.logics<1>()[0]=VLogics("gt",0); f.val<3>()=false; f.val<1>()=10000; if(f(args,kwds)==-1) return -1; Object* __self=reinterpret_cast<Object*>(self); __self->xprt=new ExportCFGMD(f.val<0>(),f.val<1>(),f.val<2>(),f.v<2>().size,f.val<3>()); return 0; } /*-------------------------------------------- --------------------------------------------*/ PyObject* ExportCFGMD::__alloc__(PyTypeObject* type,Py_ssize_t) { Object* __self=new Object; __self->ob_type=type; __self->ob_refcnt=1; __self->xprt=NULL; return reinterpret_cast<PyObject*>(__self); } /*-------------------------------------------- --------------------------------------------*/ void ExportCFGMD::__dealloc__(PyObject* self) { Object* __self=reinterpret_cast<Object*>(self); delete __self->xprt; __self->xprt=NULL; delete __self; } /*--------------------------------------------*/ PyTypeObject ExportCFGMD::TypeObject={PyObject_HEAD_INIT(NULL)}; /*--------------------------------------------*/ void ExportCFGMD::setup_tp() { TypeObject.tp_name="mapp.md.export_cfg"; TypeObject.tp_doc="export atomeye"; TypeObject.tp_flags=Py_TPFLAGS_DEFAULT; TypeObject.tp_basicsize=sizeof(Object); TypeObject.tp_new=__new__; TypeObject.tp_init=__init__; TypeObject.tp_alloc=__alloc__; TypeObject.tp_dealloc=__dealloc__; setup_tp_methods(); TypeObject.tp_methods=methods; setup_tp_getset(); TypeObject.tp_getset=getset; TypeObject.tp_base=&ExportMD::TypeObject; } /*--------------------------------------------*/ PyGetSetDef ExportCFGMD::getset[]={[0 ... 2]={NULL,NULL,NULL,NULL,NULL}}; /*--------------------------------------------*/ void ExportCFGMD::setup_tp_getset() { getset_deafult_vecs(getset[0]); getset_extra_vecs(getset[1]); } /*--------------------------------------------*/ PyMethodDef ExportCFGMD::methods[]={[0 ... 0]={NULL}}; /*--------------------------------------------*/ void ExportCFGMD::setup_tp_methods() { }
clean up
clean up
C++
mit
sinamoeini/mapp4py,sinamoeini/mapp4py,sinamoeini/mapp4py,sinamoeini/mapp4py
38e508853c9b89c75affbdc559f3b0017e99119c
src/filters/Stats.cpp
src/filters/Stats.cpp
/****************************************************************************** * Copyright (c) 2011, Michael P. Gerlek ([email protected]) * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following * conditions are met: * * * 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 Hobu, Inc. or Flaxen Geo Consulting nor the * names of its contributors may be used to endorse or promote * products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. ****************************************************************************/ #include <pdal/filters/Stats.hpp> #include <pdal/Utils.hpp> #include <pdal/PointBuffer.hpp> #include <boost/algorithm/string.hpp> namespace pdal { namespace filters { //--------------------------------------------------------------------------- namespace stats { boost::property_tree::ptree Summary::toPTree() const { boost::property_tree::ptree tree; boost::uint32_t cnt = static_cast<boost::uint32_t>(count()); tree.put("count", cnt); tree.put("minimum", minimum()); tree.put("maximum", maximum()); tree.put("average", average()); boost::property_tree::ptree bins; histogram_type hist = histogram(); for(boost::int32_t i = 0; i < hist.size(); ++i) { boost::property_tree::ptree bin; bin.add("lower_bound", hist[i].first); bin.add("count", Utils::sround(hist[i].second*cnt)); std::ostringstream binname; binname << "bin-" <<i; bins.add_child(binname.str(), bin ); } tree.add_child("histogram", bins); std::ostringstream sample; for(std::vector<double>::size_type i =0; i < m_sample.size(); ++i) { sample << m_sample[i] << " "; }; tree.add("sample", sample.str()); return tree; } } // namespace stats //--------------------------------------------------------------------------- Stats::Stats(Stage& prevStage, const Options& options) : pdal::Filter(prevStage, options) { return; } Stats::Stats(Stage& prevStage) : Filter(prevStage, Options::none()) { return; } Stats::~Stats() { } void Stats::initialize() { Filter::initialize(); return; } const Options Stats::getDefaultOptions() const { Options options; Option sample_size("sample_size", 1000, "Number of points to return for uniform random 'sample'"); Option num_bins("num_bins", 20, "Number of bins to use for histogram"); Option stats_cache_size("stats_cache_size", 1000, "Number of points to use for histogram bin determination. Defaults to total number of points read if no option is specified."); Option seed("seed", 0, "Seed to use for repeatable random sample. A seed value of 0 means no seed is used"); options.add(sample_size); options.add(num_bins); options.add(stats_cache_size); options.add(seed); return options; } pdal::StageSequentialIterator* Stats::createSequentialIterator(PointBuffer& buffer) const { return new pdal::filters::iterators::sequential::Stats(*this, buffer); } namespace iterators { namespace sequential { Stats::Stats(const pdal::filters::Stats& filter, PointBuffer& buffer) : pdal::FilterSequentialIterator(filter, buffer) , m_statsFilter(filter) { return; } boost::uint32_t Stats::readBufferImpl(PointBuffer& data) { const boost::uint32_t numRead = getPrevIterator().read(data); const boost::uint32_t numPoints = data.getNumPoints(); for (boost::uint32_t pointIndex=0; pointIndex < numPoints; pointIndex++) { std::multimap<DimensionPtr, stats::SummaryPtr>::const_iterator p; for (p = m_stats.begin(); p != m_stats.end(); ++p) { DimensionPtr d = p->first; stats::SummaryPtr c = p->second; double output = getValue(data, *d, pointIndex); c->insert(output); } } return numRead; } double Stats::getValue(PointBuffer& data, Dimension& d, boost::uint32_t pointIndex) { double output(0.0); float flt(0.0); boost::int8_t i8(0); boost::uint8_t u8(0); boost::int16_t i16(0); boost::uint16_t u16(0); boost::int32_t i32(0); boost::uint32_t u32(0); boost::int64_t i64(0); boost::uint64_t u64(0); switch (d.getInterpretation()) { case dimension::SignedByte: i8 = data.getField<boost::int8_t>(d, pointIndex); output = d.applyScaling<boost::int8_t>(i8); break; case dimension::UnsignedByte: u8 = data.getField<boost::uint8_t>(d, pointIndex); output = d.applyScaling<boost::uint8_t>(u8); break; case dimension::Float: if (d.getByteSize() == 4) { flt = data.getField<float>(d, pointIndex); output = static_cast<double>(flt); break; } else if (d.getByteSize() == 8) { output = data.getField<double>(d, pointIndex); break; } else { std::ostringstream oss; oss << "Unable to interpret Float of size '" << d.getByteSize() <<"'"; throw pdal_error(oss.str()); } case dimension::SignedInteger: if (d.getByteSize() == 1) { i8 = data.getField<boost::int8_t>(d, pointIndex); output = d.applyScaling<boost::int8_t>(i8); break; } else if (d.getByteSize() == 2) { i16 = data.getField<boost::int16_t>(d, pointIndex); output = d.applyScaling<boost::int16_t>(i16); break; } else if (d.getByteSize() == 4) { i32 = data.getField<boost::int32_t>(d, pointIndex); output = d.applyScaling<boost::int32_t>(i32); break; } else if (d.getByteSize() == 8) { i64 = data.getField<boost::int64_t>(d, pointIndex); output = d.applyScaling<boost::int64_t>(i64); break; } else { std::ostringstream oss; oss << "Unable to interpret SignedInteger of size '" << d.getByteSize() <<"'"; throw pdal_error(oss.str()); } case dimension::UnsignedInteger: if (d.getByteSize() == 1) { u8 = data.getField<boost::uint8_t>(d, pointIndex); output = d.applyScaling<boost::uint8_t>(u8); break; } else if (d.getByteSize() == 2) { u16 = data.getField<boost::uint16_t>(d, pointIndex); output = d.applyScaling<boost::uint16_t>(u16); break; } else if (d.getByteSize() == 4) { u32 = data.getField<boost::uint32_t>(d, pointIndex); output = d.applyScaling<boost::uint32_t>(u32); break; } else if (d.getByteSize() == 8) { u64 = data.getField<boost::uint64_t>(d, pointIndex); output = d.applyScaling<boost::uint64_t>(u64); break; } else { std::ostringstream oss; oss << "Unable to interpret UnsignedInteger of size '" << d.getByteSize() <<"'"; throw pdal_error(oss.str()); } case dimension::Pointer: // stored as 64 bits, even on a 32-bit box case dimension::Undefined: throw pdal_error("Dimension data type unable to be summarized"); } return output; } boost::uint64_t Stats::skipImpl(boost::uint64_t count) { getPrevIterator().skip(count); return count; } bool Stats::atEndImpl() const { return getPrevIterator().atEnd(); } void Stats::readBufferBeginImpl(PointBuffer& buffer) { // We'll assume you're not changing the schema per-read call if (m_stats.size() == 0) { Schema const& schema = buffer.getSchema(); boost::uint64_t numPoints = getStage().getPrevStage().getNumPoints(); boost::uint32_t stats_cache_size(1000); try { stats_cache_size = getStage().getOptions().getValueOrThrow<boost::uint32_t>("stats_cache_size"); getStage().log()->get(logDEBUG2) << "Using " << stats_cache_size << "for histogram cache size set from option" << std::endl; } catch (pdal::option_not_found const&) { if (numPoints != 0) { stats_cache_size = numPoints; getStage().log()->get(logDEBUG2) << "Using point count, " << numPoints << ", for histogram cache size" << std::endl; } } boost::uint32_t sample_size = getStage().getOptions().getValueOrDefault<boost::uint32_t>("sample_size", 1000); boost::uint32_t seed = getStage().getOptions().getValueOrDefault<boost::uint32_t>("seed", 0); getStage().log()->get(logDEBUG2) << "Using " << sample_size << " for sample size" << std::endl; getStage().log()->get(logDEBUG2) << "Using " << seed << " for sample seed" << std::endl; boost::uint32_t bin_count = getStage().getOptions().getValueOrDefault<boost::uint32_t>("num_bins", 20); schema::index_by_index const& dims = schema.getDimensions().get<schema::index>(); for (schema::index_by_index::const_iterator iter = dims.begin(); iter != dims.end(); ++iter) { DimensionPtr d = boost::shared_ptr<Dimension>(new Dimension( *iter)); getStage().log()->get(logDEBUG2) << "Cumulating stats for dimension " << d->getName() << std::endl; stats::SummaryPtr c = boost::shared_ptr<stats::Summary>(new stats::Summary(bin_count, sample_size, stats_cache_size)); std::pair<DimensionPtr, stats::SummaryPtr> p(d,c); m_dimensions.push_back(d); m_stats.insert(p); } } } boost::property_tree::ptree Stats::toPTree() const { boost::property_tree::ptree tree; std::vector<DimensionPtr>::const_iterator p; boost::uint32_t position(0); for (p = m_dimensions.begin(); p != m_dimensions.end(); ++p) { std::multimap<DimensionPtr, stats::SummaryPtr>::const_iterator i; DimensionPtr d = *p; i = m_stats.find(d); if (i == m_stats.end()) throw pdal_error("unable to find dimension in summary!"); const stats::SummaryPtr stat = i->second; boost::property_tree::ptree subtree = stat->toPTree(); subtree.add("position", position); tree.add_child(d->getName(), subtree); position++; } return tree; } stats::Summary const& Stats::getStats(Dimension const& dim) const { // FIXME: do this smarter std::multimap<DimensionPtr, stats::SummaryPtr>::const_iterator p; for (p = m_stats.begin(); p != m_stats.end(); ++p) { if (dim == *p->first) return *p->second; } std::ostringstream oss; oss <<"Dimension with name '" << dim.getName() << "' not found"; throw pdal_error(oss.str()); } void Stats::reset() { m_stats.clear(); } } } // iterators::sequential } } // namespaces
/****************************************************************************** * Copyright (c) 2011, Michael P. Gerlek ([email protected]) * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following * conditions are met: * * * 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 Hobu, Inc. or Flaxen Geo Consulting nor the * names of its contributors may be used to endorse or promote * products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. ****************************************************************************/ #include <pdal/filters/Stats.hpp> #include <pdal/Utils.hpp> #include <pdal/PointBuffer.hpp> #include <boost/algorithm/string.hpp> namespace pdal { namespace filters { //--------------------------------------------------------------------------- namespace stats { boost::property_tree::ptree Summary::toPTree() const { boost::property_tree::ptree tree; boost::uint32_t cnt = static_cast<boost::uint32_t>(count()); tree.put("count", cnt); tree.put("minimum", minimum()); tree.put("maximum", maximum()); tree.put("average", average()); boost::property_tree::ptree bins; histogram_type hist = histogram(); for(boost::int32_t i = 0; i < hist.size(); ++i) { boost::property_tree::ptree bin; bin.add("lower_bound", hist[i].first); bin.add("count", Utils::sround(hist[i].second*cnt)); std::ostringstream binname; binname << "bin-" <<i; bins.add_child(binname.str(), bin ); } tree.add_child("histogram", bins); std::ostringstream sample; for(std::vector<double>::size_type i =0; i < m_sample.size(); ++i) { sample << m_sample[i] << " "; }; tree.add("sample", sample.str()); return tree; } } // namespace stats //--------------------------------------------------------------------------- Stats::Stats(Stage& prevStage, const Options& options) : pdal::Filter(prevStage, options) { return; } Stats::Stats(Stage& prevStage) : Filter(prevStage, Options::none()) { return; } Stats::~Stats() { } void Stats::initialize() { Filter::initialize(); return; } const Options Stats::getDefaultOptions() const { Options options; Option sample_size("sample_size", 1000, "Number of points to return for uniform random 'sample'"); Option num_bins("num_bins", 20, "Number of bins to use for histogram"); Option stats_cache_size("stats_cache_size", 1000, "Number of points to use for histogram bin determination. Defaults to total number of points read if no option is specified."); Option seed("seed", 0, "Seed to use for repeatable random sample. A seed value of 0 means no seed is used"); options.add(sample_size); options.add(num_bins); options.add(stats_cache_size); options.add(seed); return options; } pdal::StageSequentialIterator* Stats::createSequentialIterator(PointBuffer& buffer) const { return new pdal::filters::iterators::sequential::Stats(*this, buffer); } namespace iterators { namespace sequential { Stats::Stats(const pdal::filters::Stats& filter, PointBuffer& buffer) : pdal::FilterSequentialIterator(filter, buffer) , m_statsFilter(filter) { return; } boost::uint32_t Stats::readBufferImpl(PointBuffer& data) { const boost::uint32_t numRead = getPrevIterator().read(data); const boost::uint32_t numPoints = data.getNumPoints(); for (boost::uint32_t pointIndex=0; pointIndex < numPoints; pointIndex++) { std::multimap<DimensionPtr, stats::SummaryPtr>::const_iterator p; for (p = m_stats.begin(); p != m_stats.end(); ++p) { DimensionPtr d = p->first; stats::SummaryPtr c = p->second; double output = getValue(data, *d, pointIndex); c->insert(output); } } return numRead; } double Stats::getValue(PointBuffer& data, Dimension& d, boost::uint32_t pointIndex) { double output(0.0); float flt(0.0); boost::int8_t i8(0); boost::uint8_t u8(0); boost::int16_t i16(0); boost::uint16_t u16(0); boost::int32_t i32(0); boost::uint32_t u32(0); boost::int64_t i64(0); boost::uint64_t u64(0); switch (d.getInterpretation()) { case dimension::SignedByte: i8 = data.getField<boost::int8_t>(d, pointIndex); output = d.applyScaling<boost::int8_t>(i8); break; case dimension::UnsignedByte: u8 = data.getField<boost::uint8_t>(d, pointIndex); output = d.applyScaling<boost::uint8_t>(u8); break; case dimension::Float: if (d.getByteSize() == 4) { flt = data.getField<float>(d, pointIndex); output = static_cast<double>(flt); break; } else if (d.getByteSize() == 8) { output = data.getField<double>(d, pointIndex); break; } else { std::ostringstream oss; oss << "Unable to interpret Float of size '" << d.getByteSize() <<"'"; throw pdal_error(oss.str()); } case dimension::SignedInteger: if (d.getByteSize() == 1) { i8 = data.getField<boost::int8_t>(d, pointIndex); output = d.applyScaling<boost::int8_t>(i8); break; } else if (d.getByteSize() == 2) { i16 = data.getField<boost::int16_t>(d, pointIndex); output = d.applyScaling<boost::int16_t>(i16); break; } else if (d.getByteSize() == 4) { i32 = data.getField<boost::int32_t>(d, pointIndex); output = d.applyScaling<boost::int32_t>(i32); break; } else if (d.getByteSize() == 8) { i64 = data.getField<boost::int64_t>(d, pointIndex); output = d.applyScaling<boost::int64_t>(i64); break; } else { std::ostringstream oss; oss << "Unable to interpret SignedInteger of size '" << d.getByteSize() <<"'"; throw pdal_error(oss.str()); } case dimension::UnsignedInteger: if (d.getByteSize() == 1) { u8 = data.getField<boost::uint8_t>(d, pointIndex); output = d.applyScaling<boost::uint8_t>(u8); break; } else if (d.getByteSize() == 2) { u16 = data.getField<boost::uint16_t>(d, pointIndex); output = d.applyScaling<boost::uint16_t>(u16); break; } else if (d.getByteSize() == 4) { u32 = data.getField<boost::uint32_t>(d, pointIndex); output = d.applyScaling<boost::uint32_t>(u32); break; } else if (d.getByteSize() == 8) { u64 = data.getField<boost::uint64_t>(d, pointIndex); output = d.applyScaling<boost::uint64_t>(u64); break; } else { std::ostringstream oss; oss << "Unable to interpret UnsignedInteger of size '" << d.getByteSize() <<"'"; throw pdal_error(oss.str()); } case dimension::Pointer: // stored as 64 bits, even on a 32-bit box case dimension::Undefined: throw pdal_error("Dimension data type unable to be summarized"); } return output; } boost::uint64_t Stats::skipImpl(boost::uint64_t count) { getPrevIterator().skip(count); return count; } bool Stats::atEndImpl() const { return getPrevIterator().atEnd(); } void Stats::readBufferBeginImpl(PointBuffer& buffer) { // We'll assume you're not changing the schema per-read call if (m_stats.size() == 0) { Schema const& schema = buffer.getSchema(); boost::uint64_t numPoints = getStage().getPrevStage().getNumPoints(); boost::uint32_t stats_cache_size(1000); try { stats_cache_size = getStage().getOptions().getValueOrThrow<boost::uint32_t>("stats_cache_size"); getStage().log()->get(logDEBUG2) << "Using " << stats_cache_size << "for histogram cache size set from option" << std::endl; } catch (pdal::option_not_found const&) { if (numPoints != 0) { if (numPoints > (std::numeric_limits<boost::uint32_t>::max)()) { throw std::out_of_range("too many points for the histogram cache"); } stats_cache_size = static_cast<boost::uint32_t>(numPoints); getStage().log()->get(logDEBUG2) << "Using point count, " << numPoints << ", for histogram cache size" << std::endl; } } boost::uint32_t sample_size = getStage().getOptions().getValueOrDefault<boost::uint32_t>("sample_size", 1000); boost::uint32_t seed = getStage().getOptions().getValueOrDefault<boost::uint32_t>("seed", 0); getStage().log()->get(logDEBUG2) << "Using " << sample_size << " for sample size" << std::endl; getStage().log()->get(logDEBUG2) << "Using " << seed << " for sample seed" << std::endl; boost::uint32_t bin_count = getStage().getOptions().getValueOrDefault<boost::uint32_t>("num_bins", 20); schema::index_by_index const& dims = schema.getDimensions().get<schema::index>(); for (schema::index_by_index::const_iterator iter = dims.begin(); iter != dims.end(); ++iter) { DimensionPtr d = boost::shared_ptr<Dimension>(new Dimension( *iter)); getStage().log()->get(logDEBUG2) << "Cumulating stats for dimension " << d->getName() << std::endl; stats::SummaryPtr c = boost::shared_ptr<stats::Summary>(new stats::Summary(bin_count, sample_size, stats_cache_size)); std::pair<DimensionPtr, stats::SummaryPtr> p(d,c); m_dimensions.push_back(d); m_stats.insert(p); } } } boost::property_tree::ptree Stats::toPTree() const { boost::property_tree::ptree tree; std::vector<DimensionPtr>::const_iterator p; boost::uint32_t position(0); for (p = m_dimensions.begin(); p != m_dimensions.end(); ++p) { std::multimap<DimensionPtr, stats::SummaryPtr>::const_iterator i; DimensionPtr d = *p; i = m_stats.find(d); if (i == m_stats.end()) throw pdal_error("unable to find dimension in summary!"); const stats::SummaryPtr stat = i->second; boost::property_tree::ptree subtree = stat->toPTree(); subtree.add("position", position); tree.add_child(d->getName(), subtree); position++; } return tree; } stats::Summary const& Stats::getStats(Dimension const& dim) const { // FIXME: do this smarter std::multimap<DimensionPtr, stats::SummaryPtr>::const_iterator p; for (p = m_stats.begin(); p != m_stats.end(); ++p) { if (dim == *p->first) return *p->second; } std::ostringstream oss; oss <<"Dimension with name '" << dim.getName() << "' not found"; throw pdal_error(oss.str()); } void Stats::reset() { m_stats.clear(); } } } // iterators::sequential } } // namespaces
add bounds check
add bounds check
C++
bsd-3-clause
verma/PDAL,Sciumo/PDAL,mtCarto/PDAL,lucadelu/PDAL,DougFirErickson/PDAL,Sciumo/PDAL,lucadelu/PDAL,verma/PDAL,Sciumo/PDAL,mpgerlek/PDAL-old,verma/PDAL,jwomeara/PDAL,mtCarto/PDAL,verma/PDAL,radiantbluetechnologies/PDAL,mtCarto/PDAL,boundlessgeo/PDAL,DougFirErickson/PDAL,mtCarto/PDAL,mpgerlek/PDAL-old,DougFirErickson/PDAL,DougFirErickson/PDAL,boundlessgeo/PDAL,jwomeara/PDAL,Sciumo/PDAL,verma/PDAL,radiantbluetechnologies/PDAL,verma/PDAL,radiantbluetechnologies/PDAL,boundlessgeo/PDAL,boundlessgeo/PDAL,mpgerlek/PDAL-old,radiantbluetechnologies/PDAL,lucadelu/PDAL,lucadelu/PDAL,jwomeara/PDAL,verma/PDAL,jwomeara/PDAL,mpgerlek/PDAL-old
dbc6472e943ab482f926af5608500d5ac3994284
src/autowiring/test/CoreContextTest.cpp
src/autowiring/test/CoreContextTest.cpp
// Copyright (C) 2012-2015 Leap Motion, Inc. All rights reserved. #include "stdafx.h" #include <autowiring/AutoInjectable.h> #include <autowiring/ContextEnumerator.h> #include <algorithm> #include <set> #include THREAD_HEADER #include FUTURE_HEADER class CoreContextTest: public testing::Test {}; class Foo{}; class Bar{}; class Baz{}; TEST_F(CoreContextTest, TestEnumerateChildren) { AutoCurrentContext ctxt; // Create a few anonymous children: AutoCreateContext child1; AutoCreateContext child2; AutoCreateContext child3; // Enumerate and see what we get back: std::set<std::shared_ptr<CoreContext>> allChildren; for(const auto& cur : CurrentContextEnumerator()) allChildren.insert(cur); // Verify we get exactly four back: ASSERT_EQ(4UL, allChildren.size()) << "Failed to enumerate the correct number of child contexts"; // Verify full membership: ASSERT_EQ(1UL, allChildren.count(ctxt)) << "Failed to find the root context in the returned context collection"; const char* childMissing = "Failed to find a child context in the set of children"; ASSERT_EQ(1UL, allChildren.count(child1)) << childMissing; ASSERT_EQ(1UL, allChildren.count(child2)) << childMissing; ASSERT_EQ(1UL, allChildren.count(child3)) << childMissing; //Check if filtering by sigil works AutoCreateContextT<Foo> fooCtxt; AutoCreateContextT<Bar> barCtxt; auto childFoo = barCtxt->Create<Foo>(); ContextEnumeratorT<Foo> enumerator1(ctxt); std::vector<std::shared_ptr<CoreContext>> onlyFoos(enumerator1.begin(), enumerator1.end()); ASSERT_EQ(2UL, onlyFoos.size()) << "Didn't collect only contexts with 'Foo' sigil"; ASSERT_NE(std::find(onlyFoos.begin(), onlyFoos.end(), fooCtxt), onlyFoos.end()) << "Context not enumerated"; ASSERT_NE(std::find(onlyFoos.begin(), onlyFoos.end(), childFoo), onlyFoos.end()) << "Context not enumerated"; ContextEnumeratorT<Bar> enumerator2(ctxt); std::vector<std::shared_ptr<CoreContext>> onlyBars(enumerator2.begin(), enumerator2.end()); ASSERT_EQ(1UL, onlyBars.size()) << "Didn't collect only contexts with 'Bar' sigil"; ASSERT_NE(std::find(onlyBars.begin(), onlyBars.end(), barCtxt), onlyBars.end()) << "Context not enumerated"; ContextEnumeratorT<Baz> enumerator3(ctxt); std::vector<std::shared_ptr<CoreContext>> noBaz(enumerator3.begin(), enumerator3.end()); ASSERT_TRUE(noBaz.empty()) << "Incorrectly collected contexts with 'Baz' sigil"; } TEST_F(CoreContextTest, TestEarlyLambdaReturn) { AutoCurrentContext ctxt; // Create three children: AutoCreateContext child1; AutoCreateContext child2; AutoCreateContext child3; // Enumerate, but stop after three: std::vector<std::shared_ptr<CoreContext>> allChildren; size_t totalSoFar = 0; for(const auto& ctxt : CurrentContextEnumerator()) { if(totalSoFar++ == 3) break; allChildren.push_back(ctxt); } ASSERT_EQ(3UL, allChildren.size()) << "Enumeration routine failed to quit early"; // Verify that the root context is the first one enumerated--needed to assure that we are executing a depth-first search ASSERT_EQ(ctxt, allChildren[0]) << "EnumerateChildContexts did not execute depth-first"; } /// <summary> /// Be careful! The new operator overload on this type only permits one allocation! /// </summary> class HasOverriddenNewOperator: public ContextMember { public: HasOverriddenNewOperator(bool hitDtor) { if(hitDtor) throw std::runtime_error(""); } static unsigned char s_space[]; static size_t s_deleterHitCount; static void* operator new(size_t) { return s_space; } static void operator delete(void*) { s_deleterHitCount++; } static void* operator new(size_t size, void* ptr) { return ::operator new(size, ptr); } static void operator delete(void* memory, void* ptr) throw() { return ::operator delete(memory, ptr); } }; unsigned char HasOverriddenNewOperator::s_space[sizeof(HasOverriddenNewOperator)]; size_t HasOverriddenNewOperator::s_deleterHitCount; TEST_F(CoreContextTest, CorrectHitAllocatorNew) { HasOverriddenNewOperator::s_deleterHitCount = 0; { AutoCreateContext ctxt; CurrentContextPusher pshr(ctxt); // Verify that the overload itsef gets called as expected: ASSERT_EQ( (void*) HasOverriddenNewOperator::s_space, new HasOverriddenNewOperator(false) ) << "Overloaded new operator on a test type did not get invoked as expected"; // Create an instance which won't throw: auto hono = AutoCurrentContext()->Inject<HasOverriddenNewOperator>(false); // Verify the correct new allocator was hit: ASSERT_EQ( (void*)HasOverriddenNewOperator::s_space, (void*)hono.get() ) << "Overridden new allocator was not invoked as anticipated"; } // Verify that the deleter got hit as anticipated: ASSERT_EQ(1UL, HasOverriddenNewOperator::s_deleterHitCount) << "The correct deleter was not hit under ordinary teardown"; } TEST_F(CoreContextTest, CorrectHitExceptionalTeardown) { HasOverriddenNewOperator::s_deleterHitCount = 0; // Create our type--we expect this to throw: ASSERT_ANY_THROW(AutoCurrentContext()->Inject<HasOverriddenNewOperator>(true)) << "Construct operation did not propagate an exception to the caller"; // Now verify that the correct deleter was hit to release partially constructed memory: ASSERT_EQ(1UL, HasOverriddenNewOperator::s_deleterHitCount) << "Deleter was not correctly hit in an exceptional teardown"; } struct PreBoltInjectionSigil {}; class BoltThatChecksForAThread: public Bolt<PreBoltInjectionSigil> { public: BoltThatChecksForAThread(void): m_threadPresent(false) {} void ContextCreated(void) override { m_threadPresent = Autowired<CoreThread>().IsAutowired(); } bool m_threadPresent; }; TEST_F(CoreContextTest, PreBoltInjection) { AutoRequired<BoltThatChecksForAThread> myBolt; AutoCreateContextT<PreBoltInjectionSigil> ctxt(MakeInjectable<CoreThread>()); // Basic functionality check on the injectable Autowired<CoreThread> ct(ctxt); ASSERT_TRUE(ct) << "Injection did not take place in the created context as expected"; // Verify the bolt was hit as expected ASSERT_TRUE(myBolt->m_threadPresent) << "Bolt was not correctly fired after injection"; } struct NoEnumerateBeforeBoltReturn {}; class BoltThatTakesALongTimeToReturn: public Bolt<NoEnumerateBeforeBoltReturn> { public: BoltThatTakesALongTimeToReturn(void) : m_bDoneRunning(false) {} void ContextCreated(void) override { std::this_thread::sleep_for(std::chrono::milliseconds(100)); m_bDoneRunning = true; } bool m_bDoneRunning; }; TEST_F(CoreContextTest, NoEnumerateBeforeBoltReturn) { AutoCurrentContext ctxt; AutoRequired<BoltThatTakesALongTimeToReturn> longTime; // Spin off a thread which will create the new context auto finished = std::make_shared<bool>(false); std::thread t([finished, ctxt] { AutoCreateContextT<NoEnumerateBeforeBoltReturn>(); *finished = true; }); // Verify that the context does not appear until the bolt has finished running: while(!*finished) for(auto cur : ContextEnumeratorT<NoEnumerateBeforeBoltReturn>(ctxt)) ASSERT_TRUE(longTime->m_bDoneRunning) << "A context was enumerated before a bolt finished running"; // Need to block until this thread is done t.join(); } TEST_F(CoreContextTest, InitiateCausesDelayedHold) { std::weak_ptr<CoreContext> ctxtWeak; // Create and initiate a subcontext, but do not initiate the parent context { AutoCreateContext ctxt; ctxtWeak = ctxt; ctxt->Initiate(); } // Weak pointer should not be expired yet ASSERT_FALSE(ctxtWeak.expired()) << "Subcontext expired after initiation even though its parent context was not yet initiated"; // Starting up the outer context should cause the inner one to self destruct AutoCurrentContext()->Initiate(); ASSERT_TRUE(ctxtWeak.expired()) << "Subcontext containing no threads incorrectly persisted after termination"; }
// Copyright (C) 2012-2015 Leap Motion, Inc. All rights reserved. #include "stdafx.h" #include <autowiring/AutoInjectable.h> #include <autowiring/ContextEnumerator.h> #include <algorithm> #include <set> #include THREAD_HEADER #include FUTURE_HEADER class CoreContextTest: public testing::Test {}; class Foo{}; class Bar{}; class Baz{}; TEST_F(CoreContextTest, TestEnumerateChildren) { AutoCurrentContext ctxt; // Create a few anonymous children: AutoCreateContext child1; AutoCreateContext child2; AutoCreateContext child3; // Enumerate and see what we get back: std::set<std::shared_ptr<CoreContext>> allChildren; for(const auto& cur : CurrentContextEnumerator()) allChildren.insert(cur); // Verify we get exactly four back: ASSERT_EQ(4UL, allChildren.size()) << "Failed to enumerate the correct number of child contexts"; // Verify full membership: ASSERT_EQ(1UL, allChildren.count(ctxt)) << "Failed to find the root context in the returned context collection"; const char* childMissing = "Failed to find a child context in the set of children"; ASSERT_EQ(1UL, allChildren.count(child1)) << childMissing; ASSERT_EQ(1UL, allChildren.count(child2)) << childMissing; ASSERT_EQ(1UL, allChildren.count(child3)) << childMissing; //Check if filtering by sigil works AutoCreateContextT<Foo> fooCtxt; AutoCreateContextT<Bar> barCtxt; auto childFoo = barCtxt->Create<Foo>(); ContextEnumeratorT<Foo> enumerator1(ctxt); std::vector<std::shared_ptr<CoreContext>> onlyFoos(enumerator1.begin(), enumerator1.end()); ASSERT_EQ(2UL, onlyFoos.size()) << "Didn't collect only contexts with 'Foo' sigil"; ASSERT_NE(std::find(onlyFoos.begin(), onlyFoos.end(), fooCtxt), onlyFoos.end()) << "Context not enumerated"; ASSERT_NE(std::find(onlyFoos.begin(), onlyFoos.end(), childFoo), onlyFoos.end()) << "Context not enumerated"; ContextEnumeratorT<Bar> enumerator2(ctxt); std::vector<std::shared_ptr<CoreContext>> onlyBars(enumerator2.begin(), enumerator2.end()); ASSERT_EQ(1UL, onlyBars.size()) << "Didn't collect only contexts with 'Bar' sigil"; ASSERT_NE(std::find(onlyBars.begin(), onlyBars.end(), barCtxt), onlyBars.end()) << "Context not enumerated"; ContextEnumeratorT<Baz> enumerator3(ctxt); std::vector<std::shared_ptr<CoreContext>> noBaz(enumerator3.begin(), enumerator3.end()); ASSERT_TRUE(noBaz.empty()) << "Incorrectly collected contexts with 'Baz' sigil"; } TEST_F(CoreContextTest, TestEarlyLambdaReturn) { AutoCurrentContext ctxt; // Create three children: AutoCreateContext child1; AutoCreateContext child2; AutoCreateContext child3; // Enumerate, but stop after three: std::vector<std::shared_ptr<CoreContext>> allChildren; size_t totalSoFar = 0; for(const auto& ctxt : CurrentContextEnumerator()) { if(totalSoFar++ == 3) break; allChildren.push_back(ctxt); } ASSERT_EQ(3UL, allChildren.size()) << "Enumeration routine failed to quit early"; // Verify that the root context is the first one enumerated--needed to assure that we are executing a depth-first search ASSERT_EQ(ctxt, allChildren[0]) << "EnumerateChildContexts did not execute depth-first"; } /// <summary> /// Be careful! The new operator overload on this type only permits one allocation! /// </summary> class HasOverriddenNewOperator: public ContextMember { public: HasOverriddenNewOperator(bool hitDtor) { if(hitDtor) throw std::runtime_error(""); } static unsigned char s_space[]; static size_t s_deleterHitCount; static void* operator new(size_t) { return s_space; } static void operator delete(void*) { s_deleterHitCount++; } static void* operator new(size_t size, void* ptr) { return ::operator new(size, ptr); } static void operator delete(void* memory, void* ptr) throw() { return ::operator delete(memory, ptr); } }; unsigned char HasOverriddenNewOperator::s_space[sizeof(HasOverriddenNewOperator)]; size_t HasOverriddenNewOperator::s_deleterHitCount; TEST_F(CoreContextTest, CorrectHitAllocatorNew) { HasOverriddenNewOperator::s_deleterHitCount = 0; { AutoCreateContext ctxt; CurrentContextPusher pshr(ctxt); // Verify that the overload itsef gets called as expected: ASSERT_EQ( (void*) HasOverriddenNewOperator::s_space, new HasOverriddenNewOperator(false) ) << "Overloaded new operator on a test type did not get invoked as expected"; // Create an instance which won't throw: auto hono = AutoCurrentContext()->Inject<HasOverriddenNewOperator>(false); // Verify the correct new allocator was hit: ASSERT_EQ( (void*)HasOverriddenNewOperator::s_space, (void*)hono.get() ) << "Overridden new allocator was not invoked as anticipated"; } // Verify that the deleter got hit as anticipated: ASSERT_EQ(1UL, HasOverriddenNewOperator::s_deleterHitCount) << "The correct deleter was not hit under ordinary teardown"; } TEST_F(CoreContextTest, CorrectHitExceptionalTeardown) { HasOverriddenNewOperator::s_deleterHitCount = 0; // Create our type--we expect this to throw: ASSERT_ANY_THROW(AutoCurrentContext()->Inject<HasOverriddenNewOperator>(true)) << "Construct operation did not propagate an exception to the caller"; // Now verify that the correct deleter was hit to release partially constructed memory: ASSERT_EQ(1UL, HasOverriddenNewOperator::s_deleterHitCount) << "Deleter was not correctly hit in an exceptional teardown"; } struct PreBoltInjectionSigil {}; class BoltThatChecksForAThread: public Bolt<PreBoltInjectionSigil> { public: BoltThatChecksForAThread(void): m_threadPresent(false) {} void ContextCreated(void) override { m_threadPresent = Autowired<CoreThread>().IsAutowired(); } bool m_threadPresent; }; TEST_F(CoreContextTest, PreBoltInjection) { AutoRequired<BoltThatChecksForAThread> myBolt; AutoCreateContextT<PreBoltInjectionSigil> ctxt(MakeInjectable<CoreThread>()); // Basic functionality check on the injectable Autowired<CoreThread> ct(ctxt); ASSERT_TRUE(ct) << "Injection did not take place in the created context as expected"; // Verify the bolt was hit as expected ASSERT_TRUE(myBolt->m_threadPresent) << "Bolt was not correctly fired after injection"; } struct NoEnumerateBeforeBoltReturn {}; class BoltThatTakesALongTimeToReturn: public Bolt<NoEnumerateBeforeBoltReturn> { public: BoltThatTakesALongTimeToReturn(void) : m_bDoneRunning(false) {} void ContextCreated(void) override { std::this_thread::sleep_for(std::chrono::milliseconds(100)); m_bDoneRunning = true; } bool m_bDoneRunning; }; TEST_F(CoreContextTest, NoEnumerateBeforeBoltReturn) { AutoCurrentContext ctxt; AutoRequired<BoltThatTakesALongTimeToReturn> longTime; // Spin off a thread which will create the new context auto finished = std::make_shared<bool>(false); std::thread t([finished, ctxt] { AutoCreateContextT<NoEnumerateBeforeBoltReturn>(); *finished = true; }); // Verify that the context does not appear until the bolt has finished running: while(!*finished) for(auto cur : ContextEnumeratorT<NoEnumerateBeforeBoltReturn>(ctxt)) ASSERT_TRUE(longTime->m_bDoneRunning) << "A context was enumerated before a bolt finished running"; // Need to block until this thread is done t.join(); } TEST_F(CoreContextTest, InitiateCausesDelayedHold) { std::weak_ptr<CoreContext> ctxtWeak; // Create and initiate a subcontext, but do not initiate the parent context { AutoCreateContext ctxt; ctxtWeak = ctxt; ctxt->Initiate(); } // Weak pointer should not be expired yet ASSERT_FALSE(ctxtWeak.expired()) << "Subcontext expired after initiation even though its parent context was not yet initiated"; // Starting up the outer context should cause the inner one to self destruct AutoCurrentContext()->Initiate(); ASSERT_TRUE(ctxtWeak.expired()) << "Subcontext containing no threads incorrectly persisted after termination"; } TEST_F(CoreContextTest, InitiateOrder) { AutoCurrentContext testCtxt; testCtxt->Initiate(); { auto outerCtxt = testCtxt->Create<void>(); auto middleCtxt = outerCtxt->Create<void>(); auto innerCtxt = middleCtxt->Create<void>(); middleCtxt->Initiate(); innerCtxt->Initiate(); outerCtxt->Initiate(); EXPECT_TRUE(outerCtxt->IsRunning()); EXPECT_TRUE(middleCtxt->IsRunning()); EXPECT_TRUE(innerCtxt->IsRunning()); outerCtxt->SignalShutdown(true); middleCtxt->SignalShutdown(true); innerCtxt->SignalShutdown(true); } { auto outerCtxt = testCtxt->Create<void>(); auto middleCtxt = outerCtxt->Create<void>(); auto innerCtxt = middleCtxt->Create<void>(); innerCtxt->Initiate(); middleCtxt->Initiate(); outerCtxt->Initiate(); EXPECT_TRUE(outerCtxt->IsRunning()); EXPECT_TRUE(middleCtxt->IsRunning()); EXPECT_TRUE(innerCtxt->IsRunning()); innerCtxt->SignalShutdown(true); middleCtxt->SignalShutdown(true); outerCtxt->SignalShutdown(true); } }
Add test to verify recursive context initiation
Add test to verify recursive context initiation
C++
apache-2.0
codemercenary/autowiring,leapmotion/autowiring,codemercenary/autowiring,leapmotion/autowiring,codemercenary/autowiring,leapmotion/autowiring,codemercenary/autowiring,leapmotion/autowiring,leapmotion/autowiring,leapmotion/autowiring,codemercenary/autowiring,codemercenary/autowiring
d2e15db7fa953fe36c230c01059003d45fbbf36c
src/masternodeconfig.cpp
src/masternodeconfig.cpp
#include "net.h" #include "masternodeconfig.h" #include "util.h" CMasternodeConfig masternodeConfig; void CMasternodeConfig::add(std::string alias, std::string ip, std::string privKey, std::string txHash, std::string outputIndex) { CMasternodeEntry cme(alias, ip, privKey, txHash, outputIndex); entries.push_back(cme); } bool CMasternodeConfig::read(boost::filesystem::path path) { boost::filesystem::ifstream streamConfig(GetMasternodeConfigFile()); if (!streamConfig.good()) { return true; // No masternode.conf file is OK } for(std::string line; std::getline(streamConfig, line); ) { if(line.empty()) { continue; } std::istringstream iss(line); std::string alias, ip, privKey, txHash, outputIndex; if (!(iss >> alias >> ip >> privKey >> txHash >> outputIndex)) { strErr = "Could not parse masternode.conf line: " + line; streamConfig.close(); return false; } /* if(CService(ip).GetPort() != 19999 && CService(ip).GetPort() != 9999) { strErr = "Invalid port (must be 9999 for mainnet or 19999 for testnet) detected in masternode.conf: " + line; streamConfig.close(); return false; }*/ add(alias, ip, privKey, txHash, outputIndex); } streamConfig.close(); return true; }
#include "net.h" #include "masternodeconfig.h" #include "util.h" CMasternodeConfig masternodeConfig; void CMasternodeConfig::add(std::string alias, std::string ip, std::string privKey, std::string txHash, std::string outputIndex) { CMasternodeEntry cme(alias, ip, privKey, txHash, outputIndex); entries.push_back(cme); } bool CMasternodeConfig::read(boost::filesystem::path path) { boost::filesystem::ifstream streamConfig(GetMasternodeConfigFile()); if (!streamConfig.good()) { return true; // No masternode.conf file is OK } for(std::string line; std::getline(streamConfig, line); ) { if(line.empty()) { continue; } std::istringstream iss(line); std::string alias, ip, privKey, txHash, outputIndex; if (!(iss >> alias >> ip >> privKey >> txHash >> outputIndex)) { LogPrintf("CMasternodeConfig::read - Could not parse masternode.conf. Line: %s\n", line.c_str()); streamConfig.close(); return false; } add(alias, ip, privKey, txHash, outputIndex); } streamConfig.close(); return true; }
fix #4 for masternode.conf
fix #4 for masternode.conf
C++
mit
syfares/Transfercoin,syfares/Transfercoin,bryceweiner/mojocoin,MinuteManReserve/mmr-core,bryceweiner/mojocoin,Infernoman/Transfercoin,bryceweiner/mojocoin,transferdev/Transfercoin,bryceweiner/mojocoin,syfares/Transfercoin,transferdev/Transfercoin,aspaas/ion,aspaas/ion,transferdev/Transfercoin,aspaas/ion,aspaas/ion,transferdev/Transfercoin,aspaas/ion,syfares/Transfercoin,syfares/Transfercoin,bryceweiner/mojocoin,Infernoman/Transfercoin,MinuteManReserve/mmr-core,bryceweiner/mojocoin,Infernoman/Transfercoin,Infernoman/Transfercoin,aspaas/ion,Infernoman/Transfercoin,syfares/Transfercoin,MinuteManReserve/mmr-core,MinuteManReserve/mmr-core,transferdev/Transfercoin,transferdev/Transfercoin,MinuteManReserve/mmr-core,Infernoman/Transfercoin
8fa16e47f88975b577fe1cafce1a366b78b2c340
lib/CodeGen/VirtRegMap.cpp
lib/CodeGen/VirtRegMap.cpp
//===-- llvm/CodeGen/VirtRegMap.cpp - Virtual Register Map ----------------===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the virtual register map. It also implements // the eliminateVirtRegs() function that given a virtual register map // and a machine function it eliminates all virtual references by // replacing them with physical register references and adds spill // code as necessary. // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "regalloc" #include "VirtRegMap.h" #include "llvm/Function.h" #include "llvm/CodeGen/MachineFrameInfo.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Target/TargetInstrInfo.h" #include "Support/Statistic.h" #include "Support/Debug.h" #include "Support/STLExtras.h" #include <iostream> using namespace llvm; namespace { Statistic<> numSpills("spiller", "Number of register spills"); Statistic<> numStores("spiller", "Number of stores added"); Statistic<> numLoads ("spiller", "Number of loads added"); } int VirtRegMap::assignVirt2StackSlot(unsigned virtReg) { assert(MRegisterInfo::isVirtualRegister(virtReg)); assert(v2ssMap_[virtReg] == NO_STACK_SLOT && "attempt to assign stack slot to already spilled register"); const TargetRegisterClass* rc = mf_->getSSARegMap()->getRegClass(virtReg); int frameIndex = mf_->getFrameInfo()->CreateStackObject(rc); v2ssMap_[virtReg] = frameIndex; ++numSpills; return frameIndex; } std::ostream& llvm::operator<<(std::ostream& os, const VirtRegMap& vrm) { const MRegisterInfo* mri = vrm.mf_->getTarget().getRegisterInfo(); std::cerr << "********** REGISTER MAP **********\n"; for (unsigned i = MRegisterInfo::FirstVirtualRegister, e = vrm.mf_->getSSARegMap()->getLastVirtReg(); i <= e; ++i) { if (vrm.v2pMap_[i] != VirtRegMap::NO_PHYS_REG) std::cerr << "[reg" << i << " -> " << mri->getName(vrm.v2pMap_[i]) << "]\n"; } for (unsigned i = MRegisterInfo::FirstVirtualRegister, e = vrm.mf_->getSSARegMap()->getLastVirtReg(); i <= e; ++i) { if (vrm.v2ssMap_[i] != VirtRegMap::NO_STACK_SLOT) std::cerr << "[reg" << i << " -> fi#" << vrm.v2ssMap_[i] << "]\n"; } return std::cerr << '\n'; } namespace { class Spiller { typedef std::vector<unsigned> Phys2VirtMap; typedef std::vector<bool> PhysFlag; MachineFunction& mf_; const TargetMachine& tm_; const TargetInstrInfo& tii_; const MRegisterInfo& mri_; const VirtRegMap& vrm_; Phys2VirtMap p2vMap_; PhysFlag dirty_; public: Spiller(MachineFunction& mf, const VirtRegMap& vrm) : mf_(mf), tm_(mf_.getTarget()), tii_(tm_.getInstrInfo()), mri_(*tm_.getRegisterInfo()), vrm_(vrm), p2vMap_(mri_.getNumRegs()), dirty_(mri_.getNumRegs()) { DEBUG(std::cerr << "********** REWRITE MACHINE CODE **********\n"); DEBUG(std::cerr << "********** Function: " << mf_.getFunction()->getName() << '\n'); } void eliminateVirtRegs() { for (MachineFunction::iterator mbbi = mf_.begin(), mbbe = mf_.end(); mbbi != mbbe; ++mbbi) { // clear map and dirty flag p2vMap_.assign(p2vMap_.size(), 0); dirty_.assign(dirty_.size(), false); DEBUG(std::cerr << mbbi->getBasicBlock()->getName() << ":\n"); eliminateVirtRegsInMbb(*mbbi); } } private: void vacateJustPhysReg(MachineBasicBlock& mbb, MachineBasicBlock::iterator mii, unsigned physReg) { unsigned virtReg = p2vMap_[physReg]; if (dirty_[physReg] && vrm_.hasStackSlot(virtReg)) { mri_.storeRegToStackSlot(mbb, mii, physReg, vrm_.getStackSlot(virtReg), mri_.getRegClass(physReg)); ++numStores; DEBUG(std::cerr << "*\t"; prior(mii)->print(std::cerr, tm_)); } p2vMap_[physReg] = 0; dirty_[physReg] = false; } void vacatePhysReg(MachineBasicBlock& mbb, MachineBasicBlock::iterator mii, unsigned physReg) { vacateJustPhysReg(mbb, mii, physReg); for (const unsigned* as = mri_.getAliasSet(physReg); *as; ++as) vacateJustPhysReg(mbb, mii, *as); } void handleUse(MachineBasicBlock& mbb, MachineBasicBlock::iterator mii, unsigned virtReg, unsigned physReg) { // check if we are replacing a previous mapping if (p2vMap_[physReg] != virtReg) { vacatePhysReg(mbb, mii, physReg); p2vMap_[physReg] = virtReg; // load if necessary if (vrm_.hasStackSlot(virtReg)) { mri_.loadRegFromStackSlot(mbb, mii, physReg, vrm_.getStackSlot(virtReg), mri_.getRegClass(physReg)); ++numLoads; DEBUG(std::cerr << "*\t"; prior(mii)->print(std::cerr,tm_)); } } } void handleDef(MachineBasicBlock& mbb, MachineBasicBlock::iterator mii, unsigned virtReg, unsigned physReg) { // check if we are replacing a previous mapping if (p2vMap_[physReg] != virtReg) vacatePhysReg(mbb, mii, physReg); p2vMap_[physReg] = virtReg; dirty_[physReg] = true; } void eliminateVirtRegsInMbb(MachineBasicBlock& mbb) { for (MachineBasicBlock::iterator mii = mbb.begin(), mie = mbb.end(); mii != mie; ++mii) { // rewrite all used operands for (unsigned i = 0, e = mii->getNumOperands(); i != e; ++i) { MachineOperand& op = mii->getOperand(i); if (op.isRegister() && op.getReg() && op.isUse() && MRegisterInfo::isVirtualRegister(op.getReg())) { unsigned physReg = vrm_.getPhys(op.getReg()); handleUse(mbb, mii, op.getReg(), physReg); mii->SetMachineOperandReg(i, physReg); // mark as dirty if this is def&use if (op.isDef()) dirty_[physReg] = true; } } // spill implicit defs const TargetInstrDescriptor& tid =tii_.get(mii->getOpcode()); for (const unsigned* id = tid.ImplicitDefs; *id; ++id) vacatePhysReg(mbb, mii, *id); // rewrite def operands (def&use was handled with the // uses so don't check for those here) for (unsigned i = 0, e = mii->getNumOperands(); i != e; ++i) { MachineOperand& op = mii->getOperand(i); if (op.isRegister() && op.getReg() && !op.isUse()) if (MRegisterInfo::isPhysicalRegister(op.getReg())) vacatePhysReg(mbb, mii, op.getReg()); else { unsigned physReg = vrm_.getPhys(op.getReg()); handleDef(mbb, mii, op.getReg(), physReg); mii->SetMachineOperandReg(i, physReg); } } DEBUG(std::cerr << '\t'; mii->print(std::cerr, tm_)); } for (unsigned i = 1, e = p2vMap_.size(); i != e; ++i) vacateJustPhysReg(mbb, mbb.getFirstTerminator(), i); } }; } void llvm::eliminateVirtRegs(MachineFunction& mf, const VirtRegMap& vrm) { Spiller(mf, vrm).eliminateVirtRegs(); }
//===-- llvm/CodeGen/VirtRegMap.cpp - Virtual Register Map ----------------===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the virtual register map. It also implements // the eliminateVirtRegs() function that given a virtual register map // and a machine function it eliminates all virtual references by // replacing them with physical register references and adds spill // code as necessary. // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "regalloc" #include "VirtRegMap.h" #include "llvm/Function.h" #include "llvm/CodeGen/MachineFrameInfo.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Target/TargetInstrInfo.h" #include "Support/Statistic.h" #include "Support/Debug.h" #include "Support/STLExtras.h" #include <iostream> using namespace llvm; namespace { Statistic<> numSpills("spiller", "Number of register spills"); Statistic<> numStores("spiller", "Number of stores added"); Statistic<> numLoads ("spiller", "Number of loads added"); } int VirtRegMap::assignVirt2StackSlot(unsigned virtReg) { assert(MRegisterInfo::isVirtualRegister(virtReg)); assert(v2ssMap_[virtReg] == NO_STACK_SLOT && "attempt to assign stack slot to already spilled register"); const TargetRegisterClass* rc = mf_->getSSARegMap()->getRegClass(virtReg); int frameIndex = mf_->getFrameInfo()->CreateStackObject(rc); v2ssMap_[virtReg] = frameIndex; ++numSpills; return frameIndex; } std::ostream& llvm::operator<<(std::ostream& os, const VirtRegMap& vrm) { const MRegisterInfo* mri = vrm.mf_->getTarget().getRegisterInfo(); std::cerr << "********** REGISTER MAP **********\n"; for (unsigned i = MRegisterInfo::FirstVirtualRegister, e = vrm.mf_->getSSARegMap()->getLastVirtReg(); i <= e; ++i) { if (vrm.v2pMap_[i] != VirtRegMap::NO_PHYS_REG) std::cerr << "[reg" << i << " -> " << mri->getName(vrm.v2pMap_[i]) << "]\n"; } for (unsigned i = MRegisterInfo::FirstVirtualRegister, e = vrm.mf_->getSSARegMap()->getLastVirtReg(); i <= e; ++i) { if (vrm.v2ssMap_[i] != VirtRegMap::NO_STACK_SLOT) std::cerr << "[reg" << i << " -> fi#" << vrm.v2ssMap_[i] << "]\n"; } return std::cerr << '\n'; } namespace { class Spiller { typedef std::vector<unsigned> Phys2VirtMap; typedef std::vector<bool> PhysFlag; MachineFunction& mf_; const TargetMachine& tm_; const TargetInstrInfo& tii_; const MRegisterInfo& mri_; const VirtRegMap& vrm_; Phys2VirtMap p2vMap_; PhysFlag dirty_; public: Spiller(MachineFunction& mf, const VirtRegMap& vrm) : mf_(mf), tm_(mf_.getTarget()), tii_(tm_.getInstrInfo()), mri_(*tm_.getRegisterInfo()), vrm_(vrm), p2vMap_(mri_.getNumRegs(), 0), dirty_(mri_.getNumRegs(), false) { DEBUG(std::cerr << "********** REWRITE MACHINE CODE **********\n"); DEBUG(std::cerr << "********** Function: " << mf_.getFunction()->getName() << '\n'); } void eliminateVirtRegs() { for (MachineFunction::iterator mbbi = mf_.begin(), mbbe = mf_.end(); mbbi != mbbe; ++mbbi) { DEBUG(std::cerr << mbbi->getBasicBlock()->getName() << ":\n"); eliminateVirtRegsInMbb(*mbbi); // clear map and dirty flag p2vMap_.assign(p2vMap_.size(), 0); dirty_.assign(dirty_.size(), false); } } private: void vacateJustPhysReg(MachineBasicBlock& mbb, MachineBasicBlock::iterator mii, unsigned physReg) { unsigned virtReg = p2vMap_[physReg]; if (dirty_[physReg] && vrm_.hasStackSlot(virtReg)) { mri_.storeRegToStackSlot(mbb, mii, physReg, vrm_.getStackSlot(virtReg), mri_.getRegClass(physReg)); ++numStores; DEBUG(std::cerr << "*\t"; prior(mii)->print(std::cerr, tm_)); } p2vMap_[physReg] = 0; dirty_[physReg] = false; } void vacatePhysReg(MachineBasicBlock& mbb, MachineBasicBlock::iterator mii, unsigned physReg) { vacateJustPhysReg(mbb, mii, physReg); for (const unsigned* as = mri_.getAliasSet(physReg); *as; ++as) vacateJustPhysReg(mbb, mii, *as); } void handleUse(MachineBasicBlock& mbb, MachineBasicBlock::iterator mii, unsigned virtReg, unsigned physReg) { // check if we are replacing a previous mapping if (p2vMap_[physReg] != virtReg) { vacatePhysReg(mbb, mii, physReg); p2vMap_[physReg] = virtReg; // load if necessary if (vrm_.hasStackSlot(virtReg)) { mri_.loadRegFromStackSlot(mbb, mii, physReg, vrm_.getStackSlot(virtReg), mri_.getRegClass(physReg)); ++numLoads; DEBUG(std::cerr << "*\t"; prior(mii)->print(std::cerr,tm_)); } } } void handleDef(MachineBasicBlock& mbb, MachineBasicBlock::iterator mii, unsigned virtReg, unsigned physReg) { // check if we are replacing a previous mapping if (p2vMap_[physReg] != virtReg) vacatePhysReg(mbb, mii, physReg); p2vMap_[physReg] = virtReg; dirty_[physReg] = true; } void eliminateVirtRegsInMbb(MachineBasicBlock& mbb) { for (MachineBasicBlock::iterator mii = mbb.begin(), mie = mbb.end(); mii != mie; ++mii) { // rewrite all used operands for (unsigned i = 0, e = mii->getNumOperands(); i != e; ++i) { MachineOperand& op = mii->getOperand(i); if (op.isRegister() && op.getReg() && op.isUse() && MRegisterInfo::isVirtualRegister(op.getReg())) { unsigned physReg = vrm_.getPhys(op.getReg()); handleUse(mbb, mii, op.getReg(), physReg); mii->SetMachineOperandReg(i, physReg); // mark as dirty if this is def&use if (op.isDef()) dirty_[physReg] = true; } } // spill implicit defs const TargetInstrDescriptor& tid =tii_.get(mii->getOpcode()); for (const unsigned* id = tid.ImplicitDefs; *id; ++id) vacatePhysReg(mbb, mii, *id); // rewrite def operands (def&use was handled with the // uses so don't check for those here) for (unsigned i = 0, e = mii->getNumOperands(); i != e; ++i) { MachineOperand& op = mii->getOperand(i); if (op.isRegister() && op.getReg() && !op.isUse()) if (MRegisterInfo::isPhysicalRegister(op.getReg())) vacatePhysReg(mbb, mii, op.getReg()); else { unsigned physReg = vrm_.getPhys(op.getReg()); handleDef(mbb, mii, op.getReg(), physReg); mii->SetMachineOperandReg(i, physReg); } } DEBUG(std::cerr << '\t'; mii->print(std::cerr, tm_)); } for (unsigned i = 1, e = p2vMap_.size(); i != e; ++i) vacateJustPhysReg(mbb, mbb.getFirstTerminator(), i); } }; } void llvm::eliminateVirtRegs(MachineFunction& mf, const VirtRegMap& vrm) { Spiller(mf, vrm).eliminateVirtRegs(); }
Clear maps right after basic block is processed.
Clear maps right after basic block is processed. git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@11892 91177308-0d34-0410-b5e6-96231b3b80d8
C++
apache-2.0
GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,chubbymaggie/asap,llvm-mirror/llvm,chubbymaggie/asap,apple/swift-llvm,chubbymaggie/asap,apple/swift-llvm,apple/swift-llvm,chubbymaggie/asap,llvm-mirror/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,llvm-mirror/llvm,dslab-epfl/asap,dslab-epfl/asap,GPUOpen-Drivers/llvm,dslab-epfl/asap,apple/swift-llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,apple/swift-llvm,dslab-epfl/asap,apple/swift-llvm,chubbymaggie/asap,llvm-mirror/llvm,dslab-epfl/asap,apple/swift-llvm,dslab-epfl/asap,llvm-mirror/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,dslab-epfl/asap,GPUOpen-Drivers/llvm,chubbymaggie/asap,GPUOpen-Drivers/llvm
9aa8b317c4dcfb719652a02d5d88d6d708264c58
Siv3D/include/Siv3D/Windows/Libraries.hpp
Siv3D/include/Siv3D/Windows/Libraries.hpp
//----------------------------------------------- // // This file is part of the Siv3D Engine. // // Copyright (c) 2008-2021 Ryo Suzuki // Copyright (c) 2016-2021 OpenSiv3D Project // // Licensed under the MIT License. // //----------------------------------------------- # pragma once # include <Siv3D/Platform.hpp> # if SIV3D_BUILD(DEBUG) # define SIV3D_DEBUG_LIB_POSTFIX(s) #s # else # define SIV3D_DEBUG_LIB_POSTFIX(s) # endif # pragma comment (linker, "/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='amd64' publicKeyToken='6595b64144ccf1df' language='*'\"") # pragma comment (lib, "crypt32") # pragma comment (lib, "dinput8") # pragma comment (lib, "dwmapi") # pragma comment (lib, "dxguid") # pragma comment (lib, "imm32") # pragma comment (lib, "mfuuid") # pragma comment (lib, "opengl32") # pragma comment (lib, "version") # pragma comment (lib, "winmm") # pragma comment (lib, "Ws2_32") # pragma comment (lib, "curl/libcurl" SIV3D_DEBUG_LIB_POSTFIX(-d)) # pragma comment (lib, "freetype/freetype" SIV3D_DEBUG_LIB_POSTFIX(d)) # pragma comment (lib, "glew/glew32s" SIV3D_DEBUG_LIB_POSTFIX(d)) # pragma comment (lib, "harfbuzz/harfbuzz" SIV3D_DEBUG_LIB_POSTFIX(_d)) # pragma comment (lib, "libgif/libgif" SIV3D_DEBUG_LIB_POSTFIX(_d)) # pragma comment (lib, "libjpeg-turbo/turbojpeg-static" SIV3D_DEBUG_LIB_POSTFIX(_d)) # pragma comment (lib, "libogg/libogg" SIV3D_DEBUG_LIB_POSTFIX(_d)) # pragma comment (lib, "libpng/libpng16" SIV3D_DEBUG_LIB_POSTFIX(_d)) # pragma comment (lib, "libtiff/tiff" SIV3D_DEBUG_LIB_POSTFIX(d)) # pragma comment (lib, "libvorbis/libvorbis_static" SIV3D_DEBUG_LIB_POSTFIX(_d)) # pragma comment (lib, "libvorbis/libvorbisfile_static" SIV3D_DEBUG_LIB_POSTFIX(_d)) # pragma comment (lib, "libwebp/libwebp" SIV3D_DEBUG_LIB_POSTFIX(_debug)) # pragma comment (lib, "Oniguruma/Oniguruma" SIV3D_DEBUG_LIB_POSTFIX(_d)) # pragma comment (lib, "opencv/opencv_core451" SIV3D_DEBUG_LIB_POSTFIX(d)) # pragma comment (lib, "opencv/opencv_imgcodecs451" SIV3D_DEBUG_LIB_POSTFIX(d)) # pragma comment (lib, "opencv/opencv_imgproc451" SIV3D_DEBUG_LIB_POSTFIX(d)) # pragma comment (lib, "opencv/opencv_objdetect451" SIV3D_DEBUG_LIB_POSTFIX(d)) # pragma comment (lib, "opencv/opencv_photo451" SIV3D_DEBUG_LIB_POSTFIX(d)) # pragma comment (lib, "opencv/opencv_videoio451" SIV3D_DEBUG_LIB_POSTFIX(d)) # pragma comment (lib, "opus/opus" SIV3D_DEBUG_LIB_POSTFIX(_d)) # pragma comment (lib, "opus/opusfile" SIV3D_DEBUG_LIB_POSTFIX(_d)) # pragma comment (lib, "zlib/zlib" SIV3D_DEBUG_LIB_POSTFIX(d)) # pragma comment (lib, "Siv3D" SIV3D_DEBUG_LIB_POSTFIX(_d)) # if SIV3D_BUILD(DEBUG) # pragma comment (lib, "boost/libboost_filesystem-vc142-mt-sgd-x64-1_73") # else # pragma comment (lib, "boost/libboost_filesystem-vc142-mt-s-x64-1_73") # endif # undef SIV3D_DEBUG_LIB_POSTFIX extern "C" { _declspec(selectany) _declspec(dllexport) unsigned long NvOptimusEnablement = 0x00000001; _declspec(selectany) _declspec(dllexport) int AmdPowerXpressRequestHighPerformance = 1; }
//----------------------------------------------- // // This file is part of the Siv3D Engine. // // Copyright (c) 2008-2021 Ryo Suzuki // Copyright (c) 2016-2021 OpenSiv3D Project // // Licensed under the MIT License. // //----------------------------------------------- # pragma once # include <Siv3D/Platform.hpp> # if SIV3D_BUILD(DEBUG) # define SIV3D_DEBUG_LIB_POSTFIX(s) #s # else # define SIV3D_DEBUG_LIB_POSTFIX(s) # endif # pragma comment (linker, "/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='amd64' publicKeyToken='6595b64144ccf1df' language='*'\"") # pragma comment (lib, "crypt32") # pragma comment (lib, "dinput8") # pragma comment (lib, "dwmapi") # pragma comment (lib, "dxguid") # pragma comment (lib, "imm32") # pragma comment (lib, "mfuuid") # pragma comment (lib, "opengl32") # pragma comment (lib, "Setupapi") # pragma comment (lib, "version") # pragma comment (lib, "winmm") # pragma comment (lib, "Ws2_32") # pragma comment (lib, "curl/libcurl" SIV3D_DEBUG_LIB_POSTFIX(-d)) # pragma comment (lib, "freetype/freetype" SIV3D_DEBUG_LIB_POSTFIX(d)) # pragma comment (lib, "glew/glew32s" SIV3D_DEBUG_LIB_POSTFIX(d)) # pragma comment (lib, "harfbuzz/harfbuzz" SIV3D_DEBUG_LIB_POSTFIX(_d)) # pragma comment (lib, "libgif/libgif" SIV3D_DEBUG_LIB_POSTFIX(_d)) # pragma comment (lib, "libjpeg-turbo/turbojpeg-static" SIV3D_DEBUG_LIB_POSTFIX(_d)) # pragma comment (lib, "libogg/libogg" SIV3D_DEBUG_LIB_POSTFIX(_d)) # pragma comment (lib, "libpng/libpng16" SIV3D_DEBUG_LIB_POSTFIX(_d)) # pragma comment (lib, "libtiff/tiff" SIV3D_DEBUG_LIB_POSTFIX(d)) # pragma comment (lib, "libvorbis/libvorbis_static" SIV3D_DEBUG_LIB_POSTFIX(_d)) # pragma comment (lib, "libvorbis/libvorbisfile_static" SIV3D_DEBUG_LIB_POSTFIX(_d)) # pragma comment (lib, "libwebp/libwebp" SIV3D_DEBUG_LIB_POSTFIX(_debug)) # pragma comment (lib, "Oniguruma/Oniguruma" SIV3D_DEBUG_LIB_POSTFIX(_d)) # pragma comment (lib, "opencv/opencv_core451" SIV3D_DEBUG_LIB_POSTFIX(d)) # pragma comment (lib, "opencv/opencv_imgcodecs451" SIV3D_DEBUG_LIB_POSTFIX(d)) # pragma comment (lib, "opencv/opencv_imgproc451" SIV3D_DEBUG_LIB_POSTFIX(d)) # pragma comment (lib, "opencv/opencv_objdetect451" SIV3D_DEBUG_LIB_POSTFIX(d)) # pragma comment (lib, "opencv/opencv_photo451" SIV3D_DEBUG_LIB_POSTFIX(d)) # pragma comment (lib, "opencv/opencv_videoio451" SIV3D_DEBUG_LIB_POSTFIX(d)) # pragma comment (lib, "opus/opus" SIV3D_DEBUG_LIB_POSTFIX(_d)) # pragma comment (lib, "opus/opusfile" SIV3D_DEBUG_LIB_POSTFIX(_d)) # pragma comment (lib, "zlib/zlib" SIV3D_DEBUG_LIB_POSTFIX(d)) # pragma comment (lib, "Siv3D" SIV3D_DEBUG_LIB_POSTFIX(_d)) # if SIV3D_BUILD(DEBUG) # pragma comment (lib, "boost/libboost_filesystem-vc142-mt-sgd-x64-1_73") # else # pragma comment (lib, "boost/libboost_filesystem-vc142-mt-s-x64-1_73") # endif # undef SIV3D_DEBUG_LIB_POSTFIX extern "C" { _declspec(selectany) _declspec(dllexport) unsigned long NvOptimusEnablement = 0x00000001; _declspec(selectany) _declspec(dllexport) int AmdPowerXpressRequestHighPerformance = 1; }
fix missing library
[Windows] fix missing library
C++
mit
Siv3D/OpenSiv3D,Siv3D/OpenSiv3D,Siv3D/OpenSiv3D,Siv3D/OpenSiv3D,Siv3D/OpenSiv3D,Siv3D/OpenSiv3D
aa9cf75ae0698f620fc1bfdaae0ed325194c1c49
Source/core/layout/TextRunConstructor.cpp
Source/core/layout/TextRunConstructor.cpp
/* * Copyright (C) 2013 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "core/layout/TextRunConstructor.h" #include "core/layout/LayoutText.h" #include "core/layout/style/LayoutStyle.h" #include "platform/text/BidiTextRun.h" namespace blink { template <typename CharacterType> static inline TextRun constructTextRunInternal(LayoutObject* context, const Font& font, const CharacterType* characters, int length, const LayoutStyle& style, TextDirection direction) { TextRun::ExpansionBehavior expansion = TextRun::AllowTrailingExpansion | TextRun::ForbidLeadingExpansion; bool directionalOverride = style.rtlOrdering() == VisualOrder; TextRun run(characters, length, 0, 0, expansion, direction, directionalOverride); return run; } template <typename CharacterType> static inline TextRun constructTextRunInternal(LayoutObject* context, const Font& font, const CharacterType* characters, int length, const LayoutStyle& style, TextDirection direction, TextRunFlags flags) { TextDirection textDirection = direction; bool directionalOverride = style.rtlOrdering() == VisualOrder; if (flags != DefaultTextRunFlags) { if (flags & RespectDirection) textDirection = style.direction(); if (flags & RespectDirectionOverride) directionalOverride |= isOverride(style.unicodeBidi()); } TextRun::ExpansionBehavior expansion = TextRun::AllowTrailingExpansion | TextRun::ForbidLeadingExpansion; TextRun run(characters, length, 0, 0, expansion, textDirection, directionalOverride); return run; } TextRun constructTextRun(LayoutObject* context, const Font& font, const LChar* characters, int length, const LayoutStyle& style, TextDirection direction) { return constructTextRunInternal(context, font, characters, length, style, direction); } TextRun constructTextRun(LayoutObject* context, const Font& font, const UChar* characters, int length, const LayoutStyle& style, TextDirection direction) { return constructTextRunInternal(context, font, characters, length, style, direction); } TextRun constructTextRun(LayoutObject* context, const Font& font, const LayoutText* text, const LayoutStyle& style, TextDirection direction) { if (text->is8Bit()) return constructTextRunInternal(context, font, text->characters8(), text->textLength(), style, direction); return constructTextRunInternal(context, font, text->characters16(), text->textLength(), style, direction); } TextRun constructTextRun(LayoutObject* context, const Font& font, const LayoutText* text, unsigned offset, unsigned length, const LayoutStyle& style, TextDirection direction) { ASSERT(offset + length <= text->textLength()); if (text->is8Bit()) return constructTextRunInternal(context, font, text->characters8() + offset, length, style, direction); return constructTextRunInternal(context, font, text->characters16() + offset, length, style, direction); } TextRun constructTextRun(LayoutObject* context, const Font& font, const String& string, const LayoutStyle& style, TextDirection direction, TextRunFlags flags) { unsigned length = string.length(); if (!length) return constructTextRunInternal(context, font, static_cast<const LChar*>(0), length, style, direction, flags); if (string.is8Bit()) return constructTextRunInternal(context, font, string.characters8(), length, style, direction, flags); return constructTextRunInternal(context, font, string.characters16(), length, style, direction, flags); } TextRun constructTextRun(LayoutObject* context, const Font& font, const String& string, const LayoutStyle& style, TextRunFlags flags) { return constructTextRun(context, font, string, style, string.is8Bit() ? LTR : determineDirectionality(string), flags); } TextRun constructTextRun(LayoutObject* context, const Font& font, const LayoutText* text, unsigned offset, unsigned length, const LayoutStyle& style) { ASSERT(offset + length <= text->textLength()); if (text->is8Bit()) return constructTextRunInternal(context, font, text->characters8() + offset, length, style, LTR); TextRun run = constructTextRunInternal(context, font, text->characters16() + offset, length, style, LTR); run.setDirection(directionForRun(run)); return run; } } // namespace blink
/* * Copyright (C) 2013 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "core/layout/TextRunConstructor.h" #include "core/layout/LayoutText.h" #include "core/layout/style/LayoutStyle.h" #include "platform/text/BidiTextRun.h" namespace blink { template <typename CharacterType> static inline TextRun constructTextRunInternal(LayoutObject* context, const Font& font, const CharacterType* characters, int length, const LayoutStyle& style, TextDirection direction) { TextRun::ExpansionBehavior expansion = TextRun::AllowTrailingExpansion | TextRun::ForbidLeadingExpansion; bool directionalOverride = style.rtlOrdering() == VisualOrder; TextRun run(characters, length, 0, 0, expansion, direction, directionalOverride); return run; } template <typename CharacterType> static inline TextRun constructTextRunInternal(LayoutObject* context, const Font& font, const CharacterType* characters, int length, const LayoutStyle& style, TextDirection direction, TextRunFlags flags) { TextDirection textDirection = direction; bool directionalOverride = style.rtlOrdering() == VisualOrder; if (flags != DefaultTextRunFlags) { if (flags & RespectDirection) textDirection = style.direction(); if (flags & RespectDirectionOverride) directionalOverride |= isOverride(style.unicodeBidi()); } TextRun::ExpansionBehavior expansion = TextRun::AllowTrailingExpansion | TextRun::ForbidLeadingExpansion; TextRun run(characters, length, 0, 0, expansion, textDirection, directionalOverride); return run; } TextRun constructTextRun(LayoutObject* context, const Font& font, const LChar* characters, int length, const LayoutStyle& style, TextDirection direction) { return constructTextRunInternal(context, font, characters, length, style, direction); } TextRun constructTextRun(LayoutObject* context, const Font& font, const UChar* characters, int length, const LayoutStyle& style, TextDirection direction) { return constructTextRunInternal(context, font, characters, length, style, direction); } TextRun constructTextRun(LayoutObject* context, const Font& font, const LayoutText* text, const LayoutStyle& style, TextDirection direction) { if (text->hasEmptyText()) return constructTextRunInternal(context, font, static_cast<const LChar*>(nullptr), 0, style, direction); if (text->is8Bit()) return constructTextRunInternal(context, font, text->characters8(), text->textLength(), style, direction); return constructTextRunInternal(context, font, text->characters16(), text->textLength(), style, direction); } TextRun constructTextRun(LayoutObject* context, const Font& font, const LayoutText* text, unsigned offset, unsigned length, const LayoutStyle& style, TextDirection direction) { ASSERT(offset + length <= text->textLength()); if (text->hasEmptyText()) return constructTextRunInternal(context, font, static_cast<const LChar*>(nullptr), 0, style, direction); if (text->is8Bit()) return constructTextRunInternal(context, font, text->characters8() + offset, length, style, direction); return constructTextRunInternal(context, font, text->characters16() + offset, length, style, direction); } TextRun constructTextRun(LayoutObject* context, const Font& font, const String& string, const LayoutStyle& style, TextDirection direction, TextRunFlags flags) { unsigned length = string.length(); if (!length) return constructTextRunInternal(context, font, static_cast<const LChar*>(0), length, style, direction, flags); if (string.is8Bit()) return constructTextRunInternal(context, font, string.characters8(), length, style, direction, flags); return constructTextRunInternal(context, font, string.characters16(), length, style, direction, flags); } TextRun constructTextRun(LayoutObject* context, const Font& font, const String& string, const LayoutStyle& style, TextRunFlags flags) { return constructTextRun(context, font, string, style, string.isEmpty() || string.is8Bit() ? LTR : determineDirectionality(string), flags); } TextRun constructTextRun(LayoutObject* context, const Font& font, const LayoutText* text, unsigned offset, unsigned length, const LayoutStyle& style) { ASSERT(offset + length <= text->textLength()); if (text->hasEmptyText()) return constructTextRunInternal(context, font, static_cast<const LChar*>(nullptr), 0, style, LTR); if (text->is8Bit()) return constructTextRunInternal(context, font, text->characters8() + offset, length, style, LTR); TextRun run = constructTextRunInternal(context, font, text->characters16() + offset, length, style, LTR); run.setDirection(directionForRun(run)); return run; } } // namespace blink
Fix crash in constructTextRun when string is null
Fix crash in constructTextRun when string is null This patch guards constructTextRun() variations from null strings. Recent optimizations in constructTextRun call String::is8bit(), string::characters8(), and LayoutText::characters8(), all which can make null references against null strings. BUG=465214 Review URL: https://codereview.chromium.org/993513003 git-svn-id: bf5cd6ccde378db821296732a091cfbcf5285fbd@191560 bbb929c8-8fbe-4397-9dbb-9b2b20218538
C++
bsd-3-clause
kurli/blink-crosswalk,Pluto-tv/blink-crosswalk,smishenk/blink-crosswalk,smishenk/blink-crosswalk,XiaosongWei/blink-crosswalk,Pluto-tv/blink-crosswalk,PeterWangIntel/blink-crosswalk,XiaosongWei/blink-crosswalk,XiaosongWei/blink-crosswalk,kurli/blink-crosswalk,XiaosongWei/blink-crosswalk,Bysmyyr/blink-crosswalk,kurli/blink-crosswalk,PeterWangIntel/blink-crosswalk,Bysmyyr/blink-crosswalk,kurli/blink-crosswalk,kurli/blink-crosswalk,PeterWangIntel/blink-crosswalk,PeterWangIntel/blink-crosswalk,PeterWangIntel/blink-crosswalk,XiaosongWei/blink-crosswalk,Pluto-tv/blink-crosswalk,PeterWangIntel/blink-crosswalk,Pluto-tv/blink-crosswalk,Bysmyyr/blink-crosswalk,Pluto-tv/blink-crosswalk,kurli/blink-crosswalk,XiaosongWei/blink-crosswalk,XiaosongWei/blink-crosswalk,smishenk/blink-crosswalk,kurli/blink-crosswalk,smishenk/blink-crosswalk,PeterWangIntel/blink-crosswalk,Pluto-tv/blink-crosswalk,kurli/blink-crosswalk,PeterWangIntel/blink-crosswalk,Pluto-tv/blink-crosswalk,Bysmyyr/blink-crosswalk,smishenk/blink-crosswalk,Bysmyyr/blink-crosswalk,Pluto-tv/blink-crosswalk,kurli/blink-crosswalk,smishenk/blink-crosswalk,kurli/blink-crosswalk,Bysmyyr/blink-crosswalk,Bysmyyr/blink-crosswalk,smishenk/blink-crosswalk,Bysmyyr/blink-crosswalk,Pluto-tv/blink-crosswalk,Bysmyyr/blink-crosswalk,XiaosongWei/blink-crosswalk,XiaosongWei/blink-crosswalk,smishenk/blink-crosswalk,Pluto-tv/blink-crosswalk,PeterWangIntel/blink-crosswalk,smishenk/blink-crosswalk,PeterWangIntel/blink-crosswalk,Bysmyyr/blink-crosswalk,XiaosongWei/blink-crosswalk,smishenk/blink-crosswalk
ad05100b6bcabeb2b21e25d3e9c2c7b50c444262
src/misc/parser_base.hpp
src/misc/parser_base.hpp
/* * Copyright (C) 2015-2017 Nagisa Sekiguchi * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef MISC_LIB_PARSER_BASE_HPP #define MISC_LIB_PARSER_BASE_HPP #include <vector> #include "lexer_base.hpp" BEGIN_MISC_LIB_NAMESPACE_DECL constexpr const char *TOKEN_MISMATCHED = "TokenMismatched"; constexpr const char *NO_VIABLE_ALTER = "NoViableAlter"; constexpr const char *INVALID_TOKEN = "InvalidToken"; constexpr const char *TOKEN_FORMAT = "TokenFormat"; constexpr const char *DEEP_NESTING = "DeepNesting"; template <typename T> class ParseErrorBase { private: T kind; Token errorToken; const char *errorKind; std::vector<T> expectedTokens; std::string message; public: ParseErrorBase(T kind, Token errorToken, const char *errorKind, std::string &&message) : kind(kind), errorToken(errorToken), errorKind(errorKind), expectedTokens(), message(std::move(message)) { } ParseErrorBase(T kind, Token errorToken, const char *errorKind, std::vector<T> &&expectedTokens, std::string &&message) : kind(kind), errorToken(errorToken), errorKind(errorKind), expectedTokens(std::move(expectedTokens)), message(std::move(message)) { } ~ParseErrorBase() = default; const Token &getErrorToken() const { return this->errorToken; } T getTokenKind() const { return this->kind; } const char *getErrorKind() const { return this->errorKind; } const std::vector<T> &getExpectedTokens() const { return this->expectedTokens; } const std::string &getMessage() const { return this->message; } }; template <typename T> struct EmptyTokenTracker { void operator()(T, Token) {} }; template<typename T, typename LexerImpl, typename Tracker = EmptyTokenTracker<T>> class ParserBase { protected: /** * need 'T nextToken(Token)' */ LexerImpl *lexer{nullptr}; T curKind{}; Token curToken{}; /** * kind of latest consumed token */ T consumedKind{}; /** * need 'void operator()(T, Token)' */ Tracker *tracker{nullptr}; unsigned int callCount{0}; private: std::unique_ptr<ParseErrorBase<T>> error; public: ParserBase() = default; ParserBase(ParserBase &&) noexcept = default; ParserBase &operator=(ParserBase &&o) noexcept { auto tmp(std::move(o)); this->swap(tmp); return *this; } void swap(ParserBase &o) noexcept { std::swap(this->lexer, o.lexer); std::swap(this->curKind, o.curKind); std::swap(this->curToken, o.curToken); std::swap(this->consumedKind, o.consumedKind); std::swap(this->tracker, o.tracker); std::swap(this->callCount, o.callCount); std::swap(this->error, o.error); } void setTracker(Tracker *other) { this->tracker = other; } const Tracker *getTracker() const { return this->tracker; } const LexerImpl *getLexer() const { return this->lexer; } bool hasError() const { return static_cast<bool>(this->error); } const ParseErrorBase<T> &getError() const { return *this->error; } void clear() { this->error.reset(); } protected: ~ParserBase() = default; /** * low level api. not directly use it. */ void fetchNext() { this->curKind = this->lexer->nextToken(this->curToken); } void trace() { this->consumedKind = this->curKind; if(this->tracker != nullptr) { (*this->tracker)(this->curKind, this->curToken); } } Token expect(T kind, bool fetchNext = true); void consume(); T scan() { T kind = this->curKind; this->consume(); return kind; } template <std::size_t N> void reportNoViableAlterError(const T (&alters)[N]) { this->reportNoViableAlterError(N, alters); } void reportTokenMismatchedError(T expected); void reportNoViableAlterError(unsigned int size, const T *alters); void reportInvalidTokenError(unsigned int size, const T *alters); void reportTokenFormatError(T kind, Token token, const char *msg); void reportDeepNestingError(); template <typename ...Arg> void createError(Arg && ...arg) { this->error.reset(new ParseErrorBase<T>(std::forward<Arg>(arg)...)); } }; // ######################## // ## ParserBase ## // ######################## template<typename T, typename LexerImpl, typename Tracker> Token ParserBase<T, LexerImpl, Tracker>::expect(T kind, bool fetchNext) { auto token = this->curToken; if(this->curKind != kind) { this->reportTokenMismatchedError(kind); return token; } this->trace(); if(fetchNext) { this->fetchNext(); } return token; } template<typename T, typename LexerImpl, typename Tracker> void ParserBase<T, LexerImpl, Tracker>::consume() { this->trace(); this->fetchNext(); } template<typename T, typename LexerImpl, typename Tracker> void ParserBase<T, LexerImpl, Tracker>::reportTokenMismatchedError(T expected) { if(isInvalidToken(this->curKind)) { T alter[1] = { expected }; this->reportInvalidTokenError(1, alter); } else { std::string message; if(!isEOSToken(this->curKind)) { message += "mismatched token `"; message += toString(this->curKind); message += "`, "; } message += "expected `"; message += toString(expected); message += "'"; std::vector<T> expectedTokens(1); expectedTokens[0] = expected; this->createError(this->curKind, this->curToken, TOKEN_MISMATCHED, std::move(expectedTokens), std::move(message)); } } template<typename T, typename LexerImpl, typename Tracker> void ParserBase<T, LexerImpl, Tracker>::reportNoViableAlterError(unsigned int size, const T *alters) { if(isInvalidToken(this->curKind)) { this->reportInvalidTokenError(size, alters); } else { std::string message; if(!isEOSToken(this->curKind)) { message += "mismatched token `"; message += toString(this->curKind); message += "`, "; } if(size > 0 && alters != nullptr) { message += "expected "; for(unsigned int i = 0; i < size; i++) { if(i > 0) { message += ", "; } message += "`"; message += toString(alters[i]); message += "'"; } } std::vector<T> expectedTokens(alters, alters + size); this->createError(this->curKind, this->curToken, NO_VIABLE_ALTER, std::move(expectedTokens), std::move(message)); } } template<typename T, typename LexerImpl, typename Tracker> void ParserBase<T, LexerImpl, Tracker>::reportInvalidTokenError(unsigned int size, const T *alters) { std::string message = "invalid token, expected "; if(size > 0 && alters != nullptr) { for(unsigned int i = 0; i < size; i++) { if(i > 0) { message += ", "; } message += "`"; message += toString(alters[i]); message += "'"; } } std::vector<T> expectedTokens(alters, alters + size); this->createError(this->curKind, this->curToken, INVALID_TOKEN, std::move(expectedTokens), std::move(message)); } template<typename T, typename LexerImpl, typename Tracker> void ParserBase<T, LexerImpl, Tracker>::reportTokenFormatError(T kind, Token token, const char *msg) { std::string message(msg); message += ": "; message += toString(kind); this->createError(kind, token, TOKEN_FORMAT, std::move(message)); } template<typename T, typename LexerImpl, typename Tracker> void ParserBase<T, LexerImpl, Tracker>::reportDeepNestingError() { std::string message = "parser recursion depth exceeded"; this->createError(this->curKind, this->curToken, DEEP_NESTING, std::move(message)); } END_MISC_LIB_NAMESPACE_DECL #endif //MISC_LIB_PARSER_BASE_HPP
/* * Copyright (C) 2015-2017 Nagisa Sekiguchi * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef MISC_LIB_PARSER_BASE_HPP #define MISC_LIB_PARSER_BASE_HPP #include <vector> #include "lexer_base.hpp" BEGIN_MISC_LIB_NAMESPACE_DECL constexpr const char *TOKEN_MISMATCHED = "TokenMismatched"; constexpr const char *NO_VIABLE_ALTER = "NoViableAlter"; constexpr const char *INVALID_TOKEN = "InvalidToken"; constexpr const char *TOKEN_FORMAT = "TokenFormat"; constexpr const char *DEEP_NESTING = "DeepNesting"; template <typename T> class ParseErrorBase { private: T kind; Token errorToken; const char *errorKind; std::vector<T> expectedTokens; std::string message; public: ParseErrorBase(T kind, Token errorToken, const char *errorKind, std::string &&message) : kind(kind), errorToken(errorToken), errorKind(errorKind), expectedTokens(), message(std::move(message)) { } ParseErrorBase(T kind, Token errorToken, const char *errorKind, std::vector<T> &&expectedTokens, std::string &&message) : kind(kind), errorToken(errorToken), errorKind(errorKind), expectedTokens(std::move(expectedTokens)), message(std::move(message)) { } ~ParseErrorBase() = default; const Token &getErrorToken() const { return this->errorToken; } T getTokenKind() const { return this->kind; } const char *getErrorKind() const { return this->errorKind; } const std::vector<T> &getExpectedTokens() const { return this->expectedTokens; } const std::string &getMessage() const { return this->message; } }; template <typename T> struct EmptyTokenTracker { void operator()(T, Token) {} }; template<typename T, typename LexerImpl, typename Tracker = EmptyTokenTracker<T>> class ParserBase { protected: /** * need 'T nextToken(Token)' */ LexerImpl *lexer{nullptr}; T curKind{}; Token curToken{}; /** * kind of latest consumed token */ T consumedKind{}; /** * need 'void operator()(T, Token)' */ Tracker *tracker{nullptr}; unsigned int callCount{0}; private: std::unique_ptr<ParseErrorBase<T>> error; public: ParserBase() = default; ParserBase(ParserBase &&) noexcept = default; ParserBase &operator=(ParserBase &&o) noexcept { auto tmp(std::move(o)); this->swap(tmp); return *this; } void swap(ParserBase &o) noexcept { std::swap(this->lexer, o.lexer); std::swap(this->curKind, o.curKind); std::swap(this->curToken, o.curToken); std::swap(this->consumedKind, o.consumedKind); std::swap(this->tracker, o.tracker); std::swap(this->callCount, o.callCount); std::swap(this->error, o.error); } void setTracker(Tracker *other) { this->tracker = other; } const Tracker *getTracker() const { return this->tracker; } const LexerImpl *getLexer() const { return this->lexer; } bool hasError() const { return static_cast<bool>(this->error); } const ParseErrorBase<T> &getError() const { return *this->error; } void clear() { this->error.reset(); } protected: ~ParserBase() = default; /** * low level api. not directly use it. */ void fetchNext() { this->curKind = this->lexer->nextToken(this->curToken); } void trace() { this->consumedKind = this->curKind; if(this->tracker != nullptr) { (*this->tracker)(this->curKind, this->curToken); } } Token expect(T kind, bool fetchNext = true); void consume(); T scan() { T kind = this->curKind; this->consume(); return kind; } template <std::size_t N> void reportNoViableAlterError(const T (&alters)[N]) { this->reportNoViableAlterError(N, alters); } void reportTokenMismatchedError(T expected); void reportNoViableAlterError(unsigned int size, const T *alters); void reportInvalidTokenError(unsigned int size, const T *alters); void reportTokenFormatError(T kind, Token token, const char *msg); void reportDeepNestingError(); template <typename ...Arg> void createError(Arg && ...arg) { this->error.reset(new ParseErrorBase<T>(std::forward<Arg>(arg)...)); } }; // ######################## // ## ParserBase ## // ######################## template<typename T, typename LexerImpl, typename Tracker> Token ParserBase<T, LexerImpl, Tracker>::expect(T kind, bool fetchNext) { auto token = this->curToken; if(this->curKind != kind) { this->reportTokenMismatchedError(kind); return token; } this->trace(); if(fetchNext) { this->fetchNext(); } return token; } template<typename T, typename LexerImpl, typename Tracker> void ParserBase<T, LexerImpl, Tracker>::consume() { this->trace(); this->fetchNext(); } template<typename T, typename LexerImpl, typename Tracker> void ParserBase<T, LexerImpl, Tracker>::reportTokenMismatchedError(T expected) { if(isInvalidToken(this->curKind)) { T alter[1] = { expected }; this->reportInvalidTokenError(1, alter); } else { std::string message; if(!isEOSToken(this->curKind)) { message += "mismatched token `"; message += toString(this->curKind); message += "', "; } message += "expected `"; message += toString(expected); message += "'"; std::vector<T> expectedTokens(1); expectedTokens[0] = expected; this->createError(this->curKind, this->curToken, TOKEN_MISMATCHED, std::move(expectedTokens), std::move(message)); } } template<typename T, typename LexerImpl, typename Tracker> void ParserBase<T, LexerImpl, Tracker>::reportNoViableAlterError(unsigned int size, const T *alters) { if(isInvalidToken(this->curKind)) { this->reportInvalidTokenError(size, alters); } else { std::string message; if(!isEOSToken(this->curKind)) { message += "mismatched token `"; message += toString(this->curKind); message += "', "; } if(size > 0 && alters != nullptr) { message += "expected "; for(unsigned int i = 0; i < size; i++) { if(i > 0) { message += ", "; } message += "`"; message += toString(alters[i]); message += "'"; } } std::vector<T> expectedTokens(alters, alters + size); this->createError(this->curKind, this->curToken, NO_VIABLE_ALTER, std::move(expectedTokens), std::move(message)); } } template<typename T, typename LexerImpl, typename Tracker> void ParserBase<T, LexerImpl, Tracker>::reportInvalidTokenError(unsigned int size, const T *alters) { std::string message = "invalid token, expected "; if(size > 0 && alters != nullptr) { for(unsigned int i = 0; i < size; i++) { if(i > 0) { message += ", "; } message += "`"; message += toString(alters[i]); message += "'"; } } std::vector<T> expectedTokens(alters, alters + size); this->createError(this->curKind, this->curToken, INVALID_TOKEN, std::move(expectedTokens), std::move(message)); } template<typename T, typename LexerImpl, typename Tracker> void ParserBase<T, LexerImpl, Tracker>::reportTokenFormatError(T kind, Token token, const char *msg) { std::string message(msg); message += ": "; message += toString(kind); this->createError(kind, token, TOKEN_FORMAT, std::move(message)); } template<typename T, typename LexerImpl, typename Tracker> void ParserBase<T, LexerImpl, Tracker>::reportDeepNestingError() { std::string message = "parser recursion depth exceeded"; this->createError(this->curKind, this->curToken, DEEP_NESTING, std::move(message)); } END_MISC_LIB_NAMESPACE_DECL #endif //MISC_LIB_PARSER_BASE_HPP
fix parser error message
fix parser error message
C++
apache-2.0
sekiguchi-nagisa/ydsh,sekiguchi-nagisa/ydsh,sekiguchi-nagisa/ydsh
0a9068780501887dd731c60e441139c5caefa92d
examples/tagwriter.cpp
examples/tagwriter.cpp
/* Copyright (C) 2004 Scott Wheeler <[email protected]> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <iostream> #include <string.h> #include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <stdlib.h> #include <tlist.h> #include <fileref.h> #include <tfile.h> #include <tag.h> using namespace std; bool isArgument(const char *s) { return strlen(s) == 2 && s[0] == '-'; } bool isFile(const char *s) { struct stat st; #ifdef _WIN32 return ::stat(s, &st) == 0 && (st.st_mode & (S_IFREG)); #else return ::stat(s, &st) == 0 && (st.st_mode & (S_IFREG | S_IFLNK)); #endif } void usage() { cout << endl; cout << "Usage: tagwriter <fields> <files>" << endl; cout << endl; cout << "Where the valid fields are:" << endl; cout << " -t <title>" << endl; cout << " -a <artist>" << endl; cout << " -A <album>" << endl; cout << " -c <comment>" << endl; cout << " -g <genre>" << endl; cout << " -y <year>" << endl; cout << " -T <track>" << endl; cout << endl; exit(1); } int main(int argc, char *argv[]) { TagLib::List<TagLib::FileRef> fileList; while(argc > 0 && isFile(argv[argc - 1])) { TagLib::FileRef f(argv[argc - 1]); if(!f.isNull() && f.tag()) fileList.append(f); argc--; } if(fileList.isEmpty()) usage(); for(int i = 1; i < argc - 1; i += 2) { if(isArgument(argv[i]) && i + 1 < argc && !isArgument(argv[i + 1])) { char field = argv[i][1]; TagLib::String value = argv[i + 1]; TagLib::List<TagLib::FileRef>::ConstIterator it; for(it = fileList.begin(); it != fileList.end(); ++it) { TagLib::Tag *t = (*it).tag(); switch (field) { case 't': t->setTitle(value); break; case 'a': t->setArtist(value); break; case 'A': t->setAlbum(value); break; case 'c': t->setComment(value); break; case 'g': t->setGenre(value); break; case 'y': t->setYear(value.toInt()); break; case 'T': t->setTrack(value.toInt()); break; default: usage(); break; } } } else usage(); } TagLib::List<TagLib::FileRef>::ConstIterator it; for(it = fileList.begin(); it != fileList.end(); ++it) (*it).file()->save(); return 0; }
/* Copyright (C) 2004 Scott Wheeler <[email protected]> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <iostream> #include <iomanip> #include <string.h> #include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <stdlib.h> #include <tlist.h> #include <fileref.h> #include <tfile.h> #include <tag.h> #include <tpropertymap.h> using namespace std; bool isArgument(const char *s) { return strlen(s) == 2 && s[0] == '-'; } bool isFile(const char *s) { struct stat st; #ifdef _WIN32 return ::stat(s, &st) == 0 && (st.st_mode & (S_IFREG)); #else return ::stat(s, &st) == 0 && (st.st_mode & (S_IFREG | S_IFLNK)); #endif } void usage() { cout << endl; cout << "Usage: tagwriter <fields> <files>" << endl; cout << endl; cout << "Where the valid fields are:" << endl; cout << " -t <title>" << endl; cout << " -a <artist>" << endl; cout << " -A <album>" << endl; cout << " -c <comment>" << endl; cout << " -g <genre>" << endl; cout << " -y <year>" << endl; cout << " -T <track>" << endl; cout << " -R <tagname> <tagvalue>" << endl; cout << " -I <tagname> <tagvalue>" << endl; cout << " -D <tagname>" << endl; cout << endl; exit(1); } void checkForRejectedProperties(const TagLib::PropertyMap &tags) { // stolen from tagreader.cpp if(tags.size() > 0) { unsigned int longest = 0; for(TagLib::PropertyMap::ConstIterator i = tags.begin(); i != tags.end(); ++i) { if(i->first.size() > longest) { longest = i->first.size(); } } cout << "-- rejected TAGs (properties) --" << endl; for(TagLib::PropertyMap::ConstIterator i = tags.begin(); i != tags.end(); ++i) { for(TagLib::StringList::ConstIterator j = i->second.begin(); j != i->second.end(); ++j) { cout << left << std::setw(longest) << i->first << " - " << '"' << *j << '"' << endl; } } } } int main(int argc, char *argv[]) { TagLib::List<TagLib::FileRef> fileList; while(argc > 0 && isFile(argv[argc - 1])) { TagLib::FileRef f(argv[argc - 1]); if(!f.isNull() && f.tag()) fileList.append(f); argc--; } if(fileList.isEmpty()) usage(); for(int i = 1; i < argc - 1; i += 2) { if(isArgument(argv[i]) && i + 1 < argc && !isArgument(argv[i + 1])) { char field = argv[i][1]; TagLib::String value = argv[i + 1]; TagLib::List<TagLib::FileRef>::ConstIterator it; for(it = fileList.begin(); it != fileList.end(); ++it) { TagLib::Tag *t = (*it).tag(); switch (field) { case 't': t->setTitle(value); break; case 'a': t->setArtist(value); break; case 'A': t->setAlbum(value); break; case 'c': t->setComment(value); break; case 'g': t->setGenre(value); break; case 'y': t->setYear(value.toInt()); break; case 'T': t->setTrack(value.toInt()); break; case 'R': case 'I': if(i + 2 < argc) { TagLib::PropertyMap map = (*it).file()->properties (); if(field == 'R') { map.replace(value, TagLib::String(argv[i + 2])); } else { map.insert(value, TagLib::String(argv[i + 2])); } ++i; checkForRejectedProperties((*it).file()->setProperties(map)); } else { usage(); } break; case 'D': { TagLib::PropertyMap map = (*it).file()->properties(); map.erase(value); checkForRejectedProperties((*it).file()->setProperties(map)); break; } default: usage(); break; } } } else usage(); } TagLib::List<TagLib::FileRef>::ConstIterator it; for(it = fileList.begin(); it != fileList.end(); ++it) (*it).file()->save(); return 0; }
add options R, I, D for replace/insert/delete of arbitrary tags
add options R, I, D for replace/insert/delete of arbitrary tags
C++
lgpl-2.1
TsudaKageyu/taglib,i80and/taglib,TsudaKageyu/taglib,taglib/taglib,i80and/taglib,TsudaKageyu/taglib,taglib/taglib,dlz1123/taglib,pbhd/taglib,black78/taglib,black78/taglib,taglib/taglib,dlz1123/taglib,dlz1123/taglib,black78/taglib,Distrotech/taglib,pbhd/taglib,Distrotech/taglib,i80and/taglib,Distrotech/taglib,pbhd/taglib
74926702b3d5db4ae607f9029abd9209dac43e9d
DungeonsOfNoudar486/DOS-version/WindowOperationsDOS.cpp
DungeonsOfNoudar486/DOS-version/WindowOperationsDOS.cpp
#include <stdio.h> #include <stdlib.h> #include <osmesa.h> #include <conio.h> // For kbhit, getch, textmode (console access) #include <dpmi.h> // For __dpmi_int (mouse access) #include <go32.h> // For _dos_ds (VRAM access) #include <sys/movedata.h> // For movedata (VRAM access) #include <cstdlib> #include <cstdio> #include <cmath> #include <algorithm> #include <GL/glu.h> // GLU = OpenGL utility library #include <glm/glm.hpp> #include <glm/gtc/type_ptr.hpp> #include <glm/gtc/matrix_transform.hpp> #include <cstdio> #include <assert.h> #include <math.h> #include <stdlib.h> #include <stdio.h> #include <vector> #include <string.h> #include <memory> #include <iostream> #include <map> #include <array> #include <iostream> #include <stdio.h> #include <stdlib.h> #include <GL/gl.h> #include <GL/glu.h> #include <pc.h> #include "NativeBitmap.h" #include "SoundClip.h" #include "SoundUtils.h" #include "SoundListener.h" #include "SoundEmitter.h" #include "IFileLoaderDelegate.h" #include "Vec2i.h" #include "NativeBitmap.h" #include "IMapElement.h" #include "CTeam.h" #include "CActor.h" #include "CGameDelegate.h" #include "CMap.h" #include "IRenderer.h" #include "NoudarDungeonSnapshot.h" #include "GameNativeAPI.h" #include "WindowOperations.h" #include "Common.h" #include "LoadPNG.h" bool inGraphics = true; std::vector<std::shared_ptr<odb::NativeBitmap>> gunStates; std::vector<std::shared_ptr<odb::NativeBitmap>>::iterator gunState; std::array< int, 4 > soundSource = { 100, }; std::array<int, 10>::iterator soundPos = std::end( soundSource ); namespace PC { const unsigned W = 320, H = 200; unsigned ImageBuffer[W * H]; int selector; void Init() { __dpmi_regs r; r.x.ax = 0x13; __dpmi_int(0x10, &r); outp(0x03c8, 0); for ( int r = 0; r < 4; ++r ) { for ( int g = 0; g < 4; ++g ) { for ( int b = 0; b < 4; ++b ) { outp(0x03c9, (r * 85)); outp(0x03c9, (g * 85)); outp(0x03c9, (b * 85)); } } } } void renderPalette() { _farsetsel(_dos_ds); int offset = 0; int fullSize = 320 * 200; for (int r = 0; r < 255; ++r) { for (int x = 0; x < 50; ++x) { int shade = 0; int origin = r << 16; shade += (((((origin & 0x0000FF))) / 85)); shade += (((((origin & 0x00FF00) >> 8)) / 85)) << 2; shade += (((((origin & 0xFF0000) >> 16)) / 85)) << 4; _farnspokeb(0xA0000 + (320 * x) + r, shade); } } for (int g = 0; g < 255; ++g) { for (int x = 50; x < 100; ++x) { int shade = 0; int origin = g << 8; shade += (((((origin & 0x0000FF))) / 85)); shade += (((((origin & 0x00FF00) >> 8)) / 85)) << 2; shade += (((((origin & 0xFF0000) >> 16)) / 85)) << 4; _farnspokeb(0xA0000 + (320 * x) + g, shade); } } for (int b = 0; b < 255; ++b) { for (int x = 100; x < 150; ++x) { int shade = 0; int origin = b; shade += (((((origin & 0x0000FF))) / 85)); shade += (((((origin & 0x00FF00) >> 8)) / 85)) << 2; shade += (((((origin & 0xFF0000) >> 16)) / 85)) << 4; _farnspokeb(0xA0000 + (320 * x) + b, shade); } } for (int b = 0; b < 255; ++b) { for (int x = 150; x < 200; ++x) { _farnspokeb(0xA0000 + (320 * x) + b, b); } } std::fill(std::end(ImageBuffer) - (320 * 200), std::end(ImageBuffer), 0x0); } void Render() { _farsetsel(_dos_ds); auto pixelData = (*gunState)->getPixelData(); int offset = 0; int fullSize = 320 * 200; for (int y = 100; y < 200; ++y) { for (int x = 80; x < 240; ++x) { offset = (320 * y) + x; auto origin = ImageBuffer[offset]; offset = (320 * (200 - (2 * (y - 100)))) + (((x - 80) * 320) / 160); if (pixelData[offset] & 0xFF000000) { origin = pixelData[offset]; } int shade = 0; shade += (((((origin & 0x0000FF) ) ) / 85 ) ); shade += (((((origin & 0x00FF00) >> 8 ) ) / 85 ) ) << 2; shade += (((((origin & 0xFF0000) >> 16) ) / 85 ) ) << 4; _farnspokeb( 0xA0000 + 160 + ((200 - (2 * ((y - 100)))) * 320) + ((2 * x)) + 1, shade); _farnspokeb( 0xA0000 + 160 + ((199 - (2 * ((y - 100)))) * 320) + ((2 * x)), shade); _farnspokeb( 0xA0000 + 160 + ((200 - (2 * ((y - 100)))) * 320) + ((2 * x)), shade); _farnspokeb( 0xA0000 + 160 + ((199 - (2 * ((y - 100)))) * 320) + ((2 * x)) + 1, shade); } } std::fill(std::end(ImageBuffer) - (320 * 100), std::end(ImageBuffer), 0x0); } void Close() // End graphics { textmode(C80); // Set textmode again. } } void setGraphics() { inGraphics = true; PC::Init(); } void setTextMode() { inGraphics = false; __dpmi_regs r; r.x.ax = 3; __dpmi_int(0x10, &r); } const int winWidth = 320, winHeight = 200; bool done = false; bool isActive = false; std::vector <std::shared_ptr<odb::NativeBitmap>> loadTextures() { std::vector<std::shared_ptr<odb::NativeBitmap>> toReturn; toReturn.push_back( loadPNG( "res/grass.ppm") ); toReturn.push_back( loadPNG( "res/stonef1.ppm") ); toReturn.push_back( loadPNG( "res/bricks.ppm") ); toReturn.push_back( loadPNG( "res/arch.ppm") ); toReturn.push_back( loadPNG( "res/bars.ppm") ); toReturn.push_back( loadPNG( "res/begin.ppm") ); toReturn.push_back( loadPNG( "res/exit.ppm") ); toReturn.push_back( loadPNG( "res/bricks2.ppm") ); toReturn.push_back( loadPNG( "res/bricks3.ppm") ); toReturn.push_back( loadPNG( "res/turtle0.ppm") ); toReturn.push_back( loadPNG( "res/turtle0.ppm") ); toReturn.push_back( loadPNG( "res/turtle1.ppm") ); toReturn.push_back( loadPNG( "res/turtle1.ppm") ); toReturn.push_back( loadPNG( "res/turtle1.ppm") ); toReturn.push_back( loadPNG( "res/turtle1.ppm") ); toReturn.push_back( loadPNG( "res/crusad0.ppm") ); toReturn.push_back( loadPNG( "res/crusad1.ppm") ); toReturn.push_back( loadPNG( "res/crusad2.ppm") ); toReturn.push_back( loadPNG( "res/shadow.ppm") ); toReturn.push_back( loadPNG( "res/ceilin.ppm") ); toReturn.push_back( loadPNG( "res/ceigdr.ppm") ); toReturn.push_back( loadPNG( "res/ceigbgn.ppm") ); toReturn.push_back( loadPNG( "res/ceilend.ppm") ); toReturn.push_back( loadPNG( "res/splat0.ppm") ); toReturn.push_back( loadPNG( "res/splat1.ppm") ); toReturn.push_back( loadPNG( "res/splat2.ppm") ); toReturn.push_back( loadPNG( "res/ceilbar.ppm") ); toReturn.push_back( loadPNG( "res/clouds.ppm")); toReturn.push_back( loadPNG( "res/stngrsf.ppm")); toReturn.push_back( loadPNG( "res/grsstnf.ppm")); toReturn.push_back( loadPNG( "res/stngrsn.ppm")); toReturn.push_back( loadPNG( "res/grsstnn.ppm")); toReturn.push_back( loadPNG( "res/cross.ppm")); return toReturn; } void initWindow() { auto textures = loadTextures(); gunStates.push_back( loadPNG( "res/shotgun0.ppm", 320, 200) ); gunStates.push_back( loadPNG( "res/shotgun1.ppm", 320, 200) ); gunState = std::begin( gunStates ); OSMesaContext om = OSMesaCreateContext(OSMESA_RGBA, NULL); OSMesaMakeCurrent(om, PC::ImageBuffer, GL_UNSIGNED_BYTE, PC::W, PC::H); PC::Init(); auto gVertexShader = ""; auto gFragmentShader = ""; setupGraphics(winWidth, winHeight, gVertexShader, gFragmentShader, textures); auto soundListener = std::make_shared<odb::SoundListener>(); std::vector<std::shared_ptr<odb::SoundEmitter>> sounds; std::string filenames[] { "res/grasssteps.wav", "res/stepsstones.wav", "res/bgnoise.wav", "res/monsterdamage.wav", "res/monsterdead.wav", "res/playerdamage.wav", "res/playerdead.wav", "res/swing.wav" }; for ( auto filename : filenames ) { FILE *file = fopen( filename.c_str(), "r"); auto soundClip = odb::makeSoundClipFrom( file ); sounds.push_back( std::make_shared<odb::SoundEmitter>(soundClip) ); } setSoundEmitters( sounds, soundListener ); } void tick() { //if I want at least 10fps, I need my rendering and updates to take no more than 100ms, combined if ( inGraphics ) { gameLoopTick( 250 ); renderFrame( 250 ); PC::Render(); if ( gunState != std::begin( gunStates ) ) { gunState = std::prev( gunState ); } if ( soundPos != std::end( soundSource ) ) { sound( *soundPos ); soundPos = std::next( soundPos ); } else { nosound(); } } } void setMainLoop() { while ( !done ) { while(kbhit()) switch(getch()) { case 27: done = true; break; case '1': setGraphics(); break; case '2': setTextMode(); break; case 'w': moveUp(); break; case 's': moveDown(); break; case 'd': moveRight(); break; case 'a': moveLeft(); break; case 'h': interact(); gunState = std::prev(std::end(gunStates)); soundPos = std::begin( soundSource ); break; case 'e': rotateCameraRight(); break; case 'q': rotateCameraLeft(); break; } tick(); } } void destroyWindow() { shutdown(); }
#include <stdio.h> #include <stdlib.h> #include <osmesa.h> #include <conio.h> // For kbhit, getch, textmode (console access) #include <dpmi.h> // For __dpmi_int (mouse access) #include <go32.h> // For _dos_ds (VRAM access) #include <sys/movedata.h> // For movedata (VRAM access) #include <cstdlib> #include <cstdio> #include <cmath> #include <algorithm> #include <GL/glu.h> // GLU = OpenGL utility library #include <glm/glm.hpp> #include <glm/gtc/type_ptr.hpp> #include <glm/gtc/matrix_transform.hpp> #include <cstdio> #include <assert.h> #include <math.h> #include <stdlib.h> #include <stdio.h> #include <vector> #include <string.h> #include <memory> #include <iostream> #include <map> #include <array> #include <iostream> #include <stdio.h> #include <stdlib.h> #include <GL/gl.h> #include <GL/glu.h> #include <pc.h> #include "NativeBitmap.h" #include "SoundClip.h" #include "SoundUtils.h" #include "SoundListener.h" #include "SoundEmitter.h" #include "IFileLoaderDelegate.h" #include "Vec2i.h" #include "NativeBitmap.h" #include "IMapElement.h" #include "CTeam.h" #include "CActor.h" #include "CGameDelegate.h" #include "CMap.h" #include "IRenderer.h" #include "NoudarDungeonSnapshot.h" #include "GameNativeAPI.h" #include "WindowOperations.h" #include "Common.h" #include "LoadPNG.h" bool inGraphics = true; std::vector<std::shared_ptr<odb::NativeBitmap>> gunStates; std::vector<std::shared_ptr<odb::NativeBitmap>>::iterator gunState; std::array< int, 4 > soundSource = { 100, }; std::array<int, 10>::iterator soundPos = std::end( soundSource ); namespace PC { const unsigned W = 320, H = 200; unsigned ImageBuffer[W * H]; int selector; void Init() { __dpmi_regs r; r.x.ax = 0x13; __dpmi_int(0x10, &r); outp(0x03c8, 0); for ( int r = 0; r < 4; ++r ) { for ( int g = 0; g < 4; ++g ) { for ( int b = 0; b < 4; ++b ) { outp(0x03c9, (r * 85)); outp(0x03c9, (g * 85)); outp(0x03c9, (b * 85)); } } } } void renderPalette() { _farsetsel(_dos_ds); int offset = 0; int fullSize = 320 * 200; for (int r = 0; r < 255; ++r) { for (int x = 0; x < 50; ++x) { int shade = 0; int origin = r << 16; shade += (((((origin & 0x0000FF))) / 85)); shade += (((((origin & 0x00FF00) >> 8)) / 85)) << 2; shade += (((((origin & 0xFF0000) >> 16)) / 85)) << 4; _farnspokeb(0xA0000 + (320 * x) + r, shade); } } for (int g = 0; g < 255; ++g) { for (int x = 50; x < 100; ++x) { int shade = 0; int origin = g << 8; shade += (((((origin & 0x0000FF))) / 85)); shade += (((((origin & 0x00FF00) >> 8)) / 85)) << 2; shade += (((((origin & 0xFF0000) >> 16)) / 85)) << 4; _farnspokeb(0xA0000 + (320 * x) + g, shade); } } for (int b = 0; b < 255; ++b) { for (int x = 100; x < 150; ++x) { int shade = 0; int origin = b; shade += (((((origin & 0x0000FF))) / 85)); shade += (((((origin & 0x00FF00) >> 8)) / 85)) << 2; shade += (((((origin & 0xFF0000) >> 16)) / 85)) << 4; _farnspokeb(0xA0000 + (320 * x) + b, shade); } } for (int b = 0; b < 255; ++b) { for (int x = 150; x < 200; ++x) { _farnspokeb(0xA0000 + (320 * x) + b, b); } } std::fill(std::end(ImageBuffer) - (320 * 200), std::end(ImageBuffer), 0x0); } void Render() { _farsetsel(_dos_ds); auto pixelData = (*gunState)->getPixelData(); int offset = 0; int fullSize = 320 * 200; for (int y = 100; y < 200; ++y) { for (int x = 80; x < 240; ++x) { offset = (320 * y) + x; auto origin = ImageBuffer[offset]; offset = (320 * (200 - (2 * (y - 100)))) + (((x - 80) * 320) / 160); if (pixelData[offset] & 0xFF000000) { origin = pixelData[offset]; } int shade = 0; shade += (((((origin & 0x0000FF) ) ) / 85 ) ); shade += (((((origin & 0x00FF00) >> 8 ) ) / 85 ) ) << 2; shade += (((((origin & 0xFF0000) >> 16) ) / 85 ) ) << 4; _farnspokeb( 0xA0000 + 160 + ((200 - (2 * ((y - 100)))) * 320) + ((2 * x)) + 1, shade); _farnspokeb( 0xA0000 + 160 + ((199 - (2 * ((y - 100)))) * 320) + ((2 * x)), shade); _farnspokeb( 0xA0000 + 160 + ((200 - (2 * ((y - 100)))) * 320) + ((2 * x)), shade); _farnspokeb( 0xA0000 + 160 + ((199 - (2 * ((y - 100)))) * 320) + ((2 * x)) + 1, shade); } } std::fill(std::end(ImageBuffer) - (320 * 100), std::end(ImageBuffer), 0x0); } void Close() // End graphics { textmode(C80); // Set textmode again. } } void setGraphics() { inGraphics = true; PC::Init(); } void setTextMode() { inGraphics = false; __dpmi_regs r; r.x.ax = 3; __dpmi_int(0x10, &r); } const int winWidth = 320, winHeight = 200; bool done = false; bool isActive = false; std::vector <std::shared_ptr<odb::NativeBitmap>> loadTextures() { std::vector<std::shared_ptr<odb::NativeBitmap>> toReturn; toReturn.push_back( loadPNG( "res/grass.ppm") ); toReturn.push_back( loadPNG( "res/stonef1.ppm") ); toReturn.push_back( loadPNG( "res/bricks.ppm") ); toReturn.push_back( loadPNG( "res/arch.ppm") ); toReturn.push_back( loadPNG( "res/bars.ppm") ); toReturn.push_back( loadPNG( "res/begin.ppm") ); toReturn.push_back( loadPNG( "res/exit.ppm") ); toReturn.push_back( loadPNG( "res/bricks2.ppm") ); toReturn.push_back( loadPNG( "res/bricks3.ppm") ); toReturn.push_back( loadPNG( "res/turtle0.ppm") ); toReturn.push_back( loadPNG( "res/turtle0.ppm") ); toReturn.push_back( loadPNG( "res/turtle1.ppm") ); toReturn.push_back( loadPNG( "res/turtle1.ppm") ); toReturn.push_back( loadPNG( "res/turtle1.ppm") ); toReturn.push_back( loadPNG( "res/turtle1.ppm") ); toReturn.push_back( loadPNG( "res/crusad0.ppm") ); toReturn.push_back( loadPNG( "res/crusad1.ppm") ); toReturn.push_back( loadPNG( "res/crusad2.ppm") ); toReturn.push_back( loadPNG( "res/shadow.ppm") ); toReturn.push_back( loadPNG( "res/ceilin.ppm") ); toReturn.push_back( loadPNG( "res/ceigdr.ppm") ); toReturn.push_back( loadPNG( "res/ceigbgn.ppm") ); toReturn.push_back( loadPNG( "res/ceilend.ppm") ); toReturn.push_back( loadPNG( "res/splat0.ppm") ); toReturn.push_back( loadPNG( "res/splat1.ppm") ); toReturn.push_back( loadPNG( "res/splat2.ppm") ); toReturn.push_back( loadPNG( "res/ceilbar.ppm") ); toReturn.push_back( loadPNG( "res/clouds.ppm")); toReturn.push_back( loadPNG( "res/stngrsf.ppm")); toReturn.push_back( loadPNG( "res/grsstnf.ppm")); toReturn.push_back( loadPNG( "res/stngrsn.ppm")); toReturn.push_back( loadPNG( "res/grsstnn.ppm")); toReturn.push_back( loadPNG( "res/cross.ppm")); return toReturn; } void initWindow() { auto textures = loadTextures(); gunStates.push_back( loadPNG( "res/shotgun0.ppm", 320, 200) ); gunStates.push_back( loadPNG( "res/shotgun1.ppm", 320, 200) ); gunState = std::begin( gunStates ); OSMesaContext om = OSMesaCreateContext(OSMESA_RGBA, NULL); OSMesaMakeCurrent(om, PC::ImageBuffer, GL_UNSIGNED_BYTE, PC::W, PC::H); PC::Init(); auto gVertexShader = ""; auto gFragmentShader = ""; setupGraphics(winWidth, winHeight, gVertexShader, gFragmentShader, textures); auto soundListener = std::make_shared<odb::SoundListener>(); std::vector<std::shared_ptr<odb::SoundEmitter>> sounds; std::string filenames[] { "res/grasssteps.wav", "res/stepsstones.wav", "res/bgnoise.wav", "res/monsterdamage.wav", "res/monsterdead.wav", "res/playerdamage.wav", "res/playerdead.wav", "res/swing.wav" }; for ( auto filename : filenames ) { FILE *file = fopen( filename.c_str(), "r"); auto soundClip = odb::makeSoundClipFrom( file ); sounds.push_back( std::make_shared<odb::SoundEmitter>(soundClip) ); } setSoundEmitters( sounds, soundListener ); } void tick() { //if I want at least 10fps, I need my rendering and updates to take no more than 100ms, combined if ( inGraphics ) { gameLoopTick( 250 ); renderFrame( 250 ); PC::Render(); if ( gunState != std::begin( gunStates ) ) { gunState = std::prev( gunState ); } if ( soundPos != std::end( soundSource ) ) { sound( *soundPos ); soundPos = std::next( soundPos ); } else { nosound(); } } } void setMainLoop() { while ( !done ) { while(kbhit()) switch(getch()) { case 27: done = true; break; case '1': setGraphics(); break; case '2': setTextMode(); break; case 'w': moveUp(); break; case 's': moveDown(); break; case 'd': moveRight(); break; case 'a': moveLeft(); break; case 'h': interact(); gunState = std::prev(std::end(gunStates)); soundPos = std::begin( soundSource ); break; case 'e': rotateCameraRight(); break; case 'q': rotateCameraLeft(); break; } tick(); } } void destroyWindow() { shutdown(); setTextMode(); clrscr(); std::cout << "Thank you for playing!" << std::endl; }
Add greeting at exit
Add greeting at exit
C++
bsd-2-clause
TheFakeMontyOnTheRun/dungeons-of-noudar,TheFakeMontyOnTheRun/dungeons-of-noudar
d09d3d8bcb9c3762e7ad9a22c79bd7f698a68c52
test/TestGroup.cpp
test/TestGroup.cpp
// Copyright © 2013,2014 German Neuroinformatics Node (G-Node) // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted under the terms of the BSD License. See // LICENSE file in the root of the Project. // // Author: Christian Kellner <[email protected]> #include <nix/hdf5/FileHDF5.hpp> #include "TestGroup.hpp" unsigned int & TestGroup::open_mode() { static unsigned int openMode = H5F_ACC_TRUNC; return openMode; } void TestGroup::setUp() { unsigned int &openMode = open_mode(); if (openMode == H5F_ACC_TRUNC) { h5file = H5Fcreate("test_group.h5", openMode, H5P_DEFAULT, H5P_DEFAULT); } else { h5file = H5Fopen("test_group.h5", openMode, H5P_DEFAULT); } CPPUNIT_ASSERT(H5Iis_valid(h5file)); if (openMode == H5F_ACC_TRUNC) { h5group = H5Gcreate2(h5file, "tstGroup", H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT); } else { h5group = H5Gopen2(h5file, "tstGroup", H5P_DEFAULT); } openMode = H5F_ACC_RDWR; } void TestGroup::tearDown() { H5Fclose(h5file); H5Oclose(h5group); } void TestGroup::testBaseTypes() { nix::hdf5::Group group(h5group); //int //attr group.setAttr("t_int", 42); int tint; group.getAttr("t_int", tint); CPPUNIT_ASSERT_EQUAL(tint, 42); //double //attr double deps = std::numeric_limits<double>::epsilon(); double dpi = boost::math::constants::pi<double>(); group.setAttr("t_double", dpi); double dbl; group.getAttr("t_double", dbl); CPPUNIT_ASSERT_DOUBLES_EQUAL(dpi, dbl, deps); //string const std::string testStr = "I saw the best minds of my generation destroyed by madness"; group.setAttr("t_string", testStr); std::string retString; group.getAttr("t_string", retString); CPPUNIT_ASSERT_EQUAL(testStr, retString); } void TestGroup::testMultiArray() { nix::hdf5::Group group(h5group); //arrays typedef boost::multi_array<double, 3> array_type; typedef array_type::index index; array_type A(boost::extents[3][4][2]); int values = 0; for(index i = 0; i != 3; ++i) for(index j = 0; j != 4; ++j) for(index k = 0; k != 2; ++k) A[i][j][k] = values++; group.setAttr<array_type>("t_doubleArray", A); array_type B(boost::extents[1][1][1]); group.getAttr("t_doubleArray", B); int verify = 0; int errors = 0; for(index i = 0; i != 3; ++i) { for(index j = 0; j != 4; ++j) { for(index k = 0; k != 2; ++k) { int v = verify++; errors += B[i][j][k] != v; } } } CPPUNIT_ASSERT_EQUAL(errors, 0); //data group.setData("t_doubleArray", A); array_type C(boost::extents[1][1][1]); group.getData("t_doubleArray", C); verify = 0; errors = 0; for(index i = 0; i != 3; ++i) { for(index j = 0; j != 4; ++j) { for(index k = 0; k != 2; ++k) { int v = verify++; errors += B[i][j][k] != v; } } } CPPUNIT_ASSERT_EQUAL(errors, 0); } void TestGroup::testVector() { nix::hdf5::Group group(h5group); std::vector<int> iv; iv.push_back(7); iv.push_back(23); iv.push_back(42); iv.push_back(1982); group.setAttr("t_intvector", iv); std::vector<int> tiv; group.getAttr("t_intvector", tiv); assert_vectors_equal(iv, tiv); std::vector<std::string> sv; sv.push_back("Alle"); sv.push_back("meine"); sv.push_back("Entchen"); group.setAttr("t_strvector", sv); std::vector<std::string> tsv; group.getAttr("t_strvector", tsv); assert_vectors_equal(sv, tsv); } void TestGroup::testArray() { nix::hdf5::Group group(h5group); int ia1d[5] = {1, 2, 3, 4, 5}; group.setAttr("t_intarray1d", ia1d); int tia1d[5] = {0, }; group.getAttr("t_intarray1d", tia1d); for (int i = 0; i < 5; i++) { CPPUNIT_ASSERT_EQUAL(ia1d[i], tia1d[i]); } #ifndef _WIN32 //cf. issue #72 int ia2d[3][2] = { {1, 2}, {3, 4}, {5, 6} }; group.setAttr("t_intarray2d", ia2d); int tia2d[3][2] = { {0, }, }; group.getAttr("t_intarray2d", tia2d); for (int i = 0; i < 3*2; i++) { CPPUNIT_ASSERT_EQUAL(*(ia2d[0] + i), *(tia2d[0] + i)); } #endif } void TestGroup::testOpen() { nix::hdf5::Group root(h5group); nix::hdf5::Group g = root.openGroup("name_a", true); std::string uuid = nix::util::createId(); g.setAttr("entity_id", uuid); CPPUNIT_ASSERT(root.hasGroup("name_a")); std::string idout; boost::optional<nix::hdf5::Group> a = root.findGroupByNameOrAttribute("entity_id", "name_a"); CPPUNIT_ASSERT(a); CPPUNIT_ASSERT(a->hasAttr("entity_id")); a->getAttr("entity_id", idout); CPPUNIT_ASSERT_EQUAL(uuid, idout); boost::optional<nix::hdf5::Group> b = root.findGroupByNameOrAttribute("entity_id", uuid); CPPUNIT_ASSERT(b); CPPUNIT_ASSERT(b->hasAttr("entity_id")); b->getAttr("entity_id", idout); CPPUNIT_ASSERT_EQUAL(uuid, idout); } void TestGroup::testRefCount() { nix::hdf5::Group wrapped(h5group); CPPUNIT_ASSERT_EQUAL(2, H5Iget_ref(h5group)); CPPUNIT_ASSERT_EQUAL(h5group, wrapped.h5id()); CPPUNIT_ASSERT_EQUAL(2, H5Iget_ref(h5group)); nix::hdf5::Group g; CPPUNIT_ASSERT_EQUAL(H5I_INVALID_HID, g.h5id()); g = nix::hdf5::Group(h5group); CPPUNIT_ASSERT_EQUAL(h5group, g.h5id()); CPPUNIT_ASSERT_EQUAL(3, H5Iget_ref(h5group)); nix::hdf5::Group c = g; CPPUNIT_ASSERT_EQUAL(h5group, c.h5id()); CPPUNIT_ASSERT_EQUAL(4, H5Iget_ref(h5group)); { nix::hdf5::Group tmp = g; CPPUNIT_ASSERT_EQUAL(h5group, tmp.h5id()); CPPUNIT_ASSERT_EQUAL(5, H5Iget_ref(h5group)); } CPPUNIT_ASSERT_EQUAL(4, H5Iget_ref(h5group)); hid_t ha = H5Gopen2(h5file, "/", H5P_DEFAULT); CPPUNIT_ASSERT(ha != h5group); CPPUNIT_ASSERT_EQUAL(1, H5Iget_ref(ha)); nix::hdf5::Group b(ha); CPPUNIT_ASSERT_EQUAL(ha, b.h5id()); CPPUNIT_ASSERT_EQUAL(2, H5Iget_ref(ha)); wrapped = nix::hdf5::Group(h5group); CPPUNIT_ASSERT_EQUAL(h5group, wrapped.h5id()); CPPUNIT_ASSERT_EQUAL(4, H5Iget_ref(h5group)); CPPUNIT_ASSERT_EQUAL(2, H5Iget_ref(ha)); c = nix::hdf5::Group(b); CPPUNIT_ASSERT_EQUAL(ha, c.h5id()); CPPUNIT_ASSERT_EQUAL(3, H5Iget_ref(h5group)); CPPUNIT_ASSERT_EQUAL(3, H5Iget_ref(ha)); wrapped = c; CPPUNIT_ASSERT_EQUAL(2, H5Iget_ref(h5group)); CPPUNIT_ASSERT_EQUAL(4, H5Iget_ref(ha)); b = wrapped; CPPUNIT_ASSERT_EQUAL(2, H5Iget_ref(h5group)); CPPUNIT_ASSERT_EQUAL(4, H5Iget_ref(ha)); }
// Copyright © 2013,2014 German Neuroinformatics Node (G-Node) // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted under the terms of the BSD License. See // LICENSE file in the root of the Project. // // Author: Christian Kellner <[email protected]> #include <nix/hdf5/FileHDF5.hpp> #include "TestGroup.hpp" unsigned int & TestGroup::open_mode() { static unsigned int openMode = H5F_ACC_TRUNC; return openMode; } void TestGroup::setUp() { unsigned int &openMode = open_mode(); if (openMode == H5F_ACC_TRUNC) { h5file = H5Fcreate("test_group.h5", openMode, H5P_DEFAULT, H5P_DEFAULT); } else { h5file = H5Fopen("test_group.h5", openMode, H5P_DEFAULT); } CPPUNIT_ASSERT(H5Iis_valid(h5file)); if (openMode == H5F_ACC_TRUNC) { h5group = H5Gcreate2(h5file, "tstGroup", H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT); } else { h5group = H5Gopen2(h5file, "tstGroup", H5P_DEFAULT); } openMode = H5F_ACC_RDWR; } void TestGroup::tearDown() { H5Fclose(h5file); H5Oclose(h5group); } void TestGroup::testBaseTypes() { nix::hdf5::Group group(h5group); //int //attr group.setAttr("t_int", 42); int tint; group.getAttr("t_int", tint); CPPUNIT_ASSERT_EQUAL(tint, 42); //double //attr double deps = std::numeric_limits<double>::epsilon(); double dpi = boost::math::constants::pi<double>(); group.setAttr("t_double", dpi); double dbl; group.getAttr("t_double", dbl); CPPUNIT_ASSERT_DOUBLES_EQUAL(dpi, dbl, deps); //string const std::string testStr = "I saw the best minds of my generation destroyed by madness"; group.setAttr("t_string", testStr); std::string retString; group.getAttr("t_string", retString); CPPUNIT_ASSERT_EQUAL(testStr, retString); } void TestGroup::testMultiArray() { nix::hdf5::Group group(h5group); //arrays typedef boost::multi_array<double, 3> array_type; typedef array_type::index index; array_type A(boost::extents[3][4][2]); int values = 0; for(index i = 0; i != 3; ++i) for(index j = 0; j != 4; ++j) for(index k = 0; k != 2; ++k) A[i][j][k] = values++; group.setAttr<array_type>("t_doubleArray", A); array_type B(boost::extents[1][1][1]); group.getAttr("t_doubleArray", B); int verify = 0; int errors = 0; for(index i = 0; i != 3; ++i) { for(index j = 0; j != 4; ++j) { for(index k = 0; k != 2; ++k) { int v = verify++; errors += B[i][j][k] != v; } } } CPPUNIT_ASSERT_EQUAL(errors, 0); //data group.setData("t_doubleArray", A); array_type C(boost::extents[1][1][1]); group.getData("t_doubleArray", C); verify = 0; errors = 0; for(index i = 0; i != 3; ++i) { for(index j = 0; j != 4; ++j) { for(index k = 0; k != 2; ++k) { int v = verify++; errors += B[i][j][k] != v; } } } CPPUNIT_ASSERT_EQUAL(errors, 0); } void TestGroup::testVector() { nix::hdf5::Group group(h5group); std::vector<int> iv; iv.push_back(7); iv.push_back(23); iv.push_back(42); iv.push_back(1982); group.setAttr("t_intvector", iv); std::vector<int> tiv; group.getAttr("t_intvector", tiv); assert_vectors_equal(iv, tiv); std::vector<std::string> sv; sv.push_back("Alle"); sv.push_back("meine"); sv.push_back("Entchen"); group.setAttr("t_strvector", sv); std::vector<std::string> tsv; group.getAttr("t_strvector", tsv); assert_vectors_equal(sv, tsv); } void TestGroup::testArray() { nix::hdf5::Group group(h5group); int ia1d[5] = {1, 2, 3, 4, 5}; group.setAttr("t_intarray1d", ia1d); int tia1d[5] = {0, }; group.getAttr("t_intarray1d", tia1d); for (int i = 0; i < 5; i++) { CPPUNIT_ASSERT_EQUAL(ia1d[i], tia1d[i]); } #ifndef _WIN32 //cf. issue #72 int ia2d[3][2] = { {1, 2}, {3, 4}, {5, 6} }; group.setAttr("t_intarray2d", ia2d); int tia2d[3][2] = { {0, }, }; group.getAttr("t_intarray2d", tia2d); for (int i = 0; i < 3*2; i++) { CPPUNIT_ASSERT_EQUAL(*(ia2d[0] + i), *(tia2d[0] + i)); } #endif } void TestGroup::testOpen() { nix::hdf5::Group root(h5group); nix::hdf5::Group g = root.openGroup("name_a", true); std::string uuid = nix::util::createId(); g.setAttr("entity_id", uuid); CPPUNIT_ASSERT(root.hasGroup("name_a")); std::string idout; boost::optional<nix::hdf5::Group> a = root.findGroupByNameOrAttribute("entity_id", "name_a"); CPPUNIT_ASSERT(a); CPPUNIT_ASSERT(a->hasAttr("entity_id")); a->getAttr("entity_id", idout); CPPUNIT_ASSERT_EQUAL(uuid, idout); boost::optional<nix::hdf5::Group> b = root.findGroupByNameOrAttribute("entity_id", uuid); CPPUNIT_ASSERT(b); CPPUNIT_ASSERT(b->hasAttr("entity_id")); b->getAttr("entity_id", idout); CPPUNIT_ASSERT_EQUAL(uuid, idout); } void TestGroup::testRefCount() { nix::hdf5::Group wrapped(h5group); CPPUNIT_ASSERT_EQUAL(2, H5Iget_ref(h5group)); CPPUNIT_ASSERT_EQUAL(h5group, wrapped.h5id()); CPPUNIT_ASSERT_EQUAL(2, H5Iget_ref(h5group)); nix::hdf5::Group g; CPPUNIT_ASSERT_EQUAL(H5I_INVALID_HID, g.h5id()); g = nix::hdf5::Group(h5group); CPPUNIT_ASSERT_EQUAL(h5group, g.h5id()); CPPUNIT_ASSERT_EQUAL(3, H5Iget_ref(h5group)); nix::hdf5::Group c = g; CPPUNIT_ASSERT_EQUAL(h5group, c.h5id()); CPPUNIT_ASSERT_EQUAL(4, H5Iget_ref(h5group)); { nix::hdf5::Group tmp = g; CPPUNIT_ASSERT_EQUAL(h5group, tmp.h5id()); CPPUNIT_ASSERT_EQUAL(5, H5Iget_ref(h5group)); } CPPUNIT_ASSERT_EQUAL(4, H5Iget_ref(h5group)); hid_t ha = H5Gopen2(h5file, "/", H5P_DEFAULT); CPPUNIT_ASSERT(ha != h5group); CPPUNIT_ASSERT_EQUAL(1, H5Iget_ref(ha)); nix::hdf5::Group b(ha); CPPUNIT_ASSERT_EQUAL(ha, b.h5id()); CPPUNIT_ASSERT_EQUAL(2, H5Iget_ref(ha)); wrapped = nix::hdf5::Group(h5group); // test self assignment! no inc ref CPPUNIT_ASSERT_EQUAL(h5group, wrapped.h5id()); CPPUNIT_ASSERT_EQUAL(4, H5Iget_ref(h5group)); CPPUNIT_ASSERT_EQUAL(2, H5Iget_ref(ha)); c = nix::hdf5::Group(b); CPPUNIT_ASSERT_EQUAL(ha, c.h5id()); CPPUNIT_ASSERT_EQUAL(3, H5Iget_ref(h5group)); CPPUNIT_ASSERT_EQUAL(3, H5Iget_ref(ha)); wrapped = c; CPPUNIT_ASSERT_EQUAL(2, H5Iget_ref(h5group)); CPPUNIT_ASSERT_EQUAL(4, H5Iget_ref(ha)); b = wrapped; CPPUNIT_ASSERT_EQUAL(2, H5Iget_ref(h5group)); CPPUNIT_ASSERT_EQUAL(4, H5Iget_ref(ha)); }
comment about self assignment test
TestGroup: comment about self assignment test
C++
bsd-3-clause
stoewer/nix
0819c343b64c7772d5e76ee6cb05855d4e7dcd03
src/runtime/qnames/QNamesImpl.cpp
src/runtime/qnames/QNamesImpl.cpp
/** * @copyright * ======================================================================== * Copyright FLWOR Foundation * ======================================================================== * * @author Sorin Nasoi ([email protected]) * @file runtime/qnames/QNamesImpl.cpp * */ #include "store/api/item.h" #include "runtime/qnames/QNamesImpl.h" #include "runtime/api/runtimecb.h" #include "system/globalenv.h" #include "context/static_context.h" #include "store/api/store.h" #include "store/api/item_factory.h" #include "types/typemanager.h" namespace zorba { /** *______________________________________________________________________ * * 11.1.1 fn:resolve-QName * * fn:resolve-QName($qname as xs:string?, $element as element()) as xs:QName? * *Summary: Returns an xs:QName value (that is, an expanded-QName) by taking an *xs:string that has the lexical form of an xs:QName (a string in the form *"prefix:local-name" or "local-name") and resolving it using the in-scope *namespaces for a given element. *If $qname does not have the correct lexical form for xs:QName *an error is raised [err:FOCA0002]. *If $qname is the empty sequence, returns the empty sequence. *If the $qname has a prefix and if there is no namespace binding for $element *that matches this prefix, then an error is raised [err:FONS0004]. *If the $qname has no prefix, and there is no namespace binding for $element *corresponding to the default (unnamed) namespace, then the resulting *expanded-QName has no namespace part. *The prefix (or absence of a prefix) in the supplied $qname argument is retained *in the returned expanded-QName *_______________________________________________________________________*/ /* begin class ResolveQNameIterator */ store::Item_t ResolveQNameIterator::nextImpl(PlanState& planState) const { store::Item_t res; store::Item_t itemQName; store::Item_t itemElem; xqp_string resNs = ""; xqp_string resPre = ""; xqp_string resQName = ""; int32_t index = -1; std::vector<std::pair<xqp_string, xqp_string> > NamespaceBindings; std::vector<std::pair<xqp_string, xqp_string> > ::const_iterator iter; PlanIteratorState* state; DEFAULT_STACK_INIT(PlanIteratorState, state, planState); itemQName = consumeNext(theChild0.getp(), planState ); if( itemQName != NULL) { itemQName = itemQName->getAtomizationValue(); //TODO check if $paramQName does not have the correct lexical form for xs:QName and raise an error [err:FOCA0002]. index = itemQName->getStringValue().trim().indexOf(":"); if(-1 != index) { resPre = itemQName->getStringValue().trim().substr( 0, index ); resQName = itemQName->getStringValue().trim().substr( index+1, resQName.length() - index ); itemElem = consumeNext(theChild1.getp(), planState ); if( itemElem != NULL ) { itemElem->getNamespaceBindings(NamespaceBindings); for ( iter = NamespaceBindings.begin(); iter != NamespaceBindings.end(); ++iter ) { if( (*iter).first == resPre ) { resNs = (*iter).second; break; } } } } else { resQName = itemQName->getStringValue().trim(); } res = GENV_ITEMFACTORY->createQName(resNs.getStore(), resPre.getStore(), resQName.getStore()); STACK_PUSH( res, state ); } STACK_END(); } /* end class ResolveQNameIterator */ /** *______________________________________________________________________ * * 11.1.2 fn:QName * * fn:QName($paramURI as xs:string?, $paramQName as xs:string) as xs:QName * *Summary: Returns an xs:QName with the namespace URI given in $paramURI. *If $paramURI is the zero-length string or the empty sequence, it represents *"no namespace"; in this case, if the value of $paramQName contains a colon (:), *an error is raised [err:FOCA0002]. The prefix (or absence of a prefix) *in $paramQName is retained in the returned xs:QName value. *The local name in the result is taken from the local part of $paramQName. *If $paramQName does not have the correct lexical form for xs:QName *an error is raised [err:FOCA0002]. *Note that unlike xs:QName this function does not require a xs:string literal as *the argument. *_______________________________________________________________________*/ /* begin class QNameIterator */ store::Item_t QNameIterator::nextImpl(PlanState& planState) const { store::Item_t itemURI; store::Item_t itemQName; store::Item_t res; xqp_string resNs = ""; xqp_string resQName = ""; int32_t index = -1; PlanIteratorState* state; DEFAULT_STACK_INIT(PlanIteratorState, state, planState); itemURI = consumeNext(theChild0.getp(), planState ); if ( itemURI != NULL ) { itemURI = itemURI->getAtomizationValue(); resNs = itemURI->getStringValue().trim(); } itemQName = consumeNext(theChild1.getp(), planState ); if ( itemQName != NULL ) { itemQName = itemQName->getAtomizationValue(); resQName = itemQName->getStringValue().trim(); //TODO check if $paramQName does not have the correct lexical form for xs:QName and raise an error [err:FOCA0002]. index = resQName.indexOf(":"); if( resNs.empty() && (-1 != index) ) ZORBA_ERROR(ZorbaError::FOCA0002); } if( -1 != index ) { res = GENV_ITEMFACTORY->createQName( resNs.getStore(), resQName.substr( 0, index ).getStore(), resQName.substr( index+1, resQName.length() - index ).getStore()); } else { xqpString empty(""); res = GENV_ITEMFACTORY->createQName(resNs.getStore(), empty.getStore(), resQName.getStore()); } STACK_PUSH( res, state ); STACK_END(); } /* end class QNameIterator */ /** *______________________________________________________________________ * * 11.2.1 op:QName-equal * * op:QName-equal($arg1 as xs:QName, * $arg2 as xs:QName) as xs:boolean * *Summary: Returns true if the namespace URIs of $arg1 and $arg2 are equal and *the local names of $arg1 and $arg2 are identical based on the *Unicode code point collation. Otherwise, returns false. *Two namespace URIs are considered equal if they are either both absent or *both present and identical based on the Unicode code point collation. The prefix *parts of $arg1 and $arg2, if any, are ignored. *_______________________________________________________________________*/ /* begin class QNameEqualIterator */ store::Item_t QNameEqualIterator::nextImpl(PlanState& planState) const { store::Item_t arg1; store::Item_t arg2; store::Item_t res; PlanIteratorState* state; DEFAULT_STACK_INIT(PlanIteratorState, state, planState); arg1 = consumeNext(theChild0.getp(), planState ); if ( arg1 != NULL ) { arg2 = consumeNext(theChild1.getp(), planState ); if ( arg2 != NULL ) { arg1 = arg1->getAtomizationValue(); arg2 = arg2->getAtomizationValue(); if(arg1->getLocalName() == arg2->getLocalName()) { if((arg1->getNamespace().empty() && arg2->getNamespace().empty()) || (arg1->getNamespace() == arg2->getNamespace())) res = GENV_ITEMFACTORY->createBoolean(true); else res = GENV_ITEMFACTORY->createBoolean(false); } else res = GENV_ITEMFACTORY->createBoolean(false); STACK_PUSH( res, state ); } } STACK_END(); } /* end class QNameEqualIterator */ /** *______________________________________________________________________ * * 11.2.2 fn:prefix-from-QName * * fn:prefix-from-QName($arg as xs:QName?) as xs:NCName? * *Summary: Returns an xs:NCName representing the prefix of $arg. The empty sequence *is returned if $arg is the empty sequence or if the value of $arg contains no prefix. *_______________________________________________________________________*/ /* begin class PrefixFromQNameIterator */ store::Item_t PrefixFromQNameIterator::nextImpl(PlanState& planState) const { store::Item_t item; xqp_string tmp=""; PlanIteratorState* state; DEFAULT_STACK_INIT(PlanIteratorState, state, planState); item = consumeNext(theChild.getp(), planState); if ( item != NULL ) { item = item->getAtomizationValue(); tmp = item->getPrefix(); if(!tmp.empty()) STACK_PUSH( GENV_ITEMFACTORY->createNCName(tmp.getStore()), state ); } STACK_END(); } /* end class PrefixFromQNameIterator */ /** *______________________________________________________________________ * * 11.2.3 fn:local-name-from-QName * * fn:local-name-from-QName($arg as xs:QName?) as xs:NCName? * *Summary: Returns an xs:NCName representing the local part of $arg. *If $arg is the empty sequence, returns the empty sequence. *_______________________________________________________________________*/ /* begin class LocalNameFromQNameIterator */ store::Item_t LocalNameFromQNameIterator::nextImpl(PlanState& planState) const { store::Item_t item; PlanIteratorState* state; DEFAULT_STACK_INIT(PlanIteratorState, state, planState); item = consumeNext(theChild.getp(), planState); if ( item != NULL ) { item = item->getAtomizationValue(); STACK_PUSH(GENV_ITEMFACTORY->createNCName(item->getLocalName().getStore()), state); } STACK_END(); } /* end class LocalNameFromQNameIterator */ /** *______________________________________________________________________ * * 11.2.4 fn:namespace-uri-from-QName * * fn:namespace-uri-from-QName($arg as xs:QName?) as xs:anyURI? * *Summary: Returns the namespace URI for $arg as an xs:string. *If $arg is the empty sequence, the empty sequence is returned. *If $arg is in no namespace, the zero-length string is returned. *_______________________________________________________________________*/ /* begin class NamespaceUriFromQNameIterator */ store::Item_t NamespaceUriFromQNameIterator::nextImpl(PlanState& planState) const { store::Item_t item; PlanIteratorState* state; DEFAULT_STACK_INIT(PlanIteratorState, state, planState); item = consumeNext(theChild.getp(), planState); if ( item != NULL ) { item = item->getAtomizationValue(); STACK_PUSH( GENV_ITEMFACTORY->createString(item->getNamespace().getStore()), state ); } STACK_END(); } /* end class NamespaceUriFromQNameIterator */ /** *______________________________________________________________________ * * 11.2.5 fn:namespace-uri-for-prefix * * fn:namespace-uri-for-prefix($prefix as xs:string?, * $element as element()) as xs:anyURI? * *Summary: Returns the namespace URI of one of the in-scope namespaces for *$element, identified by its namespace prefix. *If $element has an in-scope namespace whose namespace prefix is equal to $prefix, *it returns the namespace URI of that namespace. If $prefix is the zero-length string or *the empty sequence, it returns the namespace URI of the *default (unnamed) namespace. Otherwise, it returns the empty sequence. *Prefixes are equal only if their Unicode code points match exactly. *_______________________________________________________________________*/ /* begin class NamespaceUriForPrefixlIterator */ store::Item_t NamespaceUriForPrefixlIterator::nextImpl(PlanState& planState) const { store::Item_t itemPrefix; store::Item_t itemElem; xqp_string resNs = ""; std::vector<std::pair<xqp_string, xqp_string> > NamespaceBindings; std::vector<std::pair<xqp_string, xqp_string> > ::const_iterator iter; PlanIteratorState* state; DEFAULT_STACK_INIT(PlanIteratorState, state, planState); itemPrefix = consumeNext(theChild0.getp(), planState ); if( itemPrefix != NULL) { itemPrefix = itemPrefix->getAtomizationValue(); itemElem = consumeNext(theChild1.getp(), planState ); if( itemElem != NULL && !itemElem->getStringValue().empty()) { itemElem->getNamespaceBindings(NamespaceBindings); for ( iter = NamespaceBindings.begin(); iter != NamespaceBindings.end(); ++iter ) { if( (*iter).first == itemPrefix->getStringValue().trim() ) { resNs = (*iter).second; break; } } } else { resNs = planState.theRuntimeCB->theStaticContext->default_elem_type_ns(); } if( !resNs.empty() ) STACK_PUSH( GENV_ITEMFACTORY->createString(resNs.getStore()), state ); } STACK_END(); } /* end class NamespaceUriForPrefixlIterator */ /** *______________________________________________________________________ * * 11.2.6 fn:in-scope-prefixes * * fn:in-scope-prefixes($element as element()) as xs:string* * *Summary: Returns the prefixes of the in-scope namespaces for $element. *For namespaces that have a prefix, it returns the prefix as an xs:NCName. *For the default namespace, which has no prefix, it returns the zero-length string. *_______________________________________________________________________*/ store::Item_t InScopePrefixesIterator::nextImpl(PlanState& planState) const { store::Item_t itemElem; InScopePrefixesState* state; DEFAULT_STACK_INIT(InScopePrefixesState, state, planState); itemElem = consumeNext(theChild.getp(), planState ); if( itemElem != NULL) { itemElem->getNamespaceBindings(state->theBindings); while (state->theCurrentPos < state->theBindings.size()) { STACK_PUSH(GENV_ITEMFACTORY-> createNCName(state->theBindings[state->theCurrentPos].first.getStore()), state); state->theCurrentPos++; } } //STACK_PUSH(GENV_ITEMFACTORY->createNCName("xml"), state); STACK_END(); } void InScopePrefixesState::init(PlanState& planState) { PlanIteratorState::init(planState); theBindings.clear(); theCurrentPos = 0; } void InScopePrefixesState::reset(PlanState& planState) { PlanIteratorState::reset(planState); theBindings.clear(); theCurrentPos = 0; } } /* namespace zorba */
/** * @copyright * ======================================================================== * Copyright FLWOR Foundation * ======================================================================== * * @author Sorin Nasoi ([email protected]) * @file runtime/qnames/QNamesImpl.cpp * */ #include "store/api/item.h" #include "runtime/qnames/QNamesImpl.h" #include "runtime/api/runtimecb.h" #include "system/globalenv.h" #include "context/static_context.h" #include "store/api/store.h" #include "store/api/item_factory.h" #include "types/typemanager.h" namespace zorba { /** *______________________________________________________________________ * * 11.1.1 fn:resolve-QName * * fn:resolve-QName($qname as xs:string?, $element as element()) as xs:QName? * *Summary: Returns an xs:QName value (that is, an expanded-QName) by taking an *xs:string that has the lexical form of an xs:QName (a string in the form *"prefix:local-name" or "local-name") and resolving it using the in-scope *namespaces for a given element. *If $qname does not have the correct lexical form for xs:QName *an error is raised [err:FOCA0002]. *If $qname is the empty sequence, returns the empty sequence. *If the $qname has a prefix and if there is no namespace binding for $element *that matches this prefix, then an error is raised [err:FONS0004]. *If the $qname has no prefix, and there is no namespace binding for $element *corresponding to the default (unnamed) namespace, then the resulting *expanded-QName has no namespace part. *The prefix (or absence of a prefix) in the supplied $qname argument is retained *in the returned expanded-QName *_______________________________________________________________________*/ /* begin class ResolveQNameIterator */ store::Item_t ResolveQNameIterator::nextImpl(PlanState& planState) const { store::Item_t res; store::Item_t itemQName; store::Item_t itemElem; xqp_string resNs = ""; xqp_string resPre = ""; xqp_string resQName = ""; int32_t index = -1; std::vector<std::pair<xqp_string, xqp_string> > NamespaceBindings; std::vector<std::pair<xqp_string, xqp_string> > ::const_iterator iter; PlanIteratorState* state; DEFAULT_STACK_INIT(PlanIteratorState, state, planState); itemQName = consumeNext(theChild0.getp(), planState ); if( itemQName != NULL) { itemQName = itemQName->getAtomizationValue(); //TODO check if $paramQName does not have the correct lexical form for xs:QName and raise an error [err:FOCA0002]. index = itemQName->getStringValue().trim().indexOf(":"); if(-1 != index) { resPre = itemQName->getStringValue().trim().substr( 0, index ); resQName = itemQName->getStringValue().trim().substr( index+1, itemQName->getStringValue().length() - index ); itemElem = consumeNext(theChild1.getp(), planState ); if( itemElem != NULL ) { itemElem->getNamespaceBindings(NamespaceBindings); for ( iter = NamespaceBindings.begin(); iter != NamespaceBindings.end(); ++iter ) { if( (*iter).first == resPre ) { resNs = (*iter).second; break; } } } } else { resQName = itemQName->getStringValue().trim(); } res = GENV_ITEMFACTORY->createQName(resNs.getStore(), resPre.getStore(), resQName.getStore()); STACK_PUSH( res, state ); } STACK_END(); } /* end class ResolveQNameIterator */ /** *______________________________________________________________________ * * 11.1.2 fn:QName * * fn:QName($paramURI as xs:string?, $paramQName as xs:string) as xs:QName * *Summary: Returns an xs:QName with the namespace URI given in $paramURI. *If $paramURI is the zero-length string or the empty sequence, it represents *"no namespace"; in this case, if the value of $paramQName contains a colon (:), *an error is raised [err:FOCA0002]. The prefix (or absence of a prefix) *in $paramQName is retained in the returned xs:QName value. *The local name in the result is taken from the local part of $paramQName. *If $paramQName does not have the correct lexical form for xs:QName *an error is raised [err:FOCA0002]. *Note that unlike xs:QName this function does not require a xs:string literal as *the argument. *_______________________________________________________________________*/ /* begin class QNameIterator */ store::Item_t QNameIterator::nextImpl(PlanState& planState) const { store::Item_t itemURI; store::Item_t itemQName; store::Item_t res; xqp_string resNs = ""; xqp_string resQName = ""; int32_t index = -1; PlanIteratorState* state; DEFAULT_STACK_INIT(PlanIteratorState, state, planState); itemURI = consumeNext(theChild0.getp(), planState ); if ( itemURI != NULL ) { itemURI = itemURI->getAtomizationValue(); resNs = itemURI->getStringValue().trim(); } itemQName = consumeNext(theChild1.getp(), planState ); if ( itemQName != NULL ) { itemQName = itemQName->getAtomizationValue(); resQName = itemQName->getStringValue().trim(); //TODO check if $paramQName does not have the correct lexical form for xs:QName and raise an error [err:FOCA0002]. index = resQName.indexOf(":"); if( resNs.empty() && (-1 != index) ) ZORBA_ERROR(ZorbaError::FOCA0002); } if( -1 != index ) { res = GENV_ITEMFACTORY->createQName( resNs.getStore(), resQName.substr( 0, index ).getStore(), resQName.substr( index+1, resQName.length() - index ).getStore()); } else { xqpString empty(""); res = GENV_ITEMFACTORY->createQName(resNs.getStore(), empty.getStore(), resQName.getStore()); } STACK_PUSH( res, state ); STACK_END(); } /* end class QNameIterator */ /** *______________________________________________________________________ * * 11.2.1 op:QName-equal * * op:QName-equal($arg1 as xs:QName, * $arg2 as xs:QName) as xs:boolean * *Summary: Returns true if the namespace URIs of $arg1 and $arg2 are equal and *the local names of $arg1 and $arg2 are identical based on the *Unicode code point collation. Otherwise, returns false. *Two namespace URIs are considered equal if they are either both absent or *both present and identical based on the Unicode code point collation. The prefix *parts of $arg1 and $arg2, if any, are ignored. *_______________________________________________________________________*/ /* begin class QNameEqualIterator */ store::Item_t QNameEqualIterator::nextImpl(PlanState& planState) const { store::Item_t arg1; store::Item_t arg2; store::Item_t res; PlanIteratorState* state; DEFAULT_STACK_INIT(PlanIteratorState, state, planState); arg1 = consumeNext(theChild0.getp(), planState ); if ( arg1 != NULL ) { arg2 = consumeNext(theChild1.getp(), planState ); if ( arg2 != NULL ) { arg1 = arg1->getAtomizationValue(); arg2 = arg2->getAtomizationValue(); if(arg1->getLocalName() == arg2->getLocalName()) { if((arg1->getNamespace().empty() && arg2->getNamespace().empty()) || (arg1->getNamespace() == arg2->getNamespace())) res = GENV_ITEMFACTORY->createBoolean(true); else res = GENV_ITEMFACTORY->createBoolean(false); } else res = GENV_ITEMFACTORY->createBoolean(false); STACK_PUSH( res, state ); } } STACK_END(); } /* end class QNameEqualIterator */ /** *______________________________________________________________________ * * 11.2.2 fn:prefix-from-QName * * fn:prefix-from-QName($arg as xs:QName?) as xs:NCName? * *Summary: Returns an xs:NCName representing the prefix of $arg. The empty sequence *is returned if $arg is the empty sequence or if the value of $arg contains no prefix. *_______________________________________________________________________*/ /* begin class PrefixFromQNameIterator */ store::Item_t PrefixFromQNameIterator::nextImpl(PlanState& planState) const { store::Item_t item; xqp_string tmp=""; PlanIteratorState* state; DEFAULT_STACK_INIT(PlanIteratorState, state, planState); item = consumeNext(theChild.getp(), planState); if ( item != NULL ) { item = item->getAtomizationValue(); tmp = item->getPrefix(); if(!tmp.empty()) STACK_PUSH( GENV_ITEMFACTORY->createNCName(tmp.getStore()), state ); } STACK_END(); } /* end class PrefixFromQNameIterator */ /** *______________________________________________________________________ * * 11.2.3 fn:local-name-from-QName * * fn:local-name-from-QName($arg as xs:QName?) as xs:NCName? * *Summary: Returns an xs:NCName representing the local part of $arg. *If $arg is the empty sequence, returns the empty sequence. *_______________________________________________________________________*/ /* begin class LocalNameFromQNameIterator */ store::Item_t LocalNameFromQNameIterator::nextImpl(PlanState& planState) const { store::Item_t item; PlanIteratorState* state; DEFAULT_STACK_INIT(PlanIteratorState, state, planState); item = consumeNext(theChild.getp(), planState); if ( item != NULL ) { item = item->getAtomizationValue(); STACK_PUSH(GENV_ITEMFACTORY->createNCName(item->getLocalName().getStore()), state); } STACK_END(); } /* end class LocalNameFromQNameIterator */ /** *______________________________________________________________________ * * 11.2.4 fn:namespace-uri-from-QName * * fn:namespace-uri-from-QName($arg as xs:QName?) as xs:anyURI? * *Summary: Returns the namespace URI for $arg as an xs:string. *If $arg is the empty sequence, the empty sequence is returned. *If $arg is in no namespace, the zero-length string is returned. *_______________________________________________________________________*/ /* begin class NamespaceUriFromQNameIterator */ store::Item_t NamespaceUriFromQNameIterator::nextImpl(PlanState& planState) const { store::Item_t item; PlanIteratorState* state; DEFAULT_STACK_INIT(PlanIteratorState, state, planState); item = consumeNext(theChild.getp(), planState); if ( item != NULL ) { item = item->getAtomizationValue(); STACK_PUSH( GENV_ITEMFACTORY->createString(item->getNamespace().getStore()), state ); } STACK_END(); } /* end class NamespaceUriFromQNameIterator */ /** *______________________________________________________________________ * * 11.2.5 fn:namespace-uri-for-prefix * * fn:namespace-uri-for-prefix($prefix as xs:string?, * $element as element()) as xs:anyURI? * *Summary: Returns the namespace URI of one of the in-scope namespaces for *$element, identified by its namespace prefix. *If $element has an in-scope namespace whose namespace prefix is equal to $prefix, *it returns the namespace URI of that namespace. If $prefix is the zero-length string or *the empty sequence, it returns the namespace URI of the *default (unnamed) namespace. Otherwise, it returns the empty sequence. *Prefixes are equal only if their Unicode code points match exactly. *_______________________________________________________________________*/ /* begin class NamespaceUriForPrefixlIterator */ store::Item_t NamespaceUriForPrefixlIterator::nextImpl(PlanState& planState) const { store::Item_t itemPrefix; store::Item_t itemElem; xqp_string resNs = ""; std::vector<std::pair<xqp_string, xqp_string> > NamespaceBindings; std::vector<std::pair<xqp_string, xqp_string> > ::const_iterator iter; PlanIteratorState* state; DEFAULT_STACK_INIT(PlanIteratorState, state, planState); itemPrefix = consumeNext(theChild0.getp(), planState ); if( itemPrefix != NULL) { itemPrefix = itemPrefix->getAtomizationValue(); itemElem = consumeNext(theChild1.getp(), planState ); if( itemElem != NULL && !itemElem->getStringValue().empty()) { itemElem->getNamespaceBindings(NamespaceBindings); for ( iter = NamespaceBindings.begin(); iter != NamespaceBindings.end(); ++iter ) { if( (*iter).first == itemPrefix->getStringValue().trim() ) { resNs = (*iter).second; break; } } } else { resNs = planState.theRuntimeCB->theStaticContext->default_elem_type_ns(); } if( !resNs.empty() ) STACK_PUSH( GENV_ITEMFACTORY->createString(resNs.getStore()), state ); } STACK_END(); } /* end class NamespaceUriForPrefixlIterator */ /** *______________________________________________________________________ * * 11.2.6 fn:in-scope-prefixes * * fn:in-scope-prefixes($element as element()) as xs:string* * *Summary: Returns the prefixes of the in-scope namespaces for $element. *For namespaces that have a prefix, it returns the prefix as an xs:NCName. *For the default namespace, which has no prefix, it returns the zero-length string. *_______________________________________________________________________*/ store::Item_t InScopePrefixesIterator::nextImpl(PlanState& planState) const { store::Item_t itemElem; InScopePrefixesState* state; DEFAULT_STACK_INIT(InScopePrefixesState, state, planState); itemElem = consumeNext(theChild.getp(), planState ); if( itemElem != NULL) { itemElem->getNamespaceBindings(state->theBindings); while (state->theCurrentPos < state->theBindings.size()) { STACK_PUSH(GENV_ITEMFACTORY-> createNCName(state->theBindings[state->theCurrentPos].first.getStore()), state); state->theCurrentPos++; } } //STACK_PUSH(GENV_ITEMFACTORY->createNCName("xml"), state); STACK_END(); } void InScopePrefixesState::init(PlanState& planState) { PlanIteratorState::init(planState); theBindings.clear(); theCurrentPos = 0; } void InScopePrefixesState::reset(PlanState& planState) { PlanIteratorState::reset(planState); theBindings.clear(); theCurrentPos = 0; } } /* namespace zorba */
Fix in the resolve-QName.
Fix in the resolve-QName.
C++
apache-2.0
28msec/zorba,28msec/zorba,cezarfx/zorba,cezarfx/zorba,28msec/zorba,28msec/zorba,28msec/zorba,bgarrels/zorba,28msec/zorba,cezarfx/zorba,bgarrels/zorba,cezarfx/zorba,bgarrels/zorba,bgarrels/zorba,cezarfx/zorba,cezarfx/zorba,cezarfx/zorba,28msec/zorba,bgarrels/zorba,cezarfx/zorba,28msec/zorba,bgarrels/zorba,28msec/zorba,cezarfx/zorba,bgarrels/zorba,bgarrels/zorba,cezarfx/zorba
09edf9a2f0c3f25569f84f9537c432afe23b9892
demo_perceptron.cc
demo_perceptron.cc
// Demo for Chapter 1. Rosenblatt's Perceptron. #include <iostream> #include <fstream> #include "dataset.hh" #include "perceptron.hh" using namespace std; int N_ITERS = 100; int main(int argc, char *argv[]) { if (argc != 3) { cerr << "Usage: demo_perceptron train.data test.data\n"; exit(-1); } ifstream trainIn(argv[1]); ifstream testIn(argv[2]); LabeledSet trainset = LabeledSet(trainIn); LabeledSet testset = LabeledSet(testIn); Perceptron p(trainset.getInputSize()); cout << "Initial weights: " << p.fmt() << "\n"; ConfusionMatrix cm = p.test(testset); cout << "Confusion matrix:\n"; cout << " TP=" << cm.truePositives << " FP=" << cm.falsePositives << "\n"; cout << " FN=" << cm.falseNegatives << " TN=" << cm.trueNegatives << "\n"; cout << "Initial accuracy: " << cm.accuracy() << "\n"; cout << "\n1 iteration...\n\n"; p.trainConverge(trainset, 1); cout << "Weights after convergence training: " << p.fmt() << "\n"; cm = p.test(testset); cout << "Confusion matrix:\n"; cout << " TP=" << cm.truePositives << " FP=" << cm.falsePositives << "\n"; cout << " FN=" << cm.falseNegatives << " TN=" << cm.trueNegatives << "\n"; cout << "Accuracy after convergence training: " << cm.accuracy() << "\n"; cout << "\n" << N_ITERS - 1 << " more iterations...\n\n"; p.trainConverge(trainset, N_ITERS - 1); cout << "Weights after convergence training: " << p.fmt() << "\n"; cm = p.test(testset); cout << "Confusion matrix:\n"; cout << " TP=" << cm.truePositives << " FP=" << cm.falsePositives << "\n"; cout << " FN=" << cm.falseNegatives << " TN=" << cm.trueNegatives << "\n"; cout << "Accuracy after convergence training: " << cm.accuracy() << "\n"; cout << "\nvs " << N_ITERS << " iterations of batch training...\n\n"; Perceptron p2(trainset.getInputSize()); p2.trainBatch(trainset, N_ITERS); cout << "Weights after batch training: " << p2.fmt() << "\n"; cm = p2.test(testset); cout << "Confusion matrix:\n"; cout << " TP=" << cm.truePositives << " FP=" << cm.falsePositives << "\n"; cout << " FN=" << cm.falseNegatives << " TN=" << cm.trueNegatives << "\n"; cout << "Accuracy after batch training: " << cm.accuracy() << "\n"; }
// Demo for Chapter 1. Rosenblatt's Perceptron. #include <iostream> #include <fstream> #include "dataset.hh" #include "perceptron.hh" using namespace std; int N_ITERS = 100; int main(int argc, char *argv[]) { if (argc != 3) { cerr << "Usage: demo_perceptron train.data test.data\n"; exit(-1); } ifstream trainIn(argv[1]); ifstream testIn(argv[2]); LabeledSet trainset = LabeledSet(trainIn); LabeledSet testset = LabeledSet(testIn); StandalonePerceptron p(trainset.getInputSize()); cout << "Initial weights: " << p.fmt() << "\n"; ConfusionMatrix cm = p.test(testset); cout << "Confusion matrix:\n"; cout << " TP=" << cm.truePositives << " FP=" << cm.falsePositives << "\n"; cout << " FN=" << cm.falseNegatives << " TN=" << cm.trueNegatives << "\n"; cout << "Initial accuracy: " << cm.accuracy() << "\n"; cout << "\n1 iteration...\n\n"; p.trainConverge(trainset, 1); cout << "Weights after convergence training: " << p.fmt() << "\n"; cm = p.test(testset); cout << "Confusion matrix:\n"; cout << " TP=" << cm.truePositives << " FP=" << cm.falsePositives << "\n"; cout << " FN=" << cm.falseNegatives << " TN=" << cm.trueNegatives << "\n"; cout << "Accuracy after convergence training: " << cm.accuracy() << "\n"; cout << "\n" << N_ITERS - 1 << " more iterations...\n\n"; p.trainConverge(trainset, N_ITERS - 1); cout << "Weights after convergence training: " << p.fmt() << "\n"; cm = p.test(testset); cout << "Confusion matrix:\n"; cout << " TP=" << cm.truePositives << " FP=" << cm.falsePositives << "\n"; cout << " FN=" << cm.falseNegatives << " TN=" << cm.trueNegatives << "\n"; cout << "Accuracy after convergence training: " << cm.accuracy() << "\n"; cout << "\nvs " << N_ITERS << " iterations of batch training...\n\n"; StandalonePerceptron p2(trainset.getInputSize()); p2.trainBatch(trainset, N_ITERS); cout << "Weights after batch training: " << p2.fmt() << "\n"; cm = p2.test(testset); cout << "Confusion matrix:\n"; cout << " TP=" << cm.truePositives << " FP=" << cm.falsePositives << "\n"; cout << " FN=" << cm.falseNegatives << " TN=" << cm.trueNegatives << "\n"; cout << "Accuracy after batch training: " << cm.accuracy() << "\n"; }
fix demo_perceptron.cc
fix demo_perceptron.cc
C++
mit
astanin/notch,astanin/notch,astanin/notch
197ff79a8cd64d9eb059f0022e95ff74fceb8cf6
lib/VMCore/SymbolTable.cpp
lib/VMCore/SymbolTable.cpp
//===-- SymbolTable.cpp - Implement the SymbolTable class -------------------=// // // This file implements the SymbolTable class for the VMCore library. // //===----------------------------------------------------------------------===// #include "llvm/SymbolTable.h" #include "llvm/DerivedTypes.h" #include "llvm/Module.h" #include "llvm/InstrTypes.h" #include "Support/StringExtras.h" #include <iostream> #include <algorithm> using std::string; using std::pair; using std::make_pair; using std::map; using std::cerr; #define DEBUG_SYMBOL_TABLE 0 #define DEBUG_ABSTYPE 0 SymbolTable::~SymbolTable() { // Drop all abstract type references in the type plane... iterator TyPlane = find(Type::TypeTy); if (TyPlane != end()) { VarMap &TyP = TyPlane->second; for (VarMap::iterator I = TyP.begin(), E = TyP.end(); I != E; ++I) { const Type *Ty = cast<const Type>(I->second); if (Ty->isAbstract()) // If abstract, drop the reference... cast<DerivedType>(Ty)->removeAbstractTypeUser(this); } } // TODO: FIXME: BIG ONE: This doesn't unreference abstract types for the planes // that could still have entries! #ifndef NDEBUG // Only do this in -g mode... bool LeftoverValues = true; for (iterator i = begin(); i != end(); ++i) { for (type_iterator I = i->second.begin(); I != i->second.end(); ++I) if (!isa<Constant>(I->second) && !isa<Type>(I->second)) { cerr << "Value still in symbol table! Type = '" << i->first->getDescription() << "' Name = '" << I->first << "'\n"; LeftoverValues = false; } } assert(LeftoverValues && "Values remain in symbol table!"); #endif } // getUniqueName - Given a base name, return a string that is either equal to // it (or derived from it) that does not already occur in the symbol table for // the specified type. // string SymbolTable::getUniqueName(const Type *Ty, const string &BaseName) { iterator I = find(Ty); if (I == end()) return BaseName; string TryName = BaseName; unsigned Counter = 0; type_iterator End = I->second.end(); while (I->second.find(TryName) != End) // Loop until we find unoccupied TryName = BaseName + utostr(++Counter); // Name in the symbol table return TryName; } // lookup - Returns null on failure... Value *SymbolTable::lookup(const Type *Ty, const string &Name) { iterator I = find(Ty); if (I != end()) { // We have symbols in that plane... type_iterator J = I->second.find(Name); if (J != I->second.end()) // and the name is in our hash table... return J->second; } return 0; } void SymbolTable::remove(Value *N) { assert(N->hasName() && "Value doesn't have name!"); if (InternallyInconsistent) return; iterator I = find(N->getType()); assert(I != end() && "Trying to remove a type that doesn't have a plane yet!"); removeEntry(I, I->second.find(N->getName())); } // removeEntry - Remove a value from the symbol table... // Value *SymbolTable::removeEntry(iterator Plane, type_iterator Entry) { if (InternallyInconsistent) return 0; assert(Plane != super::end() && Entry != Plane->second.end() && "Invalid entry to remove!"); Value *Result = Entry->second; const Type *Ty = Result->getType(); #if DEBUG_SYMBOL_TABLE dump(); std::cerr << " Removing Value: " << Result->getName() << "\n"; #endif // Remove the value from the plane... Plane->second.erase(Entry); // If the plane is empty, remove it now! if (Plane->second.empty()) { // If the plane represented an abstract type that we were interested in, // unlink ourselves from this plane. // if (Plane->first->isAbstract()) { #if DEBUG_ABSTYPE cerr << "Plane Empty: Removing type: " << Plane->first->getDescription() << "\n"; #endif cast<DerivedType>(Plane->first)->removeAbstractTypeUser(this); } erase(Plane); } // If we are removing an abstract type, remove the symbol table from it's use // list... if (Ty == Type::TypeTy) { const Type *T = cast<const Type>(Result); if (T->isAbstract()) { #if DEBUG_ABSTYPE cerr << "Removing abs type from symtab" << T->getDescription() << "\n"; #endif cast<DerivedType>(T)->removeAbstractTypeUser(this); } } return Result; } // insertEntry - Insert a value into the symbol table with the specified // name... // void SymbolTable::insertEntry(const string &Name, const Type *VTy, Value *V) { // Check to see if there is a naming conflict. If so, rename this value! if (lookup(VTy, Name)) { string UniqueName = getUniqueName(VTy, Name); assert(InternallyInconsistent == false && "Infinite loop inserting entry!"); InternallyInconsistent = true; V->setName(UniqueName, this); InternallyInconsistent = false; return; } #if DEBUG_SYMBOL_TABLE dump(); cerr << " Inserting definition: " << Name << ": " << VTy->getDescription() << "\n"; #endif iterator I = find(VTy); if (I == end()) { // Not in collection yet... insert dummy entry // Insert a new empty element. I points to the new elements. I = super::insert(make_pair(VTy, VarMap())).first; assert(I != end() && "How did insert fail?"); // Check to see if the type is abstract. If so, it might be refined in the // future, which would cause the plane of the old type to get merged into // a new type plane. // if (VTy->isAbstract()) { cast<DerivedType>(VTy)->addAbstractTypeUser(this); #if DEBUG_ABSTYPE cerr << "Added abstract type value: " << VTy->getDescription() << "\n"; #endif } } I->second.insert(make_pair(Name, V)); // If we are adding an abstract type, add the symbol table to it's use list. if (VTy == Type::TypeTy) { const Type *T = cast<const Type>(V); if (T->isAbstract()) { cast<DerivedType>(T)->addAbstractTypeUser(this); #if DEBUG_ABSTYPE cerr << "Added abstract type to ST: " << T->getDescription() << "\n"; #endif } } } // This function is called when one of the types in the type plane are refined void SymbolTable::refineAbstractType(const DerivedType *OldType, const Type *NewType) { if (OldType == NewType && OldType->isAbstract()) return; // Noop, don't waste time dinking around // Search to see if we have any values of the type oldtype. If so, we need to // move them into the newtype plane... iterator TPI = find(OldType); if (OldType != NewType && TPI != end()) { // Get a handle to the new type plane... iterator NewTypeIt = find(NewType); if (NewTypeIt == super::end()) { // If no plane exists, add one NewTypeIt = super::insert(make_pair(NewType, VarMap())).first; if (NewType->isAbstract()) { cast<DerivedType>(NewType)->addAbstractTypeUser(this); #if DEBUG_ABSTYPE cerr << "[Added] refined to abstype: "<<NewType->getDescription()<<"\n"; #endif } } VarMap &NewPlane = NewTypeIt->second; VarMap &OldPlane = TPI->second; while (!OldPlane.empty()) { pair<const string, Value*> V = *OldPlane.begin(); // Check to see if there is already a value in the symbol table that this // would collide with. type_iterator TI = NewPlane.find(V.first); if (TI != NewPlane.end() && TI->second == V.second) { // No action } else if (TI != NewPlane.end()) { // The only thing we are allowing for now is two method prototypes being // folded into one. // Function *ExistM = dyn_cast<Function>(TI->second); Function *NewM = dyn_cast<Function>(V.second); if (ExistM && NewM && ExistM->isExternal() && NewM->isExternal()) { // Ok we have two external methods. Make all uses of the new one // use the old one... // NewM->replaceAllUsesWith(ExistM); // Now we just convert it to an unnamed method... which won't get // added to our symbol table. The problem is that if we call // setName on the method that it will try to remove itself from // the symbol table and die... because it's not in the symtab // right now. To fix this, we have an internally consistent flag // that turns remove into a noop. Thus the name will get null'd // out, but the symbol table won't get upset. // assert(InternallyInconsistent == false && "Symbol table already inconsistent!"); InternallyInconsistent = true; // Remove newM from the symtab NewM->setName(""); InternallyInconsistent = false; // Now we can remove this method from the module entirely... NewM->getParent()->getFunctionList().remove(NewM); delete NewM; } else { assert(0 && "Two planes folded together with overlapping " "value names!"); } } else { insertEntry(V.first, NewType, V.second); } // Remove the item from the old type plane OldPlane.erase(OldPlane.begin()); } // Ok, now we are not referencing the type anymore... take me off your user // list please! #if DEBUG_ABSTYPE cerr << "Removing type " << OldType->getDescription() << "\n"; #endif OldType->removeAbstractTypeUser(this); // Remove the plane that is no longer used erase(TPI); } else if (TPI != end()) { assert(OldType == NewType); #if DEBUG_ABSTYPE cerr << "Removing SELF type " << OldType->getDescription() << "\n"; #endif OldType->removeAbstractTypeUser(this); } TPI = find(Type::TypeTy); if (TPI != end()) { // Loop over all of the types in the symbol table, replacing any references // to OldType with references to NewType. Note that there may be multiple // occurances, and although we only need to remove one at a time, it's // faster to remove them all in one pass. // VarMap &TyPlane = TPI->second; for (VarMap::iterator I = TyPlane.begin(), E = TyPlane.end(); I != E; ++I) if (I->second == (Value*)OldType) { // FIXME when Types aren't const. #if DEBUG_ABSTYPE cerr << "Removing type " << OldType->getDescription() << "\n"; #endif OldType->removeAbstractTypeUser(this); I->second = (Value*)NewType; // TODO FIXME when types aren't const if (NewType->isAbstract()) { #if DEBUG_ABSTYPE cerr << "Added type " << NewType->getDescription() << "\n"; #endif cast<const DerivedType>(NewType)->addAbstractTypeUser(this); } } } } static void DumpVal(const pair<const string, Value *> &V) { std::cout << " '" << V.first << "' = "; V.second->dump(); std::cout << "\n"; } static void DumpPlane(const pair<const Type *, map<const string, Value *> >&P) { std::cout << " Plane: "; P.first->dump(); std::cout << "\n"; for_each(P.second.begin(), P.second.end(), DumpVal); } void SymbolTable::dump() const { std::cout << "Symbol table dump:\n"; for_each(begin(), end(), DumpPlane); }
//===-- SymbolTable.cpp - Implement the SymbolTable class -------------------=// // // This file implements the SymbolTable class for the VMCore library. // //===----------------------------------------------------------------------===// #include "llvm/SymbolTable.h" #include "llvm/DerivedTypes.h" #include "llvm/Module.h" #include "llvm/InstrTypes.h" #include "Support/StringExtras.h" #include <iostream> #include <algorithm> using std::string; using std::pair; using std::make_pair; using std::map; using std::cerr; #define DEBUG_SYMBOL_TABLE 0 #define DEBUG_ABSTYPE 0 SymbolTable::~SymbolTable() { // Drop all abstract type references in the type plane... iterator TyPlane = find(Type::TypeTy); if (TyPlane != end()) { VarMap &TyP = TyPlane->second; for (VarMap::iterator I = TyP.begin(), E = TyP.end(); I != E; ++I) { const Type *Ty = cast<const Type>(I->second); if (Ty->isAbstract()) // If abstract, drop the reference... cast<DerivedType>(Ty)->removeAbstractTypeUser(this); } } // TODO: FIXME: BIG ONE: This doesn't unreference abstract types for the planes // that could still have entries! #ifndef NDEBUG // Only do this in -g mode... bool LeftoverValues = true; for (iterator i = begin(); i != end(); ++i) { for (type_iterator I = i->second.begin(); I != i->second.end(); ++I) if (!isa<Constant>(I->second) && !isa<Type>(I->second)) { cerr << "Value still in symbol table! Type = '" << i->first->getDescription() << "' Name = '" << I->first << "'\n"; LeftoverValues = false; } } assert(LeftoverValues && "Values remain in symbol table!"); #endif } // getUniqueName - Given a base name, return a string that is either equal to // it (or derived from it) that does not already occur in the symbol table for // the specified type. // string SymbolTable::getUniqueName(const Type *Ty, const string &BaseName) { iterator I = find(Ty); if (I == end()) return BaseName; string TryName = BaseName; unsigned Counter = 0; type_iterator End = I->second.end(); while (I->second.find(TryName) != End) // Loop until we find unoccupied TryName = BaseName + utostr(++Counter); // Name in the symbol table return TryName; } // lookup - Returns null on failure... Value *SymbolTable::lookup(const Type *Ty, const string &Name) { iterator I = find(Ty); if (I != end()) { // We have symbols in that plane... type_iterator J = I->second.find(Name); if (J != I->second.end()) // and the name is in our hash table... return J->second; } return 0; } void SymbolTable::remove(Value *N) { assert(N->hasName() && "Value doesn't have name!"); if (InternallyInconsistent) return; iterator I = find(N->getType()); assert(I != end() && "Trying to remove a type that doesn't have a plane yet!"); removeEntry(I, I->second.find(N->getName())); } // removeEntry - Remove a value from the symbol table... // Value *SymbolTable::removeEntry(iterator Plane, type_iterator Entry) { if (InternallyInconsistent) return 0; assert(Plane != super::end() && Entry != Plane->second.end() && "Invalid entry to remove!"); Value *Result = Entry->second; const Type *Ty = Result->getType(); #if DEBUG_SYMBOL_TABLE dump(); std::cerr << " Removing Value: " << Result->getName() << "\n"; #endif // Remove the value from the plane... Plane->second.erase(Entry); // If the plane is empty, remove it now! if (Plane->second.empty()) { // If the plane represented an abstract type that we were interested in, // unlink ourselves from this plane. // if (Plane->first->isAbstract()) { #if DEBUG_ABSTYPE cerr << "Plane Empty: Removing type: " << Plane->first->getDescription() << "\n"; #endif cast<DerivedType>(Plane->first)->removeAbstractTypeUser(this); } erase(Plane); } // If we are removing an abstract type, remove the symbol table from it's use // list... if (Ty == Type::TypeTy) { const Type *T = cast<const Type>(Result); if (T->isAbstract()) { #if DEBUG_ABSTYPE cerr << "Removing abs type from symtab" << T->getDescription() << "\n"; #endif cast<DerivedType>(T)->removeAbstractTypeUser(this); } } return Result; } // insertEntry - Insert a value into the symbol table with the specified // name... // void SymbolTable::insertEntry(const string &Name, const Type *VTy, Value *V) { // Check to see if there is a naming conflict. If so, rename this value! if (lookup(VTy, Name)) { string UniqueName = getUniqueName(VTy, Name); assert(InternallyInconsistent == false && "Infinite loop inserting entry!"); InternallyInconsistent = true; V->setName(UniqueName, this); InternallyInconsistent = false; return; } #if DEBUG_SYMBOL_TABLE dump(); cerr << " Inserting definition: " << Name << ": " << VTy->getDescription() << "\n"; #endif iterator I = find(VTy); if (I == end()) { // Not in collection yet... insert dummy entry // Insert a new empty element. I points to the new elements. I = super::insert(make_pair(VTy, VarMap())).first; assert(I != end() && "How did insert fail?"); // Check to see if the type is abstract. If so, it might be refined in the // future, which would cause the plane of the old type to get merged into // a new type plane. // if (VTy->isAbstract()) { cast<DerivedType>(VTy)->addAbstractTypeUser(this); #if DEBUG_ABSTYPE cerr << "Added abstract type value: " << VTy->getDescription() << "\n"; #endif } } I->second.insert(make_pair(Name, V)); // If we are adding an abstract type, add the symbol table to it's use list. if (VTy == Type::TypeTy) { const Type *T = cast<const Type>(V); if (T->isAbstract()) { cast<DerivedType>(T)->addAbstractTypeUser(this); #if DEBUG_ABSTYPE cerr << "Added abstract type to ST: " << T->getDescription() << "\n"; #endif } } } // This function is called when one of the types in the type plane are refined void SymbolTable::refineAbstractType(const DerivedType *OldType, const Type *NewType) { if (OldType == NewType && OldType->isAbstract()) return; // Noop, don't waste time dinking around // Search to see if we have any values of the type oldtype. If so, we need to // move them into the newtype plane... iterator TPI = find(OldType); if (OldType != NewType && TPI != end()) { // Get a handle to the new type plane... iterator NewTypeIt = find(NewType); if (NewTypeIt == super::end()) { // If no plane exists, add one NewTypeIt = super::insert(make_pair(NewType, VarMap())).first; if (NewType->isAbstract()) { cast<DerivedType>(NewType)->addAbstractTypeUser(this); #if DEBUG_ABSTYPE cerr << "[Added] refined to abstype: "<<NewType->getDescription()<<"\n"; #endif } } VarMap &NewPlane = NewTypeIt->second; VarMap &OldPlane = TPI->second; while (!OldPlane.empty()) { pair<const string, Value*> V = *OldPlane.begin(); // Check to see if there is already a value in the symbol table that this // would collide with. type_iterator TI = NewPlane.find(V.first); if (TI != NewPlane.end() && TI->second == V.second) { // No action } else if (TI != NewPlane.end()) { // The only thing we are allowing for now is two external global values // folded into one. // GlobalValue *ExistGV = dyn_cast<GlobalValue>(TI->second); GlobalValue *NewGV = dyn_cast<GlobalValue>(V.second); if (ExistGV && NewGV && ExistGV->isExternal() && NewGV->isExternal()) { // Ok we have two external global values. Make all uses of the new // one use the old one... // assert(ExistGV->use_empty() && "No uses allowed on untyped value!"); //NewGV->replaceAllUsesWith(ExistGV); // Now we just convert it to an unnamed method... which won't get // added to our symbol table. The problem is that if we call // setName on the method that it will try to remove itself from // the symbol table and die... because it's not in the symtab // right now. To fix this, we have an internally consistent flag // that turns remove into a noop. Thus the name will get null'd // out, but the symbol table won't get upset. // assert(InternallyInconsistent == false && "Symbol table already inconsistent!"); InternallyInconsistent = true; // Remove newM from the symtab NewGV->setName(""); InternallyInconsistent = false; // Now we can remove this global from the module entirely... Module *M = NewGV->getParent(); if (Function *F = dyn_cast<Function>(NewGV)) M->getFunctionList().remove(F); else M->getGlobalList().remove(cast<GlobalVariable>(NewGV)); delete NewGV; } else { assert(0 && "Two planes folded together with overlapping " "value names!"); } } else { insertEntry(V.first, NewType, V.second); } // Remove the item from the old type plane OldPlane.erase(OldPlane.begin()); } // Ok, now we are not referencing the type anymore... take me off your user // list please! #if DEBUG_ABSTYPE cerr << "Removing type " << OldType->getDescription() << "\n"; #endif OldType->removeAbstractTypeUser(this); // Remove the plane that is no longer used erase(TPI); } else if (TPI != end()) { assert(OldType == NewType); #if DEBUG_ABSTYPE cerr << "Removing SELF type " << OldType->getDescription() << "\n"; #endif OldType->removeAbstractTypeUser(this); } TPI = find(Type::TypeTy); if (TPI != end()) { // Loop over all of the types in the symbol table, replacing any references // to OldType with references to NewType. Note that there may be multiple // occurances, and although we only need to remove one at a time, it's // faster to remove them all in one pass. // VarMap &TyPlane = TPI->second; for (VarMap::iterator I = TyPlane.begin(), E = TyPlane.end(); I != E; ++I) if (I->second == (Value*)OldType) { // FIXME when Types aren't const. #if DEBUG_ABSTYPE cerr << "Removing type " << OldType->getDescription() << "\n"; #endif OldType->removeAbstractTypeUser(this); I->second = (Value*)NewType; // TODO FIXME when types aren't const if (NewType->isAbstract()) { #if DEBUG_ABSTYPE cerr << "Added type " << NewType->getDescription() << "\n"; #endif cast<const DerivedType>(NewType)->addAbstractTypeUser(this); } } } } static void DumpVal(const pair<const string, Value *> &V) { std::cout << " '" << V.first << "' = "; V.second->dump(); std::cout << "\n"; } static void DumpPlane(const pair<const Type *, map<const string, Value *> >&P) { std::cout << " Plane: "; P.first->dump(); std::cout << "\n"; for_each(P.second.begin(), P.second.end(), DumpVal); } void SymbolTable::dump() const { std::cout << "Symbol table dump:\n"; for_each(begin(), end(), DumpPlane); }
Fix bug: Assembler/2002-12-15-GlobalResolve.ll
Fix bug: Assembler/2002-12-15-GlobalResolve.ll git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@5039 91177308-0d34-0410-b5e6-96231b3b80d8
C++
apache-2.0
llvm-mirror/llvm,GPUOpen-Drivers/llvm,dslab-epfl/asap,apple/swift-llvm,chubbymaggie/asap,chubbymaggie/asap,chubbymaggie/asap,dslab-epfl/asap,chubbymaggie/asap,apple/swift-llvm,apple/swift-llvm,apple/swift-llvm,chubbymaggie/asap,chubbymaggie/asap,llvm-mirror/llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,apple/swift-llvm,llvm-mirror/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,dslab-epfl/asap,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,dslab-epfl/asap,apple/swift-llvm,dslab-epfl/asap,llvm-mirror/llvm,llvm-mirror/llvm,apple/swift-llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,dslab-epfl/asap,llvm-mirror/llvm,dslab-epfl/asap,llvm-mirror/llvm
1489d537fb44536befab42f87cfe7f41ff4189a2
src/mapnik_logger.cpp
src/mapnik_logger.cpp
/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2015 Artem Pavlenko, Jean-Francois Doyon * * 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 * *****************************************************************************/ #include <mapnik/config.hpp> // boost #include "boost_std_shared_shim.hpp" #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-parameter" #pragma GCC diagnostic ignored "-Wunused-local-typedef" #pragma GCC diagnostic ignored "-Wmissing-field-initializers" #pragma GCC diagnostic ignored "-Wshadow" #pragma GCC diagnostic ignored "-Wshorten-64-to-32" #include <boost/python.hpp> #include <boost/noncopyable.hpp> #pragma GCC diagnostic pop #include <mapnik/debug.hpp> #include <mapnik/util/singleton.hpp> #include "mapnik_enumeration.hpp" void export_logger() { using mapnik::logger; using mapnik::singleton; using mapnik::CreateStatic; using namespace boost::python; class_<singleton<logger,CreateStatic>,boost::noncopyable>("Singleton",no_init) .def("instance",&singleton<logger,CreateStatic>::instance, return_value_policy<reference_existing_object>()) .staticmethod("instance") ; enum_<mapnik::logger::severity_type>("severity_type") .value("Debug", logger::debug) .value("Warn", logger::warn) .value("Error", logger::error) .value("None", logger::none) ; class_<logger,bases<singleton<logger,CreateStatic> >, boost::noncopyable>("logger",no_init) .def("get_severity", &logger::get_severity) .def("set_severity", &logger::set_severity) .def("get_object_severity", &logger::get_object_severity) .def("set_object_severity", &logger::set_object_severity) .def("clear_object_severity", &logger::clear_object_severity) .def("get_format", &logger::get_format) .def("set_format", &logger::set_format) .def("str", &logger::str) .def("use_file", &logger::use_file) .def("use_console", &logger::use_console) .staticmethod("get_severity") .staticmethod("set_severity") .staticmethod("get_object_severity") .staticmethod("set_object_severity") .staticmethod("clear_object_severity") .staticmethod("get_format") .staticmethod("set_format") .staticmethod("str") .staticmethod("use_file") .staticmethod("use_console") ; }
/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2015 Artem Pavlenko, Jean-Francois Doyon * * 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 * *****************************************************************************/ #include <mapnik/config.hpp> // boost #include "boost_std_shared_shim.hpp" #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-parameter" #pragma GCC diagnostic ignored "-Wunused-local-typedef" #pragma GCC diagnostic ignored "-Wmissing-field-initializers" #pragma GCC diagnostic ignored "-Wshadow" #pragma GCC diagnostic ignored "-Wshorten-64-to-32" #include <boost/python.hpp> #include <boost/noncopyable.hpp> #pragma GCC diagnostic pop #include <mapnik/debug.hpp> #include <mapnik/util/singleton.hpp> #include "mapnik_enumeration.hpp" void export_logger() { using mapnik::logger; using mapnik::singleton; using mapnik::CreateStatic; using namespace boost::python; class_<singleton<logger,CreateStatic>,boost::noncopyable>("Singleton",no_init) .def("instance",&singleton<logger,CreateStatic>::instance, return_value_policy<reference_existing_object>()) .staticmethod("instance") ; enum_<mapnik::logger::severity_type>("severity_type") .value("Debug", logger::debug) .value("Warn", logger::warn) .value("Error", logger::error) .value("None", logger::none) ; class_<logger,bases<singleton<logger,CreateStatic> >, boost::noncopyable>("logger",no_init) .def("get_severity", &logger::get_severity) .def("set_severity", &logger::set_severity) .def("get_object_severity", &logger::get_object_severity) .def("set_object_severity", &logger::set_object_severity) .def("clear_object_severity", &logger::clear_object_severity) .def("get_format", &logger::get_format,return_value_policy<reference_existing_object>()) .def("set_format", &logger::set_format) .def("str", &logger::str) .def("use_file", &logger::use_file) .def("use_console", &logger::use_console) .staticmethod("get_severity") .staticmethod("set_severity") .staticmethod("get_object_severity") .staticmethod("set_object_severity") .staticmethod("clear_object_severity") .staticmethod("get_format") .staticmethod("set_format") .staticmethod("str") .staticmethod("use_file") .staticmethod("use_console") ; }
fix get_format return policy
fix get_format return policy
C++
lgpl-2.1
mapnik/python-mapnik,mapycz/python-mapnik,garnertb/python-mapnik,tomhughes/python-mapnik,tomhughes/python-mapnik,mapycz/python-mapnik,mapnik/python-mapnik,davenquinn/python-mapnik,garnertb/python-mapnik,garnertb/python-mapnik,davenquinn/python-mapnik,davenquinn/python-mapnik,tomhughes/python-mapnik,mapnik/python-mapnik
d3ce9b0324d98d30e572d2db8357061bc4078072
src/mcrl2-greybox.cpp
src/mcrl2-greybox.cpp
#include <config.h> #include <algorithm> #include <iterator> #include <iostream> #include <memory> #include <string> #include <set> #include <vector> #include <stack> #include <mcrl2/atermpp/aterm_init.h> #include <mcrl2/lps/ltsmin.h> extern "C" { #include <assert.h> #include <limits.h> #include <popt.h> #include <mcrl2-greybox.h> #include <dm/dm.h> #include <runtime.h> } static std::string mcrl2_rewriter_strategy; #ifdef MCRL2_JITTYC_AVAILABLE static char const* mcrl2_args="--rewriter=jittyc"; #else static char const* mcrl2_args="--rewriter=jitty"; #endif struct state_cb { typedef int *state_vector; typedef int *label_vector; TransitionCB& cb; void* ctx; int& count; state_cb (TransitionCB& cb_, void *ctx_, int& count_) : cb(cb_), ctx(ctx_), count(count_) {} void operator()(state_vector const& next_state, label_vector const& edge_labels, int group = -1) { transition_info_t ti = { edge_labels, group }; cb (ctx, &ti, next_state); ++count; } }; class mcrl2_index { public: std::string buffer_; mcrl2_index(mcrl2::lps::pins* pins, int tag) : pins_(pins), tag_(tag) {} mcrl2::lps::pins* get_pins() const { return pins_; } int tag() const { return tag_; } protected: mcrl2::lps::pins* pins_; // crucially relies on that tag == typeno, although they // are created separately int tag_; }; extern "C" { static void * mcrl2_newmap (void *ctx) { static int tag = 0; // XXX typemap return (void*)new mcrl2_index(reinterpret_cast<mcrl2::lps::pins*>(ctx), tag++); } static int mcrl2_chunk2int (void *map_, void *chunk, int len) { mcrl2_index *map = reinterpret_cast<mcrl2_index*>(map_); mcrl2::lps::pins& pins = *map->get_pins(); return pins.data_type(map->tag()).deserialize(std::string((char*)chunk,len)); } static const void * mcrl2_int2chunk (void *map_, int idx, int *len) { mcrl2_index *map = reinterpret_cast<mcrl2_index*>(map_); mcrl2::lps::pins& pins = *map->get_pins(); map->buffer_ = pins.data_type(map->tag()).print(idx); // XXX serialize *len = map->buffer_.length(); return map->buffer_.data(); // XXX life-time } static int mcrl2_chunk_count(void *map_) { mcrl2_index *map = reinterpret_cast<mcrl2_index*>(map_); return map->get_pins()->data_type(map->tag()).size(); } static void override_chunk_methods(model_t model, mcrl2::lps::pins* pins) { Warning(info, "This mcrl2 language module does not work with the MPI backend."); GBsetChunkMethods(model, mcrl2_newmap, pins, (int2chunk_t)mcrl2_int2chunk, mcrl2_chunk2int, mcrl2_chunk_count); } static void mcrl2_popt (poptContext con, enum poptCallbackReason reason, const struct poptOption *opt, const char *arg, void *data) { (void)con;(void)opt;(void)arg;(void)data; switch (reason) { case POPT_CALLBACK_REASON_PRE: break; case POPT_CALLBACK_REASON_POST: { Warning(debug,"mcrl2 init"); int argc; char **argv; RTparseOptions (mcrl2_args,&argc,&argv); Warning (debug,"ATerm init"); MCRL2_ATERMPP_INIT(argc, argv); char *rewriter = NULL; struct poptOption options[] = { { "rewriter", 0 , POPT_ARG_STRING , &rewriter , 0 , "select rewriter" , NULL }, POPT_TABLEEND }; Warning (debug,"options"); poptContext optCon = poptGetContext(NULL, argc,const_cast<const char**>(argv), options, 0); int res = poptGetNextOpt(optCon); if (res != -1 || poptPeekArg(optCon)!=NULL) { Fatal(1,error,"Bad mcrl2 options: %s",mcrl2_args); } poptFreeContext(optCon); if (rewriter) { mcrl2_rewriter_strategy = std::string(rewriter); } else { Fatal(1,error,"unrecognized rewriter: %s (jitty, jittyc, inner and innerc supported)",rewriter); } GBregisterLoader("lps",MCRL2loadGreyboxModel); Warning(info,"mCRL2 language module initialized"); return; } case POPT_CALLBACK_REASON_OPTION: break; } Fatal(1,error,"unexpected call to mcrl2_popt"); } struct poptOption mcrl2_options[] = { { NULL, 0 , POPT_ARG_CALLBACK|POPT_CBFLAG_POST|POPT_CBFLAG_SKIPOPTION , (void*)mcrl2_popt , 0 , NULL , NULL}, { "mcrl2" , 0 , POPT_ARG_STRING|POPT_ARGFLAG_SHOW_DEFAULT , &mcrl2_args , 0, "Pass options to the mcrl2 library.","<mcrl2 options>" }, POPT_TABLEEND }; void MCRL2initGreybox (int argc,char *argv[],void* stack_bottom) { Warning(debug,"ATerm init"); MCRL2_ATERMPP_INIT(argc, argv); (void)stack_bottom; } static int MCRL2getTransitionsLong (model_t m, int group, int *src, TransitionCB cb, void *ctx) { mcrl2::lps::pins *pins = (mcrl2::lps::pins *)GBgetContext (m); int count = 0; int dst[pins->process_parameter_count()]; int labels[pins->edge_label_count()]; state_cb f(cb, ctx, count); pins->next_state_long(src, group, f, dst, labels); return count; } static int MCRL2getTransitionsAll (model_t m, int* src, TransitionCB cb, void *ctx) { mcrl2::lps::pins *pins = (mcrl2::lps::pins *)GBgetContext (m); int count = 0; int dst[pins->process_parameter_count()]; int labels[pins->edge_label_count()]; state_cb f(cb, ctx, count); pins->next_state_all(src, f, dst, labels); return count; } void MCRL2loadGreyboxModel (model_t m, const char *model_name) { Warning(info, "mCRL2 rewriter: %s", mcrl2_rewriter_strategy.c_str()); mcrl2::lps::pins *pins = new mcrl2::lps::pins(std::string(model_name), mcrl2_rewriter_strategy); GBsetContext(m,pins); lts_type_t ltstype = lts_type_create(); lts_type_set_state_length (ltstype, pins->process_parameter_count()); // create ltsmin type for each mcrl2-provided type for(size_t i = 0; i < pins->datatype_count(); ++i) { lts_type_add_type(ltstype, pins->data_type(i).name().c_str(), NULL); } // process parameters for(size_t i = 0; i < pins->process_parameter_count(); ++i) { lts_type_set_state_name(ltstype, i, pins->process_parameter_name(i).c_str()); lts_type_set_state_type(ltstype, i, pins->data_type(pins->process_parameter_type(i)).name().c_str()); } // edge labels lts_type_set_edge_label_count(ltstype, pins->edge_label_count()); for (size_t i = 0; i < pins->edge_label_count(); ++i) { lts_type_set_edge_label_name(ltstype, i, pins->edge_label_name(i).c_str()); lts_type_set_edge_label_type(ltstype, i, pins->data_type(pins->edge_label_type(i)).name().c_str()); } override_chunk_methods(m, pins); GBsetLTStype(m,ltstype); int s0[pins->process_parameter_count()]; mcrl2::lps::pins::ltsmin_state_type p_s0 = s0; pins->get_initial_state(p_s0); GBsetInitialState(m, s0); matrix_t *p_dm_info = reinterpret_cast<matrix_t *>(RTmalloc(sizeof *p_dm_info)); matrix_t *p_dm_read_info = reinterpret_cast<matrix_t *>(RTmalloc(sizeof *p_dm_read_info)); matrix_t *p_dm_write_info = reinterpret_cast<matrix_t *>(RTmalloc(sizeof *p_dm_write_info)); dm_create(p_dm_info, pins->group_count(), pins->process_parameter_count()); dm_create(p_dm_read_info, pins->group_count(), pins->process_parameter_count()); dm_create(p_dm_write_info, pins->group_count(), pins->process_parameter_count()); for (int i = 0; i <dm_nrows (p_dm_info); i++) { std::vector<size_t> const& vec_r = pins->read_group(i); for (size_t j=0; j <vec_r.size(); j++) { dm_set (p_dm_info, i, vec_r[j]); dm_set (p_dm_read_info, i, vec_r[j]); } std::vector<size_t> const& vec_w = pins->write_group(i); for (size_t j=0; j <vec_w.size(); j++) { dm_set (p_dm_info, i, vec_w[j]); dm_set (p_dm_write_info, i, vec_w[j]); } } GBsetDMInfo (m, p_dm_info); GBsetDMInfoRead (m, p_dm_read_info); GBsetDMInfoWrite (m, p_dm_write_info); matrix_t *p_sl_info = reinterpret_cast<matrix_t *>(RTmalloc(sizeof *p_sl_info)); dm_create (p_sl_info, 0, pins->process_parameter_count()); GBsetStateLabelInfo (m, p_sl_info); GBsetNextStateLong (m, MCRL2getTransitionsLong); GBsetNextStateAll (m, MCRL2getTransitionsAll); } }
#include <config.h> #include <algorithm> #include <iterator> #include <iostream> #include <memory> #include <string> #include <set> #include <vector> #include <stack> #include <mcrl2/atermpp/aterm_init.h> #include <mcrl2/lps/ltsmin.h> extern "C" { #include <assert.h> #include <limits.h> #include <popt.h> #include <mcrl2-greybox.h> #include <dm/dm.h> #include <runtime.h> } static std::string mcrl2_rewriter_strategy; #ifdef MCRL2_JITTYC_AVAILABLE static char const* mcrl2_args="--rewriter=jittyc"; #else static char const* mcrl2_args="--rewriter=jitty"; #endif struct state_cb { typedef int *state_vector; typedef int *label_vector; TransitionCB& cb; void* ctx; int& count; state_cb (TransitionCB& cb_, void *ctx_, int& count_) : cb(cb_), ctx(ctx_), count(count_) {} void operator()(state_vector const& next_state, label_vector const& edge_labels, int group = -1) { transition_info_t ti = { edge_labels, group }; cb (ctx, &ti, next_state); ++count; } }; class mcrl2_index { public: std::string buffer_; mcrl2_index(mcrl2::lps::pins* pins, int tag) : pins_(pins), tag_(tag) {} mcrl2::lps::pins* get_pins() const { return pins_; } int tag() const { return tag_; } protected: mcrl2::lps::pins* pins_; // crucially relies on that tag == typeno, although they // are created separately int tag_; }; extern "C" { static void * mcrl2_newmap (void *ctx) { static int tag = 0; // XXX typemap return (void*)new mcrl2_index(reinterpret_cast<mcrl2::lps::pins*>(ctx), tag++); } static int mcrl2_chunk2int (void *map_, void *chunk, int len) { mcrl2_index *map = reinterpret_cast<mcrl2_index*>(map_); mcrl2::lps::pins& pins = *map->get_pins(); return pins.data_type(map->tag()).deserialize(std::string((char*)chunk,len)); } static const void * mcrl2_int2chunk (void *map_, int idx, int *len) { mcrl2_index *map = reinterpret_cast<mcrl2_index*>(map_); mcrl2::lps::pins& pins = *map->get_pins(); map->buffer_ = pins.data_type(map->tag()).print(idx); // XXX serialize *len = map->buffer_.length(); return map->buffer_.data(); // XXX life-time } static int mcrl2_chunk_count(void *map_) { mcrl2_index *map = reinterpret_cast<mcrl2_index*>(map_); return map->get_pins()->data_type(map->tag()).size(); } static void override_chunk_methods(model_t model, mcrl2::lps::pins* pins) { Warning(info, "This mcrl2 language module does not work with the MPI backend."); GBsetChunkMethods(model, mcrl2_newmap, pins, (int2chunk_t)mcrl2_int2chunk, mcrl2_chunk2int, mcrl2_chunk_count); } static void mcrl2_popt (poptContext con, enum poptCallbackReason reason, const struct poptOption *opt, const char *arg, void *data) { (void)con;(void)opt;(void)arg;(void)data; switch (reason) { case POPT_CALLBACK_REASON_PRE: break; case POPT_CALLBACK_REASON_POST: { Warning(debug,"mcrl2 init"); int argc; char **argv; RTparseOptions (mcrl2_args,&argc,&argv); Warning (debug,"ATerm init"); MCRL2_ATERMPP_INIT_(argc, argv, RTstackBottom()); char *rewriter = NULL; struct poptOption options[] = { { "rewriter", 0 , POPT_ARG_STRING , &rewriter , 0 , "select rewriter" , NULL }, POPT_TABLEEND }; Warning (debug,"options"); poptContext optCon = poptGetContext(NULL, argc,const_cast<const char**>(argv), options, 0); int res = poptGetNextOpt(optCon); if (res != -1 || poptPeekArg(optCon)!=NULL) { Fatal(1,error,"Bad mcrl2 options: %s",mcrl2_args); } poptFreeContext(optCon); if (rewriter) { mcrl2_rewriter_strategy = std::string(rewriter); } else { Fatal(1,error,"unrecognized rewriter: %s (jitty, jittyc, inner and innerc supported)",rewriter); } GBregisterLoader("lps",MCRL2loadGreyboxModel); Warning(info,"mCRL2 language module initialized"); return; } case POPT_CALLBACK_REASON_OPTION: break; } Fatal(1,error,"unexpected call to mcrl2_popt"); } struct poptOption mcrl2_options[] = { { NULL, 0 , POPT_ARG_CALLBACK|POPT_CBFLAG_POST|POPT_CBFLAG_SKIPOPTION , (void*)mcrl2_popt , 0 , NULL , NULL}, { "mcrl2" , 0 , POPT_ARG_STRING|POPT_ARGFLAG_SHOW_DEFAULT , &mcrl2_args , 0, "Pass options to the mcrl2 library.","<mcrl2 options>" }, POPT_TABLEEND }; void MCRL2initGreybox (int argc,char *argv[],void* stack_bottom) { Warning(debug,"ATerm init"); MCRL2_ATERMPP_INIT_(argc, argv, stack_bottom); (void)stack_bottom; } static int MCRL2getTransitionsLong (model_t m, int group, int *src, TransitionCB cb, void *ctx) { mcrl2::lps::pins *pins = (mcrl2::lps::pins *)GBgetContext (m); int count = 0; int dst[pins->process_parameter_count()]; int labels[pins->edge_label_count()]; state_cb f(cb, ctx, count); pins->next_state_long(src, group, f, dst, labels); return count; } static int MCRL2getTransitionsAll (model_t m, int* src, TransitionCB cb, void *ctx) { mcrl2::lps::pins *pins = (mcrl2::lps::pins *)GBgetContext (m); int count = 0; int dst[pins->process_parameter_count()]; int labels[pins->edge_label_count()]; state_cb f(cb, ctx, count); pins->next_state_all(src, f, dst, labels); return count; } void MCRL2loadGreyboxModel (model_t m, const char *model_name) { Warning(info, "mCRL2 rewriter: %s", mcrl2_rewriter_strategy.c_str()); mcrl2::lps::pins *pins = new mcrl2::lps::pins(std::string(model_name), mcrl2_rewriter_strategy); GBsetContext(m,pins); lts_type_t ltstype = lts_type_create(); lts_type_set_state_length (ltstype, pins->process_parameter_count()); // create ltsmin type for each mcrl2-provided type for(size_t i = 0; i < pins->datatype_count(); ++i) { lts_type_add_type(ltstype, pins->data_type(i).name().c_str(), NULL); } // process parameters for(size_t i = 0; i < pins->process_parameter_count(); ++i) { lts_type_set_state_name(ltstype, i, pins->process_parameter_name(i).c_str()); lts_type_set_state_type(ltstype, i, pins->data_type(pins->process_parameter_type(i)).name().c_str()); } // edge labels lts_type_set_edge_label_count(ltstype, pins->edge_label_count()); for (size_t i = 0; i < pins->edge_label_count(); ++i) { lts_type_set_edge_label_name(ltstype, i, pins->edge_label_name(i).c_str()); lts_type_set_edge_label_type(ltstype, i, pins->data_type(pins->edge_label_type(i)).name().c_str()); } override_chunk_methods(m, pins); GBsetLTStype(m,ltstype); int s0[pins->process_parameter_count()]; mcrl2::lps::pins::ltsmin_state_type p_s0 = s0; pins->get_initial_state(p_s0); GBsetInitialState(m, s0); matrix_t *p_dm_info = reinterpret_cast<matrix_t *>(RTmalloc(sizeof *p_dm_info)); matrix_t *p_dm_read_info = reinterpret_cast<matrix_t *>(RTmalloc(sizeof *p_dm_read_info)); matrix_t *p_dm_write_info = reinterpret_cast<matrix_t *>(RTmalloc(sizeof *p_dm_write_info)); dm_create(p_dm_info, pins->group_count(), pins->process_parameter_count()); dm_create(p_dm_read_info, pins->group_count(), pins->process_parameter_count()); dm_create(p_dm_write_info, pins->group_count(), pins->process_parameter_count()); for (int i = 0; i <dm_nrows (p_dm_info); i++) { std::vector<size_t> const& vec_r = pins->read_group(i); for (size_t j=0; j <vec_r.size(); j++) { dm_set (p_dm_info, i, vec_r[j]); dm_set (p_dm_read_info, i, vec_r[j]); } std::vector<size_t> const& vec_w = pins->write_group(i); for (size_t j=0; j <vec_w.size(); j++) { dm_set (p_dm_info, i, vec_w[j]); dm_set (p_dm_write_info, i, vec_w[j]); } } GBsetDMInfo (m, p_dm_info); GBsetDMInfoRead (m, p_dm_read_info); GBsetDMInfoWrite (m, p_dm_write_info); matrix_t *p_sl_info = reinterpret_cast<matrix_t *>(RTmalloc(sizeof *p_sl_info)); dm_create (p_sl_info, 0, pins->process_parameter_count()); GBsetStateLabelInfo (m, p_sl_info); GBsetNextStateLong (m, MCRL2getTransitionsLong); GBsetNextStateAll (m, MCRL2getTransitionsAll); } }
Initialize Aterms using correct stack bottom
Initialize Aterms using correct stack bottom
C++
bsd-3-clause
Sybe/composition,utwente-fmt/ltsmin,vbloemen/ltsmin,Meijuh/ltsmin,buschko/ltsmin,alaarman/ltsmin,trolando/ltsmin,thedobs/LTSmin,utwente-fmt/ltsmin,vbloemen/ltsmin,trolando/ltsmin,trolando/ltsmin,lordqwerty/ltsmin,buschko/ltsmin,Sybe/composition,utwente-fmt/ltsmin,Meijuh/ltsmin,utwente-fmt/ltsmin,Meijuh/ltsmin,buschko/ltsmin,Sybe/composition,Meijuh/ltsmin,alaarman/ltsmin,lordqwerty/ltsmin,lordqwerty/ltsmin,utwente-fmt/ltsmin,vbloemen/ltsmin,vbloemen/ltsmin,vbloemen/ltsmin,thedobs/LTSmin,vbloemen/ltsmin,Meijuh/ltsmin,thedobs/LTSmin,alaarman/ltsmin,trolando/ltsmin,thedobs/LTSmin,vbloemen/ltsmin,alaarman/ltsmin,alaarman/ltsmin,alaarman/ltsmin,buschko/ltsmin,utwente-fmt/ltsmin,Meijuh/ltsmin,Sybe/composition,lordqwerty/ltsmin
2925ee18bab0e53dcbec32b1cd107f6ff55f9f30
ext/common/Logging.cpp
ext/common/Logging.cpp
/* * Phusion Passenger - https://www.phusionpassenger.com/ * Copyright (c) 2010-2014 Phusion * * "Phusion Passenger" is a trademark of Hongli Lai & Ninh Bui. * * 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 <iomanip> #include <cstdlib> #include <cstring> #include <fcntl.h> #include <unistd.h> #include <boost/atomic.hpp> #include <Logging.h> #include <Constants.h> #include <StaticString.h> #include <Utils/StrIntUtils.h> #include <Utils/IOUtils.h> namespace Passenger { volatile sig_atomic_t _logLevel = DEFAULT_LOG_LEVEL; AssertionFailureInfo lastAssertionFailure; static bool printAppOutputAsDebuggingMessages = false; static char *logFile = NULL; void setLogLevel(int value) { _logLevel = value; boost::atomic_signal_fence(boost::memory_order_seq_cst); } bool setLogFile(const char *path) { int fd = open(path, O_WRONLY | O_CREAT | O_APPEND, 0644); if (fd != -1) { char *newLogFile = strdup(path); if (newLogFile == NULL) { P_CRITICAL("Cannot allocate memory"); abort(); } dup2(fd, STDOUT_FILENO); dup2(fd, STDERR_FILENO); close(fd); if (logFile != NULL) { free(logFile); } logFile = newLogFile; return true; } else { return false; } } string getLogFile() { if (logFile == NULL) { return string(); } else { return string(logFile); } } void _prepareLogEntry(std::stringstream &sstream, const char *file, unsigned int line) { time_t the_time; struct tm the_tm; char datetime_buf[60]; struct timeval tv; if (startsWith(file, "ext/")) { file += sizeof("ext/") - 1; if (startsWith(file, "common/")) { file += sizeof("common/") - 1; if (startsWith(file, "ApplicationPool2/")) { file += sizeof("Application") - 1; } } } the_time = time(NULL); localtime_r(&the_time, &the_tm); strftime(datetime_buf, sizeof(datetime_buf) - 1, "%F %H:%M:%S", &the_tm); gettimeofday(&tv, NULL); sstream << "[ " << datetime_buf << "." << std::setfill('0') << std::setw(4) << (unsigned long) (tv.tv_usec / 100) << " " << std::dec << getpid() << "/" << std::hex << pthread_self() << std::dec << " " << file << ":" << line << " ]: "; } static void _writeLogEntry(const StaticString &str) { try { writeExact(STDERR_FILENO, str.data(), str.size()); } catch (const SystemException &) { /* The most likely reason why this fails is when the user has setup * Apache to log to a pipe (e.g. to a log rotation script). Upon * restarting the web server, the process that reads from the pipe * shuts down, so we can't write to it anymore. That's why we * just ignore write errors. It doesn't make sense to abort for * something like this. */ } } void _writeLogEntry(const std::string &str) { _writeLogEntry(StaticString(str)); } void _writeLogEntry(const char *str, unsigned int size) { _writeLogEntry(StaticString(str, size)); } const char * _strdupStringStream(const std::stringstream &stream) { string str = stream.str(); char *buf = (char *) malloc(str.size() + 1); memcpy(buf, str.data(), str.size()); buf[str.size()] = '\0'; return buf; } static void realPrintAppOutput(char *buf, unsigned int bufSize, const char *pidStr, unsigned int pidStrLen, const char *channelName, unsigned int channelNameLen, const char *message, unsigned int messageLen) { char *pos = buf; char *end = buf + bufSize; pos = appendData(pos, end, "App "); pos = appendData(pos, end, pidStr, pidStrLen); pos = appendData(pos, end, " "); pos = appendData(pos, end, channelName, channelNameLen); pos = appendData(pos, end, ": "); pos = appendData(pos, end, message, messageLen); pos = appendData(pos, end, "\n"); _writeLogEntry(StaticString(buf, pos - buf)); } void printAppOutput(pid_t pid, const char *channelName, const char *message, unsigned int size) { if (printAppOutputAsDebuggingMessages) { P_DEBUG("App " << pid << " " << channelName << ": " << StaticString(message, size)); } else { char pidStr[sizeof("4294967295")]; unsigned int pidStrLen, channelNameLen, totalLen; try { pidStrLen = integerToOtherBase<pid_t, 10>(pid, pidStr, sizeof(pidStr)); } catch (const std::length_error &) { pidStr[0] = '?'; pidStr[1] = '\0'; pidStrLen = 1; } channelNameLen = strlen(channelName); totalLen = (sizeof("App X Y: \n") - 2) + pidStrLen + channelNameLen + size; if (totalLen < 1024) { char buf[1024]; realPrintAppOutput(buf, sizeof(buf), pidStr, pidStrLen, channelName, channelNameLen, message, size); } else { DynamicBuffer buf(totalLen); realPrintAppOutput(buf.data, totalLen, pidStr, pidStrLen, channelName, channelNameLen, message, size); } } } void setPrintAppOutputAsDebuggingMessages(bool enabled) { printAppOutputAsDebuggingMessages = enabled; } } // namespace Passenger
/* * Phusion Passenger - https://www.phusionpassenger.com/ * Copyright (c) 2010-2015 Phusion * * "Phusion Passenger" is a trademark of Hongli Lai & Ninh Bui. * * 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 <iomanip> #include <cstdlib> #include <cstring> #include <fcntl.h> #include <unistd.h> #include <boost/atomic.hpp> #include <Logging.h> #include <Constants.h> #include <StaticString.h> #include <Utils/StrIntUtils.h> #include <Utils/IOUtils.h> namespace Passenger { volatile sig_atomic_t _logLevel = DEFAULT_LOG_LEVEL; AssertionFailureInfo lastAssertionFailure; static bool printAppOutputAsDebuggingMessages = false; static char *logFile = NULL; #define TRUNCATE_LOGPATHS_TO_MAXCHARS 3 // set to 0 to disable truncation void setLogLevel(int value) { _logLevel = value; boost::atomic_signal_fence(boost::memory_order_seq_cst); } bool setLogFile(const char *path) { int fd = open(path, O_WRONLY | O_CREAT | O_APPEND, 0644); if (fd != -1) { char *newLogFile = strdup(path); if (newLogFile == NULL) { P_CRITICAL("Cannot allocate memory"); abort(); } dup2(fd, STDOUT_FILENO); dup2(fd, STDERR_FILENO); close(fd); if (logFile != NULL) { free(logFile); } logFile = newLogFile; return true; } else { return false; } } string getLogFile() { if (logFile == NULL) { return string(); } else { return string(logFile); } } void _prepareLogEntry(std::stringstream &sstream, const char *file, unsigned int line) { time_t the_time; struct tm the_tm; char datetime_buf[60]; struct timeval tv; the_time = time(NULL); localtime_r(&the_time, &the_tm); strftime(datetime_buf, sizeof(datetime_buf) - 1, "%F %H:%M:%S", &the_tm); gettimeofday(&tv, NULL); sstream << "[ " << datetime_buf << "." << std::setfill('0') << std::setw(4) << (unsigned long) (tv.tv_usec / 100) << " " << std::dec << getpid() << "/" << std::hex << pthread_self() << std::dec << " "; if (startsWith(file, "ext/")) { // special reduncancy filter because most code resides in these paths file += sizeof("ext/") - 1; if (startsWith(file, "common/")) { file += sizeof("common/") - 1; } } if (TRUNCATE_LOGPATHS_TO_MAXCHARS > 0) { truncateBeforeTokens(file, "/\\", TRUNCATE_LOGPATHS_TO_MAXCHARS, sstream); } else { sstream << file; } sstream << ":" << line << " ]: "; } static void _writeLogEntry(const StaticString &str) { try { writeExact(STDERR_FILENO, str.data(), str.size()); } catch (const SystemException &) { /* The most likely reason why this fails is when the user has setup * Apache to log to a pipe (e.g. to a log rotation script). Upon * restarting the web server, the process that reads from the pipe * shuts down, so we can't write to it anymore. That's why we * just ignore write errors. It doesn't make sense to abort for * something like this. */ } } void _writeLogEntry(const std::string &str) { _writeLogEntry(StaticString(str)); } void _writeLogEntry(const char *str, unsigned int size) { _writeLogEntry(StaticString(str, size)); } const char * _strdupStringStream(const std::stringstream &stream) { string str = stream.str(); char *buf = (char *) malloc(str.size() + 1); memcpy(buf, str.data(), str.size()); buf[str.size()] = '\0'; return buf; } static void realPrintAppOutput(char *buf, unsigned int bufSize, const char *pidStr, unsigned int pidStrLen, const char *channelName, unsigned int channelNameLen, const char *message, unsigned int messageLen) { char *pos = buf; char *end = buf + bufSize; pos = appendData(pos, end, "App "); pos = appendData(pos, end, pidStr, pidStrLen); pos = appendData(pos, end, " "); pos = appendData(pos, end, channelName, channelNameLen); pos = appendData(pos, end, ": "); pos = appendData(pos, end, message, messageLen); pos = appendData(pos, end, "\n"); _writeLogEntry(StaticString(buf, pos - buf)); } void printAppOutput(pid_t pid, const char *channelName, const char *message, unsigned int size) { if (printAppOutputAsDebuggingMessages) { P_DEBUG("App " << pid << " " << channelName << ": " << StaticString(message, size)); } else { char pidStr[sizeof("4294967295")]; unsigned int pidStrLen, channelNameLen, totalLen; try { pidStrLen = integerToOtherBase<pid_t, 10>(pid, pidStr, sizeof(pidStr)); } catch (const std::length_error &) { pidStr[0] = '?'; pidStr[1] = '\0'; pidStrLen = 1; } channelNameLen = strlen(channelName); totalLen = (sizeof("App X Y: \n") - 2) + pidStrLen + channelNameLen + size; if (totalLen < 1024) { char buf[1024]; realPrintAppOutput(buf, sizeof(buf), pidStr, pidStrLen, channelName, channelNameLen, message, size); } else { DynamicBuffer buf(totalLen); realPrintAppOutput(buf.data, totalLen, pidStr, pidStrLen, channelName, channelNameLen, message, size); } } } void setPrintAppOutputAsDebuggingMessages(bool enabled) { printAppOutputAsDebuggingMessages = enabled; } } // namespace Passenger
Truncate paths in logging strings (to 3 chars) to reduce redundant info. Closes GH #1383
Truncate paths in logging strings (to 3 chars) to reduce redundant info. Closes GH #1383
C++
mit
clemensg/passenger,kewaunited/passenger,clemensg/passenger,cgvarela/passenger,kewaunited/passenger,cgvarela/passenger,phusion/passenger,antek-drzewiecki/passenger,kewaunited/passenger,phusion/passenger,kewaunited/passenger,antek-drzewiecki/passenger,phusion/passenger,clemensg/passenger,clemensg/passenger,phusion/passenger,antek-drzewiecki/passenger,antek-drzewiecki/passenger,clemensg/passenger,kewaunited/passenger,phusion/passenger,cgvarela/passenger,cgvarela/passenger,phusion/passenger,kewaunited/passenger,phusion/passenger,clemensg/passenger,kewaunited/passenger,cgvarela/passenger,clemensg/passenger,phusion/passenger,cgvarela/passenger,cgvarela/passenger,clemensg/passenger,kewaunited/passenger,antek-drzewiecki/passenger,antek-drzewiecki/passenger,cgvarela/passenger,antek-drzewiecki/passenger,antek-drzewiecki/passenger
5d478e839937f70ed509efc63032b6247155eb7c
src/mem/cache/mshr.cc
src/mem/cache/mshr.cc
/* * Copyright (c) 2012 ARM Limited * All rights reserved. * * The license below extends only to copyright in the software and shall * not be construed as granting a license to any other intellectual * property including but not limited to intellectual property relating * to a hardware implementation of the functionality of the software * licensed hereunder. You may use the software subject to the license * terms below provided that you ensure that this notice is replicated * unmodified and in its entirety in all distributions of the software, * modified or unmodified, in source code or in binary form. * * Copyright (c) 2002-2005 The Regents of The University of Michigan * Copyright (c) 2010 Advanced Micro Devices, 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 copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Authors: Erik Hallnor * Dave Greene */ /** * @file * Miss Status and Handling Register (MSHR) definitions. */ #include <algorithm> #include <cassert> #include <string> #include <vector> #include "base/misc.hh" #include "base/types.hh" #include "debug/Cache.hh" #include "mem/cache/cache.hh" #include "mem/cache/mshr.hh" #include "sim/core.hh" using namespace std; MSHR::MSHR() { inService = false; ntargets = 0; threadNum = InvalidThreadID; targets = new TargetList(); deferredTargets = new TargetList(); } MSHR::TargetList::TargetList() : needsExclusive(false), hasUpgrade(false) {} inline void MSHR::TargetList::add(PacketPtr pkt, Tick readyTime, Counter order, Target::Source source, bool markPending) { if (source != Target::FromSnoop) { if (pkt->needsExclusive()) { needsExclusive = true; } // StoreCondReq is effectively an upgrade if it's in an MSHR // since it would have been failed already if we didn't have a // read-only copy if (pkt->isUpgrade() || pkt->cmd == MemCmd::StoreCondReq) { hasUpgrade = true; } } if (markPending) { // Iterate over the SenderState stack and see if we find // an MSHR entry. If we do, set the downstreamPending // flag. Otherwise, do nothing. MSHR *mshr = pkt->findNextSenderState<MSHR>(); if (mshr != NULL) { assert(!mshr->downstreamPending); mshr->downstreamPending = true; } } push_back(Target(pkt, readyTime, order, source, markPending)); } static void replaceUpgrade(PacketPtr pkt) { if (pkt->cmd == MemCmd::UpgradeReq) { pkt->cmd = MemCmd::ReadExReq; DPRINTF(Cache, "Replacing UpgradeReq with ReadExReq\n"); } else if (pkt->cmd == MemCmd::SCUpgradeReq) { pkt->cmd = MemCmd::SCUpgradeFailReq; DPRINTF(Cache, "Replacing SCUpgradeReq with SCUpgradeFailReq\n"); } else if (pkt->cmd == MemCmd::StoreCondReq) { pkt->cmd = MemCmd::StoreCondFailReq; DPRINTF(Cache, "Replacing StoreCondReq with StoreCondFailReq\n"); } } void MSHR::TargetList::replaceUpgrades() { if (!hasUpgrade) return; Iterator end_i = end(); for (Iterator i = begin(); i != end_i; ++i) { replaceUpgrade(i->pkt); } hasUpgrade = false; } void MSHR::TargetList::clearDownstreamPending() { Iterator end_i = end(); for (Iterator i = begin(); i != end_i; ++i) { if (i->markedPending) { // Iterate over the SenderState stack and see if we find // an MSHR entry. If we find one, clear the // downstreamPending flag by calling // clearDownstreamPending(). This recursively clears the // downstreamPending flag in all caches this packet has // passed through. MSHR *mshr = i->pkt->findNextSenderState<MSHR>(); if (mshr != NULL) { mshr->clearDownstreamPending(); } } } } bool MSHR::TargetList::checkFunctional(PacketPtr pkt) { Iterator end_i = end(); for (Iterator i = begin(); i != end_i; ++i) { if (pkt->checkFunctional(i->pkt)) { return true; } } return false; } void MSHR::TargetList:: print(std::ostream &os, int verbosity, const std::string &prefix) const { ConstIterator end_i = end(); for (ConstIterator i = begin(); i != end_i; ++i) { const char *s; switch (i->source) { case Target::FromCPU: s = "FromCPU"; break; case Target::FromSnoop: s = "FromSnoop"; break; case Target::FromPrefetcher: s = "FromPrefetcher"; break; default: s = ""; break; } ccprintf(os, "%s%s: ", prefix, s); i->pkt->print(os, verbosity, ""); } } void MSHR::allocate(Addr _addr, int _size, PacketPtr target, Tick whenReady, Counter _order) { addr = _addr; size = _size; readyTime = whenReady; order = _order; assert(target); isForward = false; _isUncacheable = target->req->isUncacheable(); inService = false; downstreamPending = false; threadNum = 0; ntargets = 1; assert(targets->isReset()); // Don't know of a case where we would allocate a new MSHR for a // snoop (mem-side request), so set source according to request here Target::Source source = (target->cmd == MemCmd::HardPFReq) ? Target::FromPrefetcher : Target::FromCPU; targets->add(target, whenReady, _order, source, true); assert(deferredTargets->isReset()); data = NULL; } void MSHR::clearDownstreamPending() { assert(downstreamPending); downstreamPending = false; // recursively clear flag on any MSHRs we will be forwarding // responses to targets->clearDownstreamPending(); } bool MSHR::markInService(PacketPtr pkt) { assert(!inService); if (isForwardNoResponse()) { // we just forwarded the request packet & don't expect a // response, so get rid of it assert(getNumTargets() == 1); popTarget(); return true; } inService = true; pendingDirty = (targets->needsExclusive || (!pkt->sharedAsserted() && pkt->memInhibitAsserted())); postInvalidate = postDowngrade = false; if (!downstreamPending) { // let upstream caches know that the request has made it to a // level where it's going to get a response targets->clearDownstreamPending(); } return false; } void MSHR::deallocate() { assert(targets->empty()); targets->resetFlags(); assert(deferredTargets->isReset()); assert(ntargets == 0); inService = false; } /* * Adds a target to an MSHR */ void MSHR::allocateTarget(PacketPtr pkt, Tick whenReady, Counter _order) { // if there's a request already in service for this MSHR, we will // have to defer the new target until after the response if any of // the following are true: // - there are other targets already deferred // - there's a pending invalidate to be applied after the response // comes back (but before this target is processed) // - this target requires an exclusive block and either we're not // getting an exclusive block back or we have already snooped // another read request that will downgrade our exclusive block // to shared // assume we'd never issue a prefetch when we've got an // outstanding miss assert(pkt->cmd != MemCmd::HardPFReq); if (inService && (!deferredTargets->empty() || hasPostInvalidate() || (pkt->needsExclusive() && (!isPendingDirty() || hasPostDowngrade() || isForward)))) { // need to put on deferred list if (hasPostInvalidate()) replaceUpgrade(pkt); deferredTargets->add(pkt, whenReady, _order, Target::FromCPU, true); } else { // No request outstanding, or still OK to append to // outstanding request: append to regular target list. Only // mark pending if current request hasn't been issued yet // (isn't in service). targets->add(pkt, whenReady, _order, Target::FromCPU, !inService); } ++ntargets; } bool MSHR::handleSnoop(PacketPtr pkt, Counter _order) { DPRINTF(Cache, "%s for %s address %x size %d\n", __func__, pkt->cmdString(), pkt->getAddr(), pkt->getSize()); if (!inService || (pkt->isExpressSnoop() && downstreamPending)) { // Request has not been issued yet, or it's been issued // locally but is buffered unissued at some downstream cache // which is forwarding us this snoop. Either way, the packet // we're snooping logically precedes this MSHR's request, so // the snoop has no impact on the MSHR, but must be processed // in the standard way by the cache. The only exception is // that if we're an L2+ cache buffering an UpgradeReq from a // higher-level cache, and the snoop is invalidating, then our // buffered upgrades must be converted to read exclusives, // since the upper-level cache no longer has a valid copy. // That is, even though the upper-level cache got out on its // local bus first, some other invalidating transaction // reached the global bus before the upgrade did. if (pkt->needsExclusive()) { targets->replaceUpgrades(); deferredTargets->replaceUpgrades(); } return false; } // From here on down, the request issued by this MSHR logically // precedes the request we're snooping. if (pkt->needsExclusive()) { // snooped request still precedes the re-request we'll have to // issue for deferred targets, if any... deferredTargets->replaceUpgrades(); } if (hasPostInvalidate()) { // a prior snoop has already appended an invalidation, so // logically we don't have the block anymore; no need for // further snooping. return true; } if (isPendingDirty() || pkt->isInvalidate()) { // We need to save and replay the packet in two cases: // 1. We're awaiting an exclusive copy, so ownership is pending, // and we need to respond after we receive data. // 2. It's an invalidation (e.g., UpgradeReq), and we need // to forward the snoop up the hierarchy after the current // transaction completes. // Actual target device (typ. a memory) will delete the // packet on reception, so we need to save a copy here. PacketPtr cp_pkt = new Packet(pkt, true); targets->add(cp_pkt, curTick(), _order, Target::FromSnoop, downstreamPending && targets->needsExclusive); ++ntargets; if (isPendingDirty()) { pkt->assertMemInhibit(); pkt->setSupplyExclusive(); } if (pkt->needsExclusive()) { // This transaction will take away our pending copy postInvalidate = true; } } if (!pkt->needsExclusive()) { // This transaction will get a read-shared copy, downgrading // our copy if we had an exclusive one postDowngrade = true; pkt->assertShared(); } return true; } bool MSHR::promoteDeferredTargets() { assert(targets->empty()); if (deferredTargets->empty()) { return false; } // swap targets & deferredTargets lists TargetList *tmp = targets; targets = deferredTargets; deferredTargets = tmp; assert(targets->size() == ntargets); // clear deferredTargets flags deferredTargets->resetFlags(); order = targets->front().order; readyTime = std::max(curTick(), targets->front().readyTime); return true; } void MSHR::handleFill(Packet *pkt, CacheBlk *blk) { if (!pkt->sharedAsserted() && !(hasPostInvalidate() || hasPostDowngrade()) && deferredTargets->needsExclusive) { // We got an exclusive response, but we have deferred targets // which are waiting to request an exclusive copy (not because // of a pending invalidate). This can happen if the original // request was for a read-only (non-exclusive) block, but we // got an exclusive copy anyway because of the E part of the // MOESI/MESI protocol. Since we got the exclusive copy // there's no need to defer the targets, so move them up to // the regular target list. assert(!targets->needsExclusive); targets->needsExclusive = true; // if any of the deferred targets were upper-level cache // requests marked downstreamPending, need to clear that assert(!downstreamPending); // not pending here anymore deferredTargets->clearDownstreamPending(); // this clears out deferredTargets too targets->splice(targets->end(), *deferredTargets); deferredTargets->resetFlags(); } } bool MSHR::checkFunctional(PacketPtr pkt) { // For printing, we treat the MSHR as a whole as single entity. // For other requests, we iterate over the individual targets // since that's where the actual data lies. if (pkt->isPrint()) { pkt->checkFunctional(this, addr, size, NULL); return false; } else { return (targets->checkFunctional(pkt) || deferredTargets->checkFunctional(pkt)); } } void MSHR::print(std::ostream &os, int verbosity, const std::string &prefix) const { ccprintf(os, "%s[%x:%x] %s %s %s state: %s %s %s %s\n", prefix, addr, addr+size-1, isForward ? "Forward" : "", isForwardNoResponse() ? "ForwNoResp" : "", needsExclusive() ? "Excl" : "", _isUncacheable ? "Unc" : "", inService ? "InSvc" : "", downstreamPending ? "DwnPend" : "", hasPostInvalidate() ? "PostInv" : "", hasPostDowngrade() ? "PostDowngr" : ""); ccprintf(os, "%s Targets:\n", prefix); targets->print(os, verbosity, prefix + " "); if (!deferredTargets->empty()) { ccprintf(os, "%s Deferred Targets:\n", prefix); deferredTargets->print(os, verbosity, prefix + " "); } } std::string MSHR::print() const { ostringstream str; print(str); return str.str(); } MSHR::~MSHR() { delete[] targets; delete[] deferredTargets; }
/* * Copyright (c) 2012 ARM Limited * All rights reserved. * * The license below extends only to copyright in the software and shall * not be construed as granting a license to any other intellectual * property including but not limited to intellectual property relating * to a hardware implementation of the functionality of the software * licensed hereunder. You may use the software subject to the license * terms below provided that you ensure that this notice is replicated * unmodified and in its entirety in all distributions of the software, * modified or unmodified, in source code or in binary form. * * Copyright (c) 2002-2005 The Regents of The University of Michigan * Copyright (c) 2010 Advanced Micro Devices, 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 copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Authors: Erik Hallnor * Dave Greene */ /** * @file * Miss Status and Handling Register (MSHR) definitions. */ #include <algorithm> #include <cassert> #include <string> #include <vector> #include "base/misc.hh" #include "base/types.hh" #include "debug/Cache.hh" #include "mem/cache/cache.hh" #include "mem/cache/mshr.hh" #include "sim/core.hh" using namespace std; MSHR::MSHR() { inService = false; ntargets = 0; threadNum = InvalidThreadID; targets = new TargetList(); deferredTargets = new TargetList(); } MSHR::TargetList::TargetList() : needsExclusive(false), hasUpgrade(false) {} inline void MSHR::TargetList::add(PacketPtr pkt, Tick readyTime, Counter order, Target::Source source, bool markPending) { if (source != Target::FromSnoop) { if (pkt->needsExclusive()) { needsExclusive = true; } // StoreCondReq is effectively an upgrade if it's in an MSHR // since it would have been failed already if we didn't have a // read-only copy if (pkt->isUpgrade() || pkt->cmd == MemCmd::StoreCondReq) { hasUpgrade = true; } } if (markPending) { // Iterate over the SenderState stack and see if we find // an MSHR entry. If we do, set the downstreamPending // flag. Otherwise, do nothing. MSHR *mshr = pkt->findNextSenderState<MSHR>(); if (mshr != NULL) { assert(!mshr->downstreamPending); mshr->downstreamPending = true; } } push_back(Target(pkt, readyTime, order, source, markPending)); } static void replaceUpgrade(PacketPtr pkt) { if (pkt->cmd == MemCmd::UpgradeReq) { pkt->cmd = MemCmd::ReadExReq; DPRINTF(Cache, "Replacing UpgradeReq with ReadExReq\n"); } else if (pkt->cmd == MemCmd::SCUpgradeReq) { pkt->cmd = MemCmd::SCUpgradeFailReq; DPRINTF(Cache, "Replacing SCUpgradeReq with SCUpgradeFailReq\n"); } else if (pkt->cmd == MemCmd::StoreCondReq) { pkt->cmd = MemCmd::StoreCondFailReq; DPRINTF(Cache, "Replacing StoreCondReq with StoreCondFailReq\n"); } } void MSHR::TargetList::replaceUpgrades() { if (!hasUpgrade) return; Iterator end_i = end(); for (Iterator i = begin(); i != end_i; ++i) { replaceUpgrade(i->pkt); } hasUpgrade = false; } void MSHR::TargetList::clearDownstreamPending() { Iterator end_i = end(); for (Iterator i = begin(); i != end_i; ++i) { if (i->markedPending) { // Iterate over the SenderState stack and see if we find // an MSHR entry. If we find one, clear the // downstreamPending flag by calling // clearDownstreamPending(). This recursively clears the // downstreamPending flag in all caches this packet has // passed through. MSHR *mshr = i->pkt->findNextSenderState<MSHR>(); if (mshr != NULL) { mshr->clearDownstreamPending(); } } } } bool MSHR::TargetList::checkFunctional(PacketPtr pkt) { Iterator end_i = end(); for (Iterator i = begin(); i != end_i; ++i) { if (pkt->checkFunctional(i->pkt)) { return true; } } return false; } void MSHR::TargetList:: print(std::ostream &os, int verbosity, const std::string &prefix) const { ConstIterator end_i = end(); for (ConstIterator i = begin(); i != end_i; ++i) { const char *s; switch (i->source) { case Target::FromCPU: s = "FromCPU"; break; case Target::FromSnoop: s = "FromSnoop"; break; case Target::FromPrefetcher: s = "FromPrefetcher"; break; default: s = ""; break; } ccprintf(os, "%s%s: ", prefix, s); i->pkt->print(os, verbosity, ""); } } void MSHR::allocate(Addr _addr, int _size, PacketPtr target, Tick whenReady, Counter _order) { addr = _addr; size = _size; readyTime = whenReady; order = _order; assert(target); isForward = false; _isUncacheable = target->req->isUncacheable(); inService = false; downstreamPending = false; threadNum = 0; ntargets = 1; assert(targets->isReset()); // Don't know of a case where we would allocate a new MSHR for a // snoop (mem-side request), so set source according to request here Target::Source source = (target->cmd == MemCmd::HardPFReq) ? Target::FromPrefetcher : Target::FromCPU; targets->add(target, whenReady, _order, source, true); assert(deferredTargets->isReset()); data = NULL; } void MSHR::clearDownstreamPending() { assert(downstreamPending); downstreamPending = false; // recursively clear flag on any MSHRs we will be forwarding // responses to targets->clearDownstreamPending(); } bool MSHR::markInService(PacketPtr pkt) { assert(!inService); if (isForwardNoResponse()) { // we just forwarded the request packet & don't expect a // response, so get rid of it assert(getNumTargets() == 1); popTarget(); return true; } inService = true; pendingDirty = (targets->needsExclusive || (!pkt->sharedAsserted() && pkt->memInhibitAsserted())); postInvalidate = postDowngrade = false; if (!downstreamPending) { // let upstream caches know that the request has made it to a // level where it's going to get a response targets->clearDownstreamPending(); } return false; } void MSHR::deallocate() { assert(targets->empty()); targets->resetFlags(); assert(deferredTargets->isReset()); assert(ntargets == 0); inService = false; } /* * Adds a target to an MSHR */ void MSHR::allocateTarget(PacketPtr pkt, Tick whenReady, Counter _order) { // if there's a request already in service for this MSHR, we will // have to defer the new target until after the response if any of // the following are true: // - there are other targets already deferred // - there's a pending invalidate to be applied after the response // comes back (but before this target is processed) // - this target requires an exclusive block and either we're not // getting an exclusive block back or we have already snooped // another read request that will downgrade our exclusive block // to shared // assume we'd never issue a prefetch when we've got an // outstanding miss assert(pkt->cmd != MemCmd::HardPFReq); if (inService && (!deferredTargets->empty() || hasPostInvalidate() || (pkt->needsExclusive() && (!isPendingDirty() || hasPostDowngrade() || isForward)))) { // need to put on deferred list if (hasPostInvalidate()) replaceUpgrade(pkt); deferredTargets->add(pkt, whenReady, _order, Target::FromCPU, true); } else { // No request outstanding, or still OK to append to // outstanding request: append to regular target list. Only // mark pending if current request hasn't been issued yet // (isn't in service). targets->add(pkt, whenReady, _order, Target::FromCPU, !inService); } ++ntargets; } bool MSHR::handleSnoop(PacketPtr pkt, Counter _order) { DPRINTF(Cache, "%s for %s address %x size %d\n", __func__, pkt->cmdString(), pkt->getAddr(), pkt->getSize()); if (!inService || (pkt->isExpressSnoop() && downstreamPending)) { // Request has not been issued yet, or it's been issued // locally but is buffered unissued at some downstream cache // which is forwarding us this snoop. Either way, the packet // we're snooping logically precedes this MSHR's request, so // the snoop has no impact on the MSHR, but must be processed // in the standard way by the cache. The only exception is // that if we're an L2+ cache buffering an UpgradeReq from a // higher-level cache, and the snoop is invalidating, then our // buffered upgrades must be converted to read exclusives, // since the upper-level cache no longer has a valid copy. // That is, even though the upper-level cache got out on its // local bus first, some other invalidating transaction // reached the global bus before the upgrade did. if (pkt->needsExclusive()) { targets->replaceUpgrades(); deferredTargets->replaceUpgrades(); } return false; } // From here on down, the request issued by this MSHR logically // precedes the request we're snooping. if (pkt->needsExclusive()) { // snooped request still precedes the re-request we'll have to // issue for deferred targets, if any... deferredTargets->replaceUpgrades(); } if (hasPostInvalidate()) { // a prior snoop has already appended an invalidation, so // logically we don't have the block anymore; no need for // further snooping. return true; } if (isPendingDirty() || pkt->isInvalidate()) { // We need to save and replay the packet in two cases: // 1. We're awaiting an exclusive copy, so ownership is pending, // and we need to respond after we receive data. // 2. It's an invalidation (e.g., UpgradeReq), and we need // to forward the snoop up the hierarchy after the current // transaction completes. // Actual target device (typ. a memory) will delete the // packet on reception, so we need to save a copy here. PacketPtr cp_pkt = new Packet(pkt, true); targets->add(cp_pkt, curTick(), _order, Target::FromSnoop, downstreamPending && targets->needsExclusive); ++ntargets; if (isPendingDirty()) { pkt->assertMemInhibit(); pkt->setSupplyExclusive(); } if (pkt->needsExclusive()) { // This transaction will take away our pending copy postInvalidate = true; } } if (!pkt->needsExclusive()) { // This transaction will get a read-shared copy, downgrading // our copy if we had an exclusive one postDowngrade = true; pkt->assertShared(); } return true; } bool MSHR::promoteDeferredTargets() { assert(targets->empty()); if (deferredTargets->empty()) { return false; } // swap targets & deferredTargets lists TargetList *tmp = targets; targets = deferredTargets; deferredTargets = tmp; assert(targets->size() == ntargets); // clear deferredTargets flags deferredTargets->resetFlags(); order = targets->front().order; readyTime = std::max(curTick(), targets->front().readyTime); return true; } void MSHR::handleFill(Packet *pkt, CacheBlk *blk) { if (!pkt->sharedAsserted() && !(hasPostInvalidate() || hasPostDowngrade()) && deferredTargets->needsExclusive) { // We got an exclusive response, but we have deferred targets // which are waiting to request an exclusive copy (not because // of a pending invalidate). This can happen if the original // request was for a read-only (non-exclusive) block, but we // got an exclusive copy anyway because of the E part of the // MOESI/MESI protocol. Since we got the exclusive copy // there's no need to defer the targets, so move them up to // the regular target list. assert(!targets->needsExclusive); targets->needsExclusive = true; // if any of the deferred targets were upper-level cache // requests marked downstreamPending, need to clear that assert(!downstreamPending); // not pending here anymore deferredTargets->clearDownstreamPending(); // this clears out deferredTargets too targets->splice(targets->end(), *deferredTargets); deferredTargets->resetFlags(); } } bool MSHR::checkFunctional(PacketPtr pkt) { // For printing, we treat the MSHR as a whole as single entity. // For other requests, we iterate over the individual targets // since that's where the actual data lies. if (pkt->isPrint()) { pkt->checkFunctional(this, addr, size, NULL); return false; } else { return (targets->checkFunctional(pkt) || deferredTargets->checkFunctional(pkt)); } } void MSHR::print(std::ostream &os, int verbosity, const std::string &prefix) const { ccprintf(os, "%s[%x:%x] %s %s %s state: %s %s %s %s %s\n", prefix, addr, addr+size-1, isForward ? "Forward" : "", isForwardNoResponse() ? "ForwNoResp" : "", needsExclusive() ? "Excl" : "", _isUncacheable ? "Unc" : "", inService ? "InSvc" : "", downstreamPending ? "DwnPend" : "", hasPostInvalidate() ? "PostInv" : "", hasPostDowngrade() ? "PostDowngr" : ""); ccprintf(os, "%s Targets:\n", prefix); targets->print(os, verbosity, prefix + " "); if (!deferredTargets->empty()) { ccprintf(os, "%s Deferred Targets:\n", prefix); deferredTargets->print(os, verbosity, prefix + " "); } } std::string MSHR::print() const { ostringstream str; print(str); return str.str(); } MSHR::~MSHR() { delete[] targets; delete[] deferredTargets; }
Fix MSHR print format
mem: Fix MSHR print format This patch fixes an incorrect print format string by adding an additional string element.
C++
bsd-3-clause
andrewfu0325/gem5-aladdin,andrewfu0325/gem5-aladdin,andrewfu0325/gem5-aladdin,andrewfu0325/gem5-aladdin,andrewfu0325/gem5-aladdin,andrewfu0325/gem5-aladdin,andrewfu0325/gem5-aladdin
b9477255059de5ab9c804672d694ae4636533b14
cegui/src/CEGUIRenderedStringTextComponent.cpp
cegui/src/CEGUIRenderedStringTextComponent.cpp
/*********************************************************************** filename: CEGUIRenderedStringTextComponent.cpp created: 25/05/2009 author: Paul Turner *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2009 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 "CEGUIRenderedStringTextComponent.h" #include "CEGUIFontManager.h" #include "CEGUIFont.h" #include "CEGUISystem.h" #include "CEGUIExceptions.h" #include "CEGUITextUtils.h" // Start of CEGUI namespace section namespace CEGUI { //----------------------------------------------------------------------------// RenderedStringTextComponent::RenderedStringTextComponent() : d_font(0), d_colours(0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF) { } //----------------------------------------------------------------------------// RenderedStringTextComponent::RenderedStringTextComponent(const String& text) : d_text(text), d_font(0), d_colours(0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF) { } //----------------------------------------------------------------------------// RenderedStringTextComponent::RenderedStringTextComponent( const String& text, const String& font_name) : d_text(text), d_font(font_name.empty() ? 0 : FontManager::getSingleton().getFont(font_name)), d_colours(0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF) { } //----------------------------------------------------------------------------// RenderedStringTextComponent::RenderedStringTextComponent(const String& text, Font* font) : d_text(text), d_font(font), d_colours(0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF) { } //----------------------------------------------------------------------------// void RenderedStringTextComponent::setText(const String& text) { d_text = text; } //----------------------------------------------------------------------------// const String& RenderedStringTextComponent::getText() const { return d_text; } //----------------------------------------------------------------------------// void RenderedStringTextComponent::setFont(Font* font) { d_font = font; } //----------------------------------------------------------------------------// void RenderedStringTextComponent::setFont(const String& font_name) { d_font = font_name.empty() ? 0 : FontManager::getSingleton().getFont(font_name); } //----------------------------------------------------------------------------// Font* RenderedStringTextComponent::getFont() const { return d_font; } //----------------------------------------------------------------------------// void RenderedStringTextComponent::setColours(const ColourRect& cr) { d_colours = cr; } //----------------------------------------------------------------------------// void RenderedStringTextComponent::setColours(const colour& c) { d_colours.setColours(c); } //----------------------------------------------------------------------------// const ColourRect& RenderedStringTextComponent::getColours() const { return d_colours; } //----------------------------------------------------------------------------// void RenderedStringTextComponent::draw(GeometryBuffer& buffer, const Vector2& position, const ColourRect* mod_colours, const Rect* clip_rect, const float vertical_space, const float space_extra) const { Font* fnt = d_font ? d_font : System::getSingleton().getDefaultFont(); if (!fnt) return; Vector2 final_pos(position); float y_scale = 1.0f; // handle formatting options switch (d_verticalFormatting) { case VF_BOTTOM_ALIGNED: final_pos.d_y += vertical_space - getPixelSize().d_height; break; case VF_CENTRE_ALIGNED: final_pos.d_y += (vertical_space - getPixelSize().d_height) / 2 ; break; case VF_STRETCHED: y_scale = vertical_space / getPixelSize().d_height; break; case VF_TOP_ALIGNED: // nothing additional to do for this formatting option. break; default: throw InvalidRequestException("RenderedStringTextComponent::draw: " "unknown VerticalFormatting option specified."); } // apply padding to position: final_pos += d_padding.getPosition(); // apply modulative colours if needed. ColourRect final_cols(d_colours); if (mod_colours) final_cols *= *mod_colours; // draw the text string. fnt->drawText(buffer, d_text, final_pos, clip_rect, final_cols, 1.0f, y_scale, space_extra); } //----------------------------------------------------------------------------// Size RenderedStringTextComponent::getPixelSize() const { Font* fnt = d_font ? d_font : System::getSingleton().getDefaultFont(); Size psz(d_padding.d_left + d_padding.d_right, d_padding.d_top + d_padding.d_bottom); if (fnt) { psz.d_width += fnt->getTextExtent(d_text); psz.d_height += fnt->getFontHeight(); } return psz; } //----------------------------------------------------------------------------// bool RenderedStringTextComponent::canSplit() const { return true; } //----------------------------------------------------------------------------// RenderedStringTextComponent* RenderedStringTextComponent::split( float split_point, bool first_component) { Font* fnt = d_font ? d_font : System::getSingleton().getDefaultFont(); // This is checked, but should never fail, since if we had no font our // extent would be 0 and we would never cause a split to be needed here. if (!fnt) throw InvalidRequestException("RenderedStringTextComponent::split: " "unable to split with no font set."); // create 'left' side of split and clone our basic configuration RenderedStringTextComponent* lhs = new RenderedStringTextComponent; lhs->d_padding = d_padding; lhs->d_verticalFormatting = d_verticalFormatting; lhs->d_font = d_font; lhs->d_colours = d_colours; // calculate the 'best' place to split the text size_t left_len = 0; float left_extent = 0.0f; while (left_len < d_text.length()) { size_t token_len = getNextTokenLength(d_text, left_len); float token_extent = fnt->getTextExtent(d_text.substr(left_len, token_len)); // does the next token extend past the split point? if (left_extent + token_extent > split_point) { // if it was the first token, split the token itself if (first_component && left_len == 0) left_len = fnt->getCharAtPixel(d_text.substr(0, token_len), split_point); // left_len is now the character index at which to split the line break; } // add this token to the left side left_len += token_len; left_extent += token_extent; } // perform the split. lhs->d_text = d_text.substr(0, left_len); d_text = d_text.substr(left_len); return lhs; } //----------------------------------------------------------------------------// size_t RenderedStringTextComponent::getNextTokenLength(const String& text, size_t start_idx) { // TODO: This was copied from MultiLineEditbox. It can probably be bumped // TODO: into TextUtils since it accesses no instance data. String::size_type pos = text.find_first_of(TextUtils::DefaultWrapDelimiters, start_idx); // handle case where no more whitespace exists (so this is last token) if (pos == String::npos) return (text.length() - start_idx); // handle 'delimiter' token cases else if ((pos - start_idx) == 0) return 1; else return (pos - start_idx); } //----------------------------------------------------------------------------// RenderedStringTextComponent* RenderedStringTextComponent::clone() const { RenderedStringTextComponent* c = new RenderedStringTextComponent(*this); return c; } //----------------------------------------------------------------------------// size_t RenderedStringTextComponent::getSpaceCount() const { // TODO: The value calculated here is a good candidate for caching. size_t space_count = 0; // Count the number of spaces in this component. // NB: here I'm not countng tabs since those are really intended to be // something other than just a bigger space. const size_t char_count = d_text.length(); for (size_t c = 0; c < char_count; ++c) if (d_text[c] == ' ') // TODO: There are other space characters! ++space_count; return space_count; } //----------------------------------------------------------------------------// } // End of CEGUI namespace section
/*********************************************************************** filename: CEGUIRenderedStringTextComponent.cpp created: 25/05/2009 author: Paul Turner *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2009 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 "CEGUIRenderedStringTextComponent.h" #include "CEGUIFontManager.h" #include "CEGUIFont.h" #include "CEGUISystem.h" #include "CEGUIExceptions.h" #include "CEGUITextUtils.h" // Start of CEGUI namespace section namespace CEGUI { //----------------------------------------------------------------------------// RenderedStringTextComponent::RenderedStringTextComponent() : d_font(0), d_colours(0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF) { } //----------------------------------------------------------------------------// RenderedStringTextComponent::RenderedStringTextComponent(const String& text) : d_text(text), d_font(0), d_colours(0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF) { } //----------------------------------------------------------------------------// RenderedStringTextComponent::RenderedStringTextComponent( const String& text, const String& font_name) : d_text(text), d_font(font_name.empty() ? 0 : FontManager::getSingleton().getFont(font_name)), d_colours(0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF) { } //----------------------------------------------------------------------------// RenderedStringTextComponent::RenderedStringTextComponent(const String& text, Font* font) : d_text(text), d_font(font), d_colours(0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF) { } //----------------------------------------------------------------------------// void RenderedStringTextComponent::setText(const String& text) { d_text = text; } //----------------------------------------------------------------------------// const String& RenderedStringTextComponent::getText() const { return d_text; } //----------------------------------------------------------------------------// void RenderedStringTextComponent::setFont(Font* font) { d_font = font; } //----------------------------------------------------------------------------// void RenderedStringTextComponent::setFont(const String& font_name) { d_font = font_name.empty() ? 0 : FontManager::getSingleton().getFont(font_name); } //----------------------------------------------------------------------------// Font* RenderedStringTextComponent::getFont() const { return d_font; } //----------------------------------------------------------------------------// void RenderedStringTextComponent::setColours(const ColourRect& cr) { d_colours = cr; } //----------------------------------------------------------------------------// void RenderedStringTextComponent::setColours(const colour& c) { d_colours.setColours(c); } //----------------------------------------------------------------------------// const ColourRect& RenderedStringTextComponent::getColours() const { return d_colours; } //----------------------------------------------------------------------------// void RenderedStringTextComponent::draw(GeometryBuffer& buffer, const Vector2& position, const ColourRect* mod_colours, const Rect* clip_rect, const float vertical_space, const float space_extra) const { Font* fnt = d_font ? d_font : System::getSingleton().getDefaultFont(); if (!fnt) return; Vector2 final_pos(position); float y_scale = 1.0f; // handle formatting options switch (d_verticalFormatting) { case VF_BOTTOM_ALIGNED: final_pos.d_y += vertical_space - getPixelSize().d_height; break; case VF_CENTRE_ALIGNED: final_pos.d_y += (vertical_space - getPixelSize().d_height) / 2 ; break; case VF_STRETCHED: y_scale = vertical_space / getPixelSize().d_height; break; case VF_TOP_ALIGNED: // nothing additional to do for this formatting option. break; default: throw InvalidRequestException("RenderedStringTextComponent::draw: " "unknown VerticalFormatting option specified."); } // apply padding to position: final_pos += d_padding.getPosition(); // apply modulative colours if needed. ColourRect final_cols(d_colours); if (mod_colours) final_cols *= *mod_colours; // draw the text string. fnt->drawText(buffer, d_text, final_pos, clip_rect, final_cols, 1.0f, y_scale, space_extra); } //----------------------------------------------------------------------------// Size RenderedStringTextComponent::getPixelSize() const { Font* fnt = d_font ? d_font : System::getSingleton().getDefaultFont(); Size psz(d_padding.d_left + d_padding.d_right, d_padding.d_top + d_padding.d_bottom); if (fnt) { psz.d_width += fnt->getTextExtent(d_text); psz.d_height += fnt->getFontHeight(); } return psz; } //----------------------------------------------------------------------------// bool RenderedStringTextComponent::canSplit() const { return true; } //----------------------------------------------------------------------------// RenderedStringTextComponent* RenderedStringTextComponent::split( float split_point, bool first_component) { Font* fnt = d_font ? d_font : System::getSingleton().getDefaultFont(); // This is checked, but should never fail, since if we had no font our // extent would be 0 and we would never cause a split to be needed here. if (!fnt) throw InvalidRequestException("RenderedStringTextComponent::split: " "unable to split with no font set."); // create 'left' side of split and clone our basic configuration RenderedStringTextComponent* lhs = new RenderedStringTextComponent; lhs->d_padding = d_padding; lhs->d_verticalFormatting = d_verticalFormatting; lhs->d_font = d_font; lhs->d_colours = d_colours; // calculate the 'best' place to split the text size_t left_len = 0; float left_extent = 0.0f; while (left_len < d_text.length()) { size_t token_len = getNextTokenLength(d_text, left_len); // exit loop if no more valid tokens. if (token_len == 0) break; const float token_extent = fnt->getTextExtent(d_text.substr(left_len, token_len)); // does the next token extend past the split point? if (left_extent + token_extent > split_point) { // if it was the first token, split the token itself if (first_component && left_len == 0) left_len = fnt->getCharAtPixel(d_text.substr(0, token_len), split_point); // left_len is now the character index at which to split the line break; } // add this token to the left side left_len += token_len; left_extent += token_extent; } // perform the split. lhs->d_text = d_text.substr(0, left_len); // here we're trimming leading delimiters from the substring range size_t rhs_start = d_text.find_first_not_of(TextUtils::DefaultWrapDelimiters, left_len); if (rhs_start == String::npos) rhs_start = left_len; d_text = d_text.substr(rhs_start); return lhs; } //----------------------------------------------------------------------------// size_t RenderedStringTextComponent::getNextTokenLength(const String& text, size_t start_idx) { String::size_type word_start = text.find_first_not_of(TextUtils::DefaultWrapDelimiters, start_idx); if (word_start == String::npos) word_start = start_idx; String::size_type word_end = text.find_first_of(TextUtils::DefaultWrapDelimiters, word_start); if (word_end == String::npos) word_end = text.length(); return word_end - start_idx; } //----------------------------------------------------------------------------// RenderedStringTextComponent* RenderedStringTextComponent::clone() const { RenderedStringTextComponent* c = new RenderedStringTextComponent(*this); return c; } //----------------------------------------------------------------------------// size_t RenderedStringTextComponent::getSpaceCount() const { // TODO: The value calculated here is a good candidate for caching. size_t space_count = 0; // Count the number of spaces in this component. // NB: here I'm not countng tabs since those are really intended to be // something other than just a bigger space. const size_t char_count = d_text.length(); for (size_t c = 0; c < char_count; ++c) if (d_text[c] == ' ') // TODO: There are other space characters! ++space_count; return space_count; } //----------------------------------------------------------------------------// } // End of CEGUI namespace section
Fix the split alogorithm used in the text components for RenderedString (for better word-wrapping results).
Fix the split alogorithm used in the text components for RenderedString (for better word-wrapping results).
C++
mit
arkana-fts/cegui,arkana-fts/cegui,arkana-fts/cegui,RealityFactory/CEGUI,RealityFactory/CEGUI,cbeck88/cegui-mirror,cbeck88/cegui-mirror,arkana-fts/cegui,arkana-fts/cegui,RealityFactory/CEGUI,RealityFactory/CEGUI,cbeck88/cegui-mirror,cbeck88/cegui-mirror,cbeck88/cegui-mirror,RealityFactory/CEGUI
5306572979ffe658cadea51eb0a28cbef3664a01
src/mock/iostream.cxx
src/mock/iostream.cxx
/* -*- coding: utf-8; mode: c++; tab-width: 3 -*- Copyright 2011, 2012, 2013 Raffaello D. Di Napoli This file is part of Application-Building Components (henceforth referred to as ABC). ABC 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. ABC 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 ABC. If not, see <http://www.gnu.org/licenses/>. --------------------------------------------------------------------------------------------------*/ #include <abc/mock/iostream.hxx> #include <abc/trace.hxx> //////////////////////////////////////////////////////////////////////////////////////////////////// // abc::mock::istream namespace abc { namespace mock { ostream::ostream() : ::abc::ostream(), m_cchUsed(0) { } /// Returns true if the current contents of the stream match the specified string. // bool ostream::contents_equal(istr const & sExpected) { abc_trace_fn((this, sExpected)); istr sActual(unsafe, m_achBuf, m_cchUsed); return sActual == sExpected; } /// See ostream::write(). // /*virtual*/ void ostream::write_raw( void const * p, size_t cb, text::encoding enc /*= text::encoding::identity*/ ) { abc_trace_fn((this, p, cb, enc)); UNUSED_ARG(enc); memory::copy<void>(m_achBuf + m_cchUsed, p, cb); m_cchUsed += cb / sizeof(m_achBuf[0]); } } //namespace mock } //namespace abc ////////////////////////////////////////////////////////////////////////////////////////////////////
/* -*- coding: utf-8; mode: c++; tab-width: 3 -*- Copyright 2011, 2012, 2013 Raffaello D. Di Napoli This file is part of Application-Building Components (henceforth referred to as ABC). ABC 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. ABC 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 ABC. If not, see <http://www.gnu.org/licenses/>. --------------------------------------------------------------------------------------------------*/ #include <abc/mock/iostream.hxx> #include <abc/trace.hxx> //////////////////////////////////////////////////////////////////////////////////////////////////// // abc::mock::istream namespace abc { namespace mock { ostream::ostream() : ::abc::ostream(), m_cchUsed(0) { } bool ostream::contents_equal(istr const & sExpected) { abc_trace_fn((this, sExpected)); istr sActual(unsafe, m_achBuf, m_cchUsed); return sActual == sExpected; } /*virtual*/ void ostream::write_raw( void const * p, size_t cb, text::encoding enc /*= text::encoding::identity*/ ) { abc_trace_fn((this, p, cb, enc)); UNUSED_ARG(enc); memory::copy<void>(m_achBuf + m_cchUsed, p, cb); m_cchUsed += cb / sizeof(m_achBuf[0]); } } //namespace mock } //namespace abc ////////////////////////////////////////////////////////////////////////////////////////////////////
Remove duplicate comments already in the header file
Remove duplicate comments already in the header file
C++
lgpl-2.1
raffaellod/lofty,raffaellod/lofty
978fddba98c952302f45a05a45040bd3afaa2ff9
lib/dat/cursor-factory.cpp
lib/dat/cursor-factory.cpp
/* -*- c-basic-offset: 2 -*- */ /* Copyright(C) 2011 Brazil 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 */ #include "cursor-factory.hpp" #include "id-cursor.hpp" #include "key-cursor.hpp" #include "prefix-cursor.hpp" #include "predictive-cursor.hpp" #include <new> namespace grn { namespace dat { Cursor *CursorFactory::open(const Trie &trie, const void *min_ptr, UInt32 min_length, const void *max_ptr, UInt32 max_length, UInt32 offset, UInt32 limit, UInt32 flags) { const UInt32 cursor_type = flags & CURSOR_TYPE_MASK; switch (cursor_type) { case ID_RANGE_CURSOR: { IdCursor *cursor = new (std::nothrow) IdCursor; GRN_DAT_THROW_IF(MEMORY_ERROR, cursor == NULL); try { if (&trie != NULL) { cursor->open(trie, String(min_ptr, min_length), String(max_ptr, max_length), offset, limit, flags); } } catch (...) { delete cursor; throw; } return cursor; } case KEY_RANGE_CURSOR: { KeyCursor *cursor = new (std::nothrow) KeyCursor; GRN_DAT_THROW_IF(MEMORY_ERROR, cursor == NULL); try { if (&trie != NULL) { cursor->open(trie, String(min_ptr, min_length), String(max_ptr, max_length), offset, limit, flags); } } catch (...) { delete cursor; throw; } return cursor; } case PREFIX_CURSOR: { PrefixCursor *cursor = new (std::nothrow) PrefixCursor; GRN_DAT_THROW_IF(MEMORY_ERROR, cursor == NULL); try { if (&trie != NULL) { cursor->open(trie, String(max_ptr, max_length), min_length, offset, limit, flags); } } catch (...) { delete cursor; throw; } return cursor; } case PREDICTIVE_CURSOR: { PredictiveCursor *cursor = new (std::nothrow) PredictiveCursor; GRN_DAT_THROW_IF(MEMORY_ERROR, cursor == NULL); try { if (&trie != NULL) { cursor->open(trie, String(min_ptr, min_length), offset, limit, flags); } } catch (...) { delete cursor; throw; } return cursor; } default: { GRN_DAT_THROW(PARAM_ERROR, "unknown cursor type"); } } } } // namespace dat } // namespace grn
/* -*- c-basic-offset: 2 -*- */ /* Copyright(C) 2011 Brazil 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 */ #include "cursor-factory.hpp" #include "id-cursor.hpp" #include "key-cursor.hpp" #include "prefix-cursor.hpp" #include "predictive-cursor.hpp" #include <new> namespace grn { namespace dat { Cursor *CursorFactory::open(const Trie &trie, const void *min_ptr, UInt32 min_length, const void *max_ptr, UInt32 max_length, UInt32 offset, UInt32 limit, UInt32 flags) { GRN_DAT_THROW_IF(PARAM_ERROR, &trie == NULL); const UInt32 cursor_type = flags & CURSOR_TYPE_MASK; switch (cursor_type) { case ID_RANGE_CURSOR: { IdCursor *cursor = new (std::nothrow) IdCursor; GRN_DAT_THROW_IF(MEMORY_ERROR, cursor == NULL); try { cursor->open(trie, String(min_ptr, min_length), String(max_ptr, max_length), offset, limit, flags); } catch (...) { delete cursor; throw; } return cursor; } case KEY_RANGE_CURSOR: { KeyCursor *cursor = new (std::nothrow) KeyCursor; GRN_DAT_THROW_IF(MEMORY_ERROR, cursor == NULL); try { cursor->open(trie, String(min_ptr, min_length), String(max_ptr, max_length), offset, limit, flags); } catch (...) { delete cursor; throw; } return cursor; } case PREFIX_CURSOR: { PrefixCursor *cursor = new (std::nothrow) PrefixCursor; GRN_DAT_THROW_IF(MEMORY_ERROR, cursor == NULL); try { cursor->open(trie, String(max_ptr, max_length), min_length, offset, limit, flags); } catch (...) { delete cursor; throw; } return cursor; } case PREDICTIVE_CURSOR: { PredictiveCursor *cursor = new (std::nothrow) PredictiveCursor; GRN_DAT_THROW_IF(MEMORY_ERROR, cursor == NULL); try { cursor->open(trie, String(min_ptr, min_length), offset, limit, flags); } catch (...) { delete cursor; throw; } return cursor; } default: { GRN_DAT_THROW(PARAM_ERROR, "unknown cursor type"); } } } } // namespace dat } // namespace grn
change to throw an exception if a given reference is invalid.
change to throw an exception if a given reference is invalid.
C++
lgpl-2.1
naoa/groonga,komainu8/groonga,naoa/groonga,cosmo0920/groonga,redfigure/groonga,redfigure/groonga,myokoym/groonga,redfigure/groonga,groonga/groonga,hiroyuki-sato/groonga,hiroyuki-sato/groonga,komainu8/groonga,kenhys/groonga,hiroyuki-sato/groonga,groonga/groonga,redfigure/groonga,cosmo0920/groonga,cosmo0920/groonga,myokoym/groonga,groonga/groonga,kenhys/groonga,myokoym/groonga,redfigure/groonga,redfigure/groonga,naoa/groonga,groonga/groonga,naoa/groonga,naoa/groonga,myokoym/groonga,komainu8/groonga,naoa/groonga,komainu8/groonga,hiroyuki-sato/groonga,cosmo0920/groonga,myokoym/groonga,myokoym/groonga,hiroyuki-sato/groonga,kenhys/groonga,redfigure/groonga,kenhys/groonga,hiroyuki-sato/groonga,redfigure/groonga,groonga/groonga,hiroyuki-sato/groonga,naoa/groonga,naoa/groonga,groonga/groonga,myokoym/groonga,cosmo0920/groonga,groonga/groonga,kenhys/groonga,komainu8/groonga,cosmo0920/groonga,kenhys/groonga,hiroyuki-sato/groonga,cosmo0920/groonga,komainu8/groonga,cosmo0920/groonga,komainu8/groonga,kenhys/groonga,kenhys/groonga,groonga/groonga,komainu8/groonga,myokoym/groonga
2421ec292eafe1cbf57ffb894e2f34298f443328
src/core/kext/util/ListHookedDevice.cpp
src/core/kext/util/ListHookedDevice.cpp
#include <IOKit/hid/IOHIDKeys.h> #include "ListHookedDevice.hpp" #include "NumHeldDownKeys.hpp" namespace org_pqrs_KeyRemap4MacBook { namespace { void reset(void) { NumHeldDownKeys::reset(); } } bool HookedDevice::isIgnoreDevice(IOHIDevice* dev) { if (! dev) return false; // ------------------------------------------------------------ const OSNumber* number = NULL; number = OSDynamicCast(OSNumber, dev->getProperty(kIOHIDVendorIDKey)); if (! number) return false; UInt32 vendorID = number->unsigned32BitValue(); number = OSDynamicCast(OSNumber, dev->getProperty(kIOHIDProductIDKey)); if (! number) return false; UInt32 productID = number->unsigned32BitValue(); IOLog("KeyRemap4MacBook HookedDevice::isIgnoreDevice checking vendorID = 0x%x, productID = 0x%x\n", static_cast<unsigned int>(vendorID), static_cast<unsigned int>(productID)); // ------------------------------------------------------------ // Logitech USB Headset if (vendorID == 0x046d && productID == 0x0a0b) return true; return false; } // ---------------------------------------------------------------------- bool ListHookedDevice::initialize(void) { lock = IOLockAlloc(); if (! lock) { IOLog("[KeyRemap4MacBook WARNING] ListHookedDevice::initialize IOLockAlloc failed.\n"); return false; } return true; } bool ListHookedDevice::append(IOHIDevice *device) { if (! lock) return false; // ------------------------------------------------------------ bool result = false; IOLockLock(lock); { last = device; for (int i = 0; i < MAXNUM; ++i) { HookedDevice *p = getItem(i); if (! p) continue; if (! p->get()) { IOLog("KeyRemap4MacBook ListHookedDevice::append (device = 0x%p, slot = %d)\n", device, i); result = p->initialize(device); if (result) { // reset if any event actions are replaced. reset(); } break; } } } IOLockUnlock(lock); return result; } void ListHookedDevice::terminate(void) { if (! lock) return; // ------------------------------------------------------------ IOLock *l = NULL; if (lock) { l = lock; IOLockLock(l); lock = NULL; } { // lock scope last = NULL; for (int i = 0; i < MAXNUM; ++i) { HookedDevice *p = getItem(i); if (! p) continue; p->terminate(); } } reset(); // ---------------------------------------- if (l) { IOLockUnlock(l); IOLockFree(l); } } bool ListHookedDevice::terminate(const IOHIDevice *device) { if (! lock) return false; // ---------------------------------------------------------------------- bool result = false; IOLockLock(lock); { HookedDevice *p = get_nolock(device); if (p) { result = p->terminate(); if (result) { reset(); } } } IOLockUnlock(lock); return result; } HookedDevice * ListHookedDevice::get_nolock(const IOHIDevice *device) { last = device; if (! device) return NULL; for (int i = 0; i < MAXNUM; ++i) { HookedDevice *p = getItem(i); if (! p) continue; if (p->get() == device) return p; } return NULL; } HookedDevice * ListHookedDevice::get(const IOHIDevice *device) { if (! lock) return NULL; // ---------------------------------------------------------------------- HookedDevice *result = NULL; IOLockLock(lock); { result = get_nolock(device); } IOLockUnlock(lock); return result; } HookedDevice * ListHookedDevice::get(void) { if (! lock) return NULL; // ---------------------------------------------------------------------- HookedDevice *result = NULL; IOLockLock(lock); { result = get_nolock(last); if (! result) { for (int i = 0; i < MAXNUM; ++i) { result = getItem(i); if (result) break; } } } IOLockUnlock(lock); return result; } void ListHookedDevice::refresh(void) { if (! lock) return; // ---------------------------------------------------------------------- IOLockLock(lock); { for (int i = 0; i < MAXNUM; ++i) { HookedDevice *p = getItem(i); if (! p) continue; if (p->refresh()) { // reset if any event actions are replaced. reset(); } } } IOLockUnlock(lock); } }
#include <IOKit/hid/IOHIDKeys.h> #include "ListHookedDevice.hpp" #include "NumHeldDownKeys.hpp" namespace org_pqrs_KeyRemap4MacBook { namespace { void reset(void) { NumHeldDownKeys::reset(); } } bool HookedDevice::isIgnoreDevice(IOHIDevice* dev) { if (! dev) return false; // ------------------------------------------------------------ const OSNumber* number = NULL; number = OSDynamicCast(OSNumber, dev->getProperty(kIOHIDVendorIDKey)); if (! number) return false; UInt32 vendorID = number->unsigned32BitValue(); number = OSDynamicCast(OSNumber, dev->getProperty(kIOHIDProductIDKey)); if (! number) return false; UInt32 productID = number->unsigned32BitValue(); IOLog("KeyRemap4MacBook HookedDevice::isIgnoreDevice checking vendorID = 0x%x, productID = 0x%x\n", static_cast<unsigned int>(vendorID), static_cast<unsigned int>(productID)); // ------------------------------------------------------------ // Logitech USB Headset if (vendorID == 0x046d && productID == 0x0a0b) return true; #if 0 // Apple External Keyboard if (vendorID == 0x05ac && productID == 0x0222) return true; // My Private Mouse (SIGMA Levy) if (vendorID == 0x093a && productID == 0x2510) return true; #endif return false; } // ---------------------------------------------------------------------- bool ListHookedDevice::initialize(void) { lock = IOLockAlloc(); if (! lock) { IOLog("[KeyRemap4MacBook WARNING] ListHookedDevice::initialize IOLockAlloc failed.\n"); return false; } return true; } bool ListHookedDevice::append(IOHIDevice *device) { if (! lock) return false; // ------------------------------------------------------------ bool result = false; IOLockLock(lock); { last = device; for (int i = 0; i < MAXNUM; ++i) { HookedDevice *p = getItem(i); if (! p) continue; if (! p->get()) { IOLog("KeyRemap4MacBook ListHookedDevice::append (device = 0x%p, slot = %d)\n", device, i); result = p->initialize(device); if (result) { // reset if any event actions are replaced. reset(); } break; } } } IOLockUnlock(lock); return result; } void ListHookedDevice::terminate(void) { if (! lock) return; // ------------------------------------------------------------ IOLock *l = NULL; if (lock) { l = lock; IOLockLock(l); lock = NULL; } { // lock scope last = NULL; for (int i = 0; i < MAXNUM; ++i) { HookedDevice *p = getItem(i); if (! p) continue; p->terminate(); } } reset(); // ---------------------------------------- if (l) { IOLockUnlock(l); IOLockFree(l); } } bool ListHookedDevice::terminate(const IOHIDevice *device) { if (! lock) return false; // ---------------------------------------------------------------------- bool result = false; IOLockLock(lock); { HookedDevice *p = get_nolock(device); if (p) { result = p->terminate(); if (result) { reset(); } } } IOLockUnlock(lock); return result; } HookedDevice * ListHookedDevice::get_nolock(const IOHIDevice *device) { last = device; if (! device) return NULL; for (int i = 0; i < MAXNUM; ++i) { HookedDevice *p = getItem(i); if (! p) continue; if (p->get() == device) return p; } return NULL; } HookedDevice * ListHookedDevice::get(const IOHIDevice *device) { if (! lock) return NULL; // ---------------------------------------------------------------------- HookedDevice *result = NULL; IOLockLock(lock); { result = get_nolock(device); } IOLockUnlock(lock); return result; } HookedDevice * ListHookedDevice::get(void) { if (! lock) return NULL; // ---------------------------------------------------------------------- HookedDevice *result = NULL; IOLockLock(lock); { result = get_nolock(last); if (! result) { for (int i = 0; i < MAXNUM; ++i) { result = getItem(i); if (result) break; } } } IOLockUnlock(lock); return result; } void ListHookedDevice::refresh(void) { if (! lock) return; // ---------------------------------------------------------------------- IOLockLock(lock); { for (int i = 0; i < MAXNUM; ++i) { HookedDevice *p = getItem(i); if (! p) continue; if (p->refresh()) { // reset if any event actions are replaced. reset(); } } } IOLockUnlock(lock); } }
add dummy example @ HookedDevice::isIgnoreDevice
add dummy example @ HookedDevice::isIgnoreDevice
C++
unlicense
runarbu/Karabiner,muramasa64/Karabiner,miaotaizi/Karabiner,e-gaulue/Karabiner,miaotaizi/Karabiner,muramasa64/Karabiner,chzyer-dev/Karabiner,tekezo/Karabiner,wataash/Karabiner,e-gaulue/Karabiner,chzyer-dev/Karabiner,miaotaizi/Karabiner,tekezo/Karabiner,runarbu/Karabiner,astachurski/Karabiner,astachurski/Karabiner,tekezo/Karabiner,wataash/Karabiner,miaotaizi/Karabiner,tekezo/Karabiner,e-gaulue/Karabiner,muramasa64/Karabiner,chzyer-dev/Karabiner,runarbu/Karabiner,muramasa64/Karabiner,astachurski/Karabiner,e-gaulue/Karabiner,runarbu/Karabiner,astachurski/Karabiner,wataash/Karabiner,wataash/Karabiner,chzyer-dev/Karabiner
3d35146b78174db8735f41d9b1f63369aee08d89
src/main.cpp
src/main.cpp
#include <Arduino.h> #include <ZumoMotors.h> #include <Pushbutton.h> #include <QTRSensors.h> #include <ZumoReflectanceSensorArray.h> /* * This example uses the ZumoMotors library to follow a black line. */ #define LED_PIN 13 #define NUM_SENSORS 6 // number of sensors used #define NUM_SAMPLES_PER_SENSOR 4 // average 4 analog samples per sensor reading #define EMITTER_PIN 2 // emitter is controlled by digital pin 2 // sensors 0 through 5 are connected to analog inputs 0 through 5, respectively ZumoReflectanceSensorArray reflectanceSensors; unsigned int sensorValues[NUM_SENSORS]; double Kp = 0; int offset = 0; int integral = 0; Pushbutton button(ZUMO_BUTTON); ZumoMotors motors; // This is the maximum speed the motors will be allowed to turn. // (400 lets the motors go at top speed; decrease to impose a speed limit) const int MAX_SPEED = 400; void setup() { delay(500); // Initialize the reflectance sensors module reflectanceSensors.init(); pinMode(LED_PIN, OUTPUT); // turn on Arduino's LED to indicate we are in calibration mode digitalWrite(LED_PIN, HIGH); int i; for (i = 0; i < 80; i++) { if ((i > 10 && i <= 30) || (i > 50 && i <= 70)) motors.setSpeeds(-200, 200); else motors.setSpeeds(200, -200); reflectanceSensors.calibrate(); // Since our counter runs to 80, the total delay will be // 80*20 = 1600 ms. delay(20); } motors.setSpeeds(0,0); // turn off Arduino's LED to indicate we are through with calibration digitalWrite(LED_PIN, LOW); // print the calibration minimum values measured when emitters were on Serial.begin(9600); /* for (int i = 0; i < NUM_SENSORS; i++) { Serial.print(reflectanceSensors.calibratedMinimumOn[i]); Serial.print(' '); } Serial.println(); // print the calibration maximum values measured when emitters were on for (int i = 0; i < NUM_SENSORS; i++) { Serial.print(reflectanceSensors.calibratedMaximumOn[i]); Serial.print(' '); } Serial.println(); Serial.println(); Serial.println(offset); */ // Wait for the user button to be pressed and released button.waitForButton(); // Read the offset value after setting zumo in the right position. offset = reflectanceSensors.readLine(sensorValues); Kp = offset / MAX_SPEED; Serial.print(offset); Serial.print(' '); Serial.println(Kp); delay(1000); } // read calibrated sensor values and obtain a measure of the line position from 0 to 5000 void loop() { digitalWrite(LED_PIN, HIGH); int position = reflectanceSensors.readLine(sensorValues); int error = position - offset; integral += error; if ((integral < 0) == (error < 0)) { integral = 0; } int turn = Kp * error + integral; int leftSpeed = MAX_SPEED + turn; int rightSpeed = MAX_SPEED - turn; /* Serial.print(position); Serial.print(' '); Serial.print(leftSpeed); Serial.print(' '); Serial.println(rightSpeed); */ // Here we constrain our motor speeds to be between 0 and MAX_SPEED. // Generally speaking, one motor will always be turning at MAX_SPEED // and the other will be at MAX_SPEED-|speedDifference| if that is positive, // else it will be stationary. For some applications, you might want to // allow the motor speed to go negative so that it can spin in reverse. if (leftSpeed < 0) leftSpeed = 0; if (rightSpeed < 0) rightSpeed = 0; if (leftSpeed > MAX_SPEED) leftSpeed = MAX_SPEED; if (rightSpeed > MAX_SPEED) rightSpeed = MAX_SPEED; // Set the motor speeds motors.setSpeeds(leftSpeed, rightSpeed); }
#include <Arduino.h> #include <ZumoMotors.h> #include <Pushbutton.h> #include <QTRSensors.h> #include <ZumoReflectanceSensorArray.h> /* * This example uses the ZumoMotors library to follow a black line. * The */ #define LED_PIN 13 #define NUM_SENSORS 6 // number of sensors used #define NUM_SAMPLES_PER_SENSOR 4 // average 4 analog samples per sensor reading #define EMITTER_PIN 2 // emitter is controlled by digital pin 2 // sensors 0 through 5 are connected to analog inputs 0 through 5, respectively ZumoReflectanceSensorArray reflectanceSensors; unsigned int sensorValues[NUM_SENSORS]; double Kp = 0; int offset = 0; int integral = 0; int derivative = 0; int Kd = 100; // total guess int lastError = 0; Pushbutton button(ZUMO_BUTTON); ZumoMotors motors; // This is the maximum speed the motors will be allowed to turn. // (400 lets the motors go at top speed; decrease to impose a speed limit) const int MAX_SPEED = 400; void setup() { delay(500); // Initialize the reflectance sensors module reflectanceSensors.init(); pinMode(LED_PIN, OUTPUT); // turn on Arduino's LED to indicate we are in calibration mode digitalWrite(LED_PIN, HIGH); int i; for (i = 0; i < 80; i++) { if ((i > 10 && i <= 30) || (i > 50 && i <= 70)) motors.setSpeeds(-200, 200); else motors.setSpeeds(200, -200); reflectanceSensors.calibrate(); // Since our counter runs to 80, the total delay will be // 80*20 = 1600 ms. delay(20); } motors.setSpeeds(0,0); // turn off Arduino's LED to indicate we are through with calibration digitalWrite(LED_PIN, LOW); // Wait for the user button to be pressed and released button.waitForButton(); // Read the offset value after setting zumo in the right position. offset = reflectanceSensors.readLine(sensorValues); Kp = offset / MAX_SPEED; Serial.print(offset); Serial.print(' '); Serial.println(Kp); delay(1000); } void loop() { digitalWrite(LED_PIN, HIGH); int position = reflectanceSensors.readLine(sensorValues); int error = position - offset; derivative = error - lastError; lastError = error; integral += error; if ((integral < 0) == (error < 0)) { integral = 0; } int turn = Kp * error + integral + Kd * derivative; int leftSpeed = MAX_SPEED + turn; int rightSpeed = MAX_SPEED - turn; // Here we constrain our motor speeds to be between 0 and MAX_SPEED. // Generally speaking, one motor will always be turning at MAX_SPEED // and the other will be at MAX_SPEED-|turn| if that is positive, // else it will be stationary. For some applications, you might want to // allow the motor speed to go negative so that it can spin in reverse. if (leftSpeed < 0) leftSpeed = 0; if (rightSpeed < 0) rightSpeed = 0; if (leftSpeed > MAX_SPEED) leftSpeed = MAX_SPEED; if (rightSpeed > MAX_SPEED) rightSpeed = MAX_SPEED; // Set the motor speeds motors.setSpeeds(leftSpeed, rightSpeed); }
Complete PID controller for line follower
Complete PID controller for line follower
C++
mit
ogail/zumo-line-follower
d329ef2505542fcd137c8ac610ccd39a89a28ce2
chrome/browser/diagnostics/diagnostics_main.cc
chrome/browser/diagnostics/diagnostics_main.cc
// 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/diagnostics/diagnostics_main.h" #include "app/app_paths.h" #include "base/basictypes.h" #include "base/command_line.h" #include "base/i18n/icu_util.h" #include "base/string_util.h" #include "base/time.h" #include "chrome/browser/diagnostics/diagnostics_model.h" #include "chrome/common/chrome_paths.h" #if defined(OS_WIN) #include "base/win_util.h" namespace { // This is a minimalistic class to wrap the windows console operating // in high-level IO mode. This will be eventually replaced by a view // that can be subclassed for each platform and that the approved look // and feel. class SimpleConsole { public: // The ctor allocates a console always. This avoids having to ask // the user to start chrome from a command prompt. SimpleConsole() : std_out_(INVALID_HANDLE_VALUE), std_in_(INVALID_HANDLE_VALUE) { } ~SimpleConsole() { ::FreeConsole(); } // Init must be called before using any other method. If it returns // false there would be no console output. bool Init() { ::AllocConsole(); return SetIOHandles(); } // Writes a string to the console with the current color. bool Write(const std::wstring& txt) { DWORD sz = txt.size(); return (TRUE == ::WriteConsoleW(std_out_, txt.c_str(), sz, &sz, NULL)); } // Reads a string from the console. Internally it is limited to 256 // characters. bool Read(std::wstring* txt) { wchar_t buf[256]; DWORD read = sizeof(buf) - sizeof(buf[0]); if (!::ReadConsoleW(std_in_, buf, read, &read, NULL)) return false; // Note that |read| is in bytes. txt->assign(buf, read/2); return true; } // Sets the foreground and backgroudn color. See |kRedFG| or |kGreenFG| // below for examples how to combine colors. bool SetColor(uint16 color_combo) { return (TRUE == ::SetConsoleTextAttribute(std_out_, color_combo)); } private: bool SetIOHandles() { std_out_ = ::GetStdHandle(STD_OUTPUT_HANDLE); std_in_ = ::GetStdHandle(STD_INPUT_HANDLE); return ((std_out_ != INVALID_HANDLE_VALUE) && (std_in_ != INVALID_HANDLE_VALUE)); } // The input and output handles to the screen. They seem to be // implemented as pipes but they have non-documented protocol. HANDLE std_out_; HANDLE std_in_; DISALLOW_COPY_AND_ASSIGN(SimpleConsole); }; // This class wraps a SimpleConsole for the specific use case of // writing the results of the diagnostic tests. // TODO(cpu) figure out the localization strategy. class TestWriter { public: // The |console| must be valid and properly initialized. This // class does not own it. explicit TestWriter(SimpleConsole* console) : console_(console) { } // Write an informational line of text in white over black. bool WriteInfoText(const std::wstring& txt) { console_->SetColor(kWhiteFG); return console_->Write(txt); } // Write a result block. It consist of two lines. The first line // has [PASS] or [FAIL] with |name| and the second line has // the text in |extra|. bool WriteResult(bool success, const std::wstring& name, const std::wstring& extra) { if (success) { console_->SetColor(kGreenFG); console_->Write(L"[PASS] "); } else { console_->SetColor(kRedFG); console_->Write(L"[FAIL] "); } WriteInfoText(name + L"\n"); std::wstring second_line(L" "); second_line.append(extra); return WriteInfoText(second_line + L"\n\n"); } private: // constants for the colors we use. static const uint16 kRedFG = FOREGROUND_RED|FOREGROUND_INTENSITY; static const uint16 kGreenFG = FOREGROUND_GREEN|FOREGROUND_INTENSITY; static const uint16 kWhiteFG = kRedFG | kGreenFG | FOREGROUND_BLUE; SimpleConsole* console_; DISALLOW_COPY_AND_ASSIGN(TestWriter); }; std::wstring PrintableUSCurrentTime() { base::Time::Exploded exploded = {0}; base::Time::Now().UTCExplode(&exploded); return StringPrintf(L"%d:%d:%d.%d:%d:%d", exploded.year, exploded.month, exploded.day_of_month, exploded.hour, exploded.minute, exploded.second); } // This class is a basic test controller. In this design the view (TestWriter) // and the model (DiagnosticsModel) do not talk to each other directly but they // are mediated by the controller. This has a name: 'passive view'. // More info at http://martinfowler.com/eaaDev/PassiveScreen.html class TestController : public DiagnosticsModel::Observer { public: explicit TestController(TestWriter* writer) : writer_(writer) { } // Run all the diagnostics of |model| and invoke the view as the model // callbacks arrive. void Run(DiagnosticsModel* model) { std::wstring title(L"Chrome Diagnostics Mode ("); writer_->WriteInfoText(title.append(PrintableUSCurrentTime()) + L")\n"); if (!model) { writer_->WriteResult(false, L"Diagnostics start", L"model is null"); return; } bool icu_result = icu_util::Initialize(); if (!icu_result) { writer_->WriteResult(false, L"Diagnostics start", L"ICU failure"); return; } int count = model->GetTestAvailableCount(); writer_->WriteInfoText(StringPrintf(L"%d available test(s)\n\n", count)); model->RunAll(this); } // Next four are overriden from DiagnosticsModel::Observer virtual void OnProgress(int id, int percent, DiagnosticsModel* model) { } virtual void OnSkipped(int id, DiagnosticsModel* model) { // TODO(cpu): display skipped tests. } virtual void OnFinished(int id, DiagnosticsModel* model) { // As each test completes we output the results. ShowResult(model->GetTest(id)); } virtual void OnDoneAll(DiagnosticsModel* model) { writer_->WriteInfoText(L"DONE\n\n"); } private: void ShowResult(DiagnosticsModel::TestInfo& test_info) { bool success = (DiagnosticsModel::TEST_OK == test_info.GetResult()); writer_->WriteResult(success, test_info.GetTitle(), test_info.GetAdditionalInfo()); } DiagnosticsModel* model_; TestWriter* writer_; DISALLOW_COPY_AND_ASSIGN(TestController); }; } // namespace // This entry point is called from ChromeMain() when very few things // have been initialized. To wit: // -(win) Breakpad // -(macOS) base::EnableTerminationOnHeapCorruption() // -(macOS) base::EnableTerminationOnOutOfMemory() // -(all) RegisterInvalidParamHandler() // -(all) base::AtExitManager::AtExitManager() // -(macOS) base::ScopedNSAutoreleasePool // -(posix) Singleton<base::GlobalDescriptors>::Set(kPrimaryIPCChannel) // -(linux) Singleton<base::GlobalDescriptors>::Set(kCrashDumpSignal) // -(posix) setlocale(LC_ALL,..) // -(all) CommandLine::Init(); int DiagnosticsMain(const CommandLine& command_line) { // If we can't initialize the console exit right away. SimpleConsole console; if (!console.Init()) return 1; // We need to have the path providers registered. They both // return void so there is no early error signal that we can use. app::RegisterPathProvider(); chrome::RegisterPathProvider(); TestWriter writer(&console); DiagnosticsModel* model = MakeDiagnosticsModel(command_line); TestController controller(&writer); // Run all the diagnostic tests. controller.Run(model); delete model; // Block here so the user can see the results. writer.WriteInfoText(L"Press [enter] to continue\n"); std::wstring txt; console.Read(&txt); return 0; } #else // defined(OS_WIN) int DiagnosticsMain(const CommandLine& command_line) { return 0; } #endif
// 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/diagnostics/diagnostics_main.h" #if defined(OS_POSIX) #include <stdio.h> #include <unistd.h> #endif #include "app/app_paths.h" #include "base/basictypes.h" #include "base/command_line.h" #include "base/i18n/icu_util.h" #include "base/string_util.h" #include "base/sys_string_conversions.h" #include "base/time.h" #include "base/utf_string_conversions.h" #include "chrome/browser/diagnostics/diagnostics_model.h" #include "chrome/common/chrome_paths.h" #if defined(OS_WIN) #include "base/win_util.h" #endif namespace { // This is a minimalistic interface to wrap the platform console. This will be // eventually replaced by a view that can be subclassed for each platform and // that the approved look and feel. class SimpleConsole { public: enum Color { DEFAULT, RED, GREEN, }; virtual ~SimpleConsole() { } // Init must be called before using any other method. If it returns // false there would be no console output. virtual bool Init() = 0; // Writes a string to the console with the current color. virtual bool Write(const std::wstring& text) = 0; // Reads a string from the console. Internally it may be limited to 256 // characters. virtual bool Read(std::wstring* txt) = 0; // Sets the foreground and background color. virtual bool SetColor(Color color) = 0; // Create an appropriate SimpleConsole instance. May return NULL if there is // no implementation for the current platform. static SimpleConsole* Create(); }; #if defined(OS_WIN) // Wrapper for the windows console operating in high-level IO mode. class WinConsole : public SimpleConsole { public: // The ctor allocates a console always. This avoids having to ask // the user to start chrome from a command prompt. WinConsole() : std_out_(INVALID_HANDLE_VALUE), std_in_(INVALID_HANDLE_VALUE) { } virtual ~WinConsole() { ::FreeConsole(); } virtual bool Init() { ::AllocConsole(); return SetIOHandles(); } virtual bool Write(const std::wstring& txt) { DWORD sz = txt.size(); return (TRUE == ::WriteConsoleW(std_out_, txt.c_str(), sz, &sz, NULL)); } // Reads a string from the console. Internally it is limited to 256 // characters. virtual bool Read(std::wstring* txt) { wchar_t buf[256]; DWORD read = sizeof(buf) - sizeof(buf[0]); if (!::ReadConsoleW(std_in_, buf, read, &read, NULL)) return false; // Note that |read| is in bytes. txt->assign(buf, read/2); return true; } // Sets the foreground and background color. virtual bool SetColor(Color color) { uint16 color_combo = FOREGROUND_RED|FOREGROUND_GREEN|FOREGROUND_BLUE|FOREGROUND_INTENSITY; switch (color) { case RED: color_combo = FOREGROUND_RED|FOREGROUND_INTENSITY; break; case GREEN: color_combo = FOREGROUND_GREEN|FOREGROUND_INTENSITY; break; case DEFAULT: break; default: NOTREACHED(); } return (TRUE == ::SetConsoleTextAttribute(std_out_, color_combo)); } private: bool SetIOHandles() { std_out_ = ::GetStdHandle(STD_OUTPUT_HANDLE); std_in_ = ::GetStdHandle(STD_INPUT_HANDLE); return ((std_out_ != INVALID_HANDLE_VALUE) && (std_in_ != INVALID_HANDLE_VALUE)); } // The input and output handles to the screen. They seem to be // implemented as pipes but they have non-documented protocol. HANDLE std_out_; HANDLE std_in_; DISALLOW_COPY_AND_ASSIGN(WinConsole); }; SimpleConsole* SimpleConsole::Create() { return new WinConsole(); } #elif defined(OS_POSIX) class PosixConsole : public SimpleConsole { public: PosixConsole() { } virtual bool Init() { // Technically, we should also check the terminal capabilities before using // color, but in practice this is unlikely to be an issue. use_color_ = isatty(STDOUT_FILENO); return true; } virtual bool Write(const std::wstring& text) { printf("%s", base::SysWideToNativeMB(text).c_str()); return true; } virtual bool Read(std::wstring* txt) { // TODO(mattm): implement this. return false; } virtual bool SetColor(Color color) { if (!use_color_) return false; const char* code = "\033[m"; switch (color) { case RED: code = "\033[1;31m"; break; case GREEN: code = "\033[1;32m"; break; case DEFAULT: break; default: NOTREACHED(); } printf("%s", code); return true; } private: bool use_color_; DISALLOW_COPY_AND_ASSIGN(PosixConsole); }; SimpleConsole* SimpleConsole::Create() { return new PosixConsole(); } #else // !defined(OS_WIN) && !defined(OS_POSIX) SimpleConsole* SimpleConsole::Create() { return NULL; } #endif // This class wraps a SimpleConsole for the specific use case of // writing the results of the diagnostic tests. // TODO(cpu) figure out the localization strategy. class TestWriter { public: // The |console| must be valid and properly initialized. This // class does not own it. explicit TestWriter(SimpleConsole* console) : console_(console) { } // Write an informational line of text in white over black. bool WriteInfoText(const std::wstring& txt) { console_->SetColor(SimpleConsole::DEFAULT); return console_->Write(txt); } // Write a result block. It consist of two lines. The first line // has [PASS] or [FAIL] with |name| and the second line has // the text in |extra|. bool WriteResult(bool success, const std::wstring& name, const std::wstring& extra) { if (success) { console_->SetColor(SimpleConsole::GREEN); console_->Write(L"[PASS] "); } else { console_->SetColor(SimpleConsole::RED); console_->Write(L"[FAIL] "); } WriteInfoText(name + L"\n"); std::wstring second_line(L" "); second_line.append(extra); return WriteInfoText(second_line + L"\n\n"); } private: SimpleConsole* console_; DISALLOW_COPY_AND_ASSIGN(TestWriter); }; std::wstring PrintableUSCurrentTime() { base::Time::Exploded exploded = {0}; base::Time::Now().UTCExplode(&exploded); return StringPrintf(L"%d:%d:%d.%d:%d:%d", exploded.year, exploded.month, exploded.day_of_month, exploded.hour, exploded.minute, exploded.second); } // This class is a basic test controller. In this design the view (TestWriter) // and the model (DiagnosticsModel) do not talk to each other directly but they // are mediated by the controller. This has a name: 'passive view'. // More info at http://martinfowler.com/eaaDev/PassiveScreen.html class TestController : public DiagnosticsModel::Observer { public: explicit TestController(TestWriter* writer) : writer_(writer) { } // Run all the diagnostics of |model| and invoke the view as the model // callbacks arrive. void Run(DiagnosticsModel* model) { std::wstring title(L"Chrome Diagnostics Mode ("); writer_->WriteInfoText(title.append(PrintableUSCurrentTime()) + L")\n"); if (!model) { writer_->WriteResult(false, L"Diagnostics start", L"model is null"); return; } bool icu_result = icu_util::Initialize(); if (!icu_result) { writer_->WriteResult(false, L"Diagnostics start", L"ICU failure"); return; } int count = model->GetTestAvailableCount(); writer_->WriteInfoText(StringPrintf(L"%d available test(s)\n\n", count)); model->RunAll(this); } // Next four are overriden from DiagnosticsModel::Observer virtual void OnProgress(int id, int percent, DiagnosticsModel* model) { } virtual void OnSkipped(int id, DiagnosticsModel* model) { // TODO(cpu): display skipped tests. } virtual void OnFinished(int id, DiagnosticsModel* model) { // As each test completes we output the results. ShowResult(model->GetTest(id)); } virtual void OnDoneAll(DiagnosticsModel* model) { writer_->WriteInfoText(L"DONE\n\n"); } private: void ShowResult(DiagnosticsModel::TestInfo& test_info) { bool success = (DiagnosticsModel::TEST_OK == test_info.GetResult()); writer_->WriteResult(success, UTF16ToWide(test_info.GetTitle()), UTF16ToWide(test_info.GetAdditionalInfo())); } DiagnosticsModel* model_; TestWriter* writer_; DISALLOW_COPY_AND_ASSIGN(TestController); }; } // namespace // This entry point is called from ChromeMain() when very few things // have been initialized. To wit: // -(win) Breakpad // -(macOS) base::EnableTerminationOnHeapCorruption() // -(macOS) base::EnableTerminationOnOutOfMemory() // -(all) RegisterInvalidParamHandler() // -(all) base::AtExitManager::AtExitManager() // -(macOS) base::ScopedNSAutoreleasePool // -(posix) Singleton<base::GlobalDescriptors>::Set(kPrimaryIPCChannel) // -(linux) Singleton<base::GlobalDescriptors>::Set(kCrashDumpSignal) // -(posix) setlocale(LC_ALL,..) // -(all) CommandLine::Init(); int DiagnosticsMain(const CommandLine& command_line) { // If we can't initialize the console exit right away. SimpleConsole* console = SimpleConsole::Create(); if (!console || !console->Init()) return 1; // We need to have the path providers registered. They both // return void so there is no early error signal that we can use. app::RegisterPathProvider(); chrome::RegisterPathProvider(); TestWriter writer(console); DiagnosticsModel* model = MakeDiagnosticsModel(command_line); TestController controller(&writer); // Run all the diagnostic tests. controller.Run(model); delete model; // The "press enter to continue" prompt isn't very unixy, so only do that on // Windows. #if defined(OS_WIN) // Block here so the user can see the results. writer.WriteInfoText(L"Press [enter] to continue\n"); std::wstring txt; console->Read(&txt); #endif delete console; return 0; }
implement diagnostics mode console output.
Posix: implement diagnostics mode console output. BUG=42894,42345 TEST=chrome --diagnostics Review URL: http://codereview.chromium.org/2115001 git-svn-id: http://src.chromium.org/svn/trunk/src@47348 4ff67af0-8c30-449e-8e8b-ad334ec8d88c Former-commit-id: 9e09bee2e4330c1ba5f24e1a1975cca5c2c3f80a
C++
bsd-3-clause
meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser
a318df5971718a4657473d0a760bb476699118f1
chrome/browser/download/download_extensions.cc
chrome/browser/download/download_extensions.cc
// 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 <set> #include <string> #include "chrome/browser/download/download_extensions.h" #include "base/string_util.h" #include "net/base/mime_util.h" #include "net/base/net_util.h" namespace download_util { // For file extensions taken from mozilla: /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public 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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Mozilla Communicator client code, released * March 31, 1998. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1998-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Doug Turner <[email protected]> * Dean Tessman <[email protected]> * Brodie Thiesfield <[email protected]> * Jungshik Shin <[email protected]> * * Alternatively, the contents of this file may be used under the terms of * either of the GNU General Public License Version 2 or later (the "GPL"), * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ static const struct Executables { const char* extension; DownloadDangerLevel level; } g_executables[] = { { "class", AllowOnUserGesture }, { "htm", AllowOnUserGesture }, { "html", AllowOnUserGesture }, { "jar", AllowOnUserGesture }, { "jnlp", AllowOnUserGesture }, { "pdf", AllowOnUserGesture }, { "pdfxml", AllowOnUserGesture }, { "mars", AllowOnUserGesture }, { "fdf", AllowOnUserGesture }, { "xfdf", AllowOnUserGesture }, { "xdp", AllowOnUserGesture }, { "xfd", AllowOnUserGesture }, { "pl", AllowOnUserGesture }, { "py", AllowOnUserGesture }, { "rb", AllowOnUserGesture }, { "shtm", AllowOnUserGesture }, { "shtml", AllowOnUserGesture }, { "svg", AllowOnUserGesture }, { "swf", AllowOnUserGesture }, { "xht", AllowOnUserGesture }, { "xhtm", AllowOnUserGesture }, { "xhtml", AllowOnUserGesture }, { "xml", AllowOnUserGesture }, { "xsl", AllowOnUserGesture }, { "xslt", AllowOnUserGesture }, #if defined(OS_WIN) { "ad", AllowOnUserGesture }, { "ade", AllowOnUserGesture }, { "adp", AllowOnUserGesture }, { "app", AllowOnUserGesture }, { "application", AllowOnUserGesture }, { "asp", AllowOnUserGesture }, { "asx", AllowOnUserGesture }, { "bas", AllowOnUserGesture }, { "bat", AllowOnUserGesture }, { "chi", AllowOnUserGesture }, { "chm", AllowOnUserGesture }, { "cmd", AllowOnUserGesture }, { "com", AllowOnUserGesture }, { "cpl", AllowOnUserGesture }, { "crt", AllowOnUserGesture }, { "dll", Dangerous }, { "drv", Dangerous }, { "exe", AllowOnUserGesture }, { "fxp", AllowOnUserGesture }, { "hlp", AllowOnUserGesture }, { "hta", AllowOnUserGesture }, { "htt", AllowOnUserGesture }, { "inf", AllowOnUserGesture }, { "ins", AllowOnUserGesture }, { "isp", AllowOnUserGesture }, { "js", AllowOnUserGesture }, { "jse", AllowOnUserGesture }, { "lnk", AllowOnUserGesture }, { "mad", AllowOnUserGesture }, { "maf", AllowOnUserGesture }, { "mag", AllowOnUserGesture }, { "mam", AllowOnUserGesture }, { "maq", AllowOnUserGesture }, { "mar", AllowOnUserGesture }, { "mas", AllowOnUserGesture }, { "mat", AllowOnUserGesture }, { "mau", AllowOnUserGesture }, { "mav", AllowOnUserGesture }, { "maw", AllowOnUserGesture }, { "mda", AllowOnUserGesture }, { "mdb", AllowOnUserGesture }, { "mde", AllowOnUserGesture }, { "mdt", AllowOnUserGesture }, { "mdw", AllowOnUserGesture }, { "mdz", AllowOnUserGesture }, { "mht", AllowOnUserGesture }, { "mhtml", AllowOnUserGesture }, { "mmc", AllowOnUserGesture }, { "msc", AllowOnUserGesture }, { "msh", AllowOnUserGesture }, { "mshxml", AllowOnUserGesture }, { "msi", AllowOnUserGesture }, { "msp", AllowOnUserGesture }, { "mst", AllowOnUserGesture }, { "ocx", AllowOnUserGesture }, { "ops", AllowOnUserGesture }, { "pcd", AllowOnUserGesture }, { "pif", AllowOnUserGesture }, { "plg", AllowOnUserGesture }, { "prf", AllowOnUserGesture }, { "prg", AllowOnUserGesture }, { "pst", AllowOnUserGesture }, { "reg", AllowOnUserGesture }, { "scf", AllowOnUserGesture }, { "scr", AllowOnUserGesture }, { "sct", AllowOnUserGesture }, { "shb", AllowOnUserGesture }, { "shs", AllowOnUserGesture }, { "sys", Dangerous }, { "url", AllowOnUserGesture }, { "vb", AllowOnUserGesture }, { "vbe", AllowOnUserGesture }, { "vbs", AllowOnUserGesture }, { "vsd", AllowOnUserGesture }, { "vsmacros", AllowOnUserGesture }, { "vss", AllowOnUserGesture }, { "vst", AllowOnUserGesture }, { "vsw", AllowOnUserGesture }, { "ws", AllowOnUserGesture }, { "wsc", AllowOnUserGesture }, { "wsf", AllowOnUserGesture }, { "wsh", AllowOnUserGesture }, { "xbap", Dangerous }, #elif defined(OS_MACOSX) // TODO(thakis): Figure out what makes sense here -- crbug.com/19096 { "app", AllowOnUserGesture }, { "dmg", AllowOnUserGesture }, #elif defined(OS_POSIX) // TODO(estade): lengthen this list. { "bash", AllowOnUserGesture }, { "csh", AllowOnUserGesture }, { "deb", AllowOnUserGesture }, { "exe", AllowOnUserGesture }, { "ksh", AllowOnUserGesture }, { "rpm", AllowOnUserGesture }, { "sh", AllowOnUserGesture }, { "tcsh", AllowOnUserGesture }, #endif }; DownloadDangerLevel GetFileDangerLevel(const FilePath& path) { return GetFileExtensionDangerLevel(path.Extension()); } DownloadDangerLevel GetFileExtensionDangerLevel( const FilePath::StringType& extension) { if (extension.empty()) return NotDangerous; if (!IsStringASCII(extension)) return NotDangerous; #if defined(OS_WIN) std::string ascii_extension = WideToASCII(extension); #elif defined(OS_POSIX) std::string ascii_extension = extension; #endif // Strip out leading dot if it's still there if (ascii_extension[0] == FilePath::kExtensionSeparator) ascii_extension.erase(0, 1); for (size_t i = 0; i < arraysize(g_executables); ++i) { if (LowerCaseEqualsASCII(ascii_extension, g_executables[i].extension)) return g_executables[i].level; } return NotDangerous; } bool IsFileExtensionSafe(const FilePath::StringType& extension) { return GetFileExtensionDangerLevel(extension) == NotDangerous; } bool IsFileSafe(const FilePath& path) { return GetFileDangerLevel(path) == NotDangerous; } static const char* kExecutableWhiteList[] = { // JavaScript is just as powerful as EXE. "text/javascript", "text/javascript;version=*", "text/html", // Registry files can cause critical changes to the MS OS behavior. // Addition of this mimetype also addresses bug 7337. "text/x-registry", "text/x-sh", // Some sites use binary/octet-stream to mean application/octet-stream. // See http://code.google.com/p/chromium/issues/detail?id=1573 "binary/octet-stream" }; static const char* kExecutableBlackList[] = { // These application types are not executable. "application/*+xml", "application/xml" }; bool IsExecutableMimeType(const std::string& mime_type) { for (size_t i = 0; i < arraysize(kExecutableWhiteList); ++i) { if (net::MatchesMimeType(kExecutableWhiteList[i], mime_type)) return true; } for (size_t i = 0; i < arraysize(kExecutableBlackList); ++i) { if (net::MatchesMimeType(kExecutableBlackList[i], mime_type)) return false; } // We consider only other application types to be executable. return net::MatchesMimeType("application/*", mime_type); } } // namespace download_util
// 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 <set> #include <string> #include "chrome/browser/download/download_extensions.h" #include "base/string_util.h" #include "net/base/mime_util.h" #include "net/base/net_util.h" namespace download_util { // For file extensions taken from mozilla: /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public 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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Mozilla Communicator client code, released * March 31, 1998. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1998-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Doug Turner <[email protected]> * Dean Tessman <[email protected]> * Brodie Thiesfield <[email protected]> * Jungshik Shin <[email protected]> * * Alternatively, the contents of this file may be used under the terms of * either of the GNU General Public License Version 2 or later (the "GPL"), * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ static const struct Executables { const char* extension; DownloadDangerLevel level; } g_executables[] = { { "class", Dangerous }, { "htm", AllowOnUserGesture }, { "html", AllowOnUserGesture }, { "jar", Dangerous }, { "jnlp", Dangerous }, { "pdf", AllowOnUserGesture }, { "pdfxml", AllowOnUserGesture }, { "mars", AllowOnUserGesture }, { "fdf", AllowOnUserGesture }, { "xfdf", AllowOnUserGesture }, { "xdp", AllowOnUserGesture }, { "xfd", AllowOnUserGesture }, { "pl", AllowOnUserGesture }, { "py", AllowOnUserGesture }, { "rb", AllowOnUserGesture }, { "shtm", AllowOnUserGesture }, { "shtml", AllowOnUserGesture }, { "svg", AllowOnUserGesture }, { "swf", AllowOnUserGesture }, { "xht", AllowOnUserGesture }, { "xhtm", AllowOnUserGesture }, { "xhtml", AllowOnUserGesture }, { "xml", AllowOnUserGesture }, { "xsl", AllowOnUserGesture }, { "xslt", AllowOnUserGesture }, #if defined(OS_WIN) { "ad", AllowOnUserGesture }, { "ade", AllowOnUserGesture }, { "adp", AllowOnUserGesture }, { "app", AllowOnUserGesture }, { "application", AllowOnUserGesture }, { "asp", AllowOnUserGesture }, { "asx", AllowOnUserGesture }, { "bas", AllowOnUserGesture }, { "bat", AllowOnUserGesture }, { "chi", AllowOnUserGesture }, { "chm", AllowOnUserGesture }, { "cmd", AllowOnUserGesture }, { "com", AllowOnUserGesture }, { "cpl", AllowOnUserGesture }, { "crt", AllowOnUserGesture }, { "dll", Dangerous }, { "drv", Dangerous }, { "exe", AllowOnUserGesture }, { "fxp", AllowOnUserGesture }, { "hlp", AllowOnUserGesture }, { "hta", AllowOnUserGesture }, { "htt", AllowOnUserGesture }, { "inf", AllowOnUserGesture }, { "ins", AllowOnUserGesture }, { "isp", AllowOnUserGesture }, { "js", AllowOnUserGesture }, { "jse", AllowOnUserGesture }, { "lnk", AllowOnUserGesture }, { "mad", AllowOnUserGesture }, { "maf", AllowOnUserGesture }, { "mag", AllowOnUserGesture }, { "mam", AllowOnUserGesture }, { "maq", AllowOnUserGesture }, { "mar", AllowOnUserGesture }, { "mas", AllowOnUserGesture }, { "mat", AllowOnUserGesture }, { "mau", AllowOnUserGesture }, { "mav", AllowOnUserGesture }, { "maw", AllowOnUserGesture }, { "mda", AllowOnUserGesture }, { "mdb", AllowOnUserGesture }, { "mde", AllowOnUserGesture }, { "mdt", AllowOnUserGesture }, { "mdw", AllowOnUserGesture }, { "mdz", AllowOnUserGesture }, { "mht", AllowOnUserGesture }, { "mhtml", AllowOnUserGesture }, { "mmc", AllowOnUserGesture }, { "msc", AllowOnUserGesture }, { "msh", AllowOnUserGesture }, { "mshxml", AllowOnUserGesture }, { "msi", AllowOnUserGesture }, { "msp", AllowOnUserGesture }, { "mst", AllowOnUserGesture }, { "ocx", AllowOnUserGesture }, { "ops", AllowOnUserGesture }, { "pcd", AllowOnUserGesture }, { "pif", AllowOnUserGesture }, { "plg", AllowOnUserGesture }, { "prf", AllowOnUserGesture }, { "prg", AllowOnUserGesture }, { "pst", AllowOnUserGesture }, { "reg", AllowOnUserGesture }, { "scf", AllowOnUserGesture }, { "scr", AllowOnUserGesture }, { "sct", AllowOnUserGesture }, { "shb", AllowOnUserGesture }, { "shs", AllowOnUserGesture }, { "sys", Dangerous }, { "url", AllowOnUserGesture }, { "vb", AllowOnUserGesture }, { "vbe", AllowOnUserGesture }, { "vbs", AllowOnUserGesture }, { "vsd", AllowOnUserGesture }, { "vsmacros", AllowOnUserGesture }, { "vss", AllowOnUserGesture }, { "vst", AllowOnUserGesture }, { "vsw", AllowOnUserGesture }, { "ws", AllowOnUserGesture }, { "wsc", AllowOnUserGesture }, { "wsf", AllowOnUserGesture }, { "wsh", AllowOnUserGesture }, { "xbap", Dangerous }, #elif defined(OS_MACOSX) // TODO(thakis): Figure out what makes sense here -- crbug.com/19096 { "app", AllowOnUserGesture }, { "dmg", AllowOnUserGesture }, #elif defined(OS_POSIX) // TODO(estade): lengthen this list. { "bash", AllowOnUserGesture }, { "csh", AllowOnUserGesture }, { "deb", AllowOnUserGesture }, { "exe", AllowOnUserGesture }, { "ksh", AllowOnUserGesture }, { "rpm", AllowOnUserGesture }, { "sh", AllowOnUserGesture }, { "tcsh", AllowOnUserGesture }, #endif }; DownloadDangerLevel GetFileDangerLevel(const FilePath& path) { return GetFileExtensionDangerLevel(path.Extension()); } DownloadDangerLevel GetFileExtensionDangerLevel( const FilePath::StringType& extension) { if (extension.empty()) return NotDangerous; if (!IsStringASCII(extension)) return NotDangerous; #if defined(OS_WIN) std::string ascii_extension = WideToASCII(extension); #elif defined(OS_POSIX) std::string ascii_extension = extension; #endif // Strip out leading dot if it's still there if (ascii_extension[0] == FilePath::kExtensionSeparator) ascii_extension.erase(0, 1); for (size_t i = 0; i < arraysize(g_executables); ++i) { if (LowerCaseEqualsASCII(ascii_extension, g_executables[i].extension)) return g_executables[i].level; } return NotDangerous; } bool IsFileExtensionSafe(const FilePath::StringType& extension) { return GetFileExtensionDangerLevel(extension) == NotDangerous; } bool IsFileSafe(const FilePath& path) { return GetFileDangerLevel(path) == NotDangerous; } static const char* kExecutableWhiteList[] = { // JavaScript is just as powerful as EXE. "text/javascript", "text/javascript;version=*", "text/html", // Registry files can cause critical changes to the MS OS behavior. // Addition of this mimetype also addresses bug 7337. "text/x-registry", "text/x-sh", // Some sites use binary/octet-stream to mean application/octet-stream. // See http://code.google.com/p/chromium/issues/detail?id=1573 "binary/octet-stream" }; static const char* kExecutableBlackList[] = { // These application types are not executable. "application/*+xml", "application/xml" }; bool IsExecutableMimeType(const std::string& mime_type) { for (size_t i = 0; i < arraysize(kExecutableWhiteList); ++i) { if (net::MatchesMimeType(kExecutableWhiteList[i], mime_type)) return true; } for (size_t i = 0; i < arraysize(kExecutableBlackList); ++i) { if (net::MatchesMimeType(kExecutableBlackList[i], mime_type)) return false; } // We consider only other application types to be executable. return net::MatchesMimeType("application/*", mime_type); } } // namespace download_util
Tweak dangerous list based on (hopefully) final round of discussions. I think we have the balance about right now.
Tweak dangerous list based on (hopefully) final round of discussions. I think we have the balance about right now. BUG=67577 TEST=NONE Review URL: http://codereview.chromium.org/6035005 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@69916 0039d316-1c4b-4281-b951-d872f2087c98
C++
bsd-3-clause
ropik/chromium,Crystalnix/house-of-life-chromium,yitian134/chromium,gavinp/chromium,gavinp/chromium,yitian134/chromium,ropik/chromium,ropik/chromium,Crystalnix/house-of-life-chromium,Crystalnix/house-of-life-chromium,Crystalnix/house-of-life-chromium,Crystalnix/house-of-life-chromium,gavinp/chromium,ropik/chromium,yitian134/chromium,ropik/chromium,yitian134/chromium,gavinp/chromium,Crystalnix/house-of-life-chromium,Crystalnix/house-of-life-chromium,ropik/chromium,Crystalnix/house-of-life-chromium,yitian134/chromium,adobe/chromium,adobe/chromium,gavinp/chromium,Crystalnix/house-of-life-chromium,adobe/chromium,gavinp/chromium,gavinp/chromium,ropik/chromium,adobe/chromium,Crystalnix/house-of-life-chromium,yitian134/chromium,yitian134/chromium,adobe/chromium,gavinp/chromium,adobe/chromium,yitian134/chromium,adobe/chromium,adobe/chromium,ropik/chromium,ropik/chromium,gavinp/chromium,yitian134/chromium,gavinp/chromium,adobe/chromium,Crystalnix/house-of-life-chromium,yitian134/chromium,adobe/chromium,adobe/chromium
9106df53c6d24d3ad3800fe6a4006b9461c9fd8b
src/main.cpp
src/main.cpp
#include "sparse_matrix.hpp" // SparseMatrix #include "parser.hpp" // getRows, parsePuzzle int main(int argc, char **argv) { std::string puzzle = "-----------0-\n" "-----------00\n" "----00--0000-\n" "00000000000--\n" "00000000000--\n" "0000000000---\n" "00000000-----\n" "0000000------\n" "00---00------"; SparseMatrix sm(getRows(parsePuzzle(puzzle))); sm.findSolution(0); return 0; }
#include "sparse_matrix.hpp" // SparseMatrix #include "parser.hpp" // getRows, parsePuzzle constexpr char puzzle28[] = "-00--0000-\n" "00--000000\n" "00--000000\n" "000--00000\n" "00000--000\n" "000000--00\n" "000000--00\n" "-0000--00-"; constexpr char puzzle42[] = "-----------0-\n" "-----------00\n" "----00--0000-\n" "00000000000--\n" "00000000000--\n" "0000000000---\n" "00000000-----\n" "0000000------\n" "00---00------"; constexpr char puzzle54[] = "0000-0000\n" "000---000\n" "000---000\n" "00-----00\n" "000000000\n" "000000000\n" "000000000\n" "000000000"; int main(int argc, char **argv) { SparseMatrix sm(getRows(parsePuzzle(puzzle54))); sm.findSolution(0); return 0; } // TODO: Move pretty_print.py into here to deduplicate the puzzle.
Add more hardcoded puzzles and a TODO.
Add more hardcoded puzzles and a TODO.
C++
mit
altayhunter/Pentomino-Puzzle-Solver,altayhunter/Pentomino-Puzzle-Solver
4b38f232855ccbcceda710a4cb925db0bd3e04a4
src/neural/neuron.cpp
src/neural/neuron.cpp
#include "neural/neuron.hpp" /* * Neuron Class implementation */ // Constructors neural::Neuron::Neuron(const neural::activation_func *afunc): m_ineuron(new NeuronData(afunc)) { } neural::Neuron neural::Neuron::input_neuron() { return Neuron(&neural::af::zero); } // Getters double neural::Neuron::get_bias() const { return m_ineuron->bias; } double neural::Neuron::get_value() const { return m_ineuron->value; } // Setters void neural::Neuron::set_value(double value) { m_ineuron->value = value; } void neural::Neuron::set_bias(double bias) { m_ineuron->bias = bias; } void neural::Neuron::add_error(double error) { m_ineuron->error_buffer += error; } // Use void neural::Neuron::link(Neuron &from, double weight) { m_ineuron->inputs.push_back(std::make_pair(from.m_ineuron.get(), weight)); } void neural::Neuron::compute() { double x = m_ineuron->bias; for( auto p : m_ineuron->inputs ) { x += p.second * p.first->value; } m_ineuron->value_buffer = m_ineuron->afunc->first(x); double e = m_ineuron->error * m_ineuron->afunc->second(x); m_ineuron->bias += e; for( auto &p : m_ineuron->inputs ) { p.first->error += p.second * e; p.second += e * p.first->value; } } void neural::Neuron::sync() { m_ineuron->value = m_ineuron->value_buffer; m_ineuron->value_buffer = 0.0; m_ineuron->error = m_ineuron->error_buffer; m_ineuron->error_buffer = 0.0; }
#include "neural/neuron.hpp" /* * Neuron Class implementation */ // Constructors neural::Neuron::Neuron(const neural::activation_func *afunc): m_ineuron(new NeuronData(afunc)) { } neural::Neuron neural::Neuron::input_neuron() { return Neuron(&neural::af::zero); } // Getters double neural::Neuron::get_bias() const { return m_ineuron->bias; } double neural::Neuron::get_value() const { return m_ineuron->value; } // Setters void neural::Neuron::set_value(double value) { m_ineuron->value = value; } void neural::Neuron::set_bias(double bias) { m_ineuron->bias = bias; } void neural::Neuron::add_error(double error) { m_ineuron->error_buffer += error; } // Use void neural::Neuron::link(Neuron &from, double weight) { m_ineuron->inputs.push_back(std::make_pair(from.m_ineuron.get(), weight)); } void neural::Neuron::compute() { double x = m_ineuron->bias; for( auto p : m_ineuron->inputs ) { x += p.second * p.first->value; } m_ineuron->value_buffer = m_ineuron->afunc->first(x); double e = m_ineuron->error * m_ineuron->afunc->second(x); m_ineuron->bias += e; for( auto &p : m_ineuron->inputs ) { p.first->error_buffer += p.second * e; p.second += e * p.first->value; } } void neural::Neuron::sync() { m_ineuron->value = m_ineuron->value_buffer; m_ineuron->value_buffer = 0.0; m_ineuron->error = m_ineuron->error_buffer; m_ineuron->error_buffer = 0.0; }
fix learning computation.
neural: fix learning computation. Signed-off-by: Victor Berger <[email protected]>
C++
mit
vberger/BrainVolve
732c223167396aa84870cfad0d739247668c9dbf
src/main.cpp
src/main.cpp
//Includes all the headers necessary to use the most common public pieces of the ROS system. #include <ros/ros.h> //Use image_transport for publishing and subscribing to images in ROS #include <image_transport/image_transport.h> //Use cv_bridge to convert between ROS and OpenCV Image formats #include <cv_bridge/cv_bridge.h> //Include some useful constants for image encoding. Refer to: http://www.ros.org/doc/api/sensor_msgs/html/namespacesensor__msgs_1_1image__encodings.html for more info. #include <sensor_msgs/image_encodings.h> //Include headers for OpenCV Image processing #include <opencv2/imgproc/imgproc.hpp> //Include headers for OpenCV GUI handling #include <opencv2/highgui/highgui.hpp> #include <geometry_msgs/Twist.h> //Store all constants for image encodings in the enc namespace to be used later. namespace enc = sensor_msgs::image_encodings; //Declare a string with the name of the window that we will create using OpenCV where processed images will be displayed. static const char WINDOW[] = "Image Processed"; ros::Publisher pub; //This function is called everytime a new image is published void imageCallback(const sensor_msgs::ImageConstPtr& original_image) { //Convert from the ROS image message to a CvImage suitable for working with OpenCV for processing cv_bridge::CvImagePtr cv_ptr; try { //Always copy, returning a mutable CvImage //OpenCV expects color images to use BGR channel order. cv_ptr = cv_bridge::toCvCopy(original_image, enc::BGR8); } catch (cv_bridge::Exception& e) { //if there is an error during conversion, display it ROS_ERROR("tutorialROSOpenCV::main.cpp::cv_bridge exception: %s", e.what()); return; } // Rotate 90 deg CCW cv::transpose(cv_ptr->image, cv_ptr->image); cv::flip(cv_ptr->image, cv_ptr->image, 0); int width = cv_ptr->image.size().width; int height = cv_ptr->image.size().height; // The code below is from: http://docs.opencv.org/2.4/doc/tutorials/imgproc/imgtrans/hough_lines/hough_lines.html cv::Mat dst, cdst; cv::Canny(cv_ptr->image, dst, 50, 200, 3); cv::cvtColor(dst, cdst, CV_GRAY2BGR); std::vector<cv::Vec4i> lines; cv::HoughLinesP(dst, lines, 1, CV_PI/180, 20, 20, 5 ); long int sum = 0; float avg; for( size_t i = 0; i < lines.size(); i++ ) { cv::Vec4i l = lines[i]; line( cdst, cv::Point(l[0], l[1]), cv::Point(l[2], l[3]), cv::Scalar(0,0,255), 3, CV_AA); sum += ((l[0] + l[2]) - width) / 2; } if (lines.size() > 0) { avg = (sum / (float)lines.size()) / (float)(width / 2); //ROS_INFO("angle = %f\n", avg); geometry_msgs::Twist msg; msg.linear.x = 1.0; msg.angular.x = avg; pub.publish(msg); } cv::imshow("source", cv_ptr->image); cv::imshow("detected lines", cdst); //Display the image using OpenCV //cv::imshow(WINDOW, cv_ptr->image); //Add some delay in miliseconds. The function only works if there is at least one HighGUI window created and the window is active. If there are several HighGUI windows, any of them can be active. cv::waitKey(3); } /** * This tutorial demonstrates simple image conversion between ROS image message and OpenCV formats and image processing */ int main(int argc, char **argv) { /** * The ros::init() function needs to see argc and argv so that it can perform * any ROS arguments and name remapping that were provided at the command line. For programmatic * remappings you can use a different version of init() which takes remappings * directly, but for most command-line programs, passing argc and argv is the easiest * way to do it. The third argument to init() is the name of the node. Node names must be unique in a running system. * The name used here must be a base name, ie. it cannot have a / in it. * You must call one of the versions of ros::init() before using any other * part of the ROS system. */ ros::init(argc, argv, "image_processor"); ros::NodeHandle nh; pub = nh.advertise<geometry_msgs::Twist>("cmd_vel", 1000); //Create an ImageTransport instance, initializing it with our NodeHandle. image_transport::ImageTransport it(nh); //OpenCV HighGUI call to create a display window on start-up. cv::namedWindow(WINDOW, CV_WINDOW_AUTOSIZE); image_transport::TransportHints hints("compressed", ros::TransportHints()); image_transport::Subscriber sub = it.subscribe("camera/image", 1, imageCallback, hints); //OpenCV HighGUI call to destroy a display window on shut-down. cv::destroyWindow(WINDOW); /** * In this application all user callbacks will be called from within the ros::spin() call. * ros::spin() will not return until the node has been shutdown, either through a call * to ros::shutdown() or a Ctrl-C. */ ros::spin(); //ROS_INFO is the replacement for printf/cout. ROS_INFO("tutorialROSOpenCV::main.cpp::No error."); }
//Includes all the headers necessary to use the most common public pieces of the ROS system. #include <ros/ros.h> //Use image_transport for publishing and subscribing to images in ROS #include <image_transport/image_transport.h> //Use cv_bridge to convert between ROS and OpenCV Image formats #include <cv_bridge/cv_bridge.h> //Include some useful constants for image encoding. Refer to: http://www.ros.org/doc/api/sensor_msgs/html/namespacesensor__msgs_1_1image__encodings.html for more info. #include <sensor_msgs/image_encodings.h> //Include headers for OpenCV Image processing #include <opencv2/imgproc/imgproc.hpp> //Include headers for OpenCV GUI handling #include <opencv2/highgui/highgui.hpp> #include <geometry_msgs/Twist.h> //Store all constants for image encodings in the enc namespace to be used later. namespace enc = sensor_msgs::image_encodings; //Declare a string with the name of the window that we will create using OpenCV where processed images will be displayed. static const char WINDOW[] = "Image Processed"; ros::Publisher pub; void deletetopblob(cv::Mat *src, cv::Mat *dest) { uchar *p, *q; for(int i=0; i < src->rows; i++) { p = src->ptr<uchar>(i); q = dest->ptr<uchar>(i); if (p[0] && p[src->cols-1]) { break; // stop at first non-black line } for(int j=0; j < src->cols; j++) { // left to right if (!p[j]) { for (int k=0; k < dest->channels(); k++) { //ROS_INFO("%d\n", p[j+k]); q[j+k] = 255; } } else { break; // stop at first non-black pixel in column } } for(int j = src->cols-1; j>=0; j--) { // right to left (shameless code-duplication) if (!p[j]) { for (int k=0; k < dest->channels(); k++) { //ROS_INFO("%d\n", p[j+k]); q[j+k] = 255; } } else { break; // stop at first non-black pixel in column } } } } //This function is called everytime a new image is published void imageCallback(const sensor_msgs::ImageConstPtr& original_image) { //Convert from the ROS image message to a CvImage suitable for working with OpenCV for processing cv_bridge::CvImagePtr cv_ptr; try { //Always copy, returning a mutable CvImage //OpenCV expects color images to use BGR channel order. cv_ptr = cv_bridge::toCvCopy(original_image, enc::BGR8); } catch (cv_bridge::Exception& e) { //if there is an error during conversion, display it ROS_ERROR("tutorialROSOpenCV::main.cpp::cv_bridge exception: %s", e.what()); return; } // Rotate 90 deg CCW cv::transpose(cv_ptr->image, cv_ptr->image); cv::flip(cv_ptr->image, cv_ptr->image, 0); int width = cv_ptr->image.size().width; int height = cv_ptr->image.size().height; // The code below is from: http://docs.opencv.org/2.4/doc/tutorials/imgproc/imgtrans/hough_lines/hough_lines.html cv::Mat dst, cdst, wew, gray; cv::cvtColor(cv_ptr->image, gray, CV_BGR2GRAY); cv::threshold(gray, wew, 0, 255, cv::THRESH_BINARY + cv::THRESH_OTSU); deletetopblob(&wew, &gray); cv::Canny(gray, dst, 50, 200, 3); cv::cvtColor(dst, cdst, CV_GRAY2BGR); std::vector<cv::Vec4i> lines; cv::HoughLinesP(dst, lines, 1, CV_PI/180, 20, 20, 5 ); long int sum = 0; float avg; for( size_t i = 0; i < lines.size(); i++ ) { cv::Vec4i l = lines[i]; line( cdst, cv::Point(l[0], l[1]), cv::Point(l[2], l[3]), cv::Scalar(0,0,255), 3, CV_AA); sum += ((l[0] + l[2]) - width) / 2; } if (lines.size() > 0) { avg = (sum / (float)lines.size()) / (float)(width / 2); //ROS_INFO("angle = %f\n", avg); geometry_msgs::Twist msg; msg.linear.x = 0.6; msg.angular.z = avg * 0.5; pub.publish(msg); } cv::imshow("source", cv_ptr->image); cv::imshow("detected lines", cdst); cv::imshow("wew", wew); cv::imshow("gray", gray); //Display the image using OpenCV //cv::imshow(WINDOW, cv_ptr->image); //Add some delay in miliseconds. The function only works if there is at least one HighGUI window created and the window is active. If there are several HighGUI windows, any of them can be active. cv::waitKey(3); } /** * This tutorial demonstrates simple image conversion between ROS image message and OpenCV formats and image processing */ int main(int argc, char **argv) { /** * The ros::init() function needs to see argc and argv so that it can perform * any ROS arguments and name remapping that were provided at the command line. For programmatic * remappings you can use a different version of init() which takes remappings * directly, but for most command-line programs, passing argc and argv is the easiest * way to do it. The third argument to init() is the name of the node. Node names must be unique in a running system. * The name used here must be a base name, ie. it cannot have a / in it. * You must call one of the versions of ros::init() before using any other * part of the ROS system. */ ros::init(argc, argv, "image_processor"); ros::NodeHandle nh; pub = nh.advertise<geometry_msgs::Twist>("cmd_vel", 1000); //Create an ImageTransport instance, initializing it with our NodeHandle. image_transport::ImageTransport it(nh); //OpenCV HighGUI call to create a display window on start-up. cv::namedWindow(WINDOW, CV_WINDOW_AUTOSIZE); image_transport::TransportHints hints("compressed", ros::TransportHints()); image_transport::Subscriber sub = it.subscribe("camera/image", 1, imageCallback, hints); //OpenCV HighGUI call to destroy a display window on shut-down. cv::destroyWindow(WINDOW); /** * In this application all user callbacks will be called from within the ros::spin() call. * ros::spin() will not return until the node has been shutdown, either through a call * to ros::shutdown() or a Ctrl-C. */ ros::spin(); //ROS_INFO is the replacement for printf/cout. ROS_INFO("tutorialROSOpenCV::main.cpp::No error."); }
Add image separation
Add image separation
C++
mit
grappigegovert/ROS-linerider
0c21729b8ed145035ee8b0848b6de5b47caf30b0
src/main.cpp
src/main.cpp
#include <iostream> #include <string> #include <vector> #include <chrono> #include "io.h" #include "pattern_search.h" using std::cout; using std::string; using std::vector; const int cPatternMaxLength = 128; const int cNRuns = 100; void printUsage() { cout << "Usage: PatternSearchApp path pattern\n" << "Arguments:\n" << "path\t: path to a file or folder\n" << "pattern\t: pattern to be searched for (max " + std::to_string(cPatternMaxLength) + " characters)\n"; } int main(int argc, char *argv[]) { if (argc != 3) { printUsage(); return EXIT_FAILURE; } string path(argv[1]); string pattern(argv[2]); if (!isDir(path) && !isFile(path)) { cout << "The first argument is not a file or a directory.\n"; printUsage(); return EXIT_FAILURE; } if (pattern.size() > cPatternMaxLength) { cout << "Pattern longer than specified maximum length.\n"; printUsage(); return EXIT_FAILURE; } vector<string> output; auto begin = std::chrono::high_resolution_clock::now(); for (int i = 0; i < cNRuns; i++) { output.clear(); findPatternInFileOrDirectory(pattern, path, &output); } auto end = std::chrono::high_resolution_clock::now(); cout << "Runtime: " << std::chrono::duration_cast<std::chrono::milliseconds>( end - begin).count() / double(cNRuns) << "ms averaged over " << cNRuns << " runs\n"; for (const auto& line : output) { cout << line << "\n"; } }
#include <iostream> #include <string> #include <vector> #include <chrono> #include "io_utils.h" #include "pattern_search.h" using std::cout; using std::string; using std::vector; const int cPatternMaxLength = 128; const int cNRuns = 100; void printUsage() { cout << "Usage: PatternSearchApp path pattern\n" << "Arguments:\n" << "path\t: path to a file or folder\n" << "pattern\t: pattern to be searched for (max " + std::to_string(cPatternMaxLength) + " characters)\n"; } int main(int argc, char *argv[]) { if (argc != 3) { printUsage(); return EXIT_FAILURE; } string path(argv[1]); string pattern(argv[2]); if (!isDir(path) && !isFile(path)) { cout << "The first argument is not a file or a directory.\n"; printUsage(); return EXIT_FAILURE; } if (pattern.size() > cPatternMaxLength) { cout << "Pattern longer than specified maximum length.\n"; printUsage(); return EXIT_FAILURE; } vector<string> output; auto begin = std::chrono::high_resolution_clock::now(); for (int i = 0; i < cNRuns; i++) { output.clear(); findPatternInFileOrDirectory(pattern, path, &output); } auto end = std::chrono::high_resolution_clock::now(); cout << "Runtime: " << std::chrono::duration_cast<std::chrono::milliseconds>( end - begin).count() / double(cNRuns) << "ms averaged over " << cNRuns << " runs\n"; for (const auto& line : output) { cout << line << "\n"; } }
Fix include typo
Fix include typo
C++
bsd-3-clause
fsrajer/eset-challenge
cabf50bce6465b8329ee9b650c928dbea95ccef2
src/main.cpp
src/main.cpp
#include <common.h> #include <Parser.h> #include <Tokenizer.h> #include <TextLoader.h> #include <PatternMatch.h> #include <Configuration.h> #include <ErrorProcessor.h> #include <PatternsFileProcessor.h> using namespace Lspl; using namespace Lspl::Text; using namespace Lspl::Parser; using namespace Lspl::Pattern; using namespace Lspl::Configuration; int main( int argc, const char* argv[] ) { try { if( argc != 4 ) { cerr << "Usage: lspl2 CONFIGURATION PATTERNS TEXT" << endl; return 1; } CConfigurationPtr conf = LoadConfigurationFromFile( argv[1], cerr, cout ); if( !static_cast<bool>( conf ) ) { return 1; } CErrorProcessor errorProcessor; CPatternsBuilder patternsBuilder( conf, errorProcessor ); patternsBuilder.Read( argv[2] ); patternsBuilder.Check(); if( errorProcessor.HasAnyErrors() ) { errorProcessor.PrintErrors( cerr, argv[2] ); return 1; } const CPatterns patterns = patternsBuilder.Save(); patterns.Print( cout ); CWords words; LoadText( patterns, argv[3], words ); CText text( move( words ) ); for( TReference ref = 0; ref < patterns.Size(); ref++ ) { const CPattern& pattern = patterns.Pattern( ref ); cout << pattern.Name() << endl; CStates states; { CPatternBuildContext buildContext( patterns ); CPatternVariants variants; pattern.Build( buildContext, variants, 12 ); states = move( variants.Build( patterns ) ); } { CMatchContext matchContext( text, states ); for( TWordIndex wi = 0; wi < text.Length(); wi++ ) { matchContext.Match( wi ); } } cout << endl; } } catch( exception& e ) { cerr << e.what() << endl; return 1; } catch( ... ) { cerr << "unknown error!"; return 1; } return 0; }
#include <common.h> #include <Parser.h> #include <Tokenizer.h> #include <TextLoader.h> #include <PatternMatch.h> #include <Configuration.h> #include <ErrorProcessor.h> #include <PatternsFileProcessor.h> using namespace Lspl; using namespace Lspl::Text; using namespace Lspl::Parser; using namespace Lspl::Pattern; using namespace Lspl::Configuration; int main( int argc, const char* argv[] ) { try { if( argc != 4 ) { cerr << "Usage: lspl2 CONFIGURATION PATTERNS TEXT" << endl; return 1; } CConfigurationPtr conf = LoadConfigurationFromFile( argv[1], cerr, cout ); if( !static_cast<bool>( conf ) ) { return 1; } CErrorProcessor errorProcessor; CPatternsBuilder patternsBuilder( conf, errorProcessor ); patternsBuilder.Read( argv[2] ); patternsBuilder.Check(); if( errorProcessor.HasAnyErrors() ) { errorProcessor.PrintErrors( cerr, argv[2] ); return 1; } const CPatterns patterns = patternsBuilder.Save(); patterns.Print( cout ); CWords words; LoadText( patterns, argv[3], words ); CText text( move( words ) ); for( TReference ref = 0; ref < patterns.Size(); ref++ ) { const CPattern& pattern = patterns.Pattern( ref ); cout << pattern.Name() << endl; CStates states; { CPatternBuildContext buildContext( patterns ); CPatternVariants variants; pattern.Build( buildContext, variants, 12 ); variants.Print( patterns, cout ); states = move( variants.Build( patterns ) ); } { CMatchContext matchContext( text, states ); for( TWordIndex wi = 0; wi < text.Length(); wi++ ) { matchContext.Match( wi ); } } cout << endl; } } catch( exception& e ) { cerr << e.what() << endl; return 1; } catch( ... ) { cerr << "unknown error!"; return 1; } return 0; }
print variants in main
print variants in main
C++
mit
al-pacino/LSPL-3,al-pacino/LSPL-2,al-pacino/LSPL-2,al-pacino/LSPL-3
27ac0766b6e54b7247511b53370f87429be71b96
src/main.cpp
src/main.cpp
/* * Copyright (C) 2015 juztamau5 * * 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 <cstdio> int main(int argc, const char* argv[]) { std::printf("Hello world\n"); }
/* * Copyright (C) 2015 juztamau5 * * 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 "ipfs.h" #include <sstream> #include <string> int main(int argc, const char* argv[]) { std::stringstream args; for (int i = 0; i < argc; i++) { args << argv[i]; if (i + 1 != argc) args << " "; } std::string strArgs(args.str()); GoString str; str.p = const_cast<char*>(strArgs.c_str()); str.n = static_cast<GoInt>(strArgs.length()); runMain(str); return 0; }
Implement main() function that forwards cmd args to go-ipfs
Implement main() function that forwards cmd args to go-ipfs
C++
mit
juztamau5/libipfs,juztamau5/libipfs
2435f0510c86cff25455b5d3b59f82dcbfb25981
src/main.cpp
src/main.cpp
#include <fstream> #include "vec3.h" using namespace std; int main() { int nx = 200; int ny = 100; ofstream myfile; myfile.open ("image.ppm"); myfile << "P3\n" << nx << " " << ny << "\n255\n"; for (int j = ny-1; j >= 0 ; j--) { for (int i = 0; i < nx; i++) { float r = float(i) / float(nx); float g = float(j) / float(ny); float b = 0.2; int ir = int(255.99 * r); int ig = int(255.99 * g); int ib = int(255.99 * b); myfile << ir << " " << ig << " " << ib << "\n"; } } myfile.close(); }
#include <fstream> #include "vec3.h" using namespace std; int main() { int nx = 200; int ny = 100; ofstream myfile; myfile.open ("image.ppm"); myfile << "P3\n" << nx << " " << ny << "\n255\n"; for (int j = ny-1; j >= 0 ; j--) { for (int i = 0; i < nx; i++) { vec3 col(float(i) / float(nx), float(j) / float(ny), 0.2); int ir = int(255.99 * col[0]); int ig = int(255.99 * col[1]); int ib = int(255.99 * col[2]); myfile << ir << " " << ig << " " << ib << "\n"; } } myfile.close(); }
Update main to use vector
Update main to use vector
C++
mit
corragon/cpp-raytracer
e55763d72e42b44d7f6ab16f5259ecabc26fd950
src/main.cpp
src/main.cpp
#include <iostream> #include <thread> #include <time.h> #define STB_IMAGE_WRITE_IMPLEMENTATION #include "../sdk/stb/stb_image_write.h" // おおよそ30秒毎に、レンダリングの途中経過をbmpかpngで連番(000.png, 001.png, ...) で出力してください。 // 4分33秒以内に自動で終了してください。 #define WIDTH 256 #define HEIGHT 256 #define OUTPUT_INTERVAL 30 #define FINISH_TIME (0 * 60 + 33) //#define FINISH_TIME (4 * 60 + 33) #define FINISH_MARGIN 2 void save(const char *data, const char *filename) { int w = WIDTH; int h = HEIGHT; int comp = 3; // RGB int stride_in_bytes = 3 * w; int result = stbi_write_png(filename, w, h, comp, data, stride_in_bytes); } int main() { time_t t0 = time(NULL); time_t t_last = 0; int count = 0; // frame buffer の初期化 int current = 0; char *fb[2]; fb[0] = new char[3 * WIDTH * HEIGHT]; fb[1] = new char[3 * WIDTH * HEIGHT]; char *fb0 = fb[0], *fb1 = fb[1]; for (int i = 0; i < 3 * WIDTH * HEIGHT; i++) { fb0[i] = fb1[i] = 0; } do { // fb[current] にレンダリング std::this_thread::sleep_for(std::chrono::seconds(1)); time_t t = time(NULL) - t0; // 30 秒ごとに出力 int c = t / OUTPUT_INTERVAL; if (count < c) { current = 1 - current; char *dest = fb[current]; char *src = fb[1 - current]; for (int i = 0; i < 3 * WIDTH * HEIGHT; i++) { dest[i] = src[i]; } char filename[256]; snprintf(filename, 256, "%d.png", c); save(fb[1 - current], filename); count++; } // 4分33秒以内に終了なので、前のフレームを考えてオーバーしそうならば終了する if (FINISH_TIME - FINISH_MARGIN <= t + (t - t_last)) break; t_last = t; }while (true); delete[] fb[0]; delete[] fb[1]; return 0; }
#include <iostream> #include <thread> #include <time.h> #define STB_IMAGE_WRITE_IMPLEMENTATION #include "../sdk/stb/stb_image_write.h" // おおよそ30秒毎に、レンダリングの途中経過をbmpかpngで連番(000.png, 001.png, ...) で出力してください。 // 4分33秒以内に自動で終了してください。 #define WIDTH 256 #define HEIGHT 256 #define OUTPUT_INTERVAL 30 #define FINISH_TIME (0 * 60 + 33) //#define FINISH_TIME (4 * 60 + 33) #define FINISH_MARGIN 2 void save(const char *data, const char *filename) { int w = WIDTH; int h = HEIGHT; int comp = 3; // RGB int stride_in_bytes = 3 * w; int result = stbi_write_png(filename, w, h, comp, data, stride_in_bytes); } int main() { time_t t0 = time(NULL); time_t t_last = 0; int count = 0; // frame buffer の初期化 int current = 0; char *fb[2]; fb[0] = new char[3 * WIDTH * HEIGHT]; fb[1] = new char[3 * WIDTH * HEIGHT]; char *fb0 = fb[0], *fb1 = fb[1]; #pragma omp parallel for for (int i = 0; i < 3 * WIDTH * HEIGHT; i++) { fb0[i] = fb1[i] = 0; } do { // fb[current] にレンダリング std::this_thread::sleep_for(std::chrono::seconds(1)); time_t t = time(NULL) - t0; // 30 秒ごとに出力 int c = t / OUTPUT_INTERVAL; if (count < c) { current = 1 - current; char *dest = fb[current]; char *src = fb[1 - current]; #pragma omp parallel for for (int i = 0; i < 3 * WIDTH * HEIGHT; i++) { dest[i] = src[i]; } char filename[256]; snprintf(filename, 256, "%d.png", c); save(fb[1 - current], filename); count++; } // 4分33秒以内に終了なので、前のフレームを考えてオーバーしそうならば終了する if (FINISH_TIME - FINISH_MARGIN <= t + (t - t_last)) break; t_last = t; }while (true); delete[] fb[0]; delete[] fb[1]; return 0; }
Update main.cpp
Update main.cpp
C++
mit
imagirelab/raytracingcamp5,imagirelab/raytracingcamp5,imagirelab/raytracingcamp5
f17fea0a83defa931681483de6877bd8e58a7707
src/pass/place_device.cc
src/pass/place_device.cc
/*! * Copyright (c) 2016 by Contributors * \file place_device.cc * \brief Inference the device of each operator given known information. * Insert a copy node automatically when there is a cross device. */ #include <nnvm/pass.h> #include <nnvm/op_attr_types.h> #include <nnvm/graph_attr_types.h> namespace nnvm { namespace pass { namespace { // simply logic to place device according to device_group hint // insert copy node when there is Graph PlaceDevice(Graph src) { CHECK_NE(src.attrs.count("device_group_attr_key"), 0) << "Need graph attribute \"device_group_attr_key\" in PlaceDevice"; CHECK_NE(src.attrs.count("device_assign_map"), 0) << "Need graph attribute \"device_assign_map\" in PlaceDevice"; CHECK_NE(src.attrs.count("device_copy_op"), 0) << "Need graph attribute \"device_copy_op\" in PlaceDevice"; std::string device_group_attr_key = src.GetAttr<std::string>("device_group_attr_key"); const Op* copy_op = Op::Get(src.GetAttr<std::string>("device_copy_op")); auto& device_assign_map = src.GetAttr<DeviceAssignMap>("device_assign_map"); const IndexedGraph& idx = src.indexed_graph(); DeviceVector device; // copy on write semanatics if (src.attrs.count("device") != 0) { device = src.MoveCopyAttr<DeviceVector>("device"); CHECK_EQ(device.size(), idx.num_nodes()); } else { device.resize(idx.num_nodes(), -1); } // forward pass for (uint32_t nid = 0; nid < idx.num_nodes(); ++nid) { const auto& inode = idx[nid]; auto it = inode.source->attrs.dict.find(device_group_attr_key); if (it != inode.source->attrs.dict.end()) { const std::string& device_group = it->second; auto dit = device_assign_map.find(device_group); CHECK(dit != device_assign_map.end()) << "The device assignment not found for group " << device_group; device[nid] = dit->second; } else { for (const IndexedGraph::NodeEntry& e : inode.inputs) { if (device[e.node_id] != -1) { device[nid] = device[e.node_id]; break; } } } } // backward pass for (uint32_t i = idx.num_nodes(); i != 0; --i) { uint32_t nid = i - 1; const auto& inode = idx[nid]; if (device[nid] == -1) continue; for (const IndexedGraph::NodeEntry& e : inode.inputs) { if (device[e.node_id] == -1) device[e.node_id] = device[nid]; } } int num_dev = 1, other_dev_id = -1; for (int& dev : device) { if (dev == -1) dev = 0; if (dev != other_dev_id) { if (other_dev_id != -1) ++num_dev; other_dev_id = dev; } } if (num_dev == 1) { src.attrs.erase("device_group_attr_key"); src.attrs.erase("device_assign_map"); src.attrs.erase("device_copy_op"); src.attrs["device"] = std::make_shared<any>(std::move(device)); return src; } std::map<std::tuple<uint32_t, uint32_t, int>, NodePtr> copy_map; std::vector<NodePtr> new_node_map(idx.num_nodes(), nullptr); std::unordered_map<const Node*, int> new_device_map; static auto& fmutate_inputs = Op::GetAttr<FMutateInputs>("FMutateInputs"); // insert copy node for (uint32_t nid = 0; nid < idx.num_nodes(); ++nid) { int dev_id = device[nid]; const auto& inode = idx[nid]; // check if mutation is needed bool need_mutate = false; if (!inode.source->is_variable() && fmutate_inputs.count(inode.source->op())) { for (uint32_t index : fmutate_inputs[inode.source->op()](inode.source->attrs)) { auto e = inode.inputs[index]; if (new_node_map[e.node_id] != nullptr || dev_id != device[e.node_id]) { LOG(FATAL) << " mutable state cannot go across device" << " op=" << inode.source->op()->name << " input_state_index=" << index; } } } for (const IndexedGraph::NodeEntry& e : inode.inputs) { if (new_node_map[e.node_id] != nullptr || dev_id != device[e.node_id]) { need_mutate = true; break; } } if (!need_mutate) { for (const uint32_t cid : inode.control_deps) { if (new_node_map[cid] != nullptr) { need_mutate = true; break; } } } if (inode.source->is_variable()) { CHECK(!need_mutate) << "consistency check"; } if (need_mutate) { NodePtr new_node = Node::Create(); new_node->attrs = inode.source->attrs; new_node->inputs.reserve(inode.inputs.size()); for (size_t i = 0; i < inode.inputs.size(); ++i) { const IndexedGraph::NodeEntry& e = inode.inputs[i]; if (dev_id != device[e.node_id]) { auto copy_key = std::make_tuple(e.node_id, e.index, dev_id); auto it = copy_map.find(copy_key); if (it != copy_map.end() && it->first == copy_key) { new_node->inputs.emplace_back( NodeEntry{it->second, 0, 0}); } else { NodePtr copy_node = Node::Create(); std::ostringstream os; os << inode.source->inputs[i].node->attrs.name << "_" << e.index <<"_copy"; copy_node->attrs.op = copy_op; copy_node->attrs.name = os.str(); if (new_node_map[e.node_id] != nullptr) { copy_node->inputs.emplace_back( NodeEntry{new_node_map[e.node_id], e.index, 0}); } else { copy_node->inputs.push_back(inode.source->inputs[i]); } if (copy_node->attrs.op->attr_parser != nullptr) { copy_node->attrs.op->attr_parser(&(copy_node->attrs)); } copy_map[copy_key] = copy_node; new_device_map[copy_node.get()] = dev_id; new_node->inputs.emplace_back( NodeEntry{std::move(copy_node), 0, 0}); } } else { if (new_node_map[e.node_id] != nullptr) { new_node->inputs.emplace_back( NodeEntry{new_node_map[e.node_id], e.index, 0}); } else { new_node->inputs.push_back(inode.source->inputs[i]); } } } new_node->control_deps.reserve(inode.control_deps.size()); for (size_t i = 0; i < inode.control_deps.size(); ++i) { uint32_t cid = inode.control_deps[i]; if (new_node_map[cid] != nullptr) { new_node->control_deps.push_back(new_node_map[cid]); } else { new_node->control_deps.push_back(inode.source->control_deps[i]); } } new_device_map[new_node.get()] = dev_id; new_node_map[nid] = std::move(new_node); } else { new_device_map[inode.source] = dev_id; } } // make the new graph Graph ret; for (const NodeEntry& e : src.outputs) { if (new_node_map[idx.node_id(e.node.get())] != nullptr) { ret.outputs.emplace_back( NodeEntry{new_node_map[idx.node_id(e.node.get())], e.index, e.version}); } else { ret.outputs.emplace_back(e); } } DeviceVector new_device_vec(ret.indexed_graph().num_nodes()); for (uint32_t nid = 0; nid < ret.indexed_graph().num_nodes(); ++nid) { auto source = ret.indexed_graph()[nid].source; if (new_device_map.count(source) == 0) { LOG(FATAL) << "canot find " << source; } new_device_vec[nid] = new_device_map.at(source); } ret.attrs["device"] = std::make_shared<any>(std::move(new_device_vec)); return ret; } NNVM_REGISTER_PASS(PlaceDevice) .describe("Infer the device type of each operator."\ "Insert a copy node when there is cross device copy") .set_body(PlaceDevice) .set_change_graph(true) .provide_graph_attr("device") .depend_graph_attr("device_group_attr_key") .depend_graph_attr("device_assign_map") .depend_graph_attr("device_copy_op"); DMLC_JSON_ENABLE_ANY(DeviceAssignMap, dict_str_int); } // namespace } // namespace pass } // namespace nnvm
/*! * Copyright (c) 2016 by Contributors * \file place_device.cc * \brief Inference the device of each operator given known information. * Insert a copy node automatically when there is a cross device. */ #include <nnvm/pass.h> #include <nnvm/op_attr_types.h> #include <nnvm/graph_attr_types.h> namespace nnvm { namespace pass { namespace { // simply logic to place device according to device_group hint // insert copy node when there is Graph PlaceDevice(Graph src) { CHECK_NE(src.attrs.count("device_group_attr_key"), 0) << "Need graph attribute \"device_group_attr_key\" in PlaceDevice"; CHECK_NE(src.attrs.count("device_assign_map"), 0) << "Need graph attribute \"device_assign_map\" in PlaceDevice"; CHECK_NE(src.attrs.count("device_copy_op"), 0) << "Need graph attribute \"device_copy_op\" in PlaceDevice"; std::string device_group_attr_key = src.GetAttr<std::string>("device_group_attr_key"); const Op* copy_op = Op::Get(src.GetAttr<std::string>("device_copy_op")); auto& device_assign_map = src.GetAttr<DeviceAssignMap>("device_assign_map"); const IndexedGraph& idx = src.indexed_graph(); static auto& is_backward = Op::GetAttr<TIsBackward>("TIsBackward"); DeviceVector device; // copy on write semanatics if (src.attrs.count("device") != 0) { device = src.MoveCopyAttr<DeviceVector>("device"); CHECK_EQ(device.size(), idx.num_nodes()); } else { device.resize(idx.num_nodes(), -1); } // forward pass for (uint32_t nid = 0; nid < idx.num_nodes(); ++nid) { const auto& inode = idx[nid]; auto it = inode.source->attrs.dict.find(device_group_attr_key); if (it != inode.source->attrs.dict.end()) { const std::string& device_group = it->second; auto dit = device_assign_map.find(device_group); CHECK(dit != device_assign_map.end()) << "The device assignment not found for group " << device_group; device[nid] = dit->second; } else { if (!inode.source->is_variable() && is_backward.get(inode.source->op(), false)) { if (device[inode.control_deps[0]] != -1) { device[nid] = device[inode.control_deps[0]]; } } else { for (const IndexedGraph::NodeEntry& e : inode.inputs) { if (device[e.node_id] != -1) { device[nid] = device[e.node_id]; break; } } } } } // backward pass for (uint32_t i = idx.num_nodes(); i != 0; --i) { uint32_t nid = i - 1; const auto& inode = idx[nid]; if (device[nid] == -1) continue; for (const IndexedGraph::NodeEntry& e : inode.inputs) { if (device[e.node_id] == -1) device[e.node_id] = device[nid]; } } int num_dev = 1, other_dev_id = -1; for (int& dev : device) { if (dev == -1) dev = 0; if (dev != other_dev_id) { if (other_dev_id != -1) ++num_dev; other_dev_id = dev; } } if (num_dev == 1) { src.attrs.erase("device_group_attr_key"); src.attrs.erase("device_assign_map"); src.attrs.erase("device_copy_op"); src.attrs["device"] = std::make_shared<any>(std::move(device)); return src; } std::map<std::tuple<uint32_t, uint32_t, int>, NodePtr> copy_map; std::vector<NodePtr> new_node_map(idx.num_nodes(), nullptr); std::unordered_map<const Node*, int> new_device_map; static auto& fmutate_inputs = Op::GetAttr<FMutateInputs>("FMutateInputs"); // insert copy node for (uint32_t nid = 0; nid < idx.num_nodes(); ++nid) { int dev_id = device[nid]; const auto& inode = idx[nid]; // check if mutation is needed bool need_mutate = false; if (!inode.source->is_variable() && fmutate_inputs.count(inode.source->op())) { for (uint32_t index : fmutate_inputs[inode.source->op()](inode.source->attrs)) { auto e = inode.inputs[index]; if (new_node_map[e.node_id] != nullptr || dev_id != device[e.node_id]) { LOG(FATAL) << " mutable state cannot go across device" << " op=" << inode.source->op()->name << " input_state_index=" << index; } } } for (const IndexedGraph::NodeEntry& e : inode.inputs) { if (new_node_map[e.node_id] != nullptr || dev_id != device[e.node_id]) { need_mutate = true; break; } } if (!need_mutate) { for (const uint32_t cid : inode.control_deps) { if (new_node_map[cid] != nullptr) { need_mutate = true; break; } } } if (inode.source->is_variable()) { CHECK(!need_mutate) << "consistency check"; } if (need_mutate) { NodePtr new_node = Node::Create(); new_node->attrs = inode.source->attrs; new_node->inputs.reserve(inode.inputs.size()); for (size_t i = 0; i < inode.inputs.size(); ++i) { const IndexedGraph::NodeEntry& e = inode.inputs[i]; if (dev_id != device[e.node_id]) { auto copy_key = std::make_tuple(e.node_id, e.index, dev_id); auto it = copy_map.find(copy_key); if (it != copy_map.end() && it->first == copy_key) { new_node->inputs.emplace_back( NodeEntry{it->second, 0, 0}); } else { NodePtr copy_node = Node::Create(); std::ostringstream os; os << inode.source->inputs[i].node->attrs.name << "_" << e.index <<"_copy"; copy_node->attrs.op = copy_op; copy_node->attrs.name = os.str(); if (new_node_map[e.node_id] != nullptr) { copy_node->inputs.emplace_back( NodeEntry{new_node_map[e.node_id], e.index, 0}); } else { copy_node->inputs.push_back(inode.source->inputs[i]); } if (copy_node->attrs.op->attr_parser != nullptr) { copy_node->attrs.op->attr_parser(&(copy_node->attrs)); } copy_map[copy_key] = copy_node; new_device_map[copy_node.get()] = dev_id; new_node->inputs.emplace_back( NodeEntry{std::move(copy_node), 0, 0}); } } else { if (new_node_map[e.node_id] != nullptr) { new_node->inputs.emplace_back( NodeEntry{new_node_map[e.node_id], e.index, 0}); } else { new_node->inputs.push_back(inode.source->inputs[i]); } } } new_node->control_deps.reserve(inode.control_deps.size()); for (size_t i = 0; i < inode.control_deps.size(); ++i) { uint32_t cid = inode.control_deps[i]; if (new_node_map[cid] != nullptr) { new_node->control_deps.push_back(new_node_map[cid]); } else { new_node->control_deps.push_back(inode.source->control_deps[i]); } } new_device_map[new_node.get()] = dev_id; new_node_map[nid] = std::move(new_node); } else { new_device_map[inode.source] = dev_id; } } // make the new graph Graph ret; for (const NodeEntry& e : src.outputs) { if (new_node_map[idx.node_id(e.node.get())] != nullptr) { ret.outputs.emplace_back( NodeEntry{new_node_map[idx.node_id(e.node.get())], e.index, e.version}); } else { ret.outputs.emplace_back(e); } } DeviceVector new_device_vec(ret.indexed_graph().num_nodes()); for (uint32_t nid = 0; nid < ret.indexed_graph().num_nodes(); ++nid) { auto source = ret.indexed_graph()[nid].source; if (new_device_map.count(source) == 0) { LOG(FATAL) << "canot find " << source; } new_device_vec[nid] = new_device_map.at(source); } ret.attrs["device"] = std::make_shared<any>(std::move(new_device_vec)); return ret; } NNVM_REGISTER_PASS(PlaceDevice) .describe("Infer the device type of each operator."\ "Insert a copy node when there is cross device copy") .set_body(PlaceDevice) .set_change_graph(true) .provide_graph_attr("device") .depend_graph_attr("device_group_attr_key") .depend_graph_attr("device_assign_map") .depend_graph_attr("device_copy_op"); DMLC_JSON_ENABLE_ANY(DeviceAssignMap, dict_str_int); } // namespace } // namespace pass } // namespace nnvm
Make placedevice compatible with backward op (#88)
[PASS] Make placedevice compatible with backward op (#88)
C++
apache-2.0
ZihengJiang/nnvm,jermainewang/nnvm,piiswrong/nnvm,ZihengJiang/nnvm,ZihengJiang/nnvm,piiswrong/nnvm,imai-lm/nnvm,jermainewang/nnvm,imai-lm/nnvm,jermainewang/nnvm,imai-lm/nnvm,piiswrong/nnvm
d6358bb2382ebe706f5fbf82a0bd4124737d2a29
src/main.cpp
src/main.cpp
//#include <windows.h> #include <iostream> #include "global.h" #include "Map.h" #include "Character.h" using namespace std; void menu(); void game(); int text(void *); void options(); void about(); void gamePaused(); void loadImages(); void releaseImages(); int callcontrol(void *); int callAction(void *); int callAction2(void *); int callAction3(void *); void SDL_startup(); int menuoption=0; bool close= false; list<int> pressing; int first = 128; int enabledsound=1; #if defined(_WIN32) || defined(_WIN64) int WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, int) { #endif #ifdef __unix__ int main (int argc, char *argv[]){ #endif SDL_startup(); loadImages(); while(!close){ while(SDL_PollEvent(&event)) { menu(); if(!close){ switch(menuoption){ case 0: if(enabledsound) playSound("data/jingle_bells.wav", true, SDL_MIX_MAXVOLUME); game(); break; case 1: options(); break; case 2: about(); break; } } } } releaseImages(); SDL_CloseAudio(); TTF_Quit(); SDL_Quit(); //it finishes SDL initialisations return 0; } void menu(){ menuoption=0; int sx,sy; sx=80; sy=115; color = {0, 0, 0}; bool choose = false; while(!choose){ if(!close){ SDL_FillRect( SDL_GetVideoSurface(), NULL, 0 ); displayImage(menuImage,0,0); drawText("Aperte B para selecionar", screen, 80, 390,color); while(SDL_PollEvent(&event)){ switch(event.type){ case SDL_KEYDOWN: switch(event.key.keysym.sym){ case SDLK_UP: if(menuoption>0) menuoption=(menuoption-1)%3; break; case SDLK_DOWN: menuoption=(menuoption+1)%3; break; case SDLK_b: choose=true; break; default: break; } break; } } if (event.type == SDL_QUIT) { close=true; choose=true; } int colorkey = SDL_MapRGB(screen->format, 255, 0, 255); switch(menuoption){ case 0: sy=190; break; case 1: sy=255; break; case 2: sy=320; break; } displaySpriteImage(item_sprite, sx,sy, GRID_SIZE, 3*GRID_SIZE, GRID_SIZE, colorkey); SDL_Flip(screen); } } } void game(){ map.loadMap("src/map.txt"); player = new Player(0, 0, 0, PLAYER_SPRITE_SIZE, PLAYER_SPRITE_SIZE); enemy = new Enemy(9, 0, 1, 0, 0, ENEMY_SPRITE_SIZE); enemy2 = new Enemy(7, 6, 2, 0, ENEMY_SPRITE_SIZE, ENEMY_SPRITE_SIZE); enemy3 = new Enemy(5, 10, 3, 0, ENEMY_SPRITE_SIZE*2, ENEMY_SPRITE_SIZE); while(!close) { while(SDL_PollEvent(&event)) { switch(event.type){ case SDL_KEYDOWN: if(event.key.keysym.sym == SDLK_ESCAPE) { gamePaused(); } else { pressing.push_back(event.key.keysym.sym); } //inserir na lista event.key.keysym.sym break; case SDL_KEYUP: pressing.remove(event.key.keysym.sym); //remover da lista event.key.keysym.sym break; } if (event.type == SDL_QUIT) { close=true; } } player->handleControl(pressing); enemy->action(); enemy2->action(); enemy3->action(); //threadplayer = SDL_CreateThread(callcontrol, NULL); //threadenemy1 = SDL_CreateThread(callAction, NULL); //threadenemy2 = SDL_CreateThread(callAction2, NULL); //threadenemy3 = SDL_CreateThread(callAction3, NULL); enemy->killPlayer(); enemy2->killPlayer(); enemy3->killPlayer(); map.action(); map.paint(player->life); map.moveAnimation(); enemy->moveAnimation(); enemy2->moveAnimation(); enemy3->moveAnimation(); player->moveAnimation(); threadtext = SDL_CreateThread(text, NULL); SDL_Flip(screen); SDL_Delay(delay); } } int callcontrol(void * unused){ player->handleControl(pressing); //cout<<"Player executou"<<endl; } int callAction(void * unused){ enemy->action(); //cout<<"Enemy 1 executou"<<endl; } int callAction2(void * unused){ enemy2->action(); //cout<<"Enemy 2 executou"<<endl; } int callAction3(void * unused){ enemy3->action(); //cout<<"Enemy 3 executou"<<endl; } int text(void * unused){ color ={255,255,255}; if(first){ if(first>96) drawText("Direcionais movimentam o Bomberman...", screen, 120, 20,color); else if(first>64) drawText("aperte B para soltar Bomba...", screen, 120, 20,color); else if(first>32) drawText("ESC pausa o jogo.",screen, 120, 20,color); else drawText("Encontre a Chave!",screen, 200, 20,color); first--; } if(player->state==WIN){ drawText("YOU WIN!", screen, 350, 15,color); } else if(player->state==LOSE){ drawText("YOU LOSE!", screen, 350, 15,color); } else if(player->imuneTime && player->state!=DEAD){ drawText("Imune por", screen, 350, 15,color); char * imuneTimestr = new char [32]; drawText(to_string(player->imuneTime), screen, 430, 15,color); } } void options(){ int sx,sy; sx=180; sy=190; color = {255, 255, 255}; int colorkey = SDL_MapRGB(screen->format, 255, 0, 255); bool choose = false; SDL_Surface *optionsImage = IMG_Load("data/options.png"); while(!choose){ if(!close){ SDL_FillRect( SDL_GetVideoSurface(), NULL, 0 ); displayImage(optionsImage,0,0); drawText("Aperte B para selecionar", screen, 180, 390,color); while(SDL_PollEvent(&event)){ switch(event.type){ case SDL_KEYDOWN: switch(event.key.keysym.sym){ case SDLK_UP: enabledsound = 1; sy=190; break; case SDLK_DOWN: enabledsound = 0; sy=255; break; case SDLK_b: choose=true; break; default: break; } break; } } if (event.type == SDL_QUIT) { close=true; choose=true; } displaySpriteImage(item_sprite, sx,sy, GRID_SIZE, 3*GRID_SIZE, GRID_SIZE, colorkey); SDL_Flip(screen); } } SDL_FreeSurface(optionsImage); } void about(){ bool done=false; color = {255, 255, 255}; SDL_Surface *aboutImage = IMG_Load("data/about.png"); while(!done){ SDL_FillRect( SDL_GetVideoSurface(), NULL, 0 ); displayImage(aboutImage,0,0); drawText("Aperte B para voltar ao menu", screen, 180, 390,color); SDL_Flip(screen); while(SDL_PollEvent(&event)){ switch(event.type){ case SDL_KEYDOWN: switch(event.key.keysym.sym){ case SDLK_b: done=true; break; default: break; } break; } if (event.type == SDL_QUIT) { done=true; close=true; } } } SDL_FreeSurface(aboutImage); } void gamePaused(){ color={255,255,255}; bool choose=false; drawText("GAME PAUSED", screen, 200, 10,color); while(!choose){ if(!close){ while(SDL_PollEvent(&event)){ switch(event.type){ case SDL_KEYDOWN: switch(event.key.keysym.sym){ case SDLK_ESCAPE: choose=true; break; default: break; } break; } if (event.type == SDL_QUIT) { choose=true; close=true; } } SDL_Flip(screen); } } } void SDL_startup() { if( SDL_Init(SDL_INIT_VIDEO) != 0) { printf("Unable to initialise SDL: %s\n", SDL_GetError()); exit(1); } //it's used to guarantee that the SDL_Quit function is called when the application exits; atexit(SDL_Quit); screen = SDL_SetVideoMode(515, 442, 16, SDL_SWSURFACE); //width, height, bitdepth if(screen==NULL){ printf("Unable to set video mode: %s\n", SDL_GetError()); exit(1); } SDL_WM_SetCaption("Bomberman", "Bomberman"); //topTitle, iconTitle SDL_Surface* icon = IMG_Load("data/icon.png"); SDL_WM_SetIcon(icon, NULL); if(TTF_Init() == -1) { printf("Unable to set font : %s\n", SDL_GetError()); exit(1); } font = TTF_OpenFont("data/manaspc.ttf", 12); /* ajusta para áudio em 16-bit stereo com 22Khz */ //audioFmt.freq = 22050; audioFmt.freq = SOUND_FREQUENCY; audioFmt.format = AUDIO_S16; audioFmt.channels = 1;//2 audioFmt.samples = 1024;//512; /* um bom valor para jogos */ audioFmt.callback = mixaudio; audioFmt.userdata = NULL; if ( SDL_OpenAudio(&audioFmt, NULL) < 0 ) { fprintf(stderr, "Unable to open the audio: %s\n", SDL_GetError()); exit(1); } SDL_PauseAudio(0); SDL_FillRect( SDL_GetVideoSurface(), NULL, 0 );//parado } void loadImages() { SDL_Surface * temp; menuImage =IMG_Load("data/bgmenu.png"); mapImage = IMG_Load("data/bg.png"); temp = SDL_LoadBMP("data/enemies_sprite.bmp"); enemy_sprite = SDL_DisplayFormat(temp); SDL_FreeSurface(temp); temp = SDL_LoadBMP("data/item_sprite.bmp"); item_sprite = SDL_DisplayFormat(temp); SDL_FreeSurface(temp); temp = SDL_LoadBMP("data/player_sprite.bmp"); player_sprite = SDL_DisplayFormat(temp); SDL_FreeSurface(temp); temp = SDL_LoadBMP("data/fire_sprite.bmp"); fire_sprite = SDL_DisplayFormat(temp); SDL_FreeSurface(temp); } void releaseImages() { SDL_FreeSurface(enemy_sprite); SDL_FreeSurface(item_sprite); SDL_FreeSurface(player_sprite); SDL_FreeSurface(fire_sprite); SDL_FreeSurface(menuImage); SDL_FreeSurface(mapImage); }
//#include <windows.h> #include <iostream> #include "global.h" #include "Map.h" #include "Character.h" using namespace std; void menu(); void game(); int text(void *); void options(); void about(); void gamePaused(); void loadImages(); void releaseImages(); int callcontrol(void *); int callAction(void *); int callAction2(void *); int callAction3(void *); void SDL_startup(); int menuoption=0; bool close= false; list<int> pressing; int first = 128; int enabledsound=1; #if defined(_WIN32) || defined(_WIN64) int WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, int) { #endif #ifdef __unix__ int main (int argc, char *argv[]){ #endif SDL_startup(); loadImages(); while(!close){ while(SDL_PollEvent(&event)) { menu(); if(!close){ switch(menuoption){ case 0: if(enabledsound) playSound("data/jingle_bells.wav", true, SDL_MIX_MAXVOLUME); game(); break; case 1: options(); break; case 2: about(); break; } } } } releaseImages(); SDL_CloseAudio(); TTF_Quit(); SDL_Quit(); //it finishes SDL initialisations return 0; } void menu(){ menuoption=0; int sx,sy; sx=80; sy=190; color = {0, 0, 0}; int colorkey = SDL_MapRGB(screen->format, 255, 0, 255); bool choose = false; while(!choose && !close){ SDL_FillRect( SDL_GetVideoSurface(), NULL, 0 ); displayImage(menuImage,0,0); drawText("Aperte B para selecionar", screen, 80, 390,color); while(SDL_PollEvent(&event)){ switch(event.type){ case SDL_KEYDOWN: switch(event.key.keysym.sym){ case SDLK_UP: sy = sy - 65; if(sy<190) sy = 320; break; case SDLK_DOWN: sy = sy + 65; if(sy>320) sy = 190; break; case SDLK_b: choose=true; if(sy==320) menuoption = 2; else if(sy==255) menuoption = 1; else menuoption = 0; break; default: break; } break; } } if (event.type == SDL_QUIT) { close=true; choose=true; } displaySpriteImage(item_sprite, sx,sy, GRID_SIZE, 3*GRID_SIZE, GRID_SIZE, colorkey); SDL_Flip(screen); } } void game(){ map.loadMap("src/map.txt"); player = new Player(0, 0, 0, PLAYER_SPRITE_SIZE, PLAYER_SPRITE_SIZE); enemy = new Enemy(9, 0, 1, 0, 0, ENEMY_SPRITE_SIZE); enemy2 = new Enemy(7, 6, 2, 0, ENEMY_SPRITE_SIZE, ENEMY_SPRITE_SIZE); enemy3 = new Enemy(5, 10, 3, 0, ENEMY_SPRITE_SIZE*2, ENEMY_SPRITE_SIZE); while(!close) { while(SDL_PollEvent(&event)) { switch(event.type){ case SDL_KEYDOWN: if(event.key.keysym.sym == SDLK_ESCAPE) gamePaused(); else pressing.push_back(event.key.keysym.sym); //inserir na lista event.key.keysym.sym break; case SDL_KEYUP: pressing.remove(event.key.keysym.sym); //remover da lista event.key.keysym.sym break; } if (event.type == SDL_QUIT) { close=true; } } player->handleControl(pressing); enemy->action(); enemy2->action(); enemy3->action(); //threadplayer = SDL_CreateThread(callcontrol, NULL); //threadenemy1 = SDL_CreateThread(callAction, NULL); //threadenemy2 = SDL_CreateThread(callAction2, NULL); //threadenemy3 = SDL_CreateThread(callAction3, NULL); enemy->killPlayer(); enemy2->killPlayer(); enemy3->killPlayer(); map.action(); map.paint(player->life); map.moveAnimation(); enemy->moveAnimation(); enemy2->moveAnimation(); enemy3->moveAnimation(); player->moveAnimation(); threadtext = SDL_CreateThread(text, NULL); SDL_Flip(screen); SDL_Delay(delay); } } int callcontrol(void * unused){ player->handleControl(pressing); //cout<<"Player executou"<<endl; } int callAction(void * unused){ enemy->action(); //cout<<"Enemy 1 executou"<<endl; } int callAction2(void * unused){ enemy2->action(); //cout<<"Enemy 2 executou"<<endl; } int callAction3(void * unused){ enemy3->action(); //cout<<"Enemy 3 executou"<<endl; } int text(void * unused){ color ={255,255,255}; if(first){ if(first>96) drawText("Direcionais movimentam o Bomberman...", screen, 120, 20,color); else if(first>64) drawText("aperte B para soltar Bomba...", screen, 120, 20,color); else if(first>32) drawText("ESC pausa o jogo.",screen, 120, 20,color); else drawText("Encontre a Chave!",screen, 200, 20,color); first--; } if(player->state==WIN){ drawText("YOU WIN!", screen, 350, 15,color); } else if(player->state==LOSE){ drawText("YOU LOSE!", screen, 350, 15,color); } else if(player->imuneTime && player->state!=DEAD){ drawText("Imune por", screen, 350, 15,color); char * imuneTimestr = new char [32]; drawText(to_string(player->imuneTime), screen, 430, 15,color); } } void options(){ int sx,sy; sx=180; sy=190; color = {255, 255, 255}; int colorkey = SDL_MapRGB(screen->format, 255, 0, 255); bool choose = false; SDL_Surface *optionsImage = IMG_Load("data/options.png"); while(!choose){ if(!close){ SDL_FillRect( SDL_GetVideoSurface(), NULL, 0 ); displayImage(optionsImage,0,0); drawText("Aperte B para selecionar", screen, 180, 390,color); while(SDL_PollEvent(&event)){ switch(event.type){ case SDL_KEYDOWN: switch(event.key.keysym.sym){ case SDLK_UP: sy=sy-65; if(sy<190) sy=255; break; case SDLK_DOWN: sy=(sy+65); if(sy>255) sy=190; break; case SDLK_b: enabledsound = (sy == 255); choose=true; break; default: break; } break; } } if (event.type == SDL_QUIT) { close=true; choose=true; } displaySpriteImage(item_sprite, sx,sy, GRID_SIZE, 3*GRID_SIZE, GRID_SIZE, colorkey); SDL_Flip(screen); } } SDL_FreeSurface(optionsImage); } void about(){ bool done=false; color = {255, 255, 255}; SDL_Surface *aboutImage = IMG_Load("data/about.png"); while(!done){ SDL_FillRect( SDL_GetVideoSurface(), NULL, 0 ); displayImage(aboutImage,0,0); drawText("Aperte B para voltar ao menu", screen, 180, 390,color); SDL_Flip(screen); while(SDL_PollEvent(&event)){ switch(event.type){ case SDL_KEYDOWN: switch(event.key.keysym.sym){ case SDLK_b: done=true; break; default: break; } break; } if (event.type == SDL_QUIT) { done=true; close=true; } } } SDL_FreeSurface(aboutImage); } void gamePaused(){ color={255,255,255}; bool choose=false; drawText("GAME PAUSED", screen, 200, 10,color); while(!choose){ if(!close){ while(SDL_PollEvent(&event)){ switch(event.type){ case SDL_KEYDOWN: switch(event.key.keysym.sym){ case SDLK_ESCAPE: choose=true; break; default: break; } break; } if (event.type == SDL_QUIT) { choose=true; close=true; } } SDL_Flip(screen); } } } void SDL_startup() { if( SDL_Init(SDL_INIT_VIDEO) != 0) { printf("Unable to initialise SDL: %s\n", SDL_GetError()); exit(1); } //it's used to guarantee that the SDL_Quit function is called when the application exits; atexit(SDL_Quit); screen = SDL_SetVideoMode(515, 442, 16, SDL_SWSURFACE); //width, height, bitdepth if(screen==NULL){ printf("Unable to set video mode: %s\n", SDL_GetError()); exit(1); } SDL_WM_SetCaption("Bomberman", "Bomberman"); //topTitle, iconTitle SDL_Surface* icon = IMG_Load("data/icon.png"); SDL_WM_SetIcon(icon, NULL); if(TTF_Init() == -1) { printf("Unable to set font : %s\n", SDL_GetError()); exit(1); } font = TTF_OpenFont("data/manaspc.ttf", 12); /* ajusta para áudio em 16-bit stereo com 22Khz */ //audioFmt.freq = 22050; audioFmt.freq = SOUND_FREQUENCY; audioFmt.format = AUDIO_S16; audioFmt.channels = 1;//2 audioFmt.samples = 1024;//512; /* um bom valor para jogos */ audioFmt.callback = mixaudio; audioFmt.userdata = NULL; if ( SDL_OpenAudio(&audioFmt, NULL) < 0 ) { fprintf(stderr, "Unable to open the audio: %s\n", SDL_GetError()); exit(1); } SDL_PauseAudio(0); SDL_FillRect( SDL_GetVideoSurface(), NULL, 0 );//parado } void loadImages() { SDL_Surface * temp; menuImage =IMG_Load("data/bgmenu.png"); mapImage = IMG_Load("data/bg.png"); temp = SDL_LoadBMP("data/enemies_sprite.bmp"); enemy_sprite = SDL_DisplayFormat(temp); SDL_FreeSurface(temp); temp = SDL_LoadBMP("data/item_sprite.bmp"); item_sprite = SDL_DisplayFormat(temp); SDL_FreeSurface(temp); temp = SDL_LoadBMP("data/player_sprite.bmp"); player_sprite = SDL_DisplayFormat(temp); SDL_FreeSurface(temp); temp = SDL_LoadBMP("data/fire_sprite.bmp"); fire_sprite = SDL_DisplayFormat(temp); SDL_FreeSurface(temp); } void releaseImages() { SDL_FreeSurface(enemy_sprite); SDL_FreeSurface(item_sprite); SDL_FreeSurface(player_sprite); SDL_FreeSurface(fire_sprite); SDL_FreeSurface(menuImage); SDL_FreeSurface(mapImage); }
Refactor menu and options
Refactor menu and options
C++
mit
belinhacbr/Bomberman
f69b4de8352fb64be3bd8997bd0cf9f69e0490ce
tree/treeplayer/test/dataframe/dataframe_snapshot.cxx
tree/treeplayer/test/dataframe/dataframe_snapshot.cxx
#include "ROOT/TDataFrame.hxx" #include "ROOT/TSeq.hxx" #include "TFile.h" #include "TROOT.h" #include "TSystem.h" #include "TTree.h" #include "gtest/gtest.h" #include <limits> #include <memory> using namespace ROOT::Experimental; // TDataFrame using namespace ROOT::Experimental::TDF; // TInterface using namespace ROOT::Detail::TDF; // TLoopManager /********* FIXTURES *********/ // fixture that provides a TDF with no data-source and a single integer column "ans" with value 42 class TDFSnapshot : public ::testing::Test { protected: const ULong64_t nEvents = 100ull; // must be initialized before fLoopManager private: TDataFrame fTdf; TInterface<TLoopManager> DefineAns() { return fTdf.Define("ans", []() { return 42; }); } protected: TDFSnapshot() : fTdf(nEvents), tdf(DefineAns()) {} TInterface<TLoopManager> tdf; }; #ifdef R__USE_IMT // fixture that enables implicit MT and provides a TDF with no data-source and a single column "x" containing // normal-distributed doubles class TDFSnapshotMT : public ::testing::Test { class TIMTEnabler { public: TIMTEnabler(unsigned int nSlots) { ROOT::EnableImplicitMT(nSlots); } ~TIMTEnabler() { ROOT::DisableImplicitMT(); } }; protected: const ULong64_t kNEvents = 100ull; // must be initialized before fLoopManager const unsigned int kNSlots = 4u; private: TIMTEnabler fIMTEnabler; TDataFrame fTdf; TInterface<TLoopManager> DefineAns() { return fTdf.Define("ans", []() { return 42; }); } protected: TDFSnapshotMT() : fIMTEnabler(kNSlots), fTdf(kNEvents), tdf(DefineAns()) {} TInterface<TLoopManager> tdf; }; #endif class TDFSnapshotArrays : public ::testing::Test { protected: const static unsigned int kNEvents = 10u; static const std::vector<std::string> kFileNames; static void SetUpTestCase() { // write files containing c-arrays const auto eventsPerFile = kNEvents / kFileNames.size(); auto curEvent = 0u; for (const auto &fname : kFileNames) { TFile f(fname.c_str(), "RECREATE"); TTree t("arrayTree", "arrayTree"); const unsigned int fixedSize = 4u; float fixedSizeArr[fixedSize]; t.Branch("fixedSizeArr", fixedSizeArr, ("fixedSizeArr[" + std::to_string(fixedSize) + "]/F").c_str()); unsigned int size = 0u; t.Branch("size", &size); double varSizeArr[kNEvents + 1]; t.Branch("varSizeArr", varSizeArr, "varSizeArr[size]/D"); // for each event, fill array elements for (auto i : ROOT::TSeqU(eventsPerFile)) { for (auto j : ROOT::TSeqU(4)) fixedSizeArr[j] = curEvent * j; size = eventsPerFile - i; for (auto j : ROOT::TSeqU(size)) varSizeArr[j] = curEvent * j; t.Fill(); ++curEvent; } t.Write(); } } static void TearDownTestCase() { for (const auto &fname : kFileNames) gSystem->Unlink(fname.c_str()); } }; const std::vector<std::string> TDFSnapshotArrays::kFileNames = {"test_snapshotarray1.root", "test_snapshotarray2.root"}; /********* SINGLE THREAD TESTS ***********/ // Test for ROOT-9210 TEST_F(TDFSnapshot, Snapshot_aliases) { std::string alias0("myalias0"); auto tdfa = tdf.Alias(alias0, "ans"); testing::internal::CaptureStderr(); auto snap = tdfa.Snapshot<int>("mytree", "Snapshot_aliases.root", {alias0}); std::string err = testing::internal::GetCapturedStderr(); EXPECT_TRUE(err.empty()) << err; EXPECT_STREQ(snap.GetColumnNames()[0].c_str(), alias0.c_str()); auto takenCol = snap.Alias("a", alias0).Take<int>("a"); for (auto i : takenCol) { EXPECT_EQ(42, i); } } // Test for ROOT-9122 TEST_F(TDFSnapshot, Snapshot_nocolumnmatch) { TDataFrame d(1); int ret(1); try { testing::internal::CaptureStderr(); d.Snapshot("t", "f.root", "x"); } catch (const std::runtime_error &e) { ret = 0; } EXPECT_EQ(0, ret); } void test_snapshot_update(TInterface<TLoopManager> &tdf) { // test snapshotting two trees to the same file with two snapshots and the "UPDATE" option const auto outfile = "snapshot_test_update.root"; auto s1 = tdf.Snapshot<int>("t", outfile, {"ans"}); auto c1 = s1.Count(); auto min1 = s1.Min<int>("ans"); auto max1 = s1.Max<int>("ans"); auto mean1 = s1.Mean<int>("ans"); EXPECT_EQ(100ull, *c1); EXPECT_EQ(42, *min1); EXPECT_EQ(42, *max1); EXPECT_EQ(42, *mean1); TSnapshotOptions opts; opts.fMode = "UPDATE"; auto s2 = tdf.Define("two", []() { return 2.; }).Snapshot<double>("t2", outfile, {"two"}, opts); auto c2 = s2.Count(); auto min2 = s2.Min<double>("two"); auto max2 = s2.Max<double>("two"); auto mean2 = s2.Mean<double>("two"); EXPECT_EQ(100ull, *c2); EXPECT_DOUBLE_EQ(2., *min2); EXPECT_DOUBLE_EQ(2., *min2); EXPECT_DOUBLE_EQ(2., *mean2); // check that the output file contains both trees std::unique_ptr<TFile> f(TFile::Open(outfile)); EXPECT_NE(nullptr, f->Get("t")); EXPECT_NE(nullptr, f->Get("t2")); // clean-up gSystem->Unlink(outfile); } TEST_F(TDFSnapshot, Snapshot_update) { test_snapshot_update(tdf); } void test_snapshot_options(TInterface<TLoopManager> &tdf) { TSnapshotOptions opts; opts.fAutoFlush = 10; opts.fMode = "RECREATE"; opts.fCompressionLevel = 6; const auto outfile = "snapshot_test_opts.root"; for (auto algorithm : {ROOT::kZLIB, ROOT::kLZMA, ROOT::kLZ4}) { opts.fCompressionAlgorithm = algorithm; auto s = tdf.Snapshot<int>("t", outfile, {"ans"}, opts); auto c = s.Count(); auto min = s.Min<int>("ans"); auto max = s.Max<int>("ans"); auto mean = s.Mean<int>("ans"); EXPECT_EQ(100ull, *c); EXPECT_EQ(42, *min); EXPECT_EQ(42, *max); EXPECT_EQ(42, *mean); std::unique_ptr<TFile> f(TFile::Open("snapshot_test_opts.root")); EXPECT_EQ(algorithm, f->GetCompressionAlgorithm()); EXPECT_EQ(6, f->GetCompressionLevel()); } // clean-up gSystem->Unlink(outfile); } TEST_F(TDFSnapshot, Snapshot_action_with_options) { test_snapshot_options(tdf); } void checkSnapshotArrayFile(TInterface<TLoopManager> &df, unsigned int kNEvents) { // fixedSizeArr and varSizeArr are TResultProxy<vector<vector<T>>> auto fixedSizeArr = df.Take<TArrayBranch<float>>("fixedSizeArr"); auto varSizeArr = df.Take<TArrayBranch<double>>("varSizeArr"); auto size = df.Take<unsigned int>("size"); // check contents of fixedSizeArr const auto nEvents = fixedSizeArr->size(); const auto fixedSizeSize = fixedSizeArr->front().size(); EXPECT_EQ(nEvents, kNEvents); EXPECT_EQ(fixedSizeSize, 4u); for (auto i = 0u; i < nEvents; ++i) { for (auto j = 0u; j < fixedSizeSize; ++j) EXPECT_DOUBLE_EQ(fixedSizeArr->at(i).at(j), i * j); } // check contents of varSizeArr for (auto i = 0u; i < nEvents; ++i) { const auto &v = varSizeArr->at(i); const auto thisSize = size->at(i); EXPECT_EQ(thisSize, v.size()); for (auto j = 0u; j < thisSize; ++j) EXPECT_DOUBLE_EQ(v[j], i * j); } } TEST_F(TDFSnapshotArrays, SingleThread) { TDataFrame tdf("arrayTree", kFileNames); // template Snapshot // "size" _must_ be listed before "varSizeArr"! auto dt = tdf.Snapshot<TArrayBranch<float>, unsigned int, TArrayBranch<double>>( "outTree", "test_snapshotTArrayBranchout.root", {"fixedSizeArr", "size", "varSizeArr"}); checkSnapshotArrayFile(dt, kNEvents); } TEST_F(TDFSnapshotArrays, SingleThreadJitted) { TDataFrame tdf("arrayTree", kFileNames); // jitted Snapshot // "size" _must_ be listed before "varSizeArr"! auto dj = tdf.Snapshot("outTree", "test_snapshotTArrayBranchout.root", {"fixedSizeArr", "size", "varSizeArr"}); checkSnapshotArrayFile(dj, kNEvents); } /********* MULTI THREAD TESTS ***********/ #ifdef R__USE_IMT TEST_F(TDFSnapshotMT, Snapshot_update) { test_snapshot_update(tdf); } TEST_F(TDFSnapshotMT, Snapshot_action_with_options) { test_snapshot_options(tdf); } TEST(TDFSnapshotMore, ManyTasksPerThread) { const auto nSlots = 4u; ROOT::EnableImplicitMT(nSlots); // easiest way to be sure reading requires spawning of several tasks: create several input files const std::string inputFilePrefix = "snapshot_manytasks_"; const auto tasksPerThread = 8u; const auto nInputFiles = nSlots * tasksPerThread; ROOT::Experimental::TDataFrame d(1); auto dd = d.Define("x", []() { return 42; }); for (auto i = 0u; i < nInputFiles; ++i) dd.Snapshot<int>("t", inputFilePrefix + std::to_string(i) + ".root", {"x"}); // test multi-thread Snapshotting from many tasks per worker thread const auto outputFile = "snapshot_manytasks_out.root"; ROOT::Experimental::TDataFrame tdf("t", (inputFilePrefix + "*.root").c_str()); tdf.Snapshot<int>("t", outputFile, {"x"}); // check output contents ROOT::Experimental::TDataFrame checkTdf("t", outputFile); auto c = checkTdf.Count(); auto t = checkTdf.Take<int>("x"); for (auto v : t) EXPECT_EQ(v, 42); EXPECT_EQ(*c, nInputFiles); // clean-up input files for (auto i = 0u; i < nInputFiles; ++i) gSystem->Unlink((inputFilePrefix + std::to_string(i) + ".root").c_str()); gSystem->Unlink(outputFile); ROOT::DisableImplicitMT(); } void checkSnapshotArrayFileMT(TInterface<TLoopManager> &df, unsigned int kNEvents) { // fixedSizeArr and varSizeArr are TResultProxy<vector<vector<T>>> auto fixedSizeArr = df.Take<TArrayBranch<float>>("fixedSizeArr"); auto varSizeArr = df.Take<TArrayBranch<double>>("varSizeArr"); auto size = df.Take<unsigned int>("size"); // multi-thread execution might have scrambled events w.r.t. the original file, so we just check overall properties const auto nEvents = fixedSizeArr->size(); EXPECT_EQ(nEvents, kNEvents); // TODO check more! } TEST_F(TDFSnapshotArrays, MultiThread) { ROOT::EnableImplicitMT(4); TDataFrame tdf("arrayTree", kFileNames); auto dt = tdf.Snapshot<TArrayBranch<float>, unsigned int, TArrayBranch<double>>( "outTree", "test_snapshotTArrayBranchout.root", {"fixedSizeArr", "size", "varSizeArr"}); checkSnapshotArrayFileMT(dt, kNEvents); ROOT::DisableImplicitMT(); } TEST_F(TDFSnapshotArrays, MultiThreadJitted) { ROOT::EnableImplicitMT(4); TDataFrame tdf("arrayTree", kFileNames); auto dj = tdf.Snapshot("outTree", "test_snapshotTArrayBranchout.root", {"fixedSizeArr", "size", "varSizeArr"}); checkSnapshotArrayFileMT(dj, kNEvents); ROOT::DisableImplicitMT(); } #endif
#include "ROOT/TDataFrame.hxx" #include "ROOT/TSeq.hxx" #include "TFile.h" #include "TROOT.h" #include "TSystem.h" #include "TTree.h" #include "gtest/gtest.h" #include <limits> #include <memory> using namespace ROOT::Experimental; // TDataFrame using namespace ROOT::Experimental::TDF; // TInterface using namespace ROOT::Detail::TDF; // TLoopManager /********* FIXTURES *********/ // fixture that provides a TDF with no data-source and a single integer column "ans" with value 42 class TDFSnapshot : public ::testing::Test { protected: const ULong64_t nEvents = 100ull; // must be initialized before fLoopManager private: TDataFrame fTdf; TInterface<TLoopManager> DefineAns() { return fTdf.Define("ans", []() { return 42; }); } protected: TDFSnapshot() : fTdf(nEvents), tdf(DefineAns()) {} TInterface<TLoopManager> tdf; }; #ifdef R__USE_IMT // fixture that enables implicit MT and provides a TDF with no data-source and a single column "x" containing // normal-distributed doubles class TDFSnapshotMT : public ::testing::Test { class TIMTEnabler { public: TIMTEnabler(unsigned int nSlots) { ROOT::EnableImplicitMT(nSlots); } ~TIMTEnabler() { ROOT::DisableImplicitMT(); } }; protected: const ULong64_t kNEvents = 100ull; // must be initialized before fLoopManager const unsigned int kNSlots = 4u; private: TIMTEnabler fIMTEnabler; TDataFrame fTdf; TInterface<TLoopManager> DefineAns() { return fTdf.Define("ans", []() { return 42; }); } protected: TDFSnapshotMT() : fIMTEnabler(kNSlots), fTdf(kNEvents), tdf(DefineAns()) {} TInterface<TLoopManager> tdf; }; #endif // fixture that provides fixed and variable sized arrays as TDF columns class TDFSnapshotArrays : public ::testing::Test { protected: const static unsigned int kNEvents = 10u; static const std::vector<std::string> kFileNames; static void SetUpTestCase() { // write files containing c-arrays const auto eventsPerFile = kNEvents / kFileNames.size(); auto curEvent = 0u; for (const auto &fname : kFileNames) { TFile f(fname.c_str(), "RECREATE"); TTree t("arrayTree", "arrayTree"); const unsigned int fixedSize = 4u; float fixedSizeArr[fixedSize]; t.Branch("fixedSizeArr", fixedSizeArr, ("fixedSizeArr[" + std::to_string(fixedSize) + "]/F").c_str()); unsigned int size = 0u; t.Branch("size", &size); double varSizeArr[kNEvents + 1]; t.Branch("varSizeArr", varSizeArr, "varSizeArr[size]/D"); // for each event, fill array elements for (auto i : ROOT::TSeqU(eventsPerFile)) { for (auto j : ROOT::TSeqU(4)) fixedSizeArr[j] = curEvent * j; size = eventsPerFile - i; for (auto j : ROOT::TSeqU(size)) varSizeArr[j] = curEvent * j; t.Fill(); ++curEvent; } t.Write(); } } static void TearDownTestCase() { for (const auto &fname : kFileNames) gSystem->Unlink(fname.c_str()); } }; const std::vector<std::string> TDFSnapshotArrays::kFileNames = {"test_snapshotarray1.root", "test_snapshotarray2.root"}; /********* SINGLE THREAD TESTS ***********/ // Test for ROOT-9210 TEST_F(TDFSnapshot, Snapshot_aliases) { std::string alias0("myalias0"); auto tdfa = tdf.Alias(alias0, "ans"); testing::internal::CaptureStderr(); auto snap = tdfa.Snapshot<int>("mytree", "Snapshot_aliases.root", {alias0}); std::string err = testing::internal::GetCapturedStderr(); EXPECT_TRUE(err.empty()) << err; EXPECT_STREQ(snap.GetColumnNames()[0].c_str(), alias0.c_str()); auto takenCol = snap.Alias("a", alias0).Take<int>("a"); for (auto i : takenCol) { EXPECT_EQ(42, i); } } // Test for ROOT-9122 TEST_F(TDFSnapshot, Snapshot_nocolumnmatch) { TDataFrame d(1); int ret(1); try { testing::internal::CaptureStderr(); d.Snapshot("t", "f.root", "x"); } catch (const std::runtime_error &e) { ret = 0; } EXPECT_EQ(0, ret); } void test_snapshot_update(TInterface<TLoopManager> &tdf) { // test snapshotting two trees to the same file with two snapshots and the "UPDATE" option const auto outfile = "snapshot_test_update.root"; auto s1 = tdf.Snapshot<int>("t", outfile, {"ans"}); auto c1 = s1.Count(); auto min1 = s1.Min<int>("ans"); auto max1 = s1.Max<int>("ans"); auto mean1 = s1.Mean<int>("ans"); EXPECT_EQ(100ull, *c1); EXPECT_EQ(42, *min1); EXPECT_EQ(42, *max1); EXPECT_EQ(42, *mean1); TSnapshotOptions opts; opts.fMode = "UPDATE"; auto s2 = tdf.Define("two", []() { return 2.; }).Snapshot<double>("t2", outfile, {"two"}, opts); auto c2 = s2.Count(); auto min2 = s2.Min<double>("two"); auto max2 = s2.Max<double>("two"); auto mean2 = s2.Mean<double>("two"); EXPECT_EQ(100ull, *c2); EXPECT_DOUBLE_EQ(2., *min2); EXPECT_DOUBLE_EQ(2., *min2); EXPECT_DOUBLE_EQ(2., *mean2); // check that the output file contains both trees std::unique_ptr<TFile> f(TFile::Open(outfile)); EXPECT_NE(nullptr, f->Get("t")); EXPECT_NE(nullptr, f->Get("t2")); // clean-up gSystem->Unlink(outfile); } TEST_F(TDFSnapshot, Snapshot_update) { test_snapshot_update(tdf); } void test_snapshot_options(TInterface<TLoopManager> &tdf) { TSnapshotOptions opts; opts.fAutoFlush = 10; opts.fMode = "RECREATE"; opts.fCompressionLevel = 6; const auto outfile = "snapshot_test_opts.root"; for (auto algorithm : {ROOT::kZLIB, ROOT::kLZMA, ROOT::kLZ4}) { opts.fCompressionAlgorithm = algorithm; auto s = tdf.Snapshot<int>("t", outfile, {"ans"}, opts); auto c = s.Count(); auto min = s.Min<int>("ans"); auto max = s.Max<int>("ans"); auto mean = s.Mean<int>("ans"); EXPECT_EQ(100ull, *c); EXPECT_EQ(42, *min); EXPECT_EQ(42, *max); EXPECT_EQ(42, *mean); std::unique_ptr<TFile> f(TFile::Open("snapshot_test_opts.root")); EXPECT_EQ(algorithm, f->GetCompressionAlgorithm()); EXPECT_EQ(6, f->GetCompressionLevel()); } // clean-up gSystem->Unlink(outfile); } TEST_F(TDFSnapshot, Snapshot_action_with_options) { test_snapshot_options(tdf); } void checkSnapshotArrayFile(TInterface<TLoopManager> &df, unsigned int kNEvents) { // fixedSizeArr and varSizeArr are TResultProxy<vector<vector<T>>> auto fixedSizeArr = df.Take<TArrayBranch<float>>("fixedSizeArr"); auto varSizeArr = df.Take<TArrayBranch<double>>("varSizeArr"); auto size = df.Take<unsigned int>("size"); // check contents of fixedSizeArr const auto nEvents = fixedSizeArr->size(); const auto fixedSizeSize = fixedSizeArr->front().size(); EXPECT_EQ(nEvents, kNEvents); EXPECT_EQ(fixedSizeSize, 4u); for (auto i = 0u; i < nEvents; ++i) { for (auto j = 0u; j < fixedSizeSize; ++j) EXPECT_DOUBLE_EQ(fixedSizeArr->at(i).at(j), i * j); } // check contents of varSizeArr for (auto i = 0u; i < nEvents; ++i) { const auto &v = varSizeArr->at(i); const auto thisSize = size->at(i); EXPECT_EQ(thisSize, v.size()); for (auto j = 0u; j < thisSize; ++j) EXPECT_DOUBLE_EQ(v[j], i * j); } } TEST_F(TDFSnapshotArrays, SingleThread) { TDataFrame tdf("arrayTree", kFileNames); // template Snapshot // "size" _must_ be listed before "varSizeArr"! auto dt = tdf.Snapshot<TArrayBranch<float>, unsigned int, TArrayBranch<double>>( "outTree", "test_snapshotTArrayBranchout.root", {"fixedSizeArr", "size", "varSizeArr"}); checkSnapshotArrayFile(dt, kNEvents); } TEST_F(TDFSnapshotArrays, SingleThreadJitted) { TDataFrame tdf("arrayTree", kFileNames); // jitted Snapshot // "size" _must_ be listed before "varSizeArr"! auto dj = tdf.Snapshot("outTree", "test_snapshotTArrayBranchout.root", {"fixedSizeArr", "size", "varSizeArr"}); checkSnapshotArrayFile(dj, kNEvents); } void WriteColsWithCustomTitles(const std::string &tname, const std::string &fname) { int i; float f; int a[2]; TFile file(fname.c_str(), "RECREATE"); TTree t(tname.c_str(), tname.c_str()); auto b = t.Branch("float", &f); b->SetTitle("custom title"); b = t.Branch("i", &i); b->SetTitle("custom title"); b = t.Branch("arrint", &a, "arrint[2]/I"); b->SetTitle("custom title"); b = t.Branch("vararrint", &a, "vararrint[i]/I"); b->SetTitle("custom title"); i = 1; a[0] = 42; a[1] = 84; f = 4.2; t.Fill(); i = 2; f = 8.4; t.Fill(); t.Write(); } void CheckColsWithCustomTitles(unsigned long long int entry, int i, const TDF::TArrayBranch<int> &arrint, const TDF::TArrayBranch<int> &vararrint, float f) { if (entry == 0) { EXPECT_EQ(i, 1); EXPECT_EQ(arrint.size(), 2u); EXPECT_EQ(arrint[0], 42); EXPECT_EQ(arrint[1], 84); EXPECT_EQ(vararrint.size(), 1u); EXPECT_EQ(vararrint[0], 42); EXPECT_FLOAT_EQ(f, 4.2f); } else if (entry == 1) { EXPECT_EQ(i, 2); EXPECT_EQ(arrint.size(), 2u); EXPECT_EQ(arrint[0], 42); EXPECT_EQ(arrint[1], 84); EXPECT_EQ(vararrint.size(), 2u); EXPECT_EQ(vararrint[0], 42); EXPECT_EQ(vararrint[1], 84); EXPECT_FLOAT_EQ(f, 8.4f); } else throw std::runtime_error("tree has more entries than expected"); } TEST(TDFSnapshotMore, ColsWithCustomTitles) { const auto fname = "colswithcustomtitles.root"; const auto tname = "t"; // write test tree WriteColsWithCustomTitles(tname, fname); // read and write test tree with TDF TDataFrame d(tname, fname); const std::string prefix = "snapshotted_"; auto res_tdf = d.Snapshot(tname, prefix + fname); // check correct results have been written out res_tdf.Foreach(CheckColsWithCustomTitles, {"tdfentry_", "i", "arrint", "vararrint", "float"}); // clean-up gSystem->Unlink(fname); gSystem->Unlink((prefix + fname).c_str()); } /********* MULTI THREAD TESTS ***********/ #ifdef R__USE_IMT TEST_F(TDFSnapshotMT, Snapshot_update) { test_snapshot_update(tdf); } TEST_F(TDFSnapshotMT, Snapshot_action_with_options) { test_snapshot_options(tdf); } TEST(TDFSnapshotMore, ManyTasksPerThread) { const auto nSlots = 4u; ROOT::EnableImplicitMT(nSlots); // easiest way to be sure reading requires spawning of several tasks: create several input files const std::string inputFilePrefix = "snapshot_manytasks_"; const auto tasksPerThread = 8u; const auto nInputFiles = nSlots * tasksPerThread; ROOT::Experimental::TDataFrame d(1); auto dd = d.Define("x", []() { return 42; }); for (auto i = 0u; i < nInputFiles; ++i) dd.Snapshot<int>("t", inputFilePrefix + std::to_string(i) + ".root", {"x"}); // test multi-thread Snapshotting from many tasks per worker thread const auto outputFile = "snapshot_manytasks_out.root"; ROOT::Experimental::TDataFrame tdf("t", (inputFilePrefix + "*.root").c_str()); tdf.Snapshot<int>("t", outputFile, {"x"}); // check output contents ROOT::Experimental::TDataFrame checkTdf("t", outputFile); auto c = checkTdf.Count(); auto t = checkTdf.Take<int>("x"); for (auto v : t) EXPECT_EQ(v, 42); EXPECT_EQ(*c, nInputFiles); // clean-up input files for (auto i = 0u; i < nInputFiles; ++i) gSystem->Unlink((inputFilePrefix + std::to_string(i) + ".root").c_str()); gSystem->Unlink(outputFile); ROOT::DisableImplicitMT(); } void checkSnapshotArrayFileMT(TInterface<TLoopManager> &df, unsigned int kNEvents) { // fixedSizeArr and varSizeArr are TResultProxy<vector<vector<T>>> auto fixedSizeArr = df.Take<TArrayBranch<float>>("fixedSizeArr"); auto varSizeArr = df.Take<TArrayBranch<double>>("varSizeArr"); auto size = df.Take<unsigned int>("size"); // multi-thread execution might have scrambled events w.r.t. the original file, so we just check overall properties const auto nEvents = fixedSizeArr->size(); EXPECT_EQ(nEvents, kNEvents); // TODO check more! } TEST_F(TDFSnapshotArrays, MultiThread) { ROOT::EnableImplicitMT(4); TDataFrame tdf("arrayTree", kFileNames); auto dt = tdf.Snapshot<TArrayBranch<float>, unsigned int, TArrayBranch<double>>( "outTree", "test_snapshotTArrayBranchout.root", {"fixedSizeArr", "size", "varSizeArr"}); checkSnapshotArrayFileMT(dt, kNEvents); ROOT::DisableImplicitMT(); } TEST_F(TDFSnapshotArrays, MultiThreadJitted) { ROOT::EnableImplicitMT(4); TDataFrame tdf("arrayTree", kFileNames); auto dj = tdf.Snapshot("outTree", "test_snapshotTArrayBranchout.root", {"fixedSizeArr", "size", "varSizeArr"}); checkSnapshotArrayFileMT(dj, kNEvents); ROOT::DisableImplicitMT(); } TEST(TDFSnapshotMore, ColsWithCustomTitlesMT) { const auto fname = "colswithcustomtitlesmt.root"; const auto tname = "t"; // write test tree WriteColsWithCustomTitles(tname, fname); // read and write test tree with TDF (in parallel) ROOT::EnableImplicitMT(4); TDataFrame d(tname, fname); const std::string prefix = "snapshotted_"; auto res_tdf = d.Snapshot(tname, prefix + fname); // check correct results have been written out res_tdf.Foreach(CheckColsWithCustomTitles, {"tdfentry_", "i", "arrint", "vararrint", "float"}); // clean-up gSystem->Unlink(fname); gSystem->Unlink((prefix + fname).c_str()); ROOT::DisableImplicitMT(); } #endif
Add test for Snapshotting of branches with custom titles
[TDF] Add test for Snapshotting of branches with custom titles
C++
lgpl-2.1
olifre/root,root-mirror/root,olifre/root,root-mirror/root,olifre/root,root-mirror/root,karies/root,root-mirror/root,olifre/root,root-mirror/root,karies/root,karies/root,karies/root,karies/root,olifre/root,karies/root,root-mirror/root,karies/root,karies/root,olifre/root,olifre/root,root-mirror/root,olifre/root,root-mirror/root,olifre/root,karies/root,root-mirror/root,olifre/root,olifre/root,karies/root,karies/root,root-mirror/root,root-mirror/root
fa8bf8ff214ecfb6fec28d39a47be74e5fcc00a6
src/passes/Directize.cpp
src/passes/Directize.cpp
/* * Copyright 2019 WebAssembly Community Group participants * * 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. */ // // Turn indirect calls into direct calls. This is possible if we know // the table cannot change, and if we see a constant argument for the // indirect call's index. // #include <unordered_map> #include "ir/table-utils.h" #include "ir/type-updating.h" #include "ir/utils.h" #include "pass.h" #include "wasm-builder.h" #include "wasm-traversal.h" #include "wasm.h" namespace wasm { namespace { struct FunctionDirectizer : public WalkerPass<PostWalker<FunctionDirectizer>> { bool isFunctionParallel() override { return true; } Pass* create() override { return new FunctionDirectizer(tables); } FunctionDirectizer( const std::unordered_map<Name, TableUtils::FlatTable>& tables) : tables(tables) {} void visitCallIndirect(CallIndirect* curr) { auto it = tables.find(curr->table); if (it == tables.end()) { return; } auto& flatTable = it->second; // If the target is constant, we can emit a direct call. if (curr->target->is<Const>()) { std::vector<Expression*> operands(curr->operands.begin(), curr->operands.end()); replaceCurrent(makeDirectCall(operands, curr->target, flatTable, curr)); return; } // If the target is a select of two different constants, we can emit two // direct calls. // TODO: handle 3+ // TODO: handle the case where just one arm is a constant? if (auto* select = curr->target->dynCast<Select>()) { if (select->ifTrue->is<Const>() && select->ifFalse->is<Const>()) { Builder builder(*getModule()); auto* func = getFunction(); std::vector<Expression*> blockContents; // We must use the operands twice, and also must move the condition to // execute first; use locals for them all. While doing so, if we see // any are unreachable, stop trying to optimize and leave this for DCE. std::vector<Index> operandLocals; for (auto* operand : curr->operands) { if (operand->type == Type::unreachable || !TypeUpdating::canHandleAsLocal(operand->type)) { return; } auto currLocal = builder.addVar(func, operand->type); operandLocals.push_back(currLocal); blockContents.push_back(builder.makeLocalSet(currLocal, operand)); } if (select->condition->type == Type::unreachable) { return; } // Build the calls. auto numOperands = curr->operands.size(); auto getOperands = [&]() { std::vector<Expression*> newOperands(numOperands); for (Index i = 0; i < numOperands; i++) { newOperands[i] = builder.makeLocalGet(operandLocals[i], curr->operands[i]->type); } return newOperands; }; auto* ifTrueCall = makeDirectCall(getOperands(), select->ifTrue, flatTable, curr); auto* ifFalseCall = makeDirectCall(getOperands(), select->ifFalse, flatTable, curr); // Create the if to pick the calls, and emit the final block. auto* iff = builder.makeIf(select->condition, ifTrueCall, ifFalseCall); blockContents.push_back(iff); replaceCurrent(builder.makeBlock(blockContents)); // By adding locals we must make type adjustments at the end. changedTypes = true; } } } void doWalkFunction(Function* func) { WalkerPass<PostWalker<FunctionDirectizer>>::doWalkFunction(func); if (changedTypes) { ReFinalize().walkFunctionInModule(func, getModule()); TypeUpdating::handleNonDefaultableLocals(func, *getModule()); } } private: const std::unordered_map<Name, TableUtils::FlatTable>& tables; bool changedTypes = false; // Create a direct call for a given list of operands, an expression which is // known to contain a constant indicating the table offset, and the relevant // table. If we can see that the call will trap, instead return an // unreachable. Expression* makeDirectCall(const std::vector<Expression*>& operands, Expression* c, const TableUtils::FlatTable& flatTable, CallIndirect* original) { Index index = c->cast<Const>()->value.geti32(); // If the index is invalid, or the type is wrong, we can // emit an unreachable here, since in Binaryen it is ok to // reorder/replace traps when optimizing (but never to // remove them, at least not by default). if (index >= flatTable.names.size()) { return replaceWithUnreachable(operands); } auto name = flatTable.names[index]; if (!name.is()) { return replaceWithUnreachable(operands); } auto* func = getModule()->getFunction(name); if (original->sig != func->getSig()) { return replaceWithUnreachable(operands); } // Everything looks good! return Builder(*getModule()) .makeCall(name, operands, original->type, original->isReturn); } Expression* replaceWithUnreachable(const std::vector<Expression*>& operands) { // Emitting an unreachable means we must update parent types. changedTypes = true; Builder builder(*getModule()); std::vector<Expression*> newOperands; for (auto* operand : operands) { newOperands.push_back(builder.makeDrop(operand)); } return builder.makeSequence(builder.makeBlock(newOperands), builder.makeUnreachable()); } }; struct Directize : public Pass { void run(PassRunner* runner, Module* module) override { // Find which tables are valid to optimize on. They must not be imported nor // exported (so the outside cannot modify them), and must have no sets in // any part of the module. // First, find which tables have sets. using TablesWithSet = std::unordered_set<Name>; ModuleUtils::ParallelFunctionAnalysis<TablesWithSet> analysis( *module, [&](Function* func, TablesWithSet& tablesWithSet) { if (func->imported()) { return; } for (auto* set : FindAll<TableSet>(func->body).list) { tablesWithSet.insert(set->table); } }); TablesWithSet tablesWithSet; for (auto& kv : analysis.map) { for (auto name : kv.second) { tablesWithSet.insert(name); } } std::unordered_map<Name, TableUtils::FlatTable> validTables; for (auto& table : module->tables) { if (table->imported()) { continue; } if (tablesWithSet.count(table->name)) { continue; } bool canOptimizeCallIndirect = true; for (auto& ex : module->exports) { if (ex->kind == ExternalKind::Table && ex->value == table->name) { canOptimizeCallIndirect = false; break; } } if (!canOptimizeCallIndirect) { continue; } // All conditions are valid, this is optimizable. TableUtils::FlatTable flatTable(*module, *table); if (flatTable.valid) { validTables.emplace(table->name, flatTable); } } // Without typed function references, all we can do is optimize table // accesses, so if we can't do that, stop. if (validTables.empty() && !module->features.hasTypedFunctionReferences()) { return; } // The table exists and is constant, so this is possible. FunctionDirectizer(validTables).run(runner, module); } }; } // anonymous namespace Pass* createDirectizePass() { return new Directize(); } } // namespace wasm
/* * Copyright 2019 WebAssembly Community Group participants * * 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. */ // // Turn indirect calls into direct calls. This is possible if we know // the table cannot change, and if we see a constant argument for the // indirect call's index. // #include <unordered_map> #include "ir/table-utils.h" #include "ir/type-updating.h" #include "ir/utils.h" #include "pass.h" #include "wasm-builder.h" #include "wasm-traversal.h" #include "wasm.h" namespace wasm { namespace { struct FunctionDirectizer : public WalkerPass<PostWalker<FunctionDirectizer>> { bool isFunctionParallel() override { return true; } Pass* create() override { return new FunctionDirectizer(tables); } FunctionDirectizer( const std::unordered_map<Name, TableUtils::FlatTable>& tables) : tables(tables) {} void visitCallIndirect(CallIndirect* curr) { auto it = tables.find(curr->table); if (it == tables.end()) { return; } auto& flatTable = it->second; // If the target is constant, we can emit a direct call. if (curr->target->is<Const>()) { std::vector<Expression*> operands(curr->operands.begin(), curr->operands.end()); replaceCurrent(makeDirectCall(operands, curr->target, flatTable, curr)); return; } // If the target is a select of two different constants, we can emit two // direct calls. // TODO: handle 3+ // TODO: handle the case where just one arm is a constant? if (auto* select = curr->target->dynCast<Select>()) { if (select->ifTrue->is<Const>() && select->ifFalse->is<Const>()) { Builder builder(*getModule()); auto* func = getFunction(); std::vector<Expression*> blockContents; // We must use the operands twice, and also must move the condition to // execute first; use locals for them all. While doing so, if we see // any are unreachable, stop trying to optimize and leave this for DCE. std::vector<Index> operandLocals; for (auto* operand : curr->operands) { if (operand->type == Type::unreachable || !TypeUpdating::canHandleAsLocal(operand->type)) { return; } auto currLocal = builder.addVar(func, operand->type); operandLocals.push_back(currLocal); blockContents.push_back(builder.makeLocalSet(currLocal, operand)); } if (select->condition->type == Type::unreachable) { return; } // Build the calls. auto numOperands = curr->operands.size(); auto getOperands = [&]() { std::vector<Expression*> newOperands(numOperands); for (Index i = 0; i < numOperands; i++) { newOperands[i] = builder.makeLocalGet(operandLocals[i], curr->operands[i]->type); } return newOperands; }; auto* ifTrueCall = makeDirectCall(getOperands(), select->ifTrue, flatTable, curr); auto* ifFalseCall = makeDirectCall(getOperands(), select->ifFalse, flatTable, curr); // Create the if to pick the calls, and emit the final block. auto* iff = builder.makeIf(select->condition, ifTrueCall, ifFalseCall); blockContents.push_back(iff); replaceCurrent(builder.makeBlock(blockContents)); // By adding locals we must make type adjustments at the end. changedTypes = true; } } } void doWalkFunction(Function* func) { WalkerPass<PostWalker<FunctionDirectizer>>::doWalkFunction(func); if (changedTypes) { ReFinalize().walkFunctionInModule(func, getModule()); TypeUpdating::handleNonDefaultableLocals(func, *getModule()); } } private: const std::unordered_map<Name, TableUtils::FlatTable>& tables; bool changedTypes = false; // Create a direct call for a given list of operands, an expression which is // known to contain a constant indicating the table offset, and the relevant // table. If we can see that the call will trap, instead return an // unreachable. Expression* makeDirectCall(const std::vector<Expression*>& operands, Expression* c, const TableUtils::FlatTable& flatTable, CallIndirect* original) { Index index = c->cast<Const>()->value.geti32(); // If the index is invalid, or the type is wrong, we can // emit an unreachable here, since in Binaryen it is ok to // reorder/replace traps when optimizing (but never to // remove them, at least not by default). if (index >= flatTable.names.size()) { return replaceWithUnreachable(operands); } auto name = flatTable.names[index]; if (!name.is()) { return replaceWithUnreachable(operands); } auto* func = getModule()->getFunction(name); if (original->sig != func->getSig()) { return replaceWithUnreachable(operands); } // Everything looks good! return Builder(*getModule()) .makeCall(name, operands, original->type, original->isReturn); } Expression* replaceWithUnreachable(const std::vector<Expression*>& operands) { // Emitting an unreachable means we must update parent types. changedTypes = true; Builder builder(*getModule()); std::vector<Expression*> newOperands; for (auto* operand : operands) { newOperands.push_back(builder.makeDrop(operand)); } return builder.makeSequence(builder.makeBlock(newOperands), builder.makeUnreachable()); } }; struct Directize : public Pass { void run(PassRunner* runner, Module* module) override { // Find which tables are valid to optimize on. They must not be imported nor // exported (so the outside cannot modify them), and must have no sets in // any part of the module. // First, find which tables have sets. using TablesWithSet = std::unordered_set<Name>; ModuleUtils::ParallelFunctionAnalysis<TablesWithSet> analysis( *module, [&](Function* func, TablesWithSet& tablesWithSet) { if (func->imported()) { return; } for (auto* set : FindAll<TableSet>(func->body).list) { tablesWithSet.insert(set->table); } }); TablesWithSet tablesWithSet; for (auto& kv : analysis.map) { for (auto name : kv.second) { tablesWithSet.insert(name); } } std::unordered_map<Name, TableUtils::FlatTable> validTables; for (auto& table : module->tables) { if (table->imported()) { continue; } if (tablesWithSet.count(table->name)) { continue; } bool canOptimizeCallIndirect = true; for (auto& ex : module->exports) { if (ex->kind == ExternalKind::Table && ex->value == table->name) { canOptimizeCallIndirect = false; break; } } if (!canOptimizeCallIndirect) { continue; } // All conditions are valid, this is optimizable. TableUtils::FlatTable flatTable(*module, *table); if (flatTable.valid) { validTables.emplace(table->name, flatTable); } } if (validTables.empty()) { return; } FunctionDirectizer(validTables).run(runner, module); } }; } // anonymous namespace Pass* createDirectizePass() { return new Directize(); } } // namespace wasm
Remove forgotten call_ref-related logic in Directize. NFC (#4233)
Remove forgotten call_ref-related logic in Directize. NFC (#4233) We moved call_ref out of there, but it was still checking for the possible presence of call_refs (using the feature), which means that even if we had no valid tables to optimize on, we'd scan the whole module.
C++
apache-2.0
WebAssembly/binaryen,WebAssembly/binaryen,WebAssembly/binaryen,WebAssembly/binaryen,WebAssembly/binaryen
09de6999d368ee952da3cb4f3aa122cb198f4bda
tutorial/lesson_06_realizing_over_shifted_domains.cpp
tutorial/lesson_06_realizing_over_shifted_domains.cpp
// Halide tutorial lesson 6. // This lesson demonstrates how to evaluate a Func over a domain that // does not start at (0, 0). // This lesson can be built by invoking the command: // make tutorial_lesson_06_realizing_over_shifted_domains // in a shell with the current directory at the top of the halide source tree. // Otherwise, see the platform-specific compiler invocations below. // On linux, you can compile and run it like so: // g++ lesson_06*.cpp -g -I ../include -L ../bin -lHalide -lpthread -ldl -o lesson_06 // LD_LIBRARY_PATH=../bin ./lesson_06 // On os x: // g++ lesson_06*.cpp -g -I ../include -L ../bin -lHalide -o lesson_06 // DYLD_LIBRARY_PATH=../bin ./lesson_06 #include "Halide.h" #include <stdio.h> using namespace Halide; int main(int argc, char **argv) { // The last lesson was quite involved, and scheduling complex // multi-stage pipelines is ahead of us. As an interlude, let's // consider something easy: evaluating funcs over rectangular // domains that do not start at the origin. // We define our familiar gradient function. Func gradient("gradient"); Var x("x"), y("y"); gradient(x, y) = x + y; // And turn on tracing so we can see how it is being evaluated. gradient.trace_stores(); // Previously we've realized gradient like so: // // gradient.realize(8, 8); // // This does three things internally: // 1) Generates code than can evaluate gradient over an arbitrary // rectangle. // 2) Allocates a new 8 x 8 image. // 3) Runs the generated code to evaluate gradient for all x, y // from (0, 0) to (7, 7) and puts the result into the image. // 4) Returns the new image as the result of the realize call. // What if we're managing memory carefully and don't want Halide // to allocate a new image for us? We can call realize another // way. We can pass it an image we would like it to fill in. The // following evaluates our Func into an existing image: printf("Evaluating gradient from (0, 0) to (7, 7)\n"); Image<int> result(8, 8); gradient.realize(result); // Let's check it did what we expect: for (int y = 0; y < 8; y++) { for (int x = 0; x < 8; x++) { if (result(x, y) != x + y) { printf("Something went wrong!\n"); return -1; } } } // Now let's evaluate gradient over a 5 x 7 rectangle that starts // somewhere else -- at position (100, 50). So x and y will run // from (100, 50) to (104, 56) inclusive. // We start by creating an image that represents that rectangle: Image<int> shifted(5, 7); // In the constructor we tell it the size. shifted.set_min(100, 50); // Then we tell it the top-left corner. printf("Evaluating gradient from (100, 50) to (104, 56)\n"); // Note that this won't need to compile any new code, because when // we realized it the first time, we generated code capable of // evaluating gradient over an arbitrary rectangle. gradient.realize(shifted); // From C++, we also access the image object using coordinates // that start at (100, 50). for (int y = 50; y < 57; y++) { for (int x = 100; x < 105; x++) { if (shifted(x, y) != x + y) { printf("Something went wrong!\n"); return -1; } } } // The image 'shifted' stores the value of our Func over a domain // that starts at (100, 50), so asking for shifted(0, 0) would in // fact read out-of-bounds and probably crash. // What if we want to evaluate our Func over some region that // isn't rectangular? Too bad. Halide only does rectangles :) printf("Success!\n"); return 0; }
// Halide tutorial lesson 6. // This lesson demonstrates how to evaluate a Func over a domain that // does not start at (0, 0). // This lesson can be built by invoking the command: // make tutorial_lesson_06_realizing_over_shifted_domains // in a shell with the current directory at the top of the halide source tree. // Otherwise, see the platform-specific compiler invocations below. // On linux, you can compile and run it like so: // g++ lesson_06*.cpp -g -I ../include -L ../bin -lHalide -lpthread -ldl -o lesson_06 -std=c++11 // LD_LIBRARY_PATH=../bin ./lesson_06 // On os x: // g++ lesson_06*.cpp -g -I ../include -L ../bin -lHalide -o lesson_06 -std=c++11 // DYLD_LIBRARY_PATH=../bin ./lesson_06 #include "Halide.h" #include <stdio.h> using namespace Halide; int main(int argc, char **argv) { // The last lesson was quite involved, and scheduling complex // multi-stage pipelines is ahead of us. As an interlude, let's // consider something easy: evaluating funcs over rectangular // domains that do not start at the origin. // We define our familiar gradient function. Func gradient("gradient"); Var x("x"), y("y"); gradient(x, y) = x + y; // And turn on tracing so we can see how it is being evaluated. gradient.trace_stores(); // Previously we've realized gradient like so: // // gradient.realize(8, 8); // // This does three things internally: // 1) Generates code than can evaluate gradient over an arbitrary // rectangle. // 2) Allocates a new 8 x 8 image. // 3) Runs the generated code to evaluate gradient for all x, y // from (0, 0) to (7, 7) and puts the result into the image. // 4) Returns the new image as the result of the realize call. // What if we're managing memory carefully and don't want Halide // to allocate a new image for us? We can call realize another // way. We can pass it an image we would like it to fill in. The // following evaluates our Func into an existing image: printf("Evaluating gradient from (0, 0) to (7, 7)\n"); Image<int> result(8, 8); gradient.realize(result); // Let's check it did what we expect: for (int y = 0; y < 8; y++) { for (int x = 0; x < 8; x++) { if (result(x, y) != x + y) { printf("Something went wrong!\n"); return -1; } } } // Now let's evaluate gradient over a 5 x 7 rectangle that starts // somewhere else -- at position (100, 50). So x and y will run // from (100, 50) to (104, 56) inclusive. // We start by creating an image that represents that rectangle: Image<int> shifted(5, 7); // In the constructor we tell it the size. shifted.set_min(100, 50); // Then we tell it the top-left corner. printf("Evaluating gradient from (100, 50) to (104, 56)\n"); // Note that this won't need to compile any new code, because when // we realized it the first time, we generated code capable of // evaluating gradient over an arbitrary rectangle. gradient.realize(shifted); // From C++, we also access the image object using coordinates // that start at (100, 50). for (int y = 50; y < 57; y++) { for (int x = 100; x < 105; x++) { if (shifted(x, y) != x + y) { printf("Something went wrong!\n"); return -1; } } } // The image 'shifted' stores the value of our Func over a domain // that starts at (100, 50), so asking for shifted(0, 0) would in // fact read out-of-bounds and probably crash. // What if we want to evaluate our Func over some region that // isn't rectangular? Too bad. Halide only does rectangles :) printf("Success!\n"); return 0; }
Update lesson_06_realizing_over_shifted_domains.cpp
Update lesson_06_realizing_over_shifted_domains.cpp Fix compile command on linux Former-commit-id: 768e804335650bb9232fa5afd749ae8aa7d10548
C++
mit
darkbuck/Halide,Trass3r/Halide,Trass3r/Halide,darkbuck/Halide,Trass3r/Halide,Trass3r/Halide,darkbuck/Halide,Trass3r/Halide,darkbuck/Halide,darkbuck/Halide,darkbuck/Halide,Trass3r/Halide,darkbuck/Halide,Trass3r/Halide
9317620dcadfd953a6c2f0f06ea9903603da2047
examples/fft_verify.cpp
examples/fft_verify.cpp
#include <vexcl/vexcl.hpp> #include <vexcl/fft.hpp> #include <random> #include <fftw3.h> using namespace vex; float hsum(cl_float2 a) { return a.s[0] + a.s[1]; } #include <random> std::vector<cl_float2> random_vec(size_t n, float range) { std::vector<cl_float2> data(n); std::default_random_engine gen; std::uniform_real_distribution<float> dist(-range, range); for(size_t i = 0 ; i < n ; i++) data[i] = cl_float2{{dist(gen), dist(gen)}}; return data; } bool test(Context &ctx, std::vector<size_t> ns) { std::ostringstream name; for(size_t i = 0 ; i < ns.size() ; i++) { if(i > 0) name << 'x'; name << ns[i]; } char fc = std::cout.fill('.'); std::cout << name.str() << ": " << std::setw(62 - name.str().size()) << "." << std::flush; std::cout.fill(fc); size_t n = 1; for(size_t i = 0 ; i < ns.size() ; i++) n *= ns[i]; const float range = 1000; // random data. std::vector<cl_float2> input_h = random_vec(n, range); // reference. std::vector<cl_float2> ref_h(n); std::vector<int> ns_(ns.begin(), ns.end()); fftwf_plan p1 = fftwf_plan_dft(ns_.size(), ns_.data(), reinterpret_cast<fftwf_complex *>(&input_h[0]), reinterpret_cast<fftwf_complex *>(&ref_h[0]), FFTW_FORWARD, FFTW_ESTIMATE); fftwf_execute(p1); fftwf_destroy_plan(p1); // test vector<cl_float2> input(ctx.queue(), input_h); vector<cl_float2> output(ctx.queue(), n); vector<cl_float2> ref(ctx.queue(), ref_h); vector<cl_float2> back(ctx.queue(), n); Reductor<cl_float2, SUM> sum(ctx.queue()); #define rms(e) (100 * std::sqrt(hsum(sum(pow(e, 2))) / n) / range) try { FFT<cl_float2> fft(ctx.queue(), ns); output = fft(input); bool rc = true; const float rms_fft = rms(output - ref); rc &= rms_fft < 0.1; FFT<cl_float2> ifft(ctx.queue(), ns, inverse); back = ifft(output); const float rms_inv = rms(input - back); rc &= rms_inv < 1e-4; std::cout << (rc ? " success." : " failed.") << '\n'; std::cout << " fftw-clfft " << rms_fft << "%" << '\n'; std::cout << " x-ifft(fft(x)) " << rms_inv << "%" << '\n'; std::cout << fft.plan << '\n'; return rc; } catch(cl::Error e) { std::cerr << "FFT error " << ": " << e << std::endl; throw; } } double skew_rand(double p) { return std::pow(1.0 * rand() / RAND_MAX, p); } int main() { Context ctx(Filter::Env && Filter::Count(1), CL_QUEUE_PROFILING_ENABLE); std::cout << ctx << std::endl; bool rc = true; const size_t max = 1 << 20; fft::default_planner p; for(size_t i = 0 ; i < 20 ; i++) { // random number of dimensions, mostly 1. size_t dims = 1 + size_t(skew_rand(3) * 5); // random size. std::vector<size_t> n; size_t d_max = std::pow(max, 1.0 / dims); size_t total = 1; for(size_t d = 0 ; d < dims ; d++) { size_t sz = 1 + size_t(skew_rand(dims == 1 ? 3 : 1) * d_max); sz = p.best_size(sz); n.push_back(sz); total *= sz; } // run if(total <= max) rc &= test(ctx, n); } return rc ? EXIT_SUCCESS : EXIT_FAILURE; }
#include <vexcl/vexcl.hpp> #include <vexcl/fft.hpp> #include <random> #include <fftw3.h> using namespace vex; typedef double T; typedef cl_vector_of<T, 2>::type T2; std::vector<cl_double2> random_vec(size_t n) { std::vector<cl_double2> data(n); for(size_t i = 0 ; i < n ; i++) { data[i].s[0] = 1.0 * rand() / RAND_MAX - 0.5; data[i].s[1] = 1.0 * rand() / RAND_MAX - 0.5; } return data; } bool test(Context &ctx, std::vector<size_t> ns) { std::ostringstream name; for(size_t i = 0 ; i < ns.size() ; i++) { if(i > 0) name << 'x'; name << ns[i]; } char fc = std::cout.fill('.'); std::cout << name.str() << ": " << std::setw(62 - name.str().size()) << "." << std::flush; std::cout.fill(fc); size_t n = 1; for(size_t i = 0 ; i < ns.size() ; i++) n *= ns[i]; // random data. std::vector<cl_double2> input_h = random_vec(n); // reference. std::vector<cl_double2> ref_h(n); std::vector<int> ns_(ns.begin(), ns.end()); fftw_plan p1 = fftw_plan_dft(ns_.size(), ns_.data(), reinterpret_cast<fftw_complex *>(&input_h[0]), reinterpret_cast<fftw_complex *>(&ref_h[0]), FFTW_FORWARD, FFTW_ESTIMATE); fftw_execute(p1); fftw_destroy_plan(p1); // convert to clFFT precision std::vector<T2> input_h_t(n), ref_h_t(n); for(size_t i = 0; i != n ; i++) { input_h_t[i] = cl_convert<T2>(input_h[i]); ref_h_t[i] = cl_convert<T2>(ref_h[i]); } // test vector<T2> input(ctx.queue(), input_h_t); vector<T2> output(ctx.queue(), n); vector<T2> ref(ctx.queue(), ref_h_t); vector<T2> back(ctx.queue(), n); Reductor<T, SUM> sum(ctx.queue()); #define rms(a,b) (std::sqrt(sum(dot(a - b, a - b))) / std::sqrt(sum(dot(b, b)))) try { FFT<T2> fft(ctx.queue(), ns); output = fft(input); bool rc = true; const T rms_fft = rms(output, ref); rc &= rms_fft < 0.1; FFT<T2> ifft(ctx.queue(), ns, inverse); back = ifft(output); const T rms_inv = rms(back, input); rc &= rms_inv < 1e-3; std::cout << (rc ? " success." : " failed.") << '\n'; if(!rc) { std::cout << " fftw-clfft " << rms_fft << "%" << '\n'; std::cout << " x-ifft(fft(x)) " << rms_inv << "%" << '\n'; std::cout << fft.plan << '\n'; } return rc; } catch(cl::Error e) { std::cerr << "FFT error " << ": " << e << std::endl; throw; } } double skew_rand(double p) { return std::pow(1.0 * rand() / RAND_MAX, p); } int main() { Context ctx(Filter::Env && Filter::Count(1), CL_QUEUE_PROFILING_ENABLE); std::cout << ctx << std::endl; srand(23); bool rc = true; const size_t max = 1 << 20; fft::default_planner p; for(size_t i = 0 ; i < 100 ; i++) { // random number of dimensions, mostly 1. size_t dims = 1 + size_t(skew_rand(3) * 5); // random size. std::vector<size_t> n; size_t d_max = std::pow(max, 1.0 / dims); size_t total = 1; for(size_t d = 0 ; d < dims ; d++) { size_t sz = 1 + size_t(skew_rand(dims == 1 ? 3 : 1) * d_max); if(rand() % 7 != 0) sz = p.best_size(sz); n.push_back(sz); total *= sz; } // run if(total <= max) rc &= test(ctx, n); } return rc ? EXIT_SUCCESS : EXIT_FAILURE; }
Verify float/double CLFFT against double FFTw
Verify float/double CLFFT against double FFTw
C++
mit
Poulpy21/vexcl,kapadia/vexcl,kapadia/vexcl,ddemidov/vexcl,Poulpy21/vexcl,ddemidov/vexcl,Poulpy21/vexcl
895af0ad492132de063db8c9e8e0684f452986c0
src/plang/Redirector.cpp
src/plang/Redirector.cpp
// // Copyright (C) 2011 Mateusz Loskot <[email protected]> // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // Blog article: http://mateusz.loskot.net/?p=2819 #include <pdal/pdal_internal.hpp> #ifdef PDAL_HAVE_PYTHON #include "Redirector.hpp" #ifdef PDAL_COMPILER_MSVC # pragma warning(disable: 4127) // conditional expression is constant #endif #include <Python.h> namespace pdal { namespace plang { struct Stdout { PyObject_HEAD Redirector::stdout_write_type write; }; static PyObject* Stdout_write(PyObject* self, PyObject* args) { std::size_t written(0); Stdout* selfimpl = reinterpret_cast<Stdout*>(self); if (selfimpl->write) { char* data; if (!PyArg_ParseTuple(args, "s", &data)) return 0; std::string str(data); selfimpl->write(str); written = str.size(); } return PyLong_FromSize_t(written); } static PyObject* Stdout_flush(PyObject* /*self*/, PyObject* /*args*/) { // no-op return Py_BuildValue(""); } static PyMethodDef Stdout_methods[] = { {"write", Stdout_write, METH_VARARGS, "sys.stdout.write"}, {"flush", Stdout_flush, METH_VARARGS, "sys.stdout.write"}, {0, 0, 0, 0} // sentinel }; static PyTypeObject StdoutType = { PyVarObject_HEAD_INIT(0, 0) "redirector.StdoutType", /* tp_name */ sizeof(Stdout), /* tp_basicsize */ 0, /* tp_itemsize */ 0, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT, /* tp_flags */ "redirector.Stdout objects", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ Stdout_methods, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ 0, /* tp_init */ 0, /* tp_alloc */ 0, /* tp_new */ 0, /* tp_free */ 0, /* tp_is_gc */ 0, /* tp_bases */ 0, /* tp_mro */ 0, /* tp_cache */ 0, /* tp_subclasses */ 0, /* tp_weaklist */ 0, /* tp_del */ 0, /* tp_version_tag */ }; Redirector::Redirector() : m_stdout(NULL) , m_stdout_saved(NULL) { return; } Redirector::~Redirector() { return; } PyMODINIT_FUNC redirector_init(void) { Redirector::init(); } void Redirector::init() { StdoutType.tp_new = PyType_GenericNew; if (PyType_Ready(&StdoutType) < 0) return; PyObject* m = Py_InitModule3("redirector", 0, 0); if (m) { Py_INCREF(&StdoutType); PyModule_AddObject(m, "Stdout", reinterpret_cast<PyObject*>(&StdoutType)); } return; } static void my2argwriterfunction(std::ostream* ostr, const std::string& mssg) { *ostr << mssg; } void Redirector::set_stdout(std::ostream* ostr) { stdout_write_type my1argwriterfunction = boost::bind(&my2argwriterfunction, ostr, _1); this->set_stdout(my1argwriterfunction); return; } void Redirector::set_stdout(stdout_write_type write) { if (!m_stdout) { m_stdout_saved = PySys_GetObject("stdout"); // borrowed m_stdout = StdoutType.tp_new(&StdoutType, 0, 0); } Stdout* impl = reinterpret_cast<Stdout*>(m_stdout); impl->write = write; PySys_SetObject("stdout", m_stdout); } void Redirector::reset_stdout() { if (m_stdout_saved) PySys_SetObject("stdout", m_stdout_saved); Py_XDECREF(m_stdout); m_stdout = 0; } } //namespaces } #endif
// // Copyright (C) 2011 Mateusz Loskot <[email protected]> // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // Blog article: http://mateusz.loskot.net/?p=2819 #include <pdal/pdal_internal.hpp> #ifdef PDAL_HAVE_PYTHON #include "Redirector.hpp" #ifdef PDAL_COMPILER_MSVC # pragma warning(disable: 4127) // conditional expression is constant #endif #include <Python.h> namespace pdal { namespace plang { struct Stdout { PyObject_HEAD Redirector::stdout_write_type write; }; static PyObject* Stdout_write(PyObject* self, PyObject* args) { std::size_t written(0); Stdout* selfimpl = reinterpret_cast<Stdout*>(self); if (selfimpl->write) { char* data; if (!PyArg_ParseTuple(args, "s", &data)) return 0; std::string str(data); selfimpl->write(str); written = str.size(); } return PyLong_FromSize_t(written); } static PyObject* Stdout_flush(PyObject* /*self*/, PyObject* /*args*/) { // no-op return Py_BuildValue(""); } static PyMethodDef Stdout_methods[] = { {"write", Stdout_write, METH_VARARGS, "sys.stdout.write"}, {"flush", Stdout_flush, METH_VARARGS, "sys.stdout.write"}, {0, 0, 0, 0} // sentinel }; static PyTypeObject StdoutType = { PyVarObject_HEAD_INIT(0, 0) "redirector.StdoutType", /* tp_name */ sizeof(Stdout), /* tp_basicsize */ 0, /* tp_itemsize */ 0, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT, /* tp_flags */ "redirector.Stdout objects", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ Stdout_methods, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ 0, /* tp_init */ 0, /* tp_alloc */ 0, /* tp_new */ 0, /* tp_free */ 0, /* tp_is_gc */ 0, /* tp_bases */ 0, /* tp_mro */ 0, /* tp_cache */ 0, /* tp_subclasses */ 0, /* tp_weaklist */ 0, /* tp_del */ 0, /* tp_version_tag */ }; Redirector::Redirector() : m_stdout(NULL) , m_stdout_saved(NULL) { return; } Redirector::~Redirector() { return; } PyMODINIT_FUNC redirector_init(void) { Redirector::init(); } void Redirector::init() { StdoutType.tp_new = PyType_GenericNew; if (PyType_Ready(&StdoutType) < 0) return; PyObject* m = Py_InitModule3("redirector", 0, 0); if (m) { Py_INCREF(&StdoutType); PyModule_AddObject(m, "Stdout", reinterpret_cast<PyObject*>(&StdoutType)); } return; } static void my2argwriterfunction(std::ostream* ostr, const std::string& mssg) { *ostr << mssg; } void Redirector::set_stdout(std::ostream* ostr) { stdout_write_type my1argwriterfunction = boost::bind(&my2argwriterfunction, ostr, _1); this->set_stdout(my1argwriterfunction); return; } void Redirector::set_stdout(stdout_write_type write) { if (!m_stdout) { m_stdout_saved = PySys_GetObject(const_cast<char*>("stdout")); // borrowed m_stdout = StdoutType.tp_new(&StdoutType, 0, 0); } Stdout* impl = reinterpret_cast<Stdout*>(m_stdout); impl->write = write; PySys_SetObject(const_cast<char*>("stdout"), m_stdout); } void Redirector::reset_stdout() { if (m_stdout_saved) PySys_SetObject(const_cast<char*>("stdout"), m_stdout_saved); Py_XDECREF(m_stdout); m_stdout = 0; } } //namespaces } #endif
clean up some const_cast'able warnings
clean up some const_cast'able warnings
C++
bsd-3-clause
Sciumo/PDAL,verma/PDAL,lucadelu/PDAL,mtCarto/PDAL,mtCarto/PDAL,DougFirErickson/PDAL,jwomeara/PDAL,boundlessgeo/PDAL,DougFirErickson/PDAL,lucadelu/PDAL,radiantbluetechnologies/PDAL,mpgerlek/PDAL-old,radiantbluetechnologies/PDAL,mpgerlek/PDAL-old,DougFirErickson/PDAL,boundlessgeo/PDAL,Sciumo/PDAL,verma/PDAL,DougFirErickson/PDAL,mtCarto/PDAL,Sciumo/PDAL,mtCarto/PDAL,verma/PDAL,verma/PDAL,mpgerlek/PDAL-old,verma/PDAL,lucadelu/PDAL,mpgerlek/PDAL-old,verma/PDAL,jwomeara/PDAL,verma/PDAL,jwomeara/PDAL,boundlessgeo/PDAL,boundlessgeo/PDAL,radiantbluetechnologies/PDAL,radiantbluetechnologies/PDAL,Sciumo/PDAL,jwomeara/PDAL,lucadelu/PDAL
c40b62f9066bedffcbcc17b2203524a15719a9ab
src/platformer/world.cpp
src/platformer/world.cpp
#include "world.h" #include "animation.h" #include "background.h" #include "camera.h" #include "util/bitmap.h" #include "util/debug.h" #include "util/file-system.h" #include "util/load_exception.h" #include "util/token.h" #include "util/tokenreader.h" using namespace std; using namespace Platformer; World::World(const Token * token): resolutionX(0), resolutionY(0), dimensionsX(0), dimensionsY(0){ if ( *token != "world" ){ throw LoadException(__FILE__, __LINE__, "Not world."); } if (token->numTokens() == 1){ std::string temp; token->view() >> temp; load(Filesystem::find(Filesystem::RelativePath(temp))); } else { load(token); } } void World::load(const Filesystem::AbsolutePath & filename){ // Load up tokenizer try{ Global::debug(1,"World") << "Loading world " << filename.path() << endl; TokenReader tr(filename.path()); Token * token = tr.readToken(); load(token); } catch (const TokenException & e){ throw LoadException(__FILE__, __LINE__, e, "Error loading World"); } } void World::load(const Token * token){ TokenView view = token->view(); while (view.hasMore()){ try{ const Token * tok; view >> tok; if (*tok == "name"){ // get the name tok->view() >> name; Global::debug(0, "Platformer") << "Loading :" << name << endl; } else if (*tok == "resolution"){ // Get the resolution of the world tok->view() >> resolutionX >> resolutionY; } else if (*tok == "dimensions"){ // Get the dimensions of the world tok->view() >> dimensionsX >> dimensionsY; } else if (*tok == "players"){ // Handle player info eventually } else if (*tok == "camera"){ // Handle camera info Camera * camera = new Camera(resolutionX, resolutionY, dimensionsX, dimensionsY, tok); cameras[camera->getId()] = camera; } else if (*tok == "animation"){ Animation * animation = new Animation(tok); animations[animation->getId()] = animation; } else if (*tok == "background"){ Background * background = new Background(tok, animations); backgrounds.push_back(background); } else { Global::debug( 3 ) << "Unhandled World attribute: "<<endl; if (Global::getDebug() >= 3){ token->print(" "); } } } catch ( const TokenException & ex ) { throw LoadException(__FILE__, __LINE__, ex, "World parse error"); } catch ( const LoadException & ex ) { throw ex; } } } World::~World(){ for (std::map< int, Camera *>::iterator i = cameras.begin(); i != cameras.end(); ++i){ if (i->second){ delete i->second; } } for (std::map< std::string, Animation *>::iterator i = animations.begin(); i != animations.end(); ++i){ if (i->second){ delete i->second; } } for (std::vector< Background *>::iterator i = backgrounds.begin(); i != backgrounds.end(); ++i){ if (*i){ delete *i; } } } void World::act(){ cameras[0]->act(); for (std::map< std::string, Animation *>::iterator i = animations.begin(); i != animations.end(); ++i){ Animation * animation = i->second; if (animation){ animation->act(); } } for (std::vector< Background *>::iterator i = backgrounds.begin(); i != backgrounds.end(); ++i){ Background * background = *i; if (background){ background->act(); } } } void World::draw(const Bitmap & bmp){ // FIXME Must correct so that cameras are handled properly for (std::vector< Background *>::iterator i = backgrounds.begin(); i != backgrounds.end(); ++i){ Background * background = *i; if (background){ background->draw(*cameras[0]); } } Bitmap temp = Bitmap::temporaryBitmap(resolutionX, resolutionY); cameras[0]->draw(temp); temp.Stretch(bmp); } void World::moveCamera(int x, int y){ // FIXME this needs to change to accomodate the cameras accordingly cameras[0]->move(x,y); } const Camera & World::getCamera(int number){ // FIXME this needs to change to accomodate the cameras accordingly return *cameras[number]; }
#include "world.h" #include "animation.h" #include "background.h" #include "camera.h" #include "util/bitmap.h" #include "util/debug.h" #include "util/file-system.h" #include "util/load_exception.h" #include "util/token.h" #include "util/tokenreader.h" using namespace std; using namespace Platformer; World::World(const Token * token): resolutionX(0), resolutionY(0), dimensionsX(0), dimensionsY(0){ if ( *token != "world" ){ throw LoadException(__FILE__, __LINE__, "Not world."); } if (token->numTokens() == 1){ std::string temp; token->view() >> temp; load(Filesystem::find(Filesystem::RelativePath(temp))); } else { load(token); } } void World::load(const Filesystem::AbsolutePath & filename){ // Load up tokenizer try{ Global::debug(1,"World") << "Loading world " << filename.path() << endl; TokenReader tr(filename.path()); Token * token = tr.readToken(); load(token); } catch (const TokenException & e){ throw LoadException(__FILE__, __LINE__, e, "Error loading World"); } } void World::load(const Token * token){ TokenView view = token->view(); while (view.hasMore()){ try{ const Token * tok; view >> tok; if (*tok == "name"){ // get the name tok->view() >> name; Global::debug(0, "Platformer") << "Loading:" << name << endl; } else if (*tok == "resolution"){ // Get the resolution of the world tok->view() >> resolutionX >> resolutionY; } else if (*tok == "dimensions"){ // Get the dimensions of the world tok->view() >> dimensionsX >> dimensionsY; } else if (*tok == "players"){ // Handle player info eventually } else if (*tok == "camera"){ // Handle camera info Camera * camera = new Camera(resolutionX, resolutionY, dimensionsX, dimensionsY, tok); cameras[camera->getId()] = camera; } else if (*tok == "animation"){ Animation * animation = new Animation(tok); animations[animation->getId()] = animation; } else if (*tok == "background"){ Background * background = new Background(tok, animations); backgrounds.push_back(background); } else { Global::debug( 3 ) << "Unhandled World attribute: "<<endl; if (Global::getDebug() >= 3){ token->print(" "); } } } catch ( const TokenException & ex ) { throw LoadException(__FILE__, __LINE__, ex, "World parse error"); } catch ( const LoadException & ex ) { throw ex; } } } World::~World(){ for (std::map< int, Camera *>::iterator i = cameras.begin(); i != cameras.end(); ++i){ if (i->second){ delete i->second; } } for (std::map< std::string, Animation *>::iterator i = animations.begin(); i != animations.end(); ++i){ if (i->second){ delete i->second; } } for (std::vector< Background *>::iterator i = backgrounds.begin(); i != backgrounds.end(); ++i){ if (*i){ delete *i; } } } void World::act(){ cameras[0]->act(); for (std::map< std::string, Animation *>::iterator i = animations.begin(); i != animations.end(); ++i){ Animation * animation = i->second; if (animation){ animation->act(); } } for (std::vector< Background *>::iterator i = backgrounds.begin(); i != backgrounds.end(); ++i){ Background * background = *i; if (background){ background->act(); } } } void World::draw(const Bitmap & bmp){ // FIXME Must correct so that cameras are handled properly for (std::vector< Background *>::iterator i = backgrounds.begin(); i != backgrounds.end(); ++i){ Background * background = *i; if (background){ background->draw(*cameras[0]); } } Bitmap temp = Bitmap::temporaryBitmap(resolutionX, resolutionY); cameras[0]->draw(temp); temp.Stretch(bmp); } void World::moveCamera(int x, int y){ // FIXME this needs to change to accomodate the cameras accordingly cameras[0]->move(x,y); } const Camera & World::getCamera(int number){ // FIXME this needs to change to accomodate the cameras accordingly return *cameras[number]; }
Remove space from out text.
Remove space from out text. git-svn-id: 39e099a8ed5324aded674b764a67f7a08796d9a7@5235 662fdd30-d327-0410-a531-f549c87e1e9e
C++
bsd-3-clause
boyjimeking/paintown,Sevalecan/paintown,Sevalecan/paintown,Sevalecan/paintown,boyjimeking/paintown,boyjimeking/paintown,Sevalecan/paintown,boyjimeking/paintown,Sevalecan/paintown,boyjimeking/paintown,boyjimeking/paintown,Sevalecan/paintown,Sevalecan/paintown,boyjimeking/paintown,Sevalecan/paintown,boyjimeking/paintown
ac5e8685a779014a23dd7f0f52cf10b6bdd44e29
examples/subscriber.cpp
examples/subscriber.cpp
/////////////////////////////////////////////////////////////////////////////// // // Copyright (c) Tavendo GmbH // // Boost Software License - Version 1.0 - August 17th, 2003 // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // /////////////////////////////////////////////////////////////////////////////// #include "parameters.hpp" #include <autobahn/autobahn.hpp> #include <boost/asio.hpp> #include <iostream> #include <memory> #include <tuple> void topic1(const autobahn::wamp_event& event) { std::cerr << "received event: " << event.argument<uint64_t>(0) << std::endl; } int main(int argc, char** argv) { try { auto parameters = get_parameters(argc, argv); std::cerr << "realm: " << parameters->realm() << std::endl; boost::asio::io_service io; boost::asio::ip::tcp::socket socket(io); bool debug = parameters->debug(); auto session = std::make_shared< autobahn::wamp_session<boost::asio::ip::tcp::socket, boost::asio::ip::tcp::socket>>(io, socket, socket, debug); // Make sure the continuation futures we use do not run out of scope prematurely. // Since we are only using one thread here this can cause the io service to block // as a future generated by a continuation will block waiting for its promise to be // fulfilled when it goes out of scope. This would prevent the session from receiving // responses from the router. boost::future<void> start_future; boost::future<void> join_future; socket.async_connect(parameters->rawsocket_endpoint(), [&](boost::system::error_code ec) { if (!ec) { std::cerr << "connected to server" << std::endl; start_future = session->start().then([&](boost::future<bool> started) { if (started.get()) { std::cerr << "session started" << std::endl; join_future = session->join(parameters->realm()).then([&](boost::future<uint64_t> s) { std::cerr << "joined realm: " << s.get() << std::endl; session->subscribe("com.examples.subscriptions.topic1", &topic1); }); } else { std::cerr << "failed to start session" << std::endl; io.stop(); } }); } else { std::cerr << "connect failed: " << ec.message() << std::endl; io.stop(); } } ); std::cerr << "starting io service" << std::endl; io.run(); std::cerr << "stopped io service" << std::endl; } catch (std::exception& e) { std::cerr << e.what() << std::endl; return 1; } return 0; }
/////////////////////////////////////////////////////////////////////////////// // // Copyright (c) Tavendo GmbH // // Boost Software License - Version 1.0 - August 17th, 2003 // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // /////////////////////////////////////////////////////////////////////////////// #include "parameters.hpp" #include <autobahn/autobahn.hpp> #include <boost/asio.hpp> #include <iostream> #include <memory> #include <tuple> void topic1(const autobahn::wamp_event& event) { std::cerr << "received event: " << event.argument<std::string>(0) << std::endl; } int main(int argc, char** argv) { try { auto parameters = get_parameters(argc, argv); std::cerr << "realm: " << parameters->realm() << std::endl; boost::asio::io_service io; boost::asio::ip::tcp::socket socket(io); bool debug = parameters->debug(); auto session = std::make_shared< autobahn::wamp_session<boost::asio::ip::tcp::socket, boost::asio::ip::tcp::socket>>(io, socket, socket, debug); // Make sure the continuation futures we use do not run out of scope prematurely. // Since we are only using one thread here this can cause the io service to block // as a future generated by a continuation will block waiting for its promise to be // fulfilled when it goes out of scope. This would prevent the session from receiving // responses from the router. boost::future<void> start_future; boost::future<void> join_future; socket.async_connect(parameters->rawsocket_endpoint(), [&](boost::system::error_code ec) { if (!ec) { std::cerr << "connected to server" << std::endl; start_future = session->start().then([&](boost::future<bool> started) { if (started.get()) { std::cerr << "session started" << std::endl; join_future = session->join(parameters->realm()).then([&](boost::future<uint64_t> s) { std::cerr << "joined realm: " << s.get() << std::endl; session->subscribe("com.examples.subscriptions.topic1", &topic1); }); } else { std::cerr << "failed to start session" << std::endl; io.stop(); } }); } else { std::cerr << "connect failed: " << ec.message() << std::endl; io.stop(); } } ); std::cerr << "starting io service" << std::endl; io.run(); std::cerr << "stopped io service" << std::endl; } catch (std::exception& e) { std::cerr << e.what() << std::endl; return 1; } return 0; }
Fix invalid type conversion in publish example
Fix invalid type conversion in publish example The publish example was not working correctly because the the subscriber was trying to receive the event argument as an integer instead of a as a string. Resolves: #64 #80
C++
apache-2.0
tavendo/AutobahnCpp,tavendo/AutobahnCpp
9398575340f944fa35436193174a01ea1ac7b41b
src/main.cpp
src/main.cpp
#include <iostream> #include "TestFramework/TestFramework.h" #include "Tests/TestExample.h" #include "Tests/PulseMessageWrapper/TestPulseMessageWrapper.h" #include "Tests/HeightMeasurementStatemachine/TestHeightMeasurementStatemachine.h" #include "TestFramework/TestSuite.h" <<<<<<< HEAD #include "LightSystemTest.h" ======= #include "Tests/Serial/TestSerial.h" #include "Tests/Serial/SerialProtocollTest.h" #include "FullSerialTest.h" #include "Logger/Logger.h" >>>>>>> devel using namespace std; int main() { //################################################################################// //## THIS IS THE TEST MAIN, ADD A TEST FOR YOUR MODULE INSTEAD OF WRITING A MAIN##// //################################################################################// TestSuite ts; LOG_SET_LEVEL(DEBUG); //^ DO NOT TOUCH ^// //######################################################// //## REGISTER YOUR TESTS HERE LIKE THIS EXAMPLE SHOWS ##// //######################################################// //TEST FOR: Example Tests //ts.REG_TESTCASE(new TestExample(1, "This is an example")); //ts.REG_TESTCASE(new TestExample(2, "This is another one")); //ts.REG_TESTCASE(new TestExample(3, "And a third one")); // END Example Tests // PulseMessageWrapper tests ts.REG_TESTCASE(new TestPulseMessageWrapper(1, "Send and Receive pulse messages")); // HeightMeasurement tests ts.REG_TESTCASE(new TestHeightMeasurementStatemachine(2, "Make transitions through the statemachine of every type of puck")) // LightSystem tests ts.REG_TESTCASE(new LightSystemTest(3, "LightSystem: Level: Operating")); //TEST FOR: Serial ts.REG_TESTCASE(new TestSerial(4, "[Serial] Basic Tests for Serial")); ts.REG_TESTCASE(new SerialProtocollTest(5, "[SerialProtocoll] Test for the toplvl prot")); ts.REG_TESTCASE(new FullSerialTest(6, "[Serial] Full Serial test")); //########################################// //##THIS STARTS THE TESTS, DO NOT TOUCH ##// //########################################// ts.START_TEST("/TEST_RESULT.txt"); return 0; }
#include <iostream> #include "TestFramework/TestFramework.h" #include "Tests/TestExample.h" #include "Tests/PulseMessageWrapper/TestPulseMessageWrapper.h" #include "Tests/HeightMeasurementStatemachine/TestHeightMeasurementStatemachine.h" #include "TestFramework/TestSuite.h" #include "LightSystemTest.h" #include "Tests/Serial/TestSerial.h" #include "Tests/Serial/SerialProtocollTest.h" #include "FullSerialTest.h" #include "Logger/Logger.h" using namespace std; int main() { //################################################################################// //## THIS IS THE TEST MAIN, ADD A TEST FOR YOUR MODULE INSTEAD OF WRITING A MAIN##// //################################################################################// TestSuite ts; LOG_SET_LEVEL(DEBUG); //^ DO NOT TOUCH ^// //######################################################// //## REGISTER YOUR TESTS HERE LIKE THIS EXAMPLE SHOWS ##// //######################################################// //TEST FOR: Example Tests //ts.REG_TESTCASE(new TestExample(1, "This is an example")); //ts.REG_TESTCASE(new TestExample(2, "This is another one")); //ts.REG_TESTCASE(new TestExample(3, "And a third one")); // END Example Tests // PulseMessageWrapper tests ts.REG_TESTCASE(new TestPulseMessageWrapper(1, "Send and Receive pulse messages")); // HeightMeasurement tests ts.REG_TESTCASE(new TestHeightMeasurementStatemachine(2, "Make transitions through the statemachine of every type of puck")) // LightSystem tests ts.REG_TESTCASE(new LightSystemTest(3, "LightSystem: Level: Operating")); //TEST FOR: Serial ts.REG_TESTCASE(new TestSerial(4, "[Serial] Basic Tests for Serial")); ts.REG_TESTCASE(new SerialProtocollTest(5, "[SerialProtocoll] Test for the toplvl prot")); ts.REG_TESTCASE(new FullSerialTest(6, "[Serial] Full Serial test")); //########################################// //##THIS STARTS THE TESTS, DO NOT TOUCH ##// //########################################// ts.START_TEST("/TEST_RESULT.txt"); return 0; }
Fix stray merge headers
Fix stray merge headers
C++
mit
ReneHerthel/ConveyorBelt,ReneHerthel/ConveyorBelt
82c2b5896821ba6d2b1c3c988f7175c4d6e52609
src/feeders/routeFeeder/routeFeeder.cpp
src/feeders/routeFeeder/routeFeeder.cpp
#include <stdio.h> #include <sysexits.h> // portablish exit values. #include <stdlib.h> #include <netinet/in.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <sys/time.h> #include <string.h> #include <assert.h> #include <string> #include <client.h> // we are a client of the watcher. #include <libwatcher/edgeMessage.h> // we send edgeMessages to the watcher. #include <logger.h> using namespace std; using namespace watcher; using namespace watcher::event; static const char *rcsid __attribute__ ((unused)) = "$Id: routingfeeder.c,v 1.0 2009/04/28 22:08:47 glawler Exp $"; // #define DEBUG 1 /* This is a feeder which polls the routing table, * and draws the routing algorithm's edges on the watcher * * Copyright (C) 2006,2007,2008,2009 Sparta Inc. Written by the NIP group, SRD, ISSO */ typedef struct Route { unsigned int dst; unsigned int nexthop; unsigned int mask; char iface[16]; struct Route *next; } Route; /* Iface Destination Gateway Flags RefCnt Use Metric Mask MTU Window IRTT eth0 7402A8C0 7C02A8C0 0007 0 0 0 FFFFFFFF 00 0 eth0 7402A8C0 7202A8C0 0007 0 0 0 FFFFFFFF 00 0 */ static Route *routeRead(unsigned int network, unsigned int netmask) { TRACE_ENTER(); FILE *fil; char line[1024]; Route *list=NULL,*nxt; fil=fopen("/proc/net/route","r"); while(fgets(line,sizeof(line)-1,fil)) { char iface[16]; int flags,refcnt,use,metric,mtu,window; unsigned int dst,nexthop,mask; int rc; rc=sscanf(line,"%s\t%x\t%x\t%d\t%d\t%d\t%d\t%x\t%o\t%d\n",iface,&dst,&nexthop,&flags,&refcnt,&use,&metric,&mask,&mtu,&window); if (rc==10 && ((ntohl(dst) & ntohl(netmask)) == ntohl(network))) { nxt = (Route*)malloc(sizeof(*nxt)); assert(nxt!=NULL); nxt->dst=htonl(dst); nxt->nexthop=htonl(nexthop); nxt->mask=ntohl(mask); strncpy(nxt->iface,iface,sizeof(nxt->iface)); nxt->next=list; list=nxt; } } fclose(fil); TRACE_EXIT(); return list; } #if DEBUG static void routeDump(Route *r) { TRACE_ENTER(); while(r) { LOG_DEBUG(r->dst << " -> " << r->nexthop << " mask " << r->mask); r=r->next; } TRACE_EXIT(); } #endif // DEBUG static int routeNumber(Route *r) { TRACE_ENTER(); int count=0; while(r) { count++; r=r->next; } TRACE_EXIT_RET(count); return count; } static void routeFree(Route *r) { TRACE_ENTER(); Route *d; while(r) { d=r; r=r->next; free(d); } TRACE_EXIT(); } static void routeInsert(Route **list, Route *n) { TRACE_ENTER(); Route *nxt; nxt = (Route*)malloc(sizeof(*nxt)); nxt->dst=n->dst; nxt->nexthop=n->nexthop; nxt->mask=n->mask; nxt->next=*list; *list=nxt; TRACE_EXIT(); } /* return first route to in list which has the same nexthop */ static Route *routeSearchNext(Route *list, Route *key) { TRACE_ENTER(); Route *r; r=list; while(r) { if (r->nexthop==key->nexthop) { TRACE_EXIT_RET(r); return r; } r=r->next; } TRACE_EXIT_RET("NULL"); return NULL; } typedef struct detector { Client *watcherClientPtr; useconds_t reportperiod; /* frequency to generate reports at */ int reportnum; string iface; int routeedgewidth; Color onehopcolor; Color nexthopcolor; string nexthoplayer; string onehoplayer; int duration; /* Time to run (in seconds) or 0 to run until broken */ struct in_addr filterNetwork; struct in_addr filterMask; struct in_addr localhost; } detector; typedef struct DetectorInit { useconds_t reportperiod; /* frequency to generate reports at */ string iface; int onehopfamily; Color onehopcolor; Color nexthopcolor; int mouthnum; int duration; /* Time to run (in seconds) or 0 to run until broken */ int routeedgewidth; string serverName; string nexthoplayer; string onehoplayer; struct in_addr filterNetwork; struct in_addr filterMask; struct in_addr localhost; } DetectorInit; static void updateRoutes(detector *st, Route *list) { TRACE_ENTER(); Route *r,*tmpNextHop=NULL; Route *tmpOneHop=NULL; /* * for each edge in newlist, * if there is not an edge in oldList or tmpList to nexthop, add it, and add to tmpList */ vector<MessagePtr> messages; for(r=list;r;r=r->next) { if (!st->iface.empty()) if (st->iface != string(r->iface)) /* if we're checking interfaces, and this route is on the wrong one... */ continue; #if 1 LOG_DEBUG("nexthop inserting us -> " << r->nexthop); #endif if ((r->nexthop!=0) && (routeSearchNext(tmpNextHop,r)==NULL)) /* if its multi-hop, and not on the next hop list */ { EdgeMessagePtr em=EdgeMessagePtr(new EdgeMessage); em->node1=boost::asio::ip::address_v4(htonl(st->localhost.s_addr)); em->node2=boost::asio::ip::address_v4(r->nexthop); em->edgeColor=st->nexthopcolor; em->expiration=st->reportperiod*1.5; em->width=st->routeedgewidth; em->layer=ROUTING_LAYER; // GTL st->nexthoplayer; em->addEdge=true; em->bidirectional=false; messages.push_back(em); routeInsert(&tmpNextHop,r); } if (r->nexthop==0) /* if its a one-hop... */ { #if 1 LOG_DEBUG("onehop inserting us -> " << r->dst); #endif EdgeMessagePtr em=EdgeMessagePtr(new EdgeMessage); em->node1=boost::asio::ip::address_v4(htonl(st->localhost.s_addr)); em->node2=boost::asio::ip::address_v4(r->dst); em->edgeColor=st->onehopcolor; em->expiration=st->reportperiod*1.5; em->width=st->routeedgewidth; em->layer=ROUTING_LAYER; // GTL st->onehoplayer; em->addEdge=true; em->bidirectional=false; messages.push_back(em); routeInsert(&tmpOneHop,r); } } if (!messages.empty()) st->watcherClientPtr->sendMessages(messages); else LOG_DEBUG("No routes found so no messages sent!"); routeFree(tmpNextHop); routeFree(tmpOneHop); TRACE_EXIT(); } /* This is called regularly by the select loop (below) * It will create a message, and send it to this node's coordinator */ static void detectorSend(detector *st) { TRACE_ENTER(); Route *list; list=routeRead(st->filterNetwork.s_addr, st->filterMask.s_addr); long long int curtime; struct timeval tp; gettimeofday(&tp, NULL); curtime=(long long int)tp.tv_sec * 1000 + (long long int)tp.tv_usec/1000; LOG_DEBUG("node= " << st->localhost.s_addr << " time= " << curtime << " numroutes= " << routeNumber(list)); #ifdef DEBUG LOG_DEBUG("old:"); routeDump(st->oldList); LOG_DEBUG("new:"); routeDump(list); #endif st->reportnum++; updateRoutes(st,list); routeFree(list); TRACE_EXIT(); } static detector *detectorInit(DetectorInit *detinit) { TRACE_ENTER(); detector *st; st=new detector; st->iface=""; st->watcherClientPtr=new Client(detinit->serverName); if(st->watcherClientPtr==NULL) return NULL; st->duration=detinit->duration; st->reportperiod=detinit->reportperiod; st->reportnum=0; st->iface=detinit->iface; st->onehoplayer=detinit->onehoplayer; st->onehopcolor=detinit->onehopcolor; st->nexthoplayer=detinit->nexthoplayer; st->nexthopcolor=st->nexthopcolor; st->routeedgewidth=detinit->routeedgewidth; st->filterNetwork.s_addr=detinit->filterNetwork.s_addr; st->filterMask.s_addr=detinit->filterMask.s_addr; st->localhost.s_addr=detinit->localhost.s_addr; TRACE_EXIT(); return st; } /* * Wait around until we are ready to generate a message, then do it. */ static void selectLoop(detector *dt) { TRACE_ENTER(); time_t startTime=time(NULL); while(1) { usleep(dt->reportperiod*(useconds_t)1000.0); detectorSend(dt); if (dt->duration) if (time(NULL)-startTime>dt->duration) break; } dt->watcherClientPtr->wait(); TRACE_EXIT(); } int main(int argc, char *argv[]) { TRACE_ENTER(); detector *dt; int ch; string logPropsFile("routeFeeder.log.properties"); DetectorInit detinit; detinit.iface=""; detinit.onehopcolor=Color::green; detinit.onehoplayer="One Hop Routing"; detinit.nexthopcolor=Color::blue; detinit.nexthoplayer="Network Routing"; detinit.reportperiod=2000; detinit.duration=0; detinit.routeedgewidth=15; detinit.filterNetwork.s_addr=0; detinit.filterMask.s_addr=0; detinit.localhost.s_addr=0; while ((ch = getopt(argc, argv, "m:n:h:o:x:t:e:b:i:d:p:w:l:?")) != -1) switch (ch) { case 'm': if(-1 == inet_pton(AF_INET, optarg, &detinit.filterMask)) { fprintf(stderr, "Error parsing filter mask: %s\n", optarg); exit(EX_USAGE); } break; case 'n': if(-1 == inet_pton(AF_INET, optarg, &detinit.filterNetwork)) { fprintf(stderr, "Error parsing filter network: %s\n", optarg); exit(EX_USAGE); } break; case 'h': if(-1 == inet_pton(AF_INET, optarg, &detinit.localhost)) { fprintf(stderr, "Error parsing localhost address: %s\n", optarg); exit(EX_USAGE); } break; case 'o': detinit.onehopcolor.fromString(optarg); break; case 'x': detinit.nexthopcolor.fromString(optarg); break; case 't': sscanf(optarg,"%d",&detinit.duration); break; case 'e': detinit.onehoplayer=string(optarg); break; case 'b': detinit.nexthoplayer=string(optarg); break; case 'i': detinit.iface=string(optarg); break; case 'd': detinit.serverName=string(optarg); break; case 'p': sscanf(optarg,"%d",&detinit.reportperiod); break; case 'w': sscanf(optarg, "%d", &detinit.routeedgewidth); break; case 'l': logPropsFile=string(optarg); break; case '?': default: fprintf(stderr,"routingdetector - poll the linux routing table, and draw the routes in the watcher\n" "-d ipaddr/hostname - specify watcherd address to connect to (duck)\n" "-h ipaddr - this host's address\n" "-m netmask - the mask used to filter the routes (ex. 255.255.255.0)\n" "-n network - the network used to filter the routes (ex. 192.168.1.0)\n" "-p milliseconds - specify the period to poll and report\n" "-i interface - display only routes through this ethernet interface (or any if unspecified)\n" "-o color - onehop edge color\n" "-e layer - onehop layer name\n" "-x color - nexthop edge color\n" "-b layer - nexthop layer name\n" "-t seconds - Run for this long, then exit\n" "-w width - make edges width pixels wide (default 15)\n" ); exit(1); break; } // init the logging system LOAD_LOG_PROPS(logPropsFile); LOG_INFO("Logger initialized from file \"" << logPropsFile << "\""); // check args, errors, etc before doing real work if(detinit.localhost.s_addr == 0) { fprintf(stderr, "localhost address cannot be blank\n"); exit(EX_USAGE); } if(detinit.filterNetwork.s_addr == 0) { fprintf(stderr, "filter network cannot be blank\n"); exit(EX_USAGE); } if(detinit.filterMask.s_addr == 0) { fprintf(stderr, "filter mask cannot be blank\n"); exit(EX_USAGE); } if(detinit.serverName.empty()) { fprintf(stderr, "watcherd hostname cannot be blank\n"); exit(EX_USAGE); } dt=detectorInit(&detinit); if (dt==NULL) { fprintf(stderr,"detector init failed, probably could not connect to infrastructure demon.\n"); exit(1); } printf("%s: starting\n",argv[0]); selectLoop(dt); TRACE_EXIT(); return 0; }
#include <stdio.h> #include <sysexits.h> // portablish exit values. #include <stdlib.h> #include <netinet/in.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <sys/time.h> #include <string.h> #include <assert.h> #include <string> #include <client.h> // we are a client of the watcher. #include <libwatcher/edgeMessage.h> // we send edgeMessages to the watcher. #include <logger.h> using namespace std; using namespace watcher; using namespace watcher::event; static const char *rcsid __attribute__ ((unused)) = "$Id: routingfeeder.c,v 1.0 2009/04/28 22:08:47 glawler Exp $"; // #define DEBUG 1 /* This is a feeder which polls the routing table, * and draws the routing algorithm's edges on the watcher * * Copyright (C) 2006,2007,2008,2009 Sparta Inc. Written by the NIP group, SRD, ISSO */ typedef struct Route { unsigned int dst; unsigned int nexthop; unsigned int mask; char iface[16]; struct Route *next; } Route; /* Iface Destination Gateway Flags RefCnt Use Metric Mask MTU Window IRTT eth0 7402A8C0 7C02A8C0 0007 0 0 0 FFFFFFFF 00 0 eth0 7402A8C0 7202A8C0 0007 0 0 0 FFFFFFFF 00 0 */ static Route *routeRead(unsigned int network, unsigned int netmask) { TRACE_ENTER(); FILE *fil; char line[1024]; Route *list=NULL,*nxt; fil=fopen("/proc/net/route","r"); while(fgets(line,sizeof(line)-1,fil)) { char iface[16]; int flags,refcnt,use,metric,mtu,window; unsigned int dst,nexthop,mask; int rc; rc=sscanf(line,"%s\t%x\t%x\t%d\t%d\t%d\t%d\t%x\t%o\t%d\n",iface,&dst,&nexthop,&flags,&refcnt,&use,&metric,&mask,&mtu,&window); if (rc==10 && ((ntohl(dst) & ntohl(netmask)) == ntohl(network))) { nxt = (Route*)malloc(sizeof(*nxt)); assert(nxt!=NULL); nxt->dst=htonl(dst); nxt->nexthop=htonl(nexthop); nxt->mask=ntohl(mask); strncpy(nxt->iface,iface,sizeof(nxt->iface)); nxt->next=list; list=nxt; } } fclose(fil); TRACE_EXIT(); return list; } #if DEBUG static void routeDump(Route *r) { TRACE_ENTER(); while(r) { LOG_DEBUG(r->dst << " -> " << r->nexthop << " mask " << r->mask); r=r->next; } TRACE_EXIT(); } #endif // DEBUG static int routeNumber(Route *r) { TRACE_ENTER(); int count=0; while(r) { count++; r=r->next; } TRACE_EXIT_RET(count); return count; } static void routeFree(Route *r) { TRACE_ENTER(); Route *d; while(r) { d=r; r=r->next; free(d); } TRACE_EXIT(); } static void routeInsert(Route **list, Route *n) { TRACE_ENTER(); Route *nxt; nxt = (Route*)malloc(sizeof(*nxt)); nxt->dst=n->dst; nxt->nexthop=n->nexthop; nxt->mask=n->mask; nxt->next=*list; *list=nxt; TRACE_EXIT(); } /* return first route to in list which has the same nexthop */ static Route *routeSearchNext(Route *list, Route *key) { TRACE_ENTER(); Route *r; r=list; while(r) { if (r->nexthop==key->nexthop) { TRACE_EXIT_RET(r); return r; } r=r->next; } TRACE_EXIT_RET("NULL"); return NULL; } typedef struct detector { Client *watcherClientPtr; useconds_t reportperiod; /* frequency to generate reports at */ int reportnum; string iface; int routeedgewidth; Color onehopcolor; Color nexthopcolor; string nexthoplayer; string onehoplayer; int duration; /* Time to run (in seconds) or 0 to run until broken */ struct in_addr filterNetwork; struct in_addr filterMask; struct in_addr localhost; } detector; typedef struct DetectorInit { useconds_t reportperiod; /* frequency to generate reports at */ string iface; int onehopfamily; Color onehopcolor; Color nexthopcolor; int mouthnum; int duration; /* Time to run (in seconds) or 0 to run until broken */ int routeedgewidth; string serverName; string nexthoplayer; string onehoplayer; struct in_addr filterNetwork; struct in_addr filterMask; struct in_addr localhost; } DetectorInit; static void updateRoutes(detector *st, Route *list) { TRACE_ENTER(); Route *r,*tmpNextHop=NULL; Route *tmpOneHop=NULL; /* * for each edge in newlist, * if there is not an edge in oldList or tmpList to nexthop, add it, and add to tmpList */ static vector<MessagePtr> messages; if(!messages.empty()) messages.clear(); for(r=list;r;r=r->next) { if (!st->iface.empty()) if (st->iface != string(r->iface)) /* if we're checking interfaces, and this route is on the wrong one... */ continue; #if 1 LOG_DEBUG("nexthop inserting us -> " << r->nexthop); #endif if ((r->nexthop!=0) && (routeSearchNext(tmpNextHop,r)==NULL)) /* if its multi-hop, and not on the next hop list */ { EdgeMessagePtr em=EdgeMessagePtr(new EdgeMessage); em->node1=boost::asio::ip::address_v4(htonl(st->localhost.s_addr)); em->node2=boost::asio::ip::address_v4(r->nexthop); em->edgeColor=st->nexthopcolor; em->expiration=st->reportperiod*1.5; em->width=st->routeedgewidth; em->layer=ROUTING_LAYER; // GTL st->nexthoplayer; em->addEdge=true; em->bidirectional=false; messages.push_back(em); routeInsert(&tmpNextHop,r); } if (r->nexthop==0) /* if its a one-hop... */ { #if 1 LOG_DEBUG("onehop inserting us -> " << r->dst); #endif EdgeMessagePtr em=EdgeMessagePtr(new EdgeMessage); em->node1=boost::asio::ip::address_v4(htonl(st->localhost.s_addr)); em->node2=boost::asio::ip::address_v4(r->dst); em->edgeColor=st->onehopcolor; em->expiration=st->reportperiod*1.5; em->width=st->routeedgewidth; em->layer=ROUTING_LAYER; // GTL st->onehoplayer; em->addEdge=true; em->bidirectional=false; messages.push_back(em); routeInsert(&tmpOneHop,r); } } if (!messages.empty()) st->watcherClientPtr->sendMessages(messages); else LOG_DEBUG("No routes found so no messages sent!"); routeFree(tmpNextHop); routeFree(tmpOneHop); TRACE_EXIT(); } /* This is called regularly by the select loop (below) * It will create a message, and send it to this node's coordinator */ static void detectorSend(detector *st) { TRACE_ENTER(); Route *list; list=routeRead(st->filterNetwork.s_addr, st->filterMask.s_addr); long long int curtime; struct timeval tp; gettimeofday(&tp, NULL); curtime=(long long int)tp.tv_sec * 1000 + (long long int)tp.tv_usec/1000; LOG_DEBUG("node= " << st->localhost.s_addr << " time= " << curtime << " numroutes= " << routeNumber(list)); #ifdef DEBUG LOG_DEBUG("old:"); routeDump(st->oldList); LOG_DEBUG("new:"); routeDump(list); #endif st->reportnum++; updateRoutes(st,list); routeFree(list); TRACE_EXIT(); } static detector *detectorInit(DetectorInit *detinit) { TRACE_ENTER(); detector *st; st=new detector; st->iface=""; st->watcherClientPtr=new Client(detinit->serverName); if(st->watcherClientPtr==NULL) return NULL; st->duration=detinit->duration; st->reportperiod=detinit->reportperiod; st->reportnum=0; st->iface=detinit->iface; st->onehoplayer=detinit->onehoplayer; st->onehopcolor=detinit->onehopcolor; st->nexthoplayer=detinit->nexthoplayer; st->nexthopcolor=st->nexthopcolor; st->routeedgewidth=detinit->routeedgewidth; st->filterNetwork.s_addr=detinit->filterNetwork.s_addr; st->filterMask.s_addr=detinit->filterMask.s_addr; st->localhost.s_addr=detinit->localhost.s_addr; TRACE_EXIT(); return st; } /* * Wait around until we are ready to generate a message, then do it. */ static void selectLoop(detector *dt) { TRACE_ENTER(); time_t startTime=time(NULL); while(1) { usleep(dt->reportperiod*(useconds_t)1000.0); detectorSend(dt); if (dt->duration) if (time(NULL)-startTime>dt->duration) break; } dt->watcherClientPtr->wait(); TRACE_EXIT(); } int main(int argc, char *argv[]) { TRACE_ENTER(); detector *dt; int ch; string logPropsFile("routeFeeder.log.properties"); DetectorInit detinit; detinit.iface=""; detinit.onehopcolor=Color::green; detinit.onehoplayer="One Hop Routing"; detinit.nexthopcolor=Color::blue; detinit.nexthoplayer="Network Routing"; detinit.reportperiod=2000; detinit.duration=0; detinit.routeedgewidth=15; detinit.filterNetwork.s_addr=0; detinit.filterMask.s_addr=0; detinit.localhost.s_addr=0; while ((ch = getopt(argc, argv, "m:n:h:o:x:t:e:b:i:d:p:w:l:?")) != -1) switch (ch) { case 'm': if(-1 == inet_pton(AF_INET, optarg, &detinit.filterMask)) { fprintf(stderr, "Error parsing filter mask: %s\n", optarg); exit(EX_USAGE); } break; case 'n': if(-1 == inet_pton(AF_INET, optarg, &detinit.filterNetwork)) { fprintf(stderr, "Error parsing filter network: %s\n", optarg); exit(EX_USAGE); } break; case 'h': if(-1 == inet_pton(AF_INET, optarg, &detinit.localhost)) { fprintf(stderr, "Error parsing localhost address: %s\n", optarg); exit(EX_USAGE); } break; case 'o': detinit.onehopcolor.fromString(optarg); break; case 'x': detinit.nexthopcolor.fromString(optarg); break; case 't': sscanf(optarg,"%d",&detinit.duration); break; case 'e': detinit.onehoplayer=string(optarg); break; case 'b': detinit.nexthoplayer=string(optarg); break; case 'i': detinit.iface=string(optarg); break; case 'd': detinit.serverName=string(optarg); break; case 'p': sscanf(optarg,"%d",&detinit.reportperiod); break; case 'w': sscanf(optarg, "%d", &detinit.routeedgewidth); break; case 'l': logPropsFile=string(optarg); break; case '?': default: fprintf(stderr,"routingdetector - poll the linux routing table, and draw the routes in the watcher\n" "-d ipaddr/hostname - specify watcherd address to connect to (duck)\n" "-h ipaddr - this host's address\n" "-m netmask - the mask used to filter the routes (ex. 255.255.255.0)\n" "-n network - the network used to filter the routes (ex. 192.168.1.0)\n" "-p milliseconds - specify the period to poll and report\n" "-i interface - display only routes through this ethernet interface (or any if unspecified)\n" "-o color - onehop edge color\n" "-e layer - onehop layer name\n" "-x color - nexthop edge color\n" "-b layer - nexthop layer name\n" "-t seconds - Run for this long, then exit\n" "-w width - make edges width pixels wide (default 15)\n" ); exit(1); break; } // init the logging system LOAD_LOG_PROPS(logPropsFile); LOG_INFO("Logger initialized from file \"" << logPropsFile << "\""); // check args, errors, etc before doing real work if(detinit.localhost.s_addr == 0) { fprintf(stderr, "localhost address cannot be blank\n"); exit(EX_USAGE); } if(detinit.filterNetwork.s_addr == 0) { fprintf(stderr, "filter network cannot be blank\n"); exit(EX_USAGE); } if(detinit.filterMask.s_addr == 0) { fprintf(stderr, "filter mask cannot be blank\n"); exit(EX_USAGE); } if(detinit.serverName.empty()) { fprintf(stderr, "watcherd hostname cannot be blank\n"); exit(EX_USAGE); } dt=detectorInit(&detinit); if (dt==NULL) { fprintf(stderr,"detector init failed, probably could not connect to infrastructure demon.\n"); exit(1); } printf("%s: starting\n",argv[0]); selectLoop(dt); TRACE_EXIT(); return 0; }
Make sure the Messages are still around by the time the sendMessage threads wakes up and sends the messages. The non-blocking nature of sendMessage() should be documented. Also, maybe we should add a blocking version (or Client setting).
Make sure the Messages are still around by the time the sendMessage threads wakes up and sends the messages. The non-blocking nature of sendMessage() should be documented. Also, maybe we should add a blocking version (or Client setting).
C++
agpl-3.0
akbardotinfo/watcher-visualization,akbardotinfo/watcher-visualization,akbardotinfo/watcher-visualization,akbardotinfo/watcher-visualization,akbardotinfo/watcher-visualization
8746ab178fdad9e0f44f7330084e29432b57143e
PWG4/macros/ConfigAnalysisGammaDirect.C
PWG4/macros/ConfigAnalysisGammaDirect.C
/* $Id: $ */ /* $Log$ */ //------------------------------------ // Configuration macro example: // // Do prompt photon analysis with ESDs // Gamma in PHOS, // for EMCAL, PHOS by EMCAL where necessary // // Author : Gustavo Conesa Balbastre (INFN-LNF) //------------------------------------ AliAnaMaker* ConfigAnalysis() { // // Configuration goes here // printf("======================== \n"); printf("ConfigAnalysis() \n"); printf("======================== \n"); //Detector Fidutial Cuts AliFidutialCut * fidCut = new AliFidutialCut(); fidCut->DoCTSFidutialCut(kTRUE) ; //fidCut->DoEMCALFidutialCut(kFALSE) ; fidCut->DoPHOSFidutialCut(kTRUE) ; fidCut->SetSimpleCTSFidutialCut(0.9,0.,360.); f//idCut->SetSimpleEMCALFidutialCut(0.7,80.,190.); fidCut->SetSimplePHOSFidutialCut(0.13,220.,320.); fidCut->Print(""); //----------------------------------------------------------- // Reader //----------------------------------------------------------- AliCaloTrackReader *reader = new AliCaloTrackESDReader(); reader->SetDebug(-1); //Switch on or off the detectors information that you want reader->SwitchOffEMCAL(); reader->SwitchOnCTS(); reader->SwitchOnPHOS(); //Min particle pT //reader->SetEMCALPtMin(0.5); reader->SetPHOSPtMin(0.5); reader->SetCTSPtMin(0.2); reader->SetFidutialCut(fidCut); reader->Print(""); //--------------------------------------------------------------------- // Analysis algorithm //--------------------------------------------------------------------- //Detector Fidutial Cuts for analysis part AliFidutialCut * fidCut2 = new AliFidutialCut(); fidCut2->DoCTSFidutialCut(kFALSE) ; //fidCut2->DoEMCALFidutialCut(kTRUE) ; fidCut2->DoPHOSFidutialCut(kFALSE) ; fidCut2->SetSimpleCTSFidutialCut(0.9,0.,360.); //fidCut2->SetSimpleEMCALFidutialCut(0.7,80.,190.); fidCut2->SetSimplePHOSFidutialCut(0.13,220.,320.); fidCut2->Print(""); AliCaloPID * pid = new AliCaloPID(); // use selection with simple weights pid->SetPHOSPhotonWeight(0.7); pid->SetPHOSPi0Weight(0.7); pid->SetEMCALPhotonWeight(0.7); pid->SetEMCALPi0Weight(0.7); // use more complicated selection, particle weight depending on cluster energy // pid->UsePHOSPIDWeightFormula(kTRUE); // TFormula * photonF = new TFormula("photonWeight","0.98*(x<40)+ 0.68*(x>=100)+(x>=40 && x<100)*(0.98+x*(6e-3)-x*x*(2e-04)+x*x*x*(1.1e-06))"); // TFormula * pi0F = new TFormula("pi0Weight","0.98*(x<65)+ 0.915*(x>=100)+(x>=65 && x-x*(1.95e-3)-x*x*(4.31e-05)+x*x*x*(3.61e-07))"); // pid->SetPHOSPhotonWeightFormula(photonF); // pid->SetPHOSPi0WeightFormula(pi0F); pid->Print(""); AliIsolationCut * ic = new AliIsolationCut(); ic->SetConeSize(0.4); ic->SetPtThreshold(1.); ic->SetICMethod(AliIsolationCut::kPtThresIC); ic->Print(""); AliAnaGammaDirect *ana = new AliAnaGammaDirect(); ana->SetDebug(-1); ana->SetMinPt(5.); ana->SetCaloPID(pid); ana->SetFidutialCut(fidCut2); ana->SetIsolationCut(ic) ; ana->SetDetector("PHOS"); ana->SwitchOnDataMC() ;//Access MC stack and fill more histograms ana->SwitchOnCaloPID(); ana->SwitchOffCaloPIDRecalculation(); //recommended for EMCAL ana->SwitchOnFidutialCut(); //Select clusters with no pair, if both clusters with pi0 mass ana->SwitchOffInvariantMass(); //Do isolation cut ana->SwitchOnIsolation(); //Do or not do isolation with previously produced AODs. //No effect if use of SwitchOnSeveralIsolation() ana->SwitchOffReIsolation(); //Multiple IC ana->SwitchOffSeveralIsolation() ; // ana->SwitchOnSeveralIsolation() ; // ana->SetNCones(2) ; // ana->SetNPtThresFrac(2) ; // ana->SetConeSizes(0, 0.3) ; ana->SetConeSizes(1, 0.4) ; // ana->SetPtThresholds(0, 0.5) ; ana->SetPtThresholds(1, 1.) ; // ana->SetPtFractions(0, 1.) ; ana->SetPtFractions(1, 1.5) ; ana->Print(""); //--------------------------------------------------------------------- // Set analysis algorithm and reader //--------------------------------------------------------------------- maker = new AliAnaMaker(); maker->SetReader(reader);//pointer to reader maker->AddAnalysis(ana,0); maker->SetAODBranchName("Photon"); maker->SetAnaDebug(1) ; maker->SwitchOnHistogramsMaker() ; //maker->SwitchOffHistogramsMaker() ; maker->SwitchOnAODsMaker() ; //maker->SwitchOffAODsMaker() ; maker->Print(""); // printf("======================== \n"); printf("END ConfigAnalysis() \n"); printf("======================== \n"); return maker ; }
/* $Id:$ */ //------------------------------------ // Configuration macro example: // // Do prompt photon analysis with ESDs // Gamma in PHOS, // for EMCAL, PHOS by EMCAL where necessary // // Author : Gustavo Conesa Balbastre (INFN-LNF) //------------------------------------ AliAnaMaker* ConfigAnalysis() { // // Configuration goes here // printf("======================== \n"); printf("ConfigAnalysis() \n"); printf("======================== \n"); //Detector Fidutial Cuts AliFidutialCut * fidCut = new AliFidutialCut(); fidCut->DoCTSFidutialCut(kTRUE) ; //fidCut->DoEMCALFidutialCut(kFALSE) ; fidCut->DoPHOSFidutialCut(kTRUE) ; fidCut->SetSimpleCTSFidutialCut(0.9,0.,360.); //fidCut->SetSimpleEMCALFidutialCut(0.7,80.,190.); fidCut->SetSimplePHOSFidutialCut(0.13,220.,320.); fidCut->Print(""); //----------------------------------------------------------- // Reader //----------------------------------------------------------- AliCaloTrackReader *reader = new AliCaloTrackESDReader(); reader->SetDebug(-1); //Switch on or off the detectors information that you want reader->SwitchOffEMCAL(); reader->SwitchOnCTS(); reader->SwitchOnPHOS(); //Min particle pT //reader->SetEMCALPtMin(0.5); reader->SetPHOSPtMin(0.5); reader->SetCTSPtMin(0.2); reader->SetFidutialCut(fidCut); reader->Print(""); //--------------------------------------------------------------------- // Analysis algorithm //--------------------------------------------------------------------- //Detector Fidutial Cuts for analysis part AliFidutialCut * fidCut2 = new AliFidutialCut(); fidCut2->DoCTSFidutialCut(kFALSE) ; //fidCut2->DoEMCALFidutialCut(kTRUE) ; fidCut2->DoPHOSFidutialCut(kFALSE) ; fidCut2->SetSimpleCTSFidutialCut(0.9,0.,360.); //fidCut2->SetSimpleEMCALFidutialCut(0.7,80.,190.); fidCut2->SetSimplePHOSFidutialCut(0.13,220.,320.); fidCut2->Print(""); AliCaloPID * pid = new AliCaloPID(); // use selection with simple weights pid->SetPHOSPhotonWeight(0.7); pid->SetPHOSPi0Weight(0.7); pid->SetEMCALPhotonWeight(0.7); pid->SetEMCALPi0Weight(0.7); // use more complicated selection, particle weight depending on cluster energy // pid->UsePHOSPIDWeightFormula(kTRUE); // TFormula * photonF = new TFormula("photonWeight","0.98*(x<40)+ 0.68*(x>=100)+(x>=40 && x<100)*(0.98+x*(6e-3)-x*x*(2e-04)+x*x*x*(1.1e-06))"); // TFormula * pi0F = new TFormula("pi0Weight","0.98*(x<65)+ 0.915*(x>=100)+(x>=65 && x-x*(1.95e-3)-x*x*(4.31e-05)+x*x*x*(3.61e-07))"); // pid->SetPHOSPhotonWeightFormula(photonF); // pid->SetPHOSPi0WeightFormula(pi0F); pid->Print(""); AliIsolationCut * ic = new AliIsolationCut(); ic->SetConeSize(0.4); ic->SetPtThreshold(1.); ic->SetICMethod(AliIsolationCut::kPtThresIC); ic->Print(""); AliAnaGammaDirect *ana = new AliAnaGammaDirect(); ana->SetDebug(-1); ana->SetMinPt(5.); ana->SetCaloPID(pid); ana->SetFidutialCut(fidCut2); ana->SetIsolationCut(ic) ; ana->SetDetector("PHOS"); ana->SwitchOnDataMC() ;//Access MC stack and fill more histograms ana->SwitchOnCaloPID(); ana->SwitchOffCaloPIDRecalculation(); //recommended for EMCAL ana->SwitchOnFidutialCut(); //Select clusters with no pair, if both clusters with pi0 mass ana->SwitchOffInvariantMass(); //Do isolation cut ana->SwitchOnIsolation(); //Do or not do isolation with previously produced AODs. //No effect if use of SwitchOnSeveralIsolation() ana->SwitchOffReIsolation(); //Multiple IC ana->SwitchOffSeveralIsolation() ; // ana->SwitchOnSeveralIsolation() ; // ana->SetNCones(2) ; // ana->SetNPtThresFrac(2) ; // ana->SetConeSizes(0, 0.3) ; ana->SetConeSizes(1, 0.4) ; // ana->SetPtThresholds(0, 0.5) ; ana->SetPtThresholds(1, 1.) ; // ana->SetPtFractions(0, 1.) ; ana->SetPtFractions(1, 1.5) ; ana->Print(""); //--------------------------------------------------------------------- // Set analysis algorithm and reader //--------------------------------------------------------------------- maker = new AliAnaMaker(); maker->SetReader(reader);//pointer to reader maker->AddAnalysis(ana,0); maker->SetAODBranchName("Photon"); maker->SetAnaDebug(1) ; maker->SwitchOnHistogramsMaker() ; //maker->SwitchOffHistogramsMaker() ; maker->SwitchOnAODsMaker() ; //maker->SwitchOffAODsMaker() ; maker->Print(""); // printf("======================== \n"); printf("END ConfigAnalysis() \n"); printf("======================== \n"); return maker ; }
correct typo
correct typo
C++
bsd-3-clause
miranov25/AliRoot,ecalvovi/AliRoot,ecalvovi/AliRoot,coppedis/AliRoot,sebaleh/AliRoot,ecalvovi/AliRoot,ecalvovi/AliRoot,ALICEHLT/AliRoot,shahor02/AliRoot,coppedis/AliRoot,ALICEHLT/AliRoot,coppedis/AliRoot,shahor02/AliRoot,coppedis/AliRoot,miranov25/AliRoot,alisw/AliRoot,mkrzewic/AliRoot,ALICEHLT/AliRoot,ALICEHLT/AliRoot,miranov25/AliRoot,alisw/AliRoot,jgrosseo/AliRoot,ecalvovi/AliRoot,sebaleh/AliRoot,miranov25/AliRoot,alisw/AliRoot,alisw/AliRoot,ALICEHLT/AliRoot,shahor02/AliRoot,coppedis/AliRoot,ecalvovi/AliRoot,jgrosseo/AliRoot,miranov25/AliRoot,jgrosseo/AliRoot,coppedis/AliRoot,coppedis/AliRoot,mkrzewic/AliRoot,mkrzewic/AliRoot,ALICEHLT/AliRoot,sebaleh/AliRoot,mkrzewic/AliRoot,jgrosseo/AliRoot,jgrosseo/AliRoot,sebaleh/AliRoot,jgrosseo/AliRoot,shahor02/AliRoot,alisw/AliRoot,shahor02/AliRoot,miranov25/AliRoot,shahor02/AliRoot,alisw/AliRoot,alisw/AliRoot,mkrzewic/AliRoot,sebaleh/AliRoot,alisw/AliRoot,shahor02/AliRoot,miranov25/AliRoot,ecalvovi/AliRoot,sebaleh/AliRoot,sebaleh/AliRoot,miranov25/AliRoot,mkrzewic/AliRoot,jgrosseo/AliRoot,mkrzewic/AliRoot,ALICEHLT/AliRoot,coppedis/AliRoot
1263fc8d764f412c3cb35f1d546706e14474b9bc
src/proxy_handler.cxx
src/proxy_handler.cxx
/* * Serve HTTP requests from another HTTP/AJP server. * * author: Max Kellermann <[email protected]> */ #include "handler.hxx" #include "bp_connection.hxx" #include "bp_instance.hxx" #include "request.hxx" #include "request_forward.hxx" #include "http_server/Request.hxx" #include "http_cache.hxx" #include "http_response.hxx" #include "http_address.hxx" #include "cgi_address.hxx" #include "cookie_client.hxx" #include "uri/uri_extract.hxx" #include "strmap.hxx" #include "http_response.hxx" #include "istream/istream_pipe.hxx" #include "lhttp_address.hxx" #include "pool.hxx" /** * Return a copy of the URI for forwarding to the next server. This * omits the beng-proxy request "arguments". */ gcc_pure static const char * ForwardURI(struct pool &pool, const parsed_uri &uri) { if (uri.query.IsEmpty()) return p_strdup(pool, uri.base); else return p_strncat(&pool, uri.base.data, uri.base.size, "?", (size_t)1, uri.query.data, uri.query.size, nullptr); } /** * Return a copy of the original request URI for forwarding to the * next server. This omits the beng-proxy request "arguments" (unless * the translation server declared the "transparent" mode). */ gcc_pure static const char * ForwardURI(const Request &r) { const TranslateResponse &t = *r.translate.response; if (t.transparent || r.uri.args.IsEmpty()) /* transparent or no args: return the full URI as-is */ return r.request.uri; else /* remove the "args" part */ return ForwardURI(r.pool, r.uri); } gcc_pure static const char * GetCookieHost(const Request &r) { const TranslateResponse &t = *r.translate.response; if (t.cookie_host != nullptr) return t.cookie_host; const ResourceAddress &address = *r.translate.address; return address.GetHostAndPort(); } gcc_pure static const char * GetCookieURI(const Request &r) { return r.cookie_uri; } static void proxy_collect_cookies(Request &request2, const struct strmap *headers) { if (headers == nullptr) return; auto r = headers->EqualRange("set-cookie2"); if (r.first == r.second) { r = headers->EqualRange("set-cookie"); if (r.first == r.second) return; } const char *host_and_port = GetCookieHost(request2); if (host_and_port == nullptr) return; const char *path = GetCookieURI(request2); if (path == nullptr) return; auto *session = request2.MakeSession(); if (session == nullptr) return; for (auto i = r.first; i != r.second; ++i) cookie_jar_set_cookie2(session->cookies, i->value, host_and_port, path); session_put(session); } static void proxy_response(http_status_t status, struct strmap *headers, Istream *body, void *ctx) { auto &request2 = *(Request *)ctx; #ifndef NDEBUG const ResourceAddress &address = *request2.translate.address; assert(address.type == ResourceAddress::Type::HTTP || address.type == ResourceAddress::Type::LHTTP || address.type == ResourceAddress::Type::AJP || address.type == ResourceAddress::Type::NFS || address.IsCgiAlike()); #endif proxy_collect_cookies(request2, headers); response_handler.InvokeResponse(&request2, status, headers, body); } static void proxy_abort(GError *error, void *ctx) { auto &request2 = *(Request *)ctx; response_handler.InvokeAbort(&request2, error); } static const struct http_response_handler proxy_response_handler = { .response = proxy_response, .abort = proxy_abort, }; void proxy_handler(Request &request2) { struct pool &pool = request2.pool; const TranslateResponse &tr = *request2.translate.response; const ResourceAddress *address = request2.translate.address; assert(address->type == ResourceAddress::Type::HTTP || address->type == ResourceAddress::Type::LHTTP || address->type == ResourceAddress::Type::AJP || address->type == ResourceAddress::Type::NFS || address->IsCgiAlike()); if (request2.translate.response->transparent && (!request2.uri.args.IsEmpty() || !request2.uri.path_info.IsEmpty())) address = address->DupWithArgs(pool, request2.uri.args.data, request2.uri.args.size, request2.uri.path_info.data, request2.uri.path_info.size); if (!request2.processor_focus) /* forward query string */ address = address->DupWithQueryStringFrom(pool, request2.request.uri); if (address->IsCgiAlike() && address->u.cgi->script_name == nullptr && address->u.cgi->uri == nullptr) { const auto copy = address->Dup(pool); const auto cgi = copy->GetCgi(); /* pass the "real" request URI to the CGI (but without the "args", unless the request is "transparent") */ cgi->uri = ForwardURI(request2); address = copy; } request2.cookie_uri = address->GetUriPath(); struct forward_request forward; request_forward(forward, request2, tr.request_header_forward, GetCookieHost(request2), GetCookieURI(request2), address->type == ResourceAddress::Type::HTTP || address->type == ResourceAddress::Type::LHTTP); #ifdef SPLICE if (forward.body != nullptr) forward.body = istream_pipe_new(&pool, *forward.body, request2.instance.pipe_stock); #endif for (const auto &i : tr.request_headers) forward.headers->Add(i.key, i.value); http_cache_request(*request2.instance.http_cache, pool, request2.session_id.GetClusterHash(), forward.method, *address, forward.headers, forward.body, proxy_response_handler, &request2, request2.async_ref); }
/* * Serve HTTP requests from another HTTP/AJP server. * * author: Max Kellermann <[email protected]> */ #include "handler.hxx" #include "bp_connection.hxx" #include "bp_instance.hxx" #include "request.hxx" #include "request_forward.hxx" #include "ResourceLoader.hxx" #include "http_server/Request.hxx" #include "http_response.hxx" #include "http_address.hxx" #include "cgi_address.hxx" #include "cookie_client.hxx" #include "uri/uri_extract.hxx" #include "strmap.hxx" #include "http_response.hxx" #include "istream/istream_pipe.hxx" #include "lhttp_address.hxx" #include "pool.hxx" /** * Return a copy of the URI for forwarding to the next server. This * omits the beng-proxy request "arguments". */ gcc_pure static const char * ForwardURI(struct pool &pool, const parsed_uri &uri) { if (uri.query.IsEmpty()) return p_strdup(pool, uri.base); else return p_strncat(&pool, uri.base.data, uri.base.size, "?", (size_t)1, uri.query.data, uri.query.size, nullptr); } /** * Return a copy of the original request URI for forwarding to the * next server. This omits the beng-proxy request "arguments" (unless * the translation server declared the "transparent" mode). */ gcc_pure static const char * ForwardURI(const Request &r) { const TranslateResponse &t = *r.translate.response; if (t.transparent || r.uri.args.IsEmpty()) /* transparent or no args: return the full URI as-is */ return r.request.uri; else /* remove the "args" part */ return ForwardURI(r.pool, r.uri); } gcc_pure static const char * GetCookieHost(const Request &r) { const TranslateResponse &t = *r.translate.response; if (t.cookie_host != nullptr) return t.cookie_host; const ResourceAddress &address = *r.translate.address; return address.GetHostAndPort(); } gcc_pure static const char * GetCookieURI(const Request &r) { return r.cookie_uri; } static void proxy_collect_cookies(Request &request2, const struct strmap *headers) { if (headers == nullptr) return; auto r = headers->EqualRange("set-cookie2"); if (r.first == r.second) { r = headers->EqualRange("set-cookie"); if (r.first == r.second) return; } const char *host_and_port = GetCookieHost(request2); if (host_and_port == nullptr) return; const char *path = GetCookieURI(request2); if (path == nullptr) return; auto *session = request2.MakeSession(); if (session == nullptr) return; for (auto i = r.first; i != r.second; ++i) cookie_jar_set_cookie2(session->cookies, i->value, host_and_port, path); session_put(session); } static void proxy_response(http_status_t status, struct strmap *headers, Istream *body, void *ctx) { auto &request2 = *(Request *)ctx; #ifndef NDEBUG const ResourceAddress &address = *request2.translate.address; assert(address.type == ResourceAddress::Type::HTTP || address.type == ResourceAddress::Type::LHTTP || address.type == ResourceAddress::Type::AJP || address.type == ResourceAddress::Type::NFS || address.IsCgiAlike()); #endif proxy_collect_cookies(request2, headers); response_handler.InvokeResponse(&request2, status, headers, body); } static void proxy_abort(GError *error, void *ctx) { auto &request2 = *(Request *)ctx; response_handler.InvokeAbort(&request2, error); } static const struct http_response_handler proxy_response_handler = { .response = proxy_response, .abort = proxy_abort, }; void proxy_handler(Request &request2) { struct pool &pool = request2.pool; const TranslateResponse &tr = *request2.translate.response; const ResourceAddress *address = request2.translate.address; assert(address->type == ResourceAddress::Type::HTTP || address->type == ResourceAddress::Type::LHTTP || address->type == ResourceAddress::Type::AJP || address->type == ResourceAddress::Type::NFS || address->IsCgiAlike()); if (request2.translate.response->transparent && (!request2.uri.args.IsEmpty() || !request2.uri.path_info.IsEmpty())) address = address->DupWithArgs(pool, request2.uri.args.data, request2.uri.args.size, request2.uri.path_info.data, request2.uri.path_info.size); if (!request2.processor_focus) /* forward query string */ address = address->DupWithQueryStringFrom(pool, request2.request.uri); if (address->IsCgiAlike() && address->u.cgi->script_name == nullptr && address->u.cgi->uri == nullptr) { const auto copy = address->Dup(pool); const auto cgi = copy->GetCgi(); /* pass the "real" request URI to the CGI (but without the "args", unless the request is "transparent") */ cgi->uri = ForwardURI(request2); address = copy; } request2.cookie_uri = address->GetUriPath(); struct forward_request forward; request_forward(forward, request2, tr.request_header_forward, GetCookieHost(request2), GetCookieURI(request2), address->type == ResourceAddress::Type::HTTP || address->type == ResourceAddress::Type::LHTTP); #ifdef SPLICE if (forward.body != nullptr) forward.body = istream_pipe_new(&pool, *forward.body, request2.instance.pipe_stock); #endif for (const auto &i : tr.request_headers) forward.headers->Add(i.key, i.value); request2.instance.cached_resource_loader ->SendRequest(pool, request2.session_id.GetClusterHash(), forward.method, *address, HTTP_STATUS_OK, forward.headers, forward.body, proxy_response_handler, &request2, request2.async_ref); }
use ResourceLoader
proxy_handler: use ResourceLoader
C++
bsd-2-clause
CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy
b27b567e40165a9a9f09d85e39ebd4ff5a4e4cdc
src/qt/marketbrowser.cpp
src/qt/marketbrowser.cpp
#include "marketbrowser.h" #include "ui_marketbrowser.h" #include "main.h" #include "wallet.h" #include "base58.h" #include "clientmodel.h" #include "bitcoinrpc.h" #include <QDesktopServices> #include <sstream> #include <string> using namespace json_spirit; const QString kBaseUrl = "https://bzlcoin.org/marketbzl.php?market=market.usd"; const QString kBaseUrl0 = "https://bzlcoin.org/marketbzl.php?market=market.brl"; const QString kBaseUrl1 = "https://blockchain.info/tobtc?currency=USD&value=1"; const QString kBaseUrl2 = "https://bzlcoin.org/marketbzl.php?market=bzl.capbzl.usd"; const QString kBaseUrl3 = "https://bzlcoin.org/marketbzl.php?market=market.btc"; QString bitcoinp = ""; QString bzlcoinp = ""; QString bzlcoinp2 = ""; QString dnrmcp = ""; QString dnrbtcp = ""; double bitcoin2; double bzlcoin2; double bzlcoin3; double dnrmc2; double dnrbtc2; QString bitcoing; QString dnrmarket; QString dollarg; QString realarg; int mode=1; int o = 0; MarketBrowser::MarketBrowser(QWidget *parent) : QWidget(parent), ui(new Ui::MarketBrowser) { ui->setupUi(this); setFixedSize(400, 420); requests(); QObject::connect(&m_nam, SIGNAL(finished(QNetworkReply*)), this, SLOT(parseNetworkResponse(QNetworkReply*))); connect(ui->startButton, SIGNAL(pressed()), this, SLOT( requests())); connect(ui->egal, SIGNAL(pressed()), this, SLOT( update())); } void MarketBrowser::update() { QString temps = ui->egals->text(); double totald = dollarg.toDouble() * temps.toDouble(); double totaldb = realarg.toDouble() * temps.toDouble(); double totaldq = bitcoing.toDouble() * temps.toDouble(); ui->egald->setText("$ "+QString::number(totald)+" USD or "+QString::number(totaldq)+" BTC"); } void MarketBrowser::requests() { getRequest(kBaseUrl); getRequest(kBaseUrl0); getRequest(kBaseUrl1); getRequest(kBaseUrl2); getRequest(kBaseUrl3); } void MarketBrowser::getRequest( const QString &urlString ) { QUrl url ( urlString ); QNetworkRequest req ( url ); req.setHeader(QNetworkRequest::ContentTypeHeader, "application/json; charset=utf-8"); m_nam.get(req); } void MarketBrowser::parseNetworkResponse(QNetworkReply *finished ) { QUrl what = finished->url(); if ( finished->error() != QNetworkReply::NoError ) { // A communication error has occurred emit networkError( finished->error() ); return; } if (what == kBaseUrl) // BZLCoin Price { // QNetworkReply is a QIODevice. So we read from it just like it was a file QString bzlcoin = finished->readAll(); bzlcoin2 = (bzlcoin.toDouble()); bzlcoin = QString::number(bzlcoin2, 'f', 2); if(bzlcoin > bzlcoinp) { ui->bzlcoin->setText("<font color=\"yellow\">$" + bzlcoin + "</font>"); } else if (bzlcoin < bzlcoinp) { ui->bzlcoin->setText("<font color=\"red\">$" + bzlcoin + "</font>"); } else { ui->bzlcoin->setText("$"+bzlcoin+" USD"); } bzlcoinp = bzlcoin; dollarg = bzlcoin; } if (what == kBaseUrl0) // BZLCoin Price BRL { // QNetworkReply is a QIODevice. So we read from it just like it was a file QString bzlcoinz = finished->readAll(); bzlcoin3 = (bzlcoinz.toDouble()); bzlcoinz = QString::number(bzlcoin3, 'f', 2); /* if(bzlcoinz > bzlcoinp2) { ui->bzlcoinz->setText("<font color=\"yellow\">$" + bzlcoinz + "</font>"); } else if (bzlcoinz < bzlcoinp) { ui->bzlcoinz->setText("<font color=\"red\">$" + bzlcoinz + "</font>"); } else { ui->bzlcoin->setText("$"+bzlcoinz+" BRL"); } */ bzlcoinp2 = bzlcoinz; realarg = bzlcoinz; } if (what == kBaseUrl1) // Bitcoin Price { // QNetworkReply is a QIODevice. So we read from it just like it was a file QString bitcoin = finished->readAll(); bitcoin2 = (1 / bitcoin.toDouble()); bitcoin = QString::number(bitcoin2); if(bitcoin > bitcoinp) { ui->bitcoin->setText("<font color=\"yellow\">$" + bitcoin + " USD</font>"); } else if (bitcoin < bitcoinp) { ui->bitcoin->setText("<font color=\"red\">$" + bitcoin + " USD</font>"); } else { ui->bitcoin->setText("$"+bitcoin+" USD"); } bitcoinp = bitcoin; } if (what == kBaseUrl2) // BZLCoin Market Cap { // QNetworkReply is a QIODevice. So we read from it just like it was a file QString dnrmc = finished->readAll(); dnrmc2 = (dnrmc.toDouble()); dnrmc = QString::number(dnrmc2); if(dnrmc > dnrmcp) { ui->dnrmc->setText("<font color=\"yellow\">$" + dnrmc + "</font>"); } else if (dnrmc < dnrmcp) { ui->dnrmc->setText("<font color=\"red\">$" + dnrmc + "</font>"); } else { ui->dnrmc->setText("$"+dnrmc+" USD"); } dnrmcp = dnrmc; dnrmarket = dnrmc; } if (what == kBaseUrl3) // BZLCoin BTC Price { // QNetworkReply is a QIODevice. So we read from it just like it was a file QString dnrbtc = finished->readAll(); dnrbtc2 = (dnrbtc.toDouble()); dnrbtc = QString::number(dnrbtc2, 'f', 8); if(dnrbtc > dnrbtcp) { ui->dnrbtc->setText("<font color=\"yellow\">" + dnrbtc + " BTC</font>"); } else if (dnrbtc < dnrbtcp) { ui->dnrbtc->setText("<font color=\"red\">" + dnrbtc + " BTC</font>"); } else { ui->dnrbtc->setText(dnrbtc+" BTC"); } dnrbtcp = dnrbtc; bitcoing = dnrbtc; } finished->deleteLater(); } void MarketBrowser::setModel(ClientModel *model) { this->model = model; } MarketBrowser::~MarketBrowser() { delete ui; }
#include "marketbrowser.h" #include "ui_marketbrowser.h" #include "main.h" #include "wallet.h" #include "base58.h" #include "clientmodel.h" #include "bitcoinrpc.h" #include <QDesktopServices> #include <sstream> #include <string> using namespace json_spirit; const QString kBaseUrl = "https://bzlcoin.org/marketbzl.php?market=bzl.usd"; const QString kBaseUrl0 = "https://bzlcoin.org/marketbzl.php?market=bzl.brl"; const QString kBaseUrl1 = "https://blockchain.info/tobtc?currency=USD&value=1"; const QString kBaseUrl2 = "https://bzlcoin.org/marketbzl.php?market=bzl.capbzl.usd"; const QString kBaseUrl3 = "https://bzlcoin.org/marketbzl.php?market=market.btc"; QString bitcoinp = ""; QString bzlcoinp = ""; QString bzlcoinp2 = ""; QString dnrmcp = ""; QString dnrbtcp = ""; double bitcoin2; double bzlcoin2; double bzlcoin3; double dnrmc2; double dnrbtc2; QString bitcoing; QString dnrmarket; QString dollarg; QString realarg; int mode=1; int o = 0; MarketBrowser::MarketBrowser(QWidget *parent) : QWidget(parent), ui(new Ui::MarketBrowser) { ui->setupUi(this); setFixedSize(400, 420); requests(); QObject::connect(&m_nam, SIGNAL(finished(QNetworkReply*)), this, SLOT(parseNetworkResponse(QNetworkReply*))); connect(ui->startButton, SIGNAL(pressed()), this, SLOT( requests())); connect(ui->egal, SIGNAL(pressed()), this, SLOT( update())); } void MarketBrowser::update() { QString temps = ui->egals->text(); double totald = dollarg.toDouble() * temps.toDouble(); double totaldb = realarg.toDouble() * temps.toDouble(); double totaldq = bitcoing.toDouble() * temps.toDouble(); ui->egald->setText("$ "+QString::number(totald)+" USD or "+QString::number(totaldq)+" BTC"); } void MarketBrowser::requests() { getRequest(kBaseUrl); getRequest(kBaseUrl0); getRequest(kBaseUrl1); getRequest(kBaseUrl2); getRequest(kBaseUrl3); } void MarketBrowser::getRequest( const QString &urlString ) { QUrl url ( urlString ); QNetworkRequest req ( url ); req.setHeader(QNetworkRequest::ContentTypeHeader, "application/json; charset=utf-8"); m_nam.get(req); } void MarketBrowser::parseNetworkResponse(QNetworkReply *finished ) { QUrl what = finished->url(); if ( finished->error() != QNetworkReply::NoError ) { // A communication error has occurred emit networkError( finished->error() ); return; } if (what == kBaseUrl) // BZLCoin Price { // QNetworkReply is a QIODevice. So we read from it just like it was a file QString bzlcoin = finished->readAll(); bzlcoin2 = (bzlcoin.toDouble()); bzlcoin = QString::number(bzlcoin2, 'f', 2); if(bzlcoin > bzlcoinp) { ui->bzlcoin->setText("<font color=\"yellow\">$" + bzlcoin + "</font>"); } else if (bzlcoin < bzlcoinp) { ui->bzlcoin->setText("<font color=\"red\">$" + bzlcoin + "</font>"); } else { ui->bzlcoin->setText("$"+bzlcoin+" USD"); } bzlcoinp = bzlcoin; dollarg = bzlcoin; } if (what == kBaseUrl0) // BZLCoin Price BRL { // QNetworkReply is a QIODevice. So we read from it just like it was a file QString bzlcoinz = finished->readAll(); bzlcoin3 = (bzlcoinz.toDouble()); bzlcoinz = QString::number(bzlcoin3, 'f', 2); /* if(bzlcoinz > bzlcoinp2) { ui->bzlcoinz->setText("<font color=\"yellow\">$" + bzlcoinz + "</font>"); } else if (bzlcoinz < bzlcoinp) { ui->bzlcoinz->setText("<font color=\"red\">$" + bzlcoinz + "</font>"); } else { ui->bzlcoin->setText("$"+bzlcoinz+" BRL"); } */ bzlcoinp2 = bzlcoinz; realarg = bzlcoinz; } if (what == kBaseUrl1) // Bitcoin Price { // QNetworkReply is a QIODevice. So we read from it just like it was a file QString bitcoin = finished->readAll(); bitcoin2 = (1 / bitcoin.toDouble()); bitcoin = QString::number(bitcoin2); if(bitcoin > bitcoinp) { ui->bitcoin->setText("<font color=\"yellow\">$" + bitcoin + " USD</font>"); } else if (bitcoin < bitcoinp) { ui->bitcoin->setText("<font color=\"red\">$" + bitcoin + " USD</font>"); } else { ui->bitcoin->setText("$"+bitcoin+" USD"); } bitcoinp = bitcoin; } if (what == kBaseUrl2) // BZLCoin Market Cap { // QNetworkReply is a QIODevice. So we read from it just like it was a file QString dnrmc = finished->readAll(); dnrmc2 = (dnrmc.toDouble()); dnrmc = QString::number(dnrmc2); if(dnrmc > dnrmcp) { ui->dnrmc->setText("<font color=\"yellow\">$" + dnrmc + "</font>"); } else if (dnrmc < dnrmcp) { ui->dnrmc->setText("<font color=\"red\">$" + dnrmc + "</font>"); } else { ui->dnrmc->setText("$"+dnrmc+" USD"); } dnrmcp = dnrmc; dnrmarket = dnrmc; } if (what == kBaseUrl3) // BZLCoin BTC Price { // QNetworkReply is a QIODevice. So we read from it just like it was a file QString dnrbtc = finished->readAll(); dnrbtc2 = (dnrbtc.toDouble()); dnrbtc = QString::number(dnrbtc2, 'f', 8); if(dnrbtc > dnrbtcp) { ui->dnrbtc->setText("<font color=\"yellow\">" + dnrbtc + " BTC</font>"); } else if (dnrbtc < dnrbtcp) { ui->dnrbtc->setText("<font color=\"red\">" + dnrbtc + " BTC</font>"); } else { ui->dnrbtc->setText(dnrbtc+" BTC"); } dnrbtcp = dnrbtc; bitcoing = dnrbtc; } finished->deleteLater(); } void MarketBrowser::setModel(ClientModel *model) { this->model = model; } MarketBrowser::~MarketBrowser() { delete ui; }
Update marketbrowser.cpp
Update marketbrowser.cpp
C++
mit
bzlcoin/bzlcoin,bzlcoin/bzlcoin,bzlcoin/bzlcoin,bzlcoin/bzlcoin,bzlcoin/bzlcoin
2ceac627c5430727110b91495369bd71dabc73be
src/qt/optionsdialog.cpp
src/qt/optionsdialog.cpp
#include "optionsdialog.h" #include "ui_optionsdialog.h" #include "netbase.h" #include "bitcoinunits.h" #include "monitoreddatamapper.h" #include "optionsmodel.h" #include "qt/decoration.h" #include "init.h" #include "miner.h" #include <QDir> #include <QIntValidator> #include <QLocale> #include <QMessageBox> OptionsDialog::OptionsDialog(QWidget* parent) : QDialog(parent) , ui(new Ui::OptionsDialog) , model(nullptr) , mapper(nullptr) , fRestartWarningDisplayed_Proxy(false) , fRestartWarningDisplayed_Lang(false) , fProxyIpValid(true) { ui->setupUi(this); resize(GRC::ScaleSize(this, width(), height())); /* Network elements init */ #ifndef USE_UPNP ui->mapPortUpnp->setEnabled(false); #endif ui->proxyIp->setEnabled(false); ui->proxyPort->setEnabled(false); ui->proxyPort->setValidator(new QIntValidator(1, 65535, this)); ui->socksVersion->setEnabled(false); ui->socksVersion->addItem("5", 5); ui->socksVersion->addItem("4", 4); ui->socksVersion->setCurrentIndex(0); connect(ui->connectSocks, SIGNAL(toggled(bool)), ui->proxyIp, SLOT(setEnabled(bool))); connect(ui->connectSocks, SIGNAL(toggled(bool)), ui->proxyPort, SLOT(setEnabled(bool))); connect(ui->connectSocks, SIGNAL(toggled(bool)), ui->socksVersion, SLOT(setEnabled(bool))); connect(ui->connectSocks, SIGNAL(clicked(bool)), this, SLOT(showRestartWarning_Proxy())); ui->proxyIp->installEventFilter(this); ui->stakingEfficiency->installEventFilter(this); ui->minPostSplitOutputValue->installEventFilter(this); /* Window elements init */ #ifdef Q_OS_MAC /* hide launch at startup option on macOS */ ui->gridcoinAtStartup->setVisible(false); ui->gridcoinAtStartupMinimised->setVisible(false); ui->verticalLayout_Main->removeWidget(ui->gridcoinAtStartup); ui->verticalLayout_Main->removeWidget(ui->gridcoinAtStartupMinimised); ui->verticalLayout_Main->removeItem(ui->horizontalLayoutGridcoinStartup); #endif if (!QSystemTrayIcon::isSystemTrayAvailable()) { ui->minimizeToTray->setChecked(false); ui->minimizeToTray->setEnabled(false); ui->minimizeOnClose->setChecked(false); ui->minimizeOnClose->setEnabled(false); } /* Display elements init */ QDir translations(":translations"); ui->lang->addItem(QString("(") + tr("default") + QString(")"), QVariant("")); for (const QString& langStr : translations.entryList()) { QLocale locale(langStr); /** check if the locale name consists of 2 parts (language_country) */ if(langStr.contains("_")) { /** display language strings as "native language - native country (locale name)", e.g. "Deutsch - Deutschland (de)" */ ui->lang->addItem(locale.nativeLanguageName() + QString(" - ") + locale.nativeCountryName() + QString(" (") + langStr + QString(")"), QVariant(langStr)); } else { /** display language strings as "native language (locale name)", e.g. "Deutsch (de)" */ ui->lang->addItem(locale.nativeLanguageName() + QString(" (") + langStr + QString(")"), QVariant(langStr)); } } ui->unit->setModel(new BitcoinUnits(this)); ui->styleComboBox->addItem(tr("Dark"), QVariant("dark")); ui->styleComboBox->addItem(tr("Light"), QVariant("light")); /* Widget-to-option mapper */ mapper = new MonitoredDataMapper(this); mapper->setSubmitPolicy(QDataWidgetMapper::ManualSubmit); mapper->setOrientation(Qt::Vertical); /* enable apply button when data modified */ connect(mapper, SIGNAL(viewModified()), this, SLOT(enableApplyButton())); /* disable apply button when new data loaded */ connect(mapper, SIGNAL(currentIndexChanged(int)), this, SLOT(disableApplyButton())); /* setup/change UI elements when proxy IP, stakingEfficiency, or minStakeSplitValue is invalid/valid */ connect(this, SIGNAL(proxyIpValid(QValidatedLineEdit *, bool)), this, SLOT(handleProxyIpValid(QValidatedLineEdit *, bool))); connect(this, SIGNAL(stakingEfficiencyValid(QValidatedLineEdit *, bool)), this, SLOT(handleStakingEfficiencyValid(QValidatedLineEdit *, bool))); connect(this, SIGNAL(minStakeSplitValueValid(QValidatedLineEdit *, bool)), this, SLOT(handleMinStakeSplitValueValid(QValidatedLineEdit *, bool))); if (fTestNet) ui->disableUpdateCheck->setHidden(true); ui->gridcoinAtStartupMinimised->setHidden(!ui->gridcoinAtStartup->isChecked()); ui->limitTxnDisplayDateEdit->setHidden(!ui->limitTxnDisplayCheckBox->isChecked()); connect(ui->gridcoinAtStartup, SIGNAL(toggled(bool)), this, SLOT(hideStartMinimized())); connect(ui->gridcoinAtStartupMinimised, SIGNAL(toggled(bool)), this, SLOT(hideStartMinimized())); connect(ui->limitTxnDisplayCheckBox, SIGNAL(toggled(bool)), this, SLOT(hideLimitTxnDisplayDate())); bool stake_split_enabled = ui->enableStakeSplit->isChecked(); ui->stakingEfficiencyLabel->setHidden(!stake_split_enabled); ui->stakingEfficiency->setHidden(!stake_split_enabled); ui->minPostSplitOutputValueLabel->setHidden(!stake_split_enabled); ui->minPostSplitOutputValue->setHidden(!stake_split_enabled); connect(ui->enableStakeSplit, SIGNAL(toggled(bool)), this, SLOT(hideStakeSplitting())); } OptionsDialog::~OptionsDialog() { delete ui; } void OptionsDialog::setModel(OptionsModel *model) { this->model = model; if(model) { connect(model, SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit())); mapper->setModel(model); setMapper(); mapper->toFirst(); } /* update the display unit, to not use the default ("BTC") */ updateDisplayUnit(); updateStyle(); /* warn only when language selection changes by user action (placed here so init via mapper doesn't trigger this) */ connect(ui->lang, SIGNAL(valueChanged()), this, SLOT(showRestartWarning_Lang())); /* disable apply button after settings are loaded as there is nothing to save */ disableApplyButton(); } void OptionsDialog::setMapper() { /* Main */ mapper->addMapping(ui->reserveBalance, OptionsModel::ReserveBalance); mapper->addMapping(ui->gridcoinAtStartup, OptionsModel::StartAtStartup); mapper->addMapping(ui->gridcoinAtStartupMinimised, OptionsModel::StartMin); mapper->addMapping(ui->disableUpdateCheck, OptionsModel::DisableUpdateCheck); /* Network */ mapper->addMapping(ui->mapPortUpnp, OptionsModel::MapPortUPnP); mapper->addMapping(ui->connectSocks, OptionsModel::ProxyUse); mapper->addMapping(ui->proxyIp, OptionsModel::ProxyIP); mapper->addMapping(ui->proxyPort, OptionsModel::ProxyPort); mapper->addMapping(ui->socksVersion, OptionsModel::ProxySocksVersion); /* Staking */ mapper->addMapping(ui->enableStaking, OptionsModel::EnableStaking); mapper->addMapping(ui->enableStakeSplit, OptionsModel::EnableStakeSplit); mapper->addMapping(ui->stakingEfficiency, OptionsModel::StakingEfficiency); mapper->addMapping(ui->minPostSplitOutputValue, OptionsModel::MinStakeSplitValue); /* Window */ mapper->addMapping(ui->disableTransactionNotifications, OptionsModel::DisableTrxNotifications); mapper->addMapping(ui->disablePollNotifications, OptionsModel::DisablePollNotifications); #ifndef Q_OS_MAC if (QSystemTrayIcon::isSystemTrayAvailable()) { mapper->addMapping(ui->minimizeToTray, OptionsModel::MinimizeToTray); mapper->addMapping(ui->minimizeOnClose, OptionsModel::MinimizeOnClose); } mapper->addMapping(ui->confirmOnClose, OptionsModel::ConfirmOnClose); #endif /* Display */ mapper->addMapping(ui->lang, OptionsModel::Language); mapper->addMapping(ui->unit, OptionsModel::DisplayUnit); mapper->addMapping(ui->styleComboBox, OptionsModel::WalletStylesheet,"currentData"); mapper->addMapping(ui->limitTxnDisplayCheckBox, OptionsModel::LimitTxnDisplay); mapper->addMapping(ui->limitTxnDisplayDateEdit, OptionsModel::LimitTxnDate); mapper->addMapping(ui->displayAddresses, OptionsModel::DisplayAddresses); } void OptionsDialog::enableApplyButton() { ui->applyButton->setEnabled(true); } void OptionsDialog::disableApplyButton() { ui->applyButton->setEnabled(false); } void OptionsDialog::enableSaveButtons() { /* prevent enabling of the save buttons when data modified, if there is an invalid proxy address present */ if(fProxyIpValid) setSaveButtonState(true); } void OptionsDialog::disableSaveButtons() { setSaveButtonState(false); } void OptionsDialog::setSaveButtonState(bool fState) { ui->applyButton->setEnabled(fState); ui->okButton->setEnabled(fState); } void OptionsDialog::on_okButton_clicked() { mapper->submit(); accept(); } void OptionsDialog::on_cancelButton_clicked() { reject(); } void OptionsDialog::on_applyButton_clicked() { mapper->submit(); disableApplyButton(); } void OptionsDialog::showRestartWarning_Proxy() { if(!fRestartWarningDisplayed_Proxy) { QMessageBox::warning(this, tr("Warning"), tr("This setting will take effect after restarting Gridcoin."), QMessageBox::Ok); fRestartWarningDisplayed_Proxy = true; } } void OptionsDialog::showRestartWarning_Lang() { if(!fRestartWarningDisplayed_Lang) { QMessageBox::warning(this, tr("Warning"), tr("This setting will take effect after restarting Gridcoin."), QMessageBox::Ok); fRestartWarningDisplayed_Lang = true; } } void OptionsDialog::updateDisplayUnit() { if(model) { /* Update reserveBalance with the current unit */ ui->reserveBalance->setDisplayUnit(model->getDisplayUnit()); } } void OptionsDialog::updateStyle() { if(model) { /* Update style with the current stylesheet */ QString value=model->getCurrentStyle(); int index = ui->styleComboBox->findData(value); if ( index != -1 ) { // -1 for not found ui->styleComboBox->setCurrentIndex(index); } } } void OptionsDialog::hideStartMinimized() { if (model) { ui->gridcoinAtStartupMinimised->setHidden(!ui->gridcoinAtStartup->isChecked()); } } void OptionsDialog::hideLimitTxnDisplayDate() { if (model) { ui->limitTxnDisplayDateEdit->setHidden(!ui->limitTxnDisplayCheckBox->isChecked()); } } void OptionsDialog::hideStakeSplitting() { if (model) { bool stake_split_enabled = ui->enableStakeSplit->isChecked(); ui->stakingEfficiencyLabel->setHidden(!stake_split_enabled); ui->stakingEfficiency->setHidden(!stake_split_enabled); ui->minPostSplitOutputValueLabel->setHidden(!stake_split_enabled); ui->minPostSplitOutputValue->setHidden(!stake_split_enabled); } } void OptionsDialog::handleProxyIpValid(QValidatedLineEdit *object, bool fState) { // this is used in a check before re-enabling the save buttons fProxyIpValid = fState; if (fProxyIpValid) { enableSaveButtons(); ui->statusLabel->clear(); } else { disableSaveButtons(); object->setValid(fProxyIpValid); ui->statusLabel->setStyleSheet("QLabel { color: red; }"); ui->statusLabel->setText(tr("The supplied proxy address is invalid.")); } } void OptionsDialog::handleStakingEfficiencyValid(QValidatedLineEdit *object, bool fState) { // this is used in a check before re-enabling the save buttons fStakingEfficiencyValid = fState; if (fStakingEfficiencyValid) { enableSaveButtons(); ui->statusLabel->clear(); } else { disableSaveButtons(); object->setValid(fStakingEfficiencyValid); ui->statusLabel->setStyleSheet("QLabel { color: red; }"); ui->statusLabel->setText(tr("The supplied target staking efficiency is invalid.")); } } void OptionsDialog::handleMinStakeSplitValueValid(QValidatedLineEdit *object, bool fState) { // this is used in a check before re-enabling the save buttons fMinStakeSplitValueValid = fState; if (fMinStakeSplitValueValid) { enableSaveButtons(); ui->statusLabel->clear(); } else { disableSaveButtons(); object->setValid(fMinStakeSplitValueValid); ui->statusLabel->setStyleSheet("QLabel { color: red; }"); ui->statusLabel->setText(tr("The supplied minimum post stake-split UTXO size is invalid.")); } } bool OptionsDialog::eventFilter(QObject *object, QEvent *event) { if (event->type() == QEvent::FocusOut) { if (object == ui->proxyIp) { CService addr; /* Check proxyIp for a valid IPv4/IPv6 address and emit the proxyIpValid signal */ emit proxyIpValid(ui->proxyIp, LookupNumeric(ui->proxyIp->text().toStdString().c_str(), addr)); } if (object == ui->stakingEfficiency) { bool ok = false; double efficiency = ui->stakingEfficiency->text().toDouble(&ok); if (!ok) { emit stakingEfficiencyValid(ui->stakingEfficiency, false); } else { if (efficiency < 75.0 || efficiency > 98.0) { emit stakingEfficiencyValid(ui->stakingEfficiency, false); } else { emit stakingEfficiencyValid(ui->stakingEfficiency, true); } } } if (object == ui->minPostSplitOutputValue) { bool ok = false; CAmount post_split_min_value = (CAmount) ui->minPostSplitOutputValue->text().toULong(&ok) * COIN; if (!ok) { emit minStakeSplitValueValid(ui->minPostSplitOutputValue, false); } else { if (post_split_min_value < MIN_STAKE_SPLIT_VALUE_GRC * COIN || post_split_min_value > MAX_MONEY) { emit minStakeSplitValueValid(ui->minPostSplitOutputValue, false); } else { emit minStakeSplitValueValid(ui->minPostSplitOutputValue, true); } } } } return QDialog::eventFilter(object, event); }
#include "optionsdialog.h" #include "ui_optionsdialog.h" #include "netbase.h" #include "bitcoinunits.h" #include "monitoreddatamapper.h" #include "optionsmodel.h" #include "qt/decoration.h" #include "init.h" #include "miner.h" #include <QDir> #include <QIntValidator> #include <QLocale> #include <QMessageBox> #include <QSystemTrayIcon> OptionsDialog::OptionsDialog(QWidget* parent) : QDialog(parent) , ui(new Ui::OptionsDialog) , model(nullptr) , mapper(nullptr) , fRestartWarningDisplayed_Proxy(false) , fRestartWarningDisplayed_Lang(false) , fProxyIpValid(true) { ui->setupUi(this); resize(GRC::ScaleSize(this, width(), height())); /* Network elements init */ #ifndef USE_UPNP ui->mapPortUpnp->setEnabled(false); #endif ui->proxyIp->setEnabled(false); ui->proxyPort->setEnabled(false); ui->proxyPort->setValidator(new QIntValidator(1, 65535, this)); ui->socksVersion->setEnabled(false); ui->socksVersion->addItem("5", 5); ui->socksVersion->addItem("4", 4); ui->socksVersion->setCurrentIndex(0); connect(ui->connectSocks, SIGNAL(toggled(bool)), ui->proxyIp, SLOT(setEnabled(bool))); connect(ui->connectSocks, SIGNAL(toggled(bool)), ui->proxyPort, SLOT(setEnabled(bool))); connect(ui->connectSocks, SIGNAL(toggled(bool)), ui->socksVersion, SLOT(setEnabled(bool))); connect(ui->connectSocks, SIGNAL(clicked(bool)), this, SLOT(showRestartWarning_Proxy())); ui->proxyIp->installEventFilter(this); ui->stakingEfficiency->installEventFilter(this); ui->minPostSplitOutputValue->installEventFilter(this); /* Window elements init */ #ifdef Q_OS_MAC /* hide launch at startup option on macOS */ ui->gridcoinAtStartup->setVisible(false); ui->gridcoinAtStartupMinimised->setVisible(false); ui->verticalLayout_Main->removeWidget(ui->gridcoinAtStartup); ui->verticalLayout_Main->removeWidget(ui->gridcoinAtStartupMinimised); ui->verticalLayout_Main->removeItem(ui->horizontalLayoutGridcoinStartup); /* disable close confirmation on macOS */ ui->confirmOnClose->setChecked(false); ui->confirmOnClose->setEnabled(false); #endif if (!QSystemTrayIcon::isSystemTrayAvailable()) { ui->minimizeToTray->setChecked(false); ui->minimizeToTray->setEnabled(false); ui->minimizeOnClose->setChecked(false); ui->minimizeOnClose->setEnabled(false); } /* Display elements init */ QDir translations(":translations"); ui->lang->addItem(QString("(") + tr("default") + QString(")"), QVariant("")); for (const QString& langStr : translations.entryList()) { QLocale locale(langStr); /** check if the locale name consists of 2 parts (language_country) */ if(langStr.contains("_")) { /** display language strings as "native language - native country (locale name)", e.g. "Deutsch - Deutschland (de)" */ ui->lang->addItem(locale.nativeLanguageName() + QString(" - ") + locale.nativeCountryName() + QString(" (") + langStr + QString(")"), QVariant(langStr)); } else { /** display language strings as "native language (locale name)", e.g. "Deutsch (de)" */ ui->lang->addItem(locale.nativeLanguageName() + QString(" (") + langStr + QString(")"), QVariant(langStr)); } } ui->unit->setModel(new BitcoinUnits(this)); ui->styleComboBox->addItem(tr("Dark"), QVariant("dark")); ui->styleComboBox->addItem(tr("Light"), QVariant("light")); /* Widget-to-option mapper */ mapper = new MonitoredDataMapper(this); mapper->setSubmitPolicy(QDataWidgetMapper::ManualSubmit); mapper->setOrientation(Qt::Vertical); /* enable apply button when data modified */ connect(mapper, SIGNAL(viewModified()), this, SLOT(enableApplyButton())); /* disable apply button when new data loaded */ connect(mapper, SIGNAL(currentIndexChanged(int)), this, SLOT(disableApplyButton())); /* setup/change UI elements when proxy IP, stakingEfficiency, or minStakeSplitValue is invalid/valid */ connect(this, SIGNAL(proxyIpValid(QValidatedLineEdit *, bool)), this, SLOT(handleProxyIpValid(QValidatedLineEdit *, bool))); connect(this, SIGNAL(stakingEfficiencyValid(QValidatedLineEdit *, bool)), this, SLOT(handleStakingEfficiencyValid(QValidatedLineEdit *, bool))); connect(this, SIGNAL(minStakeSplitValueValid(QValidatedLineEdit *, bool)), this, SLOT(handleMinStakeSplitValueValid(QValidatedLineEdit *, bool))); if (fTestNet) ui->disableUpdateCheck->setHidden(true); ui->gridcoinAtStartupMinimised->setHidden(!ui->gridcoinAtStartup->isChecked()); ui->limitTxnDisplayDateEdit->setHidden(!ui->limitTxnDisplayCheckBox->isChecked()); connect(ui->gridcoinAtStartup, SIGNAL(toggled(bool)), this, SLOT(hideStartMinimized())); connect(ui->gridcoinAtStartupMinimised, SIGNAL(toggled(bool)), this, SLOT(hideStartMinimized())); connect(ui->limitTxnDisplayCheckBox, SIGNAL(toggled(bool)), this, SLOT(hideLimitTxnDisplayDate())); bool stake_split_enabled = ui->enableStakeSplit->isChecked(); ui->stakingEfficiencyLabel->setHidden(!stake_split_enabled); ui->stakingEfficiency->setHidden(!stake_split_enabled); ui->minPostSplitOutputValueLabel->setHidden(!stake_split_enabled); ui->minPostSplitOutputValue->setHidden(!stake_split_enabled); connect(ui->enableStakeSplit, SIGNAL(toggled(bool)), this, SLOT(hideStakeSplitting())); } OptionsDialog::~OptionsDialog() { delete ui; } void OptionsDialog::setModel(OptionsModel *model) { this->model = model; if(model) { connect(model, SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit())); mapper->setModel(model); setMapper(); mapper->toFirst(); } /* update the display unit, to not use the default ("BTC") */ updateDisplayUnit(); updateStyle(); /* warn only when language selection changes by user action (placed here so init via mapper doesn't trigger this) */ connect(ui->lang, SIGNAL(valueChanged()), this, SLOT(showRestartWarning_Lang())); /* disable apply button after settings are loaded as there is nothing to save */ disableApplyButton(); } void OptionsDialog::setMapper() { /* Main */ mapper->addMapping(ui->reserveBalance, OptionsModel::ReserveBalance); mapper->addMapping(ui->gridcoinAtStartup, OptionsModel::StartAtStartup); mapper->addMapping(ui->gridcoinAtStartupMinimised, OptionsModel::StartMin); mapper->addMapping(ui->disableUpdateCheck, OptionsModel::DisableUpdateCheck); /* Network */ mapper->addMapping(ui->mapPortUpnp, OptionsModel::MapPortUPnP); mapper->addMapping(ui->connectSocks, OptionsModel::ProxyUse); mapper->addMapping(ui->proxyIp, OptionsModel::ProxyIP); mapper->addMapping(ui->proxyPort, OptionsModel::ProxyPort); mapper->addMapping(ui->socksVersion, OptionsModel::ProxySocksVersion); /* Staking */ mapper->addMapping(ui->enableStaking, OptionsModel::EnableStaking); mapper->addMapping(ui->enableStakeSplit, OptionsModel::EnableStakeSplit); mapper->addMapping(ui->stakingEfficiency, OptionsModel::StakingEfficiency); mapper->addMapping(ui->minPostSplitOutputValue, OptionsModel::MinStakeSplitValue); /* Window */ mapper->addMapping(ui->disableTransactionNotifications, OptionsModel::DisableTrxNotifications); mapper->addMapping(ui->disablePollNotifications, OptionsModel::DisablePollNotifications); #ifndef Q_OS_MAC if (QSystemTrayIcon::isSystemTrayAvailable()) { mapper->addMapping(ui->minimizeToTray, OptionsModel::MinimizeToTray); mapper->addMapping(ui->minimizeOnClose, OptionsModel::MinimizeOnClose); } mapper->addMapping(ui->confirmOnClose, OptionsModel::ConfirmOnClose); #endif /* Display */ mapper->addMapping(ui->lang, OptionsModel::Language); mapper->addMapping(ui->unit, OptionsModel::DisplayUnit); mapper->addMapping(ui->styleComboBox, OptionsModel::WalletStylesheet,"currentData"); mapper->addMapping(ui->limitTxnDisplayCheckBox, OptionsModel::LimitTxnDisplay); mapper->addMapping(ui->limitTxnDisplayDateEdit, OptionsModel::LimitTxnDate); mapper->addMapping(ui->displayAddresses, OptionsModel::DisplayAddresses); } void OptionsDialog::enableApplyButton() { ui->applyButton->setEnabled(true); } void OptionsDialog::disableApplyButton() { ui->applyButton->setEnabled(false); } void OptionsDialog::enableSaveButtons() { /* prevent enabling of the save buttons when data modified, if there is an invalid proxy address present */ if(fProxyIpValid) setSaveButtonState(true); } void OptionsDialog::disableSaveButtons() { setSaveButtonState(false); } void OptionsDialog::setSaveButtonState(bool fState) { ui->applyButton->setEnabled(fState); ui->okButton->setEnabled(fState); } void OptionsDialog::on_okButton_clicked() { mapper->submit(); accept(); } void OptionsDialog::on_cancelButton_clicked() { reject(); } void OptionsDialog::on_applyButton_clicked() { mapper->submit(); disableApplyButton(); } void OptionsDialog::showRestartWarning_Proxy() { if(!fRestartWarningDisplayed_Proxy) { QMessageBox::warning(this, tr("Warning"), tr("This setting will take effect after restarting Gridcoin."), QMessageBox::Ok); fRestartWarningDisplayed_Proxy = true; } } void OptionsDialog::showRestartWarning_Lang() { if(!fRestartWarningDisplayed_Lang) { QMessageBox::warning(this, tr("Warning"), tr("This setting will take effect after restarting Gridcoin."), QMessageBox::Ok); fRestartWarningDisplayed_Lang = true; } } void OptionsDialog::updateDisplayUnit() { if(model) { /* Update reserveBalance with the current unit */ ui->reserveBalance->setDisplayUnit(model->getDisplayUnit()); } } void OptionsDialog::updateStyle() { if(model) { /* Update style with the current stylesheet */ QString value=model->getCurrentStyle(); int index = ui->styleComboBox->findData(value); if ( index != -1 ) { // -1 for not found ui->styleComboBox->setCurrentIndex(index); } } } void OptionsDialog::hideStartMinimized() { if (model) { ui->gridcoinAtStartupMinimised->setHidden(!ui->gridcoinAtStartup->isChecked()); } } void OptionsDialog::hideLimitTxnDisplayDate() { if (model) { ui->limitTxnDisplayDateEdit->setHidden(!ui->limitTxnDisplayCheckBox->isChecked()); } } void OptionsDialog::hideStakeSplitting() { if (model) { bool stake_split_enabled = ui->enableStakeSplit->isChecked(); ui->stakingEfficiencyLabel->setHidden(!stake_split_enabled); ui->stakingEfficiency->setHidden(!stake_split_enabled); ui->minPostSplitOutputValueLabel->setHidden(!stake_split_enabled); ui->minPostSplitOutputValue->setHidden(!stake_split_enabled); } } void OptionsDialog::handleProxyIpValid(QValidatedLineEdit *object, bool fState) { // this is used in a check before re-enabling the save buttons fProxyIpValid = fState; if (fProxyIpValid) { enableSaveButtons(); ui->statusLabel->clear(); } else { disableSaveButtons(); object->setValid(fProxyIpValid); ui->statusLabel->setStyleSheet("QLabel { color: red; }"); ui->statusLabel->setText(tr("The supplied proxy address is invalid.")); } } void OptionsDialog::handleStakingEfficiencyValid(QValidatedLineEdit *object, bool fState) { // this is used in a check before re-enabling the save buttons fStakingEfficiencyValid = fState; if (fStakingEfficiencyValid) { enableSaveButtons(); ui->statusLabel->clear(); } else { disableSaveButtons(); object->setValid(fStakingEfficiencyValid); ui->statusLabel->setStyleSheet("QLabel { color: red; }"); ui->statusLabel->setText(tr("The supplied target staking efficiency is invalid.")); } } void OptionsDialog::handleMinStakeSplitValueValid(QValidatedLineEdit *object, bool fState) { // this is used in a check before re-enabling the save buttons fMinStakeSplitValueValid = fState; if (fMinStakeSplitValueValid) { enableSaveButtons(); ui->statusLabel->clear(); } else { disableSaveButtons(); object->setValid(fMinStakeSplitValueValid); ui->statusLabel->setStyleSheet("QLabel { color: red; }"); ui->statusLabel->setText(tr("The supplied minimum post stake-split UTXO size is invalid.")); } } bool OptionsDialog::eventFilter(QObject *object, QEvent *event) { if (event->type() == QEvent::FocusOut) { if (object == ui->proxyIp) { CService addr; /* Check proxyIp for a valid IPv4/IPv6 address and emit the proxyIpValid signal */ emit proxyIpValid(ui->proxyIp, LookupNumeric(ui->proxyIp->text().toStdString().c_str(), addr)); } if (object == ui->stakingEfficiency) { bool ok = false; double efficiency = ui->stakingEfficiency->text().toDouble(&ok); if (!ok) { emit stakingEfficiencyValid(ui->stakingEfficiency, false); } else { if (efficiency < 75.0 || efficiency > 98.0) { emit stakingEfficiencyValid(ui->stakingEfficiency, false); } else { emit stakingEfficiencyValid(ui->stakingEfficiency, true); } } } if (object == ui->minPostSplitOutputValue) { bool ok = false; CAmount post_split_min_value = (CAmount) ui->minPostSplitOutputValue->text().toULong(&ok) * COIN; if (!ok) { emit minStakeSplitValueValid(ui->minPostSplitOutputValue, false); } else { if (post_split_min_value < MIN_STAKE_SPLIT_VALUE_GRC * COIN || post_split_min_value > MAX_MONEY) { emit minStakeSplitValueValid(ui->minPostSplitOutputValue, false); } else { emit minStakeSplitValueValid(ui->minPostSplitOutputValue, true); } } } } return QDialog::eventFilter(object, event); }
Disable close confirmation windows on macOS.
Disable close confirmation windows on macOS.
C++
mit
caraka/gridcoinresearch,gridcoin/Gridcoin-Research,gridcoin/Gridcoin-Research,caraka/gridcoinresearch,gridcoin/Gridcoin-Research,caraka/gridcoinresearch,caraka/gridcoinresearch,gridcoin/Gridcoin-Research,caraka/gridcoinresearch,gridcoin/Gridcoin-Research,gridcoin/Gridcoin-Research,caraka/gridcoinresearch
884c4c9e65ea98d8a033c23ebe24945c6eab2991
src/qt/miningpage.cpp
src/qt/miningpage.cpp
#include "miningpage.h" #include "ui_miningpage.h" MiningPage::MiningPage(QWidget *parent) : QWidget(parent), ui(new Ui::MiningPage) { ui->setupUi(this); setFixedSize(400, 420); minerActive = false; minerProcess = new QProcess(this); minerProcess->setProcessChannelMode(QProcess::MergedChannels); readTimer = new QTimer(this); acceptedShares = 0; rejectedShares = 0; roundAcceptedShares = 0; roundRejectedShares = 0; initThreads = 0; connect(readTimer, SIGNAL(timeout()), this, SLOT(readProcessOutput())); connect(ui->startButton, SIGNAL(pressed()), this, SLOT(startPressed())); connect(ui->typeBox, SIGNAL(currentIndexChanged(int)), this, SLOT(typeChanged(int))); connect(ui->debugCheckBox, SIGNAL(toggled(bool)), this, SLOT(debugToggled(bool))); connect(minerProcess, SIGNAL(started()), this, SLOT(minerStarted())); connect(minerProcess, SIGNAL(error(QProcess::ProcessError)), this, SLOT(minerError(QProcess::ProcessError))); connect(minerProcess, SIGNAL(finished(int,QProcess::ExitStatus)), this, SLOT(minerFinished())); connect(minerProcess, SIGNAL(readyRead()), this, SLOT(readProcessOutput())); } MiningPage::~MiningPage() { minerProcess->kill(); delete ui; } void MiningPage::setModel(ClientModel *model) { this->model = model; loadSettings(); bool pool = model->getMiningType() == ClientModel::PoolMining; ui->threadsBox->setValue(model->getMiningThreads()); ui->typeBox->setCurrentIndex(pool ? 1 : 0); if (model->getMiningStarted()) startPressed(); } void MiningPage::startPressed() { initThreads = ui->threadsBox->value(); if (minerActive == false) { saveSettings(); if (getMiningType() == ClientModel::SoloMining) minerStarted(); else startPoolMining(); } else { if (getMiningType() == ClientModel::SoloMining) minerFinished(); else stopPoolMining(); } } void MiningPage::startPoolMining() { QStringList args; QString url = ui->serverLine->text(); if (!url.contains("http://")) url.prepend("http://"); QString urlLine = QString("%1:%2").arg(url, ui->portLine->text()); QString userpassLine = QString("%1:%2").arg(ui->usernameLine->text(), ui->passwordLine->text()); args << "--algo" << "scrypt"; args << "--scantime" << ui->scantimeBox->text().toAscii(); args << "--url" << urlLine.toAscii(); args << "--userpass" << userpassLine.toAscii(); args << "--threads" << ui->threadsBox->text().toAscii(); args << "--retries" << "-1"; // Retry forever. args << "-P"; // This is need for this to work correctly on Windows. Extra protocol dump helps flush the buffer quicker. threadSpeed.clear(); acceptedShares = 0; rejectedShares = 0; roundAcceptedShares = 0; roundRejectedShares = 0; // If minerd is in current path, then use that. Otherwise, assume minerd is in the path somewhere. #ifdef WIN32 QString program = QDir::currentPath() + "\\minerd"; #else QString program = QDir::currentPath() + "/minerd"; #endif if (!QFile::exists(program)) program = "minerd"; if (ui->debugCheckBox->isChecked()) ui->list->addItem(args.join(" ").prepend(" ").prepend(program)); ui->mineSpeedLabel->setText("Speed: N/A"); ui->shareCount->setText("Accepted: 0 - Rejected: 0"); minerProcess->start(program,args); minerProcess->waitForStarted(-1); readTimer->start(500); } void MiningPage::stopPoolMining() { ui->mineSpeedLabel->setText(""); minerProcess->kill(); readTimer->stop(); } void MiningPage::saveSettings() { model->setMiningDebug(ui->debugCheckBox->isChecked()); model->setMiningScanTime(ui->scantimeBox->value()); model->setMiningServer(ui->serverLine->text()); model->setMiningPort(ui->portLine->text()); model->setMiningUsername(ui->usernameLine->text()); model->setMiningPassword(ui->passwordLine->text()); } void MiningPage::loadSettings() { ui->debugCheckBox->setChecked(model->getMiningDebug()); ui->scantimeBox->setValue(model->getMiningScanTime()); ui->serverLine->setText(model->getMiningServer()); ui->portLine->setText(model->getMiningPort()); ui->usernameLine->setText(model->getMiningUsername()); ui->passwordLine->setText(model->getMiningPassword()); } void MiningPage::readProcessOutput() { QByteArray output; minerProcess->reset(); output = minerProcess->readAll(); QString outputString(output); if (!outputString.isEmpty()) { QStringList list = outputString.split("\n", QString::SkipEmptyParts); int i; for (i=0; i<list.size(); i++) { QString line = list.at(i); // Ignore protocol dump if (!line.startsWith("[") || line.contains("JSON protocol") || line.contains("HTTP hdr")) continue; if (ui->debugCheckBox->isChecked()) { ui->list->addItem(line.trimmed()); ui->list->scrollToBottom(); } if (line.contains("PROOF OF WORK RESULT: true")) reportToList("Share accepted", SHARE_SUCCESS, getTime(line)); else if (line.contains("PROOF OF WORK RESULT: false")) reportToList("Share rejected", SHARE_FAIL, getTime(line)); else if (line.contains("LONGPOLL detected new block")) reportToList("LONGPOLL detected a new block", LONGPOLL, getTime(line)); else if (line.contains("Supported options:")) reportToList("Miner didn't start properly. Try checking your settings.", ERROR, NULL); else if (line.contains("The requested URL returned error: 403")) reportToList("Couldn't connect. Please check your username and password.", ERROR, NULL); else if (line.contains("HTTP request failed")) reportToList("Couldn't connect. Please check pool server and port.", ERROR, NULL); else if (line.contains("JSON-RPC call failed")) reportToList("Couldn't communicate with server. Retrying in 30 seconds.", ERROR, NULL); else if (line.contains("thread ") && line.contains("khash/sec")) { QString threadIDstr = line.at(line.indexOf("thread ")+7); int threadID = threadIDstr.toInt(); int threadSpeedindx = line.indexOf(","); QString threadSpeedstr = line.mid(threadSpeedindx); threadSpeedstr.chop(10); threadSpeedstr.remove(", "); threadSpeedstr.remove(" "); threadSpeedstr.remove('\n'); double speed=0; speed = threadSpeedstr.toDouble(); threadSpeed[threadID] = speed; updateSpeed(); } } } } void MiningPage::minerError(QProcess::ProcessError error) { if (error == QProcess::FailedToStart) { reportToList("Miner failed to start. Make sure you have the minerd executable and libraries in the same directory as Litecoin-QT.", ERROR, NULL); } } void MiningPage::minerFinished() { if (getMiningType() == ClientModel::SoloMining) reportToList("Solo mining stopped.", ERROR, NULL); else reportToList("Miner exited.", ERROR, NULL); ui->list->addItem(""); minerActive = false; resetMiningButton(); model->setMining(getMiningType(), false, initThreads, 0); } void MiningPage::minerStarted() { if (!minerActive) if (getMiningType() == ClientModel::SoloMining) reportToList("Solo mining started.", ERROR, NULL); else reportToList("Miner started. It usually takes a minute until the program starts reporting information.", STARTED, NULL); minerActive = true; resetMiningButton(); model->setMining(getMiningType(), true, initThreads, 0); } void MiningPage::updateSpeed() { double totalSpeed=0; int totalThreads=0; QMapIterator<int, double> iter(threadSpeed); while(iter.hasNext()) { iter.next(); totalSpeed += iter.value(); totalThreads++; } // If all threads haven't reported the hash speed yet, make an assumption if (totalThreads != initThreads) { totalSpeed = (totalSpeed/totalThreads)*initThreads; } QString speedString = QString("%1").arg(totalSpeed); QString threadsString = QString("%1").arg(initThreads); QString acceptedString = QString("%1").arg(acceptedShares); QString rejectedString = QString("%1").arg(rejectedShares); QString roundAcceptedString = QString("%1").arg(roundAcceptedShares); QString roundRejectedString = QString("%1").arg(roundRejectedShares); if (totalThreads == initThreads) ui->mineSpeedLabel->setText(QString("Speed: %1 khash/sec - %2 thread(s)").arg(speedString, threadsString)); else ui->mineSpeedLabel->setText(QString("Speed: ~%1 khash/sec - %2 thread(s)").arg(speedString, threadsString)); ui->shareCount->setText(QString("Accepted: %1 (%3) - Rejected: %2 (%4)").arg(acceptedString, rejectedString, roundAcceptedString, roundRejectedString)); model->setMining(getMiningType(), true, initThreads, totalSpeed*1000); } void MiningPage::reportToList(QString msg, int type, QString time) { QString message; if (time == NULL) message = QString("[%1] - %2").arg(QTime::currentTime().toString(), msg); else message = QString("[%1] - %2").arg(time, msg); switch(type) { case SHARE_SUCCESS: acceptedShares++; roundAcceptedShares++; updateSpeed(); break; case SHARE_FAIL: rejectedShares++; roundRejectedShares++; updateSpeed(); break; case LONGPOLL: roundAcceptedShares = 0; roundRejectedShares = 0; break; default: break; } ui->list->addItem(message); ui->list->scrollToBottom(); } // Function for fetching the time QString MiningPage::getTime(QString time) { if (time.contains("[")) { time.resize(21); time.remove("["); time.remove("]"); time.remove(0,11); return time; } else return NULL; } void MiningPage::enableMiningControls(bool enable) { ui->typeBox->setEnabled(enable); ui->threadsBox->setEnabled(enable); ui->scantimeBox->setEnabled(enable); ui->serverLine->setEnabled(enable); ui->portLine->setEnabled(enable); ui->usernameLine->setEnabled(enable); ui->passwordLine->setEnabled(enable); } void MiningPage::enablePoolMiningControls(bool enable) { ui->scantimeBox->setEnabled(enable); ui->serverLine->setEnabled(enable); ui->portLine->setEnabled(enable); ui->usernameLine->setEnabled(enable); ui->passwordLine->setEnabled(enable); } ClientModel::MiningType MiningPage::getMiningType() { if (ui->typeBox->currentIndex() == 0) // Solo Mining { return ClientModel::SoloMining; } else if (ui->typeBox->currentIndex() == 1) // Pool Minig { return ClientModel::PoolMining; } return ClientModel::SoloMining; } void MiningPage::typeChanged(int index) { if (index == 0) // Solo Mining { enablePoolMiningControls(false); } else if (index == 1) // Pool Minig { enablePoolMiningControls(true); } } void MiningPage::debugToggled(bool checked) { model->setMiningDebug(checked); } void MiningPage::resetMiningButton() { ui->startButton->setText(minerActive ? "Stop Mining" : "Start Mining"); enableMiningControls(!minerActive); }
#include "miningpage.h" #include "ui_miningpage.h" MiningPage::MiningPage(QWidget *parent) : QWidget(parent), ui(new Ui::MiningPage) { ui->setupUi(this); setFixedSize(400, 420); minerActive = false; minerProcess = new QProcess(this); minerProcess->setProcessChannelMode(QProcess::MergedChannels); readTimer = new QTimer(this); acceptedShares = 0; rejectedShares = 0; roundAcceptedShares = 0; roundRejectedShares = 0; initThreads = 0; connect(readTimer, SIGNAL(timeout()), this, SLOT(readProcessOutput())); connect(ui->startButton, SIGNAL(pressed()), this, SLOT(startPressed())); connect(ui->typeBox, SIGNAL(currentIndexChanged(int)), this, SLOT(typeChanged(int))); connect(ui->debugCheckBox, SIGNAL(toggled(bool)), this, SLOT(debugToggled(bool))); connect(minerProcess, SIGNAL(started()), this, SLOT(minerStarted())); connect(minerProcess, SIGNAL(error(QProcess::ProcessError)), this, SLOT(minerError(QProcess::ProcessError))); connect(minerProcess, SIGNAL(finished(int,QProcess::ExitStatus)), this, SLOT(minerFinished())); connect(minerProcess, SIGNAL(readyRead()), this, SLOT(readProcessOutput())); } MiningPage::~MiningPage() { minerProcess->kill(); delete ui; } void MiningPage::setModel(ClientModel *model) { this->model = model; loadSettings(); bool pool = model->getMiningType() == ClientModel::PoolMining; ui->threadsBox->setValue(model->getMiningThreads()); ui->typeBox->setCurrentIndex(pool ? 1 : 0); if (model->getMiningStarted()) startPressed(); } void MiningPage::startPressed() { initThreads = ui->threadsBox->value(); if (minerActive == false) { saveSettings(); if (getMiningType() == ClientModel::SoloMining) minerStarted(); else startPoolMining(); } else { if (getMiningType() == ClientModel::SoloMining) minerFinished(); else stopPoolMining(); } } void MiningPage::startPoolMining() { QStringList args; QString url = ui->serverLine->text(); if (!url.contains("http://")) url.prepend("http://"); QString urlLine = QString("%1:%2").arg(url, ui->portLine->text()); QString userpassLine = QString("%1:%2").arg(ui->usernameLine->text(), ui->passwordLine->text()); args << "--algo" << "scrypt"; args << "--scantime" << ui->scantimeBox->text().toAscii(); args << "--url" << urlLine.toAscii(); args << "--userpass" << userpassLine.toAscii(); args << "--threads" << ui->threadsBox->text().toAscii(); args << "--retries" << "-1"; // Retry forever. args << "-P"; // This is need for this to work correctly on Windows. Extra protocol dump helps flush the buffer quicker. threadSpeed.clear(); acceptedShares = 0; rejectedShares = 0; roundAcceptedShares = 0; roundRejectedShares = 0; // If minerd is in current path, then use that. Otherwise, assume minerd is in the path somewhere. QString program = QDir::current().filePath("minerd"); if (!QFile::exists(program)) program = "minerd"; if (ui->debugCheckBox->isChecked()) ui->list->addItem(args.join(" ").prepend(" ").prepend(program)); ui->mineSpeedLabel->setText("Speed: N/A"); ui->shareCount->setText("Accepted: 0 - Rejected: 0"); minerProcess->start(program,args); minerProcess->waitForStarted(-1); readTimer->start(500); } void MiningPage::stopPoolMining() { ui->mineSpeedLabel->setText(""); minerProcess->kill(); readTimer->stop(); } void MiningPage::saveSettings() { model->setMiningDebug(ui->debugCheckBox->isChecked()); model->setMiningScanTime(ui->scantimeBox->value()); model->setMiningServer(ui->serverLine->text()); model->setMiningPort(ui->portLine->text()); model->setMiningUsername(ui->usernameLine->text()); model->setMiningPassword(ui->passwordLine->text()); } void MiningPage::loadSettings() { ui->debugCheckBox->setChecked(model->getMiningDebug()); ui->scantimeBox->setValue(model->getMiningScanTime()); ui->serverLine->setText(model->getMiningServer()); ui->portLine->setText(model->getMiningPort()); ui->usernameLine->setText(model->getMiningUsername()); ui->passwordLine->setText(model->getMiningPassword()); } void MiningPage::readProcessOutput() { QByteArray output; minerProcess->reset(); output = minerProcess->readAll(); QString outputString(output); if (!outputString.isEmpty()) { QStringList list = outputString.split("\n", QString::SkipEmptyParts); int i; for (i=0; i<list.size(); i++) { QString line = list.at(i); // Ignore protocol dump if (!line.startsWith("[") || line.contains("JSON protocol") || line.contains("HTTP hdr")) continue; if (ui->debugCheckBox->isChecked()) { ui->list->addItem(line.trimmed()); ui->list->scrollToBottom(); } if (line.contains("PROOF OF WORK RESULT: true")) reportToList("Share accepted", SHARE_SUCCESS, getTime(line)); else if (line.contains("PROOF OF WORK RESULT: false")) reportToList("Share rejected", SHARE_FAIL, getTime(line)); else if (line.contains("LONGPOLL detected new block")) reportToList("LONGPOLL detected a new block", LONGPOLL, getTime(line)); else if (line.contains("Supported options:")) reportToList("Miner didn't start properly. Try checking your settings.", ERROR, NULL); else if (line.contains("The requested URL returned error: 403")) reportToList("Couldn't connect. Please check your username and password.", ERROR, NULL); else if (line.contains("HTTP request failed")) reportToList("Couldn't connect. Please check pool server and port.", ERROR, NULL); else if (line.contains("JSON-RPC call failed")) reportToList("Couldn't communicate with server. Retrying in 30 seconds.", ERROR, NULL); else if (line.contains("thread ") && line.contains("khash/sec")) { QString threadIDstr = line.at(line.indexOf("thread ")+7); int threadID = threadIDstr.toInt(); int threadSpeedindx = line.indexOf(","); QString threadSpeedstr = line.mid(threadSpeedindx); threadSpeedstr.chop(10); threadSpeedstr.remove(", "); threadSpeedstr.remove(" "); threadSpeedstr.remove('\n'); double speed=0; speed = threadSpeedstr.toDouble(); threadSpeed[threadID] = speed; updateSpeed(); } } } } void MiningPage::minerError(QProcess::ProcessError error) { if (error == QProcess::FailedToStart) { reportToList("Miner failed to start. Make sure you have the minerd executable and libraries in the same directory as Litecoin-QT.", ERROR, NULL); } } void MiningPage::minerFinished() { if (getMiningType() == ClientModel::SoloMining) reportToList("Solo mining stopped.", ERROR, NULL); else reportToList("Miner exited.", ERROR, NULL); ui->list->addItem(""); minerActive = false; resetMiningButton(); model->setMining(getMiningType(), false, initThreads, 0); } void MiningPage::minerStarted() { if (!minerActive) if (getMiningType() == ClientModel::SoloMining) reportToList("Solo mining started.", ERROR, NULL); else reportToList("Miner started. It usually takes a minute until the program starts reporting information.", STARTED, NULL); minerActive = true; resetMiningButton(); model->setMining(getMiningType(), true, initThreads, 0); } void MiningPage::updateSpeed() { double totalSpeed=0; int totalThreads=0; QMapIterator<int, double> iter(threadSpeed); while(iter.hasNext()) { iter.next(); totalSpeed += iter.value(); totalThreads++; } // If all threads haven't reported the hash speed yet, make an assumption if (totalThreads != initThreads) { totalSpeed = (totalSpeed/totalThreads)*initThreads; } QString speedString = QString("%1").arg(totalSpeed); QString threadsString = QString("%1").arg(initThreads); QString acceptedString = QString("%1").arg(acceptedShares); QString rejectedString = QString("%1").arg(rejectedShares); QString roundAcceptedString = QString("%1").arg(roundAcceptedShares); QString roundRejectedString = QString("%1").arg(roundRejectedShares); if (totalThreads == initThreads) ui->mineSpeedLabel->setText(QString("Speed: %1 khash/sec - %2 thread(s)").arg(speedString, threadsString)); else ui->mineSpeedLabel->setText(QString("Speed: ~%1 khash/sec - %2 thread(s)").arg(speedString, threadsString)); ui->shareCount->setText(QString("Accepted: %1 (%3) - Rejected: %2 (%4)").arg(acceptedString, rejectedString, roundAcceptedString, roundRejectedString)); model->setMining(getMiningType(), true, initThreads, totalSpeed*1000); } void MiningPage::reportToList(QString msg, int type, QString time) { QString message; if (time == NULL) message = QString("[%1] - %2").arg(QTime::currentTime().toString(), msg); else message = QString("[%1] - %2").arg(time, msg); switch(type) { case SHARE_SUCCESS: acceptedShares++; roundAcceptedShares++; updateSpeed(); break; case SHARE_FAIL: rejectedShares++; roundRejectedShares++; updateSpeed(); break; case LONGPOLL: roundAcceptedShares = 0; roundRejectedShares = 0; break; default: break; } ui->list->addItem(message); ui->list->scrollToBottom(); } // Function for fetching the time QString MiningPage::getTime(QString time) { if (time.contains("[")) { time.resize(21); time.remove("["); time.remove("]"); time.remove(0,11); return time; } else return NULL; } void MiningPage::enableMiningControls(bool enable) { ui->typeBox->setEnabled(enable); ui->threadsBox->setEnabled(enable); ui->scantimeBox->setEnabled(enable); ui->serverLine->setEnabled(enable); ui->portLine->setEnabled(enable); ui->usernameLine->setEnabled(enable); ui->passwordLine->setEnabled(enable); } void MiningPage::enablePoolMiningControls(bool enable) { ui->scantimeBox->setEnabled(enable); ui->serverLine->setEnabled(enable); ui->portLine->setEnabled(enable); ui->usernameLine->setEnabled(enable); ui->passwordLine->setEnabled(enable); } ClientModel::MiningType MiningPage::getMiningType() { if (ui->typeBox->currentIndex() == 0) // Solo Mining { return ClientModel::SoloMining; } else if (ui->typeBox->currentIndex() == 1) // Pool Minig { return ClientModel::PoolMining; } return ClientModel::SoloMining; } void MiningPage::typeChanged(int index) { if (index == 0) // Solo Mining { enablePoolMiningControls(false); } else if (index == 1) // Pool Minig { enablePoolMiningControls(true); } } void MiningPage::debugToggled(bool checked) { model->setMiningDebug(checked); } void MiningPage::resetMiningButton() { ui->startButton->setText(minerActive ? "Stop Mining" : "Start Mining"); enableMiningControls(!minerActive); }
Fix minerd filepath to work on windows.
Fix minerd filepath to work on windows.
C++
mit
SmeltFool/Wonker,Peer3/homework,djtms/ltc,GeekBrony/ponycoin-old,Peer3/homework,SmeltFool/Wonker,coinkeeper/2015-06-22_18-42_litecoin,djtms/ltc,SmeltFool/Wonker,SmeltFool/Yippe-Hippe,AsteraCoin/AsteraCoin,coblee/litecoin-old,coblee/litecoin-old,tatafiore/mycoin,coblee/litecoin-old,SmeltFool/Yippe-Hippe,SmeltFool/Yippe-Hippe,Peer3/homework,coinkeeper/2015-06-22_18-42_litecoin,SmeltFool/Yippe-Hippe,coinkeeper/2015-06-22_18-42_litecoin,altcoinpro/addacoin,djtms/ltc,GeekBrony/ponycoin-old,tatafiore/mycoin,xXDavasXx/Davascoin,tatafiore/mycoin,xXDavasXx/Davascoin,xXDavasXx/Davascoin,SmeltFool/Yippe-Hippe,GeekBrony/ponycoin-old,GeekBrony/ponycoin-old,altcoinpro/addacoin,coblee/litecoin-old,AsteraCoin/AsteraCoin,SmeltFool/Wonker,djtms/ltc,AsteraCoin/AsteraCoin,Peer3/homework,AsteraCoin/AsteraCoin,SmeltFool/Wonker,tatafiore/mycoin,coblee/litecoin-old,altcoinpro/addacoin,Peer3/homework,altcoinpro/addacoin,xXDavasXx/Davascoin,tatafiore/mycoin,coinkeeper/2015-06-22_18-42_litecoin,djtms/ltc
0c1912527f743a97e7fbdf4eca9148edb538afd6
src/qt/styleSheet.cpp
src/qt/styleSheet.cpp
#include <qt/styleSheet.h> #include <QFile> #include <QWidget> #include <QApplication> #include <QStyleFactory> #include <QProxyStyle> #include <QListView> #include <QComboBox> #include <QMessageBox> #include <QPushButton> #include <QPainter> #include <QLineEdit> #include <QtGlobal> #include <QSettings> static const QString STYLE_FORMAT = ":/styles/%1/%2"; static const QString STYLE_CONFIG_FORMAT = ":/styles/%1/config"; static const QColor LINK_COLOR = "#2d9ad0"; class QtumStyle : public QProxyStyle { public: QtumStyle() { message_info_path = GetStringStyleValue("appstyle/message-info-icon", ":/styles/theme1/app-icons/message_info"); message_warning_path = GetStringStyleValue("appstyle/message-warning-icon", ":/styles/theme1/app-icons/message_warning"); message_critical_path = GetStringStyleValue("appstyle/message-critical-icon", ":/styles/theme1/app-icons/message_critical"); message_question_path = GetStringStyleValue("appstyle/message-question-icon", ":/styles/theme1/app-icons/message_question"); message_icon_weight = GetIntStyleValue("appstyle/message-icon-weight", 45); message_icon_height = GetIntStyleValue("appstyle/message-icon-height", 49); button_text_upper = GetIntStyleValue("appstyle/button_text_upper", true); } void polish(QWidget *widget) { if(widget && widget->inherits("QComboBox")) { QComboBox* comboBox = (QComboBox*)widget; if(comboBox->view() && comboBox->view()->inherits("QComboBoxListView")) { comboBox->setView(new QListView()); qApp->processEvents(); } if(comboBox->view() && comboBox->view()->parentWidget()) { QWidget* parent = comboBox->view()->parentWidget(); parent->setWindowFlags(Qt::Popup | Qt::FramelessWindowHint | Qt::NoDropShadowWindowHint); parent->setAttribute(Qt::WA_TranslucentBackground); } } if(widget && widget->inherits("QMessageBox")) { QMessageBox* messageBox = (QMessageBox*)widget; QPixmap iconPixmap; QMessageBox::Icon icon = messageBox->icon(); switch (icon) { case QMessageBox::Information: iconPixmap = QPixmap(message_info_path); break; case QMessageBox::Warning: iconPixmap = QPixmap(message_warning_path); break; case QMessageBox::Critical: iconPixmap = QPixmap(message_critical_path); break; case QMessageBox::Question: iconPixmap = QPixmap(message_question_path); break; default: QProxyStyle::polish(widget); return; } messageBox->setIconPixmap(iconPixmap.scaled(message_icon_weight, message_icon_height)); } if(widget && widget->inherits("QPushButton") && button_text_upper) { QPushButton* button = (QPushButton*)widget; button->setText(button->text().toUpper()); } if(widget && widget->inherits("QLineEdit")) { QLineEdit* lineEdit = (QLineEdit*)widget; if(lineEdit->isReadOnly()) { lineEdit->setFocusPolicy(Qt::ClickFocus); } } QProxyStyle::polish(widget); } private: QString message_info_path; QString message_warning_path; QString message_critical_path; QString message_question_path; int message_icon_weight; int message_icon_height; bool button_text_upper; }; StyleSheet &StyleSheet::instance() { static StyleSheet inst; return inst; } StyleSheet::StyleSheet() { QSettings settings; m_theme = settings.value("Theme", getDefaultTheme()).toString(); QStringList supportedThemes = getSupportedThemes(); if(!supportedThemes.contains(m_theme)) m_theme = getDefaultTheme(); m_config = new QSettings(STYLE_CONFIG_FORMAT.arg(m_theme), QSettings::IniFormat); } void StyleSheet::setStyleSheet(QWidget *widget, const QString &style_name) { setObjectStyleSheet<QWidget>(widget, style_name); } void StyleSheet::setStyleSheet(QApplication *app, const QString& style_name) { QStyle* mainStyle = QStyleFactory::create("fusion"); QtumStyle* qtumStyle = new QtumStyle; qtumStyle->setBaseStyle(mainStyle); app->setStyle(qtumStyle); QPalette mainPalette(app->palette()); mainPalette.setColor(QPalette::Link, GetStyleValue("appstyle/link-color", LINK_COLOR).toString()); app->setPalette(mainPalette); // Increase the font size slightly for Windows and MAC QFont font = app->font(); qreal fontSize = font.pointSizeF(); qreal multiplier = 1; #if defined(Q_OS_WIN) || defined(Q_OS_MAC) multiplier = 1.1; #endif font.setPointSizeF(fontSize * multiplier); app->setFont(font); setObjectStyleSheet<QApplication>(app, style_name); } QString StyleSheet::getStyleSheet(const QString &style_name) { QString style; QFile file(STYLE_FORMAT.arg(m_theme, style_name)); if(file.open(QIODevice::ReadOnly)) { style = file.readAll(); m_cacheStyles[style_name] = style; } return style; } template<typename T> void StyleSheet::setObjectStyleSheet(T *object, const QString &style_name) { QString style_value = m_cacheStyles.contains(style_name) ? m_cacheStyles[style_name] : getStyleSheet(style_name); object->setStyleSheet(style_value); } QString StyleSheet::getCurrentTheme() { return m_theme; } QStringList StyleSheet::getSupportedThemes() { return QStringList() << "theme2" << "theme3" << "theme1"; } QStringList StyleSheet::getSupportedThemesNames() { return QStringList() << "Dark blue theme" << "Light blue theme" << "Black theme"; } QString StyleSheet::getDefaultTheme() { return "theme2"; } bool StyleSheet::setTheme(const QString &theme) { if(getSupportedThemes().contains(theme)) { QSettings settings; settings.setValue("Theme", theme); return true; } return false; } QVariant StyleSheet::getStyleValue(const QString &key, const QVariant &defaultValue) { if(m_config) { return m_config->value(key, defaultValue); } return defaultValue; }
#include <qt/styleSheet.h> #include <QFile> #include <QWidget> #include <QApplication> #include <QStyleFactory> #include <QProxyStyle> #include <QListView> #include <QComboBox> #include <QMessageBox> #include <QPushButton> #include <QPainter> #include <QLineEdit> #include <QtGlobal> #include <QSettings> static const QString STYLE_FORMAT = ":/styles/%1/%2"; static const QString STYLE_CONFIG_FORMAT = ":/styles/%1/config"; static const QColor LINK_COLOR = "#2d9ad0"; class QtumStyle : public QProxyStyle { public: QtumStyle() { message_info_path = GetStringStyleValue("appstyle/message-info-icon", ":/styles/theme1/app-icons/message_info"); message_warning_path = GetStringStyleValue("appstyle/message-warning-icon", ":/styles/theme1/app-icons/message_warning"); message_critical_path = GetStringStyleValue("appstyle/message-critical-icon", ":/styles/theme1/app-icons/message_critical"); message_question_path = GetStringStyleValue("appstyle/message-question-icon", ":/styles/theme1/app-icons/message_question"); message_icon_weight = GetIntStyleValue("appstyle/message-icon-weight", 45); message_icon_height = GetIntStyleValue("appstyle/message-icon-height", 49); button_text_upper = GetIntStyleValue("appstyle/button_text_upper", true); } void polish(QWidget *widget) { if(widget && widget->inherits("QComboBox")) { QComboBox* comboBox = (QComboBox*)widget; if(comboBox->view() && comboBox->view()->inherits("QComboBoxListView")) { comboBox->setView(new QListView()); qApp->processEvents(); } if(comboBox->view() && comboBox->view()->parentWidget()) { QWidget* parent = comboBox->view()->parentWidget(); parent->setWindowFlags(Qt::Popup | Qt::FramelessWindowHint | Qt::NoDropShadowWindowHint); parent->setAttribute(Qt::WA_TranslucentBackground); } } if(widget && widget->inherits("QMessageBox")) { QMessageBox* messageBox = (QMessageBox*)widget; QPixmap iconPixmap; QMessageBox::Icon icon = messageBox->icon(); switch (icon) { case QMessageBox::Information: iconPixmap = QPixmap(message_info_path); break; case QMessageBox::Warning: iconPixmap = QPixmap(message_warning_path); break; case QMessageBox::Critical: iconPixmap = QPixmap(message_critical_path); break; case QMessageBox::Question: iconPixmap = QPixmap(message_question_path); break; default: QProxyStyle::polish(widget); return; } messageBox->setIconPixmap(iconPixmap.scaled(message_icon_weight, message_icon_height)); } if(widget && widget->inherits("QPushButton") && button_text_upper) { QPushButton* button = (QPushButton*)widget; button->setText(button->text().toUpper()); } if(widget && widget->inherits("QLineEdit")) { QLineEdit* lineEdit = (QLineEdit*)widget; if(lineEdit->isReadOnly()) { lineEdit->setFocusPolicy(Qt::ClickFocus); } } QProxyStyle::polish(widget); } private: QString message_info_path; QString message_warning_path; QString message_critical_path; QString message_question_path; int message_icon_weight; int message_icon_height; bool button_text_upper; }; StyleSheet &StyleSheet::instance() { static StyleSheet inst; return inst; } StyleSheet::StyleSheet() { QSettings settings; m_theme = settings.value("Theme", getDefaultTheme()).toString(); QStringList supportedThemes = getSupportedThemes(); if(!supportedThemes.contains(m_theme)) m_theme = getDefaultTheme(); m_config = new QSettings(STYLE_CONFIG_FORMAT.arg(m_theme), QSettings::IniFormat); } void StyleSheet::setStyleSheet(QWidget *widget, const QString &style_name) { setObjectStyleSheet<QWidget>(widget, style_name); } void StyleSheet::setStyleSheet(QApplication *app, const QString& style_name) { QStyle* mainStyle = QStyleFactory::create("fusion"); QtumStyle* qtumStyle = new QtumStyle; qtumStyle->setBaseStyle(mainStyle); app->setStyle(qtumStyle); QPalette mainPalette(app->palette()); mainPalette.setColor(QPalette::Link, GetStyleValue("appstyle/link-color", LINK_COLOR).toString()); app->setPalette(mainPalette); // Increase the font size slightly for Windows and MAC QFont font = app->font(); qreal fontSize = font.pointSizeF(); qreal multiplier = 1; #if defined(Q_OS_WIN) || defined(Q_OS_MAC) multiplier = 1.1; #endif font.setPointSizeF(fontSize * multiplier); app->setFont(font); setObjectStyleSheet<QApplication>(app, style_name); } QString StyleSheet::getStyleSheet(const QString &style_name) { QString style; QFile file(STYLE_FORMAT.arg(m_theme, style_name)); if(file.open(QIODevice::ReadOnly)) { style = file.readAll(); m_cacheStyles[style_name] = style; } return style; } template<typename T> void StyleSheet::setObjectStyleSheet(T *object, const QString &style_name) { QString style_value = m_cacheStyles.contains(style_name) ? m_cacheStyles[style_name] : getStyleSheet(style_name); object->setStyleSheet(style_value); } QString StyleSheet::getCurrentTheme() { return m_theme; } QStringList StyleSheet::getSupportedThemes() { return QStringList() << "theme3" << "theme2" << "theme1"; } QStringList StyleSheet::getSupportedThemesNames() { return QStringList() << "Light blue theme" << "Dark blue theme" << "Dark theme"; } QString StyleSheet::getDefaultTheme() { return "theme3"; } bool StyleSheet::setTheme(const QString &theme) { if(getSupportedThemes().contains(theme)) { QSettings settings; settings.setValue("Theme", theme); return true; } return false; } QVariant StyleSheet::getStyleValue(const QString &key, const QVariant &defaultValue) { if(m_config) { return m_config->value(key, defaultValue); } return defaultValue; }
Change the default theme to light blue
Change the default theme to light blue
C++
mit
qtumproject/qtum,qtumproject/qtum,qtumproject/qtum,qtumproject/qtum,qtumproject/qtum,qtumproject/qtum,qtumproject/qtum
d4cc20d13bb839f4305c70e1db971a8f5a6f1f68
src/rl/mdl/Spherical.cpp
src/rl/mdl/Spherical.cpp
// // Copyright (c) 2009, Markus Rickert // 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. // // 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 HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // #include <rl/math/Rotation.h> #include "Spherical.h" namespace rl { namespace mdl { Spherical::Spherical() : Joint(4, 3) { this->qUnits(0) = ::rl::math::UNIT_NONE; // TODO this->qUnits(1) = ::rl::math::UNIT_NONE; // TODO this->qUnits(2) = ::rl::math::UNIT_NONE; // TODO this->qUnits(3) = ::rl::math::UNIT_NONE; // TODO this->qdUnits(0) = ::rl::math::UNIT_RADIAN_PER_SECOND; this->qdUnits(1) = ::rl::math::UNIT_RADIAN_PER_SECOND; this->qdUnits(2) = ::rl::math::UNIT_RADIAN_PER_SECOND; this->qddUnits(0) = ::rl::math::UNIT_RADIAN_PER_SECOND_SQUARED; this->qddUnits(1) = ::rl::math::UNIT_RADIAN_PER_SECOND_SQUARED; this->qddUnits(2) = ::rl::math::UNIT_RADIAN_PER_SECOND_SQUARED; this->S(0, 0) = 1; this->S(1, 1) = 1; this->S(2, 2) = 1; this->speedUnits(0) = ::rl::math::UNIT_RADIAN_PER_SECOND; this->speedUnits(1) = ::rl::math::UNIT_RADIAN_PER_SECOND; this->speedUnits(2) = ::rl::math::UNIT_RADIAN_PER_SECOND; this->tauUnits(0) = ::rl::math::UNIT_NEWTON_METER; this->tauUnits(1) = ::rl::math::UNIT_NEWTON_METER; this->tauUnits(2) = ::rl::math::UNIT_NEWTON_METER; } Spherical::~Spherical() { } void Spherical::clip(::rl::math::Vector& q) const { ::Eigen::Map< ::rl::math::Quaternion>(q.data()).normalize(); } ::rl::math::Real Spherical::distance(const ::rl::math::Vector& q1, const ::rl::math::Vector& q2) const { ::Eigen::Map<const ::rl::math::Quaternion> quaternion1(q1.data()); ::Eigen::Map<const ::rl::math::Quaternion> quaternion2(q2.data()); return quaternion1.angularDistance(quaternion2); } ::rl::math::Vector Spherical::generatePositionGaussian(const ::rl::math::ConstVectorRef& rand, const ::rl::math::ConstVectorRef& mean, const ::rl::math::ConstVectorRef& sigma) const { ::rl::math::Quaternion quaternion; quaternion.setFromGaussian(rand, ::Eigen::Map< const ::rl::math::Quaternion>(mean.data()), sigma); return quaternion.coeffs(); } ::rl::math::Vector Spherical::generatePositionUniform(const ::rl::math::ConstVectorRef& rand) const { ::rl::math::Quaternion quaternion; quaternion.setFromUniform(rand); return quaternion.coeffs(); } void Spherical::interpolate(const ::rl::math::Vector& q1, const ::rl::math::Vector& q2, const ::rl::math::Real& alpha, ::rl::math::Vector& q) const { ::Eigen::Map<const ::rl::math::Quaternion> quaternion1(q1.data()); ::Eigen::Map<const ::rl::math::Quaternion> quaternion2(q2.data()); q = quaternion1.slerp(alpha, quaternion2).coeffs(); } void Spherical::normalize(::rl::math::Vector& q) const { ::Eigen::Map< ::rl::math::Quaternion>(q.data()).normalize(); } void Spherical::setPosition(const ::rl::math::Vector& q) { this->q = q; this->t = ::Eigen::Map<const ::rl::math::Quaternion>(this->q.data()); this->x.rotation() = this->t.linear().transpose(); } void Spherical::step(const ::rl::math::Vector& q1, const ::rl::math::Vector& qdot, ::rl::math::Vector& q2) const { ::Eigen::Map<const ::rl::math::Quaternion> quaternion1(q1.data()); ::rl::math::Quaternion quaterniondot = quaternion1.firstDerivative(qdot); q2 = (quaternion1 * quaterniondot).coeffs(); } ::rl::math::Real Spherical::transformedDistance(const ::rl::math::Vector& q1, const ::rl::math::Vector& q2) const { return ::std::pow(this->distance(q1, q2), 2); } } }
// // Copyright (c) 2009, Markus Rickert // 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. // // 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 HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // #include <rl/math/Rotation.h> #include "Spherical.h" namespace rl { namespace mdl { Spherical::Spherical() : Joint(4, 3) { this->qUnits(0) = ::rl::math::UNIT_NONE; // TODO this->qUnits(1) = ::rl::math::UNIT_NONE; // TODO this->qUnits(2) = ::rl::math::UNIT_NONE; // TODO this->qUnits(3) = ::rl::math::UNIT_NONE; // TODO this->qdUnits(0) = ::rl::math::UNIT_RADIAN_PER_SECOND; this->qdUnits(1) = ::rl::math::UNIT_RADIAN_PER_SECOND; this->qdUnits(2) = ::rl::math::UNIT_RADIAN_PER_SECOND; this->qddUnits(0) = ::rl::math::UNIT_RADIAN_PER_SECOND_SQUARED; this->qddUnits(1) = ::rl::math::UNIT_RADIAN_PER_SECOND_SQUARED; this->qddUnits(2) = ::rl::math::UNIT_RADIAN_PER_SECOND_SQUARED; this->S(0, 0) = 1; this->S(1, 1) = 1; this->S(2, 2) = 1; this->speedUnits(0) = ::rl::math::UNIT_RADIAN_PER_SECOND; this->speedUnits(1) = ::rl::math::UNIT_RADIAN_PER_SECOND; this->speedUnits(2) = ::rl::math::UNIT_RADIAN_PER_SECOND; this->tauUnits(0) = ::rl::math::UNIT_NEWTON_METER; this->tauUnits(1) = ::rl::math::UNIT_NEWTON_METER; this->tauUnits(2) = ::rl::math::UNIT_NEWTON_METER; } Spherical::~Spherical() { } void Spherical::clip(::rl::math::Vector& q) const { ::Eigen::Map< ::rl::math::Quaternion>(q.data()).normalize(); } ::rl::math::Real Spherical::distance(const ::rl::math::Vector& q1, const ::rl::math::Vector& q2) const { ::Eigen::Map<const ::rl::math::Quaternion> quaternion1(q1.data()); ::Eigen::Map<const ::rl::math::Quaternion> quaternion2(q2.data()); return quaternion1.angularDistance(quaternion2); } ::rl::math::Vector Spherical::generatePositionGaussian(const ::rl::math::ConstVectorRef& rand, const ::rl::math::ConstVectorRef& mean, const ::rl::math::ConstVectorRef& sigma) const { ::rl::math::Quaternion quaternion; quaternion.setFromGaussian(rand, ::Eigen::Map< const ::rl::math::Quaternion>(mean.data()), sigma); return quaternion.coeffs(); } ::rl::math::Vector Spherical::generatePositionUniform(const ::rl::math::ConstVectorRef& rand) const { ::rl::math::Quaternion quaternion; quaternion.setFromUniform(rand); return quaternion.coeffs(); } void Spherical::interpolate(const ::rl::math::Vector& q1, const ::rl::math::Vector& q2, const ::rl::math::Real& alpha, ::rl::math::Vector& q) const { ::Eigen::Map<const ::rl::math::Quaternion> quaternion1(q1.data()); ::Eigen::Map<const ::rl::math::Quaternion> quaternion2(q2.data()); q = quaternion1.slerp(alpha, quaternion2).coeffs(); } void Spherical::normalize(::rl::math::Vector& q) const { ::Eigen::Map< ::rl::math::Quaternion> quaternion(q.data()); if (quaternion.squaredNorm() > 0) { quaternion.normalize(); } else { quaternion.setIdentity(); } } void Spherical::setPosition(const ::rl::math::Vector& q) { this->q = q; this->t = ::Eigen::Map<const ::rl::math::Quaternion>(this->q.data()); this->x.rotation() = this->t.linear().transpose(); } void Spherical::step(const ::rl::math::Vector& q1, const ::rl::math::Vector& qdot, ::rl::math::Vector& q2) const { ::Eigen::Map<const ::rl::math::Quaternion> quaternion1(q1.data()); ::rl::math::Quaternion quaterniondot = quaternion1.firstDerivative(qdot); q2 = (quaternion1 * quaterniondot).coeffs(); } ::rl::math::Real Spherical::transformedDistance(const ::rl::math::Vector& q1, const ::rl::math::Vector& q2) const { return ::std::pow(this->distance(q1, q2), 2); } } }
Check for zero quaternion in Joint::normalize()
Check for zero quaternion in Joint::normalize()
C++
bsd-2-clause
roboticslibrary/rl
b99701b002b6825a032a0adf684ee5b0e85c5e3f
src/runner/at-handler.hh
src/runner/at-handler.hh
/* * Copyright (C) 2009, Gostai S.A.S. * * This software is provided "as is" without warranty of any kind, * either expressed or implied, including but not limited to the * implied warranties of fitness for a particular purpose. * * See the LICENSE file for more information. */ #ifndef RUNNER_AT_HANDLER_HH #define RUNNER_AT_HANDLER_HH # include <urbi/object/fwd.hh> # include <runner/interpreter.hh> namespace runner { typedef object::rObject rObject; /// Register a new "at" job. /// /// \param starter The interpreter this job is started from. /// /// \param condition A lambda representing the expression to check. /// /// \param clause A lambda representing the code to run when the \a condition /// becomes true, or nil. This lambda must start a detached task. /// /// \param con_leave A lambda representing the code to run when \a condition /// becomes false, or nil. This lambda must start a detach task. void register_at_job(const runner::Interpreter& starter, const rObject& condition, const rObject& clause, const rObject& on_leave); } // namespace runner #endif // RUNNER_AT_HANDLER_HH
/* * Copyright (C) 2009, Gostai S.A.S. * * This software is provided "as is" without warranty of any kind, * either expressed or implied, including but not limited to the * implied warranties of fitness for a particular purpose. * * See the LICENSE file for more information. */ #ifndef RUNNER_AT_HANDLER_HH #define RUNNER_AT_HANDLER_HH # include <urbi/object/fwd.hh> # include <runner/interpreter.hh> namespace runner { typedef object::rObject rObject; /// Register a new "at" job. /// /// \param starter The interpreter this job is started from. /// /// \param condition A lambda representing the expression to check. /// /// \param clause A lambda representing the code to run when the \a condition /// becomes true, or nil. This lambda must start a detached task. /// /// \param on_leave A lambda representing the code to run when \a condition /// becomes false, or nil. This lambda must start a detach task. void register_at_job(const runner::Interpreter& starter, const rObject& condition, const rObject& clause, const rObject& on_leave); } // namespace runner #endif // RUNNER_AT_HANDLER_HH
Comment changes.
Comment changes.
C++
bsd-3-clause
aldebaran/urbi,aldebaran/urbi,urbiforge/urbi,aldebaran/urbi,urbiforge/urbi,aldebaran/urbi,urbiforge/urbi,urbiforge/urbi,urbiforge/urbi,aldebaran/urbi,urbiforge/urbi,urbiforge/urbi,urbiforge/urbi,aldebaran/urbi,urbiforge/urbi,aldebaran/urbi,aldebaran/urbi
ec8cfa52cbf0d1f0b3799ef0bb1a6feac4b677b7
src/mesh.cpp
src/mesh.cpp
#include "./mesh.h" #include <QDebug> #include <string> #include "./gl.h" Mesh::Mesh(Gl *gl, aiMesh *mesh, aiMaterial *material) : gl(gl), shaderProgram(gl, ":shader/phong.vert", ":shader/phong.frag") { for (unsigned int i = 0; i < material->mNumProperties; ++i) { auto property = material->mProperties[i]; std::cout << property->mKey.C_Str() << ": " << property->mType << "|" << property->mDataLength << std::endl; } ambientColor = loadVector4FromMaterial("$clr.ambient", material); diffuseColor = loadVector4FromMaterial("$clr.diffuse", material); specularColor = loadVector4FromMaterial("$clr.specular", material); shininess = loadFloatFromMaterial("$mat.shininess", material); std::cout << "diffuse: " << diffuseColor << " ambient: " << ambientColor << " specular: " << specularColor << " shininess: " << shininess << std::endl; unsigned int indicesPerFace = mesh->mFaces[0].mNumIndices; indexCount = indicesPerFace * mesh->mNumFaces; unsigned int *indexData = new unsigned int[indexCount]; auto indexInsertPoint = indexData; for (unsigned int i = 0; i < mesh->mNumFaces; i++) { const aiFace &face = mesh->mFaces[i]; assert(face.mNumIndices == indicesPerFace); memcpy(indexInsertPoint, face.mIndices, sizeof(unsigned int) * face.mNumIndices); indexInsertPoint += face.mNumIndices; } vertexCount = mesh->mNumVertices; auto positionData = new float[mesh->mNumVertices * 3]; memcpy(positionData, mesh->mVertices, sizeof(float) * 3 * mesh->mNumVertices); auto normalData = new float[mesh->mNumVertices * 3]; memcpy(normalData, mesh->mNormals, sizeof(float) * 3 * mesh->mNumVertices); vertexArrayObject.create(); vertexArrayObject.bind(); shaderProgram.bind(); createBuffer(QOpenGLBuffer::Type::IndexBuffer, indexData, "index", 1, indexCount); createBuffer(QOpenGLBuffer::Type::VertexBuffer, positionData, "vertexPosition", 3, vertexCount); createBuffer(QOpenGLBuffer::Type::VertexBuffer, normalData, "vertexNormal", 3, vertexCount); vertexArrayObject.release(); for (auto &buffer : buffers) buffer.release(); shaderProgram.release(); } Mesh::~Mesh() { } Eigen::Vector4f Mesh::loadVector4FromMaterial(const char *key, aiMaterial *material) { float values[4]; unsigned int size = 4; if (material->Get(key, 0, 0, values, &size) != 0) { qCritical() << "Could not load " << key << " from material"; exit(1); } return Eigen::Vector4f(values[0], values[1], values[2], values[3]); } float Mesh::loadFloatFromMaterial(const char *key, aiMaterial *material) { float result; if (material->Get(key, 0, 0, result) != 0) { qCritical() << "Could not load " << key << " from material"; exit(1); } return result; } template <class ElementType> void Mesh::createBuffer(QOpenGLBuffer::Type bufferType, ElementType *data, std::string usage, int perVertexElements, int numberOfVertices) { QOpenGLBuffer buffer(bufferType); buffer.create(); buffer.setUsagePattern(QOpenGLBuffer::StaticDraw); buffer.bind(); buffer.allocate(data, numberOfVertices * perVertexElements * sizeof(ElementType)); glCheckError(); if (bufferType != QOpenGLBuffer::Type::IndexBuffer) shaderProgram.enableAndSetAttributes(usage, perVertexElements); buffers.push_back(buffer); } void Mesh::render(Eigen::Matrix4f projection, Eigen::Matrix4f view) { shaderProgram.bind(); Eigen::Matrix4f modelViewProjection = projection * view; shaderProgram.setUniform("viewProjectionMatrix", modelViewProjection); shaderProgram.setUniform("ambientColor", ambientColor); shaderProgram.setUniform("diffuseColor", diffuseColor); shaderProgram.setUniform("specularColor", specularColor); shaderProgram.setUniform("cameraDirection", Eigen::Vector3f(view(2, 0), view(2, 1), view(2, 2))); shaderProgram.setUniform("shininess", shininess); vertexArrayObject.bind(); glAssert(gl->glDrawElements(GL_TRIANGLES, indexCount, GL_UNSIGNED_INT, 0)); vertexArrayObject.release(); shaderProgram.release(); }
#include "./mesh.h" #include <QDebug> #include <string> #include "./gl.h" Mesh::Mesh(Gl *gl, aiMesh *mesh, aiMaterial *material) : gl(gl), shaderProgram(gl, ":shader/phong.vert", ":shader/phong.frag") { /* for (unsigned int i = 0; i < material->mNumProperties; ++i) { auto property = material->mProperties[i]; std::cout << property->mKey.C_Str() << ": " << property->mType << "|" << property->mDataLength << std::endl; } */ ambientColor = loadVector4FromMaterial("$clr.ambient", material); diffuseColor = loadVector4FromMaterial("$clr.diffuse", material); specularColor = loadVector4FromMaterial("$clr.specular", material); shininess = loadFloatFromMaterial("$mat.shininess", material); /* std::cout << "diffuse: " << diffuseColor << " ambient: " << ambientColor << " specular: " << specularColor << " shininess: " << shininess << std::endl; */ unsigned int indicesPerFace = mesh->mFaces[0].mNumIndices; indexCount = indicesPerFace * mesh->mNumFaces; unsigned int *indexData = new unsigned int[indexCount]; auto indexInsertPoint = indexData; for (unsigned int i = 0; i < mesh->mNumFaces; i++) { const aiFace &face = mesh->mFaces[i]; assert(face.mNumIndices == indicesPerFace); memcpy(indexInsertPoint, face.mIndices, sizeof(unsigned int) * face.mNumIndices); indexInsertPoint += face.mNumIndices; } vertexCount = mesh->mNumVertices; auto positionData = new float[mesh->mNumVertices * 3]; memcpy(positionData, mesh->mVertices, sizeof(float) * 3 * mesh->mNumVertices); auto normalData = new float[mesh->mNumVertices * 3]; memcpy(normalData, mesh->mNormals, sizeof(float) * 3 * mesh->mNumVertices); vertexArrayObject.create(); vertexArrayObject.bind(); shaderProgram.bind(); createBuffer(QOpenGLBuffer::Type::IndexBuffer, indexData, "index", 1, indexCount); createBuffer(QOpenGLBuffer::Type::VertexBuffer, positionData, "vertexPosition", 3, vertexCount); createBuffer(QOpenGLBuffer::Type::VertexBuffer, normalData, "vertexNormal", 3, vertexCount); vertexArrayObject.release(); for (auto &buffer : buffers) buffer.release(); shaderProgram.release(); } Mesh::~Mesh() { } Eigen::Vector4f Mesh::loadVector4FromMaterial(const char *key, aiMaterial *material) { float values[4]; unsigned int size = 4; if (material->Get(key, 0, 0, values, &size) != 0) { qCritical() << "Could not load " << key << " from material"; exit(1); } return Eigen::Vector4f(values[0], values[1], values[2], values[3]); } float Mesh::loadFloatFromMaterial(const char *key, aiMaterial *material) { float result; if (material->Get(key, 0, 0, result) != 0) { qCritical() << "Could not load " << key << " from material"; exit(1); } return result; } template <class ElementType> void Mesh::createBuffer(QOpenGLBuffer::Type bufferType, ElementType *data, std::string usage, int perVertexElements, int numberOfVertices) { QOpenGLBuffer buffer(bufferType); buffer.create(); buffer.setUsagePattern(QOpenGLBuffer::StaticDraw); buffer.bind(); buffer.allocate(data, numberOfVertices * perVertexElements * sizeof(ElementType)); glCheckError(); if (bufferType != QOpenGLBuffer::Type::IndexBuffer) shaderProgram.enableAndSetAttributes(usage, perVertexElements); buffers.push_back(buffer); } void Mesh::render(Eigen::Matrix4f projection, Eigen::Matrix4f view) { shaderProgram.bind(); Eigen::Matrix4f modelViewProjection = projection * view; shaderProgram.setUniform("viewProjectionMatrix", modelViewProjection); shaderProgram.setUniform("ambientColor", ambientColor); shaderProgram.setUniform("diffuseColor", diffuseColor); shaderProgram.setUniform("specularColor", specularColor); shaderProgram.setUniform("cameraDirection", Eigen::Vector3f(view(2, 0), view(2, 1), view(2, 2))); shaderProgram.setUniform("shininess", shininess); vertexArrayObject.bind(); glAssert(gl->glDrawElements(GL_TRIANGLES, indexCount, GL_UNSIGNED_INT, 0)); vertexArrayObject.release(); shaderProgram.release(); }
Disable debug output for materials.
Disable debug output for materials.
C++
mit
Christof/voly-labeller,Christof/voly-labeller,Christof/voly-labeller,Christof/voly-labeller
cfce09877082664f856a9fef267be06b45077b99
src/script/script.cpp
src/script/script.cpp
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2016 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. // // File contains modifications by: The Gulden developers // All modifications: // Copyright (c) 2017-2018 The Gulden developers // Authored by: Malcolm MacLeod ([email protected]) // Distributed under the GULDEN software license, see the accompanying // file COPYING #include "script.h" #include "tinyformat.h" #include "utilstrencodings.h" //Gulden #include <primitives/transaction.h> const char* GetOpName(opcodetype opcode) { switch (opcode) { // push value case OP_0 : return "0"; case OP_PUSHDATA1 : return "OP_PUSHDATA1"; case OP_PUSHDATA2 : return "OP_PUSHDATA2"; case OP_PUSHDATA4 : return "OP_PUSHDATA4"; case OP_1NEGATE : return "-1"; case OP_RESERVED : return "OP_RESERVED"; case OP_1 : return "1"; case OP_2 : return "2"; case OP_3 : return "3"; case OP_4 : return "4"; case OP_5 : return "5"; case OP_6 : return "6"; case OP_7 : return "7"; case OP_8 : return "8"; case OP_9 : return "9"; case OP_10 : return "10"; case OP_11 : return "11"; case OP_12 : return "12"; case OP_13 : return "13"; case OP_14 : return "14"; case OP_15 : return "15"; case OP_16 : return "16"; // control case OP_NOP : return "OP_NOP"; case OP_VER : return "OP_VER"; case OP_IF : return "OP_IF"; case OP_NOTIF : return "OP_NOTIF"; case OP_VERIF : return "OP_VERIF"; case OP_VERNOTIF : return "OP_VERNOTIF"; case OP_ELSE : return "OP_ELSE"; case OP_ENDIF : return "OP_ENDIF"; case OP_VERIFY : return "OP_VERIFY"; case OP_RETURN : return "OP_RETURN"; // stack ops case OP_TOALTSTACK : return "OP_TOALTSTACK"; case OP_FROMALTSTACK : return "OP_FROMALTSTACK"; case OP_2DROP : return "OP_2DROP"; case OP_2DUP : return "OP_2DUP"; case OP_3DUP : return "OP_3DUP"; case OP_2OVER : return "OP_2OVER"; case OP_2ROT : return "OP_2ROT"; case OP_2SWAP : return "OP_2SWAP"; case OP_IFDUP : return "OP_IFDUP"; case OP_DEPTH : return "OP_DEPTH"; case OP_DROP : return "OP_DROP"; case OP_DUP : return "OP_DUP"; case OP_NIP : return "OP_NIP"; case OP_OVER : return "OP_OVER"; case OP_PICK : return "OP_PICK"; case OP_ROLL : return "OP_ROLL"; case OP_ROT : return "OP_ROT"; case OP_SWAP : return "OP_SWAP"; case OP_TUCK : return "OP_TUCK"; // splice ops case OP_CAT : return "OP_CAT"; case OP_SUBSTR : return "OP_SUBSTR"; case OP_LEFT : return "OP_LEFT"; case OP_RIGHT : return "OP_RIGHT"; case OP_SIZE : return "OP_SIZE"; // bit logic case OP_INVERT : return "OP_INVERT"; case OP_AND : return "OP_AND"; case OP_OR : return "OP_OR"; case OP_XOR : return "OP_XOR"; case OP_EQUAL : return "OP_EQUAL"; case OP_EQUALVERIFY : return "OP_EQUALVERIFY"; case OP_RESERVED1 : return "OP_RESERVED1"; case OP_RESERVED2 : return "OP_RESERVED2"; // numeric case OP_1ADD : return "OP_1ADD"; case OP_1SUB : return "OP_1SUB"; case OP_2MUL : return "OP_2MUL"; case OP_2DIV : return "OP_2DIV"; case OP_NEGATE : return "OP_NEGATE"; case OP_ABS : return "OP_ABS"; case OP_NOT : return "OP_NOT"; case OP_0NOTEQUAL : return "OP_0NOTEQUAL"; case OP_ADD : return "OP_ADD"; case OP_SUB : return "OP_SUB"; case OP_MUL : return "OP_MUL"; case OP_DIV : return "OP_DIV"; case OP_MOD : return "OP_MOD"; case OP_LSHIFT : return "OP_LSHIFT"; case OP_RSHIFT : return "OP_RSHIFT"; case OP_BOOLAND : return "OP_BOOLAND"; case OP_BOOLOR : return "OP_BOOLOR"; case OP_NUMEQUAL : return "OP_NUMEQUAL"; case OP_NUMEQUALVERIFY : return "OP_NUMEQUALVERIFY"; case OP_NUMNOTEQUAL : return "OP_NUMNOTEQUAL"; case OP_LESSTHAN : return "OP_LESSTHAN"; case OP_GREATERTHAN : return "OP_GREATERTHAN"; case OP_LESSTHANOREQUAL : return "OP_LESSTHANOREQUAL"; case OP_GREATERTHANOREQUAL : return "OP_GREATERTHANOREQUAL"; case OP_MIN : return "OP_MIN"; case OP_MAX : return "OP_MAX"; case OP_WITHIN : return "OP_WITHIN"; // crypto case OP_RIPEMD160 : return "OP_RIPEMD160"; case OP_SHA1 : return "OP_SHA1"; case OP_SHA256 : return "OP_SHA256"; case OP_HASH160 : return "OP_HASH160"; case OP_HASH256 : return "OP_HASH256"; case OP_CODESEPARATOR : return "OP_CODESEPARATOR"; case OP_CHECKSIG : return "OP_CHECKSIG"; case OP_CHECKSIGVERIFY : return "OP_CHECKSIGVERIFY"; case OP_CHECKMULTISIG : return "OP_CHECKMULTISIG"; case OP_CHECKMULTISIGVERIFY : return "OP_CHECKMULTISIGVERIFY"; // expansion case OP_NOP1 : return "OP_NOP1"; case OP_CHECKLOCKTIMEVERIFY : return "OP_CHECKLOCKTIMEVERIFY"; case OP_CHECKSEQUENCEVERIFY : return "OP_CHECKSEQUENCEVERIFY"; case OP_NOP4 : return "OP_NOP4"; case OP_NOP5 : return "OP_NOP5"; case OP_NOP6 : return "OP_NOP6"; case OP_NOP7 : return "OP_NOP7"; case OP_NOP8 : return "OP_NOP8"; case OP_NOP9 : return "OP_NOP9"; case OP_NOP10 : return "OP_NOP10"; case OP_INVALIDOPCODE : return "OP_INVALIDOPCODE"; // Note: // The template matching params OP_SMALLINTEGER/etc are defined in opcodetype enum // as kind of implementation hack, they are *NOT* real opcodes. If found in real // Script, just let the default: case deal with them. case OP_SMALLINTEGER: case OP_PUBKEYS: case OP_PUBKEYHASH: default: return "OP_UNKNOWN"; } } unsigned int CScript::GetSigOpCount(bool fAccurate) const { unsigned int n = 0; const_iterator pc = begin(); opcodetype lastOpcode = OP_INVALIDOPCODE; while (pc < end()) { opcodetype opcode; if (!GetOp(pc, opcode)) break; if (opcode == OP_CHECKSIG || opcode == OP_CHECKSIGVERIFY) n++; else if (opcode == OP_CHECKMULTISIG || opcode == OP_CHECKMULTISIGVERIFY) { if (fAccurate && lastOpcode >= OP_1 && lastOpcode <= OP_16) n += DecodeOP_N(lastOpcode); else n += MAX_PUBKEYS_PER_MULTISIG; } lastOpcode = opcode; } return n; } unsigned int CScript::GetSigOpCount(const CScript& scriptSig) const { if (!IsPayToScriptHash()) return GetSigOpCount(true); // This is a pay-to-script-hash scriptPubKey; // get the last item that the scriptSig // pushes onto the stack: const_iterator pc = scriptSig.begin(); std::vector<unsigned char> vData; while (pc < scriptSig.end()) { opcodetype opcode; if (!scriptSig.GetOp(pc, opcode, vData)) return 0; if (opcode > OP_16) return 0; } /// ... and return its opcount: CScript subscript(vData.begin(), vData.end()); return subscript.GetSigOpCount(true); } bool CScript::IsPayToPubkeyHash(CKeyID &hash) const { if (this->size() == 25 && (*this)[0] == OP_DUP && (*this)[1] == OP_HASH160 && (*this)[2] == 20 && (*this)[23] == OP_EQUALVERIFY && (*this)[24] == OP_CHECKSIG) { memcpy(hash.begin(), &(*this)[3], 20); return true; } return false; } bool CScript::IsPayToScriptHash() const { // Extra-fast test for pay-to-script-hash CScripts: return (this->size() == 23 && (*this)[0] == OP_HASH160 && (*this)[1] == 0x14 && (*this)[22] == OP_EQUAL); } //OP_0 [1 byte] 72 [1 byte] hash [20 byte] hash [20 byte] uint64_t [8 byte] uint64_t [8 byte] uint64_t [8 byte] uint64_t [8 byte] (74 bytes) bool CScript::IsPoW2Witness() const { if (this->size() != 74) return false; if ((*this)[0] != OP_0 || (*this)[1] != 72) return false; return true; } //OP_0 [1 byte] 72 [1 byte] hash [20 byte] hash [20 byte] uint64_t [8 byte] uint64_t [8 byte] uint64_t [8 byte] uint64_t [8 byte] (74 bytes) std::vector<unsigned char> CScript::GetPow2WitnessHash() const { assert(IsPoW2Witness()); std::vector<unsigned char> hashWitnessBytes(this->begin()+22, this->begin()+42); return hashWitnessBytes; } //OP_0 [1 byte] 72 [1 byte] hash [20 byte] hash [20 byte] uint64_t [8 byte] uint64_t [8 byte] uint64_t [8 byte] uint64_t [8 byte] (74 bytes) bool CScript::ExtractPoW2WitnessFromScript(CTxOutPoW2Witness& witness) const { if (this->size() != 74) { //fixme: (PHASE4) Better error handling - this should probably at least log something. return false; } CScript::const_iterator it = begin(); opcodetype opcode; std::vector<unsigned char> item; if (!GetOp(it, opcode, item) || opcode != OP_0) return false; if (!GetOp(it, opcode, item) || opcode != (unsigned char)72) return false; std::vector<unsigned char> vchSpendingKey( begin()+2, begin()+22 ); witness.spendingKeyID = CKeyID(uint160(vchSpendingKey)); std::vector<unsigned char> vchWitnessKey( begin()+22, begin()+42 ); witness.witnessKeyID = CKeyID(uint160(vchWitnessKey)); std::vector<unsigned char> vchLockFromBlock( begin()+42, begin()+50 ); witness.lockFromBlock = CScriptUInt64( vchLockFromBlock ).nNumber; std::vector<unsigned char> vchLockUntilBlock( begin()+50, begin()+58 ); witness.lockUntilBlock = CScriptUInt64( vchLockUntilBlock ).nNumber; std::vector<unsigned char> vchFailCount( begin()+58, begin()+66 ); witness.failCount = CScriptUInt64( vchFailCount ).nNumber; std::vector<unsigned char> vchActionNonce( begin()+66, begin()+74 ); witness.actionNonce = CScriptUInt64( vchActionNonce ).nNumber; return true; } bool CScript::IsPushOnly(const_iterator pc) const { while (pc < end()) { opcodetype opcode; if (!GetOp(pc, opcode)) return false; // Note that IsPushOnly() *does* consider OP_RESERVED to be a // push-type opcode, however execution of OP_RESERVED fails, so // it's not relevant to P2SH/BIP62 as the scriptSig would fail prior to // the P2SH special validation code being executed. if (opcode > OP_16) return false; } return true; } bool CScript::IsPushOnly() const { return this->IsPushOnly(begin()); } std::string CSegregatedSignatureData::ToString() const { std::string ret = "CSegregatedSignatureData("; for (unsigned int i = 0; i < stack.size(); i++) { if (i) { ret += ", "; } ret += HexStr(stack[i]); } return ret + ")"; } bool CScript::HasValidOps() const { CScript::const_iterator it = begin(); while (it < end()) { opcodetype opcode; std::vector<unsigned char> item; if (!GetOp(it, opcode, item) || opcode > MAX_OPCODE || item.size() > MAX_SCRIPT_ELEMENT_SIZE) { return false; } } return true; }
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2016 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. // // File contains modifications by: The Gulden developers // All modifications: // Copyright (c) 2017-2018 The Gulden developers // Authored by: Malcolm MacLeod ([email protected]) // Distributed under the GULDEN software license, see the accompanying // file COPYING #include "script.h" #include "alert.h" #include <util.h> #include "tinyformat.h" #include "utilstrencodings.h" //Gulden #include <primitives/transaction.h> const char* GetOpName(opcodetype opcode) { switch (opcode) { // push value case OP_0 : return "0"; case OP_PUSHDATA1 : return "OP_PUSHDATA1"; case OP_PUSHDATA2 : return "OP_PUSHDATA2"; case OP_PUSHDATA4 : return "OP_PUSHDATA4"; case OP_1NEGATE : return "-1"; case OP_RESERVED : return "OP_RESERVED"; case OP_1 : return "1"; case OP_2 : return "2"; case OP_3 : return "3"; case OP_4 : return "4"; case OP_5 : return "5"; case OP_6 : return "6"; case OP_7 : return "7"; case OP_8 : return "8"; case OP_9 : return "9"; case OP_10 : return "10"; case OP_11 : return "11"; case OP_12 : return "12"; case OP_13 : return "13"; case OP_14 : return "14"; case OP_15 : return "15"; case OP_16 : return "16"; // control case OP_NOP : return "OP_NOP"; case OP_VER : return "OP_VER"; case OP_IF : return "OP_IF"; case OP_NOTIF : return "OP_NOTIF"; case OP_VERIF : return "OP_VERIF"; case OP_VERNOTIF : return "OP_VERNOTIF"; case OP_ELSE : return "OP_ELSE"; case OP_ENDIF : return "OP_ENDIF"; case OP_VERIFY : return "OP_VERIFY"; case OP_RETURN : return "OP_RETURN"; // stack ops case OP_TOALTSTACK : return "OP_TOALTSTACK"; case OP_FROMALTSTACK : return "OP_FROMALTSTACK"; case OP_2DROP : return "OP_2DROP"; case OP_2DUP : return "OP_2DUP"; case OP_3DUP : return "OP_3DUP"; case OP_2OVER : return "OP_2OVER"; case OP_2ROT : return "OP_2ROT"; case OP_2SWAP : return "OP_2SWAP"; case OP_IFDUP : return "OP_IFDUP"; case OP_DEPTH : return "OP_DEPTH"; case OP_DROP : return "OP_DROP"; case OP_DUP : return "OP_DUP"; case OP_NIP : return "OP_NIP"; case OP_OVER : return "OP_OVER"; case OP_PICK : return "OP_PICK"; case OP_ROLL : return "OP_ROLL"; case OP_ROT : return "OP_ROT"; case OP_SWAP : return "OP_SWAP"; case OP_TUCK : return "OP_TUCK"; // splice ops case OP_CAT : return "OP_CAT"; case OP_SUBSTR : return "OP_SUBSTR"; case OP_LEFT : return "OP_LEFT"; case OP_RIGHT : return "OP_RIGHT"; case OP_SIZE : return "OP_SIZE"; // bit logic case OP_INVERT : return "OP_INVERT"; case OP_AND : return "OP_AND"; case OP_OR : return "OP_OR"; case OP_XOR : return "OP_XOR"; case OP_EQUAL : return "OP_EQUAL"; case OP_EQUALVERIFY : return "OP_EQUALVERIFY"; case OP_RESERVED1 : return "OP_RESERVED1"; case OP_RESERVED2 : return "OP_RESERVED2"; // numeric case OP_1ADD : return "OP_1ADD"; case OP_1SUB : return "OP_1SUB"; case OP_2MUL : return "OP_2MUL"; case OP_2DIV : return "OP_2DIV"; case OP_NEGATE : return "OP_NEGATE"; case OP_ABS : return "OP_ABS"; case OP_NOT : return "OP_NOT"; case OP_0NOTEQUAL : return "OP_0NOTEQUAL"; case OP_ADD : return "OP_ADD"; case OP_SUB : return "OP_SUB"; case OP_MUL : return "OP_MUL"; case OP_DIV : return "OP_DIV"; case OP_MOD : return "OP_MOD"; case OP_LSHIFT : return "OP_LSHIFT"; case OP_RSHIFT : return "OP_RSHIFT"; case OP_BOOLAND : return "OP_BOOLAND"; case OP_BOOLOR : return "OP_BOOLOR"; case OP_NUMEQUAL : return "OP_NUMEQUAL"; case OP_NUMEQUALVERIFY : return "OP_NUMEQUALVERIFY"; case OP_NUMNOTEQUAL : return "OP_NUMNOTEQUAL"; case OP_LESSTHAN : return "OP_LESSTHAN"; case OP_GREATERTHAN : return "OP_GREATERTHAN"; case OP_LESSTHANOREQUAL : return "OP_LESSTHANOREQUAL"; case OP_GREATERTHANOREQUAL : return "OP_GREATERTHANOREQUAL"; case OP_MIN : return "OP_MIN"; case OP_MAX : return "OP_MAX"; case OP_WITHIN : return "OP_WITHIN"; // crypto case OP_RIPEMD160 : return "OP_RIPEMD160"; case OP_SHA1 : return "OP_SHA1"; case OP_SHA256 : return "OP_SHA256"; case OP_HASH160 : return "OP_HASH160"; case OP_HASH256 : return "OP_HASH256"; case OP_CODESEPARATOR : return "OP_CODESEPARATOR"; case OP_CHECKSIG : return "OP_CHECKSIG"; case OP_CHECKSIGVERIFY : return "OP_CHECKSIGVERIFY"; case OP_CHECKMULTISIG : return "OP_CHECKMULTISIG"; case OP_CHECKMULTISIGVERIFY : return "OP_CHECKMULTISIGVERIFY"; // expansion case OP_NOP1 : return "OP_NOP1"; case OP_CHECKLOCKTIMEVERIFY : return "OP_CHECKLOCKTIMEVERIFY"; case OP_CHECKSEQUENCEVERIFY : return "OP_CHECKSEQUENCEVERIFY"; case OP_NOP4 : return "OP_NOP4"; case OP_NOP5 : return "OP_NOP5"; case OP_NOP6 : return "OP_NOP6"; case OP_NOP7 : return "OP_NOP7"; case OP_NOP8 : return "OP_NOP8"; case OP_NOP9 : return "OP_NOP9"; case OP_NOP10 : return "OP_NOP10"; case OP_INVALIDOPCODE : return "OP_INVALIDOPCODE"; // Note: // The template matching params OP_SMALLINTEGER/etc are defined in opcodetype enum // as kind of implementation hack, they are *NOT* real opcodes. If found in real // Script, just let the default: case deal with them. case OP_SMALLINTEGER: case OP_PUBKEYS: case OP_PUBKEYHASH: default: return "OP_UNKNOWN"; } } unsigned int CScript::GetSigOpCount(bool fAccurate) const { unsigned int n = 0; const_iterator pc = begin(); opcodetype lastOpcode = OP_INVALIDOPCODE; while (pc < end()) { opcodetype opcode; if (!GetOp(pc, opcode)) break; if (opcode == OP_CHECKSIG || opcode == OP_CHECKSIGVERIFY) n++; else if (opcode == OP_CHECKMULTISIG || opcode == OP_CHECKMULTISIGVERIFY) { if (fAccurate && lastOpcode >= OP_1 && lastOpcode <= OP_16) n += DecodeOP_N(lastOpcode); else n += MAX_PUBKEYS_PER_MULTISIG; } lastOpcode = opcode; } return n; } unsigned int CScript::GetSigOpCount(const CScript& scriptSig) const { if (!IsPayToScriptHash()) return GetSigOpCount(true); // This is a pay-to-script-hash scriptPubKey; // get the last item that the scriptSig // pushes onto the stack: const_iterator pc = scriptSig.begin(); std::vector<unsigned char> vData; while (pc < scriptSig.end()) { opcodetype opcode; if (!scriptSig.GetOp(pc, opcode, vData)) return 0; if (opcode > OP_16) return 0; } /// ... and return its opcount: CScript subscript(vData.begin(), vData.end()); return subscript.GetSigOpCount(true); } bool CScript::IsPayToPubkeyHash(CKeyID &hash) const { if (this->size() == 25 && (*this)[0] == OP_DUP && (*this)[1] == OP_HASH160 && (*this)[2] == 20 && (*this)[23] == OP_EQUALVERIFY && (*this)[24] == OP_CHECKSIG) { memcpy(hash.begin(), &(*this)[3], 20); return true; } return false; } bool CScript::IsPayToScriptHash() const { // Extra-fast test for pay-to-script-hash CScripts: return (this->size() == 23 && (*this)[0] == OP_HASH160 && (*this)[1] == 0x14 && (*this)[22] == OP_EQUAL); } //OP_0 [1 byte] 72 [1 byte] hash [20 byte] hash [20 byte] uint64_t [8 byte] uint64_t [8 byte] uint64_t [8 byte] uint64_t [8 byte] (74 bytes) bool CScript::IsPoW2Witness() const { if (this->size() != 74) return false; if ((*this)[0] != OP_0 || (*this)[1] != 72) return false; return true; } //OP_0 [1 byte] 72 [1 byte] hash [20 byte] hash [20 byte] uint64_t [8 byte] uint64_t [8 byte] uint64_t [8 byte] uint64_t [8 byte] (74 bytes) std::vector<unsigned char> CScript::GetPow2WitnessHash() const { assert(IsPoW2Witness()); std::vector<unsigned char> hashWitnessBytes(this->begin()+22, this->begin()+42); return hashWitnessBytes; } //OP_0 [1 byte] 72 [1 byte] hash [20 byte] hash [20 byte] uint64_t [8 byte] uint64_t [8 byte] uint64_t [8 byte] uint64_t [8 byte] (74 bytes) bool CScript::ExtractPoW2WitnessFromScript(CTxOutPoW2Witness& witness) const { //fixme: (PHASE5) - Enable UI alert for failiure here, can't use CAlert directly because its undefined in test_gulden builds if (this->size() != 74) { std::string strErrorMessage = strprintf("Can't extract witness from a script of invalid size[%d]", this->size()); //CAlert::Notify(strErrorMessage, true, true); LogPrintf("%s", strErrorMessage.c_str()); #ifdef DEBUG assert(0); #endif return false; } CScript::const_iterator it = begin(); opcodetype opcode; std::vector<unsigned char> item; if (!GetOp(it, opcode, item) || opcode != OP_0) { std::string strErrorMessage = strprintf("Can't extract witness; incorrectly encoded script"); //CAlert::Notify(strErrorMessage, true, true); LogPrintf("%s", strErrorMessage.c_str()); return false; } if (!GetOp(it, opcode, item) || opcode != (unsigned char)72) { std::string strErrorMessage = strprintf("Can't extract witness; incorrectly encoded script"); //CAlert::Notify(strErrorMessage, true, true); LogPrintf("%s", strErrorMessage.c_str()); return false; } std::vector<unsigned char> vchSpendingKey( begin()+2, begin()+22 ); witness.spendingKeyID = CKeyID(uint160(vchSpendingKey)); std::vector<unsigned char> vchWitnessKey( begin()+22, begin()+42 ); witness.witnessKeyID = CKeyID(uint160(vchWitnessKey)); std::vector<unsigned char> vchLockFromBlock( begin()+42, begin()+50 ); witness.lockFromBlock = CScriptUInt64( vchLockFromBlock ).nNumber; std::vector<unsigned char> vchLockUntilBlock( begin()+50, begin()+58 ); witness.lockUntilBlock = CScriptUInt64( vchLockUntilBlock ).nNumber; std::vector<unsigned char> vchFailCount( begin()+58, begin()+66 ); witness.failCount = CScriptUInt64( vchFailCount ).nNumber; std::vector<unsigned char> vchActionNonce( begin()+66, begin()+74 ); witness.actionNonce = CScriptUInt64( vchActionNonce ).nNumber; return true; } bool CScript::IsPushOnly(const_iterator pc) const { while (pc < end()) { opcodetype opcode; if (!GetOp(pc, opcode)) return false; // Note that IsPushOnly() *does* consider OP_RESERVED to be a // push-type opcode, however execution of OP_RESERVED fails, so // it's not relevant to P2SH/BIP62 as the scriptSig would fail prior to // the P2SH special validation code being executed. if (opcode > OP_16) return false; } return true; } bool CScript::IsPushOnly() const { return this->IsPushOnly(begin()); } std::string CSegregatedSignatureData::ToString() const { std::string ret = "CSegregatedSignatureData("; for (unsigned int i = 0; i < stack.size(); i++) { if (i) { ret += ", "; } ret += HexStr(stack[i]); } return ret + ")"; } bool CScript::HasValidOps() const { CScript::const_iterator it = begin(); while (it < end()) { opcodetype opcode; std::vector<unsigned char> item; if (!GetOp(it, opcode, item) || opcode > MAX_OPCODE || item.size() > MAX_SCRIPT_ELEMENT_SIZE) { return false; } } return true; }
Resolve a minor fixme
QA: Resolve a minor fixme
C++
mit
nlgcoin/guldencoin-official,nlgcoin/guldencoin-official,nlgcoin/guldencoin-official,nlgcoin/guldencoin-official,nlgcoin/guldencoin-official,nlgcoin/guldencoin-official
84e33cfc841f7f97f49fb1485cb64a6d8dd0a133
src/script/script.cpp
src/script/script.cpp
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2016 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "script.h" #include "tinyformat.h" #include "utilstrencodings.h" using namespace std; const char* GetOpName(opcodetype opcode) { switch (opcode) { // push value case OP_0 : return "0"; case OP_PUSHDATA1 : return "OP_PUSHDATA1"; case OP_PUSHDATA2 : return "OP_PUSHDATA2"; case OP_PUSHDATA4 : return "OP_PUSHDATA4"; case OP_1NEGATE : return "-1"; case OP_RESERVED : return "OP_RESERVED"; case OP_1 : return "1"; case OP_2 : return "2"; case OP_3 : return "3"; case OP_4 : return "4"; case OP_5 : return "5"; case OP_6 : return "6"; case OP_7 : return "7"; case OP_8 : return "8"; case OP_9 : return "9"; case OP_10 : return "10"; case OP_11 : return "11"; case OP_12 : return "12"; case OP_13 : return "13"; case OP_14 : return "14"; case OP_15 : return "15"; case OP_16 : return "16"; // control case OP_NOP : return "OP_NOP"; case OP_VER : return "OP_VER"; case OP_IF : return "OP_IF"; case OP_NOTIF : return "OP_NOTIF"; case OP_VERIF : return "OP_VERIF"; case OP_VERNOTIF : return "OP_VERNOTIF"; case OP_ELSE : return "OP_ELSE"; case OP_ENDIF : return "OP_ENDIF"; case OP_VERIFY : return "OP_VERIFY"; case OP_RETURN : return "OP_RETURN"; // stack ops case OP_TOALTSTACK : return "OP_TOALTSTACK"; case OP_FROMALTSTACK : return "OP_FROMALTSTACK"; case OP_2DROP : return "OP_2DROP"; case OP_2DUP : return "OP_2DUP"; case OP_3DUP : return "OP_3DUP"; case OP_2OVER : return "OP_2OVER"; case OP_2ROT : return "OP_2ROT"; case OP_2SWAP : return "OP_2SWAP"; case OP_IFDUP : return "OP_IFDUP"; case OP_DEPTH : return "OP_DEPTH"; case OP_DROP : return "OP_DROP"; case OP_DUP : return "OP_DUP"; case OP_NIP : return "OP_NIP"; case OP_OVER : return "OP_OVER"; case OP_PICK : return "OP_PICK"; case OP_ROLL : return "OP_ROLL"; case OP_ROT : return "OP_ROT"; case OP_SWAP : return "OP_SWAP"; case OP_TUCK : return "OP_TUCK"; // splice ops case OP_CAT : return "OP_CAT"; case OP_SUBSTR : return "OP_SUBSTR"; case OP_LEFT : return "OP_LEFT"; case OP_RIGHT : return "OP_RIGHT"; case OP_SIZE : return "OP_SIZE"; // bit logic case OP_INVERT : return "OP_INVERT"; case OP_AND : return "OP_AND"; case OP_OR : return "OP_OR"; case OP_XOR : return "OP_XOR"; case OP_EQUAL : return "OP_EQUAL"; case OP_EQUALVERIFY : return "OP_EQUALVERIFY"; case OP_RESERVED1 : return "OP_RESERVED1"; case OP_RESERVED2 : return "OP_RESERVED2"; // numeric case OP_1ADD : return "OP_1ADD"; case OP_1SUB : return "OP_1SUB"; case OP_2MUL : return "OP_2MUL"; case OP_2DIV : return "OP_2DIV"; case OP_NEGATE : return "OP_NEGATE"; case OP_ABS : return "OP_ABS"; case OP_NOT : return "OP_NOT"; case OP_0NOTEQUAL : return "OP_0NOTEQUAL"; case OP_ADD : return "OP_ADD"; case OP_SUB : return "OP_SUB"; case OP_MUL : return "OP_MUL"; case OP_DIV : return "OP_DIV"; case OP_MOD : return "OP_MOD"; case OP_LSHIFT : return "OP_LSHIFT"; case OP_RSHIFT : return "OP_RSHIFT"; case OP_BOOLAND : return "OP_BOOLAND"; case OP_BOOLOR : return "OP_BOOLOR"; case OP_NUMEQUAL : return "OP_NUMEQUAL"; case OP_NUMEQUALVERIFY : return "OP_NUMEQUALVERIFY"; case OP_NUMNOTEQUAL : return "OP_NUMNOTEQUAL"; case OP_LESSTHAN : return "OP_LESSTHAN"; case OP_GREATERTHAN : return "OP_GREATERTHAN"; case OP_LESSTHANOREQUAL : return "OP_LESSTHANOREQUAL"; case OP_GREATERTHANOREQUAL : return "OP_GREATERTHANOREQUAL"; case OP_MIN : return "OP_MIN"; case OP_MAX : return "OP_MAX"; case OP_WITHIN : return "OP_WITHIN"; // crypto case OP_RIPEMD160 : return "OP_RIPEMD160"; case OP_SHA1 : return "OP_SHA1"; case OP_SHA256 : return "OP_SHA256"; case OP_HASH160 : return "OP_HASH160"; case OP_HASH256 : return "OP_HASH256"; case OP_CODESEPARATOR : return "OP_CODESEPARATOR"; case OP_CHECKSIG : return "OP_CHECKSIG"; case OP_CHECKSIGVERIFY : return "OP_CHECKSIGVERIFY"; case OP_CHECKMULTISIG : return "OP_CHECKMULTISIG"; case OP_CHECKMULTISIGVERIFY : return "OP_CHECKMULTISIGVERIFY"; // expansion case OP_NOP1 : return "OP_NOP1"; case OP_CHECKLOCKTIMEVERIFY : return "OP_CHECKLOCKTIMEVERIFY"; case OP_CHECKSEQUENCEVERIFY : return "OP_CHECKSEQUENCEVERIFY"; case OP_NOP4 : return "OP_NOP4"; case OP_NOP5 : return "OP_NOP5"; case OP_NOP6 : return "OP_NOP6"; case OP_NOP7 : return "OP_NOP7"; case OP_NOP8 : return "OP_NOP8"; case OP_NOP9 : return "OP_NOP9"; case OP_NOP10 : return "OP_NOP10"; case OP_INVALIDOPCODE : return "OP_INVALIDOPCODE"; // Note: // The template matching params OP_SMALLINTEGER/etc are defined in opcodetype enum // as kind of implementation hack, they are *NOT* real opcodes. If found in real // Script, just let the default: case deal with them. default: return "OP_UNKNOWN"; } } unsigned int CScript::GetSigOpCount(bool fAccurate) const { unsigned int n = 0; const_iterator pc = begin(); opcodetype lastOpcode = OP_INVALIDOPCODE; while (pc < end()) { opcodetype opcode; if (!GetOp(pc, opcode)) break; if (opcode == OP_CHECKSIG || opcode == OP_CHECKSIGVERIFY) n++; else if (opcode == OP_CHECKMULTISIG || opcode == OP_CHECKMULTISIGVERIFY) { if (fAccurate && lastOpcode >= OP_1 && lastOpcode <= OP_16) n += DecodeOP_N(lastOpcode); else n += MAX_PUBKEYS_PER_MULTISIG; } lastOpcode = opcode; } return n; } unsigned int CScript::GetSigOpCount(const CScript& scriptSig) const { if (!IsPayToScriptHash()) return GetSigOpCount(true); // This is a pay-to-script-hash scriptPubKey; // get the last item that the scriptSig // pushes onto the stack: const_iterator pc = scriptSig.begin(); vector<unsigned char> data; while (pc < scriptSig.end()) { opcodetype opcode; if (!scriptSig.GetOp(pc, opcode, data)) return 0; if (opcode > OP_16) return 0; } /// ... and return its opcount: CScript subscript(data.begin(), data.end()); return subscript.GetSigOpCount(true); } bool CScript::IsPayToScriptHash() const { // Extra-fast test for pay-to-script-hash CScripts: return (this->size() == 23 && (*this)[0] == OP_HASH160 && (*this)[1] == 0x14 && (*this)[22] == OP_EQUAL); } bool CScript::IsPayToWitnessScriptHash() const { // Extra-fast test for pay-to-witness-script-hash CScripts: return (this->size() == 34 && (*this)[0] == OP_0 && (*this)[1] == 0x20); } // A witness program is any valid CScript that consists of a 1-byte push opcode // followed by a data push between 2 and 40 bytes. bool CScript::IsWitnessProgram(int& version, std::vector<unsigned char>& program) const { if (this->size() < 4 || this->size() > 42) { return false; } if ((*this)[0] != OP_0 && ((*this)[0] < OP_1 || (*this)[0] > OP_16)) { return false; } if ((size_t)((*this)[1] + 2) == this->size()) { version = DecodeOP_N((opcodetype)(*this)[0]); program = std::vector<unsigned char>(this->begin() + 2, this->end()); return true; } return false; } bool CScript::IsPushOnly(const_iterator pc) const { while (pc < end()) { opcodetype opcode; if (!GetOp(pc, opcode)) return false; // Note that IsPushOnly() *does* consider OP_RESERVED to be a // push-type opcode, however execution of OP_RESERVED fails, so // it's not relevant to P2SH/BIP62 as the scriptSig would fail prior to // the P2SH special validation code being executed. if (opcode > OP_16) return false; } return true; } bool CScript::IsPushOnly() const { return this->IsPushOnly(begin()); } std::string CScriptWitness::ToString() const { std::string ret = "CScriptWitness("; for (unsigned int i = 0; i < stack.size(); i++) { if (i) { ret += ", "; } ret += HexStr(stack[i]); } return ret + ")"; }
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2016 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "script.h" #include "tinyformat.h" #include "utilstrencodings.h" using namespace std; const char *GetOpName(opcodetype opcode) { switch (opcode) { // push value case OP_0: return "0"; case OP_PUSHDATA1: return "OP_PUSHDATA1"; case OP_PUSHDATA2: return "OP_PUSHDATA2"; case OP_PUSHDATA4: return "OP_PUSHDATA4"; case OP_1NEGATE: return "-1"; case OP_RESERVED: return "OP_RESERVED"; case OP_1: return "1"; case OP_2: return "2"; case OP_3: return "3"; case OP_4: return "4"; case OP_5: return "5"; case OP_6: return "6"; case OP_7: return "7"; case OP_8: return "8"; case OP_9: return "9"; case OP_10: return "10"; case OP_11: return "11"; case OP_12: return "12"; case OP_13: return "13"; case OP_14: return "14"; case OP_15: return "15"; case OP_16: return "16"; // control case OP_NOP: return "OP_NOP"; case OP_VER: return "OP_VER"; case OP_IF: return "OP_IF"; case OP_NOTIF: return "OP_NOTIF"; case OP_VERIF: return "OP_VERIF"; case OP_VERNOTIF: return "OP_VERNOTIF"; case OP_ELSE: return "OP_ELSE"; case OP_ENDIF: return "OP_ENDIF"; case OP_VERIFY: return "OP_VERIFY"; case OP_RETURN: return "OP_RETURN"; // stack ops case OP_TOALTSTACK: return "OP_TOALTSTACK"; case OP_FROMALTSTACK: return "OP_FROMALTSTACK"; case OP_2DROP: return "OP_2DROP"; case OP_2DUP: return "OP_2DUP"; case OP_3DUP: return "OP_3DUP"; case OP_2OVER: return "OP_2OVER"; case OP_2ROT: return "OP_2ROT"; case OP_2SWAP: return "OP_2SWAP"; case OP_IFDUP: return "OP_IFDUP"; case OP_DEPTH: return "OP_DEPTH"; case OP_DROP: return "OP_DROP"; case OP_DUP: return "OP_DUP"; case OP_NIP: return "OP_NIP"; case OP_OVER: return "OP_OVER"; case OP_PICK: return "OP_PICK"; case OP_ROLL: return "OP_ROLL"; case OP_ROT: return "OP_ROT"; case OP_SWAP: return "OP_SWAP"; case OP_TUCK: return "OP_TUCK"; // splice ops case OP_CAT: return "OP_CAT"; case OP_SUBSTR: return "OP_SUBSTR"; case OP_LEFT: return "OP_LEFT"; case OP_RIGHT: return "OP_RIGHT"; case OP_SIZE: return "OP_SIZE"; // bit logic case OP_INVERT: return "OP_INVERT"; case OP_AND: return "OP_AND"; case OP_OR: return "OP_OR"; case OP_XOR: return "OP_XOR"; case OP_EQUAL: return "OP_EQUAL"; case OP_EQUALVERIFY: return "OP_EQUALVERIFY"; case OP_RESERVED1: return "OP_RESERVED1"; case OP_RESERVED2: return "OP_RESERVED2"; // numeric case OP_1ADD: return "OP_1ADD"; case OP_1SUB: return "OP_1SUB"; case OP_2MUL: return "OP_2MUL"; case OP_2DIV: return "OP_2DIV"; case OP_NEGATE: return "OP_NEGATE"; case OP_ABS: return "OP_ABS"; case OP_NOT: return "OP_NOT"; case OP_0NOTEQUAL: return "OP_0NOTEQUAL"; case OP_ADD: return "OP_ADD"; case OP_SUB: return "OP_SUB"; case OP_MUL: return "OP_MUL"; case OP_DIV: return "OP_DIV"; case OP_MOD: return "OP_MOD"; case OP_LSHIFT: return "OP_LSHIFT"; case OP_RSHIFT: return "OP_RSHIFT"; case OP_BOOLAND: return "OP_BOOLAND"; case OP_BOOLOR: return "OP_BOOLOR"; case OP_NUMEQUAL: return "OP_NUMEQUAL"; case OP_NUMEQUALVERIFY: return "OP_NUMEQUALVERIFY"; case OP_NUMNOTEQUAL: return "OP_NUMNOTEQUAL"; case OP_LESSTHAN: return "OP_LESSTHAN"; case OP_GREATERTHAN: return "OP_GREATERTHAN"; case OP_LESSTHANOREQUAL: return "OP_LESSTHANOREQUAL"; case OP_GREATERTHANOREQUAL: return "OP_GREATERTHANOREQUAL"; case OP_MIN: return "OP_MIN"; case OP_MAX: return "OP_MAX"; case OP_WITHIN: return "OP_WITHIN"; // crypto case OP_RIPEMD160: return "OP_RIPEMD160"; case OP_SHA1: return "OP_SHA1"; case OP_SHA256: return "OP_SHA256"; case OP_HASH160: return "OP_HASH160"; case OP_HASH256: return "OP_HASH256"; case OP_CODESEPARATOR: return "OP_CODESEPARATOR"; case OP_CHECKSIG: return "OP_CHECKSIG"; case OP_CHECKSIGVERIFY: return "OP_CHECKSIGVERIFY"; case OP_CHECKMULTISIG: return "OP_CHECKMULTISIG"; case OP_CHECKMULTISIGVERIFY: return "OP_CHECKMULTISIGVERIFY"; // expansion case OP_NOP1: return "OP_NOP1"; case OP_CHECKLOCKTIMEVERIFY: return "OP_CHECKLOCKTIMEVERIFY"; case OP_CHECKSEQUENCEVERIFY: return "OP_CHECKSEQUENCEVERIFY"; case OP_NOP4: return "OP_NOP4"; case OP_NOP5: return "OP_NOP5"; case OP_NOP6: return "OP_NOP6"; case OP_NOP7: return "OP_NOP7"; case OP_NOP8: return "OP_NOP8"; case OP_NOP9: return "OP_NOP9"; case OP_NOP10: return "OP_NOP10"; case OP_INVALIDOPCODE: return "OP_INVALIDOPCODE"; // Note: // The template matching params OP_SMALLINTEGER/etc are defined in // opcodetype enum as kind of implementation hack, they are *NOT* real // opcodes. If found in real Script, just let the default: case deal // with them. default: return "OP_UNKNOWN"; } } unsigned int CScript::GetSigOpCount(bool fAccurate) const { unsigned int n = 0; const_iterator pc = begin(); opcodetype lastOpcode = OP_INVALIDOPCODE; while (pc < end()) { opcodetype opcode; if (!GetOp(pc, opcode)) break; if (opcode == OP_CHECKSIG || opcode == OP_CHECKSIGVERIFY) n++; else if (opcode == OP_CHECKMULTISIG || opcode == OP_CHECKMULTISIGVERIFY) { if (fAccurate && lastOpcode >= OP_1 && lastOpcode <= OP_16) n += DecodeOP_N(lastOpcode); else n += MAX_PUBKEYS_PER_MULTISIG; } lastOpcode = opcode; } return n; } unsigned int CScript::GetSigOpCount(const CScript &scriptSig) const { if (!IsPayToScriptHash()) return GetSigOpCount(true); // This is a pay-to-script-hash scriptPubKey; // get the last item that the scriptSig // pushes onto the stack: const_iterator pc = scriptSig.begin(); vector<unsigned char> data; while (pc < scriptSig.end()) { opcodetype opcode; if (!scriptSig.GetOp(pc, opcode, data)) return 0; if (opcode > OP_16) return 0; } /// ... and return its opcount: CScript subscript(data.begin(), data.end()); return subscript.GetSigOpCount(true); } bool CScript::IsPayToScriptHash() const { // Extra-fast test for pay-to-script-hash CScripts: return (this->size() == 23 && (*this)[0] == OP_HASH160 && (*this)[1] == 0x14 && (*this)[22] == OP_EQUAL); } bool CScript::IsPayToWitnessScriptHash() const { // Extra-fast test for pay-to-witness-script-hash CScripts: return (this->size() == 34 && (*this)[0] == OP_0 && (*this)[1] == 0x20); } // A witness program is any valid CScript that consists of a 1-byte push opcode // followed by a data push between 2 and 40 bytes. bool CScript::IsWitnessProgram(int &version, std::vector<unsigned char> &program) const { if (this->size() < 4 || this->size() > 42) { return false; } if ((*this)[0] != OP_0 && ((*this)[0] < OP_1 || (*this)[0] > OP_16)) { return false; } if ((size_t)((*this)[1] + 2) == this->size()) { version = DecodeOP_N((opcodetype)(*this)[0]); program = std::vector<unsigned char>(this->begin() + 2, this->end()); return true; } return false; } bool CScript::IsPushOnly(const_iterator pc) const { while (pc < end()) { opcodetype opcode; if (!GetOp(pc, opcode)) return false; // Note that IsPushOnly() *does* consider OP_RESERVED to be a push-type // opcode, however execution of OP_RESERVED fails, so it's not relevant // to P2SH/BIP62 as the scriptSig would fail prior to the P2SH special // validation code being executed. if (opcode > OP_16) return false; } return true; } bool CScript::IsPushOnly() const { return this->IsPushOnly(begin()); } std::string CScriptWitness::ToString() const { std::string ret = "CScriptWitness("; for (unsigned int i = 0; i < stack.size(); i++) { if (i) { ret += ", "; } ret += HexStr(stack[i]); } return ret + ")"; }
Format script.cpp
Format script.cpp
C++
mit
cculianu/bitcoin-abc,Bitcoin-ABC/bitcoin-abc,ftrader-bitcoinabc/bitcoin-abc,cculianu/bitcoin-abc,ftrader-bitcoinabc/bitcoin-abc,Bitcoin-ABC/bitcoin-abc,ftrader-bitcoinabc/bitcoin-abc,Bitcoin-ABC/bitcoin-abc,cculianu/bitcoin-abc,cculianu/bitcoin-abc,Bitcoin-ABC/bitcoin-abc,ftrader-bitcoinabc/bitcoin-abc,Bitcoin-ABC/bitcoin-abc,Bitcoin-ABC/bitcoin-abc,ftrader-bitcoinabc/bitcoin-abc,ftrader-bitcoinabc/bitcoin-abc,Bitcoin-ABC/bitcoin-abc,cculianu/bitcoin-abc,Bitcoin-ABC/bitcoin-abc,ftrader-bitcoinabc/bitcoin-abc,ftrader-bitcoinabc/bitcoin-abc,Bitcoin-ABC/bitcoin-abc,cculianu/bitcoin-abc,cculianu/bitcoin-abc,ftrader-bitcoinabc/bitcoin-abc,Bitcoin-ABC/bitcoin-abc,ftrader-bitcoinabc/bitcoin-abc,cculianu/bitcoin-abc,Bitcoin-ABC/bitcoin-abc,Bitcoin-ABC/bitcoin-abc,Bitcoin-ABC/bitcoin-abc
9b35d7cb015fe3154c4aa11dc63ffc7eb6937e5f
src/ninja.cc
src/ninja.cc
#include "ninja.h" #include <getopt.h> #include <limits.h> #include <stdio.h> #include "build.h" #include "build_log.h" #include "parsers.h" #include "graphviz.h" // Import browse.py as binary data. asm( ".data\n" "browse_data_begin:\n" ".incbin \"src/browse.py\"\n" "browse_data_end:\n" ); // Declare the symbols defined above. extern const char browse_data_begin[]; extern const char browse_data_end[]; option options[] = { { "help", no_argument, NULL, 'h' }, { } }; void usage() { fprintf(stderr, "usage: ninja [options] target\n" "\n" "options:\n" " -g output graphviz dot file for targets and exit\n" " -i FILE specify input build file [default=build.ninja]\n" " -n dry run (don't run commands but pretend they succeeded)\n" " -v show all command lines\n" " -q show inputs/outputs of target (query mode)\n" " -b browse dependency graph of target in a web browser\n" ); } struct RealFileReader : public ManifestParser::FileReader { bool ReadFile(const string& path, string* content, string* err) { return ::ReadFile(path, content, err) == 0; } }; int main(int argc, char** argv) { BuildConfig config; const char* input_file = "build.ninja"; bool graph = false; bool query = false; bool browse = false; int opt; while ((opt = getopt_long(argc, argv, "bghi:nvq", options, NULL)) != -1) { switch (opt) { case 'g': graph = true; break; case 'i': input_file = optarg; break; case 'n': config.dry_run = true; break; case 'v': config.verbosity = BuildConfig::VERBOSE; break; case 'q': query = true; break; case 'b': browse = true; break; case 'h': default: usage(); return 1; } } if (optind >= argc) { fprintf(stderr, "expected target to build\n"); usage(); return 1; } argv += optind; argc -= optind; char cwd[PATH_MAX]; if (!getcwd(cwd, sizeof(cwd))) { perror("getcwd"); return 1; } State state; RealFileReader file_reader; ManifestParser parser(&state, &file_reader); string err; if (!parser.Load(input_file, &err)) { fprintf(stderr, "error loading '%s': %s\n", input_file, err.c_str()); return 1; } if (graph) { GraphViz graph; graph.Start(); for (int i = 0; i < argc; ++i) graph.AddTarget(state.GetNode(argv[i])); graph.Finish(); return 0; } if (query) { for (int i = 0; i < argc; ++i) { Node* node = state.GetNode(argv[i]); if (node) { printf("%s:\n", argv[i]); if (node->in_edge_) { printf(" input: %s\n", node->in_edge_->rule_->name_.c_str()); for (vector<Node*>::iterator in = node->in_edge_->inputs_.begin(); in != node->in_edge_->inputs_.end(); ++in) { printf(" %s\n", (*in)->file_->path_.c_str()); } } for (vector<Edge*>::iterator edge = node->out_edges_.begin(); edge != node->out_edges_.end(); ++edge) { printf(" output: %s\n", (*edge)->rule_->name_.c_str()); for (vector<Node*>::iterator out = (*edge)->outputs_.begin(); out != (*edge)->outputs_.end(); ++out) { printf(" %s\n", (*out)->file_->path_.c_str()); } } } else { printf("%s unknown\n", argv[i]); } } return 0; } if (browse) { // Create a temporary file, dump the Python code into it, and // delete the file, keeping our open handle to it. char tmpl[] = "browsepy-XXXXXX"; int fd = mkstemp(tmpl); unlink(tmpl); const int browse_data_len = browse_data_end - browse_data_begin; int len = write(fd, browse_data_begin, browse_data_len); if (len < browse_data_len) { perror("write"); return 1; } // exec Python, telling it to use our script file. const char* command[] = { "python", "/proc/self/fd/3", argv[0], NULL }; execvp(command[0], (char**)command); // If we get here, the exec failed. printf("ERROR: Failed to spawn python for graph browsing, aborting.\n"); return 1; } const char* kLogPath = ".ninja_log"; if (!state.build_log_->Load(kLogPath, &err)) { fprintf(stderr, "error loading build log: %s\n", err.c_str()); return 1; } if (!config.dry_run && !state.build_log_->OpenForWrite(kLogPath, &err)) { fprintf(stderr, "error opening build log: %s\n", err.c_str()); return 1; } Builder builder(&state, config); for (int i = 0; i < argc; ++i) { if (!builder.AddTarget(argv[i], &err)) { if (!err.empty()) { fprintf(stderr, "%s\n", err.c_str()); return 1; } else { // Added a target that is already up-to-date; not really // an error. } } } bool success = builder.Build(&err); if (!err.empty()) { printf("build stopped: %s.\n", err.c_str()); } return success ? 0 : 1; }
#include "ninja.h" #include <getopt.h> #include <limits.h> #include <stdio.h> #include "build.h" #include "build_log.h" #include "parsers.h" #include "graphviz.h" // Import browse.py as binary data. asm( ".data\n" "browse_data_begin:\n" ".incbin \"src/browse.py\"\n" "browse_data_end:\n" ); // Declare the symbols defined above. extern const char browse_data_begin[]; extern const char browse_data_end[]; option options[] = { { "help", no_argument, NULL, 'h' }, { } }; void usage() { fprintf(stderr, "usage: ninja [options] target\n" "\n" "options:\n" " -g output graphviz dot file for targets and exit\n" " -i FILE specify input build file [default=build.ninja]\n" " -n dry run (don't run commands but pretend they succeeded)\n" " -v show all command lines\n" " -q show inputs/outputs of target (query mode)\n" " -b browse dependency graph of target in a web browser\n" ); } struct RealFileReader : public ManifestParser::FileReader { bool ReadFile(const string& path, string* content, string* err) { return ::ReadFile(path, content, err) == 0; } }; int CmdGraph(State* state, int argc, char* argv[]) { GraphViz graph; graph.Start(); for (int i = 0; i < argc; ++i) graph.AddTarget(state->GetNode(argv[i])); graph.Finish(); return 0; } int CmdQuery(State* state, int argc, char* argv[]) { for (int i = 0; i < argc; ++i) { Node* node = state->GetNode(argv[i]); if (node) { printf("%s:\n", argv[i]); if (node->in_edge_) { printf(" input: %s\n", node->in_edge_->rule_->name_.c_str()); for (vector<Node*>::iterator in = node->in_edge_->inputs_.begin(); in != node->in_edge_->inputs_.end(); ++in) { printf(" %s\n", (*in)->file_->path_.c_str()); } } for (vector<Edge*>::iterator edge = node->out_edges_.begin(); edge != node->out_edges_.end(); ++edge) { printf(" output: %s\n", (*edge)->rule_->name_.c_str()); for (vector<Node*>::iterator out = (*edge)->outputs_.begin(); out != (*edge)->outputs_.end(); ++out) { printf(" %s\n", (*out)->file_->path_.c_str()); } } } else { printf("%s unknown\n", argv[i]); return 1; } } return 0; } int CmdBrowse(State* state, int argc, char* argv[]) { // Create a temporary file, dump the Python code into it, and // delete the file, keeping our open handle to it. char tmpl[] = "browsepy-XXXXXX"; int fd = mkstemp(tmpl); unlink(tmpl); const int browse_data_len = browse_data_end - browse_data_begin; int len = write(fd, browse_data_begin, browse_data_len); if (len < browse_data_len) { perror("write"); return 1; } // exec Python, telling it to use our script file. const char* command[] = { "python", "/proc/self/fd/3", argv[0], NULL }; execvp(command[0], (char**)command); // If we get here, the exec failed. printf("ERROR: Failed to spawn python for graph browsing, aborting.\n"); return 1; } int main(int argc, char** argv) { BuildConfig config; const char* input_file = "build.ninja"; bool graph = false; bool query = false; bool browse = false; int opt; while ((opt = getopt_long(argc, argv, "bghi:nvq", options, NULL)) != -1) { switch (opt) { case 'g': graph = true; break; case 'i': input_file = optarg; break; case 'n': config.dry_run = true; break; case 'v': config.verbosity = BuildConfig::VERBOSE; break; case 'q': query = true; break; case 'b': browse = true; break; case 'h': default: usage(); return 1; } } if (optind >= argc) { fprintf(stderr, "expected target to build\n"); usage(); return 1; } argv += optind; argc -= optind; char cwd[PATH_MAX]; if (!getcwd(cwd, sizeof(cwd))) { perror("getcwd"); return 1; } State state; RealFileReader file_reader; ManifestParser parser(&state, &file_reader); string err; if (!parser.Load(input_file, &err)) { fprintf(stderr, "error loading '%s': %s\n", input_file, err.c_str()); return 1; } if (graph) return CmdGraph(&state, argc, argv); if (query) return CmdQuery(&state, argc, argv); if (browse) return CmdBrowse(&state, argc, argv); const char* kLogPath = ".ninja_log"; if (!state.build_log_->Load(kLogPath, &err)) { fprintf(stderr, "error loading build log: %s\n", err.c_str()); return 1; } if (!config.dry_run && !state.build_log_->OpenForWrite(kLogPath, &err)) { fprintf(stderr, "error opening build log: %s\n", err.c_str()); return 1; } Builder builder(&state, config); for (int i = 0; i < argc; ++i) { if (!builder.AddTarget(argv[i], &err)) { if (!err.empty()) { fprintf(stderr, "%s\n", err.c_str()); return 1; } else { // Added a target that is already up-to-date; not really // an error. } } } bool success = builder.Build(&err); if (!err.empty()) { printf("build stopped: %s.\n", err.c_str()); } return success ? 0 : 1; }
refactor main
refactor main
C++
apache-2.0
ignatenkobrain/ninja,nico/ninja,metti/ninja,bradking/ninja,ukai/ninja,PetrWolf/ninja,synaptek/ninja,tychoish/ninja,sorbits/ninja,mgaunard/ninja,metti/ninja,pcc/ninja,sxlin/dist_ninja,glensc/ninja,mohamed/ninja,pcc/ninja,jhanssen/ninja,guiquanz/ninja,autopulated/ninja,tfarina/ninja,jsternberg/ninja,sgraham/ninja,maximuska/ninja,iwadon/ninja,pck/ninja,sorbits/ninja,guiquanz/ninja,iwadon/ninja,chenyukang/ninja,syntheticpp/ninja,kimgr/ninja,rjogrady/ninja,automeka/ninja,kissthink/ninja,chenyukang/ninja,bradking/ninja,curinir/ninja,fuchsia-mirror/third_party-ninja,moroten/ninja,dpwright/ninja,Qix-/ninja,kimgr/ninja,jendrikillner/ninja,curinir/ninja,liukd/ninja,nornagon/ninja,mydongistiny/ninja,jimon/ninja,glensc/ninja,dabrahams/ninja,ThiagoGarciaAlves/ninja,martine/ninja,Maratyszcza/ninja-pypi,ctiller/ninja,sxlin/dist_ninja,tychoish/ninja,lizh06/ninja,liukd/ninja,rnk/ninja,bradking/ninja,sgraham/ninja,barak/ninja,ukai/ninja,TheOneRing/ninja,rnk/ninja,purcell/ninja,maximuska/ninja,synaptek/ninja,nocnokneo/ninja,yannicklm/ninja,pathscale/ninja,Maratyszcza/ninja-pypi,dabrahams/ninja,colincross/ninja,nickhutchinson/ninja,autopulated/ninja,moroten/ninja,AoD314/ninja,ThiagoGarciaAlves/ninja,kissthink/ninja,fuchsia-mirror/third_party-ninja,ehird/ninja,PetrWolf/ninja,juntalis/ninja,colincross/ninja,juntalis/ninja,drbo/ninja,tychoish/ninja,ikarienator/ninja,juntalis/ninja,Qix-/ninja,moroten/ninja,hnney/ninja,curinir/ninja,bmeurer/ninja,juntalis/ninja,mdempsky/ninja,ignatenkobrain/ninja,PetrWolf/ninja,tfarina/ninja,pcc/ninja,syntheticpp/ninja,automeka/ninja,sgraham/ninja,yannicklm/ninja,dabrahams/ninja,SByer/ninja,fifoforlifo/ninja,ndsol/subninja,dorgonman/ninja,okuoku/ninja,nickhutchinson/ninja,PetrWolf/ninja-main,sxlin/dist_ninja,pck/ninja,mydongistiny/ninja,Qix-/ninja,LuaDist/ninja,nornagon/ninja,guiquanz/ninja,nafest/ninja,hnney/ninja,fifoforlifo/ninja,dpwright/ninja,ctiller/ninja,ehird/ninja,SByer/ninja,maruel/ninja,liukd/ninja,jcfr/ninja,sorbits/ninja,jendrikillner/ninja,hnney/ninja,AoD314/ninja,tfarina/ninja,colincross/ninja,justinsb/ninja,atetubou/ninja,LuaDist/ninja,cipriancraciun/ninja,cipriancraciun/ninja,sorbits/ninja,sxlin/dist_ninja,mohamed/ninja,mutac/ninja,TheOneRing/ninja,jhanssen/ninja,pck/ninja,ikarienator/ninja,curinir/ninja,liukd/ninja,mathstuf/ninja,dorgonman/ninja,atetubou/ninja,jendrikillner/ninja,nickhutchinson/ninja,drbo/ninja,glensc/ninja,fifoforlifo/ninja,mathstuf/ninja,jsternberg/ninja,dendy/ninja,jendrikillner/ninja,colincross/ninja,purcell/ninja,nornagon/ninja,synaptek/ninja,Ju2ender/ninja,justinsb/ninja,mutac/ninja,vvvrrooomm/ninja,LuaDist/ninja,rjogrady/ninja,jsternberg/ninja,hnney/ninja,tychoish/ninja,nocnokneo/ninja,purcell/ninja,SByer/ninja,jcfr/ninja,ilor/ninja,PetrWolf/ninja-main,syntheticpp/ninja,barak/ninja,nico/ninja,Qix-/ninja,nafest/ninja,pck/ninja,AoD314/ninja,kimgr/ninja,metti/ninja,okuoku/ninja,rnk/ninja,mathstuf/ninja,mgaunard/ninja,maximuska/ninja,chenyukang/ninja,rjogrady/ninja,kissthink/ninja,martine/ninja,mdempsky/ninja,barak/ninja,lizh06/ninja,pcc/ninja,mgaunard/ninja,nicolasdespres/ninja,dendy/ninja,nico/ninja,LuaDist/ninja,ninja-build/ninja,ukai/ninja,mydongistiny/ninja,TheOneRing/ninja,maruel/ninja,vvvrrooomm/ninja,dorgonman/ninja,SByer/ninja,bmeurer/ninja,dpwright/ninja,pathscale/ninja,jimon/ninja,mutac/ninja,okuoku/ninja,jimon/ninja,ikarienator/ninja,nicolasdespres/ninja,kimgr/ninja,nocnokneo/ninja,ctiller/ninja,nicolasdespres/ninja,vvvrrooomm/ninja,lizh06/ninja,mohamed/ninja,ehird/ninja,maruel/ninja,syntheticpp/ninja,nornagon/ninja,dabrahams/ninja,cipriancraciun/ninja,purcell/ninja,ThiagoGarciaAlves/ninja,dpwright/ninja,PetrWolf/ninja-main,justinsb/ninja,mydongistiny/ninja,jcfr/ninja,automeka/ninja,mohamed/ninja,yannicklm/ninja,jcfr/ninja,iwadon/ninja,ninja-build/ninja,ThiagoGarciaAlves/ninja,drbo/ninja,yannicklm/ninja,maruel/ninja,rjogrady/ninja,maximuska/ninja,nafest/ninja,sxlin/dist_ninja,cipriancraciun/ninja,bmeurer/ninja,ilor/ninja,jimon/ninja,Maratyszcza/ninja-pypi,iwadon/ninja,pathscale/ninja,atetubou/ninja,ilor/ninja,ilor/ninja,mgaunard/ninja,autopulated/ninja,glensc/ninja,dendy/ninja,ukai/ninja,sgraham/ninja,automeka/ninja,fuchsia-mirror/third_party-ninja,ctiller/ninja,barak/ninja,Ju2ender/ninja,nocnokneo/ninja,autopulated/ninja,vvvrrooomm/ninja,atetubou/ninja,sxlin/dist_ninja,nico/ninja,mdempsky/ninja,chenyukang/ninja,martine/ninja,AoD314/ninja,lizh06/ninja,okuoku/ninja,nafest/ninja,fifoforlifo/ninja,ndsol/subninja,PetrWolf/ninja,ninja-build/ninja,nicolasdespres/ninja,dendy/ninja,ehird/ninja,justinsb/ninja,bradking/ninja,jhanssen/ninja,kissthink/ninja,rnk/ninja,tfarina/ninja,ndsol/subninja,pathscale/ninja,mathstuf/ninja,TheOneRing/ninja,bmeurer/ninja,martine/ninja,jsternberg/ninja,moroten/ninja,ignatenkobrain/ninja,mdempsky/ninja,PetrWolf/ninja-main,ninja-build/ninja,dorgonman/ninja,synaptek/ninja,guiquanz/ninja,metti/ninja,fuchsia-mirror/third_party-ninja,Ju2ender/ninja,ndsol/subninja,ikarienator/ninja,sxlin/dist_ninja,mutac/ninja,nickhutchinson/ninja,drbo/ninja,Maratyszcza/ninja-pypi,Ju2ender/ninja,jhanssen/ninja,ignatenkobrain/ninja
a24b2bfb9051318f6dec3c54eba4972d09817e1c
DataFactory.cpp
DataFactory.cpp
#include "DataFactory.h" // Must defined corresponding static members ... /* DataFactory * DataFactory::_instance = NULL; */ std::map<DataType,CreatorBase<AbstractData>*> DataFactory::_map = std::map<DataType,CreatorBase<AbstractData>*>(); UserDataType::UserDataType(){ a=""; }; UserDataType::UserDataType(std::string s){ a=s; }; UserDataType::~UserDataType(){ }; bool UserDataType::operator == (const UserDataType & t)const{ return (t.a == this->a); } bool UserDataType::operator < (const UserDataType & t)const{ return (t.a > this->a); } bool UserDataType::operator > (const UserDataType & t)const{ return (t.a < this->a); } std::ostream& operator <<(std::ostream& str, const UserDataType& obj){ str << obj.a; return str; } std::istream& operator >>(std::istream& str, UserDataType& obj){ str >> obj.a; return str; }
#include "DataFactory.h" // Must defined corresponding static members ... /* DataFactory * DataFactory::_instance = NULL; */ std::map<DataType,CreatorBase<AbstractData>*> DataFactory::_map = std::map<DataType,CreatorBase<AbstractData>*>(); UserDataType::UserDataType(){ a=""; }; UserDataType::UserDataType(const std::string & s){ a=s; }; UserDataType::UserDataType(const char * s){ a=s; }; UserDataType::~UserDataType(){ }; bool UserDataType::operator == (const UserDataType & t)const{ return (t.a == this->a); } bool UserDataType::operator < (const UserDataType & t)const{ return (t.a > this->a); } bool UserDataType::operator > (const UserDataType & t)const{ return (t.a < this->a); } std::ostream& operator <<(std::ostream& str, const UserDataType& obj){ str << obj.a; return str; } std::istream& operator >>(std::istream& str, UserDataType& obj){ str >> obj.a; return str; }
fix missing ctor
fix missing ctor
C++
mit
tryingsomestuff/pilot,tryingsomestuff/pilot
57d11153188dbe2a0b8f97baffcebcec5b4614fb
test/testbench.cpp
test/testbench.cpp
/* ------------------------------------------------------------------------------ * MIT License * * Copyright (c) 2017 Yann Herklotz Grave * * 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. * ------------------------------------------------------------------------------ * Description: * * Tests the math class using different tests to see if matrix operations work * correctly. * ------------------------------------------------------------------------------ */ #include "testbench.hpp" #include <algorithm> #include <stdexcept> void TestBench::startTest(const std::string &test_name) { incrementer++; Test test(test_name, false); tests_.push_back(test); } void TestBench::endTest(bool pass) { incrementer--; if(incrementer!=0) { throw std::runtime_error("Start and End don't match"); } if(pass) { passed++; } else { failed++; } tests_[passed+failed-1].passed=pass; } void TestBench::printResults() { std::sort(tests_.begin(), tests_.end(), [] (const Test &a, const Test &b) { if(a.name<b.name) return true; return false; }); printf("Results:\n"); printf("+---------------------------+---------+\n"); printf("| Test Name | Result |\n"); printf("+---------------------------+---------+\n"); for(auto test : tests_) { std::string result; if(test.passed) result="PASS"; else result="FAIL"; char test_name[25]; for(std::size_t i=0; i<25; ++i) { if(i<test.name.size()) test_name[i]=test.name[i]; else test_name[i]=' '; } printf("| %25.25s | %6s |\n", test_name, result.c_str()); } printf("+---------------------------+---------+\n"); printf("\nSummary:\n"); printf("+--------+--------+\n"); printf("| Passed | %6d |\n", passed); printf("| Failed | %6d |\n", failed); printf("| Ratio | %5.1f%% |\n", (float)passed/(float)(failed+passed) * 100.f); printf("+--------+--------+\n"); }
/* ------------------------------------------------------------------------------ * MIT License * * Copyright (c) 2017 Yann Herklotz Grave * * 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. * ------------------------------------------------------------------------------ * Description: * * Tests the math class using different tests to see if matrix operations work * correctly. * ------------------------------------------------------------------------------ */ #include "testbench.hpp" #include <algorithm> #include <stdexcept> void TestBench::startTest(const std::string &test_name) { incrementer++; Test test(test_name, false); tests_.push_back(test); } void TestBench::endTest(bool pass) { incrementer--; if(incrementer!=0) throw std::runtime_error("Start and End don't match"); if(pass) passed++; else failed++; tests_[passed+failed-1].passed=pass; } void TestBench::printResults() { std::sort(tests_.begin(), tests_.end(), [] (const Test &a, const Test &b) { if(a.name<b.name) return true; return false; }); printf("Results:\n"); printf("+---------------------------+---------+\n"); printf("| Test Name | Result |\n"); printf("+---------------------------+---------+\n"); for(auto test : tests_) { std::string result; if(test.passed) result="PASS"; else result="FAIL"; char test_name[25]; for(std::size_t i=0; i<25; ++i) { if(i<test.name.size()) test_name[i]=test.name[i]; else test_name[i]=' '; } printf("| %25.25s | %6s |\n", test_name, result.c_str()); } printf("+---------------------------+---------+\n"); printf("\nSummary:\n"); printf("+--------+--------+\n"); printf("| Passed | %6d |\n", passed); printf("| Failed | %6d |\n", failed); printf("| Ratio | %5.1f%% |\n", (float)passed/(float)(failed+passed) * 100.f); printf("+--------+--------+\n"); }
Update testbench.cpp
Update testbench.cpp
C++
mit
ymherklotz/YAGE,ymherklotz/YAGE,ymherklotz/YAGE
0653da2f9fd76d33cc8b9023748ea77a5a1326f4
src/test.cpp
src/test.cpp
#include "lex_config.h" #include "test.h" #include "token.h" #include "symseg.h" #include "lex.h" #ifdef TEST_ON /* * Simple Test Framework */ #define EXPECT_EQ_BASE(equality,expect,actual,format) \ do { \ test_count++; \ if (equality){ \ test_pass++;\ }else{ \ main_ret = 1; \ fprintf(stderr,"%s:%d: expect: " format " actual: " format "\n",__FILE__,__LINE__,expect,actual);\ } \ }while (0) #else #define EXPECT_EQ_BASE(equality, expect, actual, format) do{} while(0) #endif /* end of TEST_ON */ #define EXPECT_EQ_INT(expect, actual) EXPECT_EQ_BASE((expect) == (actual), expect, actual, "%d") #define EXPECT_EQ_DOUBLE(expect, actual) EXPECT_EQ_BASE((expect) == (actual), expect, actual, "%.17g") #define EXPECT_EQ_STRING(expect, actual, alength) \ EXPECT_EQ_BASE(sizeof(expect) - 1 == alength && memcmp(expect, actual, alength + 1) == 0, expect, actual, "%s") #define EXPECT_TRUE(actual) EXPECT_EQ_BASE((actual) != 0, "true", "false", "%s") #define EXPECT_FALSE(actual) EXPECT_EQ_BASE((actual) == 0, "false", "true", "%s") #define GET_TOKEN(idx) source_file.get_token(idx) extern std::string cur_line; extern line cur_line_info; extern source source_file; int test_count = 0; int test_pass = 0; int main_ret = 0; void test_lexer() { std::vector<std::string> test_operator = { " =!><+-*/%&|^>><<~&&||?:, ", " ()==!=>=<=+=-=*=/=%=&=|= ", " ^=>>=<<=[]{};++--->.:: ", }; std::vector<std::string> test_number = { " int a = 123; ", " int b = 123.456; ", " int c = 0xff00; ", " int d = 0123; ", }; std::vector<std::string> test_identifier = { " int a; ", " int _b; ", " int _c_d_1; ", }; std::vector<std::string> test_comment = { " //This is a single line comment ", " /* This is a ", " * multi-line ", " * ע ", " */ ", }; std::vector<std::string> test_literal = { " string s = \"hello, \\\"world\"; ", " char c = 'b'; ", }; std::vector<std::string> test_warning_and_error = { " int 3a; ", /* invalid identifier */ " ", /* unknown type name */ " int b = 123.456.789; ", /* too many decimal points in number */ " int c = 09; ", /* too many decimal points in number */ " string s = \"hello; ", /* missing terminating \" character */ " char cc = 'h; ", /* missing terminating \' character */ " cc = 'hello world'; ", /* character constant too long for its type */ }; for (std::string s : test_operator) { cur_line = s; cur_line_info++; lex(); } for (int i = 0; i < 46; i++) { EXPECT_EQ_INT(i, GET_TOKEN(i)); } printf("%d/%d (%3.2f%%) passed\n", test_pass, test_count, test_pass * 100.0 / test_count); }
#include "lex_config.h" #include "test.h" #include "token.h" #include "symseg.h" #include "lex.h" /* * Simple Test Framework */ #define EXPECT_EQ_BASE(equality,expect,actual,format) \ do { \ test_count++; \ if (equality){ \ test_pass++;\ }else{ \ main_ret = 1; \ fprintf(stderr,"%s:%d: expect: " format " actual: " format "\n",__FILE__,__LINE__,expect,actual);\ } \ }while (0) #define EXPECT_EQ_INT(expect, actual) EXPECT_EQ_BASE((expect) == (actual), expect, actual, "%d") #define EXPECT_EQ_DOUBLE(expect, actual) EXPECT_EQ_BASE((expect) == (actual), expect, actual, "%.17g") #define EXPECT_EQ_STRING(expect, actual, alength) \ EXPECT_EQ_BASE(sizeof(expect) - 1 == alength && memcmp(expect, actual, alength + 1) == 0, expect, actual, "%s") #define EXPECT_TRUE(actual) EXPECT_EQ_BASE((actual) != 0, "true", "false", "%s") #define EXPECT_FALSE(actual) EXPECT_EQ_BASE((actual) == 0, "false", "true", "%s") #define GET_TOKEN(idx) source_file.get_token(idx) extern std::string cur_line; extern line cur_line_info; extern source source_file; int test_count = 0; int test_pass = 0; int main_ret = 0; void test_lexer() { std::vector<std::string> test_operator = { " =!><+-*/%&|^>><<~&&||?:, ", " ()==!=>=<=+=-=*=/=%=&=|= ", " ^=>>=<<=[]{};++--->.:: ", }; std::vector<std::string> test_number = { " int a = 123; ", " int b = 123.456; ", " int c = 0xff00; ", " int d = 0123; ", }; std::vector<std::string> test_identifier = { " int a; ", " int _b; ", " int _c_d_1; ", }; std::vector<std::string> test_comment = { " //This is a single line comment ", " /* This is a ", " * multi-line ", " * ע ", " */ ", }; std::vector<std::string> test_literal = { " string s = \"hello, \\\"world\"; ", " char c = 'b'; ", }; std::vector<std::string> test_warning_and_error = { " int 3a; ", /* invalid identifier */ " ", /* unknown type name */ " int b = 123.456.789; ", /* too many decimal points in number */ " int c = 09; ", /* too many decimal points in number */ " string s = \"hello; ", /* missing terminating \" character */ " char cc = 'h; ", /* missing terminating \' character */ " cc = 'hello world'; ", /* character constant too long for its type */ }; for (std::string s : test_operator) { cur_line = s; cur_line_info++; lex(); } for (int i = 0; i < 46; i++) { EXPECT_EQ_INT(i, GET_TOKEN(i)); } printf("%d/%d (%3.2f%%) passed\n", test_pass, test_count, test_pass * 100.0 / test_count); }
remove a macro
remove a macro
C++
mit
Jameeeees/LambCompiler,Jameeeees/LambCompiler,Jameeeees/LambCompiler
b4446b1cc570b12607681f7b17e7b79700f917fc
src/test.cpp
src/test.cpp
#include <libunittest/all.hpp> #include "transwarp.h" #include <fstream> using transwarp::make_task; COLLECTION(test_transwarp) { void make_test_one_task(std::size_t threads) { const int value = 42; auto f1 = [value]{ return value; }; auto task = make_task(f1); task->finalize(); task->set_parallel(threads); ASSERT_EQUAL(0u, task->get_node().id); ASSERT_EQUAL(0u, task->get_node().level); ASSERT_EQUAL(0u, task->get_node().parents.size()); ASSERT_EQUAL("task0", task->get_node().name); const auto graph = task->get_graph(); ASSERT_EQUAL(0u, graph.size()); task->schedule(); auto future = task->get_future(); ASSERT_EQUAL(42, future.get()); } TEST(one_task) { make_test_one_task(0); make_test_one_task(1); make_test_one_task(2); make_test_one_task(3); make_test_one_task(4); } void make_test_three_tasks(std::size_t threads) { int value = 42; auto f1 = [&value]{ return value; }; auto task1 = make_task("t1", f1); auto f2 = [](int v) { return v + 2; }; auto task2 = make_task("\nt2\t", f2, task1); auto f3 = [](int v, int w) { return v + w + 3; }; auto task3 = make_task("t3 ", f3, task1, task2); task3->finalize(); task3->set_parallel(threads); ASSERT_EQUAL(1u, task1->get_node().id); ASSERT_EQUAL(2u, task1->get_node().level); ASSERT_EQUAL(0u, task1->get_node().parents.size()); ASSERT_EQUAL("t1", task1->get_node().name); ASSERT_EQUAL(2u, task2->get_node().id); ASSERT_EQUAL(1u, task2->get_node().level); ASSERT_EQUAL(1u, task2->get_node().parents.size()); ASSERT_EQUAL("\nt2\t", task2->get_node().name); ASSERT_EQUAL(0u, task3->get_node().id); ASSERT_EQUAL(0u, task3->get_node().level); ASSERT_EQUAL(2u, task3->get_node().parents.size()); ASSERT_EQUAL("t3 ", task3->get_node().name); task3->schedule(); ASSERT_EQUAL(89, task3->get_future().get()); ASSERT_EQUAL(42, task1->get_future().get()); ++value; task3->schedule(); ASSERT_EQUAL(91, task3->get_future().get()); ASSERT_EQUAL(43, task1->get_future().get()); const auto graph = task3->get_graph(); ASSERT_EQUAL(3u, graph.size()); const auto dot_graph = transwarp::make_dot_graph(graph); const std::string exp_dot_graph = "digraph {\n" "\"t1\n" "id 1 level 2 parents 0\" -> \"t3\n" "id 0 level 0 parents 2\"\n" "\"t2\n" "id 2 level 1 parents 1\" -> \"t3\n" "id 0 level 0 parents 2\"\n" "\"t1\n" "id 1 level 2 parents 0\" -> \"t2\n" "id 2 level 1 parents 1\"\n" "}\n"; ASSERT_EQUAL(exp_dot_graph, dot_graph); } TEST(three_tasks) { make_test_three_tasks(0); make_test_three_tasks(1); make_test_three_tasks(2); make_test_three_tasks(3); make_test_three_tasks(4); } void make_test_bunch_of_tasks(std::size_t threads) { auto f0 = []{ return 42; }; auto f1 = [](int a){ return 3 * a; }; auto f2 = [](int a, int b){ return a + b; }; auto f3 = [](int a, int b, int c){ return a + 2*b + c; }; auto task0 = make_task(f0); auto task1 = make_task(f0); auto task2 = make_task(f1, task1); auto task3 = make_task(f2, task2, task0); auto task5 = make_task(f2, task3, task2); auto task6 = make_task(f3, task1, task2, task5); auto task7 = make_task(f2, task5, task6); auto task8 = make_task(f2, task6, task7); auto task9 = make_task(f1, task7); auto task10 = make_task(f1, task9); auto task11 = make_task(f3, task10, task7, task8); auto task12 = make_task(f2, task11, task6); auto task13 = make_task(f3, task10, task11, task12); task13->finalize(); const auto task0_result = 42; const auto task3_result = 168; const auto task11_result = 11172; const auto exp_result = 42042; task13->schedule(); ASSERT_EQUAL(exp_result, task13->get_future().get()); ASSERT_EQUAL(task0_result, task0->get_future().get()); ASSERT_EQUAL(task3_result, task3->get_future().get()); ASSERT_EQUAL(task11_result, task11->get_future().get()); task13->set_parallel(threads); for (auto i=0; i<100; ++i) { task13->schedule(); ASSERT_EQUAL(task0_result, task0->get_future().get()); ASSERT_EQUAL(task3_result, task3->get_future().get()); ASSERT_EQUAL(task11_result, task11->get_future().get()); ASSERT_EQUAL(exp_result, task13->get_future().get()); } } TEST(bunch_of_tasks) { make_test_bunch_of_tasks(0); make_test_bunch_of_tasks(1); make_test_bunch_of_tasks(2); make_test_bunch_of_tasks(3); make_test_bunch_of_tasks(4); } TEST(not_finalized) { auto f1 = []{ return 42; }; auto task1 = make_task(f1); auto f2 = [](int v) { return v + 2; }; auto task2 = make_task(f2, task1); auto f3 = [](int v, int w) { return v + w + 3; }; auto task3 = make_task(f3, task1, task2); ASSERT_THROW(transwarp::task_error, [&task3]{ task3->set_parallel(2); }); ASSERT_THROW(transwarp::task_error, [&task3]{ task3->schedule(); }); ASSERT_THROW(transwarp::task_error, [&task3]{ task3->get_graph(); }); } TEST(already_finalized) { auto f1 = []{ return 42; }; auto task1 = make_task(f1); task1->finalize(); auto f2 = [](int v) { return v + 2; }; auto task2 = make_task(f2, task1); ASSERT_THROW(transwarp::task_error, [&task2]{ task2->finalize(); }); } TEST(transwarp_error) { const std::string msg = "text"; try { throw transwarp::transwarp_error(msg); } catch (const std::runtime_error& e) { ASSERT_EQUAL(msg, e.what()); } } TEST(task_error) { const std::string msg = "text"; try { throw transwarp::task_error(msg); } catch (const transwarp::transwarp_error& e) { ASSERT_EQUAL(msg, e.what()); } } TEST(pass_visitor) { transwarp::pass_visitor visitor; int value = 42; visitor(&value); ASSERT_EQUAL(42, value); } TEST(make_dot_graph_with_empty_graph) { const std::vector<transwarp::edge> graph; const auto dot_graph = transwarp::make_dot_graph(graph); const std::string exp_dot_graph = "digraph {\n}\n"; ASSERT_EQUAL(exp_dot_graph, dot_graph); } TEST(make_dot_graph_with_three_nodes) { const transwarp::node node2{1, 1, "node2", {}}; const transwarp::node node3{2, 1, "node3", {}}; const transwarp::node node1{0, 0, "node1", {&node2, &node3}}; std::vector<transwarp::edge> graph; graph.push_back({&node1, &node2}); graph.push_back({&node1, &node3}); const auto dot_graph = transwarp::make_dot_graph(graph); const std::string exp_dot_graph = "digraph {\n" "\"node2\n" "id 1 level 1 parents 0\" -> \"node1\n" "id 0 level 0 parents 2\"\n" "\"node3\n" "id 2 level 1 parents 0\" -> \"node1\n" "id 0 level 0 parents 2\"\n" "}\n"; ASSERT_EQUAL(exp_dot_graph, dot_graph); } TEST(get_functor) { auto f1 = [] { return 42; }; auto task1 = make_task(f1); ASSERT_TRUE(f1 == task1->get_functor()); } TEST(get_tasks) { auto f1 = [] { return 42; }; auto task1 = make_task(f1); static_assert(std::tuple_size<decltype(task1->get_tasks())>::value == 0, ""); auto f2 = [] { return 13; }; auto task2 = make_task(f2); static_assert(std::tuple_size<decltype(task2->get_tasks())>::value == 0, ""); auto f3 = [](int v, int w) { return v + w; }; auto task3 = make_task(f3, task1, task2); static_assert(std::tuple_size<decltype(task3->get_tasks())>::value == 2, ""); auto tasks = task3->get_tasks(); ASSERT_EQUAL(task1.get(), std::get<0>(tasks).get()); ASSERT_EQUAL(task2.get(), std::get<1>(tasks).get()); } TEST(get_node) { auto f1 = [] { return 42; }; auto task1 = make_task(f1); auto f2 = [] { return 13; }; auto task2 = make_task(f2); auto f3 = [](int v, int w) { return v + w; }; auto task3 = make_task(f3, task1, task2); task3->finalize(); // task3 ASSERT_EQUAL(0, task3->get_node().id); ASSERT_EQUAL(0, task3->get_node().level); ASSERT_EQUAL("task0", task3->get_node().name); ASSERT_EQUAL(2u, task3->get_node().parents.size()); ASSERT_EQUAL(&task1->get_node(), task3->get_node().parents[0]); ASSERT_EQUAL(&task2->get_node(), task3->get_node().parents[1]); // task1 ASSERT_EQUAL(1, task1->get_node().id); ASSERT_EQUAL(1, task1->get_node().level); ASSERT_EQUAL("task1", task1->get_node().name); ASSERT_EQUAL(0u, task1->get_node().parents.size()); // task2 ASSERT_EQUAL(2, task2->get_node().id); ASSERT_EQUAL(1, task2->get_node().level); ASSERT_EQUAL("task2", task2->get_node().name); ASSERT_EQUAL(0u, task2->get_node().parents.size()); } struct id_visitor { id_visitor() : count{1} {} template<typename Task> void operator()(Task* task) noexcept { const auto value = task->get_node().id; if (value % 2 == 0) count += value; else count *= value + 1; } std::size_t count; }; struct level_visitor { level_visitor() : count{1} {} template<typename Task> void operator()(Task* task) noexcept { const auto value = task->get_node().level; if (value % 2 == 0) count += value ; else count *= value + 1; } std::size_t count; }; TEST(visit_and_unvisit) { auto f1 = [] { return 0; }; auto task1 = make_task(f1); auto f2 = [] { return 0; }; auto task2 = make_task(f2); auto f3 = [](int, int) { return 0; }; auto task3 = make_task(f3, task1, task2); task3->finalize(); id_visitor pre; level_visitor post; task3->visit(pre, post); ASSERT_EQUAL(4, pre.count); ASSERT_EQUAL(4, post.count); pre.count = 1; post.count = 1; task3->visit(pre, post); ASSERT_EQUAL(1, pre.count); ASSERT_EQUAL(1, post.count); task3->unvisit(); task3->visit(pre, post); ASSERT_EQUAL(4, pre.count); ASSERT_EQUAL(4, post.count); } void make_test_task_with_exception_thrown(std::size_t threads) { auto f1 = [] { throw std::runtime_error("from f1"); return 42; }; auto f2 = [] (int x) { throw std::runtime_error("from f2"); return x + 13; }; auto f3 = [] (int x) { throw std::runtime_error("from f3"); return x + 1; }; auto task1 = make_task(f1); auto task2 = make_task(f2, task1); auto task3 = make_task(f3, task2); task3->finalize(); task3->set_parallel(threads); task3->schedule(); try { task3->get_future().get(); ASSERT_TRUE(false); } catch (const std::runtime_error& e) { ASSERT_EQUAL(std::string("from f1"), e.what()); } } TEST(task_with_exception_thrown) { make_test_task_with_exception_thrown(0); make_test_task_with_exception_thrown(1); make_test_task_with_exception_thrown(2); make_test_task_with_exception_thrown(3); make_test_task_with_exception_thrown(4); } }
#include <libunittest/all.hpp> #include "transwarp.h" using transwarp::make_task; COLLECTION(test_transwarp) { void make_test_one_task(std::size_t threads) { const int value = 42; auto f1 = [value]{ return value; }; auto task = make_task(f1); task->finalize(); task->set_parallel(threads); ASSERT_EQUAL(0u, task->get_node().id); ASSERT_EQUAL(0u, task->get_node().level); ASSERT_EQUAL(0u, task->get_node().parents.size()); ASSERT_EQUAL("task0", task->get_node().name); const auto graph = task->get_graph(); ASSERT_EQUAL(0u, graph.size()); task->schedule(); auto future = task->get_future(); ASSERT_EQUAL(42, future.get()); } TEST(one_task) { make_test_one_task(0); make_test_one_task(1); make_test_one_task(2); make_test_one_task(3); make_test_one_task(4); } void make_test_three_tasks(std::size_t threads) { int value = 42; auto f1 = [&value]{ return value; }; auto task1 = make_task("t1", f1); auto f2 = [](int v) { return v + 2; }; auto task2 = make_task("\nt2\t", f2, task1); auto f3 = [](int v, int w) { return v + w + 3; }; auto task3 = make_task("t3 ", f3, task1, task2); task3->finalize(); task3->set_parallel(threads); ASSERT_EQUAL(1u, task1->get_node().id); ASSERT_EQUAL(2u, task1->get_node().level); ASSERT_EQUAL(0u, task1->get_node().parents.size()); ASSERT_EQUAL("t1", task1->get_node().name); ASSERT_EQUAL(2u, task2->get_node().id); ASSERT_EQUAL(1u, task2->get_node().level); ASSERT_EQUAL(1u, task2->get_node().parents.size()); ASSERT_EQUAL("\nt2\t", task2->get_node().name); ASSERT_EQUAL(0u, task3->get_node().id); ASSERT_EQUAL(0u, task3->get_node().level); ASSERT_EQUAL(2u, task3->get_node().parents.size()); ASSERT_EQUAL("t3 ", task3->get_node().name); task3->schedule(); ASSERT_EQUAL(89, task3->get_future().get()); ASSERT_EQUAL(42, task1->get_future().get()); ++value; task3->schedule(); ASSERT_EQUAL(91, task3->get_future().get()); ASSERT_EQUAL(43, task1->get_future().get()); const auto graph = task3->get_graph(); ASSERT_EQUAL(3u, graph.size()); const auto dot_graph = transwarp::make_dot_graph(graph); const std::string exp_dot_graph = "digraph {\n" "\"t1\n" "id 1 level 2 parents 0\" -> \"t3\n" "id 0 level 0 parents 2\"\n" "\"t2\n" "id 2 level 1 parents 1\" -> \"t3\n" "id 0 level 0 parents 2\"\n" "\"t1\n" "id 1 level 2 parents 0\" -> \"t2\n" "id 2 level 1 parents 1\"\n" "}\n"; ASSERT_EQUAL(exp_dot_graph, dot_graph); } TEST(three_tasks) { make_test_three_tasks(0); make_test_three_tasks(1); make_test_three_tasks(2); make_test_three_tasks(3); make_test_three_tasks(4); } void make_test_bunch_of_tasks(std::size_t threads) { auto f0 = []{ return 42; }; auto f1 = [](int a){ return 3 * a; }; auto f2 = [](int a, int b){ return a + b; }; auto f3 = [](int a, int b, int c){ return a + 2*b + c; }; auto task0 = make_task(f0); auto task1 = make_task(f0); auto task2 = make_task(f1, task1); auto task3 = make_task(f2, task2, task0); auto task5 = make_task(f2, task3, task2); auto task6 = make_task(f3, task1, task2, task5); auto task7 = make_task(f2, task5, task6); auto task8 = make_task(f2, task6, task7); auto task9 = make_task(f1, task7); auto task10 = make_task(f1, task9); auto task11 = make_task(f3, task10, task7, task8); auto task12 = make_task(f2, task11, task6); auto task13 = make_task(f3, task10, task11, task12); task13->finalize(); const auto task0_result = 42; const auto task3_result = 168; const auto task11_result = 11172; const auto exp_result = 42042; task13->schedule(); ASSERT_EQUAL(exp_result, task13->get_future().get()); ASSERT_EQUAL(task0_result, task0->get_future().get()); ASSERT_EQUAL(task3_result, task3->get_future().get()); ASSERT_EQUAL(task11_result, task11->get_future().get()); task13->set_parallel(threads); for (auto i=0; i<100; ++i) { task13->schedule(); ASSERT_EQUAL(task0_result, task0->get_future().get()); ASSERT_EQUAL(task3_result, task3->get_future().get()); ASSERT_EQUAL(task11_result, task11->get_future().get()); ASSERT_EQUAL(exp_result, task13->get_future().get()); } } TEST(bunch_of_tasks) { make_test_bunch_of_tasks(0); make_test_bunch_of_tasks(1); make_test_bunch_of_tasks(2); make_test_bunch_of_tasks(3); make_test_bunch_of_tasks(4); } TEST(not_finalized) { auto f1 = []{ return 42; }; auto task1 = make_task(f1); auto f2 = [](int v) { return v + 2; }; auto task2 = make_task(f2, task1); auto f3 = [](int v, int w) { return v + w + 3; }; auto task3 = make_task(f3, task1, task2); ASSERT_THROW(transwarp::task_error, [&task3]{ task3->set_parallel(2); }); ASSERT_THROW(transwarp::task_error, [&task3]{ task3->schedule(); }); ASSERT_THROW(transwarp::task_error, [&task3]{ task3->get_graph(); }); } TEST(already_finalized) { auto f1 = []{ return 42; }; auto task1 = make_task(f1); task1->finalize(); auto f2 = [](int v) { return v + 2; }; auto task2 = make_task(f2, task1); ASSERT_THROW(transwarp::task_error, [&task2]{ task2->finalize(); }); } TEST(transwarp_error) { const std::string msg = "text"; try { throw transwarp::transwarp_error(msg); } catch (const std::runtime_error& e) { ASSERT_EQUAL(msg, e.what()); } } TEST(task_error) { const std::string msg = "text"; try { throw transwarp::task_error(msg); } catch (const transwarp::transwarp_error& e) { ASSERT_EQUAL(msg, e.what()); } } TEST(pass_visitor) { transwarp::pass_visitor visitor; int value = 42; visitor(&value); ASSERT_EQUAL(42, value); } TEST(make_dot_graph_with_empty_graph) { const std::vector<transwarp::edge> graph; const auto dot_graph = transwarp::make_dot_graph(graph); const std::string exp_dot_graph = "digraph {\n}\n"; ASSERT_EQUAL(exp_dot_graph, dot_graph); } TEST(make_dot_graph_with_three_nodes) { const transwarp::node node2{1, 1, "node2", {}}; const transwarp::node node3{2, 1, "node3", {}}; const transwarp::node node1{0, 0, "node1", {&node2, &node3}}; std::vector<transwarp::edge> graph; graph.push_back({&node1, &node2}); graph.push_back({&node1, &node3}); const auto dot_graph = transwarp::make_dot_graph(graph); const std::string exp_dot_graph = "digraph {\n" "\"node2\n" "id 1 level 1 parents 0\" -> \"node1\n" "id 0 level 0 parents 2\"\n" "\"node3\n" "id 2 level 1 parents 0\" -> \"node1\n" "id 0 level 0 parents 2\"\n" "}\n"; ASSERT_EQUAL(exp_dot_graph, dot_graph); } TEST(get_functor) { auto f1 = [] { return 42; }; auto task1 = make_task(f1); ASSERT_TRUE(f1 == task1->get_functor()); } TEST(get_tasks) { auto f1 = [] { return 42; }; auto task1 = make_task(f1); static_assert(std::tuple_size<decltype(task1->get_tasks())>::value == 0, ""); auto f2 = [] { return 13; }; auto task2 = make_task(f2); static_assert(std::tuple_size<decltype(task2->get_tasks())>::value == 0, ""); auto f3 = [](int v, int w) { return v + w; }; auto task3 = make_task(f3, task1, task2); static_assert(std::tuple_size<decltype(task3->get_tasks())>::value == 2, ""); auto tasks = task3->get_tasks(); ASSERT_EQUAL(task1.get(), std::get<0>(tasks).get()); ASSERT_EQUAL(task2.get(), std::get<1>(tasks).get()); } TEST(get_node) { auto f1 = [] { return 42; }; auto task1 = make_task(f1); auto f2 = [] { return 13; }; auto task2 = make_task(f2); auto f3 = [](int v, int w) { return v + w; }; auto task3 = make_task(f3, task1, task2); task3->finalize(); // task3 ASSERT_EQUAL(0, task3->get_node().id); ASSERT_EQUAL(0, task3->get_node().level); ASSERT_EQUAL("task0", task3->get_node().name); ASSERT_EQUAL(2u, task3->get_node().parents.size()); ASSERT_EQUAL(&task1->get_node(), task3->get_node().parents[0]); ASSERT_EQUAL(&task2->get_node(), task3->get_node().parents[1]); // task1 ASSERT_EQUAL(1, task1->get_node().id); ASSERT_EQUAL(1, task1->get_node().level); ASSERT_EQUAL("task1", task1->get_node().name); ASSERT_EQUAL(0u, task1->get_node().parents.size()); // task2 ASSERT_EQUAL(2, task2->get_node().id); ASSERT_EQUAL(1, task2->get_node().level); ASSERT_EQUAL("task2", task2->get_node().name); ASSERT_EQUAL(0u, task2->get_node().parents.size()); } struct id_visitor { id_visitor() : count{1} {} template<typename Task> void operator()(Task* task) noexcept { const auto value = task->get_node().id; if (value % 2 == 0) count += value; else count *= value + 1; } std::size_t count; }; struct level_visitor { level_visitor() : count{1} {} template<typename Task> void operator()(Task* task) noexcept { const auto value = task->get_node().level; if (value % 2 == 0) count += value ; else count *= value + 1; } std::size_t count; }; TEST(visit_and_unvisit) { auto f1 = [] { return 0; }; auto task1 = make_task(f1); auto f2 = [] { return 0; }; auto task2 = make_task(f2); auto f3 = [](int, int) { return 0; }; auto task3 = make_task(f3, task1, task2); task3->finalize(); id_visitor pre; level_visitor post; task3->visit(pre, post); ASSERT_EQUAL(4, pre.count); ASSERT_EQUAL(4, post.count); pre.count = 1; post.count = 1; task3->visit(pre, post); ASSERT_EQUAL(1, pre.count); ASSERT_EQUAL(1, post.count); task3->unvisit(); task3->visit(pre, post); ASSERT_EQUAL(4, pre.count); ASSERT_EQUAL(4, post.count); } void make_test_task_with_exception_thrown(std::size_t threads) { auto f1 = [] { throw std::runtime_error("from f1"); return 42; }; auto f2 = [] (int x) { throw std::runtime_error("from f2"); return x + 13; }; auto f3 = [] (int x) { throw std::runtime_error("from f3"); return x + 1; }; auto task1 = make_task(f1); auto task2 = make_task(f2, task1); auto task3 = make_task(f3, task2); task3->finalize(); task3->set_parallel(threads); task3->schedule(); try { task3->get_future().get(); ASSERT_TRUE(false); } catch (const std::runtime_error& e) { ASSERT_EQUAL(std::string("from f1"), e.what()); } } TEST(task_with_exception_thrown) { make_test_task_with_exception_thrown(0); make_test_task_with_exception_thrown(1); make_test_task_with_exception_thrown(2); make_test_task_with_exception_thrown(3); make_test_task_with_exception_thrown(4); } }
remove unused header
remove unused header
C++
mit
bloomen/transwarp,bloomen/transwarp,bloomen/transwarp
c1de51ba8439ae00ba01665f361691ada39e3946
src/util.cpp
src/util.cpp
#include <fstream> #ifdef PLATFORM_WINDOWS #include <windows.h> #include <Winerror.h> #include <shlobj.h> #elif defined(PLATFORM_OSX) #include <mach-o/dyld.h> #else #include <unistd.h> #include <linux/limits.h> #endif #include "util.hpp" #include "config.hpp" void replace_substr(std::string &tagetStr, const std::string find, const std::string replace) { size_t index = 0; while (true) { index = tagetStr.find(find, index); if (index == std::string::npos) { break; } tagetStr.replace(index, replace.size(), replace); index += replace.size(); } } std::string read_file(std::string filename, FileMode mode) { auto fileMode = std::ios::in | std::ios_base::ate; if (mode == FileMode::Binary) { fileMode |= std::ios_base::binary; } std::ifstream in(filename, fileMode); if (in) { std::string contents; contents.resize(static_cast<unsigned int>(in.tellg())); in.seekg(0, std::ios::beg); in.read(&contents[0], contents.size()); in.close(); return contents; } else { return ""; } } std::string get_base_path() // executable path { std::string basePath; #if defined(PLATFORM_WINDOWS) char buffer[MAX_PATH];//always use MAX_PATH for filepaths GetModuleFileName( NULL, buffer, sizeof(buffer) ); basePath = buffer; #elif defined(PLATFORM_OSX) char path[8192]; uint32_t size = sizeof(path); if ( _NSGetExecutablePath( path, &size ) < 0 ) { return ""; } basePath = path; #elif defined(PLATFORM_LINUX) char buff[PATH_MAX]; ssize_t len = ::readlink("/proc/self/exe", buff, sizeof(buff)-1); if (len != -1) { buff[len] = '\0'; basePath = buff; } else basePath = ""; #endif // remove executable name so we just have the path int pos = basePath.rfind( PATH_SEP ); basePath = basePath.substr( 0, pos+1 ); #if OSX_APP_BUNDLE appPath = basePath; // store full appPath // on osx we only want the path containing the app when checking BasePath pos = basePath.rfind( "MacOS" ); if ( pos != std::string::npos ) { basePath = basePath.substr( 0, pos+1 ); pos = basePath.rfind( "Contents" ); if ( pos != std::string::npos ) { basePath = basePath.substr( 0, pos+1 ); pos = basePath.rfind( APP_NAME ); if ( pos != std::string::npos ) basePath = basePath.substr( 0, pos ); } } #endif // Strip out weird occurances of /. at the end of the path std::string locator; locator.append(std::string(PATH_SEP)); locator.append("."); pos = basePath.rfind(locator); if (pos != std::string::npos) { basePath = basePath.substr(0, pos); } // Strip trailing slash if (basePath.compare(basePath.size()-1, 1, PATH_SEP) == 0) { basePath = basePath.substr(0, basePath.size()-1); } return basePath; } std::string expand_path(const std::string virPath) { std::string path = get_base_path(); std::string virPathCopy = virPath; replace_substr(virPathCopy, "/", PATH_SEP); path.append(virPath); return path; }
#include <fstream> #include "config.hpp" #if defined(PLATFORM_WINDOWS) #include <windows.h> #include <Winerror.h> #include <shlobj.h> #elif defined(PLATFORM_OSX) #include <mach-o/dyld.h> #else #include <unistd.h> #include <linux/limits.h> #endif #include "util.hpp" #include "config.hpp" void replace_substr(std::string &tagetStr, const std::string find, const std::string replace) { size_t index = 0; while (true) { index = tagetStr.find(find, index); if (index == std::string::npos) { break; } tagetStr.replace(index, replace.size(), replace); index += replace.size(); } } std::string read_file(std::string filename, FileMode mode) { auto fileMode = std::ios::in | std::ios_base::ate; if (mode == FileMode::Binary) { fileMode |= std::ios_base::binary; } std::ifstream in(filename, fileMode); if (in) { std::string contents; contents.resize(static_cast<unsigned int>(in.tellg())); in.seekg(0, std::ios::beg); in.read(&contents[0], contents.size()); in.close(); return contents; } else { return ""; } } std::string get_base_path() // executable path { std::string basePath; #if defined(PLATFORM_WINDOWS) char buffer[MAX_PATH];//always use MAX_PATH for filepaths GetModuleFileName( NULL, buffer, sizeof(buffer) ); basePath = buffer; #elif defined(PLATFORM_OSX) char path[8192]; uint32_t size = sizeof(path); if ( _NSGetExecutablePath( path, &size ) < 0 ) { return ""; } basePath = path; #elif defined(PLATFORM_LINUX) char buff[PATH_MAX]; ssize_t len = ::readlink("/proc/self/exe", buff, sizeof(buff)-1); if (len != -1) { buff[len] = '\0'; basePath = buff; } else basePath = ""; #endif // remove executable name so we just have the path int pos = basePath.rfind( PATH_SEP ); basePath = basePath.substr( 0, pos+1 ); #if OSX_APP_BUNDLE appPath = basePath; // store full appPath // on osx we only want the path containing the app when checking BasePath pos = basePath.rfind( "MacOS" ); if ( pos != std::string::npos ) { basePath = basePath.substr( 0, pos+1 ); pos = basePath.rfind( "Contents" ); if ( pos != std::string::npos ) { basePath = basePath.substr( 0, pos+1 ); pos = basePath.rfind( APP_NAME ); if ( pos != std::string::npos ) basePath = basePath.substr( 0, pos ); } } #endif // Strip out weird occurances of /. at the end of the path std::string locator; locator.append(std::string(PATH_SEP)); locator.append("."); pos = basePath.rfind(locator); if (pos != std::string::npos) { basePath = basePath.substr(0, pos); } // Strip trailing slash if (basePath.compare(basePath.size()-1, 1, PATH_SEP) == 0) { basePath = basePath.substr(0, basePath.size()-1); } return basePath; } std::string expand_path(const std::string virPath) { std::string path = get_base_path(); std::string virPathCopy = virPath; replace_substr(virPathCopy, "/", PATH_SEP); path.append(virPath); return path; }
Fix preprocessor issues.
Fix preprocessor issues.
C++
bsd-2-clause
mdsitton/atlas-test,mdsitton/atlas-test