text
stringlengths
54
60.6k
<commit_before>#include "acf_depth_channel.hpp" #include <csapex/msg/io.h> #include <csapex/msg/generic_vector_message.hpp> #include <csapex/model/node_modifier.h> #include <csapex/param/parameter_factory.h> #include <csapex/utility/register_apex_plugin.h> #include <csapex_opencv/cv_mat_message.h> #include <csapex_opencv/roi_message.h> #include <csapex_ml/features_message.h> CSAPEX_REGISTER_CLASS(csapex::vision::ACFDepthChannel, csapex::Node) using namespace csapex; using namespace csapex::vision; using namespace csapex::connection_types; void ACFDepthChannel::setup(csapex::NodeModifier& node_modifier) { in_image_ = node_modifier.addInput<CvMatMessage>("Depth Map"); in_rois_ = node_modifier.addOptionalInput<GenericVectorMessage, RoiMessage>("ROIs"); out_channels_ = node_modifier.addOutput<GenericVectorMessage, FeaturesMessage>("Channel Features"); out_visualize_ = node_modifier.addOutput<CvMatMessage>("Visualize"); } void ACFDepthChannel::setupParameters(csapex::Parameterizable& parameters) { parameters.addParameter(param::ParameterFactory::declareRange("window/width", 10, 1024, 64, 1), std::bind(&ACFDepthChannel::updateWindow, this)); parameters.addParameter(param::ParameterFactory::declareRange("window/height", 10, 1024, 128, 1), std::bind(&ACFDepthChannel::updateWindow, this)); parameters.addParameter(param::ParameterFactory::declareBool("window/keep_ratio", false), keep_ratio_); parameters.addParameter(param::ParameterFactory::declareBool("window/mirror", false), mirror_); parameters.addParameter(param::ParameterFactory::declareRange("aggregate/block_size", 1, 32, 4, 1), block_size_); static const std::map<std::string, int> available_types = { { "binary", static_cast<int>(Type::BINARY) }, { "ternary", static_cast<int>(Type::TERNARY) }, }; parameters.addParameter(param::ParameterFactory::declareParameterSet("channel/type", available_types, static_cast<int>(Type::BINARY)), reinterpret_cast<int&>(type_)); static const std::map<std::string, int> available_methods = { { "median", static_cast<int>(Method::MEDIAN) }, { "mean", static_cast<int>(Method::MEAN) }, { "histogram", static_cast<int>(Method::HISTOGRAM) }, }; parameters.addParameter(param::ParameterFactory::declareParameterSet("channel/method", available_methods, static_cast<int>(Method::MEDIAN)), reinterpret_cast<int&>(method_)); parameters.addParameter(param::ParameterFactory::declareRange("channel/threshold", 0.0, 1000.0, 0.1, 0.01), threshold_); parameters.addParameter(param::ParameterFactory::declareBool("channel/normalize", false), normalize_); } void ACFDepthChannel::updateWindow() { int old_height = window_height_; window_width_ = readParameter<int>("window/width"); window_height_ = readParameter<int>("window/height"); if (window_ratio_ == 0.0) window_ratio_ = window_height_ / double(window_width_); if (keep_ratio_) { if (window_height_ != old_height) { window_width_ = window_height_ / window_ratio_; setParameter<int>("window/width", window_width_); } else { window_height_ = window_width_ * window_ratio_; setParameter<int>("window/height", window_height_); } } } std::vector<float> ACFDepthChannel::extractChannel(const cv::Mat& depth_map) const { cv::Mat aggregated_depth_map; cv::resize(depth_map, aggregated_depth_map, cv::Size(depth_map.cols / block_size_, depth_map.rows / block_size_)); const cv::Mat valid_pixel_mask = aggregated_depth_map != 0; double min_value; double max_value; cv::minMaxLoc(aggregated_depth_map, &min_value, &max_value); float center = 0.0f; switch (method_) { case Method::HISTOGRAM: { const const float BIN_SIZE = 0.25f; static const int channels[] = { 0 }; const int bins[] = { int((max_value - min_value) / BIN_SIZE) }; const float value_range[] = { float(min_value), float(max_value) + std::numeric_limits<float>::epsilon() }; const float* ranges[] = { value_range }; cv::Mat hist; cv::calcHist(&aggregated_depth_map, 1, channels, valid_pixel_mask, hist, 1, bins, ranges, true); cv::Point max; cv::minMaxLoc(hist, nullptr, nullptr, nullptr, &max); center = min_value + (max.y + 0.5f) * BIN_SIZE; break; } case Method::MEDIAN: { cv::Mat values = aggregated_depth_map.reshape(0, 1).clone(); const auto middle = values.cols / 2; std::nth_element(values.begin<float>(), values.begin<float>() + middle, values.end<float>()); center = values.at<float>(0, middle); break; } case Method::MEAN: center = cv::mean(aggregated_depth_map)[0]; break; } std::vector<float> feature; feature.reserve(aggregated_depth_map.rows * aggregated_depth_map.cols); switch (type_) { case Type::TERNARY: std::transform(aggregated_depth_map.begin<float>(), aggregated_depth_map.end<float>(), std::back_inserter(feature), [&](float value) { if (normalize_) { const float delta = value - center; if (delta > threshold_) return delta / float(max_value - (center + threshold_)); else if (delta < -threshold_) return delta / float(center - threshold_ - min_value); else return 0.f; } else { if (value > center + threshold_) return 1.f; else if (value < center - threshold_) return -1.f; else return 0.f; } }); break; case Type::BINARY: std::transform(aggregated_depth_map.begin<float>(), aggregated_depth_map.end<float>(), std::back_inserter(feature), [&](float value) { if (normalize_) { const float delta = value - center; if (delta > threshold_) return delta / float(max_value - (center + threshold_)); else if (delta < -threshold_) return -delta / float(center - threshold_ - min_value); else return 0.f; } else { if (std::abs(value - center) > threshold_) return 1.f; else return 0.f; } }); break; } return std::move(feature); } void ACFDepthChannel::process() { CvMatMessage::ConstPtr in_image = msg::getMessage<CvMatMessage>(in_image_); const cv::Mat& image = in_image->value; std::shared_ptr<std::vector<RoiMessage> const> in_rois; if (msg::hasMessage(in_rois_)) in_rois = msg::getMessage<GenericVectorMessage, RoiMessage>(in_rois_); if (image.channels() != 1 || image.type() != CV_32F) throw std::runtime_error("Only 1 channel float images (depth maps) are supported"); CvMatMessage::Ptr out_visualize; if (msg::isConnected(out_visualize_)) { out_visualize = std::make_shared<CvMatMessage>(enc::bgr, in_image->stamp_micro_seconds); out_visualize->frame_id = in_image->frame_id; out_visualize->value = cv::Mat(image.rows, image.cols, CV_8UC3, cv::Scalar(0, 0, 0)); } auto out_features = std::make_shared<std::vector<FeaturesMessage>>(); const auto process_roi = [&](const Roi& roi) { const cv::Rect roi_region = roi.rect() & cv::Rect(0, 0, image.cols, image.rows); FeaturesMessage feature(in_image->stamp_micro_seconds); feature.classification = roi.classification(); cv::Mat image_region; cv::resize(cv::Mat(image, roi_region), image_region, cv::Size(window_width_, window_height_)); feature.value = extractChannel(image_region); out_features->push_back(feature); if (out_visualize) { const float scale_x = float(image_region.cols / block_size_) / roi_region.width; const float scale_y = float(image_region.rows / block_size_) / roi_region.height; for (int dy = 0; dy < roi_region.height; ++dy) for (int dx = 0; dx < roi_region.width; ++dx) { const int ldx = dx * scale_x; const int ldy = dy * scale_y; const int step = window_width_ / block_size_; const float value = feature.value[ldx + step * ldy]; cv::Vec3b& dst = out_visualize->value.at<cv::Vec3b>(roi_region.y + dy, roi_region.x + dx); if (value == 0) dst = cv::Vec3b(0, 255, 0); else if (value < 0) dst = cv::Vec3b(0, 0, 255) * std::abs(value); else if (value > 0) dst = cv::Vec3b(255, 0, 0) * std::abs(value); } } if (mirror_) { cv::flip(image_region, image_region, 1); feature.value = extractChannel(image_region); out_features->push_back(std::move(feature)); } }; if (in_rois) { for (const RoiMessage& roi : *in_rois) process_roi(roi.value); } else process_roi(csapex::Roi(0, 0, image.cols, image.rows)); msg::publish<GenericVectorMessage, FeaturesMessage>(out_channels_, out_features); if (out_visualize) msg::publish(out_visualize_, out_visualize); } <commit_msg>vision: ACFDepthChannel - filter valid points in all methods<commit_after>#include "acf_depth_channel.hpp" #include <csapex/msg/io.h> #include <csapex/msg/generic_vector_message.hpp> #include <csapex/model/node_modifier.h> #include <csapex/param/parameter_factory.h> #include <csapex/utility/register_apex_plugin.h> #include <csapex_opencv/cv_mat_message.h> #include <csapex_opencv/roi_message.h> #include <csapex_ml/features_message.h> CSAPEX_REGISTER_CLASS(csapex::vision::ACFDepthChannel, csapex::Node) using namespace csapex; using namespace csapex::vision; using namespace csapex::connection_types; void ACFDepthChannel::setup(csapex::NodeModifier& node_modifier) { in_image_ = node_modifier.addInput<CvMatMessage>("Depth Map"); in_rois_ = node_modifier.addOptionalInput<GenericVectorMessage, RoiMessage>("ROIs"); out_channels_ = node_modifier.addOutput<GenericVectorMessage, FeaturesMessage>("Channel Features"); out_visualize_ = node_modifier.addOutput<CvMatMessage>("Visualize"); } void ACFDepthChannel::setupParameters(csapex::Parameterizable& parameters) { parameters.addParameter(param::ParameterFactory::declareRange("window/width", 10, 1024, 64, 1), std::bind(&ACFDepthChannel::updateWindow, this)); parameters.addParameter(param::ParameterFactory::declareRange("window/height", 10, 1024, 128, 1), std::bind(&ACFDepthChannel::updateWindow, this)); parameters.addParameter(param::ParameterFactory::declareBool("window/keep_ratio", false), keep_ratio_); parameters.addParameter(param::ParameterFactory::declareBool("window/mirror", false), mirror_); parameters.addParameter(param::ParameterFactory::declareRange("aggregate/block_size", 1, 32, 4, 1), block_size_); static const std::map<std::string, int> available_types = { { "binary", static_cast<int>(Type::BINARY) }, { "ternary", static_cast<int>(Type::TERNARY) }, }; parameters.addParameter(param::ParameterFactory::declareParameterSet("channel/type", available_types, static_cast<int>(Type::BINARY)), reinterpret_cast<int&>(type_)); static const std::map<std::string, int> available_methods = { { "median", static_cast<int>(Method::MEDIAN) }, { "mean", static_cast<int>(Method::MEAN) }, { "histogram", static_cast<int>(Method::HISTOGRAM) }, }; parameters.addParameter(param::ParameterFactory::declareParameterSet("channel/method", available_methods, static_cast<int>(Method::MEDIAN)), reinterpret_cast<int&>(method_)); parameters.addParameter(param::ParameterFactory::declareRange("channel/threshold", 0.0, 1000.0, 0.1, 0.01), threshold_); parameters.addParameter(param::ParameterFactory::declareBool("channel/normalize", false), normalize_); } void ACFDepthChannel::updateWindow() { int old_height = window_height_; window_width_ = readParameter<int>("window/width"); window_height_ = readParameter<int>("window/height"); if (window_ratio_ == 0.0) window_ratio_ = window_height_ / double(window_width_); if (keep_ratio_) { if (window_height_ != old_height) { window_width_ = window_height_ / window_ratio_; setParameter<int>("window/width", window_width_); } else { window_height_ = window_width_ * window_ratio_; setParameter<int>("window/height", window_height_); } } } std::vector<float> ACFDepthChannel::extractChannel(const cv::Mat& depth_map) const { cv::Mat aggregated_depth_map; cv::resize(depth_map, aggregated_depth_map, cv::Size(depth_map.cols / block_size_, depth_map.rows / block_size_)); const cv::Mat valid_pixel_mask = aggregated_depth_map > 0; double min_value; double max_value; cv::minMaxLoc(aggregated_depth_map, &min_value, &max_value); float center = 0.0f; switch (method_) { case Method::HISTOGRAM: { const static float BIN_SIZE = 0.25f; static const int channels[] = { 0 }; const int bins[] = { int((max_value - min_value) / BIN_SIZE) }; const float value_range[] = { float(min_value), float(max_value) + std::numeric_limits<float>::epsilon() }; const float* ranges[] = { value_range }; cv::Mat hist; cv::calcHist(&aggregated_depth_map, 1, channels, valid_pixel_mask, hist, 1, bins, ranges, true); cv::Point max; cv::minMaxLoc(hist, nullptr, nullptr, nullptr, &max); center = min_value + (max.y + 0.5f) * BIN_SIZE; break; } case Method::MEDIAN: { cv::Mat values = aggregated_depth_map.reshape(0, 1).clone(); const int invalid_pixel_count = values.cols - cv::countNonZero(valid_pixel_mask); const auto middle = invalid_pixel_count + (values.cols - invalid_pixel_count) / 2; std::nth_element(values.begin<float>(), values.begin<float>() + middle, values.end<float>()); center = values.at<float>(0, middle); break; } case Method::MEAN: center = cv::mean(aggregated_depth_map, valid_pixel_mask)[0]; break; } std::vector<float> feature; feature.reserve(aggregated_depth_map.rows * aggregated_depth_map.cols); switch (type_) { case Type::TERNARY: std::transform(aggregated_depth_map.begin<float>(), aggregated_depth_map.end<float>(), std::back_inserter(feature), [&](float value) { if (normalize_) { const float delta = value - center; if (delta > threshold_) return delta / float(max_value - (center + threshold_)); else if (delta < -threshold_) return delta / float(center - threshold_ - min_value); else return 0.f; } else { if (value > center + threshold_) return 1.f; else if (value < center - threshold_) return -1.f; else return 0.f; } }); break; case Type::BINARY: std::transform(aggregated_depth_map.begin<float>(), aggregated_depth_map.end<float>(), std::back_inserter(feature), [&](float value) { if (normalize_) { const float delta = value - center; if (delta > threshold_) return delta / float(max_value - (center + threshold_)); else if (delta < -threshold_) return -delta / float(center - threshold_ - min_value); else return 0.f; } else { if (std::abs(value - center) > threshold_) return 1.f; else return 0.f; } }); break; } return std::move(feature); } void ACFDepthChannel::process() { CvMatMessage::ConstPtr in_image = msg::getMessage<CvMatMessage>(in_image_); const cv::Mat& image = in_image->value; std::shared_ptr<std::vector<RoiMessage> const> in_rois; if (msg::hasMessage(in_rois_)) in_rois = msg::getMessage<GenericVectorMessage, RoiMessage>(in_rois_); if (image.channels() != 1 || image.type() != CV_32F) throw std::runtime_error("Only 1 channel float images (depth maps) are supported"); CvMatMessage::Ptr out_visualize; if (msg::isConnected(out_visualize_)) { out_visualize = std::make_shared<CvMatMessage>(enc::bgr, in_image->stamp_micro_seconds); out_visualize->frame_id = in_image->frame_id; out_visualize->value = cv::Mat(image.rows, image.cols, CV_8UC3, cv::Scalar(0, 0, 0)); } auto out_features = std::make_shared<std::vector<FeaturesMessage>>(); const auto process_roi = [&](const Roi& roi) { const cv::Rect roi_region = roi.rect() & cv::Rect(0, 0, image.cols, image.rows); FeaturesMessage feature(in_image->stamp_micro_seconds); feature.classification = roi.classification(); cv::Mat image_region; cv::resize(cv::Mat(image, roi_region), image_region, cv::Size(window_width_, window_height_)); feature.value = extractChannel(image_region); out_features->push_back(feature); if (out_visualize) { const float scale_x = float(image_region.cols / block_size_) / roi_region.width; const float scale_y = float(image_region.rows / block_size_) / roi_region.height; for (int dy = 0; dy < roi_region.height; ++dy) for (int dx = 0; dx < roi_region.width; ++dx) { const int ldx = dx * scale_x; const int ldy = dy * scale_y; const int step = window_width_ / block_size_; const float value = feature.value[ldx + step * ldy]; cv::Vec3b& dst = out_visualize->value.at<cv::Vec3b>(roi_region.y + dy, roi_region.x + dx); if (value == 0) dst = cv::Vec3b(0, 255, 0); else if (value < 0) dst = cv::Vec3b(0, 0, 255) * std::abs(value); else if (value > 0) dst = cv::Vec3b(255, 0, 0) * std::abs(value); } } if (mirror_) { cv::flip(image_region, image_region, 1); feature.value = extractChannel(image_region); out_features->push_back(std::move(feature)); } }; if (in_rois) { for (const RoiMessage& roi : *in_rois) process_roi(roi.value); } else process_roi(csapex::Roi(0, 0, image.cols, image.rows)); msg::publish<GenericVectorMessage, FeaturesMessage>(out_channels_, out_features); if (out_visualize) msg::publish(out_visualize_, out_visualize); } <|endoftext|>
<commit_before>// This Source Code Form is licensed MPL-2.0: http://mozilla.org/MPL/2.0 #include <bse/bsemain.hh> #include <bse/testing.hh> #include "bse/internal.hh" using Bse::printerr; typedef Bse::IntegrityCheck::TestFunc TestFunc; // == BSE_INTEGRITY_TEST Registry == struct TestEntry { TestFunc test; const char *func; const char *file; int line; TestEntry (const char *_file, int _line, const char *_func, TestFunc _test) : test (_test), func (_func), file (_file), line (_line) {} }; static std::vector<TestEntry> *tests = NULL; // NOTE, this must be available for high priority early constructors // == BSE_INTEGRITY_CHECK Activation == namespace Bse { // Override Bse weak symbol to enable Bse's internal integrity tests, see bcore.hh const bool IntegrityCheck::enabled = true; // Registration function called for all integrity tests void IntegrityCheck::Test::register_test (const char *file, int line, const char *func, TestFunc test) { if (!tests) tests = new std::vector<TestEntry>(); tests->push_back (TestEntry (file, line, func, test)); } } // Bse static int // for backtrace tests my_compare_func (const void*, const void*) { BSE_BACKTRACE(); exit (0); } // == Main test program == int main (int argc, char *argv[]) { bse_init_test (&argc, argv); if (argc >= 2 && String ("--backtrace") == argv[1]) { char dummy_array[3] = { 1, 2, 3 }; qsort (dummy_array, 3, 1, my_compare_func); } else if (argc >= 2 && String ("--assert_return1") == argv[1]) { assert_return (1, 0); return 0; } else if (argc >= 2 && String ("--assert_return0") == argv[1]) { Bse::set_debug_flags (Bse::DebugFlags::SIGQUIT_ON_ABORT); assert_return (0, 0); return 0; } else if (argc >= 2 && String ("--assert_return_unreached") == argv[1]) { Bse::set_debug_flags (Bse::DebugFlags::SIGQUIT_ON_ABORT); assert_return_unreached (0); return 0; } else if (argc >= 2 && String ("--fatal_error") == argv[1]) { Bse::set_debug_flags (Bse::DebugFlags::SIGQUIT_ON_ABORT); Bse::fatal_error ("got argument --fatal_error"); return 0; } else if (argc >= 2 && String ("--return_unless0") == argv[1]) { return_unless (0, 7); return 0; } else if (argc >= 2 && String ("--return_unless1") == argv[1]) { return_unless (1, 8); return 0; } // integrity tests assert_return (Bse::IntegrityCheck::checks_enabled() == true, -1); if (tests) for (const auto &te : *tests) { // note, more than one space after "TESTING:" confuses emacs file:line matches printerr (" TESTING: %s:%u: %s…\n", te.file, te.line, te.func); te.test(); printerr (" …DONE (%s)\n", te.func); } return 0; } <commit_msg>BSE: integrity: always use SIGQUIT instead of abort() to avoid apport<commit_after>// This Source Code Form is licensed MPL-2.0: http://mozilla.org/MPL/2.0 #include <bse/bsemain.hh> #include <bse/testing.hh> #include "bse/internal.hh" using Bse::printerr; typedef Bse::IntegrityCheck::TestFunc TestFunc; // == BSE_INTEGRITY_TEST Registry == struct TestEntry { TestFunc test; const char *func; const char *file; int line; TestEntry (const char *_file, int _line, const char *_func, TestFunc _test) : test (_test), func (_func), file (_file), line (_line) {} }; static std::vector<TestEntry> *tests = NULL; // NOTE, this must be available for high priority early constructors // == BSE_INTEGRITY_CHECK Activation == namespace Bse { // Override Bse weak symbol to enable Bse's internal integrity tests, see bcore.hh const bool IntegrityCheck::enabled = true; // Registration function called for all integrity tests void IntegrityCheck::Test::register_test (const char *file, int line, const char *func, TestFunc test) { if (!tests) tests = new std::vector<TestEntry>(); tests->push_back (TestEntry (file, line, func, test)); } } // Bse static int // for backtrace tests my_compare_func (const void*, const void*) { BSE_BACKTRACE(); exit (0); } // == Main test program == int main (int argc, char *argv[]) { bse_init_test (&argc, argv); Bse::set_debug_flags (Bse::DebugFlags::SIGQUIT_ON_ABORT); if (argc >= 2 && String ("--backtrace") == argv[1]) { char dummy_array[3] = { 1, 2, 3 }; qsort (dummy_array, 3, 1, my_compare_func); } else if (argc >= 2 && String ("--assert_return1") == argv[1]) { assert_return (1, 0); return 0; } else if (argc >= 2 && String ("--assert_return0") == argv[1]) { assert_return (0, 0); return 0; } else if (argc >= 2 && String ("--assert_return_unreached") == argv[1]) { assert_return_unreached (0); return 0; } else if (argc >= 2 && String ("--fatal_error") == argv[1]) { Bse::fatal_error ("got argument --fatal_error"); return 0; } else if (argc >= 2 && String ("--return_unless0") == argv[1]) { return_unless (0, 7); return 0; } else if (argc >= 2 && String ("--return_unless1") == argv[1]) { return_unless (1, 8); return 0; } // integrity tests assert_return (Bse::IntegrityCheck::checks_enabled() == true, -1); if (tests) for (const auto &te : *tests) { // note, more than one space after "TESTING:" confuses emacs file:line matches printerr (" TESTING: %s:%u: %s…\n", te.file, te.line, te.func); te.test(); printerr (" …DONE (%s)\n", te.func); } return 0; } <|endoftext|>
<commit_before>#include "stdafx.h" #include "GSCameraPlayer.h" #include "IpCameraPipeline.h" #include "WebCameraPipeline.h" using namespace vosvideo::cameraplayer; GSCameraPlayer::GSCameraPlayer() { LOG_TRACE("GSCameraPlayer created"); } GSCameraPlayer::~GSCameraPlayer() { LOG_TRACE("GSCameraPlayer destroying camera player"); delete _pipeline; } int32_t GSCameraPlayer::OpenURL(vosvideo::data::CameraConfMsg& cameraConf) { if (_state == PlayerState::OpenPending || _state == PlayerState::Started || _state == PlayerState::Paused || _state == PlayerState::Stopped || _state == PlayerState::Closing) { return -1; } std::wstring waudioUri; std::wstring wvideoUri; cameraConf.GetUris(waudioUri, wvideoUri); _deviceId = cameraConf.GetCameraId(); _deviceName = cameraConf.GetCameraName(); std::wstring username; std::wstring password; cameraConf.GetCredentials(username, password); bool isRecordingEnabled = false; std::wstring recordingFolder; uint32_t recordingLength = 0; uint32_t maxFilesNum = 0; vosvideo::data::CameraRecordingMode recordingMode; cameraConf.GetFileSinkParameters(isRecordingEnabled, recordingFolder, recordingLength, maxFilesNum, recordingMode); cameraType_ = cameraConf.GetCameraType(); if (wvideoUri != L"webcamera") { _pipeline = new IpCameraPipeline( util::StringUtil::ToString(wvideoUri), username, password, isRecordingEnabled, recordingMode, recordingFolder, recordingLength, maxFilesNum, _deviceName); } else { _pipeline = new WebCameraPipeline( isRecordingEnabled, recordingMode, recordingFolder, recordingLength, maxFilesNum, _deviceName); } _pipeline->Create(); ////Need to convert to std::string due to LOG_TRACE not working with std::wstring //this->_deviceVideoUri = std::string(wvideoUri.begin(), wvideoUri.end()); //std::string audioUri(waudioUri.begin(), waudioUri.end()); //LOG_TRACE("GSCameraPlayer Opening Video URI " << this->_deviceVideoUri << " Audio URI " << audioUri); //this->_appThread = new boost::thread(boost::bind(&GSCameraPlayer::AppThreadStart, this)); //this->_appThread->detach(); _state = PlayerState::OpenPending; return 0; } void GSCameraPlayer::GetWebRtcCapability(webrtc::VideoCaptureCapability& webRtcCapability) { LOG_TRACE("GSCameraPlayer GetWebRtcCapability called"); _pipeline->GetWebRtcCapability(webRtcCapability); } int32_t GSCameraPlayer::Play(){ LOG_TRACE("GSCameraPlayer Play called"); return -1; } int32_t GSCameraPlayer::Pause() { LOG_TRACE("GSCameraPlayer Paused called"); return -1; } int32_t GSCameraPlayer::Stop() { LOG_TRACE("GSCameraPlayer Stop called"); return -1; } int32_t GSCameraPlayer::Shutdown() { LOG_TRACE("GSCameraPlayer Shutdown called"); return -1; } PlayerState GSCameraPlayer::GetState(std::shared_ptr<vosvideo::data::SendData>& lastErrMsg) const { LOG_TRACE("GSCameraPlayer GetState(shared_ptr) called"); return _state; } PlayerState GSCameraPlayer::GetState() const { LOG_TRACE("GSCameraPlayer GetState called"); return _state; } // Probably most important method, through it camera communicates to WebRTC void GSCameraPlayer::SetExternalCapturer(webrtc::VideoCaptureExternal* captureObserver) { LOG_TRACE("GSCameraPlayer SetExternalCapturer called"); _pipeline->AddExternalCapturer(captureObserver); } void GSCameraPlayer::RemoveExternalCapturers() { LOG_TRACE("GSCameraPlayer RemoveExternalCapturers called"); _pipeline->RemoveAllExternalCapturers(); } void GSCameraPlayer::RemoveExternalCapturer(webrtc::VideoCaptureExternal* captureObserver) { LOG_TRACE("GSCameraPlayer RemoveExternalCapturer called"); _pipeline->RemoveExternalCapturer(captureObserver); } uint32_t GSCameraPlayer::GetDeviceId() const { LOG_TRACE("GSCameraPlayer GetDeviceId called"); return _deviceId; } <commit_msg>Less traces<commit_after>#include "stdafx.h" #include "GSCameraPlayer.h" #include "IpCameraPipeline.h" #include "WebCameraPipeline.h" using namespace vosvideo::cameraplayer; GSCameraPlayer::GSCameraPlayer() { LOG_TRACE("GSCameraPlayer created"); } GSCameraPlayer::~GSCameraPlayer() { LOG_TRACE("GSCameraPlayer destroying camera player"); delete _pipeline; } int32_t GSCameraPlayer::OpenURL(vosvideo::data::CameraConfMsg& cameraConf) { if (_state == PlayerState::OpenPending || _state == PlayerState::Started || _state == PlayerState::Paused || _state == PlayerState::Stopped || _state == PlayerState::Closing) { return -1; } std::wstring waudioUri; std::wstring wvideoUri; cameraConf.GetUris(waudioUri, wvideoUri); _deviceId = cameraConf.GetCameraId(); _deviceName = cameraConf.GetCameraName(); std::wstring username; std::wstring password; cameraConf.GetCredentials(username, password); bool isRecordingEnabled = false; std::wstring recordingFolder; uint32_t recordingLength = 0; uint32_t maxFilesNum = 0; vosvideo::data::CameraRecordingMode recordingMode; cameraConf.GetFileSinkParameters(isRecordingEnabled, recordingFolder, recordingLength, maxFilesNum, recordingMode); cameraType_ = cameraConf.GetCameraType(); if (wvideoUri != L"webcamera") { _pipeline = new IpCameraPipeline( util::StringUtil::ToString(wvideoUri), username, password, isRecordingEnabled, recordingMode, recordingFolder, recordingLength, maxFilesNum, _deviceName); } else { _pipeline = new WebCameraPipeline( isRecordingEnabled, recordingMode, recordingFolder, recordingLength, maxFilesNum, _deviceName); } _pipeline->Create(); ////Need to convert to std::string due to LOG_TRACE not working with std::wstring //this->_deviceVideoUri = std::string(wvideoUri.begin(), wvideoUri.end()); //std::string audioUri(waudioUri.begin(), waudioUri.end()); //LOG_TRACE("GSCameraPlayer Opening Video URI " << this->_deviceVideoUri << " Audio URI " << audioUri); //this->_appThread = new boost::thread(boost::bind(&GSCameraPlayer::AppThreadStart, this)); //this->_appThread->detach(); _state = PlayerState::OpenPending; return 0; } void GSCameraPlayer::GetWebRtcCapability(webrtc::VideoCaptureCapability& webRtcCapability) { LOG_TRACE("GSCameraPlayer GetWebRtcCapability called"); _pipeline->GetWebRtcCapability(webRtcCapability); } int32_t GSCameraPlayer::Play(){ LOG_TRACE("GSCameraPlayer Play called"); return -1; } int32_t GSCameraPlayer::Pause() { LOG_TRACE("GSCameraPlayer Paused called"); return -1; } int32_t GSCameraPlayer::Stop() { LOG_TRACE("GSCameraPlayer Stop called"); return -1; } int32_t GSCameraPlayer::Shutdown() { LOG_TRACE("GSCameraPlayer Shutdown called"); return -1; } PlayerState GSCameraPlayer::GetState(std::shared_ptr<vosvideo::data::SendData>& lastErrMsg) const { LOG_TRACE("GSCameraPlayer GetState(shared_ptr) called"); return _state; } PlayerState GSCameraPlayer::GetState() const { return _state; } // Probably most important method, through it camera communicates to WebRTC void GSCameraPlayer::SetExternalCapturer(webrtc::VideoCaptureExternal* captureObserver) { LOG_TRACE("GSCameraPlayer SetExternalCapturer called"); _pipeline->AddExternalCapturer(captureObserver); } void GSCameraPlayer::RemoveExternalCapturers() { LOG_TRACE("GSCameraPlayer RemoveExternalCapturers called"); _pipeline->RemoveAllExternalCapturers(); } void GSCameraPlayer::RemoveExternalCapturer(webrtc::VideoCaptureExternal* captureObserver) { LOG_TRACE("GSCameraPlayer RemoveExternalCapturer called"); _pipeline->RemoveExternalCapturer(captureObserver); } uint32_t GSCameraPlayer::GetDeviceId() const { LOG_TRACE("GSCameraPlayer GetDeviceId called"); return _deviceId; } <|endoftext|>
<commit_before>#ifndef SKSAT_WINDOW_HPP #define SKSAT_WINDOW_HPP #include <sksat/common.hpp> #include <sksat/platform.hpp> namespace sksat { class window_base { public: window_base() : opend(false), xsize(default_xsize), ysize(default_ysize), xpos(default_xpos), ypos(default_ypos) {} window_base(size_t x, size_t y) : opend(false), xsize(x), ysize(y), xpos(default_xpos), ypos(default_ypos) {} window_base(sksat::string &t, size_t x, size_t y) : opend(false), title(t), xsize(x), ysize(y), xpos(default_xpos), ypos(default_ypos) {} void open(){ opend = api_open(); } void open(size_t x, size_t y){ open(); set_size(x,y); } void open(sksat::string &t){ set_title(t); open(); } void open(sksat::string &t, size_t x, size_t y){ set_title(t); open(x,y); } void close(){ if(opend) api_close(); opend=false; } void show(){ if(opend) api_show(); } void set_title(sksat::string &t){ title = t; set_title(t.c_str()); } void set_title(const char *t){ title = t; api_set_title(t); } sksat::string get_title() const { return title; } virtual void set_size(size_t x, size_t y){ xsize=x; ysize=y; if(opend) api_set_size(x,y); } void set_xsize(size_t x){ set_size(x, ysize); } void set_ysize(size_t y){ set_size(xsize, y); } size_t get_xsize() const { return xsize; } size_t get_ysize() const { return ysize; } operator bool () const { return opend; } // 描画関数 /* void draw_point(sksat::color &col, size_t x, size_t y); void draw_line(sksat::color &col, size_t x0, size_t y0, size_t x1, size_t y1); void draw_rect(sksat::color &col, size_t x0, size_t y0, size_t x1, size_t y1, bool fill); // set_color()でセットした色 void draw_point(size_t x, size_t y); void draw_line(size_t x0, size_t y0, size_t x1, size_t y1); void draw_rect(size_t x0, size_t y0, size_t x1, size_t y1, bool fill); void fill_rect(size_t x0, size_t y0, size_t x1, size_t y1){ draw_rect(x0,y0,x1,y1,true); } */ inline void flush(){ if(opend) api_flush(); } inline bool step_loop(){ if(opend) return api_step_loop(); } inline void loop(){ while(api_step_loop()); } protected: // 環境依存部(純粋仮想関数) virtual bool api_open() = 0; virtual void api_close() = 0; virtual void api_show() = 0; virtual void api_set_title(const char *t) = 0; virtual void api_set_size(size_t x, size_t y) = 0; virtual void api_flush() = 0; virtual bool api_step_loop() = 0; public: static size_t default_xsize, default_ysize; static size_t default_xpos, default_ypos; protected: bool opend; size_t xsize, ysize; size_t xpos, ypos; sksat::string title; }; size_t window_base::default_xsize = 100; size_t window_base::default_ysize = 100; size_t window_base::default_xpos = 0; size_t window_base::default_ypos = 0; } #if defined(OS_WIN32) #include <sksat/win32/window.hpp> namespace sksat{ using sksat::win32::window; } #elif defined(OS_LINUX) #include <sksat/linux/window.hpp> namespace sksat{ using sksat::linux::window; } #else #error not implemented. #endif #endif <commit_msg>[ADD] move func<commit_after>#ifndef SKSAT_WINDOW_HPP #define SKSAT_WINDOW_HPP #include <sksat/common.hpp> #include <sksat/platform.hpp> namespace sksat { class window_base { public: window_base() : opend(false), xsize(default_xsize), ysize(default_ysize), xpos(default_xpos), ypos(default_ypos) {} window_base(size_t x, size_t y) : opend(false), xsize(x), ysize(y), xpos(default_xpos), ypos(default_ypos) {} window_base(sksat::string &t, size_t x, size_t y) : opend(false), title(t), xsize(x), ysize(y), xpos(default_xpos), ypos(default_ypos) {} void open(){ opend = api_open(); } void open(size_t x, size_t y){ open(); set_size(x,y); } void open(sksat::string &t){ set_title(t); open(); } void open(sksat::string &t, size_t x, size_t y){ set_title(t); open(x,y); } void close(){ if(opend) api_close(); opend=false; } void show(){ if(opend) api_show(); } void set_title(sksat::string &t){ title = t; set_title(t.c_str()); } void set_title(const char *t){ title = t; api_set_title(t); } sksat::string get_title() const { return title; } virtual void set_size(size_t x, size_t y){ xsize=x; ysize=y; if(opend) api_set_size(x,y); } void set_xsize(size_t x){ set_size(x, ysize); } void set_ysize(size_t y){ set_size(xsize, y); } size_t get_xsize() const { return xsize; } size_t get_ysize() const { return ysize; } void move(size_t x, size_t y){ xpos=x; ypos=y; api_move(x,y); } void set_pos(size_t x, size_t y){ move(x,y); } void set_xpos(size_t x){ move(x,ypos); } void set_ypos(size_t y){ move(xpos,y); } operator bool () const { return opend; } // 描画関数 /* void draw_point(sksat::color &col, size_t x, size_t y); void draw_line(sksat::color &col, size_t x0, size_t y0, size_t x1, size_t y1); void draw_rect(sksat::color &col, size_t x0, size_t y0, size_t x1, size_t y1, bool fill); // set_color()でセットした色 void draw_point(size_t x, size_t y); void draw_line(size_t x0, size_t y0, size_t x1, size_t y1); void draw_rect(size_t x0, size_t y0, size_t x1, size_t y1, bool fill); void fill_rect(size_t x0, size_t y0, size_t x1, size_t y1){ draw_rect(x0,y0,x1,y1,true); } */ inline void flush(){ if(opend) api_flush(); } inline bool step_loop(){ if(opend) return api_step_loop(); } inline void loop(){ while(api_step_loop()); } protected: // 環境依存部(純粋仮想関数) virtual bool api_open() = 0; virtual void api_close() = 0; virtual void api_show() = 0; virtual void api_set_title(const char *t) = 0; virtual void api_set_size(size_t x, size_t y) = 0; virtual void api_flush() = 0; virtual void api_move() = 0; virtual bool api_step_loop() = 0; public: static size_t default_xsize, default_ysize; static size_t default_xpos, default_ypos; protected: bool opend; size_t xsize, ysize; size_t xpos, ypos; sksat::string title; }; size_t window_base::default_xsize = 100; size_t window_base::default_ysize = 100; size_t window_base::default_xpos = 0; size_t window_base::default_ypos = 0; } #if defined(OS_WIN32) #include <sksat/win32/window.hpp> namespace sksat{ using sksat::win32::window; } #elif defined(OS_LINUX) #include <sksat/linux/window.hpp> namespace sksat{ using sksat::linux::window; } #else #error not implemented. #endif #endif <|endoftext|>
<commit_before>// Jubatus: Online machine learning framework for distributed environment // Copyright (C) 2012 Preferred Infrastructure and Nippon Telegraph and Telephone Corporation. // // 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA #include "weight_manager.hpp" #include <cmath> #include <string> #include <utility> #include "../common/type.hpp" #include "datum_to_fv_converter.hpp" namespace jubatus { namespace core { namespace fv_converter { namespace { struct is_zero { bool operator()(const std::pair<std::string, float>& p) { return p.second == 0; } }; } // namespace weight_manager::weight_manager() : diff_weights_(), master_weights_() { } void weight_manager::update_weight(const common::sfv_t& fv) { diff_weights_.update_document_frequency(fv); } void weight_manager::get_weight(common::sfv_t& fv) const { for (common::sfv_t::iterator it = fv.begin(); it != fv.end(); ++it) { double global_weight = get_global_weight(it->first); it->second *= global_weight; } fv.erase(remove_if(fv.begin(), fv.end(), is_zero()), fv.end()); } double weight_manager::get_global_weight(const std::string& key) const { size_t p = key.find_last_of('/'); if (p == std::string::npos) { return 1.0; } std::string type = key.substr(p + 1); if (type == "bin") { return 1.0; } else if (type == "idf") { double doc_count = get_document_count(); double doc_freq = get_document_frequency(key); return log((doc_count + 1) / (doc_freq + 1)); } else if (type == "weight") { p = key.find_last_of('#'); if (p == std::string::npos) { return 0; } else { return get_user_weight(key.substr(0, p)); } } else { return 1; } } void weight_manager::add_weight(const std::string& key, float weight) { diff_weights_.add_weight(key, weight); } } // namespace fv_converter } // namespace core } // namespace jubatus <commit_msg>add explicit cast for global_weight<commit_after>// Jubatus: Online machine learning framework for distributed environment // Copyright (C) 2012 Preferred Infrastructure and Nippon Telegraph and Telephone Corporation. // // 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA #include "weight_manager.hpp" #include <cmath> #include <string> #include <utility> #include "../common/type.hpp" #include "datum_to_fv_converter.hpp" namespace jubatus { namespace core { namespace fv_converter { namespace { struct is_zero { bool operator()(const std::pair<std::string, float>& p) { return p.second == 0; } }; } // namespace weight_manager::weight_manager() : diff_weights_(), master_weights_() { } void weight_manager::update_weight(const common::sfv_t& fv) { diff_weights_.update_document_frequency(fv); } void weight_manager::get_weight(common::sfv_t& fv) const { for (common::sfv_t::iterator it = fv.begin(); it != fv.end(); ++it) { double global_weight = get_global_weight(it->first); it->second = static_cast<float>(it->second * global_weight); } fv.erase(remove_if(fv.begin(), fv.end(), is_zero()), fv.end()); } double weight_manager::get_global_weight(const std::string& key) const { size_t p = key.find_last_of('/'); if (p == std::string::npos) { return 1.0; } std::string type = key.substr(p + 1); if (type == "bin") { return 1.0; } else if (type == "idf") { double doc_count = get_document_count(); double doc_freq = get_document_frequency(key); return log((doc_count + 1) / (doc_freq + 1)); } else if (type == "weight") { p = key.find_last_of('#'); if (p == std::string::npos) { return 0; } else { return get_user_weight(key.substr(0, p)); } } else { return 1; } } void weight_manager::add_weight(const std::string& key, float weight) { diff_weights_.add_weight(key, weight); } } // namespace fv_converter } // namespace core } // namespace jubatus <|endoftext|>
<commit_before>#include <ContextGDIPlus.h> #include "utf8.h" #include <cassert> bool canvas::ContextGDIPlus::is_initialized = false; ULONG_PTR canvas::ContextGDIPlus::m_gdiplusToken; using namespace std; using namespace canvas; static std::wstring convert_to_wstring(const std::string & input) { const char * str = input.c_str(); const char * str_i = str; const char * end = str + input.size(); std::wstring output; while (str_i < end) { output += (wchar_t)utf8::next(str_i, end); } return output; } static void toGDIPath(const Path2D & path, Gdiplus::GraphicsPath & output, float display_scale) { output.StartFigure(); Gdiplus::PointF current_pos; for (auto pc : path.getData()) { switch (pc.type) { case PathComponent::MOVE_TO: current_pos = Gdiplus::PointF(Gdiplus::REAL(pc.x0 * display_scale), Gdiplus::REAL(pc.y0 * display_scale)); break; case PathComponent::LINE_TO: { Gdiplus::PointF point(Gdiplus::REAL(pc.x0 * display_scale), Gdiplus::REAL(pc.y0 * display_scale)); output.AddLine(current_pos, point); current_pos = point; } break; case PathComponent::CLOSE: output.CloseFigure(); break; case PathComponent::ARC: { double span = 0; if (0 && ((!pc.anticlockwise && (pc.ea - pc.sa >= 2 * M_PI)) || (pc.anticlockwise && (pc.sa - pc.ea >= 2 * M_PI)))) { // If the anticlockwise argument is false and endAngle-startAngle is equal to or greater than 2*PI, or, if the // anticlockwise argument is true and startAngle-endAngle is equal to or greater than 2*PI, then the arc is the whole // circumference of this circle. span = 2 * M_PI; } else { if (!pc.anticlockwise && (pc.ea < pc.sa)) { span += 2 * M_PI; } else if (pc.anticlockwise && (pc.sa < pc.ea)) { span -= 2 * M_PI; } #if 0 // this is also due to switched coordinate system // we would end up with a 0 span instead of 360 if (!(qFuzzyCompare(span + (ea - sa) + 1, 1.0) && qFuzzyCompare(qAbs(span), 360.0))) { // mod 360 span += (ea - sa) - (static_cast<int>((ea - sa) / 360)) * 360; } #else span += pc.ea - pc.sa; #endif } #if 0 // If the path is empty, move to where the arc will start to avoid painting a line from (0,0) // NOTE: QPainterPath::isEmpty() won't work here since it ignores a lone MoveToElement if (!m_path.elementCount()) m_path.arcMoveTo(xs, ys, width, height, sa); else if (!radius) { m_path.lineTo(xc, yc); return; } #endif #if 0 if (anticlockwise) { span = -M_PI / 2.0; } else { span = M_PI / 2.0; } #endif Gdiplus::RectF rect(Gdiplus::REAL(pc.x0 * display_scale - pc.radius * display_scale), Gdiplus::REAL(pc.y0 * display_scale - pc.radius * display_scale), Gdiplus::REAL(2 * pc.radius * display_scale), Gdiplus::REAL(2 * pc.radius * display_scale)); output.AddArc(rect, Gdiplus::REAL(pc.sa * 180.0f / M_PI), Gdiplus::REAL(span * 180.0f / M_PI)); output.GetLastPoint(&current_pos); } break; } } } static Gdiplus::Color toGDIColor(const Color & input, float globalAlpha = 1.0f) { int red = int(input.red * 255), green = int(input.green * 255), blue = int(input.blue * 255), alpha = int(input.alpha * globalAlpha * 255); if (red < 0) red = 0; else if (red > 255) red = 255; if (green < 0) green = 0; else if (green > 255) green = 255; if (blue < 0) blue = 0; else if (blue > 255) blue = 255; if (alpha < 0) alpha = 0; else if (alpha > 255) alpha = 255; #if 0 return Gdiplus::Color::FromArgb(alpha, red, green, blue); #else return Gdiplus::Color(alpha, red, green, blue); #endif } GDIPlusSurface::GDIPlusSurface(const std::string & filename) : Surface(0, 0, 0, 0, false) { std::wstring tmp = convert_to_wstring(filename); bitmap = std::shared_ptr<Gdiplus::Bitmap>(Gdiplus::Bitmap::FromFile(tmp.data())); Surface::resize(bitmap->GetWidth(), bitmap->GetHeight(), bitmap->GetWidth(), bitmap->GetHeight(), true); } GDIPlusSurface::GDIPlusSurface(const unsigned char * buffer, size_t size) : Surface(0, 0, 0, 0, false) { assert(0); } void GDIPlusSurface::renderPath(RenderMode mode, const Path2D & input_path, const Style & style, float lineWidth, Operator op, float display_scale, float globalAlpha) { initializeContext(); switch (op) { case SOURCE_OVER: g->SetCompositingMode(Gdiplus::CompositingModeSourceOver); break; case COPY: g->SetCompositingMode(Gdiplus::CompositingModeSourceCopy); break; } Gdiplus::GraphicsPath path; toGDIPath(input_path, path, display_scale); switch (mode) { case STROKE: { Gdiplus::Pen pen(toGDIColor(style.color, globalAlpha), lineWidth); g->DrawPath(&pen, &path); } break; case FILL: if (style.getType() == Style::LINEAR_GRADIENT) { const std::map<float, Color> & colors = style.getColors(); if (!colors.empty()) { std::map<float, Color>::const_iterator it0 = colors.begin(), it1 = colors.end(); it1--; const Color & c0 = it0->second, c1 = it1->second; Gdiplus::LinearGradientBrush brush(Gdiplus::PointF(Gdiplus::REAL(style.x0), Gdiplus::REAL(style.y0)), Gdiplus::PointF(Gdiplus::REAL(style.x1), Gdiplus::REAL(style.y1)), toGDIColor(c0, globalAlpha), toGDIColor(c1, globalAlpha)); g->FillPath(&brush, &path); } } else { Gdiplus::SolidBrush brush(toGDIColor(style.color, globalAlpha)); g->FillPath(&brush, &path); } } } void GDIPlusSurface::clip(const Path2D & input_path, float display_scale) { initializeContext(); Gdiplus::GraphicsPath path; toGDIPath(input_path, path, display_scale); Gdiplus::Region region(&path); g->SetClip(&region); } void GDIPlusSurface::drawNativeSurface(GDIPlusSurface & img, const Point & p, double w, double h, float displayScale, float globalAlpha, bool imageSmoothingEnabled) { initializeContext(); g->SetCompositingMode(Gdiplus::CompositingModeSourceOver); if (imageSmoothingEnabled) { // g->SetInterpolationMode( Gdiplus::InterpolationModeHighQualityBicubic ); g->SetInterpolationMode( Gdiplus::InterpolationModeHighQualityBilinear ); } else { g->SetInterpolationMode( Gdiplus::InterpolationModeNearestNeighbor ); } if (globalAlpha < 1.0f && 0) { #if 0 ImageAttributes imageAttributes; ColorMatrix colorMatrix = { 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, alpha, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f}; imageAttributes.SetColorMatrix( &colorMatrix, ColorMatrixFlagsDefault, ColorAdjustTypeBitmap); graphics.DrawImage( &(*(img.bitmap)), Gdiplus::Rect(p.x, p.y, w, h), // destination rectangle 0, 0, // upper-left corner of source rectangle getWidth(), // width of source rectangle getHeight(), // height of source rectangle Gdiplus::UnitPixel, &imageAttributes); #endif } else if (img.getActualWidth() == (unsigned int)w && img.getActualHeight() == (unsigned int)h && 0) { // this scales image weirdly g->DrawImage(&(*(img.bitmap)), Gdiplus::REAL(p.x), Gdiplus::REAL(p.y)); } else { g->DrawImage(&(*(img.bitmap)), Gdiplus::REAL(p.x), Gdiplus::REAL(p.y), Gdiplus::REAL(w), Gdiplus::REAL(h)); } } void GDIPlusSurface::drawImage(Surface & _img, const Point & p, double w, double h, gfloat displayScale, float globalAlpha, bool imageSmoothingEnabled) { GDIPlusSurface * img = dynamic_cast<GDIPlusSurface*>(&_img); if (img) { drawNativeSurface(*img, p, w, h, displayScale, globalAlpha, imageSmoothingEnabled); } else { auto img = _img.createImage(); GDIPlusSurface cs(*img); drawNativeSurface(cs, p, w, h, displayScale, globalAlpha, imageSmoothingEnabled); } } void GDIPlusSurface::renderText(RenderMode mode, const Font & font, const Style & style, TextBaseline textBaseline, TextAlign textAlign, const std::string & text, const Point & p, float lineWidth, Operator op, float display_scale, float globalAlpha) { initializeContext(); double x = round(p.x); double y = round(p.y); switch (op) { case SOURCE_OVER: g->SetCompositingMode(Gdiplus::CompositingModeSourceOver); break; case COPY: g->SetCompositingMode(Gdiplus::CompositingModeSourceCopy); break; } if (font.cleartype) { g->SetTextRenderingHint(Gdiplus::TextRenderingHintClearTypeGridFit); } else if (font.antialiasing && font.hinting && 0) { g->SetTextRenderingHint( Gdiplus::TextRenderingHintAntiAliasGridFit ); } else if (font.antialiasing) { g->SetTextRenderingHint( Gdiplus::TextRenderingHintAntiAlias ); } else if (font.hinting) { g->SetTextRenderingHint( Gdiplus::TextRenderingHintSingleBitPerPixelGridFit ); } else { g->SetTextRenderingHint( Gdiplus::TextRenderingHintSingleBitPerPixel ); } std::wstring text2 = convert_to_wstring(text); int style_bits = 0; if (font.weight == Font::BOLD || font.weight == Font::BOLDER) { style_bits |= Gdiplus::FontStyleBold; } if (font.slant == Font::ITALIC) { style_bits |= Gdiplus::FontStyleItalic; } Gdiplus::Font gdifont(&Gdiplus::FontFamily(L"Arial"), font.size * display_scale, style_bits, Gdiplus::UnitPixel); Gdiplus::RectF rect(Gdiplus::REAL(x * display_scale), Gdiplus::REAL(y * display_scale), 0.0f, 0.0f); Gdiplus::StringFormat f; switch (textBaseline.getType()) { case TextBaseline::TOP: break; case TextBaseline::HANGING: break; case TextBaseline::MIDDLE: f.SetLineAlignment(Gdiplus::StringAlignmentCenter); break; case TextBaseline::BOTTOM: f.SetLineAlignment(Gdiplus::StringAlignmentFar); } switch (textAlign.getType()) { case TextAlign::CENTER: f.SetAlignment(Gdiplus::StringAlignmentCenter); break; case TextAlign::END: case TextAlign::RIGHT: f.SetAlignment(Gdiplus::StringAlignmentFar); break; case TextAlign::START: case TextAlign::LEFT: f.SetAlignment(Gdiplus::StringAlignmentNear); break; } f.SetFormatFlags(Gdiplus::StringFormatFlagsBypassGDI); switch (mode) { case STROKE: // implement break; case FILL: { Gdiplus::SolidBrush brush(toGDIColor(style.color, globalAlpha)); g->DrawString(text2.data(), text2.size(), &gdifont, rect, &f, &brush); } break; } } TextMetrics GDIPlusSurface::measureText(const Font & font, const std::string & text, float display_scale) { initializeContext(); std::wstring text2 = convert_to_wstring(text); int style = 0; if (font.weight == Font::BOLD || font.weight == Font::BOLDER) { style |= Gdiplus::FontStyleBold; } if (font.slant == Font::ITALIC) { style |= Gdiplus::FontStyleItalic; } Gdiplus::Font gdi_font(&Gdiplus::FontFamily(L"Arial"), font.size * display_scale, style, Gdiplus::UnitPixel); Gdiplus::RectF layoutRect(0, 0, 512, 512), boundingBox; g->MeasureString(text2.data(), text2.size(), &gdi_font, layoutRect, &boundingBox); Gdiplus::SizeF size; boundingBox.GetSize(&size); float ascent = &Gdiplus::FontFamily(L"Arial")::GetCellAscent(style); float descent = &Gdiplus::FontFamily(L"Arial")::GetCellDescent(style); float baseline = 0; if (textBaseline == TextBaseline::MIDDLE) { baseline = (ascent + descent) / 2; } else if (textBaseline == TextBaseline::TOP) { baseline = (ascent + descent); } return TextMetrics(size.Width / display_scale, (descent - baseline) / dispaly_scale, (ascent - baseline) / display_scale); } <commit_msg>Fix typo<commit_after>#include <ContextGDIPlus.h> #include "utf8.h" #include <cassert> bool canvas::ContextGDIPlus::is_initialized = false; ULONG_PTR canvas::ContextGDIPlus::m_gdiplusToken; using namespace std; using namespace canvas; static std::wstring convert_to_wstring(const std::string & input) { const char * str = input.c_str(); const char * str_i = str; const char * end = str + input.size(); std::wstring output; while (str_i < end) { output += (wchar_t)utf8::next(str_i, end); } return output; } static void toGDIPath(const Path2D & path, Gdiplus::GraphicsPath & output, float display_scale) { output.StartFigure(); Gdiplus::PointF current_pos; for (auto pc : path.getData()) { switch (pc.type) { case PathComponent::MOVE_TO: current_pos = Gdiplus::PointF(Gdiplus::REAL(pc.x0 * display_scale), Gdiplus::REAL(pc.y0 * display_scale)); break; case PathComponent::LINE_TO: { Gdiplus::PointF point(Gdiplus::REAL(pc.x0 * display_scale), Gdiplus::REAL(pc.y0 * display_scale)); output.AddLine(current_pos, point); current_pos = point; } break; case PathComponent::CLOSE: output.CloseFigure(); break; case PathComponent::ARC: { double span = 0; if (0 && ((!pc.anticlockwise && (pc.ea - pc.sa >= 2 * M_PI)) || (pc.anticlockwise && (pc.sa - pc.ea >= 2 * M_PI)))) { // If the anticlockwise argument is false and endAngle-startAngle is equal to or greater than 2*PI, or, if the // anticlockwise argument is true and startAngle-endAngle is equal to or greater than 2*PI, then the arc is the whole // circumference of this circle. span = 2 * M_PI; } else { if (!pc.anticlockwise && (pc.ea < pc.sa)) { span += 2 * M_PI; } else if (pc.anticlockwise && (pc.sa < pc.ea)) { span -= 2 * M_PI; } #if 0 // this is also due to switched coordinate system // we would end up with a 0 span instead of 360 if (!(qFuzzyCompare(span + (ea - sa) + 1, 1.0) && qFuzzyCompare(qAbs(span), 360.0))) { // mod 360 span += (ea - sa) - (static_cast<int>((ea - sa) / 360)) * 360; } #else span += pc.ea - pc.sa; #endif } #if 0 // If the path is empty, move to where the arc will start to avoid painting a line from (0,0) // NOTE: QPainterPath::isEmpty() won't work here since it ignores a lone MoveToElement if (!m_path.elementCount()) m_path.arcMoveTo(xs, ys, width, height, sa); else if (!radius) { m_path.lineTo(xc, yc); return; } #endif #if 0 if (anticlockwise) { span = -M_PI / 2.0; } else { span = M_PI / 2.0; } #endif Gdiplus::RectF rect(Gdiplus::REAL(pc.x0 * display_scale - pc.radius * display_scale), Gdiplus::REAL(pc.y0 * display_scale - pc.radius * display_scale), Gdiplus::REAL(2 * pc.radius * display_scale), Gdiplus::REAL(2 * pc.radius * display_scale)); output.AddArc(rect, Gdiplus::REAL(pc.sa * 180.0f / M_PI), Gdiplus::REAL(span * 180.0f / M_PI)); output.GetLastPoint(&current_pos); } break; } } } static Gdiplus::Color toGDIColor(const Color & input, float globalAlpha = 1.0f) { int red = int(input.red * 255), green = int(input.green * 255), blue = int(input.blue * 255), alpha = int(input.alpha * globalAlpha * 255); if (red < 0) red = 0; else if (red > 255) red = 255; if (green < 0) green = 0; else if (green > 255) green = 255; if (blue < 0) blue = 0; else if (blue > 255) blue = 255; if (alpha < 0) alpha = 0; else if (alpha > 255) alpha = 255; #if 0 return Gdiplus::Color::FromArgb(alpha, red, green, blue); #else return Gdiplus::Color(alpha, red, green, blue); #endif } GDIPlusSurface::GDIPlusSurface(const std::string & filename) : Surface(0, 0, 0, 0, false) { std::wstring tmp = convert_to_wstring(filename); bitmap = std::shared_ptr<Gdiplus::Bitmap>(Gdiplus::Bitmap::FromFile(tmp.data())); Surface::resize(bitmap->GetWidth(), bitmap->GetHeight(), bitmap->GetWidth(), bitmap->GetHeight(), true); } GDIPlusSurface::GDIPlusSurface(const unsigned char * buffer, size_t size) : Surface(0, 0, 0, 0, false) { assert(0); } void GDIPlusSurface::renderPath(RenderMode mode, const Path2D & input_path, const Style & style, float lineWidth, Operator op, float display_scale, float globalAlpha) { initializeContext(); switch (op) { case SOURCE_OVER: g->SetCompositingMode(Gdiplus::CompositingModeSourceOver); break; case COPY: g->SetCompositingMode(Gdiplus::CompositingModeSourceCopy); break; } Gdiplus::GraphicsPath path; toGDIPath(input_path, path, display_scale); switch (mode) { case STROKE: { Gdiplus::Pen pen(toGDIColor(style.color, globalAlpha), lineWidth); g->DrawPath(&pen, &path); } break; case FILL: if (style.getType() == Style::LINEAR_GRADIENT) { const std::map<float, Color> & colors = style.getColors(); if (!colors.empty()) { std::map<float, Color>::const_iterator it0 = colors.begin(), it1 = colors.end(); it1--; const Color & c0 = it0->second, c1 = it1->second; Gdiplus::LinearGradientBrush brush(Gdiplus::PointF(Gdiplus::REAL(style.x0), Gdiplus::REAL(style.y0)), Gdiplus::PointF(Gdiplus::REAL(style.x1), Gdiplus::REAL(style.y1)), toGDIColor(c0, globalAlpha), toGDIColor(c1, globalAlpha)); g->FillPath(&brush, &path); } } else { Gdiplus::SolidBrush brush(toGDIColor(style.color, globalAlpha)); g->FillPath(&brush, &path); } } } void GDIPlusSurface::clip(const Path2D & input_path, float display_scale) { initializeContext(); Gdiplus::GraphicsPath path; toGDIPath(input_path, path, display_scale); Gdiplus::Region region(&path); g->SetClip(&region); } void GDIPlusSurface::drawNativeSurface(GDIPlusSurface & img, const Point & p, double w, double h, float displayScale, float globalAlpha, bool imageSmoothingEnabled) { initializeContext(); g->SetCompositingMode(Gdiplus::CompositingModeSourceOver); if (imageSmoothingEnabled) { // g->SetInterpolationMode( Gdiplus::InterpolationModeHighQualityBicubic ); g->SetInterpolationMode( Gdiplus::InterpolationModeHighQualityBilinear ); } else { g->SetInterpolationMode( Gdiplus::InterpolationModeNearestNeighbor ); } if (globalAlpha < 1.0f && 0) { #if 0 ImageAttributes imageAttributes; ColorMatrix colorMatrix = { 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, alpha, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f}; imageAttributes.SetColorMatrix( &colorMatrix, ColorMatrixFlagsDefault, ColorAdjustTypeBitmap); graphics.DrawImage( &(*(img.bitmap)), Gdiplus::Rect(p.x, p.y, w, h), // destination rectangle 0, 0, // upper-left corner of source rectangle getWidth(), // width of source rectangle getHeight(), // height of source rectangle Gdiplus::UnitPixel, &imageAttributes); #endif } else if (img.getActualWidth() == (unsigned int)w && img.getActualHeight() == (unsigned int)h && 0) { // this scales image weirdly g->DrawImage(&(*(img.bitmap)), Gdiplus::REAL(p.x), Gdiplus::REAL(p.y)); } else { g->DrawImage(&(*(img.bitmap)), Gdiplus::REAL(p.x), Gdiplus::REAL(p.y), Gdiplus::REAL(w), Gdiplus::REAL(h)); } } void GDIPlusSurface::drawImage(Surface & _img, const Point & p, double w, double h, gfloat displayScale, float globalAlpha, bool imageSmoothingEnabled) { GDIPlusSurface * img = dynamic_cast<GDIPlusSurface*>(&_img); if (img) { drawNativeSurface(*img, p, w, h, displayScale, globalAlpha, imageSmoothingEnabled); } else { auto img = _img.createImage(); GDIPlusSurface cs(*img); drawNativeSurface(cs, p, w, h, displayScale, globalAlpha, imageSmoothingEnabled); } } void GDIPlusSurface::renderText(RenderMode mode, const Font & font, const Style & style, TextBaseline textBaseline, TextAlign textAlign, const std::string & text, const Point & p, float lineWidth, Operator op, float display_scale, float globalAlpha) { initializeContext(); double x = round(p.x); double y = round(p.y); switch (op) { case SOURCE_OVER: g->SetCompositingMode(Gdiplus::CompositingModeSourceOver); break; case COPY: g->SetCompositingMode(Gdiplus::CompositingModeSourceCopy); break; } if (font.cleartype) { g->SetTextRenderingHint(Gdiplus::TextRenderingHintClearTypeGridFit); } else if (font.antialiasing && font.hinting && 0) { g->SetTextRenderingHint( Gdiplus::TextRenderingHintAntiAliasGridFit ); } else if (font.antialiasing) { g->SetTextRenderingHint( Gdiplus::TextRenderingHintAntiAlias ); } else if (font.hinting) { g->SetTextRenderingHint( Gdiplus::TextRenderingHintSingleBitPerPixelGridFit ); } else { g->SetTextRenderingHint( Gdiplus::TextRenderingHintSingleBitPerPixel ); } std::wstring text2 = convert_to_wstring(text); int style_bits = 0; if (font.weight == Font::BOLD || font.weight == Font::BOLDER) { style_bits |= Gdiplus::FontStyleBold; } if (font.slant == Font::ITALIC) { style_bits |= Gdiplus::FontStyleItalic; } Gdiplus::Font gdifont(&Gdiplus::FontFamily(L"Arial"), font.size * display_scale, style_bits, Gdiplus::UnitPixel); Gdiplus::RectF rect(Gdiplus::REAL(x * display_scale), Gdiplus::REAL(y * display_scale), 0.0f, 0.0f); Gdiplus::StringFormat f; switch (textBaseline.getType()) { case TextBaseline::TOP: break; case TextBaseline::HANGING: break; case TextBaseline::MIDDLE: f.SetLineAlignment(Gdiplus::StringAlignmentCenter); break; case TextBaseline::BOTTOM: f.SetLineAlignment(Gdiplus::StringAlignmentFar); } switch (textAlign.getType()) { case TextAlign::CENTER: f.SetAlignment(Gdiplus::StringAlignmentCenter); break; case TextAlign::END: case TextAlign::RIGHT: f.SetAlignment(Gdiplus::StringAlignmentFar); break; case TextAlign::START: case TextAlign::LEFT: f.SetAlignment(Gdiplus::StringAlignmentNear); break; } f.SetFormatFlags(Gdiplus::StringFormatFlagsBypassGDI); switch (mode) { case STROKE: // implement break; case FILL: { Gdiplus::SolidBrush brush(toGDIColor(style.color, globalAlpha)); g->DrawString(text2.data(), text2.size(), &gdifont, rect, &f, &brush); } break; } } TextMetrics GDIPlusSurface::measureText(const Font & font, const std::string & text, float display_scale) { initializeContext(); std::wstring text2 = convert_to_wstring(text); int style = 0; if (font.weight == Font::BOLD || font.weight == Font::BOLDER) { style |= Gdiplus::FontStyleBold; } if (font.slant == Font::ITALIC) { style |= Gdiplus::FontStyleItalic; } Gdiplus::Font gdi_font(&Gdiplus::FontFamily(L"Arial"), font.size * display_scale, style, Gdiplus::UnitPixel); Gdiplus::RectF layoutRect(0, 0, 512, 512), boundingBox; g->MeasureString(text2.data(), text2.size(), &gdi_font, layoutRect, &boundingBox); Gdiplus::SizeF size; boundingBox.GetSize(&size); float ascent = &Gdiplus::FontFamily(L"Arial")::GetCellAscent(style); float descent = &Gdiplus::FontFamily(L"Arial")::GetCellDescent(style); float baseline = 0; if (textBaseline == TextBaseline::MIDDLE) { baseline = (ascent + descent) / 2; } else if (textBaseline == TextBaseline::TOP) { baseline = (ascent + descent); } return TextMetrics(size.Width / display_scale, (descent - baseline) / display_scale, (ascent - baseline) / display_scale); } <|endoftext|>
<commit_before>#include <cstdlib> #include <cmath> #include <fstream> #include <sstream> #include <iostream> #include <iomanip> #include <string> #include <vector> #include <algorithm> #include <exception> #include <sys/time.h> #include "modules/htmTree.h" #include "modules/kdTree.h" #include "misc.h" #include "feat.h" #include "structs.h" #include "collision.h" #include "global.h" //reduce redistributes, updates 07/02/15 rnc int main(int argc, char **argv) { //// Initializations --------------------------------------------- srand48(1234); // Make sure we have reproducability check_args(argc); Time t, time; // t for global, time for local init_time(t); Feat F; MTL M; // Read parameters file // F.readInputFile(argv[1]); printFile(argv[1]); // Read Secretfile // Secret contains the identity of each target: QSO-Ly-a, QSO-tracers, LRG, ELG, fake QSO, fake LRG, SS, SF Gals Secret; printf("before read secretfile \n"); init_time_at(time,"# read Secret file",t); Secret=read_Secretfile(F.Secretfile,F); printf("# Read %d galaxies from %s \n",Secret.size(),F.Secretfile.c_str()); print_time(time,"# ... took :"); std::vector<int> count; count=count_galaxies(Secret); printf(" Number of galaxies by type, QSO-Ly-a, QSO-tracers, LRG, ELG, fake QSO, fake LRG, SS, SF\n"); for(int i=0;i<8;i++){printf (" type %d number %d \n",i, count[i]);} //read the three input files init_time_at(time,"# read target, SS, SF files",t); MTL Targ=read_MTLfile(F.Targfile,F,0,0); MTL SStars=read_MTLfile(F.SStarsfile,F,1,0); MTL SkyF=read_MTLfile(F.SkyFfile,F,0,1); print_time(time,"# ... took :"); //combine the three input files M=Targ; printf(" M size %d \n",M.size()); M.insert(M.end(),SStars.begin(),SStars.end()); printf(" M size %d \n",M.size()); M.insert(M.end(),SkyF.begin(),SkyF.end()); printf(" M size %d \n",M.size()); F.Ngal=M.size(); assign_priority_class(M); //establish priority classes init_time_at(time,"# establish priority clasess",t); std::vector <int> count_class(M.priority_list.size(),0); for(int i;i<M.size();++i){ if(!M[i].SS&&!M[i].SF){ count_class[M[i].priority_class]+=1; } } print_time(time,"# ... took :"); for(int i;i<M.priority_list.size();++i){ printf(" class %d number %d\n",i,count_class[i]); } PP pp; pp.read_fiber_positions(F); F.Nfiber = pp.fp.size()/2; F.Npetal = max(pp.spectrom)+1; F.Nfbp = (int) (F.Nfiber/F.Npetal);// fibers per petal = 500 pp.get_neighbors(F); pp.compute_fibsofsp(F); //P is original list of plates Plates P = read_plate_centers(F); printf(" future plates %d\n",P.size()); F.Nplate=P.size(); printf("# Read %s plate centers from %s and %d fibers from %s\n",f(F.Nplate).c_str(),F.tileFile.c_str(),F.Nfiber,F.fibFile.c_str()); // Computes geometries of cb and fh: pieces of positioner - used to determine possible collisions F.cb = create_cb(); // cb=central body F.fh = create_fh(); // fh=fiber holder //// Collect available galaxies <-> tilefibers -------------------- // HTM Tree of galaxies const double MinTreeSize = 0.01; init_time_at(time,"# Start building HTM tree",t); htmTree<struct target> T(M,MinTreeSize); print_time(time,"# ... took :");//T.stats(); init_time_at(time,"# collect galaxies at ",t); // For plates/fibers, collect available galaxies; done in parallel collect_galaxies_for_all(M,T,P,pp,F); print_time(time,"# ... took :");//T.stats(); init_time_at(time,"# collect available tile-fibers at",t); // For each galaxy, computes available tilefibers G[i].av_tfs = [(j1,k1),(j2,k2),..] collect_available_tilefibers(M,P,F); //results_on_inputs("doc/figs/",G,P,F,true); //// Assignment ||||||||||||||||||||||||||||||||||||||||||||||||||| printf(" Nplate %d Ngal %d Nfiber %d \n", F.Nplate, F.Ngal, F.Nfiber); Assignment A(M,F); print_time(t,"# Start assignment at : "); // Make a plan ---------------------------------------------------- // Plans whole survey without sky fibers, standard stars // assumes maximum number of observations needed for QSOs, LRGs simple_assign(M,P,pp,F,A); //check to see if there are tiles with no galaxies //need to keep mapping of old tile list to new tile list //and inverse map A.inv_order=initList(F.Nplate,0); for (int j=0;j<F.Nplate ;++j){ bool not_done=true; for(int k=0;k<F.Nfiber && not_done;++k){ if(A.TF[j][k]!=-1){ A.suborder.push_back(j); not_done=false; } } } F.NUsedplate=A.suborder.size(); printf(" Plates after screening %d \n",F.NUsedplate); //if(F.diagnose)diagnostic(M,G,F,A); print_hist("Unused fibers",5,histogram(A.unused_fbp(pp,F),5),false); // Hist of unused fibs // Smooth out distribution of free fibers, and increase the number of assignments for (int i=0; i<1; i++) redistribute_tf(M,P,pp,F,A,0);// more iterations will improve performance slightly for (int i=0; i<1; i++) { improve(M,P,pp,F,A,0); redistribute_tf(M,P,pp,F,A,0); } print_hist("Unused fibers",5,histogram(A.unused_fbp(pp,F),5),false); //try assigning SF and SS before real time assignment for (int j=0;j<F.NUsedplate;++j){ int js=A.suborder[j]; assign_sf_ss(js,M,P,pp,F,A); // Assign SS and SF for each tile assign_unused(js,M,P,pp,F,A); } if(F.diagnose)diagnostic(M,Secret,F,A); init_time_at(time,"# Begin real time assignment",t); //Execute plan, updating targets at intervals for(int i=0;i<F.pass_intervals.size();i++)printf(" i=%d interval %d \n",i,F.pass_intervals[i]); std::vector <int> update_intervals=F.pass_intervals; update_intervals.push_back(F.NUsedplate);//to end intervals at last plate for(int i=0;i<update_intervals.size()-1;++i){//go plate by used plate int starter=update_intervals[i]; printf(" before pass = %d at %d tiles \n",i,starter); //display_results("doc/figs/",G,P,pp,F,A,true); //plan whole survey from this point out /* for (int jj=starter; jj<F.NUsedplate; jj++) { int js = A.suborder[jj]; assign_sf_ss(js,M,P,pp,F,A); // Assign SS and SF assign_unused(js,M,P,pp,F,A); } */ //update target information for interval i } /* for (int jj=starter; jj<update_intervals[i+1]; jj++) { // Update corrects all future occurrences of wrong QSOs etc and tries to observe something else if (0<=jj-F.Analysis) update_plan_from_one_obs(jj,Secret,M,P,pp,F,A); else printf("\n no update\n"); } redistribute_tf(M,P,pp,F,A,starter); improve(M,P,pp,F,A,starter); redistribute_tf(M,P,pp,F,A,starter); //} if(F.diagnose)diagnostic(M,Secret,F,A); // check on SS and SF /* for(int j=0;j<F.NUsedplate;++j){ int js=A.suborder[j]; printf("\n js = %d\n",js); for (int p=0;p<F.Npetal;++p){ int count_SS=0; int count_SF=0; for (int k=0;k<F.Nfbp;++k){ int kk=pp.fibers_of_sp[p][k]; int g=A.TF[js][kk]; if(g!=-1 && M[g].SS)count_SS++; if(g!=-1 && M[g].SF)count_SF++; } printf(" %d %d ",count_SS,count_SF); } printf("\n"); } } */ // Results ------------------------------------------------------- if (F.PrintAscii) for (int j=0; j<F.NUsedplate; j++){ write_FAtile_ascii(A.suborder[j],F.outDir,M,P,pp,F,A); } if (F.PrintFits) for (int j=0; j<F.NUsedplate; j++){ fa_write(A.suborder[j],F.outDir,M,P,pp,F,A); // Write output } display_results("doc/figs/",Secret,M,P,pp,F,A,true); if (F.Verif) A.verif(P,M,pp,F); // Verification that the assignment is sane print_time(t,"# Finished !... in"); return(0); } <commit_msg>diagnostic<commit_after>#include <cstdlib> #include <cmath> #include <fstream> #include <sstream> #include <iostream> #include <iomanip> #include <string> #include <vector> #include <algorithm> #include <exception> #include <sys/time.h> #include "modules/htmTree.h" #include "modules/kdTree.h" #include "misc.h" #include "feat.h" #include "structs.h" #include "collision.h" #include "global.h" //reduce redistributes, updates 07/02/15 rnc int main(int argc, char **argv) { //// Initializations --------------------------------------------- srand48(1234); // Make sure we have reproducability check_args(argc); Time t, time; // t for global, time for local init_time(t); Feat F; MTL M; // Read parameters file // F.readInputFile(argv[1]); printFile(argv[1]); // Read Secretfile // Secret contains the identity of each target: QSO-Ly-a, QSO-tracers, LRG, ELG, fake QSO, fake LRG, SS, SF Gals Secret; printf("before read secretfile \n"); init_time_at(time,"# read Secret file",t); Secret=read_Secretfile(F.Secretfile,F); printf("# Read %d galaxies from %s \n",Secret.size(),F.Secretfile.c_str()); print_time(time,"# ... took :"); std::vector<int> count; count=count_galaxies(Secret); printf(" Number of galaxies by type, QSO-Ly-a, QSO-tracers, LRG, ELG, fake QSO, fake LRG, SS, SF\n"); for(int i=0;i<8;i++){printf (" type %d number %d \n",i, count[i]);} //read the three input files init_time_at(time,"# read target, SS, SF files",t); MTL Targ=read_MTLfile(F.Targfile,F,0,0); MTL SStars=read_MTLfile(F.SStarsfile,F,1,0); MTL SkyF=read_MTLfile(F.SkyFfile,F,0,1); print_time(time,"# ... took :"); //combine the three input files M=Targ; printf(" M size %d \n",M.size()); M.insert(M.end(),SStars.begin(),SStars.end()); printf(" M size %d \n",M.size()); M.insert(M.end(),SkyF.begin(),SkyF.end()); printf(" M size %d \n",M.size()); F.Ngal=M.size(); assign_priority_class(M); //establish priority classes init_time_at(time,"# establish priority clasess",t); std::vector <int> count_class(M.priority_list.size(),0); for(int i;i<M.size();++i){ if(!M[i].SS&&!M[i].SF){ count_class[M[i].priority_class]+=1; } } print_time(time,"# ... took :"); for(int i;i<M.priority_list.size();++i){ printf(" class %d number %d\n",i,count_class[i]); } PP pp; pp.read_fiber_positions(F); F.Nfiber = pp.fp.size()/2; F.Npetal = max(pp.spectrom)+1; F.Nfbp = (int) (F.Nfiber/F.Npetal);// fibers per petal = 500 pp.get_neighbors(F); pp.compute_fibsofsp(F); //P is original list of plates Plates P = read_plate_centers(F); printf(" future plates %d\n",P.size()); F.Nplate=P.size(); printf("# Read %s plate centers from %s and %d fibers from %s\n",f(F.Nplate).c_str(),F.tileFile.c_str(),F.Nfiber,F.fibFile.c_str()); // Computes geometries of cb and fh: pieces of positioner - used to determine possible collisions F.cb = create_cb(); // cb=central body F.fh = create_fh(); // fh=fiber holder //// Collect available galaxies <-> tilefibers -------------------- // HTM Tree of galaxies const double MinTreeSize = 0.01; init_time_at(time,"# Start building HTM tree",t); htmTree<struct target> T(M,MinTreeSize); print_time(time,"# ... took :");//T.stats(); init_time_at(time,"# collect galaxies at ",t); // For plates/fibers, collect available galaxies; done in parallel collect_galaxies_for_all(M,T,P,pp,F); print_time(time,"# ... took :");//T.stats(); init_time_at(time,"# collect available tile-fibers at",t); // For each galaxy, computes available tilefibers G[i].av_tfs = [(j1,k1),(j2,k2),..] collect_available_tilefibers(M,P,F); //results_on_inputs("doc/figs/",G,P,F,true); //// Assignment ||||||||||||||||||||||||||||||||||||||||||||||||||| printf(" Nplate %d Ngal %d Nfiber %d \n", F.Nplate, F.Ngal, F.Nfiber); Assignment A(M,F); print_time(t,"# Start assignment at : "); // Make a plan ---------------------------------------------------- // Plans whole survey without sky fibers, standard stars // assumes maximum number of observations needed for QSOs, LRGs simple_assign(M,P,pp,F,A); //check to see if there are tiles with no galaxies //need to keep mapping of old tile list to new tile list //and inverse map A.inv_order=initList(F.Nplate,0); for (int j=0;j<F.Nplate ;++j){ bool not_done=true; for(int k=0;k<F.Nfiber && not_done;++k){ if(A.TF[j][k]!=-1){ A.suborder.push_back(j); not_done=false; } } } F.NUsedplate=A.suborder.size(); printf(" Plates after screening %d \n",F.NUsedplate); //if(F.diagnose)diagnostic(M,G,F,A); print_hist("Unused fibers",5,histogram(A.unused_fbp(pp,F),5),false); // Hist of unused fibs // Smooth out distribution of free fibers, and increase the number of assignments for (int i=0; i<1; i++) redistribute_tf(M,P,pp,F,A,0);// more iterations will improve performance slightly for (int i=0; i<1; i++) { improve(M,P,pp,F,A,0); redistribute_tf(M,P,pp,F,A,0); } print_hist("Unused fibers",5,histogram(A.unused_fbp(pp,F),5),false); //try assigning SF and SS before real time assignment for (int j=0;j<F.NUsedplate;++j){ int js=A.suborder[j]; assign_sf_ss(js,M,P,pp,F,A); // Assign SS and SF for each tile assign_unused(js,M,P,pp,F,A); } if(F.diagnose)diagnostic(M,Secret,F,A); init_time_at(time,"# Begin real time assignment",t); //Execute plan, updating targets at intervals for(int i=0;i<F.pass_intervals.size();i++)printf(" i=%d interval %d \n",i,F.pass_intervals[i]); std::vector <int> update_intervals=F.pass_intervals; update_intervals.push_back(F.NUsedplate);//to end intervals at last plate for(int i=0;i<update_intervals.size()-1;++i){//go plate by used plate int starter=update_intervals[i]; printf(" before pass = %d at %d tiles \n",i,starter); //display_results("doc/figs/",G,P,pp,F,A,true); //plan whole survey from this point out /* for (int jj=starter; jj<F.NUsedplate; jj++) { int js = A.suborder[jj]; assign_sf_ss(js,M,P,pp,F,A); // Assign SS and SF assign_unused(js,M,P,pp,F,A); } */ //update target information for interval i for (int jj=starter; jj<update_intervals[i+1]; jj++) { // Update corrects all future occurrences of wrong QSOs etc and tries to observe something else if (0<=jj-F.Analysis) update_plan_from_one_obs(jj,Secret,M,P,pp,F,A); else printf("\n no update\n"); } } /* redistribute_tf(M,P,pp,F,A,starter); improve(M,P,pp,F,A,starter); redistribute_tf(M,P,pp,F,A,starter); //} if(F.diagnose)diagnostic(M,Secret,F,A); // check on SS and SF /* for(int j=0;j<F.NUsedplate;++j){ int js=A.suborder[j]; printf("\n js = %d\n",js); for (int p=0;p<F.Npetal;++p){ int count_SS=0; int count_SF=0; for (int k=0;k<F.Nfbp;++k){ int kk=pp.fibers_of_sp[p][k]; int g=A.TF[js][kk]; if(g!=-1 && M[g].SS)count_SS++; if(g!=-1 && M[g].SF)count_SF++; } printf(" %d %d ",count_SS,count_SF); } printf("\n"); } } */ // Results ------------------------------------------------------- if (F.PrintAscii) for (int j=0; j<F.NUsedplate; j++){ write_FAtile_ascii(A.suborder[j],F.outDir,M,P,pp,F,A); } if (F.PrintFits) for (int j=0; j<F.NUsedplate; j++){ fa_write(A.suborder[j],F.outDir,M,P,pp,F,A); // Write output } display_results("doc/figs/",Secret,M,P,pp,F,A,true); if (F.Verif) A.verif(P,M,pp,F); // Verification that the assignment is sane print_time(t,"# Finished !... in"); return(0); } <|endoftext|>
<commit_before>/* * Copyright (C) 2019 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 <stdlib.h> #include <sys/system_properties.h> #include <sys/types.h> #include <sys/wait.h> #include "perfetto/base/logging.h" #include "perfetto/tracing/core/data_source_config.h" #include "src/base/test/test_task_runner.h" #include "test/cts/utils.h" #include "test/gtest_and_gmock.h" #include "test/test_helper.h" #include "protos/perfetto/config/profiling/java_hprof_config.gen.h" #include "protos/perfetto/trace/profiling/heap_graph.gen.h" #include "protos/perfetto/trace/profiling/profile_common.gen.h" #include "protos/perfetto/trace/trace_packet.gen.h" namespace perfetto { namespace { std::string RandomSessionName() { std::random_device rd; std::default_random_engine generator(rd()); std::uniform_int_distribution<char> distribution('a', 'z'); constexpr size_t kSessionNameLen = 20; std::string result(kSessionNameLen, '\0'); for (size_t i = 0; i < kSessionNameLen; ++i) result[i] = distribution(generator); return result; } std::vector<protos::gen::TracePacket> ProfileRuntime(std::string app_name) { base::TestTaskRunner task_runner; // (re)start the target app's main activity if (IsAppRunning(app_name)) { StopApp(app_name, "old.app.stopped", &task_runner); task_runner.RunUntilCheckpoint("old.app.stopped", 1000 /*ms*/); } StartAppActivity(app_name, "MainActivity", "target.app.running", &task_runner, /*delay_ms=*/100); task_runner.RunUntilCheckpoint("target.app.running", 1000 /*ms*/); // If we try to dump too early in app initialization, we sometimes deadlock. sleep(1); // set up tracing TestHelper helper(&task_runner); helper.ConnectConsumer(); helper.WaitForConsumerConnect(); TraceConfig trace_config; trace_config.add_buffers()->set_size_kb(20 * 1024); trace_config.set_duration_ms(6000); trace_config.set_unique_session_name(RandomSessionName().c_str()); auto* ds_config = trace_config.add_data_sources()->mutable_config(); ds_config->set_name("android.java_hprof"); ds_config->set_target_buffer(0); protos::gen::JavaHprofConfig java_hprof_config; java_hprof_config.add_process_cmdline(app_name.c_str()); ds_config->set_java_hprof_config_raw(java_hprof_config.SerializeAsString()); // start tracing helper.StartTracing(trace_config); helper.WaitForTracingDisabled(10000 /*ms*/); helper.ReadData(); helper.WaitForReadData(); PERFETTO_CHECK(IsAppRunning(app_name)); StopApp(app_name, "new.app.stopped", &task_runner); task_runner.RunUntilCheckpoint("new.app.stopped", 1000 /*ms*/); return helper.trace(); } void AssertGraphPresent(std::vector<protos::gen::TracePacket> packets) { ASSERT_GT(packets.size(), 0u); size_t objects = 0; size_t roots = 0; for (const auto& packet : packets) { objects += static_cast<size_t>(packet.heap_graph().objects_size()); roots += static_cast<size_t>(packet.heap_graph().roots_size()); } ASSERT_GT(objects, 0u); ASSERT_GT(roots, 0u); } void AssertNoProfileContents(std::vector<protos::gen::TracePacket> packets) { // If profile packets are present, they must be empty. for (const auto& packet : packets) { ASSERT_EQ(packet.heap_graph().roots_size(), 0); ASSERT_EQ(packet.heap_graph().objects_size(), 0); ASSERT_EQ(packet.heap_graph().type_names_size(), 0); ASSERT_EQ(packet.heap_graph().field_names_size(), 0); } } TEST(HeapprofdJavaCtsTest, DebuggableAppRuntime) { std::string app_name = "android.perfetto.cts.app.debuggable"; const auto& packets = ProfileRuntime(app_name); AssertGraphPresent(packets); } TEST(HeapprofdJavaCtsTest, ProfileableAppRuntime) { std::string app_name = "android.perfetto.cts.app.profileable"; const auto& packets = ProfileRuntime(app_name); AssertGraphPresent(packets); } TEST(HeapprofdJavaCtsTest, ReleaseAppRuntime) { std::string app_name = "android.perfetto.cts.app.release"; const auto& packets = ProfileRuntime(app_name); if (IsDebuggableBuild()) AssertGraphPresent(packets); else AssertNoProfileContents(packets); } } // namespace } // namespace perfetto <commit_msg>Increase buffer size for Java Heap Prof CTS. am: e8990636e0 am: d17b6a1b16 am: a7be53d5a2<commit_after>/* * Copyright (C) 2019 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 <stdlib.h> #include <sys/system_properties.h> #include <sys/types.h> #include <sys/wait.h> #include "perfetto/base/logging.h" #include "perfetto/tracing/core/data_source_config.h" #include "src/base/test/test_task_runner.h" #include "test/cts/utils.h" #include "test/gtest_and_gmock.h" #include "test/test_helper.h" #include "protos/perfetto/config/profiling/java_hprof_config.gen.h" #include "protos/perfetto/trace/profiling/heap_graph.gen.h" #include "protos/perfetto/trace/profiling/profile_common.gen.h" #include "protos/perfetto/trace/trace_packet.gen.h" namespace perfetto { namespace { std::string RandomSessionName() { std::random_device rd; std::default_random_engine generator(rd()); std::uniform_int_distribution<char> distribution('a', 'z'); constexpr size_t kSessionNameLen = 20; std::string result(kSessionNameLen, '\0'); for (size_t i = 0; i < kSessionNameLen; ++i) result[i] = distribution(generator); return result; } std::vector<protos::gen::TracePacket> ProfileRuntime(std::string app_name) { base::TestTaskRunner task_runner; // (re)start the target app's main activity if (IsAppRunning(app_name)) { StopApp(app_name, "old.app.stopped", &task_runner); task_runner.RunUntilCheckpoint("old.app.stopped", 1000 /*ms*/); } StartAppActivity(app_name, "MainActivity", "target.app.running", &task_runner, /*delay_ms=*/100); task_runner.RunUntilCheckpoint("target.app.running", 1000 /*ms*/); // If we try to dump too early in app initialization, we sometimes deadlock. sleep(1); // set up tracing TestHelper helper(&task_runner); helper.ConnectConsumer(); helper.WaitForConsumerConnect(); TraceConfig trace_config; trace_config.add_buffers()->set_size_kb(40 * 1024); trace_config.set_duration_ms(6000); trace_config.set_unique_session_name(RandomSessionName().c_str()); auto* ds_config = trace_config.add_data_sources()->mutable_config(); ds_config->set_name("android.java_hprof"); ds_config->set_target_buffer(0); protos::gen::JavaHprofConfig java_hprof_config; java_hprof_config.add_process_cmdline(app_name.c_str()); ds_config->set_java_hprof_config_raw(java_hprof_config.SerializeAsString()); // start tracing helper.StartTracing(trace_config); helper.WaitForTracingDisabled(10000 /*ms*/); helper.ReadData(); helper.WaitForReadData(); PERFETTO_CHECK(IsAppRunning(app_name)); StopApp(app_name, "new.app.stopped", &task_runner); task_runner.RunUntilCheckpoint("new.app.stopped", 1000 /*ms*/); return helper.trace(); } void AssertGraphPresent(std::vector<protos::gen::TracePacket> packets) { ASSERT_GT(packets.size(), 0u); size_t objects = 0; size_t roots = 0; for (const auto& packet : packets) { objects += static_cast<size_t>(packet.heap_graph().objects_size()); roots += static_cast<size_t>(packet.heap_graph().roots_size()); } ASSERT_GT(objects, 0u); ASSERT_GT(roots, 0u); } void AssertNoProfileContents(std::vector<protos::gen::TracePacket> packets) { // If profile packets are present, they must be empty. for (const auto& packet : packets) { ASSERT_EQ(packet.heap_graph().roots_size(), 0); ASSERT_EQ(packet.heap_graph().objects_size(), 0); ASSERT_EQ(packet.heap_graph().type_names_size(), 0); ASSERT_EQ(packet.heap_graph().field_names_size(), 0); } } TEST(HeapprofdJavaCtsTest, DebuggableAppRuntime) { std::string app_name = "android.perfetto.cts.app.debuggable"; const auto& packets = ProfileRuntime(app_name); AssertGraphPresent(packets); } TEST(HeapprofdJavaCtsTest, ProfileableAppRuntime) { std::string app_name = "android.perfetto.cts.app.profileable"; const auto& packets = ProfileRuntime(app_name); AssertGraphPresent(packets); } TEST(HeapprofdJavaCtsTest, ReleaseAppRuntime) { std::string app_name = "android.perfetto.cts.app.release"; const auto& packets = ProfileRuntime(app_name); if (IsDebuggableBuild()) AssertGraphPresent(packets); else AssertNoProfileContents(packets); } } // namespace } // namespace perfetto <|endoftext|>
<commit_before>// Copyright 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "web_layer_impl.h" #include "SkMatrix44.h" #ifdef LOG #undef LOG #endif #include "base/string_util.h" #include "cc/active_animation.h" #include "cc/layer.h" #include "cc/region.h" #include "third_party/WebKit/Source/Platform/chromium/public/WebFloatPoint.h" #include "third_party/WebKit/Source/Platform/chromium/public/WebFloatRect.h" #include "third_party/WebKit/Source/Platform/chromium/public/WebSize.h" #include "third_party/WebKit/Source/Platform/chromium/public/WebTransformationMatrix.h" #include "web_animation_impl.h" using cc::ActiveAnimation; using cc::Layer; namespace WebKit { namespace { WebTransformationMatrix transformationMatrixFromSkMatrix44(const SkMatrix44& matrix) { double data[16]; matrix.asColMajord(data); return WebTransformationMatrix(data[0], data[1], data[2], data[3], data[4], data[5], data[6], data[7], data[8], data[9], data[10], data[11], data[12], data[13], data[14], data[15]); } SkMatrix44 skMatrix44FromTransformationMatrix(const WebTransformationMatrix& matrix) { SkMatrix44 skMatrix; skMatrix.set(0, 0, SkDoubleToMScalar(matrix.m11())); skMatrix.set(1, 0, SkDoubleToMScalar(matrix.m12())); skMatrix.set(2, 0, SkDoubleToMScalar(matrix.m13())); skMatrix.set(3, 0, SkDoubleToMScalar(matrix.m14())); skMatrix.set(0, 1, SkDoubleToMScalar(matrix.m21())); skMatrix.set(1, 1, SkDoubleToMScalar(matrix.m22())); skMatrix.set(2, 1, SkDoubleToMScalar(matrix.m23())); skMatrix.set(3, 1, SkDoubleToMScalar(matrix.m24())); skMatrix.set(0, 2, SkDoubleToMScalar(matrix.m31())); skMatrix.set(1, 2, SkDoubleToMScalar(matrix.m32())); skMatrix.set(2, 2, SkDoubleToMScalar(matrix.m33())); skMatrix.set(3, 2, SkDoubleToMScalar(matrix.m34())); skMatrix.set(0, 3, SkDoubleToMScalar(matrix.m41())); skMatrix.set(1, 3, SkDoubleToMScalar(matrix.m42())); skMatrix.set(2, 3, SkDoubleToMScalar(matrix.m43())); skMatrix.set(3, 3, SkDoubleToMScalar(matrix.m44())); return skMatrix; } } WebLayer* WebLayer::create() { return new WebLayerImpl(); } WebLayerImpl::WebLayerImpl() : m_layer(Layer::create()) { } WebLayerImpl::WebLayerImpl(scoped_refptr<Layer> layer) : m_layer(layer) { } WebLayerImpl::~WebLayerImpl() { m_layer->clearRenderSurface(); m_layer->setLayerAnimationDelegate(0); } int WebLayerImpl::id() const { return m_layer->id(); } void WebLayerImpl::invalidateRect(const WebFloatRect& rect) { m_layer->setNeedsDisplayRect(rect); } void WebLayerImpl::invalidate() { m_layer->setNeedsDisplay(); } void WebLayerImpl::addChild(WebLayer* child) { m_layer->addChild(static_cast<WebLayerImpl*>(child)->layer()); } void WebLayerImpl::insertChild(WebLayer* child, size_t index) { m_layer->insertChild(static_cast<WebLayerImpl*>(child)->layer(), index); } void WebLayerImpl::replaceChild(WebLayer* reference, WebLayer* newLayer) { m_layer->replaceChild(static_cast<WebLayerImpl*>(reference)->layer(), static_cast<WebLayerImpl*>(newLayer)->layer()); } void WebLayerImpl::removeFromParent() { m_layer->removeFromParent(); } void WebLayerImpl::removeAllChildren() { m_layer->removeAllChildren(); } void WebLayerImpl::setAnchorPoint(const WebFloatPoint& anchorPoint) { m_layer->setAnchorPoint(anchorPoint); } WebFloatPoint WebLayerImpl::anchorPoint() const { return m_layer->anchorPoint(); } void WebLayerImpl::setAnchorPointZ(float anchorPointZ) { m_layer->setAnchorPointZ(anchorPointZ); } float WebLayerImpl::anchorPointZ() const { return m_layer->anchorPointZ(); } void WebLayerImpl::setBounds(const WebSize& size) { m_layer->setBounds(size); } WebSize WebLayerImpl::bounds() const { return m_layer->bounds(); } void WebLayerImpl::setMasksToBounds(bool masksToBounds) { m_layer->setMasksToBounds(masksToBounds); } bool WebLayerImpl::masksToBounds() const { return m_layer->masksToBounds(); } void WebLayerImpl::setMaskLayer(WebLayer* maskLayer) { m_layer->setMaskLayer(maskLayer ? static_cast<WebLayerImpl*>(maskLayer)->layer() : 0); } void WebLayerImpl::setReplicaLayer(WebLayer* replicaLayer) { m_layer->setReplicaLayer(replicaLayer ? static_cast<WebLayerImpl*>(replicaLayer)->layer() : 0); } void WebLayerImpl::setOpacity(float opacity) { m_layer->setOpacity(opacity); } float WebLayerImpl::opacity() const { return m_layer->opacity(); } void WebLayerImpl::setOpaque(bool opaque) { m_layer->setContentsOpaque(opaque); } bool WebLayerImpl::opaque() const { return m_layer->contentsOpaque(); } void WebLayerImpl::setPosition(const WebFloatPoint& position) { m_layer->setPosition(position); } WebFloatPoint WebLayerImpl::position() const { return m_layer->position(); } void WebLayerImpl::setSublayerTransform(const SkMatrix44& matrix) { m_layer->setSublayerTransform(transformationMatrixFromSkMatrix44(matrix)); } void WebLayerImpl::setSublayerTransform(const WebTransformationMatrix& matrix) { m_layer->setSublayerTransform(matrix); } SkMatrix44 WebLayerImpl::sublayerTransform() const { return skMatrix44FromTransformationMatrix(m_layer->sublayerTransform()); } void WebLayerImpl::setTransform(const SkMatrix44& matrix) { m_layer->setTransform(transformationMatrixFromSkMatrix44(matrix)); } void WebLayerImpl::setTransform(const WebTransformationMatrix& matrix) { m_layer->setTransform(matrix); } SkMatrix44 WebLayerImpl::transform() const { return skMatrix44FromTransformationMatrix(m_layer->transform()); } void WebLayerImpl::setDrawsContent(bool drawsContent) { m_layer->setIsDrawable(drawsContent); } bool WebLayerImpl::drawsContent() const { return m_layer->drawsContent(); } void WebLayerImpl::setPreserves3D(bool preserve3D) { m_layer->setPreserves3D(preserve3D); } void WebLayerImpl::setUseParentBackfaceVisibility(bool useParentBackfaceVisibility) { m_layer->setUseParentBackfaceVisibility(useParentBackfaceVisibility); } void WebLayerImpl::setBackgroundColor(WebColor color) { m_layer->setBackgroundColor(color); } WebColor WebLayerImpl::backgroundColor() const { return m_layer->backgroundColor(); } void WebLayerImpl::setFilters(const WebFilterOperations& filters) { m_layer->setFilters(filters); } void WebLayerImpl::setBackgroundFilters(const WebFilterOperations& filters) { m_layer->setBackgroundFilters(filters); } void WebLayerImpl::setFilter(SkImageFilter* filter) { m_layer->setFilter(filter); } void WebLayerImpl::setDebugBorderColor(const WebColor& color) { NOTREACHED(); } void WebLayerImpl::setDebugBorderWidth(float width) { NOTREACHED(); } void WebLayerImpl::setDebugName(WebString name) { m_layer->setDebugName(UTF16ToASCII(string16(name.data(), name.length()))); } void WebLayerImpl::setAnimationDelegate(WebAnimationDelegate* delegate) { m_layer->setLayerAnimationDelegate(delegate); } bool WebLayerImpl::addAnimation(WebAnimation* animation) { return m_layer->addAnimation(static_cast<WebAnimationImpl*>(animation)->cloneToAnimation()); } void WebLayerImpl::removeAnimation(int animationId) { m_layer->removeAnimation(animationId); } void WebLayerImpl::removeAnimation(int animationId, WebAnimation::TargetProperty targetProperty) { m_layer->layerAnimationController()->removeAnimation(animationId, static_cast<ActiveAnimation::TargetProperty>(targetProperty)); } void WebLayerImpl::pauseAnimation(int animationId, double timeOffset) { m_layer->pauseAnimation(animationId, timeOffset); } void WebLayerImpl::suspendAnimations(double monotonicTime) { m_layer->suspendAnimations(monotonicTime); } void WebLayerImpl::resumeAnimations(double monotonicTime) { m_layer->resumeAnimations(monotonicTime); } bool WebLayerImpl::hasActiveAnimation() { return m_layer->hasActiveAnimation(); } void WebLayerImpl::transferAnimationsTo(WebLayer* other) { DCHECK(other); static_cast<WebLayerImpl*>(other)->m_layer->setLayerAnimationController(m_layer->releaseLayerAnimationController()); } void WebLayerImpl::setForceRenderSurface(bool forceRenderSurface) { m_layer->setForceRenderSurface(forceRenderSurface); } void WebLayerImpl::setScrollPosition(WebPoint position) { m_layer->setScrollOffset(gfx::Point(position).OffsetFromOrigin()); } WebPoint WebLayerImpl::scrollPosition() const { return gfx::PointAtOffsetFromOrigin(m_layer->scrollOffset()); } void WebLayerImpl::setMaxScrollPosition(WebSize maxScrollPosition) { m_layer->setMaxScrollOffset(maxScrollPosition); } WebSize WebLayerImpl::maxScrollPosition() const { return m_layer->maxScrollOffset(); } void WebLayerImpl::setScrollable(bool scrollable) { m_layer->setScrollable(scrollable); } bool WebLayerImpl::scrollable() const { return m_layer->scrollable(); } void WebLayerImpl::setHaveWheelEventHandlers(bool haveWheelEventHandlers) { m_layer->setHaveWheelEventHandlers(haveWheelEventHandlers); } bool WebLayerImpl::haveWheelEventHandlers() const { return m_layer->haveWheelEventHandlers(); } void WebLayerImpl::setShouldScrollOnMainThread(bool shouldScrollOnMainThread) { m_layer->setShouldScrollOnMainThread(shouldScrollOnMainThread); } bool WebLayerImpl::shouldScrollOnMainThread() const { return m_layer->shouldScrollOnMainThread(); } void WebLayerImpl::setNonFastScrollableRegion(const WebVector<WebRect>& rects) { cc::Region region; for (size_t i = 0; i < rects.size(); ++i) region.Union(rects[i]); m_layer->setNonFastScrollableRegion(region); } WebVector<WebRect> WebLayerImpl::nonFastScrollableRegion() const { size_t numRects = 0; for (cc::Region::Iterator regionRects(m_layer->nonFastScrollableRegion()); regionRects.has_rect(); regionRects.next()) ++numRects; WebVector<WebRect> result(numRects); size_t i = 0; for (cc::Region::Iterator regionRects(m_layer->nonFastScrollableRegion()); regionRects.has_rect(); regionRects.next()) { result[i] = regionRects.rect(); ++i; } return result; } void WebLayerImpl::setTouchEventHandlerRegion(const WebVector<WebRect>& rects) { cc::Region region; for (size_t i = 0; i < rects.size(); ++i) region.Union(rects[i]); m_layer->setTouchEventHandlerRegion(region); } WebVector<WebRect> WebLayerImpl::touchEventHandlerRegion() const { size_t numRects = 0; for (cc::Region::Iterator regionRects(m_layer->touchEventHandlerRegion()); regionRects.has_rect(); regionRects.next()) ++numRects; WebVector<WebRect> result(numRects); size_t i = 0; for (cc::Region::Iterator regionRects(m_layer->touchEventHandlerRegion()); regionRects.has_rect(); regionRects.next()) { result[i] = regionRects.rect(); ++i; } return result; } void WebLayerImpl::setIsContainerForFixedPositionLayers(bool enable) { m_layer->setIsContainerForFixedPositionLayers(enable); } bool WebLayerImpl::isContainerForFixedPositionLayers() const { return m_layer->isContainerForFixedPositionLayers(); } void WebLayerImpl::setFixedToContainerLayer(bool enable) { m_layer->setFixedToContainerLayer(enable); } bool WebLayerImpl::fixedToContainerLayer() const { return m_layer->fixedToContainerLayer(); } void WebLayerImpl::setScrollClient(WebLayerScrollClient* scrollClient) { m_layer->setLayerScrollClient(scrollClient); } Layer* WebLayerImpl::layer() const { return m_layer.get(); } } // namespace WebKit <commit_msg>cc: Remove some more unneeded asserts for methods that the UI compositor is using temporarily during transition to the new debug borders.<commit_after>// Copyright 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "web_layer_impl.h" #include "SkMatrix44.h" #ifdef LOG #undef LOG #endif #include "base/string_util.h" #include "cc/active_animation.h" #include "cc/layer.h" #include "cc/region.h" #include "third_party/WebKit/Source/Platform/chromium/public/WebFloatPoint.h" #include "third_party/WebKit/Source/Platform/chromium/public/WebFloatRect.h" #include "third_party/WebKit/Source/Platform/chromium/public/WebSize.h" #include "third_party/WebKit/Source/Platform/chromium/public/WebTransformationMatrix.h" #include "web_animation_impl.h" using cc::ActiveAnimation; using cc::Layer; namespace WebKit { namespace { WebTransformationMatrix transformationMatrixFromSkMatrix44(const SkMatrix44& matrix) { double data[16]; matrix.asColMajord(data); return WebTransformationMatrix(data[0], data[1], data[2], data[3], data[4], data[5], data[6], data[7], data[8], data[9], data[10], data[11], data[12], data[13], data[14], data[15]); } SkMatrix44 skMatrix44FromTransformationMatrix(const WebTransformationMatrix& matrix) { SkMatrix44 skMatrix; skMatrix.set(0, 0, SkDoubleToMScalar(matrix.m11())); skMatrix.set(1, 0, SkDoubleToMScalar(matrix.m12())); skMatrix.set(2, 0, SkDoubleToMScalar(matrix.m13())); skMatrix.set(3, 0, SkDoubleToMScalar(matrix.m14())); skMatrix.set(0, 1, SkDoubleToMScalar(matrix.m21())); skMatrix.set(1, 1, SkDoubleToMScalar(matrix.m22())); skMatrix.set(2, 1, SkDoubleToMScalar(matrix.m23())); skMatrix.set(3, 1, SkDoubleToMScalar(matrix.m24())); skMatrix.set(0, 2, SkDoubleToMScalar(matrix.m31())); skMatrix.set(1, 2, SkDoubleToMScalar(matrix.m32())); skMatrix.set(2, 2, SkDoubleToMScalar(matrix.m33())); skMatrix.set(3, 2, SkDoubleToMScalar(matrix.m34())); skMatrix.set(0, 3, SkDoubleToMScalar(matrix.m41())); skMatrix.set(1, 3, SkDoubleToMScalar(matrix.m42())); skMatrix.set(2, 3, SkDoubleToMScalar(matrix.m43())); skMatrix.set(3, 3, SkDoubleToMScalar(matrix.m44())); return skMatrix; } } WebLayer* WebLayer::create() { return new WebLayerImpl(); } WebLayerImpl::WebLayerImpl() : m_layer(Layer::create()) { } WebLayerImpl::WebLayerImpl(scoped_refptr<Layer> layer) : m_layer(layer) { } WebLayerImpl::~WebLayerImpl() { m_layer->clearRenderSurface(); m_layer->setLayerAnimationDelegate(0); } int WebLayerImpl::id() const { return m_layer->id(); } void WebLayerImpl::invalidateRect(const WebFloatRect& rect) { m_layer->setNeedsDisplayRect(rect); } void WebLayerImpl::invalidate() { m_layer->setNeedsDisplay(); } void WebLayerImpl::addChild(WebLayer* child) { m_layer->addChild(static_cast<WebLayerImpl*>(child)->layer()); } void WebLayerImpl::insertChild(WebLayer* child, size_t index) { m_layer->insertChild(static_cast<WebLayerImpl*>(child)->layer(), index); } void WebLayerImpl::replaceChild(WebLayer* reference, WebLayer* newLayer) { m_layer->replaceChild(static_cast<WebLayerImpl*>(reference)->layer(), static_cast<WebLayerImpl*>(newLayer)->layer()); } void WebLayerImpl::removeFromParent() { m_layer->removeFromParent(); } void WebLayerImpl::removeAllChildren() { m_layer->removeAllChildren(); } void WebLayerImpl::setAnchorPoint(const WebFloatPoint& anchorPoint) { m_layer->setAnchorPoint(anchorPoint); } WebFloatPoint WebLayerImpl::anchorPoint() const { return m_layer->anchorPoint(); } void WebLayerImpl::setAnchorPointZ(float anchorPointZ) { m_layer->setAnchorPointZ(anchorPointZ); } float WebLayerImpl::anchorPointZ() const { return m_layer->anchorPointZ(); } void WebLayerImpl::setBounds(const WebSize& size) { m_layer->setBounds(size); } WebSize WebLayerImpl::bounds() const { return m_layer->bounds(); } void WebLayerImpl::setMasksToBounds(bool masksToBounds) { m_layer->setMasksToBounds(masksToBounds); } bool WebLayerImpl::masksToBounds() const { return m_layer->masksToBounds(); } void WebLayerImpl::setMaskLayer(WebLayer* maskLayer) { m_layer->setMaskLayer(maskLayer ? static_cast<WebLayerImpl*>(maskLayer)->layer() : 0); } void WebLayerImpl::setReplicaLayer(WebLayer* replicaLayer) { m_layer->setReplicaLayer(replicaLayer ? static_cast<WebLayerImpl*>(replicaLayer)->layer() : 0); } void WebLayerImpl::setOpacity(float opacity) { m_layer->setOpacity(opacity); } float WebLayerImpl::opacity() const { return m_layer->opacity(); } void WebLayerImpl::setOpaque(bool opaque) { m_layer->setContentsOpaque(opaque); } bool WebLayerImpl::opaque() const { return m_layer->contentsOpaque(); } void WebLayerImpl::setPosition(const WebFloatPoint& position) { m_layer->setPosition(position); } WebFloatPoint WebLayerImpl::position() const { return m_layer->position(); } void WebLayerImpl::setSublayerTransform(const SkMatrix44& matrix) { m_layer->setSublayerTransform(transformationMatrixFromSkMatrix44(matrix)); } void WebLayerImpl::setSublayerTransform(const WebTransformationMatrix& matrix) { m_layer->setSublayerTransform(matrix); } SkMatrix44 WebLayerImpl::sublayerTransform() const { return skMatrix44FromTransformationMatrix(m_layer->sublayerTransform()); } void WebLayerImpl::setTransform(const SkMatrix44& matrix) { m_layer->setTransform(transformationMatrixFromSkMatrix44(matrix)); } void WebLayerImpl::setTransform(const WebTransformationMatrix& matrix) { m_layer->setTransform(matrix); } SkMatrix44 WebLayerImpl::transform() const { return skMatrix44FromTransformationMatrix(m_layer->transform()); } void WebLayerImpl::setDrawsContent(bool drawsContent) { m_layer->setIsDrawable(drawsContent); } bool WebLayerImpl::drawsContent() const { return m_layer->drawsContent(); } void WebLayerImpl::setPreserves3D(bool preserve3D) { m_layer->setPreserves3D(preserve3D); } void WebLayerImpl::setUseParentBackfaceVisibility(bool useParentBackfaceVisibility) { m_layer->setUseParentBackfaceVisibility(useParentBackfaceVisibility); } void WebLayerImpl::setBackgroundColor(WebColor color) { m_layer->setBackgroundColor(color); } WebColor WebLayerImpl::backgroundColor() const { return m_layer->backgroundColor(); } void WebLayerImpl::setFilters(const WebFilterOperations& filters) { m_layer->setFilters(filters); } void WebLayerImpl::setBackgroundFilters(const WebFilterOperations& filters) { m_layer->setBackgroundFilters(filters); } void WebLayerImpl::setFilter(SkImageFilter* filter) { m_layer->setFilter(filter); } void WebLayerImpl::setDebugBorderColor(const WebColor& color) { } void WebLayerImpl::setDebugBorderWidth(float width) { } void WebLayerImpl::setDebugName(WebString name) { m_layer->setDebugName(UTF16ToASCII(string16(name.data(), name.length()))); } void WebLayerImpl::setAnimationDelegate(WebAnimationDelegate* delegate) { m_layer->setLayerAnimationDelegate(delegate); } bool WebLayerImpl::addAnimation(WebAnimation* animation) { return m_layer->addAnimation(static_cast<WebAnimationImpl*>(animation)->cloneToAnimation()); } void WebLayerImpl::removeAnimation(int animationId) { m_layer->removeAnimation(animationId); } void WebLayerImpl::removeAnimation(int animationId, WebAnimation::TargetProperty targetProperty) { m_layer->layerAnimationController()->removeAnimation(animationId, static_cast<ActiveAnimation::TargetProperty>(targetProperty)); } void WebLayerImpl::pauseAnimation(int animationId, double timeOffset) { m_layer->pauseAnimation(animationId, timeOffset); } void WebLayerImpl::suspendAnimations(double monotonicTime) { m_layer->suspendAnimations(monotonicTime); } void WebLayerImpl::resumeAnimations(double monotonicTime) { m_layer->resumeAnimations(monotonicTime); } bool WebLayerImpl::hasActiveAnimation() { return m_layer->hasActiveAnimation(); } void WebLayerImpl::transferAnimationsTo(WebLayer* other) { DCHECK(other); static_cast<WebLayerImpl*>(other)->m_layer->setLayerAnimationController(m_layer->releaseLayerAnimationController()); } void WebLayerImpl::setForceRenderSurface(bool forceRenderSurface) { m_layer->setForceRenderSurface(forceRenderSurface); } void WebLayerImpl::setScrollPosition(WebPoint position) { m_layer->setScrollOffset(gfx::Point(position).OffsetFromOrigin()); } WebPoint WebLayerImpl::scrollPosition() const { return gfx::PointAtOffsetFromOrigin(m_layer->scrollOffset()); } void WebLayerImpl::setMaxScrollPosition(WebSize maxScrollPosition) { m_layer->setMaxScrollOffset(maxScrollPosition); } WebSize WebLayerImpl::maxScrollPosition() const { return m_layer->maxScrollOffset(); } void WebLayerImpl::setScrollable(bool scrollable) { m_layer->setScrollable(scrollable); } bool WebLayerImpl::scrollable() const { return m_layer->scrollable(); } void WebLayerImpl::setHaveWheelEventHandlers(bool haveWheelEventHandlers) { m_layer->setHaveWheelEventHandlers(haveWheelEventHandlers); } bool WebLayerImpl::haveWheelEventHandlers() const { return m_layer->haveWheelEventHandlers(); } void WebLayerImpl::setShouldScrollOnMainThread(bool shouldScrollOnMainThread) { m_layer->setShouldScrollOnMainThread(shouldScrollOnMainThread); } bool WebLayerImpl::shouldScrollOnMainThread() const { return m_layer->shouldScrollOnMainThread(); } void WebLayerImpl::setNonFastScrollableRegion(const WebVector<WebRect>& rects) { cc::Region region; for (size_t i = 0; i < rects.size(); ++i) region.Union(rects[i]); m_layer->setNonFastScrollableRegion(region); } WebVector<WebRect> WebLayerImpl::nonFastScrollableRegion() const { size_t numRects = 0; for (cc::Region::Iterator regionRects(m_layer->nonFastScrollableRegion()); regionRects.has_rect(); regionRects.next()) ++numRects; WebVector<WebRect> result(numRects); size_t i = 0; for (cc::Region::Iterator regionRects(m_layer->nonFastScrollableRegion()); regionRects.has_rect(); regionRects.next()) { result[i] = regionRects.rect(); ++i; } return result; } void WebLayerImpl::setTouchEventHandlerRegion(const WebVector<WebRect>& rects) { cc::Region region; for (size_t i = 0; i < rects.size(); ++i) region.Union(rects[i]); m_layer->setTouchEventHandlerRegion(region); } WebVector<WebRect> WebLayerImpl::touchEventHandlerRegion() const { size_t numRects = 0; for (cc::Region::Iterator regionRects(m_layer->touchEventHandlerRegion()); regionRects.has_rect(); regionRects.next()) ++numRects; WebVector<WebRect> result(numRects); size_t i = 0; for (cc::Region::Iterator regionRects(m_layer->touchEventHandlerRegion()); regionRects.has_rect(); regionRects.next()) { result[i] = regionRects.rect(); ++i; } return result; } void WebLayerImpl::setIsContainerForFixedPositionLayers(bool enable) { m_layer->setIsContainerForFixedPositionLayers(enable); } bool WebLayerImpl::isContainerForFixedPositionLayers() const { return m_layer->isContainerForFixedPositionLayers(); } void WebLayerImpl::setFixedToContainerLayer(bool enable) { m_layer->setFixedToContainerLayer(enable); } bool WebLayerImpl::fixedToContainerLayer() const { return m_layer->fixedToContainerLayer(); } void WebLayerImpl::setScrollClient(WebLayerScrollClient* scrollClient) { m_layer->setLayerScrollClient(scrollClient); } Layer* WebLayerImpl::layer() const { return m_layer.get(); } } // namespace WebKit <|endoftext|>
<commit_before>//--------------------------------------------------------- // Copyright 2017 Ontario Institute for Cancer Research // Written by Jared Simpson (jared.simpson@oicr.on.ca) //--------------------------------------------------------- // // nanopolish_phase_reads -- phase variants onto reads // #include <stdio.h> #include <stdlib.h> #include <string.h> #include <string> #include <vector> #include <inttypes.h> #include <assert.h> #include <cmath> #include <sys/time.h> #include <algorithm> #include <fstream> #include <sstream> #include <iomanip> #include <set> #include <map> #include <omp.h> #include <getopt.h> #include <cstddef> #include "htslib/faidx.h" #include "nanopolish_iupac.h" #include "nanopolish_poremodel.h" #include "nanopolish_transition_parameters.h" #include "nanopolish_profile_hmm.h" #include "nanopolish_pore_model_set.h" #include "nanopolish_variant.h" #include "nanopolish_haplotype.h" #include "nanopolish_alignment_db.h" #include "nanopolish_bam_processor.h" #include "nanopolish_bam_utils.h" #include "nanopolish_index.h" #include "H5pubconf.h" #include "profiler.h" #include "progress.h" #include "logger.hpp" using namespace std::placeholders; // // structs // // // Getopt // #define SUBPROGRAM "phase-reads" static const char *PHASE_READS_VERSION_MESSAGE = SUBPROGRAM " Version " PACKAGE_VERSION "\n" "Written by Jared Simpson.\n" "\n" "Copyright 2017 Ontario Institute for Cancer Research\n"; static const char *PHASE_READS_USAGE_MESSAGE = "Usage: " PACKAGE_NAME " " SUBPROGRAM " [OPTIONS] --reads reads.fa --bam alignments.bam --genome genome.fa variants.vcf\n" "Train a duration model\n" "\n" " -v, --verbose display verbose output\n" " --version display version\n" " --help display this help and exit\n" " -r, --reads=FILE the 2D ONT reads are in fasta FILE\n" " -b, --bam=FILE the reads aligned to the genome assembly are in bam FILE\n" " -g, --genome=FILE the reference genome is in FILE\n" " -w, --window=STR only phase reads in the window STR (format: ctg:start-end)\n" " -t, --threads=NUM use NUM threads (default: 1)\n" " --progress print out a progress message\n" "\nReport bugs to " PACKAGE_BUGREPORT "\n\n"; namespace opt { static unsigned int verbose; static std::string reads_file; static std::string bam_file; static std::string genome_file; static std::string variants_file; static std::string region; static unsigned progress = 0; static unsigned num_threads = 1; static unsigned batch_size = 128; static int min_flanking_sequence = 30; } static const char* shortopts = "r:b:g:t:w:v"; enum { OPT_HELP = 1, OPT_VERSION, OPT_PROGRESS, OPT_LOG_LEVEL }; static const struct option longopts[] = { { "verbose", no_argument, NULL, 'v' }, { "reads", required_argument, NULL, 'r' }, { "bam", required_argument, NULL, 'b' }, { "genome", required_argument, NULL, 'g' }, { "threads", required_argument, NULL, 't' }, { "window", required_argument, NULL, 'w' }, { "progress", no_argument, NULL, OPT_PROGRESS }, { "help", no_argument, NULL, OPT_HELP }, { "version", no_argument, NULL, OPT_VERSION }, { "log-level", required_argument, NULL, OPT_LOG_LEVEL }, { NULL, 0, NULL, 0 } }; void parse_phase_reads_options(int argc, char** argv) { bool die = false; for (char c; (c = getopt_long(argc, argv, shortopts, longopts, NULL)) != -1;) { std::istringstream arg(optarg != NULL ? optarg : ""); switch (c) { case 'r': arg >> opt::reads_file; break; case 'g': arg >> opt::genome_file; break; case 'b': arg >> opt::bam_file; break; case 'w': arg >> opt::region; break; case '?': die = true; break; case 't': arg >> opt::num_threads; break; case 'v': opt::verbose++; break; case OPT_PROGRESS: opt::progress = true; break; case OPT_HELP: std::cout << PHASE_READS_USAGE_MESSAGE; exit(EXIT_SUCCESS); case OPT_VERSION: std::cout << PHASE_READS_VERSION_MESSAGE; exit(EXIT_SUCCESS); case OPT_LOG_LEVEL: logger::Logger::set_level_from_option(arg.str()); break; } } if(argc - optind > 0) { opt::variants_file = argv[optind++]; } else { fprintf(stderr, "Error, variants file is missing\n"); die = true; } if (argc - optind > 0) { std::cerr << SUBPROGRAM ": too many arguments\n"; die = true; } if(opt::num_threads <= 0) { std::cerr << SUBPROGRAM ": invalid number of threads: " << opt::num_threads << "\n"; die = true; } if(opt::reads_file.empty()) { std::cerr << SUBPROGRAM ": a --reads file must be provided\n"; die = true; } if(opt::genome_file.empty()) { std::cerr << SUBPROGRAM ": a --genome file must be provided\n"; die = true; } if(opt::bam_file.empty()) { std::cerr << SUBPROGRAM ": a --bam file must be provided\n"; die = true; } if (die) { std::cout << "\n" << PHASE_READS_USAGE_MESSAGE; exit(EXIT_FAILURE); } } void phase_single_read(const ReadDB& read_db, const faidx_t* fai, const std::vector<Variant>& variants, samFile* sam_fp, const bam_hdr_t* hdr, const bam1_t* record, size_t read_idx, int region_start, int region_end) { const double MAX_Q_SCORE = 30; const double BAM_Q_OFFSET = 0; int tid = omp_get_thread_num(); uint32_t alignment_flags = HAF_ALLOW_PRE_CLIP | HAF_ALLOW_POST_CLIP; // Load a squiggle read for the mapped read std::string read_name = bam_get_qname(record); // load read SquiggleRead sr(read_name, read_db); std::string ref_name = hdr->target_name[record->core.tid]; int alignment_start_pos = record->core.pos; int alignment_end_pos = bam_endpos(record); // Search the variant collection for the index of the first/last variants to phase Variant lower_search; lower_search.ref_name = ref_name; lower_search.ref_position = alignment_start_pos; auto lower_iter = std::lower_bound(variants.begin(), variants.end(), lower_search, sortByPosition); Variant upper_search; upper_search.ref_name = ref_name; upper_search.ref_position = alignment_end_pos; auto upper_iter = std::upper_bound(variants.begin(), variants.end(), upper_search, sortByPosition); fprintf(stderr, "Phasing read %s %s:%u-%u %zu\n", read_name.c_str(), ref_name.c_str(), alignment_start_pos, alignment_end_pos, upper_iter - lower_iter); // no variants to phase? if(lower_iter == variants.end()) { return; } int fetched_len; std::string reference_seq = get_reference_region_ts(fai, ref_name.c_str(), alignment_start_pos, alignment_end_pos, &fetched_len); std::string read_outseq = reference_seq; std::string read_outqual(reference_seq.length(), MAX_Q_SCORE + BAM_Q_OFFSET); Haplotype reference_haplotype(ref_name, alignment_start_pos, reference_seq); for(size_t strand_idx = 0; strand_idx < NUM_STRANDS; ++strand_idx) { // skip if 1D reads and this is the wrong strand if(!sr.has_events_for_strand(strand_idx)) { continue; } // only phase using template strand if(strand_idx != 0) { continue; } SequenceAlignmentRecord seq_align_record(record); EventAlignmentRecord event_align_record(&sr, strand_idx, seq_align_record); // for(; lower_iter < upper_iter; ++lower_iter) { const Variant& v = *lower_iter; if(!v.is_snp()) { continue; } int calling_start = v.ref_position - opt::min_flanking_sequence; int calling_end = v.ref_position + opt::min_flanking_sequence; HMMInputData data; data.read = event_align_record.sr; data.strand = event_align_record.strand; data.rc = event_align_record.rc; data.event_stride = event_align_record.stride; data.pore_model = data.read->get_base_model(data.strand); int e1,e2; bool bounded = AlignmentDB::_find_by_ref_bounds(event_align_record.aligned_events, calling_start, calling_end, e1, e2); // The events of this read do not span the calling window, skip if(!bounded || fabs(e2 - e1) / (calling_start - calling_end) > MAX_EVENT_TO_BP_RATIO) { continue; } data.event_start_idx = e1; data.event_stop_idx = e2; Haplotype calling_haplotype = reference_haplotype.substr_by_reference(calling_start, calling_end); double ref_score = profile_hmm_score(calling_haplotype.get_sequence(), data, alignment_flags); bool good_haplotype = calling_haplotype.apply_variant(v); if(good_haplotype) { double alt_score = profile_hmm_score(calling_haplotype.get_sequence(), data, alignment_flags); double log_sum = add_logs(alt_score, ref_score); double log_p_ref = ref_score - log_sum; double log_p_alt = alt_score - log_sum; char call; double log_p_wrong; if(alt_score > ref_score) { call = v.alt_seq[0]; log_p_wrong = log_p_ref; } else { call = v.ref_seq[0]; log_p_wrong = log_p_alt; } double q_score = -10 * log_p_wrong / log(10); q_score = std::min(MAX_Q_SCORE, q_score); char q_char = (int)q_score + 33; //fprintf(stderr, "\t%s score: %.2lf %.2lf %c p_wrong: %.3lf Q: %d QC: %c\n", v.key().c_str(), ref_score, alt_score, call, log_p_wrong, (int)q_score, q_char); int out_position = v.ref_position - alignment_start_pos; assert(read_outseq[out_position] == v.ref_seq[0]); read_outseq[out_position] = call; read_outqual[out_position] = q_char; } } // Construct the output bam record bam1_t* out_record = bam_init1(); // basic stats out_record->core.tid = record->core.tid; out_record->core.pos = alignment_start_pos; out_record->core.qual = record->core.qual; out_record->core.flag = record->core.flag; // no read pairs out_record->core.mtid = -1; out_record->core.mpos = -1; out_record->core.isize = 0; std::vector<uint32_t> cigar; uint32_t cigar_op = read_outseq.size() << BAM_CIGAR_SHIFT | BAM_CMATCH; cigar.push_back(cigar_op); write_bam_vardata(out_record, read_name, cigar, read_outseq, read_outqual); #pragma omp critical { sam_write1(sam_fp, hdr, out_record); } bam_destroy1(out_record); // automatically frees malloc'd segment } // for strand } int phase_reads_main(int argc, char** argv) { parse_phase_reads_options(argc, argv); omp_set_num_threads(opt::num_threads); ReadDB read_db; read_db.load(opt::reads_file); // load reference fai file faidx_t *fai = fai_load(opt::genome_file.c_str()); std::vector<Variant> variants; if(!opt::region.empty()) { std::string contig; int start_base; int end_base; parse_region_string(opt::region, contig, start_base, end_base); // Read the variants for this region variants = read_variants_for_region(opt::variants_file, contig, start_base, end_base); } else { variants = read_variants_from_file(opt::variants_file); } // Sort variants by reference coordinate std::sort(variants.begin(), variants.end(), sortByPosition); // remove hom reference auto new_end = std::remove_if(variants.begin(), variants.end(), [](Variant v) { return v.genotype == "0/0"; }); variants.erase( new_end, variants.end()); samFile* sam_out = sam_open("-", "w"); // the BamProcessor framework calls the input function with the // bam record, read index, etc passed as parameters // bind the other parameters the worker function needs here auto f = std::bind(phase_single_read, std::ref(read_db), std::ref(fai), std::ref(variants), sam_out, _1, _2, _3, _4, _5); BamProcessor processor(opt::bam_file, opt::region, opt::num_threads); // Copy the bam header to std sam_hdr_write(sam_out, processor.get_bam_header()); processor.parallel_run(f); fai_destroy(fai); sam_close(sam_out); return EXIT_SUCCESS; } <commit_msg>emit warning on unexpected reference base, do not print status unless verbose is set<commit_after>//--------------------------------------------------------- // Copyright 2017 Ontario Institute for Cancer Research // Written by Jared Simpson (jared.simpson@oicr.on.ca) //--------------------------------------------------------- // // nanopolish_phase_reads -- phase variants onto reads // #include <stdio.h> #include <stdlib.h> #include <string.h> #include <string> #include <vector> #include <inttypes.h> #include <assert.h> #include <cmath> #include <sys/time.h> #include <algorithm> #include <fstream> #include <sstream> #include <iomanip> #include <set> #include <map> #include <omp.h> #include <getopt.h> #include <cstddef> #include "htslib/faidx.h" #include "nanopolish_iupac.h" #include "nanopolish_poremodel.h" #include "nanopolish_transition_parameters.h" #include "nanopolish_profile_hmm.h" #include "nanopolish_pore_model_set.h" #include "nanopolish_variant.h" #include "nanopolish_haplotype.h" #include "nanopolish_alignment_db.h" #include "nanopolish_bam_processor.h" #include "nanopolish_bam_utils.h" #include "nanopolish_index.h" #include "H5pubconf.h" #include "profiler.h" #include "progress.h" #include "logger.hpp" using namespace std::placeholders; // // structs // // // Getopt // #define SUBPROGRAM "phase-reads" static const char *PHASE_READS_VERSION_MESSAGE = SUBPROGRAM " Version " PACKAGE_VERSION "\n" "Written by Jared Simpson.\n" "\n" "Copyright 2017 Ontario Institute for Cancer Research\n"; static const char *PHASE_READS_USAGE_MESSAGE = "Usage: " PACKAGE_NAME " " SUBPROGRAM " [OPTIONS] --reads reads.fa --bam alignments.bam --genome genome.fa variants.vcf\n" "Train a duration model\n" "\n" " -v, --verbose display verbose output\n" " --version display version\n" " --help display this help and exit\n" " -r, --reads=FILE the 2D ONT reads are in fasta FILE\n" " -b, --bam=FILE the reads aligned to the genome assembly are in bam FILE\n" " -g, --genome=FILE the reference genome is in FILE\n" " -w, --window=STR only phase reads in the window STR (format: ctg:start-end)\n" " -t, --threads=NUM use NUM threads (default: 1)\n" " --progress print out a progress message\n" "\nReport bugs to " PACKAGE_BUGREPORT "\n\n"; namespace opt { static unsigned int verbose; static std::string reads_file; static std::string bam_file; static std::string genome_file; static std::string variants_file; static std::string region; static unsigned progress = 0; static unsigned num_threads = 1; static unsigned batch_size = 128; static int min_flanking_sequence = 30; } static const char* shortopts = "r:b:g:t:w:v"; enum { OPT_HELP = 1, OPT_VERSION, OPT_PROGRESS, OPT_LOG_LEVEL }; static const struct option longopts[] = { { "verbose", no_argument, NULL, 'v' }, { "reads", required_argument, NULL, 'r' }, { "bam", required_argument, NULL, 'b' }, { "genome", required_argument, NULL, 'g' }, { "threads", required_argument, NULL, 't' }, { "window", required_argument, NULL, 'w' }, { "progress", no_argument, NULL, OPT_PROGRESS }, { "help", no_argument, NULL, OPT_HELP }, { "version", no_argument, NULL, OPT_VERSION }, { "log-level", required_argument, NULL, OPT_LOG_LEVEL }, { NULL, 0, NULL, 0 } }; void parse_phase_reads_options(int argc, char** argv) { bool die = false; for (char c; (c = getopt_long(argc, argv, shortopts, longopts, NULL)) != -1;) { std::istringstream arg(optarg != NULL ? optarg : ""); switch (c) { case 'r': arg >> opt::reads_file; break; case 'g': arg >> opt::genome_file; break; case 'b': arg >> opt::bam_file; break; case 'w': arg >> opt::region; break; case '?': die = true; break; case 't': arg >> opt::num_threads; break; case 'v': opt::verbose++; break; case OPT_PROGRESS: opt::progress = true; break; case OPT_HELP: std::cout << PHASE_READS_USAGE_MESSAGE; exit(EXIT_SUCCESS); case OPT_VERSION: std::cout << PHASE_READS_VERSION_MESSAGE; exit(EXIT_SUCCESS); case OPT_LOG_LEVEL: logger::Logger::set_level_from_option(arg.str()); break; } } if(argc - optind > 0) { opt::variants_file = argv[optind++]; } else { fprintf(stderr, "Error, variants file is missing\n"); die = true; } if (argc - optind > 0) { std::cerr << SUBPROGRAM ": too many arguments\n"; die = true; } if(opt::num_threads <= 0) { std::cerr << SUBPROGRAM ": invalid number of threads: " << opt::num_threads << "\n"; die = true; } if(opt::reads_file.empty()) { std::cerr << SUBPROGRAM ": a --reads file must be provided\n"; die = true; } if(opt::genome_file.empty()) { std::cerr << SUBPROGRAM ": a --genome file must be provided\n"; die = true; } if(opt::bam_file.empty()) { std::cerr << SUBPROGRAM ": a --bam file must be provided\n"; die = true; } if (die) { std::cout << "\n" << PHASE_READS_USAGE_MESSAGE; exit(EXIT_FAILURE); } } void phase_single_read(const ReadDB& read_db, const faidx_t* fai, const std::vector<Variant>& variants, samFile* sam_fp, const bam_hdr_t* hdr, const bam1_t* record, size_t read_idx, int region_start, int region_end) { const double MAX_Q_SCORE = 30; const double BAM_Q_OFFSET = 0; int tid = omp_get_thread_num(); uint32_t alignment_flags = HAF_ALLOW_PRE_CLIP | HAF_ALLOW_POST_CLIP; // Load a squiggle read for the mapped read std::string read_name = bam_get_qname(record); // load read SquiggleRead sr(read_name, read_db); std::string ref_name = hdr->target_name[record->core.tid]; int alignment_start_pos = record->core.pos; int alignment_end_pos = bam_endpos(record); // Search the variant collection for the index of the first/last variants to phase Variant lower_search; lower_search.ref_name = ref_name; lower_search.ref_position = alignment_start_pos; auto lower_iter = std::lower_bound(variants.begin(), variants.end(), lower_search, sortByPosition); Variant upper_search; upper_search.ref_name = ref_name; upper_search.ref_position = alignment_end_pos; auto upper_iter = std::upper_bound(variants.begin(), variants.end(), upper_search, sortByPosition); if(opt::verbose >= 1) { fprintf(stderr, "Phasing read %s %s:%u-%u %zu\n", read_name.c_str(), ref_name.c_str(), alignment_start_pos, alignment_end_pos, upper_iter - lower_iter); } // no variants to phase? if(lower_iter == variants.end()) { return; } int fetched_len; std::string reference_seq = get_reference_region_ts(fai, ref_name.c_str(), alignment_start_pos, alignment_end_pos, &fetched_len); std::string read_outseq = reference_seq; std::string read_outqual(reference_seq.length(), MAX_Q_SCORE + BAM_Q_OFFSET); Haplotype reference_haplotype(ref_name, alignment_start_pos, reference_seq); for(size_t strand_idx = 0; strand_idx < NUM_STRANDS; ++strand_idx) { // skip if 1D reads and this is the wrong strand if(!sr.has_events_for_strand(strand_idx)) { continue; } // only phase using template strand if(strand_idx != 0) { continue; } SequenceAlignmentRecord seq_align_record(record); EventAlignmentRecord event_align_record(&sr, strand_idx, seq_align_record); // for(; lower_iter < upper_iter; ++lower_iter) { const Variant& v = *lower_iter; if(!v.is_snp()) { continue; } int calling_start = v.ref_position - opt::min_flanking_sequence; int calling_end = v.ref_position + opt::min_flanking_sequence; HMMInputData data; data.read = event_align_record.sr; data.strand = event_align_record.strand; data.rc = event_align_record.rc; data.event_stride = event_align_record.stride; data.pore_model = data.read->get_base_model(data.strand); int e1,e2; bool bounded = AlignmentDB::_find_by_ref_bounds(event_align_record.aligned_events, calling_start, calling_end, e1, e2); // The events of this read do not span the calling window, skip if(!bounded || fabs(e2 - e1) / (calling_start - calling_end) > MAX_EVENT_TO_BP_RATIO) { continue; } data.event_start_idx = e1; data.event_stop_idx = e2; Haplotype calling_haplotype = reference_haplotype.substr_by_reference(calling_start, calling_end); double ref_score = profile_hmm_score(calling_haplotype.get_sequence(), data, alignment_flags); bool good_haplotype = calling_haplotype.apply_variant(v); if(good_haplotype) { double alt_score = profile_hmm_score(calling_haplotype.get_sequence(), data, alignment_flags); double log_sum = add_logs(alt_score, ref_score); double log_p_ref = ref_score - log_sum; double log_p_alt = alt_score - log_sum; char call; double log_p_wrong; if(alt_score > ref_score) { call = v.alt_seq[0]; log_p_wrong = log_p_ref; } else { call = v.ref_seq[0]; log_p_wrong = log_p_alt; } double q_score = -10 * log_p_wrong / log(10); q_score = std::min(MAX_Q_SCORE, q_score); char q_char = (int)q_score + 33; //fprintf(stderr, "\t%s score: %.2lf %.2lf %c p_wrong: %.3lf Q: %d QC: %c\n", v.key().c_str(), ref_score, alt_score, call, log_p_wrong, (int)q_score, q_char); int out_position = v.ref_position - alignment_start_pos; if(read_outseq[out_position] != v.ref_seq[0]) { fprintf(stderr, "warning: reference base at position %d does not match variant record (%c != %c)\n", v.ref_position, v.ref_seq[0], read_outseq[out_position]); } read_outseq[out_position] = call; read_outqual[out_position] = q_char; } } // Construct the output bam record bam1_t* out_record = bam_init1(); // basic stats out_record->core.tid = record->core.tid; out_record->core.pos = alignment_start_pos; out_record->core.qual = record->core.qual; out_record->core.flag = record->core.flag; // no read pairs out_record->core.mtid = -1; out_record->core.mpos = -1; out_record->core.isize = 0; std::vector<uint32_t> cigar; uint32_t cigar_op = read_outseq.size() << BAM_CIGAR_SHIFT | BAM_CMATCH; cigar.push_back(cigar_op); write_bam_vardata(out_record, read_name, cigar, read_outseq, read_outqual); #pragma omp critical { sam_write1(sam_fp, hdr, out_record); } bam_destroy1(out_record); // automatically frees malloc'd segment } // for strand } int phase_reads_main(int argc, char** argv) { parse_phase_reads_options(argc, argv); omp_set_num_threads(opt::num_threads); ReadDB read_db; read_db.load(opt::reads_file); // load reference fai file faidx_t *fai = fai_load(opt::genome_file.c_str()); std::vector<Variant> variants; if(!opt::region.empty()) { std::string contig; int start_base; int end_base; parse_region_string(opt::region, contig, start_base, end_base); // Read the variants for this region variants = read_variants_for_region(opt::variants_file, contig, start_base, end_base); } else { variants = read_variants_from_file(opt::variants_file); } // Sort variants by reference coordinate std::sort(variants.begin(), variants.end(), sortByPosition); // remove hom reference auto new_end = std::remove_if(variants.begin(), variants.end(), [](Variant v) { return v.genotype == "0/0"; }); variants.erase( new_end, variants.end()); samFile* sam_out = sam_open("-", "w"); // the BamProcessor framework calls the input function with the // bam record, read index, etc passed as parameters // bind the other parameters the worker function needs here auto f = std::bind(phase_single_read, std::ref(read_db), std::ref(fai), std::ref(variants), sam_out, _1, _2, _3, _4, _5); BamProcessor processor(opt::bam_file, opt::region, opt::num_threads); // Copy the bam header to std sam_hdr_write(sam_out, processor.get_bam_header()); processor.parallel_run(f); fai_destroy(fai); sam_close(sam_out); return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/* This file is part of the KDE project Copyright (C) 2001 Christoph Cullmann <cullmann@kde.org> Copyright (C) 2001 Joseph Wenninger <jowenn@kde.org> Copyright (C) 2001 Anders Lund <anders.lund@lund.tdcadsl.dk> Copyright (C) 2007 Mirko Stocker <me@misto.ch> Copyright (C) 2009 Dominik Haumann <dhaumann kde org> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License version 2 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ //BEGIN Includes #include "katefilebrowser.h" #include "katefilebrowser.moc" #include "katebookmarkhandler.h" #include <ktexteditor/document.h> #include <ktexteditor/view.h> #include <KActionCollection> #include <KActionMenu> #include <KConfigGroup> #include <KDebug> #include <KDirOperator> #include <KFilePlacesModel> #include <KHistoryComboBox> #include <KLocale> #include <KToolBar> #include <KUrlNavigator> #include <QAbstractItemView> #include <QDir> #include <QLabel> #include <QLineEdit> #include <QToolButton> //END Includes KateFileBrowser::KateFileBrowser(Kate::MainWindow *mainWindow, QWidget * parent, const char * name) : KVBox (parent) , m_mainWindow(mainWindow) { setObjectName(name); m_toolbar = new KToolBar(this); m_toolbar->setMovable(false); m_toolbar->setToolButtonStyle(Qt::ToolButtonIconOnly); m_toolbar->setContextMenuPolicy(Qt::NoContextMenu); // includes some actions, but not hooked into the shortcut dialog atm m_actionCollection = new KActionCollection(this); m_actionCollection->addAssociatedWidget(this); KFilePlacesModel* model = new KFilePlacesModel(this); m_urlNavigator = new KUrlNavigator(model, KUrl(QDir::homePath()), this); connect(m_urlNavigator, SIGNAL(urlChanged(const KUrl&)), SLOT(updateDirOperator(const KUrl&))); m_dirOperator = new KDirOperator(KUrl(), this); m_dirOperator->setView(KFile::/* Simple */Detail); m_dirOperator->view()->setSelectionMode(QAbstractItemView::ExtendedSelection); connect(m_dirOperator, SIGNAL(viewChanged(QAbstractItemView *)), this, SLOT(selectorViewChanged(QAbstractItemView *))); m_dirOperator->setSizePolicy(QSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding)); setFocusProxy(m_dirOperator); // now all actions exist in dir operator and we can use them in the toolbar setupToolbar(); KHBox* filterBox = new KHBox(this); QLabel* filterLabel = new QLabel(i18n("Filter:"), filterBox); m_filter = new KHistoryComboBox(true, filterBox); filterLabel->setBuddy(m_filter); m_filter->setMaxCount(10); m_filter->setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed)); connect(m_filter, SIGNAL(editTextChanged(const QString&)), SLOT(slotFilterChange(const QString&))); connect(m_filter, SIGNAL(returnPressed(const QString&)), m_filter, SLOT(addToHistory(const QString&))); connect(m_filter, SIGNAL(returnPressed(const QString&)), m_dirOperator, SLOT(setFocus())); connect(m_dirOperator, SIGNAL(urlEntered(const KUrl&)), this, SLOT(updateUrlNavigator(const KUrl&))); // Connect the bookmark handler connect(m_bookmarkHandler, SIGNAL(openUrl(const QString&)), this, SLOT(setDir(const QString&))); m_filter->setWhatsThis(i18n("Enter a name filter to limit which files are displayed.")); connect(m_dirOperator, SIGNAL(fileSelected(const KFileItem&)), this, SLOT(fileSelected(const KFileItem&))); connect(m_mainWindow, SIGNAL(viewChanged()), this, SLOT(autoSyncFolder())); } KateFileBrowser::~KateFileBrowser() { } //END Constroctor/Destrctor //BEGIN Public Methods void KateFileBrowser::setupToolbar() { // remove all actions from the toolbar (there should be none) m_toolbar->clear(); // create action list QList<QAction*> actions; actions << m_dirOperator->actionCollection()->action("back"); actions << m_dirOperator->actionCollection()->action("forward"); // bookmarks action! KActionMenu *acmBookmarks = new KActionMenu(KIcon("bookmarks"), i18n("Bookmarks"), this); acmBookmarks->setDelayed(false); m_bookmarkHandler = new KateBookmarkHandler(this, acmBookmarks->menu()); acmBookmarks->setShortcutContext(Qt::WidgetWithChildrenShortcut); actions << acmBookmarks; // action for synchronising the dir operator with the current document path KAction* syncFolder = new KAction(this); syncFolder->setShortcutContext(Qt::WidgetWithChildrenShortcut); syncFolder->setText(i18n("Current Document Folder")); syncFolder->setIcon(KIcon("system-switch-user")); connect(syncFolder, SIGNAL(triggered()), this, SLOT(setActiveDocumentDir())); actions << syncFolder; // now add all actions to the toolbar foreach (QAction* ac, actions) { if (ac) { m_toolbar->addAction(ac); } } m_actionCollection->addAction("sync_dir", syncFolder); m_actionCollection->addAction("bookmarks", acmBookmarks); // section for settings menu KActionMenu *optionsMenu = new KActionMenu(KIcon("configure"), i18n("Options"), this); optionsMenu->setDelayed(false); optionsMenu->addAction(m_dirOperator->actionCollection()->action("short view")); optionsMenu->addAction(m_dirOperator->actionCollection()->action("detailed view")); optionsMenu->addAction(m_dirOperator->actionCollection()->action("tree view")); optionsMenu->addAction(m_dirOperator->actionCollection()->action("detailed tree view")); optionsMenu->addSeparator(); optionsMenu->addAction(m_dirOperator->actionCollection()->action("show hidden")); // action for synchronising the dir operator with the current document path m_autoSyncFolder = new KAction(this); m_autoSyncFolder->setCheckable(true); m_autoSyncFolder->setText(i18n("Automatically synchronize with current document")); m_autoSyncFolder->setIcon(KIcon("system-switch-user")); connect(m_autoSyncFolder, SIGNAL(triggered()), this, SLOT(autoSyncFolder())); optionsMenu->addAction(m_autoSyncFolder); m_toolbar->addSeparator(); m_toolbar->addAction(optionsMenu); } void KateFileBrowser::readSessionConfig(KConfigBase *config, const QString & name) { KConfigGroup cgDir(config, name + ":dir"); m_dirOperator->readConfig(cgDir); m_dirOperator->setView(KFile::Default); KConfigGroup cg(config, name); m_urlNavigator->setUrl(cg.readPathEntry("location", QDir::homePath())); setDir(cg.readPathEntry("location", QDir::homePath())); m_autoSyncFolder->setChecked(cg.readEntry("auto sync folder", false)); m_filter->setHistoryItems(cg.readEntry("filter history", QStringList()), true); } void KateFileBrowser::writeSessionConfig(KConfigBase *config, const QString & name) { KConfigGroup cgDir(config, name + ":dir"); m_dirOperator->writeConfig(cgDir); KConfigGroup cg = KConfigGroup(config, name); cg.writePathEntry("location", m_urlNavigator->url().url()); cg.writeEntry("auto sync folder", m_autoSyncFolder->isChecked()); cg.writeEntry("filter history", m_filter->historyItems()); } //END Public Methods //BEGIN Public Slots void KateFileBrowser::slotFilterChange(const QString & nf) { QString f = '*' + nf.trimmed() + '*'; const bool empty = f.isEmpty() || f == "*" || f == "**" || f == "***"; if (empty) { m_dirOperator->clearFilter(); m_filter->lineEdit()->clear(); } else { m_dirOperator->setNameFilter(f); } m_dirOperator->updateDir(); } bool kateFileSelectorIsReadable (const KUrl& url) { if (!url.isLocalFile()) return true; // what else can we say? QDir dir(url.toLocalFile()); return dir.exists (); } void KateFileBrowser::setDir(KUrl u) { KUrl newurl; if (!u.isValid()) newurl.setPath(QDir::homePath()); else newurl = u; QString pathstr = newurl.path(KUrl::AddTrailingSlash); newurl.setPath(pathstr); if (!kateFileSelectorIsReadable (newurl)) newurl.cd(QString::fromLatin1("..")); if (!kateFileSelectorIsReadable (newurl)) newurl.setPath(QDir::homePath()); m_dirOperator->setUrl(newurl, true); } //END Public Slots //BEGIN Private Slots void KateFileBrowser::fileSelected(const KFileItem & /*file*/) { openSelectedFiles(); } void KateFileBrowser::openSelectedFiles() { const KFileItemList list = m_dirOperator->selectedItems(); foreach (const KFileItem& item, list) { m_mainWindow->openUrl(item.url()); } m_dirOperator->view()->selectionModel()->clear(); } void KateFileBrowser::updateDirOperator(const KUrl& u) { m_dirOperator->setUrl(u, true); } void KateFileBrowser::updateUrlNavigator(const KUrl& u) { m_urlNavigator->setUrl(u); } void KateFileBrowser::setActiveDocumentDir() { // kDebug(13001)<<"KateFileBrowser::setActiveDocumentDir()"; KUrl u = activeDocumentUrl(); // kDebug(13001)<<"URL: "<<u.prettyUrl(); if (!u.isEmpty()) setDir(u.upUrl()); // kDebug(13001)<<"... setActiveDocumentDir() DONE!"; } void KateFileBrowser::autoSyncFolder() { if (m_autoSyncFolder->isChecked()) { setActiveDocumentDir(); } } void KateFileBrowser::selectorViewChanged(QAbstractItemView * newView) { newView->setSelectionMode(QAbstractItemView::ExtendedSelection); } //END Private Slots //BEGIN Protected KUrl KateFileBrowser::activeDocumentUrl() { KTextEditor::View *v = m_mainWindow->activeView(); if (v) return v->document()->url(); return KUrl(); } //END Protected // kate: space-indent on; indent-width 2; replace-tabs on; <commit_msg>focus diroperator after chaing url in navigator<commit_after>/* This file is part of the KDE project Copyright (C) 2001 Christoph Cullmann <cullmann@kde.org> Copyright (C) 2001 Joseph Wenninger <jowenn@kde.org> Copyright (C) 2001 Anders Lund <anders.lund@lund.tdcadsl.dk> Copyright (C) 2007 Mirko Stocker <me@misto.ch> Copyright (C) 2009 Dominik Haumann <dhaumann kde org> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License version 2 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ //BEGIN Includes #include "katefilebrowser.h" #include "katefilebrowser.moc" #include "katebookmarkhandler.h" #include <ktexteditor/document.h> #include <ktexteditor/view.h> #include <KActionCollection> #include <KActionMenu> #include <KConfigGroup> #include <KDebug> #include <KDirOperator> #include <KFilePlacesModel> #include <KHistoryComboBox> #include <KLocale> #include <KToolBar> #include <KUrlNavigator> #include <QAbstractItemView> #include <QDir> #include <QLabel> #include <QLineEdit> #include <QToolButton> //END Includes KateFileBrowser::KateFileBrowser(Kate::MainWindow *mainWindow, QWidget * parent, const char * name) : KVBox (parent) , m_mainWindow(mainWindow) { setObjectName(name); m_toolbar = new KToolBar(this); m_toolbar->setMovable(false); m_toolbar->setToolButtonStyle(Qt::ToolButtonIconOnly); m_toolbar->setContextMenuPolicy(Qt::NoContextMenu); // includes some actions, but not hooked into the shortcut dialog atm m_actionCollection = new KActionCollection(this); m_actionCollection->addAssociatedWidget(this); KFilePlacesModel* model = new KFilePlacesModel(this); m_urlNavigator = new KUrlNavigator(model, KUrl(QDir::homePath()), this); connect(m_urlNavigator, SIGNAL(urlChanged(const KUrl&)), SLOT(updateDirOperator(const KUrl&))); m_dirOperator = new KDirOperator(KUrl(), this); m_dirOperator->setView(KFile::/* Simple */Detail); m_dirOperator->view()->setSelectionMode(QAbstractItemView::ExtendedSelection); connect(m_dirOperator, SIGNAL(viewChanged(QAbstractItemView *)), this, SLOT(selectorViewChanged(QAbstractItemView *))); m_dirOperator->setSizePolicy(QSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding)); setFocusProxy(m_dirOperator); // now all actions exist in dir operator and we can use them in the toolbar setupToolbar(); KHBox* filterBox = new KHBox(this); QLabel* filterLabel = new QLabel(i18n("Filter:"), filterBox); m_filter = new KHistoryComboBox(true, filterBox); filterLabel->setBuddy(m_filter); m_filter->setMaxCount(10); m_filter->setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed)); connect(m_filter, SIGNAL(editTextChanged(const QString&)), SLOT(slotFilterChange(const QString&))); connect(m_filter, SIGNAL(returnPressed(const QString&)), m_filter, SLOT(addToHistory(const QString&))); connect(m_filter, SIGNAL(returnPressed(const QString&)), m_dirOperator, SLOT(setFocus())); connect(m_dirOperator, SIGNAL(urlEntered(const KUrl&)), this, SLOT(updateUrlNavigator(const KUrl&))); // Connect the bookmark handler connect(m_bookmarkHandler, SIGNAL(openUrl(const QString&)), this, SLOT(setDir(const QString&))); m_filter->setWhatsThis(i18n("Enter a name filter to limit which files are displayed.")); connect(m_dirOperator, SIGNAL(fileSelected(const KFileItem&)), this, SLOT(fileSelected(const KFileItem&))); connect(m_mainWindow, SIGNAL(viewChanged()), this, SLOT(autoSyncFolder())); } KateFileBrowser::~KateFileBrowser() { } //END Constroctor/Destrctor //BEGIN Public Methods void KateFileBrowser::setupToolbar() { // remove all actions from the toolbar (there should be none) m_toolbar->clear(); // create action list QList<QAction*> actions; actions << m_dirOperator->actionCollection()->action("back"); actions << m_dirOperator->actionCollection()->action("forward"); // bookmarks action! KActionMenu *acmBookmarks = new KActionMenu(KIcon("bookmarks"), i18n("Bookmarks"), this); acmBookmarks->setDelayed(false); m_bookmarkHandler = new KateBookmarkHandler(this, acmBookmarks->menu()); acmBookmarks->setShortcutContext(Qt::WidgetWithChildrenShortcut); actions << acmBookmarks; // action for synchronising the dir operator with the current document path KAction* syncFolder = new KAction(this); syncFolder->setShortcutContext(Qt::WidgetWithChildrenShortcut); syncFolder->setText(i18n("Current Document Folder")); syncFolder->setIcon(KIcon("system-switch-user")); connect(syncFolder, SIGNAL(triggered()), this, SLOT(setActiveDocumentDir())); actions << syncFolder; // now add all actions to the toolbar foreach (QAction* ac, actions) { if (ac) { m_toolbar->addAction(ac); } } m_actionCollection->addAction("sync_dir", syncFolder); m_actionCollection->addAction("bookmarks", acmBookmarks); // section for settings menu KActionMenu *optionsMenu = new KActionMenu(KIcon("configure"), i18n("Options"), this); optionsMenu->setDelayed(false); optionsMenu->addAction(m_dirOperator->actionCollection()->action("short view")); optionsMenu->addAction(m_dirOperator->actionCollection()->action("detailed view")); optionsMenu->addAction(m_dirOperator->actionCollection()->action("tree view")); optionsMenu->addAction(m_dirOperator->actionCollection()->action("detailed tree view")); optionsMenu->addSeparator(); optionsMenu->addAction(m_dirOperator->actionCollection()->action("show hidden")); // action for synchronising the dir operator with the current document path m_autoSyncFolder = new KAction(this); m_autoSyncFolder->setCheckable(true); m_autoSyncFolder->setText(i18n("Automatically synchronize with current document")); m_autoSyncFolder->setIcon(KIcon("system-switch-user")); connect(m_autoSyncFolder, SIGNAL(triggered()), this, SLOT(autoSyncFolder())); optionsMenu->addAction(m_autoSyncFolder); m_toolbar->addSeparator(); m_toolbar->addAction(optionsMenu); } void KateFileBrowser::readSessionConfig(KConfigBase *config, const QString & name) { KConfigGroup cgDir(config, name + ":dir"); m_dirOperator->readConfig(cgDir); m_dirOperator->setView(KFile::Default); KConfigGroup cg(config, name); m_urlNavigator->setUrl(cg.readPathEntry("location", QDir::homePath())); setDir(cg.readPathEntry("location", QDir::homePath())); m_autoSyncFolder->setChecked(cg.readEntry("auto sync folder", false)); m_filter->setHistoryItems(cg.readEntry("filter history", QStringList()), true); } void KateFileBrowser::writeSessionConfig(KConfigBase *config, const QString & name) { KConfigGroup cgDir(config, name + ":dir"); m_dirOperator->writeConfig(cgDir); KConfigGroup cg = KConfigGroup(config, name); cg.writePathEntry("location", m_urlNavigator->url().url()); cg.writeEntry("auto sync folder", m_autoSyncFolder->isChecked()); cg.writeEntry("filter history", m_filter->historyItems()); } //END Public Methods //BEGIN Public Slots void KateFileBrowser::slotFilterChange(const QString & nf) { QString f = '*' + nf.trimmed() + '*'; const bool empty = f.isEmpty() || f == "*" || f == "**" || f == "***"; if (empty) { m_dirOperator->clearFilter(); m_filter->lineEdit()->clear(); } else { m_dirOperator->setNameFilter(f); } m_dirOperator->updateDir(); } bool kateFileSelectorIsReadable (const KUrl& url) { if (!url.isLocalFile()) return true; // what else can we say? QDir dir(url.toLocalFile()); return dir.exists (); } void KateFileBrowser::setDir(KUrl u) { KUrl newurl; if (!u.isValid()) newurl.setPath(QDir::homePath()); else newurl = u; QString pathstr = newurl.path(KUrl::AddTrailingSlash); newurl.setPath(pathstr); if (!kateFileSelectorIsReadable (newurl)) newurl.cd(QString::fromLatin1("..")); if (!kateFileSelectorIsReadable (newurl)) newurl.setPath(QDir::homePath()); m_dirOperator->setUrl(newurl, true); } //END Public Slots //BEGIN Private Slots void KateFileBrowser::fileSelected(const KFileItem & /*file*/) { openSelectedFiles(); } void KateFileBrowser::openSelectedFiles() { const KFileItemList list = m_dirOperator->selectedItems(); foreach (const KFileItem& item, list) { m_mainWindow->openUrl(item.url()); } m_dirOperator->view()->selectionModel()->clear(); } void KateFileBrowser::updateDirOperator(const KUrl& u) { m_dirOperator->setFocus(); m_dirOperator->setUrl(u, true); } void KateFileBrowser::updateUrlNavigator(const KUrl& u) { m_urlNavigator->setUrl(u); } void KateFileBrowser::setActiveDocumentDir() { // kDebug(13001)<<"KateFileBrowser::setActiveDocumentDir()"; KUrl u = activeDocumentUrl(); // kDebug(13001)<<"URL: "<<u.prettyUrl(); if (!u.isEmpty()) setDir(u.upUrl()); // kDebug(13001)<<"... setActiveDocumentDir() DONE!"; } void KateFileBrowser::autoSyncFolder() { if (m_autoSyncFolder->isChecked()) { setActiveDocumentDir(); } } void KateFileBrowser::selectorViewChanged(QAbstractItemView * newView) { newView->setSelectionMode(QAbstractItemView::ExtendedSelection); } //END Private Slots //BEGIN Protected KUrl KateFileBrowser::activeDocumentUrl() { KTextEditor::View *v = m_mainWindow->activeView(); if (v) return v->document()->url(); return KUrl(); } //END Protected // kate: space-indent on; indent-width 2; replace-tabs on; <|endoftext|>
<commit_before>#include "DataLikelihood.h" #include "multichoose.h" #include "multipermute.h" long double probObservedAllelesGivenGenotype( Sample& sample, Genotype& genotype, long double dependenceFactor, bool useMapQ) { int observationCount = sample.observationCount(); vector<long double> alleleProbs = genotype.alleleProbabilities(); vector<int> observationCounts = genotype.alleleObservationCounts(sample); int countOut = 0; long double prodQout = 0; // the probability that the reads not in the genotype are all wrong for (Sample::iterator s = sample.begin(); s != sample.end(); ++s) { const string& base = s->first; if (!genotype.containsAllele(base)) { vector<Allele*>& alleles = s->second; if (useMapQ) { for (vector<Allele*>::iterator a = alleles.begin(); a != alleles.end(); ++a) { prodQout += (*a)->lnquality + (*a)->lnmapQuality; } } else { for (vector<Allele*>::iterator a = alleles.begin(); a != alleles.end(); ++a) { prodQout += (*a)->lnquality; } } countOut += alleles.size(); } } // read dependence factor, asymptotically downgrade quality values of // successive reads to dependenceFactor * quality if (countOut > 1) { prodQout *= (1 + (countOut - 1) * dependenceFactor) / countOut; } if (sum(observationCounts) == 0) { return prodQout; } else { return prodQout + multinomialSamplingProbLn(alleleProbs, observationCounts); } } vector<pair<Genotype*, long double> > probObservedAllelesGivenGenotypes( Sample& sample, vector<Genotype*>& genotypes, long double dependenceFactor, bool useMapQ) { vector<pair<Genotype*, long double> > results; for (vector<Genotype*>::iterator g = genotypes.begin(); g != genotypes.end(); ++g) { results.push_back(make_pair(*g, probObservedAllelesGivenGenotype(sample, **g, dependenceFactor, useMapQ))); } return results; } <commit_msg>take the minimum of base quality and mapping quality<commit_after>#include "DataLikelihood.h" #include "multichoose.h" #include "multipermute.h" long double probObservedAllelesGivenGenotype( Sample& sample, Genotype& genotype, long double dependenceFactor, bool useMapQ) { int observationCount = sample.observationCount(); vector<long double> alleleProbs = genotype.alleleProbabilities(); vector<int> observationCounts = genotype.alleleObservationCounts(sample); int countOut = 0; long double prodQout = 0; // the probability that the reads not in the genotype are all wrong for (Sample::iterator s = sample.begin(); s != sample.end(); ++s) { const string& base = s->first; if (!genotype.containsAllele(base)) { vector<Allele*>& alleles = s->second; if (useMapQ) { for (vector<Allele*>::iterator a = alleles.begin(); a != alleles.end(); ++a) { // take the lesser of mapping quality and base quality (in log space) prodQout += max((*a)->lnquality, (*a)->lnmapQuality); } } else { for (vector<Allele*>::iterator a = alleles.begin(); a != alleles.end(); ++a) { prodQout += (*a)->lnquality; } } countOut += alleles.size(); } } // read dependence factor, asymptotically downgrade quality values of // successive reads to dependenceFactor * quality if (countOut > 1) { prodQout *= (1 + (countOut - 1) * dependenceFactor) / countOut; } if (sum(observationCounts) == 0) { return prodQout; } else { return prodQout + multinomialSamplingProbLn(alleleProbs, observationCounts); } } vector<pair<Genotype*, long double> > probObservedAllelesGivenGenotypes( Sample& sample, vector<Genotype*>& genotypes, long double dependenceFactor, bool useMapQ) { vector<pair<Genotype*, long double> > results; for (vector<Genotype*>::iterator g = genotypes.begin(); g != genotypes.end(); ++g) { results.push_back(make_pair(*g, probObservedAllelesGivenGenotype(sample, **g, dependenceFactor, useMapQ))); } return results; } <|endoftext|>
<commit_before>/****************************************************************************** * This file is part of the Gluon Development Platform * Copyright (C) 2010 Dan Leinir Turthra Jensen <admin@leinir.dk> * * 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 "prefabprivate.h" #include "engine/gameobject.h" #include "prefabinstance.h" #include "prefabinstancechild.h" using namespace GluonEngine; PrefabPrivate::PrefabPrivate() : gameObject( 0 ) , preCacheSize( 0 ) , additionalCacheSize( 0 ) { } PrefabPrivate::PrefabPrivate( const PrefabPrivate& other ) : instances( other.instances ) , gameObject( other.gameObject ) , preCacheSize( 0 ) , additionalCacheSize( 0 ) { } PrefabPrivate::~PrefabPrivate() { delete( gameObject ); } void PrefabPrivate::updateChildrenFromOther(GluonCore::GluonObject* updateThis, const GluonCore::GluonObject* updateFrom) { // Firstly, we have to ensure the children are in the right place (otherwise the next bit might // not function correctly) moveChildrenIntoPlace(updateThis, updateFrom); removeAndAddChildren(updateThis, updateFrom); } void PrefabPrivate::moveChildrenIntoPlace(GluonCore::GluonObject* updateThis, const GluonCore::GluonObject* updateFrom) { // Go through all children recursively on "updateFrom" and... foreach(QObject* child, updateFrom->children()) { GluonCore::GluonObject* childObject = qobject_cast<GluonCore::GluonObject*>(child); if(!childObject) continue; // operate on a local list of children, so as to easily allow for the removal of children // in the end QObjectList otherChildList = updateThis->children(); foreach(QObject* otherChild, otherChildList) { GluonCore::GluonObject* otherChildObject = qobject_cast<GluonCore::GluonObject*>(otherChild); if(!otherChildObject) continue; // recurse... moveChildrenIntoPlace(otherChildObject, childObject); otherChildList.removeOne(otherChild); } // If there are children left in the list... foreach(QObject* otherChild, otherChildList) { otherChild->deleteLater(); } } } void PrefabPrivate::removeAndAddChildren(GluonCore::GluonObject* updateThis, const GluonCore::GluonObject* updateFrom) { // Go through all children on "updateThis" and remove all objects which no longer // exist on updateFrom foreach(QObject* child, updateThis->children()) { GluonCore::GluonObject* childObject = qobject_cast<GluonCore::GluonObject*>(child); if(!childObject) continue; // Check if the child in the item we're updating still exists in the item we're updating from QString qualifiedName = childObject->qualifiedName(gameObject); GluonCore::GluonObject* otherChild = updateFrom->findItemByName(qualifiedName); if(!otherChild) { // If we've not found the child, that means it was deleted, and we should remove it // from here as well updateThis->removeChild(childObject); childObject->deleteLater(); // Remove object with same name on all linked instances foreach(PrefabInstance* linkedInstance, instances) { GluonCore::GluonObject* linkedChild = linkedInstance->findItemByName(qualifiedName); if(linkedChild) { GluonCore::GluonObject* linkedParent = qobject_cast< GluonCore::GluonObject* >(linkedChild->parent()); linkedParent->removeChild(linkedChild); linkedChild->deleteLater(); } } } } // Go through all children on "updateFrom" and add all new objects to updateThis foreach(QObject* child, updateFrom->children()) { GluonCore::GluonObject* childObject = qobject_cast<GluonCore::GluonObject*>(child); if(!childObject) continue; // Check if the child in the item we're updating from exists in the item we're updating GluonCore::GluonObject* otherChild = updateThis->findItemByName(childObject->name()); if(!otherChild) { // Clone the new child... QString qualifiedName = otherChild->qualifiedName(gameObject); GluonCore::GluonObject* clone = otherChild->clone(updateThis); // - add object in same position on all linked instances foreach(PrefabInstance* linkedInstance, instances) { if(qobject_cast<GameObject*>(clone)) { // If new object is a GameObject, we need to add it as a PrefabInstanceChild... PrefabInstanceChild* newChildInstance = new PrefabInstanceChild(); linkedInstance->addChild(newChildInstance); // Clone the tree from the cloned GameObject newChildInstance->cloneFromGameObject(qobject_cast<GameObject*>(clone)); } else { // Otherwise, just clone it verbatim GluonCore::GluonObject* newInstanceChild = clone->clone(linkedInstance); // Reclone properties Prefab::cloneObjectProperties(newInstanceChild, clone); } } } } // Finally. go through all children on "updateFrom" and... foreach(QObject* child, updateFrom->children()) { GluonCore::GluonObject* childObject = qobject_cast<GluonCore::GluonObject*>(child); if(!childObject) continue; //...recurse GluonCore::GluonObject* otherChildObject = updateThis->findItemByName(childObject->name()); if(otherChildObject) removeAndAddChildren(otherChildObject, childObject); } } <commit_msg>clone() already clones properties, no need to do it again<commit_after>/****************************************************************************** * This file is part of the Gluon Development Platform * Copyright (C) 2010 Dan Leinir Turthra Jensen <admin@leinir.dk> * * 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 "prefabprivate.h" #include "engine/gameobject.h" #include "prefabinstance.h" #include "prefabinstancechild.h" using namespace GluonEngine; PrefabPrivate::PrefabPrivate() : gameObject( 0 ) , preCacheSize( 0 ) , additionalCacheSize( 0 ) { } PrefabPrivate::PrefabPrivate( const PrefabPrivate& other ) : instances( other.instances ) , gameObject( other.gameObject ) , preCacheSize( 0 ) , additionalCacheSize( 0 ) { } PrefabPrivate::~PrefabPrivate() { delete( gameObject ); } void PrefabPrivate::updateChildrenFromOther(GluonCore::GluonObject* updateThis, const GluonCore::GluonObject* updateFrom) { // Firstly, we have to ensure the children are in the right place (otherwise the next bit might // not function correctly) moveChildrenIntoPlace(updateThis, updateFrom); removeAndAddChildren(updateThis, updateFrom); } void PrefabPrivate::moveChildrenIntoPlace(GluonCore::GluonObject* updateThis, const GluonCore::GluonObject* updateFrom) { // Go through all children recursively on "updateFrom" and... foreach(QObject* child, updateFrom->children()) { GluonCore::GluonObject* childObject = qobject_cast<GluonCore::GluonObject*>(child); if(!childObject) continue; // operate on a local list of children, so as to easily allow for the removal of children // in the end QObjectList otherChildList = updateThis->children(); foreach(QObject* otherChild, otherChildList) { GluonCore::GluonObject* otherChildObject = qobject_cast<GluonCore::GluonObject*>(otherChild); if(!otherChildObject) continue; // recurse... moveChildrenIntoPlace(otherChildObject, childObject); otherChildList.removeOne(otherChild); } // If there are children left in the list... foreach(QObject* otherChild, otherChildList) { otherChild->deleteLater(); } } } void PrefabPrivate::removeAndAddChildren(GluonCore::GluonObject* updateThis, const GluonCore::GluonObject* updateFrom) { // Go through all children on "updateThis" and remove all objects which no longer // exist on updateFrom foreach(QObject* child, updateThis->children()) { GluonCore::GluonObject* childObject = qobject_cast<GluonCore::GluonObject*>(child); if(!childObject) continue; // Check if the child in the item we're updating still exists in the item we're updating from QString qualifiedName = childObject->qualifiedName(gameObject); GluonCore::GluonObject* otherChild = updateFrom->findItemByName(qualifiedName); if(!otherChild) { // If we've not found the child, that means it was deleted, and we should remove it // from here as well updateThis->removeChild(childObject); childObject->deleteLater(); // Remove object with same name on all linked instances foreach(PrefabInstance* linkedInstance, instances) { GluonCore::GluonObject* linkedChild = linkedInstance->findItemByName(qualifiedName); if(linkedChild) { GluonCore::GluonObject* linkedParent = qobject_cast< GluonCore::GluonObject* >(linkedChild->parent()); linkedParent->removeChild(linkedChild); linkedChild->deleteLater(); } } } } // Go through all children on "updateFrom" and add all new objects to updateThis foreach(QObject* child, updateFrom->children()) { GluonCore::GluonObject* childObject = qobject_cast<GluonCore::GluonObject*>(child); if(!childObject) continue; // Check if the child in the item we're updating from exists in the item we're updating GluonCore::GluonObject* otherChild = updateThis->findItemByName(childObject->name()); if(!otherChild) { // Clone the new child... QString qualifiedName = otherChild->qualifiedName(gameObject); GluonCore::GluonObject* clone = otherChild->clone(updateThis); // - add object in same position on all linked instances foreach(PrefabInstance* linkedInstance, instances) { if(qobject_cast<GameObject*>(clone)) { // If new object is a GameObject, we need to add it as a PrefabInstanceChild... PrefabInstanceChild* newChildInstance = new PrefabInstanceChild(); linkedInstance->addChild(newChildInstance); // Clone the tree from the cloned GameObject newChildInstance->cloneFromGameObject(qobject_cast<GameObject*>(clone)); } else { // Otherwise, just clone it verbatim GluonCore::GluonObject* newInstanceChild = clone->clone(linkedInstance); } } } } // Finally. go through all children on "updateFrom" and... foreach(QObject* child, updateFrom->children()) { GluonCore::GluonObject* childObject = qobject_cast<GluonCore::GluonObject*>(child); if(!childObject) continue; //...recurse GluonCore::GluonObject* otherChildObject = updateThis->findItemByName(childObject->name()); if(otherChildObject) removeAndAddChildren(otherChildObject, childObject); } } <|endoftext|>
<commit_before>/** * @file * @author Jason Lingle * @date 2012.02.04 * @brief Implementation of NetworkConnection class */ #include <iostream> #include <SDL.h> #include "network_connection.hxx" #include "network_assembly.hxx" #include "network_geraet.hxx" #include "antenna.hxx" #include "io.hxx" #include "src/sim/game_field.hxx" #include "src/sim/game_object.hxx" using namespace std; NetworkConnection::geraetNumMap_t* NetworkConnection::geraetNumMap; NetworkConnection::NetworkConnection(NetworkAssembly* assembly_, const Antenna::endpoint& endpoint_, bool incomming) : field(assembly_->field->width, assembly_->field->height), nextOutSeq(0), greatestSeq(0), latency(0), lastIncommingTime(SDL_GetTicks()), status(incomming? Established : Connecting), endpoint(endpoint_), parent(assembly_), scg(NULL) //TODO: replace with actual object later { //TODO: put SCG in channel map } NetworkConnection::~NetworkConnection() { //scg is stored within the channel map, so we don't have to explicitly //delete it. for (geraete_t::const_iterator it = geraete.begin(); it != geraete.end(); ++it) delete it->second; } void NetworkConnection::update(unsigned et) noth { //TODO: do something } void NetworkConnection::process(const Antenna::endpoint& source, Antenna* antenna, Tuner* tuner, const byte* data, unsigned datlen) noth { if (datlen < 4) { //Packet does not even have a header #ifdef DEBUG cerr << "Warning: Dropping packet of length " << datlen << " from source " << source << endl; #endif return; } channel chan; seq_t seq; io::read(data, seq); io::read(data, chan); datlen -= 4; //Range check if (seq-greatestSeq < 1024 || greatestSeq-seq < 1024) { //Dupe check if (recentlyReceived.count(seq) == 0) { //Possibly update greatestSeq if (seq-greatestSeq < 1024) greatestSeq = seq; //OK, add to set and queue, possibly trim both recentlyReceived.insert(seq); recentlyReceivedQueue.push_back(seq); if (recentlyReceivedQueue.size() > 1024) { recentlyReceived.erase(recentlyReceivedQueue.front()); recentlyReceivedQueue.pop_front(); } //Accept packet; does the channel exist? chanmap_t::const_iterator it = locchan.find(chan); if (it != locchan.end()) { it->second->receive(seq, data, datlen); } else { #ifdef DEBUG cerr << "Warning: Dropping packet to closed channel " << chan << " from source " << source << endl; #endif } } } else { #ifdef DEBUG cerr << "Warning: Dropping packet of seq " << seq << " due to range check; greatestSeq = " << greatestSeq << "; from source " << source << endl; #endif } } <commit_msg>Maintain lastIncommingTime in NetworkConnection.<commit_after>/** * @file * @author Jason Lingle * @date 2012.02.04 * @brief Implementation of NetworkConnection class */ #include <iostream> #include <SDL.h> #include "network_connection.hxx" #include "network_assembly.hxx" #include "network_geraet.hxx" #include "antenna.hxx" #include "io.hxx" #include "src/sim/game_field.hxx" #include "src/sim/game_object.hxx" using namespace std; NetworkConnection::geraetNumMap_t* NetworkConnection::geraetNumMap; NetworkConnection::NetworkConnection(NetworkAssembly* assembly_, const Antenna::endpoint& endpoint_, bool incomming) : field(assembly_->field->width, assembly_->field->height), nextOutSeq(0), greatestSeq(0), latency(0), lastIncommingTime(SDL_GetTicks()), status(incomming? Established : Connecting), endpoint(endpoint_), parent(assembly_), scg(NULL) //TODO: replace with actual object later { //TODO: put SCG in channel map } NetworkConnection::~NetworkConnection() { //scg is stored within the channel map, so we don't have to explicitly //delete it. for (geraete_t::const_iterator it = geraete.begin(); it != geraete.end(); ++it) delete it->second; } void NetworkConnection::update(unsigned et) noth { //TODO: do something } void NetworkConnection::process(const Antenna::endpoint& source, Antenna* antenna, Tuner* tuner, const byte* data, unsigned datlen) noth { if (datlen < 4) { //Packet does not even have a header #ifdef DEBUG cerr << "Warning: Dropping packet of length " << datlen << " from source " << source << endl; #endif return; } channel chan; seq_t seq; io::read(data, seq); io::read(data, chan); datlen -= 4; //Range check if (seq-greatestSeq < 1024 || greatestSeq-seq < 1024) { //Dupe check if (recentlyReceived.count(seq) == 0) { //Possibly update greatestSeq if (seq-greatestSeq < 1024) greatestSeq = seq; //OK, add to set and queue, possibly trim both recentlyReceived.insert(seq); recentlyReceivedQueue.push_back(seq); if (recentlyReceivedQueue.size() > 1024) { recentlyReceived.erase(recentlyReceivedQueue.front()); recentlyReceivedQueue.pop_front(); } //Update time of most recent receive lastIncommingTime = SDL_GetTicks(); //Accept packet; does the channel exist? chanmap_t::const_iterator it = locchan.find(chan); if (it != locchan.end()) { it->second->receive(seq, data, datlen); } else { #ifdef DEBUG cerr << "Warning: Dropping packet to closed channel " << chan << " from source " << source << endl; #endif } } } else { #ifdef DEBUG cerr << "Warning: Dropping packet of seq " << seq << " due to range check; greatestSeq = " << greatestSeq << "; from source " << source << endl; #endif } } <|endoftext|>
<commit_before>#include <Arduino.h> #include "DollhousePanel.h" #include "TimingHelpers.h" #include <Adafruit_TLC59711.h> #include <Adafruit_NeoPixel.h> #include <LiquidCrystal.h> #include <SPI.h> #include <Fsm.h> #include <EnableInterrupt.h> const char NUM_TLC59711 = 1; const char TLC_DATA = 12; const char TLC_CLK = 13; const char PIXEL_COUNT = 3; const char PIXEL_PIN = 8; enum events { CHANGE_LIGHT_MODE, NEXT_ROOM, PREVIOUS_ROOM, RESET_ROOMS }; // Lighting modes finite state machine State state_lighting_mode(on_lighting_mode_enter, NULL, &on_lighting_mode_exit); State state_party_mode(on_party_mode_enter, NULL, &on_party_mode_exit); State state_nitelite_mode(on_nitelite_mode_enter, NULL, &on_nitelite_mode_exit); State state_off_mode(on_off_mode_enter, NULL, &on_off_mode_exit); Fsm modes(&state_off_mode); enum Modes { LIGHTING_MODE, PARTY_MODE, NITELITE_MODE, OFF_MODE }; String modeNames[] = {"Lighting", "Party", "Nitelite", "Off"}; // Rooms finite state machine State state_all_rooms(on_all_enter, NULL, &on_all_exit); State state_hall(on_hall_enter, NULL, &on_hall_exit); State state_living_room(on_living_room_enter, NULL, &on_living_room_exit); State state_kitchen(on_kitchen_enter, NULL, &on_kitchen_exit); State state_bedroom(on_bedroom_enter, NULL, &on_bedroom_exit); State state_bathroom(on_bathroom_enter, NULL, &on_bathroom_exit); State state_attic(on_attic_enter, NULL, &on_attic_exit); Fsm rooms(&state_all_rooms); // LastROOM is included to make it easier to figure out the size of the enum // for things like sizing the brightness state array enum Rooms { ALL_ROOMS, LIVING_ROOM, HALL, KITCHEN, BEDROOM, BATHROOM, ATTIC, LastROOM }; String roomNames[] = {"All", "Living", "Hall", "Kitchen", "Bedroom", "Bathroom", "Attic"}; // NeoPixels (for the attic & !!!PARTY MODE!!!) Adafruit_NeoPixel strip = Adafruit_NeoPixel(PIXEL_COUNT, PIXEL_PIN, NEO_GRB + NEO_KHZ800); // PWM board (controls the room lights) Adafruit_TLC59711 tlc = Adafruit_TLC59711(NUM_TLC59711, TLC_CLK, TLC_DATA); // 16x2 LCD display LiquidCrystal lcd(7, 6, 5, 4, 3, 2); // Panel RGB LED pins const char RED_PIN = 9; const char GREEN_PIN = 10; const char BLUE_PIN = 11; int brightness = 90; int deltaLevel = 30; int minLevel = 0; int maxLevel = 180; int roomBrightness[LastROOM]; int currentRoom = ALL_ROOMS; int currentMode = OFF_MODE; int debounceDelay = 150; long timeDebounce = 0; void setup() { // Fire up the LCD display lcd.begin(16, 2); pinMode(RED_PIN, OUTPUT); pinMode(GREEN_PIN, OUTPUT); pinMode(BLUE_PIN, OUTPUT); // initialize the NeoPixel strand strip.begin(); strip.show(); // Initialize the PWM board tlc.begin(); tlc.write(); // set defualt room brightness setDefaultLightLevel(); // enable interrupts on buttons // The button interface is a Smartmaker 5A5 (annoying, but it works) enableInterrupt(A0, handleButtonOne, FALLING); enableInterrupt(A1, handleButtonTwo, FALLING); enableInterrupt(A2, handleButtonThree, FALLING); enableInterrupt(A3, handleButtonFour, FALLING); enableInterrupt(A4, handleButtonFive, FALLING); // mode FSM transitions modes.add_transition(&state_off_mode, &state_lighting_mode, CHANGE_LIGHT_MODE, NULL); modes.add_transition(&state_lighting_mode, &state_party_mode, CHANGE_LIGHT_MODE, NULL); modes.add_transition(&state_party_mode, &state_nitelite_mode, CHANGE_LIGHT_MODE, NULL); modes.add_transition(&state_nitelite_mode, &state_off_mode, CHANGE_LIGHT_MODE, NULL); // rooms FSM transitions // looping "forward" through the rooms rooms.add_transition(&state_all_rooms, &state_hall, NEXT_ROOM, NULL); rooms.add_transition(&state_hall, &state_living_room, NEXT_ROOM, NULL); rooms.add_transition(&state_living_room, &state_kitchen, NEXT_ROOM, NULL); rooms.add_transition(&state_kitchen, &state_bedroom, NEXT_ROOM, NULL); rooms.add_transition(&state_bedroom, &state_bathroom, NEXT_ROOM, NULL); rooms.add_transition(&state_bathroom, &state_attic, NEXT_ROOM, NULL); rooms.add_transition(&state_attic, &state_all_rooms, NEXT_ROOM, NULL); // looping "backward" through the rooms rooms.add_transition(&state_all_rooms, &state_attic, PREVIOUS_ROOM, NULL); rooms.add_transition(&state_attic, &state_bathroom, PREVIOUS_ROOM, NULL); rooms.add_transition(&state_bathroom, &state_bedroom, PREVIOUS_ROOM, NULL); rooms.add_transition(&state_bedroom, &state_kitchen, PREVIOUS_ROOM, NULL); rooms.add_transition(&state_kitchen, &state_living_room, PREVIOUS_ROOM, NULL); rooms.add_transition(&state_living_room, &state_hall, PREVIOUS_ROOM, NULL); rooms.add_transition(&state_hall, &state_all_rooms, PREVIOUS_ROOM, NULL); // resetting to the default room (all rooms) rooms.add_transition(&state_hall, &state_all_rooms, RESET_ROOMS, NULL); rooms.add_transition(&state_living_room, &state_all_rooms, RESET_ROOMS, NULL); rooms.add_transition(&state_kitchen, &state_all_rooms, RESET_ROOMS, NULL); rooms.add_transition(&state_bedroom, &state_all_rooms, RESET_ROOMS, NULL); rooms.add_transition(&state_bathroom, &state_all_rooms, RESET_ROOMS, NULL); rooms.add_transition(&state_attic, &state_all_rooms, RESET_ROOMS, NULL); // run each state machine once to initialize them; this is basically a NOOP // thanks the default state rooms.run_machine(); modes.run_machine(); lcd.clear(); lcd.print("Doll house"); lcd.setCursor(0,1); lcd.print("lighting!"); } // ***** Button event handlers ***** // // Use button one to set the light mode for all rooms void handleButtonOne() { if (!still_bouncing()) { lcd.clear(); rooms.trigger(RESET_ROOMS); modes.trigger(CHANGE_LIGHT_MODE); } } // Use button two to increase brightness for the current room void handleButtonTwo() { if (!still_bouncing()) { setRoomBrightness(currentRoom, min(roomBrightness[currentRoom] + deltaLevel, maxLevel)); printCurrentRoom(); } } // Use button three to select the previous room void handleButtonThree() { if (!still_bouncing()) { lcd.clear(); rooms.trigger(PREVIOUS_ROOM); } } // Use button four to decrease brightness for the current room void handleButtonFour() { if (!still_bouncing()) { setRoomBrightness(currentRoom, max(roomBrightness[currentRoom] - deltaLevel, minLevel)); printCurrentRoom(); } } // Use button five to select the next room void handleButtonFive() { if (!still_bouncing()) { lcd.clear(); rooms.trigger(NEXT_ROOM); } } // ***** helpers ***** // void setRGBColor(int red, int green, int blue) { int myRed = constrain(red, 0, 255); int myGreen = constrain(green, 0, 255); int myBlue = constrain(blue, 0, 255); analogWrite(RED_PIN, myRed); analogWrite(GREEN_PIN, myGreen); analogWrite(BLUE_PIN, myBlue); } void setRoomBrightness(int room, int level) { setRGBColor(0,0,level); roomBrightness[room] = level; tlc.setPWM(room * 3, roomBrightness[room] * maxLevel); tlc.write(); } void setDefaultLightLevel() { setRGBColor(0,0,brightness); for (int i = 0; i != LastROOM; i++) { roomBrightness[i] = brightness; } } void setCurrentMode(int mode) { currentMode = mode; printCurrentMode(); } void printCurrentMode() { lcd.clear(); lcd.print("Mode: "); lcd.print(modeNames[currentMode]); } void setCurrentRoom(int room) { currentRoom = room; setRGBColor(0,0,roomBrightness[room]); printCurrentRoom(); } void printCurrentRoom() { lcd.clear(); lcd.print("room: "); lcd.print(roomNames[currentRoom]); lcd.setCursor(0,1); lcd.print("brightness: "); lcd.print(roomBrightness[currentRoom]); } // ***** FSM event handlers ***** // // ---- lighting mode states ---- // void on_lighting_mode_enter(){ setCurrentMode(LIGHTING_MODE); } void on_lighting_mode_exit(){ } void on_party_mode_enter(){ setCurrentMode(PARTY_MODE); } void on_party_mode_exit(){ } void on_nitelite_mode_enter(){ setCurrentMode(NITELITE_MODE); } void on_nitelite_mode_exit(){ } void on_off_mode_enter(){ setCurrentMode(OFF_MODE); } void on_off_mode_exit(){ } // ---- room selection states ---- // void on_all_enter() { setCurrentRoom(ALL_ROOMS); } void on_all_exit() { } void on_hall_enter() { setCurrentRoom(HALL); } void on_hall_exit() { } void on_living_room_enter() { setCurrentRoom(LIVING_ROOM); } void on_living_room_exit() { } void on_kitchen_enter() { setCurrentRoom(KITCHEN); } void on_kitchen_exit() { } void on_bathroom_enter() { setCurrentRoom(BATHROOM); } void on_bathroom_exit() { } void on_bedroom_enter() { setCurrentRoom(BEDROOM); } void on_bedroom_exit() { } void on_attic_enter() { setCurrentRoom(ATTIC); } void on_attic_exit() { } // Debonce timer boolean still_bouncing() { // If the debounce timer is not running, then we can assume the buttons // aren't bouncing because nothing has been pressed recently if (timerDebounce == 0) { startTimer(timerDebounce); return false; } if (timerIsExpired(timerDebounce, debounceDelay)) { clearTimer(timerDebounce); startTimer(timerDebounce); return false; } return true; } void loop() { // do nothing; everything is handled via FSM events. // We also don't need to call the ".run_machine" methods of // the FSMs as there are no "on_state" handlers or timed transitions } <commit_msg>Fixed timer<commit_after>#include <Arduino.h> #include "DollhousePanel.h" #include "TimingHelpers.h" #include <Adafruit_TLC59711.h> #include <Adafruit_NeoPixel.h> #include <LiquidCrystal.h> #include <SPI.h> #include <Fsm.h> #include <EnableInterrupt.h> const char NUM_TLC59711 = 1; const char TLC_DATA = 12; const char TLC_CLK = 13; const char PIXEL_COUNT = 3; const char PIXEL_PIN = 8; enum events { CHANGE_LIGHT_MODE, NEXT_ROOM, PREVIOUS_ROOM, RESET_ROOMS }; // Lighting modes finite state machine State state_lighting_mode(on_lighting_mode_enter, NULL, &on_lighting_mode_exit); State state_party_mode(on_party_mode_enter, NULL, &on_party_mode_exit); State state_nitelite_mode(on_nitelite_mode_enter, NULL, &on_nitelite_mode_exit); State state_off_mode(on_off_mode_enter, NULL, &on_off_mode_exit); Fsm modes(&state_off_mode); enum Modes { LIGHTING_MODE, PARTY_MODE, NITELITE_MODE, OFF_MODE }; String modeNames[] = {"Lighting", "Party", "Nitelite", "Off"}; // Rooms finite state machine State state_all_rooms(on_all_enter, NULL, &on_all_exit); State state_hall(on_hall_enter, NULL, &on_hall_exit); State state_living_room(on_living_room_enter, NULL, &on_living_room_exit); State state_kitchen(on_kitchen_enter, NULL, &on_kitchen_exit); State state_bedroom(on_bedroom_enter, NULL, &on_bedroom_exit); State state_bathroom(on_bathroom_enter, NULL, &on_bathroom_exit); State state_attic(on_attic_enter, NULL, &on_attic_exit); Fsm rooms(&state_all_rooms); // LastROOM is included to make it easier to figure out the size of the enum // for things like sizing the brightness state array enum Rooms { ALL_ROOMS, LIVING_ROOM, HALL, KITCHEN, BEDROOM, BATHROOM, ATTIC, LastROOM }; String roomNames[] = {"All", "Living", "Hall", "Kitchen", "Bedroom", "Bathroom", "Attic"}; // NeoPixels (for the attic & !!!PARTY MODE!!!) Adafruit_NeoPixel strip = Adafruit_NeoPixel(PIXEL_COUNT, PIXEL_PIN, NEO_GRB + NEO_KHZ800); // PWM board (controls the room lights) Adafruit_TLC59711 tlc = Adafruit_TLC59711(NUM_TLC59711, TLC_CLK, TLC_DATA); // 16x2 LCD display LiquidCrystal lcd(7, 6, 5, 4, 3, 2); // Panel RGB LED pins const char RED_PIN = 9; const char GREEN_PIN = 10; const char BLUE_PIN = 11; int brightness = 90; int deltaLevel = 30; int minLevel = 0; int maxLevel = 180; int roomBrightness[LastROOM]; int currentRoom = ALL_ROOMS; int currentMode = OFF_MODE; int debounceDelay = 150; long timerDebounce = 0; void setup() { // Fire up the LCD display lcd.begin(16, 2); pinMode(RED_PIN, OUTPUT); pinMode(GREEN_PIN, OUTPUT); pinMode(BLUE_PIN, OUTPUT); // initialize the NeoPixel strand strip.begin(); strip.show(); // Initialize the PWM board tlc.begin(); tlc.write(); // set defualt room brightness setDefaultLightLevel(); // enable interrupts on buttons // The button interface is a Smartmaker 5A5 (annoying, but it works) enableInterrupt(A0, handleButtonOne, FALLING); enableInterrupt(A1, handleButtonTwo, FALLING); enableInterrupt(A2, handleButtonThree, FALLING); enableInterrupt(A3, handleButtonFour, FALLING); enableInterrupt(A4, handleButtonFive, FALLING); // mode FSM transitions modes.add_transition(&state_off_mode, &state_lighting_mode, CHANGE_LIGHT_MODE, NULL); modes.add_transition(&state_lighting_mode, &state_party_mode, CHANGE_LIGHT_MODE, NULL); modes.add_transition(&state_party_mode, &state_nitelite_mode, CHANGE_LIGHT_MODE, NULL); modes.add_transition(&state_nitelite_mode, &state_off_mode, CHANGE_LIGHT_MODE, NULL); // rooms FSM transitions // looping "forward" through the rooms rooms.add_transition(&state_all_rooms, &state_hall, NEXT_ROOM, NULL); rooms.add_transition(&state_hall, &state_living_room, NEXT_ROOM, NULL); rooms.add_transition(&state_living_room, &state_kitchen, NEXT_ROOM, NULL); rooms.add_transition(&state_kitchen, &state_bedroom, NEXT_ROOM, NULL); rooms.add_transition(&state_bedroom, &state_bathroom, NEXT_ROOM, NULL); rooms.add_transition(&state_bathroom, &state_attic, NEXT_ROOM, NULL); rooms.add_transition(&state_attic, &state_all_rooms, NEXT_ROOM, NULL); // looping "backward" through the rooms rooms.add_transition(&state_all_rooms, &state_attic, PREVIOUS_ROOM, NULL); rooms.add_transition(&state_attic, &state_bathroom, PREVIOUS_ROOM, NULL); rooms.add_transition(&state_bathroom, &state_bedroom, PREVIOUS_ROOM, NULL); rooms.add_transition(&state_bedroom, &state_kitchen, PREVIOUS_ROOM, NULL); rooms.add_transition(&state_kitchen, &state_living_room, PREVIOUS_ROOM, NULL); rooms.add_transition(&state_living_room, &state_hall, PREVIOUS_ROOM, NULL); rooms.add_transition(&state_hall, &state_all_rooms, PREVIOUS_ROOM, NULL); // resetting to the default room (all rooms) rooms.add_transition(&state_hall, &state_all_rooms, RESET_ROOMS, NULL); rooms.add_transition(&state_living_room, &state_all_rooms, RESET_ROOMS, NULL); rooms.add_transition(&state_kitchen, &state_all_rooms, RESET_ROOMS, NULL); rooms.add_transition(&state_bedroom, &state_all_rooms, RESET_ROOMS, NULL); rooms.add_transition(&state_bathroom, &state_all_rooms, RESET_ROOMS, NULL); rooms.add_transition(&state_attic, &state_all_rooms, RESET_ROOMS, NULL); // run each state machine once to initialize them; this is basically a NOOP // thanks the default state rooms.run_machine(); modes.run_machine(); lcd.clear(); lcd.print("Doll house"); lcd.setCursor(0,1); lcd.print("lighting!"); } // ***** Button event handlers ***** // // Use button one to set the light mode for all rooms void handleButtonOne() { if (!still_bouncing()) { lcd.clear(); rooms.trigger(RESET_ROOMS); modes.trigger(CHANGE_LIGHT_MODE); } } // Use button two to increase brightness for the current room void handleButtonTwo() { if (!still_bouncing()) { setRoomBrightness(currentRoom, min(roomBrightness[currentRoom] + deltaLevel, maxLevel)); printCurrentRoom(); } } // Use button three to select the previous room void handleButtonThree() { if (!still_bouncing()) { lcd.clear(); rooms.trigger(PREVIOUS_ROOM); } } // Use button four to decrease brightness for the current room void handleButtonFour() { if (!still_bouncing()) { setRoomBrightness(currentRoom, max(roomBrightness[currentRoom] - deltaLevel, minLevel)); printCurrentRoom(); } } // Use button five to select the next room void handleButtonFive() { if (!still_bouncing()) { lcd.clear(); rooms.trigger(NEXT_ROOM); } } // ***** helpers ***** // void setRGBColor(int red, int green, int blue) { int myRed = constrain(red, 0, 255); int myGreen = constrain(green, 0, 255); int myBlue = constrain(blue, 0, 255); analogWrite(RED_PIN, myRed); analogWrite(GREEN_PIN, myGreen); analogWrite(BLUE_PIN, myBlue); } void setRoomBrightness(int room, int level) { setRGBColor(0,0,level); roomBrightness[room] = level; tlc.setPWM(room * 3, roomBrightness[room] * maxLevel); tlc.write(); } void setDefaultLightLevel() { setRGBColor(0,0,brightness); for (int i = 0; i != LastROOM; i++) { roomBrightness[i] = brightness; } } void setCurrentMode(int mode) { currentMode = mode; printCurrentMode(); } void printCurrentMode() { lcd.clear(); lcd.print("Mode: "); lcd.print(modeNames[currentMode]); } void setCurrentRoom(int room) { currentRoom = room; setRGBColor(0,0,roomBrightness[room]); printCurrentRoom(); } void printCurrentRoom() { lcd.clear(); lcd.print("room: "); lcd.print(roomNames[currentRoom]); lcd.setCursor(0,1); lcd.print("brightness: "); lcd.print(roomBrightness[currentRoom]); } // ***** FSM event handlers ***** // // ---- lighting mode states ---- // void on_lighting_mode_enter(){ setCurrentMode(LIGHTING_MODE); } void on_lighting_mode_exit(){ } void on_party_mode_enter(){ setCurrentMode(PARTY_MODE); } void on_party_mode_exit(){ } void on_nitelite_mode_enter(){ setCurrentMode(NITELITE_MODE); } void on_nitelite_mode_exit(){ } void on_off_mode_enter(){ setCurrentMode(OFF_MODE); } void on_off_mode_exit(){ } // ---- room selection states ---- // void on_all_enter() { setCurrentRoom(ALL_ROOMS); } void on_all_exit() { } void on_hall_enter() { setCurrentRoom(HALL); } void on_hall_exit() { } void on_living_room_enter() { setCurrentRoom(LIVING_ROOM); } void on_living_room_exit() { } void on_kitchen_enter() { setCurrentRoom(KITCHEN); } void on_kitchen_exit() { } void on_bathroom_enter() { setCurrentRoom(BATHROOM); } void on_bathroom_exit() { } void on_bedroom_enter() { setCurrentRoom(BEDROOM); } void on_bedroom_exit() { } void on_attic_enter() { setCurrentRoom(ATTIC); } void on_attic_exit() { } // Debonce timer boolean still_bouncing() { // If the debounce timer is not running, then we can assume the buttons // aren't bouncing because nothing has been pressed recently if (timerDebounce == 0) { startTimer(timerDebounce); return false; } if (isTimerExpired(timerDebounce, debounceDelay)) { clearTimer(timerDebounce); startTimer(timerDebounce); return false; } return true; } void loop() { // do nothing; everything is handled via FSM events. // We also don't need to call the ".run_machine" methods of // the FSMs as there are no "on_state" handlers or timed transitions } <|endoftext|>
<commit_before>/* The MIT License (MIT) Copyright (c) 2013-2014 Anatoli Steinmark 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 <cassert> #include <cstring> #include "ImageImpl.hpp" #include "octreequant.hpp" namespace azura { //-------------------------------------------------------------- ImageImpl::ImageImpl(int width, int height, PixelFormat::Enum pf) : _width(width) , _height(height) , _pixelFormat(pf) , _pixels(0) , _palette(0) { assert(width > 0); assert(height > 0); assert(pf >= 0 && pf < PixelFormat::Count); PixelFormatDescriptor pfd = GetPixelFormatDescriptor(pf); _pixels = new u8[width * height * pfd.bytesPerPixel]; if (!pfd.isDirectColor) { _palette = new RGB[256]; } } //-------------------------------------------------------------- ImageImpl::~ImageImpl() { delete[] _pixels; if (_palette) { delete[] _palette; } } //-------------------------------------------------------------- int ImageImpl::getWidth() const { return _width; } //-------------------------------------------------------------- int ImageImpl::getHeight() const { return _height; } //-------------------------------------------------------------- PixelFormat::Enum ImageImpl::getPixelFormat() const { return _pixelFormat; } //-------------------------------------------------------------- const u8* ImageImpl::getPixels() const { return _pixels; } //-------------------------------------------------------------- u8* ImageImpl::getPixels() { return _pixels; } //-------------------------------------------------------------- void ImageImpl::setPixels(const u8* pixels) { assert(pixels); if (pixels) { PixelFormatDescriptor pfd = GetPixelFormatDescriptor(_pixelFormat); std::memcpy(_pixels, pixels, _width * _height * pfd.bytesPerPixel); } } //-------------------------------------------------------------- const RGB* ImageImpl::getPalette() const { return _palette; } //-------------------------------------------------------------- RGB* ImageImpl::getPalette() { return _palette; } //-------------------------------------------------------------- void ImageImpl::setPalette(const RGB palette[256]) { assert(_palette); assert(palette); if (_palette && palette) { std::memcpy(_palette, palette, 256 * sizeof(RGB)); } } //-------------------------------------------------------------- Image::Ptr ImageImpl::convert(PixelFormat::Enum pf) { if (pf < 0 || pf >= PixelFormat::Count) { // invalid pixel format requested return 0; } if (_pixelFormat == pf) { // already in requested pixel format return this; } PixelFormatDescriptor spfd = GetPixelFormatDescriptor(_pixelFormat); PixelFormatDescriptor dpfd = GetPixelFormatDescriptor(pf); if (spfd.isDirectColor && dpfd.isDirectColor) { RefPtr<ImageImpl> result = new ImageImpl(_width, _height, pf); u8* sptr = _pixels; u8* dptr = result->_pixels; for (int i = _width * _height; i > 0; i--) { dptr[dpfd.redMask] = sptr[spfd.redMask]; dptr[dpfd.greenMask] = sptr[spfd.greenMask]; dptr[dpfd.blueMask] = sptr[spfd.blueMask]; if (dpfd.hasAlpha) { if (spfd.hasAlpha) { dptr[dpfd.alphaMask] = sptr[spfd.alphaMask]; } else { dptr[dpfd.alphaMask] = 255; } } sptr += spfd.bytesPerPixel; dptr += dpfd.bytesPerPixel; } return result; } else if (!spfd.isDirectColor && dpfd.isDirectColor) { RefPtr<ImageImpl> result = new ImageImpl(_width, _height, pf); u8* sptr = _pixels; RGB* splt = _palette; u8* dptr = result->_pixels; for (int i = _width * _height; i > 0; i--) { RGB col = splt[*sptr]; dptr[dpfd.redMask] = col.red; dptr[dpfd.greenMask] = col.green; dptr[dpfd.blueMask] = col.blue; if (dpfd.hasAlpha) { dptr[dpfd.alphaMask] = 255; } sptr += spfd.bytesPerPixel; dptr += dpfd.bytesPerPixel; } return result; } else if (spfd.isDirectColor && !dpfd.isDirectColor) { // color quantization requires source pixels in RGB format Image::Ptr rgb_image = convert(PixelFormat::RGB); Image::Ptr plt_image = new ImageImpl(_width, _height, pf); OctreeQuant((RGB*)rgb_image->getPixels(), _width * _height, plt_image->getPixels(), plt_image->getPalette()); return plt_image; } // no suitable conversion available return 0; } } <commit_msg>Zero-initialize image buffers.<commit_after>/* The MIT License (MIT) Copyright (c) 2013-2014 Anatoli Steinmark 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 <cassert> #include <cstring> #include "ImageImpl.hpp" #include "octreequant.hpp" namespace azura { //-------------------------------------------------------------- ImageImpl::ImageImpl(int width, int height, PixelFormat::Enum pf) : _width(width) , _height(height) , _pixelFormat(pf) , _pixels(0) , _palette(0) { assert(width > 0); assert(height > 0); assert(pf >= 0 && pf < PixelFormat::Count); PixelFormatDescriptor pfd = GetPixelFormatDescriptor(pf); _pixels = new u8[width * height * pfd.bytesPerPixel]; std::memset(_pixels, 0x00, width * height * pfd.bytesPerPixel); if (!pfd.isDirectColor) { _palette = new RGB[256]; std::memset(_palette, 0x00, 256 * sizeof(RGB)); } } //-------------------------------------------------------------- ImageImpl::~ImageImpl() { delete[] _pixels; if (_palette) { delete[] _palette; } } //-------------------------------------------------------------- int ImageImpl::getWidth() const { return _width; } //-------------------------------------------------------------- int ImageImpl::getHeight() const { return _height; } //-------------------------------------------------------------- PixelFormat::Enum ImageImpl::getPixelFormat() const { return _pixelFormat; } //-------------------------------------------------------------- const u8* ImageImpl::getPixels() const { return _pixels; } //-------------------------------------------------------------- u8* ImageImpl::getPixels() { return _pixels; } //-------------------------------------------------------------- void ImageImpl::setPixels(const u8* pixels) { assert(pixels); if (pixels) { PixelFormatDescriptor pfd = GetPixelFormatDescriptor(_pixelFormat); std::memcpy(_pixels, pixels, _width * _height * pfd.bytesPerPixel); } } //-------------------------------------------------------------- const RGB* ImageImpl::getPalette() const { return _palette; } //-------------------------------------------------------------- RGB* ImageImpl::getPalette() { return _palette; } //-------------------------------------------------------------- void ImageImpl::setPalette(const RGB palette[256]) { assert(_palette); assert(palette); if (_palette && palette) { std::memcpy(_palette, palette, 256 * sizeof(RGB)); } } //-------------------------------------------------------------- Image::Ptr ImageImpl::convert(PixelFormat::Enum pf) { if (pf < 0 || pf >= PixelFormat::Count) { // invalid pixel format requested return 0; } if (_pixelFormat == pf) { // already in requested pixel format return this; } PixelFormatDescriptor spfd = GetPixelFormatDescriptor(_pixelFormat); PixelFormatDescriptor dpfd = GetPixelFormatDescriptor(pf); if (spfd.isDirectColor && dpfd.isDirectColor) { RefPtr<ImageImpl> result = new ImageImpl(_width, _height, pf); u8* sptr = _pixels; u8* dptr = result->_pixels; for (int i = _width * _height; i > 0; i--) { dptr[dpfd.redMask] = sptr[spfd.redMask]; dptr[dpfd.greenMask] = sptr[spfd.greenMask]; dptr[dpfd.blueMask] = sptr[spfd.blueMask]; if (dpfd.hasAlpha) { if (spfd.hasAlpha) { dptr[dpfd.alphaMask] = sptr[spfd.alphaMask]; } else { dptr[dpfd.alphaMask] = 255; } } sptr += spfd.bytesPerPixel; dptr += dpfd.bytesPerPixel; } return result; } else if (!spfd.isDirectColor && dpfd.isDirectColor) { RefPtr<ImageImpl> result = new ImageImpl(_width, _height, pf); u8* sptr = _pixels; RGB* splt = _palette; u8* dptr = result->_pixels; for (int i = _width * _height; i > 0; i--) { RGB col = splt[*sptr]; dptr[dpfd.redMask] = col.red; dptr[dpfd.greenMask] = col.green; dptr[dpfd.blueMask] = col.blue; if (dpfd.hasAlpha) { dptr[dpfd.alphaMask] = 255; } sptr += spfd.bytesPerPixel; dptr += dpfd.bytesPerPixel; } return result; } else if (spfd.isDirectColor && !dpfd.isDirectColor) { // color quantization requires source pixels in RGB format Image::Ptr rgb_image = convert(PixelFormat::RGB); Image::Ptr plt_image = new ImageImpl(_width, _height, pf); OctreeQuant((RGB*)rgb_image->getPixels(), _width * _height, plt_image->getPixels(), plt_image->getPalette()); return plt_image; } // no suitable conversion available return 0; } } <|endoftext|>
<commit_before>#ifndef TESTERDRIVER_H #define TESTERDRIVER_H #include <iostream> #include <string.h> using namespace std; #include "wrapperregdriver.h" #include "TesterWrapper.h" // uncomment the second line here to enable verbose reg read/writes //#define __TESTERDRIVER_DEBUG(x) (cout << x << endl) #define __TESTERDRIVER_DEBUG(x) (0) // register driver for the Tester platform, using the Chisel-generated C++ model to // interface with the accelerator model // note that TesterWrapper.h must be generated for each new accelerator, it is the // model header not just for the wrapper, but the entire system (wrapper+accel) class TesterRegDriver : public WrapperRegDriver { public: TesterRegDriver() {m_freePtr = 0;} virtual void attach(const char * name) { m_inst = new TesterWrapper_t(); // get # words in the memory m_memWords = m_inst->TesterWrapper__mem.length(); // initialize and reset the model m_inst->init(); reset(); m_regCount = m_inst->TesterWrapper__io_regFileIF_regCount.to_ulong(); } virtual void detach() { delete m_inst; } virtual void copyBufferHostToAccel(void * hostBuffer, void * accelBuffer, unsigned int numBytes) { uint64_t accelBufBase = (uint64_t) accelBuffer; __TESTERDRIVER_DEBUG("host2accel(" << (uint64_t) hostBuffer << " -> " << accelBufBase << " : " << numBytes << " bytes)"); if((numBytes % 8 == 0) && (accelBufBase % 8 == 0)) alignedCopyBufferHostToAccel(hostBuffer, accelBuffer, numBytes); else { // align base and size uint64_t alignedBase = accelBufBase - (accelBufBase % 8); uint64_t startDiff = accelBufBase - alignedBase; unsigned int alignedSize = (startDiff + numBytes + 7) / 8 * 8; // copy containing block into host memory char * tmp = new char[alignedSize]; alignedCopyBufferAccelToHost((void *)alignedBase, (void *) tmp, alignedSize); // do host-to-host unaligned copy memcpy((void *)&tmp[startDiff], hostBuffer, numBytes); // write containing block back to accel memory alignedCopyBufferHostToAccel((void *)tmp, (void *)alignedBase, alignedSize); delete [] tmp; } } virtual void copyBufferAccelToHost(void * accelBuffer, void * hostBuffer, unsigned int numBytes) { uint64_t accelBufBase = (uint64_t) accelBuffer; __TESTERDRIVER_DEBUG("accel2host(" << accelBufBase << " -> " << (uint64_t) hostBuffer << " : " << numBytes << " bytes)"); if((numBytes % 8 == 0) && (accelBufBase % 8 == 0)) alignedCopyBufferAccelToHost(hostBuffer, accelBuffer, numBytes); else { // implement unaligned accel-to-host // align base and size uint64_t alignedBase = accelBufBase - (accelBufBase % 8); uint64_t startDiff = accelBufBase - alignedBase; unsigned int alignedSize = (startDiff + numBytes + 7) / 8 * 8; // copy containing block into host memory char * tmp = new char[alignedSize]; alignedCopyBufferAccelToHost((void *)alignedBase, (void *) tmp, alignedSize); // do host-to-host unaligned copy memcpy(hostBuffer, (void *)&tmp[startDiff],numBytes); delete [] tmp; } } virtual void * allocAccelBuffer(unsigned int numBytes) { // all this assumes allocation and mem word size of 8 bytes // round requested size to nearest multiple of 8 unsigned int actualAllocSize = (numBytes + 7) / 8 * 8; void * accelBuf = (void *) m_freePtr; // update free pointer and sanity check m_freePtr += actualAllocSize; if(m_freePtr > m_memWords * 8) throw "Not enough memory in allocAccelBuffer"; __TESTERDRIVER_DEBUG("allocAccelBuffer(" << numBytes << ", alloc " << actualAllocSize <<") = " << (uint64_t) accelBuf); return accelBuf; } // register access methods for the platform wrapper virtual void writeReg(unsigned int regInd, AccelReg regValue) { __TESTERDRIVER_DEBUG("writeReg(" << regInd << ", " << regValue << ") "); m_inst->TesterWrapper__io_regFileIF_cmd_bits_writeData = regValue; m_inst->TesterWrapper__io_regFileIF_cmd_bits_write = 1; m_inst->TesterWrapper__io_regFileIF_cmd_bits_regID = regInd; m_inst->TesterWrapper__io_regFileIF_cmd_valid = 1; step(); m_inst->TesterWrapper__io_regFileIF_cmd_valid = 0; m_inst->TesterWrapper__io_regFileIF_cmd_bits_write = 0; step(5); // extra delay on write completion to be realistic } virtual AccelReg readReg(unsigned int regInd) { AccelReg ret; m_inst->TesterWrapper__io_regFileIF_cmd_bits_regID = regInd; m_inst->TesterWrapper__io_regFileIF_cmd_valid = 1; m_inst->TesterWrapper__io_regFileIF_cmd_bits_read = 1; step(); // don't actually need 1 cycle, regfile reads are combinational if(!m_inst->TesterWrapper__io_regFileIF_readData_valid.to_bool()) throw "Could not read register"; m_inst->TesterWrapper__io_regFileIF_cmd_valid = 0; m_inst->TesterWrapper__io_regFileIF_cmd_bits_read = 0; ret = m_inst->TesterWrapper__io_regFileIF_readData_bits.to_ulong(); __TESTERDRIVER_DEBUG("readReg(" << regInd << ") = " << ret); step(5); // extra delay on read completion to be realistic return ret; } void printAllRegs() { for(unsigned int i = 0; i < m_regCount; i++) { AccelReg val = readReg(i); cout << "Reg " << i << " = " << val << " (0x" << hex << val << dec << ")" << endl; } } protected: TesterWrapper_t * m_inst; unsigned int m_memWords; unsigned int m_regCount; uint64_t m_freePtr; void reset() { m_inst->clock(1); m_inst->clock(0); // Chisel c++ backend requires this workaround to get out the correct values m_inst->clock_lo(0); } void step(int n = 1) { for(int i = 0; i < n; i++) { m_inst->clock(0); // Chisel c++ backend requires this workaround to get out the correct values m_inst->clock_lo(0); } } void memWrite(uint64_t addr, uint64_t value) { m_inst->TesterWrapper__io_memAddr = addr; m_inst->TesterWrapper__io_memWriteData = value; m_inst->TesterWrapper__io_memWriteEn = 1; step(); m_inst->TesterWrapper__io_memWriteEn = 0; } uint64_t memRead(uint64_t addr) { m_inst->TesterWrapper__io_memAddr = addr; step(); uint64_t ret = m_inst->TesterWrapper__io_memReadData[0]; return ret; } // "aligned" copy functions, where accel ptr start and size are guaranteed to be 8-aligned void alignedCopyBufferHostToAccel(void * hostBuffer, void * accelBuffer, unsigned int numBytes) { uint64_t * host_buf = (uint64_t *) hostBuffer; uint64_t accelBufBase = (uint64_t) accelBuffer; for(unsigned int i = 0; i < numBytes/8; i++) memWrite(accelBufBase + i*8, host_buf[i]); } void alignedCopyBufferAccelToHost(void * accelBuffer, void * hostBuffer, unsigned int numBytes) { uint64_t accelBufBase = (uint64_t) accelBuffer; uint64_t * readBuf = (uint64_t *) hostBuffer; for(unsigned int i = 0; i < numBytes/8; i++) readBuf[i] = memRead(accelBufBase + i*8); } }; #endif <commit_msg>TesterDriver bugfix: src-dest in copy switched places<commit_after>#ifndef TESTERDRIVER_H #define TESTERDRIVER_H #include <iostream> #include <string.h> using namespace std; #include "wrapperregdriver.h" #include "TesterWrapper.h" // uncomment the second line here to enable verbose reg read/writes //#define __TESTERDRIVER_DEBUG(x) (cout << x << endl) #define __TESTERDRIVER_DEBUG(x) (0) // register driver for the Tester platform, using the Chisel-generated C++ model to // interface with the accelerator model // note that TesterWrapper.h must be generated for each new accelerator, it is the // model header not just for the wrapper, but the entire system (wrapper+accel) class TesterRegDriver : public WrapperRegDriver { public: TesterRegDriver() {m_freePtr = 0;} virtual void attach(const char * name) { m_inst = new TesterWrapper_t(); // get # words in the memory m_memWords = m_inst->TesterWrapper__mem.length(); // initialize and reset the model m_inst->init(); reset(); m_regCount = m_inst->TesterWrapper__io_regFileIF_regCount.to_ulong(); } virtual void detach() { delete m_inst; } virtual void copyBufferHostToAccel(void * hostBuffer, void * accelBuffer, unsigned int numBytes) { uint64_t accelBufBase = (uint64_t) accelBuffer; __TESTERDRIVER_DEBUG("host2accel(" << (uint64_t) hostBuffer << " -> " << accelBufBase << " : " << numBytes << " bytes)"); if((numBytes % 8 == 0) && (accelBufBase % 8 == 0)) alignedCopyBufferHostToAccel(hostBuffer, accelBuffer, numBytes); else { // align base and size uint64_t alignedBase = accelBufBase - (accelBufBase % 8); uint64_t startDiff = accelBufBase - alignedBase; unsigned int alignedSize = (startDiff + numBytes + 7) / 8 * 8; // copy containing block into host memory char * tmp = new char[alignedSize]; alignedCopyBufferAccelToHost((void *)alignedBase, (void *) tmp, alignedSize); // do host-to-host unaligned copy memcpy((void *)&tmp[startDiff], hostBuffer, numBytes); // write containing block back to accel memory alignedCopyBufferHostToAccel((void *)tmp, (void *)alignedBase, alignedSize); delete [] tmp; } } virtual void copyBufferAccelToHost(void * accelBuffer, void * hostBuffer, unsigned int numBytes) { uint64_t accelBufBase = (uint64_t) accelBuffer; __TESTERDRIVER_DEBUG("accel2host(" << accelBufBase << " -> " << (uint64_t) hostBuffer << " : " << numBytes << " bytes)"); if((numBytes % 8 == 0) && (accelBufBase % 8 == 0)) alignedCopyBufferAccelToHost(accelBuffer, hostBuffer, numBytes); else { // implement unaligned accel-to-host // align base and size uint64_t alignedBase = accelBufBase - (accelBufBase % 8); uint64_t startDiff = accelBufBase - alignedBase; unsigned int alignedSize = (startDiff + numBytes + 7) / 8 * 8; // copy containing block into host memory char * tmp = new char[alignedSize]; alignedCopyBufferAccelToHost((void *)alignedBase, (void *) tmp, alignedSize); // do host-to-host unaligned copy memcpy(hostBuffer, (void *)&tmp[startDiff],numBytes); delete [] tmp; } } virtual void * allocAccelBuffer(unsigned int numBytes) { // all this assumes allocation and mem word size of 8 bytes // round requested size to nearest multiple of 8 unsigned int actualAllocSize = (numBytes + 7) / 8 * 8; void * accelBuf = (void *) m_freePtr; // update free pointer and sanity check m_freePtr += actualAllocSize; if(m_freePtr > m_memWords * 8) throw "Not enough memory in allocAccelBuffer"; __TESTERDRIVER_DEBUG("allocAccelBuffer(" << numBytes << ", alloc " << actualAllocSize <<") = " << (uint64_t) accelBuf); return accelBuf; } // register access methods for the platform wrapper virtual void writeReg(unsigned int regInd, AccelReg regValue) { __TESTERDRIVER_DEBUG("writeReg(" << regInd << ", " << regValue << ") "); m_inst->TesterWrapper__io_regFileIF_cmd_bits_writeData = regValue; m_inst->TesterWrapper__io_regFileIF_cmd_bits_write = 1; m_inst->TesterWrapper__io_regFileIF_cmd_bits_regID = regInd; m_inst->TesterWrapper__io_regFileIF_cmd_valid = 1; step(); m_inst->TesterWrapper__io_regFileIF_cmd_valid = 0; m_inst->TesterWrapper__io_regFileIF_cmd_bits_write = 0; step(5); // extra delay on write completion to be realistic } virtual AccelReg readReg(unsigned int regInd) { AccelReg ret; m_inst->TesterWrapper__io_regFileIF_cmd_bits_regID = regInd; m_inst->TesterWrapper__io_regFileIF_cmd_valid = 1; m_inst->TesterWrapper__io_regFileIF_cmd_bits_read = 1; step(); // don't actually need 1 cycle, regfile reads are combinational if(!m_inst->TesterWrapper__io_regFileIF_readData_valid.to_bool()) throw "Could not read register"; m_inst->TesterWrapper__io_regFileIF_cmd_valid = 0; m_inst->TesterWrapper__io_regFileIF_cmd_bits_read = 0; ret = m_inst->TesterWrapper__io_regFileIF_readData_bits.to_ulong(); __TESTERDRIVER_DEBUG("readReg(" << regInd << ") = " << ret); step(5); // extra delay on read completion to be realistic return ret; } void printAllRegs() { for(unsigned int i = 0; i < m_regCount; i++) { AccelReg val = readReg(i); cout << "Reg " << i << " = " << val << " (0x" << hex << val << dec << ")" << endl; } } protected: TesterWrapper_t * m_inst; unsigned int m_memWords; unsigned int m_regCount; uint64_t m_freePtr; void reset() { m_inst->clock(1); m_inst->clock(0); // Chisel c++ backend requires this workaround to get out the correct values m_inst->clock_lo(0); } void step(int n = 1) { for(int i = 0; i < n; i++) { m_inst->clock(0); // Chisel c++ backend requires this workaround to get out the correct values m_inst->clock_lo(0); } } void memWrite(uint64_t addr, uint64_t value) { m_inst->TesterWrapper__io_memAddr = addr; m_inst->TesterWrapper__io_memWriteData = value; m_inst->TesterWrapper__io_memWriteEn = 1; step(); m_inst->TesterWrapper__io_memWriteEn = 0; } uint64_t memRead(uint64_t addr) { m_inst->TesterWrapper__io_memAddr = addr; step(); uint64_t ret = m_inst->TesterWrapper__io_memReadData[0]; return ret; } // "aligned" copy functions, where accel ptr start and size are guaranteed to be 8-aligned void alignedCopyBufferHostToAccel(void * hostBuffer, void * accelBuffer, unsigned int numBytes) { uint64_t * host_buf = (uint64_t *) hostBuffer; uint64_t accelBufBase = (uint64_t) accelBuffer; for(unsigned int i = 0; i < numBytes/8; i++) memWrite(accelBufBase + i*8, host_buf[i]); } void alignedCopyBufferAccelToHost(void * accelBuffer, void * hostBuffer, unsigned int numBytes) { uint64_t accelBufBase = (uint64_t) accelBuffer; uint64_t * readBuf = (uint64_t *) hostBuffer; for(unsigned int i = 0; i < numBytes/8; i++) readBuf[i] = memRead(accelBufBase + i*8); } }; #endif <|endoftext|>
<commit_before>#ifdef HAVE_CONFIG_H #include <config.h> #endif #include <asio.hpp> #include <cstring> #include <cstdlib> #include <iostream> #include <vector> #include "antenna.hxx" #include "tuner.hxx" #include "io.hxx" #include "packet_processor.hxx" #include "abuhops.hxx" using namespace std; namespace abuhops { #define MIN_TIME_BETWEEN_WHOAMI 1024 #define MAX_TIME_BETWEEN_WHOAMI 4096 #define MIN_TIME_BETWEEN_PING 16384 #define MAX_TIME_BETWEEN_PING 32768 #define TIME_BETWEEN_CONNECT 1024 #define MAX_CONNECT_ATTEMPTS 16 #define CONNECT 0 #define PING 1 #define PROXY 2 #define POST 3 #define LIST 4 #define SIGN 5 #define BYE 6 #define YOUARE 0 #define PONG 1 #define FROMOTHER 2 #define ADVERT 3 #define SIGNATURE 5 #define IPV4PORT 12545 #define IPV6PORT 12546 #define SERVER "ABENDSTERN.SERVEGAME.COM." #define HMAC_SIZE 32 #define MAX_NAME_LENGTH 128 #ifdef DEBUG #define debug(x) cout << "abuhops: " << x << endl; #else #define debug(x) #endif static unsigned timeUntilPing = 0; static bool isConnected4 = false, isConnected6 = false, isConnecting = true; static unsigned timeUntilConnectXmit = 0; static byte connectPacket[1+4+4+HMAC_SIZE+MAX_NAME_LENGTH+1]; static unsigned connectPacketSize; static unsigned connectionAttempts = 0; static bool knowIpv4Address = false, knowIpv6Address = false; static Antenna::endpoint server4, server6; static bool hasv4 = false, hasv6 = false; static bool hasInit = false; static void sendConnectPacket(); static void processPacket(bool v6, const byte* data, unsigned len); void connect(unsigned id, const char* name, unsigned timestamp, const char* hmac) { debug(">> CONNECT"); if (!hasInit) { hasInit = true; try { //Look server IP address up asio::io_service svc; asio::ip::udp::resolver resolver(svc); asio::ip::udp::resolver::query query(SERVER, "0"); asio::ip::udp::resolver::iterator it(resolver.resolve(query)), end; while (it != end && (!hasv4 || !hasv6)) { asio::ip::address addr(it++->endpoint().address()); if (addr.is_v4() && !hasv4) { hasv4 = true; server4 = Antenna::endpoint(addr, IPV4PORT); cout << "Resolved " << SERVER << " ipv4 to " << addr.to_string() << endl; } else if (addr.is_v6() && !hasv6) { hasv6 = true; server6 = Antenna::endpoint(addr, IPV6PORT); cout << "Resolved " << SERVER << " ipv6 to " << addr.to_string() << endl; } } } catch (const asio::system_error& err) { cerr << "Error resolving " << SERVER << ": " << err.what() << endl; } //Even if we did get a result for a certain protocol, we can't use it //if it is not available hasv4 &= antenna.hasV4(); hasv6 &= antenna.hasV6(); ensureRegistered(); } //Set initial conditions isConnected4 = isConnected6 = false; isConnecting = true; timeUntilConnectXmit = 0; connectionAttempts = 0; //Write the connection packet byte* pack = connectPacket; *pack++ = CONNECT; io::write(pack, id); io::write(pack, timestamp); //Convert HMAC from hex for (unsigned i = 0; i < HMAC_SIZE; ++i) { #define HEXIT(x) (x >= '0' && x <= '9'? x-'0' : \ x >= 'a' && x <= 'f'? x-'a'+0xa : x-'A'+0xA) *pack++ = (HEXIT(hmac[2*i])<<4) | HEXIT(hmac[2*i+1]); #undef HEXIT } //Copy name into packet. strncpy((char*)pack, name, MAX_NAME_LENGTH); pack[MAX_NAME_LENGTH] = 0; //Set packet size connectPacketSize = (pack - connectPacket) + strlen(name)+1; //Done, send the first packet immediately sendConnectPacket(); } static void sendConnectPacket() { debug(">> CONNECT (send)"); if (hasv4 && !isConnected4) antenna.send(server4, connectPacket, connectPacketSize); if (hasv6 && !isConnected6) antenna.send(server6, connectPacket, connectPacketSize); ++connectionAttempts; if (connectionAttempts > MAX_CONNECT_ATTEMPTS) { //Give up, the server probably is not reachable on one or both protocols hasv4 &= isConnected4; hasv6 &= isConnected6; isConnecting = false; } //If we have not given up or connected yet, try again in a little bit timeUntilConnectXmit = TIME_BETWEEN_CONNECT; } void ensureRegistered() { class PP: public PacketProcessor { public: bool v6; PP(bool v) : v6(v) {} virtual void process(const Antenna::endpoint&, Antenna*, Tuner*, const byte* data, unsigned len) noth { processPacket(v6, data, len); } } static ppv4(false), ppv6(true); if (antenna.tuner) { if (hasv4) antenna.tuner->connect(server4, &ppv4); if (hasv6) antenna.tuner->connect(server6, &ppv6); } } void bye() { debug(">> BYE"); byte pack = BYE; if (hasv4) antenna.send(server4, &pack, 1); if (hasv6) antenna.send(server6, &pack, 1); isConnecting = isConnected4 = isConnected6 = false; } void post(bool v6, const byte* dat, unsigned len) { debug(">> POST"); vector<byte> pack(1 + len); pack[0] = POST; memcpy(&pack[1], dat, len); if (isConnected4 && !v6) antenna.send(server4, &pack[0], pack.size()); if (isConnected6 && v6) antenna.send(server6, &pack[0], pack.size()); } void list() { debug(">> LIST"); byte pack = LIST; if (isConnected4) antenna.send(server4, &pack, 1); if (isConnected6) antenna.send(server6, &pack, 1); } void stopList() { } void proxy(const Antenna::endpoint& dst, const byte* payload, unsigned len) { debug(">> PROXY"); vector<byte> pack(1 + (dst.address().is_v4()? 4 : 2*8) + 2 + len); pack[0] = PROXY; byte* dat = &pack[1]; if (dst.address().is_v4()) { asio::ip::address_v4::bytes_type b(dst.address().to_v4().to_bytes()); memcpy(dat, &b[0], 4); dat += 4; } else { asio::ip::address_v6::bytes_type b(dst.address().to_v6().to_bytes()); io::a6fromlbo(dat, &b[0]); dat += 16; } io::write(dat, dst.port()); memcpy(dat, payload, len); if (dst.address().is_v4() && isConnected4) antenna.send(server4, &pack[0], pack.size()); else if (dst.address().is_v6() && isConnected6) antenna.send(server6, &pack[0], pack.size()); else cerr << "warn: Attempt to proxy via unavailable IP version." << endl; } bool ready() { return hasInit && (!hasv4 || (knowIpv4Address && isConnected4)) && (!hasv6 || (knowIpv6Address && isConnected6)); } void update(unsigned et) { if (isConnecting) { //Move to non-connecting state if both IP versions we support are //connected if ((!hasv4 || isConnected4) && (!hasv6 || isConnected6)) isConnecting = true; //Otherwise, retransmit connect packet if necessary else if (timeUntilConnectXmit <= et) sendConnectPacket(); else timeUntilConnectXmit -= et; } else if (isConnected4 || isConnected6) { //Send PING if needed if (timeUntilPing < et) { bool whoAmI = (hasv4 && !knowIpv4Address) || (hasv6 && !knowIpv6Address); byte pack[2] = { PING, (byte)whoAmI }; if (hasv4) antenna.send(server4, pack, 2); if (hasv6) antenna.send(server6, pack, 2); unsigned lower = whoAmI? MIN_TIME_BETWEEN_WHOAMI:MIN_TIME_BETWEEN_PING; unsigned upper = whoAmI? MAX_TIME_BETWEEN_WHOAMI:MAX_TIME_BETWEEN_PING; timeUntilPing = lower + rand()%(upper-lower); } else { timeUntilPing -= et; } } } static void processYouAre(bool, const byte*, unsigned); static void processPong(bool, const byte*, unsigned); static void processFromOther(bool, const byte*, unsigned); static void processAdvert(bool, const byte*, unsigned); static void (*const packetTypes[256])(bool, const byte*, unsigned) = { processYouAre, processPong, processFromOther, processAdvert, NULL, /* processSignature, */ /* rest of array is NULL implicitly */ }; static void processPacket(bool v6, const byte* dat, unsigned len) { if (packetTypes[dat[0]]) packetTypes[dat[0]](v6, dat+1, len-1); else { #ifdef DEBUG cerr << "WARN: Dropping unknown abuhops packet type " << (unsigned)dat[0] << endl; #endif } } static void processYouAre(bool v6, const byte* dat, unsigned len) { debug("<< YOU-ARE"); if (v6) { GlobalID& gid(*antenna.getGlobalID6()); if (len != 8*2 + 2) { #ifdef DEBUG cerr << "WARN: Dropping IPv6 YOU-ARE packet of length " << len << endl; #endif } else { for (unsigned i = 0; i < 8; ++i) io::read(dat, gid.ia6[i]); io::read(dat, gid.iport); knowIpv6Address = true; isConnected6 = true; cout << "Our IPv6 GlobalID is " << gid.toString() << endl; } } else { GlobalID& gid(*antenna.getGlobalID4()); if (len != 4 + 2) { #ifdef DEBUG cerr << "WARN: Dropping IPv4 YOU-ARE packet of length " << len << endl; #endif } else { memcpy(gid.ia4, dat, 4); dat += 4; io::read(dat, gid.iport); knowIpv4Address = true; isConnected4 = true; cout << "Our IPv4 GlobalID is " << gid.toString() << endl; } } } static void processPong(bool v6, const byte* dat, unsigned len) { //Nothing to do debug("<< PONG"); } static void processFromOther(bool v6, const byte* dat, unsigned len) { debug("<< FROM-OTHER"); if (!len) { #ifdef DEBUG cerr << "WARN: Dropping FROM-OTHER with empty payload." << endl; #endif return; } //The default endpoint is used to tell the NetworkGame that it must get the //Internet IP address from the STX itself Antenna::endpoint defaultEndpoint; if (antenna.tuner) antenna.tuner->receivePacket(defaultEndpoint, &antenna, dat, len); } static const char requiredAdvertHeader[] = "Abendspiel"; #define ADVERT_IPV_OFF (sizeof(requiredAdvertHeader)-1 + 4 + 1) static void processAdvert(bool v6, const byte* dat, unsigned len) { debug("<< ADVERT"); Antenna::endpoint defaultEndpoint; if (len < ADVERT_IPV_OFF || memcmp(dat, requiredAdvertHeader, sizeof(requiredAdvertHeader)-1)) { #ifdef DEBUG cerr << "WARN: Dropping non-Abendspiel ADVERT" << endl; #endif return; } //Ensure that the reported IP version of the advert matches the Abuhops //realm it is comming from if ((unsigned)v6 != dat[ADVERT_IPV_OFF]) { /* * This warning is meaningless, since the Abendstern abuhops client * always posts to both realms. #ifdef DEBUG cerr << "WARN: Dropping ADVERT for wrong IP version" << endl; #endif */ return; } if (antenna.tuner) antenna.tuner->receivePacket(defaultEndpoint, &antenna, dat, len); } } <commit_msg>Fix Abuhops client not PINGing.<commit_after>#ifdef HAVE_CONFIG_H #include <config.h> #endif #include <asio.hpp> #include <cstring> #include <cstdlib> #include <iostream> #include <vector> #include "antenna.hxx" #include "tuner.hxx" #include "io.hxx" #include "packet_processor.hxx" #include "abuhops.hxx" using namespace std; namespace abuhops { #define MIN_TIME_BETWEEN_WHOAMI 1024 #define MAX_TIME_BETWEEN_WHOAMI 4096 #define MIN_TIME_BETWEEN_PING 16384 #define MAX_TIME_BETWEEN_PING 32768 #define TIME_BETWEEN_CONNECT 1024 #define MAX_CONNECT_ATTEMPTS 16 #define CONNECT 0 #define PING 1 #define PROXY 2 #define POST 3 #define LIST 4 #define SIGN 5 #define BYE 6 #define YOUARE 0 #define PONG 1 #define FROMOTHER 2 #define ADVERT 3 #define SIGNATURE 5 #define IPV4PORT 12545 #define IPV6PORT 12546 #define SERVER "ABENDSTERN.SERVEGAME.COM." #define HMAC_SIZE 32 #define MAX_NAME_LENGTH 128 #ifdef DEBUG #define debug(x) cout << "abuhops: " << x << endl; #else #define debug(x) #endif static unsigned timeUntilPing = 0; static bool isConnected4 = false, isConnected6 = false, isConnecting = true; static unsigned timeUntilConnectXmit = 0; static byte connectPacket[1+4+4+HMAC_SIZE+MAX_NAME_LENGTH+1]; static unsigned connectPacketSize; static unsigned connectionAttempts = 0; static bool knowIpv4Address = false, knowIpv6Address = false; static Antenna::endpoint server4, server6; static bool hasv4 = false, hasv6 = false; static bool hasInit = false; static void sendConnectPacket(); static void processPacket(bool v6, const byte* data, unsigned len); void connect(unsigned id, const char* name, unsigned timestamp, const char* hmac) { debug(">> CONNECT"); if (!hasInit) { hasInit = true; try { //Look server IP address up asio::io_service svc; asio::ip::udp::resolver resolver(svc); asio::ip::udp::resolver::query query(SERVER, "0"); asio::ip::udp::resolver::iterator it(resolver.resolve(query)), end; while (it != end && (!hasv4 || !hasv6)) { asio::ip::address addr(it++->endpoint().address()); if (addr.is_v4() && !hasv4) { hasv4 = true; server4 = Antenna::endpoint(addr, IPV4PORT); cout << "Resolved " << SERVER << " ipv4 to " << addr.to_string() << endl; } else if (addr.is_v6() && !hasv6) { hasv6 = true; server6 = Antenna::endpoint(addr, IPV6PORT); cout << "Resolved " << SERVER << " ipv6 to " << addr.to_string() << endl; } } } catch (const asio::system_error& err) { cerr << "Error resolving " << SERVER << ": " << err.what() << endl; } //Even if we did get a result for a certain protocol, we can't use it //if it is not available hasv4 &= antenna.hasV4(); hasv6 &= antenna.hasV6(); ensureRegistered(); } //Set initial conditions isConnected4 = isConnected6 = false; isConnecting = true; timeUntilConnectXmit = 0; connectionAttempts = 0; //Write the connection packet byte* pack = connectPacket; *pack++ = CONNECT; io::write(pack, id); io::write(pack, timestamp); //Convert HMAC from hex for (unsigned i = 0; i < HMAC_SIZE; ++i) { #define HEXIT(x) (x >= '0' && x <= '9'? x-'0' : \ x >= 'a' && x <= 'f'? x-'a'+0xa : x-'A'+0xA) *pack++ = (HEXIT(hmac[2*i])<<4) | HEXIT(hmac[2*i+1]); #undef HEXIT } //Copy name into packet. strncpy((char*)pack, name, MAX_NAME_LENGTH); pack[MAX_NAME_LENGTH] = 0; //Set packet size connectPacketSize = (pack - connectPacket) + strlen(name)+1; //Done, send the first packet immediately sendConnectPacket(); } static void sendConnectPacket() { debug(">> CONNECT (send)"); if (hasv4 && !isConnected4) antenna.send(server4, connectPacket, connectPacketSize); if (hasv6 && !isConnected6) antenna.send(server6, connectPacket, connectPacketSize); ++connectionAttempts; if (connectionAttempts > MAX_CONNECT_ATTEMPTS) { //Give up, the server probably is not reachable on one or both protocols hasv4 &= isConnected4; hasv6 &= isConnected6; isConnecting = false; } //If we have not given up or connected yet, try again in a little bit timeUntilConnectXmit = TIME_BETWEEN_CONNECT; } void ensureRegistered() { class PP: public PacketProcessor { public: bool v6; PP(bool v) : v6(v) {} virtual void process(const Antenna::endpoint&, Antenna*, Tuner*, const byte* data, unsigned len) noth { processPacket(v6, data, len); } } static ppv4(false), ppv6(true); if (antenna.tuner) { if (hasv4) antenna.tuner->connect(server4, &ppv4); if (hasv6) antenna.tuner->connect(server6, &ppv6); } } void bye() { debug(">> BYE"); byte pack = BYE; if (hasv4) antenna.send(server4, &pack, 1); if (hasv6) antenna.send(server6, &pack, 1); isConnecting = isConnected4 = isConnected6 = false; } void post(bool v6, const byte* dat, unsigned len) { debug(">> POST"); vector<byte> pack(1 + len); pack[0] = POST; memcpy(&pack[1], dat, len); if (isConnected4 && !v6) antenna.send(server4, &pack[0], pack.size()); if (isConnected6 && v6) antenna.send(server6, &pack[0], pack.size()); } void list() { debug(">> LIST"); byte pack = LIST; if (isConnected4) antenna.send(server4, &pack, 1); if (isConnected6) antenna.send(server6, &pack, 1); } void stopList() { } void proxy(const Antenna::endpoint& dst, const byte* payload, unsigned len) { debug(">> PROXY"); vector<byte> pack(1 + (dst.address().is_v4()? 4 : 2*8) + 2 + len); pack[0] = PROXY; byte* dat = &pack[1]; if (dst.address().is_v4()) { asio::ip::address_v4::bytes_type b(dst.address().to_v4().to_bytes()); memcpy(dat, &b[0], 4); dat += 4; } else { asio::ip::address_v6::bytes_type b(dst.address().to_v6().to_bytes()); io::a6fromlbo(dat, &b[0]); dat += 16; } io::write(dat, dst.port()); memcpy(dat, payload, len); if (dst.address().is_v4() && isConnected4) antenna.send(server4, &pack[0], pack.size()); else if (dst.address().is_v6() && isConnected6) antenna.send(server6, &pack[0], pack.size()); else cerr << "warn: Attempt to proxy via unavailable IP version." << endl; } bool ready() { return hasInit && (!hasv4 || (knowIpv4Address && isConnected4)) && (!hasv6 || (knowIpv6Address && isConnected6)); } void update(unsigned et) { if (isConnecting) { //Move to non-connecting state if both IP versions we support are //connected if ((!hasv4 || isConnected4) && (!hasv6 || isConnected6)) isConnecting = false; //Otherwise, retransmit connect packet if necessary else if (timeUntilConnectXmit <= et) sendConnectPacket(); else timeUntilConnectXmit -= et; } else if (isConnected4 || isConnected6) { //Send PING if needed if (timeUntilPing < et) { bool whoAmI = (hasv4 && !knowIpv4Address) || (hasv6 && !knowIpv6Address); debug(">> PING " << whoAmI); byte pack[2] = { PING, (byte)whoAmI }; if (hasv4) antenna.send(server4, pack, 2); if (hasv6) antenna.send(server6, pack, 2); unsigned lower = whoAmI? MIN_TIME_BETWEEN_WHOAMI:MIN_TIME_BETWEEN_PING; unsigned upper = whoAmI? MAX_TIME_BETWEEN_WHOAMI:MAX_TIME_BETWEEN_PING; timeUntilPing = lower + rand()%(upper-lower); } else { timeUntilPing -= et; } } } static void processYouAre(bool, const byte*, unsigned); static void processPong(bool, const byte*, unsigned); static void processFromOther(bool, const byte*, unsigned); static void processAdvert(bool, const byte*, unsigned); static void (*const packetTypes[256])(bool, const byte*, unsigned) = { processYouAre, processPong, processFromOther, processAdvert, NULL, /* processSignature, */ /* rest of array is NULL implicitly */ }; static void processPacket(bool v6, const byte* dat, unsigned len) { if (packetTypes[dat[0]]) packetTypes[dat[0]](v6, dat+1, len-1); else { #ifdef DEBUG cerr << "WARN: Dropping unknown abuhops packet type " << (unsigned)dat[0] << endl; #endif } } static void processYouAre(bool v6, const byte* dat, unsigned len) { debug("<< YOU-ARE"); if (v6) { GlobalID& gid(*antenna.getGlobalID6()); if (len != 8*2 + 2) { #ifdef DEBUG cerr << "WARN: Dropping IPv6 YOU-ARE packet of length " << len << endl; #endif } else { for (unsigned i = 0; i < 8; ++i) io::read(dat, gid.ia6[i]); io::read(dat, gid.iport); knowIpv6Address = true; isConnected6 = true; cout << "Our IPv6 GlobalID is " << gid.toString() << endl; } } else { GlobalID& gid(*antenna.getGlobalID4()); if (len != 4 + 2) { #ifdef DEBUG cerr << "WARN: Dropping IPv4 YOU-ARE packet of length " << len << endl; #endif } else { memcpy(gid.ia4, dat, 4); dat += 4; io::read(dat, gid.iport); knowIpv4Address = true; isConnected4 = true; cout << "Our IPv4 GlobalID is " << gid.toString() << endl; } } } static void processPong(bool v6, const byte* dat, unsigned len) { //Nothing to do debug("<< PONG"); } static void processFromOther(bool v6, const byte* dat, unsigned len) { debug("<< FROM-OTHER"); if (!len) { #ifdef DEBUG cerr << "WARN: Dropping FROM-OTHER with empty payload." << endl; #endif return; } //The default endpoint is used to tell the NetworkGame that it must get the //Internet IP address from the STX itself Antenna::endpoint defaultEndpoint; if (antenna.tuner) antenna.tuner->receivePacket(defaultEndpoint, &antenna, dat, len); } static const char requiredAdvertHeader[] = "Abendspiel"; #define ADVERT_IPV_OFF (sizeof(requiredAdvertHeader)-1 + 4 + 1) static void processAdvert(bool v6, const byte* dat, unsigned len) { debug("<< ADVERT"); Antenna::endpoint defaultEndpoint; if (len < ADVERT_IPV_OFF || memcmp(dat, requiredAdvertHeader, sizeof(requiredAdvertHeader)-1)) { #ifdef DEBUG cerr << "WARN: Dropping non-Abendspiel ADVERT" << endl; #endif return; } //Ensure that the reported IP version of the advert matches the Abuhops //realm it is comming from if ((unsigned)v6 != dat[ADVERT_IPV_OFF]) { /* * This warning is meaningless, since the Abendstern abuhops client * always posts to both realms. #ifdef DEBUG cerr << "WARN: Dropping ADVERT for wrong IP version" << endl; #endif */ return; } if (antenna.tuner) antenna.tuner->receivePacket(defaultEndpoint, &antenna, dat, len); } } <|endoftext|>
<commit_before>#include "osm2nav.h" #include <stdio.h> #include <iostream> #include <boost/lexical_cast.hpp> #include "type/data.h" #include "third_party/osmpbfreader/osmpbfreader.h" #include "osm_tags_reader.h" #include "georef/georef.h" #include "utils/functions.h" namespace navitia { namespace georef { struct OSMHouseNumber{ type::GeographicalCoord coord; int number; OSMHouseNumber(): number(-1){} }; struct Node { public: double lon() const {return static_cast<double>(this->lon_m) / precision;} double lat() const {return static_cast<double>(this->lat_m) / precision;} uint32_t uses; int32_t idx; Node(double lon = 0, double lat = 0) : uses(0), idx(-1), lon_m(lon * precision), lat_m(lat * precision){} bool increment_use(int idx){ uses++; if(this->idx == -1 && uses > 1){ this->idx = idx; return true; } else { return false; } } private: int32_t lon_m; int32_t lat_m; static constexpr double precision = 10e6; }; struct OSMWay { const static uint8_t CYCLE_FWD = 0; const static uint8_t CYCLE_BWD = 1; const static uint8_t CAR_FWD = 2; const static uint8_t CAR_BWD = 3; const static uint8_t FOOT_FWD = 4; const static uint8_t FOOT_BWD = 5; std::vector<uint64_t> refs; uint64_t id; std::bitset<8> properties; type::idx_t idx; }; using namespace CanalTP; struct Visitor{ std::unordered_map<uint64_t, Node> nodes; std::unordered_map<uint64_t, OSMHouseNumber> housenumbers; int total_ways; int total_house_number; std::vector<OSMWay> ways; georef::GeoRef & geo_ref; Visitor(GeoRef & to_fill) : total_ways(0), total_house_number(0), geo_ref(to_fill){} void add_osm_housenumber(uint64_t osmid, const Tags & tags){ if(tags.find("addr:housenumber") != tags.end()){ OSMHouseNumber osm_hn; osm_hn.number = str_to_int(tags.at("addr:housenumber")); if (osm_hn.number > 0 ){ this->housenumbers[osmid] = osm_hn; } } } void node_callback(uint64_t osmid, double lon, double lat, const Tags & tags){ this->nodes[osmid] = Node(lon, lat); add_osm_housenumber(osmid, tags); } void way_callback(uint64_t osmid, const Tags &tags, const std::vector<uint64_t> &refs){ total_ways++; std::bitset<8> properties = parse_way_tags(tags); if(properties.any()){ OSMWay w; w.idx = ways.size(); w.refs = refs; w.id = osmid; ways.push_back(w); georef::Way gr_way; gr_way.idx = w.idx; gr_way.external_code = std::to_string(w.idx); gr_way.city_idx = type::invalid_idx; if(tags.find("name") != tags.end()) gr_way.name = tags.at("name"); geo_ref.ways.push_back(gr_way); }else{ add_osm_housenumber(refs.front(), tags); } } // Once all the ways and nodes are read, we count how many times a node is used to detect intersections void count_nodes_uses() { int count = 0; for(auto w : ways){ for(uint64_t ref : w.refs){ if(nodes[ref].increment_use(count)){ Vertex v; count++; v.coord = type::GeographicalCoord( nodes[ref].lon(), nodes[ref].lat()); boost::add_vertex(v, geo_ref.graph); } } // make sure that the last node is considered as an extremity if(nodes[w.refs.front()].increment_use(count)){ count++; Vertex v; v.coord = type::GeographicalCoord(nodes[w.refs.front()].lon(), nodes[w.refs.front()].lat()); boost::add_vertex(v, geo_ref.graph); } if(nodes[w.refs.back()].increment_use(count)){ count++; Vertex v; v.coord = type::GeographicalCoord(nodes[w.refs.back()].lon(), nodes[w.refs.back()].lat()); boost::add_vertex(v, geo_ref.graph); } } std::cout << "On a : " << boost::num_vertices(geo_ref.graph) << " nœuds" << std::endl; } // Returns the source and target node of the edges void edges(){ for(OSMWay w : ways){ if(w.refs.size() > 0){ Node n = nodes[w.refs[0]]; type::idx_t source = n.idx; type::GeographicalCoord prev(n.lon(), n.lat()); float length = 0; for(size_t i = 1; i < w.refs.size(); ++i){ Node current_node = nodes[w.refs[i]]; type::GeographicalCoord current(current_node.lon(), current_node.lat()); length += current.distance_to(prev); prev = current; // If a node is used more than once, it is an intersection, hence it's a node of the road network graph if(current_node.uses > 1){ type::idx_t target = current_node.idx; georef::Edge e; e.length = length; e.way_idx = w.idx; e.cyclable = w.properties[CYCLE_FWD]; boost::add_edge(source, target, e, geo_ref.graph); e.cyclable = w.properties[CYCLE_BWD]; boost::add_edge(target, source, e, geo_ref.graph); source = target; length = 0; } } } } std::cout << "On a " << boost::num_edges(geo_ref.graph) << " arcs" << std::endl; } void HouseNumbers(){ type::idx_t idx; georef::HouseNumber gr_hn; geo_ref.build_proximity_list(); for(auto hn : housenumbers){ try{ Node n = nodes[hn.first]; gr_hn.number = hn.second.number; gr_hn.coord.set_lon(n.lon()); gr_hn.coord.set_lat(n.lat()); idx = geo_ref.graph[geo_ref.nearest_edge(gr_hn.coord)].way_idx; geo_ref.ways[idx].add_house_number(gr_hn); total_house_number ++; } catch(navitia::proximitylist::NotFound) { std::cout << "Attention, l'adresse n'est pas importée dont le numéro et les coordonnées sont : [" << gr_hn.number<<";"<< gr_hn.coord.lon()<< ";"<< gr_hn.coord.lat()<< "] Impossible de trouver le segment le plus proche. " << std::endl; }catch(...){ std::cout << "Attention, l'adresse n'est pas importée dont le numéro et les coordonnées sont : [" << gr_hn.number<<";"<< gr_hn.coord.lon()<< ";"<< gr_hn.coord.lat()<< "]. " << std::endl; } } } // We don't care about relations void relation_callback(uint64_t /*osmid*/, const Tags &/*tags*/, const References & /*refs*/){} }; void fill_from_osm(GeoRef & geo_ref_to_fill, const std::string & osm_pbf_filename){ Visitor v(geo_ref_to_fill); CanalTP::read_osm_pbf(osm_pbf_filename, v); std::cout << v.nodes.size() << " nodes, " << v.ways.size() << " ways/" << v.total_ways << std::endl; v.count_nodes_uses(); v.edges(); v.HouseNumbers(); std::cout << "On a " << v.total_house_number << " adresses" << std::endl; } }} <commit_msg>georef : Ajout des edges au ways<commit_after>#include "osm2nav.h" #include <stdio.h> #include <iostream> #include <boost/lexical_cast.hpp> #include "type/data.h" #include "third_party/osmpbfreader/osmpbfreader.h" #include "osm_tags_reader.h" #include "georef/georef.h" #include "utils/functions.h" namespace navitia { namespace georef { struct OSMHouseNumber{ type::GeographicalCoord coord; int number; OSMHouseNumber(): number(-1){} }; struct Node { public: double lon() const {return static_cast<double>(this->lon_m) / precision;} double lat() const {return static_cast<double>(this->lat_m) / precision;} uint32_t uses; int32_t idx; Node(double lon = 0, double lat = 0) : uses(0), idx(-1), lon_m(lon * precision), lat_m(lat * precision){} bool increment_use(int idx){ uses++; if(this->idx == -1 && uses > 1){ this->idx = idx; return true; } else { return false; } } private: int32_t lon_m; int32_t lat_m; static constexpr double precision = 10e6; }; struct OSMWay { const static uint8_t CYCLE_FWD = 0; const static uint8_t CYCLE_BWD = 1; const static uint8_t CAR_FWD = 2; const static uint8_t CAR_BWD = 3; const static uint8_t FOOT_FWD = 4; const static uint8_t FOOT_BWD = 5; std::vector<uint64_t> refs; uint64_t id; std::bitset<8> properties; type::idx_t idx; }; using namespace CanalTP; struct Visitor{ std::unordered_map<uint64_t, Node> nodes; std::unordered_map<uint64_t, OSMHouseNumber> housenumbers; int total_ways; int total_house_number; std::vector<OSMWay> ways; georef::GeoRef & geo_ref; Visitor(GeoRef & to_fill) : total_ways(0), total_house_number(0), geo_ref(to_fill){} void add_osm_housenumber(uint64_t osmid, const Tags & tags){ if(tags.find("addr:housenumber") != tags.end()){ OSMHouseNumber osm_hn; osm_hn.number = str_to_int(tags.at("addr:housenumber")); if (osm_hn.number > 0 ){ this->housenumbers[osmid] = osm_hn; } } } void node_callback(uint64_t osmid, double lon, double lat, const Tags & tags){ this->nodes[osmid] = Node(lon, lat); add_osm_housenumber(osmid, tags); } void way_callback(uint64_t osmid, const Tags &tags, const std::vector<uint64_t> &refs){ total_ways++; std::bitset<8> properties = parse_way_tags(tags); if(properties.any()){ OSMWay w; w.idx = ways.size(); w.refs = refs; w.id = osmid; ways.push_back(w); georef::Way gr_way; gr_way.idx = w.idx; gr_way.external_code = std::to_string(w.idx); gr_way.city_idx = type::invalid_idx; if(tags.find("name") != tags.end()) gr_way.name = tags.at("name"); geo_ref.ways.push_back(gr_way); }else{ add_osm_housenumber(refs.front(), tags); } } // Once all the ways and nodes are read, we count how many times a node is used to detect intersections void count_nodes_uses() { int count = 0; for(auto w : ways){ for(uint64_t ref : w.refs){ if(nodes[ref].increment_use(count)){ Vertex v; count++; v.coord = type::GeographicalCoord( nodes[ref].lon(), nodes[ref].lat()); boost::add_vertex(v, geo_ref.graph); } } // make sure that the last node is considered as an extremity if(nodes[w.refs.front()].increment_use(count)){ count++; Vertex v; v.coord = type::GeographicalCoord(nodes[w.refs.front()].lon(), nodes[w.refs.front()].lat()); boost::add_vertex(v, geo_ref.graph); } if(nodes[w.refs.back()].increment_use(count)){ count++; Vertex v; v.coord = type::GeographicalCoord(nodes[w.refs.back()].lon(), nodes[w.refs.back()].lat()); boost::add_vertex(v, geo_ref.graph); } } std::cout << "On a : " << boost::num_vertices(geo_ref.graph) << " nœuds" << std::endl; } // Returns the source and target node of the edges void edges(){ for(OSMWay w : ways){ if(w.refs.size() > 0){ Node n = nodes[w.refs[0]]; type::idx_t source = n.idx; type::GeographicalCoord prev(n.lon(), n.lat()); float length = 0; for(size_t i = 1; i < w.refs.size(); ++i){ Node current_node = nodes[w.refs[i]]; type::GeographicalCoord current(current_node.lon(), current_node.lat()); length += current.distance_to(prev); prev = current; // If a node is used more than once, it is an intersection, hence it's a node of the road network graph if(current_node.uses > 1){ type::idx_t target = current_node.idx; georef::Edge e; e.length = length; e.way_idx = w.idx; e.cyclable = w.properties[CYCLE_FWD]; boost::add_edge(source, target, e, geo_ref.graph); geo_ref.ways[w.idx].edges.push_back(std::make_pair(source, target)); e.cyclable = w.properties[CYCLE_BWD]; boost::add_edge(target, source, e, geo_ref.graph); geo_ref.ways[w.idx].edges.push_back(std::make_pair(target, source)); source = target; length = 0; } } } } std::cout << "On a " << boost::num_edges(geo_ref.graph) << " arcs" << std::endl; } void HouseNumbers(){ type::idx_t idx; georef::HouseNumber gr_hn; geo_ref.build_proximity_list(); for(auto hn : housenumbers){ try{ Node n = nodes[hn.first]; gr_hn.number = hn.second.number; gr_hn.coord.set_lon(n.lon()); gr_hn.coord.set_lat(n.lat()); idx = geo_ref.graph[geo_ref.nearest_edge(gr_hn.coord)].way_idx; geo_ref.ways[idx].add_house_number(gr_hn); total_house_number ++; } catch(navitia::proximitylist::NotFound) { std::cout << "Attention, l'adresse n'est pas importée dont le numéro et les coordonnées sont : [" << gr_hn.number<<";"<< gr_hn.coord.lon()<< ";"<< gr_hn.coord.lat()<< "] Impossible de trouver le segment le plus proche. " << std::endl; }catch(...){ std::cout << "Attention, l'adresse n'est pas importée dont le numéro et les coordonnées sont : [" << gr_hn.number<<";"<< gr_hn.coord.lon()<< ";"<< gr_hn.coord.lat()<< "]. " << std::endl; } } } // We don't care about relations void relation_callback(uint64_t /*osmid*/, const Tags &/*tags*/, const References & /*refs*/){} }; void fill_from_osm(GeoRef & geo_ref_to_fill, const std::string & osm_pbf_filename){ Visitor v(geo_ref_to_fill); CanalTP::read_osm_pbf(osm_pbf_filename, v); std::cout << v.nodes.size() << " nodes, " << v.ways.size() << " ways/" << v.total_ways << std::endl; v.count_nodes_uses(); v.edges(); v.HouseNumbers(); std::cout << "On a " << v.total_house_number << " adresses" << std::endl; } }} <|endoftext|>
<commit_before>/* * Copyright 2016 - 2019 gtalent2@gmail.com * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "addresses.hpp" #include <ox/std/assert.hpp> #include <ox/std/bit.hpp> // this warning is too dumb to realize that it can actually confirm the hard // coded address aligns with the requirement of HeapSegment, so it must be // suppressed #pragma GCC diagnostic ignored "-Wcast-align" #define HEAP_BEGIN reinterpret_cast<HeapSegment*>(MEM_WRAM_BEGIN) // set size to half of WRAM #define HEAP_SIZE ((MEM_WRAM_END - MEM_WRAM_BEGIN) / 2) #define HEAP_END reinterpret_cast<HeapSegment*>(MEM_WRAM_BEGIN + HEAP_SIZE) namespace nostalgia::core { static class HeapSegment *volatile g_heapBegin = nullptr; static class HeapSegment *volatile g_heapEnd = nullptr; static class HeapSegment *volatile heapIdx = nullptr; static constexpr std::size_t alignedSize(std::size_t sz) { return sz + (sz & 7); } template<typename T> static constexpr std::size_t alignedSize(T = {}) { return alignedSize(sizeof(T)); } struct HeapSegment { std::size_t size; uint8_t inUse; void init(std::size_t maxSize = ox::bit_cast<std::size_t>(g_heapEnd)) { this->size = maxSize - ox::bit_cast<std::size_t>(this); this->inUse = false; } template<typename T> T *data() { return ox::bit_cast<T*>(ox::bit_cast<uint8_t*>(this) + alignedSize(this)); } template<typename T = uint8_t> T *end() { const auto size = alignedSize(this) + alignedSize(this->size); auto e = ox::bit_cast<uintptr_t>(ox::bit_cast<uint8_t*>(this) + size); return ox::bit_cast<T*>(e); } }; void initHeap(char *heapBegin, char *heapEnd) { g_heapBegin = ox::bit_cast<HeapSegment*>(heapBegin); g_heapEnd = ox::bit_cast<HeapSegment*>(heapEnd); heapIdx = g_heapBegin; heapIdx->size = ox::bit_cast<std::size_t>(heapEnd) - ox::bit_cast<std::size_t>(heapIdx); heapIdx->inUse = false; } void initHeap() { initHeap(ox::bit_cast<char*>(HEAP_BEGIN), ox::bit_cast<char*>(HEAP_END)); } struct SegmentPair { HeapSegment *anteSegment = nullptr; HeapSegment *segment = nullptr; }; static SegmentPair findSegmentOf(void *ptr) { HeapSegment *prev = nullptr; for (auto seg = HEAP_BEGIN; seg < HEAP_END;) { if (seg->data<void>() == ptr) { return {prev, seg}; } prev = seg; seg = seg->end<HeapSegment>(); } return {}; } static HeapSegment *findSegmentFor(std::size_t sz) { for (auto s = g_heapBegin; s <= g_heapEnd; s = s->end<HeapSegment>()) { if (s->size >= sz && !s->inUse) { return s; } } oxPanic(OxError(1), "malloc: could not find segment"); return nullptr; } [[nodiscard]] void *malloc(std::size_t allocSize) { const auto targetSize = alignedSize(sizeof(HeapSegment)) + alignedSize(allocSize); auto seg = findSegmentFor(targetSize); if (seg == nullptr) { return nullptr; } const auto bytesRemaining = seg->size - targetSize; seg->size = targetSize; seg->inUse = true; seg->end<HeapSegment>()->init(bytesRemaining); return seg->data<void>(); } void free(void *ptr) { auto p = findSegmentOf(ptr); if (p.anteSegment) { p.anteSegment->size += p.segment->size; } else if (p.segment) { p.segment->inUse = false; } else { oxPanic(OxError(1), "Bad heap free"); } } } #ifndef OX_USE_STDLIB using namespace nostalgia; void *operator new(std::size_t allocSize) { return core::malloc(allocSize); } void *operator new[](std::size_t allocSize) { return core::malloc(allocSize); } void operator delete(void *ptr) { core::free(ptr); } void operator delete[](void *ptr) { core::free(ptr); } void operator delete(void *ptr, unsigned) { core::free(ptr); } void operator delete[](void *ptr, unsigned) { core::free(ptr); } void operator delete(void *ptr, unsigned long int) { core::free(ptr); } void operator delete[](void *ptr, unsigned long int) { core::free(ptr); } #endif <commit_msg>[nostalgia/core/gba] Cleanup class/struct inconsistency<commit_after>/* * Copyright 2016 - 2019 gtalent2@gmail.com * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "addresses.hpp" #include <ox/std/assert.hpp> #include <ox/std/bit.hpp> // this warning is too dumb to realize that it can actually confirm the hard // coded address aligns with the requirement of HeapSegment, so it must be // suppressed #pragma GCC diagnostic ignored "-Wcast-align" #define HEAP_BEGIN reinterpret_cast<HeapSegment*>(MEM_WRAM_BEGIN) // set size to half of WRAM #define HEAP_SIZE ((MEM_WRAM_END - MEM_WRAM_BEGIN) / 2) #define HEAP_END reinterpret_cast<HeapSegment*>(MEM_WRAM_BEGIN + HEAP_SIZE) namespace nostalgia::core { static struct HeapSegment *volatile g_heapBegin = nullptr; static struct HeapSegment *volatile g_heapEnd = nullptr; static struct HeapSegment *volatile heapIdx = nullptr; static constexpr std::size_t alignedSize(std::size_t sz) { return sz + (sz & 7); } template<typename T> static constexpr std::size_t alignedSize(T = {}) { return alignedSize(sizeof(T)); } struct HeapSegment { std::size_t size; uint8_t inUse; void init(std::size_t maxSize = ox::bit_cast<std::size_t>(g_heapEnd)) { this->size = maxSize - ox::bit_cast<std::size_t>(this); this->inUse = false; } template<typename T> T *data() { return ox::bit_cast<T*>(ox::bit_cast<uint8_t*>(this) + alignedSize(this)); } template<typename T = uint8_t> T *end() { const auto size = alignedSize(this) + alignedSize(this->size); auto e = ox::bit_cast<uintptr_t>(ox::bit_cast<uint8_t*>(this) + size); return ox::bit_cast<T*>(e); } }; void initHeap(char *heapBegin, char *heapEnd) { g_heapBegin = ox::bit_cast<HeapSegment*>(heapBegin); g_heapEnd = ox::bit_cast<HeapSegment*>(heapEnd); heapIdx = g_heapBegin; heapIdx->size = ox::bit_cast<std::size_t>(heapEnd) - ox::bit_cast<std::size_t>(heapIdx); heapIdx->inUse = false; } void initHeap() { initHeap(ox::bit_cast<char*>(HEAP_BEGIN), ox::bit_cast<char*>(HEAP_END)); } struct SegmentPair { HeapSegment *anteSegment = nullptr; HeapSegment *segment = nullptr; }; static SegmentPair findSegmentOf(void *ptr) { HeapSegment *prev = nullptr; for (auto seg = HEAP_BEGIN; seg < HEAP_END;) { if (seg->data<void>() == ptr) { return {prev, seg}; } prev = seg; seg = seg->end<HeapSegment>(); } return {}; } static HeapSegment *findSegmentFor(std::size_t sz) { for (auto s = g_heapBegin; s <= g_heapEnd; s = s->end<HeapSegment>()) { if (s->size >= sz && !s->inUse) { return s; } } oxPanic(OxError(1), "malloc: could not find segment"); return nullptr; } [[nodiscard]] void *malloc(std::size_t allocSize) { const auto targetSize = alignedSize(sizeof(HeapSegment)) + alignedSize(allocSize); auto seg = findSegmentFor(targetSize); if (seg == nullptr) { return nullptr; } const auto bytesRemaining = seg->size - targetSize; seg->size = targetSize; seg->inUse = true; seg->end<HeapSegment>()->init(bytesRemaining); return seg->data<void>(); } void free(void *ptr) { auto p = findSegmentOf(ptr); if (p.anteSegment) { p.anteSegment->size += p.segment->size; } else if (p.segment) { p.segment->inUse = false; } else { oxPanic(OxError(1), "Bad heap free"); } } } #ifndef OX_USE_STDLIB using namespace nostalgia; void *operator new(std::size_t allocSize) { return core::malloc(allocSize); } void *operator new[](std::size_t allocSize) { return core::malloc(allocSize); } void operator delete(void *ptr) { core::free(ptr); } void operator delete[](void *ptr) { core::free(ptr); } void operator delete(void *ptr, unsigned) { core::free(ptr); } void operator delete[](void *ptr, unsigned) { core::free(ptr); } void operator delete(void *ptr, unsigned long int) { core::free(ptr); } void operator delete[](void *ptr, unsigned long int) { core::free(ptr); } #endif <|endoftext|>
<commit_before>#ifndef CXX_CONVERSIONS_HXX # define CXX_CONVERSIONS_HXX # include <libport/symbol.hh> # include <object/cxx-object.hh> # include <object/float-class.hh> # include <object/string-class.hh> # include <scheduler/tag.hh> namespace object { // Nothing to do for objects template <> class CxxConvert<libport::shared_ptr<Object, true> > { public: static rObject to(const rObject& o, const libport::Symbol&) { return o; } static rObject from(rObject o, const libport::Symbol&) { if (!o) return void_class; return o; } }; // Convert between Urbi types template <typename Urbi> struct CxxConvert<libport::shared_ptr<Urbi, true> > { typedef libport::shared_ptr<Urbi, true> T; static T to(const rObject& o, const libport::Symbol& name) { type_check<Urbi>(o, name); return o->as<Urbi>(); } static rObject from(const T& v, const libport::Symbol&) { return v; } }; // Conversion with prio_type template<> struct CxxConvert<scheduler::prio_type> { static scheduler::prio_type to(const rObject& o, const libport::Symbol& name) { type_check<Float>(o, name); rFloat f = o->as<Float>(); int res = f->to_int(name); if (res < 0) throw BadInteger(f->value_get(), name); return res; } static rObject from(const scheduler::prio_type& v, const libport::Symbol&) { return new Float(v); } }; // Conversion with std::strings template <> struct CxxConvert<std::string> { static std::string to(const rObject& o, const libport::Symbol& name) { type_check<String>(o, name); return o->as<String>()->value_get().name_get(); } static rObject from(const std::string& v, const libport::Symbol&) { return new String(libport::Symbol(v)); } }; // Conversion with libport::Symbols template <> struct CxxConvert<libport::Symbol> { static libport::Symbol to(const rObject& o, const libport::Symbol& name) { type_check<String>(o, name); return o->as<String>()->value_get(); } static rObject from(const libport::Symbol& v, const libport::Symbol&) { return new String(v); } }; // Conversion with bools template <> struct CxxConvert<bool> { static bool to(const rObject& o, const libport::Symbol& name) { return is_true(o, name); } static rObject from(bool v, const libport::Symbol&) { return v ? true_class : false_class; } }; } #endif <commit_msg>Generalize the conversion to unsigned int.<commit_after>#ifndef CXX_CONVERSIONS_HXX # define CXX_CONVERSIONS_HXX # include <libport/symbol.hh> # include <object/cxx-object.hh> # include <object/float-class.hh> # include <object/string-class.hh> # include <scheduler/tag.hh> namespace object { // Nothing to do for objects template <> class CxxConvert<libport::shared_ptr<Object, true> > { public: static rObject to(const rObject& o, const libport::Symbol&) { return o; } static rObject from(rObject o, const libport::Symbol&) { if (!o) return void_class; return o; } }; // Convert between Urbi types template <typename Urbi> struct CxxConvert<libport::shared_ptr<Urbi, true> > { typedef libport::shared_ptr<Urbi, true> T; static T to(const rObject& o, const libport::Symbol& name) { type_check<Urbi>(o, name); return o->as<Urbi>(); } static rObject from(const T& v, const libport::Symbol&) { return v; } }; // Conversion with unsigned int template<> struct CxxConvert<unsigned int> { static unsigned int to(const rObject& o, const libport::Symbol& name) { type_check<Float>(o, name); return o->as<Float>()->to_unsigned_int(name); } static rObject from(const unsigned int& v, const libport::Symbol&) { return new Float(v); } }; // Conversion with std::strings template <> struct CxxConvert<std::string> { static std::string to(const rObject& o, const libport::Symbol& name) { type_check<String>(o, name); return o->as<String>()->value_get().name_get(); } static rObject from(const std::string& v, const libport::Symbol&) { return new String(libport::Symbol(v)); } }; // Conversion with libport::Symbols template <> struct CxxConvert<libport::Symbol> { static libport::Symbol to(const rObject& o, const libport::Symbol& name) { type_check<String>(o, name); return o->as<String>()->value_get(); } static rObject from(const libport::Symbol& v, const libport::Symbol&) { return new String(v); } }; // Conversion with bools template <> struct CxxConvert<bool> { static bool to(const rObject& o, const libport::Symbol& name) { return is_true(o, name); } static rObject from(bool v, const libport::Symbol&) { return v ? true_class : false_class; } }; } #endif <|endoftext|>
<commit_before>#include <node.h> #include <v8.h> #include "Application.h" #include "SpotifyService/SpotifyService.h" #include "NodeCallback.h" #include "objects/node/StaticCallbackSetter.h" #include "objects/spotify/PlaylistContainer.h" #include "objects/node/NodePlaylist.h" #include "objects/node/NodeTrack.h" #include "objects/node/NodePlayer.h" #include "objects/node/NodeAlbum.h" #include "objects/node/NodeArtist.h" #include "objects/node/NodeSearch.h" extern "C" { #include "audio/audio.h" } using namespace v8; Application* application; Handle<Value> login(const Arguments& args) { HandleScope scope; String::Utf8Value v8User(args[0]->ToString()); String::Utf8Value v8Password(args[1]->ToString()); bool rememberMe = args[2]->ToBoolean()->Value(); bool withRemembered = args[3]->ToBoolean()->Value(); std::string user(*v8User); std::string password(*v8Password); application->spotifyService->login(user, password, rememberMe, withRemembered); return scope.Close(Undefined()); } Handle<Value> logout(const Arguments& args) { HandleScope scope; auto callback = [] () { application->spotifyService->logout(); }; application->spotifyService->executeSpotifyAPIcall(callback); return scope.Close(Undefined()); } Handle<Value> ready(const Arguments& args) { HandleScope scope; Handle<Function> fun = Handle<Function>::Cast(args[0]); Persistent<Function> p = Persistent<Function>::New(fun); application->loginCallback = p; return scope.Close(Undefined()); } Handle<Value> getPlaylists(const Arguments& args) { HandleScope scope; std::vector<std::shared_ptr<Playlist>> playlists = application->playlistContainer->getPlaylists(); Local<Array> nPlaylists = Array::New(playlists.size()); for(int i = 0; i < (int)playlists.size(); i++) { NodePlaylist* nodePlaylist = new NodePlaylist(playlists[i]); nPlaylists->Set(Number::New(i), nodePlaylist->getV8Object()); } return scope.Close(nPlaylists); } Handle<Value> getStarred(const Arguments& args) { HandleScope scope; NodePlaylist* starredPlaylist = new NodePlaylist(application->playlistContainer->starredPlaylist); return scope.Close(starredPlaylist->getV8Object()); } /** * Handle a NodeCallback sent to this thread. * The handle should contain a NodeCallback struct **/ void resolveCallback(uv_async_t* handle, int status) { HandleScope scope; NodeCallback* nodeCallback = (NodeCallback*)handle->data; Handle<Function>* fun = nodeCallback->function; const unsigned int argc = 0; Local<Value> argv[argc] = { }; if(!(*fun).IsEmpty() && (*fun)->IsCallable()) { //Check if an object is attached to the struct and if, use it as the scope. if(nodeCallback->object == 0 || nodeCallback->object->getV8Object().IsEmpty()) (*fun)->Call(Context::GetCurrent()->Global(), argc, argv); else (*fun)->Call(nodeCallback->object->getV8Object(), argc, argv); } scope.Close(Undefined()); } Handle<Value> rememberedUser(const Arguments& args) { HandleScope scope; if(application->spotifyService->rememberedUser != 0) { return scope.Close(String::New(application->spotifyService->rememberedUser)); } else { return scope.Close(Undefined()); } } void init(Handle<Object> target) { NodePlaylist::init(); NodeTrack::init(); NodeArtist::init(); NodePlayer::init(); NodeAlbum::init(); NodeSearch::init(target); StaticCallbackSetter<NodePlaylist>::init(target, "playlists"); application = new Application(); application->spotifyService = std::unique_ptr<SpotifyService>(new SpotifyService()); audio_init(&application->audio_fifo); target->Set(String::NewSymbol("login"), FunctionTemplate::New(login)->GetFunction()); target->Set(String::NewSymbol("logout"), FunctionTemplate::New(logout)->GetFunction()); target->Set(String::NewSymbol("getPlaylists"), FunctionTemplate::New(getPlaylists)->GetFunction()); target->Set(String::NewSymbol("getStarred"), FunctionTemplate::New(getStarred)->GetFunction()); target->Set(String::NewSymbol("ready"), FunctionTemplate::New(ready)->GetFunction()); target->Set(String::NewSymbol("player"), NodePlayer::getInstance().getV8Object()); target->Set(String::NewSymbol("rememberedUser"), FunctionTemplate::New(rememberedUser)->GetFunction()); //Initialize waiting for callbacks from the spotify thread uv_async_init(uv_default_loop(), &application->asyncHandle, resolveCallback); } NODE_MODULE(spotify, init) <commit_msg>Callbacks are now called in the fashion of function(err, object) instead of mutating this<commit_after>#include <node.h> #include <v8.h> #include "Application.h" #include "SpotifyService/SpotifyService.h" #include "NodeCallback.h" #include "objects/node/StaticCallbackSetter.h" #include "objects/spotify/PlaylistContainer.h" #include "objects/node/NodePlaylist.h" #include "objects/node/NodeTrack.h" #include "objects/node/NodePlayer.h" #include "objects/node/NodeAlbum.h" #include "objects/node/NodeArtist.h" #include "objects/node/NodeSearch.h" extern "C" { #include "audio/audio.h" } using namespace v8; Application* application; Handle<Value> login(const Arguments& args) { HandleScope scope; String::Utf8Value v8User(args[0]->ToString()); String::Utf8Value v8Password(args[1]->ToString()); bool rememberMe = args[2]->ToBoolean()->Value(); bool withRemembered = args[3]->ToBoolean()->Value(); std::string user(*v8User); std::string password(*v8Password); application->spotifyService->login(user, password, rememberMe, withRemembered); return scope.Close(Undefined()); } Handle<Value> logout(const Arguments& args) { HandleScope scope; auto callback = [] () { application->spotifyService->logout(); }; application->spotifyService->executeSpotifyAPIcall(callback); return scope.Close(Undefined()); } Handle<Value> ready(const Arguments& args) { HandleScope scope; Handle<Function> fun = Handle<Function>::Cast(args[0]); Persistent<Function> p = Persistent<Function>::New(fun); application->loginCallback = p; return scope.Close(Undefined()); } Handle<Value> getPlaylists(const Arguments& args) { HandleScope scope; std::vector<std::shared_ptr<Playlist>> playlists = application->playlistContainer->getPlaylists(); Local<Array> nPlaylists = Array::New(playlists.size()); for(int i = 0; i < (int)playlists.size(); i++) { NodePlaylist* nodePlaylist = new NodePlaylist(playlists[i]); nPlaylists->Set(Number::New(i), nodePlaylist->getV8Object()); } return scope.Close(nPlaylists); } Handle<Value> getStarred(const Arguments& args) { HandleScope scope; NodePlaylist* starredPlaylist = new NodePlaylist(application->playlistContainer->starredPlaylist); return scope.Close(starredPlaylist->getV8Object()); } /** * Handle a NodeCallback sent to this thread. * The handle should contain a NodeCallback struct **/ void resolveCallback(uv_async_t* handle, int status) { HandleScope scope; NodeCallback* callbackStruct = (NodeCallback*)handle->data; Handle<Function>* callback = callbackStruct->function; //only execute if a callback is attached if(!(*callback).IsEmpty() && (*callback)->IsCallable()) { unsigned int argc; Handle<Value>* argv; //if the callback has a V8 object attach use it as the second argument for the callback //TODO: atm error is constantly undefined. if(callbackStruct->object != nullptr && !callbackStruct->object->getV8Object().IsEmpty()) { argc = 2; argv = new Handle<Value>[2]; argv[0] = Undefined(); argv[1] = callbackStruct->object->getV8Object(); } else { argc = 1; argv = new Handle<Value>[1]; argv[0] = Undefined(); } (*callback)->Call(Context::GetCurrent()->Global(), argc, argv); delete[] argv; } scope.Close(Undefined()); } Handle<Value> rememberedUser(const Arguments& args) { HandleScope scope; if(application->spotifyService->rememberedUser != 0) { return scope.Close(String::New(application->spotifyService->rememberedUser)); } else { return scope.Close(Undefined()); } } void init(Handle<Object> target) { NodePlaylist::init(); NodeTrack::init(); NodeArtist::init(); NodePlayer::init(); NodeAlbum::init(); NodeSearch::init(target); StaticCallbackSetter<NodePlaylist>::init(target, "playlists"); application = new Application(); application->spotifyService = std::unique_ptr<SpotifyService>(new SpotifyService()); audio_init(&application->audio_fifo); target->Set(String::NewSymbol("login"), FunctionTemplate::New(login)->GetFunction()); target->Set(String::NewSymbol("logout"), FunctionTemplate::New(logout)->GetFunction()); target->Set(String::NewSymbol("getPlaylists"), FunctionTemplate::New(getPlaylists)->GetFunction()); target->Set(String::NewSymbol("getStarred"), FunctionTemplate::New(getStarred)->GetFunction()); target->Set(String::NewSymbol("ready"), FunctionTemplate::New(ready)->GetFunction()); target->Set(String::NewSymbol("player"), NodePlayer::getInstance().getV8Object()); target->Set(String::NewSymbol("rememberedUser"), FunctionTemplate::New(rememberedUser)->GetFunction()); //Initialize waiting for callbacks from the spotify thread uv_async_init(uv_default_loop(), &application->asyncHandle, resolveCallback); } NODE_MODULE(spotify, init) <|endoftext|>
<commit_before>#include <BRepBuilderAPI_MakeShape.hxx> #include <BRepPrimAPI_MakeBox.hxx> #include <StlAPI_Writer.hxx> #include <rice/Class.hpp> using namespace Rice; void shape_write_stl(Object self, const char *path) { Data_Object<TopoDS_Shape> shape = self.call("render"); StlAPI_Writer writer; writer.ASCIIMode() = false; writer.RelativeMode() = false; writer.SetDeflection(0.05); // TODO: deflection param writer.Write(*shape, path); } void box_initialize(Object self, double xsize, double ysize, double zsize) { self.iv_set("@xsize", xsize); self.iv_set("@ysize", ysize); self.iv_set("@zsize", zsize); self.iv_set("@shape", BRepPrimAPI_MakeBox(xsize, ysize, zsize).Shape()); } void union_initialize(Object self, Object a, Object b) { self.iv_set("@a", a); self.iv_set("@b", b); } extern "C" void Init__yrcad() { Data_Type<TopoDS_Shape> rb_cRenderedShape = define_class<TopoDS_Shape>("RenderedShape"); Class rb_cShape = define_class("Shape") .define_method("write_stl", &shape_write_stl); Class rb_cBox = define_class("Box", rb_cShape) .define_method("initialize", &box_initialize); Class rb_cUnion = define_class("Union", rb_cShape) .define_method("initialize", &union_initialize); } <commit_msg>Accept String param correctly in shape_write_stl.<commit_after>#include <BRepPrimAPI_MakeBox.hxx> #include <StlAPI_Writer.hxx> #include <rice/Class.hpp> using namespace Rice; void shape_write_stl(Object self, String path) { Data_Object<TopoDS_Shape> shape = self.call("render"); StlAPI_Writer writer; writer.ASCIIMode() = false; writer.RelativeMode() = false; writer.SetDeflection(0.05); // TODO: deflection param writer.Write(*shape, path.c_str()); } void box_initialize(Object self, double xsize, double ysize, double zsize) { self.iv_set("@xsize", xsize); self.iv_set("@ysize", ysize); self.iv_set("@zsize", zsize); self.iv_set("@shape", BRepPrimAPI_MakeBox(xsize, ysize, zsize).Shape()); } void union_initialize(Object self, Object a, Object b) { self.iv_set("@a", a); self.iv_set("@b", b); } extern "C" void Init__yrcad() { Data_Type<TopoDS_Shape> rb_cRenderedShape = define_class<TopoDS_Shape>("RenderedShape"); Class rb_cShape = define_class("Shape") .define_method("write_stl", &shape_write_stl); Class rb_cBox = define_class("Box", rb_cShape) .define_method("initialize", &box_initialize); Class rb_cUnion = define_class("Union", rb_cShape) .define_method("initialize", &union_initialize); } <|endoftext|>
<commit_before>/* * Copyright (C) 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. */ #define LOG_TAG "JNIHelp" #include "JNIHelp.h" #include "log_compat.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> /** * Equivalent to ScopedLocalRef, but for C_JNIEnv instead. (And slightly more powerful.) */ template<typename T> class scoped_local_ref { public: scoped_local_ref(JNIEnv* env, T localRef = NULL) : mEnv(env), mLocalRef(localRef) { } ~scoped_local_ref() { reset(); } void reset(T localRef = NULL) { if (mLocalRef != NULL) { mEnv->DeleteLocalRef(mLocalRef); mLocalRef = localRef; } } T get() const { return mLocalRef; } private: JNIEnv* mEnv; T mLocalRef; // Disallow copy and assignment. scoped_local_ref(const scoped_local_ref&); void operator=(const scoped_local_ref&); }; static jclass findClass(JNIEnv* env, const char* className) { return env->FindClass(className); } extern "C" int jniRegisterNativeMethods(JNIEnv* env, const char* className, const JNINativeMethod* gMethods, int numMethods) { ALOGV("Registering %s's %d native methods...", className, numMethods); scoped_local_ref<jclass> c(env, findClass(env, className)); if (c.get() == NULL) { char* msg; (void)asprintf(&msg, "Native registration unable to find class '%s'; aborting...", className); env->FatalError(msg); } if (env->RegisterNatives(c.get(), gMethods, numMethods) < 0) { char* msg; (void)asprintf(&msg, "RegisterNatives failed for '%s'; aborting...", className); env->FatalError(msg); } return 0; } #ifdef __cplusplus extern "C" #endif int jniThrowException(JNIEnv* env, const char* className, const char* msg) { jclass exceptionClass = env->FindClass(className); if (exceptionClass == NULL) { ALOGD("Unable to find exception class %s", className); /* ClassNotFoundException now pending */ return -1; } if (env->ThrowNew(exceptionClass, msg) != JNI_OK) { ALOGD("Failed throwing '%s' '%s'", className, msg); /* an exception, most likely OOM, will now be pending */ return -1; } env->DeleteLocalRef(exceptionClass); return 0; } int jniThrowExceptionFmt(JNIEnv* env, const char* className, const char* fmt, va_list args) { char msgBuf[512]; vsnprintf(msgBuf, sizeof(msgBuf), fmt, args); return jniThrowException(env, className, msgBuf); } int jniThrowNullPointerException(JNIEnv* env, const char* msg) { return jniThrowException(env, "java/lang/NullPointerException", msg); } int jniThrowRuntimeException(JNIEnv* env, const char* msg) { return jniThrowException(env, "java/lang/RuntimeException", msg); } int jniThrowIOException(JNIEnv* env, int errnum) { char buffer[80]; const char* message = jniStrError(errnum, buffer, sizeof(buffer)); return jniThrowException(env, "java/io/IOException", message); } const char* jniStrError(int errnum, char* buf, size_t buflen) { #if __GLIBC__ // Note: glibc has a nonstandard strerror_r that returns char* rather than POSIX's int. // char *strerror_r(int errnum, char *buf, size_t n); return strerror_r(errnum, buf, buflen); #else int rc = strerror_r(errnum, buf, buflen); if (rc != 0) { // (POSIX only guarantees a value other than 0. The safest // way to implement this function is to use C++ and overload on the // type of strerror_r to accurately distinguish GNU from POSIX.) snprintf(buf, buflen, "errno %d", errnum); } return buf; #endif } int jniGetFDFromFileDescriptor(JNIEnv* env, jobject fileDescriptor) { scoped_local_ref<jclass> localClass(env, env->FindClass("java/io/FileDescriptor")); static jfieldID fid = env->GetFieldID(localClass.get(), "descriptor", "I"); if (fileDescriptor != NULL) { return env->GetIntField(fileDescriptor, fid); } else { return -1; } } <commit_msg>Properly select file-descriptor field on non-Android VMs for TLS ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=122108670 am: 271dc367ef am: 448f388951<commit_after>/* * Copyright (C) 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. */ #define LOG_TAG "JNIHelp" #include "JNIHelp.h" #include "log_compat.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> /** * Equivalent to ScopedLocalRef, but for C_JNIEnv instead. (And slightly more powerful.) */ template<typename T> class scoped_local_ref { public: scoped_local_ref(JNIEnv* env, T localRef = NULL) : mEnv(env), mLocalRef(localRef) { } ~scoped_local_ref() { reset(); } void reset(T localRef = NULL) { if (mLocalRef != NULL) { mEnv->DeleteLocalRef(mLocalRef); mLocalRef = localRef; } } T get() const { return mLocalRef; } private: JNIEnv* mEnv; T mLocalRef; // Disallow copy and assignment. scoped_local_ref(const scoped_local_ref&); void operator=(const scoped_local_ref&); }; static jclass findClass(JNIEnv* env, const char* className) { return env->FindClass(className); } extern "C" int jniRegisterNativeMethods(JNIEnv* env, const char* className, const JNINativeMethod* gMethods, int numMethods) { ALOGV("Registering %s's %d native methods...", className, numMethods); scoped_local_ref<jclass> c(env, findClass(env, className)); if (c.get() == NULL) { char* msg; (void)asprintf(&msg, "Native registration unable to find class '%s'; aborting...", className); env->FatalError(msg); } if (env->RegisterNatives(c.get(), gMethods, numMethods) < 0) { char* msg; (void)asprintf(&msg, "RegisterNatives failed for '%s'; aborting...", className); env->FatalError(msg); } return 0; } #ifdef __cplusplus extern "C" #endif int jniThrowException(JNIEnv* env, const char* className, const char* msg) { jclass exceptionClass = env->FindClass(className); if (exceptionClass == NULL) { ALOGD("Unable to find exception class %s", className); /* ClassNotFoundException now pending */ return -1; } if (env->ThrowNew(exceptionClass, msg) != JNI_OK) { ALOGD("Failed throwing '%s' '%s'", className, msg); /* an exception, most likely OOM, will now be pending */ return -1; } env->DeleteLocalRef(exceptionClass); return 0; } int jniThrowExceptionFmt(JNIEnv* env, const char* className, const char* fmt, va_list args) { char msgBuf[512]; vsnprintf(msgBuf, sizeof(msgBuf), fmt, args); return jniThrowException(env, className, msgBuf); } int jniThrowNullPointerException(JNIEnv* env, const char* msg) { return jniThrowException(env, "java/lang/NullPointerException", msg); } int jniThrowRuntimeException(JNIEnv* env, const char* msg) { return jniThrowException(env, "java/lang/RuntimeException", msg); } int jniThrowIOException(JNIEnv* env, int errnum) { char buffer[80]; const char* message = jniStrError(errnum, buffer, sizeof(buffer)); return jniThrowException(env, "java/io/IOException", message); } const char* jniStrError(int errnum, char* buf, size_t buflen) { #if __GLIBC__ // Note: glibc has a nonstandard strerror_r that returns char* rather than POSIX's int. // char *strerror_r(int errnum, char *buf, size_t n); return strerror_r(errnum, buf, buflen); #else int rc = strerror_r(errnum, buf, buflen); if (rc != 0) { // (POSIX only guarantees a value other than 0. The safest // way to implement this function is to use C++ and overload on the // type of strerror_r to accurately distinguish GNU from POSIX.) snprintf(buf, buflen, "errno %d", errnum); } return buf; #endif } int jniGetFDFromFileDescriptor(JNIEnv* env, jobject fileDescriptor) { scoped_local_ref<jclass> localClass(env, env->FindClass("java/io/FileDescriptor")); static jfieldID fid = env->GetFieldID(localClass.get(), "fd", "I"); if (fileDescriptor != NULL) { return env->GetIntField(fileDescriptor, fid); } else { return -1; } } <|endoftext|>
<commit_before>// Copyright (c) 2014, Facebook, Inc. All rights reserved. // This source code is licensed under the BSD-style license found in the // LICENSE file in the root directory of this source tree. An additional grant // of patent rights can be found in the PATENTS file in the same directory. #include "util/sync_point.h" #ifndef NDEBUG namespace rocksdb { SyncPoint* SyncPoint::GetInstance() { static SyncPoint sync_point; return &sync_point; } void SyncPoint::LoadDependency(const std::vector<Dependency>& dependencies) { successors_.clear(); predecessors_.clear(); cleared_points_.clear(); for (const auto& dependency : dependencies) { successors_[dependency.predecessor].push_back(dependency.successor); predecessors_[dependency.successor].push_back(dependency.predecessor); } } bool SyncPoint::PredecessorsAllCleared(const std::string& point) { for (const auto& pred : predecessors_[point]) { if (cleared_points_.count(pred) == 0) { return false; } } return true; } void SyncPoint::EnableProcessing() { std::unique_lock<std::mutex> lock(mutex_); enabled_ = true; } void SyncPoint::DisableProcessing() { std::unique_lock<std::mutex> lock(mutex_); enabled_ = false; } void SyncPoint::ClearTrace() { std::unique_lock<std::mutex> lock(mutex_); cleared_points_.clear(); } void SyncPoint::Process(const std::string& point) { std::unique_lock<std::mutex> lock(mutex_); if (!enabled_) return; while (!PredecessorsAllCleared(point)) { cv_.wait(lock); } cleared_points_.insert(point); cv_.notify_all(); } } // namespace rocksdb #endif // NDEBUG <commit_msg>Fix race in sync point.<commit_after>// Copyright (c) 2014, Facebook, Inc. All rights reserved. // This source code is licensed under the BSD-style license found in the // LICENSE file in the root directory of this source tree. An additional grant // of patent rights can be found in the PATENTS file in the same directory. #include "util/sync_point.h" #ifndef NDEBUG namespace rocksdb { SyncPoint* SyncPoint::GetInstance() { static SyncPoint sync_point; return &sync_point; } void SyncPoint::LoadDependency(const std::vector<Dependency>& dependencies) { std::unique_lock<std::mutex> lock(mutex_); successors_.clear(); predecessors_.clear(); cleared_points_.clear(); for (const auto& dependency : dependencies) { successors_[dependency.predecessor].push_back(dependency.successor); predecessors_[dependency.successor].push_back(dependency.predecessor); } cv_.notify_all(); } bool SyncPoint::PredecessorsAllCleared(const std::string& point) { for (const auto& pred : predecessors_[point]) { if (cleared_points_.count(pred) == 0) { return false; } } return true; } void SyncPoint::EnableProcessing() { std::unique_lock<std::mutex> lock(mutex_); enabled_ = true; } void SyncPoint::DisableProcessing() { std::unique_lock<std::mutex> lock(mutex_); enabled_ = false; } void SyncPoint::ClearTrace() { std::unique_lock<std::mutex> lock(mutex_); cleared_points_.clear(); } void SyncPoint::Process(const std::string& point) { std::unique_lock<std::mutex> lock(mutex_); if (!enabled_) return; while (!PredecessorsAllCleared(point)) { cv_.wait(lock); } cleared_points_.insert(point); cv_.notify_all(); } } // namespace rocksdb #endif // NDEBUG <|endoftext|>
<commit_before>//===- unittest/ProfileData/CoverageMappingTest.cpp -------------------------=// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/ProfileData/CoverageMapping.h" #include "llvm/ProfileData/CoverageMappingReader.h" #include "llvm/ProfileData/CoverageMappingWriter.h" #include "llvm/ProfileData/InstrProfReader.h" #include "llvm/ProfileData/InstrProfWriter.h" #include "llvm/Support/raw_ostream.h" #include "gtest/gtest.h" #include <sstream> using namespace llvm; using namespace coverage; static ::testing::AssertionResult NoError(std::error_code EC) { if (!EC) return ::testing::AssertionSuccess(); return ::testing::AssertionFailure() << "error " << EC.value() << ": " << EC.message(); } namespace llvm { namespace coverage { void PrintTo(const Counter &C, ::std::ostream *os) { if (C.isZero()) *os << "Zero"; else if (C.isExpression()) *os << "Expression " << C.getExpressionID(); else *os << "Counter " << C.getCounterID(); } void PrintTo(const CoverageSegment &S, ::std::ostream *os) { *os << "CoverageSegment(" << S.Line << ", " << S.Col << ", "; if (S.HasCount) *os << S.Count << ", "; *os << (S.IsRegionEntry ? "true" : "false") << ")"; } } } namespace { struct OneFunctionCoverageReader : CoverageMappingReader { StringRef Name; uint64_t Hash; std::vector<StringRef> Filenames; ArrayRef<CounterMappingRegion> Regions; bool Done; OneFunctionCoverageReader(StringRef Name, uint64_t Hash, ArrayRef<StringRef> Filenames, ArrayRef<CounterMappingRegion> Regions) : Name(Name), Hash(Hash), Filenames(Filenames), Regions(Regions), Done(false) {} std::error_code readNextRecord(CoverageMappingRecord &Record) override { if (Done) return instrprof_error::eof; Done = true; Record.FunctionName = Name; Record.FunctionHash = Hash; Record.Filenames = Filenames; Record.Expressions = {}; Record.MappingRegions = Regions; return instrprof_error::success; } }; struct CoverageMappingTest : ::testing::Test { StringMap<unsigned> Files; unsigned NextFile; std::vector<CounterMappingRegion> InputCMRs; std::vector<StringRef> OutputFiles; std::vector<CounterExpression> OutputExpressions; std::vector<CounterMappingRegion> OutputCMRs; InstrProfWriter ProfileWriter; std::unique_ptr<IndexedInstrProfReader> ProfileReader; std::unique_ptr<CoverageMapping> LoadedCoverage; void SetUp() override { NextFile = 0; ProfileWriter.setOutputSparse(false); } unsigned getFile(StringRef Name) { auto R = Files.find(Name); if (R != Files.end()) return R->second; Files[Name] = NextFile; return NextFile++; } void addCMR(Counter C, StringRef File, unsigned LS, unsigned CS, unsigned LE, unsigned CE) { InputCMRs.push_back( CounterMappingRegion::makeRegion(C, getFile(File), LS, CS, LE, CE)); } void addExpansionCMR(StringRef File, StringRef ExpandedFile, unsigned LS, unsigned CS, unsigned LE, unsigned CE) { InputCMRs.push_back(CounterMappingRegion::makeExpansion( getFile(File), getFile(ExpandedFile), LS, CS, LE, CE)); } std::string writeCoverageRegions() { SmallVector<unsigned, 8> FileIDs; for (const auto &E : Files) FileIDs.push_back(E.getValue()); std::string Coverage; llvm::raw_string_ostream OS(Coverage); CoverageMappingWriter(FileIDs, None, InputCMRs).write(OS); return OS.str(); } void readCoverageRegions(std::string Coverage) { SmallVector<StringRef, 8> Filenames; for (const auto &E : Files) Filenames.push_back(E.getKey()); RawCoverageMappingReader Reader(Coverage, Filenames, OutputFiles, OutputExpressions, OutputCMRs); ASSERT_TRUE(NoError(Reader.read())); } void readProfCounts() { auto Profile = ProfileWriter.writeBuffer(); auto ReaderOrErr = IndexedInstrProfReader::create(std::move(Profile)); ASSERT_TRUE(NoError(ReaderOrErr.getError())); ProfileReader = std::move(ReaderOrErr.get()); } void loadCoverageMapping(StringRef FuncName, uint64_t Hash, bool EmitFilenames = true) { std::string Regions = writeCoverageRegions(); readCoverageRegions(Regions); SmallVector<StringRef, 8> Filenames; if (EmitFilenames) for (const auto &E : Files) Filenames.push_back(E.getKey()); OneFunctionCoverageReader CovReader(FuncName, Hash, Filenames, OutputCMRs); auto CoverageOrErr = CoverageMapping::load(CovReader, *ProfileReader); ASSERT_TRUE(NoError(CoverageOrErr.getError())); LoadedCoverage = std::move(CoverageOrErr.get()); } }; struct MaybeSparseCoverageMappingTest : public CoverageMappingTest, public ::testing::WithParamInterface<bool> { void SetUp() { CoverageMappingTest::SetUp(); ProfileWriter.setOutputSparse(GetParam()); } }; TEST_P(MaybeSparseCoverageMappingTest, basic_write_read) { addCMR(Counter::getCounter(0), "foo", 1, 1, 1, 1); addCMR(Counter::getCounter(1), "foo", 2, 1, 2, 2); addCMR(Counter::getZero(), "foo", 3, 1, 3, 4); addCMR(Counter::getCounter(2), "foo", 4, 1, 4, 8); addCMR(Counter::getCounter(3), "bar", 1, 2, 3, 4); std::string Coverage = writeCoverageRegions(); readCoverageRegions(Coverage); size_t N = makeArrayRef(InputCMRs).size(); ASSERT_EQ(N, OutputCMRs.size()); for (size_t I = 0; I < N; ++I) { ASSERT_EQ(InputCMRs[I].Count, OutputCMRs[I].Count); ASSERT_EQ(InputCMRs[I].FileID, OutputCMRs[I].FileID); ASSERT_EQ(InputCMRs[I].startLoc(), OutputCMRs[I].startLoc()); ASSERT_EQ(InputCMRs[I].endLoc(), OutputCMRs[I].endLoc()); ASSERT_EQ(InputCMRs[I].Kind, OutputCMRs[I].Kind); } } TEST_P(MaybeSparseCoverageMappingTest, expansion_gets_first_counter) { addCMR(Counter::getCounter(1), "foo", 10, 1, 10, 2); // This starts earlier in "foo", so the expansion should get its counter. addCMR(Counter::getCounter(2), "foo", 1, 1, 20, 1); addExpansionCMR("bar", "foo", 3, 3, 3, 3); std::string Coverage = writeCoverageRegions(); readCoverageRegions(Coverage); ASSERT_EQ(CounterMappingRegion::ExpansionRegion, OutputCMRs[2].Kind); ASSERT_EQ(Counter::getCounter(2), OutputCMRs[2].Count); ASSERT_EQ(3U, OutputCMRs[2].LineStart); } TEST_P(MaybeSparseCoverageMappingTest, basic_coverage_iteration) { InstrProfRecord Record("func", 0x1234, {30, 20, 10, 0}); ProfileWriter.addRecord(std::move(Record)); readProfCounts(); addCMR(Counter::getCounter(0), "file1", 1, 1, 9, 9); addCMR(Counter::getCounter(1), "file1", 1, 1, 4, 7); addCMR(Counter::getCounter(2), "file1", 5, 8, 9, 1); addCMR(Counter::getCounter(3), "file1", 10, 10, 11, 11); loadCoverageMapping("func", 0x1234); CoverageData Data = LoadedCoverage->getCoverageForFile("file1"); std::vector<CoverageSegment> Segments(Data.begin(), Data.end()); ASSERT_EQ(7U, Segments.size()); ASSERT_EQ(CoverageSegment(1, 1, 20, true), Segments[0]); ASSERT_EQ(CoverageSegment(4, 7, 30, false), Segments[1]); ASSERT_EQ(CoverageSegment(5, 8, 10, true), Segments[2]); ASSERT_EQ(CoverageSegment(9, 1, 30, false), Segments[3]); ASSERT_EQ(CoverageSegment(9, 9, false), Segments[4]); ASSERT_EQ(CoverageSegment(10, 10, 0, true), Segments[5]); ASSERT_EQ(CoverageSegment(11, 11, false), Segments[6]); } TEST_P(MaybeSparseCoverageMappingTest, uncovered_function) { readProfCounts(); addCMR(Counter::getZero(), "file1", 1, 2, 3, 4); loadCoverageMapping("func", 0x1234); CoverageData Data = LoadedCoverage->getCoverageForFile("file1"); std::vector<CoverageSegment> Segments(Data.begin(), Data.end()); ASSERT_EQ(2U, Segments.size()); ASSERT_EQ(CoverageSegment(1, 2, 0, true), Segments[0]); ASSERT_EQ(CoverageSegment(3, 4, false), Segments[1]); } TEST_P(MaybeSparseCoverageMappingTest, uncovered_function_with_mapping) { readProfCounts(); addCMR(Counter::getCounter(0), "file1", 1, 1, 9, 9); addCMR(Counter::getCounter(1), "file1", 1, 1, 4, 7); loadCoverageMapping("func", 0x1234); CoverageData Data = LoadedCoverage->getCoverageForFile("file1"); std::vector<CoverageSegment> Segments(Data.begin(), Data.end()); ASSERT_EQ(3U, Segments.size()); ASSERT_EQ(CoverageSegment(1, 1, 0, true), Segments[0]); ASSERT_EQ(CoverageSegment(4, 7, 0, false), Segments[1]); ASSERT_EQ(CoverageSegment(9, 9, false), Segments[2]); } TEST_P(MaybeSparseCoverageMappingTest, combine_regions) { InstrProfRecord Record("func", 0x1234, {10, 20, 30}); ProfileWriter.addRecord(std::move(Record)); readProfCounts(); addCMR(Counter::getCounter(0), "file1", 1, 1, 9, 9); addCMR(Counter::getCounter(1), "file1", 3, 3, 4, 4); addCMR(Counter::getCounter(2), "file1", 3, 3, 4, 4); loadCoverageMapping("func", 0x1234); CoverageData Data = LoadedCoverage->getCoverageForFile("file1"); std::vector<CoverageSegment> Segments(Data.begin(), Data.end()); ASSERT_EQ(4U, Segments.size()); ASSERT_EQ(CoverageSegment(1, 1, 10, true), Segments[0]); ASSERT_EQ(CoverageSegment(3, 3, 50, true), Segments[1]); ASSERT_EQ(CoverageSegment(4, 4, 10, false), Segments[2]); ASSERT_EQ(CoverageSegment(9, 9, false), Segments[3]); } TEST_P(MaybeSparseCoverageMappingTest, dont_combine_expansions) { InstrProfRecord Record1("func", 0x1234, {10, 20}); InstrProfRecord Record2("func", 0x1234, {0, 0}); ProfileWriter.addRecord(std::move(Record1)); ProfileWriter.addRecord(std::move(Record2)); readProfCounts(); addCMR(Counter::getCounter(0), "file1", 1, 1, 9, 9); addCMR(Counter::getCounter(1), "file1", 3, 3, 4, 4); addCMR(Counter::getCounter(1), "include1", 6, 6, 7, 7); addExpansionCMR("file1", "include1", 3, 3, 4, 4); loadCoverageMapping("func", 0x1234); CoverageData Data = LoadedCoverage->getCoverageForFile("file1"); std::vector<CoverageSegment> Segments(Data.begin(), Data.end()); ASSERT_EQ(4U, Segments.size()); ASSERT_EQ(CoverageSegment(1, 1, 10, true), Segments[0]); ASSERT_EQ(CoverageSegment(3, 3, 20, true), Segments[1]); ASSERT_EQ(CoverageSegment(4, 4, 10, false), Segments[2]); ASSERT_EQ(CoverageSegment(9, 9, false), Segments[3]); } TEST_P(MaybeSparseCoverageMappingTest, strip_filename_prefix) { InstrProfRecord Record("file1:func", 0x1234, {0}); ProfileWriter.addRecord(std::move(Record)); readProfCounts(); addCMR(Counter::getCounter(0), "file1", 1, 1, 9, 9); loadCoverageMapping("file1:func", 0x1234); std::vector<std::string> Names; for (const auto &Func : LoadedCoverage->getCoveredFunctions()) Names.push_back(Func.Name); ASSERT_EQ(1U, Names.size()); ASSERT_EQ("func", Names[0]); } TEST_P(MaybeSparseCoverageMappingTest, strip_unknown_filename_prefix) { InstrProfRecord Record("<unknown>:func", 0x1234, {0}); ProfileWriter.addRecord(std::move(Record)); readProfCounts(); addCMR(Counter::getCounter(0), "", 1, 1, 9, 9); loadCoverageMapping("<unknown>:func", 0x1234, /*EmitFilenames=*/false); std::vector<std::string> Names; for (const auto &Func : LoadedCoverage->getCoveredFunctions()) Names.push_back(Func.Name); ASSERT_EQ(1U, Names.size()); ASSERT_EQ("func", Names[0]); } INSTANTIATE_TEST_CASE_P(MaybeSparse, MaybeSparseCoverageMappingTest, ::testing::Bool()); } // end anonymous namespace <commit_msg>[Coverage] Update testing methods to support more than two files<commit_after>//===- unittest/ProfileData/CoverageMappingTest.cpp -------------------------=// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/ProfileData/CoverageMapping.h" #include "llvm/ProfileData/CoverageMappingReader.h" #include "llvm/ProfileData/CoverageMappingWriter.h" #include "llvm/ProfileData/InstrProfReader.h" #include "llvm/ProfileData/InstrProfWriter.h" #include "llvm/Support/raw_ostream.h" #include "gtest/gtest.h" #include <sstream> using namespace llvm; using namespace coverage; static ::testing::AssertionResult NoError(std::error_code EC) { if (!EC) return ::testing::AssertionSuccess(); return ::testing::AssertionFailure() << "error " << EC.value() << ": " << EC.message(); } namespace llvm { namespace coverage { void PrintTo(const Counter &C, ::std::ostream *os) { if (C.isZero()) *os << "Zero"; else if (C.isExpression()) *os << "Expression " << C.getExpressionID(); else *os << "Counter " << C.getCounterID(); } void PrintTo(const CoverageSegment &S, ::std::ostream *os) { *os << "CoverageSegment(" << S.Line << ", " << S.Col << ", "; if (S.HasCount) *os << S.Count << ", "; *os << (S.IsRegionEntry ? "true" : "false") << ")"; } } } namespace { struct OneFunctionCoverageReader : CoverageMappingReader { StringRef Name; uint64_t Hash; std::vector<StringRef> Filenames; ArrayRef<CounterMappingRegion> Regions; bool Done; OneFunctionCoverageReader(StringRef Name, uint64_t Hash, ArrayRef<StringRef> Filenames, ArrayRef<CounterMappingRegion> Regions) : Name(Name), Hash(Hash), Filenames(Filenames), Regions(Regions), Done(false) {} std::error_code readNextRecord(CoverageMappingRecord &Record) override { if (Done) return instrprof_error::eof; Done = true; Record.FunctionName = Name; Record.FunctionHash = Hash; Record.Filenames = Filenames; Record.Expressions = {}; Record.MappingRegions = Regions; return instrprof_error::success; } }; struct CoverageMappingTest : ::testing::Test { StringMap<unsigned> Files; std::vector<CounterMappingRegion> InputCMRs; std::vector<StringRef> OutputFiles; std::vector<CounterExpression> OutputExpressions; std::vector<CounterMappingRegion> OutputCMRs; InstrProfWriter ProfileWriter; std::unique_ptr<IndexedInstrProfReader> ProfileReader; std::unique_ptr<CoverageMapping> LoadedCoverage; void SetUp() override { ProfileWriter.setOutputSparse(false); } unsigned getFile(StringRef Name) { auto R = Files.find(Name); if (R != Files.end()) return R->second; unsigned Index = Files.size(); Files.emplace_second(Name, Index); return Index; } void addCMR(Counter C, StringRef File, unsigned LS, unsigned CS, unsigned LE, unsigned CE) { InputCMRs.push_back( CounterMappingRegion::makeRegion(C, getFile(File), LS, CS, LE, CE)); } void addExpansionCMR(StringRef File, StringRef ExpandedFile, unsigned LS, unsigned CS, unsigned LE, unsigned CE) { InputCMRs.push_back(CounterMappingRegion::makeExpansion( getFile(File), getFile(ExpandedFile), LS, CS, LE, CE)); } std::string writeCoverageRegions() { SmallVector<unsigned, 8> FileIDs(Files.size()); for (unsigned I = 0; I < FileIDs.size(); ++I) FileIDs[I] = I; std::string Coverage; llvm::raw_string_ostream OS(Coverage); CoverageMappingWriter(FileIDs, None, InputCMRs).write(OS); return OS.str(); } void readCoverageRegions(std::string Coverage) { SmallVector<StringRef, 8> Filenames(Files.size()); for (const auto &E : Files) Filenames[E.getValue()] = E.getKey(); RawCoverageMappingReader Reader(Coverage, Filenames, OutputFiles, OutputExpressions, OutputCMRs); ASSERT_TRUE(NoError(Reader.read())); } void readProfCounts() { auto Profile = ProfileWriter.writeBuffer(); auto ReaderOrErr = IndexedInstrProfReader::create(std::move(Profile)); ASSERT_TRUE(NoError(ReaderOrErr.getError())); ProfileReader = std::move(ReaderOrErr.get()); } void loadCoverageMapping(StringRef FuncName, uint64_t Hash, bool EmitFilenames = true) { std::string Regions = writeCoverageRegions(); readCoverageRegions(Regions); SmallVector<StringRef, 8> Filenames; if (EmitFilenames) { Filenames.resize(Files.size()); for (const auto &E : Files) Filenames[E.getValue()] = E.getKey(); } OneFunctionCoverageReader CovReader(FuncName, Hash, Filenames, OutputCMRs); auto CoverageOrErr = CoverageMapping::load(CovReader, *ProfileReader); ASSERT_TRUE(NoError(CoverageOrErr.getError())); LoadedCoverage = std::move(CoverageOrErr.get()); } }; struct MaybeSparseCoverageMappingTest : public CoverageMappingTest, public ::testing::WithParamInterface<bool> { void SetUp() { CoverageMappingTest::SetUp(); ProfileWriter.setOutputSparse(GetParam()); } }; TEST_P(MaybeSparseCoverageMappingTest, basic_write_read) { addCMR(Counter::getCounter(0), "foo", 1, 1, 1, 1); addCMR(Counter::getCounter(1), "foo", 2, 1, 2, 2); addCMR(Counter::getZero(), "foo", 3, 1, 3, 4); addCMR(Counter::getCounter(2), "foo", 4, 1, 4, 8); addCMR(Counter::getCounter(3), "bar", 1, 2, 3, 4); std::string Coverage = writeCoverageRegions(); readCoverageRegions(Coverage); size_t N = makeArrayRef(InputCMRs).size(); ASSERT_EQ(N, OutputCMRs.size()); for (size_t I = 0; I < N; ++I) { ASSERT_EQ(InputCMRs[I].Count, OutputCMRs[I].Count); ASSERT_EQ(InputCMRs[I].FileID, OutputCMRs[I].FileID); ASSERT_EQ(InputCMRs[I].startLoc(), OutputCMRs[I].startLoc()); ASSERT_EQ(InputCMRs[I].endLoc(), OutputCMRs[I].endLoc()); ASSERT_EQ(InputCMRs[I].Kind, OutputCMRs[I].Kind); } } TEST_P(MaybeSparseCoverageMappingTest, correct_deserialize_for_more_than_two_files) { const char *FileNames[] = {"bar", "baz", "foo"}; static const unsigned N = array_lengthof(FileNames); for (unsigned I = 0; I < N; ++I) // Use LineStart to hold the index of the file name // in order to preserve that information during possible sorting of CMRs. addCMR(Counter::getCounter(0), FileNames[I], I, 1, I, 1); std::string Coverage = writeCoverageRegions(); readCoverageRegions(Coverage); ASSERT_EQ(N, OutputCMRs.size()); ASSERT_EQ(N, OutputFiles.size()); for (unsigned I = 0; I < N; ++I) { ASSERT_GT(N, OutputCMRs[I].FileID); ASSERT_GT(N, OutputCMRs[I].LineStart); EXPECT_EQ(FileNames[OutputCMRs[I].LineStart], OutputFiles[OutputCMRs[I].FileID]); } } TEST_P(MaybeSparseCoverageMappingTest, load_coverage_for_more_than_two_files) { InstrProfRecord Record("func", 0x1234, {0}); ProfileWriter.addRecord(std::move(Record)); readProfCounts(); const char *FileNames[] = {"bar", "baz", "foo"}; static const unsigned N = array_lengthof(FileNames); for (unsigned I = 0; I < N; ++I) // Use LineStart to hold the index of the file name // in order to preserve that information during possible sorting of CMRs. addCMR(Counter::getCounter(0), FileNames[I], I, 1, I, 1); loadCoverageMapping("func", 0x1234); for (unsigned I = 0; I < N; ++I) { CoverageData Data = LoadedCoverage->getCoverageForFile(FileNames[I]); ASSERT_TRUE(!Data.empty()); EXPECT_EQ(I, Data.begin()->Line); } } TEST_P(MaybeSparseCoverageMappingTest, expansion_gets_first_counter) { addCMR(Counter::getCounter(1), "foo", 10, 1, 10, 2); // This starts earlier in "foo", so the expansion should get its counter. addCMR(Counter::getCounter(2), "foo", 1, 1, 20, 1); addExpansionCMR("bar", "foo", 3, 3, 3, 3); std::string Coverage = writeCoverageRegions(); readCoverageRegions(Coverage); ASSERT_EQ(CounterMappingRegion::ExpansionRegion, OutputCMRs[2].Kind); ASSERT_EQ(Counter::getCounter(2), OutputCMRs[2].Count); ASSERT_EQ(3U, OutputCMRs[2].LineStart); } TEST_P(MaybeSparseCoverageMappingTest, basic_coverage_iteration) { InstrProfRecord Record("func", 0x1234, {30, 20, 10, 0}); ProfileWriter.addRecord(std::move(Record)); readProfCounts(); addCMR(Counter::getCounter(0), "file1", 1, 1, 9, 9); addCMR(Counter::getCounter(1), "file1", 1, 1, 4, 7); addCMR(Counter::getCounter(2), "file1", 5, 8, 9, 1); addCMR(Counter::getCounter(3), "file1", 10, 10, 11, 11); loadCoverageMapping("func", 0x1234); CoverageData Data = LoadedCoverage->getCoverageForFile("file1"); std::vector<CoverageSegment> Segments(Data.begin(), Data.end()); ASSERT_EQ(7U, Segments.size()); ASSERT_EQ(CoverageSegment(1, 1, 20, true), Segments[0]); ASSERT_EQ(CoverageSegment(4, 7, 30, false), Segments[1]); ASSERT_EQ(CoverageSegment(5, 8, 10, true), Segments[2]); ASSERT_EQ(CoverageSegment(9, 1, 30, false), Segments[3]); ASSERT_EQ(CoverageSegment(9, 9, false), Segments[4]); ASSERT_EQ(CoverageSegment(10, 10, 0, true), Segments[5]); ASSERT_EQ(CoverageSegment(11, 11, false), Segments[6]); } TEST_P(MaybeSparseCoverageMappingTest, uncovered_function) { readProfCounts(); addCMR(Counter::getZero(), "file1", 1, 2, 3, 4); loadCoverageMapping("func", 0x1234); CoverageData Data = LoadedCoverage->getCoverageForFile("file1"); std::vector<CoverageSegment> Segments(Data.begin(), Data.end()); ASSERT_EQ(2U, Segments.size()); ASSERT_EQ(CoverageSegment(1, 2, 0, true), Segments[0]); ASSERT_EQ(CoverageSegment(3, 4, false), Segments[1]); } TEST_P(MaybeSparseCoverageMappingTest, uncovered_function_with_mapping) { readProfCounts(); addCMR(Counter::getCounter(0), "file1", 1, 1, 9, 9); addCMR(Counter::getCounter(1), "file1", 1, 1, 4, 7); loadCoverageMapping("func", 0x1234); CoverageData Data = LoadedCoverage->getCoverageForFile("file1"); std::vector<CoverageSegment> Segments(Data.begin(), Data.end()); ASSERT_EQ(3U, Segments.size()); ASSERT_EQ(CoverageSegment(1, 1, 0, true), Segments[0]); ASSERT_EQ(CoverageSegment(4, 7, 0, false), Segments[1]); ASSERT_EQ(CoverageSegment(9, 9, false), Segments[2]); } TEST_P(MaybeSparseCoverageMappingTest, combine_regions) { InstrProfRecord Record("func", 0x1234, {10, 20, 30}); ProfileWriter.addRecord(std::move(Record)); readProfCounts(); addCMR(Counter::getCounter(0), "file1", 1, 1, 9, 9); addCMR(Counter::getCounter(1), "file1", 3, 3, 4, 4); addCMR(Counter::getCounter(2), "file1", 3, 3, 4, 4); loadCoverageMapping("func", 0x1234); CoverageData Data = LoadedCoverage->getCoverageForFile("file1"); std::vector<CoverageSegment> Segments(Data.begin(), Data.end()); ASSERT_EQ(4U, Segments.size()); ASSERT_EQ(CoverageSegment(1, 1, 10, true), Segments[0]); ASSERT_EQ(CoverageSegment(3, 3, 50, true), Segments[1]); ASSERT_EQ(CoverageSegment(4, 4, 10, false), Segments[2]); ASSERT_EQ(CoverageSegment(9, 9, false), Segments[3]); } TEST_P(MaybeSparseCoverageMappingTest, dont_combine_expansions) { InstrProfRecord Record1("func", 0x1234, {10, 20}); InstrProfRecord Record2("func", 0x1234, {0, 0}); ProfileWriter.addRecord(std::move(Record1)); ProfileWriter.addRecord(std::move(Record2)); readProfCounts(); addCMR(Counter::getCounter(0), "file1", 1, 1, 9, 9); addCMR(Counter::getCounter(1), "file1", 3, 3, 4, 4); addCMR(Counter::getCounter(1), "include1", 6, 6, 7, 7); addExpansionCMR("file1", "include1", 3, 3, 4, 4); loadCoverageMapping("func", 0x1234); CoverageData Data = LoadedCoverage->getCoverageForFile("file1"); std::vector<CoverageSegment> Segments(Data.begin(), Data.end()); ASSERT_EQ(4U, Segments.size()); ASSERT_EQ(CoverageSegment(1, 1, 10, true), Segments[0]); ASSERT_EQ(CoverageSegment(3, 3, 20, true), Segments[1]); ASSERT_EQ(CoverageSegment(4, 4, 10, false), Segments[2]); ASSERT_EQ(CoverageSegment(9, 9, false), Segments[3]); } TEST_P(MaybeSparseCoverageMappingTest, strip_filename_prefix) { InstrProfRecord Record("file1:func", 0x1234, {0}); ProfileWriter.addRecord(std::move(Record)); readProfCounts(); addCMR(Counter::getCounter(0), "file1", 1, 1, 9, 9); loadCoverageMapping("file1:func", 0x1234); std::vector<std::string> Names; for (const auto &Func : LoadedCoverage->getCoveredFunctions()) Names.push_back(Func.Name); ASSERT_EQ(1U, Names.size()); ASSERT_EQ("func", Names[0]); } TEST_P(MaybeSparseCoverageMappingTest, strip_unknown_filename_prefix) { InstrProfRecord Record("<unknown>:func", 0x1234, {0}); ProfileWriter.addRecord(std::move(Record)); readProfCounts(); addCMR(Counter::getCounter(0), "", 1, 1, 9, 9); loadCoverageMapping("<unknown>:func", 0x1234, /*EmitFilenames=*/false); std::vector<std::string> Names; for (const auto &Func : LoadedCoverage->getCoveredFunctions()) Names.push_back(Func.Name); ASSERT_EQ(1U, Names.size()); ASSERT_EQ("func", Names[0]); } INSTANTIATE_TEST_CASE_P(MaybeSparse, MaybeSparseCoverageMappingTest, ::testing::Bool()); } // end anonymous namespace <|endoftext|>
<commit_before>/* * Copyright (C) 2005-2019 Centre National d'Etudes Spatiales (CNES) * * This file is part of Orfeo Toolbox * * https://www.orfeo-toolbox.org/ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Software Guide : BeginCommandLineArgs // OUTPUTS: {mapProjectionExample-output.txt} // Software Guide : EndCommandLineArgs // Software Guide : BeginLatex // // Map projection is an important issue when working with satellite // images. In the orthorectification process, converting between // geographic and cartographic coordinates is a key step. In this // process, everything is integrated and you don't need to know the // details. // // However, sometimes, you need to go hands-on and find out the // nitty-gritty details. This example shows you how to play with map // projections in OTB and how to convert coordinates. In most cases, // the underlying work is done by OSSIM. // // First, we start by including the otbMapProjections header. In this // file, over 30 projections are defined and ready to use. It is easy // to add new one. // // The otbGenericMapProjection enables you to instantiate a map // projection from a WKT (Well Known Text) string, which is popular // with OGR for example. // // Software Guide : EndLatex #include <fstream> #include <iomanip> // Software Guide : BeginCodeSnippet #include "otbSpatialReference.h" #include "otbGenericMapProjection.h" // Software Guide : EndCodeSnippet int main(int argc, char* argv[]) { if (argc < 2) { std::cout << argv[0] << " <outputfile> " << std::endl; return EXIT_FAILURE; } // Software Guide : BeginLatex // // We retrieve the command line parameters and put them in the // correct variables. The transforms are going to work with an // \doxygen{itk}{Point}. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet const char * outFileName = argv[1]; itk::Point<double, 2> point; point[0] = 1.4835345; point[1] = 43.55968261; // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // The output of this program will be saved in a text file. We also want // to make sure that the precision of the digits will be enough. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet std::ofstream file; file.open(outFileName); file << std::setprecision(15); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // We can now instantiate our first map projection. Here, it is a // UTM projection. We also need to provide the information about // the zone and the hemisphere for the projection. These are // specific to the UTM projection. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef otb::GenericMapProjection<otb::TransformDirection::FORWARD> MapProjectionType; otb::SpatialReference utmSRS = otb::SpatialReference::FromUTM(31,otb::SpatialReference::hemisphere::north); MapProjectionType::Pointer utmProjection = MapProjectionType::New(); utmProjection->SetWkt(utmSRS.ToWkt()); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // The TransformPoint() method returns the coordinates of the point in the // new projection. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet file << "Forward UTM projection: " << std::endl; file << point << " -> "; file << utmProjection->TransformPoint(point); file << std::endl << std::endl; // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // We follow the same path for the Lambert93 projection: // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet // EPSG:2154 is the EPSG code for lambert 93 otb::SpatialReference lamb93SRS = otb::SpatialReference::FromDescription("EPSG:3154"); MapProjectionType::Pointer lambertProjection = MapProjectionType::New(); lambertProjection->SetWkt(lamb93SRS.ToWkt()); file << "Forward Lambert93 projection: " << std::endl; file << point << " -> "; file << lambertProjection->TransformPoint(point); file << std::endl << std::endl; // Software Guide : BeginLatex // // And of course, we don't forget to close the file: // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet file.close(); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // The final output of the program should be: // // \begin{verbatim} // Forward UTM projection: // [1.4835345, 43.55968261] -> [377522.448427013, 4824086.71129131] // // Forward Lambert93 projection: // [1.4835345, 43.55968261] -> [577437.889798954, 6274578.791561] // // \end{verbatim} // // Software Guide : EndLatex return EXIT_SUCCESS; } <commit_msg>BUG: update example typo<commit_after>/* * Copyright (C) 2005-2019 Centre National d'Etudes Spatiales (CNES) * * This file is part of Orfeo Toolbox * * https://www.orfeo-toolbox.org/ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Software Guide : BeginCommandLineArgs // OUTPUTS: {mapProjectionExample-output.txt} // Software Guide : EndCommandLineArgs // Software Guide : BeginLatex // // Map projection is an important issue when working with satellite // images. In the orthorectification process, converting between // geographic and cartographic coordinates is a key step. In this // process, everything is integrated and you don't need to know the // details. // // However, sometimes, you need to go hands-on and find out the // nitty-gritty details. This example shows you how to play with map // projections in OTB and how to convert coordinates. In most cases, // the underlying work is done by OSSIM. // // First, we start by including the otbMapProjections header. In this // file, over 30 projections are defined and ready to use. It is easy // to add new one. // // The otbGenericMapProjection enables you to instantiate a map // projection from a WKT (Well Known Text) string, which is popular // with OGR for example. // // Software Guide : EndLatex #include <fstream> #include <iomanip> // Software Guide : BeginCodeSnippet #include "otbSpatialReference.h" #include "otbGenericMapProjection.h" // Software Guide : EndCodeSnippet int main(int argc, char* argv[]) { if (argc < 2) { std::cout << argv[0] << " <outputfile> " << std::endl; return EXIT_FAILURE; } // Software Guide : BeginLatex // // We retrieve the command line parameters and put them in the // correct variables. The transforms are going to work with an // \doxygen{itk}{Point}. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet const char * outFileName = argv[1]; itk::Point<double, 2> point; point[0] = 1.4835345; point[1] = 43.55968261; // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // The output of this program will be saved in a text file. We also want // to make sure that the precision of the digits will be enough. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet std::ofstream file; file.open(outFileName); file << std::setprecision(15); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // We can now instantiate our first map projection. Here, it is a // UTM projection. We also need to provide the information about // the zone and the hemisphere for the projection. These are // specific to the UTM projection. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef otb::GenericMapProjection<otb::TransformDirection::FORWARD> MapProjectionType; otb::SpatialReference utmSRS = otb::SpatialReference::FromUTM(31,otb::SpatialReference::hemisphere::north); MapProjectionType::Pointer utmProjection = MapProjectionType::New(); utmProjection->SetWkt(utmSRS.ToWkt()); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // The TransformPoint() method returns the coordinates of the point in the // new projection. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet file << "Forward UTM projection: " << std::endl; file << point << " -> "; file << utmProjection->TransformPoint(point); file << std::endl << std::endl; // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // We follow the same path for the Lambert93 projection: // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet // EPSG:2154 is the EPSG code for lambert 93 otb::SpatialReference lamb93SRS = otb::SpatialReference::FromDescription("EPSG:2154"); MapProjectionType::Pointer lambertProjection = MapProjectionType::New(); lambertProjection->SetWkt(lamb93SRS.ToWkt()); file << "Forward Lambert93 projection: " << std::endl; file << point << " -> "; file << lambertProjection->TransformPoint(point); file << std::endl << std::endl; // Software Guide : BeginLatex // // And of course, we don't forget to close the file: // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet file.close(); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // The final output of the program should be: // // \begin{verbatim} // Forward UTM projection: // [1.4835345, 43.55968261] -> [377522.448427013, 4824086.71129131] // // Forward Lambert93 projection: // [1.4835345, 43.55968261] -> [577437.889798954, 6274578.791561] // // \end{verbatim} // // Software Guide : EndLatex return EXIT_SUCCESS; } <|endoftext|>
<commit_before>// call from command line like, for instance: // root -l 'acat19.cpp()' R__LOAD_LIBRARY(libRooFit) #include <chrono> #include <iostream> using namespace RooFit; //////////////////////////////////////////////////////////////////////////////////////////////////// // timing_flag is used to activate only selected timing statements [1-7] // num_cpu: -1 is special option -> compare overhead communication protocol (wrt 1 cpu) // parallel_interleave: 0 = blocks of equal size, 1 = interleave, 2 = simultaneous pdfs mode // { BulkPartition=0, Interleave=1, SimComponents=2, Hybrid=3 } //////////////////////////////////////////////////////////////////////////////////////////////////// void acat19() { TFile *_file0 = TFile::Open("/user/pbos/data_atlas/carsten/comb-5xs-80ifb-v8.root"); RooWorkspace* w = static_cast<RooWorkspace*>(gDirectory->Get("combWS")); RooAbsData *data = w->data("combData"); auto mc = dynamic_cast<RooStats::ModelConfig *>(w->genobj("ModelConfig")); auto global_observables = mc->GetGlobalObservables(); auto nuisance_parameters = mc->GetNuisanceParameters(); RooAbsPdf *pdf = w->pdf(mc->GetPdf()->GetName()); w->var("mu")->setVal(1.5); RooAbsReal *nll = pdf->createNLL(*data, RooFit::GlobalObservables(*global_observables), RooFit::Constrain(*nuisance_parameters), RooFit::Offset(kTRUE)); RooFit::MultiProcess::GradMinimizer m(*nll, 1); m.setPrintLevel(-1); m.setStrategy(0); m.setProfile(false); m.optimizeConst(2); m.setMinimizerType("Minuit2"); m.setVerbose(kTRUE); auto start = std::chrono::high_resolution_clock::now(); m.migrad(); auto end = std::chrono::high_resolution_clock::now(); auto elapsed_seconds = std::chrono::duration_cast<std::chrono::duration<double>>( end - start).count(); std::cout << "migrad: " << elapsed_seconds << "s" << std::endl; } <commit_msg>add benchmarking info back in in acat19 script (d'oh)<commit_after>// call from command line like, for instance: // root -l 'acat19.cpp()' R__LOAD_LIBRARY(libRooFit) #include <chrono> #include <iostream> using namespace RooFit; //////////////////////////////////////////////////////////////////////////////////////////////////// // timing_flag is used to activate only selected timing statements [1-7] // num_cpu: -1 is special option -> compare overhead communication protocol (wrt 1 cpu) // parallel_interleave: 0 = blocks of equal size, 1 = interleave, 2 = simultaneous pdfs mode // { BulkPartition=0, Interleave=1, SimComponents=2, Hybrid=3 } //////////////////////////////////////////////////////////////////////////////////////////////////// void acat19() { RooMsgService::instance().deleteStream(0); RooMsgService::instance().deleteStream(0); RooMsgService::instance().addStream(RooFit::DEBUG, RooFit::Topic(RooFit::Benchmarking1)); RooMsgService::instance().addStream(RooFit::DEBUG, RooFit::Topic(RooFit::Benchmarking2)); std::size_t seed = 1; RooRandom::randomGenerator()->SetSeed(seed); TFile *_file0 = TFile::Open("/user/pbos/data_atlas/carsten/comb-5xs-80ifb-v8.root"); RooWorkspace* w = static_cast<RooWorkspace*>(gDirectory->Get("combWS")); RooAbsData *data = w->data("combData"); auto mc = dynamic_cast<RooStats::ModelConfig *>(w->genobj("ModelConfig")); auto global_observables = mc->GetGlobalObservables(); auto nuisance_parameters = mc->GetNuisanceParameters(); RooAbsPdf *pdf = w->pdf(mc->GetPdf()->GetName()); w->var("mu")->setVal(1.5); RooAbsReal *nll = pdf->createNLL(*data, RooFit::GlobalObservables(*global_observables), RooFit::Constrain(*nuisance_parameters), RooFit::Offset(kTRUE)); RooFit::MultiProcess::GradMinimizer m(*nll, 1); m.setPrintLevel(-1); m.setStrategy(0); m.setProfile(false); m.optimizeConst(2); m.setMinimizerType("Minuit2"); m.setVerbose(kTRUE); auto start = std::chrono::high_resolution_clock::now(); m.migrad(); auto end = std::chrono::high_resolution_clock::now(); auto elapsed_seconds = std::chrono::duration_cast<std::chrono::duration<double>>( end - start).count(); std::cout << "migrad: " << elapsed_seconds << "s" << std::endl; } <|endoftext|>
<commit_before>/* -*- coding: utf-8; mode: c++; tab-width: 3; indent-tabs-mode: nil -*- Copyright 2016-2017 Raffaello D. Di Napoli This file is part of Lofty. Lofty is free software: you can redistribute it and/or modify it under the terms of version 2.1 of the GNU Lesser General Public License as published by the Free Software Foundation. Lofty is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. ------------------------------------------------------------------------------------------------------------*/ #include <lofty.hxx> #include <lofty/testing/test_case.hxx> #include <lofty/text.hxx> ////////////////////////////////////////////////////////////////////////////////////////////////////////////// namespace lofty { namespace test { LOFTY_TESTING_TEST_CASE_FUNC( io_text_istream_scan_0_captures, "lofty::io::text::istream::scan() – no captures" ) { LOFTY_TRACE_FUNC(this); // Syntax errors. LOFTY_TESTING_ASSERT_THROWS(text::syntax_error, io::text::str_istream(str::empty).scan(LOFTY_SL("+"))); LOFTY_TESTING_ASSERT_THROWS(text::syntax_error, io::text::str_istream(str::empty).scan(LOFTY_SL("("))); // No captures. LOFTY_TESTING_ASSERT_TRUE(io::text::str_istream(str::empty).scan(str::empty)); //? LOFTY_TESTING_ASSERT_DOES_NOT_THROW(io::text::str_istream(LOFTY_SL("x")).scan(str::empty)); LOFTY_TESTING_ASSERT_TRUE(io::text::str_istream(LOFTY_SL("x")).scan(LOFTY_SL("x"))); //? LOFTY_TESTING_ASSERT_DOES_NOT_THROW(io::text::str_istream(LOFTY_SL("xx")).scan(LOFTY_SL("x"))); LOFTY_TESTING_ASSERT_TRUE(io::text::str_istream(LOFTY_SL("x")).scan(LOFTY_SL("x+"))); LOFTY_TESTING_ASSERT_TRUE(io::text::str_istream(LOFTY_SL("x")).scan(LOFTY_SL("^x$"))); //? LOFTY_TESTING_ASSERT_DOES_NOT_THROW(io::text::str_istream(LOFTY_SL("xx")).scan(LOFTY_SL("^x$"))); LOFTY_TESTING_ASSERT_TRUE(io::text::str_istream(LOFTY_SL("x")).scan(LOFTY_SL("^x+$"))); } }} //namespace lofty::test ////////////////////////////////////////////////////////////////////////////////////////////////////////////// namespace lofty { namespace test { LOFTY_TESTING_TEST_CASE_FUNC( io_text_istream_scan_1_capture, "lofty::io::text::istream::scan() – one capture" ) { LOFTY_TRACE_FUNC(this); str captured1; LOFTY_TESTING_ASSERT_TRUE(io::text::str_istream(LOFTY_SL("a")).scan(LOFTY_SL("^()$"), &captured1)); LOFTY_TESTING_ASSERT_EQUAL(captured1, LOFTY_SL("a")); LOFTY_TESTING_ASSERT_TRUE(io::text::str_istream(LOFTY_SL("xb")).scan(LOFTY_SL("^x()$"), &captured1)); LOFTY_TESTING_ASSERT_EQUAL(captured1, LOFTY_SL("b")); LOFTY_TESTING_ASSERT_TRUE(io::text::str_istream(LOFTY_SL("cx")).scan(LOFTY_SL("^()x$"), &captured1)); LOFTY_TESTING_ASSERT_EQUAL(captured1, LOFTY_SL("c")); LOFTY_TESTING_ASSERT_TRUE(io::text::str_istream(LOFTY_SL("xdx")).scan(LOFTY_SL("^x()x$"), &captured1)); LOFTY_TESTING_ASSERT_EQUAL(captured1, LOFTY_SL("d")); LOFTY_TESTING_ASSERT_TRUE(io::text::str_istream(LOFTY_SL("(e)")).scan(LOFTY_SL("^\\(()\\)$"), &captured1)); LOFTY_TESTING_ASSERT_EQUAL(captured1, LOFTY_SL("e")); int captured2; LOFTY_TESTING_ASSERT_TRUE(io::text::str_istream(LOFTY_SL("31")).scan(LOFTY_SL("^()$"), &captured2)); LOFTY_TESTING_ASSERT_EQUAL(captured2, 31); LOFTY_TESTING_ASSERT_TRUE(io::text::str_istream(LOFTY_SL("20")).scan(LOFTY_SL("^(x)$"), &captured2)); LOFTY_TESTING_ASSERT_EQUAL(captured2, 32); LOFTY_TESTING_ASSERT_TRUE(io::text::str_istream(LOFTY_SL("0x21")).scan(LOFTY_SL("^(#)$"), &captured2)); LOFTY_TESTING_ASSERT_EQUAL(captured2, 33); LOFTY_TESTING_ASSERT_TRUE(io::text::str_istream(LOFTY_SL("0x22")).scan(LOFTY_SL("^(#x)$"), &captured2)); LOFTY_TESTING_ASSERT_EQUAL(captured2, 34); } }} //namespace lofty::test ////////////////////////////////////////////////////////////////////////////////////////////////////////////// namespace lofty { namespace test { LOFTY_TESTING_TEST_CASE_FUNC( io_text_istream_scan_competing_str_with_format, "lofty::io::text::istream::scan() – competing string captures with format" ) { LOFTY_TRACE_FUNC(this); str captured1, captured2; LOFTY_TESTING_ASSERT_TRUE(io::text::str_istream(LOFTY_SL("ab")).scan(LOFTY_SL("^(.)(.)$"), &captured1, &captured2)); LOFTY_TESTING_ASSERT_EQUAL(captured1, LOFTY_SL("a")); LOFTY_TESTING_ASSERT_EQUAL(captured2, LOFTY_SL("b")); // Both formats are greedy, but the first one will consume characters first. LOFTY_TESTING_ASSERT_TRUE(io::text::str_istream(LOFTY_SL("abcd")).scan(LOFTY_SL("^(.+)(.+)$"), &captured1, &captured2)); LOFTY_TESTING_ASSERT_EQUAL(captured1, LOFTY_SL("abc")); LOFTY_TESTING_ASSERT_EQUAL(captured2, LOFTY_SL("d")); LOFTY_TESTING_ASSERT_TRUE(io::text::str_istream(LOFTY_SL("axb")).scan(LOFTY_SL("^()x()$"), &captured1, &captured2)); LOFTY_TESTING_ASSERT_EQUAL(captured1, LOFTY_SL("a")); LOFTY_TESTING_ASSERT_EQUAL(captured2, LOFTY_SL("b")); } }} //namespace lofty::test <commit_msg>Add tests for bracket expressions<commit_after>/* -*- coding: utf-8; mode: c++; tab-width: 3; indent-tabs-mode: nil -*- Copyright 2016-2017 Raffaello D. Di Napoli This file is part of Lofty. Lofty is free software: you can redistribute it and/or modify it under the terms of version 2.1 of the GNU Lesser General Public License as published by the Free Software Foundation. Lofty is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. ------------------------------------------------------------------------------------------------------------*/ #include <lofty.hxx> #include <lofty/testing/test_case.hxx> #include <lofty/text.hxx> ////////////////////////////////////////////////////////////////////////////////////////////////////////////// namespace lofty { namespace test { LOFTY_TESTING_TEST_CASE_FUNC( io_text_istream_scan_0_captures, "lofty::io::text::istream::scan() – no captures" ) { LOFTY_TRACE_FUNC(this); // Syntax errors. LOFTY_TESTING_ASSERT_THROWS(text::syntax_error, io::text::str_istream(str::empty).scan(LOFTY_SL("+"))); LOFTY_TESTING_ASSERT_THROWS(text::syntax_error, io::text::str_istream(str::empty).scan(LOFTY_SL("("))); // No captures. LOFTY_TESTING_ASSERT_TRUE(io::text::str_istream(str::empty).scan(str::empty)); //? LOFTY_TESTING_ASSERT_DOES_NOT_THROW(io::text::str_istream(LOFTY_SL("x")).scan(str::empty)); LOFTY_TESTING_ASSERT_TRUE(io::text::str_istream(LOFTY_SL("x")).scan(LOFTY_SL("x"))); //? LOFTY_TESTING_ASSERT_DOES_NOT_THROW(io::text::str_istream(LOFTY_SL("xx")).scan(LOFTY_SL("x"))); LOFTY_TESTING_ASSERT_TRUE(io::text::str_istream(LOFTY_SL("x")).scan(LOFTY_SL("x+"))); LOFTY_TESTING_ASSERT_TRUE(io::text::str_istream(LOFTY_SL("x")).scan(LOFTY_SL("^x$"))); //? LOFTY_TESTING_ASSERT_DOES_NOT_THROW(io::text::str_istream(LOFTY_SL("xx")).scan(LOFTY_SL("^x$"))); LOFTY_TESTING_ASSERT_TRUE(io::text::str_istream(LOFTY_SL("x")).scan(LOFTY_SL("^x+$"))); LOFTY_TESTING_ASSERT_TRUE(io::text::str_istream(LOFTY_SL("a")).scan(LOFTY_SL("^[a]$"))); LOFTY_TESTING_ASSERT_FALSE(io::text::str_istream(LOFTY_SL("a")).scan(LOFTY_SL("^[b]$"))); LOFTY_TESTING_ASSERT_TRUE(io::text::str_istream(LOFTY_SL("a")).scan(LOFTY_SL("^[^m]$"))); LOFTY_TESTING_ASSERT_FALSE(io::text::str_istream(LOFTY_SL("m")).scan(LOFTY_SL("^[^m]$"))); LOFTY_TESTING_ASSERT_TRUE(io::text::str_istream(LOFTY_SL("z")).scan(LOFTY_SL("^[^m]$"))); } }} //namespace lofty::test ////////////////////////////////////////////////////////////////////////////////////////////////////////////// namespace lofty { namespace test { LOFTY_TESTING_TEST_CASE_FUNC( io_text_istream_scan_1_capture, "lofty::io::text::istream::scan() – one capture" ) { LOFTY_TRACE_FUNC(this); str captured1; LOFTY_TESTING_ASSERT_TRUE(io::text::str_istream(LOFTY_SL("a")).scan(LOFTY_SL("^()$"), &captured1)); LOFTY_TESTING_ASSERT_EQUAL(captured1, LOFTY_SL("a")); LOFTY_TESTING_ASSERT_TRUE(io::text::str_istream(LOFTY_SL("xb")).scan(LOFTY_SL("^x()$"), &captured1)); LOFTY_TESTING_ASSERT_EQUAL(captured1, LOFTY_SL("b")); LOFTY_TESTING_ASSERT_TRUE(io::text::str_istream(LOFTY_SL("cx")).scan(LOFTY_SL("^()x$"), &captured1)); LOFTY_TESTING_ASSERT_EQUAL(captured1, LOFTY_SL("c")); LOFTY_TESTING_ASSERT_TRUE(io::text::str_istream(LOFTY_SL("xdx")).scan(LOFTY_SL("^x()x$"), &captured1)); LOFTY_TESTING_ASSERT_EQUAL(captured1, LOFTY_SL("d")); LOFTY_TESTING_ASSERT_TRUE(io::text::str_istream(LOFTY_SL("(e)")).scan(LOFTY_SL("^\\(()\\)$"), &captured1)); LOFTY_TESTING_ASSERT_EQUAL(captured1, LOFTY_SL("e")); LOFTY_TESTING_ASSERT_TRUE(io::text::str_istream(LOFTY_SL("f")).scan(LOFTY_SL("^(f+)$"), &captured1)); LOFTY_TESTING_ASSERT_EQUAL(captured1, LOFTY_SL("f")); LOFTY_TESTING_ASSERT_TRUE(io::text::str_istream(LOFTY_SL("g")).scan(LOFTY_SL("^([a-z]+)$"), &captured1)); LOFTY_TESTING_ASSERT_EQUAL(captured1, LOFTY_SL("g")); LOFTY_TESTING_ASSERT_TRUE(io::text::str_istream(LOFTY_SL("h")).scan(LOFTY_SL("^([^ ]+)$"), &captured1)); LOFTY_TESTING_ASSERT_EQUAL(captured1, LOFTY_SL("h")); int captured2; LOFTY_TESTING_ASSERT_TRUE(io::text::str_istream(LOFTY_SL("31")).scan(LOFTY_SL("^()$"), &captured2)); LOFTY_TESTING_ASSERT_EQUAL(captured2, 31); LOFTY_TESTING_ASSERT_TRUE(io::text::str_istream(LOFTY_SL("20")).scan(LOFTY_SL("^(x)$"), &captured2)); LOFTY_TESTING_ASSERT_EQUAL(captured2, 32); LOFTY_TESTING_ASSERT_TRUE(io::text::str_istream(LOFTY_SL("0x21")).scan(LOFTY_SL("^(#)$"), &captured2)); LOFTY_TESTING_ASSERT_EQUAL(captured2, 33); LOFTY_TESTING_ASSERT_TRUE(io::text::str_istream(LOFTY_SL("0x22")).scan(LOFTY_SL("^(#x)$"), &captured2)); LOFTY_TESTING_ASSERT_EQUAL(captured2, 34); } }} //namespace lofty::test ////////////////////////////////////////////////////////////////////////////////////////////////////////////// namespace lofty { namespace test { LOFTY_TESTING_TEST_CASE_FUNC( io_text_istream_scan_competing_str_with_format, "lofty::io::text::istream::scan() – competing string captures with format" ) { LOFTY_TRACE_FUNC(this); str captured1, captured2; LOFTY_TESTING_ASSERT_TRUE(io::text::str_istream(LOFTY_SL("ab")).scan(LOFTY_SL("^(.)(.)$"), &captured1, &captured2)); LOFTY_TESTING_ASSERT_EQUAL(captured1, LOFTY_SL("a")); LOFTY_TESTING_ASSERT_EQUAL(captured2, LOFTY_SL("b")); // Both formats are greedy, but the first one will consume characters first. LOFTY_TESTING_ASSERT_TRUE(io::text::str_istream(LOFTY_SL("abcd")).scan(LOFTY_SL("^(.+)(.+)$"), &captured1, &captured2)); LOFTY_TESTING_ASSERT_EQUAL(captured1, LOFTY_SL("abc")); LOFTY_TESTING_ASSERT_EQUAL(captured2, LOFTY_SL("d")); LOFTY_TESTING_ASSERT_TRUE(io::text::str_istream(LOFTY_SL("axb")).scan(LOFTY_SL("^()x()$"), &captured1, &captured2)); LOFTY_TESTING_ASSERT_EQUAL(captured1, LOFTY_SL("a")); LOFTY_TESTING_ASSERT_EQUAL(captured2, LOFTY_SL("b")); } }} //namespace lofty::test <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: ucbstreamhelper.cxx,v $ * * $Revision: 1.10 $ * * last change: $Author: mba $ $Date: 2001-07-16 09:28:18 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #include <unotools/ucblockbytes.hxx> #include <unotools/ucbstreamhelper.hxx> #include <comphelper/processfactory.hxx> #ifndef _COM_SUN_STAR_UCB_COMMANDABORTEDEXCEPTION_HPP_ #include <com/sun/star/ucb/CommandAbortedException.hpp> #endif #ifndef _COM_SUN_STAR_UCB_XCOMMANDENVIRONMENT_HDL_ #include <com/sun/star/ucb/XCommandEnvironment.hdl> #endif #ifndef _COM_SUN_STAR_UCB_INSERTCOMMANDARGUMENT_HPP_ #include <com/sun/star/ucb/InsertCommandArgument.hpp> #endif #ifndef _COM_SUN_STAR_IO_XACTIVEDATASTREAMER_HPP_ #include <com/sun/star/io/XActiveDataStreamer.hpp> #endif #include <ucbhelper/contentbroker.hxx> #include <ucbhelper/content.hxx> #include <tools/debug.hxx> using namespace ::com::sun::star::uno; using namespace ::com::sun::star::io; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::ucb; using namespace ::com::sun::star::task; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::beans; namespace utl { SvStream* UcbStreamHelper::CreateStream( const String& rFileName, StreamMode eOpenMode, UcbLockBytesHandler* pHandler, sal_Bool bForceSynchron ) { return CreateStream( rFileName, eOpenMode, Reference < XInteractionHandler >(), pHandler, bForceSynchron ); } SvStream* UcbStreamHelper::CreateStream( const String& rFileName, StreamMode eOpenMode, Reference < XInteractionHandler > xInteractionHandler, UcbLockBytesHandler* pHandler, sal_Bool bForceSynchron ) { SvStream* pStream = NULL; ::ucb::ContentBroker* pBroker = ::ucb::ContentBroker::get(); if ( pBroker ) { UcbLockBytesRef xLockBytes; if ( eOpenMode & STREAM_WRITE ) { sal_Bool bTruncate = ( eOpenMode & STREAM_TRUNC ); if ( bTruncate ) { try { // truncate is implemented with deleting the original file ::ucb::Content aCnt( rFileName, Reference < XCommandEnvironment >() ); aCnt.executeCommand( ::rtl::OUString::createFromAscii( "delete" ), makeAny( sal_Bool( sal_True ) ) ); } catch ( CommandAbortedException& ) { // couldn't truncate/delete } catch ( ContentCreationException& ) { } catch ( Exception& ) { } } try { // make sure that the desired file exists before trying to open ::ucb::Content aContent( rFileName, Reference < XCommandEnvironment >() ); InsertCommandArgument aInsertArg; aInsertArg.Data = Reference< XInputStream >(); aInsertArg.ReplaceExisting = sal_False; Any aCmdArg; aCmdArg <<= aInsertArg; aContent.executeCommand( ::rtl::OUString::createFromAscii( "insert" ), aCmdArg ); } // it is NOT an error when the stream already exists and no truncation was desired catch ( CommandAbortedException& ) { // currently never an error is detected ! } catch ( ContentCreationException& ) { } catch ( Exception& ) { } } try { // create LockBytes using UCB ::ucb::Content aContent( rFileName, Reference < XCommandEnvironment >() ); xLockBytes = UcbLockBytes::CreateLockBytes( aContent.get(), Sequence < PropertyValue >(), eOpenMode, xInteractionHandler, pHandler ); if ( xLockBytes.Is() ) { pStream = new SvStream( xLockBytes ); pStream->SetBufferSize( 4096 ); pStream->SetError( xLockBytes->GetError() ); } } catch ( CommandAbortedException& ) { } catch ( ContentCreationException& ) { } catch ( Exception& ) { } } else // if no UCB is present at least conventional file io is supported pStream = new SvFileStream( rFileName, eOpenMode ); return pStream; } SvStream* UcbStreamHelper::CreateStream( Reference < XInputStream > xStream ) { SvStream* pStream = NULL; UcbLockBytesRef xLockBytes = UcbLockBytes::CreateInputLockBytes( xStream ); if ( xLockBytes.Is() ) { pStream = new SvStream( xLockBytes ); pStream->SetBufferSize( 4096 ); pStream->SetError( xLockBytes->GetError() ); } return pStream; }; }; <commit_msg>#89377#: OpenMode ReadWrite now handled by UCP<commit_after>/************************************************************************* * * $RCSfile: ucbstreamhelper.cxx,v $ * * $Revision: 1.11 $ * * last change: $Author: mba $ $Date: 2001-07-16 11:57:22 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #include <unotools/ucblockbytes.hxx> #include <unotools/ucbstreamhelper.hxx> #include <comphelper/processfactory.hxx> #ifndef _COM_SUN_STAR_UCB_COMMANDABORTEDEXCEPTION_HPP_ #include <com/sun/star/ucb/CommandAbortedException.hpp> #endif #ifndef _COM_SUN_STAR_UCB_XCOMMANDENVIRONMENT_HDL_ #include <com/sun/star/ucb/XCommandEnvironment.hdl> #endif #ifndef _COM_SUN_STAR_UCB_INSERTCOMMANDARGUMENT_HPP_ #include <com/sun/star/ucb/InsertCommandArgument.hpp> #endif #ifndef _COM_SUN_STAR_IO_XACTIVEDATASTREAMER_HPP_ #include <com/sun/star/io/XActiveDataStreamer.hpp> #endif #include <ucbhelper/contentbroker.hxx> #include <ucbhelper/content.hxx> #include <tools/debug.hxx> using namespace ::com::sun::star::uno; using namespace ::com::sun::star::io; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::ucb; using namespace ::com::sun::star::task; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::beans; namespace utl { SvStream* UcbStreamHelper::CreateStream( const String& rFileName, StreamMode eOpenMode, UcbLockBytesHandler* pHandler, sal_Bool bForceSynchron ) { return CreateStream( rFileName, eOpenMode, Reference < XInteractionHandler >(), pHandler, bForceSynchron ); } SvStream* UcbStreamHelper::CreateStream( const String& rFileName, StreamMode eOpenMode, Reference < XInteractionHandler > xInteractionHandler, UcbLockBytesHandler* pHandler, sal_Bool bForceSynchron ) { SvStream* pStream = NULL; ::ucb::ContentBroker* pBroker = ::ucb::ContentBroker::get(); if ( pBroker ) { UcbLockBytesRef xLockBytes; if ( eOpenMode & STREAM_WRITE ) { sal_Bool bTruncate = ( eOpenMode & STREAM_TRUNC ); if ( bTruncate ) { try { // truncate is implemented with deleting the original file ::ucb::Content aCnt( rFileName, Reference < XCommandEnvironment >() ); aCnt.executeCommand( ::rtl::OUString::createFromAscii( "delete" ), makeAny( sal_Bool( sal_True ) ) ); } catch ( CommandAbortedException& ) { // couldn't truncate/delete } catch ( ContentCreationException& ) { } catch ( Exception& ) { } } /* try { // make sure that the desired file exists before trying to open ::ucb::Content aContent( rFileName, Reference < XCommandEnvironment >() ); InsertCommandArgument aInsertArg; aInsertArg.Data = Reference< XInputStream >(); aInsertArg.ReplaceExisting = sal_False; Any aCmdArg; aCmdArg <<= aInsertArg; aContent.executeCommand( ::rtl::OUString::createFromAscii( "insert" ), aCmdArg ); } // it is NOT an error when the stream already exists and no truncation was desired catch ( CommandAbortedException& ) { // currently never an error is detected ! } catch ( ContentCreationException& ) { } catch ( Exception& ) { } */ } try { // create LockBytes using UCB ::ucb::Content aContent( rFileName, Reference < XCommandEnvironment >() ); xLockBytes = UcbLockBytes::CreateLockBytes( aContent.get(), Sequence < PropertyValue >(), eOpenMode, xInteractionHandler, pHandler ); if ( xLockBytes.Is() ) { pStream = new SvStream( xLockBytes ); pStream->SetBufferSize( 4096 ); pStream->SetError( xLockBytes->GetError() ); } } catch ( CommandAbortedException& ) { } catch ( ContentCreationException& ) { } catch ( Exception& ) { } } else // if no UCB is present at least conventional file io is supported pStream = new SvFileStream( rFileName, eOpenMode ); return pStream; } SvStream* UcbStreamHelper::CreateStream( Reference < XInputStream > xStream ) { SvStream* pStream = NULL; UcbLockBytesRef xLockBytes = UcbLockBytes::CreateInputLockBytes( xStream ); if ( xLockBytes.Is() ) { pStream = new SvStream( xLockBytes ); pStream->SetBufferSize( 4096 ); pStream->SetError( xLockBytes->GetError() ); } return pStream; }; }; <|endoftext|>
<commit_before>/* -*-c++-*- OpenSceneGraph - Copyright (C) 2009 Wang Rui * * This library is open source and may be redistributed and/or modified under * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or * (at your option) any later version. The full license is in LICENSE file * included with this distribution, and on the openscenegraph.org website. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * OpenSceneGraph Public License for more details. */ #include <osgQt/GraphicsWindowQt> namespace osgQt { GraphWidget::GraphWidget( const QGLFormat& format, QWidget* parent, const QGLWidget* shareWidget, Qt::WindowFlags f ) : QGLWidget(format, parent, shareWidget, f) { setAutoBufferSwap( false ); setMouseTracking( true ); } void GraphWidget::setKeyboardModifiers( QInputEvent* event ) { int modkey = event->modifiers() & (Qt::ShiftModifier | Qt::ControlModifier | Qt::AltModifier); unsigned int mask = 0; if ( modkey & Qt::ShiftModifier ) mask |= osgGA::GUIEventAdapter::MODKEY_SHIFT; if ( modkey & Qt::ControlModifier ) mask |= osgGA::GUIEventAdapter::MODKEY_CTRL; if ( modkey & Qt::AltModifier ) mask |= osgGA::GUIEventAdapter::MODKEY_ALT; _gw->getEventQueue()->getCurrentEventState()->setModKeyMask( mask ); } void GraphWidget::resizeEvent( QResizeEvent* event ) { const QSize& size = event->size(); _gw->getEventQueue()->windowResize( 0, 0, size.width(), size.height() ); _gw->resized( 0, 0, size.width(), size.height() ); } void GraphWidget::keyPressEvent( QKeyEvent* event ) { setKeyboardModifiers( event ); _gw->getEventQueue()->keyPress( (osgGA::GUIEventAdapter::KeySymbol) *(event->text().toAscii().data()) ); } void GraphWidget::keyReleaseEvent( QKeyEvent* event ) { setKeyboardModifiers( event ); _gw->getEventQueue()->keyRelease( (osgGA::GUIEventAdapter::KeySymbol) *(event->text().toAscii().data()) ); } void GraphWidget::mousePressEvent( QMouseEvent* event ) { int button = 0; switch ( event->button() ) { case Qt::LeftButton: button = 1; break; case Qt::MidButton: button = 2; break; case Qt::RightButton: button = 3; break; case Qt::NoButton: button = 0; break; default: button = 0; break; } setKeyboardModifiers( event ); _gw->getEventQueue()->mouseButtonPress( event->x(), event->y(), button ); } void GraphWidget::mouseReleaseEvent( QMouseEvent* event ) { int button = 0; switch ( event->button() ) { case Qt::LeftButton: button = 1; break; case Qt::MidButton: button = 2; break; case Qt::RightButton: button = 3; break; case Qt::NoButton: button = 0; break; default: button = 0; break; } setKeyboardModifiers( event ); _gw->getEventQueue()->mouseButtonRelease( event->x(), event->y(), button ); } void GraphWidget::mouseDoubleClickEvent( QMouseEvent* event ) { int button = 0; switch ( event->button() ) { case Qt::LeftButton: button = 1; break; case Qt::MidButton: button = 2; break; case Qt::RightButton: button = 3; break; case Qt::NoButton: button = 0; break; default: button = 0; break; } setKeyboardModifiers( event ); _gw->getEventQueue()->mouseDoubleButtonPress( event->x(), event->y(), button ); } void GraphWidget::mouseMoveEvent( QMouseEvent* event ) { setKeyboardModifiers( event ); _gw->getEventQueue()->mouseMotion( event->x(), event->y() ); } void GraphWidget::wheelEvent( QWheelEvent* event ) { setKeyboardModifiers( event ); _gw->getEventQueue()->mouseScroll( event->delta()>0 ? osgGA::GUIEventAdapter::SCROLL_UP : osgGA::GUIEventAdapter::SCROLL_DOWN ); } GraphicsWindowQt::GraphicsWindowQt( osg::GraphicsContext::Traits* traits ) : _widget(0), _initialized(false), _realized(false) { _traits = traits; _initialized = init(); if ( valid() ) { setState( new osg::State ); getState()->setGraphicsContext(this); if ( _traits.valid() && _traits->sharedContext ) { getState()->setContextID( _traits->sharedContext->getState()->getContextID() ); incrementContextIDUsageCount( getState()->getContextID() ); } else { getState()->setContextID( osg::GraphicsContext::createNewContextID() ); } } } GraphicsWindowQt::~GraphicsWindowQt() { close(); } bool GraphicsWindowQt::init() { QGLFormat format( QGLFormat::defaultFormat() ); format.setAlphaBufferSize( _traits->alpha ); format.setRedBufferSize( _traits->red ); format.setGreenBufferSize( _traits->green ); format.setBlueBufferSize( _traits->blue ); format.setDepthBufferSize( _traits->depth ); format.setStencilBufferSize( _traits->stencil ); format.setSampleBuffers( _traits->sampleBuffers ); format.setSamples( _traits->samples ); format.setAlpha( _traits->alpha>0 ); format.setDepth( _traits->depth>0 ); format.setStencil( _traits->stencil>0 ); format.setDoubleBuffer( _traits->doubleBuffer ); format.setSwapInterval( _traits->vsync ? 1 : 0 ); format.setStereo( _traits->quadBufferStereo ? 1 : 0 ); WindowData* windowData = _traits.get() ? dynamic_cast<WindowData*>(_traits->inheritedWindowData.get()) : 0; _widget = windowData ? windowData->_widget : 0; if ( !_widget ) { GraphicsWindowQt* sharedContextQt = dynamic_cast<GraphicsWindowQt*>(_traits->sharedContext); QGLWidget* shareWidget = sharedContextQt ? sharedContextQt->getGraphWidget() : 0; Qt::WindowFlags flags = Qt::Window|Qt::CustomizeWindowHint;//|Qt::WindowStaysOnTopHint; if ( _traits->windowDecoration ) flags |= Qt::WindowTitleHint|Qt::WindowMinMaxButtonsHint|Qt::WindowSystemMenuHint; _widget = new GraphWidget( format, 0, shareWidget, flags ); } _widget->setWindowTitle( _traits->windowName.c_str() ); _widget->move( _traits->x, _traits->y ); if ( !_traits->supportsResize ) _widget->setFixedSize( _traits->width, _traits->height ); else _widget->resize( _traits->width, _traits->height ); _widget->setFocusPolicy( Qt::WheelFocus ); _widget->setGraphicsWindow( this ); useCursor( _traits->useCursor ); return true; } bool GraphicsWindowQt::setWindowRectangleImplementation( int x, int y, int width, int height ) { if ( _widget ) _widget->setGeometry( x, y, width, height ); return _widget!=NULL; } void GraphicsWindowQt::getWindowRectangle( int& x, int& y, int& width, int& height ) { if ( _widget ) { const QRect& geom = _widget->geometry(); x = geom.x(); y = geom.y(); width = geom.width(); height = geom.height(); } } bool GraphicsWindowQt::setWindowDecorationImplementation( bool windowDecoration ) { Qt::WindowFlags flags = Qt::Window|Qt::CustomizeWindowHint;//|Qt::WindowStaysOnTopHint; if ( windowDecoration ) flags |= Qt::WindowTitleHint|Qt::WindowMinMaxButtonsHint|Qt::WindowSystemMenuHint; _traits->windowDecoration = windowDecoration; // FIXME: Calling setWindowFlags or reparent widget will recreate the window handle, // which makes QGLContext no longer work...How to deal with that? //if ( _widget ) _widget->setWindowFlags( flags ); return false; } bool GraphicsWindowQt::getWindowDecoration() const { return _traits->windowDecoration; } void GraphicsWindowQt::grabFocus() { if ( _widget ) _widget->setFocus( Qt::ActiveWindowFocusReason ); } void GraphicsWindowQt::grabFocusIfPointerInWindow() { if ( _widget->underMouse() ) _widget->setFocus( Qt::ActiveWindowFocusReason ); } void GraphicsWindowQt::raiseWindow() { if ( _widget ) _widget->raise(); } void GraphicsWindowQt::setWindowName( const std::string& name ) { if ( _widget ) _widget->setWindowTitle( name.c_str() ); } std::string GraphicsWindowQt::getWindowName() { return _widget ? _widget->windowTitle().toStdString() : ""; } void GraphicsWindowQt::useCursor( bool cursorOn ) { if ( _widget ) { _traits->useCursor = cursorOn; if ( !cursorOn ) _widget->setCursor( Qt::BlankCursor ); else _widget->setCursor( _currentCursor ); } } void GraphicsWindowQt::setCursor( MouseCursor cursor ) { if ( cursor==InheritCursor && _widget ) { _widget->unsetCursor(); } switch ( cursor ) { case NoCursor: _currentCursor = Qt::BlankCursor; break; case RightArrowCursor: case LeftArrowCursor: _currentCursor = Qt::ArrowCursor; break; case InfoCursor: _currentCursor = Qt::SizeAllCursor; break; case DestroyCursor: _currentCursor = Qt::ForbiddenCursor; break; case HelpCursor: _currentCursor = Qt::WhatsThisCursor; break; case CycleCursor: _currentCursor = Qt::ForbiddenCursor; break; case SprayCursor: _currentCursor = Qt::SizeAllCursor; break; case WaitCursor: _currentCursor = Qt::WaitCursor; break; case TextCursor: _currentCursor = Qt::IBeamCursor; break; case CrosshairCursor: _currentCursor = Qt::CrossCursor; break; case HandCursor: _currentCursor = Qt::OpenHandCursor; break; case UpDownCursor: _currentCursor = Qt::SizeVerCursor; break; case LeftRightCursor: _currentCursor = Qt::SizeHorCursor; break; case TopSideCursor: case BottomSideCursor: _currentCursor = Qt::UpArrowCursor; break; case LeftSideCursor: case RightSideCursor: _currentCursor = Qt::SizeHorCursor; break; case TopLeftCorner: _currentCursor = Qt::SizeBDiagCursor; break; case TopRightCorner: _currentCursor = Qt::SizeFDiagCursor; break; case BottomRightCorner: _currentCursor = Qt::SizeBDiagCursor; break; case BottomLeftCorner: _currentCursor = Qt::SizeFDiagCursor; break; default: break; }; if ( _widget ) _widget->setCursor( _currentCursor ); } bool GraphicsWindowQt::valid() const { return _widget && _widget->isValid(); } bool GraphicsWindowQt::realizeImplementation() { if ( !_initialized ) _initialized = init(); // A makeCurrent()/doneCurrent() seems to be required for // realizing the context(?) before starting drawing _widget->makeCurrent(); _widget->doneCurrent(); _realized = true; return true; } bool GraphicsWindowQt::isRealizedImplementation() const { return _realized; } void GraphicsWindowQt::closeImplementation() { if ( _widget ) _widget->close(); } bool GraphicsWindowQt::makeCurrentImplementation() { _widget->makeCurrent(); return true; } bool GraphicsWindowQt::releaseContextImplementation() { _widget->doneCurrent(); return true; } void GraphicsWindowQt::swapBuffersImplementation() { _widget->swapBuffers(); } void GraphicsWindowQt::requestWarpPointer( float x, float y ) { if ( _widget ) QCursor::setPos( _widget->mapToGlobal(QPoint((int)x,(int)y)) ); } } <commit_msg>From Benjamin Wasty and David Guthrie, "currently, non-alpha-numeric keys are not recognized (except as modifiers) in osgQt, so I added the mapping code from my Qt integration to GraphicsWindowQt (which is based on Delta3D code from David Guthrie - he gave me permission to submit it under OSGPL)."<commit_after>/* -*-c++-*- OpenSceneGraph - Copyright (C) 2009 Wang Rui * * This library is open source and may be redistributed and/or modified under * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or * (at your option) any later version. The full license is in LICENSE file * included with this distribution, and on the openscenegraph.org website. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * OpenSceneGraph Public License for more details. */ #include <osgQt/GraphicsWindowQt> namespace osgQt { class QtKeyboardMap { public: QtKeyboardMap() { mKeyMap[Qt::Key_Escape ] = osgGA::GUIEventAdapter::KEY_Escape; mKeyMap[Qt::Key_Delete ] = osgGA::GUIEventAdapter::KEY_Delete; mKeyMap[Qt::Key_Home ] = osgGA::GUIEventAdapter::KEY_Home; mKeyMap[Qt::Key_Enter ] = osgGA::GUIEventAdapter::KEY_KP_Enter; mKeyMap[Qt::Key_End ] = osgGA::GUIEventAdapter::KEY_End; mKeyMap[Qt::Key_Return ] = osgGA::GUIEventAdapter::KEY_Return; mKeyMap[Qt::Key_PageUp ] = osgGA::GUIEventAdapter::KEY_Page_Up; mKeyMap[Qt::Key_PageDown ] = osgGA::GUIEventAdapter::KEY_Page_Down; mKeyMap[Qt::Key_Left ] = osgGA::GUIEventAdapter::KEY_Left; mKeyMap[Qt::Key_Right ] = osgGA::GUIEventAdapter::KEY_Right; mKeyMap[Qt::Key_Up ] = osgGA::GUIEventAdapter::KEY_Up; mKeyMap[Qt::Key_Down ] = osgGA::GUIEventAdapter::KEY_Down; mKeyMap[Qt::Key_Backspace ] = osgGA::GUIEventAdapter::KEY_BackSpace; mKeyMap[Qt::Key_Tab ] = osgGA::GUIEventAdapter::KEY_Tab; mKeyMap[Qt::Key_Space ] = osgGA::GUIEventAdapter::KEY_Space; mKeyMap[Qt::Key_Delete ] = osgGA::GUIEventAdapter::KEY_Delete; mKeyMap[Qt::Key_Alt ] = osgGA::GUIEventAdapter::KEY_Alt_L; mKeyMap[Qt::Key_Shift ] = osgGA::GUIEventAdapter::KEY_Shift_L; mKeyMap[Qt::Key_Control ] = osgGA::GUIEventAdapter::KEY_Control_L; mKeyMap[Qt::Key_Meta ] = osgGA::GUIEventAdapter::KEY_Meta_L; mKeyMap[Qt::Key_F1 ] = osgGA::GUIEventAdapter::KEY_F1; mKeyMap[Qt::Key_F2 ] = osgGA::GUIEventAdapter::KEY_F2; mKeyMap[Qt::Key_F3 ] = osgGA::GUIEventAdapter::KEY_F3; mKeyMap[Qt::Key_F4 ] = osgGA::GUIEventAdapter::KEY_F4; mKeyMap[Qt::Key_F5 ] = osgGA::GUIEventAdapter::KEY_F5; mKeyMap[Qt::Key_F6 ] = osgGA::GUIEventAdapter::KEY_F6; mKeyMap[Qt::Key_F7 ] = osgGA::GUIEventAdapter::KEY_F7; mKeyMap[Qt::Key_F8 ] = osgGA::GUIEventAdapter::KEY_F8; mKeyMap[Qt::Key_F9 ] = osgGA::GUIEventAdapter::KEY_F9; mKeyMap[Qt::Key_F10 ] = osgGA::GUIEventAdapter::KEY_F10; mKeyMap[Qt::Key_F11 ] = osgGA::GUIEventAdapter::KEY_F11; mKeyMap[Qt::Key_F12 ] = osgGA::GUIEventAdapter::KEY_F12; mKeyMap[Qt::Key_F13 ] = osgGA::GUIEventAdapter::KEY_F13; mKeyMap[Qt::Key_F14 ] = osgGA::GUIEventAdapter::KEY_F14; mKeyMap[Qt::Key_F15 ] = osgGA::GUIEventAdapter::KEY_F15; mKeyMap[Qt::Key_F16 ] = osgGA::GUIEventAdapter::KEY_F16; mKeyMap[Qt::Key_F17 ] = osgGA::GUIEventAdapter::KEY_F17; mKeyMap[Qt::Key_F18 ] = osgGA::GUIEventAdapter::KEY_F18; mKeyMap[Qt::Key_F19 ] = osgGA::GUIEventAdapter::KEY_F19; mKeyMap[Qt::Key_F20 ] = osgGA::GUIEventAdapter::KEY_F20; mKeyMap[Qt::Key_hyphen ] = '-'; mKeyMap[Qt::Key_Equal ] = '='; mKeyMap[Qt::Key_division ] = osgGA::GUIEventAdapter::KEY_KP_Divide; mKeyMap[Qt::Key_multiply ] = osgGA::GUIEventAdapter::KEY_KP_Multiply; mKeyMap[Qt::Key_Minus ] = '-'; mKeyMap[Qt::Key_Plus ] = '+'; //mKeyMap[Qt::Key_H ] = osgGA::GUIEventAdapter::KEY_KP_Home; //mKeyMap[Qt::Key_ ] = osgGA::GUIEventAdapter::KEY_KP_Up; //mKeyMap[92 ] = osgGA::GUIEventAdapter::KEY_KP_Page_Up; //mKeyMap[86 ] = osgGA::GUIEventAdapter::KEY_KP_Left; //mKeyMap[87 ] = osgGA::GUIEventAdapter::KEY_KP_Begin; //mKeyMap[88 ] = osgGA::GUIEventAdapter::KEY_KP_Right; //mKeyMap[83 ] = osgGA::GUIEventAdapter::KEY_KP_End; //mKeyMap[84 ] = osgGA::GUIEventAdapter::KEY_KP_Down; //mKeyMap[85 ] = osgGA::GUIEventAdapter::KEY_KP_Page_Down; mKeyMap[Qt::Key_Insert ] = osgGA::GUIEventAdapter::KEY_KP_Insert; //mKeyMap[Qt::Key_Delete ] = osgGA::GUIEventAdapter::KEY_KP_Delete; } ~QtKeyboardMap() { } int remapKey(QKeyEvent* event) { KeyMap::iterator itr = mKeyMap.find(event->key()); if (itr == mKeyMap.end()) { return int(*(event->text().toAscii().data())); } else return itr->second; } private: typedef std::map<unsigned int, int> KeyMap; KeyMap mKeyMap; }; static QtKeyboardMap s_QtKeyboardMap; GraphWidget::GraphWidget( const QGLFormat& format, QWidget* parent, const QGLWidget* shareWidget, Qt::WindowFlags f ) : QGLWidget(format, parent, shareWidget, f) { setAutoBufferSwap( false ); setMouseTracking( true ); } void GraphWidget::setKeyboardModifiers( QInputEvent* event ) { int modkey = event->modifiers() & (Qt::ShiftModifier | Qt::ControlModifier | Qt::AltModifier); unsigned int mask = 0; if ( modkey & Qt::ShiftModifier ) mask |= osgGA::GUIEventAdapter::MODKEY_SHIFT; if ( modkey & Qt::ControlModifier ) mask |= osgGA::GUIEventAdapter::MODKEY_CTRL; if ( modkey & Qt::AltModifier ) mask |= osgGA::GUIEventAdapter::MODKEY_ALT; _gw->getEventQueue()->getCurrentEventState()->setModKeyMask( mask ); } void GraphWidget::resizeEvent( QResizeEvent* event ) { const QSize& size = event->size(); _gw->getEventQueue()->windowResize( 0, 0, size.width(), size.height() ); _gw->resized( 0, 0, size.width(), size.height() ); } void GraphWidget::keyPressEvent( QKeyEvent* event ) { setKeyboardModifiers( event ); int value = s_QtKeyboardMap.remapKey(event); _gw->getEventQueue()->keyPress(value); } void GraphWidget::keyReleaseEvent( QKeyEvent* event ) { setKeyboardModifiers( event ); int value = s_QtKeyboardMap.remapKey(event); _gw->getEventQueue()->keyRelease(value); } void GraphWidget::mousePressEvent( QMouseEvent* event ) { int button = 0; switch ( event->button() ) { case Qt::LeftButton: button = 1; break; case Qt::MidButton: button = 2; break; case Qt::RightButton: button = 3; break; case Qt::NoButton: button = 0; break; default: button = 0; break; } setKeyboardModifiers( event ); _gw->getEventQueue()->mouseButtonPress( event->x(), event->y(), button ); } void GraphWidget::mouseReleaseEvent( QMouseEvent* event ) { int button = 0; switch ( event->button() ) { case Qt::LeftButton: button = 1; break; case Qt::MidButton: button = 2; break; case Qt::RightButton: button = 3; break; case Qt::NoButton: button = 0; break; default: button = 0; break; } setKeyboardModifiers( event ); _gw->getEventQueue()->mouseButtonRelease( event->x(), event->y(), button ); } void GraphWidget::mouseDoubleClickEvent( QMouseEvent* event ) { int button = 0; switch ( event->button() ) { case Qt::LeftButton: button = 1; break; case Qt::MidButton: button = 2; break; case Qt::RightButton: button = 3; break; case Qt::NoButton: button = 0; break; default: button = 0; break; } setKeyboardModifiers( event ); _gw->getEventQueue()->mouseDoubleButtonPress( event->x(), event->y(), button ); } void GraphWidget::mouseMoveEvent( QMouseEvent* event ) { setKeyboardModifiers( event ); _gw->getEventQueue()->mouseMotion( event->x(), event->y() ); } void GraphWidget::wheelEvent( QWheelEvent* event ) { setKeyboardModifiers( event ); _gw->getEventQueue()->mouseScroll( event->delta()>0 ? osgGA::GUIEventAdapter::SCROLL_UP : osgGA::GUIEventAdapter::SCROLL_DOWN ); } GraphicsWindowQt::GraphicsWindowQt( osg::GraphicsContext::Traits* traits ) : _widget(0), _initialized(false), _realized(false) { _traits = traits; _initialized = init(); if ( valid() ) { setState( new osg::State ); getState()->setGraphicsContext(this); if ( _traits.valid() && _traits->sharedContext ) { getState()->setContextID( _traits->sharedContext->getState()->getContextID() ); incrementContextIDUsageCount( getState()->getContextID() ); } else { getState()->setContextID( osg::GraphicsContext::createNewContextID() ); } } } GraphicsWindowQt::~GraphicsWindowQt() { close(); } bool GraphicsWindowQt::init() { QGLFormat format( QGLFormat::defaultFormat() ); format.setAlphaBufferSize( _traits->alpha ); format.setRedBufferSize( _traits->red ); format.setGreenBufferSize( _traits->green ); format.setBlueBufferSize( _traits->blue ); format.setDepthBufferSize( _traits->depth ); format.setStencilBufferSize( _traits->stencil ); format.setSampleBuffers( _traits->sampleBuffers ); format.setSamples( _traits->samples ); format.setAlpha( _traits->alpha>0 ); format.setDepth( _traits->depth>0 ); format.setStencil( _traits->stencil>0 ); format.setDoubleBuffer( _traits->doubleBuffer ); format.setSwapInterval( _traits->vsync ? 1 : 0 ); format.setStereo( _traits->quadBufferStereo ? 1 : 0 ); WindowData* windowData = _traits.get() ? dynamic_cast<WindowData*>(_traits->inheritedWindowData.get()) : 0; _widget = windowData ? windowData->_widget : 0; if ( !_widget ) { GraphicsWindowQt* sharedContextQt = dynamic_cast<GraphicsWindowQt*>(_traits->sharedContext); QGLWidget* shareWidget = sharedContextQt ? sharedContextQt->getGraphWidget() : 0; Qt::WindowFlags flags = Qt::Window|Qt::CustomizeWindowHint;//|Qt::WindowStaysOnTopHint; if ( _traits->windowDecoration ) flags |= Qt::WindowTitleHint|Qt::WindowMinMaxButtonsHint|Qt::WindowSystemMenuHint; _widget = new GraphWidget( format, 0, shareWidget, flags ); } _widget->setWindowTitle( _traits->windowName.c_str() ); _widget->move( _traits->x, _traits->y ); if ( !_traits->supportsResize ) _widget->setFixedSize( _traits->width, _traits->height ); else _widget->resize( _traits->width, _traits->height ); _widget->setFocusPolicy( Qt::WheelFocus ); _widget->setGraphicsWindow( this ); useCursor( _traits->useCursor ); return true; } bool GraphicsWindowQt::setWindowRectangleImplementation( int x, int y, int width, int height ) { if ( _widget ) _widget->setGeometry( x, y, width, height ); return _widget!=NULL; } void GraphicsWindowQt::getWindowRectangle( int& x, int& y, int& width, int& height ) { if ( _widget ) { const QRect& geom = _widget->geometry(); x = geom.x(); y = geom.y(); width = geom.width(); height = geom.height(); } } bool GraphicsWindowQt::setWindowDecorationImplementation( bool windowDecoration ) { Qt::WindowFlags flags = Qt::Window|Qt::CustomizeWindowHint;//|Qt::WindowStaysOnTopHint; if ( windowDecoration ) flags |= Qt::WindowTitleHint|Qt::WindowMinMaxButtonsHint|Qt::WindowSystemMenuHint; _traits->windowDecoration = windowDecoration; // FIXME: Calling setWindowFlags or reparent widget will recreate the window handle, // which makes QGLContext no longer work...How to deal with that? //if ( _widget ) _widget->setWindowFlags( flags ); return false; } bool GraphicsWindowQt::getWindowDecoration() const { return _traits->windowDecoration; } void GraphicsWindowQt::grabFocus() { if ( _widget ) _widget->setFocus( Qt::ActiveWindowFocusReason ); } void GraphicsWindowQt::grabFocusIfPointerInWindow() { if ( _widget->underMouse() ) _widget->setFocus( Qt::ActiveWindowFocusReason ); } void GraphicsWindowQt::raiseWindow() { if ( _widget ) _widget->raise(); } void GraphicsWindowQt::setWindowName( const std::string& name ) { if ( _widget ) _widget->setWindowTitle( name.c_str() ); } std::string GraphicsWindowQt::getWindowName() { return _widget ? _widget->windowTitle().toStdString() : ""; } void GraphicsWindowQt::useCursor( bool cursorOn ) { if ( _widget ) { _traits->useCursor = cursorOn; if ( !cursorOn ) _widget->setCursor( Qt::BlankCursor ); else _widget->setCursor( _currentCursor ); } } void GraphicsWindowQt::setCursor( MouseCursor cursor ) { if ( cursor==InheritCursor && _widget ) { _widget->unsetCursor(); } switch ( cursor ) { case NoCursor: _currentCursor = Qt::BlankCursor; break; case RightArrowCursor: case LeftArrowCursor: _currentCursor = Qt::ArrowCursor; break; case InfoCursor: _currentCursor = Qt::SizeAllCursor; break; case DestroyCursor: _currentCursor = Qt::ForbiddenCursor; break; case HelpCursor: _currentCursor = Qt::WhatsThisCursor; break; case CycleCursor: _currentCursor = Qt::ForbiddenCursor; break; case SprayCursor: _currentCursor = Qt::SizeAllCursor; break; case WaitCursor: _currentCursor = Qt::WaitCursor; break; case TextCursor: _currentCursor = Qt::IBeamCursor; break; case CrosshairCursor: _currentCursor = Qt::CrossCursor; break; case HandCursor: _currentCursor = Qt::OpenHandCursor; break; case UpDownCursor: _currentCursor = Qt::SizeVerCursor; break; case LeftRightCursor: _currentCursor = Qt::SizeHorCursor; break; case TopSideCursor: case BottomSideCursor: _currentCursor = Qt::UpArrowCursor; break; case LeftSideCursor: case RightSideCursor: _currentCursor = Qt::SizeHorCursor; break; case TopLeftCorner: _currentCursor = Qt::SizeBDiagCursor; break; case TopRightCorner: _currentCursor = Qt::SizeFDiagCursor; break; case BottomRightCorner: _currentCursor = Qt::SizeBDiagCursor; break; case BottomLeftCorner: _currentCursor = Qt::SizeFDiagCursor; break; default: break; }; if ( _widget ) _widget->setCursor( _currentCursor ); } bool GraphicsWindowQt::valid() const { return _widget && _widget->isValid(); } bool GraphicsWindowQt::realizeImplementation() { if ( !_initialized ) _initialized = init(); // A makeCurrent()/doneCurrent() seems to be required for // realizing the context(?) before starting drawing _widget->makeCurrent(); _widget->doneCurrent(); _realized = true; return true; } bool GraphicsWindowQt::isRealizedImplementation() const { return _realized; } void GraphicsWindowQt::closeImplementation() { if ( _widget ) _widget->close(); } bool GraphicsWindowQt::makeCurrentImplementation() { _widget->makeCurrent(); return true; } bool GraphicsWindowQt::releaseContextImplementation() { _widget->doneCurrent(); return true; } void GraphicsWindowQt::swapBuffersImplementation() { _widget->swapBuffers(); } void GraphicsWindowQt::requestWarpPointer( float x, float y ) { if ( _widget ) QCursor::setPos( _widget->mapToGlobal(QPoint((int)x,(int)y)) ); } } <|endoftext|>
<commit_before>//===--- CallerAnalysis.cpp - Determine callsites to a function ----------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #include "swift/SILOptimizer/Analysis/CallerAnalysis.h" #include "swift/Basic/Fallthrough.h" #include "swift/SIL/SILModule.h" #include "swift/SILOptimizer/Utils/Local.h" using namespace swift; static SILFunction *getCallee(FullApplySite &Apply) { SILValue Callee = Apply.getCallee(); // Strip ThinToThickFunctionInst. if (auto TTTF = dyn_cast<ThinToThickFunctionInst>(Callee)) { Callee = TTTF->getOperand(); } // Find the target function. auto *FRI = dyn_cast<FunctionRefInst>(Callee); if (!FRI) return nullptr; return FRI->getReferencedFunction(); } void CallerAnalysis::processFunctionCallSites(SILFunction *F) { // Scan the whole module and search Apply sites. for (auto &BB : *F) { for (auto &II : BB) { if (auto Apply = FullApplySite::isa(&II)) { SILFunction *CalleeFn = getCallee(Apply); if (!CalleeFn) continue; // Update the callee information for this fucntion. CallerAnalysisFunctionInfo &CallerInfo = CallInfo.FindAndConstruct(F).second; CallerInfo.Callees.push_back(CalleeFn); // Update the callsite information for the callee. CallerAnalysisFunctionInfo &CalleeInfo = CallInfo.FindAndConstruct(CalleeFn).second; CalleeInfo.CallSites[F].push_back(Apply); } } } } void CallerAnalysis::invalidateExistingCalleeRelation(SILFunction *F) { CallerAnalysisFunctionInfo &CallerInfo = CallInfo.FindAndConstruct(F).second; for (auto Callee : CallerInfo.Callees) { CallerAnalysisFunctionInfo &CalleeInfo = CallInfo.find(Callee)->second; CalleeInfo.CallSites[F].clear(); } } //===----------------------------------------------------------------------===// // Main Entry Point //===----------------------------------------------------------------------===// SILAnalysis *swift::createCallerAnalysis(SILModule *M) { return new CallerAnalysis(M); } <commit_msg>[gardening] Fix recently introduced typo: "fucntion" → "function"<commit_after>//===--- CallerAnalysis.cpp - Determine callsites to a function ----------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #include "swift/SILOptimizer/Analysis/CallerAnalysis.h" #include "swift/Basic/Fallthrough.h" #include "swift/SIL/SILModule.h" #include "swift/SILOptimizer/Utils/Local.h" using namespace swift; static SILFunction *getCallee(FullApplySite &Apply) { SILValue Callee = Apply.getCallee(); // Strip ThinToThickFunctionInst. if (auto TTTF = dyn_cast<ThinToThickFunctionInst>(Callee)) { Callee = TTTF->getOperand(); } // Find the target function. auto *FRI = dyn_cast<FunctionRefInst>(Callee); if (!FRI) return nullptr; return FRI->getReferencedFunction(); } void CallerAnalysis::processFunctionCallSites(SILFunction *F) { // Scan the whole module and search Apply sites. for (auto &BB : *F) { for (auto &II : BB) { if (auto Apply = FullApplySite::isa(&II)) { SILFunction *CalleeFn = getCallee(Apply); if (!CalleeFn) continue; // Update the callee information for this function. CallerAnalysisFunctionInfo &CallerInfo = CallInfo.FindAndConstruct(F).second; CallerInfo.Callees.push_back(CalleeFn); // Update the callsite information for the callee. CallerAnalysisFunctionInfo &CalleeInfo = CallInfo.FindAndConstruct(CalleeFn).second; CalleeInfo.CallSites[F].push_back(Apply); } } } } void CallerAnalysis::invalidateExistingCalleeRelation(SILFunction *F) { CallerAnalysisFunctionInfo &CallerInfo = CallInfo.FindAndConstruct(F).second; for (auto Callee : CallerInfo.Callees) { CallerAnalysisFunctionInfo &CalleeInfo = CallInfo.find(Callee)->second; CalleeInfo.CallSites[F].clear(); } } //===----------------------------------------------------------------------===// // Main Entry Point //===----------------------------------------------------------------------===// SILAnalysis *swift::createCallerAnalysis(SILModule *M) { return new CallerAnalysis(M); } <|endoftext|>
<commit_before>//============================================================================================================= /** * @file babymegclient.cpp * @author Limin Sun <liminsun@nmr.mgh.harvard.edu>; * Christoph Dinh <chdinh@nmr.mgh.harvard.edu>; * Matti Hamalainen <msh@nmr.mgh.harvard.edu> * @version 1.0 * @date April, 2013 * * @section LICENSE * * Copyright (C) 2013, Limin Sun, Christoph Dinh and Matti Hamalainen. 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 Massachusetts General Hospital 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 MASSACHUSETTS GENERAL HOSPITAL 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. * * * @brief implementation of the BabyMEGClient Class. * */ //************************************************************************************************************* //============================================================================================================= // INCLUDES //============================================================================================================= #include "babymegclient.h" //************************************************************************************************************* //============================================================================================================= // QT INCLUDES //============================================================================================================= #include <QDebug> #include <QtNetwork/QtNetwork> #include <QtEndian> //************************************************************************************************************* BabyMEGClient::BabyMEGClient(int myPort, QObject *parent) : QThread(parent) { connect(this,SIGNAL(DataAcq()),this,SLOT(run())); tcpSocket = new QTcpSocket(this); connect(tcpSocket,SIGNAL(readyRead()),this,SLOT(ReadToBuffer())); connect(this, SIGNAL(error(int,QString)), this, SLOT(DisplayError(int,QString))); //find out name of this machine name = QHostInfo::localHostName(); if(!name.isEmpty()) { QString domain = QHostInfo::localDomainName(); if (!domain.isEmpty()) name = name + QChar('.') + domain; } if (name!=QString("localhost")) name = QString("localhost"); qDebug()<< "- " + name; port = myPort;//6340; SocketIsConnected = false; SkipLoop = false; DataAcqStartFlag = false; numBlock = 0; DataACK = false; } //************************************************************************************************************* void BabyMEGClient::SetInfo(BabyMEGInfo *pInfo) { myBabyMEGInfo = pInfo; } //************************************************************************************************************* void BabyMEGClient::DisplayError(int socketError, const QString &message) { switch (socketError){ case QAbstractSocket::RemoteHostClosedError: break; case QAbstractSocket::HostNotFoundError: qDebug()<< "The host was not found. Please check the host name and the port number"; break; case QAbstractSocket::ConnectionRefusedError: qDebug()<< "The connection was refused by the peer. Make sure the server is running?"; break; default: qDebug()<< "Error: " << message; } } //************************************************************************************************************* int BabyMEGClient::MGH_LM_Byte2Int(QByteArray b) { int value= 0; for (int i=0;i<2;i++) { QByteArray t; t[0] = b[i]; b[i] = b[3-i]; b[3-i] = t[0]; } memcpy((char *)&value,b,4); return value; } //************************************************************************************************************* QByteArray BabyMEGClient::MGH_LM_Int2Byte(int a) { QByteArray b = QByteArray::fromRawData((char *)&a,4); for (int i=0;i<2;i++) { QByteArray t; t[0] = b[i]; b[i] = b[3-i]; b[3-i] = t[0]; } return b; } //************************************************************************************************************* double BabyMEGClient::MGH_LM_Byte2Double(QByteArray b) { double value= 1.0; // reverse the byte order for (int i=0;i<4;i++) { QByteArray t; t[0] = b[i]; b[i] = b[7-i]; b[7-i] = t[0]; } memcpy((char *)&value,b,8); return value; } //************************************************************************************************************* void BabyMEGClient::HexDisplay(double a) { QByteArray data = QByteArray::fromRawData((char *)&a,8); qDebug() << data.toHex(); } //************************************************************************************************************* void BabyMEGClient::ConnectToBabyMEG() { // return true: sucessfully connect to babyMEG server // false: fail. SocketIsConnected = false; // Connect to the server of babyMEG [labview] qDebug()<< "Client is started!"; if (!this->isRunning()) { this->start(); } for(int i=0;i<5;i++){ tcpSocket->connectToHost(name,port,QIODevice::ReadWrite); if (tcpSocket->waitForConnected(10000)) { SocketIsConnected = true; qDebug("Connect to BabyMEG Server ... Ok"); //download parameters qDebug()<< "Send the initial parameter request"; if (tcpSocket->state()==QAbstractSocket::ConnectedState) { buffer.clear(); SendCommand("INFO"); } return; } else{ qDebug("Connect to BabyMEG Server ... Fail"); qDebug("Try another time connection"); } qDebug("Please check the babyMEG server: if started"); } return; } //************************************************************************************************************* void BabyMEGClient::DisConnectBabyMEG() { if(SocketIsConnected && tcpSocket->state()==QAbstractSocket::ConnectedState) SendCommand("QUIT"); } //************************************************************************************************************* void BabyMEGClient::SendCommandToBabyMEGShortConnection() { qDebug() << "SendCommandToBabyMEGShortConnection"; tcpSocket->connectToHost(name,port,QIODevice::ReadWrite); if (tcpSocket->waitForConnected(10000)) { qDebug()<<"Connection is built."; if(tcpSocket->state()==QAbstractSocket::ConnectedState) { qDebug()<<"Send Command [COMS]"; tcpSocket->write("COMS"); int strlen = 3; QByteArray Scmd = MGH_LM_Int2Byte(strlen); tcpSocket->write(Scmd); tcpSocket->write("SLM"); tcpSocket->waitForBytesWritten(); } } } //************************************************************************************************************* void BabyMEGClient::SendCommandToBabyMEG() { qDebug()<<"Send Command"; if(SocketIsConnected && tcpSocket->state()==QAbstractSocket::ConnectedState) { m_qMutex.lock(); tcpSocket->write("COMD"); tcpSocket->waitForBytesWritten(); int strlen = 3; QByteArray Scmd = MGH_LM_Int2Byte(strlen); tcpSocket->write(Scmd); tcpSocket->write("SLM"); tcpSocket->waitForBytesWritten(); m_qMutex.unlock(); } } //************************************************************************************************************* void BabyMEGClient::ReadToBuffer() { QByteArray dat; int numBytes = tcpSocket->bytesAvailable(); // qDebug() << "1.byte available: " << numBytes; if (numBytes > 0){ dat = tcpSocket->read(numBytes); // read all pending data // qDebug()<<"[dat Size]"<<dat.size(); if (!dat.isEmpty()){ buffer.append(dat); // and append it to your own buffer // qDebug()<<"[ReadToBuffer: Buffer Size]"<<buffer.size(); } else { qDebug()<<"[Empty dat: error]"<<tcpSocket->errorString(); } } // qDebug()<<"read buffer is done!"; handleBuffer(); return; } //************************************************************************************************************* void BabyMEGClient::handleBuffer() { if(buffer.size()>= 8){ QByteArray CMD = buffer.left(4); QByteArray DLEN = buffer.mid(4,4); int tmp = MGH_LM_Byte2Int(DLEN); // qDebug() << "First 4 bytes + length" << CMD << "["<<CMD.toHex()<<"]"; // qDebug() << "Command[" << CMD <<"]"; // qDebug() << "Body Length[" << tmp << "]"; if (tmp <= (buffer.size() - 8)) { buffer.remove(0,8); int OPT = 0; if (CMD == "INFO") OPT = 1; else if (CMD == "DATR") OPT = 2; else if (CMD == "COMD") OPT = 3; else if (CMD == "QUIT") OPT = 4; else if (CMD == "COMS") OPT = 5; else if (CMD == "QUIS") OPT = 6; switch (OPT){ case 1: // from buffer get data package { QByteArray PARA = buffer.left(tmp); qDebug()<<"[INFO]"<<PARA; //Parse parameters from PARA string myBabyMEGInfo->MGH_LM_Parse_Para(PARA); buffer.remove(0,tmp); qDebug()<<"ACQ Start"; SendCommand("DATA"); } break; case 2: // read data package from buffer // Ask for the next data block SendCommand("DATA"); DispatchDataPackage(tmp); break; case 3: { QByteArray RESP = buffer.left(tmp); qDebug()<< "5.Readbytes:"<<RESP.size(); qDebug() << RESP; } buffer.remove(0,tmp); break; case 4: //quit qDebug()<<"Quit"; SendCommand("QREL"); tcpSocket->disconnectFromHost(); if(tcpSocket->state() != QAbstractSocket::UnconnectedState) tcpSocket->waitForDisconnected(); SocketIsConnected = false; qDebug()<< "Disconnect Server"; qDebug()<< "Client is End!"; qDebug()<< "You can close this application or restart to connect Server."; break; case 5://command short connection { QByteArray RESP = buffer.left(tmp); qDebug()<< "5.Readbytes:"<<RESP.size(); qDebug() << RESP; } buffer.remove(0,tmp); SendCommand("QUIT"); break; case 6: //quit qDebug()<<"Quit"; SendCommand("QREL"); tcpSocket->disconnectFromHost(); if(tcpSocket->state() != QAbstractSocket::UnconnectedState) tcpSocket->waitForDisconnected(); SocketIsConnected = false; qDebug()<< "Disconnect Server"; break; default: qDebug()<< "Unknow Type"; break; } } }// buffer is not empty and larger than 8 bytes } //************************************************************************************************************* void BabyMEGClient::DispatchDataPackage(int tmp) { // qDebug()<<"Acq data from buffer [buffer size() =" << buffer.size()<<"]"; QByteArray DATA = buffer.left(tmp); qDebug()<< "5.Readbytes:"<<DATA.size(); // myBabyMEGInfo->EnQueue(DATA); buffer.remove(0,tmp); // qDebug()<<"Rest buffer [buffer size() =" << buffer.size()<<"]"; numBlock ++; qDebug()<< "Next Block ..." << numBlock; // DATA.clear(); // ReadNextBlock(tmp); } //************************************************************************************************************* void BabyMEGClient::ReadNextBlock(int tmp) { QByteArray CMD1; QByteArray DLEN1; QByteArray DATA1; int tmp1; while (buffer.size()>=(tmp+8)) { // process the extra data block to reduce the load of data buffer CMD1 = buffer.left(4); qDebug()<<"CMD"<< CMD1; if (CMD1 == "DATR") { DLEN1 = buffer.mid(4,4); tmp1 = MGH_LM_Byte2Int(DLEN1); qDebug() << "[2]First 4 bytes + length" << CMD1 << "["<<CMD1.toHex()<<"]"; qDebug() << "[2]Command[" << CMD1 <<"]"; qDebug() << "[2]Body Length[" << tmp1 << "]"; buffer.remove(0,8); DATA1 = buffer.left(tmp1); myBabyMEGInfo->EnQueue(DATA1); buffer.remove(0,tmp1); qDebug()<<"End of DataPackeage" << buffer.left(3); qDebug()<<"[2]Rest buffer [buffer size() =" << buffer.size()<<"]"; numBlock ++; qDebug()<< "[2]Next Block ..." << numBlock; } else { qDebug()<<"[CMD1]"<<CMD1.toHex(); break; } qDebug()<<"[ReadNextBlock:buffer size]"<<buffer.size(); } DATA1.clear(); CMD1.clear(); DLEN1.clear(); } //************************************************************************************************************* void BabyMEGClient::SendCommand(QString s) { QByteArray array; array.append(s); int WrtNum; if (tcpSocket->state()==QAbstractSocket::ConnectedState) { m_qMutex.lock(); // qDebug()<<"[Send Command]"<<array; WrtNum = tcpSocket->write(array,4); if(WrtNum==-1) { qDebug()<<"Error for sending a command"; } if(WrtNum != array.size()) { qDebug()<<"Uncorrectly sending"; } tcpSocket->flush(); tcpSocket->waitForBytesWritten(); m_qMutex.unlock(); qDebug()<<"[Done: Send Command]"<<array<<"[Send bytes]"<<WrtNum; } else { qDebug()<<"Not in Connected state"; //re-connect to server ConnectToBabyMEG(); buffer.clear(); SendCommand("DATA"); } // sleep(1); } //************************************************************************************************************* void BabyMEGClient::run() { } <commit_msg>comments<commit_after>//============================================================================================================= /** * @file babymegclient.cpp * @author Limin Sun <liminsun@nmr.mgh.harvard.edu>; * Christoph Dinh <chdinh@nmr.mgh.harvard.edu>; * Matti Hamalainen <msh@nmr.mgh.harvard.edu> * @version 1.0 * @date April, 2013 * * @section LICENSE * * Copyright (C) 2013, Limin Sun, Christoph Dinh and Matti Hamalainen. 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 Massachusetts General Hospital nor the names of its contributors may be used * to endorse or promote products derived from this software without specific prior written permission. * * 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. * * * @brief implementation of the BabyMEGClient Class. * * 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 MASSACHUSETTS GENERAL HOSPITAL BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, */ //************************************************************************************************************* //============================================================================================================= // INCLUDES //============================================================================================================= #include "babymegclient.h" //************************************************************************************************************* //============================================================================================================= // QT INCLUDES //============================================================================================================= #include <QDebug> #include <QtNetwork/QtNetwork> #include <QtEndian> //************************************************************************************************************* BabyMEGClient::BabyMEGClient(int myPort, QObject *parent) : QThread(parent) { connect(this,SIGNAL(DataAcq()),this,SLOT(run())); tcpSocket = new QTcpSocket(this); connect(tcpSocket,SIGNAL(readyRead()),this,SLOT(ReadToBuffer())); connect(this, SIGNAL(error(int,QString)), this, SLOT(DisplayError(int,QString))); //find out name of this machine name = QHostInfo::localHostName(); if(!name.isEmpty()) { QString domain = QHostInfo::localDomainName(); if (!domain.isEmpty()) name = name + QChar('.') + domain; } if (name!=QString("localhost")) name = QString("localhost"); qDebug()<< "- " + name; port = myPort;//6340; SocketIsConnected = false; SkipLoop = false; DataAcqStartFlag = false; numBlock = 0; DataACK = false; } //************************************************************************************************************* void BabyMEGClient::SetInfo(BabyMEGInfo *pInfo) { myBabyMEGInfo = pInfo; } //************************************************************************************************************* void BabyMEGClient::DisplayError(int socketError, const QString &message) { switch (socketError){ case QAbstractSocket::RemoteHostClosedError: break; case QAbstractSocket::HostNotFoundError: qDebug()<< "The host was not found. Please check the host name and the port number"; break; case QAbstractSocket::ConnectionRefusedError: qDebug()<< "The connection was refused by the peer. Make sure the server is running?"; break; default: qDebug()<< "Error: " << message; } } //************************************************************************************************************* int BabyMEGClient::MGH_LM_Byte2Int(QByteArray b) { int value= 0; for (int i=0;i<2;i++) { QByteArray t; t[0] = b[i]; b[i] = b[3-i]; b[3-i] = t[0]; } memcpy((char *)&value,b,4); return value; } //************************************************************************************************************* QByteArray BabyMEGClient::MGH_LM_Int2Byte(int a) { QByteArray b = QByteArray::fromRawData((char *)&a,4); for (int i=0;i<2;i++) { QByteArray t; t[0] = b[i]; b[i] = b[3-i]; b[3-i] = t[0]; } return b; } //************************************************************************************************************* double BabyMEGClient::MGH_LM_Byte2Double(QByteArray b) { double value= 1.0; // reverse the byte order for (int i=0;i<4;i++) { QByteArray t; t[0] = b[i]; b[i] = b[7-i]; b[7-i] = t[0]; } memcpy((char *)&value,b,8); return value; } //************************************************************************************************************* void BabyMEGClient::HexDisplay(double a) { QByteArray data = QByteArray::fromRawData((char *)&a,8); qDebug() << data.toHex(); } //************************************************************************************************************* void BabyMEGClient::ConnectToBabyMEG() { // return true: sucessfully connect to babyMEG server // false: fail. SocketIsConnected = false; // Connect to the server of babyMEG [labview] qDebug()<< "Client is started!"; if (!this->isRunning()) { this->start(); } for(int i=0;i<5;i++){ tcpSocket->connectToHost(name,port,QIODevice::ReadWrite); if (tcpSocket->waitForConnected(10000)) { SocketIsConnected = true; qDebug("Connect to BabyMEG Server ... Ok"); //download parameters qDebug()<< "Send the initial parameter request"; if (tcpSocket->state()==QAbstractSocket::ConnectedState) { buffer.clear(); SendCommand("INFO"); } return; } else{ qDebug("Connect to BabyMEG Server ... Fail"); qDebug("Try another time connection"); } qDebug("Please check the babyMEG server: if started"); } return; } //************************************************************************************************************* void BabyMEGClient::DisConnectBabyMEG() { if(SocketIsConnected && tcpSocket->state()==QAbstractSocket::ConnectedState) SendCommand("QUIT"); } //************************************************************************************************************* void BabyMEGClient::SendCommandToBabyMEGShortConnection() { qDebug() << "SendCommandToBabyMEGShortConnection"; tcpSocket->connectToHost(name,port,QIODevice::ReadWrite); if (tcpSocket->waitForConnected(10000)) { qDebug()<<"Connection is built."; if(tcpSocket->state()==QAbstractSocket::ConnectedState) { qDebug()<<"Send Command [COMS]"; tcpSocket->write("COMS"); int strlen = 3; QByteArray Scmd = MGH_LM_Int2Byte(strlen); tcpSocket->write(Scmd); tcpSocket->write("SLM"); tcpSocket->waitForBytesWritten(); } } } //************************************************************************************************************* void BabyMEGClient::SendCommandToBabyMEG() { qDebug()<<"Send Command"; if(SocketIsConnected && tcpSocket->state()==QAbstractSocket::ConnectedState) { m_qMutex.lock(); tcpSocket->write("COMD"); tcpSocket->waitForBytesWritten(); int strlen = 3; QByteArray Scmd = MGH_LM_Int2Byte(strlen); tcpSocket->write(Scmd); tcpSocket->write("SLM"); tcpSocket->waitForBytesWritten(); m_qMutex.unlock(); } } //************************************************************************************************************* void BabyMEGClient::ReadToBuffer() { QByteArray dat; int numBytes = tcpSocket->bytesAvailable(); // qDebug() << "1.byte available: " << numBytes; if (numBytes > 0){ dat = tcpSocket->read(numBytes); // read all pending data // qDebug()<<"[dat Size]"<<dat.size(); if (!dat.isEmpty()){ buffer.append(dat); // and append it to your own buffer // qDebug()<<"[ReadToBuffer: Buffer Size]"<<buffer.size(); } else { qDebug()<<"[Empty dat: error]"<<tcpSocket->errorString(); } } // qDebug()<<"read buffer is done!"; handleBuffer(); return; } //************************************************************************************************************* void BabyMEGClient::handleBuffer() { if(buffer.size()>= 8){ QByteArray CMD = buffer.left(4); QByteArray DLEN = buffer.mid(4,4); int tmp = MGH_LM_Byte2Int(DLEN); // qDebug() << "First 4 bytes + length" << CMD << "["<<CMD.toHex()<<"]"; // qDebug() << "Command[" << CMD <<"]"; // qDebug() << "Body Length[" << tmp << "]"; if (tmp <= (buffer.size() - 8)) { buffer.remove(0,8); int OPT = 0; if (CMD == "INFO") OPT = 1; else if (CMD == "DATR") OPT = 2; else if (CMD == "COMD") OPT = 3; else if (CMD == "QUIT") OPT = 4; else if (CMD == "COMS") OPT = 5; else if (CMD == "QUIS") OPT = 6; switch (OPT){ case 1: // from buffer get data package { QByteArray PARA = buffer.left(tmp); qDebug()<<"[INFO]"<<PARA; //Parse parameters from PARA string myBabyMEGInfo->MGH_LM_Parse_Para(PARA); buffer.remove(0,tmp); qDebug()<<"ACQ Start"; SendCommand("DATA"); } break; case 2: // read data package from buffer // Ask for the next data block SendCommand("DATA"); DispatchDataPackage(tmp); break; case 3: { QByteArray RESP = buffer.left(tmp); qDebug()<< "5.Readbytes:"<<RESP.size(); qDebug() << RESP; } buffer.remove(0,tmp); break; case 4: //quit qDebug()<<"Quit"; SendCommand("QREL"); tcpSocket->disconnectFromHost(); if(tcpSocket->state() != QAbstractSocket::UnconnectedState) tcpSocket->waitForDisconnected(); SocketIsConnected = false; qDebug()<< "Disconnect Server"; qDebug()<< "Client is End!"; qDebug()<< "You can close this application or restart to connect Server."; break; case 5://command short connection { QByteArray RESP = buffer.left(tmp); qDebug()<< "5.Readbytes:"<<RESP.size(); qDebug() << RESP; } buffer.remove(0,tmp); SendCommand("QUIT"); break; case 6: //quit qDebug()<<"Quit"; SendCommand("QREL"); tcpSocket->disconnectFromHost(); if(tcpSocket->state() != QAbstractSocket::UnconnectedState) tcpSocket->waitForDisconnected(); SocketIsConnected = false; qDebug()<< "Disconnect Server"; break; default: qDebug()<< "Unknow Type"; break; } } }// buffer is not empty and larger than 8 bytes } //************************************************************************************************************* void BabyMEGClient::DispatchDataPackage(int tmp) { // qDebug()<<"Acq data from buffer [buffer size() =" << buffer.size()<<"]"; QByteArray DATA = buffer.left(tmp); qDebug()<< "5.Readbytes:"<<DATA.size(); // myBabyMEGInfo->EnQueue(DATA); buffer.remove(0,tmp); // qDebug()<<"Rest buffer [buffer size() =" << buffer.size()<<"]"; numBlock ++; qDebug()<< "Next Block ..." << numBlock; // DATA.clear(); // ReadNextBlock(tmp); } //************************************************************************************************************* void BabyMEGClient::ReadNextBlock(int tmp) { QByteArray CMD1; QByteArray DLEN1; QByteArray DATA1; int tmp1; while (buffer.size()>=(tmp+8)) { // process the extra data block to reduce the load of data buffer CMD1 = buffer.left(4); qDebug()<<"CMD"<< CMD1; if (CMD1 == "DATR") { DLEN1 = buffer.mid(4,4); tmp1 = MGH_LM_Byte2Int(DLEN1); qDebug() << "[2]First 4 bytes + length" << CMD1 << "["<<CMD1.toHex()<<"]"; qDebug() << "[2]Command[" << CMD1 <<"]"; qDebug() << "[2]Body Length[" << tmp1 << "]"; buffer.remove(0,8); DATA1 = buffer.left(tmp1); myBabyMEGInfo->EnQueue(DATA1); buffer.remove(0,tmp1); qDebug()<<"End of DataPackeage" << buffer.left(3); qDebug()<<"[2]Rest buffer [buffer size() =" << buffer.size()<<"]"; numBlock ++; qDebug()<< "[2]Next Block ..." << numBlock; } else { qDebug()<<"[CMD1]"<<CMD1.toHex(); break; } qDebug()<<"[ReadNextBlock:buffer size]"<<buffer.size(); } DATA1.clear(); CMD1.clear(); DLEN1.clear(); } //************************************************************************************************************* void BabyMEGClient::SendCommand(QString s) { QByteArray array; array.append(s); int WrtNum; if (tcpSocket->state()==QAbstractSocket::ConnectedState) { m_qMutex.lock(); // qDebug()<<"[Send Command]"<<array; WrtNum = tcpSocket->write(array,4); if(WrtNum==-1) { qDebug()<<"Error for sending a command"; } if(WrtNum != array.size()) { qDebug()<<"Uncorrectly sending"; } tcpSocket->flush(); tcpSocket->waitForBytesWritten(); m_qMutex.unlock(); qDebug()<<"[Done: Send Command]"<<array<<"[Send bytes]"<<WrtNum; } else { qDebug()<<"Not in Connected state"; //re-connect to server ConnectToBabyMEG(); buffer.clear(); SendCommand("DATA"); } // sleep(1); } //************************************************************************************************************* void BabyMEGClient::run() { } <|endoftext|>
<commit_before>#include "GL/glew.h" #include <stdlib.h> #include <stdio.h> #include <glm/glm.hpp> #include <glm/gtc/type_ptr.hpp> #include <glm/gtx/rotate_vector.hpp> #include "photon_opengl.h" #include "photon_window_managment.h" #include "photon_core.h" #include "photon_blocks.h" #include "photon_texture.h" #include <physfs.h> #include <SOIL.h> namespace photon{ namespace opengl{ photon_shader shader_scene; photon_shader shader_laser; photon_shader shader_light; photon_shader shader_fx; photon_shader shader_text; GLuint photon_texture; GLuint background; void InitOpenGL(photon_window &window){ PrintToLog("INFO: Initializing OpenGL."); SDL_GL_MakeCurrent(window.window_SDL, window.context_SDL); GLuint glewstatus = glewInit(); if(glewstatus != GLEW_OK){ PrintToLog("GLEW ERROR: %s", glewGetErrorString(glewstatus)); return; } if(GLEW_VERSION_2_0){ PrintToLog("INFO: OpenGL 2.0 support detected, things should work fine."); }else{ PrintToLog("WARNING: OpenGL 2.0 support NOT detected, things probably won't work."); } glClearColor(0.0f, 0.0f, 0.0f, 0.0f); glGenTextures(1, &window.light_buffer_texture); glBindTexture(GL_TEXTURE_2D, window.light_buffer_texture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); // texture size is 1x1 because it will get resized properly later (on resized event from window creation) glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, 1, 1, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0); glBindTexture(GL_TEXTURE_2D, 0); glGenFramebuffers(1, &window.light_buffer); glBindFramebuffer(GL_FRAMEBUFFER, window.light_buffer); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, window.light_buffer_texture, 0); GLenum buffer = GL_COLOR_ATTACHMENT0; glDrawBuffers(1, &buffer); if(glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE){ PrintToLog("ERROR: Frambuffer creation failed!"); // TODO - proper error handling. throw; } glBindFramebuffer(GL_FRAMEBUFFER, 0); glDisable(GL_CULL_FACE); glEnable(GL_MULTISAMPLE); glEnableVertexAttribArray(PHOTON_VERTEX_LOCATION_ATTRIBUTE); glEnableVertexAttribArray(PHOTON_VERTEX_UV_ATTRIBUTE); shader_scene = LoadShaderXML("/shaders/scene.xml"); glUniform1f(glGetUniformLocation(shader_scene.program, "zoom"), 1.0f); shader_laser = LoadShaderXML("/shaders/laser.xml"); glUniform1f(glGetUniformLocation(shader_laser.program, "zoom"), 1.0f); shader_light = LoadShaderXML("/shaders/light.xml"); glUniform1f(glGetUniformLocation(shader_light.program, "zoom"), 1.0f); shader_fx = LoadShaderXML("/shaders/fx.xml"); glUniform1f(glGetUniformLocation(shader_fx.program, "zoom"), 1.0f); shader_text = LoadShaderXML("/shaders/text.xml"); blocks::LoadTextures(); photon_texture = texture::Load("/textures/photon.png"); background = texture::Load("/textures/background.png"); if(!opengl::CheckOpenGLErrors()){ PrintToLog("INFO: OpenGL succesfully initilized."); } } void GarbageCollect(photon_window &window){ SDL_GL_MakeCurrent(window.window_SDL, window.context_SDL); CheckOpenGLErrors(); texture::GarbageCollect(); DeleteShader(shader_scene); PrintToLog("INFO: OpenGL garbage collection complete."); } void OnResize(uint32_t width, uint32_t height, photon_window &window){ SDL_GL_MakeCurrent(window.window_SDL, window.context_SDL); PrintToLog("INFO: Resizing window to %ix%i.", width, height); float aspect = (float)width/(float)height; glUseProgram(shader_scene.program); glUniform1f(glGetUniformLocation(shader_scene.program, "aspect"), aspect); glUseProgram(shader_laser.program); glUniform1f(glGetUniformLocation(shader_laser.program, "aspect"), aspect); glUseProgram(shader_light.program); glUniform1f(glGetUniformLocation(shader_light.program, "aspect"), aspect); glUseProgram(shader_fx.program); glUniform1f(glGetUniformLocation(shader_fx.program, "aspect"), aspect); glUseProgram(shader_text.program); glUniform1f(glGetUniformLocation(shader_text.program, "aspect"), aspect); glViewport(0, 0, width, height); window.width = width; window.height = height; glBindTexture(GL_TEXTURE_2D, window.light_buffer_texture); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0); } GLenum CheckOpenGLErrors(){ GLenum err = glGetError(); switch(err){ case GL_INVALID_ENUM: PrintToLog("OPENGL ERROR: Invalid Enum."); break; case GL_INVALID_VALUE: PrintToLog("OPENGL ERROR: Invalid Value."); break; case GL_INVALID_OPERATION: PrintToLog("OPENGL ERROR: Invalid Operation."); break; case GL_INVALID_FRAMEBUFFER_OPERATION: PrintToLog("OPENGL ERROR: Invalid Framebuffer Operation."); break; case GL_OUT_OF_MEMORY: PrintToLog("OPENGL ERROR: Out Of Memory."); break; case GL_NO_ERROR: break; } return err; } void UpdateZoom(const float &zoom){ glUseProgram(shader_scene.program); glUniform1f(glGetUniformLocation(shader_scene.program, "zoom"), 1.0f / zoom); glUseProgram(shader_laser.program); glUniform1f(glGetUniformLocation(shader_laser.program, "zoom"), 1.0f / zoom); glUseProgram(shader_light.program); glUniform1f(glGetUniformLocation(shader_light.program, "zoom"), 1.0f / zoom); glUseProgram(shader_fx.program); glUniform1f(glGetUniformLocation(shader_fx.program, "zoom"), 1.0f / zoom); } void UpdateCenter(const glm::vec2 &center){ glUseProgram(shader_scene.program); glUniform2fv(glGetUniformLocation(shader_scene.program, "center"), 1, glm::value_ptr(center)); glUseProgram(shader_laser.program); glUniform2fv(glGetUniformLocation(shader_laser.program, "center"), 1, glm::value_ptr(center)); glUseProgram(shader_light.program); glUniform2fv(glGetUniformLocation(shader_light.program, "center"), 1, glm::value_ptr(center)); glUseProgram(shader_fx.program); glUniform2fv(glGetUniformLocation(shader_fx.program, "center"), 1, glm::value_ptr(center)); } void DrawModeScene(photon_window &window){ SDL_GL_MakeCurrent(window.window_SDL, window.context_SDL); glBindFramebuffer(GL_FRAMEBUFFER, 0); glClear(GL_COLOR_BUFFER_BIT); glDisable(GL_BLEND); glActiveTexture(PHOTON_TEXTURE_UNIT_LIGHT); glBindTexture(GL_TEXTURE_2D, window.light_buffer_texture); glActiveTexture(PHOTON_TEXTURE_UNIT_COLOR); } void DrawModeLaser(photon_window &window){ SDL_GL_MakeCurrent(window.window_SDL, window.context_SDL); glEnable(GL_BLEND); glBlendFunc(GL_ONE,GL_ONE); glUseProgram(shader_laser.program); } void DrawModeLevel(photon_window &window){ SDL_GL_MakeCurrent(window.window_SDL, window.context_SDL); glBindFramebuffer(GL_FRAMEBUFFER, 0); glEnable(GL_BLEND); glBlendFunc(GL_ONE,GL_ONE_MINUS_SRC_ALPHA); glUseProgram(shader_scene.program); glActiveTexture(PHOTON_TEXTURE_UNIT_LIGHT); glBindTexture(GL_TEXTURE_2D, window.light_buffer_texture); glActiveTexture(PHOTON_TEXTURE_UNIT_COLOR); } void DrawModeLight(photon_window &window){ SDL_GL_MakeCurrent(window.window_SDL, window.context_SDL); glBindFramebuffer(GL_FRAMEBUFFER, window.light_buffer); glClear(GL_COLOR_BUFFER_BIT); glEnable(GL_BLEND); glBlendFunc(GL_ONE,GL_ONE); glUseProgram(shader_light.program); glActiveTexture(PHOTON_TEXTURE_UNIT_LIGHT); glBindTexture(GL_TEXTURE_2D, 0); glActiveTexture(PHOTON_TEXTURE_UNIT_COLOR); } void DrawPhoton(const glm::vec2 &location){ glBindTexture(GL_TEXTURE_2D, photon_texture); SetFacFX(1.0f); static const float verts[] = { 0.2f, 0.2f, -0.2f, 0.2f, -0.2f,-0.2f, 0.2f,-0.2f}; static const float uv[] = {1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f}; opengl::SetModelMatrix(glm::mat3(1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, location.x, location.y, 1.0f)); glVertexAttribPointer(PHOTON_VERTEX_LOCATION_ATTRIBUTE, 2, GL_FLOAT, GL_FALSE, 0, verts); glVertexAttribPointer(PHOTON_VERTEX_UV_ATTRIBUTE, 2, GL_FLOAT, GL_FALSE, 0, uv); glDrawArrays(GL_TRIANGLE_FAN, 0, 4); } void DrawPhotonLight(const glm::vec2 &location){ static const float verts[] = { 16.0f, 16.0f, -16.0f, 16.0f, -16.0f,-16.0f, 16.0f,-16.0f}; static const float uv[] = { 1.0f, 1.0f, -1.0f, 1.0f, -1.0f,-1.0f, 1.0f,-1.0f}; opengl::SetModelMatrix(glm::mat3(1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, location.x, location.y, 1.0f)); glVertexAttribPointer(PHOTON_VERTEX_LOCATION_ATTRIBUTE, 2, GL_FLOAT, GL_FALSE, 0, verts); glVertexAttribPointer(PHOTON_VERTEX_UV_ATTRIBUTE, 2, GL_FLOAT, GL_FALSE, 0, uv); glDrawArrays(GL_TRIANGLE_FAN, 0, 4); } void DrawModeGUI(photon_window &window){ SDL_GL_MakeCurrent(window.window_SDL, window.context_SDL); glBindFramebuffer(GL_FRAMEBUFFER, 0); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA); glUseProgram(shader_text.program); } void SetColorGUI(const glm::vec4 &color){ glUseProgram(shader_text.program); glUniform4fv(glGetUniformLocation(shader_text.program, "color"), 1, glm::value_ptr(color)); } void SetCenterGUI(const glm::vec2 &center){ glUseProgram(shader_text.program); glUniform2fv(glGetUniformLocation(shader_text.program, "center"), 1, glm::value_ptr(center)); } void SetFacFX(const float &fac){ glUniform1f(glGetUniformLocation(shader_fx.program, "fac"), fac); } void SetLaserColor(const glm::vec3 &color){ glUniform3fv(glGetUniformLocation(shader_laser.program, "color"), 1, glm::value_ptr(color)); glUniform3fv(glGetUniformLocation(shader_light.program, "color"), 1, glm::value_ptr(color)); } void SetModelMatrix(const glm::mat3 &matrix){ GLint program = 0; glGetIntegerv(GL_CURRENT_PROGRAM, &program); GLint uniform = glGetUniformLocation(program, "model"); if(uniform > -1){ glUniformMatrix3fv(uniform, 1, GL_FALSE, glm::value_ptr(matrix)); } } void DrawModeFX(photon_window &window){ SDL_GL_MakeCurrent(window.window_SDL, window.context_SDL); glBindFramebuffer(GL_FRAMEBUFFER, 0); glEnable(GL_BLEND); glBlendFunc(GL_ONE,GL_ONE); glUseProgram(shader_fx.program); glActiveTexture(PHOTON_TEXTURE_UNIT_LIGHT); glBindTexture(GL_TEXTURE_2D, 0); glActiveTexture(PHOTON_TEXTURE_UNIT_COLOR); } void DrawBackground(photon_instance &instance){ static const float verts[] = { 1.0f, 1.0f, 1.0f,-1.0f, -1.0f,-1.0f, -1.0f, 1.0f}; static const float uv[] = {1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f}; DrawModeLevel(instance.window); glBindTexture(GL_TEXTURE_2D, background); glm::mat3 matrix(instance.zoom); float aspect = float(instance.window.width) / float(instance.window.height); if(aspect > 1.0f){ matrix *= aspect; }else if(aspect < 1.0f){ matrix /= aspect; } matrix[2] = glm::vec3(instance.player.location, 1.0f); opengl::SetModelMatrix(matrix); glVertexAttribPointer(PHOTON_VERTEX_LOCATION_ATTRIBUTE, 2, GL_FLOAT, GL_FALSE, 0, verts); glVertexAttribPointer(PHOTON_VERTEX_UV_ATTRIBUTE, 2, GL_FLOAT, GL_FALSE, 0, uv); glDrawArrays(GL_TRIANGLE_FAN, 0, 4); } } } <commit_msg>draw background with some flat lighting.<commit_after>#include "GL/glew.h" #include <stdlib.h> #include <stdio.h> #include <glm/glm.hpp> #include <glm/gtc/type_ptr.hpp> #include <glm/gtx/rotate_vector.hpp> #include "photon_opengl.h" #include "photon_window_managment.h" #include "photon_core.h" #include "photon_blocks.h" #include "photon_texture.h" #include <physfs.h> #include <SOIL.h> namespace photon{ namespace opengl{ photon_shader shader_scene; photon_shader shader_laser; photon_shader shader_light; photon_shader shader_fx; photon_shader shader_text; GLuint photon_texture; GLuint background; void InitOpenGL(photon_window &window){ PrintToLog("INFO: Initializing OpenGL."); SDL_GL_MakeCurrent(window.window_SDL, window.context_SDL); GLuint glewstatus = glewInit(); if(glewstatus != GLEW_OK){ PrintToLog("GLEW ERROR: %s", glewGetErrorString(glewstatus)); return; } if(GLEW_VERSION_2_0){ PrintToLog("INFO: OpenGL 2.0 support detected, things should work fine."); }else{ PrintToLog("WARNING: OpenGL 2.0 support NOT detected, things probably won't work."); } glClearColor(0.0f, 0.0f, 0.0f, 0.0f); glGenTextures(1, &window.light_buffer_texture); glBindTexture(GL_TEXTURE_2D, window.light_buffer_texture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); // texture size is 1x1 because it will get resized properly later (on resized event from window creation) glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, 1, 1, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0); glBindTexture(GL_TEXTURE_2D, 0); glGenFramebuffers(1, &window.light_buffer); glBindFramebuffer(GL_FRAMEBUFFER, window.light_buffer); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, window.light_buffer_texture, 0); GLenum buffer = GL_COLOR_ATTACHMENT0; glDrawBuffers(1, &buffer); if(glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE){ PrintToLog("ERROR: Frambuffer creation failed!"); // TODO - proper error handling. throw; } glBindFramebuffer(GL_FRAMEBUFFER, 0); glDisable(GL_CULL_FACE); glEnable(GL_MULTISAMPLE); glEnableVertexAttribArray(PHOTON_VERTEX_LOCATION_ATTRIBUTE); glEnableVertexAttribArray(PHOTON_VERTEX_UV_ATTRIBUTE); shader_scene = LoadShaderXML("/shaders/scene.xml"); glUniform1f(glGetUniformLocation(shader_scene.program, "zoom"), 1.0f); shader_laser = LoadShaderXML("/shaders/laser.xml"); glUniform1f(glGetUniformLocation(shader_laser.program, "zoom"), 1.0f); shader_light = LoadShaderXML("/shaders/light.xml"); glUniform1f(glGetUniformLocation(shader_light.program, "zoom"), 1.0f); shader_fx = LoadShaderXML("/shaders/fx.xml"); glUniform1f(glGetUniformLocation(shader_fx.program, "zoom"), 1.0f); shader_text = LoadShaderXML("/shaders/text.xml"); blocks::LoadTextures(); photon_texture = texture::Load("/textures/photon.png"); background = texture::Load("/textures/background.png"); if(!opengl::CheckOpenGLErrors()){ PrintToLog("INFO: OpenGL succesfully initilized."); } } void GarbageCollect(photon_window &window){ SDL_GL_MakeCurrent(window.window_SDL, window.context_SDL); CheckOpenGLErrors(); texture::GarbageCollect(); DeleteShader(shader_scene); PrintToLog("INFO: OpenGL garbage collection complete."); } void OnResize(uint32_t width, uint32_t height, photon_window &window){ SDL_GL_MakeCurrent(window.window_SDL, window.context_SDL); PrintToLog("INFO: Resizing window to %ix%i.", width, height); float aspect = (float)width/(float)height; glUseProgram(shader_scene.program); glUniform1f(glGetUniformLocation(shader_scene.program, "aspect"), aspect); glUseProgram(shader_laser.program); glUniform1f(glGetUniformLocation(shader_laser.program, "aspect"), aspect); glUseProgram(shader_light.program); glUniform1f(glGetUniformLocation(shader_light.program, "aspect"), aspect); glUseProgram(shader_fx.program); glUniform1f(glGetUniformLocation(shader_fx.program, "aspect"), aspect); glUseProgram(shader_text.program); glUniform1f(glGetUniformLocation(shader_text.program, "aspect"), aspect); glViewport(0, 0, width, height); window.width = width; window.height = height; glBindTexture(GL_TEXTURE_2D, window.light_buffer_texture); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0); } GLenum CheckOpenGLErrors(){ GLenum err = glGetError(); switch(err){ case GL_INVALID_ENUM: PrintToLog("OPENGL ERROR: Invalid Enum."); break; case GL_INVALID_VALUE: PrintToLog("OPENGL ERROR: Invalid Value."); break; case GL_INVALID_OPERATION: PrintToLog("OPENGL ERROR: Invalid Operation."); break; case GL_INVALID_FRAMEBUFFER_OPERATION: PrintToLog("OPENGL ERROR: Invalid Framebuffer Operation."); break; case GL_OUT_OF_MEMORY: PrintToLog("OPENGL ERROR: Out Of Memory."); break; case GL_NO_ERROR: break; } return err; } void UpdateZoom(const float &zoom){ glUseProgram(shader_scene.program); glUniform1f(glGetUniformLocation(shader_scene.program, "zoom"), 1.0f / zoom); glUseProgram(shader_laser.program); glUniform1f(glGetUniformLocation(shader_laser.program, "zoom"), 1.0f / zoom); glUseProgram(shader_light.program); glUniform1f(glGetUniformLocation(shader_light.program, "zoom"), 1.0f / zoom); glUseProgram(shader_fx.program); glUniform1f(glGetUniformLocation(shader_fx.program, "zoom"), 1.0f / zoom); } void UpdateCenter(const glm::vec2 &center){ glUseProgram(shader_scene.program); glUniform2fv(glGetUniformLocation(shader_scene.program, "center"), 1, glm::value_ptr(center)); glUseProgram(shader_laser.program); glUniform2fv(glGetUniformLocation(shader_laser.program, "center"), 1, glm::value_ptr(center)); glUseProgram(shader_light.program); glUniform2fv(glGetUniformLocation(shader_light.program, "center"), 1, glm::value_ptr(center)); glUseProgram(shader_fx.program); glUniform2fv(glGetUniformLocation(shader_fx.program, "center"), 1, glm::value_ptr(center)); } void DrawModeScene(photon_window &window){ SDL_GL_MakeCurrent(window.window_SDL, window.context_SDL); glBindFramebuffer(GL_FRAMEBUFFER, 0); glClear(GL_COLOR_BUFFER_BIT); glDisable(GL_BLEND); glActiveTexture(PHOTON_TEXTURE_UNIT_LIGHT); glBindTexture(GL_TEXTURE_2D, window.light_buffer_texture); glActiveTexture(PHOTON_TEXTURE_UNIT_COLOR); } void DrawModeLaser(photon_window &window){ SDL_GL_MakeCurrent(window.window_SDL, window.context_SDL); glEnable(GL_BLEND); glBlendFunc(GL_ONE,GL_ONE); glUseProgram(shader_laser.program); } void DrawModeLevel(photon_window &window){ SDL_GL_MakeCurrent(window.window_SDL, window.context_SDL); glBindFramebuffer(GL_FRAMEBUFFER, 0); glEnable(GL_BLEND); glBlendFunc(GL_ONE,GL_ONE_MINUS_SRC_ALPHA); glUseProgram(shader_scene.program); glActiveTexture(PHOTON_TEXTURE_UNIT_LIGHT); glBindTexture(GL_TEXTURE_2D, window.light_buffer_texture); glActiveTexture(PHOTON_TEXTURE_UNIT_COLOR); } void DrawModeLight(photon_window &window){ SDL_GL_MakeCurrent(window.window_SDL, window.context_SDL); glBindFramebuffer(GL_FRAMEBUFFER, window.light_buffer); glClear(GL_COLOR_BUFFER_BIT); glEnable(GL_BLEND); glBlendFunc(GL_ONE,GL_ONE); glUseProgram(shader_light.program); glActiveTexture(PHOTON_TEXTURE_UNIT_LIGHT); glBindTexture(GL_TEXTURE_2D, 0); glActiveTexture(PHOTON_TEXTURE_UNIT_COLOR); } void DrawPhoton(const glm::vec2 &location){ glBindTexture(GL_TEXTURE_2D, photon_texture); SetFacFX(1.0f); static const float verts[] = { 0.2f, 0.2f, -0.2f, 0.2f, -0.2f,-0.2f, 0.2f,-0.2f}; static const float uv[] = {1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f}; opengl::SetModelMatrix(glm::mat3(1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, location.x, location.y, 1.0f)); glVertexAttribPointer(PHOTON_VERTEX_LOCATION_ATTRIBUTE, 2, GL_FLOAT, GL_FALSE, 0, verts); glVertexAttribPointer(PHOTON_VERTEX_UV_ATTRIBUTE, 2, GL_FLOAT, GL_FALSE, 0, uv); glDrawArrays(GL_TRIANGLE_FAN, 0, 4); } void DrawPhotonLight(const glm::vec2 &location){ static const float verts[] = { 16.0f, 16.0f, -16.0f, 16.0f, -16.0f,-16.0f, 16.0f,-16.0f}; static const float uv[] = { 1.0f, 1.0f, -1.0f, 1.0f, -1.0f,-1.0f, 1.0f,-1.0f}; opengl::SetModelMatrix(glm::mat3(1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, location.x, location.y, 1.0f)); glVertexAttribPointer(PHOTON_VERTEX_LOCATION_ATTRIBUTE, 2, GL_FLOAT, GL_FALSE, 0, verts); glVertexAttribPointer(PHOTON_VERTEX_UV_ATTRIBUTE, 2, GL_FLOAT, GL_FALSE, 0, uv); glDrawArrays(GL_TRIANGLE_FAN, 0, 4); } void DrawModeGUI(photon_window &window){ SDL_GL_MakeCurrent(window.window_SDL, window.context_SDL); glBindFramebuffer(GL_FRAMEBUFFER, 0); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA); glUseProgram(shader_text.program); } void SetColorGUI(const glm::vec4 &color){ glUseProgram(shader_text.program); glUniform4fv(glGetUniformLocation(shader_text.program, "color"), 1, glm::value_ptr(color)); } void SetCenterGUI(const glm::vec2 &center){ glUseProgram(shader_text.program); glUniform2fv(glGetUniformLocation(shader_text.program, "center"), 1, glm::value_ptr(center)); } void SetFacFX(const float &fac){ glUniform1f(glGetUniformLocation(shader_fx.program, "fac"), fac); } void SetLaserColor(const glm::vec3 &color){ glUniform3fv(glGetUniformLocation(shader_laser.program, "color"), 1, glm::value_ptr(color)); glUniform3fv(glGetUniformLocation(shader_light.program, "color"), 1, glm::value_ptr(color)); } void SetModelMatrix(const glm::mat3 &matrix){ GLint program = 0; glGetIntegerv(GL_CURRENT_PROGRAM, &program); GLint uniform = glGetUniformLocation(program, "model"); if(uniform > -1){ glUniformMatrix3fv(uniform, 1, GL_FALSE, glm::value_ptr(matrix)); } } void DrawModeFX(photon_window &window){ SDL_GL_MakeCurrent(window.window_SDL, window.context_SDL); glBindFramebuffer(GL_FRAMEBUFFER, 0); glEnable(GL_BLEND); glBlendFunc(GL_ONE,GL_ONE); glUseProgram(shader_fx.program); glActiveTexture(PHOTON_TEXTURE_UNIT_LIGHT); glBindTexture(GL_TEXTURE_2D, 0); glActiveTexture(PHOTON_TEXTURE_UNIT_COLOR); } void DrawBackground(photon_instance &instance){ static const float verts[] = { 1.0f, 1.0f, 1.0f,-1.0f, -1.0f,-1.0f, -1.0f, 1.0f}; static const float uv[] = {1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f}; DrawModeLevel(instance.window); glBindTexture(GL_TEXTURE_2D, background); glm::mat3 matrix(instance.zoom); float aspect = float(instance.window.width) / float(instance.window.height); if(aspect > 1.0f){ matrix *= aspect; }else if(aspect < 1.0f){ matrix /= aspect; } matrix[2] = glm::vec3(instance.player.location, 1.0f); opengl::SetModelMatrix(matrix); glVertexAttribPointer(PHOTON_VERTEX_LOCATION_ATTRIBUTE, 2, GL_FLOAT, GL_FALSE, 0, verts); glVertexAttribPointer(PHOTON_VERTEX_UV_ATTRIBUTE, 2, GL_FLOAT, GL_FALSE, 0, uv); glDrawArrays(GL_TRIANGLE_FAN, 0, 4); DrawModeFX(instance.window); SetFacFX(0.4f); opengl::SetModelMatrix(matrix); glDrawArrays(GL_TRIANGLE_FAN, 0, 4); } } } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: provider.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: abi $ $Date: 2001-06-06 14:48:47 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ /************************************************************************** TODO ************************************************************************** *************************************************************************/ #ifndef _VOS_DIAGNOSE_HXX_ #include <vos/diagnose.hxx> #endif #ifndef _UCBHELPER_CONTENTIDENTIFIER_HXX #include <ucbhelper/contentidentifier.hxx> #endif #ifndef _DATABASES_HXX_ #include <provider/databases.hxx> #endif #ifndef _PROVIDER_HXX #include <provider/provider.hxx> #endif #ifndef _CONTENT_HXX #include <provider/content.hxx> #endif #ifndef _DATABASES_HXX_ #include <provider/databases.hxx> #endif #ifndef COM_SUN_STAR_CONTAINER_XHIERARCHICALNAMEACCESS_HPP_ #include <com/sun/star/container/XHierarchicalNameAccess.hpp> #endif #ifndef _COM_SUN_STAR_FRAME_XCONFIGMANAGER_HPP_ #include <com/sun/star/frame/XConfigManager.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_PROPERTYATTRIBBUTE_HPP_ #include <com/sun/star/beans/PropertyAttribute.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_ #include <com/sun/star/beans/PropertyValue.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_PROPERTYSTATE_HPP_ #include <com/sun/star/beans/PropertyState.hpp> #endif using namespace com::sun::star::frame; using namespace com::sun::star::beans; using namespace com::sun::star::container; using namespace com::sun::star::lang; using namespace com::sun::star::ucb; using namespace com::sun::star::uno; using namespace rtl; using namespace chelp; //========================================================================= //========================================================================= // // ContentProvider Implementation. // //========================================================================= //========================================================================= ContentProvider::ContentProvider( const Reference< XMultiServiceFactory >& rSMgr ) : ::ucb::ContentProviderImplHelper( rSMgr ), isInitialized( false ), m_aScheme( OUString::createFromAscii( MYUCP_URL_SCHEME ) ), m_pDatabases( 0 ) { } //========================================================================= // virtual ContentProvider::~ContentProvider() { delete m_pDatabases; } //========================================================================= // // XInterface methods. // //========================================================================= XINTERFACE_IMPL_3( ContentProvider, XTypeProvider, XServiceInfo, XContentProvider ); //========================================================================= // // XTypeProvider methods. // //========================================================================= XTYPEPROVIDER_IMPL_3( ContentProvider, XTypeProvider, XServiceInfo, XContentProvider ); //========================================================================= // // XServiceInfo methods. // //========================================================================= XSERVICEINFO_IMPL_1( ContentProvider, OUString::createFromAscii( "CHelpContentProvider" ), OUString::createFromAscii( MYUCP_CONTENT_PROVIDER_SERVICE_NAME ) ); //========================================================================= // // Service factory implementation. // //========================================================================= ONE_INSTANCE_SERVICE_FACTORY_IMPL( ContentProvider ); //========================================================================= // // XContentProvider methods. // //========================================================================= // virtual Reference< XContent > SAL_CALL ContentProvider::queryContent( const Reference< XContentIdentifier >& xCanonicId ) throw( IllegalIdentifierException, RuntimeException ) { if ( ! xCanonicId->getContentProviderScheme().equalsIgnoreAsciiCase( m_aScheme ) ) { // Wrong URL-scheme throw IllegalIdentifierException(); } { osl::MutexGuard aGuard( m_aMutex ); if( ! isInitialized ) init(); } if( ! m_pDatabases ) throw RuntimeException(); // Check, if a content with given id already exists... Reference< XContent > xContent = queryExistingContent( xCanonicId ).getBodyPtr(); if ( xContent.is() ) return xContent; xContent = new Content( m_xSMgr,this,xCanonicId,m_pDatabases ); // Further checks if ( !xContent->getIdentifier().is() ) throw IllegalIdentifierException(); return xContent; } void ContentProvider::init() { rtl::OUString sProviderService = rtl::OUString::createFromAscii( "com.sun.star.configuration.ConfigurationProvider" ); // New access to configuration Any aAny; aAny <<= rtl::OUString::createFromAscii( "plugin" ); PropertyValue aProp( rtl::OUString::createFromAscii( "servertype" ), -1, aAny, PropertyState_DIRECT_VALUE ); Sequence< Any > seq(1); seq[0] <<= aProp; Reference< XMultiServiceFactory > sProvider( m_xSMgr->createInstanceWithArguments( sProviderService,seq ), UNO_QUERY ); rtl::OUString sReaderService = rtl::OUString::createFromAscii( "com.sun.star.configuration.ConfigurationAccess" ); seq[0] <<= rtl::OUString::createFromAscii( "org.openoffice.Office.Common" ); Reference< XHierarchicalNameAccess > xHierAccess( sProvider->createInstanceWithArguments( sReaderService,seq ),UNO_QUERY ); aAny = xHierAccess->getByHierarchicalName( rtl::OUString::createFromAscii("Path/Current/Help") ); rtl::OUString instPath; if( ! ( aAny >>= instPath ) ) ; else instPath = rtl::OUString::createFromAscii( "$(instpath)/help" ); Reference< XConfigManager > xCfgMgr( m_xSMgr->createInstance( rtl::OUString::createFromAscii( "com.sun.star.config.SpecialConfigManager" ) ), UNO_QUERY ); VOS_ENSURE( xCfgMgr.is(), "HelpProvider::init - No Config Manager!" ); if( xCfgMgr.is() ) instPath = xCfgMgr->substituteVariables( instPath ); m_pDatabases = new Databases( instPath,m_xSMgr ); isInitialized = true; } <commit_msg>now only runtime exception if configuration can't be instantiated<commit_after>/************************************************************************* * * $RCSfile: provider.cxx,v $ * * $Revision: 1.6 $ * * last change: $Author: abi $ $Date: 2001-07-06 13:32:50 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ /************************************************************************** TODO ************************************************************************** *************************************************************************/ #ifndef _VOS_DIAGNOSE_HXX_ #include <vos/diagnose.hxx> #endif #ifndef _UCBHELPER_CONTENTIDENTIFIER_HXX #include <ucbhelper/contentidentifier.hxx> #endif #ifndef _DATABASES_HXX_ #include <provider/databases.hxx> #endif #ifndef _PROVIDER_HXX #include <provider/provider.hxx> #endif #ifndef _CONTENT_HXX #include <provider/content.hxx> #endif #ifndef _DATABASES_HXX_ #include <provider/databases.hxx> #endif #ifndef COM_SUN_STAR_CONTAINER_XHIERARCHICALNAMEACCESS_HPP_ #include <com/sun/star/container/XHierarchicalNameAccess.hpp> #endif #ifndef _COM_SUN_STAR_FRAME_XCONFIGMANAGER_HPP_ #include <com/sun/star/frame/XConfigManager.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_PROPERTYATTRIBBUTE_HPP_ #include <com/sun/star/beans/PropertyAttribute.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_ #include <com/sun/star/beans/PropertyValue.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_PROPERTYSTATE_HPP_ #include <com/sun/star/beans/PropertyState.hpp> #endif using namespace com::sun::star::frame; using namespace com::sun::star::beans; using namespace com::sun::star::container; using namespace com::sun::star::lang; using namespace com::sun::star::ucb; using namespace com::sun::star::uno; using namespace rtl; using namespace chelp; //========================================================================= //========================================================================= // // ContentProvider Implementation. // //========================================================================= //========================================================================= ContentProvider::ContentProvider( const Reference< XMultiServiceFactory >& rSMgr ) : ::ucb::ContentProviderImplHelper( rSMgr ), isInitialized( false ), m_aScheme( OUString::createFromAscii( MYUCP_URL_SCHEME ) ), m_pDatabases( 0 ) { } //========================================================================= // virtual ContentProvider::~ContentProvider() { delete m_pDatabases; } //========================================================================= // // XInterface methods. // //========================================================================= XINTERFACE_IMPL_3( ContentProvider, XTypeProvider, XServiceInfo, XContentProvider ); //========================================================================= // // XTypeProvider methods. // //========================================================================= XTYPEPROVIDER_IMPL_3( ContentProvider, XTypeProvider, XServiceInfo, XContentProvider ); //========================================================================= // // XServiceInfo methods. // //========================================================================= XSERVICEINFO_IMPL_1( ContentProvider, OUString::createFromAscii( "CHelpContentProvider" ), OUString::createFromAscii( MYUCP_CONTENT_PROVIDER_SERVICE_NAME ) ); //========================================================================= // // Service factory implementation. // //========================================================================= ONE_INSTANCE_SERVICE_FACTORY_IMPL( ContentProvider ); //========================================================================= // // XContentProvider methods. // //========================================================================= // virtual Reference< XContent > SAL_CALL ContentProvider::queryContent( const Reference< XContentIdentifier >& xCanonicId ) throw( IllegalIdentifierException, RuntimeException ) { if ( ! xCanonicId->getContentProviderScheme().equalsIgnoreAsciiCase( m_aScheme ) ) { // Wrong URL-scheme throw IllegalIdentifierException(); } { osl::MutexGuard aGuard( m_aMutex ); if( ! isInitialized ) init(); } if( ! m_pDatabases ) throw RuntimeException(); // Check, if a content with given id already exists... Reference< XContent > xContent = queryExistingContent( xCanonicId ).getBodyPtr(); if ( xContent.is() ) return xContent; xContent = new Content( m_xSMgr,this,xCanonicId,m_pDatabases ); // Further checks if ( !xContent->getIdentifier().is() ) throw IllegalIdentifierException(); return xContent; } void ContentProvider::init() { isInitialized = true; rtl::OUString sProviderService = rtl::OUString::createFromAscii( "com.sun.star.configuration.ConfigurationProvider" ); Any aAny; aAny <<= rtl::OUString::createFromAscii( "local" ); PropertyValue aProp( rtl::OUString::createFromAscii( "servertype" ), -1, aAny, PropertyState_DIRECT_VALUE ); Sequence< Any > seq(1); seq[0] <<= aProp; Reference< XMultiServiceFactory > sProvider; try { sProvider = Reference< XMultiServiceFactory >( m_xSMgr->createInstanceWithArguments( sProviderService,seq ), UNO_QUERY ); } catch( const com::sun::star::uno::Exception& e ) { VOS_ENSHURE( sProvider.is()," cant instantiate the multiservicefactory " ); } if( ! sProvider.is() ) { return; } rtl::OUString sReaderService = rtl::OUString::createFromAscii( "com.sun.star.configuration.ConfigurationAccess" ); seq[0] <<= rtl::OUString::createFromAscii( "org.openoffice.Office.Common" ); Reference< XHierarchicalNameAccess > xHierAccess; try { xHierAccess = Reference< XHierarchicalNameAccess > ( sProvider->createInstanceWithArguments( sReaderService,seq ), UNO_QUERY ); } catch( const com::sun::star::uno::Exception& e ) { VOS_ENSHURE( xHierAccess.is()," cant instantiate the reader service " ); } if( ! xHierAccess.is() ) return; try { aAny = xHierAccess->getByHierarchicalName( rtl::OUString::createFromAscii("Path/Current/Help") ); } catch( const com::sun::star::container::NoSuchElementException& e ) { VOS_ENSHURE( false," path to help files could not be determined " ); return; } rtl::OUString instPath; bool err = ! ( aAny >>= instPath ); if( err ) { VOS_ENSHURE( false," path to help files could not be determined " ); return; } instPath = rtl::OUString::createFromAscii( "$(instpath)/help" ); Reference< XConfigManager > xCfgMgr; try { xCfgMgr = Reference< XConfigManager >( m_xSMgr->createInstance( rtl::OUString::createFromAscii( "com.sun.star.config.SpecialConfigManager" ) ), UNO_QUERY ); } catch( const com::sun::star::uno::Exception& e ) { VOS_ENSHURE( xCfgMgr.is()," cant instantiate the special config manager " ); } if( ! xCfgMgr.is() ) return; instPath = xCfgMgr->substituteVariables( instPath ); m_pDatabases = new Databases( instPath,m_xSMgr ); } <|endoftext|>
<commit_before>/* Copyright (c) 2010 - 2021 Advanced Micro Devices, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME #define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER #define AMD_PLATFORM_BUILD_NUMBER 3475 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER #define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO #define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING \ XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO #define AMD_PLATFORM_INFO \ "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \ "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <commit_msg>SWDEV-2 - Change OpenCL version number from 3475 to 3476<commit_after>/* Copyright (c) 2010 - 2021 Advanced Micro Devices, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME #define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER #define AMD_PLATFORM_BUILD_NUMBER 3476 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER #define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO #define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING \ XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO #define AMD_PLATFORM_INFO \ "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \ "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <|endoftext|>
<commit_before>/* Copyright (c) 2010 - 2021 Advanced Micro Devices, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME #define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER #define AMD_PLATFORM_BUILD_NUMBER 3477 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER #define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO #define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING \ XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO #define AMD_PLATFORM_INFO \ "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \ "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <commit_msg>SWDEV-2 - Change OpenCL version number from 3477 to 3478<commit_after>/* Copyright (c) 2010 - 2021 Advanced Micro Devices, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME #define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER #define AMD_PLATFORM_BUILD_NUMBER 3478 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER #define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO #define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING \ XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO #define AMD_PLATFORM_INFO \ "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \ "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <|endoftext|>
<commit_before>/* Copyright (c) 2010 - 2021 Advanced Micro Devices, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME #define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER #define AMD_PLATFORM_BUILD_NUMBER 3501 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER #define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO #define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING \ XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO #define AMD_PLATFORM_INFO \ "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \ "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <commit_msg>SWDEV-2 - Change OpenCL version number from 3501 to 3502<commit_after>/* Copyright (c) 2010 - 2021 Advanced Micro Devices, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME #define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER #define AMD_PLATFORM_BUILD_NUMBER 3502 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER #define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO #define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING \ XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO #define AMD_PLATFORM_INFO \ "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \ "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <|endoftext|>
<commit_before>/* Copyright (c) 2010-present Advanced Micro Devices, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME #define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER #define AMD_PLATFORM_BUILD_NUMBER 3166 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER #define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO #define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING \ XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO #define AMD_PLATFORM_INFO \ "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \ "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <commit_msg>SWDEV-2 - Change OpenCL version number from 3166 to 3167<commit_after>/* Copyright (c) 2010-present Advanced Micro Devices, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME #define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER #define AMD_PLATFORM_BUILD_NUMBER 3167 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER #define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO #define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING \ XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO #define AMD_PLATFORM_INFO \ "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \ "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <|endoftext|>
<commit_before>/* * copyright (c) 2017 Matthew Oliver * * This file is part of ShiftMediaProject. * * ShiftMediaProject 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. * * ShiftMediaProject 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 ShiftMediaProject; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "projectGenerator.h" #include <algorithm> #include <utility> bool ProjectGenerator::findSourceFile(const string & sFile, const string & sExtension, string & sRetFileName) { string sFileName; sRetFileName = m_sProjectDir + sFile + sExtension; if (!findFile(sRetFileName, sFileName)) { // Check if this is a built file uint uiSPos = m_sProjectDir.rfind('/', m_sProjectDir.length() - 2); uiSPos = (uiSPos == string::npos) ? 0 : uiSPos + 1; string sProjectName = m_sProjectDir.substr(uiSPos); sProjectName = (m_sProjectDir.compare("./") != 0) ? sProjectName : ""; sRetFileName = m_ConfigHelper.m_sSolutionDirectory + sProjectName + sFile + sExtension; if (!findFile(sRetFileName, sFileName)) { // Check if this file already includes the project folder in its name if(sFile.find(sProjectName) != string::npos) { sRetFileName = m_sProjectDir + sFile.substr(sFile.find(sProjectName) + sProjectName.length()) + sExtension; return findFile(sRetFileName, sFileName); } return false; } } return true; } bool ProjectGenerator::findSourceFiles(const string & sFile, const string & sExtension, vector<string> & vRetFiles) { string sFileName = m_sProjectDir + sFile + sExtension; return findFiles(sFileName, vRetFiles); } bool ProjectGenerator::checkProjectFiles() { //Check that all headers are correct for (StaticList::iterator itIt = m_vHIncludes.begin(); itIt != m_vHIncludes.end(); itIt++) { string sRetFileName; if (!findSourceFile(*itIt, ".h", sRetFileName)) { outputError("Could not find input header file for object (" + *itIt + ")"); return false; } //Update the entry with the found file with complete path m_ConfigHelper.makeFileProjectRelative(sRetFileName, *itIt); } //Check that all C Source are correct for (StaticList::iterator itIt = m_vCIncludes.begin(); itIt != m_vCIncludes.end(); itIt++) { string sRetFileName; if (!findSourceFile(*itIt, ".c", sRetFileName)) { outputError("Could not find input C source file for object (" + *itIt + ")"); return false; } //Update the entry with the found file with complete path m_ConfigHelper.makeFileProjectRelative(sRetFileName, *itIt); } //Check that all CPP Source are correct for (StaticList::iterator itIt = m_vCPPIncludes.begin(); itIt != m_vCPPIncludes.end(); itIt++) { string sRetFileName; if (!findSourceFile(*itIt, ".cpp", sRetFileName)) { outputError("Could not find input C++ source file for object (" + *itIt + ")"); return false; } //Update the entry with the found file with complete path m_ConfigHelper.makeFileProjectRelative(sRetFileName, *itIt); } //Check that all ASM Source are correct for (StaticList::iterator itIt = m_vASMIncludes.begin(); itIt != m_vASMIncludes.end(); itIt++) { string sRetFileName; if (!findSourceFile(*itIt, ".asm", sRetFileName)) { outputError("Could not find input ASM source file for object (" + *itIt + ")"); return false; } //Update the entry with the found file with complete path m_ConfigHelper.makeFileProjectRelative(sRetFileName, *itIt); } //Check the output Unknown Includes and find there corresponding file if (!findProjectFiles(m_vIncludes, m_vCIncludes, m_vCPPIncludes, m_vASMIncludes, m_vHIncludes)) { return false; } if (m_ConfigHelper.m_bDCEOnly) { //Don't need to check for replace files return true; } //Check all source files associated with replaced config values StaticList vReplaceIncludes, vReplaceCPPIncludes, vReplaceCIncludes, vReplaceASMIncludes; for (UnknownList::iterator itIt = m_mReplaceIncludes.begin(); itIt != m_mReplaceIncludes.end(); itIt++) { vReplaceIncludes.push_back(itIt->first); } if (!findProjectFiles(vReplaceIncludes, vReplaceCIncludes, vReplaceCPPIncludes, vReplaceASMIncludes, m_vHIncludes)) { return false; } else { //Need to create local files for any replace objects if (!createReplaceFiles(vReplaceCIncludes, m_vCIncludes)) { return false; } if (!createReplaceFiles(vReplaceCPPIncludes, m_vCPPIncludes)) { return false; } if (!createReplaceFiles(vReplaceASMIncludes, m_vASMIncludes)) { return false; } } return true; } bool ProjectGenerator::createReplaceFiles(const StaticList& vReplaceIncludes, StaticList& vExistingIncludes) { for (StaticList::const_iterator itIt = vReplaceIncludes.cbegin(); itIt != vReplaceIncludes.cend(); itIt++) { //Check hasnt already been included as a fixed object if (find(vExistingIncludes.begin(), vExistingIncludes.end(), *itIt) != vExistingIncludes.end()) { //skip this item continue; } //Convert file to format required to search ReplaceIncludes uint uiExtPos = itIt->rfind('.'); uint uiCutPos = itIt->rfind('/') + 1; string sFilename = itIt->substr(uiCutPos, uiExtPos - uiCutPos); string sExtension = itIt->substr(uiExtPos); //Get the files dynamic config requirement string sIdents; for (StaticList::iterator itIdents = m_mReplaceIncludes[sFilename].begin(); itIdents < m_mReplaceIncludes[sFilename].end(); itIdents++) { sIdents += *itIdents; if ((itIdents + 1) < m_mReplaceIncludes[sFilename].end()) { sIdents += " || "; } } //Create new file to wrap input object string sPrettyFile = "../" + *itIt; string sNewFile = getCopywriteHeader(sFilename + sExtension + " file wrapper for " + m_sProjectName); sNewFile += "\n\ \n\ #include \"config.h\"\n\ #if " + sIdents + "\n\ # include \"" + sPrettyFile + "\"\n\ #endif"; //Write output project if (!makeDirectory(m_ConfigHelper.m_sSolutionDirectory + m_sProjectName)) { outputError("Failed creating local " + m_sProjectName + " directory"); return false; } string sOutFile = m_ConfigHelper.m_sSolutionDirectory + m_sProjectName + "/" + sFilename + "_wrap" + sExtension; if (!writeToFile(sOutFile, sNewFile)) { return false; } //Add the new file to list of objects m_ConfigHelper.makeFileProjectRelative(sOutFile, sOutFile); vExistingIncludes.push_back(sOutFile); } return true; } bool ProjectGenerator::findProjectFiles(const StaticList& vIncludes, StaticList& vCIncludes, StaticList& vCPPIncludes, StaticList& vASMIncludes, StaticList& vHIncludes) { for (StaticList::const_iterator itIt = vIncludes.cbegin(); itIt != vIncludes.cend(); itIt++) { string sRetFileName; if (findSourceFile(*itIt, ".c", sRetFileName)) { //Found a C File to include if (find(vCIncludes.begin(), vCIncludes.end(), sRetFileName) != vCIncludes.end()) { //skip this item continue; } m_ConfigHelper.makeFileProjectRelative(sRetFileName, sRetFileName); vCIncludes.push_back(sRetFileName); } else if (findSourceFile(*itIt, ".cpp", sRetFileName)) { //Found a C++ File to include if (find(vCPPIncludes.begin(), vCPPIncludes.end(), sRetFileName) != vCPPIncludes.end()) { //skip this item continue; } m_ConfigHelper.makeFileProjectRelative(sRetFileName, sRetFileName); vCPPIncludes.push_back(sRetFileName); } else if (findSourceFile(*itIt, ".asm", sRetFileName)) { //Found a ASM File to include if (find(vASMIncludes.begin(), vASMIncludes.end(), sRetFileName) != vASMIncludes.end()) { //skip this item continue; } m_ConfigHelper.makeFileProjectRelative(sRetFileName, sRetFileName); vASMIncludes.push_back(sRetFileName); } else if (findSourceFile(*itIt, ".h", sRetFileName)) { //Found a H File to include if (find(vHIncludes.begin(), vHIncludes.end(), sRetFileName) != vHIncludes.end()) { //skip this item continue; } m_ConfigHelper.makeFileProjectRelative(sRetFileName, sRetFileName); vHIncludes.push_back(sRetFileName); } else { outputError("Could not find valid source file for object (" + *itIt + ")"); return false; } } return true; }<commit_msg>Check that replace "wrap" file hasnt been added multiple times to project.<commit_after>/* * copyright (c) 2017 Matthew Oliver * * This file is part of ShiftMediaProject. * * ShiftMediaProject 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. * * ShiftMediaProject 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 ShiftMediaProject; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "projectGenerator.h" #include <algorithm> #include <utility> bool ProjectGenerator::findSourceFile(const string & sFile, const string & sExtension, string & sRetFileName) { string sFileName; sRetFileName = m_sProjectDir + sFile + sExtension; if (!findFile(sRetFileName, sFileName)) { // Check if this is a built file uint uiSPos = m_sProjectDir.rfind('/', m_sProjectDir.length() - 2); uiSPos = (uiSPos == string::npos) ? 0 : uiSPos + 1; string sProjectName = m_sProjectDir.substr(uiSPos); sProjectName = (m_sProjectDir.compare("./") != 0) ? sProjectName : ""; sRetFileName = m_ConfigHelper.m_sSolutionDirectory + sProjectName + sFile + sExtension; if (!findFile(sRetFileName, sFileName)) { // Check if this file already includes the project folder in its name if(sFile.find(sProjectName) != string::npos) { sRetFileName = m_sProjectDir + sFile.substr(sFile.find(sProjectName) + sProjectName.length()) + sExtension; return findFile(sRetFileName, sFileName); } return false; } } return true; } bool ProjectGenerator::findSourceFiles(const string & sFile, const string & sExtension, vector<string> & vRetFiles) { string sFileName = m_sProjectDir + sFile + sExtension; return findFiles(sFileName, vRetFiles); } bool ProjectGenerator::checkProjectFiles() { //Check that all headers are correct for (StaticList::iterator itIt = m_vHIncludes.begin(); itIt != m_vHIncludes.end(); itIt++) { string sRetFileName; if (!findSourceFile(*itIt, ".h", sRetFileName)) { outputError("Could not find input header file for object (" + *itIt + ")"); return false; } //Update the entry with the found file with complete path m_ConfigHelper.makeFileProjectRelative(sRetFileName, *itIt); } //Check that all C Source are correct for (StaticList::iterator itIt = m_vCIncludes.begin(); itIt != m_vCIncludes.end(); itIt++) { string sRetFileName; if (!findSourceFile(*itIt, ".c", sRetFileName)) { outputError("Could not find input C source file for object (" + *itIt + ")"); return false; } //Update the entry with the found file with complete path m_ConfigHelper.makeFileProjectRelative(sRetFileName, *itIt); } //Check that all CPP Source are correct for (StaticList::iterator itIt = m_vCPPIncludes.begin(); itIt != m_vCPPIncludes.end(); itIt++) { string sRetFileName; if (!findSourceFile(*itIt, ".cpp", sRetFileName)) { outputError("Could not find input C++ source file for object (" + *itIt + ")"); return false; } //Update the entry with the found file with complete path m_ConfigHelper.makeFileProjectRelative(sRetFileName, *itIt); } //Check that all ASM Source are correct for (StaticList::iterator itIt = m_vASMIncludes.begin(); itIt != m_vASMIncludes.end(); itIt++) { string sRetFileName; if (!findSourceFile(*itIt, ".asm", sRetFileName)) { outputError("Could not find input ASM source file for object (" + *itIt + ")"); return false; } //Update the entry with the found file with complete path m_ConfigHelper.makeFileProjectRelative(sRetFileName, *itIt); } //Check the output Unknown Includes and find there corresponding file if (!findProjectFiles(m_vIncludes, m_vCIncludes, m_vCPPIncludes, m_vASMIncludes, m_vHIncludes)) { return false; } if (m_ConfigHelper.m_bDCEOnly) { //Don't need to check for replace files return true; } //Check all source files associated with replaced config values StaticList vReplaceIncludes, vReplaceCPPIncludes, vReplaceCIncludes, vReplaceASMIncludes; for (UnknownList::iterator itIt = m_mReplaceIncludes.begin(); itIt != m_mReplaceIncludes.end(); itIt++) { vReplaceIncludes.push_back(itIt->first); } if (!findProjectFiles(vReplaceIncludes, vReplaceCIncludes, vReplaceCPPIncludes, vReplaceASMIncludes, m_vHIncludes)) { return false; } else { //Need to create local files for any replace objects if (!createReplaceFiles(vReplaceCIncludes, m_vCIncludes)) { return false; } if (!createReplaceFiles(vReplaceCPPIncludes, m_vCPPIncludes)) { return false; } if (!createReplaceFiles(vReplaceASMIncludes, m_vASMIncludes)) { return false; } } return true; } bool ProjectGenerator::createReplaceFiles(const StaticList& vReplaceIncludes, StaticList& vExistingIncludes) { for (StaticList::const_iterator itIt = vReplaceIncludes.cbegin(); itIt != vReplaceIncludes.cend(); itIt++) { //Check hasnt already been included as a fixed object if (find(vExistingIncludes.begin(), vExistingIncludes.end(), *itIt) != vExistingIncludes.end()) { //skip this item continue; } //Convert file to format required to search ReplaceIncludes uint uiExtPos = itIt->rfind('.'); uint uiCutPos = itIt->rfind('/') + 1; string sFilename = itIt->substr(uiCutPos, uiExtPos - uiCutPos); string sExtension = itIt->substr(uiExtPos); string sOutFile = m_ConfigHelper.m_sSolutionDirectory + m_sProjectName + "/" + sFilename + "_wrap" + sExtension; string sNewOutFile; m_ConfigHelper.makeFileProjectRelative(sOutFile, sNewOutFile); // Check hasnt already been included as a wrapped object if (find(vExistingIncludes.begin(), vExistingIncludes.end(), sNewOutFile) != vExistingIncludes.end()) { // skip this item outputInfo(sNewOutFile); continue; } //Get the files dynamic config requirement string sIdents; for (StaticList::iterator itIdents = m_mReplaceIncludes[sFilename].begin(); itIdents < m_mReplaceIncludes[sFilename].end(); itIdents++) { sIdents += *itIdents; if ((itIdents + 1) < m_mReplaceIncludes[sFilename].end()) { sIdents += " || "; } } //Create new file to wrap input object string sPrettyFile = "../" + *itIt; string sNewFile = getCopywriteHeader(sFilename + sExtension + " file wrapper for " + m_sProjectName); sNewFile += "\n\ \n\ #include \"config.h\"\n\ #if " + sIdents + "\n\ # include \"" + sPrettyFile + "\"\n\ #endif"; //Write output project if (!makeDirectory(m_ConfigHelper.m_sSolutionDirectory + m_sProjectName)) { outputError("Failed creating local " + m_sProjectName + " directory"); return false; } if (!writeToFile(sOutFile, sNewFile)) { return false; } //Add the new file to list of objects vExistingIncludes.push_back(sNewOutFile); } return true; } bool ProjectGenerator::findProjectFiles(const StaticList& vIncludes, StaticList& vCIncludes, StaticList& vCPPIncludes, StaticList& vASMIncludes, StaticList& vHIncludes) { for (StaticList::const_iterator itIt = vIncludes.cbegin(); itIt != vIncludes.cend(); itIt++) { string sRetFileName; if (findSourceFile(*itIt, ".c", sRetFileName)) { //Found a C File to include if (find(vCIncludes.begin(), vCIncludes.end(), sRetFileName) != vCIncludes.end()) { //skip this item continue; } m_ConfigHelper.makeFileProjectRelative(sRetFileName, sRetFileName); vCIncludes.push_back(sRetFileName); } else if (findSourceFile(*itIt, ".cpp", sRetFileName)) { //Found a C++ File to include if (find(vCPPIncludes.begin(), vCPPIncludes.end(), sRetFileName) != vCPPIncludes.end()) { //skip this item continue; } m_ConfigHelper.makeFileProjectRelative(sRetFileName, sRetFileName); vCPPIncludes.push_back(sRetFileName); } else if (findSourceFile(*itIt, ".asm", sRetFileName)) { //Found a ASM File to include if (find(vASMIncludes.begin(), vASMIncludes.end(), sRetFileName) != vASMIncludes.end()) { //skip this item continue; } m_ConfigHelper.makeFileProjectRelative(sRetFileName, sRetFileName); vASMIncludes.push_back(sRetFileName); } else if (findSourceFile(*itIt, ".h", sRetFileName)) { //Found a H File to include if (find(vHIncludes.begin(), vHIncludes.end(), sRetFileName) != vHIncludes.end()) { //skip this item continue; } m_ConfigHelper.makeFileProjectRelative(sRetFileName, sRetFileName); vHIncludes.push_back(sRetFileName); } else { outputError("Could not find valid source file for object (" + *itIt + ")"); return false; } } return true; }<|endoftext|>
<commit_before>/*************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (testabilitydriver@nokia.com) ** ** This file is part of Testability Driver Qt Agent ** ** If you have questions regarding the use of this file, please contact ** Nokia at testabilitydriver@nokia.com . ** ** 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 ** and appearing in the file LICENSE.LGPL included in the packaging ** of this file. ** ****************************************************************************/ #include <QDebug> #include <QProcess> #include <QCoreApplication> #include <taslogger.h> #include <tascoreutils.h> #include <tasdatashare.h> #include "tasdeviceutils.h" #include "tasclientmanager.h" #include "startappservice.h" #if (defined(Q_OS_WIN32) || defined(Q_OS_WINCE)) #include <windows.h> #elif (defined(Q_OS_UNIX) || defined(Q_OS_WS_MAC)) #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <QSharedMemory> #endif const char* const SET_PARAMS_ONLY = "set_params_only"; const char* const DETACH_MODE = "detached"; const char* const NO_WAIT = "noWait"; StartAppService::StartAppService() {} StartAppService::~StartAppService() {} bool StartAppService::executeService(TasCommandModel& model, TasResponse& response) { if(model.service() == serviceName() ){ // Turn screen on. TasDeviceUtils::resetInactivity(); TasCommand* command = getCommandParameters(model, "Run"); if(command){ startApplication(*command, response); } else{ TasLogger::logger()->error("StartAppService::executeService no Run command found!"); response.setErrorMessage("Could not parse Run command from the request!"); } return true; } else{ return false; } } /*! Attempts to start a process using the application path send in the command model. */ void StartAppService::startApplication(TasCommand& command, TasResponse& response) { QString applicationPath = command.parameter("application_path"); QString args = command.parameter("arguments"); QString envs = command.parameter("environment"); TasLogger::logger()->debug(QString("TasServer::startApplication: '%1'").arg(applicationPath)); TasLogger::logger()->debug(QString("TasServer::startApplication: Arguments: '%1'").arg(args)); TasLogger::logger()->debug(QString("TasServer::startApplication: Environment: '%1'").arg(envs)); QStringList arguments = args.split(","); QStringList environmentVars = envs.split(" "); setRuntimeParams(command); if(arguments.contains(SET_PARAMS_ONLY)){ // do not start app, just need to set the parameters response.requester()->sendResponse(response.messageId(), QString("0")); } else{ arguments.removeAll(DETACH_MODE); arguments.removeAll(NO_WAIT); launchDetached(applicationPath, arguments, environmentVars, response); } } void StartAppService::setRuntimeParams(TasCommand& command) { QString applicationPath = command.parameter("application_path"); QString eventList = command.parameter("events_to_listen"); QString signalList = command.parameter("signals_to_listen"); TasLogger::logger()->debug("StartAppService::setRuntimeParams signals: " + signalList); if(!eventList.isEmpty() || !signalList.isEmpty()){ TasSharedData startupData(eventList.split(","), signalList.split(",")); QString identifier = TasCoreUtils::parseExecutable(applicationPath); if(!TasClientManager::instance()->writeStartupData(identifier, startupData)){ TasLogger::logger()->error("StartAppService::setRuntimeParams could not set run time params for identifier: " + identifier + "!"); } else { TasLogger::logger()->error("StartAppService::setRuntimeParams set with identifier: " + identifier); } } } QHash<QString, QString> StartAppService::parseEnvironmentVariables(const QString& env) { QHash<QString,QString> vars; QStringList var = env.split(" "); foreach(QString str, var) { QStringList key = str.split("="); if (key.size() == 2) { vars[key.at(0)] = key.at(1); } } return vars; } #ifdef Q_OS_SYMBIAN //Qt startDetach seems to leak memory so need to do it for now. //to be removed when fix in qt static void qt_create_symbian_commandline( const QStringList &arguments, const QString &nativeArguments, QString &commandLine) { for (int i = 0; i < arguments.size(); ++i) { QString tmp = arguments.at(i); tmp.replace(QLatin1String("\\\""), QLatin1String("\\\\\"")); tmp.replace(QLatin1String("\""), QLatin1String("\\\"")); if (tmp.isEmpty() || tmp.contains(QLatin1Char(' ')) || tmp.contains(QLatin1Char('\t'))) { QString endQuote(QLatin1String("\"")); int i = tmp.length(); while (i > 0 && tmp.at(i - 1) == QLatin1Char('\\')) { --i; endQuote += QLatin1String("\\"); } commandLine += QLatin1String("\"") + tmp.left(i) + endQuote + QLatin1Char(' '); } else { commandLine += tmp + QLatin1Char(' '); } } if (!nativeArguments.isEmpty()) commandLine += nativeArguments; else if (!commandLine.isEmpty()) // Chop the extra trailing space if any arguments were appended commandLine.chop(1); } #endif void StartAppService::launchDetached(const QString& applicationPath, const QStringList& arguments, const QStringList& environmentVars, TasResponse& response) { #ifdef Q_OS_SYMBIAN //Qt startDetach seems to leak memory so need to do it for now. //to be removed when fix in qt qint64 pid; QString commandLine; QString nativeArguments; qt_create_symbian_commandline(arguments, nativeArguments, commandLine); TPtrC program_ptr(reinterpret_cast<const TText*>(applicationPath.constData())); TPtrC cmdline_ptr(reinterpret_cast<const TText*>(commandLine.constData())); RProcess process; if( process.Create(program_ptr, cmdline_ptr) == KErrNone){ process.Resume(); pid = process.Id().Id(); process.Close(); TasClientManager::instance()->addStartedApp(applicationPath, QDateTime::currentDateTime().toString("yyyyMMddhhmmsszzz")); response.setData(QString::number(pid)); } #elif (defined(Q_OS_WIN32) || defined(Q_OS_WINCE)) STARTUPINFO si; PROCESS_INFORMATION pi; ZeroMemory( &si, sizeof(si) ); si.cb = sizeof(si); ZeroMemory( &pi, sizeof(pi) ); // Arguments QString argv = applicationPath + " " + arguments.join(" "); // Environment bloc variable QStringList envList = QProcess::systemEnvironment() << environmentVars; WCHAR* envp = (WCHAR*)malloc((envList.join(" ").length() + 2) * sizeof(WCHAR)); // just counting memory in cluding the NULL (\0) string ends and binal NULL block end LPTSTR env = (LPTSTR) envp; for (int i = 0; i < envList.length(); i++) { env = lstrcpy( env, (LPTSTR) envList[i].utf16() ); env += lstrlen( (LPTSTR) envList[i].utf16() ) +1; } *env = (WCHAR) NULL; // DEBUG // LPTSTR lpszVariable = envp; // while (*lpszVariable) //while not null // { // TasLogger::logger()->debug( QString("TasServer::launchDetached: ENV: %1").arg(QString::fromUtf16((ushort *) lpszVariable)) ); // lpszVariable += lstrlen(lpszVariable) + 1; // } // Start the child process. if( CreateProcess( NULL, // No module name (use command line) (WCHAR *) argv.utf16(), // Command line NULL, // Process handle not inheritable NULL, // Thread handle not inheritable FALSE, // Set handle inheritance to FALSE CREATE_UNICODE_ENVIRONMENT, // 0 for no creation flags (LPVOID) envp, // Use parent's environment block NULL, // Use parent's starting directory &si, // Pointer to STARTUPINFO structure &pi ) // Pointer to PROCESS_INFORMATION structure ) { QString pid = QString::number(pi.dwProcessId); CloseHandle( pi.hProcess ); CloseHandle( pi.hThread ); TasLogger::logger()->debug( QString("TasServer::launchDetached: Child PID: %1").arg(pid) ); response.setData(pid); } #elif (defined(Q_OS_UNIX) || defined(Q_OS_WS_MAC)) pid_t pid, sid, grandpid; /////int pidPipeDesc[2]; /////qt_safe_pipe(pidPipeDesc); // Using shared memory pro IPC instead of qt pipes to avoid using private qt libraries. QSharedMemory mem("pid_mem"); if ( !mem.create(sizeof(pid_t)) ) { TasLogger::logger()->debug(QString("TasServer::startApplication: SharedMem ERROR: ").arg(mem.errorString())); } mem.lock(); pid_t *mem_ptr = (pid_t *) mem.data(); *mem_ptr = 0; mem.unlock(); // Create Arguments ARRAY (application path to executable on first element) QStringList paramList; paramList << applicationPath; paramList << arguments; char **paramListArray = new char*[ paramList.length() + 1 ]; for( int i = 0; i < paramList.length(); i++) { QByteArray variable = ((QString) paramList[i]).toLocal8Bit(); char *const variablePtr = new char[variable.length() + 1]; strcpy(variablePtr, variable.data()); paramListArray[i] = variablePtr; } paramListArray[paramList.length()] = NULL; // Create environment Array with NULL end element QStringList envList = QProcess::systemEnvironment() << environmentVars; //TasLogger::logger()->debug(QString("TasServer::startApplipidPipeDesccation: ALL '%1'").arg(envList.join(","))); //TasLogger::logger()->debug(QString("TasServer::startApplication: USER '%1'").arg(environmentVars.join(","))); char **envListArray = new char*[ envList.length() + 1 ]; for( int i = 0; i < envList.length(); i++) { QByteArray variable = ((QString) envList[i]).toLocal8Bit(); char *const variablePtr = new char[variable.length() + 1]; strcpy(variablePtr, variable.data()); envListArray[i] = variablePtr; } envListArray[envList.length()] = NULL; // START MAKING CHILDREN HERE :D // Child if ( (pid = fork()) == 0) { // We are only going to write on the pipe for papa /////qt_safe_close(pidPipeDesc[0]); // Create new session for the process (detatch from parent process group) sid = setsid(); if ( sid < 0 ) { TasLogger::logger()->error( QString("TasServer::launchDetached:Failed to detach child.")); exit(1); } // Grandchild if ( ( grandpid = fork() ) == 0 ) { // detach ont he grandchild. mem.detach(); // Try see if we don't need path execve( paramListArray[0], paramListArray, envListArray); // Try also on all path directories if above fails const QString path = QString::fromLocal8Bit(::getenv("PATH")); const QString file = QString::fromLocal8Bit(paramListArray[0]); if (!path.isEmpty()) { QStringList pathEntries = path.split(QLatin1Char(':')); for (int k = 0; k < pathEntries.size(); ++k) { QByteArray tmp = QFile::encodeName(pathEntries.at(k)); if (!tmp.endsWith('/')) tmp += '/'; tmp += QFile::encodeName(file); paramListArray[0] = tmp.data(); TasLogger::logger()->error( QString("TasServer::launchDetached: PATH = '%1'").arg((char *) paramListArray[0])); execve( paramListArray[0], paramListArray, envListArray); } } TasLogger::logger()->error( QString("TasServer::launchDetached: Granhild process died straight away.")); } // Child exit in order to end detachment of grandchild else if( grandpid > 0) { /////qt_safe_write(pidPipeDesc[1], &grandpid, sizeof(pid_t)); /////qt_safe_close(pidPipeDesc[1]); QSharedMemory mem("pid_mem"); mem.attach(); mem.lock(); pid_t *mem_ptr = (pid_t *) mem.data(); *mem_ptr = grandpid; mem.unlock(); mem.detach(); _exit(0); } else { // if child fork fails detach mem and kill child // TODO Return with error? mem.detach(); _exit(0); } } // Parent else if (pid > 0) { // We are only going to read from the pipe from child /////qt_safe_close(pidPipeDesc[1]); pid_t actualpid = 0; /////qt_safe_read(pidPipeDesc[0], &actualpid, sizeof(pid_t)); /////qt_safe_close(pidPipeDesc[0]); while(!actualpid) { mem.lock(); pid_t *mem_ptr = (pid_t *) mem.data(); actualpid = *mem_ptr; mem.unlock(); TasLogger::logger()->debug( QString("TasServer::launchDetached: ACTUAL Child PID: %1").arg((int)actualpid) ); //TODO? add counter to break free if error on fork() } mem.detach(); pid = actualpid; // Free memory for (int i = 0; i < paramList.length(); i++ ) { delete [] paramListArray[i]; } delete [] paramListArray; for (int i = 0; i < envList.length(); i++ ) { delete [] envListArray[i]; } delete [] envListArray; TasLogger::logger()->debug( QString("TasServer::launchDetached: Child PID: %1").arg((int)pid) ); response.setData(QString::number((int) pid)); } #else qint64 pid; if(QProcess::startDetached(applicationPath, arguments, ".", &pid)){ TasClientManager::instance()->addStartedApp(applicationPath, QDateTime::currentDateTime().toString("yyyyMMddhhmmsszzz")); response.setData(QString::number(pid)); } #endif else{ #if (defined(Q_OS_UNIX) || defined(Q_OS_WS_MAC)) && !defined(Q_OS_SYMBIAN) // if parent fork fails, clear mem and send error mem.detach(); #endif TasLogger::logger()->error("TasServer::launchDetached: Could not start the application " + applicationPath); response.setErrorMessage("Could not start the application " + applicationPath); } #if (defined(Q_OS_WIN32) || defined(Q_OS_WINCE)) free(envp); #endif } <commit_msg>Modified error handling on startappservice for linux<commit_after>/*************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (testabilitydriver@nokia.com) ** ** This file is part of Testability Driver Qt Agent ** ** If you have questions regarding the use of this file, please contact ** Nokia at testabilitydriver@nokia.com . ** ** 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 ** and appearing in the file LICENSE.LGPL included in the packaging ** of this file. ** ****************************************************************************/ #include <QDebug> #include <QProcess> #include <QCoreApplication> #include <taslogger.h> #include <tascoreutils.h> #include <tasdatashare.h> #include "tasdeviceutils.h" #include "tasclientmanager.h" #include "startappservice.h" #if (defined(Q_OS_WIN32) || defined(Q_OS_WINCE)) #include <windows.h> #elif (defined(Q_OS_UNIX) || defined(Q_OS_WS_MAC)) #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <QSharedMemory> #endif const char* const SET_PARAMS_ONLY = "set_params_only"; const char* const DETACH_MODE = "detached"; const char* const NO_WAIT = "noWait"; StartAppService::StartAppService() {} StartAppService::~StartAppService() {} bool StartAppService::executeService(TasCommandModel& model, TasResponse& response) { if(model.service() == serviceName() ){ // Turn screen on. TasDeviceUtils::resetInactivity(); TasCommand* command = getCommandParameters(model, "Run"); if(command){ startApplication(*command, response); } else{ TasLogger::logger()->error("StartAppService::executeService no Run command found!"); response.setErrorMessage("Could not parse Run command from the request!"); } return true; } else{ return false; } } /*! Attempts to start a process using the application path send in the command model. */ void StartAppService::startApplication(TasCommand& command, TasResponse& response) { QString applicationPath = command.parameter("application_path"); QString args = command.parameter("arguments"); QString envs = command.parameter("environment"); TasLogger::logger()->debug(QString("TasServer::startApplication: '%1'").arg(applicationPath)); TasLogger::logger()->debug(QString("TasServer::startApplication: Arguments: '%1'").arg(args)); TasLogger::logger()->debug(QString("TasServer::startApplication: Environment: '%1'").arg(envs)); QStringList arguments = args.split(","); QStringList environmentVars = envs.split(" "); setRuntimeParams(command); if(arguments.contains(SET_PARAMS_ONLY)){ // do not start app, just need to set the parameters response.requester()->sendResponse(response.messageId(), QString("0")); } else{ arguments.removeAll(DETACH_MODE); arguments.removeAll(NO_WAIT); launchDetached(applicationPath, arguments, environmentVars, response); } } void StartAppService::setRuntimeParams(TasCommand& command) { QString applicationPath = command.parameter("application_path"); QString eventList = command.parameter("events_to_listen"); QString signalList = command.parameter("signals_to_listen"); TasLogger::logger()->debug("StartAppService::setRuntimeParams signals: " + signalList); if(!eventList.isEmpty() || !signalList.isEmpty()){ TasSharedData startupData(eventList.split(","), signalList.split(",")); QString identifier = TasCoreUtils::parseExecutable(applicationPath); if(!TasClientManager::instance()->writeStartupData(identifier, startupData)){ TasLogger::logger()->error("StartAppService::setRuntimeParams could not set run time params for identifier: " + identifier + "!"); } else { TasLogger::logger()->error("StartAppService::setRuntimeParams set with identifier: " + identifier); } } } QHash<QString, QString> StartAppService::parseEnvironmentVariables(const QString& env) { QHash<QString,QString> vars; QStringList var = env.split(" "); foreach(QString str, var) { QStringList key = str.split("="); if (key.size() == 2) { vars[key.at(0)] = key.at(1); } } return vars; } #ifdef Q_OS_SYMBIAN //Qt startDetach seems to leak memory so need to do it for now. //to be removed when fix in qt static void qt_create_symbian_commandline( const QStringList &arguments, const QString &nativeArguments, QString &commandLine) { for (int i = 0; i < arguments.size(); ++i) { QString tmp = arguments.at(i); tmp.replace(QLatin1String("\\\""), QLatin1String("\\\\\"")); tmp.replace(QLatin1String("\""), QLatin1String("\\\"")); if (tmp.isEmpty() || tmp.contains(QLatin1Char(' ')) || tmp.contains(QLatin1Char('\t'))) { QString endQuote(QLatin1String("\"")); int i = tmp.length(); while (i > 0 && tmp.at(i - 1) == QLatin1Char('\\')) { --i; endQuote += QLatin1String("\\"); } commandLine += QLatin1String("\"") + tmp.left(i) + endQuote + QLatin1Char(' '); } else { commandLine += tmp + QLatin1Char(' '); } } if (!nativeArguments.isEmpty()) commandLine += nativeArguments; else if (!commandLine.isEmpty()) // Chop the extra trailing space if any arguments were appended commandLine.chop(1); } #endif void StartAppService::launchDetached(const QString& applicationPath, const QStringList& arguments, const QStringList& environmentVars, TasResponse& response) { #ifdef Q_OS_SYMBIAN //Qt startDetach seems to leak memory so need to do it for now. //to be removed when fix in qt qint64 pid; QString commandLine; QString nativeArguments; qt_create_symbian_commandline(arguments, nativeArguments, commandLine); TPtrC program_ptr(reinterpret_cast<const TText*>(applicationPath.constData())); TPtrC cmdline_ptr(reinterpret_cast<const TText*>(commandLine.constData())); RProcess process; if( process.Create(program_ptr, cmdline_ptr) == KErrNone){ process.Resume(); pid = process.Id().Id(); process.Close(); TasClientManager::instance()->addStartedApp(applicationPath, QDateTime::currentDateTime().toString("yyyyMMddhhmmsszzz")); response.setData(QString::number(pid)); } #elif (defined(Q_OS_WIN32) || defined(Q_OS_WINCE)) STARTUPINFO si; PROCESS_INFORMATION pi; ZeroMemory( &si, sizeof(si) ); si.cb = sizeof(si); ZeroMemory( &pi, sizeof(pi) ); // Arguments QString argv = applicationPath + " " + arguments.join(" "); // Environment bloc variable QStringList envList = QProcess::systemEnvironment() << environmentVars; WCHAR* envp = (WCHAR*)malloc((envList.join(" ").length() + 2) * sizeof(WCHAR)); // just counting memory in cluding the NULL (\0) string ends and binal NULL block end LPTSTR env = (LPTSTR) envp; for (int i = 0; i < envList.length(); i++) { env = lstrcpy( env, (LPTSTR) envList[i].utf16() ); env += lstrlen( (LPTSTR) envList[i].utf16() ) +1; } *env = (WCHAR) NULL; // DEBUG // LPTSTR lpszVariable = envp; // while (*lpszVariable) //while not null // { // TasLogger::logger()->debug( QString("TasServer::launchDetached: ENV: %1").arg(QString::fromUtf16((ushort *) lpszVariable)) ); // lpszVariable += lstrlen(lpszVariable) + 1; // } // Start the child process. if( CreateProcess( NULL, // No module name (use command line) (WCHAR *) argv.utf16(), // Command line NULL, // Process handle not inheritable NULL, // Thread handle not inheritable FALSE, // Set handle inheritance to FALSE CREATE_UNICODE_ENVIRONMENT, // 0 for no creation flags (LPVOID) envp, // Use parent's environment block NULL, // Use parent's starting directory &si, // Pointer to STARTUPINFO structure &pi ) // Pointer to PROCESS_INFORMATION structure ) { QString pid = QString::number(pi.dwProcessId); CloseHandle( pi.hProcess ); CloseHandle( pi.hThread ); TasLogger::logger()->debug( QString("TasServer::launchDetached: Child PID: %1").arg(pid) ); response.setData(pid); } #elif (defined(Q_OS_UNIX) || defined(Q_OS_WS_MAC)) pid_t pid, sid, grandpid; // Create Arguments ARRAY (application path to executable on first element) QStringList paramList; paramList << applicationPath; paramList << arguments; char **paramListArray = new char*[ paramList.length() + 1 ]; for( int i = 0; i < paramList.length(); i++) { QByteArray variable = ((QString) paramList[i]).toLocal8Bit(); char *const variablePtr = new char[variable.length() + 1]; strcpy(variablePtr, variable.data()); paramListArray[i] = variablePtr; } paramListArray[paramList.length()] = NULL; // Create environment Array with NULL end element QStringList envList = QProcess::systemEnvironment() << environmentVars; char **envListArray = new char*[ envList.length() + 1 ]; for( int i = 0; i < envList.length(); i++) { QByteArray variable = ((QString) envList[i]).toLocal8Bit(); char *const variablePtr = new char[variable.length() + 1]; strcpy(variablePtr, variable.data()); envListArray[i] = variablePtr; } envListArray[envList.length()] = NULL; /////int pidPipeDesc[2]; /////qt_safe_pipe(pidPipeDesc); // Using shared memory pro IPC instead of qt pipes to avoid using private qt libraries. QSharedMemory mem("pid_mem"); if ( mem.create(sizeof(pid_t)) ) { mem.lock(); pid_t *mem_ptr = (pid_t *) mem.data(); *mem_ptr = 0; mem.unlock(); // START MAKING CHILDREN HERE :D // Child if ( (pid = fork()) == 0) { // We are only going to write on the pipe for papa /////qt_safe_close(pidPipeDesc[0]); // Create new session for the process (detatch from parent process group) sid = setsid(); if ( sid < 0 ) { TasLogger::logger()->error( QString("TasServer::launchDetached:Failed to detach child.")); exit(1); } // Grandchild if ( ( grandpid = fork() ) == 0 ) { // detach ont he grandchild. mem.detach(); // Try see if we don't need path execve( paramListArray[0], paramListArray, envListArray); // Try also on all path directories if above fails const QString path = QString::fromLocal8Bit(::getenv("PATH")); const QString file = QString::fromLocal8Bit(paramListArray[0]); if (!path.isEmpty()) { QStringList pathEntries = path.split(QLatin1Char(':')); for (int k = 0; k < pathEntries.size(); ++k) { QByteArray tmp = QFile::encodeName(pathEntries.at(k)); if (!tmp.endsWith('/')) tmp += '/'; tmp += QFile::encodeName(file); paramListArray[0] = tmp.data(); TasLogger::logger()->error( QString("TasServer::launchDetached: PATH = '%1'").arg((char *) paramListArray[0])); execve( paramListArray[0], paramListArray, envListArray); } } TasLogger::logger()->error( QString("TasServer::launchDetached: Granhild process died straight away.")); } // Child exit in order to end detachment of grandchild else if( grandpid > 0) { /////qt_safe_write(pidPipeDesc[1], &grandpid, sizeof(pid_t)); /////qt_safe_close(pidPipeDesc[1]); QSharedMemory mem("pid_mem"); mem.attach(); mem.lock(); pid_t *mem_ptr = (pid_t *) mem.data(); *mem_ptr = grandpid; mem.unlock(); mem.detach(); _exit(0); } else { // if child fork fails detach mem and kill child // TODO Return with error? mem.detach(); _exit(0); } } // Parent else if (pid > 0) { // We are only going to read from the pipe from child /////qt_safe_close(pidPipeDesc[1]); pid_t actualpid = 0; /////qt_safe_read(pidPipeDesc[0], &actualpid, sizeof(pid_t)); /////qt_safe_close(pidPipeDesc[0]); while(!actualpid) { mem.lock(); pid_t *mem_ptr = (pid_t *) mem.data(); actualpid = *mem_ptr; mem.unlock(); TasLogger::logger()->debug( QString("TasServer::launchDetached: ACTUAL Child PID: %1").arg((int)actualpid) ); //TODO? add counter to break free if error on fork() } mem.detach(); pid = actualpid; // Free memory for (int i = 0; i < paramList.length(); i++ ) { delete [] paramListArray[i]; } delete [] paramListArray; for (int i = 0; i < envList.length(); i++ ) { delete [] envListArray[i]; } delete [] envListArray; TasLogger::logger()->debug( QString("TasServer::launchDetached: Child PID: %1").arg((int)pid) ); response.setData(QString::number((int) pid)); } else { //fails, clear mem and send error mem.detach(); TasLogger::logger()->error("TasServer::launchDetached: Could not start the application " + applicationPath); response.setErrorMessage("Could not start the application " + applicationPath); } } #else qint64 pid; if(QProcess::startDetached(applicationPath, arguments, ".", &pid)){ TasClientManager::instance()->addStartedApp(applicationPath, QDateTime::currentDateTime().toString("yyyyMMddhhmmsszzz")); response.setData(QString::number(pid)); } #endif else{ #if (defined(Q_OS_UNIX) || defined(Q_OS_WS_MAC)) && !defined(Q_OS_SYMBIAN) // if parent fork fails, clear mem and send error mem.detach(); TasLogger::logger()->debug(QString("TasServer::startApplication: SharedMem ERROR: ").arg(mem.errorString())); #endif TasLogger::logger()->error("TasServer::launchDetached: Could not start the application " + applicationPath); response.setErrorMessage("Could not start the application " + applicationPath); } #if (defined(Q_OS_WIN32) || defined(Q_OS_WINCE)) free(envp); #endif } <|endoftext|>
<commit_before>/** * light_scan_sim test_ray_cast.cpp * @brief Test simulating laser rays on an image. * * @copyright 2017 Joseph Duchesne * @author Joseph Duchesne */ #include "light_scan_sim/ray_cast.h" #include <gtest/gtest.h> #include <opencv2/core/core.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/highgui/highgui.hpp> // The fixture for testing class RayCast class RayCastTest : public ::testing::Test {}; TEST_F(RayCastTest, TestTest) { RayCast rc; cv::Point start, end, hit; // Set up the raycast with a very simple map cv::Mat mat = cv::Mat::zeros(20, 20, CV_8UC1); cv::rectangle( mat, cv::Point( 10, 0 ), cv::Point( 20, 20), 255, CV_FILLED); rc.SetMap(mat, 1.0); // Test tracing from empty space into wall start = cv::Point(5,5); end = cv::Point(15,5); EXPECT_TRUE(rc.Trace(start, end, hit)); EXPECT_NEAR(hit.x, 10, 1e-5); EXPECT_NEAR(hit.y, 5, 1e-5); // Test tracing out of map into empty space start = cv::Point(5,5); end = cv::Point(-5,5); EXPECT_FALSE(rc.Trace(start, end, hit)); } int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <commit_msg>added RayCast.Scan unit test<commit_after>/** * light_scan_sim test_ray_cast.cpp * @brief Test simulating laser rays on an image. * * @copyright 2017 Joseph Duchesne * @author Joseph Duchesne */ #include "light_scan_sim/ray_cast.h" #include <gtest/gtest.h> #include <opencv2/core/core.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <sensor_msgs/LaserScan.h> // The fixture for testing class RayCast class RayCastTest : public ::testing::Test {}; TEST_F(RayCastTest, TraceTest) { RayCast rc; cv::Point start, end, hit; // Set up the raycast with a very simple map cv::Mat mat = cv::Mat::zeros(20, 20, CV_8UC1); cv::rectangle( mat, cv::Point( 10, 0 ), cv::Point( 20, 20), 255, CV_FILLED); rc.SetMap(mat, 1.0); // Test tracing from empty space into wall start = cv::Point(5,5); end = cv::Point(15,5); EXPECT_TRUE(rc.Trace(start, end, hit)); EXPECT_NEAR(hit.x, 10, 1e-5); EXPECT_NEAR(hit.y, 5, 1e-5); // Test tracing out of map into empty space start = cv::Point(5,5); end = cv::Point(-5,5); EXPECT_FALSE(rc.Trace(start, end, hit)); } TEST_F(RayCastTest, ScanTest) { RayCast rc(0, 50, -M_PI_2, M_PI_2, M_PI_2, 0); cv::Point start(5,5); // Set up the raycast with a very simple map cv::Mat mat = cv::Mat::zeros(20, 20, CV_8UC1); cv::rectangle( mat, cv::Point( 15, 0 ), cv::Point( 20, 20), 255, CV_FILLED); cv::rectangle( mat, cv::Point( 0, 17 ), cv::Point( 20, 20), 255, CV_FILLED); rc.SetMap(mat, 2.0); // 2.0m per pixel // Test tracing from empty space into wall sensor_msgs::LaserScan s = rc.Scan(start, M_PI_2); // Scan angled up // General properties EXPECT_NEAR(s.angle_min, -M_PI_2, 1e-5); EXPECT_EQ(3, s.ranges.size()); // Right wall EXPECT_NEAR(s.ranges[0], 20.0, 1e-5); // 20m to right wall EXPECT_NEAR(s.ranges[1], 24.0, 1e-5); // 24m to top wall EXPECT_NEAR(s.ranges[2], 51.0, 1e-5); // max range + 1m for no return } int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <|endoftext|>
<commit_before>#include <algorithm> #include <istream> #include <sstream> #include "parsers/parse_error.hh" #include "parsers/tina.hh" #include "pn/arc.hh" namespace pnmc { namespace parsers { /*------------------------------------------------------------------------------------------------*/ /*------------------------------------------------------------------------------------------------*/ std::pair<std::string, unsigned int> place_valuation(const std::string& s) { const auto star_cit = std::find(s.cbegin(), s.cend(), '*'); if (star_cit == s.cend()) { return std::make_pair(s, 1); } try { const auto valuation = std::stoi(std::string(star_cit + 1, s.cend())); return std::make_pair(std::string(s.cbegin(), star_cit), valuation); } catch (const std::invalid_argument&) { throw parse_error("Valuation '" + std::string(star_cit + 1, s.cend()) + "' is not a value"); } } /*------------------------------------------------------------------------------------------------*/ unsigned int marking(const std::string& s) { if (*s.cbegin() == '(' and *std::prev(s.cend()) == ')') { try { return std::stoi(std::string(std::next(s.cbegin()), std::prev(s.cend()))); } catch (const std::invalid_argument&) { throw parse_error( "Marking '" + std::string(std::next(s.cbegin()), std::prev(s.cend())) + "' is not a value"); } } else { throw parse_error("Invalid marking format: " + s); } } /*------------------------------------------------------------------------------------------------*/ std::shared_ptr<pn::net> tina(std::istream& in) { std::shared_ptr<pn::net> net_ptr = std::make_shared<pn::net>(); auto& net = *net_ptr; try { std::string line, s0, s1, s2; line.reserve(1024); while (std::getline(in, line)) { std::istringstream ss(line); // Empty line or comment. if (((ss >> std::ws).peek() == '#') or not (ss >> s0)) { continue; } // Net if (s0 == "net") { continue; } // Transitions else if (s0 == "tr") { std::string place_id; unsigned int valuation; if (ss >> s0) { net.add_transition(s0, ""); } else { throw parse_error("Invalid transition: " + line); } // Skip time interval, if any. const auto c = (ss >> std::ws).peek(); if (c == '[' or c == ']') { ss >> s1; } while (ss >> s1) { if (s1 == "->") { break; } std::tie(place_id, valuation) = place_valuation(s1); net.add_pre_place(s0, place_id, pn::arc(valuation)); } while (ss >> s1) { std::tie(place_id, valuation) = place_valuation(s1); net.add_post_place(s0, place_id, pn::arc(valuation)); } } // Places else if (s0 == "pl") { if (ss >> s1 >> s2) { net.add_place(s1, "", marking(s2)); } else { throw parse_error("Invalid place: " + line); } } // Error. else { throw parse_error("Invalid line: " + line); } } } catch (const parse_error& p) { std::cerr << p.what() << std::endl; return nullptr; } return net_ptr; } /*------------------------------------------------------------------------------------------------*/ }} // namespace pnmc::parsers <commit_msg>Check that ‘->’ is present in a TINA transition.<commit_after>#include <algorithm> #include <istream> #include <sstream> #include "parsers/parse_error.hh" #include "parsers/tina.hh" #include "pn/arc.hh" namespace pnmc { namespace parsers { /*------------------------------------------------------------------------------------------------*/ /*------------------------------------------------------------------------------------------------*/ std::pair<std::string, unsigned int> place_valuation(const std::string& s) { const auto star_cit = std::find(s.cbegin(), s.cend(), '*'); if (star_cit == s.cend()) { return std::make_pair(s, 1); } try { const auto valuation = std::stoi(std::string(star_cit + 1, s.cend())); return std::make_pair(std::string(s.cbegin(), star_cit), valuation); } catch (const std::invalid_argument&) { throw parse_error("Valuation '" + std::string(star_cit + 1, s.cend()) + "' is not a value"); } } /*------------------------------------------------------------------------------------------------*/ unsigned int marking(const std::string& s) { if (*s.cbegin() == '(' and *std::prev(s.cend()) == ')') { try { return std::stoi(std::string(std::next(s.cbegin()), std::prev(s.cend()))); } catch (const std::invalid_argument&) { throw parse_error( "Marking '" + std::string(std::next(s.cbegin()), std::prev(s.cend())) + "' is not a value"); } } else { throw parse_error("Invalid marking format: " + s); } } /*------------------------------------------------------------------------------------------------*/ std::shared_ptr<pn::net> tina(std::istream& in) { std::shared_ptr<pn::net> net_ptr = std::make_shared<pn::net>(); auto& net = *net_ptr; try { std::string line, s0, s1, s2; line.reserve(1024); while (std::getline(in, line)) { std::istringstream ss(line); // Empty line or comment. if (((ss >> std::ws).peek() == '#') or not (ss >> s0)) { continue; } // Net if (s0 == "net") { continue; } // Transitions else if (s0 == "tr") { std::string place_id; unsigned int valuation; if (ss >> s0) { net.add_transition(s0, ""); } else { throw parse_error("Invalid transition: " + line); } // Skip time interval, if any. const auto c = (ss >> std::ws).peek(); if (c == '[' or c == ']') { ss >> s1; } bool found_arrow = false; while (ss >> s1) { if (s1 == "->") { found_arrow = true; break; } std::tie(place_id, valuation) = place_valuation(s1); net.add_pre_place(s0, place_id, pn::arc(valuation)); } if (not found_arrow) { throw parse_error("Invalid transition (missing '->'): " + line); } while (ss >> s1) { std::tie(place_id, valuation) = place_valuation(s1); net.add_post_place(s0, place_id, pn::arc(valuation)); } } // Places else if (s0 == "pl") { if (ss >> s1 >> s2) { net.add_place(s1, "", marking(s2)); } else { throw parse_error("Invalid place: " + line); } } // Error. else { throw parse_error("Invalid line: " + line); } } } catch (const parse_error& p) { std::cerr << p.what() << std::endl; return nullptr; } return net_ptr; } /*------------------------------------------------------------------------------------------------*/ }} // namespace pnmc::parsers <|endoftext|>
<commit_before>#include "parsing/utf8.hpp" #include <string> #include <string.h> #include "rdb_protocol/datum_string.hpp" namespace utf8 { static unsigned int HIGH_BIT = 0x80; static unsigned int HIGH_TWO_BITS = 0xC0; static unsigned int HIGH_THREE_BITS = 0xE0; static unsigned int HIGH_FOUR_BITS = 0xF0; static unsigned int HIGH_FIVE_BITS = 0xF8; inline bool is_standalone(char c) { // 0xxxxxxx - ASCII character return (c & HIGH_BIT) == 0; } inline bool is_twobyte_start(char c) { // 110xxxxx - two character multibyte return (c & HIGH_THREE_BITS) == HIGH_TWO_BITS; } inline bool is_threebyte_start(char c) { // 1110xxxx - three character multibyte return (c & HIGH_FOUR_BITS) == HIGH_THREE_BITS; } inline bool is_fourbyte_start(char c) { // 11110xxx - four character multibyte return (c & HIGH_FIVE_BITS) == HIGH_FOUR_BITS; } inline bool is_continuation(char c) { // 10xxxxxx - continuation character return ((c & HIGH_TWO_BITS) == HIGH_BIT); } inline unsigned int extract_bits(char c, unsigned int bits) { return ((c & ~bits) & 0xFF); } inline unsigned int continuation_data(char c) { return extract_bits(c, HIGH_TWO_BITS); } inline unsigned int extract_and_shift(char c, unsigned int bits, unsigned int amount) { return extract_bits(c, bits) << amount; } template <class Iterator> inline bool check_continuation(const Iterator &p, const Iterator &end, size_t position, reason_t *reason) { if (p == end) { reason->position = position; reason->explanation = "Expected continuation byte, saw end of string"; return false; } if (!is_continuation(*p)) { reason->position = position; reason->explanation = "Expected continuation byte, saw something else"; return false; } return true; } template <class Iterator> inline bool is_valid_internal(const Iterator &begin, const Iterator &end, reason_t *reason) { Iterator p = begin; size_t position = 0; while (p != end) { if (is_standalone(*p)) { // 0xxxxxxx - ASCII character // don't need to do anything } else if (is_twobyte_start(*p)) { // 110xxxxx - two character multibyte unsigned int result = extract_and_shift(*p, HIGH_THREE_BITS, 6); ++p; ++position; if (!check_continuation(p, end, position, reason)) return false; result |= continuation_data(*p); if (result < 0x0080) { // can be represented in one byte, so using two is illegal reason->position = position; reason->explanation = "Overlong encoding seen"; return false; } } else if (is_threebyte_start(*p)) { // 1110xxxx - three character multibyte unsigned int result = extract_and_shift(*p, HIGH_FOUR_BITS, 12); ++p; ++position; if (!check_continuation(p, end, position, reason)) return false; result |= continuation_data(*p) << 6; ++p; ++position; if (!check_continuation(p, end, position, reason)) return false; result |= continuation_data(*p); if (result < 0x0800) { // can be represented in two bytes, so using three is illegal reason->position = position; reason->explanation = "Overlong encoding seen"; return false; } } else if (is_fourbyte_start(*p)) { // 11110xxx - four character multibyte unsigned int result = extract_and_shift(*p, HIGH_FIVE_BITS, 18); ++p; ++position; if (!check_continuation(p, end, position, reason)) return false; result |= continuation_data(*p) << 12; ++p; ++position; if (!check_continuation(p, end, position, reason)) return false; result |= continuation_data(*p) << 6; ++p; ++position; if (!check_continuation(p, end, position, reason)) return false; result |= continuation_data(*p); if (result < 0x10000) { // can be represented in three bytes, so using four is illegal reason->position = position; reason->explanation = "Overlong encoding seen"; return false; } if (result > 0x10FFFF) { // UTF-8 defined by RFC 3629 to end at U+10FFFF now reason->position = position; reason->explanation = "Non-Unicode character encoded (beyond U+10FFFF)"; return false; } } else { // high bit character outside of a surrogate context reason->position = position; reason->explanation = "Invalid initial byte seen"; return false; } ++p; ++position; } return true; } bool is_valid(const datum_string_t &str) { reason_t reason; return is_valid_internal(str.data(), str.data() + str.size(), &reason); } bool is_valid(const std::string &str) { reason_t reason; return is_valid_internal(str.begin(), str.end(), &reason); } bool is_valid(const char *start, const char *end) { reason_t reason; return is_valid_internal(start, end, &reason); } bool is_valid(const char *str) { reason_t reason; size_t len = strlen(str); const char *end = str + len; return is_valid_internal(str, end, &reason); } bool is_valid(const datum_string_t &str, reason_t *reason) { return is_valid_internal(str.data(), str.data() + str.size(), reason); } bool is_valid(const std::string &str, reason_t *reason) { return is_valid_internal(str.begin(), str.end(), reason); } bool is_valid(const char *start, const char *end, reason_t *reason) { return is_valid_internal(start, end, reason); } bool is_valid(const char *str, reason_t *reason) { size_t len = strlen(str); const char *end = str + len; return is_valid_internal(str, end, reason); } }; <commit_msg>Add namespace comment.<commit_after>#include "parsing/utf8.hpp" #include <string> #include <string.h> #include "rdb_protocol/datum_string.hpp" namespace utf8 { static unsigned int HIGH_BIT = 0x80; static unsigned int HIGH_TWO_BITS = 0xC0; static unsigned int HIGH_THREE_BITS = 0xE0; static unsigned int HIGH_FOUR_BITS = 0xF0; static unsigned int HIGH_FIVE_BITS = 0xF8; inline bool is_standalone(char c) { // 0xxxxxxx - ASCII character return (c & HIGH_BIT) == 0; } inline bool is_twobyte_start(char c) { // 110xxxxx - two character multibyte return (c & HIGH_THREE_BITS) == HIGH_TWO_BITS; } inline bool is_threebyte_start(char c) { // 1110xxxx - three character multibyte return (c & HIGH_FOUR_BITS) == HIGH_THREE_BITS; } inline bool is_fourbyte_start(char c) { // 11110xxx - four character multibyte return (c & HIGH_FIVE_BITS) == HIGH_FOUR_BITS; } inline bool is_continuation(char c) { // 10xxxxxx - continuation character return ((c & HIGH_TWO_BITS) == HIGH_BIT); } inline unsigned int extract_bits(char c, unsigned int bits) { return ((c & ~bits) & 0xFF); } inline unsigned int continuation_data(char c) { return extract_bits(c, HIGH_TWO_BITS); } inline unsigned int extract_and_shift(char c, unsigned int bits, unsigned int amount) { return extract_bits(c, bits) << amount; } template <class Iterator> inline bool check_continuation(const Iterator &p, const Iterator &end, size_t position, reason_t *reason) { if (p == end) { reason->position = position; reason->explanation = "Expected continuation byte, saw end of string"; return false; } if (!is_continuation(*p)) { reason->position = position; reason->explanation = "Expected continuation byte, saw something else"; return false; } return true; } template <class Iterator> inline bool is_valid_internal(const Iterator &begin, const Iterator &end, reason_t *reason) { Iterator p = begin; size_t position = 0; while (p != end) { if (is_standalone(*p)) { // 0xxxxxxx - ASCII character // don't need to do anything } else if (is_twobyte_start(*p)) { // 110xxxxx - two character multibyte unsigned int result = extract_and_shift(*p, HIGH_THREE_BITS, 6); ++p; ++position; if (!check_continuation(p, end, position, reason)) return false; result |= continuation_data(*p); if (result < 0x0080) { // can be represented in one byte, so using two is illegal reason->position = position; reason->explanation = "Overlong encoding seen"; return false; } } else if (is_threebyte_start(*p)) { // 1110xxxx - three character multibyte unsigned int result = extract_and_shift(*p, HIGH_FOUR_BITS, 12); ++p; ++position; if (!check_continuation(p, end, position, reason)) return false; result |= continuation_data(*p) << 6; ++p; ++position; if (!check_continuation(p, end, position, reason)) return false; result |= continuation_data(*p); if (result < 0x0800) { // can be represented in two bytes, so using three is illegal reason->position = position; reason->explanation = "Overlong encoding seen"; return false; } } else if (is_fourbyte_start(*p)) { // 11110xxx - four character multibyte unsigned int result = extract_and_shift(*p, HIGH_FIVE_BITS, 18); ++p; ++position; if (!check_continuation(p, end, position, reason)) return false; result |= continuation_data(*p) << 12; ++p; ++position; if (!check_continuation(p, end, position, reason)) return false; result |= continuation_data(*p) << 6; ++p; ++position; if (!check_continuation(p, end, position, reason)) return false; result |= continuation_data(*p); if (result < 0x10000) { // can be represented in three bytes, so using four is illegal reason->position = position; reason->explanation = "Overlong encoding seen"; return false; } if (result > 0x10FFFF) { // UTF-8 defined by RFC 3629 to end at U+10FFFF now reason->position = position; reason->explanation = "Non-Unicode character encoded (beyond U+10FFFF)"; return false; } } else { // high bit character outside of a surrogate context reason->position = position; reason->explanation = "Invalid initial byte seen"; return false; } ++p; ++position; } return true; } bool is_valid(const datum_string_t &str) { reason_t reason; return is_valid_internal(str.data(), str.data() + str.size(), &reason); } bool is_valid(const std::string &str) { reason_t reason; return is_valid_internal(str.begin(), str.end(), &reason); } bool is_valid(const char *start, const char *end) { reason_t reason; return is_valid_internal(start, end, &reason); } bool is_valid(const char *str) { reason_t reason; size_t len = strlen(str); const char *end = str + len; return is_valid_internal(str, end, &reason); } bool is_valid(const datum_string_t &str, reason_t *reason) { return is_valid_internal(str.data(), str.data() + str.size(), reason); } bool is_valid(const std::string &str, reason_t *reason) { return is_valid_internal(str.begin(), str.end(), reason); } bool is_valid(const char *start, const char *end, reason_t *reason) { return is_valid_internal(start, end, reason); } bool is_valid(const char *str, reason_t *reason) { size_t len = strlen(str); const char *end = str + len; return is_valid_internal(str, end, reason); } } // namespace utf8 <|endoftext|>
<commit_before>/*************************************************************************** * mng/mng.h * * Part of the STXXL. See http://stxxl.sourceforge.net * * Copyright (C) 2002-2004 Roman Dementiev <dementiev@mpi-sb.mpg.de> * Copyright (C) 2008 Andreas Beckmann <beckmann@cs.uni-frankfurt.de> * * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE_1_0.txt or copy at * http://www.boost.org/LICENSE_1_0.txt) **************************************************************************/ #include <stxxl/mng> #include <stxxl/bits/io/io.h> #include <stxxl/bits/version.h> __STXXL_BEGIN_NAMESPACE void DiskAllocator::dump() { int64 total = 0; sortseq::const_iterator cur = free_space.begin(); STXXL_ERRMSG("Free regions dump:"); for ( ; cur != free_space.end(); ++cur) { STXXL_ERRMSG("Free chunk: begin: " << (cur->first) << " size: " << (cur->second)); total += cur->second; } STXXL_ERRMSG("Total bytes: " << total); } void config::init(const char * config_path) { logger::get_instance(); STXXL_MSG(get_version_string()); std::vector<DiskEntry> flash_props; std::ifstream cfg_file(config_path); if (!cfg_file) { STXXL_ERRMSG("Warning: no config file found."); STXXL_ERRMSG("Using default disk configuration."); #ifndef BOOST_MSVC DiskEntry entry1 = { "/var/tmp/stxxl", "syscall", 1000 * 1024 * 1024, true }; #else DiskEntry entry1 = { "", "wincall", 1000 * 1024 * 1024, true }; char * tmpstr = new char[255]; stxxl_check_ne_0(GetTempPath(255, tmpstr), resource_error); entry1.path = tmpstr; entry1.path += "stxxl"; delete[] tmpstr; #endif #if 0 DiskEntry entry2 = { "/tmp/stxxl1", "mmap", 100 * 1024 * 1024, true }; DiskEntry entry3 = { "/tmp/stxxl2", "simdisk", 1000 * 1024 * 1024, false }; #endif disks_props.push_back(entry1); //disks_props.push_back(entry2); //disks_props.push_back(entry3); } else { std::string line; while (cfg_file >> line) { std::vector<std::string> tmp = split(line, "="); bool is_disk; if (tmp[0][0] == '#') { } else if ((is_disk = (tmp[0] == "disk")) || tmp[0] == "flash") { tmp = split(tmp[1], ","); DiskEntry entry = { tmp[0], tmp[2], int64(atoi(tmp[1].c_str())) * int64(1024 * 1024), false }; if (is_disk) disks_props.push_back(entry); else flash_props.push_back(entry); } else { std::cerr << "Unknown token " << tmp[0] << std::endl; } } cfg_file.close(); } // put flash devices after regular disks first_flash = disks_props.size(); disks_props.insert(disks_props.end(), flash_props.begin(), flash_props.end()); if (disks_props.empty()) { STXXL_THROW(std::runtime_error, "config::config", "No disks found in '" << config_path << "' ."); } else { #ifdef STXXL_VERBOSE_DISKS for (std::vector<DiskEntry>::const_iterator it = disks_props.begin(); it != disks_props.end(); it++) { STXXL_MSG("Disk '" << (*it).path << "' is allocated, space: " << ((*it).size) / (1024 * 1024) << " MB, I/O implementation: " << (*it).io_impl); } #else int64 total_size = 0; for (std::vector<DiskEntry>::const_iterator it = disks_props.begin(); it != disks_props.end(); it++) total_size += (*it).size; STXXL_MSG("" << disks_props.size() << " disks are allocated, total space: " << (total_size / (1024 * 1024)) << " MB"); #endif } } file * FileCreator::create(const std::string & io_impl, const std::string & filename, int options, int disk) { if (io_impl == "syscall") { ufs_file_base * result = new syscall_file(filename, options, disk); result->lock(); return result; } #ifndef BOOST_MSVC else if (io_impl == "mmap") { ufs_file_base * result = new mmap_file(filename, options, disk); result->lock(); return result; } else if (io_impl == "simdisk") { ufs_file_base * result = new sim_disk_file(filename, options, disk); result->lock(); return result; } #else else if (io_impl == "wincall") { wfs_file_base * result = new wincall_file(filename, options, disk); result->lock(); return result; } #endif #ifdef STXXL_BOOST_CONFIG else if (io_impl == "boostfd") { return new boostfd_file(filename, options, disk); } #endif else if (io_impl == "memory") { mem_file * result = new mem_file(disk); result->lock(); return result; } else if (io_impl == "fileperblock") { fileperblock_file<syscall_file> * result = new fileperblock_file<syscall_file>(filename, options, 8 * 1048576, disk); result->lock(); return result; } STXXL_THROW(std::runtime_error, "FileCreator::create", "Unsupported disk I/O implementation " << io_impl << " ."); return NULL; } block_manager::block_manager() { FileCreator fc; debugmon::get_instance(); config * cfg = config::get_instance(); ndisks = cfg->disks_number(); disk_allocators = new DiskAllocator *[ndisks]; disk_files = new file *[ndisks]; for (unsigned i = 0; i < ndisks; i++) { disk_files[i] = fc.create(cfg->disk_io_impl(i), cfg->disk_path(i), file::CREAT | file::RDWR | file::DIRECT, i); disk_files[i]->set_size(cfg->disk_size(i)); disk_allocators[i] = new DiskAllocator(cfg->disk_size(i)); } } block_manager::~block_manager() { STXXL_VERBOSE1("Block manager destructor"); for (unsigned i = 0; i < ndisks; i++) { delete disk_allocators[i]; delete disk_files[i]; } delete[] disk_allocators; delete[] disk_files; } __STXXL_END_NAMESPACE // vim: et:ts=4:sw=4 <commit_msg>Configurable block size for fileperblock.<commit_after>/*************************************************************************** * mng/mng.h * * Part of the STXXL. See http://stxxl.sourceforge.net * * Copyright (C) 2002-2004 Roman Dementiev <dementiev@mpi-sb.mpg.de> * Copyright (C) 2008 Andreas Beckmann <beckmann@cs.uni-frankfurt.de> * * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE_1_0.txt or copy at * http://www.boost.org/LICENSE_1_0.txt) **************************************************************************/ #include <sstream> #include <stxxl/mng> #include <stxxl/bits/io/io.h> #include <stxxl/bits/version.h> __STXXL_BEGIN_NAMESPACE void DiskAllocator::dump() { int64 total = 0; sortseq::const_iterator cur = free_space.begin(); STXXL_ERRMSG("Free regions dump:"); for ( ; cur != free_space.end(); ++cur) { STXXL_ERRMSG("Free chunk: begin: " << (cur->first) << " size: " << (cur->second)); total += cur->second; } STXXL_ERRMSG("Total bytes: " << total); } void config::init(const char * config_path) { logger::get_instance(); STXXL_MSG(get_version_string()); std::vector<DiskEntry> flash_props; std::ifstream cfg_file(config_path); if (!cfg_file) { STXXL_ERRMSG("Warning: no config file found."); STXXL_ERRMSG("Using default disk configuration."); #ifndef BOOST_MSVC DiskEntry entry1 = { "/var/tmp/stxxl", "syscall", 1000 * 1024 * 1024, true }; #else DiskEntry entry1 = { "", "wincall", 1000 * 1024 * 1024, true }; char * tmpstr = new char[255]; stxxl_check_ne_0(GetTempPath(255, tmpstr), resource_error); entry1.path = tmpstr; entry1.path += "stxxl"; delete[] tmpstr; #endif #if 0 DiskEntry entry2 = { "/tmp/stxxl1", "mmap", 100 * 1024 * 1024, true }; DiskEntry entry3 = { "/tmp/stxxl2", "simdisk", 1000 * 1024 * 1024, false }; #endif disks_props.push_back(entry1); //disks_props.push_back(entry2); //disks_props.push_back(entry3); } else { std::string line; while (cfg_file >> line) { std::vector<std::string> tmp = split(line, "="); bool is_disk; if (tmp[0][0] == '#') { } else if ((is_disk = (tmp[0] == "disk")) || tmp[0] == "flash") { tmp = split(tmp[1], ","); DiskEntry entry = { tmp[0], tmp[2], int64(atoi(tmp[1].c_str())) * int64(1024 * 1024), false }; if (is_disk) disks_props.push_back(entry); else flash_props.push_back(entry); } else { std::cerr << "Unknown token " << tmp[0] << std::endl; } } cfg_file.close(); } // put flash devices after regular disks first_flash = disks_props.size(); disks_props.insert(disks_props.end(), flash_props.begin(), flash_props.end()); if (disks_props.empty()) { STXXL_THROW(std::runtime_error, "config::config", "No disks found in '" << config_path << "' ."); } else { #ifdef STXXL_VERBOSE_DISKS for (std::vector<DiskEntry>::const_iterator it = disks_props.begin(); it != disks_props.end(); it++) { STXXL_MSG("Disk '" << (*it).path << "' is allocated, space: " << ((*it).size) / (1024 * 1024) << " MB, I/O implementation: " << (*it).io_impl); } #else int64 total_size = 0; for (std::vector<DiskEntry>::const_iterator it = disks_props.begin(); it != disks_props.end(); it++) total_size += (*it).size; STXXL_MSG("" << disks_props.size() << " disks are allocated, total space: " << (total_size / (1024 * 1024)) << " MB"); #endif } } file * FileCreator::create(const std::string & io_impl, const std::string & filename, int options, int disk) { if (io_impl == "syscall") { ufs_file_base * result = new syscall_file(filename, options, disk); result->lock(); return result; } #ifndef BOOST_MSVC else if (io_impl == "mmap") { ufs_file_base * result = new mmap_file(filename, options, disk); result->lock(); return result; } else if (io_impl == "simdisk") { ufs_file_base * result = new sim_disk_file(filename, options, disk); result->lock(); return result; } #else else if (io_impl == "wincall") { wfs_file_base * result = new wincall_file(filename, options, disk); result->lock(); return result; } #endif #ifdef STXXL_BOOST_CONFIG else if (io_impl == "boostfd") { return new boostfd_file(filename, options, disk); } #endif else if (io_impl == "memory") { mem_file * result = new mem_file(disk); result->lock(); return result; } else if (io_impl.find_first_of("fileperblock(") == 0) { std::istringstream input(io_impl); input.ignore(std::string("fileperblock(").size()); size_t block_size; input >> block_size; if(block_size <= 0) STXXL_THROW(std::runtime_error, "FileCreator::create", "No/incorrect block size given for fileperblock."); fileperblock_file<syscall_file> * result = new fileperblock_file<syscall_file>(filename, options, block_size, disk); result->lock(); return result; } STXXL_THROW(std::runtime_error, "FileCreator::create", "Unsupported disk I/O implementation " << io_impl << " ."); return NULL; } block_manager::block_manager() { FileCreator fc; debugmon::get_instance(); config * cfg = config::get_instance(); ndisks = cfg->disks_number(); disk_allocators = new DiskAllocator *[ndisks]; disk_files = new file *[ndisks]; for (unsigned i = 0; i < ndisks; i++) { disk_files[i] = fc.create(cfg->disk_io_impl(i), cfg->disk_path(i), file::CREAT | file::RDWR | file::DIRECT, i); disk_files[i]->set_size(cfg->disk_size(i)); disk_allocators[i] = new DiskAllocator(cfg->disk_size(i)); } } block_manager::~block_manager() { STXXL_VERBOSE1("Block manager destructor"); for (unsigned i = 0; i < ndisks; i++) { delete disk_allocators[i]; delete disk_files[i]; } delete[] disk_allocators; delete[] disk_files; } __STXXL_END_NAMESPACE // vim: et:ts=4:sw=4 <|endoftext|>
<commit_before>/*************************************************** Bunny Shed Climate Control Richard Huish 2016 ESP8266 based with local home-assistant.io GUI, 433Mhz transmitter for heater/fan control and DHT22 temperature-humidity sensor ---------- Key Libraries: ESP8266WiFi.h> https://github.com/esp8266/Arduino RCSwitch.h https://github.com/sui77/rc-switch DHT.h https://github.com/adafruit/DHT-sensor-library Adafruit_Sensor.g https://github.com/adafruit/Adafruit_Sensor required for DHT.h ---------- GUi: Locally hosted home assistant ---------- The circuit: NodeMCU Amica (ESP8266) Inputs: DHT22 temperature-humidity sensor - GPIO pin 5 (NodeMCU Pin D1) Outputs: 433Mhz Transmitter - GPIO pin 2 (NodeMCU Pin D4) LED_NODEMCU - pin 16 (NodeMCU Pin D0) LED_ESP - GPIO pin 2 (NodeMCU Pin D4) (Shared with 433Mhz TX) ---------- Notes: NodeMCU lED lights to show MQTT conenction. ESP lED lights to show WIFI conenction. ****************************************************/ // Note: Libaries are inluced in "Project Dependencies" file platformio.ini #include <ESP8266WiFi.h> // ESP8266 core for Arduino https://github.com/esp8266/Arduino #include <PubSubClient.h> // Arduino Client for MQTT https://github.com/knolleary/pubsubclient #include <RCSwitch.h> // https://github.com/sui77/rc-switch #include <DHT.h> // https://github.com/adafruit/DHT-sensor-library #include <Adafruit_Sensor.h> // have to add for the DHT to work https://github.com/adafruit/Adafruit_Sensor #include <secretes.h> // Passwords etc not for github // Define state machine states typedef enum { s_idle = 0, // state idle s_start = 1, // state start s_on = 2, // state on s_stop = 3, // state stop } e_state; int stateMachine = 0; // DHT sensor parameters #define DHTPIN 5 // GPIO pin 5 (NodeMCU Pin D1) #define DHTTYPE DHT22 // DHT sensor instance DHT dht(DHTPIN, DHTTYPE, 15); // 433Mhz transmitter parameters const int tx433Mhz_pin = 2; // GPIO pin 2 (NODEMCU Pin D4) const int setPulseLength = 305; // 433MHZ TX instance RCSwitch mySwitch = RCSwitch(); // WiFi parameters const char* wifi_ssid = secrete_wifi_ssid; // Wifi access point SSID const char* wifi_password = secrete_wifi_password; // Wifi access point password // MQTT Settings const char* mqtt_server = secrete_mqtt_server; // E.G. 192.168.1.xx const char* clientName = secrete_clientName; // Client to report to MQTT const char* mqtt_username = secrete_mqtt_username; // MQTT Username const char* mqtt_password = secrete_mqtt_password; // MQTT Password boolean willRetain = true; // MQTT Last Will and Testament const char* willMessage = "offline"; // MQTT Last Will and Testament Message // Publish const char* publishOutputState = secrete_publishOutputState; // const char* publishTemperature = secrete_publishTemperature; // const char* publishHumidity = secrete_publishHumidity; // const char* publishSetTemperature = secrete_publishSetTemperature; // const char* publishLastWillTopic = secrete_publishLastWillTopic; // // Subscribe const char* subscribeSetTemperature = secrete_subscribeSetTemperature; // // MQTT instance WiFiClient espClient; PubSubClient mqttClient(espClient); char message_buff[100]; long lastReconnectAttempt = 0; // Reconnecting MQTT - non-blocking https://github.com/knolleary/pubsubclient/blob/master/examples/mqtt_reconnect_nonblocking/mqtt_reconnect_nonblocking.ino // MQTT publish frequency unsigned long previousMillis = 0; const long publishInterval = 60000; // Publish requency in milliseconds 60000 = 1 min // LED output parameters const int DIGITAL_PIN_LED_ESP = 2; // Define LED on ESP8266 sub-modual const int DIGITAL_PIN_LED_NODEMCU = 16; // Define LED on NodeMCU board - Lights on pin LOW // Climate parameters // Target temperature (Set in code, but modified by web commands, local setpoint incase of internet connection break) float targetTemperature = 8; //CHANGE TO ACCOMIDATE FAN AND HEATER // Target temperature Hysteresis const float targetTemperatureHyst = 1; // Output powered status bool outputPoweredStatus = false; // // Output powered mode // bool heaterOrCooler = true; // // Setp the connection to WIFI and the MQTT Broker. Normally called only once from setup void setup_wifi() { // We start by connecting to a WiFi network Serial.println(); Serial.print("Connecting to "); Serial.print(wifi_ssid); WiFi.begin(wifi_ssid, wifi_password); while (WiFi.status() != WL_CONNECTED) { delay(250); Serial.print("."); } Serial.print(""); Serial.println("WiFi connected"); Serial.print("IP address: "); Serial.println(WiFi.localIP()); digitalWrite(DIGITAL_PIN_LED_NODEMCU, LOW); // Lights on LOW. Light the NodeMCU LED to show wifi connection. } // MQTT payload in seconds will turn on output. A payload of 0 will turn off the output. void mqttcallback(char* topic, byte* payload, unsigned int length) { //If you want to publish a message from within the message callback function, it is necessary to make a copy of the topic and payload values as the client uses the same internal buffer for inbound and outbound messages: //http://www.hivemq.com/blog/mqtt-client-library-encyclopedia-arduino-pubsubclient/ Serial.print("Message arrived ["); Serial.print(topic); Serial.print("] "); for (int i = 0; i < length; i++) { Serial.print((char)payload[i]); } Serial.println(); // create character buffer with ending null terminator (string) int i = 0; for (i = 0; i < length; i++) { message_buff[i] = payload[i]; } message_buff[i] = '\0'; // Check the value of the message String msgString = String(message_buff); Serial.println(msgString); // Check the message topic String srtTopic = topic; String strTopicCompairSetpoint = subscribeSetTemperature; if (srtTopic.equals(strTopicCompairSetpoint)) { if (targetTemperature != msgString.toFloat()) { Serial.println("new setpoint"); targetTemperature = msgString.toFloat(); } } } /* Non-Blocking mqtt reconnect. Called from checkMqttConnection. */ boolean mqttReconnect() { // Call on the background functions to allow them to do their thing yield(); // Attempt to connect if (mqttClient.connect(clientName, mqtt_username, mqtt_password, publishLastWillTopic, 0, willRetain, willMessage)) { Serial.print("Attempting MQTT connection..."); // Once connected, update status to online - will Message will drop in if we go offline ... mqttClient.publish(publishLastWillTopic,"online",true); // Resubscribe to feeds mqttClient.subscribe(subscribeSetTemperature); Serial.println("connected"); } else { Serial.print("Failed MQTT connection, rc="); Serial.print(mqttClient.state()); Serial.println(" try in 1.5 seconds"); } return mqttClient.connected(); } /* Checks if connection to the MQTT server is ok. Client connected using a non-blocking reconnect function. If the client loses its connection, it attempts to reconnect every 5 seconds without blocking the main loop. Called from main loop. */ void checkMqttConnection() { if (!mqttClient.connected()) { // We are not connected. Turn off the wifi LED digitalWrite(DIGITAL_PIN_LED_ESP, HIGH); // Lights on LOW long now = millis(); if (now - lastReconnectAttempt > 5000) { lastReconnectAttempt = now; // Attempt to reconnect if (mqttReconnect()) { lastReconnectAttempt = 0; } } } else { // We are connected. digitalWrite(DIGITAL_PIN_LED_ESP, LOW); // Lights on LOW //call on the background functions to allow them to do their thing. yield(); // Client connected: MQTT client loop processing mqttClient.loop(); } } // Returns true if heating is required boolean checkHeatRequired(float roomTemperature, float targetTemperature, float targetTempHyst) { // Is room too cold ? if (roomTemperature < (targetTemperature - targetTempHyst)) { // Heat needed return true; } // Else room is hot enough else { // No heat needed return false; } } // Control heater void controlHeater(boolean heaterStateRequested) { // Acknowledgements // thisoldgeek/ESP8266-RCSwitch // https://github.com/thisoldgeek/ESP8266-RCSwitch // Find the codes for your RC Switch using https://github.com/ninjablocks/433Utils (RF_Sniffer.ino) if (heaterStateRequested == 1) { mySwitch.send(2006879, 24); Serial.println(F("433Mhz TX ON command sent!")); outputPoweredStatus = true; } else { mySwitch.send(2006871, 24); Serial.println(F("433Mhz TX OFF command sent!")); outputPoweredStatus = false; } String strOutput = String(outputPoweredStatus); if (!mqttClient.publish(publishOutputState, strOutput.c_str())) Serial.print(F("Failed to output state to [")), Serial.print(publishOutputState), Serial.print("] "); else Serial.print(F("Output state published to [")), Serial.print(publishOutputState), Serial.println("] "); } // State machine for controller void checkState() { switch (stateMachine) { case s_idle: // State is currently: idle // Check if we need to start, by checking if heat is still required. if (checkHeatRequired(dht.readTemperature(), targetTemperature, targetTemperatureHyst)) { // Heat no longer required, stop. stateMachine = s_start; } break; case s_start: // State is currently: starting Serial.println("State is currently: starting"); // Command the heater to turn on. controlHeater(true); stateMachine = s_on; break; case s_on: // State is currently: On // Check if we need to stop, by checking if heat is still required. if (!checkHeatRequired(dht.readTemperature(), targetTemperature, targetTemperatureHyst)) { // Heat no longer required, stop. stateMachine = s_stop; } break; case s_stop: // State is currently: stopping Serial.println("State is currently: stopping"); // Command the heater to turn off. controlHeater(false); // Set state mahcine to idle on the next loop stateMachine = s_idle; break; } } void mtqqPublish() { // Only run when publishInterval in milliseonds exspires unsigned long currentMillis = millis(); // CODE TO MOVE TO functions if (currentMillis - previousMillis >= publishInterval) { // save the last time this ran previousMillis = currentMillis; if (mqttClient.connected()) { // Publish data // Grab the current state of the sensor String strTemp = String(dht.readTemperature()); //Could use String(dht.readTemperature()).c_str()) to do it all in one line if (!mqttClient.publish(publishTemperature, String(dht.readTemperature()).c_str())) // Convert dht.readTemperature() to string object, then to char array. Serial.print(F("Failed to published to [")), Serial.print(publishTemperature), Serial.print("] "); else Serial.print(F("Temperature published to [")), Serial.print(publishTemperature), Serial.println("] "); String strHumi = String(dht.readHumidity()); if (!mqttClient.publish(publishHumidity, strHumi.c_str())) Serial.print(F("Failed to humidity to [")), Serial.print(publishHumidity), Serial.print("] "); else Serial.print(F("Humidity published to [")), Serial.print(publishHumidity), Serial.println("] "); String strSetpoint = String(targetTemperature); if (!mqttClient.publish(publishSetTemperature, strSetpoint.c_str(), true)) // retained = true Serial.print(F("Failed to target temperature to [")), Serial.print(publishSetTemperature), Serial.print("] "); else Serial.print(F("Target temperature published to [")), Serial.print(publishSetTemperature), Serial.println("] "); String strOutput = String(outputPoweredStatus); if (!mqttClient.publish(publishOutputState, strOutput.c_str())) Serial.print(F("Failed to output state to [")), Serial.print(publishOutputState), Serial.print("] "); else Serial.print(F("Output state published to [")), Serial.print(publishOutputState), Serial.println("] "); } } } void setup() { // Initialize pins pinMode(DIGITAL_PIN_LED_NODEMCU, OUTPUT); pinMode(DIGITAL_PIN_LED_ESP, OUTPUT); // Initialize pin start values digitalWrite(DIGITAL_PIN_LED_NODEMCU, LOW); // Lights on HIGH digitalWrite(DIGITAL_PIN_LED_ESP, HIGH); // Lights on LOW // set serial speed Serial.begin(115200); Serial.println("Setup Starting"); // Setup 433Mhz Transmitter pinMode(tx433Mhz_pin, OUTPUT); // Set 433Mhz pin to output mySwitch.enableTransmit(tx433Mhz_pin); // Set pulse length. mySwitch.setPulseLength(setPulseLength); // Optional set protocol (default is 1, will work for most outlets) mySwitch.setProtocol(1); // Init temperature and humidity sensor dht.begin(); // Call on the background functions to allow them to do their thing yield(); // Setup wifi setup_wifi(); // Call on the background functions to allow them to do their thing yield(); // Set MQTT settings mqttClient.setServer(mqtt_server, 1883); mqttClient.setCallback(mqttcallback); // Call on the background functions to allow them to do their thing yield(); Serial.println("Setup Complete"); } /// Main working loop void loop() { yield(); //call on the background functions to allow them to do their thing. // First check if we are connected to the MQTT broker checkMqttConnection(); //call on the background functions to allow them to do their thing. yield(); // Check the status and do actions checkState(); mtqqPublish(); } <commit_msg>Added MQTT to description<commit_after>/*************************************************** Bunny Shed Climate Control Richard Huish 2016 ESP8266 based with local home-assistant.io GUI, 433Mhz transmitter for heater/fan control and DHT22 temperature-humidity sensor ---------- Key Libraries: ESP8266WiFi.h> https://github.com/esp8266/Arduino RCSwitch.h https://github.com/sui77/rc-switch DHT.h https://github.com/adafruit/DHT-sensor-library Adafruit_Sensor.g https://github.com/adafruit/Adafruit_Sensor required for DHT.h ---------- GUi: Locally hosted home assistant MQTT: Locally hosted broker https://mosquitto.org/ ---------- The circuit: NodeMCU Amica (ESP8266) Inputs: DHT22 temperature-humidity sensor - GPIO pin 5 (NodeMCU Pin D1) Outputs: 433Mhz Transmitter - GPIO pin 2 (NodeMCU Pin D4) LED_NODEMCU - pin 16 (NodeMCU Pin D0) LED_ESP - GPIO pin 2 (NodeMCU Pin D4) (Shared with 433Mhz TX) ---------- Notes: NodeMCU lED lights to show MQTT conenction. ESP lED lights to show WIFI conenction. ****************************************************/ // Note: Libaries are inluced in "Project Dependencies" file platformio.ini #include <ESP8266WiFi.h> // ESP8266 core for Arduino https://github.com/esp8266/Arduino #include <PubSubClient.h> // Arduino Client for MQTT https://github.com/knolleary/pubsubclient #include <RCSwitch.h> // https://github.com/sui77/rc-switch #include <DHT.h> // https://github.com/adafruit/DHT-sensor-library #include <Adafruit_Sensor.h> // have to add for the DHT to work https://github.com/adafruit/Adafruit_Sensor #include <secretes.h> // Passwords etc not for github // Define state machine states typedef enum { s_idle = 0, // state idle s_start = 1, // state start s_on = 2, // state on s_stop = 3, // state stop } e_state; int stateMachine = 0; // DHT sensor parameters #define DHTPIN 5 // GPIO pin 5 (NodeMCU Pin D1) #define DHTTYPE DHT22 // DHT sensor instance DHT dht(DHTPIN, DHTTYPE, 15); // 433Mhz transmitter parameters const int tx433Mhz_pin = 2; // GPIO pin 2 (NODEMCU Pin D4) const int setPulseLength = 305; // 433MHZ TX instance RCSwitch mySwitch = RCSwitch(); // WiFi parameters const char* wifi_ssid = secrete_wifi_ssid; // Wifi access point SSID const char* wifi_password = secrete_wifi_password; // Wifi access point password // MQTT Settings const char* mqtt_server = secrete_mqtt_server; // E.G. 192.168.1.xx const char* clientName = secrete_clientName; // Client to report to MQTT const char* mqtt_username = secrete_mqtt_username; // MQTT Username const char* mqtt_password = secrete_mqtt_password; // MQTT Password boolean willRetain = true; // MQTT Last Will and Testament const char* willMessage = "offline"; // MQTT Last Will and Testament Message // Publish const char* publishOutputState = secrete_publishOutputState; // const char* publishTemperature = secrete_publishTemperature; // const char* publishHumidity = secrete_publishHumidity; // const char* publishSetTemperature = secrete_publishSetTemperature; // const char* publishLastWillTopic = secrete_publishLastWillTopic; // // Subscribe const char* subscribeSetTemperature = secrete_subscribeSetTemperature; // // MQTT instance WiFiClient espClient; PubSubClient mqttClient(espClient); char message_buff[100]; long lastReconnectAttempt = 0; // Reconnecting MQTT - non-blocking https://github.com/knolleary/pubsubclient/blob/master/examples/mqtt_reconnect_nonblocking/mqtt_reconnect_nonblocking.ino // MQTT publish frequency unsigned long previousMillis = 0; const long publishInterval = 60000; // Publish requency in milliseconds 60000 = 1 min // LED output parameters const int DIGITAL_PIN_LED_ESP = 2; // Define LED on ESP8266 sub-modual const int DIGITAL_PIN_LED_NODEMCU = 16; // Define LED on NodeMCU board - Lights on pin LOW // Climate parameters // Target temperature (Set in code, but modified by web commands, local setpoint incase of internet connection break) float targetTemperature = 8; //CHANGE TO ACCOMIDATE FAN AND HEATER // Target temperature Hysteresis const float targetTemperatureHyst = 1; // Output powered status bool outputPoweredStatus = false; // // Output powered mode // bool heaterOrCooler = true; // // Setp the connection to WIFI and the MQTT Broker. Normally called only once from setup void setup_wifi() { // We start by connecting to a WiFi network Serial.println(); Serial.print("Connecting to "); Serial.print(wifi_ssid); WiFi.begin(wifi_ssid, wifi_password); while (WiFi.status() != WL_CONNECTED) { delay(250); Serial.print("."); } Serial.print(""); Serial.println("WiFi connected"); Serial.print("IP address: "); Serial.println(WiFi.localIP()); digitalWrite(DIGITAL_PIN_LED_NODEMCU, LOW); // Lights on LOW. Light the NodeMCU LED to show wifi connection. } // MQTT payload in seconds will turn on output. A payload of 0 will turn off the output. void mqttcallback(char* topic, byte* payload, unsigned int length) { //If you want to publish a message from within the message callback function, it is necessary to make a copy of the topic and payload values as the client uses the same internal buffer for inbound and outbound messages: //http://www.hivemq.com/blog/mqtt-client-library-encyclopedia-arduino-pubsubclient/ Serial.print("Message arrived ["); Serial.print(topic); Serial.print("] "); for (int i = 0; i < length; i++) { Serial.print((char)payload[i]); } Serial.println(); // create character buffer with ending null terminator (string) int i = 0; for (i = 0; i < length; i++) { message_buff[i] = payload[i]; } message_buff[i] = '\0'; // Check the value of the message String msgString = String(message_buff); Serial.println(msgString); // Check the message topic String srtTopic = topic; String strTopicCompairSetpoint = subscribeSetTemperature; if (srtTopic.equals(strTopicCompairSetpoint)) { if (targetTemperature != msgString.toFloat()) { Serial.println("new setpoint"); targetTemperature = msgString.toFloat(); } } } /* Non-Blocking mqtt reconnect. Called from checkMqttConnection. */ boolean mqttReconnect() { // Call on the background functions to allow them to do their thing yield(); // Attempt to connect if (mqttClient.connect(clientName, mqtt_username, mqtt_password, publishLastWillTopic, 0, willRetain, willMessage)) { Serial.print("Attempting MQTT connection..."); // Once connected, update status to online - will Message will drop in if we go offline ... mqttClient.publish(publishLastWillTopic,"online",true); // Resubscribe to feeds mqttClient.subscribe(subscribeSetTemperature); Serial.println("connected"); } else { Serial.print("Failed MQTT connection, rc="); Serial.print(mqttClient.state()); Serial.println(" try in 1.5 seconds"); } return mqttClient.connected(); } /* Checks if connection to the MQTT server is ok. Client connected using a non-blocking reconnect function. If the client loses its connection, it attempts to reconnect every 5 seconds without blocking the main loop. Called from main loop. */ void checkMqttConnection() { if (!mqttClient.connected()) { // We are not connected. Turn off the wifi LED digitalWrite(DIGITAL_PIN_LED_ESP, HIGH); // Lights on LOW long now = millis(); if (now - lastReconnectAttempt > 5000) { lastReconnectAttempt = now; // Attempt to reconnect if (mqttReconnect()) { lastReconnectAttempt = 0; } } } else { // We are connected. digitalWrite(DIGITAL_PIN_LED_ESP, LOW); // Lights on LOW //call on the background functions to allow them to do their thing. yield(); // Client connected: MQTT client loop processing mqttClient.loop(); } } // Returns true if heating is required boolean checkHeatRequired(float roomTemperature, float targetTemperature, float targetTempHyst) { // Is room too cold ? if (roomTemperature < (targetTemperature - targetTempHyst)) { // Heat needed return true; } // Else room is hot enough else { // No heat needed return false; } } // Control heater void controlHeater(boolean heaterStateRequested) { // Acknowledgements // thisoldgeek/ESP8266-RCSwitch // https://github.com/thisoldgeek/ESP8266-RCSwitch // Find the codes for your RC Switch using https://github.com/ninjablocks/433Utils (RF_Sniffer.ino) if (heaterStateRequested == 1) { mySwitch.send(2006879, 24); Serial.println(F("433Mhz TX ON command sent!")); outputPoweredStatus = true; } else { mySwitch.send(2006871, 24); Serial.println(F("433Mhz TX OFF command sent!")); outputPoweredStatus = false; } String strOutput = String(outputPoweredStatus); if (!mqttClient.publish(publishOutputState, strOutput.c_str())) Serial.print(F("Failed to output state to [")), Serial.print(publishOutputState), Serial.print("] "); else Serial.print(F("Output state published to [")), Serial.print(publishOutputState), Serial.println("] "); } // State machine for controller void checkState() { switch (stateMachine) { case s_idle: // State is currently: idle // Check if we need to start, by checking if heat is still required. if (checkHeatRequired(dht.readTemperature(), targetTemperature, targetTemperatureHyst)) { // Heat no longer required, stop. stateMachine = s_start; } break; case s_start: // State is currently: starting Serial.println("State is currently: starting"); // Command the heater to turn on. controlHeater(true); stateMachine = s_on; break; case s_on: // State is currently: On // Check if we need to stop, by checking if heat is still required. if (!checkHeatRequired(dht.readTemperature(), targetTemperature, targetTemperatureHyst)) { // Heat no longer required, stop. stateMachine = s_stop; } break; case s_stop: // State is currently: stopping Serial.println("State is currently: stopping"); // Command the heater to turn off. controlHeater(false); // Set state mahcine to idle on the next loop stateMachine = s_idle; break; } } void mtqqPublish() { // Only run when publishInterval in milliseonds exspires unsigned long currentMillis = millis(); // CODE TO MOVE TO functions if (currentMillis - previousMillis >= publishInterval) { // save the last time this ran previousMillis = currentMillis; if (mqttClient.connected()) { // Publish data // Grab the current state of the sensor String strTemp = String(dht.readTemperature()); //Could use String(dht.readTemperature()).c_str()) to do it all in one line if (!mqttClient.publish(publishTemperature, String(dht.readTemperature()).c_str())) // Convert dht.readTemperature() to string object, then to char array. Serial.print(F("Failed to published to [")), Serial.print(publishTemperature), Serial.print("] "); else Serial.print(F("Temperature published to [")), Serial.print(publishTemperature), Serial.println("] "); String strHumi = String(dht.readHumidity()); if (!mqttClient.publish(publishHumidity, strHumi.c_str())) Serial.print(F("Failed to humidity to [")), Serial.print(publishHumidity), Serial.print("] "); else Serial.print(F("Humidity published to [")), Serial.print(publishHumidity), Serial.println("] "); String strSetpoint = String(targetTemperature); if (!mqttClient.publish(publishSetTemperature, strSetpoint.c_str(), true)) // retained = true Serial.print(F("Failed to target temperature to [")), Serial.print(publishSetTemperature), Serial.print("] "); else Serial.print(F("Target temperature published to [")), Serial.print(publishSetTemperature), Serial.println("] "); String strOutput = String(outputPoweredStatus); if (!mqttClient.publish(publishOutputState, strOutput.c_str())) Serial.print(F("Failed to output state to [")), Serial.print(publishOutputState), Serial.print("] "); else Serial.print(F("Output state published to [")), Serial.print(publishOutputState), Serial.println("] "); } } } void setup() { // Initialize pins pinMode(DIGITAL_PIN_LED_NODEMCU, OUTPUT); pinMode(DIGITAL_PIN_LED_ESP, OUTPUT); // Initialize pin start values digitalWrite(DIGITAL_PIN_LED_NODEMCU, LOW); // Lights on HIGH digitalWrite(DIGITAL_PIN_LED_ESP, HIGH); // Lights on LOW // set serial speed Serial.begin(115200); Serial.println("Setup Starting"); // Setup 433Mhz Transmitter pinMode(tx433Mhz_pin, OUTPUT); // Set 433Mhz pin to output mySwitch.enableTransmit(tx433Mhz_pin); // Set pulse length. mySwitch.setPulseLength(setPulseLength); // Optional set protocol (default is 1, will work for most outlets) mySwitch.setProtocol(1); // Init temperature and humidity sensor dht.begin(); // Call on the background functions to allow them to do their thing yield(); // Setup wifi setup_wifi(); // Call on the background functions to allow them to do their thing yield(); // Set MQTT settings mqttClient.setServer(mqtt_server, 1883); mqttClient.setCallback(mqttcallback); // Call on the background functions to allow them to do their thing yield(); Serial.println("Setup Complete"); } /// Main working loop void loop() { yield(); //call on the background functions to allow them to do their thing. // First check if we are connected to the MQTT broker checkMqttConnection(); //call on the background functions to allow them to do their thing. yield(); // Check the status and do actions checkState(); mtqqPublish(); } <|endoftext|>
<commit_before>#include <iostream> using namespace std; #include "EasyCL.h" #include "CLKernel_structs.h" #include "util/StatefulTimer.h" #include "util/easycl_stringhelper.h" typedef struct Info { int dims; int offset; int sizes[25]; int strides[25]; } Info; static const char *kernelSource = R"DELIM( typedef struct Info { int dims; int offset; int sizes[25]; int strides[25]; } Info; kernel void test(int totalN, global struct Info *out_info, global float*out_data, global struct Info *in1_info, global float *in1_data, global struct Info *in2_info, global float *in2_data) { int linearId = get_global_id(0); if(linearId < totalN) { out_data[linearId] = in1_data[linearId] * in2_data[linearId]; } } )DELIM"; void test(EasyCL *cl, int its, int size) { int totalN = size; string templatedSource = kernelSource; CLKernel *kernel = cl->buildKernelFromString(templatedSource, "test", ""); const int workgroupSize = 64; int numWorkgroups = (totalN + workgroupSize - 1) / workgroupSize; float *out = new float[totalN]; float *in1 = new float[totalN]; float *in2 = new float[totalN]; for( int i = 0; i < totalN; i++ ) { in1[i] = (i + 4) % 1000000; in2[i] = (i + 6) % 1000000; } CLWrapper *outwrap = cl->wrap(totalN, out); CLWrapper *in1wrap = cl->wrap(totalN, in1); CLWrapper *in2wrap = cl->wrap(totalN, in2); in1wrap->copyToDevice(); in2wrap->copyToDevice(); outwrap->createOnDevice(); cl->finish(); cl->dumpProfiling(); Info outInfo; Info in1Info; Info in2Info; outInfo.offset = in1Info.offset = in2Info.offset = 0; outInfo.dims = in1Info.dims = in2Info.dims = 1; outInfo.sizes[0] = in1Info.sizes[0] = in2Info.sizes[0] = 6400; outInfo.strides[0] = in1Info.strides[0] = in2Info.strides[0] = 1; double start = StatefulTimer::instance()->getSystemMilliseconds(); for(int it = 0; it < its; it++) { kernel->in(totalN); kernel->in(1, &outInfo); kernel->out(outwrap); kernel->in(1, &in1Info); kernel->in(in1wrap); kernel->in(1, &in2Info); kernel->in(in2wrap); kernel->run_1d(numWorkgroups * workgroupSize, workgroupSize); } cl->finish(); double end = StatefulTimer::instance()->getSystemMilliseconds(); cl->dumpProfiling(); cout << "its=" << its << " size=" << size << "time=" << (end - start) << "ms" << endl; outwrap->copyToHost(); cl->finish(); int errorCount = 0; for( int i = 0; i < totalN; i++ ) { float targetValue = in1[i] * in2[i]; if(abs(out[i] - targetValue)> 0.1f) { errorCount++; if( errorCount < 20 ) { cout << "out[" << i << "]" << " != " << targetValue << endl; cout << abs(out[i] - targetValue) << endl; } } } // cout << endl; if( errorCount > 0 ) { cout << "errors: " << errorCount << " out of totalN=" << totalN << endl; } else { } delete outwrap; delete in1wrap; delete in2wrap; delete[] in1; delete[] in2; delete[] out; delete kernel; } int main(int argc, char *argv[]) { int gpu = 0; if( argc == 2 ) { gpu = atoi(argv[1]); } cout << "using gpu " << gpu << endl; EasyCL *cl = EasyCL::createForIndexedGpu(gpu); cl->setProfiling(true); test(cl, 900, 6400); test(cl, 9000, 6400); cl->dumpProfiling(); delete cl; return 0; } <commit_msg>reuse struct buffers<commit_after>#include <iostream> using namespace std; #include "EasyCL.h" #include "CLKernel_structs.h" #include "util/StatefulTimer.h" #include "util/easycl_stringhelper.h" typedef struct Info { int dims; int offset; int sizes[25]; int strides[25]; } Info; static const char *kernelSource = R"DELIM( typedef struct Info { int dims; int offset; int sizes[25]; int strides[25]; } Info; kernel void test(int totalN, global struct Info *out_info, global struct Info *in1_info, global struct Info *in2_info, global float*out_data, global float *in1_data, global float *in2_data ) { int linearId = get_global_id(0); if(linearId < totalN) { out_data[linearId] = in1_data[linearId] * in2_data[linearId]; } } )DELIM"; void test(EasyCL *cl, int its, int size, bool reuseStructBuffers) { int totalN = size; string templatedSource = kernelSource; CLKernel *kernel = cl->buildKernelFromString(templatedSource, "test", ""); const int workgroupSize = 64; int numWorkgroups = (totalN + workgroupSize - 1) / workgroupSize; float *out = new float[totalN]; float *in1 = new float[totalN]; float *in2 = new float[totalN]; for( int i = 0; i < totalN; i++ ) { in1[i] = (i + 4) % 1000000; in2[i] = (i + 6) % 1000000; } CLWrapper *outwrap = cl->wrap(totalN, out); CLWrapper *in1wrap = cl->wrap(totalN, in1); CLWrapper *in2wrap = cl->wrap(totalN, in2); in1wrap->copyToDevice(); in2wrap->copyToDevice(); outwrap->createOnDevice(); Info outInfo; Info in1Info; Info in2Info; outInfo.offset = in1Info.offset = in2Info.offset = 0; outInfo.dims = in1Info.dims = in2Info.dims = 1; outInfo.sizes[0] = in1Info.sizes[0] = in2Info.sizes[0] = 6400; outInfo.strides[0] = in1Info.strides[0] = in2Info.strides[0] = 1; float *outInfoFloat = reinterpret_cast<float *>(&outInfo); float *in1InfoFloat = reinterpret_cast<float *>(&in1Info); float *in2InfoFloat = reinterpret_cast<float *>(&in2Info); CLWrapper *outInfoWrap = cl->wrap(64, outInfoFloat); CLWrapper *in1InfoWrap = cl->wrap(64, in1InfoFloat); CLWrapper *in2InfoWrap = cl->wrap(64, in2InfoFloat); outInfoWrap->copyToDevice(); in1InfoWrap->copyToDevice(); in2InfoWrap->copyToDevice(); cl->finish(); cl->dumpProfiling(); double start = StatefulTimer::instance()->getSystemMilliseconds(); for(int it = 0; it < its; it++) { kernel->in(totalN); if(reuseStructBuffers) { kernel->in(outInfoWrap); kernel->in(in1InfoWrap); kernel->in(in2InfoWrap); } else { kernel->in(1, &outInfo); kernel->in(1, &in1Info); kernel->in(1, &in2Info); } kernel->out(outwrap); kernel->in(in1wrap); kernel->in(in2wrap); kernel->run_1d(numWorkgroups * workgroupSize, workgroupSize); } cl->finish(); double end = StatefulTimer::instance()->getSystemMilliseconds(); cl->dumpProfiling(); cout << "its=" << its << " size=" << size << " reusestructbuffers=" << reuseStructBuffers << " time=" << (end - start) << "ms" << endl; outwrap->copyToHost(); cl->finish(); int errorCount = 0; for( int i = 0; i < totalN; i++ ) { float targetValue = in1[i] * in2[i]; if(abs(out[i] - targetValue)> 0.1f) { errorCount++; if( errorCount < 20 ) { cout << "out[" << i << "]" << " != " << targetValue << endl; cout << abs(out[i] - targetValue) << endl; } } } // cout << endl; if( errorCount > 0 ) { cout << "errors: " << errorCount << " out of totalN=" << totalN << endl; } else { } delete outwrap; delete in1wrap; delete in2wrap; delete[] in1; delete[] in2; delete[] out; delete kernel; } int main(int argc, char *argv[]) { int gpu = 0; if( argc == 2 ) { gpu = atoi(argv[1]); } cout << "using gpu " << gpu << endl; EasyCL *cl = EasyCL::createForIndexedGpu(gpu); cl->setProfiling(true); test(cl, 900, 6400, false); test(cl, 900, 6400, true); test(cl, 9000, 6400, false); test(cl, 9000, 6400, true); cl->dumpProfiling(); delete cl; return 0; } <|endoftext|>
<commit_before>/* * Copyright (C) 2008-2013 The Communi Project * 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 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 <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 DAMAGE. */ #include "zncmanager.h" #include "textdocument.h" #include <ircconnection.h> #include <ircmessage.h> #include <ircbuffer.h> ZncManager::ZncManager(QObject* parent) : QObject(parent) { d.model = 0; d.buffer = 0; d.timestamp = 0; d.playback = false; d.timestamper.invalidate(); d.timeStampFormat = "[hh:mm:ss]"; setModel(qobject_cast<IrcBufferModel*>(parent)); } ZncManager::~ZncManager() { } IrcBufferModel* ZncManager::model() const { return d.model; } void ZncManager::setModel(IrcBufferModel* model) { if (d.model != model) { if (d.model && d.model->connection()) { IrcConnection* connection = d.model->connection(); disconnect(connection, SIGNAL(connected()), this, SLOT(onConnected())); disconnect(connection->network(), SIGNAL(requestingCapabilities()), this, SLOT(requestCapabilities())); connection->removeMessageFilter(this); } d.model = model; if (d.model && d.model->connection()) { IrcConnection* connection = d.model->connection(); connect(connection, SIGNAL(connected()), this, SLOT(onConnected())); connect(connection->network(), SIGNAL(requestingCapabilities()), this, SLOT(requestCapabilities())); connection->installMessageFilter(this); } emit modelChanged(model); } } QString ZncManager::timeStampFormat() const { return d.timeStampFormat; } void ZncManager::setTimeStampFormat(const QString& format) { if (d.timeStampFormat != format) { d.timeStampFormat = format; emit timeStampFormatChanged(format); } } bool ZncManager::messageFilter(IrcMessage* message) { if (d.timestamp > 0 && d.timestamper.isValid()) { long elapsed = d.timestamper.elapsed() / 1000; if (elapsed > 0) { d.timestamp += elapsed; d.timestamper.restart(); } } if (message->type() == IrcMessage::Private) { if (message->nick() == QLatin1String("***") && message->ident() == QLatin1String("znc")) { IrcPrivateMessage* privMsg = static_cast<IrcPrivateMessage*>(message); QString content = privMsg->content(); if (content == QLatin1String("Buffer Playback...")) { d.playback = true; d.buffer = d.model->find(privMsg->target()); if (d.buffer) { QList<TextDocument*> documents = d.buffer->findChildren<TextDocument*>(); foreach (TextDocument* doc, documents) doc->beginLowlight(); } return false; } else if (content == QLatin1String("Playback Complete.")) { if (d.buffer) { QList<TextDocument*> documents = d.buffer->findChildren<TextDocument*>(); foreach (TextDocument* doc, documents) doc->endLowlight(); } d.playback = false; d.buffer = 0; return false; } } } else if (message->type() == IrcMessage::Notice) { if (message->nick() == "*communi") { d.timestamp = static_cast<IrcNoticeMessage*>(message)->content().toLong(); d.timestamper.restart(); return true; } } if (d.playback && d.buffer) { switch (message->type()) { case IrcMessage::Private: return processMessage(static_cast<IrcPrivateMessage*>(message)); case IrcMessage::Notice: return processNotice(static_cast<IrcNoticeMessage*>(message)); default: break; } } return false; } bool ZncManager::processMessage(IrcPrivateMessage* message) { QString msg = message->content(); int idx = msg.indexOf(" "); if (idx != -1) { QDateTime timeStamp = QDateTime::fromString(msg.left(idx), d.timeStampFormat); if (timeStamp.isValid()) { msg.remove(0, idx + 1); if (message->nick() == "*buffextras") { idx = msg.indexOf(" "); QString prefix = msg.left(idx); QString content = msg.mid(idx + 1); IrcMessage* tmp = 0; if (content.startsWith("joined")) { tmp = IrcMessage::fromParameters(prefix, "JOIN", QStringList() << message->target(), message->connection()); } else if (content.startsWith("parted")) { QString reason = content.mid(content.indexOf("[") + 1); reason.chop(1); tmp = IrcMessage::fromParameters(prefix, "PART", QStringList() << message->target() << reason , message->connection()); } else if (content.startsWith("quit")) { QString reason = content.mid(content.indexOf("[") + 1); reason.chop(1); tmp = IrcMessage::fromParameters(prefix, "QUIT", QStringList() << reason , message->connection()); } else if (content.startsWith("is")) { QStringList tokens = content.split(" ", QString::SkipEmptyParts); tmp = IrcMessage::fromParameters(prefix, "NICK", QStringList() << tokens.last() , message->connection()); } else if (content.startsWith("set")) { QStringList tokens = content.split(" ", QString::SkipEmptyParts); QString user = tokens.takeLast(); QString mode = tokens.takeLast(); tmp = IrcMessage::fromParameters(prefix, "MODE", QStringList() << message->target() << mode << user, message->connection()); } else if (content.startsWith("changed")) { QString topic = content.mid(content.indexOf(":") + 2); tmp = IrcMessage::fromParameters(prefix, "TOPIC", QStringList() << message->target() << topic, message->connection()); } else if (content.startsWith("kicked")) { QString reason = content.mid(content.indexOf("[") + 1); reason.chop(1); QStringList tokens = content.split(" ", QString::SkipEmptyParts); tmp = IrcMessage::fromParameters(prefix, "KICK", QStringList() << message->target() << tokens.value(1) << reason, message->connection()); } if (tmp) { tmp->setTimeStamp(timeStamp); d.buffer->receiveMessage(tmp); tmp->deleteLater(); return true; } } if (message->isAction()) msg = QString("\1ACTION %1\1").arg(msg); else if (message->isRequest()) msg = QString("\1%1\1").arg(msg); message->setParameters(QStringList() << message->target() << msg); message->setTimeStamp(timeStamp); } } return false; } bool ZncManager::processNotice(IrcNoticeMessage* message) { QString msg = message->content(); int idx = msg.indexOf(" "); if (idx != -1) { QDateTime timeStamp = QDateTime::fromString(msg.left(idx), d.timeStampFormat); if (timeStamp.isValid()) { message->setTimeStamp(timeStamp); msg.remove(0, idx + 1); if (message->isReply()) msg = QString("\1%1\1").arg(msg); message->setParameters(QStringList() << message->target() << msg); } } return false; } void ZncManager::onConnected() { d.timestamper.invalidate(); } void ZncManager::requestCapabilities() { QStringList available = d.model->network()->availableCapabilities(); if (available.contains("communi")) { QStringList caps = QStringList() << "communi" << QString("communi/%1").arg(d.timestamp); d.model->network()->requestCapabilities(caps); } } <commit_msg>Make ZncManager more permissive for PanicBNC<commit_after>/* * Copyright (C) 2008-2013 The Communi Project * 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 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 <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 DAMAGE. */ #include "zncmanager.h" #include "textdocument.h" #include <ircconnection.h> #include <ircmessage.h> #include <ircbuffer.h> ZncManager::ZncManager(QObject* parent) : QObject(parent) { d.model = 0; d.buffer = 0; d.timestamp = 0; d.playback = false; d.timestamper.invalidate(); d.timeStampFormat = "[hh:mm:ss]"; setModel(qobject_cast<IrcBufferModel*>(parent)); } ZncManager::~ZncManager() { } IrcBufferModel* ZncManager::model() const { return d.model; } void ZncManager::setModel(IrcBufferModel* model) { if (d.model != model) { if (d.model && d.model->connection()) { IrcConnection* connection = d.model->connection(); disconnect(connection, SIGNAL(connected()), this, SLOT(onConnected())); disconnect(connection->network(), SIGNAL(requestingCapabilities()), this, SLOT(requestCapabilities())); connection->removeMessageFilter(this); } d.model = model; if (d.model && d.model->connection()) { IrcConnection* connection = d.model->connection(); connect(connection, SIGNAL(connected()), this, SLOT(onConnected())); connect(connection->network(), SIGNAL(requestingCapabilities()), this, SLOT(requestCapabilities())); connection->installMessageFilter(this); } emit modelChanged(model); } } QString ZncManager::timeStampFormat() const { return d.timeStampFormat; } void ZncManager::setTimeStampFormat(const QString& format) { if (d.timeStampFormat != format) { d.timeStampFormat = format; emit timeStampFormatChanged(format); } } bool ZncManager::messageFilter(IrcMessage* message) { if (d.timestamp > 0 && d.timestamper.isValid()) { long elapsed = d.timestamper.elapsed() / 1000; if (elapsed > 0) { d.timestamp += elapsed; d.timestamper.restart(); } } if (message->type() == IrcMessage::Private) { if (message->nick() == QLatin1String("***")) { IrcPrivateMessage* privMsg = static_cast<IrcPrivateMessage*>(message); QString content = privMsg->content(); if (content == QLatin1String("Buffer Playback...")) { d.playback = true; d.buffer = d.model->find(privMsg->target()); if (d.buffer) { QList<TextDocument*> documents = d.buffer->findChildren<TextDocument*>(); foreach (TextDocument* doc, documents) doc->beginLowlight(); } return false; } else if (content == QLatin1String("Playback Complete.")) { if (d.buffer) { QList<TextDocument*> documents = d.buffer->findChildren<TextDocument*>(); foreach (TextDocument* doc, documents) doc->endLowlight(); } d.playback = false; d.buffer = 0; return false; } } } else if (message->type() == IrcMessage::Notice) { if (message->nick() == "*communi") { d.timestamp = static_cast<IrcNoticeMessage*>(message)->content().toLong(); d.timestamper.restart(); return true; } } if (d.playback && d.buffer) { switch (message->type()) { case IrcMessage::Private: return processMessage(static_cast<IrcPrivateMessage*>(message)); case IrcMessage::Notice: return processNotice(static_cast<IrcNoticeMessage*>(message)); default: break; } } return false; } bool ZncManager::processMessage(IrcPrivateMessage* message) { QString msg = message->content(); int idx = msg.indexOf(" "); if (idx != -1) { QDateTime timeStamp = QDateTime::fromString(msg.left(idx), d.timeStampFormat); if (timeStamp.isValid()) { msg.remove(0, idx + 1); if (message->nick() == "*buffextras") { idx = msg.indexOf(" "); QString prefix = msg.left(idx); QString content = msg.mid(idx + 1); IrcMessage* tmp = 0; if (content.startsWith("joined")) { tmp = IrcMessage::fromParameters(prefix, "JOIN", QStringList() << message->target(), message->connection()); } else if (content.startsWith("parted")) { QString reason = content.mid(content.indexOf("[") + 1); reason.chop(1); tmp = IrcMessage::fromParameters(prefix, "PART", QStringList() << message->target() << reason , message->connection()); } else if (content.startsWith("quit")) { QString reason = content.mid(content.indexOf("[") + 1); reason.chop(1); tmp = IrcMessage::fromParameters(prefix, "QUIT", QStringList() << reason , message->connection()); } else if (content.startsWith("is")) { QStringList tokens = content.split(" ", QString::SkipEmptyParts); tmp = IrcMessage::fromParameters(prefix, "NICK", QStringList() << tokens.last() , message->connection()); } else if (content.startsWith("set")) { QStringList tokens = content.split(" ", QString::SkipEmptyParts); QString user = tokens.takeLast(); QString mode = tokens.takeLast(); tmp = IrcMessage::fromParameters(prefix, "MODE", QStringList() << message->target() << mode << user, message->connection()); } else if (content.startsWith("changed")) { QString topic = content.mid(content.indexOf(":") + 2); tmp = IrcMessage::fromParameters(prefix, "TOPIC", QStringList() << message->target() << topic, message->connection()); } else if (content.startsWith("kicked")) { QString reason = content.mid(content.indexOf("[") + 1); reason.chop(1); QStringList tokens = content.split(" ", QString::SkipEmptyParts); tmp = IrcMessage::fromParameters(prefix, "KICK", QStringList() << message->target() << tokens.value(1) << reason, message->connection()); } if (tmp) { tmp->setTimeStamp(timeStamp); d.buffer->receiveMessage(tmp); tmp->deleteLater(); return true; } } if (message->isAction()) msg = QString("\1ACTION %1\1").arg(msg); else if (message->isRequest()) msg = QString("\1%1\1").arg(msg); message->setParameters(QStringList() << message->target() << msg); message->setTimeStamp(timeStamp); } } return false; } bool ZncManager::processNotice(IrcNoticeMessage* message) { QString msg = message->content(); int idx = msg.indexOf(" "); if (idx != -1) { QDateTime timeStamp = QDateTime::fromString(msg.left(idx), d.timeStampFormat); if (timeStamp.isValid()) { message->setTimeStamp(timeStamp); msg.remove(0, idx + 1); if (message->isReply()) msg = QString("\1%1\1").arg(msg); message->setParameters(QStringList() << message->target() << msg); } } return false; } void ZncManager::onConnected() { d.timestamper.invalidate(); } void ZncManager::requestCapabilities() { QStringList available = d.model->network()->availableCapabilities(); if (available.contains("communi")) { QStringList caps = QStringList() << "communi" << QString("communi/%1").arg(d.timestamp); d.model->network()->requestCapabilities(caps); } } <|endoftext|>
<commit_before>/* * Copyright (c) 2004 The Regents of The University of Michigan * 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: Ali Saidi * Ron Dreslinski */ /** * DRAMsim v2 integration * Author: Rio Xiangyu Dong * Tao Zhang */ #include <cstdlib> #include <iomanip> #include "mem/DRAMSim2.hh" DRAMSim2::DRAMSim2(const Params *p) : DRAMSim2Wrapper(p) { warn("This is an integrated DRAMsim v2 module"); int memoryCapacity = (int)(params()->range.size() / 1024 / 1024); std::cout << "device file: " << p->deviceConfigFile << std::endl; std::cout << "system file: " << p->systemConfigFile << std::endl; std::cout << "output file: " << p->outputFile << std::endl; //dramsim2 = new DRAMSim::MultiChannelMemorySystem(p->deviceConfigFile, p->systemConfigFile, p->cwd, p->traceFile, memoryCapacity, "./results/output", NULL, NULL); dramsim2 = new DRAMSim::MultiChannelMemorySystem(p->deviceConfigFile, p->systemConfigFile, atoi((p->tpTurnLength).c_str()), p->genTrace, p->cwd, p->traceFile, memoryCapacity, p->outputFile, NULL, NULL, p->numPids, p->fixAddr, p->diffPeriod, p->p0Period, p->p1Period, p->offset); // intentionally set CPU:Memory clock ratio as 1, we do the synchronization later dramsim2->setCPUClockSpeed(0); num_pids = p->numPids; std::cout << "CPU Clock = " << (int)(1000000 / p->cpu_clock) << "MHz" << std::endl; std::cout << "DRAM Clock = " << (1000 / tCK) << "MHz" << std::endl; std::cout << "Memory Capacity = " << memoryCapacity << "MB" << std::endl; DRAMSim::Callback_t *read_cb = new DRAMSim::Callback<DRAMSim2, void, unsigned, uint64_t, uint64_t, uint64_t>(this, &DRAMSim2::read_complete); DRAMSim::Callback_t *write_cb = new DRAMSim::Callback<DRAMSim2, void, unsigned, uint64_t, uint64_t, uint64_t>(this, &DRAMSim2::write_complete); dramsim2->RegisterCallbacks(read_cb, write_cb, NULL); } DRAMSim2 * DRAMSim2Params::create() { return new DRAMSim2(this); } bool DRAMSim2::MemoryPort::recvTimingReq(PacketPtr pkt) { /* I don't know when they can remove this... */ /// @todo temporary hack to deal with memory corruption issue until /// 4-phase transactions are complete. Remove me later //cout << "Cycle: " << dramsim2->currentClockCycle << " Receive Timing Request" << endl; this->removePendingDelete(); DRAMSim2* dram = dynamic_cast<DRAMSim2*>(memory); bool retVal = false; // if DRAMSim2 is disabled, just use the default recvTiming. if( !dram ) { return SimpleTimingPort::recvTimingReq(pkt); } else { if (pkt->memInhibitAsserted()) { // snooper will supply based on copy of packet // still target's responsibility to delete packet delete pkt; return true; } uint64_t addr = pkt->getAddr(); AccessMetaInfo meta; meta.pkt = pkt; meta.port = this; TransactionType transType; while ((double)dramsim2->currentClockCycle <= (double)(curTick()) / 1000.0 / tCK) { dramsim2->update(); } if (pkt->needsResponse()) { if (pkt->isRead()) { transType = DATA_READ; } else if (pkt->isWrite()) { transType = DATA_WRITE; } else { // only leverage the atomic access to move data, don't use the // latency //std::cout << "case 1" << std::endl; dram->doAtomicAccess(pkt); assert(pkt->isResponse()); //TODO possible bug fix required schedTimingResp(pkt, curTick() + 1); return true; } // record the READ/WRITE request for later use uint64_t index = addr << 1; if (transType == DATA_WRITE) index = index | 0x1; dram->ongoingAccess.insert(make_pair(index, meta)); uint64_t threadID = pkt->threadID; // For trace generation if (threadID >= dram->num_pids) threadID = 0; Transaction tr = Transaction(transType, addr, NULL, threadID, dramsim2->currentClockCycle, 0); retVal = dramsim2->addTransaction(tr); //std::cout << "case 2" << std::endl; //std::cout << "Thread: " << threadID << std::endl; //std::cout << "Addr : " << std::hex << setfill('0') << setw(8) << addr << std::endl; } else { if (pkt->isWrite()) { // write-back does not need a response, but DRAMsim2 needs to track it transType = DATA_WRITE; uint64_t threadID = pkt->threadID; // For trace generation if (threadID >= dram->num_pids) threadID = 0; Transaction tr = Transaction(transType, addr, NULL, threadID, dramsim2->currentClockCycle, 0); retVal = dramsim2->addTransaction(tr); if (retVal == true) { dram->doAtomicAccess(pkt); this->addPendingDelete(pkt); } //std::cout << "case 3" << std::endl; // assert(retVal == true); } else { //std::cout << "case 4" << std::endl; retVal = dram->doAtomicAccess(pkt); // Again, I don't know.... /// @todo nominally we should just delete the packet here. /// Until 4-phase stuff we can't because the sending /// cache is still relying on it this->addPendingDelete(pkt); } } } return retVal; } void DRAMSim2::read_complete(unsigned id, uint64_t address, uint64_t clock_cycle, uint64_t threadID) { //printf("read complete for %llx @ cycle %llu\n", address, clock_cycle); uint64_t index = address << 1; if (ongoingAccess.count(index)) { AccessMetaInfo meta = ongoingAccess.find(index)->second; PacketPtr pkt = meta.pkt; DRAMSim2::MemoryPort *my_port = (DRAMSim2::MemoryPort*)(meta.port); my_port->removePendingDelete(); if (pkt->needsResponse()) { doAtomicAccess(pkt); assert(pkt->isResponse()); // remove the skew between DRAMSim2 and gem5 Tick toSchedule = (Tick)(clock_cycle) * (Tick)(tCK * 1000); if (toSchedule <= curTick()) toSchedule = curTick() + 1; //not accurate, but I have to if (toSchedule >= curTick() + SimClock::Int::ms) toSchedule = curTick() + SimClock::Int::ms - 1; //not accurate my_port->schedTimingResp(pkt, toSchedule, threadID); } else { my_port->addPendingDelete(pkt); } ongoingAccess.erase(ongoingAccess.find(index)); } } void DRAMSim2::write_complete(unsigned id, uint64_t address, uint64_t clock_cycle, uint64_t threadID) { uint64_t index = address << 1; index = index | 0x1; if (ongoingAccess.count(index)) { AccessMetaInfo meta = ongoingAccess.find(index)->second; PacketPtr pkt = meta.pkt; DRAMSim2::MemoryPort *my_port = (DRAMSim2::MemoryPort*)(meta.port); my_port->removePendingDelete(); if (pkt->needsResponse()) { doAtomicAccess(pkt); assert(pkt->isResponse()); Tick toSchedule = (Tick)(clock_cycle) * (Tick)(tCK * 1000); if (toSchedule <= curTick()) toSchedule = curTick() + 1; //not accurate, but I have to if (toSchedule >= curTick() + SimClock::Int::ms) toSchedule = curTick() + SimClock::Int::ms - 1; //not accurate //TODO possible bug fix required my_port->schedTimingResp(pkt, toSchedule); } else { my_port->addPendingDelete(pkt); } ongoingAccess.erase(ongoingAccess.find(index)); } } void DRAMSim2::report_power(double a, double b, double c, double d) { } <commit_msg>Fixed potential bug in memctl port split implementation Second to last bug?<commit_after>/* * Copyright (c) 2004 The Regents of The University of Michigan * 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: Ali Saidi * Ron Dreslinski */ /** * DRAMsim v2 integration * Author: Rio Xiangyu Dong * Tao Zhang */ #include <cstdlib> #include <iomanip> #include "mem/DRAMSim2.hh" DRAMSim2::DRAMSim2(const Params *p) : DRAMSim2Wrapper(p) { warn("This is an integrated DRAMsim v2 module"); int memoryCapacity = (int)(params()->range.size() / 1024 / 1024); std::cout << "device file: " << p->deviceConfigFile << std::endl; std::cout << "system file: " << p->systemConfigFile << std::endl; std::cout << "output file: " << p->outputFile << std::endl; //dramsim2 = new DRAMSim::MultiChannelMemorySystem(p->deviceConfigFile, p->systemConfigFile, p->cwd, p->traceFile, memoryCapacity, "./results/output", NULL, NULL); dramsim2 = new DRAMSim::MultiChannelMemorySystem(p->deviceConfigFile, p->systemConfigFile, atoi((p->tpTurnLength).c_str()), p->genTrace, p->cwd, p->traceFile, memoryCapacity, p->outputFile, NULL, NULL, p->numPids, p->fixAddr, p->diffPeriod, p->p0Period, p->p1Period, p->offset); // intentionally set CPU:Memory clock ratio as 1, we do the synchronization later dramsim2->setCPUClockSpeed(0); num_pids = p->numPids; std::cout << "CPU Clock = " << (int)(1000000 / p->cpu_clock) << "MHz" << std::endl; std::cout << "DRAM Clock = " << (1000 / tCK) << "MHz" << std::endl; std::cout << "Memory Capacity = " << memoryCapacity << "MB" << std::endl; DRAMSim::Callback_t *read_cb = new DRAMSim::Callback<DRAMSim2, void, unsigned, uint64_t, uint64_t, uint64_t>(this, &DRAMSim2::read_complete); DRAMSim::Callback_t *write_cb = new DRAMSim::Callback<DRAMSim2, void, unsigned, uint64_t, uint64_t, uint64_t>(this, &DRAMSim2::write_complete); dramsim2->RegisterCallbacks(read_cb, write_cb, NULL); } DRAMSim2 * DRAMSim2Params::create() { return new DRAMSim2(this); } bool DRAMSim2::MemoryPort::recvTimingReq(PacketPtr pkt) { /* I don't know when they can remove this... */ /// @todo temporary hack to deal with memory corruption issue until /// 4-phase transactions are complete. Remove me later //cout << "Cycle: " << dramsim2->currentClockCycle << " Receive Timing Request" << endl; this->removePendingDelete(); DRAMSim2* dram = dynamic_cast<DRAMSim2*>(memory); bool retVal = false; // if DRAMSim2 is disabled, just use the default recvTiming. if( !dram ) { return SimpleTimingPort::recvTimingReq(pkt); } else { if (pkt->memInhibitAsserted()) { // snooper will supply based on copy of packet // still target's responsibility to delete packet delete pkt; return true; } uint64_t addr = pkt->getAddr(); AccessMetaInfo meta; meta.pkt = pkt; meta.port = this; TransactionType transType; while ((double)dramsim2->currentClockCycle <= (double)(curTick()) / 1000.0 / tCK) { dramsim2->update(); } if (pkt->needsResponse()) { if (pkt->isRead()) { transType = DATA_READ; } else if (pkt->isWrite()) { transType = DATA_WRITE; } else { // only leverage the atomic access to move data, don't use the // latency //std::cout << "case 1" << std::endl; dram->doAtomicAccess(pkt); assert(pkt->isResponse()); schedTimingResp(pkt, curTick() + 1, pkt->threadID); return true; } // record the READ/WRITE request for later use uint64_t index = addr << 1; if (transType == DATA_WRITE) index = index | 0x1; dram->ongoingAccess.insert(make_pair(index, meta)); uint64_t threadID = pkt->threadID; // For trace generation if (threadID >= dram->num_pids) threadID = 0; Transaction tr = Transaction(transType, addr, NULL, threadID, dramsim2->currentClockCycle, 0); retVal = dramsim2->addTransaction(tr); //std::cout << "case 2" << std::endl; //std::cout << "Thread: " << threadID << std::endl; //std::cout << "Addr : " << std::hex << setfill('0') << setw(8) << addr << std::endl; } else { if (pkt->isWrite()) { // write-back does not need a response, but DRAMsim2 needs to track it transType = DATA_WRITE; uint64_t threadID = pkt->threadID; // For trace generation if (threadID >= dram->num_pids) threadID = 0; Transaction tr = Transaction(transType, addr, NULL, threadID, dramsim2->currentClockCycle, 0); retVal = dramsim2->addTransaction(tr); if (retVal == true) { dram->doAtomicAccess(pkt); this->addPendingDelete(pkt); } //std::cout << "case 3" << std::endl; // assert(retVal == true); } else { //std::cout << "case 4" << std::endl; retVal = dram->doAtomicAccess(pkt); // Again, I don't know.... /// @todo nominally we should just delete the packet here. /// Until 4-phase stuff we can't because the sending /// cache is still relying on it this->addPendingDelete(pkt); } } } return retVal; } void DRAMSim2::read_complete(unsigned id, uint64_t address, uint64_t clock_cycle, uint64_t threadID) { //printf("read complete for %llx @ cycle %llu\n", address, clock_cycle); uint64_t index = address << 1; if (ongoingAccess.count(index)) { AccessMetaInfo meta = ongoingAccess.find(index)->second; PacketPtr pkt = meta.pkt; DRAMSim2::MemoryPort *my_port = (DRAMSim2::MemoryPort*)(meta.port); my_port->removePendingDelete(); if (pkt->needsResponse()) { doAtomicAccess(pkt); assert(pkt->isResponse()); // remove the skew between DRAMSim2 and gem5 Tick toSchedule = (Tick)(clock_cycle) * (Tick)(tCK * 1000); if (toSchedule <= curTick()) toSchedule = curTick() + 1; //not accurate, but I have to if (toSchedule >= curTick() + SimClock::Int::ms) toSchedule = curTick() + SimClock::Int::ms - 1; //not accurate my_port->schedTimingResp(pkt, toSchedule, threadID); } else { my_port->addPendingDelete(pkt); } ongoingAccess.erase(ongoingAccess.find(index)); } } void DRAMSim2::write_complete(unsigned id, uint64_t address, uint64_t clock_cycle, uint64_t threadID) { uint64_t index = address << 1; index = index | 0x1; if (ongoingAccess.count(index)) { AccessMetaInfo meta = ongoingAccess.find(index)->second; PacketPtr pkt = meta.pkt; DRAMSim2::MemoryPort *my_port = (DRAMSim2::MemoryPort*)(meta.port); my_port->removePendingDelete(); if (pkt->needsResponse()) { doAtomicAccess(pkt); assert(pkt->isResponse()); Tick toSchedule = (Tick)(clock_cycle) * (Tick)(tCK * 1000); if (toSchedule <= curTick()) toSchedule = curTick() + 1; //not accurate, but I have to if (toSchedule >= curTick() + SimClock::Int::ms) toSchedule = curTick() + SimClock::Int::ms - 1; //not accurate my_port->schedTimingResp(pkt, toSchedule, threadID); } else { my_port->addPendingDelete(pkt); } ongoingAccess.erase(ongoingAccess.find(index)); } } void DRAMSim2::report_power(double a, double b, double c, double d) { } <|endoftext|>
<commit_before>#include "SkFontHost.h" #include <math.h> // define this to use pre-compiled tables for gamma. This is slightly faster, // and doesn't create any RW global memory, but means we cannot change the // gamma at runtime. #define USE_PREDEFINED_GAMMA_TABLES #ifndef USE_PREDEFINED_GAMMA_TABLES // define this if you want to spew out the "C" code for the tables, given // the current values for SK_BLACK_GAMMA and SK_WHITE_GAMMA. #define DUMP_GAMMA_TABLESx #endif /////////////////////////////////////////////////////////////////////////////// #ifdef USE_PREDEFINED_GAMMA_TABLES #include "sk_predefined_gamma.h" #else // use writable globals for gamma tables static bool gGammaIsBuilt; static uint8_t gBlackGamma[256], gWhiteGamma[256]; #define SK_BLACK_GAMMA (1.4f) #define SK_WHITE_GAMMA (1/1.4f) static void build_power_table(uint8_t table[], float ee) { // printf("------ build_power_table %g\n", ee); for (int i = 0; i < 256; i++) { float x = i / 255.f; // printf(" %d %g", i, x); x = powf(x, ee); // printf(" %g", x); int xx = SkScalarRound(SkFloatToScalar(x * 255)); // printf(" %d\n", xx); table[i] = SkToU8(xx); } } #ifdef DUMP_GAMMA_TABLES #include "SkString.h" static void dump_a_table(const char name[], const uint8_t table[], float gamma) { SkDebugf("\n"); SkDebugf("\/\/ Gamma table for %g\n", gamma); SkDebugf("static const uint8_t %s[] = {\n", name); for (int y = 0; y < 16; y++) { SkString line, tmp; for (int x = 0; x < 16; x++) { tmp.printf("0x%02X, ", *table++); line.append(tmp); } SkDebugf(" %s\n", line.c_str()); } SkDebugf("};\n"); } #endif #endif /////////////////////////////////////////////////////////////////////////////// void SkFontHost::GetGammaTables(const uint8_t* tables[2]) { #ifndef USE_PREDEFINED_GAMMA_TABLES if (!gGammaIsBuilt) { build_power_table(gBlackGamma, SK_BLACK_GAMMA); build_power_table(gWhiteGamma, SK_WHITE_GAMMA); gGammaIsBuilt = true; #ifdef DUMP_GAMMA_TABLES dump_a_table("gBlackGamma", gBlackGamma, SK_BLACK_GAMMA); dump_a_table("gWhiteGamma", gWhiteGamma, SK_WHITE_GAMMA); #endif } #endif tables[0] = gBlackGamma; tables[1] = gWhiteGamma; } // If the luminance is <= this value, then apply the black gamma table #define BLACK_GAMMA_THRESHOLD 0x40 // If the luminance is >= this value, then apply the white gamma table #define WHITE_GAMMA_THRESHOLD 0xC0 int SkFontHost::ComputeGammaFlag(const SkPaint& paint) { if (paint.getShader() == NULL) { SkColor c = paint.getColor(); int r = SkColorGetR(c); int g = SkColorGetG(c); int b = SkColorGetB(c); int luminance = (r * 2 + g * 5 + b) >> 3; if (luminance <= BLACK_GAMMA_THRESHOLD) { // printf("------ black gamma for [%d %d %d]\n", r, g, b); return SkScalerContext::kGammaForBlack_Flag; } if (luminance >= WHITE_GAMMA_THRESHOLD) { // printf("------ white gamma for [%d %d %d]\n", r, g, b); return SkScalerContext::kGammaForWhite_Flag; } } return 0; } <commit_msg>am 9d93915d: enable runtime changes to gamma tables<commit_after>#include "SkFontHost.h" #include <math.h> // define this to use pre-compiled tables for gamma. This is slightly faster, // and doesn't create any RW global memory, but means we cannot change the // gamma at runtime. //#define USE_PREDEFINED_GAMMA_TABLES #ifndef USE_PREDEFINED_GAMMA_TABLES // define this if you want to spew out the "C" code for the tables, given // the current values for SK_BLACK_GAMMA and SK_WHITE_GAMMA. #define DUMP_GAMMA_TABLESx #endif /////////////////////////////////////////////////////////////////////////////// #include "SkGraphics.h" // declared here, so we can link against it elsewhere void skia_set_text_gamma(float blackGamma, float whiteGamma); #ifdef USE_PREDEFINED_GAMMA_TABLES #include "sk_predefined_gamma.h" void skia_set_text_gamma(float blackGamma, float whiteGamma) {} #else // use writable globals for gamma tables static void build_power_table(uint8_t table[], float ee) { SkDebugf("------ build_power_table %g\n", ee); for (int i = 0; i < 256; i++) { float x = i / 255.f; // printf(" %d %g", i, x); x = powf(x, ee); // printf(" %g", x); int xx = SkScalarRound(SkFloatToScalar(x * 255)); // printf(" %d\n", xx); table[i] = SkToU8(xx); } } static bool gGammaIsBuilt; static uint8_t gBlackGamma[256], gWhiteGamma[256]; static float gBlackGammaCoeff = 1.4f; static float gWhiteGammaCoeff = 1/1.4f; void skia_set_text_gamma(float blackGamma, float whiteGamma) { gBlackGammaCoeff = blackGamma; gWhiteGammaCoeff = whiteGamma; gGammaIsBuilt = false; SkGraphics::SetFontCacheUsed(0); build_power_table(gBlackGamma, gBlackGammaCoeff); build_power_table(gWhiteGamma, gWhiteGammaCoeff); } #ifdef DUMP_GAMMA_TABLES #include "SkString.h" static void dump_a_table(const char name[], const uint8_t table[], float gamma) { SkDebugf("\n"); SkDebugf("\/\/ Gamma table for %g\n", gamma); SkDebugf("static const uint8_t %s[] = {\n", name); for (int y = 0; y < 16; y++) { SkString line, tmp; for (int x = 0; x < 16; x++) { tmp.printf("0x%02X, ", *table++); line.append(tmp); } SkDebugf(" %s\n", line.c_str()); } SkDebugf("};\n"); } #endif #endif /////////////////////////////////////////////////////////////////////////////// void SkFontHost::GetGammaTables(const uint8_t* tables[2]) { #ifndef USE_PREDEFINED_GAMMA_TABLES if (!gGammaIsBuilt) { build_power_table(gBlackGamma, gBlackGammaCoeff); build_power_table(gWhiteGamma, gWhiteGammaCoeff); gGammaIsBuilt = true; #ifdef DUMP_GAMMA_TABLES dump_a_table("gBlackGamma", gBlackGamma, gBlackGammaCoeff); dump_a_table("gWhiteGamma", gWhiteGamma, gWhiteGammaCoeff); #endif } #endif tables[0] = gBlackGamma; tables[1] = gWhiteGamma; } // If the luminance is <= this value, then apply the black gamma table #define BLACK_GAMMA_THRESHOLD 0x40 // If the luminance is >= this value, then apply the white gamma table #define WHITE_GAMMA_THRESHOLD 0xC0 int SkFontHost::ComputeGammaFlag(const SkPaint& paint) { if (paint.getShader() == NULL) { SkColor c = paint.getColor(); int r = SkColorGetR(c); int g = SkColorGetG(c); int b = SkColorGetB(c); int luminance = (r * 2 + g * 5 + b) >> 3; if (luminance <= BLACK_GAMMA_THRESHOLD) { // printf("------ black gamma for [%d %d %d]\n", r, g, b); return SkScalerContext::kGammaForBlack_Flag; } if (luminance >= WHITE_GAMMA_THRESHOLD) { // printf("------ white gamma for [%d %d %d]\n", r, g, b); return SkScalerContext::kGammaForWhite_Flag; } } return 0; } <|endoftext|>
<commit_before>/* This file is part of fus. * * fus is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * fus is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with fus. If not, see <http://www.gnu.org/licenses/>. */ FUS_NET_STRUCT_BEGIN(db_pingRequest) FUS_NET_FIELD_UINT32(transId) FUS_NET_FIELD_UINT32(pingTime) FUS_NET_STRUCT_END(db_pingRequest) FUS_NET_STRUCT_BEGIN(db_acctCreateRequest) FUS_NET_FIELD_UINT32(transId) FUS_NET_FIELD_STRING(name, 64) FUS_NET_FIELD_UINT32(flags) FUS_NET_FIELD_BUFFER_TINY(hash) FUS_NET_STRUCT_END(db_acctCreateRequest) // ================================================================================= FUS_NET_STRUCT_BEGIN(db_pingReply) FUS_NET_FIELD_UINT32(transId) FUS_NET_FIELD_UINT32(pingTime) FUS_NET_STRUCT_END(db_pingReply) FUS_NET_STRUCT_BEGIN(db_acctCreateReply) FUS_NET_FIELD_UINT32(transId) FUS_NET_FIELD_UINT32(result) FUS_NET_FIELD_UUID(uuid) FUS_NET_STRUCT_END(db_acctCreateReply) <commit_msg>Fix VS's "helpful" deindent<commit_after>/* This file is part of fus. * * fus is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * fus is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with fus. If not, see <http://www.gnu.org/licenses/>. */ FUS_NET_STRUCT_BEGIN(db_pingRequest) FUS_NET_FIELD_UINT32(transId) FUS_NET_FIELD_UINT32(pingTime) FUS_NET_STRUCT_END(db_pingRequest) FUS_NET_STRUCT_BEGIN(db_acctCreateRequest) FUS_NET_FIELD_UINT32(transId) FUS_NET_FIELD_STRING(name, 64) FUS_NET_FIELD_UINT32(flags) FUS_NET_FIELD_BUFFER_TINY(hash) FUS_NET_STRUCT_END(db_acctCreateRequest) // ================================================================================= FUS_NET_STRUCT_BEGIN(db_pingReply) FUS_NET_FIELD_UINT32(transId) FUS_NET_FIELD_UINT32(pingTime) FUS_NET_STRUCT_END(db_pingReply) FUS_NET_STRUCT_BEGIN(db_acctCreateReply) FUS_NET_FIELD_UINT32(transId) FUS_NET_FIELD_UINT32(result) FUS_NET_FIELD_UUID(uuid) FUS_NET_STRUCT_END(db_acctCreateReply) <|endoftext|>
<commit_before>// -*- C++ -*- #include <iostream> #include <string> #include "apache2/httpd.h" #include "apache2/http_core.h" #include "apache2/http_protocol.h" #include "apache2/http_request.h" #include "apache2/util_script.h" #include "acmacs-base/read-file.hh" // #include "apr_hooks.h" static void register_hooks(apr_pool_t *pool); static int acmacs_handler(request_rec *r); extern "C" module acmacs_module; module AP_MODULE_DECLARE_DATA acmacs_module = { STANDARD20_MODULE_STUFF, nullptr, nullptr, nullptr, nullptr, nullptr, register_hooks }; static void register_hooks(apr_pool_t * /*pool*/) { ap_hook_handler(acmacs_handler, nullptr, nullptr, APR_HOOK_LAST); } static int acmacs_handler(request_rec *r) { // std::cerr << "acmacs_handler handler " << r->handler << '\n'; if (!r->handler || r->handler != std::string("acmacs")) return (DECLINED); apr_table_t *GET; ap_args_to_table(r, &GET); const auto acv = apr_table_get(GET, "acv"); const std::string data = acmacs::file::read(r->filename); ap_set_content_type(r, "application/json"); ap_rprintf(r, "{N: \"Hello, world! filename:[%s] args:[%s] acv:[%s]\"}\n\n", r->filename, r->args, acv ? acv : "null"); // ap_rputs(data.c_str(), r); return OK; } // ---------------------------------------------------------------------- /// Local Variables: /// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer)) /// End: <commit_msg>apache module mod_acmacs development<commit_after>// -*- C++ -*- #include <iostream> #include <string> #include "apache2/httpd.h" #include "apache2/http_core.h" #include "apache2/http_protocol.h" #include "apache2/http_request.h" #include "apache2/http_log.h" #include "apache2/util_script.h" #include "acmacs-base/read-file.hh" // #include "apr_hooks.h" extern "C" { // module acmacs_module; //AP_DECLARE_MODULE(acmacs); } #define AP_LOG_DEBUG(rec, fmt, ...) ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, rec, fmt, ##__VA_ARGS__) #define AP_LOG_INFO(rec, fmt, ...) ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, rec, "[" HR_AUTH "] " fmt, ##__VA_ARGS__) #define AP_LOG_WARN(rec, fmt, ...) ap_log_rerror(APLOG_MARK, APLOG_WARNING,0, rec, "[" HR_AUTH "] " fmt, ##__VA_ARGS__) #define AP_LOG_ERR(rec, fmt, ...) ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, rec, "[" HR_AUTH "] " fmt, ##__VA_ARGS__) static void register_hooks(apr_pool_t *pool); static int acmacs_handler(request_rec *r); // extern "C" module acmacs_module; extern "C" { module AP_MODULE_DECLARE_DATA acmacs_module = { STANDARD20_MODULE_STUFF, nullptr, nullptr, nullptr, nullptr, nullptr, register_hooks }; } static void register_hooks(apr_pool_t * /*pool*/) { ap_hook_handler(acmacs_handler, nullptr, nullptr, APR_HOOK_LAST); } static int acmacs_handler_processed = 0; static int acmacs_handler(request_rec *r) { // std::cerr << "acmacs_handler handler " << r->handler << '\n'; if (!r->handler || r->handler != std::string("acmacs")) return DECLINED; apr_table_t *GET; ap_args_to_table(r, &GET); const auto acv = apr_table_get(GET, "acv"); if (!acv) return DECLINED; ++acmacs_handler_processed; // AP_LOG_DEBUG(r, "acv: %s processed: %d", acv, acmacs_handler_processed); const std::string data = acmacs::file::read(r->filename); ap_set_content_type(r, "application/json"); ap_rprintf(r, "{N: \"Hello, world! filename:[%s] args:[%s] acv:[%s]\", processed: %d}\n\n", r->filename, r->args, acv ? acv : "null", acmacs_handler_processed); // ap_rputs(data.c_str(), r); return OK; } // ---------------------------------------------------------------------- /// Local Variables: /// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer)) /// End: <|endoftext|>
<commit_before>/* * @file adaboost_impl.hpp * @author Udit Saxena * * Implementation of the AdaBoost class. * * @code * @article{schapire1999improved, * author = {Schapire, Robert E. and Singer, Yoram}, * title = {Improved Boosting Algorithms Using Confidence-rated Predictions}, * journal = {Machine Learning}, * volume = {37}, * number = {3}, * month = dec, * year = {1999}, * issn = {0885-6125}, * pages = {297--336}, * } * @endcode */ #ifndef __MLPACK_METHODS_ADABOOST_ADABOOST_IMPL_HPP #define __MLPACK_METHODS_ADABOOST_ADABOOST_IMPL_HPP #include "adaboost.hpp" namespace mlpack { namespace adaboost { /** * Constructor. Currently runs the AdaBoost.MH algorithm. * * @param data Input data * @param labels Corresponding labels * @param iterations Number of boosting rounds * @param tol Tolerance for termination of Adaboost.MH. * @param other Weak Learner, which has been initialized already. */ template<typename WeakLearnerType, typename MatType> AdaBoost<WeakLearnerType, MatType>::AdaBoost( const MatType& data, const arma::Row<size_t>& labels, const WeakLearnerType& other, const size_t iterations, const double tol) { Train(data, labels, other, iterations, tol); } // Empty constructor. template<typename WeakLearnerType, typename MatType> AdaBoost<WeakLearnerType, MatType>::AdaBoost(const double tolerance) : tolerance(tolerance) { // Nothing to do. } // Train AdaBoost. template<typename WeakLearnerType, typename MatType> void AdaBoost<WeakLearnerType, MatType>::Train( const MatType& data, const arma::Row<size_t>& labels, const WeakLearnerType& other, const size_t iterations, const double tolerance) { // Clear information from previous runs. wl.clear(); alpha.clear(); // Count the number of classes. classes = (arma::max(labels) - arma::min(labels)) + 1; this->tolerance = tolerance; // crt is the cumulative rt value for terminating the optimization when rt is // changing by less than the tolerance. double rt, crt, alphat = 0.0, zt; ztProduct = 1.0; // To be used for prediction by the weak learner. arma::Row<size_t> predictedLabels(labels.n_cols); // Use tempData to modify input data for incorporating weights. MatType tempData(data); // This matrix is a helper matrix used to calculate the final hypothesis. arma::mat sumFinalH = arma::zeros<arma::mat>(classes, predictedLabels.n_cols); // Load the initial weights into a 2-D matrix. const double initWeight = 1.0 / double(data.n_cols * classes); arma::mat D(classes, data.n_cols); D.fill(initWeight); // Weights are stored in this row vector. arma::rowvec weights(predictedLabels.n_cols); // This is the final hypothesis. arma::Row<size_t> finalH(predictedLabels.n_cols); // Now, start the boosting rounds. for (size_t i = 0; i < iterations; i++) { // Initialized to zero in every round. rt is used for calculation of // alphat; it is the weighted error. // rt = (sum) D(i) y(i) ht(xi) rt = 0.0; // zt is used for weight normalization. zt = 0.0; // Build the weight vectors. weights = arma::sum(D); // Use the existing weak learner to train a new one with new weights. WeakLearnerType w(other, tempData, labels, weights); w.Classify(tempData, predictedLabels); // Now from predictedLabels, build ht, the weak hypothesis // buildClassificationMatrix(ht, predictedLabels); // Now, calculate alpha(t) using ht. for (size_t j = 0; j < D.n_cols; j++) // instead of D, ht { if (predictedLabels(j) == labels(j)) rt += arma::accu(D.col(j)); else rt -= arma::accu(D.col(j)); } if ((i > 0) && (std::abs(rt - crt) < tolerance)) break; crt = rt; // Our goal is to find alphat which mizimizes or approximately minimizes the // value of Z as a function of alpha. alphat = 0.5 * log((1 + rt) / (1 - rt)); alpha.push_back(alphat); wl.push_back(w); // Now start modifying the weights. for (size_t j = 0; j < D.n_cols; j++) { const double expo = exp(alphat); if (predictedLabels(j) == labels(j)) { for (size_t k = 0; k < D.n_rows; k++) { // We calculate zt, the normalization constant. D(k, j) /= expo; zt += D(k, j); // * exp(-1 * alphat * yt(j,k) * ht(j,k)); // Add to the final hypothesis matrix. // sumFinalH(k, j) += (alphat * ht(k, j)); if (k == labels(j)) sumFinalH(k, j) += (alphat); // * ht(k, j)); else sumFinalH(k, j) -= (alphat); } } else { for (size_t k = 0; k < D.n_rows; k++) { // We calculate zt, the normalization constant. D(k, j) *= expo; zt += D(k, j); // Add to the final hypothesis matrix. if (k == labels(j)) sumFinalH(k, j) += alphat; // * ht(k, j)); else sumFinalH(k, j) -= alphat; } } } // Normalize D. D /= zt; // Accumulate the value of zt for the Hamming loss bound. ztProduct *= zt; } } /** * Classify the given test points. */ template<typename WeakLearnerType, typename MatType> void AdaBoost<WeakLearnerType, MatType>::Classify( const MatType& test, arma::Row<size_t>& predictedLabels) { arma::Row<size_t> tempPredictedLabels(test.n_cols); arma::mat cMatrix(classes, test.n_cols); cMatrix.zeros(); predictedLabels.set_size(test.n_cols); for (size_t i = 0; i < wl.size(); i++) { wl[i].Classify(test, tempPredictedLabels); for (size_t j = 0; j < tempPredictedLabels.n_cols; j++) cMatrix(tempPredictedLabels(j), j) += alpha[i]; } arma::colvec cMRow; arma::uword maxIndex; for (size_t i = 0; i < predictedLabels.n_cols; i++) { cMRow = cMatrix.unsafe_col(i); cMRow.max(maxIndex); predictedLabels(i) = maxIndex; } } /** * Serialize the AdaBoost model. */ template<typename WeakLearnerType, typename MatType> template<typename Archive> void AdaBoost<WeakLearnerType, MatType>::Serialize(Archive& ar, const unsigned int /* version */) { ar & data::CreateNVP(classes, "classes"); ar & data::CreateNVP(tolerance, "tolerance"); ar & data::CreateNVP(ztProduct, "ztProduct"); ar & data::CreateNVP(alpha, "alpha"); // Now serialize each weak learner. if (Archive::is_loading::value) { wl.clear(); wl.resize(alpha.size()); } for (size_t i = 0; i < wl.size(); ++i) { std::ostringstream oss; oss << "weakLearner" << i; ar & data::CreateNVP(wl[i], oss.str()); } } } // namespace adaboost } // namespace mlpack #endif <commit_msg>Fix -Wmaybe-uninitialized.<commit_after>/* * @file adaboost_impl.hpp * @author Udit Saxena * * Implementation of the AdaBoost class. * * @code * @article{schapire1999improved, * author = {Schapire, Robert E. and Singer, Yoram}, * title = {Improved Boosting Algorithms Using Confidence-rated Predictions}, * journal = {Machine Learning}, * volume = {37}, * number = {3}, * month = dec, * year = {1999}, * issn = {0885-6125}, * pages = {297--336}, * } * @endcode */ #ifndef __MLPACK_METHODS_ADABOOST_ADABOOST_IMPL_HPP #define __MLPACK_METHODS_ADABOOST_ADABOOST_IMPL_HPP #include "adaboost.hpp" namespace mlpack { namespace adaboost { /** * Constructor. Currently runs the AdaBoost.MH algorithm. * * @param data Input data * @param labels Corresponding labels * @param iterations Number of boosting rounds * @param tol Tolerance for termination of Adaboost.MH. * @param other Weak Learner, which has been initialized already. */ template<typename WeakLearnerType, typename MatType> AdaBoost<WeakLearnerType, MatType>::AdaBoost( const MatType& data, const arma::Row<size_t>& labels, const WeakLearnerType& other, const size_t iterations, const double tol) { Train(data, labels, other, iterations, tol); } // Empty constructor. template<typename WeakLearnerType, typename MatType> AdaBoost<WeakLearnerType, MatType>::AdaBoost(const double tolerance) : tolerance(tolerance) { // Nothing to do. } // Train AdaBoost. template<typename WeakLearnerType, typename MatType> void AdaBoost<WeakLearnerType, MatType>::Train( const MatType& data, const arma::Row<size_t>& labels, const WeakLearnerType& other, const size_t iterations, const double tolerance) { // Clear information from previous runs. wl.clear(); alpha.clear(); // Count the number of classes. classes = (arma::max(labels) - arma::min(labels)) + 1; this->tolerance = tolerance; // crt is the cumulative rt value for terminating the optimization when rt is // changing by less than the tolerance. double rt, crt = 0.0, alphat = 0.0, zt; ztProduct = 1.0; // To be used for prediction by the weak learner. arma::Row<size_t> predictedLabels(labels.n_cols); // Use tempData to modify input data for incorporating weights. MatType tempData(data); // This matrix is a helper matrix used to calculate the final hypothesis. arma::mat sumFinalH = arma::zeros<arma::mat>(classes, predictedLabels.n_cols); // Load the initial weights into a 2-D matrix. const double initWeight = 1.0 / double(data.n_cols * classes); arma::mat D(classes, data.n_cols); D.fill(initWeight); // Weights are stored in this row vector. arma::rowvec weights(predictedLabels.n_cols); // This is the final hypothesis. arma::Row<size_t> finalH(predictedLabels.n_cols); // Now, start the boosting rounds. for (size_t i = 0; i < iterations; i++) { // Initialized to zero in every round. rt is used for calculation of // alphat; it is the weighted error. // rt = (sum) D(i) y(i) ht(xi) rt = 0.0; // zt is used for weight normalization. zt = 0.0; // Build the weight vectors. weights = arma::sum(D); // Use the existing weak learner to train a new one with new weights. WeakLearnerType w(other, tempData, labels, weights); w.Classify(tempData, predictedLabels); // Now from predictedLabels, build ht, the weak hypothesis // buildClassificationMatrix(ht, predictedLabels); // Now, calculate alpha(t) using ht. for (size_t j = 0; j < D.n_cols; j++) // instead of D, ht { if (predictedLabels(j) == labels(j)) rt += arma::accu(D.col(j)); else rt -= arma::accu(D.col(j)); } if ((i > 0) && (std::abs(rt - crt) < tolerance)) break; crt = rt; // Our goal is to find alphat which mizimizes or approximately minimizes the // value of Z as a function of alpha. alphat = 0.5 * log((1 + rt) / (1 - rt)); alpha.push_back(alphat); wl.push_back(w); // Now start modifying the weights. for (size_t j = 0; j < D.n_cols; j++) { const double expo = exp(alphat); if (predictedLabels(j) == labels(j)) { for (size_t k = 0; k < D.n_rows; k++) { // We calculate zt, the normalization constant. D(k, j) /= expo; zt += D(k, j); // * exp(-1 * alphat * yt(j,k) * ht(j,k)); // Add to the final hypothesis matrix. // sumFinalH(k, j) += (alphat * ht(k, j)); if (k == labels(j)) sumFinalH(k, j) += (alphat); // * ht(k, j)); else sumFinalH(k, j) -= (alphat); } } else { for (size_t k = 0; k < D.n_rows; k++) { // We calculate zt, the normalization constant. D(k, j) *= expo; zt += D(k, j); // Add to the final hypothesis matrix. if (k == labels(j)) sumFinalH(k, j) += alphat; // * ht(k, j)); else sumFinalH(k, j) -= alphat; } } } // Normalize D. D /= zt; // Accumulate the value of zt for the Hamming loss bound. ztProduct *= zt; } } /** * Classify the given test points. */ template<typename WeakLearnerType, typename MatType> void AdaBoost<WeakLearnerType, MatType>::Classify( const MatType& test, arma::Row<size_t>& predictedLabels) { arma::Row<size_t> tempPredictedLabels(test.n_cols); arma::mat cMatrix(classes, test.n_cols); cMatrix.zeros(); predictedLabels.set_size(test.n_cols); for (size_t i = 0; i < wl.size(); i++) { wl[i].Classify(test, tempPredictedLabels); for (size_t j = 0; j < tempPredictedLabels.n_cols; j++) cMatrix(tempPredictedLabels(j), j) += alpha[i]; } arma::colvec cMRow; arma::uword maxIndex; for (size_t i = 0; i < predictedLabels.n_cols; i++) { cMRow = cMatrix.unsafe_col(i); cMRow.max(maxIndex); predictedLabels(i) = maxIndex; } } /** * Serialize the AdaBoost model. */ template<typename WeakLearnerType, typename MatType> template<typename Archive> void AdaBoost<WeakLearnerType, MatType>::Serialize(Archive& ar, const unsigned int /* version */) { ar & data::CreateNVP(classes, "classes"); ar & data::CreateNVP(tolerance, "tolerance"); ar & data::CreateNVP(ztProduct, "ztProduct"); ar & data::CreateNVP(alpha, "alpha"); // Now serialize each weak learner. if (Archive::is_loading::value) { wl.clear(); wl.resize(alpha.size()); } for (size_t i = 0; i < wl.size(); ++i) { std::ostringstream oss; oss << "weakLearner" << i; ar & data::CreateNVP(wl[i], oss.str()); } } } // namespace adaboost } // namespace mlpack #endif <|endoftext|>
<commit_before>// Copyright 2010-2013 RethinkDB, all rights reserved. #include "rdb_protocol/terms/terms.hpp" #include <string> #include <utility> #include "errors.hpp" #include <boost/bind.hpp> #include "rdb_protocol/datum_stream.hpp" #include "rdb_protocol/error.hpp" #include "rdb_protocol/func.hpp" #include "rdb_protocol/op.hpp" #include "rdb_protocol/term_walker.hpp" namespace ql { // NOTE: `asc` and `desc` don't fit into our type system (they're a hack for // orderby to avoid string parsing), so we instead literally examine the // protobuf to determine whether they're present. This is a hack. (This is // implemented internally in terms of string concatenation because that's what // the old string-parsing solution was, and this was a quick way to get the new // behavior that also avoided dumping already-tested code paths. I'm probably // going to hell for it though.) class asc_term_t : public op_term_t { public: asc_term_t(compile_env_t *env, const protob_t<const Term> &term) : op_term_t(env, term, argspec_t(1)) { } private: virtual counted_t<val_t> eval_impl(scope_env_t *env, UNUSED eval_flags_t flags) { return arg(env, 0); } virtual const char *name() const { return "asc"; } }; class desc_term_t : public op_term_t { public: desc_term_t(compile_env_t *env, const protob_t<const Term> &term) : op_term_t(env, term, argspec_t(1)) { } private: virtual counted_t<val_t> eval_impl(scope_env_t *env, UNUSED eval_flags_t flags) { return arg(env, 0); } virtual const char *name() const { return "desc"; } }; class orderby_term_t : public op_term_t { public: orderby_term_t(compile_env_t *env, const protob_t<const Term> &term) : op_term_t(env, term, argspec_t(1, -1), optargspec_t({"index"})), src_term(term) { } private: enum order_direction_t { ASC, DESC }; class lt_cmp_t { public: typedef bool result_type; explicit lt_cmp_t( std::vector<std::pair<order_direction_t, counted_t<func_t> > > _comparisons) : comparisons(std::move(_comparisons)) { } bool operator()(env_t *env, profile::sampler_t *sampler, counted_t<const datum_t> l, counted_t<const datum_t> r) const { sampler->new_sample(); for (auto it = comparisons.begin(); it != comparisons.end(); ++it) { counted_t<const datum_t> lval; counted_t<const datum_t> rval; try { lval = it->second->call(env, l)->as_datum(); } catch (const base_exc_t &e) { if (e.get_type() != base_exc_t::NON_EXISTENCE) { throw; } } try { rval = it->second->call(env, r)->as_datum(); } catch (const base_exc_t &e) { if (e.get_type() != base_exc_t::NON_EXISTENCE) { throw; } } if (!lval.has() && !rval.has()) { continue; } if (!lval.has()) { return true != (it->first == DESC); } if (!rval.has()) { return false != (it->first == DESC); } // TODO: use datum_t::cmp instead to be faster if (*lval == *rval) { continue; } return (*lval < *rval) != (it->first == DESC); } return false; } private: const std::vector<std::pair<order_direction_t, counted_t<func_t> > > comparisons; }; virtual counted_t<val_t> eval_impl(scope_env_t *env, UNUSED eval_flags_t flags) { std::vector<std::pair<order_direction_t, counted_t<func_t> > > comparisons; scoped_ptr_t<datum_t> arr(new datum_t(datum_t::R_ARRAY)); for (size_t i = 1; i < num_args(); ++i) { if (get_src()->args(i).type() == Term::DESC) { comparisons.push_back( std::make_pair(DESC, arg(env, i)->as_func(GET_FIELD_SHORTCUT))); } else { comparisons.push_back( std::make_pair(ASC, arg(env, i)->as_func(GET_FIELD_SHORTCUT))); } } lt_cmp_t lt_cmp(comparisons); counted_t<table_t> tbl; counted_t<datum_stream_t> seq; counted_t<val_t> v0 = arg(env, 0); if (v0->get_type().is_convertible(val_t::type_t::TABLE)) { tbl = v0->as_table(); } else if (v0->get_type().is_convertible(val_t::type_t::SELECTION)) { std::pair<counted_t<table_t>, counted_t<datum_stream_t> > ts = v0->as_selection(env->env); tbl = ts.first; seq = ts.second; } else { seq = v0->as_seq(env->env); } /* Add a sorting to the table if we're doing indexed sorting. */ if (counted_t<val_t> index = optarg(env, "index")) { rcheck(tbl.has(), base_exc_t::GENERIC, "Indexed order_by can only be performed on a TABLE."); rcheck(!seq.has(), base_exc_t::GENERIC, "Indexed order_by can only be performed on a TABLE."); sorting_t sorting = sorting_t::UNORDERED; for (int i = 0; i < get_src()->optargs_size(); ++i) { if (get_src()->optargs(i).key() == "index") { if (get_src()->optargs(i).val().type() == Term::DESC) { sorting = sorting_t::DESCENDING; } else { sorting = sorting_t::ASCENDING; } } } r_sanity_check(sorting != sorting_t::UNORDERED); std::string index_str = index->as_str().to_std(); tbl->add_sorting(index_str, sorting, this); if (index_str != tbl->get_pkey() && !comparisons.empty()) { seq = make_counted<indexed_sort_datum_stream_t>( tbl->as_datum_stream(env->env, backtrace()), lt_cmp); } else { seq = tbl->as_datum_stream(env->env, backtrace()); } } else { if (!seq.has()) { seq = tbl->as_datum_stream(env->env, backtrace()); } rcheck(!comparisons.empty(), base_exc_t::GENERIC, "Must specify something to order by."); std::vector<counted_t<const datum_t> > to_sort; batchspec_t batchspec = batchspec_t::user(batch_type_t::TERMINAL, env->env); for (;;) { std::vector<counted_t<const datum_t> > data = seq->next_batch(env->env, batchspec); if (data.size() == 0) { break; } std::move(data.begin(), data.end(), std::back_inserter(to_sort)); rcheck(to_sort.size() <= array_size_limit(), base_exc_t::GENERIC, strprintf("Array over size limit %zu.", array_size_limit()).c_str()); } profile::sampler_t sampler("Sorting in-memory.", env->env->trace); auto fn = boost::bind(lt_cmp, env->env, &sampler, _1, _2); std::sort(to_sort.begin(), to_sort.end(), fn); seq = make_counted<array_datum_stream_t>( make_counted<const datum_t>(std::move(to_sort)), backtrace()); } return tbl.has() ? new_val(seq, tbl) : new_val(env->env, seq); } virtual const char *name() const { return "orderby"; } private: protob_t<const Term> src_term; }; class distinct_term_t : public op_term_t { public: distinct_term_t(compile_env_t *env, const protob_t<const Term> &term) : op_term_t(env, term, argspec_t(1)) { } private: static bool lt_cmp(env_t *, counted_t<const datum_t> l, counted_t<const datum_t> r) { return *l < *r; } virtual counted_t<val_t> eval_impl(scope_env_t *env, UNUSED eval_flags_t flags) { counted_t<datum_stream_t> s = arg(env, 0)->as_seq(env->env); std::vector<counted_t<const datum_t> > arr; counted_t<const datum_t> last; batchspec_t batchspec = batchspec_t::user(batch_type_t::TERMINAL, env->env); { profile::sampler_t sampler("Evaluating elements in distinct.", env->env->trace); while (counted_t<const datum_t> d = s->next(env->env, batchspec)) { arr.push_back(std::move(d)); rcheck_array_size(arr, base_exc_t::GENERIC); sampler.new_sample(); } } std::sort(arr.begin(), arr.end(), std::bind(lt_cmp, env->env, ph::_1, ph::_2)); std::vector<counted_t<const datum_t> > toret; for (auto it = arr.begin(); it != arr.end(); ++it) { if (toret.size() == 0 || **it != *toret[toret.size()-1]) { toret.push_back(std::move(*it)); } } return new_val(make_counted<const datum_t>(std::move(toret))); } virtual const char *name() const { return "distinct"; } }; counted_t<term_t> make_orderby_term(compile_env_t *env, const protob_t<const Term> &term) { return make_counted<orderby_term_t>(env, term); } counted_t<term_t> make_distinct_term(compile_env_t *env, const protob_t<const Term> &term) { return make_counted<distinct_term_t>(env, term); } counted_t<term_t> make_asc_term(compile_env_t *env, const protob_t<const Term> &term) { return make_counted<asc_term_t>(env, term); } counted_t<term_t> make_desc_term(compile_env_t *env, const protob_t<const Term> &term) { return make_counted<desc_term_t>(env, term); } } // namespace ql <commit_msg>Fix order_by on empty sequences.<commit_after>// Copyright 2010-2013 RethinkDB, all rights reserved. #include "rdb_protocol/terms/terms.hpp" #include <string> #include <utility> #include "errors.hpp" #include <boost/bind.hpp> #include "rdb_protocol/datum_stream.hpp" #include "rdb_protocol/error.hpp" #include "rdb_protocol/func.hpp" #include "rdb_protocol/op.hpp" #include "rdb_protocol/term_walker.hpp" namespace ql { // NOTE: `asc` and `desc` don't fit into our type system (they're a hack for // orderby to avoid string parsing), so we instead literally examine the // protobuf to determine whether they're present. This is a hack. (This is // implemented internally in terms of string concatenation because that's what // the old string-parsing solution was, and this was a quick way to get the new // behavior that also avoided dumping already-tested code paths. I'm probably // going to hell for it though.) class asc_term_t : public op_term_t { public: asc_term_t(compile_env_t *env, const protob_t<const Term> &term) : op_term_t(env, term, argspec_t(1)) { } private: virtual counted_t<val_t> eval_impl(scope_env_t *env, UNUSED eval_flags_t flags) { return arg(env, 0); } virtual const char *name() const { return "asc"; } }; class desc_term_t : public op_term_t { public: desc_term_t(compile_env_t *env, const protob_t<const Term> &term) : op_term_t(env, term, argspec_t(1)) { } private: virtual counted_t<val_t> eval_impl(scope_env_t *env, UNUSED eval_flags_t flags) { return arg(env, 0); } virtual const char *name() const { return "desc"; } }; class orderby_term_t : public op_term_t { public: orderby_term_t(compile_env_t *env, const protob_t<const Term> &term) : op_term_t(env, term, argspec_t(1, -1), optargspec_t({"index"})), src_term(term) { } private: enum order_direction_t { ASC, DESC }; class lt_cmp_t { public: typedef bool result_type; explicit lt_cmp_t( std::vector<std::pair<order_direction_t, counted_t<func_t> > > _comparisons) : comparisons(std::move(_comparisons)) { } bool operator()(env_t *env, profile::sampler_t *sampler, counted_t<const datum_t> l, counted_t<const datum_t> r) const { sampler->new_sample(); for (auto it = comparisons.begin(); it != comparisons.end(); ++it) { counted_t<const datum_t> lval; counted_t<const datum_t> rval; try { lval = it->second->call(env, l)->as_datum(); } catch (const base_exc_t &e) { if (e.get_type() != base_exc_t::NON_EXISTENCE) { throw; } } try { rval = it->second->call(env, r)->as_datum(); } catch (const base_exc_t &e) { if (e.get_type() != base_exc_t::NON_EXISTENCE) { throw; } } if (!lval.has() && !rval.has()) { continue; } if (!lval.has()) { return true != (it->first == DESC); } if (!rval.has()) { return false != (it->first == DESC); } // TODO: use datum_t::cmp instead to be faster if (*lval == *rval) { continue; } return (*lval < *rval) != (it->first == DESC); } return false; } private: const std::vector<std::pair<order_direction_t, counted_t<func_t> > > comparisons; }; virtual counted_t<val_t> eval_impl(scope_env_t *env, UNUSED eval_flags_t flags) { std::vector<std::pair<order_direction_t, counted_t<func_t> > > comparisons; scoped_ptr_t<datum_t> arr(new datum_t(datum_t::R_ARRAY)); for (size_t i = 1; i < num_args(); ++i) { if (get_src()->args(i).type() == Term::DESC) { comparisons.push_back( std::make_pair(DESC, arg(env, i)->as_func(GET_FIELD_SHORTCUT))); } else { comparisons.push_back( std::make_pair(ASC, arg(env, i)->as_func(GET_FIELD_SHORTCUT))); } } lt_cmp_t lt_cmp(comparisons); counted_t<table_t> tbl; counted_t<datum_stream_t> seq; counted_t<val_t> v0 = arg(env, 0); if (v0->get_type().is_convertible(val_t::type_t::TABLE)) { tbl = v0->as_table(); } else if (v0->get_type().is_convertible(val_t::type_t::SELECTION)) { std::pair<counted_t<table_t>, counted_t<datum_stream_t> > ts = v0->as_selection(env->env); tbl = ts.first; seq = ts.second; } else { seq = v0->as_seq(env->env); } if (seq.has() && seq->is_exhausted()){ /* Do nothing for empty sequence */ /* Add a sorting to the table if we're doing indexed sorting. */ }else if (counted_t<val_t> index = optarg(env, "index")) { rcheck(tbl.has(), base_exc_t::GENERIC, "Indexed order_by can only be performed on a TABLE."); rcheck(!seq.has(), base_exc_t::GENERIC, "Indexed order_by can only be performed on a TABLE."); sorting_t sorting = sorting_t::UNORDERED; for (int i = 0; i < get_src()->optargs_size(); ++i) { if (get_src()->optargs(i).key() == "index") { if (get_src()->optargs(i).val().type() == Term::DESC) { sorting = sorting_t::DESCENDING; } else { sorting = sorting_t::ASCENDING; } } } r_sanity_check(sorting != sorting_t::UNORDERED); std::string index_str = index->as_str().to_std(); tbl->add_sorting(index_str, sorting, this); if (index_str != tbl->get_pkey() && !comparisons.empty()) { seq = make_counted<indexed_sort_datum_stream_t>( tbl->as_datum_stream(env->env, backtrace()), lt_cmp); } else { seq = tbl->as_datum_stream(env->env, backtrace()); } } else { if (!seq.has()) { seq = tbl->as_datum_stream(env->env, backtrace()); } rcheck(!comparisons.empty(), base_exc_t::GENERIC, "Must specify something to order by."); std::vector<counted_t<const datum_t> > to_sort; batchspec_t batchspec = batchspec_t::user(batch_type_t::TERMINAL, env->env); for (;;) { std::vector<counted_t<const datum_t> > data = seq->next_batch(env->env, batchspec); if (data.size() == 0) { break; } std::move(data.begin(), data.end(), std::back_inserter(to_sort)); rcheck(to_sort.size() <= array_size_limit(), base_exc_t::GENERIC, strprintf("Array over size limit %zu.", array_size_limit()).c_str()); } profile::sampler_t sampler("Sorting in-memory.", env->env->trace); auto fn = boost::bind(lt_cmp, env->env, &sampler, _1, _2); std::sort(to_sort.begin(), to_sort.end(), fn); seq = make_counted<array_datum_stream_t>( make_counted<const datum_t>(std::move(to_sort)), backtrace()); } return tbl.has() ? new_val(seq, tbl) : new_val(env->env, seq); } virtual const char *name() const { return "orderby"; } private: protob_t<const Term> src_term; }; class distinct_term_t : public op_term_t { public: distinct_term_t(compile_env_t *env, const protob_t<const Term> &term) : op_term_t(env, term, argspec_t(1)) { } private: static bool lt_cmp(env_t *, counted_t<const datum_t> l, counted_t<const datum_t> r) { return *l < *r; } virtual counted_t<val_t> eval_impl(scope_env_t *env, UNUSED eval_flags_t flags) { counted_t<datum_stream_t> s = arg(env, 0)->as_seq(env->env); std::vector<counted_t<const datum_t> > arr; counted_t<const datum_t> last; batchspec_t batchspec = batchspec_t::user(batch_type_t::TERMINAL, env->env); { profile::sampler_t sampler("Evaluating elements in distinct.", env->env->trace); while (counted_t<const datum_t> d = s->next(env->env, batchspec)) { arr.push_back(std::move(d)); rcheck_array_size(arr, base_exc_t::GENERIC); sampler.new_sample(); } } std::sort(arr.begin(), arr.end(), std::bind(lt_cmp, env->env, ph::_1, ph::_2)); std::vector<counted_t<const datum_t> > toret; for (auto it = arr.begin(); it != arr.end(); ++it) { if (toret.size() == 0 || **it != *toret[toret.size()-1]) { toret.push_back(std::move(*it)); } } return new_val(make_counted<const datum_t>(std::move(toret))); } virtual const char *name() const { return "distinct"; } }; counted_t<term_t> make_orderby_term(compile_env_t *env, const protob_t<const Term> &term) { return make_counted<orderby_term_t>(env, term); } counted_t<term_t> make_distinct_term(compile_env_t *env, const protob_t<const Term> &term) { return make_counted<distinct_term_t>(env, term); } counted_t<term_t> make_asc_term(compile_env_t *env, const protob_t<const Term> &term) { return make_counted<asc_term_t>(env, term); } counted_t<term_t> make_desc_term(compile_env_t *env, const protob_t<const Term> &term) { return make_counted<desc_term_t>(env, term); } } // namespace ql <|endoftext|>
<commit_before>#include "Bootstrapper.hpp" #include <functional> #include <lua-cxx/LuaValue.hpp> #include <lua-cxx/loaders.hpp> #include <lua-cxx/userdata.hpp> #include "LuaPainter.hpp" #include "LuaFont.hpp" Bootstrapper::Bootstrapper() : _lua(), _desktop(_lua), _rainback(_lua) { _rainback.setWidget(&_desktop); lua::load_file(_lua, "../../demo/init.lua"); } QWidget& Bootstrapper::mainWidget() { return _desktop; } // vim: set ts=4 sw=4 : <commit_msg>Use Qt to load init.lua<commit_after>#include "Bootstrapper.hpp" #include <functional> #include <lua-cxx/LuaValue.hpp> #include <lua-cxx/loaders.hpp> #include <lua-cxx/userdata.hpp> #include "LuaPainter.hpp" #include "LuaFont.hpp" Bootstrapper::Bootstrapper() : _lua(), _desktop(_lua), _rainback(_lua) { _rainback.setWidget(&_desktop); QFile file("../../demo/init.lua"); _lua(file); } QWidget& Bootstrapper::mainWidget() { return _desktop; } // vim: set ts=4 sw=4 : <|endoftext|>
<commit_before> /* * Copyright 2012 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "Test.h" #include "SkChecksum.h" #include "SkCityHash.h" // Word size that is large enough to hold results of any checksum type. typedef uint64_t checksum_result; namespace skiatest { class ChecksumTestClass : public Test { public: static Test* Factory(void*) {return SkNEW(ChecksumTestClass); } protected: virtual void onGetName(SkString* name) { name->set("Checksum"); } virtual void onRun(Reporter* reporter) { this->fReporter = reporter; RunTest(); } private: enum Algorithm { kSkChecksum, kSkCityHash32, kSkCityHash64 }; // Call Compute(data, size) on the appropriate checksum algorithm, // depending on this->fWhichAlgorithm. checksum_result ComputeChecksum(const char *data, size_t size) { switch(fWhichAlgorithm) { case kSkChecksum: REPORTER_ASSERT_MESSAGE(fReporter, reinterpret_cast<uintptr_t>(data) % 4 == 0, "test data pointer is not 32-bit aligned"); REPORTER_ASSERT_MESSAGE(fReporter, SkIsAlign4(size), "test data size is not 32-bit aligned"); return SkChecksum::Compute(reinterpret_cast<const uint32_t *>(data), size); case kSkCityHash32: return SkCityHash::Compute32(data, size); case kSkCityHash64: return SkCityHash::Compute64(data, size); default: SkString message("fWhichAlgorithm has unknown value "); message.appendf("%d", fWhichAlgorithm); fReporter->reportFailed(message); } // we never get here return 0; } // Confirm that the checksum algorithm (specified by fWhichAlgorithm) // generates the same results if called twice over the same data. void TestChecksumSelfConsistency(size_t buf_size) { SkAutoMalloc storage(buf_size); char* ptr = reinterpret_cast<char *>(storage.get()); REPORTER_ASSERT(fReporter, GetTestDataChecksum(8, 0) == GetTestDataChecksum(8, 0)); REPORTER_ASSERT(fReporter, GetTestDataChecksum(8, 0) != GetTestDataChecksum(8, 1)); sk_bzero(ptr, buf_size); checksum_result prev = 0; // assert that as we change values (from 0 to non-zero) in // our buffer, we get a different value for (size_t i = 0; i < buf_size; ++i) { ptr[i] = (i & 0x7f) + 1; // need some non-zero value here // Try checksums of different-sized chunks, but always // 32-bit aligned and big enough to contain all the // nonzero bytes. (Remaining bytes will still be zero // from the initial sk_bzero() call.) size_t checksum_size = (((i/4)+1)*4); REPORTER_ASSERT(fReporter, checksum_size <= buf_size); checksum_result curr = ComputeChecksum(ptr, checksum_size); REPORTER_ASSERT(fReporter, prev != curr); checksum_result again = ComputeChecksum(ptr, checksum_size); REPORTER_ASSERT(fReporter, again == curr); prev = curr; } } // Return the checksum of a buffer of bytes 'len' long. // The pattern of values within the buffer will be consistent // for every call, based on 'seed'. checksum_result GetTestDataChecksum(size_t len, char seed=0) { SkAutoMalloc storage(len); char* start = reinterpret_cast<char *>(storage.get()); char* ptr = start; for (size_t i = 0; i < len; ++i) { *ptr++ = ((seed+i) & 0x7f); } checksum_result result = ComputeChecksum(start, len); return result; } void RunTest() { // Test self-consistency of checksum algorithms. fWhichAlgorithm = kSkChecksum; TestChecksumSelfConsistency(128); fWhichAlgorithm = kSkCityHash32; TestChecksumSelfConsistency(128); fWhichAlgorithm = kSkCityHash64; TestChecksumSelfConsistency(128); // Test checksum results that should be consistent across // versions and platforms. fWhichAlgorithm = kSkChecksum; REPORTER_ASSERT(fReporter, ComputeChecksum(NULL, 0) == 0); fWhichAlgorithm = kSkCityHash32; REPORTER_ASSERT(fReporter, ComputeChecksum(NULL, 0) == 0xdc56d17a); REPORTER_ASSERT(fReporter, GetTestDataChecksum(4) == 0x616e1132); REPORTER_ASSERT(fReporter, GetTestDataChecksum(8) == 0xeb0fd2d6); REPORTER_ASSERT(fReporter, GetTestDataChecksum(128) == 0x5321e430); REPORTER_ASSERT(fReporter, GetTestDataChecksum(132) == 0x924a10e4); REPORTER_ASSERT(fReporter, GetTestDataChecksum(256) == 0xd4de9dc9); REPORTER_ASSERT(fReporter, GetTestDataChecksum(260) == 0xecf0325d); fWhichAlgorithm = kSkCityHash64; REPORTER_ASSERT(fReporter, ComputeChecksum(NULL, 0) == 0x9ae16a3b2f90404f); REPORTER_ASSERT(fReporter, GetTestDataChecksum(4) == 0x82bffd898958e540); REPORTER_ASSERT(fReporter, GetTestDataChecksum(8) == 0xad5a13e1e8e93b98); REPORTER_ASSERT(fReporter, GetTestDataChecksum(128) == 0x10b153630af1f395); REPORTER_ASSERT(fReporter, GetTestDataChecksum(132) == 0x7db71dc4adcc6647); REPORTER_ASSERT(fReporter, GetTestDataChecksum(256) == 0xeee763519b91b010); REPORTER_ASSERT(fReporter, GetTestDataChecksum(260) == 0x2fe19e0b2239bc23); // TODO: note the weakness exposed by these collisions... // We need to improve the SkChecksum algorithm. // We would prefer that these asserts FAIL! // Filed as https://code.google.com/p/skia/issues/detail?id=981 // ('SkChecksum algorithm allows for way too many collisions') fWhichAlgorithm = kSkChecksum; REPORTER_ASSERT(fReporter, GetTestDataChecksum(128) == GetTestDataChecksum(256)); REPORTER_ASSERT(fReporter, GetTestDataChecksum(132) == GetTestDataChecksum(260)); } Reporter* fReporter; Algorithm fWhichAlgorithm; }; static TestRegistry gReg(ChecksumTestClass::Factory); } <commit_msg>Mark 64-bit constants as ULL to fix broken 32-bit Mac 10.6 build TBR=bungeman Review URL: https://codereview.appspot.com/6867079<commit_after> /* * Copyright 2012 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "Test.h" #include "SkChecksum.h" #include "SkCityHash.h" // Word size that is large enough to hold results of any checksum type. typedef uint64_t checksum_result; namespace skiatest { class ChecksumTestClass : public Test { public: static Test* Factory(void*) {return SkNEW(ChecksumTestClass); } protected: virtual void onGetName(SkString* name) { name->set("Checksum"); } virtual void onRun(Reporter* reporter) { this->fReporter = reporter; RunTest(); } private: enum Algorithm { kSkChecksum, kSkCityHash32, kSkCityHash64 }; // Call Compute(data, size) on the appropriate checksum algorithm, // depending on this->fWhichAlgorithm. checksum_result ComputeChecksum(const char *data, size_t size) { switch(fWhichAlgorithm) { case kSkChecksum: REPORTER_ASSERT_MESSAGE(fReporter, reinterpret_cast<uintptr_t>(data) % 4 == 0, "test data pointer is not 32-bit aligned"); REPORTER_ASSERT_MESSAGE(fReporter, SkIsAlign4(size), "test data size is not 32-bit aligned"); return SkChecksum::Compute(reinterpret_cast<const uint32_t *>(data), size); case kSkCityHash32: return SkCityHash::Compute32(data, size); case kSkCityHash64: return SkCityHash::Compute64(data, size); default: SkString message("fWhichAlgorithm has unknown value "); message.appendf("%d", fWhichAlgorithm); fReporter->reportFailed(message); } // we never get here return 0; } // Confirm that the checksum algorithm (specified by fWhichAlgorithm) // generates the same results if called twice over the same data. void TestChecksumSelfConsistency(size_t buf_size) { SkAutoMalloc storage(buf_size); char* ptr = reinterpret_cast<char *>(storage.get()); REPORTER_ASSERT(fReporter, GetTestDataChecksum(8, 0) == GetTestDataChecksum(8, 0)); REPORTER_ASSERT(fReporter, GetTestDataChecksum(8, 0) != GetTestDataChecksum(8, 1)); sk_bzero(ptr, buf_size); checksum_result prev = 0; // assert that as we change values (from 0 to non-zero) in // our buffer, we get a different value for (size_t i = 0; i < buf_size; ++i) { ptr[i] = (i & 0x7f) + 1; // need some non-zero value here // Try checksums of different-sized chunks, but always // 32-bit aligned and big enough to contain all the // nonzero bytes. (Remaining bytes will still be zero // from the initial sk_bzero() call.) size_t checksum_size = (((i/4)+1)*4); REPORTER_ASSERT(fReporter, checksum_size <= buf_size); checksum_result curr = ComputeChecksum(ptr, checksum_size); REPORTER_ASSERT(fReporter, prev != curr); checksum_result again = ComputeChecksum(ptr, checksum_size); REPORTER_ASSERT(fReporter, again == curr); prev = curr; } } // Return the checksum of a buffer of bytes 'len' long. // The pattern of values within the buffer will be consistent // for every call, based on 'seed'. checksum_result GetTestDataChecksum(size_t len, char seed=0) { SkAutoMalloc storage(len); char* start = reinterpret_cast<char *>(storage.get()); char* ptr = start; for (size_t i = 0; i < len; ++i) { *ptr++ = ((seed+i) & 0x7f); } checksum_result result = ComputeChecksum(start, len); return result; } void RunTest() { // Test self-consistency of checksum algorithms. fWhichAlgorithm = kSkChecksum; TestChecksumSelfConsistency(128); fWhichAlgorithm = kSkCityHash32; TestChecksumSelfConsistency(128); fWhichAlgorithm = kSkCityHash64; TestChecksumSelfConsistency(128); // Test checksum results that should be consistent across // versions and platforms. fWhichAlgorithm = kSkChecksum; REPORTER_ASSERT(fReporter, ComputeChecksum(NULL, 0) == 0); fWhichAlgorithm = kSkCityHash32; REPORTER_ASSERT(fReporter, ComputeChecksum(NULL, 0) == 0xdc56d17a); REPORTER_ASSERT(fReporter, GetTestDataChecksum(4) == 0x616e1132); REPORTER_ASSERT(fReporter, GetTestDataChecksum(8) == 0xeb0fd2d6); REPORTER_ASSERT(fReporter, GetTestDataChecksum(128) == 0x5321e430); REPORTER_ASSERT(fReporter, GetTestDataChecksum(132) == 0x924a10e4); REPORTER_ASSERT(fReporter, GetTestDataChecksum(256) == 0xd4de9dc9); REPORTER_ASSERT(fReporter, GetTestDataChecksum(260) == 0xecf0325d); fWhichAlgorithm = kSkCityHash64; REPORTER_ASSERT(fReporter, ComputeChecksum(NULL, 0) == 0x9ae16a3b2f90404fULL); REPORTER_ASSERT(fReporter, GetTestDataChecksum(4) == 0x82bffd898958e540ULL); REPORTER_ASSERT(fReporter, GetTestDataChecksum(8) == 0xad5a13e1e8e93b98ULL); REPORTER_ASSERT(fReporter, GetTestDataChecksum(128) == 0x10b153630af1f395ULL); REPORTER_ASSERT(fReporter, GetTestDataChecksum(132) == 0x7db71dc4adcc6647ULL); REPORTER_ASSERT(fReporter, GetTestDataChecksum(256) == 0xeee763519b91b010ULL); REPORTER_ASSERT(fReporter, GetTestDataChecksum(260) == 0x2fe19e0b2239bc23ULL); // TODO: note the weakness exposed by these collisions... // We need to improve the SkChecksum algorithm. // We would prefer that these asserts FAIL! // Filed as https://code.google.com/p/skia/issues/detail?id=981 // ('SkChecksum algorithm allows for way too many collisions') fWhichAlgorithm = kSkChecksum; REPORTER_ASSERT(fReporter, GetTestDataChecksum(128) == GetTestDataChecksum(256)); REPORTER_ASSERT(fReporter, GetTestDataChecksum(132) == GetTestDataChecksum(260)); } Reporter* fReporter; Algorithm fWhichAlgorithm; }; static TestRegistry gReg(ChecksumTestClass::Factory); } <|endoftext|>
<commit_before>/********************************************************************************* * * Inviwo - Interactive Visualization Workshop * * Copyright (c) 2017 Inviwo Foundation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * *********************************************************************************/ #include <warn/push> #include <warn/ignore/all> #include <gtest/gtest.h> #include <warn/pop> #ifdef WIN32 #define NOMINMAX #define WIN32_LEAN_AND_MEAN #include <windows.h> #endif #include <inviwo/core/util/filesystem.h> #include <inviwo/core/util/exception.h> #include <modules/cimg/cimgutils.h> #include <modules/cimg/cimglayerreader.h> #include <fstream> #include <array> #include <cstdio> #include <algorithm> namespace inviwo { #ifdef WIN32 std::wstring get_utf16(const std::string &str, int codepage) { if (str.empty()) return std::wstring(); int sz = MultiByteToWideChar(codepage, 0, &str[0], (int)str.size(), 0, 0); std::wstring res(sz, 0); MultiByteToWideChar(codepage, 0, &str[0], (int)str.size(), &res[0], sz); return res; } #endif class TempFileHandle { public: explicit TempFileHandle(const std::string& prefix = "", const std::string& suffix = "") { #ifdef WIN32 // get temp directory std::array<wchar_t, MAX_PATH> tempPath; std::array<wchar_t, MAX_PATH> tempFile; auto retVal = GetTempPath(MAX_PATH, tempPath.data()); if ((retVal > MAX_PATH) || (retVal == 0)) { throw Exception("could not locate temp folder"); } // generate temp file name std::wstring prefixW(prefix.begin(), prefix.end()); auto uRetVal = GetTempFileName(tempPath.data(), // directory for tmp files prefixW.c_str(), // temp file name prefix 0, // create unique name tempFile.data()); // buffer for name if (uRetVal == 0) { throw Exception("could not create temporary file name"); } filename.assign(tempFile.begin(), tempFile.begin() + std::min<size_t>(wcslen(tempFile.data()), MAX_PATH)); filename += suffix; handle_ = fopen(filename_.c_str(), "w"); if (!handle_) { throw Exception("could not open temporary file"); } #else static const std::string unqiue = "XXXXXX"; const int suffixlen = suffix.size(); std::vector<char> fileTemplate; fileTemplate.insert(fileTemplate.end(), prefix.begin(), prefix.end()); fileTemplate.insert(fileTemplate.end(), unqiue.begin(), unqiue.end()); fileTemplate.insert(fileTemplate.end(), suffix.begin(), suffix.end()); fileTemplate.push_back('\0'); int fd = mkstemps(fileTemplate.data(), suffixlen); if (fd == -1) { throw Exception("could not create temporary file"); } handle_ = fdopen(fd, "w"); if (!handle_) { throw Exception("could not open temporary file"); } filename_.assign(fileTemplate.begin(), fileTemplate.end() - 1); #endif } TempFileHandle(const TempFileHandle&) = delete; TempFileHandle& operator=(const TempFileHandle&) = delete; TempFileHandle(TempFileHandle&& rhs) : handle_{rhs.handle_}, filename_{std::move(rhs.filename_)} { rhs.handle_ = nullptr; rhs.filename_ = ""; } TempFileHandle& operator=(TempFileHandle&& rhs) { if (this != &rhs) { cleanup(); handle_ = rhs.handle_; filename_ = std::move(rhs.filename_); rhs.handle_ = nullptr; rhs.filename_ = ""; } return *this; } ~TempFileHandle() { cleanup(); } const std::string& getFileName() const { return filename_; } FILE* getHandle() { return handle_; } operator FILE*() { return handle_; }; private: void cleanup() { if (handle_) fclose(handle_); if (!filename_.empty()) { #ifdef WIN32 std::wstring fileW(filename_.begin(), filename_.end()); DeleteFile(fileW.c_str()); #else remove(filename_.c_str()); #endif } } FILE* handle_; std::string filename_; }; TEST(CImgUtils, cimgToBuffer) { // load source image const auto filename = filesystem::getPath(PathType::Tests, "/images/swirl.png"); CImgLayerReader reader; auto layer = reader.readData(filename); const std::string testExtension = "png"; // write layer to a temporary png file TempFileHandle tmpFile("cimg", std::string(".") + testExtension); cimgutil::saveLayer(tmpFile.getFileName(), layer.get()); // read file contents std::vector<unsigned char> fileContents; std::ifstream in(tmpFile.getFileName().c_str(), std::ifstream::binary); if (in.is_open()) { in.seekg(0, in.end); size_t fileLen = in.tellg(); in.seekg(0, in.beg); fileContents.resize(fileLen); in.read(reinterpret_cast<char*>(fileContents.data()), fileLen); in.close(); } // write layer to buffer auto imgBuffer = cimgutil::saveLayerToBuffer(testExtension, layer.get()); ASSERT_TRUE(imgBuffer != nullptr) << "buffer is empty"; // compare buffer and file contents ASSERT_TRUE(fileContents.size() == imgBuffer->size()) << "buffer and file size does not match"; EXPECT_EQ(*imgBuffer.get(), fileContents) << "buffer and file contents do not match"; } } <commit_msg>Cimg: UnitTest: Windows compile fix<commit_after>/********************************************************************************* * * Inviwo - Interactive Visualization Workshop * * Copyright (c) 2017 Inviwo Foundation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * *********************************************************************************/ #include <warn/push> #include <warn/ignore/all> #include <gtest/gtest.h> #include <warn/pop> #ifdef WIN32 #define NOMINMAX #define WIN32_LEAN_AND_MEAN #include <windows.h> #endif #include <inviwo/core/util/filesystem.h> #include <inviwo/core/util/exception.h> #include <modules/cimg/cimgutils.h> #include <modules/cimg/cimglayerreader.h> #include <fstream> #include <array> #include <cstdio> #include <algorithm> namespace inviwo { #ifdef WIN32 std::wstring get_utf16(const std::string &str, int codepage) { if (str.empty()) return std::wstring(); int sz = MultiByteToWideChar(codepage, 0, &str[0], (int)str.size(), 0, 0); std::wstring res(sz, 0); MultiByteToWideChar(codepage, 0, &str[0], (int)str.size(), &res[0], sz); return res; } #endif class TempFileHandle { public: explicit TempFileHandle(const std::string& prefix = "", const std::string& suffix = "") { #ifdef WIN32 // get temp directory std::array<wchar_t, MAX_PATH> tempPath; std::array<wchar_t, MAX_PATH> tempFile; auto retVal = GetTempPath(MAX_PATH, tempPath.data()); if ((retVal > MAX_PATH) || (retVal == 0)) { throw Exception("could not locate temp folder"); } // generate temp file name std::wstring prefixW(prefix.begin(), prefix.end()); auto uRetVal = GetTempFileName(tempPath.data(), // directory for tmp files prefixW.c_str(), // temp file name prefix 0, // create unique name tempFile.data()); // buffer for name if (uRetVal == 0) { throw Exception("could not create temporary file name"); } filename_.assign(tempFile.begin(), tempFile.begin() + std::min<size_t>(wcslen(tempFile.data()), MAX_PATH)); filename_ += suffix; handle_ = fopen(filename_.c_str(), "w"); if (!handle_) { throw Exception("could not open temporary file"); } #else static const std::string unqiue = "XXXXXX"; const int suffixlen = suffix.size(); std::vector<char> fileTemplate; fileTemplate.insert(fileTemplate.end(), prefix.begin(), prefix.end()); fileTemplate.insert(fileTemplate.end(), unqiue.begin(), unqiue.end()); fileTemplate.insert(fileTemplate.end(), suffix.begin(), suffix.end()); fileTemplate.push_back('\0'); int fd = mkstemps(fileTemplate.data(), suffixlen); if (fd == -1) { throw Exception("could not create temporary file"); } handle_ = fdopen(fd, "w"); if (!handle_) { throw Exception("could not open temporary file"); } filename_.assign(fileTemplate.begin(), fileTemplate.end() - 1); #endif } TempFileHandle(const TempFileHandle&) = delete; TempFileHandle& operator=(const TempFileHandle&) = delete; TempFileHandle(TempFileHandle&& rhs) : handle_{rhs.handle_}, filename_{std::move(rhs.filename_)} { rhs.handle_ = nullptr; rhs.filename_ = ""; } TempFileHandle& operator=(TempFileHandle&& rhs) { if (this != &rhs) { cleanup(); handle_ = rhs.handle_; filename_ = std::move(rhs.filename_); rhs.handle_ = nullptr; rhs.filename_ = ""; } return *this; } ~TempFileHandle() { cleanup(); } const std::string& getFileName() const { return filename_; } FILE* getHandle() { return handle_; } operator FILE*() { return handle_; }; private: void cleanup() { if (handle_) fclose(handle_); if (!filename_.empty()) { #ifdef WIN32 std::wstring fileW(filename_.begin(), filename_.end()); DeleteFile(fileW.c_str()); #else remove(filename_.c_str()); #endif } } FILE* handle_; std::string filename_; }; TEST(CImgUtils, cimgToBuffer) { // load source image const auto filename = filesystem::getPath(PathType::Tests, "/images/swirl.png"); CImgLayerReader reader; auto layer = reader.readData(filename); const std::string testExtension = "png"; // write layer to a temporary png file TempFileHandle tmpFile("cimg", std::string(".") + testExtension); cimgutil::saveLayer(tmpFile.getFileName(), layer.get()); // read file contents std::vector<unsigned char> fileContents; std::ifstream in(tmpFile.getFileName().c_str(), std::ifstream::binary); if (in.is_open()) { in.seekg(0, in.end); size_t fileLen = in.tellg(); in.seekg(0, in.beg); fileContents.resize(fileLen); in.read(reinterpret_cast<char*>(fileContents.data()), fileLen); in.close(); } // write layer to buffer auto imgBuffer = cimgutil::saveLayerToBuffer(testExtension, layer.get()); ASSERT_TRUE(imgBuffer != nullptr) << "buffer is empty"; // compare buffer and file contents ASSERT_TRUE(fileContents.size() == imgBuffer->size()) << "buffer and file size does not match"; EXPECT_EQ(*imgBuffer.get(), fileContents) << "buffer and file contents do not match"; } } <|endoftext|>
<commit_before>/* Copyright 2011 Google 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. */ #include "SkReader32.h" #include "Test.h" static void assert_eof(skiatest::Reporter* reporter, const SkReader32& reader) { REPORTER_ASSERT(reporter, reader.eof()); REPORTER_ASSERT(reporter, reader.size() == reader.offset()); REPORTER_ASSERT(reporter, (const char*)reader.peek() == (const char*)reader.base() + reader.size()); } static void assert_start(skiatest::Reporter* reporter, const SkReader32& reader) { REPORTER_ASSERT(reporter, 0 == reader.offset()); REPORTER_ASSERT(reporter, reader.size() == reader.available()); REPORTER_ASSERT(reporter, reader.isAvailable(reader.size())); REPORTER_ASSERT(reporter, !reader.isAvailable(reader.size() + 1)); REPORTER_ASSERT(reporter, reader.peek() == reader.base()); } static void assert_empty(skiatest::Reporter* reporter, const SkReader32& reader) { REPORTER_ASSERT(reporter, 0 == reader.size()); REPORTER_ASSERT(reporter, 0 == reader.offset()); REPORTER_ASSERT(reporter, 0 == reader.available()); REPORTER_ASSERT(reporter, !reader.isAvailable(1)); assert_eof(reporter, reader); assert_start(reporter, reader); } static void Tests(skiatest::Reporter* reporter) { SkReader32 reader; assert_empty(reporter, reader); REPORTER_ASSERT(reporter, NULL == reader.base()); REPORTER_ASSERT(reporter, NULL == reader.peek()); size_t i; const int32_t data[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; const SkScalar data2[] = { 0, SK_Scalar1, -SK_Scalar1, SK_Scalar1/2 }; char buffer[SkMax32(sizeof(data), sizeof(data2))]; reader.setMemory(data, sizeof(data)); for (i = 0; i < SK_ARRAY_COUNT(data); ++i) { REPORTER_ASSERT(reporter, sizeof(data) == reader.size()); REPORTER_ASSERT(reporter, i*4 == reader.offset()); REPORTER_ASSERT(reporter, (const void*)data == reader.base()); REPORTER_ASSERT(reporter, (const void*)&data[i] == reader.peek()); REPORTER_ASSERT(reporter, data[i] == reader.readInt()); } assert_eof(reporter, reader); reader.rewind(); assert_start(reporter, reader); reader.read(buffer, sizeof(buffer)); REPORTER_ASSERT(reporter, !memcmp(data, buffer, sizeof(buffer))); reader.setMemory(data2, sizeof(data2)); for (i = 0; i < SK_ARRAY_COUNT(data2); ++i) { REPORTER_ASSERT(reporter, sizeof(data2) == reader.size()); REPORTER_ASSERT(reporter, i*4 == reader.offset()); REPORTER_ASSERT(reporter, (const void*)data2 == reader.base()); REPORTER_ASSERT(reporter, (const void*)&data2[i] == reader.peek()); REPORTER_ASSERT(reporter, data2[i] == reader.readScalar()); } assert_eof(reporter, reader); reader.rewind(); assert_start(reporter, reader); reader.read(buffer, sizeof(buffer)); REPORTER_ASSERT(reporter, !memcmp(data2, buffer, sizeof(buffer))); reader.setMemory(NULL, 0); assert_empty(reporter, reader); REPORTER_ASSERT(reporter, NULL == reader.base()); REPORTER_ASSERT(reporter, NULL == reader.peek()); } #include "TestClassDef.h" DEFINE_TESTCLASS("Reader32", Reader32Class, Tests) <commit_msg>pass correct size to read(buffer, ...) tests<commit_after>/* Copyright 2011 Google 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. */ #include "SkReader32.h" #include "Test.h" static void assert_eof(skiatest::Reporter* reporter, const SkReader32& reader) { REPORTER_ASSERT(reporter, reader.eof()); REPORTER_ASSERT(reporter, reader.size() == reader.offset()); REPORTER_ASSERT(reporter, (const char*)reader.peek() == (const char*)reader.base() + reader.size()); } static void assert_start(skiatest::Reporter* reporter, const SkReader32& reader) { REPORTER_ASSERT(reporter, 0 == reader.offset()); REPORTER_ASSERT(reporter, reader.size() == reader.available()); REPORTER_ASSERT(reporter, reader.isAvailable(reader.size())); REPORTER_ASSERT(reporter, !reader.isAvailable(reader.size() + 1)); REPORTER_ASSERT(reporter, reader.peek() == reader.base()); } static void assert_empty(skiatest::Reporter* reporter, const SkReader32& reader) { REPORTER_ASSERT(reporter, 0 == reader.size()); REPORTER_ASSERT(reporter, 0 == reader.offset()); REPORTER_ASSERT(reporter, 0 == reader.available()); REPORTER_ASSERT(reporter, !reader.isAvailable(1)); assert_eof(reporter, reader); assert_start(reporter, reader); } static void Tests(skiatest::Reporter* reporter) { SkReader32 reader; assert_empty(reporter, reader); REPORTER_ASSERT(reporter, NULL == reader.base()); REPORTER_ASSERT(reporter, NULL == reader.peek()); size_t i; const int32_t data[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; const SkScalar data2[] = { 0, SK_Scalar1, -SK_Scalar1, SK_Scalar1/2 }; char buffer[SkMax32(sizeof(data), sizeof(data2))]; reader.setMemory(data, sizeof(data)); for (i = 0; i < SK_ARRAY_COUNT(data); ++i) { REPORTER_ASSERT(reporter, sizeof(data) == reader.size()); REPORTER_ASSERT(reporter, i*4 == reader.offset()); REPORTER_ASSERT(reporter, (const void*)data == reader.base()); REPORTER_ASSERT(reporter, (const void*)&data[i] == reader.peek()); REPORTER_ASSERT(reporter, data[i] == reader.readInt()); } assert_eof(reporter, reader); reader.rewind(); assert_start(reporter, reader); reader.read(buffer, sizeof(data)); REPORTER_ASSERT(reporter, !memcmp(data, buffer, sizeof(data))); reader.setMemory(data2, sizeof(data2)); for (i = 0; i < SK_ARRAY_COUNT(data2); ++i) { REPORTER_ASSERT(reporter, sizeof(data2) == reader.size()); REPORTER_ASSERT(reporter, i*4 == reader.offset()); REPORTER_ASSERT(reporter, (const void*)data2 == reader.base()); REPORTER_ASSERT(reporter, (const void*)&data2[i] == reader.peek()); REPORTER_ASSERT(reporter, data2[i] == reader.readScalar()); } assert_eof(reporter, reader); reader.rewind(); assert_start(reporter, reader); reader.read(buffer, sizeof(data2)); REPORTER_ASSERT(reporter, !memcmp(data2, buffer, sizeof(data2))); reader.setMemory(NULL, 0); assert_empty(reporter, reader); REPORTER_ASSERT(reporter, NULL == reader.base()); REPORTER_ASSERT(reporter, NULL == reader.peek()); } #include "TestClassDef.h" DEFINE_TESTCLASS("Reader32", Reader32Class, Tests) <|endoftext|>
<commit_before>/// /// @file LoadBalancerS2.cpp /// @brief The LoadBalancerS2 assigns work to the individual threads /// in the computation of the special leaves in the /// Lagarias-Miller-Odlyzko, Deleglise-Rivat and Gourdon /// prime counting algorithms. This load balancer is used /// by the S2_hard(x, y) and D(x, y) functions. /// /// Simply parallelizing the computation of the special /// leaves in the Lagarias-Miller-Odlyzko algorithm by /// subdividing the sieve interval by the number of threads /// into equally sized subintervals does not scale because /// the distribution of the special leaves is highly skewed /// and most special leaves are in the first few segments /// whereas later on there are very few special leaves. /// /// This LoadBalancerS2 gradually increases the number of /// segments to sieve as long the expected runtime of the /// sieve distance is smaller than the expected finish time /// of the algorithm. Near the end the LoadBalancerS2 will /// gradually decrease the number of segments to sieve in /// order to prevent that 1 thread will run much longer /// than all the other threads. /// /// Copyright (C) 2021 Kim Walisch, <kim.walisch@gmail.com> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #include <LoadBalancerS2.hpp> #include <primecount-internal.hpp> #include <Status.hpp> #include <Sieve.hpp> #include <imath.hpp> #include <int128_t.hpp> #include <min.hpp> #include <print.hpp> #include <stdint.h> namespace primecount { LoadBalancerS2::LoadBalancerS2(maxint_t x, int64_t sieve_limit, maxint_t sum_approx, int threads, bool is_print) : sieve_limit_(sieve_limit), segments_(1), sum_approx_(sum_approx), time_(get_time()), is_print_(is_print), status_(x) { // Try to use a segment size that fits exactly // into the CPU's L1 data cache. Also the // segmented sieve of Eratosthenes requires the // segment size to be >= sqrt(sieve_limit). int64_t l1_dcache_size = 32 * (1 << 10); int64_t numbers_per_byte = 30; int64_t sqrt_limit = isqrt(sieve_limit); max_size_ = max(sqrt_limit, l1_dcache_size * numbers_per_byte); // When a single thread is used (and printing // is disabled) we can set segment_size to // its maximum size as load balancing is only // useful for multi-threading. if (threads == 1 && !is_print) segment_size_ = max_size_; else { // Start with a tiny segment size of x^(1/4) as // most special leaves are in the first few // segments and as we need to ensure that all // threads are assigned an equal amount of work. segment_size_ = isqrt(isqrt(x)); } int64_t min_size = 1 << 9; segment_size_ = max(min_size, segment_size_); segment_size_ = Sieve::get_segment_size(segment_size_); } maxint_t LoadBalancerS2::get_sum() const { return sum_; } bool LoadBalancerS2::get_work(ThreadSettings& thread) { LockGuard lockGuard(lock_); sum_ += thread.sum; if (is_print_) { uint64_t dist = thread.segments * thread.segment_size; uint64_t high = thread.low + dist; status_.print(high, sieve_limit_, sum_, sum_approx_); } update_load_balancing(thread); thread.low = low_; thread.segments = segments_; thread.segment_size = segment_size_; thread.sum = 0; thread.secs = 0; thread.init_secs = 0; low_ += segments_ * segment_size_; bool is_work = thread.low < sieve_limit_; return is_work; } void LoadBalancerS2::update_load_balancing(const ThreadSettings& thread) { if (thread.low > max_low_) { max_low_ = thread.low; segments_ = thread.segments; // We only start increasing the segment_size and segments // per thread once the first special leaves have been // found. Near the start there is a very large number of // leaves and we don't want a single thread to compute // them all by himself (which would cause scaling issues). if (sum_ == 0) return; // Slowly increase the segment size until it reaches // sqrt(sieve_limit). Most special leaves are located // around y, hence we need to be careful to not assign too // much work to a single thread in this region. if (segment_size_ < max_size_) { segment_size_ += segment_size_ / 16; segment_size_ = min(segment_size_, max_size_); segment_size_ = Sieve::get_segment_size(segment_size_); } else update_segments(thread); } } /// Increase or decrease the number of segments per thread /// based on the remaining runtime. /// void LoadBalancerS2::update_segments(const ThreadSettings& thread) { // Near the end it is important that threads run only for // a short amount of time in order to ensure that all // threads finish nearly at the same time. Since the // remaining time is just a rough estimation we want to be // very conservative so we divide the remaining time by 3. double rem_secs = remaining_secs() / 3; // If the previous thread runtime is larger than the // estimated remaining time the factor that we calculate // below will be < 1 and we will reduce the number of // segments per thread. Otherwise if the factor > 1 we // will increase the number of segments per thread. double min_secs = 0.001; double divider = max(min_secs, thread.secs); double factor = rem_secs / divider; // For small and medium computations the thread runtime // should be about 5000x the thread initialization time. // However for very large computations we want to further // reduce the thread runtimes in order to increase the // backup frequency. If the thread runtime is > 6 hours // we reduce the thread runtime to about 50x the thread // initialization time. double init_secs = max(min_secs, thread.init_secs); double init_factor = in_between(50, (3600 * 6) / init_secs, 5000); // Reduce the thread runtime if it is much larger than // its initialization time. This increases the number of // backups without deteriorating performance as we make // sure that the thread runtime is still much larger than // the thread initialization time. if (thread.secs > min_secs && thread.secs > thread.init_secs * init_factor) { double old = factor; double next_runtime = thread.init_secs * init_factor; factor = next_runtime / thread.secs; factor = min(factor, old); } // Near the end when the remaining time goes close to 0 // the load balancer tends to reduce the number of // segments per thread also close to 0 which is very bad // for performance. The condition below fixes this issue // and ensures that the thread runtime is always at // least 20x the thread initialization time. if (thread.secs > 0 && thread.secs * factor < thread.init_secs * 20) { double next_runtime = thread.init_secs * 20; double current_runtime = thread.secs; factor = next_runtime / current_runtime; } // Since the distribution of the special leaves is highly // skewed (at the beginning) we want to increase the // number of segments per thread very slowly. Because if // the previously sieved interval contained no special // leaves but the next interval contains many special // leaves then sieving the next interval might take orders // of magnitude more time even if the interval size is // identical. factor = in_between(0.5, factor, 2.0); double next_runtime = thread.secs * factor; if (next_runtime < min_secs) segments_ *= 2; else { double new_segments = round(segments_ * factor); segments_ = (int64_t) new_segments; segments_ = max(segments_, 1); } } /// Remaining seconds till finished double LoadBalancerS2::remaining_secs() const { double percent = status_.getPercent(low_, sieve_limit_, sum_, sum_approx_); percent = in_between(10, percent, 100); double total_secs = get_time() - time_; double secs = total_secs * (100 / percent) - total_secs; return secs; } } // namespace <commit_msg>Remove unused header<commit_after>/// /// @file LoadBalancerS2.cpp /// @brief The LoadBalancerS2 assigns work to the individual threads /// in the computation of the special leaves in the /// Lagarias-Miller-Odlyzko, Deleglise-Rivat and Gourdon /// prime counting algorithms. This load balancer is used /// by the S2_hard(x, y) and D(x, y) functions. /// /// Simply parallelizing the computation of the special /// leaves in the Lagarias-Miller-Odlyzko algorithm by /// subdividing the sieve interval by the number of threads /// into equally sized subintervals does not scale because /// the distribution of the special leaves is highly skewed /// and most special leaves are in the first few segments /// whereas later on there are very few special leaves. /// /// This LoadBalancerS2 gradually increases the number of /// segments to sieve as long the expected runtime of the /// sieve distance is smaller than the expected finish time /// of the algorithm. Near the end the LoadBalancerS2 will /// gradually decrease the number of segments to sieve in /// order to prevent that 1 thread will run much longer /// than all the other threads. /// /// Copyright (C) 2021 Kim Walisch, <kim.walisch@gmail.com> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #include <LoadBalancerS2.hpp> #include <primecount-internal.hpp> #include <Status.hpp> #include <Sieve.hpp> #include <imath.hpp> #include <int128_t.hpp> #include <min.hpp> #include <stdint.h> namespace primecount { LoadBalancerS2::LoadBalancerS2(maxint_t x, int64_t sieve_limit, maxint_t sum_approx, int threads, bool is_print) : sieve_limit_(sieve_limit), segments_(1), sum_approx_(sum_approx), time_(get_time()), is_print_(is_print), status_(x) { // Try to use a segment size that fits exactly // into the CPU's L1 data cache. Also the // segmented sieve of Eratosthenes requires the // segment size to be >= sqrt(sieve_limit). int64_t l1_dcache_size = 32 * (1 << 10); int64_t numbers_per_byte = 30; int64_t sqrt_limit = isqrt(sieve_limit); max_size_ = max(sqrt_limit, l1_dcache_size * numbers_per_byte); // When a single thread is used (and printing // is disabled) we can set segment_size to // its maximum size as load balancing is only // useful for multi-threading. if (threads == 1 && !is_print) segment_size_ = max_size_; else { // Start with a tiny segment size of x^(1/4) as // most special leaves are in the first few // segments and as we need to ensure that all // threads are assigned an equal amount of work. segment_size_ = isqrt(isqrt(x)); } int64_t min_size = 1 << 9; segment_size_ = max(min_size, segment_size_); segment_size_ = Sieve::get_segment_size(segment_size_); } maxint_t LoadBalancerS2::get_sum() const { return sum_; } bool LoadBalancerS2::get_work(ThreadSettings& thread) { LockGuard lockGuard(lock_); sum_ += thread.sum; if (is_print_) { uint64_t dist = thread.segments * thread.segment_size; uint64_t high = thread.low + dist; status_.print(high, sieve_limit_, sum_, sum_approx_); } update_load_balancing(thread); thread.low = low_; thread.segments = segments_; thread.segment_size = segment_size_; thread.sum = 0; thread.secs = 0; thread.init_secs = 0; low_ += segments_ * segment_size_; bool is_work = thread.low < sieve_limit_; return is_work; } void LoadBalancerS2::update_load_balancing(const ThreadSettings& thread) { if (thread.low > max_low_) { max_low_ = thread.low; segments_ = thread.segments; // We only start increasing the segment_size and segments // per thread once the first special leaves have been // found. Near the start there is a very large number of // leaves and we don't want a single thread to compute // them all by himself (which would cause scaling issues). if (sum_ == 0) return; // Slowly increase the segment size until it reaches // sqrt(sieve_limit). Most special leaves are located // around y, hence we need to be careful to not assign too // much work to a single thread in this region. if (segment_size_ < max_size_) { segment_size_ += segment_size_ / 16; segment_size_ = min(segment_size_, max_size_); segment_size_ = Sieve::get_segment_size(segment_size_); } else update_segments(thread); } } /// Increase or decrease the number of segments per thread /// based on the remaining runtime. /// void LoadBalancerS2::update_segments(const ThreadSettings& thread) { // Near the end it is important that threads run only for // a short amount of time in order to ensure that all // threads finish nearly at the same time. Since the // remaining time is just a rough estimation we want to be // very conservative so we divide the remaining time by 3. double rem_secs = remaining_secs() / 3; // If the previous thread runtime is larger than the // estimated remaining time the factor that we calculate // below will be < 1 and we will reduce the number of // segments per thread. Otherwise if the factor > 1 we // will increase the number of segments per thread. double min_secs = 0.001; double divider = max(min_secs, thread.secs); double factor = rem_secs / divider; // For small and medium computations the thread runtime // should be about 5000x the thread initialization time. // However for very large computations we want to further // reduce the thread runtimes in order to increase the // backup frequency. If the thread runtime is > 6 hours // we reduce the thread runtime to about 50x the thread // initialization time. double init_secs = max(min_secs, thread.init_secs); double init_factor = in_between(50, (3600 * 6) / init_secs, 5000); // Reduce the thread runtime if it is much larger than // its initialization time. This increases the number of // backups without deteriorating performance as we make // sure that the thread runtime is still much larger than // the thread initialization time. if (thread.secs > min_secs && thread.secs > thread.init_secs * init_factor) { double old = factor; double next_runtime = thread.init_secs * init_factor; factor = next_runtime / thread.secs; factor = min(factor, old); } // Near the end when the remaining time goes close to 0 // the load balancer tends to reduce the number of // segments per thread also close to 0 which is very bad // for performance. The condition below fixes this issue // and ensures that the thread runtime is always at // least 20x the thread initialization time. if (thread.secs > 0 && thread.secs * factor < thread.init_secs * 20) { double next_runtime = thread.init_secs * 20; double current_runtime = thread.secs; factor = next_runtime / current_runtime; } // Since the distribution of the special leaves is highly // skewed (at the beginning) we want to increase the // number of segments per thread very slowly. Because if // the previously sieved interval contained no special // leaves but the next interval contains many special // leaves then sieving the next interval might take orders // of magnitude more time even if the interval size is // identical. factor = in_between(0.5, factor, 2.0); double next_runtime = thread.secs * factor; if (next_runtime < min_secs) segments_ *= 2; else { double new_segments = round(segments_ * factor); segments_ = (int64_t) new_segments; segments_ = max(segments_, 1); } } /// Remaining seconds till finished double LoadBalancerS2::remaining_secs() const { double percent = status_.getPercent(low_, sieve_limit_, sum_, sum_approx_); percent = in_between(10, percent, 100); double total_secs = get_time() - time_; double secs = total_secs * (100 / percent) - total_secs; return secs; } } // namespace <|endoftext|>
<commit_before>#include "MenuStyle.hpp" #include <Config/Globals.hpp> #include <algorithm> MenuStyle::MenuStyle(int h, int w): Style(h, w), menu(nullptr) { create(); } void MenuStyle::create() { Style::create(); destroy(); title = new Window(main, Globals::title_height + 2, -1, 1, 1); int hh = main->getH() - title->getH() - 2; int ww = main->getW() / 3; int y = title->getH() + 1; int x = main->getW() / 3 - 2; menu = new Window(main, hh, ww, y, x); // windows should be pushed from the background to the foreground // otherwise expect the unexpected windows.push_back(&main); windows.push_back(&title); windows.push_back(&menu); } MenuStyle::~MenuStyle() { destroy(); } void MenuStyle::destroy() { if (menu) { delete menu; menu = nullptr; } } void MenuStyle::draw(MenuData *data) { clear(); data->draw(menu); title->print(Globals::title, 1, title->getW() / 2 - Globals::title_length/2, COLOR_RED, -1); refresh(); } void MenuStyle::resize(MenuData *data, int h, int w) { _h = h; _w = w; clearScreen(); create(); draw(data); } void MenuStyle::clearScreen() { clear(); refresh(); } void MenuStyle::clear() { std::for_each(windows.begin(), windows.end(), [this](Window** &w){(**w).clear();}); } void MenuStyle::refresh() { std::for_each(windows.rbegin(), windows.rend(), [this](Window** &w){(**w).refresh();}); } void MenuStyle::setBorders() { std::for_each(windows.begin(), windows.end(), [this](Window** &w){(**w).toggleBorders();}); }<commit_msg>Recenter list of menu options<commit_after>#include "MenuStyle.hpp" #include <Config/Globals.hpp> #include <algorithm> MenuStyle::MenuStyle(int h, int w): Style(h, w), menu(nullptr) { create(); } void MenuStyle::create() { Style::create(); destroy(); title = new Window(main, Globals::title_height + 2, -1, 1, 1); int h = main->getH() - title->getH() - 2; int w = main->getW() / 3; int y = title->getH() + 1; int x = main->getW()/2 - w/2; menu = new Window(main, h, w, y, x); // windows should be pushed from the background to the foreground // otherwise expect the unexpected windows.push_back(&main); windows.push_back(&title); windows.push_back(&menu); } MenuStyle::~MenuStyle() { destroy(); } void MenuStyle::destroy() { if (menu) { delete menu; menu = nullptr; } } void MenuStyle::draw(MenuData *data) { clear(); data->draw(menu); title->print(Globals::title, 1, title->getW() / 2 - Globals::title_length/2, COLOR_RED, -1); refresh(); } void MenuStyle::resize(MenuData *data, int h, int w) { _h = h; _w = w; clearScreen(); create(); draw(data); } void MenuStyle::clearScreen() { clear(); refresh(); } void MenuStyle::clear() { std::for_each(windows.begin(), windows.end(), [this](Window** &w){(**w).clear();}); } void MenuStyle::refresh() { std::for_each(windows.rbegin(), windows.rend(), [this](Window** &w){(**w).refresh();}); } void MenuStyle::setBorders() { std::for_each(windows.begin(), windows.end(), [this](Window** &w){(**w).toggleBorders();}); }<|endoftext|>
<commit_before>#include "MoCapSimulator.h" #include "Logging.h" #undef LOG_CLASS #define LOG_CLASS "MoCapSimulator" #include <algorithm> #include <iterator> #include <string> #include "math.h" const float _frameRate = 60; struct sRigidBodyMovementParams { char* szName; int axis; float radius; float posOffset; float rotOffset; float speed; }; const sRigidBodyMovementParams RIGID_BODY_PARAMS[] = { { "Walk_1m", 1, -1, 1.5, -25, 1.0f / 15 }, // negative radius to make Z-axis face inwards, looking down towards origin { "Walk_2m", 1, -2, 1.5, -20, 1.0f / 20 }, // " { "Walk_3m", 1, -3, 1.5, -15, 1.0f / -25 }, // " { "Walk_4m", 1, -4, 1.5, -10, 1.0f / -30 }, // " { "Walk_5m", 1, -5, 1.5, -7, 1.0f / 40 }, // " { "Walk_10m", 1, -10, 1.5, -5, 1.0f / 50 }, // " { "Oculus", 1, -3, 1.5, -15, 1.0f / 30 }, { "RotX_pos", 0, 0.5, 1.0, 0, 1.0f / 10 }, { "RotX_neg", 0, -0.5, -1.0, 0, 1.0f / -10 }, { "RotY_pos", 1, 0.5, 1.0, 0, 1.0f / 10 }, { "RotY_neg", 1, -0.5, -1.0, 0, 1.0f / -10 }, { "RotZ_pos", 2, 0.5, 1.0, 0, 1.0f / 10 }, { "RotZ_neg", 2, -0.5, -1.0, 0, 1.0f / -10 }, }; const int MARKER_COUNT = 4; const int RIGID_BODY_COUNT = sizeof(RIGID_BODY_PARAMS) / sizeof(RIGID_BODY_PARAMS[0]); const int SKELETON_COUNT = 0; MoCapSimulator::MoCapSimulator() : initialised(false) { } bool MoCapSimulator::initialise() { if (!initialised) { fTime = 0; iFrame = 0; arrPos.resize(RIGID_BODY_COUNT); arrRot.resize(RIGID_BODY_COUNT); arrTrackingLostCounter.resize(RIGID_BODY_COUNT); for (int i = 0; i < RIGID_BODY_COUNT; i++) { arrTrackingLostCounter[i] = 0; } trackingUnreliable = false; LOG_INFO("Initialised"); initialised = true; } return initialised; } bool MoCapSimulator::isActive() { return initialised; } float MoCapSimulator::getUpdateRate() { return _frameRate; } bool MoCapSimulator::update() { iFrame += 1; fTime += (1.0f / _frameRate); for (int b = 0; b < RIGID_BODY_COUNT; b++) { // calculate new positions/rotations float t = fTime * RIGID_BODY_PARAMS[b].speed; float r = RIGID_BODY_PARAMS[b].radius; float oPos = RIGID_BODY_PARAMS[b].posOffset; float oRot = RIGID_BODY_PARAMS[b].rotOffset; switch (RIGID_BODY_PARAMS[b].axis) { case 0: { arrPos[b].set(oPos, r * cos(t), r * sin(t)); // zero degrees = Y+ up arrRot[b].fromAxisAngle(1, 0, 0, t); break; } case 1: { arrPos[b].set(r * -sin(t), oPos, r * -cos(t)); // zero degrees = Z- forwards arrRot[b].fromAxisAngle(0, 1, 0, t); // apply pitch Quaternion rotX(1, 0, 0, oRot * (float) (M_PI / 180)); arrRot[b] = arrRot[b].mult(rotX); break; } case 2: { arrPos[b].set(r * -sin(t), r * cos(t), oPos); // zero degrees = Y+ upwards arrRot[b].fromAxisAngle(0, 0, 1, t); break; } } if (trackingUnreliable) { if (rand() < RAND_MAX / 1000) { arrTrackingLostCounter[b] = rand() * 100 / RAND_MAX; } } } /* for (int s = 0; s < SKELETON_COUNT; s++) { } */ signalNewFrame(); return true; } bool MoCapSimulator::getSceneDescription(MoCapData& refData) { LOG_INFO("Requesting scene description") int descrIdx = 0; for (int b = 0; b < RIGID_BODY_COUNT; b++) { // create markerset description and frame sMarkerSetDescription* pMarkerDesc = new sMarkerSetDescription(); sMarkerSetData& msData = refData.frame.MocapData[b]; // name of marker set strcpy_s(pMarkerDesc->szName, sizeof(pMarkerDesc->szName), RIGID_BODY_PARAMS[b].szName); strcpy_s(msData.szName, sizeof(msData.szName), pMarkerDesc->szName); // number of markers pMarkerDesc->nMarkers = MARKER_COUNT; msData.nMarkers = MARKER_COUNT; // names of markers pMarkerDesc->szMarkerNames = new char*[MARKER_COUNT]; msData.Markers = new MarkerData[MARKER_COUNT]; for (int m = 0; m < MARKER_COUNT; m++) { char czMarkerName[10]; sprintf_s(czMarkerName, sizeof(czMarkerName), "%02d", m + 1); pMarkerDesc->szMarkerNames[m] = _strdup(czMarkerName); } // add to description list refData.description.arrDataDescriptions[descrIdx].type = Descriptor_MarkerSet; refData.description.arrDataDescriptions[descrIdx].Data.MarkerSetDescription = pMarkerDesc; descrIdx++; sRigidBodyDescription* pBodyDesc = new sRigidBodyDescription(); // fill in description structure pBodyDesc->ID = b; // needs to be equal to array index pBodyDesc->parentID = -1; pBodyDesc->offsetx = 0; pBodyDesc->offsety = 0; pBodyDesc->offsetz = 0; strcpy_s(pBodyDesc->szName, sizeof(pBodyDesc->szName), pMarkerDesc->szName); refData.description.arrDataDescriptions[descrIdx].type = Descriptor_RigidBody; refData.description.arrDataDescriptions[descrIdx].Data.RigidBodyDescription = pBodyDesc; descrIdx++; } for (int s = 0; s < SKELETON_COUNT; s++) { sSkeletonDescription* pSkeleton = new sSkeletonDescription(); // fill in description structure pSkeleton->nRigidBodies = 2; //strcpy_s(pSkeleton->szName, ...); // pre-fill in frame structure for marker sets sSkeletonData& skData = refData.frame.Skeletons[s]; //todo refData.description.arrDataDescriptions[descrIdx].type = Descriptor_Skeleton; refData.description.arrDataDescriptions[descrIdx].Data.SkeletonDescription = pSkeleton; descrIdx++; } refData.description.nDataDescriptions = descrIdx; // pre-fill in frame data refData.frame.nMarkerSets = RIGID_BODY_COUNT; refData.frame.nRigidBodies = RIGID_BODY_COUNT; refData.frame.nSkeletons = SKELETON_COUNT; refData.frame.nOtherMarkers = 0; refData.frame.OtherMarkers = NULL; refData.frame.nLabeledMarkers = 0; refData.frame.nForcePlates = 0; refData.frame.fLatency = 0.01f; // simulate 10ms refData.frame.Timecode = 0; refData.frame.TimecodeSubframe = 0; return true; } bool MoCapSimulator::getFrameData(MoCapData& refData) { refData.frame.iFrame = iFrame; for (int b = 0; b < RIGID_BODY_COUNT; b++) { // simulate tracking loss bool trackingLost = false; if (arrTrackingLostCounter[b] > 0) { trackingLost = true; arrTrackingLostCounter[b]--; } // update marker data sMarkerSetData& msData = refData.frame.MocapData[b]; for (int m = 0; m < msData.nMarkers; m++) { msData.Markers[m][0] = arrPos[b].x + (rand() * 0.1f / RAND_MAX - 0.05f); msData.Markers[m][1] = arrPos[b].y + (rand() * 0.1f / RAND_MAX - 0.05f); msData.Markers[m][2] = arrPos[b].z + (rand() * 0.1f / RAND_MAX - 0.05f); } // update rigid body data sRigidBodyData& rbData = refData.frame.RigidBodies[b]; rbData.ID = b; rbData.x = trackingLost ? 0 : arrPos[b].x; rbData.y = trackingLost ? 0 : arrPos[b].y; rbData.z = trackingLost ? 0 : arrPos[b].z; rbData.qx = trackingLost ? 0 : arrRot[b].x; rbData.qy = trackingLost ? 0 : arrRot[b].y; rbData.qz = trackingLost ? 0 : arrRot[b].z; rbData.qw = trackingLost ? 0 : arrRot[b].w; rbData.nMarkers = 0; rbData.MeanError = 0; rbData.params = trackingLost ? 0x00 : 0x01; // tracking OK } return true; } bool MoCapSimulator::processCommand(const std::string& strCommand) { bool processed = false; // convert commandto lowercase std::string strCmdLowerCase; std::transform(strCommand.begin(), strCommand.end(), std::back_inserter(strCmdLowerCase), ::tolower); if (strCmdLowerCase == "lossy" ) { trackingUnreliable = true; LOG_INFO("Tracking unreliable/lossy"); processed = true; } else if (strCmdLowerCase == "lossless") { trackingUnreliable = false; LOG_INFO("Tracking reliable/lossless"); processed = true; } return processed; } bool MoCapSimulator::deinitialise() { if (initialised) { // nothing much to do here LOG_INFO("Deinitialised"); initialised = false; } return !initialised; } MoCapSimulator::~MoCapSimulator() { deinitialise(); } <commit_msg>Changed simulator commands<commit_after>#include "MoCapSimulator.h" #include "Logging.h" #undef LOG_CLASS #define LOG_CLASS "MoCapSimulator" #include <algorithm> #include <iterator> #include <string> #include "math.h" const float _frameRate = 60; struct sRigidBodyMovementParams { char* szName; int axis; float radius; float posOffset; float rotOffset; float speed; }; const sRigidBodyMovementParams RIGID_BODY_PARAMS[] = { { "Walk_1m", 1, -1, 1.5, -25, 1.0f / 15 }, // negative radius to make Z-axis face inwards, looking down towards origin { "Walk_2m", 1, -2, 1.5, -20, 1.0f / 20 }, // " { "Walk_3m", 1, -3, 1.5, -15, 1.0f / -25 }, // " { "Walk_4m", 1, -4, 1.5, -10, 1.0f / -30 }, // " { "Walk_5m", 1, -5, 1.5, -7, 1.0f / 40 }, // " { "Walk_10m", 1, -10, 1.5, -5, 1.0f / 50 }, // " { "Oculus", 1, -3, 1.5, -15, 1.0f / 30 }, { "RotX_pos", 0, 0.5, 1.0, 0, 1.0f / 10 }, { "RotX_neg", 0, -0.5, -1.0, 0, 1.0f / -10 }, { "RotY_pos", 1, 0.5, 1.0, 0, 1.0f / 10 }, { "RotY_neg", 1, -0.5, -1.0, 0, 1.0f / -10 }, { "RotZ_pos", 2, 0.5, 1.0, 0, 1.0f / 10 }, { "RotZ_neg", 2, -0.5, -1.0, 0, 1.0f / -10 }, }; const int MARKER_COUNT = 4; const int RIGID_BODY_COUNT = sizeof(RIGID_BODY_PARAMS) / sizeof(RIGID_BODY_PARAMS[0]); const int SKELETON_COUNT = 0; MoCapSimulator::MoCapSimulator() : initialised(false) { } bool MoCapSimulator::initialise() { if (!initialised) { fTime = 0; iFrame = 0; arrPos.resize(RIGID_BODY_COUNT); arrRot.resize(RIGID_BODY_COUNT); arrTrackingLostCounter.resize(RIGID_BODY_COUNT); for (int i = 0; i < RIGID_BODY_COUNT; i++) { arrTrackingLostCounter[i] = 0; } trackingUnreliable = false; LOG_INFO("Initialised"); initialised = true; } return initialised; } bool MoCapSimulator::isActive() { return initialised; } float MoCapSimulator::getUpdateRate() { return _frameRate; } bool MoCapSimulator::update() { iFrame += 1; fTime += (1.0f / _frameRate); for (int b = 0; b < RIGID_BODY_COUNT; b++) { // calculate new positions/rotations float t = fTime * RIGID_BODY_PARAMS[b].speed; float r = RIGID_BODY_PARAMS[b].radius; float oPos = RIGID_BODY_PARAMS[b].posOffset; float oRot = RIGID_BODY_PARAMS[b].rotOffset; switch (RIGID_BODY_PARAMS[b].axis) { case 0: { arrPos[b].set(oPos, r * cos(t), r * sin(t)); // zero degrees = Y+ up arrRot[b].fromAxisAngle(1, 0, 0, t); break; } case 1: { arrPos[b].set(r * -sin(t), oPos, r * -cos(t)); // zero degrees = Z- forwards arrRot[b].fromAxisAngle(0, 1, 0, t); // apply pitch Quaternion rotX(1, 0, 0, oRot * (float) (M_PI / 180)); arrRot[b] = arrRot[b].mult(rotX); break; } case 2: { arrPos[b].set(r * -sin(t), r * cos(t), oPos); // zero degrees = Y+ upwards arrRot[b].fromAxisAngle(0, 0, 1, t); break; } } if (trackingUnreliable) { if (rand() < RAND_MAX / 1000) { arrTrackingLostCounter[b] = rand() * 100 / RAND_MAX; } } } /* for (int s = 0; s < SKELETON_COUNT; s++) { } */ signalNewFrame(); return true; } bool MoCapSimulator::getSceneDescription(MoCapData& refData) { LOG_INFO("Requesting scene description") int descrIdx = 0; for (int b = 0; b < RIGID_BODY_COUNT; b++) { // create markerset description and frame sMarkerSetDescription* pMarkerDesc = new sMarkerSetDescription(); sMarkerSetData& msData = refData.frame.MocapData[b]; // name of marker set strcpy_s(pMarkerDesc->szName, sizeof(pMarkerDesc->szName), RIGID_BODY_PARAMS[b].szName); strcpy_s(msData.szName, sizeof(msData.szName), pMarkerDesc->szName); // number of markers pMarkerDesc->nMarkers = MARKER_COUNT; msData.nMarkers = MARKER_COUNT; // names of markers pMarkerDesc->szMarkerNames = new char*[MARKER_COUNT]; msData.Markers = new MarkerData[MARKER_COUNT]; for (int m = 0; m < MARKER_COUNT; m++) { char czMarkerName[10]; sprintf_s(czMarkerName, sizeof(czMarkerName), "%02d", m + 1); pMarkerDesc->szMarkerNames[m] = _strdup(czMarkerName); } // add to description list refData.description.arrDataDescriptions[descrIdx].type = Descriptor_MarkerSet; refData.description.arrDataDescriptions[descrIdx].Data.MarkerSetDescription = pMarkerDesc; descrIdx++; sRigidBodyDescription* pBodyDesc = new sRigidBodyDescription(); // fill in description structure pBodyDesc->ID = b; // needs to be equal to array index pBodyDesc->parentID = -1; pBodyDesc->offsetx = 0; pBodyDesc->offsety = 0; pBodyDesc->offsetz = 0; strcpy_s(pBodyDesc->szName, sizeof(pBodyDesc->szName), pMarkerDesc->szName); refData.description.arrDataDescriptions[descrIdx].type = Descriptor_RigidBody; refData.description.arrDataDescriptions[descrIdx].Data.RigidBodyDescription = pBodyDesc; descrIdx++; } for (int s = 0; s < SKELETON_COUNT; s++) { sSkeletonDescription* pSkeleton = new sSkeletonDescription(); // fill in description structure pSkeleton->nRigidBodies = 2; //strcpy_s(pSkeleton->szName, ...); // pre-fill in frame structure for marker sets sSkeletonData& skData = refData.frame.Skeletons[s]; //todo refData.description.arrDataDescriptions[descrIdx].type = Descriptor_Skeleton; refData.description.arrDataDescriptions[descrIdx].Data.SkeletonDescription = pSkeleton; descrIdx++; } refData.description.nDataDescriptions = descrIdx; // pre-fill in frame data refData.frame.nMarkerSets = RIGID_BODY_COUNT; refData.frame.nRigidBodies = RIGID_BODY_COUNT; refData.frame.nSkeletons = SKELETON_COUNT; refData.frame.nOtherMarkers = 0; refData.frame.OtherMarkers = NULL; refData.frame.nLabeledMarkers = 0; refData.frame.nForcePlates = 0; refData.frame.fLatency = 0.01f; // simulate 10ms refData.frame.Timecode = 0; refData.frame.TimecodeSubframe = 0; return true; } bool MoCapSimulator::getFrameData(MoCapData& refData) { refData.frame.iFrame = iFrame; for (int b = 0; b < RIGID_BODY_COUNT; b++) { // simulate tracking loss bool trackingLost = false; if (arrTrackingLostCounter[b] > 0) { trackingLost = true; arrTrackingLostCounter[b]--; } // update marker data sMarkerSetData& msData = refData.frame.MocapData[b]; for (int m = 0; m < msData.nMarkers; m++) { msData.Markers[m][0] = arrPos[b].x + (rand() * 0.1f / RAND_MAX - 0.05f); msData.Markers[m][1] = arrPos[b].y + (rand() * 0.1f / RAND_MAX - 0.05f); msData.Markers[m][2] = arrPos[b].z + (rand() * 0.1f / RAND_MAX - 0.05f); } // update rigid body data sRigidBodyData& rbData = refData.frame.RigidBodies[b]; rbData.ID = b; rbData.x = trackingLost ? 0 : arrPos[b].x; rbData.y = trackingLost ? 0 : arrPos[b].y; rbData.z = trackingLost ? 0 : arrPos[b].z; rbData.qx = trackingLost ? 0 : arrRot[b].x; rbData.qy = trackingLost ? 0 : arrRot[b].y; rbData.qz = trackingLost ? 0 : arrRot[b].z; rbData.qw = trackingLost ? 0 : arrRot[b].w; rbData.nMarkers = 0; rbData.MeanError = 0; rbData.params = trackingLost ? 0x00 : 0x01; // tracking OK } return true; } bool MoCapSimulator::processCommand(const std::string& strCommand) { bool processed = false; // convert commandto lowercase std::string strCmdLowerCase; std::transform(strCommand.begin(), strCommand.end(), std::back_inserter(strCmdLowerCase), ::tolower); if (strCmdLowerCase == "enabletrackingloss" ) { trackingUnreliable = true; LOG_INFO("Tracking loss enabled"); processed = true; } else if (strCmdLowerCase == "disabletrackingloss") { trackingUnreliable = false; LOG_INFO("Tracking loss disabled"); processed = true; } return processed; } bool MoCapSimulator::deinitialise() { if (initialised) { // nothing much to do here LOG_INFO("Deinitialised"); initialised = false; } return !initialised; } MoCapSimulator::~MoCapSimulator() { deinitialise(); } <|endoftext|>
<commit_before>#include <stdio.h> #include <stdlib.h> #include <string.h> #include <kernel/libc.h> #include <kernel/icxxabi.h> #include <sys/stat.h> #include <fcntl.h> #include <dirent.h> #include <kernel/assert.h> #include <kernel/tty.h> #include <kernel/heap.h> #include <kernel/video.h> #include <kernel/context.h> #include <kernel/vga_context.h> #include <kernel/window.h> #include <kernel/list.h> #include <kernel/desktop.h> #include <kernel/ramdisk.h> #include <kernel/fs/tar.h> #include <kernel/fs/vfs.h> #include <kernel/fs/initrd.h> #include <kernel/devmanager.h> #define _GRAPHICS 0 #include <arch/i386/idt.h> #include <arch/i386/gdt.h> #include <arch/i386/paging.h> #include <arch/i386/serial.h> #include <arch/i386/mouse.h> #include <arch/i386/keyboard.h> #include <arch/i386/multiboot.h> #include <arch/i386/keyboard.h> multiboot_info_t *mboot_info; extern "C" void kearly (multiboot_info_t *_mboot_info) { mboot_info = _mboot_info; init_kheap (*(uint32_t *)(mboot_info->mods_addr + 4)); } extern "C" void kmain (void) { init_gdt (); puts ("GDT initialized"); init_idt (); puts ("IDT initialized"); init_paging (); puts ("Paging initialized"); const char *serial_test = "Hello Serial World!\n\r"; Driver::COM1.Write (serial_test, strlen (serial_test), 0); puts ("Serial initialized"); init_keyboard (); printf ("Keyboard initialized\n"); init_mouse (); printf ("Mouse initialized\n"); asm volatile ("sti"); puts ("\nWelcome to ChronOS, well, the kernel to be more specific."); DeviceManager::devman->ListDevices (); /*auto *ramdisk = new Driver::Ramdisk (4, "initrd", (void *) *(uint32_t *)(mboot_info->mods_addr)); auto *tar = FileSystem::Tar::Parse (ramdisk);*/ auto *initrd = new FileSystem::Initrd ("/"); VFS::InitVFS (initrd); mkdir ("/boot", 0777); mkdir ("/dev", 0777); struct stat bootst; struct stat devst; stat ("/boot", &bootst); stat ("/dev", &devst); assert (S_ISDIR (bootst.st_mode)); assert (S_ISDIR (devst.st_mode)); /*int file = open ("/greet.txt", O_RDONLY); if (file == -1) puts ("Could not open /greet.txt"); else printf ("/greet.txt open in fd: %d\n", file); struct stat st; stat ("/", &st); assert (S_ISDIR(st.st_mode)); stat ("/greet.txt", &st); assert (S_ISREG(st.st_mode)); assert (false);*/ /*DIR *root = opendir ("/"); struct dirent *et = readdir (root); printf ("First file name: %s\n", et->name);*/ #if _GRAPHICS == 1 Desktop *desktop = new Desktop (new VGAContext (3, "vga")); desktop->CreateWindow (10, 10, 80, 50); desktop->CreateWindow (100, 50, 50, 60); desktop->CreateWindow (200, 100, 50, 50); while (true) { desktop->update_mouse (mouse_x, mouse_y, mouse_left); } #endif __cxa_finalize (0); for (;;) asm ("hlt"); } <commit_msg>Fixed a quick thing.<commit_after>#include <stdio.h> #include <stdlib.h> #include <string.h> #include <kernel/libc.h> #include <kernel/icxxabi.h> #include <sys/stat.h> #include <fcntl.h> #include <dirent.h> #include <kernel/assert.h> #include <kernel/tty.h> #include <kernel/heap.h> #include <kernel/video.h> #include <kernel/context.h> #include <kernel/vga_context.h> #include <kernel/window.h> #include <kernel/list.h> #include <kernel/desktop.h> #include <kernel/ramdisk.h> #include <kernel/fs/tar.h> #include <kernel/fs/vfs.h> #include <kernel/fs/initrd.h> #include <kernel/devmanager.h> #define _GRAPHICS 0 #include <arch/i386/idt.h> #include <arch/i386/gdt.h> #include <arch/i386/paging.h> #include <arch/i386/serial.h> #include <arch/i386/mouse.h> #include <arch/i386/keyboard.h> #include <arch/i386/multiboot.h> #include <arch/i386/keyboard.h> multiboot_info_t *mboot_info; extern "C" void kearly (multiboot_info_t *_mboot_info) { mboot_info = _mboot_info; init_kheap (*(uint32_t *)(mboot_info->mods_addr + 4)); } extern "C" void kmain (void) { init_gdt (); puts ("GDT initialized"); init_idt (); puts ("IDT initialized"); init_paging (); puts ("Paging initialized"); const char *serial_test = "Hello Serial World!\n\r"; Driver::COM1.Write (serial_test, strlen (serial_test), 0); puts ("Serial initialized"); init_keyboard (); printf ("Keyboard initialized\n"); init_mouse (); printf ("Mouse initialized\n"); asm volatile ("sti"); puts ("\nWelcome to ChronOS, well, the kernel to be more specific."); DeviceManager::devman->ListDevices (); /*auto *ramdisk = new Driver::Ramdisk (4, "initrd", (void *) *(uint32_t *)(mboot_info->mods_addr)); auto *tar = FileSystem::Tar::Parse (ramdisk);*/ auto *initrd = new FileSystem::Initrd ("/"); VFS::InitVFS (initrd); mkdir ("/boot", 0777); mkdir ("/dev", 0777); struct stat bootst; struct stat devst; stat ("/boot", &bootst); stat ("/dev", &devst); assert (S_ISDIR (bootst.st_mode)); assert (S_ISDIR (devst.st_mode)); /*int file = open ("/greet.txt", O_RDONLY); if (file == -1) puts ("Could not open /greet.txt"); else printf ("/greet.txt open in fd: %d\n", file); struct stat st; stat ("/", &st); assert (S_ISDIR(st.st_mode)); stat ("/greet.txt", &st); assert (S_ISREG(st.st_mode)); assert (false);*/ /*DIR *root = opendir ("/"); struct dirent *et = readdir (root); printf ("First file name: %s\n", et->name);*/ #if _GRAPHICS == 1 Desktop *desktop = new Desktop (new VGAContext ("vga")); desktop->CreateWindow (10, 10, 80, 50); desktop->CreateWindow (100, 50, 50, 60); desktop->CreateWindow (200, 100, 50, 50); while (true) { desktop->update_mouse (mouse_x, mouse_y, mouse_left); } #endif __cxa_finalize (0); for (;;) asm ("hlt"); } <|endoftext|>
<commit_before>// Sample code to train the encoder-decoder model using small English-Japanese // parallel corpora. // // Model detail: // Sutskever et al., 2014. // Sequence to Sequence Learning with Neural Networks. // https://arxiv.org/abs/1409.3215 // // Corpora detail: // https://github.com/odashi/small_parallel_enja // // Usage: // Run 'download_data.sh' in the same directory before using this code. // g++ // -std=c++11 // -I/path/to/primitiv/includes (typically -I../..) // -L/path/to/primitiv/libs (typically -L../../build/primitiv) // encdec.cc -lprimitiv #include <algorithm> #include <fstream> #include <iostream> #include <random> #include <string> #include <utility> #include <vector> #include <primitiv/primitiv.h> #include <primitiv/primitiv_cuda.h> using primitiv::trainers::Adam; namespace F = primitiv::node_ops; namespace I = primitiv::initializers; using namespace primitiv; using namespace std; namespace { static const unsigned NUM_EMBED_UNITS = 512; static const unsigned NUM_HIDDEN_UNITS = 512; static const unsigned BATCH_SIZE = 64; static const unsigned MAX_EPOCH = 100; static const float DROPOUT_RATE = 0.5; // Gathers the set of words from space-separated corpus. unordered_map<string, unsigned> make_vocab(const string &filename) { ifstream ifs(filename); if (!ifs.is_open()) { cerr << "File could not be opened: " << filename << endl; exit(1); } unordered_map<string, unsigned> vocab; vocab.emplace(make_pair("<unk>", 0)); string line, word; while (getline(ifs, line)) { line = "<s> " + line + " <s>"; stringstream ss(line); while (getline(ss, word, ' ')) { if (vocab.find(word) == vocab.end()) { const unsigned id = vocab.size(); vocab.emplace(make_pair(word, id)); } } } return vocab; } // Generates word ID list using corpus and vocab. vector<vector<unsigned>> load_corpus( const string &filename, const unordered_map<string, unsigned> &vocab) { ifstream ifs(filename); if (!ifs.is_open()) { cerr << "File could not be opened: " << filename << endl; exit(1); } vector<vector<unsigned>> corpus; string line, word; while (getline(ifs, line)) { line = "<s> " + line + " <s>"; stringstream ss (line); vector<unsigned> sentence; while (getline(ss, word, ' ')) { const auto it = vocab.find(word); if (it != vocab.end()) sentence.emplace_back(it->second); else sentence.emplace_back(0); // <unk> } corpus.emplace_back(move(sentence)); } return corpus; } // Counts output labels in the corpus. unsigned count_labels(const vector<vector<unsigned>> &corpus) { unsigned ret = 0; for (const auto &sent :corpus) ret += sent.size() - 1; return ret; } // Extracts a minibatch from loaded corpus vector<vector<unsigned>> make_batch( const vector<vector<unsigned>> &corpus, const vector<unsigned> &sent_ids, unsigned eos_id) { const unsigned batch_size = sent_ids.size(); unsigned max_len = 0; for (const unsigned sid : sent_ids) { max_len = std::max<unsigned>(max_len, corpus[sid].size()); } vector<vector<unsigned>> batch(max_len, vector<unsigned>(batch_size, eos_id)); for (unsigned i = 0; i < batch_size; ++i) { const auto &sent = corpus[sent_ids[i]]; for (unsigned j = 0; j < sent.size(); ++j) { batch[j][i] = sent[j]; } } return batch; } // Hand-written LSTM with input/forget/output gates and no peepholes. // Formulation: // i = sigmoid(W_xi . x[t] + W_hi . h[t-1] + b_i) // f = sigmoid(W_xf . x[t] + W_hf . h[t-1] + b_f) // o = sigmoid(W_xo . x[t] + W_ho . h[t-1] + b_o) // j = tanh (W_xj . x[t] + W_hj . h[t-1] + b_j) // c[t] = i * j + f * c[t-1] // h[t] = o * tanh(c[t]) class LSTM { public: LSTM(const string &name, unsigned in_size, unsigned out_size, Trainer &trainer) : out_size_(out_size) , pwxh_(name + "_wxh", {4 * out_size, in_size}, I::XavierUniform()) , pwhh_(name + "_whh", {4 * out_size, out_size}, I::XavierUniform()) , pbh_(name + "_bh", {4 * out_size}, I::Constant(0)) { trainer.add_parameter(pwxh_); trainer.add_parameter(pwhh_); trainer.add_parameter(pbh_); } // Initializes internal values. void init(const Node &init_c = Node()) { wxh_ = F::input(pwxh_); whh_ = F::input(pwhh_); bh_ = F::input(pbh_); if (!init_c.valid()) { h_ = c_ = F::zeros({out_size_}); } else { c_ = init_c; h_ = F::tanh(c_); } } // Forward one step. Node forward(const Node &x) { const Node u = F::matmul(wxh_, x) + F::matmul(whh_, h_) + bh_; const Node i = F::sigmoid(F::slice(u, 0, 0, out_size_)); const Node f = F::sigmoid(F::slice(u, 0, out_size_, 2 * out_size_)); const Node o = F::sigmoid(F::slice(u, 0, 2 * out_size_, 3 * out_size_)); const Node j = F::tanh(F::slice(u, 0, 3 * out_size_, 4 * out_size_)); c_ = i * j + f * c_; h_ = o * F::tanh(c_); return h_; } // Retrieves current cell. Node get_cell() const { return c_; } private: unsigned out_size_; Parameter pwxh_, pwhh_, pbh_; Node wxh_, whh_, bh_, h_, c_; }; // Encoder-decoder translation model. class EncoderDecoder { public: EncoderDecoder(unsigned src_vocab_size, unsigned trg_vocab_size, unsigned embed_size, unsigned hidden_size, Trainer &trainer) : psrc_lookup_( "src_lookup", {embed_size, src_vocab_size}, I::XavierUniform()) , ptrg_lookup_( "trg_lookup", {embed_size, trg_vocab_size}, I::XavierUniform()) , pwhy_("why", {trg_vocab_size, hidden_size}, I::XavierUniform()) , pby_("by", {trg_vocab_size}, I::Constant(0)) , src_lstm_("src_lstm", embed_size, hidden_size, trainer) , trg_lstm_("trg_lstm", embed_size, hidden_size, trainer) { trainer.add_parameter(psrc_lookup_); trainer.add_parameter(ptrg_lookup_); trainer.add_parameter(pwhy_); trainer.add_parameter(pby_); } // Forward function for training encoder-decoder. Both source and target data // should be arranged as: // src_tokens, trg_tokens = { // {sent1_word1, sent2_word1, ..., sentN_word1}, // 1st token (<s>) // {sent1_word2, sent2_word2, ..., sentN_word2}, // 2nd token (first word) // ..., // {sent1_wordM, sent2_wordM, ..., sentN_wordM}, // last token (<s>) // }; Node forward_loss( const vector<vector<unsigned>> &src_tokens, const vector<vector<unsigned>> &trg_tokens, bool train) { Node src_lookup = F::input(psrc_lookup_); Node trg_lookup = F::input(ptrg_lookup_); Node why = F::input(pwhy_); Node by = F::input(pby_); // Reversed encoding (w/o first <s>) src_lstm_.init(); for (unsigned i = src_tokens.size(); i > 1; --i) { Node x = F::pick(src_lookup, 1, src_tokens[i - 1]); x = F::dropout(x, DROPOUT_RATE, train); src_lstm_.forward(x); } // Decoding vector<Node> losses; trg_lstm_.init(src_lstm_.get_cell()); for (unsigned i = 0; i < trg_tokens.size() - 1; ++i) { Node x = F::pick(trg_lookup, 1, trg_tokens[i]); x = F::dropout(x, DROPOUT_RATE, train); Node h = trg_lstm_.forward(x); h = F::dropout(h, DROPOUT_RATE, train); Node y = F::matmul(why, h) + by; losses.emplace_back(F::softmax_cross_entropy(y, 0, trg_tokens[i + 1])); } return F::batch::mean(F::sum(losses)); } private: Parameter psrc_lookup_, ptrg_lookup_, pwhy_, pby_; ::LSTM src_lstm_, trg_lstm_; }; } // namespace int main() { // Loads vocab. const auto src_vocab = ::make_vocab("data/train.en"); const auto trg_vocab = ::make_vocab("data/train.ja"); cout << "#src_vocab: " << src_vocab.size() << endl; cout << "#trg_vocab: " << trg_vocab.size() << endl; const unsigned src_eos_id = src_vocab.at("<s>"); const unsigned trg_eos_id = trg_vocab.at("<s>"); // Loads all corpus. const auto train_src_corpus = ::load_corpus("data/train.en", src_vocab); const auto train_trg_corpus = ::load_corpus("data/train.ja", trg_vocab); const auto valid_src_corpus = ::load_corpus("data/dev.en", src_vocab); const auto valid_trg_corpus = ::load_corpus("data/dev.ja", trg_vocab); const unsigned num_train_sents = train_trg_corpus.size(); const unsigned num_valid_sents = valid_trg_corpus.size(); const unsigned num_train_labels = ::count_labels(train_trg_corpus); const unsigned num_valid_labels = ::count_labels(valid_trg_corpus); cout << "train: " << num_train_sents << " sentences, " << num_train_labels << " labels" << endl; cout << "valid: " << num_valid_sents << " sentences, " << num_valid_labels << " labels" << endl; // Uses GPU. CUDADevice dev(0); Device::set_default_device(dev); // Trainer. Adam trainer; trainer.set_weight_decay(1e-6); trainer.set_gradient_clipping(5); // Our translation model. ::EncoderDecoder encdec( src_vocab.size(), trg_vocab.size(), NUM_EMBED_UNITS, NUM_HIDDEN_UNITS, trainer); // Batch randomizer. random_device rd; mt19937 rng(rd()); // Sentence IDs. vector<unsigned> train_ids(num_train_sents); vector<unsigned> valid_ids(num_valid_sents); iota(begin(train_ids), end(train_ids), 0); iota(begin(valid_ids), end(valid_ids), 0); // Train/valid loop. for (unsigned epoch = 0; epoch < MAX_EPOCH; ++epoch) { cout << "epoch " << (epoch + 1) << '/' << MAX_EPOCH << ':' << endl; // Shuffles train sentence IDs. shuffle(begin(train_ids), end(train_ids), rng); // Training. float train_loss = 0; for (unsigned ofs = 0; ofs < num_train_sents; ofs += BATCH_SIZE) { const vector<unsigned> batch_ids( begin(train_ids) + ofs, begin(train_ids) + std::min<unsigned>( ofs + BATCH_SIZE, num_train_sents)); const auto src_batch = ::make_batch( train_src_corpus, batch_ids, src_eos_id); const auto trg_batch = ::make_batch( train_trg_corpus, batch_ids, trg_eos_id); trainer.reset_gradients(); Graph g; Graph::set_default_graph(g); const auto loss = encdec.forward_loss(src_batch, trg_batch, true); train_loss += g.forward(loss).to_vector()[0] * batch_ids.size(); g.backward(loss); trainer.update(1); cout << ofs << '\r' << flush; } const float train_ppl = std::exp(train_loss / num_train_labels); cout << " train ppl = " << train_ppl << endl; // Validation. float valid_loss = 0; for (unsigned ofs = 0; ofs < num_valid_sents; ofs += BATCH_SIZE) { const vector<unsigned> batch_ids( begin(valid_ids) + ofs, begin(valid_ids) + std::min<unsigned>( ofs + BATCH_SIZE, num_valid_sents)); const auto src_batch = ::make_batch( valid_src_corpus, batch_ids, src_eos_id); const auto trg_batch = ::make_batch( valid_trg_corpus, batch_ids, trg_eos_id); Graph g; Graph::set_default_graph(g); const auto loss = encdec.forward_loss(src_batch, trg_batch, false); valid_loss += g.forward(loss).to_vector()[0] * batch_ids.size(); cout << ofs << '\r' << flush; } const float valid_ppl = std::exp(valid_loss / num_valid_labels); cout << " valid ppl = " << valid_ppl << endl; } return 0; } <commit_msg>add frequency filter of vocabulary.<commit_after>// Sample code to train the encoder-decoder model using small English-Japanese // parallel corpora. // // Model detail: // Sutskever et al., 2014. // Sequence to Sequence Learning with Neural Networks. // https://arxiv.org/abs/1409.3215 // // Corpora detail: // https://github.com/odashi/small_parallel_enja // // Usage: // Run 'download_data.sh' in the same directory before using this code. // g++ // -std=c++11 // -I/path/to/primitiv/includes (typically -I../..) // -L/path/to/primitiv/libs (typically -L../../build/primitiv) // encdec.cc -lprimitiv #include <algorithm> #include <fstream> #include <iostream> #include <queue> #include <random> #include <sstream> #include <string> #include <utility> #include <vector> #include <primitiv/primitiv.h> #include <primitiv/primitiv_cuda.h> using primitiv::trainers::Adam; namespace F = primitiv::node_ops; namespace I = primitiv::initializers; using namespace primitiv; using namespace std; namespace { static const unsigned NUM_EMBED_UNITS = 512; static const unsigned NUM_HIDDEN_UNITS = 512; static const unsigned BATCH_SIZE = 64; static const unsigned MAX_EPOCH = 100; static const float DROPOUT_RATE = 0.5; // Gathers the set of words from space-separated corpus. unordered_map<string, unsigned> make_vocab( const string &filename, unsigned size) { if (size < 3) { cerr << "vocab size should be equal-to or grater-than 3." << endl; exit(1); } ifstream ifs(filename); if (!ifs.is_open()) { cerr << "File could not be opened: " << filename << endl; exit(1); } unordered_map<string, unsigned> freq; string line, word; while (getline(ifs, line)) { stringstream ss(line); while (getline(ss, word, ' ')) ++freq[word]; } using freq_t = pair<string, unsigned>; auto cmp = [](const freq_t &a, const freq_t &b) { return a.second < b.second; }; priority_queue<freq_t, vector<freq_t>, decltype(cmp)> q(cmp); for (const auto &x : freq) q.push(x); unordered_map<string, unsigned> vocab; vocab.insert(make_pair("<unk>", 0)); vocab.insert(make_pair("<bos>", 1)); vocab.insert(make_pair("<eos>", 2)); for (unsigned i = 3; i < size; ++i) { vocab.insert(make_pair(q.top().first, i)); q.pop(); } return vocab; } // Generates word ID list using corpus and vocab. vector<vector<unsigned>> load_corpus( const string &filename, const unordered_map<string, unsigned> &vocab) { ifstream ifs(filename); if (!ifs.is_open()) { cerr << "File could not be opened: " << filename << endl; exit(1); } vector<vector<unsigned>> corpus; string line, word; while (getline(ifs, line)) { line = "<bos> " + line + " <eos>"; stringstream ss (line); vector<unsigned> sentence; while (getline(ss, word, ' ')) { const auto it = vocab.find(word); if (it != vocab.end()) sentence.emplace_back(it->second); else sentence.emplace_back(0); // <unk> } corpus.emplace_back(move(sentence)); } return corpus; } // Counts output labels in the corpus. unsigned count_labels(const vector<vector<unsigned>> &corpus) { unsigned ret = 0; for (const auto &sent :corpus) ret += sent.size() - 1; // w/o <bos> return ret; } // Extracts a minibatch from loaded corpus vector<vector<unsigned>> make_batch( const vector<vector<unsigned>> &corpus, const vector<unsigned> &sent_ids, unsigned eos_id) { const unsigned batch_size = sent_ids.size(); unsigned max_len = 0; for (const unsigned sid : sent_ids) { max_len = std::max<unsigned>(max_len, corpus[sid].size()); } vector<vector<unsigned>> batch(max_len, vector<unsigned>(batch_size, eos_id)); for (unsigned i = 0; i < batch_size; ++i) { const auto &sent = corpus[sent_ids[i]]; for (unsigned j = 0; j < sent.size(); ++j) { batch[j][i] = sent[j]; } } return batch; } // Hand-written LSTM with input/forget/output gates and no peepholes. // Formulation: // i = sigmoid(W_xi . x[t] + W_hi . h[t-1] + b_i) // f = sigmoid(W_xf . x[t] + W_hf . h[t-1] + b_f) // o = sigmoid(W_xo . x[t] + W_ho . h[t-1] + b_o) // j = tanh (W_xj . x[t] + W_hj . h[t-1] + b_j) // c[t] = i * j + f * c[t-1] // h[t] = o * tanh(c[t]) class LSTM { public: LSTM(const string &name, unsigned in_size, unsigned out_size, Trainer &trainer) : out_size_(out_size) , pwxh_(name + "_wxh", {4 * out_size, in_size}, I::XavierUniform()) , pwhh_(name + "_whh", {4 * out_size, out_size}, I::XavierUniform()) , pbh_(name + "_bh", {4 * out_size}, I::Constant(0)) { trainer.add_parameter(pwxh_); trainer.add_parameter(pwhh_); trainer.add_parameter(pbh_); } // Initializes internal values. void init(const Node &init_c = Node()) { wxh_ = F::input(pwxh_); whh_ = F::input(pwhh_); bh_ = F::input(pbh_); if (!init_c.valid()) { h_ = c_ = F::zeros({out_size_}); } else { c_ = init_c; h_ = F::tanh(c_); } } // Forward one step. Node forward(const Node &x) { const Node u = F::matmul(wxh_, x) + F::matmul(whh_, h_) + bh_; const Node i = F::sigmoid(F::slice(u, 0, 0, out_size_)); const Node f = F::sigmoid(F::slice(u, 0, out_size_, 2 * out_size_)); const Node o = F::sigmoid(F::slice(u, 0, 2 * out_size_, 3 * out_size_)); const Node j = F::tanh(F::slice(u, 0, 3 * out_size_, 4 * out_size_)); c_ = i * j + f * c_; h_ = o * F::tanh(c_); return h_; } // Retrieves current cell. Node get_cell() const { return c_; } private: unsigned out_size_; Parameter pwxh_, pwhh_, pbh_; Node wxh_, whh_, bh_, h_, c_; }; // Encoder-decoder translation model. class EncoderDecoder { public: EncoderDecoder(unsigned src_vocab_size, unsigned trg_vocab_size, unsigned embed_size, unsigned hidden_size, Trainer &trainer) : psrc_lookup_( "src_lookup", {embed_size, src_vocab_size}, I::XavierUniform()) , ptrg_lookup_( "trg_lookup", {embed_size, trg_vocab_size}, I::XavierUniform()) , pwhy_("why", {trg_vocab_size, hidden_size}, I::XavierUniform()) , pby_("by", {trg_vocab_size}, I::Constant(0)) , src_lstm_("src_lstm", embed_size, hidden_size, trainer) , trg_lstm_("trg_lstm", embed_size, hidden_size, trainer) { trainer.add_parameter(psrc_lookup_); trainer.add_parameter(ptrg_lookup_); trainer.add_parameter(pwhy_); trainer.add_parameter(pby_); } // Forward function for training encoder-decoder. Both source and target data // should be arranged as: // src_tokens, trg_tokens = { // {sent1_word1, sent2_word1, ..., sentN_word1}, // 1st token (<bos>) // {sent1_word2, sent2_word2, ..., sentN_word2}, // 2nd token (first word) // ..., // {sent1_wordM, sent2_wordM, ..., sentN_wordM}, // last token (<eos>) // }; Node forward_loss( const vector<vector<unsigned>> &src_tokens, const vector<vector<unsigned>> &trg_tokens, bool train) { Node src_lookup = F::input(psrc_lookup_); Node trg_lookup = F::input(ptrg_lookup_); Node why = F::input(pwhy_); Node by = F::input(pby_); // Reversed encoding src_lstm_.init(); for (unsigned i = src_tokens.size(); i > 0; --i) { Node x = F::pick(src_lookup, 1, src_tokens[i - 1]); x = F::dropout(x, DROPOUT_RATE, train); src_lstm_.forward(x); } // Decoding vector<Node> losses; trg_lstm_.init(src_lstm_.get_cell()); for (unsigned i = 0; i < trg_tokens.size() - 1; ++i) { Node x = F::pick(trg_lookup, 1, trg_tokens[i]); x = F::dropout(x, DROPOUT_RATE, train); Node h = trg_lstm_.forward(x); h = F::dropout(h, DROPOUT_RATE, train); Node y = F::matmul(why, h) + by; losses.emplace_back(F::softmax_cross_entropy(y, 0, trg_tokens[i + 1])); } return F::batch::mean(F::sum(losses)); } private: Parameter psrc_lookup_, ptrg_lookup_, pwhy_, pby_; ::LSTM src_lstm_, trg_lstm_; }; } // namespace int main() { // Loads vocab. const auto src_vocab = ::make_vocab("data/train.en", 4000); const auto trg_vocab = ::make_vocab("data/train.ja", 5000); cout << "#src_vocab: " << src_vocab.size() << endl; cout << "#trg_vocab: " << trg_vocab.size() << endl; const unsigned src_eos_id = src_vocab.at("<eos>"); const unsigned trg_eos_id = trg_vocab.at("<eos>"); // Loads all corpus. const auto train_src_corpus = ::load_corpus("data/train.en", src_vocab); const auto train_trg_corpus = ::load_corpus("data/train.ja", trg_vocab); const auto valid_src_corpus = ::load_corpus("data/dev.en", src_vocab); const auto valid_trg_corpus = ::load_corpus("data/dev.ja", trg_vocab); const unsigned num_train_sents = train_trg_corpus.size(); const unsigned num_valid_sents = valid_trg_corpus.size(); const unsigned num_train_labels = ::count_labels(train_trg_corpus); const unsigned num_valid_labels = ::count_labels(valid_trg_corpus); cout << "train: " << num_train_sents << " sentences, " << num_train_labels << " labels" << endl; cout << "valid: " << num_valid_sents << " sentences, " << num_valid_labels << " labels" << endl; // Uses GPU. CUDADevice dev(0); Device::set_default_device(dev); // Trainer. Adam trainer; trainer.set_weight_decay(1e-6); trainer.set_gradient_clipping(5); // Our translation model. ::EncoderDecoder encdec( src_vocab.size(), trg_vocab.size(), NUM_EMBED_UNITS, NUM_HIDDEN_UNITS, trainer); // Batch randomizer. random_device rd; mt19937 rng(rd()); // Sentence IDs. vector<unsigned> train_ids(num_train_sents); vector<unsigned> valid_ids(num_valid_sents); iota(begin(train_ids), end(train_ids), 0); iota(begin(valid_ids), end(valid_ids), 0); // Train/valid loop. for (unsigned epoch = 0; epoch < MAX_EPOCH; ++epoch) { cout << "epoch " << (epoch + 1) << '/' << MAX_EPOCH << ':' << endl; // Shuffles train sentence IDs. shuffle(begin(train_ids), end(train_ids), rng); // Training. float train_loss = 0; for (unsigned ofs = 0; ofs < num_train_sents; ofs += BATCH_SIZE) { const vector<unsigned> batch_ids( begin(train_ids) + ofs, begin(train_ids) + std::min<unsigned>( ofs + BATCH_SIZE, num_train_sents)); const auto src_batch = ::make_batch( train_src_corpus, batch_ids, src_eos_id); const auto trg_batch = ::make_batch( train_trg_corpus, batch_ids, trg_eos_id); trainer.reset_gradients(); Graph g; Graph::set_default_graph(g); const auto loss = encdec.forward_loss(src_batch, trg_batch, true); train_loss += g.forward(loss).to_vector()[0] * batch_ids.size(); g.backward(loss); trainer.update(1); cout << ofs << '\r' << flush; } const float train_ppl = std::exp(train_loss / num_train_labels); cout << " train ppl = " << train_ppl << endl; // Validation. float valid_loss = 0; for (unsigned ofs = 0; ofs < num_valid_sents; ofs += BATCH_SIZE) { const vector<unsigned> batch_ids( begin(valid_ids) + ofs, begin(valid_ids) + std::min<unsigned>( ofs + BATCH_SIZE, num_valid_sents)); const auto src_batch = ::make_batch( valid_src_corpus, batch_ids, src_eos_id); const auto trg_batch = ::make_batch( valid_trg_corpus, batch_ids, trg_eos_id); Graph g; Graph::set_default_graph(g); const auto loss = encdec.forward_loss(src_batch, trg_batch, false); valid_loss += g.forward(loss).to_vector()[0] * batch_ids.size(); cout << ofs << '\r' << flush; } const float valid_ppl = std::exp(valid_loss / num_valid_labels); cout << " valid ppl = " << valid_ppl << endl; } return 0; } <|endoftext|>
<commit_before>/********************************************************************************* * * Inviwo - Interactive Visualization Workshop * * Copyright (c) 2013-2017 Inviwo Foundation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * *********************************************************************************/ #include "textoverlaygl.h" #include <modules/fontrendering/util/fontutils.h> #include <inviwo/core/common/inviwoapplication.h> #include <inviwo/core/datastructures/image/image.h> #include <inviwo/core/util/filesystem.h> #include <modules/opengl/inviwoopengl.h> #include <modules/opengl/texture/textureutils.h> #include <modules/opengl/openglutils.h> #include <modules/opengl/shader/shaderutils.h> #include <modules/opengl/image/imagegl.h> #include <inviwo/core/util/assertion.h> #include <cctype> #include <locale> namespace inviwo { const ProcessorInfo TextOverlayGL::processorInfo_{ "org.inviwo.TextOverlayGL", // Class identifier "Text Overlay", // Display name "Drawing", // Category CodeState::Stable, // Code state Tags::GL, // Tags }; const ProcessorInfo TextOverlayGL::getProcessorInfo() const { return processorInfo_; } TextOverlayGL::TextOverlayGL() : Processor() , inport_("inport") , outport_("outport") , enable_("enable","Enabled",true) , text_("Text", "Text", "Lorem ipsum etc.", InvalidationLevel::InvalidOutput, PropertySemantics::TextEditor) , color_("color_", "Color", vec4(1.0f), vec4(0.0f), vec4(1.0f), vec4(0.01f), InvalidationLevel::InvalidOutput, PropertySemantics::Color) , fontFace_("fontFace", "Font Face") , fontSize_("fontSize", "Font size") , fontPos_("Position", "Position", vec2(0.0f), vec2(0.0f), vec2(1.0f), vec2(0.01f)) , anchorPos_("Anchor", "Anchor", vec2(-1.0f), vec2(-1.0f), vec2(1.0f), vec2(0.01f)) , addArgButton_("addArgBtn", "Add String Argument") , numArgs_(0u) { addPort(inport_); addPort(outport_); addProperty(enable_); addProperty(text_); addProperty(color_); addProperty(fontFace_); addProperty(fontPos_); addProperty(anchorPos_); addProperty(fontSize_); addProperty(addArgButton_); addArgButton_.onChange([this]() { if (numArgs_ >= maxNumArgs_) { addArgButton_.setReadOnly(numArgs_ >= maxNumArgs_); return; } ++numArgs_; std::string num = std::to_string(numArgs_); auto property = new StringProperty(std::string("arg") + num, "Arg " + num); property->setSerializationMode(PropertySerializationMode::All); addProperty(property, true); }); auto fonts = util::getAvailableFonts(); for (auto font : fonts) { auto identifier = filesystem::getFileNameWithoutExtension(font.second); // use the file name w/o extension as identifier fontFace_.addOption(identifier, font.first, font.second); } fontFace_.setSelectedIdentifier("arial"); fontFace_.setCurrentStateAsDefault(); // set up different font sizes std::vector<int> fontSizes ={ 8, 10, 11, 12, 14, 16, 20, 24, 28, 36, 48, 60, 72, 96 }; for (auto size : fontSizes) { std::string str = std::to_string(size); fontSize_.addOption(str, str, size); } fontSize_.setSelectedIndex(4); fontSize_.setCurrentStateAsDefault(); } void TextOverlayGL::process() { if (!enable_.get()) { outport_.setData(inport_.getData()); return; } if (fontFace_.isModified()) { textRenderer_.setFont(fontFace_.get()); } // check whether a property was modified if (!cacheTexture_ || util::any_of(getProperties(), [](const auto& p) { return p->isModified(); })) { updateCache(); } // draw cached overlay on top of the input image utilgl::activateTargetAndCopySource(outport_, inport_, ImageType::ColorDepthPicking); utilgl::DepthFuncState depthFunc(GL_ALWAYS); utilgl::BlendModeState blending(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // use integer position for best results vec2 size(cacheTexture_->getDimensions()); vec2 shift = 0.5f * size * (anchorPos_.get() + vec2(1.0f, 1.0f)); ivec2 pos(fontPos_.get() * vec2(outport_.getDimensions())); pos -= ivec2(shift); // render texture containing the text onto the current canvas textureRenderer_.render(cacheTexture_, pos, outport_.getDimensions()); utilgl::deactivateCurrentTarget(); } void TextOverlayGL::deserialize(Deserializer & d) { Processor::deserialize(d); // update the number of place markers properties using the total number of string properties in // this processor. Note that this number is one element larger. auto args = this->getPropertiesByType<StringProperty>(false); numArgs_ = args.size() - 1; // only maxNumArgs_ are supported, disable button if more exist addArgButton_.setReadOnly(numArgs_ > maxNumArgs_); } std::string TextOverlayGL::getString() const { std::string str = text_.get(); // replace all occurrences of place markers with the corresponding args auto args = this->getPropertiesByType<StringProperty>(false); // remove default text string property util::erase_remove_if(args, [this](const auto& p) { return p == &text_; }); ivwAssert(numArgs_ == args.size(), "TextOverlayGL: number arguments not matching internal count"); // parse string for all "%" and try to extract the number following the percent sign bool printWarning = false; std::string matchStr("%"); for (std::size_t offset = str.find(matchStr, 0u); offset != std::string::npos; offset = str.find(matchStr, offset)) { // extract number substring, // read 3 characters to ensure that the number only has at most 2 digits std::string numStr = str.substr(offset + 1, 3); if (std::isdigit(numStr[0])) { std::size_t numDigits = 0; // extract number and reduce it by one since the %args start with 1 // std::stoul will not throw an invalid argument exception since we made sure, it is a // number (std::isdigit above) std::size_t argNum = std::stoul(numStr, &numDigits) - 1; if (argNum <= numArgs_) { // make textual replacement ("%" and number of digits) str.replace(offset, numDigits + 1, args[argNum]->get()); offset += args[argNum]->get().size(); } else { if (numDigits > 2) printWarning = true; offset += 1 + numDigits; } } } if (printWarning) { LogWarn("Input text contains more than the allowed " << maxNumArgs_ << " place markers."); } return str; } void TextOverlayGL::updateCache() { textRenderer_.setFontSize(fontSize_.getSelectedValue()); std::string str(getString()); size2_t labelSize(textRenderer_.computeTextSize(str)); if (!cacheTexture_ || (cacheTexture_->getDimensions() != labelSize)) { auto texture = std::make_shared<Texture2D>(labelSize, GL_RGBA, GL_RGBA, GL_UNSIGNED_BYTE, GL_LINEAR); texture->initialize(nullptr); cacheTexture_ = texture; } textRenderer_.renderToTexture(cacheTexture_, str, color_.get()); } } // namespace <commit_msg>FontRendering: Use util to create texture<commit_after>/********************************************************************************* * * Inviwo - Interactive Visualization Workshop * * Copyright (c) 2013-2017 Inviwo Foundation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * *********************************************************************************/ #include "textoverlaygl.h" #include <modules/fontrendering/util/fontutils.h> #include <inviwo/core/common/inviwoapplication.h> #include <inviwo/core/datastructures/image/image.h> #include <inviwo/core/util/filesystem.h> #include <modules/opengl/inviwoopengl.h> #include <modules/opengl/texture/textureutils.h> #include <modules/opengl/openglutils.h> #include <modules/opengl/shader/shaderutils.h> #include <modules/opengl/image/imagegl.h> #include <inviwo/core/util/assertion.h> #include <cctype> #include <locale> namespace inviwo { const ProcessorInfo TextOverlayGL::processorInfo_{ "org.inviwo.TextOverlayGL", // Class identifier "Text Overlay", // Display name "Drawing", // Category CodeState::Stable, // Code state Tags::GL, // Tags }; const ProcessorInfo TextOverlayGL::getProcessorInfo() const { return processorInfo_; } TextOverlayGL::TextOverlayGL() : Processor() , inport_("inport") , outport_("outport") , enable_("enable","Enabled",true) , text_("Text", "Text", "Lorem ipsum etc.", InvalidationLevel::InvalidOutput, PropertySemantics::TextEditor) , color_("color_", "Color", vec4(1.0f), vec4(0.0f), vec4(1.0f), vec4(0.01f), InvalidationLevel::InvalidOutput, PropertySemantics::Color) , fontFace_("fontFace", "Font Face") , fontSize_("fontSize", "Font size") , fontPos_("Position", "Position", vec2(0.0f), vec2(0.0f), vec2(1.0f), vec2(0.01f)) , anchorPos_("Anchor", "Anchor", vec2(-1.0f), vec2(-1.0f), vec2(1.0f), vec2(0.01f)) , addArgButton_("addArgBtn", "Add String Argument") , numArgs_(0u) { addPort(inport_); addPort(outport_); addProperty(enable_); addProperty(text_); addProperty(color_); addProperty(fontFace_); addProperty(fontPos_); addProperty(anchorPos_); addProperty(fontSize_); addProperty(addArgButton_); addArgButton_.onChange([this]() { if (numArgs_ >= maxNumArgs_) { addArgButton_.setReadOnly(numArgs_ >= maxNumArgs_); return; } ++numArgs_; std::string num = std::to_string(numArgs_); auto property = new StringProperty(std::string("arg") + num, "Arg " + num); property->setSerializationMode(PropertySerializationMode::All); addProperty(property, true); }); auto fonts = util::getAvailableFonts(); for (auto font : fonts) { auto identifier = filesystem::getFileNameWithoutExtension(font.second); // use the file name w/o extension as identifier fontFace_.addOption(identifier, font.first, font.second); } fontFace_.setSelectedIdentifier("arial"); fontFace_.setCurrentStateAsDefault(); // set up different font sizes std::vector<int> fontSizes ={ 8, 10, 11, 12, 14, 16, 20, 24, 28, 36, 48, 60, 72, 96 }; for (auto size : fontSizes) { std::string str = std::to_string(size); fontSize_.addOption(str, str, size); } fontSize_.setSelectedIndex(4); fontSize_.setCurrentStateAsDefault(); } void TextOverlayGL::process() { if (!enable_.get()) { outport_.setData(inport_.getData()); return; } if (fontFace_.isModified()) { textRenderer_.setFont(fontFace_.get()); } // check whether a property was modified if (!cacheTexture_ || util::any_of(getProperties(), [](const auto& p) { return p->isModified(); })) { updateCache(); } // draw cached overlay on top of the input image utilgl::activateTargetAndCopySource(outport_, inport_, ImageType::ColorDepthPicking); utilgl::DepthFuncState depthFunc(GL_ALWAYS); utilgl::BlendModeState blending(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // use integer position for best results vec2 size(cacheTexture_->getDimensions()); vec2 shift = 0.5f * size * (anchorPos_.get() + vec2(1.0f, 1.0f)); ivec2 pos(fontPos_.get() * vec2(outport_.getDimensions())); pos -= ivec2(shift); // render texture containing the text onto the current canvas textureRenderer_.render(cacheTexture_, pos, outport_.getDimensions()); utilgl::deactivateCurrentTarget(); } void TextOverlayGL::deserialize(Deserializer & d) { Processor::deserialize(d); // update the number of place markers properties using the total number of string properties in // this processor. Note that this number is one element larger. auto args = this->getPropertiesByType<StringProperty>(false); numArgs_ = args.size() - 1; // only maxNumArgs_ are supported, disable button if more exist addArgButton_.setReadOnly(numArgs_ > maxNumArgs_); } std::string TextOverlayGL::getString() const { std::string str = text_.get(); // replace all occurrences of place markers with the corresponding args auto args = this->getPropertiesByType<StringProperty>(false); // remove default text string property util::erase_remove_if(args, [this](const auto& p) { return p == &text_; }); ivwAssert(numArgs_ == args.size(), "TextOverlayGL: number arguments not matching internal count"); // parse string for all "%" and try to extract the number following the percent sign bool printWarning = false; std::string matchStr("%"); for (std::size_t offset = str.find(matchStr, 0u); offset != std::string::npos; offset = str.find(matchStr, offset)) { // extract number substring, // read 3 characters to ensure that the number only has at most 2 digits std::string numStr = str.substr(offset + 1, 3); if (std::isdigit(numStr[0])) { std::size_t numDigits = 0; // extract number and reduce it by one since the %args start with 1 // std::stoul will not throw an invalid argument exception since we made sure, it is a // number (std::isdigit above) std::size_t argNum = std::stoul(numStr, &numDigits) - 1; if (argNum <= numArgs_) { // make textual replacement ("%" and number of digits) str.replace(offset, numDigits + 1, args[argNum]->get()); offset += args[argNum]->get().size(); } else { if (numDigits > 2) printWarning = true; offset += 1 + numDigits; } } } if (printWarning) { LogWarn("Input text contains more than the allowed " << maxNumArgs_ << " place markers."); } return str; } void TextOverlayGL::updateCache() { textRenderer_.setFontSize(fontSize_.getSelectedValue()); std::string str(getString()); cacheTexture_ = util::createTextTexture(textRenderer_ , str , fontSize_.getSelectedValue() , color_.get() , cacheTexture_ ); } } // namespace <|endoftext|>
<commit_before>/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/planning/planner/rtk/rtk_replay_planner.h" #include <fstream> #include <utility> #include "cyber/common/log.h" #include "modules/common/util/string_tokenizer.h" #include "modules/common/vehicle_state/vehicle_state_provider.h" #include "modules/planning/common/planning_gflags.h" namespace apollo { namespace planning { using apollo::common::ErrorCode; using apollo::common::Status; using apollo::common::TrajectoryPoint; using apollo::common::VehicleStateProvider; RTKReplayPlanner::RTKReplayPlanner() { ReadTrajectoryFile(FLAGS_rtk_trajectory_filename); } Status RTKReplayPlanner::Init(const PlanningConfig&) { return Status::OK(); } Status RTKReplayPlanner::Plan(const TrajectoryPoint& planning_start_point, Frame* frame) { auto status = Status::OK(); bool has_plan = false; auto it = std::find_if( frame->mutable_reference_line_info()->begin(), frame->mutable_reference_line_info()->end(), [](const ReferenceLineInfo& ref) { return ref.IsChangeLanePath(); }); if (it != frame->mutable_reference_line_info()->end()) { status = PlanOnReferenceLine(planning_start_point, frame, &(*it)); has_plan = (it->IsDrivable() && it->IsChangeLanePath() && it->TrajectoryLength() > FLAGS_change_lane_min_length); if (!has_plan) { AERROR << "Fail to plan for lane change."; } } if (!has_plan || !FLAGS_prioritize_change_lane) { for (auto& reference_line_info : *frame->mutable_reference_line_info()) { if (reference_line_info.IsChangeLanePath()) { continue; } status = PlanOnReferenceLine(planning_start_point, frame, &reference_line_info); if (status != Status::OK()) { AERROR << "planner failed to make a driving plan for: " << reference_line_info.Lanes().Id(); } } } return status; } Status RTKReplayPlanner::PlanOnReferenceLine( const TrajectoryPoint& planning_init_point, Frame*, ReferenceLineInfo* reference_line_info) { if (complete_rtk_trajectory_.empty() || complete_rtk_trajectory_.size() < 2) { std::string msg( "RTKReplayPlanner doesn't have a recorded trajectory or " "the recorded trajectory doesn't have enough valid trajectory " "points."); AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } std::uint32_t matched_index = QueryPositionMatchedPoint(planning_init_point, complete_rtk_trajectory_); std::uint32_t forward_buffer = FLAGS_rtk_trajectory_forward; // end_index is excluded. std::uint32_t end_index = std::min<std::uint32_t>( complete_rtk_trajectory_.size(), matched_index + forward_buffer); // auto* trajectory_points = trajectory_pb->mutable_trajectory_point(); std::vector<TrajectoryPoint> trajectory_points( complete_rtk_trajectory_.begin() + matched_index, complete_rtk_trajectory_.begin() + end_index); // reset relative time double zero_time = complete_rtk_trajectory_[matched_index].relative_time(); for (auto& trajectory_point : trajectory_points) { trajectory_point.set_relative_time(trajectory_point.relative_time() - zero_time); } // check if the trajectory has enough points; // if not, append the last points multiple times and // adjust their corresponding time stamps. while (trajectory_points.size() < static_cast<std::size_t>(FLAGS_rtk_trajectory_forward)) { const auto& last_point = trajectory_points.rbegin(); auto new_point = last_point; new_point->set_relative_time(new_point->relative_time() + FLAGS_rtk_trajectory_resolution); trajectory_points.push_back(*new_point); } reference_line_info->SetTrajectory(DiscretizedTrajectory(trajectory_points)); return Status::OK(); } void RTKReplayPlanner::ReadTrajectoryFile(const std::string& filename) { if (!complete_rtk_trajectory_.empty()) { complete_rtk_trajectory_.clear(); } std::ifstream file_in(filename.c_str()); if (!file_in.is_open()) { AERROR << "RTKReplayPlanner cannot open trajectory file: " << filename; return; } std::string line; // skip the header line. getline(file_in, line); while (true) { getline(file_in, line); if (line == "") { break; } auto tokens = apollo::common::util::StringTokenizer::Split(line, "\t "); if (tokens.size() < 11) { AERROR << "RTKReplayPlanner parse line failed; the data dimension does " "not match."; AERROR << line; continue; } TrajectoryPoint point; point.mutable_path_point()->set_x(std::stod(tokens[0])); point.mutable_path_point()->set_y(std::stod(tokens[1])); point.mutable_path_point()->set_z(std::stod(tokens[2])); point.set_v(std::stod(tokens[3])); point.set_a(std::stod(tokens[4])); point.mutable_path_point()->set_kappa(std::stod(tokens[5])); point.mutable_path_point()->set_dkappa(std::stod(tokens[6])); point.set_relative_time(std::stod(tokens[7])); point.mutable_path_point()->set_theta(std::stod(tokens[8])); point.mutable_path_point()->set_s(std::stod(tokens[10])); complete_rtk_trajectory_.push_back(std::move(point)); } file_in.close(); } std::uint32_t RTKReplayPlanner::QueryPositionMatchedPoint( const TrajectoryPoint& start_point, const std::vector<TrajectoryPoint>& trajectory) const { auto func_distance_square = [](const TrajectoryPoint& point, const double x, const double y) { double dx = point.path_point().x() - x; double dy = point.path_point().y() - y; return dx * dx + dy * dy; }; double d_min = func_distance_square(trajectory.front(), start_point.path_point().x(), start_point.path_point().y()); std::uint32_t index_min = 0; for (std::uint32_t i = 1; i < trajectory.size(); ++i) { double d_temp = func_distance_square(trajectory[i], start_point.path_point().x(), start_point.path_point().y()); if (d_temp < d_min) { d_min = d_temp; index_min = i; } } return index_min; } } // namespace planning } // namespace apollo <commit_msg>planning: fix compile warning.<commit_after>/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/planning/planner/rtk/rtk_replay_planner.h" #include <fstream> #include <utility> #include "cyber/common/log.h" #include "modules/common/util/string_tokenizer.h" #include "modules/common/vehicle_state/vehicle_state_provider.h" #include "modules/planning/common/planning_gflags.h" namespace apollo { namespace planning { using apollo::common::ErrorCode; using apollo::common::Status; using apollo::common::TrajectoryPoint; using apollo::common::VehicleStateProvider; RTKReplayPlanner::RTKReplayPlanner() { ReadTrajectoryFile(FLAGS_rtk_trajectory_filename); } Status RTKReplayPlanner::Init(const PlanningConfig&) { return Status::OK(); } Status RTKReplayPlanner::Plan(const TrajectoryPoint& planning_start_point, Frame* frame) { auto status = Status::OK(); bool has_plan = false; auto it = std::find_if( frame->mutable_reference_line_info()->begin(), frame->mutable_reference_line_info()->end(), [](const ReferenceLineInfo& ref) { return ref.IsChangeLanePath(); }); if (it != frame->mutable_reference_line_info()->end()) { status = PlanOnReferenceLine(planning_start_point, frame, &(*it)); has_plan = (it->IsDrivable() && it->IsChangeLanePath() && it->TrajectoryLength() > FLAGS_change_lane_min_length); if (!has_plan) { AERROR << "Fail to plan for lane change."; } } if (!has_plan || !FLAGS_prioritize_change_lane) { for (auto& reference_line_info : *frame->mutable_reference_line_info()) { if (reference_line_info.IsChangeLanePath()) { continue; } status = PlanOnReferenceLine(planning_start_point, frame, &reference_line_info); if (status != Status::OK()) { AERROR << "planner failed to make a driving plan for: " << reference_line_info.Lanes().Id(); } } } return status; } Status RTKReplayPlanner::PlanOnReferenceLine( const TrajectoryPoint& planning_init_point, Frame*, ReferenceLineInfo* reference_line_info) { if (complete_rtk_trajectory_.empty() || complete_rtk_trajectory_.size() < 2) { std::string msg( "RTKReplayPlanner doesn't have a recorded trajectory or " "the recorded trajectory doesn't have enough valid trajectory " "points."); AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } std::uint32_t matched_index = QueryPositionMatchedPoint(planning_init_point, complete_rtk_trajectory_); std::uint32_t forward_buffer = static_cast<std::uint32_t>(FLAGS_rtk_trajectory_forward); // end_index is excluded. std::uint32_t end_index = std::min<std::uint32_t>( static_cast<std::uint32_t>(complete_rtk_trajectory_.size()), matched_index + forward_buffer); // auto* trajectory_points = trajectory_pb->mutable_trajectory_point(); std::vector<TrajectoryPoint> trajectory_points( complete_rtk_trajectory_.begin() + matched_index, complete_rtk_trajectory_.begin() + end_index); // reset relative time double zero_time = complete_rtk_trajectory_[matched_index].relative_time(); for (auto& trajectory_point : trajectory_points) { trajectory_point.set_relative_time(trajectory_point.relative_time() - zero_time); } // check if the trajectory has enough points; // if not, append the last points multiple times and // adjust their corresponding time stamps. while (trajectory_points.size() < static_cast<std::size_t>(FLAGS_rtk_trajectory_forward)) { const auto& last_point = trajectory_points.rbegin(); auto new_point = last_point; new_point->set_relative_time(new_point->relative_time() + FLAGS_rtk_trajectory_resolution); trajectory_points.push_back(*new_point); } reference_line_info->SetTrajectory(DiscretizedTrajectory(trajectory_points)); return Status::OK(); } void RTKReplayPlanner::ReadTrajectoryFile(const std::string& filename) { if (!complete_rtk_trajectory_.empty()) { complete_rtk_trajectory_.clear(); } std::ifstream file_in(filename.c_str()); if (!file_in.is_open()) { AERROR << "RTKReplayPlanner cannot open trajectory file: " << filename; return; } std::string line; // skip the header line. getline(file_in, line); while (true) { getline(file_in, line); if (line == "") { break; } auto tokens = apollo::common::util::StringTokenizer::Split(line, "\t "); if (tokens.size() < 11) { AERROR << "RTKReplayPlanner parse line failed; the data dimension does " "not match."; AERROR << line; continue; } TrajectoryPoint point; point.mutable_path_point()->set_x(std::stod(tokens[0])); point.mutable_path_point()->set_y(std::stod(tokens[1])); point.mutable_path_point()->set_z(std::stod(tokens[2])); point.set_v(std::stod(tokens[3])); point.set_a(std::stod(tokens[4])); point.mutable_path_point()->set_kappa(std::stod(tokens[5])); point.mutable_path_point()->set_dkappa(std::stod(tokens[6])); point.set_relative_time(std::stod(tokens[7])); point.mutable_path_point()->set_theta(std::stod(tokens[8])); point.mutable_path_point()->set_s(std::stod(tokens[10])); complete_rtk_trajectory_.push_back(std::move(point)); } file_in.close(); } std::uint32_t RTKReplayPlanner::QueryPositionMatchedPoint( const TrajectoryPoint& start_point, const std::vector<TrajectoryPoint>& trajectory) const { auto func_distance_square = [](const TrajectoryPoint& point, const double x, const double y) { double dx = point.path_point().x() - x; double dy = point.path_point().y() - y; return dx * dx + dy * dy; }; double d_min = func_distance_square(trajectory.front(), start_point.path_point().x(), start_point.path_point().y()); std::uint32_t index_min = 0; for (std::uint32_t i = 1; i < trajectory.size(); ++i) { double d_temp = func_distance_square(trajectory[i], start_point.path_point().x(), start_point.path_point().y()); if (d_temp < d_min) { d_min = d_temp; index_min = i; } } return index_min; } } // namespace planning } // namespace apollo <|endoftext|>
<commit_before>/* Copyright (c) 2003, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TORRENT_HTTP_TRACKER_CONNECTION_HPP_INCLUDED #define TORRENT_HTTP_TRACKER_CONNECTION_HPP_INCLUDED #include <string> #ifdef _MSC_VER #pragma warning(push, 1) #endif #include <boost/shared_ptr.hpp> #ifdef _MSC_VER #pragma warning(pop) #endif #include "libtorrent/peer_id.hpp" #include "libtorrent/tracker_manager.hpp" #include "libtorrent/config.hpp" namespace libtorrent { class http_connection; class entry; class http_parser; class connection_queue; class session_settings; class TORRENT_EXPORT http_tracker_connection : public tracker_connection { friend class tracker_manager; public: http_tracker_connection( io_service& ios , connection_queue& cc , tracker_manager& man , tracker_request const& req , address bind_infc , boost::weak_ptr<request_callback> c , session_settings const& stn , proxy_settings const& ps , std::string const& password = ""); void close(); private: boost::intrusive_ptr<http_tracker_connection> self() { return boost::intrusive_ptr<http_tracker_connection>(this); } void on_response(asio::error_code const& ec, http_parser const& parser , char const* data, int size); virtual void on_timeout() {} void parse(int status_code, const entry& e); bool extract_peer_info(const entry& e, peer_entry& ret); tracker_manager& m_man; boost::shared_ptr<http_connection> m_tracker_connection; }; } #endif // TORRENT_HTTP_TRACKER_CONNECTION_HPP_INCLUDED <commit_msg>silence msvc warning<commit_after>/* Copyright (c) 2003, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TORRENT_HTTP_TRACKER_CONNECTION_HPP_INCLUDED #define TORRENT_HTTP_TRACKER_CONNECTION_HPP_INCLUDED #include <string> #ifdef _MSC_VER #pragma warning(push, 1) #endif #include <boost/shared_ptr.hpp> #ifdef _MSC_VER #pragma warning(pop) #endif #include "libtorrent/peer_id.hpp" #include "libtorrent/tracker_manager.hpp" #include "libtorrent/config.hpp" namespace libtorrent { struct http_connection; class entry; class http_parser; class connection_queue; class session_settings; class TORRENT_EXPORT http_tracker_connection : public tracker_connection { friend class tracker_manager; public: http_tracker_connection( io_service& ios , connection_queue& cc , tracker_manager& man , tracker_request const& req , address bind_infc , boost::weak_ptr<request_callback> c , session_settings const& stn , proxy_settings const& ps , std::string const& password = ""); void close(); private: boost::intrusive_ptr<http_tracker_connection> self() { return boost::intrusive_ptr<http_tracker_connection>(this); } void on_response(asio::error_code const& ec, http_parser const& parser , char const* data, int size); virtual void on_timeout() {} void parse(int status_code, const entry& e); bool extract_peer_info(const entry& e, peer_entry& ret); tracker_manager& m_man; boost::shared_ptr<http_connection> m_tracker_connection; }; } #endif // TORRENT_HTTP_TRACKER_CONNECTION_HPP_INCLUDED <|endoftext|>
<commit_before>#pragma once #include "oqpi/platform.hpp" #include "oqpi/error_handling.hpp" #include "oqpi/synchronization/sync_common.hpp" namespace oqpi { //---------------------------------------------------------------------------------------------- // Forward declaration of this platform mutex implementation using mutex_impl = class win_mutex; //---------------------------------------------------------------------------------------------- class win_mutex { protected: //------------------------------------------------------------------------------------------ using native_handle_type = HANDLE; protected: //------------------------------------------------------------------------------------------ win_mutex(const std::string &name, sync_object_creation_options creationOption, bool lockOnCreation) : handle_(nullptr) { if (creationOption == sync_object_creation_options::open_existing) { oqpi_check(!name.empty()); handle_ = OpenMutexA(MUTEX_ALL_ACCESS, FALSE, name.c_str()); } else { handle_ = CreateMutexA(nullptr, lockOnCreation, name.empty() ? nullptr : name.c_str()); if ((handle_ != nullptr) && (creationOption == sync_object_creation_options::create_if_nonexistent) && (GetLastError() == ERROR_ALREADY_EXISTS)) { CloseHandle(handle_); handle_ = nullptr; } } } //------------------------------------------------------------------------------------------ ~win_mutex() { if (handle_) { CloseHandle(handle_); handle_ = nullptr; } } //------------------------------------------------------------------------------------------ win_mutex(win_mutex &&other) : handle_(other.handle_) { other.handle_ = nullptr; } //------------------------------------------------------------------------------------------ win_mutex& operator =(win_mutex &&rhs) { if (this != &rhs) { handle_ = rhs.handle_; rhs.handle_ = nullptr; } return (*this); } protected: //------------------------------------------------------------------------------------------ // User interface native_handle_type getNativeHandle() const { return handle_; } //------------------------------------------------------------------------------------------ bool isValid() const { return handle_ != nullptr; } //------------------------------------------------------------------------------------------ bool lock() { return internalWait(INFINITE, TRUE); } //------------------------------------------------------------------------------------------ bool tryLock() { return internalWait(0, TRUE); } //------------------------------------------------------------------------------------------ template<typename _Rep, typename _Period> bool tryLockFor(const std::chrono::duration<_Rep, _Period>& relTime) { const auto dwMilliseconds = DWORD(std::chrono::duration_cast<std::chrono::milliseconds>(relTime).count()); return internalWait(dwMilliseconds, TRUE); } //------------------------------------------------------------------------------------------ void unlock() { oqpi_verify(ReleaseMutex(handle_) != FALSE); } private: //------------------------------------------------------------------------------------------ bool internalWait(DWORD dwMilliseconds, BOOL bAlertable) { const auto result = WaitForSingleObjectEx(handle_, dwMilliseconds, bAlertable); if (oqpi_failed(result == WAIT_OBJECT_0 || result == WAIT_TIMEOUT)) { oqpi_error("WaitForSingleObjectEx failed with error code 0x%x", GetLastError()); } return (result == WAIT_OBJECT_0); } private: //------------------------------------------------------------------------------------------ // Not copyable win_mutex(const win_mutex &) = delete; win_mutex& operator =(const win_mutex &) = delete; private: //------------------------------------------------------------------------------------------ HANDLE handle_; }; } /*oqpi*/ <commit_msg>Do not assert if a wait on mutex fails<commit_after>#pragma once #include "oqpi/platform.hpp" #include "oqpi/error_handling.hpp" #include "oqpi/synchronization/sync_common.hpp" namespace oqpi { //---------------------------------------------------------------------------------------------- // Forward declaration of this platform mutex implementation using mutex_impl = class win_mutex; //---------------------------------------------------------------------------------------------- class win_mutex { protected: //------------------------------------------------------------------------------------------ using native_handle_type = HANDLE; protected: //------------------------------------------------------------------------------------------ win_mutex(const std::string &name, sync_object_creation_options creationOption, bool lockOnCreation) : handle_(nullptr) { if (creationOption == sync_object_creation_options::open_existing) { oqpi_check(!name.empty()); handle_ = OpenMutexA(MUTEX_ALL_ACCESS, FALSE, name.c_str()); } else { handle_ = CreateMutexA(nullptr, lockOnCreation, name.empty() ? nullptr : name.c_str()); if ((handle_ != nullptr) && (creationOption == sync_object_creation_options::create_if_nonexistent) && (GetLastError() == ERROR_ALREADY_EXISTS)) { CloseHandle(handle_); handle_ = nullptr; } } } //------------------------------------------------------------------------------------------ ~win_mutex() { if (handle_) { CloseHandle(handle_); handle_ = nullptr; } } //------------------------------------------------------------------------------------------ win_mutex(win_mutex &&other) : handle_(other.handle_) { other.handle_ = nullptr; } //------------------------------------------------------------------------------------------ win_mutex& operator =(win_mutex &&rhs) { if (this != &rhs) { handle_ = rhs.handle_; rhs.handle_ = nullptr; } return (*this); } protected: //------------------------------------------------------------------------------------------ // User interface native_handle_type getNativeHandle() const { return handle_; } //------------------------------------------------------------------------------------------ bool isValid() const { return handle_ != nullptr; } //------------------------------------------------------------------------------------------ bool lock() { return internalWait(INFINITE, TRUE); } //------------------------------------------------------------------------------------------ bool tryLock() { return internalWait(0, TRUE); } //------------------------------------------------------------------------------------------ template<typename _Rep, typename _Period> bool tryLockFor(const std::chrono::duration<_Rep, _Period>& relTime) { const auto dwMilliseconds = DWORD(std::chrono::duration_cast<std::chrono::milliseconds>(relTime).count()); return internalWait(dwMilliseconds, TRUE); } //------------------------------------------------------------------------------------------ void unlock() { oqpi_verify(ReleaseMutex(handle_) != FALSE); } private: //------------------------------------------------------------------------------------------ bool internalWait(DWORD dwMilliseconds, BOOL bAlertable) { const auto result = WaitForSingleObjectEx(handle_, dwMilliseconds, bAlertable); if (result == WAIT_FAILED) { oqpi_error("WaitForSingleObjectEx failed with error code 0x%x", GetLastError()); } return (result == WAIT_OBJECT_0); } private: //------------------------------------------------------------------------------------------ // Not copyable win_mutex(const win_mutex &) = delete; win_mutex& operator =(const win_mutex &) = delete; private: //------------------------------------------------------------------------------------------ HANDLE handle_; }; } /*oqpi*/ <|endoftext|>
<commit_before>#include "Expression.hpp" #ifdef Expression_defined Expression::Expression() { IsLeft = false; } NumberExpression::NumberExpression(int number) { Value = number; } double NumberExpression::Eval() { return Value; } BinaryExpression::BinaryExpression(BinaryOperator Op, std::unique_ptr<Expression>&& First, std::unique_ptr<Expression>&& Second) : First(move(First)), Second(move(Second)), Op(Op) { } double BinaryExpression::Eval() { auto lhs = First->Eval(); auto rhs = Second->Eval(); switch (Op) { case BinaryOperator::Plus: return lhs + rhs; case BinaryOperator::Minus: return lhs - rhs; case BinaryOperator::Multiply: return lhs * rhs; case BinaryOperator::Divide: return lhs / rhs; default: throw Exception(nullptr, nullptr); } } Exception::Exception(std::string aStart, const wchar_t* aError) { Start = aStart; Error = aError; } bool Is(std::stringstream& Stream, const char Text) { auto Read = Stream.tellg(); while (Stream.peek() == ' ')Stream.get(); if (Stream.peek() == Text) { Stream.get(); return true; } Stream.seekg(Read); return false; } std::unique_ptr<NumberExpression> GetNumber(std::stringstream& Stream) { auto Result = 0; auto GotNumber = false; while (Stream.peek() == ' ')Stream.get(); while (true) { auto c = Stream.peek(); if ('0' <= c && c <= '9') { Result = Result * 10 + (c - '0'); GotNumber = true; Stream.get(); } else { break; } } if (GotNumber) { return std::make_unique<NumberExpression>(Result); } throw Exception(Stream.str(), L"此处需要表达式"); } std::unique_ptr<Expression> GetTerm(std::stringstream& Stream) { try { return GetNumber(Stream); } catch (Exception) { if (Is(Stream, '(')) { auto Result = GetExp(Stream); if (Is(Stream, ')')) { return Result; } throw Exception(Stream.str(), L"此处需要右括号"); } throw; } } std::unique_ptr<Expression> GetFactor(std::stringstream& Stream) { auto Result = GetTerm(Stream); while (true) { BinaryOperator Operator; if (Is(Stream, '*')) { Operator = BinaryOperator::Multiply; } else if (Is(Stream, '/')) { Operator = BinaryOperator::Divide; } else { break; } Result = std::make_unique<BinaryExpression>(Operator, move(Result), GetTerm(Stream)); } return Result; } std::unique_ptr<Expression> GetExp(std::stringstream& Stream) { auto Result = GetFactor(Stream); while (true) { BinaryOperator Operator; if (Is(Stream, '+')) { Operator = BinaryOperator::Plus; } else if (Is(Stream, '-')) { Operator = BinaryOperator::Minus; } else { break; } Result = std::make_unique<BinaryExpression>(Operator, move(Result), GetFactor(Stream)); } return Result; } std::unique_ptr<Expression> GetExp(std::string Exp){ std::stringstream ss(Exp); return GetExp(ss); } #endif<commit_msg>FIX unused case<commit_after>#include "Expression.hpp" #ifdef Expression_defined Expression::Expression() { IsLeft = false; } NumberExpression::NumberExpression(int number) { Value = number; } double NumberExpression::Eval() { return Value; } BinaryExpression::BinaryExpression(BinaryOperator Op, std::unique_ptr<Expression>&& First, std::unique_ptr<Expression>&& Second) : First(move(First)), Second(move(Second)), Op(Op) { } double BinaryExpression::Eval() { auto lhs = First->Eval(); auto rhs = Second->Eval(); switch (Op) { case BinaryOperator::Plus: return lhs + rhs; case BinaryOperator::Minus: return lhs - rhs; case BinaryOperator::Multiply: return lhs * rhs; case BinaryOperator::Divide: return lhs / rhs; } } Exception::Exception(std::string aStart, const wchar_t* aError) { Start = aStart; Error = aError; } bool Is(std::stringstream& Stream, const char Text) { auto Read = Stream.tellg(); while (Stream.peek() == ' ')Stream.get(); if (Stream.peek() == Text) { Stream.get(); return true; } Stream.seekg(Read); return false; } std::unique_ptr<NumberExpression> GetNumber(std::stringstream& Stream) { auto Result = 0; auto GotNumber = false; while (Stream.peek() == ' ')Stream.get(); while (true) { auto c = Stream.peek(); if ('0' <= c && c <= '9') { Result = Result * 10 + (c - '0'); GotNumber = true; Stream.get(); } else { break; } } if (GotNumber) { return std::make_unique<NumberExpression>(Result); } throw Exception(Stream.str(), L"此处需要表达式"); } std::unique_ptr<Expression> GetTerm(std::stringstream& Stream) { try { return GetNumber(Stream); } catch (Exception) { if (Is(Stream, '(')) { auto Result = GetExp(Stream); if (Is(Stream, ')')) { return Result; } throw Exception(Stream.str(), L"此处需要右括号"); } throw; } } std::unique_ptr<Expression> GetFactor(std::stringstream& Stream) { auto Result = GetTerm(Stream); while (true) { BinaryOperator Operator; if (Is(Stream, '*')) { Operator = BinaryOperator::Multiply; } else if (Is(Stream, '/')) { Operator = BinaryOperator::Divide; } else { break; } Result = std::make_unique<BinaryExpression>(Operator, move(Result), GetTerm(Stream)); } return Result; } std::unique_ptr<Expression> GetExp(std::stringstream& Stream) { auto Result = GetFactor(Stream); while (true) { BinaryOperator Operator; if (Is(Stream, '+')) { Operator = BinaryOperator::Plus; } else if (Is(Stream, '-')) { Operator = BinaryOperator::Minus; } else { break; } Result = std::make_unique<BinaryExpression>(Operator, move(Result), GetFactor(Stream)); } return Result; } std::unique_ptr<Expression> GetExp(std::string Exp){ std::stringstream ss(Exp); return GetExp(ss); } #endif<|endoftext|>
<commit_before>/* * FileSystem.cpp * * Created on: Jun 20, 2014 * Author: Pimenta */ // this #include "FileSystem.hpp" using namespace std; using namespace helpers; FileSystem::Folder FileSystem::rootFolder; uint32_t FileSystem::localIP; int FileSystem::Folder::getTotalFiles() { int total = files.size(); for (auto& kv : subfolders) total += kv.second.getTotalFiles(); return total; } int FileSystem::Folder::getTotalSize() { int total = 0; for (auto& kv : files) total += kv.second.size; for (auto& kv : subfolders) total += kv.second.getTotalSize(); return total; } void FileSystem::init(uint32_t localIP) { rootFolder.subfolders.clear(); rootFolder.files.clear(); system("rm www/files/*"); FileSystem::localIP = localIP; } bool FileSystem::parseName(const string& name) { static set<char> allowedChars; static StaticInitializer staticInitializar([&]() { for (char c = '0'; c <= '9'; c++) allowedChars.insert(c); for (char c = 'a'; c <= 'z'; c++) allowedChars.insert(c); for (char c = 'A'; c <= 'Z'; c++) allowedChars.insert(c); allowedChars.insert('_'); allowedChars.insert('-'); allowedChars.insert('+'); allowedChars.insert('.'); }); if (!name.size()) // if the name is empty return false; for (int i = 0; i < int(name.size()); i++) { // check if all chars are allowed if (allowedChars.find(name[i]) != allowedChars.end()) return false; } return true; } bool FileSystem::parsePath(const string& path) { if (!path.size()) // if the path is empty return false; list<string> atoms = explode(path, '/'); if (!atoms.size()) // if no atom was found return false; auto it = atoms.begin(); if (!parseName(*it)) // if the first name is invalid return false; string tmp = *it; it++; for (int i = 1; i < int(atoms.size()); i++) { // if there's an invalid name if (!parseName(*it)) return false; tmp += '/'; tmp += (*it); it++; } return tmp == path; // if the reassembled path is equals to the parsed } bool FileSystem::createFolder(const string& fullPath) { if (!parsePath(fullPath)) // if the path is invalid return false; if (folders.find(fullPath) != folders.end()) // if the folder already exists return false; pair<string, string> divided = divide(fullPath, '/'); auto motherFolder = folders.find(divided.first); if (motherFolder == folders.end()) // if the mother folder doesn't exist return false; motherFolder->second.subfolders.insert(divided.second); folders[fullPath]; return true; } FileSystem::Folder* FileSystem::retrieveFolder(const string& fullPath) { auto folder = folders.find(fullPath); if (folder == folders.end()) return nullptr; return &folder->second; } bool FileSystem::updateFolder(const string& fullPath, const string& newName) { if (fullPath == "root") // if the full path is the root folder return false; if (!parseName(newName)) // if the new name is invalid return false; pair<string, string> fullDivided = divide(fullPath, '/'); if (fullDivided.second == newName) // if the new name is the current name return false; auto folder = folders.find(fullPath); if (folder == folders.end()) // if the folder doesn't exist return false; // create a new folder string newPath = (fullDivided.first + "/") + newName; auto& newFolder = folders[newPath]; newFolder.subfolders = folder->second.subfolders; newFolder.files = folder->second.files; // erase old folder folders.erase(folder); for (auto& subfolder : newFolder.subfolders) updateFolder((fullPath + "/") // rename files stored in this peer //TODO return true; } bool FileSystem::deleteFolder(const string& fullPath) { //TODO return false; } FileSystem::File* FileSystem::retrieveFile(const string& fullPath) { return nullptr;//TODO } int FileSystem::getTotalFiles() { return rootFolder.getTotalFiles(); } int FileSystem::getTotalSize() { return rootFolder.getTotalSize(); } ByteQueue FileSystem::readFile(FILE* fp) { fseek(fp, 0, SEEK_END); size_t size = ftell(fp); fseek(fp, 0, SEEK_SET); ByteQueue data(size); fread(data.ptr(), size, 1, fp); return data; } <commit_msg>Changing variable name<commit_after>/* * FileSystem.cpp * * Created on: Jun 20, 2014 * Author: Pimenta */ // this #include "FileSystem.hpp" using namespace std; using namespace helpers; FileSystem::Folder FileSystem::rootFolder; uint32_t FileSystem::localIP; int FileSystem::Folder::getTotalFiles() { int total = files.size(); for (auto& kv : subfolders) total += kv.second.getTotalFiles(); return total; } int FileSystem::Folder::getTotalSize() { int total = 0; for (auto& kv : files) total += kv.second.size; for (auto& kv : subfolders) total += kv.second.getTotalSize(); return total; } void FileSystem::init(uint32_t localIP) { rootFolder.subfolders.clear(); rootFolder.files.clear(); system("rm www/files/*"); FileSystem::localIP = localIP; } bool FileSystem::parseName(const string& name) { static set<char> allowedChars; static StaticInitializer staticInitializar([&]() { for (char c = '0'; c <= '9'; c++) allowedChars.insert(c); for (char c = 'a'; c <= 'z'; c++) allowedChars.insert(c); for (char c = 'A'; c <= 'Z'; c++) allowedChars.insert(c); allowedChars.insert('_'); allowedChars.insert('-'); allowedChars.insert('+'); allowedChars.insert('.'); }); if (!name.size()) // if the name is empty return false; for (int i = 0; i < int(name.size()); i++) { // check if all chars are allowed if (allowedChars.find(name[i]) != allowedChars.end()) return false; } return true; } bool FileSystem::parsePath(const string& path) { if (!path.size()) // if the path is empty return false; list<string> atoms = explode(path, '/'); if (!atoms.size()) // if no atom was found return false; auto it = atoms.begin(); if (!parseName(*it)) // if the first name is invalid return false; string reassembledPath = *it; it++; for (int i = 1; i < int(atoms.size()); i++) { // if there's an invalid name if (!parseName(*it)) return false; reassembledPath += '/'; reassembledPath += (*it); it++; } return reassembledPath == path; } bool FileSystem::createFolder(const string& fullPath) { if (!parsePath(fullPath)) // if the path is invalid return false; if (folders.find(fullPath) != folders.end()) // if the folder already exists return false; pair<string, string> divided = divide(fullPath, '/'); auto motherFolder = folders.find(divided.first); if (motherFolder == folders.end()) // if the mother folder doesn't exist return false; motherFolder->second.subfolders.insert(divided.second); folders[fullPath]; return true; } FileSystem::Folder* FileSystem::retrieveFolder(const string& fullPath) { auto folder = folders.find(fullPath); if (folder == folders.end()) return nullptr; return &folder->second; } bool FileSystem::updateFolder(const string& fullPath, const string& newName) { if (fullPath == "root") // if the full path is the root folder return false; if (!parseName(newName)) // if the new name is invalid return false; pair<string, string> fullDivided = divide(fullPath, '/'); if (fullDivided.second == newName) // if the new name is the current name return false; auto folder = folders.find(fullPath); if (folder == folders.end()) // if the folder doesn't exist return false; // create a new folder string newPath = (fullDivided.first + "/") + newName; auto& newFolder = folders[newPath]; newFolder.subfolders = folder->second.subfolders; newFolder.files = folder->second.files; // erase old folder folders.erase(folder); for (auto& subfolder : newFolder.subfolders) updateFolder((fullPath + "/") // rename files stored in this peer //TODO return true; } bool FileSystem::deleteFolder(const string& fullPath) { //TODO return false; } FileSystem::File* FileSystem::retrieveFile(const string& fullPath) { return nullptr;//TODO } int FileSystem::getTotalFiles() { return rootFolder.getTotalFiles(); } int FileSystem::getTotalSize() { return rootFolder.getTotalSize(); } ByteQueue FileSystem::readFile(FILE* fp) { fseek(fp, 0, SEEK_END); size_t size = ftell(fp); fseek(fp, 0, SEEK_SET); ByteQueue data(size); fread(data.ptr(), size, 1, fp); return data; } <|endoftext|>
<commit_before>/* * Copyright 2016-2017 Kacper Kasper <kacperkasper@gmail.com> * All rights reserved. Distributed under the terms of the MIT license. */ #include "FindWindow.h" #include <ScintillaView.h> #include <Application.h> #include <Box.h> #include <Button.h> #include <Catalog.h> #include <CheckBox.h> #include <LayoutBuilder.h> #include <Message.h> #include <RadioButton.h> #include <StringView.h> #undef B_TRANSLATION_CONTEXT #define B_TRANSLATION_CONTEXT "FindWindow" FindWindow::FindWindow() : BWindow(BRect(0, 0, 400, 300), B_TRANSLATE("Find/Replace"), B_TITLED_WINDOW, B_NOT_ZOOMABLE | B_NOT_RESIZABLE | B_AUTO_UPDATE_SIZE_LIMITS, 0), fFlagsChanged(false) { _InitInterface(); CenterOnScreen(); } FindWindow::~FindWindow() { } void FindWindow::MessageReceived(BMessage* message) { switch(message->what) { case FINDWINDOW_FIND: case FINDWINDOW_REPLACE: case FINDWINDOW_REPLACEFIND: case FINDWINDOW_REPLACEALL: { int32 findLength = fFindTC->TextLength() + 1; int32 replaceLength = fReplaceTC->TextLength() + 1; std::string findText(findLength + 1, '\0'); std::string replaceText(replaceLength + 1, '\0'); fFindTC->GetText(0, findLength, &findText[0]); fReplaceTC->GetText(0, replaceLength, &replaceText[0]); bool newSearch = (fFlagsChanged || fOldFindText != findText || fOldReplaceText != replaceText); message->AddBool("newSearch", newSearch); message->AddBool("inSelection", (fInSelectionCB->Value() == B_CONTROL_ON ? true : false)); message->AddBool("matchCase", (fMatchCaseCB->Value() == B_CONTROL_ON ? true : false)); message->AddBool("matchWord", (fMatchWordCB->Value() == B_CONTROL_ON ? true : false)); message->AddBool("wrapAround", (fWrapAroundCB->Value() == B_CONTROL_ON ? true : false)); message->AddBool("regex", (fRegexCB->Value() == B_CONTROL_ON ? true : false)); message->AddBool("backwards", (fDirectionUpRadio->Value() == B_CONTROL_ON ? true : false)); message->AddString("findText", findText.c_str()); message->AddString("replaceText", replaceText.c_str()); be_app->PostMessage(message); fOldFindText = findText; fOldReplaceText = replaceText; if(message->what == FINDWINDOW_REPLACEALL) { fFlagsChanged = true; // Force scope retargeting on next search } else { fFlagsChanged = false; } } break; case Actions::MATCH_CASE: case Actions::MATCH_WORD: case Actions::WRAP_AROUND: case Actions::DIRECTION_UP: case Actions::DIRECTION_DOWN: case Actions::IN_SELECTION: { fFlagsChanged = true; } break; default: { BWindow::MessageReceived(message); } break; } } void FindWindow::WindowActivated(bool active) { fFindTC->MakeFocus(); fFindTC->SendMessage(SCI_SELECTALL); } void FindWindow::Quit() { be_app->PostMessage(FINDWINDOW_QUITTING); BWindow::Quit(); } void FindWindow::SetFindText(const std::string text) { fFindTC->SetText(text.c_str()); } void FindWindow::_InitInterface() { fFindString = new BStringView("findString", B_TRANSLATE("Find:")); fReplaceString = new BStringView("replaceString", B_TRANSLATE("Replace:")); fFindTC = new BScintillaView("findText", 0, true, true); fFindTC->SetExplicitMinSize(BSize(200, 100)); fReplaceTC = new BScintillaView("replaceText", 0, true, true); fReplaceTC->SetExplicitMinSize(BSize(200, 100)); fFindButton = new BButton(B_TRANSLATE("Find"), new BMessage((uint32) FINDWINDOW_FIND)); fFindButton->MakeDefault(true); fFindButton->SetExplicitMaxSize(BSize(B_SIZE_UNLIMITED, B_SIZE_UNSET)); fReplaceButton = new BButton(B_TRANSLATE("Replace"), new BMessage((uint32) FINDWINDOW_REPLACE)); fReplaceButton->SetExplicitMaxSize(BSize(B_SIZE_UNLIMITED, B_SIZE_UNSET)); fReplaceFindButton = new BButton(B_TRANSLATE("Replace and find"), new BMessage((uint32) FINDWINDOW_REPLACEFIND)); fReplaceFindButton->SetExplicitMaxSize(BSize(B_SIZE_UNLIMITED, B_SIZE_UNSET)); fReplaceAllButton = new BButton(B_TRANSLATE("Replace all"), new BMessage((uint32) FINDWINDOW_REPLACEALL)); fReplaceAllButton->SetExplicitMaxSize(BSize(B_SIZE_UNLIMITED, B_SIZE_UNSET)); fMatchCaseCB = new BCheckBox("matchCase", B_TRANSLATE("Match case"), new BMessage((uint32) Actions::MATCH_CASE)); fMatchWordCB = new BCheckBox("matchWord", B_TRANSLATE("Match entire words"), new BMessage((uint32) Actions::MATCH_WORD)); fWrapAroundCB = new BCheckBox("wrapAround", B_TRANSLATE("Wrap around"), new BMessage((uint32) Actions::WRAP_AROUND)); fInSelectionCB = new BCheckBox("inSelection", B_TRANSLATE("In selection"), new BMessage((uint32) Actions::IN_SELECTION)); fRegexCB = new BCheckBox("regex", B_TRANSLATE("Regex"), new BMessage((uint32) Actions::REGEX)); fDirectionBox = new BBox("direction"); fDirectionUpRadio = new BRadioButton("directionUp", B_TRANSLATE("Up"), new BMessage((uint32) Actions::DIRECTION_UP)); fDirectionDownRadio = new BRadioButton("directionDown", B_TRANSLATE("Down"), new BMessage((uint32) Actions::DIRECTION_DOWN)); fDirectionDownRadio->SetValue(B_CONTROL_ON); BLayoutBuilder::Group<>(fDirectionBox, B_VERTICAL, 5) .Add(fDirectionUpRadio) .Add(fDirectionDownRadio) .SetInsets(10, 25, 15, 10); fDirectionBox->SetLabel(B_TRANSLATE("Direction")); BLayoutBuilder::Group<>(this, B_HORIZONTAL, 5) .AddGroup(B_VERTICAL, 5) .AddGrid(1, 1) .Add(fFindString, 0, 0) .Add(fFindTC, 1, 0) .Add(fReplaceString, 0, 1) .Add(fReplaceTC, 1, 1) .End() .AddGrid(1, 1) .Add(fMatchCaseCB, 0, 0) .Add(fWrapAroundCB, 1, 0) .Add(fMatchWordCB, 0, 1) .Add(fInSelectionCB, 1, 1) .Add(fDirectionBox, 0, 2) .Add(fRegexCB, 1, 2) .End() .End() .AddGroup(B_VERTICAL, 5) .Add(fFindButton) .Add(fReplaceButton) .Add(fReplaceFindButton) .Add(fReplaceAllButton) .AddGlue() .End() .SetInsets(5, 5, 5, 5); } <commit_msg>Fix keyboard navigation in Find/Replace.<commit_after>/* * Copyright 2016-2017 Kacper Kasper <kacperkasper@gmail.com> * All rights reserved. Distributed under the terms of the MIT license. */ #include "FindWindow.h" #include <ScintillaView.h> #include <Application.h> #include <Box.h> #include <Button.h> #include <Catalog.h> #include <CheckBox.h> #include <LayoutBuilder.h> #include <Message.h> #include <RadioButton.h> #include <StringView.h> #undef B_TRANSLATION_CONTEXT #define B_TRANSLATION_CONTEXT "FindWindow" FindWindow::FindWindow() : BWindow(BRect(0, 0, 400, 300), B_TRANSLATE("Find/Replace"), B_TITLED_WINDOW, B_NOT_ZOOMABLE | B_NOT_RESIZABLE | B_AUTO_UPDATE_SIZE_LIMITS, 0), fFlagsChanged(false) { _InitInterface(); CenterOnScreen(); } FindWindow::~FindWindow() { } void FindWindow::MessageReceived(BMessage* message) { switch(message->what) { case FINDWINDOW_FIND: case FINDWINDOW_REPLACE: case FINDWINDOW_REPLACEFIND: case FINDWINDOW_REPLACEALL: { int32 findLength = fFindTC->TextLength() + 1; int32 replaceLength = fReplaceTC->TextLength() + 1; std::string findText(findLength + 1, '\0'); std::string replaceText(replaceLength + 1, '\0'); fFindTC->GetText(0, findLength, &findText[0]); fReplaceTC->GetText(0, replaceLength, &replaceText[0]); bool newSearch = (fFlagsChanged || fOldFindText != findText || fOldReplaceText != replaceText); message->AddBool("newSearch", newSearch); message->AddBool("inSelection", (fInSelectionCB->Value() == B_CONTROL_ON ? true : false)); message->AddBool("matchCase", (fMatchCaseCB->Value() == B_CONTROL_ON ? true : false)); message->AddBool("matchWord", (fMatchWordCB->Value() == B_CONTROL_ON ? true : false)); message->AddBool("wrapAround", (fWrapAroundCB->Value() == B_CONTROL_ON ? true : false)); message->AddBool("regex", (fRegexCB->Value() == B_CONTROL_ON ? true : false)); message->AddBool("backwards", (fDirectionUpRadio->Value() == B_CONTROL_ON ? true : false)); message->AddString("findText", findText.c_str()); message->AddString("replaceText", replaceText.c_str()); be_app->PostMessage(message); fOldFindText = findText; fOldReplaceText = replaceText; if(message->what == FINDWINDOW_REPLACEALL) { fFlagsChanged = true; // Force scope retargeting on next search } else { fFlagsChanged = false; } } break; case Actions::MATCH_CASE: case Actions::MATCH_WORD: case Actions::WRAP_AROUND: case Actions::DIRECTION_UP: case Actions::DIRECTION_DOWN: case Actions::IN_SELECTION: { fFlagsChanged = true; } break; default: { BWindow::MessageReceived(message); } break; } } void FindWindow::WindowActivated(bool active) { fFindTC->MakeFocus(); fFindTC->SendMessage(SCI_SELECTALL); } void FindWindow::Quit() { be_app->PostMessage(FINDWINDOW_QUITTING); BWindow::Quit(); } void FindWindow::SetFindText(const std::string text) { fFindTC->SetText(text.c_str()); } void FindWindow::_InitInterface() { fFindString = new BStringView("findString", B_TRANSLATE("Find:")); fReplaceString = new BStringView("replaceString", B_TRANSLATE("Replace:")); fFindTC = new BScintillaView("findText", 0, true, true); fFindTC->SetExplicitMinSize(BSize(200, 100)); fFindTC->Target()->SetFlags(fFindTC->Target()->Flags() | B_NAVIGABLE); fReplaceTC = new BScintillaView("replaceText", 0, true, true); fReplaceTC->SetExplicitMinSize(BSize(200, 100)); fReplaceTC->Target()->SetFlags(fReplaceTC->Target()->Flags() | B_NAVIGABLE); fFindButton = new BButton(B_TRANSLATE("Find"), new BMessage((uint32) FINDWINDOW_FIND)); fFindButton->MakeDefault(true); fFindButton->SetExplicitMaxSize(BSize(B_SIZE_UNLIMITED, B_SIZE_UNSET)); fReplaceButton = new BButton(B_TRANSLATE("Replace"), new BMessage((uint32) FINDWINDOW_REPLACE)); fReplaceButton->SetExplicitMaxSize(BSize(B_SIZE_UNLIMITED, B_SIZE_UNSET)); fReplaceFindButton = new BButton(B_TRANSLATE("Replace and find"), new BMessage((uint32) FINDWINDOW_REPLACEFIND)); fReplaceFindButton->SetExplicitMaxSize(BSize(B_SIZE_UNLIMITED, B_SIZE_UNSET)); fReplaceAllButton = new BButton(B_TRANSLATE("Replace all"), new BMessage((uint32) FINDWINDOW_REPLACEALL)); fReplaceAllButton->SetExplicitMaxSize(BSize(B_SIZE_UNLIMITED, B_SIZE_UNSET)); fMatchCaseCB = new BCheckBox("matchCase", B_TRANSLATE("Match case"), new BMessage((uint32) Actions::MATCH_CASE)); fMatchWordCB = new BCheckBox("matchWord", B_TRANSLATE("Match entire words"), new BMessage((uint32) Actions::MATCH_WORD)); fWrapAroundCB = new BCheckBox("wrapAround", B_TRANSLATE("Wrap around"), new BMessage((uint32) Actions::WRAP_AROUND)); fInSelectionCB = new BCheckBox("inSelection", B_TRANSLATE("In selection"), new BMessage((uint32) Actions::IN_SELECTION)); fRegexCB = new BCheckBox("regex", B_TRANSLATE("Regex"), new BMessage((uint32) Actions::REGEX)); fDirectionBox = new BBox("direction"); fDirectionUpRadio = new BRadioButton("directionUp", B_TRANSLATE("Up"), new BMessage((uint32) Actions::DIRECTION_UP)); fDirectionDownRadio = new BRadioButton("directionDown", B_TRANSLATE("Down"), new BMessage((uint32) Actions::DIRECTION_DOWN)); fDirectionDownRadio->SetValue(B_CONTROL_ON); BLayoutBuilder::Group<>(fDirectionBox, B_VERTICAL, 5) .Add(fDirectionUpRadio) .Add(fDirectionDownRadio) .SetInsets(10, 25, 15, 10); fDirectionBox->SetLabel(B_TRANSLATE("Direction")); BLayoutBuilder::Group<>(this, B_HORIZONTAL, 5) .AddGroup(B_VERTICAL, 5) .AddGrid(1, 1) .Add(fFindString, 0, 0) .Add(fFindTC, 1, 0) .Add(fReplaceString, 0, 1) .Add(fReplaceTC, 1, 1) .End() .AddGrid(1, 1) .Add(fMatchCaseCB, 0, 0) .Add(fWrapAroundCB, 1, 0) .Add(fMatchWordCB, 0, 1) .Add(fInSelectionCB, 1, 1) .Add(fDirectionBox, 0, 2) .Add(fRegexCB, 1, 2) .End() .End() .AddGroup(B_VERTICAL, 5) .Add(fFindButton) .Add(fReplaceButton) .Add(fReplaceFindButton) .Add(fReplaceAllButton) .AddGlue() .End() .SetInsets(5, 5, 5, 5); } <|endoftext|>
<commit_before>// // Created by Domagoj Boros on 18/12/2016. // #include "OverlapUtils.h" #include <vector> #include <algorithm> #include <map> #include "GraphUtils.h" #include <limits.h> static void popBubble(Graph &g, Vertex &v) { } static void isUnitigEnd(GraphEdgeType &graphEdgeType, Vertex &vertexOut, const Graph &graph, const Vertex &vertexIn) { const std::vector<Edge> &edges(graph.at(std::make_pair(vertexIn.first, !vertexIn.second))); size_t undeletedSize(0); size_t i(0); size_t undeletedEdgeIdx(0); for (const auto &edge : edges) { if (!edge.del) { ++undeletedSize; undeletedEdgeIdx = i; } ++i; } if (undeletedSize == 0) { graphEdgeType = GraphEdgeType::GRAPH_EDGE_TYPE_TIP; return; } if (undeletedSize > 1) { graphEdgeType = GraphEdgeType::GRAPH_EDGE_TYPE_MULTI_OUT; return; } vertexOut = std::make_pair(edges[undeletedEdgeIdx].bId, edges[undeletedEdgeIdx].bIsReversed); Vertex vertexOutNeg = std::make_pair(vertexOut.first, !vertexOut.second); undeletedSize = 0; for (const auto &edge : graph.at(vertexOutNeg)) { if (!edge.del) { ++undeletedSize; } } graphEdgeType = undeletedSize != 1 ? GRAPH_EDGE_TYPE_MULTI_NEI : GRAPH_EDGE_TYPE_MERGEABLE; } static void extend(std::vector<read_id_t> &readIds, GraphEdgeType &graphEdgeType, const Graph &g, const Vertex &v, const Params &params) { size_t tipExtension(params.maximalTipExtension); Vertex vertex = v; readIds.push_back(vertex.first); while (true) { isUnitigEnd(graphEdgeType, vertex, g, std::make_pair(vertex.first, !vertex.second)); // printf("%d\n",graphEdgeType); if (graphEdgeType != GraphEdgeType::GRAPH_EDGE_TYPE_MERGEABLE) break; readIds.push_back(vertex.first); if (--tipExtension == 0) break; } } void generateGraph(Graph &g, const Overlaps &overlaps, const ReadTrims &readTrims, Params &params) { int edgeCnt = 0; for (const auto &o : overlaps) { OverlapClassification c; Edge e; classifyOverlapAndMeasureItsLength(c, e, o, readTrims.at(o.aId()).length(), readTrims.at(o.bId()).length(), params.maximalOverhangLength, params.mappingLengthRatio, params.minimalOverlap); if (c == OVERLAP_A_TO_B || c == OVERLAP_B_TO_A) { g[std::make_pair(e.aId, e.aIsReversed)].push_back(e); edgeCnt++; } } for (auto &p : g) { std::sort(p.second.begin(), p.second.end(), [](const Edge &a, const Edge &b) { return (a.overlapLength < b.overlapLength); }); } std::cout << "Generated " << edgeCnt << " edges" << std::endl; } void filterTransitiveEdges(Graph &g, read_size_t FUZZ) { #define VACANT 0 #define INPLAY 1 #define ELIMINATED 2 std::map<std::pair<read_id_t, bool>, char> mark; for (const auto &p : g) { mark[p.first] = VACANT; for (const Edge &vw : p.second) mark[std::make_pair(vw.bId, vw.bIsReversed)] = VACANT; } int reduceCnt = 0; for (auto &p : g) { for (const auto &vw : p.second) mark[std::make_pair(vw.bId, vw.bIsReversed)] = INPLAY; if(p.second.size() == 0) continue; read_size_t longest = p.second[p.second.size() - 1].overlapLength + FUZZ; for (const auto &vw : p.second) { std::pair<read_id_t, bool> w(vw.bId, vw.bIsReversed); if (mark[w] == INPLAY) { for (const auto &wx : g[w]) { if (wx.overlapLength + vw.overlapLength > longest) break; std::pair<read_id_t, bool> x(wx.bId, wx.bIsReversed); if (mark[x] == INPLAY) mark[x] = ELIMINATED; } } } // for (const auto& vw : p.second) { // read_id_t w = vw.bId; // int i = 0; // for (const auto& wx : g[w]) { // if (wx.overlapLength >= FUZZ && i != 0) break; // read_id_t x = wx.bId; // if (mark[x] == INPLAY) mark[x] = ELIMINATED; // i++; // } // } for (auto &vw : p.second) { std::pair<read_id_t, bool> w (vw.bId, vw.bIsReversed); if (mark[w] == ELIMINATED) { vw.del = 1; reduceCnt++; } mark[w] = VACANT; } } cleanGraph(g); std::cout << "Reduced " << reduceCnt << " edges" << std::endl; #undef VACANT #undef INPLAY #undef ELIMINATED } void logGraph(const Graph &g) { for (const auto &pair : g) { auto u(pair.first); std::cout << u.first << " !"[u.second] << std::endl; const auto &edges(pair.second); for (auto const &edge: edges) { std::cout << "\t" << edge.aId << " !"[edge.aIsReversed] << " --" << edge.overlapLength << "--> " << edge.bId << " !"[edge.bIsReversed] << " " << " D"[edge.del] << std::endl; } } } void removeAsymetricEdges(Graph &g) { size_t cnt(0); for (auto& p : g) { for (auto& e : p.second) { bool found = false; for (auto& e2 : g[std::make_pair(e.bId, !e.bIsReversed)]) { if (e2.bId == p.first.first && e2.bIsReversed != p.first.second) { found = true; break; } } if (!found) { e.del = true; ++cnt; } } } cleanGraph(g); std::cout << "Removing " << cnt << " asymetric edges" << std::endl; } void cleanGraph(Graph &g) { for (auto & p : g) { std::vector<Edge> newEdges; for (auto& e : p.second) { if (!e.del) newEdges.push_back(e); } p.second.swap(newEdges); newEdges.clear(); } } void cutTips(Graph &g, ReadTrims &readTrims, const Params &params) { size_t cnt(0); // auto p(std::make_pair(std::make_pair(198,false),g[std::make_pair(198,false)])); for (auto &p : g) { // std::cout<<p.first.first<<" !"[p.first.second]<<std::endl; Vertex vertexOut; GraphEdgeType graphEdgeType; isUnitigEnd(graphEdgeType, vertexOut, g, p.first); if(readTrims[p.first.first].del) continue; // printf("Not deleted\n"); if (graphEdgeType != GRAPH_EDGE_TYPE_TIP) continue; // not a tip // printf("Is tip\n"); std::vector<read_id_t> readIds; extend(readIds, graphEdgeType, g, p.first, params); if (graphEdgeType == GRAPH_EDGE_TYPE_MERGEABLE) continue; // printf("Not unitig\n"); // if (readIds.size() == 0) continue; ++cnt; for (read_id_t readId: readIds) { readTrims[readId].del = true; // delete all outgoing edges from u and u' and all reverse edges (if u->v is deleted delete v'->u') for (int i = 0; i < 2; ++i) { for (auto &edge: g[std::make_pair(readId, static_cast<bool>(i))]) { edge.del = true; for (auto &edge2: g[std::make_pair(edge.bId, !edge.bIsReversed)]) { if(edge2.bId == readId && edge2.bIsReversed != edge.aIsReversed){ edge2.del = true; } } } } } } cleanGraph(g); std::cout << "Cutting " << cnt << " tips" << std::endl; } int countIncoming(Graph& g, Vertex& v) { int cnt = 0; for (const auto& e : g[std::make_pair(v.first, !v.second)]) if (!e.del) cnt++; return cnt; } void popBubbles(Graph& g , ReadTrims &readTrims) { #define D 50000 std::vector<Vertex> S; std::map<Vertex, int> distances; std::map<Vertex, int> unvisitedIncoming; std::vector<Vertex> visitedV; std::map<Vertex, Vertex> optPath; for (auto& p : g) { if (p.second.size() < 2 || readTrims[p.first.first].del) continue; int nonDeleted = 0; // distances.clear(); unvisitedIncoming.clear(); S.clear(); visitedV.clear(); optPath.clear(); const Vertex& read0 = p.first; for (auto& p2 : g) distances[p2.first] = INT_MAX; distances[read0] = 0; S.push_back(read0); int pv = 0; while (S.size() > 0) { Vertex& read = S.back(); S.pop_back(); for (auto& edge: g[read]) { if(edge.bId == read0.first) break; // jel se moze napisat ovak il se mora cijeli vertex usporedit if (edge.del) continue; edge.visited = true; Vertex b = std::make_pair(edge.bId, edge.bIsReversed); if(distances[read] + edge.overlapLength > D) break; if(distances[b] == INT_MAX) { // not visited unvisitedIncoming[b] = countIncoming(g, b); ++pv; visitedV.push_back(b); optPath[b] = read; } else { // visited } if(distances[read] + edge.overlapLength < distances[b]) { distances[b] = distances[read] + edge.overlapLength; optPath[b] = read; } --unvisitedIncoming[b]; if(unvisitedIncoming[b] == 0) { if(g[b].size() != 0) S.push_back(b); --pv; } } if (S.size() == 1 && pv == 0) { std::cout << "Found bubble " << read0.first << " !"[read0.second] << " -> " << S.back().first << " !"[S.back().second] << std::endl; // delete visited vertex and edges for (auto& vv : visitedV) { // std::cout << "Visiting " << vv.first << " !"[vv.second] << std::endl; readTrims[vv.first].del = true; } for (auto& p2 : g) { for (auto &edge: p2.second) { if (edge.visited) { // std::cout << "Deleting : " << std::endl << edge.aId << " !"[edge.aIsReversed] << " -> " << edge.bId << " !"[edge.bIsReversed] << std::endl; edge.del = true; for (auto &edge2: g[std::make_pair(edge.bId, !edge.bIsReversed)]) { if (edge2.bId == edge.aId && edge2.bIsReversed != edge.aIsReversed) { // std::cout << edge2.aId << " !"[edge2.aIsReversed] << " -> " << edge2.bId << " !"[edge2.bIsReversed] << std::endl; edge2.del = true; } } } } } Vertex& v = S.back(); // std::cout << "Visiting " << v.first << " !"[v.second] << std::endl; while (v != read0) { Vertex& u = optPath[v]; // u -> v // std::cout << "Visiting " << u.first << " !"[u.second] << std::endl; readTrims[v.first].del = false; for (auto& edge: g[u]) if (edge.bId == v.first && edge.bIsReversed == v.second) edge.del = false; for (auto& edge: g[std::make_pair(v.first, !v.second)]) if (edge.bId == u.first && edge.bIsReversed == !u.second) edge.del = false; v = u; } break; } } for (auto& p2 : g) for (auto& e : p2.second) e.visited = false; } cleanGraph(g); #undef D } <commit_msg>Good fix<commit_after>// // Created by Domagoj Boros on 18/12/2016. // #include "OverlapUtils.h" #include <vector> #include <algorithm> #include <map> #include "GraphUtils.h" #include <limits.h> static void popBubble(Graph &g, Vertex &v) { } static void isUnitigEnd(GraphEdgeType &graphEdgeType, Vertex &vertexOut, const Graph &graph, const Vertex &vertexIn) { const std::vector<Edge> &edges(graph.at(std::make_pair(vertexIn.first, !vertexIn.second))); size_t undeletedSize(0); size_t i(0); size_t undeletedEdgeIdx(0); for (const auto &edge : edges) { if (!edge.del) { ++undeletedSize; undeletedEdgeIdx = i; } ++i; } if (undeletedSize == 0) { graphEdgeType = GraphEdgeType::GRAPH_EDGE_TYPE_TIP; return; } if (undeletedSize > 1) { graphEdgeType = GraphEdgeType::GRAPH_EDGE_TYPE_MULTI_OUT; return; } vertexOut = std::make_pair(edges[undeletedEdgeIdx].bId, edges[undeletedEdgeIdx].bIsReversed); Vertex vertexOutNeg = std::make_pair(vertexOut.first, !vertexOut.second); undeletedSize = 0; for (const auto &edge : graph.at(vertexOutNeg)) { if (!edge.del) { ++undeletedSize; } } graphEdgeType = undeletedSize != 1 ? GRAPH_EDGE_TYPE_MULTI_NEI : GRAPH_EDGE_TYPE_MERGEABLE; } static void extend(std::vector<read_id_t> &readIds, GraphEdgeType &graphEdgeType, const Graph &g, const Vertex &v, const Params &params) { size_t tipExtension(params.maximalTipExtension); Vertex vertex = v; readIds.push_back(vertex.first); while (true) { isUnitigEnd(graphEdgeType, vertex, g, std::make_pair(vertex.first, !vertex.second)); // printf("%d\n",graphEdgeType); if (graphEdgeType != GraphEdgeType::GRAPH_EDGE_TYPE_MERGEABLE) break; readIds.push_back(vertex.first); if (--tipExtension == 0) break; } } void generateGraph(Graph &g, const Overlaps &overlaps, const ReadTrims &readTrims, Params &params) { int edgeCnt = 0; for (const auto &o : overlaps) { OverlapClassification c; Edge e; classifyOverlapAndMeasureItsLength(c, e, o, readTrims.at(o.aId()).length(), readTrims.at(o.bId()).length(), params.maximalOverhangLength, params.mappingLengthRatio, params.minimalOverlap); if (c == OVERLAP_A_TO_B || c == OVERLAP_B_TO_A) { g[std::make_pair(e.aId, e.aIsReversed)].push_back(e); edgeCnt++; } } for (auto &p : g) { std::sort(p.second.begin(), p.second.end(), [](const Edge &a, const Edge &b) { return (a.overlapLength < b.overlapLength); }); } std::cout << "Generated " << edgeCnt << " edges" << std::endl; } void filterTransitiveEdges(Graph &g, read_size_t FUZZ) { #define VACANT 0 #define INPLAY 1 #define ELIMINATED 2 std::map<std::pair<read_id_t, bool>, char> mark; for (const auto &p : g) { mark[p.first] = VACANT; for (const Edge &vw : p.second) mark[std::make_pair(vw.bId, vw.bIsReversed)] = VACANT; } int reduceCnt = 0; for (auto &p : g) { for (const auto &vw : p.second) mark[std::make_pair(vw.bId, vw.bIsReversed)] = INPLAY; if(p.second.size() == 0) continue; read_size_t longest = p.second[p.second.size() - 1].overlapLength + FUZZ; for (const auto &vw : p.second) { std::pair<read_id_t, bool> w(vw.bId, vw.bIsReversed); if (mark[w] == INPLAY) { for (const auto &wx : g[w]) { if (wx.overlapLength + vw.overlapLength > longest) break; std::pair<read_id_t, bool> x(wx.bId, wx.bIsReversed); if (mark[x] == INPLAY) mark[x] = ELIMINATED; } } } // for (const auto& vw : p.second) { // read_id_t w = vw.bId; // int i = 0; // for (const auto& wx : g[w]) { // if (wx.overlapLength >= FUZZ && i != 0) break; // read_id_t x = wx.bId; // if (mark[x] == INPLAY) mark[x] = ELIMINATED; // i++; // } // } for (auto &vw : p.second) { std::pair<read_id_t, bool> w (vw.bId, vw.bIsReversed); if (mark[w] == ELIMINATED) { vw.del = 1; reduceCnt++; } mark[w] = VACANT; } } cleanGraph(g); std::cout << "Reduced " << reduceCnt << " edges" << std::endl; #undef VACANT #undef INPLAY #undef ELIMINATED } void logGraph(const Graph &g) { for (const auto &pair : g) { auto u(pair.first); std::cout << u.first << " !"[u.second] << std::endl; const auto &edges(pair.second); for (auto const &edge: edges) { std::cout << "\t" << edge.aId << " !"[edge.aIsReversed] << " --" << edge.overlapLength << "--> " << edge.bId << " !"[edge.bIsReversed] << " " << " D"[edge.del] << std::endl; } } } void removeAsymetricEdges(Graph &g) { size_t cnt(0); for (auto& p : g) { for (auto& e : p.second) { bool found = false; for (auto& e2 : g[std::make_pair(e.bId, !e.bIsReversed)]) { if (e2.bId == p.first.first && e2.bIsReversed != p.first.second) { found = true; break; } } if (!found) { e.del = true; ++cnt; } } } cleanGraph(g); std::cout << "Removing " << cnt << " asymetric edges" << std::endl; } void cleanGraph(Graph &g) { for (auto & p : g) { std::vector<Edge> newEdges; for (auto& e : p.second) { if (!e.del) newEdges.push_back(e); } p.second.swap(newEdges); newEdges.clear(); } } void cutTips(Graph &g, ReadTrims &readTrims, const Params &params) { size_t cnt(0); // auto p(std::make_pair(std::make_pair(198,false),g[std::make_pair(198,false)])); for (auto &p : g) { // std::cout<<p.first.first<<" !"[p.first.second]<<std::endl; Vertex vertexOut; GraphEdgeType graphEdgeType; isUnitigEnd(graphEdgeType, vertexOut, g, p.first); if(readTrims[p.first.first].del) continue; // printf("Not deleted\n"); if (graphEdgeType != GRAPH_EDGE_TYPE_TIP) continue; // not a tip // printf("Is tip\n"); std::vector<read_id_t> readIds; extend(readIds, graphEdgeType, g, p.first, params); if (graphEdgeType == GRAPH_EDGE_TYPE_MERGEABLE) continue; // printf("Not unitig\n"); // if (readIds.size() == 0) continue; ++cnt; for (read_id_t readId: readIds) { readTrims[readId].del = true; // delete all outgoing edges from u and u' and all reverse edges (if u->v is deleted delete v'->u') for (int i = 0; i < 2; ++i) { for (auto &edge: g[std::make_pair(readId, static_cast<bool>(i))]) { edge.del = true; for (auto &edge2: g[std::make_pair(edge.bId, !edge.bIsReversed)]) { if(edge2.bId == readId && edge2.bIsReversed != edge.aIsReversed){ edge2.del = true; } } } } } } cleanGraph(g); std::cout << "Cutting " << cnt << " tips" << std::endl; } int countIncoming(Graph& g, Vertex& v) { int cnt = 0; for (const auto& e : g[std::make_pair(v.first, !v.second)]) if (!e.del) cnt++; return cnt; } void popBubbles(Graph& g , ReadTrims &readTrims) { #define D 50000 std::vector<Vertex> S; std::map<Vertex, int> distances; std::map<Vertex, int> unvisitedIncoming; std::vector<Vertex> visitedV; std::map<Vertex, Vertex> optPath; for (auto& p : g) { if (p.second.size() < 2 || readTrims[p.first.first].del) continue; int nonDeleted = 0; // distances.clear(); unvisitedIncoming.clear(); S.clear(); visitedV.clear(); optPath.clear(); const Vertex& read0 = p.first; for (auto& p2 : g) distances[p2.first] = INT_MAX; distances[read0] = 0; S.push_back(read0); int pv = 0; while (S.size() > 0) { Vertex& read = S.back(); S.pop_back(); for (auto& edge: g[read]) { if(edge.bId == read0.first) break; // jel se moze napisat ovak il se mora cijeli vertex usporedit if (edge.del) continue; edge.visited = true; Vertex b = std::make_pair(edge.bId, edge.bIsReversed); if(distances[read] + edge.overlapLength > D) break; if(distances[b] == INT_MAX) { // not visited unvisitedIncoming[b] = countIncoming(g, b); ++pv; visitedV.push_back(b); optPath[b] = read; } else { // visited } if(distances[read] + edge.overlapLength < distances[b]) { distances[b] = distances[read] + edge.overlapLength; optPath[b] = read; } --unvisitedIncoming[b]; if(unvisitedIncoming[b] == 0) { if(g[b].size() != 0) S.push_back(b); --pv; } } if (S.size() == 1 && pv == 0) { std::cout << "Found bubble " << read0.first << " !"[read0.second] << " -> " << S.back().first << " !"[S.back().second] << std::endl; // delete visited vertex and edges for (auto& vv : visitedV) { // std::cout << "Visiting " << vv.first << " !"[vv.second] << std::endl; readTrims[vv.first].del = true; } for (auto& p2 : g) { for (auto &edge: p2.second) { if (edge.visited) { // std::cout << "Deleting : " << std::endl << edge.aId << " !"[edge.aIsReversed] << " -> " << edge.bId << " !"[edge.bIsReversed] << std::endl; edge.del = true; for (auto &edge2: g[std::make_pair(edge.bId, !edge.bIsReversed)]) { if (edge2.bId == edge.aId && edge2.bIsReversed != edge.aIsReversed) { // std::cout << edge2.aId << " !"[edge2.aIsReversed] << " -> " << edge2.bId << " !"[edge2.bIsReversed] << std::endl; edge2.del = true; } } } } } Vertex& v = S.back(); // std::cout << "Visiting " << v.first << " !"[v.second] << std::endl; while (v != read0) { Vertex& u = optPath[v]; // u -> v // std::cout << "Visiting " << u.first << " !"[u.second] << std::endl; readTrims[v.first].del = false; for (auto& edge: g[u]) if (edge.bId == v.first && edge.bIsReversed == v.second) edge.del = false; for (auto& edge: g[std::make_pair(v.first, !v.second)]) if (edge.bId == u.first && edge.bIsReversed == !u.second) edge.del = false; v = u; } cleanGraph(g); break; } } for (auto& p2 : g) for (auto& e : p2.second) e.visited = false; } #undef D } <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2014 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 "projectwindow.h" #include "doubletabwidget.h" #include "panelswidget.h" #include "kitmanager.h" #include "project.h" #include "projectexplorer.h" #include "projectpanelfactory.h" #include "session.h" #include "target.h" #include <coreplugin/idocument.h> #include <extensionsystem/pluginmanager.h> #include <utils/algorithm.h> #include <utils/qtcassert.h> #include <QStackedWidget> #include <QVBoxLayout> using namespace ProjectExplorer; using namespace ProjectExplorer::Internal; /// // ProjectWindow /// ProjectWindow::ProjectWindow(QWidget *parent) : QWidget(parent), m_ignoreChange(false), m_currentWidget(0) { // Setup overall layout: QVBoxLayout *viewLayout = new QVBoxLayout(this); viewLayout->setMargin(0); viewLayout->setSpacing(0); m_tabWidget = new DoubleTabWidget(this); viewLayout->addWidget(m_tabWidget); // Setup our container for the contents: m_centralWidget = new QStackedWidget(this); viewLayout->addWidget(m_centralWidget); // Connections connect(m_tabWidget, SIGNAL(currentIndexChanged(int,int)), this, SLOT(showProperties(int,int))); QObject *sessionManager = SessionManager::instance(); connect(sessionManager, SIGNAL(projectAdded(ProjectExplorer::Project*)), this, SLOT(registerProject(ProjectExplorer::Project*))); connect(sessionManager, SIGNAL(aboutToRemoveProject(ProjectExplorer::Project*)), this, SLOT(deregisterProject(ProjectExplorer::Project*))); connect(sessionManager, SIGNAL(startupProjectChanged(ProjectExplorer::Project*)), this, SLOT(startupProjectChanged(ProjectExplorer::Project*))); connect(sessionManager, SIGNAL(projectDisplayNameChanged(ProjectExplorer::Project*)), this, SLOT(projectDisplayNameChanged(ProjectExplorer::Project*))); // Update properties to empty project for now: showProperties(-1, -1); } ProjectWindow::~ProjectWindow() { } void ProjectWindow::aboutToShutdown() { showProperties(-1, -1); // that's a bit stupid, but otherwise stuff is still // connected to the session m_cache.clear(); disconnect(KitManager::instance(), 0, this, 0); disconnect(SessionManager::instance(), 0, this, 0); } void ProjectWindow::removedTarget(Target *) { Project *p = qobject_cast<Project *>(sender()); QTC_ASSERT(p, return); if (p->targets().isEmpty()) projectUpdated(p); } void ProjectWindow::projectUpdated(Project *project) { // Called after a project was configured int currentIndex = m_tabWidget->currentIndex(); int oldSubIndex = m_tabWidget->currentSubIndex(); removeCurrentWidget(); int newSubIndex = m_cache.recheckFactories(project, oldSubIndex); if (newSubIndex == -1) newSubIndex = 0; m_tabWidget->setSubTabs(currentIndex, m_cache.tabNames(project)); m_ignoreChange = true; m_tabWidget->setCurrentIndex(currentIndex, newSubIndex); m_ignoreChange = false; QWidget *widget = m_cache.widgetFor(project, newSubIndex); if (widget) { m_currentWidget = widget; m_centralWidget->addWidget(m_currentWidget); m_centralWidget->setCurrentWidget(m_currentWidget); m_currentWidget->show(); } } void ProjectWindow::projectDisplayNameChanged(Project *project) { int index = m_cache.indexForProject(project); if (index < 0) return; m_ignoreChange = true; bool isCurrentIndex = m_tabWidget->currentIndex() == index; int subIndex = m_tabWidget->currentSubIndex(); QStringList subTabs = m_tabWidget->subTabs(index); m_tabWidget->removeTab(index); m_cache.sort(); int newIndex = m_cache.indexForProject(project); m_tabWidget->insertTab(newIndex, project->displayName(), project->projectFilePath().toString(), subTabs); if (isCurrentIndex) m_tabWidget->setCurrentIndex(newIndex, subIndex); m_ignoreChange = false; } void ProjectWindow::registerProject(ProjectExplorer::Project *project) { if (m_cache.isRegistered(project)) return; m_cache.registerProject(project); m_tabWidget->insertTab(m_cache.indexForProject(project), project->displayName(), project->projectFilePath().toString(), m_cache.tabNames(project)); connect(project, SIGNAL(removedTarget(ProjectExplorer::Target*)), this, SLOT(removedTarget(ProjectExplorer::Target*))); } bool ProjectWindow::deregisterProject(ProjectExplorer::Project *project) { int index = m_cache.indexForProject(project); if (index == -1) return false; QVector<QWidget *> deletedWidgets = m_cache.deregisterProject(project); if (deletedWidgets.contains(m_currentWidget)) m_currentWidget = 0; m_tabWidget->removeTab(index); disconnect(project, SIGNAL(removedTarget(ProjectExplorer::Target*)), this, SLOT(removedTarget(ProjectExplorer::Target*))); return true; } void ProjectWindow::startupProjectChanged(ProjectExplorer::Project *p) { int index = m_cache.indexForProject(p); if (index != -1) m_tabWidget->setCurrentIndex(index); } void ProjectWindow::showProperties(int index, int subIndex) { if (m_ignoreChange) return; removeCurrentWidget(); Project *project = m_cache.projectFor(index); if (!project) { return; } QWidget *widget = m_cache.widgetFor(project, subIndex); if (widget) { m_currentWidget = widget; m_centralWidget->addWidget(m_currentWidget); m_centralWidget->setCurrentWidget(m_currentWidget); m_currentWidget->show(); if (hasFocus()) // we get assigned focus from setFocusToCurrentMode, pass that on m_currentWidget->setFocus(); } SessionManager::setStartupProject(project); } void ProjectWindow::removeCurrentWidget() { if (m_currentWidget) { m_centralWidget->removeWidget(m_currentWidget); m_currentWidget->hide(); m_currentWidget = 0; } } // WidgetCache void WidgetCache::registerProject(Project *project) { QTC_ASSERT(!isRegistered(project), return); QList<ProjectPanelFactory *> fac = ProjectPanelFactory::factories(); int factorySize = fac.size(); ProjectInfo info; info.project = project; info.widgets.resize(factorySize); info.supports.resize(factorySize); for (int i = 0; i < factorySize; ++i) info.supports[i] = fac.at(i)->supports(project); m_projects.append(info); sort(); } QVector<QWidget *> WidgetCache::deregisterProject(Project *project) { QTC_ASSERT(isRegistered(project), return QVector<QWidget *>()); int index = indexForProject(project); ProjectInfo info = m_projects.at(index); QVector<QWidget *> deletedWidgets = info.widgets; qDeleteAll(info.widgets); m_projects.removeAt(index); return deletedWidgets; } QStringList WidgetCache::tabNames(Project *project) const { int index = indexForProject(project); if (index == -1) return QStringList(); QList<ProjectPanelFactory *> fac = ProjectPanelFactory::factories(); ProjectInfo info = m_projects.at(index); int end = info.supports.size(); QStringList names; for (int i = 0; i < end; ++i) if (info.supports.at(i)) names << fac.at(i)->displayName(); return names; } int WidgetCache::factoryIndex(int projectIndex, int supportsIndex) const { QList<ProjectPanelFactory *> fac = ProjectPanelFactory::factories(); int end = fac.size(); const ProjectInfo &info = m_projects.at(projectIndex); for (int i = 0; i < end; ++i) { if (info.supports.at(i)) { if (supportsIndex == 0) return i; else --supportsIndex; } } return -1; } QWidget *WidgetCache::widgetFor(Project *project, int supportsIndex) { int projectIndex = indexForProject(project); if (projectIndex == -1) return 0; QList<ProjectPanelFactory *> fac = ProjectPanelFactory::factories(); int factoryIndex = factoryIndex(projectIndex, supportsIndex); if (factoryIndex < 0 ||factoryIndex >= m_projects.at(projectIndex).widgets.size()) return 0; if (!m_projects.at(projectIndex).widgets.at(factoryIndex)) m_projects[projectIndex].widgets[factoryIndex] = fac.at(factoryIndex)->createWidget(project); return m_projects.at(projectIndex).widgets.at(factoryIndex); } bool WidgetCache::isRegistered(Project *project) const { return Utils::anyOf(m_projects, [&project](ProjectInfo pinfo) { return pinfo.project == project; }); } int WidgetCache::indexForProject(Project *project) const { return Utils::indexOf(m_projects, [&project](ProjectInfo pinfo) { return pinfo.project == project; }); } Project *WidgetCache::projectFor(int projectIndex) const { if (projectIndex < 0) return 0; if (projectIndex >= m_projects.size()) return 0; return m_projects.at(projectIndex).project; } void WidgetCache::sort() { Utils::sort(m_projects, [](const ProjectInfo &a, const ProjectInfo &b) -> bool { QString aName = a.project->displayName(); QString bName = b.project->displayName(); if (aName == bName) { Utils::FileName aPath = a.project->projectFilePath(); Utils::FileName bPath = b.project->projectFilePath(); if (aPath == bPath) return a.project < b.project; else return aPath < bPath; } else { return aName < bName; } }); } int WidgetCache::recheckFactories(Project *project, int oldSupportsIndex) { int projectIndex = indexForProject(project); int factoryIndex = factoryIndex(projectIndex, oldSupportsIndex); ProjectInfo &info = m_projects[projectIndex]; QList<ProjectPanelFactory *> fac = ProjectPanelFactory::factories(); int end = fac.size(); for (int i = 0; i < end; ++i) { info.supports[i] = fac.at(i)->supports(project); if (!info.supports.at(i)) { delete info.widgets.at(i); info.widgets[i] = 0; } } if (factoryIndex < 0) return -1; if (!info.supports.at(factoryIndex)) return -1; int newIndex = 0; for (int i = 0; i < factoryIndex; ++i) { if (info.supports.at(i)) ++newIndex; } return newIndex; } void WidgetCache::clear() { while (!m_projects.isEmpty()) deregisterProject(m_projects.first().project); } <commit_msg>Fix compile<commit_after>/**************************************************************************** ** ** Copyright (C) 2014 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 "projectwindow.h" #include "doubletabwidget.h" #include "panelswidget.h" #include "kitmanager.h" #include "project.h" #include "projectexplorer.h" #include "projectpanelfactory.h" #include "session.h" #include "target.h" #include <coreplugin/idocument.h> #include <extensionsystem/pluginmanager.h> #include <utils/algorithm.h> #include <utils/qtcassert.h> #include <QStackedWidget> #include <QVBoxLayout> using namespace ProjectExplorer; using namespace ProjectExplorer::Internal; /// // ProjectWindow /// ProjectWindow::ProjectWindow(QWidget *parent) : QWidget(parent), m_ignoreChange(false), m_currentWidget(0) { // Setup overall layout: QVBoxLayout *viewLayout = new QVBoxLayout(this); viewLayout->setMargin(0); viewLayout->setSpacing(0); m_tabWidget = new DoubleTabWidget(this); viewLayout->addWidget(m_tabWidget); // Setup our container for the contents: m_centralWidget = new QStackedWidget(this); viewLayout->addWidget(m_centralWidget); // Connections connect(m_tabWidget, SIGNAL(currentIndexChanged(int,int)), this, SLOT(showProperties(int,int))); QObject *sessionManager = SessionManager::instance(); connect(sessionManager, SIGNAL(projectAdded(ProjectExplorer::Project*)), this, SLOT(registerProject(ProjectExplorer::Project*))); connect(sessionManager, SIGNAL(aboutToRemoveProject(ProjectExplorer::Project*)), this, SLOT(deregisterProject(ProjectExplorer::Project*))); connect(sessionManager, SIGNAL(startupProjectChanged(ProjectExplorer::Project*)), this, SLOT(startupProjectChanged(ProjectExplorer::Project*))); connect(sessionManager, SIGNAL(projectDisplayNameChanged(ProjectExplorer::Project*)), this, SLOT(projectDisplayNameChanged(ProjectExplorer::Project*))); // Update properties to empty project for now: showProperties(-1, -1); } ProjectWindow::~ProjectWindow() { } void ProjectWindow::aboutToShutdown() { showProperties(-1, -1); // that's a bit stupid, but otherwise stuff is still // connected to the session m_cache.clear(); disconnect(KitManager::instance(), 0, this, 0); disconnect(SessionManager::instance(), 0, this, 0); } void ProjectWindow::removedTarget(Target *) { Project *p = qobject_cast<Project *>(sender()); QTC_ASSERT(p, return); if (p->targets().isEmpty()) projectUpdated(p); } void ProjectWindow::projectUpdated(Project *project) { // Called after a project was configured int currentIndex = m_tabWidget->currentIndex(); int oldSubIndex = m_tabWidget->currentSubIndex(); removeCurrentWidget(); int newSubIndex = m_cache.recheckFactories(project, oldSubIndex); if (newSubIndex == -1) newSubIndex = 0; m_tabWidget->setSubTabs(currentIndex, m_cache.tabNames(project)); m_ignoreChange = true; m_tabWidget->setCurrentIndex(currentIndex, newSubIndex); m_ignoreChange = false; QWidget *widget = m_cache.widgetFor(project, newSubIndex); if (widget) { m_currentWidget = widget; m_centralWidget->addWidget(m_currentWidget); m_centralWidget->setCurrentWidget(m_currentWidget); m_currentWidget->show(); } } void ProjectWindow::projectDisplayNameChanged(Project *project) { int index = m_cache.indexForProject(project); if (index < 0) return; m_ignoreChange = true; bool isCurrentIndex = m_tabWidget->currentIndex() == index; int subIndex = m_tabWidget->currentSubIndex(); QStringList subTabs = m_tabWidget->subTabs(index); m_tabWidget->removeTab(index); m_cache.sort(); int newIndex = m_cache.indexForProject(project); m_tabWidget->insertTab(newIndex, project->displayName(), project->projectFilePath().toString(), subTabs); if (isCurrentIndex) m_tabWidget->setCurrentIndex(newIndex, subIndex); m_ignoreChange = false; } void ProjectWindow::registerProject(ProjectExplorer::Project *project) { if (m_cache.isRegistered(project)) return; m_cache.registerProject(project); m_tabWidget->insertTab(m_cache.indexForProject(project), project->displayName(), project->projectFilePath().toString(), m_cache.tabNames(project)); connect(project, SIGNAL(removedTarget(ProjectExplorer::Target*)), this, SLOT(removedTarget(ProjectExplorer::Target*))); } bool ProjectWindow::deregisterProject(ProjectExplorer::Project *project) { int index = m_cache.indexForProject(project); if (index == -1) return false; QVector<QWidget *> deletedWidgets = m_cache.deregisterProject(project); if (deletedWidgets.contains(m_currentWidget)) m_currentWidget = 0; m_tabWidget->removeTab(index); disconnect(project, SIGNAL(removedTarget(ProjectExplorer::Target*)), this, SLOT(removedTarget(ProjectExplorer::Target*))); return true; } void ProjectWindow::startupProjectChanged(ProjectExplorer::Project *p) { int index = m_cache.indexForProject(p); if (index != -1) m_tabWidget->setCurrentIndex(index); } void ProjectWindow::showProperties(int index, int subIndex) { if (m_ignoreChange) return; removeCurrentWidget(); Project *project = m_cache.projectFor(index); if (!project) { return; } QWidget *widget = m_cache.widgetFor(project, subIndex); if (widget) { m_currentWidget = widget; m_centralWidget->addWidget(m_currentWidget); m_centralWidget->setCurrentWidget(m_currentWidget); m_currentWidget->show(); if (hasFocus()) // we get assigned focus from setFocusToCurrentMode, pass that on m_currentWidget->setFocus(); } SessionManager::setStartupProject(project); } void ProjectWindow::removeCurrentWidget() { if (m_currentWidget) { m_centralWidget->removeWidget(m_currentWidget); m_currentWidget->hide(); m_currentWidget = 0; } } // WidgetCache void WidgetCache::registerProject(Project *project) { QTC_ASSERT(!isRegistered(project), return); QList<ProjectPanelFactory *> fac = ProjectPanelFactory::factories(); int factorySize = fac.size(); ProjectInfo info; info.project = project; info.widgets.resize(factorySize); info.supports.resize(factorySize); for (int i = 0; i < factorySize; ++i) info.supports[i] = fac.at(i)->supports(project); m_projects.append(info); sort(); } QVector<QWidget *> WidgetCache::deregisterProject(Project *project) { QTC_ASSERT(isRegistered(project), return QVector<QWidget *>()); int index = indexForProject(project); ProjectInfo info = m_projects.at(index); QVector<QWidget *> deletedWidgets = info.widgets; qDeleteAll(info.widgets); m_projects.removeAt(index); return deletedWidgets; } QStringList WidgetCache::tabNames(Project *project) const { int index = indexForProject(project); if (index == -1) return QStringList(); QList<ProjectPanelFactory *> fac = ProjectPanelFactory::factories(); ProjectInfo info = m_projects.at(index); int end = info.supports.size(); QStringList names; for (int i = 0; i < end; ++i) if (info.supports.at(i)) names << fac.at(i)->displayName(); return names; } int WidgetCache::factoryIndex(int projectIndex, int supportsIndex) const { QList<ProjectPanelFactory *> fac = ProjectPanelFactory::factories(); int end = fac.size(); const ProjectInfo &info = m_projects.at(projectIndex); for (int i = 0; i < end; ++i) { if (info.supports.at(i)) { if (supportsIndex == 0) return i; else --supportsIndex; } } return -1; } QWidget *WidgetCache::widgetFor(Project *project, int supportsIndex) { int projectIndex = indexForProject(project); if (projectIndex == -1) return 0; QList<ProjectPanelFactory *> fac = ProjectPanelFactory::factories(); int factoryIdx = factoryIndex(projectIndex, supportsIndex); if (factoryIdx < 0 ||factoryIdx >= m_projects.at(projectIndex).widgets.size()) return 0; if (!m_projects.at(projectIndex).widgets.at(factoryIdx)) m_projects[projectIndex].widgets[factoryIdx] = fac.at(factoryIdx)->createWidget(project); return m_projects.at(projectIndex).widgets.at(factoryIdx); } bool WidgetCache::isRegistered(Project *project) const { return Utils::anyOf(m_projects, [&project](ProjectInfo pinfo) { return pinfo.project == project; }); } int WidgetCache::indexForProject(Project *project) const { return Utils::indexOf(m_projects, [&project](ProjectInfo pinfo) { return pinfo.project == project; }); } Project *WidgetCache::projectFor(int projectIndex) const { if (projectIndex < 0) return 0; if (projectIndex >= m_projects.size()) return 0; return m_projects.at(projectIndex).project; } void WidgetCache::sort() { Utils::sort(m_projects, [](const ProjectInfo &a, const ProjectInfo &b) -> bool { QString aName = a.project->displayName(); QString bName = b.project->displayName(); if (aName == bName) { Utils::FileName aPath = a.project->projectFilePath(); Utils::FileName bPath = b.project->projectFilePath(); if (aPath == bPath) return a.project < b.project; else return aPath < bPath; } else { return aName < bName; } }); } int WidgetCache::recheckFactories(Project *project, int oldSupportsIndex) { int projectIndex = indexForProject(project); int factoryIdx = factoryIndex(projectIndex, oldSupportsIndex); ProjectInfo &info = m_projects[projectIndex]; QList<ProjectPanelFactory *> fac = ProjectPanelFactory::factories(); int end = fac.size(); for (int i = 0; i < end; ++i) { info.supports[i] = fac.at(i)->supports(project); if (!info.supports.at(i)) { delete info.widgets.at(i); info.widgets[i] = 0; } } if (factoryIdx < 0) return -1; if (!info.supports.at(factoryIdx)) return -1; int newIndex = 0; for (int i = 0; i < factoryIdx; ++i) { if (info.supports.at(i)) ++newIndex; } return newIndex; } void WidgetCache::clear() { while (!m_projects.isEmpty()) deregisterProject(m_projects.first().project); } <|endoftext|>
<commit_before>// // // #include "MicroTasksTask.h" #include "MicroTasksEvent.h" #include "MicroTasksAlarm.h" #include "MicroTasks.h" #include "debug.h" using namespace MicroTasks; uint32_t MicroTasksClass::WaitForEvent = (1 << 31); uint32_t MicroTasksClass::WaitForMessage = (1 << 30); uint32_t MicroTasksClass::WaitForMask = MicroTasksClass::WaitForEvent | WaitForMessage; uint32_t MicroTasksClass::Infinate = ~MicroTasksClass::WaitForMask; MicroTasksClass::MicroTasksClass() { } void MicroTasksClass::init() { } uint32_t MicroTasksClass::update() { uint32_t uiNextEvent = 0xFFFFFFFF; // Any events triggered? Event *oNextEvent; for (Event *oEvent = (Event *)Event::oEvents.GetFirst(); oEvent; oEvent = oNextEvent) { oNextEvent = (Event *)oEvent->GetNext(); if (oEvent->triggered) { EventListener *oNextEventListener; for (EventListener *oEventListener = (EventListener *)(oEvent->oClients.GetFirst()); oEventListener; oEventListener = oNextEventListener) { // Keep a pointer to the next task in case this on is stopped oNextEventListener = (EventListener *)(oEventListener->GetNext()); oEventListener->triggered = 1; wakeTask(oEventListener->GetTask(), WakeReason_Event); oEventListener->triggered = 0; } oEvent->triggered = 0; } } // Any alarms triggered? Alarm *oNextAlarm; for (Alarm *oAlarm = (Alarm *)Alarm::oAlarms.GetFirst(); oAlarm; oAlarm = oNextAlarm) { oNextAlarm = (Alarm *)oAlarm->GetNext(); if(millis() >= oAlarm->uiTime) { oAlarm->Trigger(); if(oAlarm->bRepeat) { oAlarm->Reset(); } else { oAlarm->Clear(); } } if(oAlarm->IsValid() && oAlarm->uiTime < uiNextEvent) { uiNextEvent = oAlarm->uiTime; } } // Any tasks waiting to be woken Task *oNextTask; for (Task *oTask = (Task *)oTasks.GetFirst(); oTask; oTask = oNextTask) { // Keep a pointer to the next task in case this one is stopped oNextTask = (Task *)oTask->GetNext(); if (oTask->ulNextLoop <= millis()) { wakeTask(oTask, WakeReason_Scheduled); } if(oTask->IsValid() && oTask->ulNextLoop < uiNextEvent) { uiNextEvent = oTask->ulNextLoop; } } DEBUG_PORT.flush(); return uiNextEvent; } void MicroTasksClass::wakeTask(Task *oTask, WakeReason eReason) { DBUG(millis()); DBUG(": W "); DBUG((unsigned int)oTask); DBUG(" ["); DBUG((int)eReason); DBUG("] -> "); #ifdef ENABLE_DEBUG_MICROTASKS uint32_t ulStart = micros(); #endif uint32_t ulDelay = oTask->loop(eReason); DBUG(micros() - ulStart); DBUG(":"); uint32_t ulNext = ulDelay & ~MicroTask.WaitForMask; oTask->uiFlags = ulDelay & MicroTask.WaitForMask; if (MicroTask.Infinate == ulNext) { oTask->ulNextLoop = 0xFFFFFFFF; DBUGLN("Forever"); } else { oTask->ulNextLoop = millis() + ulNext; DBUG(ulNext); DBUG(":"); DBUGLN(oTask->ulNextLoop); } } void MicroTasksClass::startTask(Task *oTask) { oTasks.Add(oTask); oTask->setup(); } void MicroTasksClass::stopTask(Task *oTask) { oTasks.Remove(oTask); oTask->ulNextLoop = 0xFFFFFFFF; } MicroTasksClass MicroTask; <commit_msg>In some Arduino cores (<1.0?) flush clears the Rx buffer this change attempts to limit the impact of this by only calling flush if debug is enabed.<commit_after>// // // #include "MicroTasksTask.h" #include "MicroTasksEvent.h" #include "MicroTasksAlarm.h" #include "MicroTasks.h" #include "debug.h" using namespace MicroTasks; uint32_t MicroTasksClass::WaitForEvent = (1 << 31); uint32_t MicroTasksClass::WaitForMessage = (1 << 30); uint32_t MicroTasksClass::WaitForMask = MicroTasksClass::WaitForEvent | WaitForMessage; uint32_t MicroTasksClass::Infinate = ~MicroTasksClass::WaitForMask; MicroTasksClass::MicroTasksClass() { } void MicroTasksClass::init() { } uint32_t MicroTasksClass::update() { uint32_t uiNextEvent = 0xFFFFFFFF; // Any events triggered? Event *oNextEvent; for (Event *oEvent = (Event *)Event::oEvents.GetFirst(); oEvent; oEvent = oNextEvent) { oNextEvent = (Event *)oEvent->GetNext(); if (oEvent->triggered) { EventListener *oNextEventListener; for (EventListener *oEventListener = (EventListener *)(oEvent->oClients.GetFirst()); oEventListener; oEventListener = oNextEventListener) { // Keep a pointer to the next task in case this on is stopped oNextEventListener = (EventListener *)(oEventListener->GetNext()); oEventListener->triggered = 1; wakeTask(oEventListener->GetTask(), WakeReason_Event); oEventListener->triggered = 0; } oEvent->triggered = 0; } } // Any alarms triggered? Alarm *oNextAlarm; for (Alarm *oAlarm = (Alarm *)Alarm::oAlarms.GetFirst(); oAlarm; oAlarm = oNextAlarm) { oNextAlarm = (Alarm *)oAlarm->GetNext(); if(millis() >= oAlarm->uiTime) { oAlarm->Trigger(); if(oAlarm->bRepeat) { oAlarm->Reset(); } else { oAlarm->Clear(); } } if(oAlarm->IsValid() && oAlarm->uiTime < uiNextEvent) { uiNextEvent = oAlarm->uiTime; } } // Any tasks waiting to be woken Task *oNextTask; for (Task *oTask = (Task *)oTasks.GetFirst(); oTask; oTask = oNextTask) { // Keep a pointer to the next task in case this one is stopped oNextTask = (Task *)oTask->GetNext(); if (oTask->ulNextLoop <= millis()) { wakeTask(oTask, WakeReason_Scheduled); } if(oTask->IsValid() && oTask->ulNextLoop < uiNextEvent) { uiNextEvent = oTask->ulNextLoop; } } #ifdef ENABLE_DEBUG_MICROTASKS DEBUG_PORT.flush(); #endif return uiNextEvent; } void MicroTasksClass::wakeTask(Task *oTask, WakeReason eReason) { DBUG(millis()); DBUG(": W "); DBUG((unsigned int)oTask); DBUG(" ["); DBUG((int)eReason); DBUG("] -> "); #ifdef ENABLE_DEBUG_MICROTASKS uint32_t ulStart = micros(); #endif uint32_t ulDelay = oTask->loop(eReason); DBUG(micros() - ulStart); DBUG(":"); uint32_t ulNext = ulDelay & ~MicroTask.WaitForMask; oTask->uiFlags = ulDelay & MicroTask.WaitForMask; if (MicroTask.Infinate == ulNext) { oTask->ulNextLoop = 0xFFFFFFFF; DBUGLN("Forever"); } else { oTask->ulNextLoop = millis() + ulNext; DBUG(ulNext); DBUG(":"); DBUGLN(oTask->ulNextLoop); } } void MicroTasksClass::startTask(Task *oTask) { oTasks.Add(oTask); oTask->setup(); } void MicroTasksClass::stopTask(Task *oTask) { oTasks.Remove(oTask); oTask->ulNextLoop = 0xFFFFFFFF; } MicroTasksClass MicroTask; <|endoftext|>
<commit_before>/** * The Seeks proxy and plugin framework are part of the SEEKS project. * Copyright (C) 2011 Emmanuel Benazera <ebenazer@seeks-project.info> * * 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 */ #define _PCREPOSIX_H // avoid pcreposix.h conflict with regex.h used by gtest #include <gtest/gtest.h> #include "se_handler.h" #include "query_context.h" #include "websearch.h" #include "websearch_configuration.h" #include "miscutil.h" #include "errlog.h" using namespace seeks_plugins; using sp::miscutil; using sp::errlog; class SEHandlerTest : public testing::Test { protected: virtual void SetUp() { errlog::init_log_module(); errlog::set_debug_level(LOG_LEVEL_FATAL | LOG_LEVEL_ERROR | LOG_LEVEL_INFO | LOG_LEVEL_DEBUG); } }; TEST_F(SEHandlerTest,query_to_ses_fail_no_engine) { feeds engines; hash_map<const char*,const char*,hash<const char*>,eqstr> parameters; int nresults = 0; query_context *qc = NULL; std::string **output = NULL; int code = SP_ERR_OK; try { output = se_handler::query_to_ses(&parameters,nresults,qc,engines); } catch (sp_exception &e) { code = e.code(); } ASSERT_EQ(WB_ERR_NO_ENGINE,code); parameters.clear(); } TEST_F(SEHandlerTest,query_to_ses_fail_connect) { feeds engines("dummy","url1"); hash_map<const char*,const char*,hash<const char*>,eqstr> *parameters = new hash_map<const char*,const char*,hash<const char*>,eqstr>(2); miscutil::add_map_entry(parameters,"q",1,"test",1); miscutil::add_map_entry(parameters,"expansion",1,"",1); websearch::_wconfig = new websearch_configuration(""); websearch::_wconfig->_se_connect_timeout = 1; websearch::_wconfig->_se_transfer_timeout = 1; ASSERT_TRUE(NULL!=websearch::_wconfig); int nresults = 0; query_context qc; std::string **output = NULL; int code = SP_ERR_OK; try { output = se_handler::query_to_ses(parameters,nresults,&qc,engines); } catch (sp_exception &e) { code = e.code(); } ASSERT_EQ(WB_ERR_NO_ENGINE_OUTPUT,code); delete websearch::_wconfig; miscutil::free_map(parameters); } int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <commit_msg>fixed cleanup of curl handlers in se_handler unit test<commit_after>/** * The Seeks proxy and plugin framework are part of the SEEKS project. * Copyright (C) 2011 Emmanuel Benazera <ebenazer@seeks-project.info> * * 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 */ #define _PCREPOSIX_H // avoid pcreposix.h conflict with regex.h used by gtest #include <gtest/gtest.h> #include "se_handler.h" #include "query_context.h" #include "websearch.h" #include "websearch_configuration.h" #include "miscutil.h" #include "errlog.h" using namespace seeks_plugins; using sp::miscutil; using sp::errlog; class SEHandlerTest : public testing::Test { protected: virtual void SetUp() { errlog::init_log_module(); errlog::set_debug_level(LOG_LEVEL_FATAL | LOG_LEVEL_ERROR | LOG_LEVEL_INFO | LOG_LEVEL_DEBUG); } }; TEST_F(SEHandlerTest,query_to_ses_fail_no_engine) { feeds engines; hash_map<const char*,const char*,hash<const char*>,eqstr> parameters; int nresults = 0; query_context *qc = NULL; std::string **output = NULL; int code = SP_ERR_OK; try { output = se_handler::query_to_ses(&parameters,nresults,qc,engines); } catch (sp_exception &e) { code = e.code(); } ASSERT_EQ(WB_ERR_NO_ENGINE,code); parameters.clear(); se_handler::cleanup_handlers(); } TEST_F(SEHandlerTest,query_to_ses_fail_connect) { feeds engines("dummy","url1"); hash_map<const char*,const char*,hash<const char*>,eqstr> *parameters = new hash_map<const char*,const char*,hash<const char*>,eqstr>(2); miscutil::add_map_entry(parameters,"q",1,"test",1); miscutil::add_map_entry(parameters,"expansion",1,"",1); websearch::_wconfig = new websearch_configuration(""); websearch::_wconfig->_se_connect_timeout = 1; websearch::_wconfig->_se_transfer_timeout = 1; ASSERT_TRUE(NULL!=websearch::_wconfig); int nresults = 0; query_context qc; std::string **output = NULL; int code = SP_ERR_OK; try { output = se_handler::query_to_ses(parameters,nresults,&qc,engines); } catch (sp_exception &e) { code = e.code(); } ASSERT_EQ(WB_ERR_NO_ENGINE_OUTPUT,code); delete websearch::_wconfig; miscutil::free_map(parameters); se_handler::cleanup_handlers(); } int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <|endoftext|>
<commit_before>//Copyright (c) 2018 Ultimaker B.V. //CuraEngine is released under the terms of the AGPLv3 or higher. #include "PrimeTower.h" #include <algorithm> #include <limits> #include "ExtruderTrain.h" #include "sliceDataStorage.h" #include "gcodeExport.h" #include "LayerPlan.h" #include "infill.h" #include "PrintFeature.h" #include "raft.h" #define CIRCLE_RESOLUTION 32 //The number of vertices in each circle. namespace cura { PrimeTower::PrimeTower(const SliceDataStorage& storage) : wipe_from_middle(false) { enabled = storage.getSettingBoolean("prime_tower_enable") && storage.getSettingInMicrons("prime_tower_wall_thickness") > 10 && storage.getSettingInMicrons("prime_tower_size") > 10; extruder_count = storage.meshgroup->getExtruderCount(); extruder_order.resize(extruder_count); for (unsigned int extruder_nr = 0; extruder_nr < extruder_count; extruder_nr++) { extruder_order[extruder_nr] = extruder_nr; //Start with default order, then sort. } //Sort from high adhesion to low adhesion. const SliceDataStorage* storage_ptr = &storage; //Communicate to lambda via pointer to prevent copy. std::sort(extruder_order.begin(), extruder_order.end(), [storage_ptr](const unsigned int& extruder_nr_a, const unsigned int& extruder_nr_b) -> bool { const double adhesion_a = storage_ptr->meshgroup->getExtruderTrain(extruder_nr_a)->getSettingAsRatio("material_adhesion_tendency"); const double adhesion_b = storage_ptr->meshgroup->getExtruderTrain(extruder_nr_b)->getSettingAsRatio("material_adhesion_tendency"); return adhesion_a < adhesion_b; }); } void PrimeTower::generateGroundpoly(const SliceDataStorage& storage) { if (!enabled) { return; } coord_t tower_size = storage.getSettingInMicrons("prime_tower_size"); bool circular_prime_tower = storage.getSettingBoolean("prime_tower_circular"); PolygonRef p = outer_poly.newPoly(); int tower_distance = 0; int x = storage.getSettingInMicrons("prime_tower_position_x"); // storage.model_max.x int y = storage.getSettingInMicrons("prime_tower_position_y"); // storage.model_max.y if (circular_prime_tower) { double_t tower_radius = tower_size / 2; for (unsigned int i = 0; i < CIRCLE_RESOLUTION; i++) { const double angle = (double) i / CIRCLE_RESOLUTION * 2 * M_PI; //In radians. p.add(Point(x - tower_radius + tower_distance + cos(angle) * tower_radius, y + tower_radius + tower_distance + sin(angle) * tower_radius)); } } else { p.add(Point(x + tower_distance, y + tower_distance)); p.add(Point(x + tower_distance, y + tower_distance + tower_size)); p.add(Point(x + tower_distance - tower_size, y + tower_distance + tower_size)); p.add(Point(x + tower_distance - tower_size, y + tower_distance)); } middle = Point(x - tower_size / 2, y + tower_size / 2); post_wipe_point = Point(x + tower_distance - tower_size / 2, y + tower_distance + tower_size / 2); } void PrimeTower::generatePaths(const SliceDataStorage& storage) { enabled &= storage.max_print_height_second_to_last_extruder >= 0; //Maybe it turns out that we don't need a prime tower after all because there are no layer switches. if (enabled) { generatePaths_denseInfill(storage); } } void PrimeTower::generatePaths_denseInfill(const SliceDataStorage& storage) { int n_patterns = 2; // alternating patterns between layers coord_t infill_overlap = 60; // so that it can't be zero; EDIT: wtf? coord_t extra_infill_shift = 0; coord_t tower_size = storage.getSettingInMicrons("prime_tower_size"); coord_t cumulative_inset = 0; //Each tower shape is going to be printed inside the other. This is the inset we're doing for each extruder. coord_t z = 0; // (TODO) because the prime tower stores the paths for each extruder for once instead of generating each layer, we don't know the z position EFillMethod first_layer_infill_method; for (unsigned int extruder = 0; extruder < extruder_count; extruder++) { const coord_t line_width = storage.meshgroup->getExtruderTrain(extruder)->getSettingInMicrons("prime_tower_line_width"); const coord_t wall_thickness = storage.meshgroup->getExtruderTrain(extruder)->getSettingInMicrons("prime_tower_wall_thickness"); patterns_per_extruder.emplace_back(n_patterns); std::vector<ExtrusionMoves>& patterns = patterns_per_extruder.back(); patterns.resize(n_patterns); // If the prime tower is circular, instead of creating a concentric infill in the normal layers, the tower is // built as walls, in order to keep always the same direction while printing if (storage.getSettingBoolean("prime_tower_circular")) { first_layer_infill_method = EFillMethod::CONCENTRIC; const int walls = std::ceil(wall_thickness / line_width); for (int wall_nr = 0; wall_nr < walls; wall_nr++) { // Create a new polygon with an offset from the outer polygon. The polygon is copied in the n_patterns, // since printing walls will be the same in each layer. Polygons polygons = outer_poly.offset(-cumulative_inset - wall_nr * line_width - line_width / 2); for (int pattern_idx = 0; pattern_idx < n_patterns; pattern_idx++) { patterns[pattern_idx].polygons.add(polygons); } } cumulative_inset += walls * line_width; } else { first_layer_infill_method = EFillMethod::LINES; for (int pattern_idx = 0; pattern_idx < n_patterns; pattern_idx++) { Polygons polygons = outer_poly.offset(-cumulative_inset - line_width / 2); if ((wall_thickness + cumulative_inset) * 2 < tower_size) { polygons = polygons.difference(polygons.offset(-wall_thickness)); } patterns[pattern_idx].polygons = polygons; Polygons& result_lines = patterns[pattern_idx].lines; const coord_t outline_offset = -line_width / 2; const coord_t line_distance = line_width; const double fill_angle = 45 + pattern_idx * 90; Polygons& result_polygons = patterns[pattern_idx].polygons; // should remain empty, since we generate lines pattern! constexpr bool zig_zaggify_infill = false; Infill infill_comp(EFillMethod::LINES, zig_zaggify_infill, polygons, outline_offset, line_width, line_distance, infill_overlap, fill_angle, z, extra_infill_shift); infill_comp.generate(result_polygons, result_lines); } cumulative_inset += wall_thickness; } coord_t line_width_layer0 = line_width; if (storage.getSettingAsPlatformAdhesion("adhesion_type") != EPlatformAdhesion::RAFT) { line_width_layer0 *= storage.meshgroup->getExtruderTrain(extruder)->getSettingAsRatio("initial_layer_line_width_factor"); } pattern_per_extruder_layer0.emplace_back(); ExtrusionMoves& pattern = pattern_per_extruder_layer0.back(); pattern.polygons = outer_poly.offset(-line_width_layer0 / 2); const coord_t outline_offset = -line_width_layer0; const coord_t line_distance = line_width_layer0; constexpr double fill_angle = 45; constexpr bool zig_zaggify_infill = false; Infill infill_comp(first_layer_infill_method, zig_zaggify_infill, outer_poly, outline_offset, line_width_layer0, line_distance, infill_overlap, fill_angle, z, extra_infill_shift); infill_comp.generate(pattern.polygons, pattern.lines); } } void PrimeTower::addToGcode(const SliceDataStorage& storage, LayerPlan& gcode_layer, const GCodeExport& gcode, const int prev_extruder, const int new_extruder) const { if (!enabled) { return; } if (gcode_layer.getPrimeTowerIsPlanned(new_extruder)) { // don't print the prime tower if it has been printed already with this extruder. return; } if (gcode_layer.getLayerNr() > storage.max_print_height_second_to_last_extruder + 1) { return; } bool post_wipe = storage.meshgroup->getExtruderTrain(prev_extruder)->getSettingBoolean("prime_tower_wipe_enabled"); // Do not wipe on the first layer, we will generate non-hollow prime tower there for better bed adhesion. const int layer_nr = gcode_layer.getLayerNr(); if (prev_extruder == new_extruder || layer_nr == 0) { post_wipe = false; } addToGcode_denseInfill(storage, gcode_layer, new_extruder); // post-wipe: if (post_wipe) { //Make sure we wipe the old extruder on the prime tower. gcode_layer.addTravel(post_wipe_point - gcode.getExtruderOffset(prev_extruder) + gcode.getExtruderOffset(new_extruder)); } gcode_layer.setPrimeTowerIsPlanned(new_extruder); } void PrimeTower::addToGcode_denseInfill(const SliceDataStorage& storage, LayerPlan& gcode_layer, const int extruder_nr) const { const ExtrusionMoves& pattern = (gcode_layer.getLayerNr() == -Raft::getFillerLayerCount(storage)) ? pattern_per_extruder_layer0[extruder_nr] : patterns_per_extruder[extruder_nr][((gcode_layer.getLayerNr() % 2) + 2) % 2]; // +2) %2 to handle negative layer numbers const GCodePathConfig& config = gcode_layer.configs_storage.prime_tower_config_per_extruder[extruder_nr]; gcode_layer.addPolygonsByOptimizer(pattern.polygons, config); gcode_layer.addLinesByOptimizer(pattern.lines, config, SpaceFillType::Lines); } Point PrimeTower::getLocationBeforePrimeTower(const SliceDataStorage& storage) const { Point ret(0, 0); int absolute_starting_points = 0; for (int extruder_nr = 0; extruder_nr < storage.meshgroup->getExtruderCount(); extruder_nr++) { ExtruderTrain& train = *storage.meshgroup->getExtruderTrain(0); if (train.getSettingBoolean("machine_extruder_start_pos_abs")) { ret += Point(train.getSettingInMicrons("machine_extruder_start_pos_x"), train.getSettingInMicrons("machine_extruder_start_pos_y")); absolute_starting_points++; } } if (absolute_starting_points > 0) { // take the average over all absolute starting positions ret /= absolute_starting_points; } else { // use the middle of the bed ret = storage.machine_size.flatten().getMiddle(); } return ret; } void PrimeTower::subtractFromSupport(SliceDataStorage& storage) { const Polygons outside_polygon = outer_poly.getOutsidePolygons(); AABB outside_polygon_boundary_box(outside_polygon); for(size_t layer = 0; layer <= (size_t)storage.max_print_height_second_to_last_extruder + 1 && layer < storage.support.supportLayers.size(); layer++) { SupportLayer& support_layer = storage.support.supportLayers[layer]; // take the differences of the support infill parts and the prime tower area support_layer.excludeAreasFromSupportInfillAreas(outside_polygon, outside_polygon_boundary_box); } } }//namespace cura <commit_msg>Print prime tower shells in the pre-determined order<commit_after>//Copyright (c) 2018 Ultimaker B.V. //CuraEngine is released under the terms of the AGPLv3 or higher. #include "PrimeTower.h" #include <algorithm> #include <limits> #include "ExtruderTrain.h" #include "sliceDataStorage.h" #include "gcodeExport.h" #include "LayerPlan.h" #include "infill.h" #include "PrintFeature.h" #include "raft.h" #define CIRCLE_RESOLUTION 32 //The number of vertices in each circle. namespace cura { PrimeTower::PrimeTower(const SliceDataStorage& storage) : wipe_from_middle(false) { enabled = storage.getSettingBoolean("prime_tower_enable") && storage.getSettingInMicrons("prime_tower_wall_thickness") > 10 && storage.getSettingInMicrons("prime_tower_size") > 10; extruder_count = storage.meshgroup->getExtruderCount(); extruder_order.resize(extruder_count); for (unsigned int extruder_nr = 0; extruder_nr < extruder_count; extruder_nr++) { extruder_order[extruder_nr] = extruder_nr; //Start with default order, then sort. } //Sort from high adhesion to low adhesion. const SliceDataStorage* storage_ptr = &storage; //Communicate to lambda via pointer to prevent copy. std::sort(extruder_order.begin(), extruder_order.end(), [storage_ptr](const unsigned int& extruder_nr_a, const unsigned int& extruder_nr_b) -> bool { const double adhesion_a = storage_ptr->meshgroup->getExtruderTrain(extruder_nr_a)->getSettingAsRatio("material_adhesion_tendency"); const double adhesion_b = storage_ptr->meshgroup->getExtruderTrain(extruder_nr_b)->getSettingAsRatio("material_adhesion_tendency"); return adhesion_a < adhesion_b; }); } void PrimeTower::generateGroundpoly(const SliceDataStorage& storage) { if (!enabled) { return; } coord_t tower_size = storage.getSettingInMicrons("prime_tower_size"); bool circular_prime_tower = storage.getSettingBoolean("prime_tower_circular"); PolygonRef p = outer_poly.newPoly(); int tower_distance = 0; int x = storage.getSettingInMicrons("prime_tower_position_x"); // storage.model_max.x int y = storage.getSettingInMicrons("prime_tower_position_y"); // storage.model_max.y if (circular_prime_tower) { double_t tower_radius = tower_size / 2; for (unsigned int i = 0; i < CIRCLE_RESOLUTION; i++) { const double angle = (double) i / CIRCLE_RESOLUTION * 2 * M_PI; //In radians. p.add(Point(x - tower_radius + tower_distance + cos(angle) * tower_radius, y + tower_radius + tower_distance + sin(angle) * tower_radius)); } } else { p.add(Point(x + tower_distance, y + tower_distance)); p.add(Point(x + tower_distance, y + tower_distance + tower_size)); p.add(Point(x + tower_distance - tower_size, y + tower_distance + tower_size)); p.add(Point(x + tower_distance - tower_size, y + tower_distance)); } middle = Point(x - tower_size / 2, y + tower_size / 2); post_wipe_point = Point(x + tower_distance - tower_size / 2, y + tower_distance + tower_size / 2); } void PrimeTower::generatePaths(const SliceDataStorage& storage) { enabled &= storage.max_print_height_second_to_last_extruder >= 0; //Maybe it turns out that we don't need a prime tower after all because there are no layer switches. if (enabled) { generatePaths_denseInfill(storage); } } void PrimeTower::generatePaths_denseInfill(const SliceDataStorage& storage) { int n_patterns = 2; // alternating patterns between layers coord_t infill_overlap = 60; // so that it can't be zero; EDIT: wtf? coord_t extra_infill_shift = 0; coord_t tower_size = storage.getSettingInMicrons("prime_tower_size"); patterns_per_extruder.resize(extruder_order.size()); coord_t cumulative_inset = 0; //Each tower shape is going to be printed inside the other. This is the inset we're doing for each extruder. coord_t z = 0; // (TODO) because the prime tower stores the paths for each extruder for once instead of generating each layer, we don't know the z position EFillMethod first_layer_infill_method; for (unsigned int extruder : extruder_order) { const coord_t line_width = storage.meshgroup->getExtruderTrain(extruder)->getSettingInMicrons("prime_tower_line_width"); const coord_t wall_thickness = storage.meshgroup->getExtruderTrain(extruder)->getSettingInMicrons("prime_tower_wall_thickness"); patterns_per_extruder[extruder] = std::vector<ExtrusionMoves>(n_patterns); std::vector<ExtrusionMoves>& patterns = patterns_per_extruder[extruder]; patterns.resize(n_patterns); // If the prime tower is circular, instead of creating a concentric infill in the normal layers, the tower is // built as walls, in order to keep always the same direction while printing if (storage.getSettingBoolean("prime_tower_circular")) { first_layer_infill_method = EFillMethod::CONCENTRIC; const int walls = std::ceil(wall_thickness / line_width); for (int wall_nr = 0; wall_nr < walls; wall_nr++) { // Create a new polygon with an offset from the outer polygon. The polygon is copied in the n_patterns, // since printing walls will be the same in each layer. Polygons polygons = outer_poly.offset(-cumulative_inset - wall_nr * line_width - line_width / 2); for (int pattern_idx = 0; pattern_idx < n_patterns; pattern_idx++) { patterns[pattern_idx].polygons.add(polygons); } } cumulative_inset += walls * line_width; } else { first_layer_infill_method = EFillMethod::LINES; for (int pattern_idx = 0; pattern_idx < n_patterns; pattern_idx++) { Polygons polygons = outer_poly.offset(-cumulative_inset - line_width / 2); if ((wall_thickness + cumulative_inset) * 2 < tower_size) { polygons = polygons.difference(polygons.offset(-wall_thickness)); } patterns[pattern_idx].polygons = polygons; Polygons& result_lines = patterns[pattern_idx].lines; const coord_t outline_offset = -line_width / 2; const coord_t line_distance = line_width; const double fill_angle = 45 + pattern_idx * 90; Polygons& result_polygons = patterns[pattern_idx].polygons; // should remain empty, since we generate lines pattern! constexpr bool zig_zaggify_infill = false; Infill infill_comp(EFillMethod::LINES, zig_zaggify_infill, polygons, outline_offset, line_width, line_distance, infill_overlap, fill_angle, z, extra_infill_shift); infill_comp.generate(result_polygons, result_lines); } cumulative_inset += wall_thickness; } coord_t line_width_layer0 = line_width; if (storage.getSettingAsPlatformAdhesion("adhesion_type") != EPlatformAdhesion::RAFT) { line_width_layer0 *= storage.meshgroup->getExtruderTrain(extruder)->getSettingAsRatio("initial_layer_line_width_factor"); } pattern_per_extruder_layer0.emplace_back(); ExtrusionMoves& pattern = pattern_per_extruder_layer0.back(); pattern.polygons = outer_poly.offset(-line_width_layer0 / 2); const coord_t outline_offset = -line_width_layer0; const coord_t line_distance = line_width_layer0; constexpr double fill_angle = 45; constexpr bool zig_zaggify_infill = false; Infill infill_comp(first_layer_infill_method, zig_zaggify_infill, outer_poly, outline_offset, line_width_layer0, line_distance, infill_overlap, fill_angle, z, extra_infill_shift); infill_comp.generate(pattern.polygons, pattern.lines); } } void PrimeTower::addToGcode(const SliceDataStorage& storage, LayerPlan& gcode_layer, const GCodeExport& gcode, const int prev_extruder, const int new_extruder) const { if (!enabled) { return; } if (gcode_layer.getPrimeTowerIsPlanned(new_extruder)) { // don't print the prime tower if it has been printed already with this extruder. return; } if (gcode_layer.getLayerNr() > storage.max_print_height_second_to_last_extruder + 1) { return; } bool post_wipe = storage.meshgroup->getExtruderTrain(prev_extruder)->getSettingBoolean("prime_tower_wipe_enabled"); // Do not wipe on the first layer, we will generate non-hollow prime tower there for better bed adhesion. const int layer_nr = gcode_layer.getLayerNr(); if (prev_extruder == new_extruder || layer_nr == 0) { post_wipe = false; } addToGcode_denseInfill(storage, gcode_layer, new_extruder); // post-wipe: if (post_wipe) { //Make sure we wipe the old extruder on the prime tower. gcode_layer.addTravel(post_wipe_point - gcode.getExtruderOffset(prev_extruder) + gcode.getExtruderOffset(new_extruder)); } gcode_layer.setPrimeTowerIsPlanned(new_extruder); } void PrimeTower::addToGcode_denseInfill(const SliceDataStorage& storage, LayerPlan& gcode_layer, const int extruder_nr) const { const ExtrusionMoves& pattern = (gcode_layer.getLayerNr() == -Raft::getFillerLayerCount(storage)) ? pattern_per_extruder_layer0[extruder_nr] : patterns_per_extruder[extruder_nr][((gcode_layer.getLayerNr() % 2) + 2) % 2]; // +2) %2 to handle negative layer numbers const GCodePathConfig& config = gcode_layer.configs_storage.prime_tower_config_per_extruder[extruder_nr]; gcode_layer.addPolygonsByOptimizer(pattern.polygons, config); gcode_layer.addLinesByOptimizer(pattern.lines, config, SpaceFillType::Lines); } Point PrimeTower::getLocationBeforePrimeTower(const SliceDataStorage& storage) const { Point ret(0, 0); int absolute_starting_points = 0; for (int extruder_nr = 0; extruder_nr < storage.meshgroup->getExtruderCount(); extruder_nr++) { ExtruderTrain& train = *storage.meshgroup->getExtruderTrain(0); if (train.getSettingBoolean("machine_extruder_start_pos_abs")) { ret += Point(train.getSettingInMicrons("machine_extruder_start_pos_x"), train.getSettingInMicrons("machine_extruder_start_pos_y")); absolute_starting_points++; } } if (absolute_starting_points > 0) { // take the average over all absolute starting positions ret /= absolute_starting_points; } else { // use the middle of the bed ret = storage.machine_size.flatten().getMiddle(); } return ret; } void PrimeTower::subtractFromSupport(SliceDataStorage& storage) { const Polygons outside_polygon = outer_poly.getOutsidePolygons(); AABB outside_polygon_boundary_box(outside_polygon); for(size_t layer = 0; layer <= (size_t)storage.max_print_height_second_to_last_extruder + 1 && layer < storage.support.supportLayers.size(); layer++) { SupportLayer& support_layer = storage.support.supportLayers[layer]; // take the differences of the support infill parts and the prime tower area support_layer.excludeAreasFromSupportInfillAreas(outside_polygon, outside_polygon_boundary_box); } } }//namespace cura <|endoftext|>
<commit_before> // License: BSD 3-clause // Copyright: Nick Porcino, 2017 #include "Screenplay.h" #include <LabText/TextScanner.h> #include <LabText/TextScanner.hpp> namespace lab { using namespace std; using namespace TextScanner; std::string ScriptNode::as_string() const { switch (kind) { case NodeKind::KeyValue: return key + ": " + content; case NodeKind::Divider: return content + "\n"; case NodeKind::Character: case NodeKind::Location: return content + "\n"; case NodeKind::Action: return content + "\n"; case NodeKind::Dialog: return key + "\n" + content; case NodeKind::Direction: return content + "\n"; case NodeKind::Transition: return ToUpper(content) + "\n"; break; } return ""; } Sequence::Sequence(const std::string & name_, bool interior, bool exterior) : interior(interior), exterior(exterior) { name = TextScanner::StripLeadingWhitespace(name_); } Sequence::Sequence(Sequence && rh) : name(rh.name), interior(rh.interior), exterior(rh.exterior) { nodes.swap(rh.nodes); } Sequence & Sequence::operator=(Sequence && rh) { interior = rh.interior; exterior = rh.exterior; name = rh.name; nodes.swap(rh.nodes); return *this; } std::string Sequence::as_string() const { std::string res; if (interior && exterior) res = "INT/EXT "; else if (interior) res = "INT. "; else if (exterior) res = "EXT. "; return res + name; } Script::Script(Script && rh) noexcept : title(std::move(rh.title)) , characters(std::move(rh.characters)) , sets(std::move(rh.sets)) , sequences(std::move(rh.sequences)) { } #ifdef _MSC_VER inline FILE* open_file(const filesystem::path& p) { return _wfopen(p.c_str(), L"r"); } #else inline FILE* open_file(const filesystem::path& p) { return std::fopen(p.c_str(), "r"); } #endif bool isLineContinuation(const string & s) { if (s.length() < 1) return false; return s[0] == '\t' || (s[0] == ' '); } string parseValue(const string & s, const vector<string> & lines, size_t & i) { string result; size_t off = s.find(':'); if (off != string::npos) result = s.substr(off); size_t line = i + 1; while (isLineContinuation(lines[line])) { result += lines[line]; ++line; } i = line - 1; return StripLeadingWhitespace(result); } bool lineIsUpperCase(const char * curr, const char * end) { const char * next = tsScanForBeginningOfNextLine(curr, end); while (next > curr) { if (*curr >= 'a' && *curr <= 'z') return false; ++curr; } return true; } bool charIsEmphasis(char c) { return c == '*' || c == '_'; } #ifdef _MSC_VER #define strnicmp _strnicmp #endif bool beginsWith(const std::string& input, const char * match) { return !strnicmp(input.c_str(), match, (strlen(match))); } string parseShot(const std::string & input, bool & interior, bool & exterior) { interior = false; exterior = false; if (input.length() < 2) return ""; if (input[0] == '.') return StripLeadingWhitespace(input.substr(1)); if (beginsWith(input, "INT./EXT.") || beginsWith(input, "EXT./INT.")) { interior = true; exterior = true; return StripLeadingWhitespace(input.substr(9)); } if (beginsWith(input, "INT./EXT") || beginsWith(input, "EXT./INT")) { interior = true; exterior = true; return StripLeadingWhitespace(input.substr(8)); } if (beginsWith(input, "INT/EXT") || beginsWith(input, "EXT/INT")) { interior = true; exterior = true; return StripLeadingWhitespace(input.substr(7)); } if (beginsWith(input, "INT ") || beginsWith(input, "EXT ") || beginsWith(input, "INT.") || beginsWith(input, "EXT.") || beginsWith(input, "I/E ")) { interior = beginsWith(input, "I"); exterior = beginsWith(input, "E") || beginsWith(input, "I/E "); return StripLeadingWhitespace(input.substr(4)); } return ""; } bool isShot(const std::string& input) { if (input.length() < 2) return false; if (input[0] == '.' && input[1] != '.') return true; return beginsWith(input, "INT ") || beginsWith(input, "EXT ") || beginsWith(input, "INT.") || beginsWith(input, "EXT.") || beginsWith(input, "INT/EXT") || beginsWith(input, "EXT/INT") || beginsWith(input, "I/E "); } bool isTransition(const std::string & input) { if (!input.length()) return false; string s = StripLeadingWhitespace(input); size_t len = s.length() - 1; if (len < 4) return false; if (s[0] == '>') return true; if (!lineIsUpperCase(input.c_str(), input.c_str() + input.length())) return false; const char * transitions[] = { "CUT TO BLACK", "cut to:", "CUT TO:", "INTERCUT WITH:", "FADE IN:", "TITLE OVER:", "SPLIT SCREEN:", "OPENING CREDITS", "END CREDITS" }; for (auto str : transitions) if (s.find(str) != string::npos) return true; string end = s.substr(len - 3, len - 2); return beginsWith(end, " TO") || beginsWith(end, " IN"); } string parseTransition(const std::string & input) { string r = StripLeadingWhitespace(input); if (r[0] == '>') r = r.substr(1); return StripTrailingWhitespace(StripLeadingWhitespace(r)); } bool isDialog(const std::string & input) { if (input.length() < 2) return false; if (input[0] == '@') return true; if (isTransition(input)) return false; return lineIsUpperCase(input.c_str(), input.c_str() + input.length()); } string parseDialog(const string& s, string& character, const vector<string>& lines, size_t & i) { if (s[0] == '@') character = s.substr(1); else character = s; string result; size_t line = i + 1; while (line < lines.size() && lines[line].length() > 0) { result += lines[line] + "\n"; ++line; } i = line - 1; return result; } struct ScriptEdit { Script* script = nullptr; Sequence* curr_sequence = nullptr; ScriptNode curr_node; void start_node(NodeKind kind, const std::string& value) { finalize_current_node(); curr_node = { kind, value }; if (kind == NodeKind::Dialog) { /// @TODO how to interpret a value with parentheses? What does the spec say...? script->characters.insert(value); } } void finalize_current_node() { if (curr_node.kind != NodeKind::Unknown) { curr_sequence->nodes.push_back(curr_node); curr_node.kind = NodeKind::Unknown; curr_node.content = ""; } } void append_text(const std::string& s) { if (curr_node.kind == NodeKind::Unknown) curr_node.kind = NodeKind::Action; if (curr_node.content.size()) curr_node.content += '\n'; curr_node.content += s; } void start_sequence(const string& name, bool interior, bool exterior) { finalize_current_sequence(); script->sequences.emplace_back(Sequence(name, interior, exterior)); script->sets.insert(script->sequences.back().as_string()); curr_sequence = &script->sequences.back(); } void finalize_current_sequence() { finalize_current_node(); curr_sequence = nullptr; } }; Script Script::parseFountain(const std::string& text) { Script script; ScriptEdit edit = { &script, &script.title }; std::vector<std::string> lines = TextScanner::SplitLines(text); const char* title_page_tags[] = { "Title:", "Credit:", "Author:", "Source:", "Draft Date:", "Notes:", "Contact:", "Copyright:" }; for (auto& line : lines) { auto s = StripLeadingWhitespace(line); if (beginsWith(s, "===")) { edit.start_node(NodeKind::Divider, s); edit.finalize_current_node(); continue; } bool titled = false; for (auto t : title_page_tags) { if (beginsWith(s, t)) { edit.start_node(NodeKind::KeyValue, std::string(t, strlen(t) - 1)); titled = true; break; } } if (titled) continue; if (isShot(s)) { bool interior, exterior; string shot_name = parseShot(s, interior, exterior); edit.start_sequence(shot_name, interior, exterior); continue; } if (isTransition(s)) { edit.start_node(NodeKind::Transition, parseTransition(s)); edit.finalize_current_node(); continue; } if (isDialog(s)) { if (s[0] == '@') s = s.substr(1); s = StripLeadingWhitespace(s); edit.start_node(NodeKind::Dialog, s); continue; } edit.append_text(s); } edit.finalize_current_sequence(); return script; } Script Script::parseFountain(const filesystem::path& fountainFile) { FILE* f = open_file(fountainFile); if (!f) throw std::runtime_error("Couldn't open file"); fseek(f, 0, SEEK_END); size_t len = ftell(f); fseek(f, 0, SEEK_SET); char* text = new char[len + 1]; fread(text, 1, len, f); text[len] = '\0'; fclose(f); char* end = text + len; std::string txt(text, end); delete[] text; return parseFountain(txt); } } <commit_msg>Put character in key field<commit_after> // License: BSD 3-clause // Copyright: Nick Porcino, 2017 #include "Screenplay.h" #include <LabText/TextScanner.h> #include <LabText/TextScanner.hpp> namespace lab { using namespace std; using namespace TextScanner; std::string ScriptNode::as_string() const { switch (kind) { case NodeKind::KeyValue: return key + ": " + content; case NodeKind::Divider: return content + "\n"; case NodeKind::Character: case NodeKind::Location: return content + "\n"; case NodeKind::Action: return content + "\n"; case NodeKind::Dialog: return key + "\n" + content; case NodeKind::Direction: return content + "\n"; case NodeKind::Transition: return ToUpper(content) + "\n"; break; } return ""; } Sequence::Sequence(const std::string & name_, bool interior, bool exterior) : interior(interior), exterior(exterior) { name = TextScanner::StripLeadingWhitespace(name_); } Sequence::Sequence(Sequence && rh) : name(rh.name), interior(rh.interior), exterior(rh.exterior) { nodes.swap(rh.nodes); } Sequence & Sequence::operator=(Sequence && rh) { interior = rh.interior; exterior = rh.exterior; name = rh.name; nodes.swap(rh.nodes); return *this; } std::string Sequence::as_string() const { std::string res; if (interior && exterior) res = "INT/EXT "; else if (interior) res = "INT. "; else if (exterior) res = "EXT. "; return res + name; } Script::Script(Script && rh) noexcept : title(std::move(rh.title)) , characters(std::move(rh.characters)) , sets(std::move(rh.sets)) , sequences(std::move(rh.sequences)) { } #ifdef _MSC_VER inline FILE* open_file(const filesystem::path& p) { return _wfopen(p.c_str(), L"r"); } #else inline FILE* open_file(const filesystem::path& p) { return std::fopen(p.c_str(), "r"); } #endif bool isLineContinuation(const string & s) { if (s.length() < 1) return false; return s[0] == '\t' || (s[0] == ' '); } string parseValue(const string & s, const vector<string> & lines, size_t & i) { string result; size_t off = s.find(':'); if (off != string::npos) result = s.substr(off); size_t line = i + 1; while (isLineContinuation(lines[line])) { result += lines[line]; ++line; } i = line - 1; return StripLeadingWhitespace(result); } bool lineIsUpperCase(const char * curr, const char * end) { const char * next = tsScanForBeginningOfNextLine(curr, end); while (next > curr) { if (*curr >= 'a' && *curr <= 'z') return false; ++curr; } return true; } bool charIsEmphasis(char c) { return c == '*' || c == '_'; } #ifdef _MSC_VER #define strnicmp _strnicmp #endif bool beginsWith(const std::string& input, const char * match) { return !strnicmp(input.c_str(), match, (strlen(match))); } string parseShot(const std::string & input, bool & interior, bool & exterior) { interior = false; exterior = false; if (input.length() < 2) return ""; if (input[0] == '.') return StripLeadingWhitespace(input.substr(1)); if (beginsWith(input, "INT./EXT.") || beginsWith(input, "EXT./INT.")) { interior = true; exterior = true; return StripLeadingWhitespace(input.substr(9)); } if (beginsWith(input, "INT./EXT") || beginsWith(input, "EXT./INT")) { interior = true; exterior = true; return StripLeadingWhitespace(input.substr(8)); } if (beginsWith(input, "INT/EXT") || beginsWith(input, "EXT/INT")) { interior = true; exterior = true; return StripLeadingWhitespace(input.substr(7)); } if (beginsWith(input, "INT ") || beginsWith(input, "EXT ") || beginsWith(input, "INT.") || beginsWith(input, "EXT.") || beginsWith(input, "I/E ")) { interior = beginsWith(input, "I"); exterior = beginsWith(input, "E") || beginsWith(input, "I/E "); return StripLeadingWhitespace(input.substr(4)); } return ""; } bool isShot(const std::string& input) { if (input.length() < 2) return false; if (input[0] == '.' && input[1] != '.') return true; return beginsWith(input, "INT ") || beginsWith(input, "EXT ") || beginsWith(input, "INT.") || beginsWith(input, "EXT.") || beginsWith(input, "INT/EXT") || beginsWith(input, "EXT/INT") || beginsWith(input, "I/E "); } bool isTransition(const std::string & input) { if (!input.length()) return false; string s = StripLeadingWhitespace(input); size_t len = s.length() - 1; if (len < 4) return false; if (s[0] == '>') return true; if (!lineIsUpperCase(input.c_str(), input.c_str() + input.length())) return false; const char * transitions[] = { "CUT TO BLACK", "cut to:", "CUT TO:", "INTERCUT WITH:", "FADE IN:", "TITLE OVER:", "SPLIT SCREEN:", "OPENING CREDITS", "END CREDITS" }; for (auto str : transitions) if (s.find(str) != string::npos) return true; string end = s.substr(len - 3, len - 2); return beginsWith(end, " TO") || beginsWith(end, " IN"); } string parseTransition(const std::string & input) { string r = StripLeadingWhitespace(input); if (r[0] == '>') r = r.substr(1); return StripTrailingWhitespace(StripLeadingWhitespace(r)); } bool isDialog(const std::string & input) { if (input.length() < 2) return false; if (input[0] == '@') return true; if (isTransition(input)) return false; return lineIsUpperCase(input.c_str(), input.c_str() + input.length()); } string parseDialog(const string& s, string& character, const vector<string>& lines, size_t & i) { if (s[0] == '@') character = s.substr(1); else character = s; string result; size_t line = i + 1; while (line < lines.size() && lines[line].length() > 0) { result += lines[line] + "\n"; ++line; } i = line - 1; return result; } struct ScriptEdit { Script* script = nullptr; Sequence* curr_sequence = nullptr; ScriptNode curr_node; void start_node(NodeKind kind, const std::string& value) { finalize_current_node(); curr_node = { kind, value, "" }; if (kind == NodeKind::Dialog) { /// @TODO how to interpret a value with parentheses? What does the spec say...? script->characters.insert(value); } } void finalize_current_node() { if (curr_node.kind != NodeKind::Unknown) { curr_sequence->nodes.push_back(curr_node); curr_node.kind = NodeKind::Unknown; curr_node.key = ""; curr_node.content = ""; } } void append_text(const std::string& s) { if (curr_node.kind == NodeKind::Unknown) curr_node.kind = NodeKind::Action; if (curr_node.content.size()) curr_node.content += '\n'; curr_node.content += s; } void start_sequence(const string& name, bool interior, bool exterior) { finalize_current_sequence(); script->sequences.emplace_back(Sequence(name, interior, exterior)); script->sets.insert(script->sequences.back().as_string()); curr_sequence = &script->sequences.back(); } void finalize_current_sequence() { finalize_current_node(); curr_sequence = nullptr; } }; Script Script::parseFountain(const std::string& text) { Script script; ScriptEdit edit = { &script, &script.title }; std::vector<std::string> lines = TextScanner::SplitLines(text); const char* title_page_tags[] = { "Title:", "Credit:", "Author:", "Source:", "Draft Date:", "Notes:", "Contact:", "Copyright:" }; for (auto& line : lines) { auto s = StripLeadingWhitespace(line); if (beginsWith(s, "===")) { edit.start_node(NodeKind::Divider, s); edit.finalize_current_node(); continue; } bool titled = false; for (auto t : title_page_tags) { if (beginsWith(s, t)) { edit.start_node(NodeKind::KeyValue, std::string(t, strlen(t) - 1)); titled = true; break; } } if (titled) continue; if (isShot(s)) { bool interior, exterior; string shot_name = parseShot(s, interior, exterior); edit.start_sequence(shot_name, interior, exterior); continue; } if (isTransition(s)) { edit.start_node(NodeKind::Transition, ToUpper(parseTransition(s))); edit.finalize_current_node(); continue; } if (isDialog(s)) { if (s[0] == '@') s = s.substr(1); s = StripLeadingWhitespace(s); edit.start_node(NodeKind::Dialog, s); continue; } edit.append_text(s); } edit.finalize_current_sequence(); return script; } Script Script::parseFountain(const filesystem::path& fountainFile) { FILE* f = open_file(fountainFile); if (!f) throw std::runtime_error("Couldn't open file"); fseek(f, 0, SEEK_END); size_t len = ftell(f); fseek(f, 0, SEEK_SET); char* text = new char[len + 1]; fread(text, 1, len, f); text[len] = '\0'; fclose(f); char* end = text + len; std::string txt(text, end); delete[] text; return parseFountain(txt); } } <|endoftext|>
<commit_before>#include "service.h" Service::Service() { } bool Service::addNewPersonToList(const vector<int> computerConnectionID,const string name,const string gender, const string birthYear, const string deathYear,const string comment) { if(_cSPersonService.addNewPersonToList(name, gender,birthYear, deathYear, comment)) { return true; } return false; } bool Service::addNewComputerToList(const vector<int> scientistConnectionID,const string name,const int designYear, const int buildYear, const string type, const bool created) { Computer newComputer; int computerID = 0; if(_computerService.addNewComputerToList(newComputer, name, designYear, buildYear, type, created)) { computerID = _dbCon.addComputer(newComputer); return true; } return false; } bool Service::removePersonFromList(const string id) { /*if (_cSPersonService.removePersonFromList(id)) { return true; }*/ return false; } vector<CSPerson> Service::getComputerScientistList() { updateComputerScientistList(); return _computerScientists; } vector <string> Service::getComputerTypesList() { // Not finished //Get list from DB return _computerTypes; } vector<Computer> Service::getComputerList() { updateComputerList(); return _computerList; } void Service::updateComputerList() { _dbCon.getComputers(_computerList); } void Service::updateComputerScientistList() { _dbCon.getComputerScientists(_computerScientists); } //Þau föll sem er ekki búið að fara yfir fyrir (aðlaga) Viku2 void Service::sortListAlphabetically() { //_cSPersonService.sortByName(); } void Service::sortListAlphabeticallyASC() { //_cSPersonService.sortByNameASC(); } void Service::sortListByGender() { //_cSPersonService.sortByGender(); } void Service::sortListByDeathYear() { //_cSPersonService.sortByDeathYear(); } void Service::sortListByBirthYear() { //_cSPersonService.sortByBirthYear(); } void Service::sortListByBirthYearASC() { //_cSPersonService.sortByBirthYearASC(); } void Service::sortListByAge() { //_cSPersonService.sortByAge(); } vector<CSPerson> Service::searchByName(const string searchString) { vector <CSPerson> searchByName;// = _cSPersonService.searchByName(searchString); return searchByName; } vector<CSPerson> Service::searchByYearOfBirth(const string searchString) { vector <CSPerson> searchByYOB;// = _cSPersonService.searchByYearOfBirth(searchString); return searchByYOB; } vector<CSPerson> Service::searchByYearOfDeath(const string searchString) { vector <CSPerson> searchByYOD;// = _cSPersonService.searchByYearOfDeath(searchString); return searchByYOD; } vector<Computer> searchComputerByName(const string searchString) { // TODO vector <Computer> searchByName; return searchByName; } vector<Computer> searchComputerByType(const string searchString) { // TODO vector <Computer> searchByType; return searchByType; } vector<Computer> searchComputerByYear(const string searchString) { // TODO vector <Computer> searchByYear; return searchByYear; } <commit_msg>sort functions for computer added in service class<commit_after>#include "service.h" Service::Service() { } bool Service::addNewPersonToList(const vector<int> computerConnectionID,const string name,const string gender, const string birthYear, const string deathYear,const string comment) { if(_cSPersonService.addNewPersonToList(name, gender,birthYear, deathYear, comment)) { return true; } return false; } bool Service::addNewComputerToList(const vector<int> scientistConnectionID,const string name,const int designYear, const int buildYear, const string type, const bool created) { Computer newComputer; int computerID = 0; if(_computerService.addNewComputerToList(newComputer, name, designYear, buildYear, type, created)) { computerID = _dbCon.addComputer(newComputer); return true; } return false; } bool Service::removePersonFromList(const string id) { /*if (_cSPersonService.removePersonFromList(id)) { return true; }*/ return false; } vector<CSPerson> Service::getComputerScientistList() { updateComputerScientistList(); return _computerScientists; } vector <string> Service::getComputerTypesList() { // Not finished //Get list from DB return _computerTypes; } vector<Computer> Service::getComputerList() { updateComputerList(); return _computerList; } void Service::updateComputerList() { _dbCon.getComputers(_computerList); } void Service::updateComputerScientistList() { _dbCon.getComputerScientists(_computerScientists); } //Þau föll sem er ekki búið að fara yfir fyrir (aðlaga) Viku2 void Service::sortListAlphabetically() { //_cSPersonService.sortByName(); } void Service::sortListAlphabeticallyASC() { //_cSPersonService.sortByNameASC(); } void Service::sortListByGender() { //_cSPersonService.sortByGender(); } void Service::sortListByDeathYear() { //_cSPersonService.sortByDeathYear(); } void Service::sortListByBirthYear() { //_cSPersonService.sortByBirthYear(); } void Service::sortListByBirthYearASC() { //_cSPersonService.sortByBirthYearASC(); } void Service::sortListByAge() { //_cSPersonService.sortByAge(); } vector<CSPerson> Service::searchByName(const string searchString) { vector <CSPerson> searchByName;// = _cSPersonService.searchByName(searchString); return searchByName; } vector<CSPerson> Service::searchByYearOfBirth(const string searchString) { vector <CSPerson> searchByYOB;// = _cSPersonService.searchByYearOfBirth(searchString); return searchByYOB; } vector<CSPerson> Service::searchByYearOfDeath(const string searchString) { vector <CSPerson> searchByYOD;// = _cSPersonService.searchByYearOfDeath(searchString); return searchByYOD; } vector<Computer> Service::searchComputerByName(const string searchString) { // TODO vector <Computer> searchByName; return searchByName; } vector<Computer> Service::searchComputerByType(const string searchString) { // TODO vector <Computer> searchByType; return searchByType; } vector<Computer> Service::searchComputerByYear(const string searchString) { // TODO vector <Computer> searchByYear; return searchByYear; } <|endoftext|>
<commit_before>/* FLTKKeyboardWidget.hpp: Copyright (C) 2006 Steven Yi This file is part of Csound. The Csound 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. Csound 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 Csound; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "FLTKKeyboardWidget.hpp" static void allNotesOff(Fl_Widget *widget, void * v) { FLTKKeyboardWidget *win = (FLTKKeyboardWidget *)v; win->keyboard->allNotesOff(); } static void channelChange(Fl_Widget *widget, void * v) { Fl_Spinner *spinner = (Fl_Spinner *)widget; FLTKKeyboardWidget *win = (FLTKKeyboardWidget *)v; win->lock(); int channel = (int)spinner->value() - 1; win->keyboardMapping->setCurrentChannel(channel); win->bankChoice->value(win->keyboardMapping->getCurrentBank()); win->setProgramNames(); win->unlock(); } static void bankChange(Fl_Widget *widget, void * v) { Fl_Choice *choice = (Fl_Choice *)widget; FLTKKeyboardWidget *win = (FLTKKeyboardWidget *)v; win->lock(); win->keyboardMapping->setCurrentBank((int)choice->value()); win->setProgramNames(); win->unlock(); } static void programChange(Fl_Widget *widget, void * v) { Fl_Choice *choice = (Fl_Choice *)widget; FLTKKeyboardWidget *win = (FLTKKeyboardWidget *)v; win->lock(); win->keyboardMapping->setCurrentProgram((int)choice->value()); win->unlock(); } FLTKKeyboardWidget::FLTKKeyboardWidget(CSOUND *csound, const char *deviceMap, int X, int Y) : Fl_Group(X, Y, 624, 120) { this->csound = csound; this->mutex = csound->Create_Mutex(0); this->keyboardMapping = new KeyboardMapping(csound, deviceMap); this->begin(); int row1 = 0; int row2 = row1 + 20; int row3 = row2 + 20; this->channelSpinner = new Fl_Spinner(60, row1, 80, 20, "Channel"); channelSpinner->maximum(16); channelSpinner->minimum(1); this->channelSpinner->callback((Fl_Callback*) channelChange, this); this->bankChoice = new Fl_Choice(180, row1, 180, 20, "Bank"); this->programChoice = new Fl_Choice(420, row1, 200, 20, "Program"); bankChoice->clear(); for(unsigned int i = 0; i < keyboardMapping->banks.size(); i++) { bankChoice->add(keyboardMapping->banks[i]->name); } bankChoice->value(0); setProgramNames(); this->bankChoice->callback((Fl_Callback*)bankChange, this); this->programChoice->callback((Fl_Callback*)programChange, this); this->allNotesOffButton = new Fl_Button(0, row2, 623, 20, "All Notes Off"); this->allNotesOffButton->callback((Fl_Callback*) allNotesOff, this); this->keyboard = new FLTKKeyboard(csound, 0, row3, 624, 80, "Keyboard"); this->end(); } FLTKKeyboardWidget::~FLTKKeyboardWidget() { if (mutex) { csound->DestroyMutex(mutex); mutex = (void*) 0; } delete keyboardMapping; } void FLTKKeyboardWidget::setProgramNames() { Bank* bank = keyboardMapping->banks[keyboardMapping->getCurrentBank()]; programChoice->clear(); for( vector<Program>::iterator iter = bank->programs.begin(); iter != bank->programs.end(); iter++ ) { programChoice->add((*iter).name); } programChoice->value(bank->currentProgram); } int FLTKKeyboardWidget::handle(int event) { //this->csound->Message(this->csound, "Keyboard event: %d\n", event); switch(event) { case FL_KEYDOWN: return this->keyboard->handle(event); case FL_KEYUP: return this->keyboard->handle(event); // case FL_DEACTIVATE: // this->keyboard->allNotesOff(); // csound->Message(csound, "Deactivate\n"); // return 1; default: return Fl_Group::handle(event); } } void FLTKKeyboardWidget::lock() { if(mutex) { csound->LockMutex(mutex); } } void FLTKKeyboardWidget::unlock() { if(mutex) { csound->UnlockMutex(mutex); } } <commit_msg>fixes for x and y values<commit_after>/* FLTKKeyboardWidget.hpp: Copyright (C) 2006 Steven Yi This file is part of Csound. The Csound 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. Csound 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 Csound; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "FLTKKeyboardWidget.hpp" static void allNotesOff(Fl_Widget *widget, void * v) { FLTKKeyboardWidget *win = (FLTKKeyboardWidget *)v; win->keyboard->allNotesOff(); } static void channelChange(Fl_Widget *widget, void * v) { Fl_Spinner *spinner = (Fl_Spinner *)widget; FLTKKeyboardWidget *win = (FLTKKeyboardWidget *)v; win->lock(); int channel = (int)spinner->value() - 1; win->keyboardMapping->setCurrentChannel(channel); win->bankChoice->value(win->keyboardMapping->getCurrentBank()); win->setProgramNames(); win->unlock(); } static void bankChange(Fl_Widget *widget, void * v) { Fl_Choice *choice = (Fl_Choice *)widget; FLTKKeyboardWidget *win = (FLTKKeyboardWidget *)v; win->lock(); win->keyboardMapping->setCurrentBank((int)choice->value()); win->setProgramNames(); win->unlock(); } static void programChange(Fl_Widget *widget, void * v) { Fl_Choice *choice = (Fl_Choice *)widget; FLTKKeyboardWidget *win = (FLTKKeyboardWidget *)v; win->lock(); win->keyboardMapping->setCurrentProgram((int)choice->value()); win->unlock(); } FLTKKeyboardWidget::FLTKKeyboardWidget(CSOUND *csound, const char *deviceMap, int X, int Y) : Fl_Group(X, Y, 624, 120) { this->csound = csound; this->mutex = csound->Create_Mutex(0); this->keyboardMapping = new KeyboardMapping(csound, deviceMap); this->begin(); int baseX = this->x(); int baseY = this->y(); int row1 = baseY; int row2 = row1 + 20; int row3 = row2 + 20; this->channelSpinner = new Fl_Spinner(baseX + 60, row1, 80, 20, "Channel"); channelSpinner->maximum(16); channelSpinner->minimum(1); this->channelSpinner->callback((Fl_Callback*) channelChange, this); this->bankChoice = new Fl_Choice(baseX + 180, row1, 180, 20, "Bank"); this->programChoice = new Fl_Choice(baseX + 420, row1, 200, 20, "Program"); bankChoice->clear(); for(unsigned int i = 0; i < keyboardMapping->banks.size(); i++) { bankChoice->add(keyboardMapping->banks[i]->name); } bankChoice->value(0); setProgramNames(); this->bankChoice->callback((Fl_Callback*)bankChange, this); this->programChoice->callback((Fl_Callback*)programChange, this); this->allNotesOffButton = new Fl_Button(baseX, row2, 623, 20, "All Notes Off"); this->allNotesOffButton->callback((Fl_Callback*) allNotesOff, this); this->keyboard = new FLTKKeyboard(csound, baseX, row3, 624, 80, "Keyboard"); this->end(); } FLTKKeyboardWidget::~FLTKKeyboardWidget() { if (mutex) { csound->DestroyMutex(mutex); mutex = (void*) 0; } delete keyboardMapping; } void FLTKKeyboardWidget::setProgramNames() { Bank* bank = keyboardMapping->banks[keyboardMapping->getCurrentBank()]; programChoice->clear(); for( vector<Program>::iterator iter = bank->programs.begin(); iter != bank->programs.end(); iter++ ) { programChoice->add((*iter).name); } programChoice->value(bank->currentProgram); } int FLTKKeyboardWidget::handle(int event) { switch(event) { case FL_KEYDOWN: return this->keyboard->handle(event); case FL_KEYUP: return this->keyboard->handle(event); // case FL_DEACTIVATE: // this->keyboard->allNotesOff(); // csound->Message(csound, "Deactivate\n"); // return 1; default: // this->csound->Message(this->csound, "Keyboard event: %d\n", event); return Fl_Group::handle(event); } } void FLTKKeyboardWidget::lock() { if(mutex) { csound->LockMutex(mutex); } } void FLTKKeyboardWidget::unlock() { if(mutex) { csound->UnlockMutex(mutex); } } <|endoftext|>
<commit_before> /** * * Copyright (C) 2013 - 2014 Jolla Ltd. * Contact: Thomas Perl <thomas.perl@jollamobile.com> * All rights reserved. * * This file is part of libsailfishapp * * You may use this file 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. * * 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 * and appearing in the file license.lgpl included in the packaging * of this file. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * **/ #include "sailfishapp.h" #include "sailfishapp_priv.h" #include <QtGlobal> #include <QGuiApplication> #include <QScopedPointer> #include <QScreen> #include <QSize> #include <QQuickView> #include <QString> #include <QDir> #include <QQmlEngine> namespace SailfishApp { QGuiApplication *application(int &argc, char **argv) { static QGuiApplication *app = NULL; if (app == NULL) { app = SailfishAppPriv::application(argc, argv); } else { qWarning("SailfishApp::application() called multiple times"); } return app; } QQuickView *createView() { QQuickWindow::setDefaultAlphaBuffer(true); QQuickView *view = SailfishAppPriv::view(); // Add import path to allow private QML import modules in /usr/share/<name>/ view->engine()->addImportPath(SailfishAppPriv::dataDir()); return view; } QUrl pathTo(const QString &filename) { return QUrl::fromLocalFile(QDir::cleanPath(QString("%1/%2") .arg(SailfishAppPriv::dataDir()) .arg(filename))); } QUrl pathToMainQml() { QString mainQml = QString("qml/%1.qml").arg(SailfishAppPriv::appName()); return pathTo(mainQml); } int main(int &argc, char **argv) { QScopedPointer<QGuiApplication> app(SailfishApp::application(argc, argv)); QScopedPointer<QQuickView> view(SailfishApp::createView()); view->setSource(SailfishApp::pathToMainQml()); view->show(); return app->exec(); } }; /* namespace SailfishApp */ <commit_msg>[libsailfishapp] Resize root object to the view size. Fixes JB#40253<commit_after> /** * * Copyright (C) 2013 - 2014 Jolla Ltd. * Contact: Thomas Perl <thomas.perl@jollamobile.com> * All rights reserved. * * This file is part of libsailfishapp * * You may use this file 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. * * 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 * and appearing in the file license.lgpl included in the packaging * of this file. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * **/ #include "sailfishapp.h" #include "sailfishapp_priv.h" #include <QtGlobal> #include <QGuiApplication> #include <QScopedPointer> #include <QScreen> #include <QSize> #include <QQuickView> #include <QString> #include <QDir> #include <QQmlEngine> namespace SailfishApp { QGuiApplication *application(int &argc, char **argv) { static QGuiApplication *app = NULL; if (app == NULL) { app = SailfishAppPriv::application(argc, argv); } else { qWarning("SailfishApp::application() called multiple times"); } return app; } QQuickView *createView() { QQuickWindow::setDefaultAlphaBuffer(true); QQuickView *view = SailfishAppPriv::view(); // Add import path to allow private QML import modules in /usr/share/<name>/ view->engine()->addImportPath(SailfishAppPriv::dataDir()); view->setResizeMode(QQuickView::SizeRootObjectToView); return view; } QUrl pathTo(const QString &filename) { return QUrl::fromLocalFile(QDir::cleanPath(QString("%1/%2") .arg(SailfishAppPriv::dataDir()) .arg(filename))); } QUrl pathToMainQml() { QString mainQml = QString("qml/%1.qml").arg(SailfishAppPriv::appName()); return pathTo(mainQml); } int main(int &argc, char **argv) { QScopedPointer<QGuiApplication> app(SailfishApp::application(argc, argv)); QScopedPointer<QQuickView> view(SailfishApp::createView()); view->setSource(SailfishApp::pathToMainQml()); view->show(); return app->exec(); } }; /* namespace SailfishApp */ <|endoftext|>
<commit_before>#pragma once #include <type_traits> #include "ksp_plugin/plugin.hpp" // DLL-exported functions for interfacing with Platform Invocation Services. #if defined(DLLEXPORT) #error "DLLEXPORT already defined" #else #if defined(_WIN32) #define DLLEXPORT __declspec(dllexport) #else #define DLLEXPORT __attribute__((visibility("default"))) #endif #endif namespace principia { namespace ksp_plugin { extern "C" struct XYZ { double x, y, z; }; static_assert(std::is_standard_layout<XYZ>::value, "XYZ is used for interfacing"); // Sets stderr to log INFO, and redirects stderr, which Unity does not log, to // "<KSP directory>/stderr.log". This provides an easily accessible file // containing a sufficiently verbose log of the latest session, instead of // requiring users to dig in the archive of all past logs at all severities. // This archive is written to // "<KSP directory>/glog/Principia/<SEVERITY>.<date>-<time>.<pid>", // where date and time are in ISO 8601 basic format. // TODO(egg): libglog should really be statically linked, what happens if two // plugins use glog? extern "C" DLLEXPORT void InitGoogleLogging(); // Exports |LOG(SEVERITY) << message| for fast logging from the C# adapter. // This will always evaluate its argument even if the corresponding log severity // is disabled, so it is less efficient than LOG(INFO). It will not report the // line and file of the caller. extern "C" DLLEXPORT void LogInfo(char const* message); extern "C" DLLEXPORT void LogWarning(char const* message); extern "C" DLLEXPORT void LogError(char const* message); extern "C" DLLEXPORT void LogFatal(char const* message); // Returns a pointer to a plugin constructed with the arguments given. // The caller takes ownership of the result. extern "C" DLLEXPORT Plugin* NewPlugin(double const initial_time, int const sun_index, double const sun_gravitational_parameter, double const planetarium_rotation_in_degrees); // Deletes and nulls |*plugin|. // |plugin| should not be null. No transfer of ownership of |*plugin|, // takes ownership of |**plugin|. extern "C" DLLEXPORT void DeletePlugin(Plugin const** const plugin); // Calls |plugin->InsertCelestial| with the arguments given. // |plugin| should not be null. No transfer of ownership. extern "C" DLLEXPORT void InsertCelestial(Plugin* const plugin, int const celestial_index, double const gravitational_parameter, int const parent_index, XYZ const from_parent_position, XYZ const from_parent_velocity); // Calls |plugin->UpdateCelestialHierarchy| with the arguments given. // |plugin| should not be null. No transfer of ownership. extern "C" DLLEXPORT void UpdateCelestialHierarchy(Plugin const* const plugin, int const celestial_index, int const parent_index); // Calls |plugin->InsertOrKeepVessel| with the arguments given. // |plugin| should not be null. No transfer of ownership. extern "C" DLLEXPORT void InsertOrKeepVessel(Plugin* const plugin, char const* vessel_guid, int const parent_index); // Calls |plugin->SetVesselStateOffset| with the arguments given. // |plugin| should not be null. No transfer of ownership. extern "C" DLLEXPORT void SetVesselStateOffset(Plugin const* const plugin, char const* vessel_guid, XYZ const from_parent_position, XYZ const from_parent_velocity); // Calls |plugin->VesselDisplacementFromParent| with the arguments given. // |plugin| should not be null. No transfer of ownership. extern "C" DLLEXPORT XYZ VesselDisplacementFromParent(Plugin const* const plugin, char const* vessel_guid); // Calls |plugin->VesselParentRelativeVelocity| with the arguments given. // |plugin| should not be null. No transfer of ownership. extern "C" DLLEXPORT XYZ VesselParentRelativeVelocity(Plugin const* const plugin, char const* vessel_guid); // Calls |plugin->CelestialDisplacementFromParent| with the arguments given. // |plugin| should not be null. No transfer of ownership. extern "C" DLLEXPORT XYZ CelestialDisplacementFromParent(Plugin const* const plugin, int const celestial_index); // Calls |plugin->CelestialParentRelativeVelocity| with the arguments given. // |plugin| should not be null. No transfer of ownership. extern "C" DLLEXPORT XYZ CelestialParentRelativeVelocity(Plugin const* const plugin, int const celestial_index); // Says hello, convenient for checking that calls to the DLL work. extern "C" DLLEXPORT char const* SayHello(); } // namespace ksp_plugin } // namespace principia #undef DLLEXPORT <commit_msg>cdecl<commit_after>#pragma once #include <type_traits> #include "ksp_plugin/plugin.hpp" // DLL-exported functions for interfacing with Platform Invocation Services. #if defined(DLLEXPORT) #error "DLLEXPORT already defined" #elif defined(CDECL) #error "CDECL already defined" #else #if defined(_WIN32) || defined(_WIN64) #define DLLEXPORT __declspec(dllexport) #else #define DLLEXPORT __attribute__((visibility("default"))) #endif // Architecture macros from http://goo.gl/ZypnO8. // We use cdecl on x86, the calling convention is unambiguous on x86-64. #if defined(__i386) || defined(_M_IX86) #if defined(_MSC_VER) || defined(__clang__) #define CDECL __cdecl #elif defined(__GNUC__) || defined(__INTEL_COMPILER) #define CDECL __attribute__((cdecl)) #else #error "Get a real compiler" #endif #elif defined(_M_X64) || defined(__x86_64__) #define CDECL #else #error "Have you tried a Cray-1?" #endif #endif namespace principia { namespace ksp_plugin { extern "C" struct XYZ { double x, y, z; }; static_assert(std::is_standard_layout<XYZ>::value, "XYZ is used for interfacing"); // Sets stderr to log INFO, and redirects stderr, which Unity does not log, to // "<KSP directory>/stderr.log". This provides an easily accessible file // containing a sufficiently verbose log of the latest session, instead of // requiring users to dig in the archive of all past logs at all severities. // This archive is written to // "<KSP directory>/glog/Principia/<SEVERITY>.<date>-<time>.<pid>", // where date and time are in ISO 8601 basic format. // TODO(egg): libglog should really be statically linked, what happens if two // plugins use glog? extern "C" DLLEXPORT void CDECL InitGoogleLogging(); // Exports |LOG(SEVERITY) << message| for fast logging from the C# adapter. // This will always evaluate its argument even if the corresponding log severity // is disabled, so it is less efficient than LOG(INFO). It will not report the // line and file of the caller. extern "C" DLLEXPORT void CDECL LogInfo(char const* message); extern "C" DLLEXPORT void CDECL LogWarning(char const* message); extern "C" DLLEXPORT void CDECL LogError(char const* message); extern "C" DLLEXPORT void CDECL LogFatal(char const* message); // Returns a pointer to a plugin constructed with the arguments given. // The caller takes ownership of the result. extern "C" DLLEXPORT Plugin* CDECL NewPlugin(double const initial_time, int const sun_index, double const sun_gravitational_parameter, double const planetarium_rotation_in_degrees); // Deletes and nulls |*plugin|. // |plugin| should not be null. No transfer of ownership of |*plugin|, // takes ownership of |**plugin|. extern "C" DLLEXPORT void CDECL DeletePlugin(Plugin const** const plugin); // Calls |plugin->InsertCelestial| with the arguments given. // |plugin| should not be null. No transfer of ownership. extern "C" DLLEXPORT void CDECL InsertCelestial(Plugin* const plugin, int const celestial_index, double const gravitational_parameter, int const parent_index, XYZ const from_parent_position, XYZ const from_parent_velocity); // Calls |plugin->UpdateCelestialHierarchy| with the arguments given. // |plugin| should not be null. No transfer of ownership. extern "C" DLLEXPORT void CDECL UpdateCelestialHierarchy(Plugin const* const plugin, int const celestial_index, int const parent_index); // Calls |plugin->InsertOrKeepVessel| with the arguments given. // |plugin| should not be null. No transfer of ownership. extern "C" DLLEXPORT void CDECL InsertOrKeepVessel(Plugin* const plugin, char const* vessel_guid, int const parent_index); // Calls |plugin->SetVesselStateOffset| with the arguments given. // |plugin| should not be null. No transfer of ownership. extern "C" DLLEXPORT void CDECL SetVesselStateOffset(Plugin const* const plugin, char const* vessel_guid, XYZ const from_parent_position, XYZ const from_parent_velocity); // Calls |plugin->VesselDisplacementFromParent| with the arguments given. // |plugin| should not be null. No transfer of ownership. extern "C" DLLEXPORT XYZ CDECL VesselDisplacementFromParent(Plugin const* const plugin, char const* vessel_guid); // Calls |plugin->VesselParentRelativeVelocity| with the arguments given. // |plugin| should not be null. No transfer of ownership. extern "C" DLLEXPORT XYZ CDECL VesselParentRelativeVelocity(Plugin const* const plugin, char const* vessel_guid); // Calls |plugin->CelestialDisplacementFromParent| with the arguments given. // |plugin| should not be null. No transfer of ownership. extern "C" DLLEXPORT XYZ CDECL CelestialDisplacementFromParent(Plugin const* const plugin, int const celestial_index); // Calls |plugin->CelestialParentRelativeVelocity| with the arguments given. // |plugin| should not be null. No transfer of ownership. extern "C" DLLEXPORT XYZ CDECL CelestialParentRelativeVelocity(Plugin const* const plugin, int const celestial_index); // Says hello, convenient for checking that calls to the DLL work. extern "C" DLLEXPORT char const* CDECL SayHello(); } // namespace ksp_plugin } // namespace principia #undef DLLEXPORT #undef CDECL <|endoftext|>
<commit_before>// NanoWin32 // ----------------------------------------------------------------------- // Simple library to subset Win32(64) API functions implemenation on POSIX // This software distributed by MIT license // ShellEx functions #include "NanoWinShellEx.h" #include "NanoWinError.h" #include "NanoWinFileSys.h" NW_EXTERN_C_BEGIN extern int SHCreateDirectoryExW ( HWND hwnd, LPCWSTR pszPath, const SECURITY_ATTRIBUTES *psa ) { // TODO: Refine implemenation (create folders among full path) // Error codes: (at least): [see doc] // ERROR_SUCCESS: // ERROR_FILE_EXISTS: // ERROR_ALREADY_EXISTS: if (hwnd != NULL) { return(NanoWinSetLastError(NW_DEFAULT_ERROR_AT_FAIL)); } if (CreateDirectoryW(pszPath, const_cast<SECURITY_ATTRIBUTES*>(psa))) { return(ERROR_SUCCESS); } else if (GetLastError() != ERROR_SUCCESS) { return(GetLastError()); } else // GetLastError() not set, but we have failed to action { return(NanoWinSetLastError(NW_DEFAULT_ERROR_AT_FAIL)); } } extern int SHCreateDirectoryExA ( HWND hwnd, LPCSTR pszPath, const SECURITY_ATTRIBUTES *psa ) { // TODO: Refine implemenation (create folders among full path) // Error codes: (at least): [see doc] // ERROR_SUCCESS: // ERROR_FILE_EXISTS: // ERROR_ALREADY_EXISTS: if (hwnd != NULL) { return(NanoWinSetLastError(NW_DEFAULT_ERROR_AT_FAIL)); } if (CreateDirectoryA(pszPath, const_cast<SECURITY_ATTRIBUTES*>(psa))) { return(ERROR_SUCCESS); } else if (GetLastError() != ERROR_SUCCESS) { return(GetLastError()); } else // GetLastError() not set, but we have failed to action { return(NanoWinSetLastError(NW_DEFAULT_ERROR_AT_FAIL)); } } NW_EXTERN_C_END <commit_msg>intermediate subdirs creation support added to SHCreateDirectoryEx function<commit_after>// NanoWin32 // ----------------------------------------------------------------------- // Simple library to subset Win32(64) API functions implemenation on POSIX // This software distributed by MIT license // ShellEx functions #include <string.h> #include "NanoWinShellEx.h" #include "NanoWinError.h" #include "NanoWinFileSys.h" #include "NanoWinStrConvert.h" #define NanoWinShellExDirSepChar ('/') #define NanoWinShellExDirSepAltChar ('\\') NW_EXTERN_C_BEGIN extern int SHCreateDirectoryExW ( HWND hwnd, LPCWSTR pszPath, const SECURITY_ATTRIBUTES *psa ) { try { return SHCreateDirectoryExA(hwnd,NanoWin::StrConverter::Convert(pszPath).c_str(),psa); } catch (NanoWin::StrConverter::Error) { SetLastError(ERROR_NO_UNICODE_TRANSLATION); return ERROR_NO_UNICODE_TRANSLATION; } } // returns either position of found char or strlen(str) if char wasn't found static size_t StrFindChars(const char *str, char ch, char altCh) { const char *ptr = str; while (*ptr != '\0' && *ptr != ch && *ptr != altCh) { ptr++; } return (size_t)(ptr - str); } extern int SHCreateDirectoryExA ( HWND hwnd, LPCSTR pszPath, const SECURITY_ATTRIBUTES *psa ) { // Error codes: (at least): [see doc] // ERROR_SUCCESS: // ERROR_FILE_EXISTS: // ERROR_ALREADY_EXISTS: constexpr size_t PATH_MAX_LEN = (248 - 1); // according to MS documentation if (hwnd != NULL) { return(NanoWinSetLastError(NW_DEFAULT_ERROR_AT_FAIL)); } bool ok = true; size_t sepPos = StrFindChars(pszPath,NanoWinShellExDirSepChar,NanoWinShellExDirSepAltChar); if (pszPath[sepPos] != '\0') { // subdirs(or absolute path) found in path, need to check if parent dirs need to be created char subPath[PATH_MAX_LEN + 1]; if (sepPos < PATH_MAX_LEN) { memcpy(subPath,pszPath,sepPos); subPath[sepPos] = NanoWinShellExDirSepChar; subPath[++sepPos] = '\0'; size_t startPos = 0; bool pathExists = false; // sepPos points to the char after separator // subPath contains current path prefix with trailing path separator (if any) do { pathExists = PathFileExistsA(subPath); if (!pathExists) { ok = CreateDirectoryA(subPath, const_cast<SECURITY_ATTRIBUTES*>(psa)); } if (ok) { startPos = sepPos; if (pszPath[startPos] != '\0') { sepPos += StrFindChars(&pszPath[startPos],NanoWinShellExDirSepChar,NanoWinShellExDirSepAltChar); memcpy(&subPath[startPos],&pszPath[startPos],sepPos - startPos + 1); if (subPath[sepPos] != '\0') { subPath[sepPos] = NanoWinShellExDirSepChar; subPath[++sepPos] = '\0'; } } } } while (ok && pszPath[startPos] != '\0'); if (ok && pathExists) { ok = false; SetLastError(ERROR_ALREADY_EXISTS); } } else { ok = false; SetLastError(ERROR_FILENAME_EXCED_RANGE); } } else { // no subdirs found in path, just create directory ok = CreateDirectoryA(pszPath, const_cast<SECURITY_ATTRIBUTES*>(psa)); } if (ok) { return(ERROR_SUCCESS); } else if (GetLastError() != ERROR_SUCCESS) { return(GetLastError()); } else // GetLastError() not set, but we have failed to action { return(NanoWinSetLastError(NW_DEFAULT_ERROR_AT_FAIL)); } } NW_EXTERN_C_END <|endoftext|>
<commit_before>#define BOOST_TEST_MODULE TestImpedanceSpectroscopy #define BOOST_TEST_MAIN #include <cap/energy_storage_device.h> #include <boost/format.hpp> #include <boost/foreach.hpp> #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/xml_parser.hpp> #include <boost/math/constants/constants.hpp> #include <boost/test/unit_test.hpp> #include <gsl/gsl_fft_real.h> #include <iostream> #include <fstream> #include <complex> namespace cap { std::complex<double> measure_impedance(std::shared_ptr<cap::EnergyStorageDevice> dev, std::shared_ptr<boost::property_tree::ptree const> database); std::complex<double> measure_impedance(std::shared_ptr<cap::EnergyStorageDevice> dev, std::shared_ptr<boost::property_tree::ptree const> database) { double const frequency = database->get<double>("frequency" ); double const amplitude = database->get<double>("amplitude" ); int const cycles = database->get<int >("cycles" ); int const steps_per_cycle = database->get<int >("steps_per_cycle"); double const initial_voltage = 0.0; std::vector<int> const powers_of_two = { 1, 2 ,4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536, 131072, 262144, 524288 }; // first 20 powers of two if (find(powers_of_two.begin(), powers_of_two.end(), (cycles-1)*steps_per_cycle) == powers_of_two.end()) throw std::runtime_error("(cycles-1)*steps_per_cycle must be a power of two"); double time = 0.0; double const time_step = 1.0 / frequency / steps_per_cycle; double const phase = std::asin(initial_voltage / amplitude); double const pi = std::acos(-1.0); double const angular_frequency = 2.0 * pi * frequency; dev->reset_voltage(initial_voltage); double voltage; double current; std::vector<double> excitation; std::vector<double> response; for (int n = 0; n < cycles*steps_per_cycle; ++n) { time += time_step; voltage = amplitude * std::sin(angular_frequency * time + phase); dev->evolve_one_time_step_changing_voltage(time_step, voltage); dev->get_current(current); if (n >= steps_per_cycle) { excitation.push_back(voltage); response .push_back(current); } } gsl_fft_real_radix2_transform(&(excitation[0]), 1, excitation.size()); gsl_fft_real_radix2_transform(&(response [0]), 1, response .size()); std::complex<double> const impedance = std::complex<double>(excitation[(cycles-1)], excitation[excitation.size()-(cycles-1)]) / std::complex<double>(response [(cycles-1)], response [response .size()-(cycles-1)]); return impedance; } void impedance_spectroscopy(std::shared_ptr<cap::EnergyStorageDevice> dev, std::shared_ptr<boost::property_tree::ptree const> database, std::ostream & os = std::cout) { double const frequency_lower_limit = database->get<double>("frequency_lower_limit"); double const frequency_upper_limit = database->get<double>("frequency_upper_limit"); double const ratio = database->get<double>("ratio" ); double const pi = boost::math::constants::pi<double>(); std::shared_ptr<boost::property_tree::ptree> tmp = std::make_shared<boost::property_tree::ptree>(*database); for (double frequency = frequency_lower_limit; frequency <= frequency_upper_limit; frequency *= ratio) { tmp->put("frequency", frequency); std::complex<double> impedance = measure_impedance(dev, tmp); os<<boost::format( " %20.15e %20.15e %20.15e %20.15e %20.15e \n") % frequency % impedance.real() % impedance.imag() % std::abs(impedance) % (std::arg(impedance) * 180.0 / pi) ; } } } // end namespace cap BOOST_AUTO_TEST_CASE( test_measure_impedance ) { // parse input file std::shared_ptr<boost::property_tree::ptree> input_database = std::make_shared<boost::property_tree::ptree>(); read_xml("input_impedance_spectroscopy", *input_database); std::string const type = input_database->get<std::string>("device.type"); // current test will only work for series or parallel rc circuit if ((type.compare("SeriesRC") != 0) && (type.compare("ParallelRC") != 0)) throw std::runtime_error("test measure impedance check not implemented for "+type); // build an energy storage system std::shared_ptr<boost::property_tree::ptree> device_database = std::make_shared<boost::property_tree::ptree>(input_database->get_child("device")); std::shared_ptr<cap::EnergyStorageDevice> device = cap::buildEnergyStorageDevice(std::make_shared<cap::Parameters>(device_database)); double const frequency_lower_limit = input_database->get<double>("impedance_spectroscopy.frequency_lower_limit"); double const frequency_upper_limit = input_database->get<double>("impedance_spectroscopy.frequency_upper_limit"); double const ratio = input_database->get<double>("impedance_spectroscopy.ratio" ); double const percent_tolerance = input_database->get<double>("impedance_spectroscopy.percent_tolerance" ); double const series_resistance = input_database->get<double>("device.series_resistance" ); double const parallel_resistance = input_database->get<double>("device.parallel_resistance" ); double const capacitance = input_database->get<double>("device.capacitance" ); double const pi = boost::math::constants::pi<double>(); std::shared_ptr<boost::property_tree::ptree> impedance_spectroscopy_database = std::make_shared<boost::property_tree::ptree>(input_database->get_child("impedance_spectroscopy")); std::fstream fout("computed_vs_exact_impedance_spectroscopy_data", std::fstream::out); for (double frequency = frequency_lower_limit; frequency < frequency_upper_limit; frequency *= ratio) { double const angular_frequency = 2.0 * pi * frequency; impedance_spectroscopy_database->put("frequency", frequency); std::complex<double> computed_impedance = cap::measure_impedance(device, impedance_spectroscopy_database); std::complex<double> exact_impedance = ( (type.compare("SeriesRC") == 0) ? series_resistance + 1.0 / std::complex<double>(0.0, capacitance * angular_frequency) : series_resistance + parallel_resistance / std::complex<double>(1.0, parallel_resistance * capacitance * angular_frequency) ); fout<<boost::format(" %22.15e %22.15e %22.15e %22.15e %22.15e %22.15e %22.15e %22.15e %22.15e \n") % frequency % computed_impedance.real() % computed_impedance.imag() % std::abs(computed_impedance) % (std::arg(computed_impedance) * 180.0 / pi) % exact_impedance.real() % exact_impedance.imag() % std::abs(exact_impedance) % (std::arg(exact_impedance) * 180.0 / pi) ; // BOOST_CHECK_CLOSE(computed_impedance.real(), exact_impedance.real(), percent_tolerance); // BOOST_CHECK_CLOSE(computed_impedance.imag(), exact_impedance.imag(), percent_tolerance); BOOST_CHECK_CLOSE(std::abs(computed_impedance), std::abs(exact_impedance), percent_tolerance); BOOST_CHECK_CLOSE(std::arg(computed_impedance), std::arg(exact_impedance), percent_tolerance); } } BOOST_AUTO_TEST_CASE( test_impedance_spectroscopy ) { // parse input file std::shared_ptr<boost::property_tree::ptree> input_database = std::make_shared<boost::property_tree::ptree>(); read_xml("input_impedance_spectroscopy", *input_database); // build an energy storage system std::shared_ptr<boost::property_tree::ptree> device_database = std::make_shared<boost::property_tree::ptree>(input_database->get_child("device")); std::shared_ptr<cap::EnergyStorageDevice> device = cap::buildEnergyStorageDevice(std::make_shared<cap::Parameters>(device_database)); // measure its impedance std::fstream fout; fout.open("impedance_spectroscopy_data", std::fstream::out); std::shared_ptr<boost::property_tree::ptree> impedance_spectroscopy_database = std::make_shared<boost::property_tree::ptree>(input_database->get_child("impedance_spectroscopy")); cap::impedance_spectroscopy(device, impedance_spectroscopy_database, fout); } <commit_msg>removed useless forward declaration<commit_after>#define BOOST_TEST_MODULE TestImpedanceSpectroscopy #define BOOST_TEST_MAIN #include <cap/energy_storage_device.h> #include <boost/format.hpp> #include <boost/foreach.hpp> #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/xml_parser.hpp> #include <boost/math/constants/constants.hpp> #include <boost/test/unit_test.hpp> #include <gsl/gsl_fft_real.h> #include <iostream> #include <fstream> #include <complex> namespace cap { std::complex<double> measure_impedance(std::shared_ptr<cap::EnergyStorageDevice> dev, std::shared_ptr<boost::property_tree::ptree const> database) { double const frequency = database->get<double>("frequency" ); double const amplitude = database->get<double>("amplitude" ); int const cycles = database->get<int >("cycles" ); int const steps_per_cycle = database->get<int >("steps_per_cycle"); double const initial_voltage = 0.0; std::vector<int> const powers_of_two = { 1, 2 ,4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536, 131072, 262144, 524288 }; // first 20 powers of two if (find(powers_of_two.begin(), powers_of_two.end(), (cycles-1)*steps_per_cycle) == powers_of_two.end()) throw std::runtime_error("(cycles-1)*steps_per_cycle must be a power of two"); double time = 0.0; double const time_step = 1.0 / frequency / steps_per_cycle; double const phase = std::asin(initial_voltage / amplitude); double const pi = std::acos(-1.0); double const angular_frequency = 2.0 * pi * frequency; dev->reset_voltage(initial_voltage); double voltage; double current; std::vector<double> excitation; std::vector<double> response; for (int n = 0; n < cycles*steps_per_cycle; ++n) { time += time_step; voltage = amplitude * std::sin(angular_frequency * time + phase); dev->evolve_one_time_step_changing_voltage(time_step, voltage); dev->get_current(current); if (n >= steps_per_cycle) { excitation.push_back(voltage); response .push_back(current); } } gsl_fft_real_radix2_transform(&(excitation[0]), 1, excitation.size()); gsl_fft_real_radix2_transform(&(response [0]), 1, response .size()); std::complex<double> const impedance = std::complex<double>(excitation[(cycles-1)], excitation[excitation.size()-(cycles-1)]) / std::complex<double>(response [(cycles-1)], response [response .size()-(cycles-1)]); return impedance; } void impedance_spectroscopy(std::shared_ptr<cap::EnergyStorageDevice> dev, std::shared_ptr<boost::property_tree::ptree const> database, std::ostream & os = std::cout) { double const frequency_lower_limit = database->get<double>("frequency_lower_limit"); double const frequency_upper_limit = database->get<double>("frequency_upper_limit"); double const ratio = database->get<double>("ratio" ); double const pi = boost::math::constants::pi<double>(); std::shared_ptr<boost::property_tree::ptree> tmp = std::make_shared<boost::property_tree::ptree>(*database); for (double frequency = frequency_lower_limit; frequency <= frequency_upper_limit; frequency *= ratio) { tmp->put("frequency", frequency); std::complex<double> impedance = measure_impedance(dev, tmp); os<<boost::format( " %20.15e %20.15e %20.15e %20.15e %20.15e \n") % frequency % impedance.real() % impedance.imag() % std::abs(impedance) % (std::arg(impedance) * 180.0 / pi) ; } } } // end namespace cap BOOST_AUTO_TEST_CASE( test_measure_impedance ) { // parse input file std::shared_ptr<boost::property_tree::ptree> input_database = std::make_shared<boost::property_tree::ptree>(); read_xml("input_impedance_spectroscopy", *input_database); std::string const type = input_database->get<std::string>("device.type"); // current test will only work for series or parallel rc circuit if ((type.compare("SeriesRC") != 0) && (type.compare("ParallelRC") != 0)) throw std::runtime_error("test measure impedance check not implemented for "+type); // build an energy storage system std::shared_ptr<boost::property_tree::ptree> device_database = std::make_shared<boost::property_tree::ptree>(input_database->get_child("device")); std::shared_ptr<cap::EnergyStorageDevice> device = cap::buildEnergyStorageDevice(std::make_shared<cap::Parameters>(device_database)); double const frequency_lower_limit = input_database->get<double>("impedance_spectroscopy.frequency_lower_limit"); double const frequency_upper_limit = input_database->get<double>("impedance_spectroscopy.frequency_upper_limit"); double const ratio = input_database->get<double>("impedance_spectroscopy.ratio" ); double const percent_tolerance = input_database->get<double>("impedance_spectroscopy.percent_tolerance" ); double const series_resistance = input_database->get<double>("device.series_resistance" ); double const parallel_resistance = input_database->get<double>("device.parallel_resistance" ); double const capacitance = input_database->get<double>("device.capacitance" ); double const pi = boost::math::constants::pi<double>(); std::shared_ptr<boost::property_tree::ptree> impedance_spectroscopy_database = std::make_shared<boost::property_tree::ptree>(input_database->get_child("impedance_spectroscopy")); std::fstream fout("computed_vs_exact_impedance_spectroscopy_data", std::fstream::out); for (double frequency = frequency_lower_limit; frequency < frequency_upper_limit; frequency *= ratio) { double const angular_frequency = 2.0 * pi * frequency; impedance_spectroscopy_database->put("frequency", frequency); std::complex<double> computed_impedance = cap::measure_impedance(device, impedance_spectroscopy_database); std::complex<double> exact_impedance = ( (type.compare("SeriesRC") == 0) ? series_resistance + 1.0 / std::complex<double>(0.0, capacitance * angular_frequency) : series_resistance + parallel_resistance / std::complex<double>(1.0, parallel_resistance * capacitance * angular_frequency) ); fout<<boost::format(" %22.15e %22.15e %22.15e %22.15e %22.15e %22.15e %22.15e %22.15e %22.15e \n") % frequency % computed_impedance.real() % computed_impedance.imag() % std::abs(computed_impedance) % (std::arg(computed_impedance) * 180.0 / pi) % exact_impedance.real() % exact_impedance.imag() % std::abs(exact_impedance) % (std::arg(exact_impedance) * 180.0 / pi) ; // BOOST_CHECK_CLOSE(computed_impedance.real(), exact_impedance.real(), percent_tolerance); // BOOST_CHECK_CLOSE(computed_impedance.imag(), exact_impedance.imag(), percent_tolerance); BOOST_CHECK_CLOSE(std::abs(computed_impedance), std::abs(exact_impedance), percent_tolerance); BOOST_CHECK_CLOSE(std::arg(computed_impedance), std::arg(exact_impedance), percent_tolerance); } } BOOST_AUTO_TEST_CASE( test_impedance_spectroscopy ) { // parse input file std::shared_ptr<boost::property_tree::ptree> input_database = std::make_shared<boost::property_tree::ptree>(); read_xml("input_impedance_spectroscopy", *input_database); // build an energy storage system std::shared_ptr<boost::property_tree::ptree> device_database = std::make_shared<boost::property_tree::ptree>(input_database->get_child("device")); std::shared_ptr<cap::EnergyStorageDevice> device = cap::buildEnergyStorageDevice(std::make_shared<cap::Parameters>(device_database)); // measure its impedance std::fstream fout; fout.open("impedance_spectroscopy_data", std::fstream::out); std::shared_ptr<boost::property_tree::ptree> impedance_spectroscopy_database = std::make_shared<boost::property_tree::ptree>(input_database->get_child("impedance_spectroscopy")); cap::impedance_spectroscopy(device, impedance_spectroscopy_database, fout); } <|endoftext|>
<commit_before>/* Copyright (c) 2003, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <iostream> #include <fstream> #include <iterator> #include <exception> #include "libtorrent/entry.hpp" #include "libtorrent/bencode.hpp" #include "libtorrent/session.hpp" #include "libtorrent/http_settings.hpp" #ifdef WIN32 #include <conio.h> bool sleep_and_input(char* c) { Sleep(500); if (kbhit()) { *c = getch(); return true; } return false; }; #endif std::string add_suffix(float val) { const char* prefix[] = {"B", "kB", "MB", "GB", "TB"}; const int num_prefix = sizeof(prefix) / sizeof(const char*); int i; for (i = 0; i < num_prefix; ++i) { if (val < 1024.f) return boost::lexical_cast<std::string>(val) + prefix[i]; val /= 1024.f; } return boost::lexical_cast<std::string>(val) + prefix[i]; } int main(int argc, char* argv[]) { using namespace libtorrent; if (argc < 2) { std::cerr << "usage: ./client_test torrent-files ...\n" "to stop the client, type a number and press enter.\n"; return 1; } http_settings settings; // settings.proxy_ip = "192.168.0.1"; // settings.proxy_port = 80; // settings.proxy_login = "hyd"; // settings.proxy_password = "foobar"; settings.user_agent = "example"; try { std::vector<torrent_handle> handles; session s(6881, "E\x1"); s.set_http_settings(settings); for (int i = 0; i < argc-1; ++i) { try { std::ifstream in(argv[i+1], std::ios_base::binary); in.unsetf(std::ios_base::skipws); entry e = bdecode(std::istream_iterator<char>(in), std::istream_iterator<char>()); torrent_info t(e); t.print(std::cout); handles.push_back(s.add_torrent(t, "")); } catch (std::exception& e) { std::cout << e.what() << "\n"; } } std::vector<peer_info> peers; for (;;) { char c; if (sleep_and_input(&c)) { if (c == 'q') break; } for (std::vector<torrent_handle>::iterator i = handles.begin(); i != handles.end(); ++i) { torrent_status s = i->status(); switch(s.state) { case torrent_status::queued_for_checking: std::cout << "queued for checking: "; break; case torrent_status::checking_files: std::cout << "checking files: "; break; case torrent_status::downloading: std::cout << "downloading: "; break; case torrent_status::seeding: std::cout << "seeding: "; break; }; std::cout << s.progress*100 << "% "; // calculate download and upload speeds i->get_peer_info(peers); float down = 0.f; float up = 0.f; unsigned int total_down = 0; unsigned int total_up = 0; int num_peers = peers.size(); for (std::vector<peer_info>::iterator i = peers.begin(); i != peers.end(); ++i) { down += i->down_speed; up += i->up_speed; total_down += i->total_download; total_up += i->total_upload; } std::cout << "p:" << num_peers; std::cout << " d:(" << add_suffix(total_down) << ") " << add_suffix(down) << "/s up:(" << add_suffix(total_up) << ") " << add_suffix(up) << "/s\n"; } std::cout << "----\n"; } } catch (std::exception& e) { std::cout << e.what() << "\n"; } return 0; } <commit_msg>client_test now works on linux again.<commit_after>/* Copyright (c) 2003, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <iostream> #include <fstream> #include <iterator> #include <exception> #include "libtorrent/entry.hpp" #include "libtorrent/bencode.hpp" #include "libtorrent/session.hpp" #include "libtorrent/http_settings.hpp" #ifdef WIN32 #include <conio.h> bool sleep_and_input(char* c) { Sleep(500); if (kbhit()) { *c = getch(); return true; } return false; }; #else #include <stdlib.h> #include <stdio.h> #include <termios.h> #include <string.h> struct set_keypress { set_keypress() { termios new_settings; tcgetattr(0,&stored_settings); new_settings = stored_settings; // Disable canonical mode, and set buffer size to 1 byte new_settings.c_lflag &= (~ICANON); new_settings.c_cc[VTIME] = 0; new_settings.c_cc[VMIN] = 1; tcsetattr(0,TCSANOW,&new_settings); } ~set_keypress() { tcsetattr(0,TCSANOW,&stored_settings); } termios stored_settings; }; bool sleep_and_input(char* c) { // sets the terminal to single-character mode // and resets when destructed set_keypress s; fd_set set; FD_ZERO(&set); FD_SET(0, &set); timeval tv = {1, 0}; if (select(1, &set, 0, 0, &tv) > 0) { *c = getc(stdin); return true; } return false; } #endif std::string add_suffix(float val) { const char* prefix[] = {"B", "kB", "MB", "GB", "TB"}; const int num_prefix = sizeof(prefix) / sizeof(const char*); int i; for (i = 0; i < num_prefix; ++i) { if (val < 1024.f) return boost::lexical_cast<std::string>(val) + prefix[i]; val /= 1024.f; } return boost::lexical_cast<std::string>(val) + prefix[i]; } int main(int argc, char* argv[]) { using namespace libtorrent; if (argc < 2) { std::cerr << "usage: ./client_test torrent-files ...\n" "to stop the client, type a number and press enter.\n"; return 1; } http_settings settings; // settings.proxy_ip = "192.168.0.1"; // settings.proxy_port = 80; // settings.proxy_login = "hyd"; // settings.proxy_password = "foobar"; settings.user_agent = "example"; try { std::vector<torrent_handle> handles; session s(6881, "E\x1"); s.set_http_settings(settings); for (int i = 0; i < argc-1; ++i) { try { std::ifstream in(argv[i+1], std::ios_base::binary); in.unsetf(std::ios_base::skipws); entry e = bdecode(std::istream_iterator<char>(in), std::istream_iterator<char>()); torrent_info t(e); t.print(std::cout); handles.push_back(s.add_torrent(t, "")); } catch (std::exception& e) { std::cout << e.what() << "\n"; } } std::vector<peer_info> peers; for (;;) { char c; if (sleep_and_input(&c)) { if (c == 'q') break; } for (std::vector<torrent_handle>::iterator i = handles.begin(); i != handles.end(); ++i) { torrent_status s = i->status(); switch(s.state) { case torrent_status::queued_for_checking: std::cout << "queued for checking: "; break; case torrent_status::checking_files: std::cout << "checking files: "; break; case torrent_status::downloading: std::cout << "downloading: "; break; case torrent_status::seeding: std::cout << "seeding: "; break; }; std::cout << s.progress*100 << "% "; // calculate download and upload speeds i->get_peer_info(peers); float down = 0.f; float up = 0.f; unsigned int total_down = 0; unsigned int total_up = 0; int num_peers = peers.size(); for (std::vector<peer_info>::iterator i = peers.begin(); i != peers.end(); ++i) { down += i->down_speed; up += i->up_speed; total_down += i->total_download; total_up += i->total_upload; } std::cout << "p:" << num_peers; std::cout << " d:(" << add_suffix(total_down) << ") " << add_suffix(down) << "/s up:(" << add_suffix(total_up) << ") " << add_suffix(up) << "/s\n"; } std::cout << "----\n"; } } catch (std::exception& e) { std::cout << e.what() << "\n"; } return 0; } <|endoftext|>
<commit_before>// jemalloc C++ threaded test // Author: Rustam Abdullaev // Public Domain #include <atomic> #include <functional> #include <future> #include <random> #include <thread> #include <vector> #include <stdio.h> #include <jemalloc/jemalloc.h> #include <windows.h> using std::vector; using std::thread; using std::uniform_int_distribution; using std::minstd_rand; #if NDEBUG && JEMALLOC_ISSUE_318_WORKAROUND extern "C" JEMALLOC_EXPORT void _malloc_thread_cleanup(void); static thread_local struct JeMallocThreadHelper { ~JeMallocThreadHelper() { _malloc_thread_cleanup(); } } tls_jemallocThreadHelper; #endif int test_threads() { je_malloc_conf = "narenas:3"; int narenas = 0; size_t sz = sizeof(narenas); je_mallctl("opt.narenas", &narenas, &sz, NULL, 0); if (narenas != 3) { printf("Error: unexpected number of arenas: %d\n", narenas); return 1; } static const int sizes[] = { 7, 16, 32, 60, 91, 100, 120, 144, 169, 199, 255, 400, 670, 900, 917, 1025, 3333, 5190, 13131, 49192, 99999, 123123, 255265, 2333111 }; static const int numSizes = (int)(sizeof(sizes) / sizeof(sizes[0])); vector<thread> workers; static const int numThreads = narenas + 1, numAllocsMax = 25, numIter1 = 50, numIter2 = 50; je_malloc_stats_print(NULL, NULL, NULL); size_t allocated1; size_t sz1 = sizeof(allocated1); je_mallctl("stats.active", &allocated1, &sz1, NULL, 0); printf("\nPress Enter to start threads...\n"); getchar(); printf("Starting %d threads x %d x %d iterations...\n", numThreads, numIter1, numIter2); for (int i = 0; i < numThreads; i++) { workers.emplace_back([tid=i]() { uniform_int_distribution<int> sizeDist(0, numSizes - 1); minstd_rand rnd(tid * 17); uint8_t* ptrs[numAllocsMax]; int ptrsz[numAllocsMax]; for (int i = 0; i < numIter1; ++i) { thread t([&]() { for (int i = 0; i < numIter2; ++i) { const int numAllocs = numAllocsMax - sizeDist(rnd); for (int j = 0; j < numAllocs; j += 64) { const int x = sizeDist(rnd); const int sz = sizes[x]; ptrsz[j] = sz; ptrs[j] = (uint8_t*)je_malloc(sz); if (!ptrs[j]) { printf("Unable to allocate %d bytes in thread %d, iter %d, alloc %d. %d\n", sz, tid, i, j, x); exit(1); } for (int k = 0; k < sz; k++) ptrs[j][k] = tid + k; } for (int j = 0; j < numAllocs; j += 64) { for (int k = 0, sz = ptrsz[j]; k < sz; k++) if (ptrs[j][k] != (uint8_t)(tid + k)) { printf("Memory error in thread %d, iter %d, alloc %d @ %d : %02X!=%02X\n", tid, i, j, k, ptrs[j][k], (uint8_t)(tid + k)); exit(1); } je_free(ptrs[j]); } } }); t.join(); } }); } for (thread& t : workers) { t.join(); } je_malloc_stats_print(NULL, NULL, NULL); size_t allocated2; je_mallctl("stats.active", &allocated2, &sz1, NULL, 0); size_t leaked = allocated2 - allocated1; printf("\nDone. Leaked: %Id bytes\n", leaked); bool failed = leaked > 65536; // in case C++ runtime allocated something (e.g. iostream locale or facet) printf("\nTest %s!\n", (failed ? "FAILED" : "successful")); printf("\nPress Enter to continue...\n"); getchar(); return failed ? 1 : 0; } <commit_msg>Make test_threads more generic<commit_after>// jemalloc C++ threaded test // Author: Rustam Abdullaev // Public Domain #include <atomic> #include <functional> #include <future> #include <random> #include <thread> #include <vector> #include <stdio.h> #include <jemalloc/jemalloc.h> using std::vector; using std::thread; using std::uniform_int_distribution; using std::minstd_rand; int test_threads() { je_malloc_conf = "narenas:3"; int narenas = 0; size_t sz = sizeof(narenas); je_mallctl("opt.narenas", &narenas, &sz, NULL, 0); if (narenas != 3) { printf("Error: unexpected number of arenas: %d\n", narenas); return 1; } static const int sizes[] = { 7, 16, 32, 60, 91, 100, 120, 144, 169, 199, 255, 400, 670, 900, 917, 1025, 3333, 5190, 13131, 49192, 99999, 123123, 255265, 2333111 }; static const int numSizes = (int)(sizeof(sizes) / sizeof(sizes[0])); vector<thread> workers; static const int numThreads = narenas + 1, numAllocsMax = 25, numIter1 = 50, numIter2 = 50; je_malloc_stats_print(NULL, NULL, NULL); size_t allocated1; size_t sz1 = sizeof(allocated1); je_mallctl("stats.active", &allocated1, &sz1, NULL, 0); printf("\nPress Enter to start threads...\n"); getchar(); printf("Starting %d threads x %d x %d iterations...\n", numThreads, numIter1, numIter2); for (int i = 0; i < numThreads; i++) { workers.emplace_back([tid=i]() { uniform_int_distribution<int> sizeDist(0, numSizes - 1); minstd_rand rnd(tid * 17); uint8_t* ptrs[numAllocsMax]; int ptrsz[numAllocsMax]; for (int i = 0; i < numIter1; ++i) { thread t([&]() { for (int i = 0; i < numIter2; ++i) { const int numAllocs = numAllocsMax - sizeDist(rnd); for (int j = 0; j < numAllocs; j += 64) { const int x = sizeDist(rnd); const int sz = sizes[x]; ptrsz[j] = sz; ptrs[j] = (uint8_t*)je_malloc(sz); if (!ptrs[j]) { printf("Unable to allocate %d bytes in thread %d, iter %d, alloc %d. %d\n", sz, tid, i, j, x); exit(1); } for (int k = 0; k < sz; k++) ptrs[j][k] = tid + k; } for (int j = 0; j < numAllocs; j += 64) { for (int k = 0, sz = ptrsz[j]; k < sz; k++) if (ptrs[j][k] != (uint8_t)(tid + k)) { printf("Memory error in thread %d, iter %d, alloc %d @ %d : %02X!=%02X\n", tid, i, j, k, ptrs[j][k], (uint8_t)(tid + k)); exit(1); } je_free(ptrs[j]); } } }); t.join(); } }); } for (thread& t : workers) { t.join(); } je_malloc_stats_print(NULL, NULL, NULL); size_t allocated2; je_mallctl("stats.active", &allocated2, &sz1, NULL, 0); size_t leaked = allocated2 - allocated1; printf("\nDone. Leaked: %zd bytes\n", leaked); bool failed = leaked > 65536; // in case C++ runtime allocated something (e.g. iostream locale or facet) printf("\nTest %s!\n", (failed ? "FAILED" : "successful")); printf("\nPress Enter to continue...\n"); getchar(); return failed ? 1 : 0; } <|endoftext|>
<commit_before> #include "Globals.h" // NOTE: MSVC stupidness requires this to be the same across all modules #include "ChestEntity.h" #include "../Item.h" #include "../Entities/Player.h" #include "../UI/Window.h" #include "json/json.h" cChestEntity::cChestEntity(int a_BlockX, int a_BlockY, int a_BlockZ, cWorld * a_World) : super(E_BLOCK_CHEST, a_BlockX, a_BlockY, a_BlockZ, ContentsWidth, ContentsHeight, a_World) { cBlockEntityWindowOwner::SetBlockEntity(this); } cChestEntity::~cChestEntity() { cWindow * Window = GetWindow(); if (Window != NULL) { Window->OwnerDestroyed(); } } bool cChestEntity::LoadFromJson(const Json::Value & a_Value) { m_PosX = a_Value.get("x", 0).asInt(); m_PosY = a_Value.get("y", 0).asInt(); m_PosZ = a_Value.get("z", 0).asInt(); Json::Value AllSlots = a_Value.get("Slots", 0); int SlotIdx = 0; for (Json::Value::iterator itr = AllSlots.begin(); itr != AllSlots.end(); ++itr) { cItem Item; Item.FromJson(*itr); SetSlot(SlotIdx, Item); SlotIdx++; } return true; } void cChestEntity::SaveToJson(Json::Value & a_Value) { a_Value["x"] = m_PosX; a_Value["y"] = m_PosY; a_Value["z"] = m_PosZ; Json::Value AllSlots; for (int i = m_Contents.GetNumSlots() - 1; i >= 0; i--) { Json::Value Slot; m_Contents.GetSlot(i).GetJson(Slot); AllSlots.append(Slot); } a_Value["Slots"] = AllSlots; } void cChestEntity::SendTo(cClientHandle & a_Client) { // The chest entity doesn't need anything sent to the client when it's created / gets in the viewdistance // All the actual handling is in the cWindow UI code that gets called when the chest is rclked UNUSED(a_Client); } void cChestEntity::UsedBy(cPlayer * a_Player) { // If the window is not created, open it anew: cWindow * Window = GetWindow(); if (Window == NULL) { OpenNewWindow(); Window = GetWindow(); } // Open the window for the player: if (Window != NULL) { if (a_Player->GetWindow() != Window) { a_Player->OpenWindow(Window); } } // This is rather a hack // Instead of marking the chunk as dirty upon chest contents change, we mark it dirty now // We cannot properly detect contents change, but such a change doesn't happen without a player opening the chest first. // The few false positives aren't much to worry about int ChunkX, ChunkZ; cChunkDef::BlockToChunk(m_PosX, m_PosZ, ChunkX, ChunkZ); m_World->MarkChunkDirty(ChunkX, ChunkZ); } void cChestEntity::OpenNewWindow(void) { // Callback for opening together with neighbor chest: class cOpenDouble : public cChestCallback { cChestEntity * m_ThisChest; public: cOpenDouble(cChestEntity * a_ThisChest) : m_ThisChest(a_ThisChest) { } virtual bool Item(cChestEntity * a_Chest) override { // The primary chest should eb the one with lesser X or Z coord: cChestEntity * Primary = a_Chest; cChestEntity * Secondary = m_ThisChest; if ( (Primary->GetPosX() > Secondary->GetPosX()) || (Primary->GetPosZ() > Secondary->GetPosZ()) ) { std::swap(Primary, Secondary); } m_ThisChest->OpenWindow(new cChestWindow(Primary, Secondary)); return false; } } ; // Scan neighbors for adjacent chests: cOpenDouble OpenDbl(this); if ( m_World->DoWithChestAt(m_PosX - 1, m_PosY, m_PosZ, OpenDbl) || m_World->DoWithChestAt(m_PosX + 1, m_PosY, m_PosZ, OpenDbl) || m_World->DoWithChestAt(m_PosX , m_PosY, m_PosZ - 1, OpenDbl) || m_World->DoWithChestAt(m_PosX , m_PosY, m_PosZ + 1, OpenDbl) ) { // The double-chest window has been opened in the callback return; } // There is no chest neighbor, open a single-chest window: OpenWindow(new cChestWindow(this)); } <commit_msg>Chests don't open if obstructed<commit_after> #include "Globals.h" // NOTE: MSVC stupidness requires this to be the same across all modules #include "ChestEntity.h" #include "../Item.h" #include "../Entities/Player.h" #include "../UI/Window.h" #include "json/json.h" cChestEntity::cChestEntity(int a_BlockX, int a_BlockY, int a_BlockZ, cWorld * a_World) : super(E_BLOCK_CHEST, a_BlockX, a_BlockY, a_BlockZ, ContentsWidth, ContentsHeight, a_World) { cBlockEntityWindowOwner::SetBlockEntity(this); } cChestEntity::~cChestEntity() { cWindow * Window = GetWindow(); if (Window != NULL) { Window->OwnerDestroyed(); } } bool cChestEntity::LoadFromJson(const Json::Value & a_Value) { m_PosX = a_Value.get("x", 0).asInt(); m_PosY = a_Value.get("y", 0).asInt(); m_PosZ = a_Value.get("z", 0).asInt(); Json::Value AllSlots = a_Value.get("Slots", 0); int SlotIdx = 0; for (Json::Value::iterator itr = AllSlots.begin(); itr != AllSlots.end(); ++itr) { cItem Item; Item.FromJson(*itr); SetSlot(SlotIdx, Item); SlotIdx++; } return true; } void cChestEntity::SaveToJson(Json::Value & a_Value) { a_Value["x"] = m_PosX; a_Value["y"] = m_PosY; a_Value["z"] = m_PosZ; Json::Value AllSlots; for (int i = m_Contents.GetNumSlots() - 1; i >= 0; i--) { Json::Value Slot; m_Contents.GetSlot(i).GetJson(Slot); AllSlots.append(Slot); } a_Value["Slots"] = AllSlots; } void cChestEntity::SendTo(cClientHandle & a_Client) { // The chest entity doesn't need anything sent to the client when it's created / gets in the viewdistance // All the actual handling is in the cWindow UI code that gets called when the chest is rclked UNUSED(a_Client); } void cChestEntity::UsedBy(cPlayer * a_Player) { // If the window is not created, open it anew: cWindow * Window = GetWindow(); if (Window == NULL) { OpenNewWindow(); Window = GetWindow(); } // Open the window for the player: if (Window != NULL) { if (a_Player->GetWindow() != Window) { a_Player->OpenWindow(Window); } } // This is rather a hack // Instead of marking the chunk as dirty upon chest contents change, we mark it dirty now // We cannot properly detect contents change, but such a change doesn't happen without a player opening the chest first. // The few false positives aren't much to worry about int ChunkX, ChunkZ; cChunkDef::BlockToChunk(m_PosX, m_PosZ, ChunkX, ChunkZ); m_World->MarkChunkDirty(ChunkX, ChunkZ); } void cChestEntity::OpenNewWindow(void) { // TODO: cats are an obstruction if ((GetPosY() + 1 < cChunkDef::Height) && cBlockInfo::IsSolid(GetWorld()->GetBlock(GetPosX(), GetPosY() + 1, GetPosZ()))) { // Obstruction, don't open return; } // Callback for opening together with neighbor chest: class cOpenDouble : public cChestCallback { cChestEntity * m_ThisChest; public: cOpenDouble(cChestEntity * a_ThisChest) : m_ThisChest(a_ThisChest) { } virtual bool Item(cChestEntity * a_Chest) override { if ((a_Chest->GetPosY() + 1 < cChunkDef::Height) && cBlockInfo::IsSolid(a_Chest->GetWorld()->GetBlock(a_Chest->GetPosX(), a_Chest->GetPosY() + 1, a_Chest->GetPosZ()))) { // Obstruction, don't open return false; } // The primary chest should eb the one with lesser X or Z coord: cChestEntity * Primary = a_Chest; cChestEntity * Secondary = m_ThisChest; if ( (Primary->GetPosX() > Secondary->GetPosX()) || (Primary->GetPosZ() > Secondary->GetPosZ()) ) { std::swap(Primary, Secondary); } m_ThisChest->OpenWindow(new cChestWindow(Primary, Secondary)); return false; } } ; // Scan neighbors for adjacent chests: cOpenDouble OpenDbl(this); if ( m_World->DoWithChestAt(m_PosX - 1, m_PosY, m_PosZ, OpenDbl) || m_World->DoWithChestAt(m_PosX + 1, m_PosY, m_PosZ, OpenDbl) || m_World->DoWithChestAt(m_PosX , m_PosY, m_PosZ - 1, OpenDbl) || m_World->DoWithChestAt(m_PosX , m_PosY, m_PosZ + 1, OpenDbl) ) { // The double-chest window has been opened in the callback return; } // There is no chest neighbor, open a single-chest window: OpenWindow(new cChestWindow(this)); } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: DocumentLoader.cxx,v $ * * $Revision: 1.9 $ * * last change: $Author: hr $ $Date: 2004-02-02 20:07:32 $ * * The Contents of this file are made available subject to the terms of * the BSD license. * * Copyright (c) 2003 by Sun Microsystems, 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: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of Sun Microsystems, 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. * *************************************************************************/ /***************************************************************************** ***************************************************************************** * * Simple client application using the UnoUrlResolver service. * ***************************************************************************** *****************************************************************************/ #include <stdio.h> #include <cppuhelper/bootstrap.hxx> #include <osl/file.hxx> #include <osl/process.h> #include <com/sun/star/bridge/XUnoUrlResolver.hpp> #include <com/sun/star/frame/XComponentLoader.hpp> #include <com/sun/star/beans/XPropertySet.hpp> #include <string.h> using namespace rtl; using namespace com::sun::star::uno; using namespace com::sun::star::lang; using namespace com::sun::star::beans; using namespace com::sun::star::bridge; using namespace com::sun::star::frame; using namespace com::sun::star::registry; //============================================================================ int SAL_CALL main( int argc, char **argv ) { OUString sConnectionString(RTL_CONSTASCII_USTRINGPARAM("uno:socket,host=localhost,port=2083;urp;StarOffice.ServiceManager")); if (argc < 2) { printf("using: DocumentLoader <file_url> [<uno_connection_url>]\n\n" "example: DocumentLoader \"file:///e:/temp/test.sxw\" \"uno:socket,host=localhost,port=2083;urp;StarOffice.ServiceManager\"\n"); exit(1); } if (argc == 3) { sConnectionString = OUString::createFromAscii(argv[2]); } // Creates a simple registry service instance. Reference< XSimpleRegistry > xSimpleRegistry( ::cppu::createSimpleRegistry() ); // Connects the registry to a persistent data source represented by an URL. xSimpleRegistry->open( OUString( RTL_CONSTASCII_USTRINGPARAM( "DocumentLoader.rdb") ), sal_True, sal_False ); /* Bootstraps an initial component context with service manager upon a given registry. This includes insertion of initial services: - (registry) service manager, shared lib loader, - simple registry, nested registry, - implementation registration - registry typedescription provider, typedescription manager (also installs it into cppu core) */ Reference< XComponentContext > xComponentContext( ::cppu::bootstrap_InitialComponentContext( xSimpleRegistry ) ); /* Bootstraps an initial component context with service manager upon default types and services registry. This includes insertion of initial services: - (registry) service manager, shared lib loader, - simple registry, nested registry, - implementation registration - registry typedescription provider, typedescription manager (also installs it into cppu core) This function tries to find its parameters via these bootstrap variables: - UNO_TYPES -- a space separated list of file urls of type rdbs - UNO_SERVICES -- a space separated list of file urls of service rdbs - UNO_WRITERDB -- a file url of a write rdb (e.g. user.rdb) For further info, please look at: http://udk.openoffice.org/common/man/concept/uno_default_bootstrapping.html */ /* Reference< XComponentContext > xComponentContext( ::cppu::defaultBootstrap_InitialComponentContext() ); OSL_ASSERT( xcomponentcontext.is() ); */ /* Gets the service manager instance to be used (or null). This method has been added for convenience, because the service manager is a often used object. */ Reference< XMultiComponentFactory > xMultiComponentFactoryClient( xComponentContext->getServiceManager() ); /* Creates an instance of a component which supports the services specified by the factory. */ Reference< XInterface > xInterface = xMultiComponentFactoryClient->createInstanceWithContext( OUString::createFromAscii( "com.sun.star.bridge.UnoUrlResolver" ), xComponentContext ); Reference< XUnoUrlResolver > resolver( xInterface, UNO_QUERY ); // Resolves the component context from the office, on the uno URL given by argv[1]. try { xInterface = Reference< XInterface >( resolver->resolve( sConnectionString ), UNO_QUERY ); } catch ( Exception& e ) { printf("Error: cannot establish a connection using '%s':\n %s\n", OUStringToOString(sConnectionString, RTL_TEXTENCODING_ASCII_US).getStr(), OUStringToOString(e.Message, RTL_TEXTENCODING_ASCII_US).getStr()); exit(1); } // gets the server component context as property of the office component factory Reference< XPropertySet > xPropSet( xInterface, UNO_QUERY ); xPropSet->getPropertyValue( OUString::createFromAscii("DefaultContext") ) >>= xComponentContext; // gets the service manager from the office Reference< XMultiComponentFactory > xMultiComponentFactoryServer( xComponentContext->getServiceManager() ); /* Creates an instance of a component which supports the services specified by the factory. Important: using the office component context. */ Reference < XComponentLoader > xComponentLoader( xMultiComponentFactoryServer->createInstanceWithContext( OUString( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.frame.Desktop" ) ), xComponentContext ), UNO_QUERY ); /* Loads a component specified by an URL into the specified new or existing frame. */ OUString sDocUrl, sWorkingDir; osl_getProcessWorkingDir(&sWorkingDir.pData); osl::FileBase::getAbsoluteFileURL( sWorkingDir, OUString::createFromAscii(argv[1]), sDocUrl); Reference< XComponent > xComponent = xComponentLoader->loadComponentFromURL( sDocUrl, OUString( RTL_CONSTASCII_USTRINGPARAM("_blank") ), 0, Sequence < ::com::sun::star::beans::PropertyValue >() ); // dispose the local service manager Reference< XComponent >::query( xMultiComponentFactoryClient )->dispose(); return 0; } <commit_msg>INTEGRATION: CWS sdksample (1.9.40); FILE MERGED 2005/01/12 15:17:56 jsc 1.9.40.3: #i39890# change to new OpenDocument format 2004/07/21 16:17:16 jsc 1.9.40.2: #i29308# take care of full qualified path 2004/07/21 14:28:17 jsc 1.9.40.1: #i29308# take care of full qualified path<commit_after>/************************************************************************* * * $RCSfile: DocumentLoader.cxx,v $ * * $Revision: 1.10 $ * * last change: $Author: rt $ $Date: 2005-01-31 17:02:04 $ * * The Contents of this file are made available subject to the terms of * the BSD license. * * Copyright (c) 2003 by Sun Microsystems, 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: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of Sun Microsystems, 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. * *************************************************************************/ /***************************************************************************** ***************************************************************************** * * Simple client application using the UnoUrlResolver service. * ***************************************************************************** *****************************************************************************/ #include <stdio.h> #include <wchar.h> #include <cppuhelper/bootstrap.hxx> #include <osl/file.hxx> #include <osl/process.h> #include <com/sun/star/bridge/XUnoUrlResolver.hpp> #include <com/sun/star/frame/XComponentLoader.hpp> #include <com/sun/star/beans/XPropertySet.hpp> #include <string.h> using namespace rtl; using namespace com::sun::star::uno; using namespace com::sun::star::lang; using namespace com::sun::star::beans; using namespace com::sun::star::bridge; using namespace com::sun::star::frame; using namespace com::sun::star::registry; //============================================================================ int SAL_CALL main( int argc, char **argv ) { OUString sConnectionString(RTL_CONSTASCII_USTRINGPARAM("uno:socket,host=localhost,port=2083;urp;StarOffice.ServiceManager")); if (argc < 2) { printf("using: DocumentLoader <file_url> [<uno_connection_url>]\n\n" "example: DocumentLoader \"file:///e:/temp/test.odt\" \"uno:socket,host=localhost,port=2083;urp;StarOffice.ServiceManager\"\n"); exit(1); } if (argc == 3) { sConnectionString = OUString::createFromAscii(argv[2]); } // Creates a simple registry service instance. Reference< XSimpleRegistry > xSimpleRegistry( ::cppu::createSimpleRegistry() ); // Connects the registry to a persistent data source represented by an URL. xSimpleRegistry->open( OUString( RTL_CONSTASCII_USTRINGPARAM( "DocumentLoader.rdb") ), sal_True, sal_False ); /* Bootstraps an initial component context with service manager upon a given registry. This includes insertion of initial services: - (registry) service manager, shared lib loader, - simple registry, nested registry, - implementation registration - registry typedescription provider, typedescription manager (also installs it into cppu core) */ Reference< XComponentContext > xComponentContext( ::cppu::bootstrap_InitialComponentContext( xSimpleRegistry ) ); /* Gets the service manager instance to be used (or null). This method has been added for convenience, because the service manager is a often used object. */ Reference< XMultiComponentFactory > xMultiComponentFactoryClient( xComponentContext->getServiceManager() ); /* Creates an instance of a component which supports the services specified by the factory. */ Reference< XInterface > xInterface = xMultiComponentFactoryClient->createInstanceWithContext( OUString::createFromAscii( "com.sun.star.bridge.UnoUrlResolver" ), xComponentContext ); Reference< XUnoUrlResolver > resolver( xInterface, UNO_QUERY ); // Resolves the component context from the office, on the uno URL given by argv[1]. try { xInterface = Reference< XInterface >( resolver->resolve( sConnectionString ), UNO_QUERY ); } catch ( Exception& e ) { printf("Error: cannot establish a connection using '%s':\n %s\n", OUStringToOString(sConnectionString, RTL_TEXTENCODING_ASCII_US).getStr(), OUStringToOString(e.Message, RTL_TEXTENCODING_ASCII_US).getStr()); exit(1); } // gets the server component context as property of the office component factory Reference< XPropertySet > xPropSet( xInterface, UNO_QUERY ); xPropSet->getPropertyValue( OUString::createFromAscii("DefaultContext") ) >>= xComponentContext; // gets the service manager from the office Reference< XMultiComponentFactory > xMultiComponentFactoryServer( xComponentContext->getServiceManager() ); /* Creates an instance of a component which supports the services specified by the factory. Important: using the office component context. */ Reference < XComponentLoader > xComponentLoader( xMultiComponentFactoryServer->createInstanceWithContext( OUString( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.frame.Desktop" ) ), xComponentContext ), UNO_QUERY ); /* Loads a component specified by an URL into the specified new or existing frame. */ OUString sAbsoluteDocUrl, sWorkingDir, sDocPathUrl; osl_getProcessWorkingDir(&sWorkingDir.pData); osl::FileBase::getFileURLFromSystemPath( OUString::createFromAscii(argv[1]), sDocPathUrl); osl::FileBase::getAbsoluteFileURL( sWorkingDir, sDocPathUrl, sAbsoluteDocUrl); Reference< XComponent > xComponent = xComponentLoader->loadComponentFromURL( sAbsoluteDocUrl, OUString( RTL_CONSTASCII_USTRINGPARAM("_blank") ), 0, Sequence < ::com::sun::star::beans::PropertyValue >() ); // dispose the local service manager Reference< XComponent >::query( xMultiComponentFactoryClient )->dispose(); return 0; } <|endoftext|>
<commit_before>#include "stdafx.h" #include "ResourceLoader.h" #include <iostream> #include "Logger.h" std::string ResourceLoader::loadTextResource(HMODULE moduleHandle, int id, LPTSTR type) { HRSRC resourceHandle = ::FindResource(moduleHandle, MAKEINTRESOURCE(id), type); if (!resourceHandle) { std::string msg("Unable to find resource with id: ["); msg += std::to_string(id); msg += "] because of error with code: "; msg += std::to_string(::GetLastError()); LOG_ERROR(msg); throw std::runtime_error(msg); } HGLOBAL resourceData = ::LoadResource(moduleHandle, resourceHandle); LPVOID dataFirstByte = ::LockResource(resourceData); DWORD dataSize = ::SizeofResource(moduleHandle, resourceHandle); return {static_cast<const char*>(dataFirstByte), dataSize}; } <commit_msg>Using old constructor syntax.<commit_after>#include "stdafx.h" #include "ResourceLoader.h" #include <iostream> #include "Logger.h" std::string ResourceLoader::loadTextResource(HMODULE moduleHandle, int id, LPTSTR type) { HRSRC resourceHandle = ::FindResource(moduleHandle, MAKEINTRESOURCE(id), type); if (!resourceHandle) { std::string msg("Unable to find resource with id: ["); msg += std::to_string(id); msg += "] because of error with code: "; msg += std::to_string(::GetLastError()); LOG_ERROR(msg); throw std::runtime_error(msg); } HGLOBAL resourceData = ::LoadResource(moduleHandle, resourceHandle); LPVOID dataFirstByte = ::LockResource(resourceData); DWORD dataSize = ::SizeofResource(moduleHandle, resourceHandle); return std::string(static_cast<const char*>(dataFirstByte), dataSize); } <|endoftext|>
<commit_before>#include "SDLAudioDriver.h" #include "CircularBuffer.h" #include "Gui.h" #include "Stream.h" #include <SDL.h> #include <SDL_audio.h> #include <array> constexpr struct { static const bool Enabled = true; // Whether to output the source samples or the target samples static const bool SourceSamples = false; } OutputRawAudioFileStream; namespace { template <SDL_AudioFormat Format> struct AudioFormat; template <> struct AudioFormat<AUDIO_S16> { typedef int16_t Type; static Type Remap(float ratio) { return static_cast<Type>(((ratio - 0.5f) * 2.f) * (std::numeric_limits<Type>::max() - 1)); } }; template <> struct AudioFormat<AUDIO_U16> { typedef uint16_t Type; static Type Remap(float ratio) { return static_cast<Type>(ratio * std::numeric_limits<Type>::max()); } }; template <> struct AudioFormat<AUDIO_F32> { typedef float Type; static Type Remap(float ratio) { return (ratio - 0.5f) * 2.f; } }; } // namespace class SDLAudioDriverImpl { public: static const int kSampleRate = 44100; static const SDL_AudioFormat kSampleFormat = AUDIO_S16; // Apparently supported by all drivers? // static const SDL_AudioFormat kSampleFormat = AUDIO_U16; // static const SDL_AudioFormat kSampleFormat = AUDIO_F32; static const int kNumChannels = 1; static const int kSamplesPerCallback = 1024; using CurrAudioFormat = AudioFormat<kSampleFormat>; using SampleFormatType = CurrAudioFormat::Type; SDLAudioDriverImpl() : m_audioDeviceID(0) {} ~SDLAudioDriverImpl() { Shutdown(); } void Initialize() { SDL_InitSubSystem(SDL_INIT_AUDIO); SDL_AudioSpec desired; SDL_zero(desired); desired.freq = kSampleRate; desired.format = kSampleFormat; desired.channels = kNumChannels; desired.samples = kSamplesPerCallback; desired.callback = AudioCallback; desired.userdata = this; SDL_AudioSpec actual; // No changes allowed, meaning SDL will take care of converting our samples in our desired // format to the actual target format. int allowedChanges = 0; m_audioDeviceID = SDL_OpenAudioDevice(NULL, 0, &desired, &actual, allowedChanges); m_audioSpec = desired; if (m_audioDeviceID == 0) FAIL_MSG("Failed to open audio device (error code %d)", SDL_GetError()); // Set buffer size as a function of the latency we allow const float kDesiredLatencySecs = 50 / 1000.0f; const float desiredLatencySamples = kDesiredLatencySecs * GetSampleRate(); const size_t bufferSize = static_cast<size_t>( desiredLatencySamples * 2); // We wait until buffer is 50% full to start playing m_samples.Init(bufferSize); if constexpr (OutputRawAudioFileStream.Enabled) { m_rawAudioOutputFS.Open("RawAudio.raw", "wb"); } m_paused = false; SetPaused(true); } void Shutdown() { m_rawAudioOutputFS.Close(); SDL_CloseAudioDevice(m_audioDeviceID); SDL_QuitSubSystem(SDL_INIT_AUDIO); } void Update(double /*frameTime*/) { AdjustBufferFlow(); // Debug output { //@TODO: Control with option Gui::EnabledWindows[Gui::Window::AudioDebug] = true; static std::array<float, 10000> bufferUsageHistory; static std::array<float, 10000> pauseHistory; static int index = 0; bufferUsageHistory[index] = GetBufferUsageRatio(); pauseHistory[index] = m_paused ? 0.f : 1.f; index = (index + 1) % bufferUsageHistory.size(); if (index == 0) { std::fill(bufferUsageHistory.begin(), bufferUsageHistory.end(), 0.f); std::fill(pauseHistory.begin(), pauseHistory.end(), 0.f); } IMGUI_CALL(AudioDebug, ImGui::PlotLines("Buffer Usage", bufferUsageHistory.data(), (int)bufferUsageHistory.size(), 0, 0, 0.f, 1.f, ImVec2(0, 100.f))); IMGUI_CALL(AudioDebug, ImGui::PlotLines("Unpaused", pauseHistory.data(), (int)pauseHistory.size(), 0, 0, 0.f, 1.f, ImVec2(0, 100.f))); const auto color = m_paused ? IM_COL32(255, 0, 0, 255) : IM_COL32(255, 255, 0, 255); IMGUI_CALL(AudioDebug, ImGui::PushStyleColor(ImGuiCol_PlotHistogram, color)); IMGUI_CALL(AudioDebug, ImGui::ProgressBar(GetBufferUsageRatio(), ImVec2(-1, 100))); IMGUI_CALL(AudioDebug, ImGui::PopStyleColor()); } } size_t GetSampleRate() const { return m_audioSpec.freq; } float GetBufferUsageRatio() const { return static_cast<float>(m_samples.UsedSize()) / m_samples.TotalSize(); } void SetPaused(bool paused) { if (paused != m_paused) { m_paused = paused; SDL_PauseAudioDevice(m_audioDeviceID, m_paused ? 1 : 0); } } void AdjustBufferFlow() { // Unpause when buffer is half full; pause if almost depleted to give buffer a chance to // fill up again. const auto bufferUsageRatio = GetBufferUsageRatio(); if (bufferUsageRatio >= 0.5f) { SetPaused(false); } else if (bufferUsageRatio < 0.1f) { SetPaused(true); } } void AddSample(float sample) { assert(sample >= 0.0f && sample <= 1.0f); auto targetSample = CurrAudioFormat::Remap(sample); SDL_LockAudioDevice(m_audioDeviceID); m_samples.PushBack(targetSample); SDL_UnlockAudioDevice(m_audioDeviceID); // AdjustBufferFlow(); if constexpr (OutputRawAudioFileStream.Enabled && OutputRawAudioFileStream.SourceSamples) { m_rawAudioOutputFS.WriteValue(sample); } } void AddSamples(float* samples, size_t size) { for (size_t i = 0; i < size; ++i) AddSample(samples[i]); } private: static void AudioCallback(void* userData, Uint8* byteStream, int byteStreamLength) { auto audioDriver = reinterpret_cast<SDLAudioDriverImpl*>(userData); auto stream = reinterpret_cast<SampleFormatType*>(byteStream); size_t numSamplesToRead = byteStreamLength / sizeof(SampleFormatType); //@TODO: sync access to m_samples with a mutex here size_t numSamplesRead = audioDriver->m_samples.PopFront(stream, numSamplesToRead); // If we haven't written enough samples, fill out the rest with the last sample // written. This will usually hide the error. if (numSamplesRead < numSamplesToRead) { SampleFormatType lastSample = numSamplesRead == 0 ? 0 : stream[numSamplesRead - 1]; std::fill_n(stream + numSamplesRead, numSamplesToRead - numSamplesRead, lastSample); } if constexpr (OutputRawAudioFileStream.Enabled && !OutputRawAudioFileStream.SourceSamples) { for (int i = 0; i < numSamplesToRead; ++i) { audioDriver->m_rawAudioOutputFS.WriteValue(stream[i]); } } } SDL_AudioDeviceID m_audioDeviceID; SDL_AudioSpec m_audioSpec; CircularBuffer<SampleFormatType> m_samples; FileStream m_rawAudioOutputFS; bool m_paused; }; SDLAudioDriver::SDLAudioDriver() = default; SDLAudioDriver::~SDLAudioDriver() = default; void SDLAudioDriver::Initialize() { m_impl->Initialize(); } void SDLAudioDriver::Shutdown() { m_impl->Shutdown(); } void SDLAudioDriver::Update(double frameTime) { m_impl->Update(frameTime); } size_t SDLAudioDriver::GetSampleRate() const { return m_impl->GetSampleRate(); } float SDLAudioDriver::GetBufferUsageRatio() const { return m_impl->GetBufferUsageRatio(); } void SDLAudioDriver::AddSample(float sample) { m_impl->AddSample(sample); } void SDLAudioDriver::AddSamples(float* samples, size_t size) { m_impl->AddSamples(samples, size); } <commit_msg>SDLAudioDriver: fix invalid filestream access after shutdown and signed/unsigned mismatch warning<commit_after>#include "SDLAudioDriver.h" #include "CircularBuffer.h" #include "Gui.h" #include "Stream.h" #include <SDL.h> #include <SDL_audio.h> #include <array> constexpr struct { static const bool Enabled = true; // Whether to output the source samples or the target samples static const bool SourceSamples = false; } OutputRawAudioFileStream; namespace { template <SDL_AudioFormat Format> struct AudioFormat; template <> struct AudioFormat<AUDIO_S16> { typedef int16_t Type; static Type Remap(float ratio) { return static_cast<Type>(((ratio - 0.5f) * 2.f) * (std::numeric_limits<Type>::max() - 1)); } }; template <> struct AudioFormat<AUDIO_U16> { typedef uint16_t Type; static Type Remap(float ratio) { return static_cast<Type>(ratio * std::numeric_limits<Type>::max()); } }; template <> struct AudioFormat<AUDIO_F32> { typedef float Type; static Type Remap(float ratio) { return (ratio - 0.5f) * 2.f; } }; } // namespace class SDLAudioDriverImpl { public: static const int kSampleRate = 44100; static const SDL_AudioFormat kSampleFormat = AUDIO_S16; // Apparently supported by all drivers? // static const SDL_AudioFormat kSampleFormat = AUDIO_U16; // static const SDL_AudioFormat kSampleFormat = AUDIO_F32; static const int kNumChannels = 1; static const int kSamplesPerCallback = 1024; using CurrAudioFormat = AudioFormat<kSampleFormat>; using SampleFormatType = CurrAudioFormat::Type; SDLAudioDriverImpl() : m_audioDeviceID(0) {} ~SDLAudioDriverImpl() { Shutdown(); } void Initialize() { SDL_InitSubSystem(SDL_INIT_AUDIO); SDL_AudioSpec desired; SDL_zero(desired); desired.freq = kSampleRate; desired.format = kSampleFormat; desired.channels = kNumChannels; desired.samples = kSamplesPerCallback; desired.callback = AudioCallback; desired.userdata = this; SDL_AudioSpec actual; // No changes allowed, meaning SDL will take care of converting our samples in our desired // format to the actual target format. int allowedChanges = 0; m_audioDeviceID = SDL_OpenAudioDevice(NULL, 0, &desired, &actual, allowedChanges); m_audioSpec = desired; if (m_audioDeviceID == 0) FAIL_MSG("Failed to open audio device (error code %d)", SDL_GetError()); // Set buffer size as a function of the latency we allow const float kDesiredLatencySecs = 50 / 1000.0f; const float desiredLatencySamples = kDesiredLatencySecs * GetSampleRate(); const size_t bufferSize = static_cast<size_t>( desiredLatencySamples * 2); // We wait until buffer is 50% full to start playing m_samples.Init(bufferSize); if constexpr (OutputRawAudioFileStream.Enabled) { m_rawAudioOutputFS.Open("RawAudio.raw", "wb"); } m_paused = false; SetPaused(true); } void Shutdown() { SDL_CloseAudioDevice(m_audioDeviceID); SDL_QuitSubSystem(SDL_INIT_AUDIO); m_rawAudioOutputFS.Close(); } void Update(double /*frameTime*/) { AdjustBufferFlow(); // Debug output { //@TODO: Control with option Gui::EnabledWindows[Gui::Window::AudioDebug] = true; static std::array<float, 10000> bufferUsageHistory; static std::array<float, 10000> pauseHistory; static int index = 0; bufferUsageHistory[index] = GetBufferUsageRatio(); pauseHistory[index] = m_paused ? 0.f : 1.f; index = (index + 1) % bufferUsageHistory.size(); if (index == 0) { std::fill(bufferUsageHistory.begin(), bufferUsageHistory.end(), 0.f); std::fill(pauseHistory.begin(), pauseHistory.end(), 0.f); } IMGUI_CALL(AudioDebug, ImGui::PlotLines("Buffer Usage", bufferUsageHistory.data(), (int)bufferUsageHistory.size(), 0, 0, 0.f, 1.f, ImVec2(0, 100.f))); IMGUI_CALL(AudioDebug, ImGui::PlotLines("Unpaused", pauseHistory.data(), (int)pauseHistory.size(), 0, 0, 0.f, 1.f, ImVec2(0, 100.f))); const auto color = m_paused ? IM_COL32(255, 0, 0, 255) : IM_COL32(255, 255, 0, 255); IMGUI_CALL(AudioDebug, ImGui::PushStyleColor(ImGuiCol_PlotHistogram, color)); IMGUI_CALL(AudioDebug, ImGui::ProgressBar(GetBufferUsageRatio(), ImVec2(-1, 100))); IMGUI_CALL(AudioDebug, ImGui::PopStyleColor()); } } size_t GetSampleRate() const { return m_audioSpec.freq; } float GetBufferUsageRatio() const { return static_cast<float>(m_samples.UsedSize()) / m_samples.TotalSize(); } void SetPaused(bool paused) { if (paused != m_paused) { m_paused = paused; SDL_PauseAudioDevice(m_audioDeviceID, m_paused ? 1 : 0); } } void AdjustBufferFlow() { // Unpause when buffer is half full; pause if almost depleted to give buffer a chance to // fill up again. const auto bufferUsageRatio = GetBufferUsageRatio(); if (bufferUsageRatio >= 0.5f) { SetPaused(false); } else if (bufferUsageRatio < 0.1f) { SetPaused(true); } } void AddSample(float sample) { assert(sample >= 0.0f && sample <= 1.0f); auto targetSample = CurrAudioFormat::Remap(sample); SDL_LockAudioDevice(m_audioDeviceID); m_samples.PushBack(targetSample); SDL_UnlockAudioDevice(m_audioDeviceID); // AdjustBufferFlow(); if constexpr (OutputRawAudioFileStream.Enabled && OutputRawAudioFileStream.SourceSamples) { m_rawAudioOutputFS.WriteValue(sample); } } void AddSamples(float* samples, size_t size) { for (size_t i = 0; i < size; ++i) AddSample(samples[i]); } private: static void AudioCallback(void* userData, Uint8* byteStream, int byteStreamLength) { auto audioDriver = reinterpret_cast<SDLAudioDriverImpl*>(userData); auto stream = reinterpret_cast<SampleFormatType*>(byteStream); size_t numSamplesToRead = byteStreamLength / sizeof(SampleFormatType); //@TODO: sync access to m_samples with a mutex here size_t numSamplesRead = audioDriver->m_samples.PopFront(stream, numSamplesToRead); // If we haven't written enough samples, fill out the rest with the last sample // written. This will usually hide the error. if (numSamplesRead < numSamplesToRead) { SampleFormatType lastSample = numSamplesRead == 0 ? 0 : stream[numSamplesRead - 1]; std::fill_n(stream + numSamplesRead, numSamplesToRead - numSamplesRead, lastSample); } if constexpr (OutputRawAudioFileStream.Enabled && !OutputRawAudioFileStream.SourceSamples) { for (size_t i = 0; i < numSamplesToRead; ++i) { audioDriver->m_rawAudioOutputFS.WriteValue(stream[i]); } } } SDL_AudioDeviceID m_audioDeviceID; SDL_AudioSpec m_audioSpec; CircularBuffer<SampleFormatType> m_samples; FileStream m_rawAudioOutputFS; bool m_paused; }; SDLAudioDriver::SDLAudioDriver() = default; SDLAudioDriver::~SDLAudioDriver() = default; void SDLAudioDriver::Initialize() { m_impl->Initialize(); } void SDLAudioDriver::Shutdown() { m_impl->Shutdown(); } void SDLAudioDriver::Update(double frameTime) { m_impl->Update(frameTime); } size_t SDLAudioDriver::GetSampleRate() const { return m_impl->GetSampleRate(); } float SDLAudioDriver::GetBufferUsageRatio() const { return m_impl->GetBufferUsageRatio(); } void SDLAudioDriver::AddSample(float sample) { m_impl->AddSample(sample); } void SDLAudioDriver::AddSamples(float* samples, size_t size) { m_impl->AddSamples(samples, size); } <|endoftext|>
<commit_before>#include <iostream> #include <clang/Frontend/CompilerInstance.h> #include <clang/Frontend/FrontendActions.h> #include <clang/Tooling/CommonOptionsParser.h> #include <clang/Tooling/Refactoring.h> #include <llvm/Support/Signals.h> namespace { class RedundantPPCallbacks : public clang::PPCallbacks { public: RedundantPPCallbacks(clang::Preprocessor& rPP); void Ifndef(clang::SourceLocation aLoc, const clang::Token& rMacroNameTok, const clang::MacroDefinition& rMacroDefinition) override; void Endif(clang::SourceLocation aLoc, clang::SourceLocation aIfLoc) override; private: clang::Preprocessor& m_rPP; }; RedundantPPCallbacks::RedundantPPCallbacks(clang::Preprocessor& rPP) : m_rPP(rPP) { } void RedundantPPCallbacks::Ifndef( clang::SourceLocation aLoc, const clang::Token& rMacroNameTok, const clang::MacroDefinition& /*rMacroDefinition*/) { std::cerr << "debug, RedundantPPCallbacks::Ifndef: aLoc is "; aLoc.dump(m_rPP.getSourceManager()); std::cerr << ", rMacroNameTok is '" << m_rPP.getSpelling(rMacroNameTok) << "'" << std::endl; } void RedundantPPCallbacks::Endif(clang::SourceLocation aLoc, clang::SourceLocation aIfLoc) { std::cerr << "debug, RedundantPPCallbacks::Endif: aLoc is "; aLoc.dump(m_rPP.getSourceManager()); std::cerr << ", IfLoc is "; aIfLoc.dump(m_rPP.getSourceManager()); std::cerr << std::endl; } class RedundantPPConsumer : public clang::ASTConsumer { public: RedundantPPConsumer(clang::Preprocessor& rPP) { rPP.addPPCallbacks(llvm::make_unique<RedundantPPCallbacks>(rPP)); } }; class RedundantPPAction : public clang::SyntaxOnlyAction { public: RedundantPPAction() {} protected: std::unique_ptr<clang::ASTConsumer> CreateASTConsumer(clang::CompilerInstance& rInstance, StringRef /*aFile*/) override { return llvm::make_unique<RedundantPPConsumer>( rInstance.getPreprocessor()); } }; class RedundantPPFrontendActionFactory : public clang::tooling::FrontendActionFactory { public: RedundantPPFrontendActionFactory() {} RedundantPPAction* create() override { return new RedundantPPAction(); } }; llvm::cl::extrahelp aCommonHelp(clang::tooling::CommonOptionsParser::HelpMessage); llvm::cl::OptionCategory aCategory("redundant-pp options"); } int main(int argc, const char** argv) { llvm::sys::PrintStackTraceOnErrorSignal(argv[0]); clang::tooling::CommonOptionsParser aOptionsParser(argc, argv, aCategory); clang::tooling::RefactoringTool aTool(aOptionsParser.getCompilations(), aOptionsParser.getSourcePathList()); RedundantPPFrontendActionFactory aFactory; return aTool.run(&aFactory); } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>llvm, C++ readability-redundant-pp: add actual functionality<commit_after>#include <iostream> #include <stack> #include <clang/Frontend/CompilerInstance.h> #include <clang/Frontend/FrontendActions.h> #include <clang/Tooling/CommonOptionsParser.h> #include <clang/Tooling/Refactoring.h> #include <llvm/Support/Signals.h> namespace { struct Entry { clang::SourceLocation m_aLoc; std::string m_aMacroName; }; class RedundantPPCallbacks : public clang::PPCallbacks { public: RedundantPPCallbacks(clang::Preprocessor& rPP); void Ifndef(clang::SourceLocation aLoc, const clang::Token& rMacroNameTok, const clang::MacroDefinition& rMacroDefinition) override; void Endif(clang::SourceLocation aLoc, clang::SourceLocation aIfLoc) override; ~RedundantPPCallbacks() override; private: clang::DiagnosticBuilder reportWarning(llvm::StringRef aString, clang::SourceLocation aLocation); clang::DiagnosticBuilder report(clang::DiagnosticIDs::Level eLevel, llvm::StringRef aString, clang::SourceLocation aLocation); clang::Preprocessor& m_rPP; std::vector<Entry> m_aStack; }; RedundantPPCallbacks::RedundantPPCallbacks(clang::Preprocessor& rPP) : m_rPP(rPP) { } RedundantPPCallbacks::~RedundantPPCallbacks() {} void RedundantPPCallbacks::Ifndef( clang::SourceLocation aLoc, const clang::Token& rMacroNameTok, const clang::MacroDefinition& /*rMacroDefinition*/) { if (m_rPP.getSourceManager().isInMainFile(aLoc)) { std::string aMacroName = m_rPP.getSpelling(rMacroNameTok); for (const auto& rEntry : m_aStack) { if (rEntry.m_aMacroName == aMacroName) { reportWarning("nested ifdef", aLoc); report(clang::DiagnosticIDs::Note, "previous ifdef", rEntry.m_aLoc); } } } Entry aEntry; aEntry.m_aLoc = aLoc; aEntry.m_aMacroName = m_rPP.getSpelling(rMacroNameTok); m_aStack.push_back(aEntry); } void RedundantPPCallbacks::Endif(clang::SourceLocation /*aLoc*/, clang::SourceLocation aIfLoc) { if (m_aStack.empty()) return; if (aIfLoc == m_aStack.back().m_aLoc) m_aStack.pop_back(); } clang::DiagnosticBuilder RedundantPPCallbacks::reportWarning(llvm::StringRef aString, clang::SourceLocation aLocation) { clang::DiagnosticsEngine& rEngine = m_rPP.getDiagnostics(); clang::DiagnosticIDs::Level eLevel = clang::DiagnosticIDs::Level::Warning; if (rEngine.getWarningsAsErrors()) eLevel = clang::DiagnosticIDs::Level::Error; return report(eLevel, aString, aLocation); } clang::DiagnosticBuilder RedundantPPCallbacks::report(clang::DiagnosticIDs::Level eLevel, llvm::StringRef aString, clang::SourceLocation aLocation) { clang::DiagnosticsEngine& rEngine = m_rPP.getDiagnostics(); return rEngine.Report( aLocation, rEngine.getDiagnosticIDs()->getCustomDiagID(eLevel, aString)); } class RedundantPPConsumer : public clang::ASTConsumer { public: RedundantPPConsumer(clang::Preprocessor& rPP) { rPP.addPPCallbacks(llvm::make_unique<RedundantPPCallbacks>(rPP)); } }; class RedundantPPAction : public clang::SyntaxOnlyAction { public: RedundantPPAction() {} protected: std::unique_ptr<clang::ASTConsumer> CreateASTConsumer(clang::CompilerInstance& rInstance, StringRef /*aFile*/) override { return llvm::make_unique<RedundantPPConsumer>( rInstance.getPreprocessor()); } }; class RedundantPPFrontendActionFactory : public clang::tooling::FrontendActionFactory { public: RedundantPPFrontendActionFactory() {} RedundantPPAction* create() override { return new RedundantPPAction(); } }; llvm::cl::extrahelp aCommonHelp(clang::tooling::CommonOptionsParser::HelpMessage); llvm::cl::OptionCategory aCategory("redundant-pp options"); } int main(int argc, const char** argv) { llvm::sys::PrintStackTraceOnErrorSignal(argv[0]); clang::tooling::CommonOptionsParser aOptionsParser(argc, argv, aCategory); clang::tooling::RefactoringTool aTool(aOptionsParser.getCompilations(), aOptionsParser.getSourcePathList()); RedundantPPFrontendActionFactory aFactory; return aTool.run(&aFactory); } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>// // GameplayScene.cpp // MasmorraDados // // Created by Marlon Andrade on 16/02/2015. // // #include "GameplayScene.h" #include "BackgroundLayer.h" #include "CharacterDiceSprite.h" #include "RoomPlacement.h" USING_NS_CC; #pragma mark - Public Interface bool GameplayScene::init() { if (!Scene::init()) { return false; } this->_enableInteractions(); auto game = Game::createWithRoomPlacedDelegate([&](Vector<RoomPlacement*> placements) { this->_disableInteractions(); float delayTime = 0; int zOrder = placements.size(); for (auto placement : placements) { auto room = placement->getRoom(); auto position = placement->getPosition(); auto roomSprite = Sprite::create(room->getImagePath()); auto name = this->getGame()->getDungeon()->nameForPosition(position); roomSprite->setName(name); auto size = Director::getInstance()->getVisibleSize(); auto origin = Director::getInstance()->getVisibleOrigin(); auto deckPosition = Vec2(origin.x + size.width - TILE_DIMENSION / 2 - 20, origin.y + size.height - TILE_DIMENSION / 2 - 20); roomSprite->setPosition(deckPosition); this->getObjectsLayer()->addChild(roomSprite, zOrder); auto spritePosition = this->_positionInScene(position); auto delay = DelayTime::create(delayTime); auto animationStarted = CallFunc::create([=]() { this->_disableInteractions(); roomSprite->setLocalZOrder(DUNGEON_ROOM_Z_ORDER + 10); }); auto easeMove = EaseBackIn::create(MoveTo::create(PLACE_ROOM_DURATION, spritePosition)); auto animationEnded = CallFunc::create([=]() { this->_enableInteractions(); roomSprite->setLocalZOrder(DUNGEON_ROOM_Z_ORDER); }); roomSprite->runAction(Sequence::create(delay, animationStarted, easeMove, animationEnded, NULL)); delayTime += PLACE_ROOM_DURATION; zOrder--; } }); this->setGame(game); this->adjustInitialLayers(); return true; } #pragma mark - Private Interface void GameplayScene::adjustInitialLayers() { auto center = this->_centerOfScene(); auto backgroundLayer = BackgroundLayer::create(); this->addChild(backgroundLayer, -2); auto objectsLayer = this->_createObjectsLayer(); this->addChild(objectsLayer, -1); auto controlsLayer = this->_createControlsLayer(); this->addChild(controlsLayer, 1); this->getGame()->setCharacterPosition(INITIAL_POSITION); this->_adjustCharacterDiceSpritePosition(); } Layer* GameplayScene::_createObjectsLayer() { auto objectsLayer = Layer::create(); objectsLayer->setTag(OBJECTS_LAYER_TAG); auto initialRoom = this->getGame()->getDungeon()->getInitialRoom(); auto initialPosition = INITIAL_POSITION; auto initialSprite = Sprite::create(initialRoom->getImagePath()); auto name = this->getGame()->getDungeon()->nameForPosition(initialPosition); initialSprite->setName(name); initialSprite->setPosition(this->_positionInScene(INITIAL_POSITION)); objectsLayer->addChild(initialSprite, DUNGEON_ROOM_Z_ORDER); objectsLayer->addChild(this->_createCharacterDiceSprite(), GAME_OBJECTS_Z_ORDER); return objectsLayer; } Layer* GameplayScene::_createControlsLayer() { auto controlsLayer = Layer::create(); controlsLayer->setTag(CONTROLS_LAYER_TAG); return controlsLayer; } Node* GameplayScene::_createCharacterDiceSprite() { auto sprite = CharacterDiceSprite::create(); sprite->setTag(CHARACTER_DICE_SPRITE_TAG); auto touchListener = EventListenerTouchOneByOne::create(); touchListener->onTouchBegan = [&](Touch* touch, Event* event) { auto bounds = event->getCurrentTarget()->getBoundingBox(); auto touchInSprite = bounds.containsPoint(touch->getLocation()); bool containsBoot = true; auto canMove = this->_isInteractionEnabled() && touchInSprite && containsBoot; if (canMove) { Vector<Node*> visibleNodes; visibleNodes.pushBack(this->getObjectsLayer()->getChildByTag(CHARACTER_DICE_SPRITE_TAG)); visibleNodes.pushBack(this->_getNodeForCharacterPosition()); visibleNodes.pushBack(this->_getNodesForAdjacentCharacterPosition()); this->_addOverlayWithVisibleNodes(visibleNodes); } return canMove; }; touchListener->onTouchMoved = [=](Touch* touch, Event* event) { auto touchLocation = touch->getLocation(); for (auto adjacentNode : this->_getNodesForAdjacentCharacterPosition()) { Color3B color = Color3B::WHITE; if (adjacentNode->getBoundingBox().containsPoint(touchLocation)) { color = Color3B(170, 255, 170); } adjacentNode->setColor(color); } sprite->setPosition(touch->getLocation()); }; touchListener->onTouchEnded = [=](Touch* touch, Event* event) { bool characterMoved = false; auto touchLocation = touch->getLocation(); auto coordinate = this->getGame()->getCharacterPosition(); auto scenePosition = this->_positionInScene(coordinate); this->_removeOverlay(); for (auto adjacentNode : this->_getNodesForAdjacentCharacterPosition()) { adjacentNode->setColor(Color3B::WHITE); if (adjacentNode->getBoundingBox().containsPoint(touchLocation)) { characterMoved = true; auto newCoordinate = this->_positionInGameCoordinate(touchLocation); auto newPosition = this->_positionInScene(newCoordinate); auto moveNewPosition = MoveTo::create(RETURN_CHARACTER_DURATION, newPosition); auto actionEnded = CallFunc::create([=]() { this->getGame()->setCharacterPosition(newCoordinate); }); sprite->runAction(Sequence::create(moveNewPosition, actionEnded, NULL)); } } if (!characterMoved) { auto moveBack = MoveTo::create(RETURN_CHARACTER_DURATION, scenePosition); sprite->runAction(moveBack); } }; auto dispatcher = Director::getInstance()->getEventDispatcher(); dispatcher->addEventListenerWithSceneGraphPriority(touchListener, sprite); return sprite; } Layer* GameplayScene::getObjectsLayer() { return (Layer*) this->getChildByTag(OBJECTS_LAYER_TAG); } Layer* GameplayScene::getControlsLayer() { return (Layer*) this->getChildByTag(CONTROLS_LAYER_TAG); } Vec2 GameplayScene::_positionInScene(Vec2 gameCoordinate) { auto centerPosition = INITIAL_POSITION; auto centerOfScene = this->_centerOfScene(); auto offsetX = gameCoordinate.x - centerPosition.x; auto offsetY = gameCoordinate.y - centerPosition.y; return Vec2(centerOfScene.x + offsetX * TILE_DIMENSION, centerOfScene.y + offsetY * TILE_DIMENSION); } Vec2 GameplayScene::_positionInGameCoordinate(Vec2 scenePosition) { auto centerPosition = INITIAL_POSITION; auto centerOfScene = this->_centerOfScene(); auto offsetX = scenePosition.x - centerOfScene.x; auto offsetY = scenePosition.y - centerOfScene.y; auto halfTileDimension = TILE_DIMENSION / 2; offsetX > halfTileDimension ? offsetX += halfTileDimension : offsetX -= halfTileDimension; offsetY > halfTileDimension ? offsetY += halfTileDimension : offsetY -= halfTileDimension; return Vec2(centerPosition.x + int(offsetX / TILE_DIMENSION), centerPosition.y + int(offsetY / TILE_DIMENSION)); } void GameplayScene::_adjustCharacterDiceSpritePosition() { auto sprite = this->getObjectsLayer()->getChildByTag(CHARACTER_DICE_SPRITE_TAG); auto characterPosition = this->getGame()->getCharacterPosition(); sprite->setPosition(this->_positionInScene(characterPosition)); } void GameplayScene::_addOverlayWithVisibleNodes(Vector<Node *> visibleNodes) { auto overlayLayer = LayerColor::create(Color4B(0, 0, 0, 0)); overlayLayer->setTag(OVERLAY_LAYER_TAG); this->getObjectsLayer()->addChild(overlayLayer, OVERLAY_Z_ORDER); auto fadeIn = FadeTo::create(OVERLAY_DURATION, OVERLAY_OPACITY); overlayLayer->runAction(fadeIn); for (auto visibleNode : visibleNodes) { auto newZOrder = visibleNode->getLocalZOrder() + OVERLAY_Z_ORDER; visibleNode->setLocalZOrder(newZOrder); } this->setInteractableNodes(visibleNodes); } void GameplayScene::_removeOverlay() { this->_disableInteractions(); auto overlayLayer = this->getObjectsLayer()->getChildByTag(OVERLAY_LAYER_TAG); auto fadeOut = FadeOut::create(OVERLAY_DURATION); auto delayToFinishCharacterAnimation = DelayTime::create(RETURN_CHARACTER_DURATION); auto changeLayer = CallFunc::create([=]() { for (auto node : this->getInteractableNodes()) { auto oldZOrder = node->getLocalZOrder() - OVERLAY_Z_ORDER; node->setLocalZOrder(oldZOrder); } }); auto removeSelf = RemoveSelf::create(); auto animationEnded = CallFunc::create([=]() { this->_enableInteractions(); }); overlayLayer->runAction(Sequence::create(fadeOut, delayToFinishCharacterAnimation, changeLayer, removeSelf, animationEnded, NULL)); } Vec2 GameplayScene::_centerOfScene() { Vec2 visibleOrigin = Director::getInstance()->getVisibleOrigin(); Size visibleSize = Director::getInstance()->getVisibleSize(); return Vec2(visibleSize.width / 2 + visibleOrigin.x, visibleSize.height / 2 + visibleOrigin.y); } Node* GameplayScene::_getNodeForCharacterPosition() { auto position = this->getGame()->getCharacterPosition(); auto name = this->getGame()->getDungeon()->nameForPosition(position); return this->getObjectsLayer()->getChildByName(name); } Vector<Node*> GameplayScene::_getNodesForAdjacentCharacterPosition() { Node* activeLayer = this->getObjectsLayer(); auto overlayLayer = this->getChildByTag(OVERLAY_LAYER_TAG); if (overlayLayer) { activeLayer = overlayLayer; } Vector<Node*> nodes; auto position = this->getGame()->getCharacterPosition(); auto adjacentPositions = this->getGame()->getDungeon()->adjacentPositionsTo(position); for (auto adjacentPosition : adjacentPositions) { auto name = this->getGame()->getDungeon()->nameForPosition(adjacentPosition); nodes.pushBack(activeLayer->getChildByName(name)); } return nodes; } bool GameplayScene::_isInteractionEnabled() { return _userInteractionEnabled; } void GameplayScene::_disableInteractions() { _userInteractionEnabled = false; } void GameplayScene::_enableInteractions() { _userInteractionEnabled = true; }<commit_msg>Removendo delay para animação do personagem ao retirar overlay<commit_after>// // GameplayScene.cpp // MasmorraDados // // Created by Marlon Andrade on 16/02/2015. // // #include "GameplayScene.h" #include "BackgroundLayer.h" #include "CharacterDiceSprite.h" #include "RoomPlacement.h" USING_NS_CC; #pragma mark - Public Interface bool GameplayScene::init() { if (!Scene::init()) { return false; } this->_enableInteractions(); auto game = Game::createWithRoomPlacedDelegate([&](Vector<RoomPlacement*> placements) { this->_disableInteractions(); float delayTime = 0; int zOrder = placements.size(); for (auto placement : placements) { auto room = placement->getRoom(); auto position = placement->getPosition(); auto roomSprite = Sprite::create(room->getImagePath()); auto name = this->getGame()->getDungeon()->nameForPosition(position); roomSprite->setName(name); auto size = Director::getInstance()->getVisibleSize(); auto origin = Director::getInstance()->getVisibleOrigin(); auto deckPosition = Vec2(origin.x + size.width - TILE_DIMENSION / 2 - 20, origin.y + size.height - TILE_DIMENSION / 2 - 20); roomSprite->setPosition(deckPosition); this->getObjectsLayer()->addChild(roomSprite, zOrder); auto spritePosition = this->_positionInScene(position); auto delay = DelayTime::create(delayTime); auto animationStarted = CallFunc::create([=]() { this->_disableInteractions(); roomSprite->setLocalZOrder(DUNGEON_ROOM_Z_ORDER + 10); }); auto easeMove = EaseBackIn::create(MoveTo::create(PLACE_ROOM_DURATION, spritePosition)); auto animationEnded = CallFunc::create([=]() { this->_enableInteractions(); roomSprite->setLocalZOrder(DUNGEON_ROOM_Z_ORDER); }); roomSprite->runAction(Sequence::create(delay, animationStarted, easeMove, animationEnded, NULL)); delayTime += PLACE_ROOM_DURATION; zOrder--; } }); this->setGame(game); this->adjustInitialLayers(); return true; } #pragma mark - Private Interface void GameplayScene::adjustInitialLayers() { auto center = this->_centerOfScene(); auto backgroundLayer = BackgroundLayer::create(); this->addChild(backgroundLayer, -2); auto objectsLayer = this->_createObjectsLayer(); this->addChild(objectsLayer, -1); auto controlsLayer = this->_createControlsLayer(); this->addChild(controlsLayer, 1); this->getGame()->setCharacterPosition(INITIAL_POSITION); this->_adjustCharacterDiceSpritePosition(); } Layer* GameplayScene::_createObjectsLayer() { auto objectsLayer = Layer::create(); objectsLayer->setTag(OBJECTS_LAYER_TAG); auto initialRoom = this->getGame()->getDungeon()->getInitialRoom(); auto initialPosition = INITIAL_POSITION; auto initialSprite = Sprite::create(initialRoom->getImagePath()); auto name = this->getGame()->getDungeon()->nameForPosition(initialPosition); initialSprite->setName(name); initialSprite->setPosition(this->_positionInScene(INITIAL_POSITION)); objectsLayer->addChild(initialSprite, DUNGEON_ROOM_Z_ORDER); objectsLayer->addChild(this->_createCharacterDiceSprite(), GAME_OBJECTS_Z_ORDER); return objectsLayer; } Layer* GameplayScene::_createControlsLayer() { auto controlsLayer = Layer::create(); controlsLayer->setTag(CONTROLS_LAYER_TAG); return controlsLayer; } Node* GameplayScene::_createCharacterDiceSprite() { auto sprite = CharacterDiceSprite::create(); sprite->setTag(CHARACTER_DICE_SPRITE_TAG); auto touchListener = EventListenerTouchOneByOne::create(); touchListener->onTouchBegan = [&](Touch* touch, Event* event) { auto bounds = event->getCurrentTarget()->getBoundingBox(); auto touchInSprite = bounds.containsPoint(touch->getLocation()); bool containsBoot = true; auto canMove = this->_isInteractionEnabled() && touchInSprite && containsBoot; if (canMove) { Vector<Node*> visibleNodes; visibleNodes.pushBack(this->getObjectsLayer()->getChildByTag(CHARACTER_DICE_SPRITE_TAG)); visibleNodes.pushBack(this->_getNodeForCharacterPosition()); visibleNodes.pushBack(this->_getNodesForAdjacentCharacterPosition()); this->_addOverlayWithVisibleNodes(visibleNodes); } return canMove; }; touchListener->onTouchMoved = [=](Touch* touch, Event* event) { auto touchLocation = touch->getLocation(); for (auto adjacentNode : this->_getNodesForAdjacentCharacterPosition()) { Color3B color = Color3B::WHITE; if (adjacentNode->getBoundingBox().containsPoint(touchLocation)) { color = Color3B(170, 255, 170); } adjacentNode->setColor(color); } sprite->setPosition(touch->getLocation()); }; touchListener->onTouchEnded = [=](Touch* touch, Event* event) { bool characterMoved = false; auto touchLocation = touch->getLocation(); auto coordinate = this->getGame()->getCharacterPosition(); auto scenePosition = this->_positionInScene(coordinate); this->_removeOverlay(); for (auto adjacentNode : this->_getNodesForAdjacentCharacterPosition()) { adjacentNode->setColor(Color3B::WHITE); if (adjacentNode->getBoundingBox().containsPoint(touchLocation)) { characterMoved = true; auto newCoordinate = this->_positionInGameCoordinate(touchLocation); auto newPosition = this->_positionInScene(newCoordinate); auto moveNewPosition = MoveTo::create(RETURN_CHARACTER_DURATION, newPosition); auto actionEnded = CallFunc::create([=]() { this->getGame()->setCharacterPosition(newCoordinate); }); sprite->runAction(Sequence::create(moveNewPosition, actionEnded, NULL)); } } if (!characterMoved) { auto moveBack = MoveTo::create(RETURN_CHARACTER_DURATION, scenePosition); sprite->runAction(moveBack); } }; auto dispatcher = Director::getInstance()->getEventDispatcher(); dispatcher->addEventListenerWithSceneGraphPriority(touchListener, sprite); return sprite; } Layer* GameplayScene::getObjectsLayer() { return (Layer*) this->getChildByTag(OBJECTS_LAYER_TAG); } Layer* GameplayScene::getControlsLayer() { return (Layer*) this->getChildByTag(CONTROLS_LAYER_TAG); } Vec2 GameplayScene::_positionInScene(Vec2 gameCoordinate) { auto centerPosition = INITIAL_POSITION; auto centerOfScene = this->_centerOfScene(); auto offsetX = gameCoordinate.x - centerPosition.x; auto offsetY = gameCoordinate.y - centerPosition.y; return Vec2(centerOfScene.x + offsetX * TILE_DIMENSION, centerOfScene.y + offsetY * TILE_DIMENSION); } Vec2 GameplayScene::_positionInGameCoordinate(Vec2 scenePosition) { auto centerPosition = INITIAL_POSITION; auto centerOfScene = this->_centerOfScene(); auto offsetX = scenePosition.x - centerOfScene.x; auto offsetY = scenePosition.y - centerOfScene.y; auto halfTileDimension = TILE_DIMENSION / 2; offsetX > halfTileDimension ? offsetX += halfTileDimension : offsetX -= halfTileDimension; offsetY > halfTileDimension ? offsetY += halfTileDimension : offsetY -= halfTileDimension; return Vec2(centerPosition.x + int(offsetX / TILE_DIMENSION), centerPosition.y + int(offsetY / TILE_DIMENSION)); } void GameplayScene::_adjustCharacterDiceSpritePosition() { auto sprite = this->getObjectsLayer()->getChildByTag(CHARACTER_DICE_SPRITE_TAG); auto characterPosition = this->getGame()->getCharacterPosition(); sprite->setPosition(this->_positionInScene(characterPosition)); } void GameplayScene::_addOverlayWithVisibleNodes(Vector<Node *> visibleNodes) { auto overlayLayer = LayerColor::create(Color4B(0, 0, 0, 0)); overlayLayer->setTag(OVERLAY_LAYER_TAG); this->getObjectsLayer()->addChild(overlayLayer, OVERLAY_Z_ORDER); auto fadeIn = FadeTo::create(OVERLAY_DURATION, OVERLAY_OPACITY); overlayLayer->runAction(fadeIn); for (auto visibleNode : visibleNodes) { auto newZOrder = visibleNode->getLocalZOrder() + OVERLAY_Z_ORDER; visibleNode->setLocalZOrder(newZOrder); } this->setInteractableNodes(visibleNodes); } void GameplayScene::_removeOverlay() { this->_disableInteractions(); auto overlayLayer = this->getObjectsLayer()->getChildByTag(OVERLAY_LAYER_TAG); auto fadeOut = FadeOut::create(OVERLAY_DURATION); auto changeLayer = CallFunc::create([=]() { for (auto node : this->getInteractableNodes()) { auto oldZOrder = node->getLocalZOrder() - OVERLAY_Z_ORDER; node->setLocalZOrder(oldZOrder); } }); auto removeSelf = RemoveSelf::create(); auto animationEnded = CallFunc::create([=]() { this->_enableInteractions(); }); overlayLayer->runAction(Sequence::create(fadeOut, changeLayer, removeSelf, animationEnded, NULL)); } Vec2 GameplayScene::_centerOfScene() { Vec2 visibleOrigin = Director::getInstance()->getVisibleOrigin(); Size visibleSize = Director::getInstance()->getVisibleSize(); return Vec2(visibleSize.width / 2 + visibleOrigin.x, visibleSize.height / 2 + visibleOrigin.y); } Node* GameplayScene::_getNodeForCharacterPosition() { auto position = this->getGame()->getCharacterPosition(); auto name = this->getGame()->getDungeon()->nameForPosition(position); return this->getObjectsLayer()->getChildByName(name); } Vector<Node*> GameplayScene::_getNodesForAdjacentCharacterPosition() { Node* activeLayer = this->getObjectsLayer(); auto overlayLayer = this->getChildByTag(OVERLAY_LAYER_TAG); if (overlayLayer) { activeLayer = overlayLayer; } Vector<Node*> nodes; auto position = this->getGame()->getCharacterPosition(); auto adjacentPositions = this->getGame()->getDungeon()->adjacentPositionsTo(position); for (auto adjacentPosition : adjacentPositions) { auto name = this->getGame()->getDungeon()->nameForPosition(adjacentPosition); nodes.pushBack(activeLayer->getChildByName(name)); } return nodes; } bool GameplayScene::_isInteractionEnabled() { return _userInteractionEnabled; } void GameplayScene::_disableInteractions() { _userInteractionEnabled = false; } void GameplayScene::_enableInteractions() { _userInteractionEnabled = true; }<|endoftext|>
<commit_before>/*========================================================================= * * Copyright Insight Software Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #ifndef itkFixedArray_hxx #define itkFixedArray_hxx #include "itkNumericTraitsFixedArrayPixel.h" namespace itk { /** * Constructor to initialize entire array to one value. */ template< typename TValue, unsigned int VLength > FixedArray< TValue, VLength > ::FixedArray(const ValueType & r) { for ( Iterator i = Begin(); i != End(); ++i ) { *i = r; } } /** * Constructor assumes input points to array of correct size. * Values are copied individually instead of with a binary copy. This * allows the ValueType's assignment operator to be executed. */ template< typename TValue, unsigned int VLength > FixedArray< TValue, VLength > ::FixedArray(const ValueType r[VLength]) { ConstIterator input = r; Iterator i = this->Begin(); while ( i != this->End() ) { *i++ = *input++; } } /** * Assignment operator assumes input points to array of correct size. * Values are copied individually instead of with a binary copy. This * allows the ValueType's assignment operator to be executed. */ template< typename TValue, unsigned int VLength > FixedArray< TValue, VLength > & FixedArray< TValue, VLength > ::operator=(const ValueType r[VLength]) { if ( r != m_InternalArray ) { ConstIterator input = r; Iterator i = this->Begin(); while ( i != this->End() ) { *i++ = *input++; } } return *this; } /** * Operator != compares different types of arrays. */ template< typename TValue, unsigned int VLength > bool FixedArray< TValue, VLength > ::operator==(const FixedArray & r) const { ConstIterator i = this->Begin(); ConstIterator j = r.Begin(); while ( i != this->End() ) { CLANG_PRAGMA_PUSH CLANG_SUPPRESS_Wfloat_equal if ( *i != *j ) CLANG_PRAGMA_POP { return false; } ++j; ++i; } return true; } /** * Get an Iterator for the beginning of the FixedArray. */ template< typename TValue, unsigned int VLength > typename FixedArray< TValue, VLength >::Iterator FixedArray< TValue, VLength > ::Begin() { return Iterator(m_InternalArray); } /** * Get a ConstIterator for the beginning of the FixedArray. */ template< typename TValue, unsigned int VLength > typename FixedArray< TValue, VLength >::ConstIterator FixedArray< TValue, VLength > ::Begin() const { return ConstIterator(m_InternalArray); } /** * Get an Iterator for the end of the FixedArray. */ template< typename TValue, unsigned int VLength > typename FixedArray< TValue, VLength >::Iterator FixedArray< TValue, VLength > ::End() { return Iterator(m_InternalArray + VLength); } /** * Get a ConstIterator for the end of the FixedArray. */ template< typename TValue, unsigned int VLength > typename FixedArray< TValue, VLength >::ConstIterator FixedArray< TValue, VLength > ::End() const { return ConstIterator(m_InternalArray + VLength); } #if !defined ( ITK_LEGACY_REMOVE ) /** * Get a begin ReverseIterator. */ template< typename TValue, unsigned int VLength > typename FixedArray< TValue, VLength >::ReverseIterator FixedArray< TValue, VLength > ::rBegin() { return ReverseIterator(m_InternalArray + VLength); } /** * Get a begin ConstReverseIterator. */ template< typename TValue, unsigned int VLength > typename FixedArray< TValue, VLength >::ConstReverseIterator FixedArray< TValue, VLength > ::rBegin() const { return ConstReverseIterator(m_InternalArray + VLength); } /** * Get an end ReverseIterator. */ template< typename TValue, unsigned int VLength > typename FixedArray< TValue, VLength >::ReverseIterator FixedArray< TValue, VLength > ::rEnd() { return ReverseIterator(m_InternalArray); } /** * Get an end ConstReverseIterator. */ template< typename TValue, unsigned int VLength > typename FixedArray< TValue, VLength >::ConstReverseIterator FixedArray< TValue, VLength > ::rEnd() const { return ConstReverseIterator(m_InternalArray); } #endif // defined ( ITK_LEGACY_REMOVE ) /** * Get the size of the FixedArray. */ template< typename TValue, unsigned int VLength > typename FixedArray< TValue, VLength >::SizeType FixedArray< TValue, VLength > ::Size() const { return VLength; } /** * Fill all elements of the array with the given value. */ template< typename TValue, unsigned int VLength > void FixedArray< TValue, VLength > ::Fill(const ValueType & value) { Iterator i = this->Begin(); while ( i != this->End() ) { *i++ = value; } } /** * Return an FixedArray with all elements assigned to the given value. */ template< typename TValue, unsigned int VLength > FixedArray< TValue, VLength > FixedArray< TValue, VLength > ::Filled(const ValueType & value) { FixedArray< ValueType, VLength > array; array.Fill(value); return array; } template< typename TValue, unsigned int VLength > std::ostream & operator<<(std::ostream & os, const FixedArray< TValue, VLength > & arr) { os << "["; if ( VLength == 1 ) { os << arr[0]; } else { for ( int i = 0; i < static_cast< int >( VLength ) - 1; ++i ) { os << arr[i] << ", "; } os << arr[VLength - 1]; } os << "]"; return os; } } // namespace itk #endif <commit_msg>STYLE: itkFixedArray.hxx using std::equal, and C++11 fill_n and copy_n<commit_after>/*========================================================================= * * Copyright Insight Software Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #ifndef itkFixedArray_hxx #define itkFixedArray_hxx #include "itkNumericTraitsFixedArrayPixel.h" namespace itk { /** * Constructor to initialize entire array to one value. */ template< typename TValue, unsigned int VLength > FixedArray< TValue, VLength > ::FixedArray(const ValueType & r) { std::fill_n(m_InternalArray, VLength, r); } /** * Constructor assumes input points to array of correct size. * Values are copied individually instead of with a binary copy. This * allows the ValueType's assignment operator to be executed. */ template< typename TValue, unsigned int VLength > FixedArray< TValue, VLength > ::FixedArray(const ValueType r[VLength]) { std::copy_n(r, VLength, m_InternalArray); } /** * Assignment operator assumes input points to array of correct size. * Values are copied individually instead of with a binary copy. This * allows the ValueType's assignment operator to be executed. */ template< typename TValue, unsigned int VLength > FixedArray< TValue, VLength > & FixedArray< TValue, VLength > ::operator=(const ValueType r[VLength]) { if ( r != m_InternalArray ) { std::copy_n(r, VLength, m_InternalArray); } return *this; } /** * Operator != compares different types of arrays. */ template< typename TValue, unsigned int VLength > bool FixedArray< TValue, VLength > ::operator==(const FixedArray & r) const { return std::equal(m_InternalArray, m_InternalArray + VLength, r.m_InternalArray); } /** * Get an Iterator for the beginning of the FixedArray. */ template< typename TValue, unsigned int VLength > typename FixedArray< TValue, VLength >::Iterator FixedArray< TValue, VLength > ::Begin() { return Iterator(m_InternalArray); } /** * Get a ConstIterator for the beginning of the FixedArray. */ template< typename TValue, unsigned int VLength > typename FixedArray< TValue, VLength >::ConstIterator FixedArray< TValue, VLength > ::Begin() const { return ConstIterator(m_InternalArray); } /** * Get an Iterator for the end of the FixedArray. */ template< typename TValue, unsigned int VLength > typename FixedArray< TValue, VLength >::Iterator FixedArray< TValue, VLength > ::End() { return Iterator(m_InternalArray + VLength); } /** * Get a ConstIterator for the end of the FixedArray. */ template< typename TValue, unsigned int VLength > typename FixedArray< TValue, VLength >::ConstIterator FixedArray< TValue, VLength > ::End() const { return ConstIterator(m_InternalArray + VLength); } #if !defined ( ITK_LEGACY_REMOVE ) /** * Get a begin ReverseIterator. */ template< typename TValue, unsigned int VLength > typename FixedArray< TValue, VLength >::ReverseIterator FixedArray< TValue, VLength > ::rBegin() { return ReverseIterator(m_InternalArray + VLength); } /** * Get a begin ConstReverseIterator. */ template< typename TValue, unsigned int VLength > typename FixedArray< TValue, VLength >::ConstReverseIterator FixedArray< TValue, VLength > ::rBegin() const { return ConstReverseIterator(m_InternalArray + VLength); } /** * Get an end ReverseIterator. */ template< typename TValue, unsigned int VLength > typename FixedArray< TValue, VLength >::ReverseIterator FixedArray< TValue, VLength > ::rEnd() { return ReverseIterator(m_InternalArray); } /** * Get an end ConstReverseIterator. */ template< typename TValue, unsigned int VLength > typename FixedArray< TValue, VLength >::ConstReverseIterator FixedArray< TValue, VLength > ::rEnd() const { return ConstReverseIterator(m_InternalArray); } #endif // defined ( ITK_LEGACY_REMOVE ) /** * Get the size of the FixedArray. */ template< typename TValue, unsigned int VLength > typename FixedArray< TValue, VLength >::SizeType FixedArray< TValue, VLength > ::Size() const { return VLength; } /** * Fill all elements of the array with the given value. */ template< typename TValue, unsigned int VLength > void FixedArray< TValue, VLength > ::Fill(const ValueType & value) { std::fill_n(m_InternalArray, VLength, value); } /** * Return an FixedArray with all elements assigned to the given value. */ template< typename TValue, unsigned int VLength > FixedArray< TValue, VLength > FixedArray< TValue, VLength > ::Filled(const ValueType & value) { FixedArray< ValueType, VLength > array; array.Fill(value); return array; } template< typename TValue, unsigned int VLength > std::ostream & operator<<(std::ostream & os, const FixedArray< TValue, VLength > & arr) { os << "["; if ( VLength == 1 ) { os << arr[0]; } else { for ( int i = 0; i < static_cast< int >( VLength ) - 1; ++i ) { os << arr[i] << ", "; } os << arr[VLength - 1]; } os << "]"; return os; } } // namespace itk #endif <|endoftext|>
<commit_before>/*========================================================================= * * Copyright Insight Software Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ /*========================================================================= * * Portions of this file are subject to the VTK Toolkit Version 3 copyright. * * Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen * * For complete copyright, license and disclaimer of warranty information * please refer to the NOTICE file at the top of the ITK source tree. * *=========================================================================*/ #include "itkTestDriverIncludeRequiredIOFactories.h" /* Select the environment variable holding the shared library runtime search path for this platform. */ /* Linux */ #if defined(__linux) || defined(__FreeBSD__) || defined(__OpenBSD__) # define ITK_TEST_DRIVER_LDPATH "LD_LIBRARY_PATH" # define ITK_TEST_DRIVER_LDPATH64 ITK_TEST_DRIVER_LDPATH /* OSX */ #elif defined(__APPLE__) # define ITK_TEST_DRIVER_LDPATH "DYLD_LIBRARY_PATH" # define ITK_TEST_DRIVER_LDPATH64 ITK_TEST_DRIVER_LDPATH /* AIX */ #elif defined(_AIX) # define ITK_TEST_DRIVER_LDPATH "LIBPATH" # define ITK_TEST_DRIVER_LDPATH64 ITK_TEST_DRIVER_LDPATH /* SUN */ #elif defined(__sun) # define ITK_TEST_DRIVER_LDPATH "LD_LIBRARY_PATH" # define ITK_TEST_DRIVER_LDPATH64 "LD_LIBRARY_PATH_64" /* HP-UX */ #elif defined(__hpux) # define ITK_TEST_DRIVER_LDPATH "SHLIB_PATH" # define ITK_TEST_DRIVER_LDPATH64 "LD_LIBRARY_PATH" /* SGI MIPS */ #elif defined(__sgi) && defined(_MIPS_SIM) # if _MIPS_SIM == _ABIO32 # define ITK_TEST_DRIVER_LDPATH "LD_LIBRARY_PATH" # elif _MIPS_SIM == _ABIN32 # define ITK_TEST_DRIVER_LDPATH "LD_LIBRARYN32_PATH" # endif # define ITK_TEST_DRIVER_LDPATH64 "LD_LIBRARY64_PATH" /* Cygwin */ #elif defined(__CYGWIN__) # define ITK_TEST_DRIVER_LDPATH "PATH" # define ITK_TEST_DRIVER_LDPATH64 ITK_TEST_DRIVER_LDPATH /* Windows */ #elif defined(_WIN32) # define ITK_TEST_DRIVER_LDPATH "PATH" # define ITK_TEST_DRIVER_LDPATH64 ITK_TEST_DRIVER_LDPATH /* Guess on this unknown system. */ #else # define ITK_TEST_DRIVER_LDPATH "LD_LIBRARY_PATH" # define ITK_TEST_DRIVER_LDPATH64 ITK_TEST_DRIVER_LDPATH #endif #if defined(_WIN32) && !defined(__CYGWIN__) # define ITK_TEST_DRIVER_PATH_SEP ';' # define ITK_TEST_DRIVER_PATH_SLASH '\\' #else # define ITK_TEST_DRIVER_PATH_SEP ':' # define ITK_TEST_DRIVER_PATH_SLASH '/' #endif void AddEntriesBeforeLibraryPath( const ArgumentsList & args ) { unsigned int i = 0; while( i < args.size() ) { std::string libpath = ITK_TEST_DRIVER_LDPATH; libpath += "="; libpath += args[i]; char *oldenv = getenv(ITK_TEST_DRIVER_LDPATH); if ( oldenv ) { libpath += ITK_TEST_DRIVER_PATH_SEP; libpath += oldenv; } itksys::SystemTools::PutEnv( libpath.c_str() ); // on some 64 bit systems, LD_LIBRARY_PATH_64 is used before // LD_LIBRARY_PATH if it is set. It can lead the test to load // the system library instead of the expected one, so this // var must also be set if ( std::string(ITK_TEST_DRIVER_LDPATH) != ITK_TEST_DRIVER_LDPATH64 ) { std::string libpath64 = ITK_TEST_DRIVER_LDPATH64; libpath64 += "="; libpath64 += args[i]; char *oldenv64 = getenv(ITK_TEST_DRIVER_LDPATH64); if ( oldenv64 ) { libpath64 += ITK_TEST_DRIVER_PATH_SEP; libpath64 += oldenv64; } itksys::SystemTools::PutEnv( libpath64.c_str() ); } i++; } } void AddEntriesBeforeEnvironment( const ArgumentsList & args ) { unsigned int i = 0; while( i < args.size() ) { std::string env = args[i]; env += "="; env += args[i+1]; char *oldenv = getenv( args[i] ); if ( oldenv ) { env += ITK_TEST_DRIVER_PATH_SEP; env += oldenv; } itksys::SystemTools::PutEnv( env.c_str() ); i += 2; } } void AddEntriesBeforeEnvironmentWithSeparator( const ArgumentsList & args ) { unsigned int i = 0; while( i < args.size() ) { std::string env = args[i]; env += "="; env += args[i+1]; char *oldenv = getenv( args[i] ); if ( oldenv ) { env += args[i+2]; env += oldenv; } itksys::SystemTools::PutEnv( env.c_str() ); i += 3; } } int TestDriverInvokeProcess( const ArgumentsList & args ) { // a NULL is required at the end of the table char ** argv = new char *[args.size() + 1]; for ( unsigned int i = 0; i < args.size(); i++ ) { argv[i] = args[i]; } argv[args.size()] = NULL; itksysProcess *process = itksysProcess_New(); itksysProcess_SetCommand(process, argv); itksysProcess_SetPipeShared(process, itksysProcess_Pipe_STDOUT, true); itksysProcess_SetPipeShared(process, itksysProcess_Pipe_STDERR, true); itksysProcess_Execute(process); itksysProcess_WaitForExit(process, NULL); delete[] argv; int state = itksysProcess_GetState(process); switch( state ) { case itksysProcess_State_Error: { std::cerr << "itkTestDriver: Process error: " << itksysProcess_GetErrorString(process) << std::endl; itksysProcess_Delete(process); return 1; } case itksysProcess_State_Exception: { std::cerr << "itkTestDriver: Process exception: " << itksysProcess_GetExceptionString(process) << std::endl; itksysProcess_Delete(process); return 1; } case itksysProcess_State_Executing: { // this is not a possible state after itksysProcess_WaitForExit std::cerr << "itkTestDriver: Internal error: process can't be in Executing State." << std::endl; itksysProcess_Delete(process); return 1; } case itksysProcess_State_Exited: { // this is the normal case - it is treated later break; } case itksysProcess_State_Expired: { // this is not a possible state after itksysProcess_WaitForExit std::cerr << "itkTestDriver: Internal error: process can't be in Expired State." << std::endl; itksysProcess_Delete(process); return 1; } case itksysProcess_State_Killed: { std::cerr << "itkTestDriver: The process has been killed." << std::endl; itksysProcess_Delete(process); return 1; } case itksysProcess_State_Disowned: { std::cerr << "itkTestDriver: Process disowned." << std::endl; itksysProcess_Delete(process); return 1; } default: { // this is not a possible state after itksysProcess_WaitForExit std::cerr << "itkTestDriver: Internal error: unknown State." << std::endl; itksysProcess_Delete(process); return 1; } } int retCode = itksysProcess_GetExitValue(process); if ( retCode != 0 ) { std::cerr << "itkTestDriver: Process exited with return value: " << retCode << std::endl; } itksysProcess_Delete(process); return retCode; } int main(int ac, char *av[]) { RegisterRequiredFactories(); ProcessedOutputType po; int result = 0; result = ProcessArguments(&ac, &av, &po); if ( po.externalProcessMustBeCalled && po.args.empty() ) { usage(); return 1; } if ( !po.externalProcessMustBeCalled && !po.args.empty() ) { usage(); return 1; } if ( !result && po.externalProcessMustBeCalled ) { AddEntriesBeforeLibraryPath( po.add_before_libpath ); AddEntriesBeforeEnvironment( po.add_before_env ); AddEntriesBeforeEnvironmentWithSeparator( po.add_before_env_with_sep ); result = TestDriverInvokeProcess( po.args ); } if (result == 0) { #include "itkTestDriverBeforeTest.inc" #include "itkTestDriverAfterTest.inc" } return result; } <commit_msg>BUG: itkTestDriver should only print usage once<commit_after>/*========================================================================= * * Copyright Insight Software Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ /*========================================================================= * * Portions of this file are subject to the VTK Toolkit Version 3 copyright. * * Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen * * For complete copyright, license and disclaimer of warranty information * please refer to the NOTICE file at the top of the ITK source tree. * *=========================================================================*/ #include "itkTestDriverIncludeRequiredIOFactories.h" /* Select the environment variable holding the shared library runtime search path for this platform. */ /* Linux */ #if defined(__linux) || defined(__FreeBSD__) || defined(__OpenBSD__) # define ITK_TEST_DRIVER_LDPATH "LD_LIBRARY_PATH" # define ITK_TEST_DRIVER_LDPATH64 ITK_TEST_DRIVER_LDPATH /* OSX */ #elif defined(__APPLE__) # define ITK_TEST_DRIVER_LDPATH "DYLD_LIBRARY_PATH" # define ITK_TEST_DRIVER_LDPATH64 ITK_TEST_DRIVER_LDPATH /* AIX */ #elif defined(_AIX) # define ITK_TEST_DRIVER_LDPATH "LIBPATH" # define ITK_TEST_DRIVER_LDPATH64 ITK_TEST_DRIVER_LDPATH /* SUN */ #elif defined(__sun) # define ITK_TEST_DRIVER_LDPATH "LD_LIBRARY_PATH" # define ITK_TEST_DRIVER_LDPATH64 "LD_LIBRARY_PATH_64" /* HP-UX */ #elif defined(__hpux) # define ITK_TEST_DRIVER_LDPATH "SHLIB_PATH" # define ITK_TEST_DRIVER_LDPATH64 "LD_LIBRARY_PATH" /* SGI MIPS */ #elif defined(__sgi) && defined(_MIPS_SIM) # if _MIPS_SIM == _ABIO32 # define ITK_TEST_DRIVER_LDPATH "LD_LIBRARY_PATH" # elif _MIPS_SIM == _ABIN32 # define ITK_TEST_DRIVER_LDPATH "LD_LIBRARYN32_PATH" # endif # define ITK_TEST_DRIVER_LDPATH64 "LD_LIBRARY64_PATH" /* Cygwin */ #elif defined(__CYGWIN__) # define ITK_TEST_DRIVER_LDPATH "PATH" # define ITK_TEST_DRIVER_LDPATH64 ITK_TEST_DRIVER_LDPATH /* Windows */ #elif defined(_WIN32) # define ITK_TEST_DRIVER_LDPATH "PATH" # define ITK_TEST_DRIVER_LDPATH64 ITK_TEST_DRIVER_LDPATH /* Guess on this unknown system. */ #else # define ITK_TEST_DRIVER_LDPATH "LD_LIBRARY_PATH" # define ITK_TEST_DRIVER_LDPATH64 ITK_TEST_DRIVER_LDPATH #endif #if defined(_WIN32) && !defined(__CYGWIN__) # define ITK_TEST_DRIVER_PATH_SEP ';' # define ITK_TEST_DRIVER_PATH_SLASH '\\' #else # define ITK_TEST_DRIVER_PATH_SEP ':' # define ITK_TEST_DRIVER_PATH_SLASH '/' #endif void AddEntriesBeforeLibraryPath( const ArgumentsList & args ) { unsigned int i = 0; while( i < args.size() ) { std::string libpath = ITK_TEST_DRIVER_LDPATH; libpath += "="; libpath += args[i]; char *oldenv = getenv(ITK_TEST_DRIVER_LDPATH); if ( oldenv ) { libpath += ITK_TEST_DRIVER_PATH_SEP; libpath += oldenv; } itksys::SystemTools::PutEnv( libpath.c_str() ); // on some 64 bit systems, LD_LIBRARY_PATH_64 is used before // LD_LIBRARY_PATH if it is set. It can lead the test to load // the system library instead of the expected one, so this // var must also be set if ( std::string(ITK_TEST_DRIVER_LDPATH) != ITK_TEST_DRIVER_LDPATH64 ) { std::string libpath64 = ITK_TEST_DRIVER_LDPATH64; libpath64 += "="; libpath64 += args[i]; char *oldenv64 = getenv(ITK_TEST_DRIVER_LDPATH64); if ( oldenv64 ) { libpath64 += ITK_TEST_DRIVER_PATH_SEP; libpath64 += oldenv64; } itksys::SystemTools::PutEnv( libpath64.c_str() ); } i++; } } void AddEntriesBeforeEnvironment( const ArgumentsList & args ) { unsigned int i = 0; while( i < args.size() ) { std::string env = args[i]; env += "="; env += args[i+1]; char *oldenv = getenv( args[i] ); if ( oldenv ) { env += ITK_TEST_DRIVER_PATH_SEP; env += oldenv; } itksys::SystemTools::PutEnv( env.c_str() ); i += 2; } } void AddEntriesBeforeEnvironmentWithSeparator( const ArgumentsList & args ) { unsigned int i = 0; while( i < args.size() ) { std::string env = args[i]; env += "="; env += args[i+1]; char *oldenv = getenv( args[i] ); if ( oldenv ) { env += args[i+2]; env += oldenv; } itksys::SystemTools::PutEnv( env.c_str() ); i += 3; } } int TestDriverInvokeProcess( const ArgumentsList & args ) { // a NULL is required at the end of the table char ** argv = new char *[args.size() + 1]; for ( unsigned int i = 0; i < args.size(); i++ ) { argv[i] = args[i]; } argv[args.size()] = NULL; itksysProcess *process = itksysProcess_New(); itksysProcess_SetCommand(process, argv); itksysProcess_SetPipeShared(process, itksysProcess_Pipe_STDOUT, true); itksysProcess_SetPipeShared(process, itksysProcess_Pipe_STDERR, true); itksysProcess_Execute(process); itksysProcess_WaitForExit(process, NULL); delete[] argv; int state = itksysProcess_GetState(process); switch( state ) { case itksysProcess_State_Error: { std::cerr << "itkTestDriver: Process error: " << itksysProcess_GetErrorString(process) << std::endl; itksysProcess_Delete(process); return 1; } case itksysProcess_State_Exception: { std::cerr << "itkTestDriver: Process exception: " << itksysProcess_GetExceptionString(process) << std::endl; itksysProcess_Delete(process); return 1; } case itksysProcess_State_Executing: { // this is not a possible state after itksysProcess_WaitForExit std::cerr << "itkTestDriver: Internal error: process can't be in Executing State." << std::endl; itksysProcess_Delete(process); return 1; } case itksysProcess_State_Exited: { // this is the normal case - it is treated later break; } case itksysProcess_State_Expired: { // this is not a possible state after itksysProcess_WaitForExit std::cerr << "itkTestDriver: Internal error: process can't be in Expired State." << std::endl; itksysProcess_Delete(process); return 1; } case itksysProcess_State_Killed: { std::cerr << "itkTestDriver: The process has been killed." << std::endl; itksysProcess_Delete(process); return 1; } case itksysProcess_State_Disowned: { std::cerr << "itkTestDriver: Process disowned." << std::endl; itksysProcess_Delete(process); return 1; } default: { // this is not a possible state after itksysProcess_WaitForExit std::cerr << "itkTestDriver: Internal error: unknown State." << std::endl; itksysProcess_Delete(process); return 1; } } int retCode = itksysProcess_GetExitValue(process); if ( retCode != 0 ) { std::cerr << "itkTestDriver: Process exited with return value: " << retCode << std::endl; } itksysProcess_Delete(process); return retCode; } int main(int ac, char *av[]) { RegisterRequiredFactories(); ProcessedOutputType po; int result = 0; result = ProcessArguments(&ac, &av, &po); if( result ) { // There was a problem parsing the arguments, so usage has already // been printed, just return return 1; } if ( po.externalProcessMustBeCalled && po.args.empty() ) { usage(); return 1; } if ( !po.externalProcessMustBeCalled && !po.args.empty() ) { usage(); return 1; } if ( !result && po.externalProcessMustBeCalled ) { AddEntriesBeforeLibraryPath( po.add_before_libpath ); AddEntriesBeforeEnvironment( po.add_before_env ); AddEntriesBeforeEnvironmentWithSeparator( po.add_before_env_with_sep ); result = TestDriverInvokeProcess( po.args ); } if (result == 0) { #include "itkTestDriverBeforeTest.inc" #include "itkTestDriverAfterTest.inc" } return result; } <|endoftext|>
<commit_before>#include "Character.h" #include "PlayScene.h" CCharacter::CCharacter(void) { } CCharacter::~CCharacter(void) { } void CCharacter::initStatus( void ) { } /* Լ : DetermineAttackTarget : ü attack_target ϴ Լ ϸ ȴ. Ŀ GoAttackTarget Լ ϸ ֿ : ̱ Scene ִ Police迭 鼭 NNPoint Լ ̿ Ÿ ϰ Ÿ Ͽ شϴ idx Ÿ ȯѴ. : 2013/11/03 : 2013/11/04 ISSUE : 1 . switch ݺǴ For ϳ ãƾ . . */ void CCharacter::DetermineAttackTarget() { float return_distnace = 1000000.0f; float next_distance; CZombie *tmp_closer_target_zombie = NULL; CPolice *tmp_closer_target_police = NULL; CCharacter *return_target = NULL; switch(this->GetIdentity()) { case Zombie: for(const auto& child : CPlayScene::GetInstance()->GetPoliceList()) { next_distance = this->GetPosition().GetDistance(child->GetPosition()); if(return_distnace > next_distance) { return_distnace = next_distance; m_AttackTarget = child; } } if(m_AttackTarget == NULL) m_AttackTarget = CPlayScene::GetInstance()->GetMapCreator()->GetPoliceBase(); break; case Police: for(const auto& child : CPlayScene::GetInstance()->GetZombieList()) { next_distance= this->GetPosition().GetDistance(child->GetPosition()); if(return_distnace > next_distance) { return_distnace = next_distance; m_AttackTarget = child; } } if(m_AttackTarget == NULL) m_AttackTarget = CPlayScene::GetInstance()->GetMapCreator()->GetZombieBase(); break; default: break; } } void CCharacter::InitSprite( std::wstring imagePath ) { m_Sprite = NNSprite::Create(imagePath); // θ ġ ޱ // θ ij ġ ϰ // ڽ sprite (0, 0) ʱȭѴ. // ̰Ͷ ѽð Ф m_Sprite->SetPosition(0.0f, 0.0f); AddChild(m_Sprite, 1); } void CCharacter::SetRandomPositionAroundBase() { NNPoint baseLocation; switch (m_Identity) { case Zombie: baseLocation = CPlayScene::GetInstance()->GetMapCreator()->GetZombieBase()->GetPosition(); baseLocation.SetX(baseLocation.GetX()+TILE_SIZE_X); baseLocation.SetY(baseLocation.GetY()+TILE_SIZE_Y); break; case Police: baseLocation = CPlayScene::GetInstance()->GetMapCreator()->GetPoliceBase()->GetPosition(); baseLocation.SetX(baseLocation.GetX()-TILE_SIZE_X); break; default: break; } int random_location_x = rand() % TILE_SIZE_X; int random_location_y = rand() % TILE_SIZE_Y; SetPosition((baseLocation.GetX()+random_location_x),(baseLocation.GetY()+random_location_y)); } void CCharacter::Render() { NNObject::Render(); } void CCharacter::Update( float dTime ) { DetermineAttackTarget(); if(IsAttack()) Attack(); else GoToAttackTarget(dTime); } void CCharacter::Attack() { CCharacter* target = this->m_AttackTarget; if(this->m_AttackTarget){ int damage = this->GetAttackPower() - target->GetDefensivePower(); target->SetHP(target->GetHP()-damage) ; } } void CCharacter::GoToAttackTarget(float dTime) { float gap_x = m_AttackTarget->GetPositionX() - m_Position.GetX(); float gap_y = m_AttackTarget->GetPositionY() - m_Position.GetY(); float t_x = (gap_x) / (gap_x+gap_y); float t_y = (gap_y) / (gap_x+gap_y); this->SetPosition(this->m_Position - NNPoint( (m_MovingSpeed*t_x),( m_MovingSpeed*t_y) )*dTime); } bool CCharacter::IsAttack() { float distance_attacktarget; distance_attacktarget = this->GetPosition().GetDistance(m_AttackTarget->GetPosition()); if(distance_attacktarget <= m_AttackRange) return true; else return false; } <commit_msg>주석 추가. 일부 코드 리팩토링<commit_after>#include "Character.h" #include "PlayScene.h" CCharacter::CCharacter(void) { } CCharacter::~CCharacter(void) { } void CCharacter::initStatus( void ) { } /* Լ : DetermineAttackTarget : ü attack_target ϴ Լ ϸ ȴ. Ŀ GoAttackTarget Լ ϸ ֿ : ̱ Scene ִ Police迭 鼭 NNPoint Լ ̿ Ÿ ϰ Ÿ Ͽ شϴ idx Ÿ ȯѴ. : 2013/11/03 : 2013/11/14 ISSUE : 1 . switch ݺǴ For ϳ ãƾ . . 11/14 : Enemy (NULL) attackTarget Base ϵ */ void CCharacter::DetermineAttackTarget() { float return_distnace = 1000000.0f; float next_distance; CZombie *tmp_closer_target_zombie = NULL; CPolice *tmp_closer_target_police = NULL; CCharacter *return_target = NULL; switch(this->GetIdentity()) { case Zombie: for(const auto& child : CPlayScene::GetInstance()->GetPoliceList()) { next_distance = this->GetPosition().GetDistance(child->GetPosition()); if(return_distnace > next_distance) { return_distnace = next_distance; m_AttackTarget = child; } } if(m_AttackTarget == NULL) m_AttackTarget = CPlayScene::GetInstance()->GetMapCreator()->GetPoliceBase(); break; case Police: for(const auto& child : CPlayScene::GetInstance()->GetZombieList()) { next_distance= this->GetPosition().GetDistance(child->GetPosition()); if(return_distnace > next_distance) { return_distnace = next_distance; m_AttackTarget = child; } } if(m_AttackTarget == NULL) m_AttackTarget = CPlayScene::GetInstance()->GetMapCreator()->GetZombieBase(); break; default: break; } } void CCharacter::InitSprite( std::wstring imagePath ) { m_Sprite = NNSprite::Create(imagePath); // θ ġ ޱ // θ ij ġ ϰ // ڽ sprite (0, 0) ʱȭѴ. // ̰Ͷ ѽð Ф m_Sprite->SetPosition(0.0f, 0.0f); AddChild(m_Sprite, 1); } void CCharacter::SetRandomPositionAroundBase() { NNPoint baseLocation; switch (m_Identity) { case Zombie: baseLocation = CPlayScene::GetInstance()->GetMapCreator()->GetZombieBase()->GetPosition(); baseLocation.SetX(baseLocation.GetX()+TILE_SIZE_X); baseLocation.SetY(baseLocation.GetY()+TILE_SIZE_Y); break; case Police: baseLocation = CPlayScene::GetInstance()->GetMapCreator()->GetPoliceBase()->GetPosition(); baseLocation.SetX(baseLocation.GetX()-TILE_SIZE_X); break; default: break; } int random_location_x = rand() % TILE_SIZE_X; int random_location_y = rand() % TILE_SIZE_Y; SetPosition((baseLocation.GetX()+random_location_x),(baseLocation.GetY()+random_location_y)); } void CCharacter::Render() { NNObject::Render(); } void CCharacter::Update( float dTime ) { //AttackTarget ϰ Attack ϸ(Ÿ üũ) //ϰ ׷ Attack Target DetermineAttackTarget(); if(IsAttack()) Attack(); else GoToAttackTarget(dTime); } void CCharacter::Attack() { CCharacter* target = this->m_AttackTarget; if(this->m_AttackTarget){ int damage = this->GetAttackPower() - target->GetDefensivePower(); target->SetHP(target->GetHP()-damage) ; } } /* ȣ. 11/14 Attack_target Ÿ Ͽ ϵ . Issue : ϴ MakeCharacterWalk  */ void CCharacter::GoToAttackTarget(float dTime) { float gap_x = m_AttackTarget->GetPositionX() - m_Position.GetX(); float gap_y = m_AttackTarget->GetPositionY() - m_Position.GetY(); float t_x = (gap_x) / (gap_x+gap_y); float t_y = (gap_y) / (gap_x+gap_y); this->SetPosition(this->m_Position - NNPoint( (m_MovingSpeed*t_x),( m_MovingSpeed*t_y) )*dTime); } /* ȣ. 11/14 Ȳ AttackTarget Ÿ ȿ ִ üũ. ϸ True, (־) False */ bool CCharacter::IsAttack() { float distance_attacktarget; distance_attacktarget = this->GetPosition().GetDistance(m_AttackTarget->GetPosition()); if(distance_attacktarget <= m_AttackRange) return true; else return false; } <|endoftext|>
<commit_before>#include "SystemUtils.h" #include "PlatformSpecificUtils.h" #ifndef _MSC_VER #include <unistd.h> #endif #include <stdio.h> #include <iostream> #include <signal.h> #include <string.h> #include <sys/stat.h> #ifdef _MSC_VER int gettimeofday(struct timeval * tp, struct timezone * tzp) { // Note: some broken versions only have 8 trailing zero's, the correct epoch has 9 trailing zero's static const uint64_t EPOCH = ((uint64_t)116444736000000000ULL); SYSTEMTIME system_time; FILETIME file_time; uint64_t time; GetSystemTime(&system_time); SystemTimeToFileTime(&system_time, &file_time); time = ((uint64_t)file_time.dwLowDateTime); time += ((uint64_t)file_time.dwHighDateTime) << 32; tp->tv_sec = (long)((time - EPOCH) / 10000000L); tp->tv_usec = (long)(system_time.wMilliseconds * 1000); return 0; } #endif namespace pcpp { const SystemCore SystemCores::Core0 = { 0x01, 0 }; const SystemCore SystemCores::Core1 = { 0x02, 1 }; const SystemCore SystemCores::Core2 = { 0x04, 2 }; const SystemCore SystemCores::Core3 = { 0x08, 3 }; const SystemCore SystemCores::Core4 = { 0x10, 4 }; const SystemCore SystemCores::Core5 = { 0x20, 5 }; const SystemCore SystemCores::Core6 = { 0x40, 6 }; const SystemCore SystemCores::Core7 = { 0x80, 7 }; const SystemCore SystemCores::Core8 = { 0x100, 8 }; const SystemCore SystemCores::Core9 = { 0x200, 9 }; const SystemCore SystemCores::Core10 = { 0x400, 10 }; const SystemCore SystemCores::Core11 = { 0x800, 11 }; const SystemCore SystemCores::Core12 = { 0x1000, 12 }; const SystemCore SystemCores::Core13 = { 0x2000, 13 }; const SystemCore SystemCores::Core14 = { 0x4000, 14 }; const SystemCore SystemCores::Core15 = { 0x8000, 15 }; const SystemCore SystemCores::Core16 = { 0x10000, 16 }; const SystemCore SystemCores::Core17 = { 0x20000, 17 }; const SystemCore SystemCores::Core18 = { 0x40000, 18 }; const SystemCore SystemCores::Core19 = { 0x80000, 19 }; const SystemCore SystemCores::Core20 = { 0x100000, 20 }; const SystemCore SystemCores::Core21 = { 0x200000, 21 }; const SystemCore SystemCores::Core22 = { 0x400000, 22 }; const SystemCore SystemCores::Core23 = { 0x800000, 23 }; const SystemCore SystemCores::Core24 = { 0x1000000, 24 }; const SystemCore SystemCores::Core25 = { 0x2000000, 25 }; const SystemCore SystemCores::Core26 = { 0x4000000, 26 }; const SystemCore SystemCores::Core27 = { 0x8000000, 27 }; const SystemCore SystemCores::Core28 = { 0x10000000, 28 }; const SystemCore SystemCores::Core29 = { 0x20000000, 29 }; const SystemCore SystemCores::Core30 = { 0x40000000, 30 }; const SystemCore SystemCores::Core31 = { 0x80000000, 31 }; const SystemCore SystemCores::IdToSystemCore[MAX_NUM_OF_CORES] = { SystemCores::Core0, SystemCores::Core1, SystemCores::Core2, SystemCores::Core3, SystemCores::Core4, SystemCores::Core5, SystemCores::Core6, SystemCores::Core7, SystemCores::Core8, SystemCores::Core9, SystemCores::Core10, SystemCores::Core11, SystemCores::Core12, SystemCores::Core13, SystemCores::Core14, SystemCores::Core15, SystemCores::Core16, SystemCores::Core17, SystemCores::Core18, SystemCores::Core19, SystemCores::Core20, SystemCores::Core21, SystemCores::Core22, SystemCores::Core23, SystemCores::Core24, SystemCores::Core25, SystemCores::Core26, SystemCores::Core27, SystemCores::Core28, SystemCores::Core29, SystemCores::Core30, SystemCores::Core31 }; int getNumOfCores() { #ifdef WIN32 SYSTEM_INFO sysinfo; GetSystemInfo( &sysinfo ); return sysinfo.dwNumberOfProcessors; #else return sysconf(_SC_NPROCESSORS_ONLN); #endif } CoreMask getCoreMaskForAllMachineCores() { int numOfCores = getNumOfCores(); CoreMask result = 0; for (int i = 0; i < numOfCores; i++) { result = result | SystemCores::IdToSystemCore[i].Mask; } return result; } CoreMask createCoreMaskFromCoreVector(std::vector<SystemCore> cores) { CoreMask result = 0; for (std::vector<SystemCore>::iterator iter = cores.begin(); iter != cores.end(); iter++) { result |= iter->Mask; } return result; } CoreMask createCoreMaskFromCoreIds(std::vector<int> coreIds) { CoreMask result = 0; for (std::vector<int>::iterator iter = coreIds.begin(); iter != coreIds.end(); iter++) { result |= SystemCores::IdToSystemCore[*iter].Mask; } return result; } void createCoreVectorFromCoreMask(CoreMask coreMask, std::vector<SystemCore>& resultVec) { int i = 0; while (coreMask != 0) { if (1 & coreMask) { resultVec.push_back(SystemCores::IdToSystemCore[i]); } coreMask = coreMask >> 1; i++; } } std::string executeShellCommand(const std::string command) { FILE* pipe = POPEN(command.c_str(), "r"); if (!pipe) return "ERROR"; char buffer[128]; std::string result = ""; while(!feof(pipe)) { if(fgets(buffer, 128, pipe) != NULL) result += buffer; } PCLOSE(pipe); return result; } bool directoryExists(std::string dirPath) { struct stat info; if (stat(dirPath.c_str(), &info) != 0) return false; else if(info.st_mode & S_IFDIR) return true; else return false; } std::string AppName::m_AppName; #ifdef WIN32 BOOL WINAPI ApplicationEventHandler::handlerRoutine(DWORD fdwCtrlType) { switch (fdwCtrlType) { case CTRL_C_EVENT: case CTRL_BREAK_EVENT: { if (ApplicationEventHandler::getInstance().m_ApplicationInterruptedHandler != NULL) ApplicationEventHandler::getInstance().m_ApplicationInterruptedHandler(ApplicationEventHandler::getInstance().m_ApplicationInterruptedCookie); return TRUE; } default: return FALSE; } } #else void ApplicationEventHandler::handlerRoutine(int signum) { switch (signum) { case SIGINT: { // Most calls are unsafe in a signal handler, and this includes printf(). In particular, // if the signal is caught while inside printf() it may be called twice at the same time which might not be a good idea // The way to make sure the signal is called only once is using this lock and putting NULL in m_ApplicationInterruptedHandler pthread_mutex_lock(&ApplicationEventHandler::getInstance().m_HandlerRoutineMutex); if (ApplicationEventHandler::getInstance().m_ApplicationInterruptedHandler != NULL) ApplicationEventHandler::getInstance().m_ApplicationInterruptedHandler(ApplicationEventHandler::getInstance().m_ApplicationInterruptedCookie); ApplicationEventHandler::getInstance().m_ApplicationInterruptedHandler = NULL; pthread_mutex_unlock(&ApplicationEventHandler::getInstance().m_HandlerRoutineMutex); return; } default: { return; } } } #endif ApplicationEventHandler::ApplicationEventHandler() : m_ApplicationInterruptedHandler(NULL), m_ApplicationInterruptedCookie(NULL) { #ifndef WIN32 pthread_mutex_init(&m_HandlerRoutineMutex, 0); #endif } void ApplicationEventHandler::onApplicationInterrupted(EventHandlerCallback handler, void* cookie) { m_ApplicationInterruptedHandler = handler; m_ApplicationInterruptedCookie = cookie; #ifdef WIN32 SetConsoleCtrlHandler((PHANDLER_ROUTINE)handlerRoutine, TRUE); #else struct sigaction action; memset(&action, 0, sizeof(struct sigaction)); action.sa_handler = handlerRoutine; sigemptyset(&action.sa_mask); sigaction(SIGINT, &action, NULL); #endif } } // namespace pcpp <commit_msg>Bugfix #117 - Limit the number of cores, no more than 32.<commit_after>#include "SystemUtils.h" #include "PlatformSpecificUtils.h" #ifndef _MSC_VER #include <unistd.h> #endif #include <stdio.h> #include <iostream> #include <signal.h> #include <string.h> #include <sys/stat.h> #ifdef _MSC_VER int gettimeofday(struct timeval * tp, struct timezone * tzp) { // Note: some broken versions only have 8 trailing zero's, the correct epoch has 9 trailing zero's static const uint64_t EPOCH = ((uint64_t)116444736000000000ULL); SYSTEMTIME system_time; FILETIME file_time; uint64_t time; GetSystemTime(&system_time); SystemTimeToFileTime(&system_time, &file_time); time = ((uint64_t)file_time.dwLowDateTime); time += ((uint64_t)file_time.dwHighDateTime) << 32; tp->tv_sec = (long)((time - EPOCH) / 10000000L); tp->tv_usec = (long)(system_time.wMilliseconds * 1000); return 0; } #endif namespace pcpp { const SystemCore SystemCores::Core0 = { 0x01, 0 }; const SystemCore SystemCores::Core1 = { 0x02, 1 }; const SystemCore SystemCores::Core2 = { 0x04, 2 }; const SystemCore SystemCores::Core3 = { 0x08, 3 }; const SystemCore SystemCores::Core4 = { 0x10, 4 }; const SystemCore SystemCores::Core5 = { 0x20, 5 }; const SystemCore SystemCores::Core6 = { 0x40, 6 }; const SystemCore SystemCores::Core7 = { 0x80, 7 }; const SystemCore SystemCores::Core8 = { 0x100, 8 }; const SystemCore SystemCores::Core9 = { 0x200, 9 }; const SystemCore SystemCores::Core10 = { 0x400, 10 }; const SystemCore SystemCores::Core11 = { 0x800, 11 }; const SystemCore SystemCores::Core12 = { 0x1000, 12 }; const SystemCore SystemCores::Core13 = { 0x2000, 13 }; const SystemCore SystemCores::Core14 = { 0x4000, 14 }; const SystemCore SystemCores::Core15 = { 0x8000, 15 }; const SystemCore SystemCores::Core16 = { 0x10000, 16 }; const SystemCore SystemCores::Core17 = { 0x20000, 17 }; const SystemCore SystemCores::Core18 = { 0x40000, 18 }; const SystemCore SystemCores::Core19 = { 0x80000, 19 }; const SystemCore SystemCores::Core20 = { 0x100000, 20 }; const SystemCore SystemCores::Core21 = { 0x200000, 21 }; const SystemCore SystemCores::Core22 = { 0x400000, 22 }; const SystemCore SystemCores::Core23 = { 0x800000, 23 }; const SystemCore SystemCores::Core24 = { 0x1000000, 24 }; const SystemCore SystemCores::Core25 = { 0x2000000, 25 }; const SystemCore SystemCores::Core26 = { 0x4000000, 26 }; const SystemCore SystemCores::Core27 = { 0x8000000, 27 }; const SystemCore SystemCores::Core28 = { 0x10000000, 28 }; const SystemCore SystemCores::Core29 = { 0x20000000, 29 }; const SystemCore SystemCores::Core30 = { 0x40000000, 30 }; const SystemCore SystemCores::Core31 = { 0x80000000, 31 }; const SystemCore SystemCores::IdToSystemCore[MAX_NUM_OF_CORES] = { SystemCores::Core0, SystemCores::Core1, SystemCores::Core2, SystemCores::Core3, SystemCores::Core4, SystemCores::Core5, SystemCores::Core6, SystemCores::Core7, SystemCores::Core8, SystemCores::Core9, SystemCores::Core10, SystemCores::Core11, SystemCores::Core12, SystemCores::Core13, SystemCores::Core14, SystemCores::Core15, SystemCores::Core16, SystemCores::Core17, SystemCores::Core18, SystemCores::Core19, SystemCores::Core20, SystemCores::Core21, SystemCores::Core22, SystemCores::Core23, SystemCores::Core24, SystemCores::Core25, SystemCores::Core26, SystemCores::Core27, SystemCores::Core28, SystemCores::Core29, SystemCores::Core30, SystemCores::Core31 }; int getNumOfCores() { #ifdef WIN32 SYSTEM_INFO sysinfo; GetSystemInfo( &sysinfo ); return sysinfo.dwNumberOfProcessors; #else return sysconf(_SC_NPROCESSORS_ONLN); #endif } CoreMask getCoreMaskForAllMachineCores() { int numOfCores = getNumOfCores() < 32 ? getNumOfCores() : 32; CoreMask result = 0; for (int i = 0; i < numOfCores; i++) { result = result | SystemCores::IdToSystemCore[i].Mask; } return result; } CoreMask createCoreMaskFromCoreVector(std::vector<SystemCore> cores) { CoreMask result = 0; for (std::vector<SystemCore>::iterator iter = cores.begin(); iter != cores.end(); iter++) { result |= iter->Mask; } return result; } CoreMask createCoreMaskFromCoreIds(std::vector<int> coreIds) { CoreMask result = 0; for (std::vector<int>::iterator iter = coreIds.begin(); iter != coreIds.end(); iter++) { result |= SystemCores::IdToSystemCore[*iter].Mask; } return result; } void createCoreVectorFromCoreMask(CoreMask coreMask, std::vector<SystemCore>& resultVec) { int i = 0; while (coreMask != 0) { if (1 & coreMask) { resultVec.push_back(SystemCores::IdToSystemCore[i]); } coreMask = coreMask >> 1; i++; } } std::string executeShellCommand(const std::string command) { FILE* pipe = POPEN(command.c_str(), "r"); if (!pipe) return "ERROR"; char buffer[128]; std::string result = ""; while(!feof(pipe)) { if(fgets(buffer, 128, pipe) != NULL) result += buffer; } PCLOSE(pipe); return result; } bool directoryExists(std::string dirPath) { struct stat info; if (stat(dirPath.c_str(), &info) != 0) return false; else if(info.st_mode & S_IFDIR) return true; else return false; } std::string AppName::m_AppName; #ifdef WIN32 BOOL WINAPI ApplicationEventHandler::handlerRoutine(DWORD fdwCtrlType) { switch (fdwCtrlType) { case CTRL_C_EVENT: case CTRL_BREAK_EVENT: { if (ApplicationEventHandler::getInstance().m_ApplicationInterruptedHandler != NULL) ApplicationEventHandler::getInstance().m_ApplicationInterruptedHandler(ApplicationEventHandler::getInstance().m_ApplicationInterruptedCookie); return TRUE; } default: return FALSE; } } #else void ApplicationEventHandler::handlerRoutine(int signum) { switch (signum) { case SIGINT: { // Most calls are unsafe in a signal handler, and this includes printf(). In particular, // if the signal is caught while inside printf() it may be called twice at the same time which might not be a good idea // The way to make sure the signal is called only once is using this lock and putting NULL in m_ApplicationInterruptedHandler pthread_mutex_lock(&ApplicationEventHandler::getInstance().m_HandlerRoutineMutex); if (ApplicationEventHandler::getInstance().m_ApplicationInterruptedHandler != NULL) ApplicationEventHandler::getInstance().m_ApplicationInterruptedHandler(ApplicationEventHandler::getInstance().m_ApplicationInterruptedCookie); ApplicationEventHandler::getInstance().m_ApplicationInterruptedHandler = NULL; pthread_mutex_unlock(&ApplicationEventHandler::getInstance().m_HandlerRoutineMutex); return; } default: { return; } } } #endif ApplicationEventHandler::ApplicationEventHandler() : m_ApplicationInterruptedHandler(NULL), m_ApplicationInterruptedCookie(NULL) { #ifndef WIN32 pthread_mutex_init(&m_HandlerRoutineMutex, 0); #endif } void ApplicationEventHandler::onApplicationInterrupted(EventHandlerCallback handler, void* cookie) { m_ApplicationInterruptedHandler = handler; m_ApplicationInterruptedCookie = cookie; #ifdef WIN32 SetConsoleCtrlHandler((PHANDLER_ROUTINE)handlerRoutine, TRUE); #else struct sigaction action; memset(&action, 0, sizeof(struct sigaction)); action.sa_handler = handlerRoutine; sigemptyset(&action.sa_mask); sigaction(SIGINT, &action, NULL); #endif } } // namespace pcpp <|endoftext|>
<commit_before>//DEFINITION OF A FEW CONSTANTS const Int_t numberOfSigmasPID = 3; // ANALYSIS TYPE const Bool_t anaType = 1;//0 HD; 1 UU; const Bool_t usePID = kTRUE; //---------------------------------------------------- AliAnalysisTaskSEDStarSpectra *AddTaskDStarSpectra(Bool_t theMCon=kFALSE) { AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { ::Error("AddTaskDStarSpectra", "No analysis manager to connect to."); return NULL; } TString cutobjname="Dstar"; // D0 daughters pre-selections // AliRDHFCutsDStartoKpipi* RDHFDStartoKpipi=new AliRDHFCutsDStartoKpipi(); RDHFDStartoKpipi->SetName("DstartoKpipi"); RDHFDStartoKpipi->SetTitle("cuts for D* analysis"); AliESDtrackCuts* esdTrackCuts=new AliESDtrackCuts(); esdTrackCuts->SetRequireSigmaToVertex(kFALSE); //default esdTrackCuts->SetRequireTPCRefit(kTRUE); esdTrackCuts->SetRequireITSRefit(kTRUE); esdTrackCuts->SetMinNClustersITS(4); // default is 5 esdTrackCuts->SetClusterRequirementITS(AliESDtrackCuts::kSPD, AliESDtrackCuts::kAny); //test d0 asimmetry // default is kBoth, otherwise kAny esdTrackCuts->SetMinDCAToVertexXY(0.); esdTrackCuts->SetPtRange(0.1,1.e10); // // soft pion pre-selections // AliESDtrackCuts* esdSoftPicuts=new AliESDtrackCuts(); esdSoftPicuts->SetRequireSigmaToVertex(kFALSE); //default esdSoftPicuts->SetRequireTPCRefit(kFALSE); esdSoftPicuts->SetRequireITSRefit(kFALSE); esdSoftPicuts->SetMinNClustersITS(4); // default is 4 esdSoftPicuts->SetClusterRequirementITS(AliESDtrackCuts::kSPD, AliESDtrackCuts::kAny); //test d0 asimmetry esdSoftPicuts->SetPtRange(0.0,1.e10); // set pre selections RDHFDStartoKpipi->AddTrackCuts(esdTrackCuts); RDHFDStartoKpipi->AddTrackCutsSoftPi(esdSoftPicuts); const Int_t nvars=14; const Int_t nptbins=7; Float_t* ptbins; ptbins=new Float_t[nptbins+1]; ptbins[0]=0.7; ptbins[1]=1.; ptbins[2]=2.; ptbins[3]=3.; ptbins[4]=5.; ptbins[5]=8.; ptbins[6]=12.; ptbins[7]=18.; RDHFDStartoKpipi->SetPtBins(nptbins+1,ptbins); Float_t** rdcutsvalmine; rdcutsvalmine=new Float_t*[nvars]; for(Int_t iv=0;iv<nvars;iv++){ rdcutsvalmine[iv]=new Float_t[nptbins]; } if(anaType==1){ // UU cuts rdcutsvalmine[0][0]=0.7; rdcutsvalmine[1][0]=0.022; rdcutsvalmine[2][0]=0.7; rdcutsvalmine[3][0]=0.21; rdcutsvalmine[4][0]=0.21; rdcutsvalmine[5][0]=0.05; rdcutsvalmine[6][0]=0.05; rdcutsvalmine[7][0]=-0.00005; rdcutsvalmine[8][0]=0.85; rdcutsvalmine[9][0]=0.3.; rdcutsvalmine[10][0]=0.1; rdcutsvalmine[11][0]=0.05; rdcutsvalmine[12][0]=100.; rdcutsvalmine[13][0]=0.5; rdcutsvalmine[0][1]=0.7; rdcutsvalmine[1][1]=0.03; rdcutsvalmine[2][1]=0.8; rdcutsvalmine[3][1]=0.45; rdcutsvalmine[4][1]=0.45; rdcutsvalmine[5][1]=0.09; rdcutsvalmine[6][1]=0.09; rdcutsvalmine[7][1]=-0.00029; rdcutsvalmine[8][1]=0.8; rdcutsvalmine[9][1]=0.3; rdcutsvalmine[10][1]=0.1; rdcutsvalmine[11][1]=0.05; rdcutsvalmine[12][1]=100.; rdcutsvalmine[13][1]=1.0; rdcutsvalmine[0][2]=0.7; rdcutsvalmine[1][2]=0.02; rdcutsvalmine[2][2]=0.8; rdcutsvalmine[3][2]=0.7; rdcutsvalmine[4][2]=0.7; rdcutsvalmine[5][2]=0.08; rdcutsvalmine[6][2]=0.08; rdcutsvalmine[7][2]=-0.00018; rdcutsvalmine[8][2]=0.90; rdcutsvalmine[9][2]=0.3; rdcutsvalmine[10][2]=0.1; rdcutsvalmine[11][2]=0.05; rdcutsvalmine[12][2]=100.; rdcutsvalmine[13][2]=0.5; rdcutsvalmine[0][3]=0.7; rdcutsvalmine[1][3]=0.05; rdcutsvalmine[2][3]=0.8; rdcutsvalmine[3][3]=1.; rdcutsvalmine[4][3]=1.; rdcutsvalmine[5][3]=0.042; rdcutsvalmine[6][3]=0.056; rdcutsvalmine[7][3]=-0.000065; rdcutsvalmine[8][3]=0.9; rdcutsvalmine[9][3]=0.3; rdcutsvalmine[10][3]=0.1; rdcutsvalmine[11][3]=0.05; rdcutsvalmine[12][3]=100.; rdcutsvalmine[13][3]=0.5; rdcutsvalmine[0][4]=0.7; rdcutsvalmine[1][4]=0.08; rdcutsvalmine[2][4]=0.9; rdcutsvalmine[3][4]=1.2; rdcutsvalmine[4][4]=1.2; rdcutsvalmine[5][4]=0.07; rdcutsvalmine[6][4]=0.07; rdcutsvalmine[7][4]=0.0001; rdcutsvalmine[8][4]=0.9; rdcutsvalmine[9][4]=0.3; rdcutsvalmine[10][4]=0.1; rdcutsvalmine[11][4]=0.05; rdcutsvalmine[12][4]=100.; rdcutsvalmine[13][4]=0.5; rdcutsvalmine[0][5]=0.7; rdcutsvalmine[1][5]=0.1; rdcutsvalmine[2][5]=1.0; rdcutsvalmine[3][5]=1.; rdcutsvalmine[4][5]=1.; rdcutsvalmine[5][5]=0.08; rdcutsvalmine[6][5]=0.08; rdcutsvalmine[7][5]=0.0004; rdcutsvalmine[8][5]=0.9; rdcutsvalmine[9][5]=0.3; rdcutsvalmine[10][5]=0.1; rdcutsvalmine[11][5]=0.05; rdcutsvalmine[12][5]=100000.; rdcutsvalmine[13][5]=0.5; rdcutsvalmine[0][6]=0.7; rdcutsvalmine[1][6]=0.1; rdcutsvalmine[2][6]=1.0; rdcutsvalmine[3][6]=1.; rdcutsvalmine[4][6]=1.; rdcutsvalmine[5][6]=0.1; rdcutsvalmine[6][6]=0.1; rdcutsvalmine[7][6]=0.0005; rdcutsvalmine[8][6]=0.9; rdcutsvalmine[9][6]=0.3; rdcutsvalmine[10][6]=0.1; rdcutsvalmine[11][6]=0.05; rdcutsvalmine[12][6]=100.; rdcutsvalmine[13][6]=0.5; rdcutsvalmine[0][7]=0.7; rdcutsvalmine[1][7]=0.1; rdcutsvalmine[2][7]=1.0; rdcutsvalmine[3][7]=1.; rdcutsvalmine[4][7]=1.; rdcutsvalmine[5][7]=0.1; rdcutsvalmine[6][7]=0.1; rdcutsvalmine[7][7]=0.001; rdcutsvalmine[8][7]=0.9; rdcutsvalmine[9][7]=0.3; rdcutsvalmine[10][7]=0.1; rdcutsvalmine[11][7]=0.05; rdcutsvalmine[12][7]=100.; rdcutsvalmine[13][7]=0.5; }else{ // HD cuts - To be setted rdcutsvalmine[0][0]=0.450; rdcutsvalmine[1][0]=0.02; rdcutsvalmine[2][0]=0.7; rdcutsvalmine[3][0]=0.8; rdcutsvalmine[4][0]=0.8; rdcutsvalmine[5][0]=0.1; rdcutsvalmine[6][0]=0.1; rdcutsvalmine[7][0]=0.000002; rdcutsvalmine[8][0]=0.9; rdcutsvalmine[9][0]=200.; rdcutsvalmine[10][0]=200.; rdcutsvalmine[11][0]=0.021; rdcutsvalmine[12][0]=100.; rdcutsvalmine[13][0]=0.5; rdcutsvalmine[0][1]=0.45; rdcutsvalmine[1][1]=0.03; rdcutsvalmine[2][1]=0.7; rdcutsvalmine[3][1]=0.8; rdcutsvalmine[4][1]=0.8; rdcutsvalmine[5][1]=0.1; rdcutsvalmine[6][1]=0.1; rdcutsvalmine[7][1]=-0.00002; rdcutsvalmine[8][1]=0.9; rdcutsvalmine[9][1]=200.; rdcutsvalmine[10][1]=200.; rdcutsvalmine[11][1]=0.021; rdcutsvalmine[12][1]=100.; rdcutsvalmine[13][1]=0.5; rdcutsvalmine[0][2]=0.450; rdcutsvalmine[1][2]=0.03; rdcutsvalmine[2][2]=0.7; rdcutsvalmine[3][2]=0.8; rdcutsvalmine[4][2]=0.8; rdcutsvalmine[5][2]=0.1; rdcutsvalmine[6][2]=0.1; rdcutsvalmine[7][2]=-0.00002; rdcutsvalmine[8][2]=0.9; rdcutsvalmine[9][2]=200.; rdcutsvalmine[10][2]=200.; rdcutsvalmine[11][2]=0.021; rdcutsvalmine[12][2]=100.; rdcutsvalmine[13][2]=0.5; rdcutsvalmine[0][3]=0.45; rdcutsvalmine[1][3]=0.03; rdcutsvalmine[2][3]=0.7; rdcutsvalmine[3][3]=0.9; rdcutsvalmine[4][3]=0.9; rdcutsvalmine[5][3]=0.1; rdcutsvalmine[6][3]=0.1; rdcutsvalmine[7][3]=0.000002; rdcutsvalmine[8][3]=0.8; rdcutsvalmine[9][3]=200.; rdcutsvalmine[10][3]=200.; rdcutsvalmine[11][3]=0.021; rdcutsvalmine[12][3]=100.; rdcutsvalmine[13][3]=0.5; rdcutsvalmine[0][4]=0.45; rdcutsvalmine[1][4]=0.03; rdcutsvalmine[2][4]=0.7; rdcutsvalmine[3][4]=1.; rdcutsvalmine[4][4]=1.; rdcutsvalmine[5][4]=0.1; rdcutsvalmine[6][4]=0.1; rdcutsvalmine[7][4]=0.000002; rdcutsvalmine[8][4]=0.8; rdcutsvalmine[9][4]=200.; rdcutsvalmine[10][4]=200.; rdcutsvalmine[11][4]=0.021; rdcutsvalmine[12][4]=100.; rdcutsvalmine[13][4]=0.5; rdcutsvalmine[0][5]=0.45; rdcutsvalmine[1][5]=0.03; rdcutsvalmine[2][5]=0.7; rdcutsvalmine[3][5]=1.; rdcutsvalmine[4][5]=1.; rdcutsvalmine[5][5]=0.1; rdcutsvalmine[6][5]=0.1; rdcutsvalmine[7][5]=0.000002; rdcutsvalmine[8][5]=0.8; rdcutsvalmine[9][5]=200.; rdcutsvalmine[10][5]=200.; rdcutsvalmine[11][5]=0.021; rdcutsvalmine[12][5]=100.; rdcutsvalmine[13][5]=0.5; rdcutsvalmine[0][6]=0.45; rdcutsvalmine[1][6]=0.03; rdcutsvalmine[2][6]=0.7; rdcutsvalmine[3][6]=1.; rdcutsvalmine[4][6]=1.; rdcutsvalmine[5][6]=0.1; rdcutsvalmine[6][6]=0.1; rdcutsvalmine[7][6]=0.000002; rdcutsvalmine[8][6]=0.8; rdcutsvalmine[9][6]=200.; rdcutsvalmine[10][6]=200.; rdcutsvalmine[11][6]=0.021; rdcutsvalmine[12][6]=100.; rdcutsvalmine[13][6]=0.5; rdcutsvalmine[0][7]=0.45; rdcutsvalmine[1][7]=0.03; rdcutsvalmine[2][7]=0.7; rdcutsvalmine[3][7]=1.; rdcutsvalmine[4][7]=1.; rdcutsvalmine[5][7]=0.1; rdcutsvalmine[6][7]=0.1; rdcutsvalmine[7][7]=0.000002; rdcutsvalmine[8][7]=0.8; rdcutsvalmine[9][7]=200.; rdcutsvalmine[10][7]=200.; rdcutsvalmine[11][7]=0.021; rdcutsvalmine[12][7]=100.; rdcutsvalmine[13][7]=0.5; } RDHFDStartoKpipi->SetCuts(nvars,nptbins,rdcutsvalmine); RDHFDStartoKpipi->PrintAll(); //CREATE THE TASK printf("CREATE TASK\n"); // create the task AliAnalysisTaskSEDStarSpectra *task = new AliAnalysisTaskSEDStarSpectra("AliAnalysisTaskSEDStarSpectra",RDHFDStartoKpipi); task->SetAnalysisType(anaType); task->SetNSigmasPID(numberOfSigmasPID); task->SetMC(theMCon); task->SetPID(usePID); task->SetDebugLevel(0); mgr->AddTask(task); // Create and connect containers for input/output TString outputfile = AliAnalysisManager::GetCommonFileName(); if (anaType == 0) outputfile += ":PWG3_D2H_DStarSpectraHD"; if (anaType == 1) outputfile += ":PWG3_D2H_DStarSpectraUU"; // ------ input data ------ //AliAnalysisDataContainer *cinput0 = mgr->GetCommonInputContainer(); AliAnalysisDataContainer *cinput0 = mgr->CreateContainer("indstar",TChain::Class(), AliAnalysisManager::kInputContainer); // ----- output data ----- AliAnalysisDataContainer *coutput1 = mgr->CreateContainer("chist1",TList::Class(),AliAnalysisManager::kOutputContainer,outputfile.Data()); AliAnalysisDataContainer *coutputDStar1 = mgr->CreateContainer("DStarSpectrum",TList::Class(),AliAnalysisManager::kOutputContainer, outputfile.Data()); AliAnalysisDataContainer *coutputDStar2 = mgr->CreateContainer("DStarAll",TList::Class(),AliAnalysisManager::kOutputContainer,outputfile.Data()); AliAnalysisDataContainer *coutputDStar3 = mgr->CreateContainer("DStarPID3",TList::Class(),AliAnalysisManager::kOutputContainer, outputfile.Data()); AliAnalysisDataContainer *coutputDStar4 = mgr->CreateContainer("DStarPID2",TList::Class(),AliAnalysisManager::kOutputContainer,outputfile.Data()); AliAnalysisDataContainer *coutputDStar5 = mgr->CreateContainer("DStarPID1",TList::Class(),AliAnalysisManager::kOutputContainer, outputfile.Data()); AliAnalysisDataContainer *coutputDStar6 = mgr->CreateContainer("cuts",AliRDHFCutsDStartoKpipi::Class(),AliAnalysisManager::kOutputContainer, outputfile.Data()); //cuts mgr->ConnectInput(task,0,mgr->GetCommonInputContainer()); mgr->ConnectOutput(task,1,coutput1); mgr->ConnectOutput(task,2,coutputDStar1); mgr->ConnectOutput(task,3,coutputDStar2); mgr->ConnectOutput(task,4,coutputDStar3); mgr->ConnectOutput(task,5,coutputDStar4); mgr->ConnectOutput(task,6,coutputDStar5); mgr->ConnectOutput(task,7,coutputDStar6); return task; } <commit_msg>update (Alessandro)<commit_after>//if like define a different number of signal for TPC PID //by default the task is anyway computing 1, 2 and 3 sigmas const Int_t numberOfSigmasPID = 3; // option to switch on and off the TPC PID. const Bool_t usePID = kTRUE; // analysis type... TO BE REMOVED!!! const Bool_t anaType = 1;//0 HD; 1 UU; //---------------------------------------------------- AliAnalysisTaskSEDStarSpectra *AddTaskDStarSpectra(Bool_t theMCon=kFALSE) { AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { ::Error("AddTaskDStarSpectra", "No analysis manager to connect to."); return NULL; } // cuts are stored in a TFile generated by makeTFile4CutsDStartoKpipi.C in ./macros/ // set there the cuts!!!!! TFile* filecuts=new TFile("DStartoKpipiCuts.root"); if(!filecuts->IsOpen()){ cout<<"Input file not found: exit"<<endl; return; } AliRDHFCutsDStartoKpipi* RDHFDStartoKpipi=new AliRDHFCutsDStartoKpipi(); RDHFDStartoKpipi = (AliRDHFCutsDStartoKpipi*)filecuts->Get("DStartoKpipiCuts"); RDHFDStartoKpipi->SetName("DStartoKpipiCuts"); // mm let's see if everything is ok if(!RDHFDStartoKpipi){ cout<<"Specific AliRDHFCuts not found"<<endl; return; } //CREATE THE TASK printf("CREATE TASK\n"); // create the task AliAnalysisTaskSEDStarSpectra *task = new AliAnalysisTaskSEDStarSpectra("AliAnalysisTaskSEDStarSpectra",RDHFDStartoKpipi); task->SetAnalysisType(anaType); task->SetNSigmasPID(numberOfSigmasPID); task->SetMC(theMCon); task->SetPID(usePID); task->SetDebugLevel(0); mgr->AddTask(task); // Create and connect containers for input/output TString outputfile = AliAnalysisManager::GetCommonFileName(); outputfile += ":PWG3_D2H_DStarSpectra"; // ------ input data ------ //AliAnalysisDataContainer *cinput0 = mgr->GetCommonInputContainer(); AliAnalysisDataContainer *cinput0 = mgr->CreateContainer("indstar",TChain::Class(), AliAnalysisManager::kInputContainer); // ----- output data ----- AliAnalysisDataContainer *coutput1 = mgr->CreateContainer("chist1",TList::Class(),AliAnalysisManager::kOutputContainer,outputfile.Data()); AliAnalysisDataContainer *coutputDStar1 = mgr->CreateContainer("DStarSpectrum",TList::Class(),AliAnalysisManager::kOutputContainer, outputfile.Data()); AliAnalysisDataContainer *coutputDStar2 = mgr->CreateContainer("DStarAll",TList::Class(),AliAnalysisManager::kOutputContainer,outputfile.Data()); AliAnalysisDataContainer *coutputDStar3 = mgr->CreateContainer("DStarPID3",TList::Class(),AliAnalysisManager::kOutputContainer, outputfile.Data()); AliAnalysisDataContainer *coutputDStar4 = mgr->CreateContainer("DStarPID2",TList::Class(),AliAnalysisManager::kOutputContainer,outputfile.Data()); AliAnalysisDataContainer *coutputDStar5 = mgr->CreateContainer("DStarPID1",TList::Class(),AliAnalysisManager::kOutputContainer, outputfile.Data()); AliAnalysisDataContainer *coutputDStar6 = mgr->CreateContainer("cuts",AliRDHFCutsDStartoKpipi::Class(),AliAnalysisManager::kOutputContainer, outputfile.Data()); //cuts mgr->ConnectInput(task,0,mgr->GetCommonInputContainer()); mgr->ConnectOutput(task,1,coutput1); mgr->ConnectOutput(task,2,coutputDStar1); mgr->ConnectOutput(task,3,coutputDStar2); mgr->ConnectOutput(task,4,coutputDStar3); mgr->ConnectOutput(task,5,coutputDStar4); mgr->ConnectOutput(task,6,coutputDStar5); mgr->ConnectOutput(task,7,coutputDStar6); return task; } <|endoftext|>
<commit_before>/****************************************************************************** nomlib - C++11 cross-platform game engine Copyright (c) 2013, 2014 Jeffrey Carpenter <i8degrees@gmail.com> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ******************************************************************************/ #include "nomlib/gui/Button.hpp" namespace nom { Button::Button ( UIWidget* parent, int64 id, const Point2i& pos, const Size2i& size ) : UIWidget( parent, id, pos, size ) // Base class { // NOM_LOG_TRACE( NOM ); // Use explicitly set coordinates as the widget's minimum size requirements. // // Note that if size is invalid (NULL), the minimum size returned will be // Size2i(0,0) // // Note that the size policy is only used when the widget is used inside a // layout. this->set_minimum_size( size ); // Set the size policy of the widget to use explicitly set size dimensions. // // Note that the size policy is only used when the widget is used inside a // layout. if( size != Size2i::null ) { this->set_size_policy( UILayoutPolicy::Policy::Minimum, UILayoutPolicy::Policy::Fixed ); } // Set the size policy of the widget to use dimensions that are calculated // with respect to the text label string, font, point size, etc. // // Note that the size policy is only used when the widget is used inside a // layout. else { this->set_size_policy( UILayoutPolicy::Policy::Preferred, UILayoutPolicy::Policy::Fixed ); } // Widget's focus type. this->set_focus_policy( FocusPolicy::StrongFocus ); // Auto-generate a name tag for our widget. this->set_name( "button" ); // Default state this->set_button_state( Button::State::Default ); // Initialize the default event listeners for the widget. NOM_CONNECT_UIEVENT( this, UIEvent::ON_WINDOW_SIZE_CHANGED, this->on_size_changed ); NOM_CONNECT_UIEVENT( this, UIEvent::ON_WIDGET_UPDATE, this->on_update ); } // Button::Button( UIWidget* parent ) : // UIWidget( parent, parent->id(), parent->position(), parent->size() ) // Base class // { // // NOM_LOG_TRACE( NOM ); // // Use explicitly set coordinates for our minimum widget size // this->set_minimum_size( parent->size() ); // this->set_size_policy( UILayoutPolicy::Policy::Preferred, UILayoutPolicy::Policy::Fixed ); // // Auto-generate a name tag for our widget. // this->set_name( "button" ); // // Default state // this->set_button_state( Button::State::Default ); // // Initialize the default event listeners for the widget. // NOM_CONNECT_UIEVENT( this, UIEvent::ON_WINDOW_SIZE_CHANGED, this->on_size_changed ); // NOM_CONNECT_UIEVENT( this, UIEvent::ON_WIDGET_UPDATE, this->on_update ); // // Widget's focus type. // this->set_focus_policy( FocusPolicy::StrongFocus ); // } Button::~Button( void ) { // NOM_LOG_TRACE( NOM ); } const Size2i Button::minimum_size( void ) const { // Our preferred size will always be two times what is actually required return Size2i( this->size_hint().w / 2, this->size_hint().h / 2 ); } const Size2i Button::size_hint( void ) const { // Maximum text width requirements for the label (with respect to font). // // We dedicate two times the width required in order to: a) help account for // dynamic length text labels that are set after initialization of the // layout -- the layout manager *should* catch this early enough, but just // in case; b) Simple, minimal approach to getting the look of the button // to *feel* right in terms of size dimensions (in comparison to standard GUI // elements). int total_text_width = this->label_.width() * 2; // Total text height requirements for the label (with respect to font). // // Note that this variable will be scaled up by a factor of two as well; see // the above note regarding total_text_width for my reasoning logic on // requesting this. sint total_text_height = 0; uint point_size = nom::DEFAULT_FONT_SIZE; FontMetrics face = this->label_.font()->metrics(); // NOM_DUMP( this->name() ); // NOM_DUMP( face.name ); // NOM_DUMP( this->label_->text() ); // Use the point size of the widget's style, if one has been set: if( this->style() != nullptr ) { point_size = this->style()->font_size(); } total_text_height += this->label_.font()->newline( point_size ) * 2; return Size2i( total_text_width, total_text_height ); // Err return Size2i( 0, 0 ); } ObjectTypeInfo Button::type( void ) const { return NOM_OBJECT_TYPE_INFO( self_type ); } void Button::draw( RenderTarget& target ) const { // UIWidget::draw( target ); if( this->label_.valid() == true ) { this->label_.draw( target ); } } Button::State Button::button_state( void ) const { return this->button_state_; } const std::string& Button::label_text( void ) const { return this->label_.text(); } void Button::set_label( const std::string& text ) { this->text_ = text; NOM_ASSERT( this->style() != nullptr ); this->label_.set_font( this->font() ); this->label_.set_text_size( this->style()->font_size() ); this->label_.set_text( this->text_ ); this->label_.set_position( this->position() ); this->label_.set_size( this->size() ); this->label_.set_alignment( this->style()->text_alignment() ); this->label_.set_style( this->style()->font_style() ); this->label_.set_color( this->style()->font_color() ); this->update_bounds(); this->update(); } void Button::set_button_state( Button::State state ) { this->button_state_ = state; } // Protected scope void Button::update_bounds( void ) { this->label_.set_position( this->position() ); this->label_.set_size( this->size() ); } void Button::on_update( const UIWidgetEvent& ev ) { // NOM_LOG_TRACE( NOM ); Event evt = ev.event(); if( evt.type != UIEvent::ON_WIDGET_UPDATE ) { return; } this->label_.set_font( this->font() ); this->update_bounds(); this->update(); } void Button::on_size_changed( const UIWidgetEvent& ev ) { Event evt = ev.event(); if( evt.type != SDL_WINDOWEVENT_SIZE_CHANGED ) { return; } if( this->decorator() ) { // Update the attached decorator (border & possibly a background) this->decorator()->set_bounds( ev.resized_bounds_ ); } // Update ourselves with the new rendering coordinates this->set_bounds( ev.resized_bounds_ ); // Updating the text label's coordinates and dimensions also ensures that its // alignment is recalculated. this->label_.set_position( this->position() ); this->label_.set_size( this->size() ); this->update_bounds(); this->update(); } void Button::on_mouse_down( const UIWidgetEvent& ev ) { this->set_button_state( Button::State::Pressed ); UIWidgetEvent evt( this->button_state(), this->name(), ev.event(), this->id() ); // Send the UI event object to the registered private event callback. this->dispatcher()->emit( UIEvent::ON_MOUSE_DOWN, evt ); // Send the UI event object to the registered public event callback. this->dispatcher()->emit( UIEvent::MOUSE_DOWN, evt ); } void Button::on_mouse_up( const UIWidgetEvent& ev ) { this->set_button_state( Button::State::Default ); UIWidgetEvent evt( this->button_state(), this->name(), ev.event(), this->id() ); // Send the UI event object to the registered private event callback. this->dispatcher()->emit( UIEvent::ON_MOUSE_DOWN, evt ); // Send the UI event object to the registered public event callback. this->dispatcher()->emit( UIEvent::MOUSE_DOWN, evt ); } void Button::on_mouse_enter( const UIWidgetEvent& ev ) { // this->set_button_state( Button::State::Pressed ); // Send the button state and text string of the set label at the time of // the event. UIWidgetEvent evt( this->button_state(), this->label_text(), ev.event(), this->id() ); // Send the UI event object to the registered private event callback. this->dispatcher()->emit( UIEvent::ON_MOUSE_MOTION_ENTER, evt ); // Send the UI event object to the registered public event callback. this->dispatcher()->emit( UIEvent::MOUSE_MOTION_ENTER, evt ); } void Button::on_mouse_leave( const UIWidgetEvent& ev ) { // this->set_button_state( Button::State::Default ); // Send the button state and text string of the set label at the time of // the event. UIWidgetEvent evt( this->button_state(), this->label_text(), ev.event(), this->id() ); // Send the UI event object to the registered private event callback. this->dispatcher()->emit( UIEvent::ON_MOUSE_MOTION_LEAVE, evt ); // Send the UI event object to the registered public event callback. this->dispatcher()->emit( UIEvent::MOUSE_MOTION_LEAVE, evt ); } // Private scope void Button::update( void ) { // Nothing to do } } // namespace nom <commit_msg>Fix bug in Button::on_mouse_up (wrong event emission)<commit_after>/****************************************************************************** nomlib - C++11 cross-platform game engine Copyright (c) 2013, 2014 Jeffrey Carpenter <i8degrees@gmail.com> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ******************************************************************************/ #include "nomlib/gui/Button.hpp" namespace nom { Button::Button ( UIWidget* parent, int64 id, const Point2i& pos, const Size2i& size ) : UIWidget( parent, id, pos, size ) // Base class { // NOM_LOG_TRACE( NOM ); // Use explicitly set coordinates as the widget's minimum size requirements. // // Note that if size is invalid (NULL), the minimum size returned will be // Size2i(0,0) // // Note that the size policy is only used when the widget is used inside a // layout. this->set_minimum_size( size ); // Set the size policy of the widget to use explicitly set size dimensions. // // Note that the size policy is only used when the widget is used inside a // layout. if( size != Size2i::null ) { this->set_size_policy( UILayoutPolicy::Policy::Minimum, UILayoutPolicy::Policy::Fixed ); } // Set the size policy of the widget to use dimensions that are calculated // with respect to the text label string, font, point size, etc. // // Note that the size policy is only used when the widget is used inside a // layout. else { this->set_size_policy( UILayoutPolicy::Policy::Preferred, UILayoutPolicy::Policy::Fixed ); } // Widget's focus type. this->set_focus_policy( FocusPolicy::StrongFocus ); // Auto-generate a name tag for our widget. this->set_name( "button" ); // Default state this->set_button_state( Button::State::Default ); // Initialize the default event listeners for the widget. NOM_CONNECT_UIEVENT( this, UIEvent::ON_WINDOW_SIZE_CHANGED, this->on_size_changed ); NOM_CONNECT_UIEVENT( this, UIEvent::ON_WIDGET_UPDATE, this->on_update ); } // Button::Button( UIWidget* parent ) : // UIWidget( parent, parent->id(), parent->position(), parent->size() ) // Base class // { // // NOM_LOG_TRACE( NOM ); // // Use explicitly set coordinates for our minimum widget size // this->set_minimum_size( parent->size() ); // this->set_size_policy( UILayoutPolicy::Policy::Preferred, UILayoutPolicy::Policy::Fixed ); // // Auto-generate a name tag for our widget. // this->set_name( "button" ); // // Default state // this->set_button_state( Button::State::Default ); // // Initialize the default event listeners for the widget. // NOM_CONNECT_UIEVENT( this, UIEvent::ON_WINDOW_SIZE_CHANGED, this->on_size_changed ); // NOM_CONNECT_UIEVENT( this, UIEvent::ON_WIDGET_UPDATE, this->on_update ); // // Widget's focus type. // this->set_focus_policy( FocusPolicy::StrongFocus ); // } Button::~Button( void ) { // NOM_LOG_TRACE( NOM ); } const Size2i Button::minimum_size( void ) const { // Our preferred size will always be two times what is actually required return Size2i( this->size_hint().w / 2, this->size_hint().h / 2 ); } const Size2i Button::size_hint( void ) const { // Maximum text width requirements for the label (with respect to font). // // We dedicate two times the width required in order to: a) help account for // dynamic length text labels that are set after initialization of the // layout -- the layout manager *should* catch this early enough, but just // in case; b) Simple, minimal approach to getting the look of the button // to *feel* right in terms of size dimensions (in comparison to standard GUI // elements). int total_text_width = this->label_.width() * 2; // Total text height requirements for the label (with respect to font). // // Note that this variable will be scaled up by a factor of two as well; see // the above note regarding total_text_width for my reasoning logic on // requesting this. sint total_text_height = 0; uint point_size = nom::DEFAULT_FONT_SIZE; FontMetrics face = this->label_.font()->metrics(); // NOM_DUMP( this->name() ); // NOM_DUMP( face.name ); // NOM_DUMP( this->label_->text() ); // Use the point size of the widget's style, if one has been set: if( this->style() != nullptr ) { point_size = this->style()->font_size(); } total_text_height += this->label_.font()->newline( point_size ) * 2; return Size2i( total_text_width, total_text_height ); // Err return Size2i( 0, 0 ); } ObjectTypeInfo Button::type( void ) const { return NOM_OBJECT_TYPE_INFO( self_type ); } void Button::draw( RenderTarget& target ) const { // UIWidget::draw( target ); if( this->label_.valid() == true ) { this->label_.draw( target ); } } Button::State Button::button_state( void ) const { return this->button_state_; } const std::string& Button::label_text( void ) const { return this->label_.text(); } void Button::set_label( const std::string& text ) { this->text_ = text; NOM_ASSERT( this->style() != nullptr ); this->label_.set_font( this->font() ); this->label_.set_text_size( this->style()->font_size() ); this->label_.set_text( this->text_ ); this->label_.set_position( this->position() ); this->label_.set_size( this->size() ); this->label_.set_alignment( this->style()->text_alignment() ); this->label_.set_style( this->style()->font_style() ); this->label_.set_color( this->style()->font_color() ); this->update_bounds(); this->update(); } void Button::set_button_state( Button::State state ) { this->button_state_ = state; } // Protected scope void Button::update_bounds( void ) { this->label_.set_position( this->position() ); this->label_.set_size( this->size() ); } void Button::on_update( const UIWidgetEvent& ev ) { // NOM_LOG_TRACE( NOM ); Event evt = ev.event(); if( evt.type != UIEvent::ON_WIDGET_UPDATE ) { return; } this->label_.set_font( this->font() ); this->update_bounds(); this->update(); } void Button::on_size_changed( const UIWidgetEvent& ev ) { Event evt = ev.event(); if( evt.type != SDL_WINDOWEVENT_SIZE_CHANGED ) { return; } if( this->decorator() ) { // Update the attached decorator (border & possibly a background) this->decorator()->set_bounds( ev.resized_bounds_ ); } // Update ourselves with the new rendering coordinates this->set_bounds( ev.resized_bounds_ ); // Updating the text label's coordinates and dimensions also ensures that its // alignment is recalculated. this->label_.set_position( this->position() ); this->label_.set_size( this->size() ); this->update_bounds(); this->update(); } void Button::on_mouse_down( const UIWidgetEvent& ev ) { this->set_button_state( Button::State::Pressed ); UIWidgetEvent evt( this->button_state(), this->name(), ev.event(), this->id() ); // Send the UI event object to the registered private event callback. this->dispatcher()->emit( UIEvent::ON_MOUSE_DOWN, evt ); // Send the UI event object to the registered public event callback. this->dispatcher()->emit( UIEvent::MOUSE_DOWN, evt ); } void Button::on_mouse_up( const UIWidgetEvent& ev ) { this->set_button_state( Button::State::Default ); UIWidgetEvent evt( this->button_state(), this->name(), ev.event(), this->id() ); // Send the UI event object to the registered private event callback. this->dispatcher()->emit( UIEvent::ON_MOUSE_UP, evt ); // Send the UI event object to the registered public event callback. this->dispatcher()->emit( UIEvent::MOUSE_UP, evt ); } void Button::on_mouse_enter( const UIWidgetEvent& ev ) { // this->set_button_state( Button::State::Pressed ); // Send the button state and text string of the set label at the time of // the event. UIWidgetEvent evt( this->button_state(), this->label_text(), ev.event(), this->id() ); // Send the UI event object to the registered private event callback. this->dispatcher()->emit( UIEvent::ON_MOUSE_MOTION_ENTER, evt ); // Send the UI event object to the registered public event callback. this->dispatcher()->emit( UIEvent::MOUSE_MOTION_ENTER, evt ); } void Button::on_mouse_leave( const UIWidgetEvent& ev ) { // this->set_button_state( Button::State::Default ); // Send the button state and text string of the set label at the time of // the event. UIWidgetEvent evt( this->button_state(), this->label_text(), ev.event(), this->id() ); // Send the UI event object to the registered private event callback. this->dispatcher()->emit( UIEvent::ON_MOUSE_MOTION_LEAVE, evt ); // Send the UI event object to the registered public event callback. this->dispatcher()->emit( UIEvent::MOUSE_MOTION_LEAVE, evt ); } // Private scope void Button::update( void ) { // Nothing to do } } // namespace nom <|endoftext|>
<commit_before><commit_msg>refactor(Scripts/Event): convert pilgrims_bounty into new system (#9608)<commit_after><|endoftext|>
<commit_before>// Copyright 2014 Alessio Sclocco <a.sclocco@vu.nl> // // 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 <iostream> #include <fstream> #include <exception> #include <string> #include <limits> #include <cctype> #include <CImg.h> #include <ArgumentList.hpp> #include <ColorMap.hpp> #include <utils.hpp> int main(int argc, char * argv[]) { bool gray = false; unsigned int nrDMs = 0; unsigned int nrPeriods = 0; float minSNR = std::numeric_limits< float >::max(); float maxSNR = std::numeric_limits< float >::min(); float snrSpaceDim = 0.0f; float * snrSpace = 0; std::string outFilename; std::ifstream searchFile; isa::utils::ArgumentList args(argc, argv); try { gray = args.getSwitch("-gray"); outFilename = args.getSwitchArgument< std::string >("-output"); nrDMs = args.getSwitchArgument< unsigned int >("-dms"); nrPeriods = args.getSwitchArgument< unsigned int >("-periods"); } catch ( isa::utils::EmptyCommandLine & err ) { std::cerr << args.getName() << " [-gray] -output ... -dms ... -periods ... input" << std::endl; return 1; } catch ( std::exception & err ) { std::cerr << err.what() << std::endl; return 1; } snrSpace = new float [nrDMs * nrPeriods]; try { while ( true ) { searchFile.open(args.getFirst< std::string >()); while ( ! searchFile.eof() ) { std::string temp; unsigned int splitPoint = 0; unsigned int DM = 0; unsigned int period = 0; float snr = 0.0f; std::getline(searchFile, temp); if ( ! std::isdigit(temp[0]) ) { continue; } splitPoint = temp.find(" "); period = isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)); temp = temp.substr(splitPoint + 1); splitPoint = temp.find(" "); DM = isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)); temp = temp.substr(splitPoint + 1); splitPoint = temp.find(" "); snr = isa::utils::castToType< std::string, float >(temp); if ( snr > maxSNR ) { maxSNR = snr; } if ( snr < minSNR ) { minSNR = snr; } snrSpace[(period * nrDMs) + DM] = snr; } searchFile.close(); } } catch ( isa::utils::EmptyCommandLine & err ) { snrSpaceDim = maxSNR - minSNR; } cimg_library::CImg< unsigned char > searchImage; AstroData::Color * colorMap; if ( gray ) { searchImage = cimg_library::CImg< unsigned char >(nrDMs, nrPeriods, 1, 1); } else { searchImage = cimg_library::CImg< unsigned char >(nrDMs, nrPeriods, 1, 3); colorMap = AstroData::getColorMap(); } for ( unsigned int period = 0; period < nrPeriods; period++ ) { for ( unsigned int DM = 0; DM < nrDMs; DM++ ) { float snr = snrSpace[(period * nrDMs) + DM]; if ( gray ) { searchImage(DM, (nrPeriods - 1) - period, 0, 0) = static_cast< unsigned char >(((snr - minSNR) * 256.0) / snrSpaceDim); } else { searchImage(DM, (nrPeriods - 1) - period, 0, 0) = (colorMap[static_cast< unsigned int >(((snr - minSNR) * 256.0) / snrSpaceDim)]).getR(); searchImage(DM, (nrPeriods - 1) - period, 0, 1) = (colorMap[static_cast< unsigned int >(((snr - minSNR) * 256.0) / snrSpaceDim)]).getG(); searchImage(DM, (nrPeriods - 1) - period, 0, 2) = (colorMap[static_cast< unsigned int >(((snr - minSNR) * 256.0) / snrSpaceDim)]).getB(); } } } searchImage.save(outFilename.c_str()); delete [] snrSpace; return 0; } <commit_msg>Small fix for the gray values.<commit_after>// Copyright 2014 Alessio Sclocco <a.sclocco@vu.nl> // // 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 <iostream> #include <fstream> #include <exception> #include <string> #include <limits> #include <cctype> #include <CImg.h> #include <ArgumentList.hpp> #include <ColorMap.hpp> #include <utils.hpp> int main(int argc, char * argv[]) { bool gray = false; unsigned int nrDMs = 0; unsigned int nrPeriods = 0; float minSNR = std::numeric_limits< float >::max(); float maxSNR = std::numeric_limits< float >::min(); float snrSpaceDim = 0.0f; float * snrSpace = 0; std::string outFilename; std::ifstream searchFile; isa::utils::ArgumentList args(argc, argv); try { gray = args.getSwitch("-gray"); outFilename = args.getSwitchArgument< std::string >("-output"); nrDMs = args.getSwitchArgument< unsigned int >("-dms"); nrPeriods = args.getSwitchArgument< unsigned int >("-periods"); } catch ( isa::utils::EmptyCommandLine & err ) { std::cerr << args.getName() << " [-gray] -output ... -dms ... -periods ... input" << std::endl; return 1; } catch ( std::exception & err ) { std::cerr << err.what() << std::endl; return 1; } snrSpace = new float [nrDMs * nrPeriods]; try { while ( true ) { searchFile.open(args.getFirst< std::string >()); while ( ! searchFile.eof() ) { std::string temp; unsigned int splitPoint = 0; unsigned int DM = 0; unsigned int period = 0; float snr = 0.0f; std::getline(searchFile, temp); if ( ! std::isdigit(temp[0]) ) { continue; } splitPoint = temp.find(" "); period = isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)); temp = temp.substr(splitPoint + 1); splitPoint = temp.find(" "); DM = isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)); temp = temp.substr(splitPoint + 1); splitPoint = temp.find(" "); snr = isa::utils::castToType< std::string, float >(temp); if ( snr > maxSNR ) { maxSNR = snr; } if ( snr < minSNR ) { minSNR = snr; } snrSpace[(period * nrDMs) + DM] = snr; } searchFile.close(); } } catch ( isa::utils::EmptyCommandLine & err ) { snrSpaceDim = maxSNR - minSNR; } cimg_library::CImg< unsigned char > searchImage; AstroData::Color * colorMap; if ( gray ) { searchImage = cimg_library::CImg< unsigned char >(nrDMs, nrPeriods, 1, 1); } else { searchImage = cimg_library::CImg< unsigned char >(nrDMs, nrPeriods, 1, 3); colorMap = AstroData::getColorMap(); } for ( unsigned int period = 0; period < nrPeriods; period++ ) { for ( unsigned int DM = 0; DM < nrDMs; DM++ ) { float snr = snrSpace[(period * nrDMs) + DM]; if ( gray ) { searchImage(DM, (nrPeriods - 1) - period, 0, 0) = static_cast< unsigned char >(((snr - minSNR) * 255.0) / snrSpaceDim); } else { searchImage(DM, (nrPeriods - 1) - period, 0, 0) = (colorMap[static_cast< unsigned int >(((snr - minSNR) * 256.0) / snrSpaceDim)]).getR(); searchImage(DM, (nrPeriods - 1) - period, 0, 1) = (colorMap[static_cast< unsigned int >(((snr - minSNR) * 256.0) / snrSpaceDim)]).getG(); searchImage(DM, (nrPeriods - 1) - period, 0, 2) = (colorMap[static_cast< unsigned int >(((snr - minSNR) * 256.0) / snrSpaceDim)]).getB(); } } } searchImage.save(outFilename.c_str()); delete [] snrSpace; return 0; } <|endoftext|>
<commit_before>/* -------------------------------------------------------------------------- * * OpenSim: RegisterTypes_osimCommon.cpp * * -------------------------------------------------------------------------- * * The OpenSim API is a toolkit for musculoskeletal modeling and simulation. * * See http://opensim.stanford.edu and the NOTICE file for more information. * * OpenSim is developed at Stanford University and supported by the US * * National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA * * through the Warrior Web program. * * * * Copyright (c) 2005-2012 Stanford University and the Authors * * Author(s): Frank C. Anderson * * * * 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 "Object.h" #include "Component.h" #include "RegisterTypes_osimCommon.h" #include "FunctionSet.h" #include "GCVSplineSet.h" #include "ScaleSet.h" #include "GCVSpline.h" #include "Scale.h" #include "SimmSpline.h" #include "Constant.h" #include "Sine.h" #include "StepFunction.h" #include "LinearFunction.h" #include "PiecewiseLinearFunction.h" #include "PiecewiseConstantFunction.h" #include "MultiplierFunction.h" #include "PolynomialFunction.h" #include "ObjectGroup.h" #include "Reporter.h" #include <string> #include <iostream> #include <exception> using namespace OpenSim; using namespace std; //_____________________________________________________________________________ /** * The purpose of this routine is to register all class types exported by * the osimCommon library. */ OSIMCOMMON_API void RegisterTypes_osimCommon() { try { Object::registerType(Connector<Component>()); // Register commonly used Inputs for de/serialization Object::registerType(Input<double>()); Object::registerType(Input<SimTK::Vec3>()); Object::registerType(Input<SimTK::Vector>()); Object::registerType(Input<SimTK::SpatialVec>()); //SimTK::Xml::setXmlCondenseWhiteSpace(false); Object::registerType( FunctionSet() ); Object::registerType( GCVSplineSet() ); Object::registerType( ScaleSet() ); Object::registerType( GCVSpline() ); Object::registerType( Scale() ); Object::registerType( SimmSpline() ); Object::registerType( Constant() ); Object::registerType( Sine() ); Object::registerType( StepFunction() ); Object::registerType( LinearFunction() ); Object::registerType( PiecewiseLinearFunction() ); Object::registerType( PiecewiseConstantFunction() ); Object::registerType( MultiplierFunction() ); Object::registerType(PolynomialFunction()); Object::registerType( ObjectGroup() ); Object::registerType( TableReporter() ); Object::registerType( TableReporterVec3() ); Object::registerType( TableReporterVector() ); Object::registerType( ConsoleReporter() ); Object::registerType( ConsoleReporterVec3() ); // TODO: temporarily map old NaturalCubicSpline (which wasn't a // natural cubic spline) to renamed SimmSpline class. Later we // will replace this with an actual natural cubic spline. Object::renameType("NaturalCubicSpline", "SimmSpline"); // To support older type name of "natCubicSpline" Object::renameType("natCubicSpline", "SimmSpline"); } catch (const std::exception& e) { std::cerr << "ERROR during osimCommon Object registration:\n" << e.what() << "\n"; } } <commit_msg>Register TableSource and TableSourceVec3.<commit_after>/* -------------------------------------------------------------------------- * * OpenSim: RegisterTypes_osimCommon.cpp * * -------------------------------------------------------------------------- * * The OpenSim API is a toolkit for musculoskeletal modeling and simulation. * * See http://opensim.stanford.edu and the NOTICE file for more information. * * OpenSim is developed at Stanford University and supported by the US * * National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA * * through the Warrior Web program. * * * * Copyright (c) 2005-2012 Stanford University and the Authors * * Author(s): Frank C. Anderson * * * * 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 "Object.h" #include "Component.h" #include "RegisterTypes_osimCommon.h" #include "FunctionSet.h" #include "GCVSplineSet.h" #include "ScaleSet.h" #include "GCVSpline.h" #include "Scale.h" #include "SimmSpline.h" #include "Constant.h" #include "Sine.h" #include "StepFunction.h" #include "LinearFunction.h" #include "PiecewiseLinearFunction.h" #include "PiecewiseConstantFunction.h" #include "MultiplierFunction.h" #include "PolynomialFunction.h" #include "ObjectGroup.h" #include "Reporter.h" #include "TableSource.h" #include <string> #include <iostream> #include <exception> using namespace OpenSim; using namespace std; //_____________________________________________________________________________ /** * The purpose of this routine is to register all class types exported by * the osimCommon library. */ OSIMCOMMON_API void RegisterTypes_osimCommon() { try { Object::registerType(Connector<Component>()); // Register commonly used Inputs for de/serialization Object::registerType(Input<double>()); Object::registerType(Input<SimTK::Vec3>()); Object::registerType(Input<SimTK::Vector>()); Object::registerType(Input<SimTK::SpatialVec>()); //SimTK::Xml::setXmlCondenseWhiteSpace(false); Object::registerType( FunctionSet() ); Object::registerType( GCVSplineSet() ); Object::registerType( ScaleSet() ); Object::registerType( GCVSpline() ); Object::registerType( Scale() ); Object::registerType( SimmSpline() ); Object::registerType( Constant() ); Object::registerType( Sine() ); Object::registerType( StepFunction() ); Object::registerType( LinearFunction() ); Object::registerType( PiecewiseLinearFunction() ); Object::registerType( PiecewiseConstantFunction() ); Object::registerType( MultiplierFunction() ); Object::registerType(PolynomialFunction()); Object::registerType( ObjectGroup() ); Object::registerType( TableSource() ); Object::registerType( TableSourceVec3() ); Object::registerType( TableReporter() ); Object::registerType( TableReporterVec3() ); Object::registerType( TableReporterVector() ); Object::registerType( ConsoleReporter() ); Object::registerType( ConsoleReporterVec3() ); // TODO: temporarily map old NaturalCubicSpline (which wasn't a // natural cubic spline) to renamed SimmSpline class. Later we // will replace this with an actual natural cubic spline. Object::renameType("NaturalCubicSpline", "SimmSpline"); // To support older type name of "natCubicSpline" Object::renameType("natCubicSpline", "SimmSpline"); } catch (const std::exception& e) { std::cerr << "ERROR during osimCommon Object registration:\n" << e.what() << "\n"; } } <|endoftext|>
<commit_before>#include "gtest/gtest.h" #include <pistache/optional.h> using Pistache::Optional; TEST(optional, constructor) { Optional<bool> value(Pistache::Some(true)); ASSERT_FALSE(value.isEmpty()); EXPECT_TRUE(value.get()); } TEST(optional, copy_constructor) { Optional<bool> value(Pistache::Some(true)); ASSERT_FALSE(value.isEmpty()); EXPECT_TRUE(value.get()); Optional<bool> copy_constructed(value); ASSERT_FALSE(copy_constructed.isEmpty()); EXPECT_TRUE(copy_constructed.get()); } TEST(optional, assignment_operator) { Optional<bool> value; EXPECT_TRUE(value.isEmpty()); value = Pistache::Some(true); ASSERT_FALSE(value.isEmpty()); EXPECT_TRUE(value.get()); } TEST(optional, copy_assignment_operator) { Optional<bool> value(Pistache::Some(true)); ASSERT_FALSE(value.isEmpty()); Optional<bool> other; EXPECT_TRUE(other.isEmpty()); other = value; ASSERT_FALSE(other.isEmpty()); EXPECT_TRUE(other.get()); } TEST(optional, move_constructor) { Optional<bool> value(Pistache::Some(true)); ASSERT_FALSE(value.isEmpty()); EXPECT_TRUE(value.get()); Optional<bool> value_from_move(std::move(value)); ASSERT_FALSE(value_from_move.isEmpty()); EXPECT_TRUE(value_from_move.get()); } TEST(optional, move_assignment_operator) { Optional<bool> value(Pistache::Some(true)); ASSERT_FALSE(value.isEmpty()); EXPECT_TRUE(value.get()); Optional<bool> move_assigned = std::move(value); ASSERT_FALSE(move_assigned.isEmpty()); EXPECT_TRUE(move_assigned.get()); } TEST(optional, constructor_none) { Optional<bool> value(Pistache::None()); EXPECT_TRUE(value.isEmpty()); } TEST(optional, copy_constructor_none) { Optional<bool> value(Pistache::None()); EXPECT_TRUE(value.isEmpty()); Optional<bool> copy_constructed(value); EXPECT_TRUE(value.isEmpty()); } TEST(optional, assignment_operator_none) { Optional<bool> value(Pistache::None()); EXPECT_TRUE(value.isEmpty()); Optional<bool> assigned = Pistache::None(); EXPECT_TRUE(assigned.isEmpty()); } TEST(optional, move_constructor_none) { Optional<bool> value(Pistache::None()); EXPECT_TRUE(value.isEmpty()); Optional<bool> move_constructed(std::move(value)); EXPECT_TRUE(move_constructed.isEmpty()); } TEST(optional, move_assignment_operator_none) { Optional<bool> value(Pistache::None()); EXPECT_TRUE(value.isEmpty()); Optional<bool> move_assigned(std::move(value)); EXPECT_TRUE(move_assigned.isEmpty()); } <commit_msg>explicitly state "copy" for tests of the copy assignment operator<commit_after>#include "gtest/gtest.h" #include <pistache/optional.h> using Pistache::Optional; TEST(optional, constructor) { Optional<bool> value(Pistache::Some(true)); ASSERT_FALSE(value.isEmpty()); EXPECT_TRUE(value.get()); } TEST(optional, copy_constructor) { Optional<bool> value(Pistache::Some(true)); ASSERT_FALSE(value.isEmpty()); EXPECT_TRUE(value.get()); Optional<bool> copy_constructed(value); ASSERT_FALSE(copy_constructed.isEmpty()); EXPECT_TRUE(copy_constructed.get()); } TEST(optional, copy_assignment_operator_for_convertible_type) { Optional<bool> value; EXPECT_TRUE(value.isEmpty()); value = Pistache::Some(true); ASSERT_FALSE(value.isEmpty()); EXPECT_TRUE(value.get()); } TEST(optional, copy_assignment_operator) { Optional<bool> value(Pistache::Some(true)); ASSERT_FALSE(value.isEmpty()); Optional<bool> other; EXPECT_TRUE(other.isEmpty()); other = value; ASSERT_FALSE(other.isEmpty()); EXPECT_TRUE(other.get()); } TEST(optional, move_constructor) { Optional<bool> value(Pistache::Some(true)); ASSERT_FALSE(value.isEmpty()); EXPECT_TRUE(value.get()); Optional<bool> value_from_move(std::move(value)); ASSERT_FALSE(value_from_move.isEmpty()); EXPECT_TRUE(value_from_move.get()); } TEST(optional, move_assignment_operator) { Optional<bool> value(Pistache::Some(true)); ASSERT_FALSE(value.isEmpty()); EXPECT_TRUE(value.get()); Optional<bool> move_assigned = std::move(value); ASSERT_FALSE(move_assigned.isEmpty()); EXPECT_TRUE(move_assigned.get()); } TEST(optional, constructor_none) { Optional<bool> value(Pistache::None()); EXPECT_TRUE(value.isEmpty()); } TEST(optional, copy_constructor_none) { Optional<bool> value(Pistache::None()); EXPECT_TRUE(value.isEmpty()); Optional<bool> copy_constructed(value); EXPECT_TRUE(value.isEmpty()); } TEST(optional, copy_assignment_operator_none) { Optional<bool> value(Pistache::None()); EXPECT_TRUE(value.isEmpty()); Optional<bool> assigned = Pistache::None(); EXPECT_TRUE(assigned.isEmpty()); } TEST(optional, move_constructor_none) { Optional<bool> value(Pistache::None()); EXPECT_TRUE(value.isEmpty()); Optional<bool> move_constructed(std::move(value)); EXPECT_TRUE(move_constructed.isEmpty()); } TEST(optional, move_assignment_operator_none) { Optional<bool> value(Pistache::None()); EXPECT_TRUE(value.isEmpty()); Optional<bool> move_assigned(std::move(value)); EXPECT_TRUE(move_assigned.isEmpty()); } <|endoftext|>