text
stringlengths
54
60.6k
<commit_before>/* Copyright (c) 2017 Wenova - Rise of Conquerors. All rights reserved. * * This work is licensed under the terms of the MIT license. * For a copy, see <https://opensource.org/licenses/MIT>. */ /** * @file EditableFloor.cpp * Implements class EditableFloor methods. */ /** * Commented debugs should be used with extreme care because it causes * extremelly lose of performance and giant log files. */ #include "EditableFloor.h" #include "Collision.h" #include "InputManager.h" #include "Rectangle.h" #include <cstdio> #define BACKGROUND_WIDTH 1280 #define BACKGROUND_HEIGHT 720 #define RESIZING_SPEED 0.005 #define ROTATING_SPEED 0.01 #define MOVE_SPEED 0.5 #define ACCELERATION 1 #define MAXIMUM_ACCELERATION 4 #define ACCELERATION_INCREASE_STEP 0.2 #define RIGID_PLATFORM_PATH "edit_state/floor/editable_floor.png" #define CROSSINGABLE_PLATFORM_PATH "edit_state/floor/editable_platform.png" #define SELECTED_CROSSINGABLE_PLATFORM_PATH \ "edit_state/floor/selected_editable_floor.png" #define DEBUG_SIZE 500 #define FILL_MISSING_PIXELS_DEBUGRMATIONS 15 #define LAYER 0 #define FLOOR_INITIAL_WIDTH 100 #define PI 3.14159265358979 #define PI_DEGREES 180 /** * Create box with default width of 100px. * * @param x Position in X axis. Unit: px, [0,screen_width] * @param y Position in Y axis. Unit: px, [0,screen_height] * @param crotation Unit: degrees * @param cplatform [0,1] */ EditableFloor::EditableFloor(float x, float y, float crotation, bool cplatform) : Floor(x, y, FLOOR_INITIAL_WIDTH, crotation, cplatform), standard_sprite(Sprite(RIGID_PLATFORM_PATH)), platform_sprite(Sprite(CROSSINGABLE_PLATFORM_PATH)), selected_sprite(Sprite(SELECTED_CROSSINGABLE_PLATFORM_PATH)) { #ifndef NDEBUG std::string log_message = "Starting EditableFloor constructor with x: "; log_message += std::to_string(x) + ", y: " + std::to_string(y); log_message += ", crotation: " + std::to_string(crotation); log_message += ", cplatfrom: " + std::to_string(static_cast<int>(cplatform)); LOG(DEBUG) << log_message; #endif box = Rectangle(x, y, standard_sprite.get_width(), standard_sprite.get_height()); is_deleted = false; is_selected = false; LOG(DEBUG) << "Ending EditableFloor constructor"; } /** * Create box with specific width. * * @param x Position in X axis. Unit: px, [0,screen_width] * @param y Position in Y axis. Unit: px, [0,screen_height] * @param width Unit: px, [0,] * @param crotation Unit: degrees * @param cplatform [0,1] */ EditableFloor::EditableFloor(float x, float y, float width, float crotation, bool cplatform) : EditableFloor(x, y, crotation, cplatform) { #ifndef NDEBUG std::string log_message = "Starting EditableFloor constructor with x: "; log_message += std::to_string(x) + ", y: " + std::to_string(y); log_message += ", width:" + std::to_string(width); log_message += ", crotation: " + std::to_string(crotation); log_message += ", cplatfrom: " + std::to_string(static_cast<int>(cplatform)); LOG(DEBUG) << log_message; if (x <= BACKGROUND_WIDTH) { /* Nothing to do. */ } else { LOG(FATAL) << "platform is out of screen in axis x"; } if (x <= BACKGROUND_WIDTH) { /* Nothing to do. */ } else { LOG(FATAL) << "platform is out of screen in axis y"; } #endif standard_sprite.set_scale_x(width / standard_sprite.get_width()); platform_sprite.set_scale_x(width / platform_sprite.get_width()); selected_sprite.set_scale_x(width / selected_sprite.get_width()); box.width = standard_sprite.get_width(); LOG(DEBUG) << "Ending EditableFloor init"; } /** * Not implemented. */ EditableFloor::~EditableFloor() { } /** * Get information about many aspects of an box. * * @returns String in format: "x y width rotated level is_crossingable?" */ string EditableFloor::get_information() { LOG(DEBUG) << "Starting EditableFloor get_information"; char info_c[DEBUG_SIZE]; snprintf(info_c, sizeof(info_c), "%f %f %f %f %d", box.x, box.y, box.width, rotation * PI_DEGREES / PI, static_cast<int>(is_crossingable)); string info(info_c); for (auto &c : info) { c += FILL_MISSING_PIXELS_DEBUGRMATIONS; } string return_value = info; /* * Check if string reallyhas the elements. * info == info_c for sure */ float float1, float2, float3, float4; int int1; if (sscanf(info_c, "%f %f %f %f %d", &float1, &float2, &float3, &float4, &int1) == 5) { /* Nothing to do. */ } else { LOG(WARNING) << "Info doesn't has all the information it should have"; } std::string log_message = "Ending EditableFloor get_information returning value: " + return_value; LOG(DEBUG) << log_message; return return_value; } /** * Select elements which will be edited. * * @param cis_selected [0,1] */ void EditableFloor::set_selected(bool cis_selected) { #ifndef NDEBUG std::string log_message = "Starting EditableFloor set_selected with cis_selected: " + static_cast<int>(cis_selected); LOG(DEBUG) << log_message; #endif is_selected = cis_selected; LOG(DEBUG) << "Ending EditableFloor set_selected"; } /** * Render selected box considering if it is selected. */ void EditableFloor::render() { // LOG(DEBUG) << "Starting EditableFloor render"; if (is_selected) { selected_sprite.render(box.get_draw_x(), box.get_draw_y(), rotation); } else { /* Nothing to do. */ } if (is_crossingable) { platform_sprite.render(box.get_draw_x(), box.get_draw_y(), rotation); } else { standard_sprite.render(box.get_draw_x(), box.get_draw_y(), rotation); } // LOG(DEBUG) << "Ending EditableFloor render"; } /** * Manages player interaction with the box. * * @param delta_time Difference in position of the box. */ void EditableFloor::update(float delta_time) { /* #ifndef NDEBUG char log_message_c[60]; snprintf(log_message_c, sizeof(log_message_c), "Starting EditableFloor update with delta_time: %.2f", delta_time); std::string log_message(log_message_c); LOG(DEBUG) << log_message; #endif */ handle_platforms_interaction(delta_time); // LOG(DEBUG) << "Ending EditableFloor update"; } /** * True if box has been deleted. * * @returns [0,1] */ bool EditableFloor::is_dead() { // LOG(DEBUG) << "Starting EditableFloor is_dead"; bool return_value = is_deleted; /* #ifndef NDEBUG std::string log_message = "Ending EditableFloor is_dead returning value: " + std::to_string(static_cast<int>(return_value)); LOG(DEBUG) << log_message; #endif */ return return_value; } /** * Will handle all interaction of the user with the platform. * * @param delta_time time spent on each frame of sprites */ void EditableFloor::handle_platforms_interaction(float delta_time) { // LOG(DEBUG) << "Starting EditableFloor handle_platforms_interaction // method"; InputManager *input_manager = InputManager::get_instance(); if (input_manager->mouse_press(InputManager::LEFT_MOUSE_BUTTON)) { int x = input_manager->get_mouse_x_position(); int y = input_manager->get_mouse_y_position(); Rectangle mouse = Rectangle(x, y, 1, 1); is_selected = Collision::is_colliding(box, mouse, rotation, 0); } else { /* Nothing to do. */ } if (is_selected) { static float acceleration = ACCELERATION; float delta_space = MOVE_SPEED * delta_time * acceleration; bool moved = false; handle_box_moving(moved, delta_space); handle_box_resizing(moved, delta_time); handle_box_rotating(acceleration, delta_space); handle_acceleration_increasing(moved, acceleration); /** * Toggle Floor. */ if (input_manager->key_press(InputManager::K_C)) { is_crossingable = not is_crossingable; } else { /* Nothing to do. */ } /** * Delete floor. */ if (input_manager->is_key_down(InputManager::K_DEL)) { is_deleted = true; } else { /* Nothing to do. */ } } else { /* Nothing to do. */ } // LOG(DEBUG) << "Ending EditableFloor handle_platforms_interaction method"; } /** * Handle platform player interaction with the platforms. * * @param moved will become true if platform move * @param delta_space how much platform will move */ void EditableFloor::handle_box_moving(bool &moved, float delta_space) { // NOLINT // LOG(DEBUG) << "Starting EditableFloor handle_box_moving method"; InputManager *input_manager = InputManager::get_instance(); if (input_manager->is_key_down(InputManager::K_ARROW_RIGHT)) { box.x += delta_space; moved = true; } else if (input_manager->is_key_down(InputManager::K_ARROW_LEFT)) { box.x -= delta_space; moved = true; } else { /* Nothing to do. */ } if (input_manager->is_key_down(InputManager::K_ARROW_UP)) { box.y -= delta_space; moved = true; } else if (input_manager->is_key_down(InputManager::K_ARROW_DOWN)) { box.y += delta_space; moved = true; } else { /* Nothing to do. */ } // LOG(DEBUG) << "Ending EditableFloor handle_box_moving method"; } /** * Handle platform player interaction with the platforms. * * @param moved will become true if platform move * @param delta_space how much platform will move */ void EditableFloor::handle_box_resizing(bool &moved, float delta_space) { // NOLINT // LOG(DEBUG) << "Starting EditableFloor handle_box_resizing method"; /** * Limit box sizes. */ if (box.x < 0) { box.x = 0; } else if (box.x > BACKGROUND_WIDTH) { box.x = BACKGROUND_WIDTH; } else if (box.y < 0) { box.y = 0; } else if (box.y > BACKGROUND_HEIGHT) { box.y = BACKGROUND_HEIGHT; } else { /* Nothing to do. */ } InputManager *input_manager = InputManager::get_instance(); /** * Increase floor width. */ if (input_manager->is_key_down(InputManager::K_INC_W)) { standard_sprite.update_scale_x(RESIZING_SPEED * delta_space); platform_sprite.update_scale_x(RESIZING_SPEED * delta_space); selected_sprite.update_scale_x(RESIZING_SPEED * delta_space); box.width = standard_sprite.get_width(); moved = true; } else { /* Nothing to do. */ } /** * Decrease floor width. */ if (input_manager->is_key_down(InputManager::K_DEC_W)) { standard_sprite.update_scale_x(-RESIZING_SPEED * delta_space); platform_sprite.update_scale_x(-RESIZING_SPEED * delta_space); selected_sprite.update_scale_x(-RESIZING_SPEED * delta_space); box.width = standard_sprite.get_width(); moved = true; } else { /* Nothing to do. */ } // LOG(DEBUG) << "Ending EditableFloor handle_box_resizing method"; } /** * Will handle rotation for both sides and reset. * * @param acceleration acceleration for rotating platform * @param delta_space intensifies rotating speed */ void EditableFloor::handle_box_rotating(float acceleration, float delta_space) { // LOG(DEBUG) << "Starting EditableFloor handle_box_rotating method"; InputManager *input_manager = InputManager::get_instance(); /** * Rotate box to corresponding direction or reset it. */ if (input_manager->is_key_down(InputManager::K_ROT_LEFT)) { rotation += ROTATING_SPEED * delta_space / acceleration; } else if (input_manager->is_key_down(InputManager::K_ROT_RIGHT)) { rotation -= ROTATING_SPEED * delta_space / acceleration; } else if (input_manager->is_key_down(InputManager::K_ROT_RESET)) { rotation = 0; } else { /* Nothing to do. */ } // LOG(DEBUG) << "Ending EditableFloor handle_box_rotating method"; } /** * Will handle if acceleration increase keeps ou reset * * @param moved if platform was moved, it will change behavior * @param acceleration acceleration that will be changed */ void EditableFloor::handle_acceleration_increasing( bool &moved, float &acceleration) { // NOLINT // LOG(DEBUG) << "Starting EditableFloor handle_acceleration_increasing // method"; if (moved) { acceleration = fmin(acceleration + ACCELERATION_INCREASE_STEP, MAXIMUM_ACCELERATION); } else { acceleration = ACCELERATION; } // LOG(DEBUG) << "Ending EditableFloor handle_acceleration_increasing // method"; } /** * Not implemented. * * @param unamed An game object. */ void EditableFloor::notify_collision(GameObject &) { } <commit_msg>Appropriate error handling on EditableFloor<commit_after>/* Copyright (c) 2017 Wenova - Rise of Conquerors. All rights reserved. * * This work is licensed under the terms of the MIT license. * For a copy, see <https://opensource.org/licenses/MIT>. */ /** * @file EditableFloor.cpp * Implements class EditableFloor methods. */ /** * Commented debugs should be used with extreme care because it causes * extremelly lose of performance and giant log files. */ #include "EditableFloor.h" #include "Collision.h" #include "InputManager.h" #include "Rectangle.h" #include <cstdio> #define BACKGROUND_WIDTH 1280 #define BACKGROUND_HEIGHT 720 #define RESIZING_SPEED 0.005 #define ROTATING_SPEED 0.01 #define MOVE_SPEED 0.5 #define ACCELERATION 1 #define MAXIMUM_ACCELERATION 4 #define ACCELERATION_INCREASE_STEP 0.2 #define RIGID_PLATFORM_PATH "edit_state/floor/editable_floor.png" #define CROSSINGABLE_PLATFORM_PATH "edit_state/floor/editable_platform.png" #define SELECTED_CROSSINGABLE_PLATFORM_PATH \ "edit_state/floor/selected_editable_floor.png" #define DEBUG_SIZE 500 #define FILL_MISSING_PIXELS_DEBUGRMATIONS 15 #define LAYER 0 #define FLOOR_INITIAL_WIDTH 100 #define PI 3.14159265358979 #define PI_DEGREES 180 /** * Create box with default width of 100px. * * @param x Position in X axis. Unit: px, [0,screen_width] * @param y Position in Y axis. Unit: px, [0,screen_height] * @param crotation Unit: degrees * @param cplatform [0,1] */ EditableFloor::EditableFloor(float x, float y, float crotation, bool cplatform) : Floor(x, y, FLOOR_INITIAL_WIDTH, crotation, cplatform), standard_sprite(Sprite(RIGID_PLATFORM_PATH)), platform_sprite(Sprite(CROSSINGABLE_PLATFORM_PATH)), selected_sprite(Sprite(SELECTED_CROSSINGABLE_PLATFORM_PATH)) { #ifndef NDEBUG try { std::string log_message = "Starting EditableFloor constructor with x: "; log_message += std::to_string(x) + ", y: " + std::to_string(y); log_message += ", crotation: " + std::to_string(crotation); log_message += ", cplatfrom: " + std::to_string(static_cast<int>(cplatform)); LOG(DEBUG) << log_message; } catch (std::bad_alloc &error) { string str_error(error.what()); string log_message = "Couldn't convert to string: " + str_error + '\n'; LOG(FATAL) << log_message; } #endif box = Rectangle(x, y, standard_sprite.get_width(), standard_sprite.get_height()); is_deleted = false; is_selected = false; LOG(DEBUG) << "Ending EditableFloor constructor"; } /** * Create box with specific width. * * @param x Position in X axis. Unit: px, [0,screen_width] * @param y Position in Y axis. Unit: px, [0,screen_height] * @param width Unit: px, [0,] * @param crotation Unit: degrees * @param cplatform [0,1] */ EditableFloor::EditableFloor(float x, float y, float width, float crotation, bool cplatform) : EditableFloor(x, y, crotation, cplatform) { #ifndef NDEBUG try { std::string log_message = "Starting EditableFloor constructor with x: "; log_message += std::to_string(x) + ", y: " + std::to_string(y); log_message += ", width:" + std::to_string(width); log_message += ", crotation: " + std::to_string(crotation); log_message += ", cplatfrom: " + std::to_string(static_cast<int>(cplatform)); LOG(DEBUG) << log_message; } catch (std::bad_alloc &error) { string str_error(error.what()); string log_message = "Couldn't convert to string: " + str_error + '\n'; LOG(FATAL) << log_message; } if (x <= BACKGROUND_WIDTH) { /* Nothing to do. */ } else { LOG(FATAL) << "platform is out of screen in axis x"; } if (x <= BACKGROUND_WIDTH) { /* Nothing to do. */ } else { LOG(FATAL) << "platform is out of screen in axis y"; } #endif standard_sprite.set_scale_x(width / standard_sprite.get_width()); platform_sprite.set_scale_x(width / platform_sprite.get_width()); selected_sprite.set_scale_x(width / selected_sprite.get_width()); box.width = standard_sprite.get_width(); LOG(DEBUG) << "Ending EditableFloor init"; } /** * Not implemented. */ EditableFloor::~EditableFloor() { } /** * Get information about many aspects of an box. * * @returns String in format: "x y width rotated level is_crossingable?" */ string EditableFloor::get_information() { LOG(DEBUG) << "Starting EditableFloor get_information"; char info_c[DEBUG_SIZE]; int snprint_return = snprintf( info_c, sizeof(info_c), "%f %f %f %f %d", box.x, box.y, box.width, rotation * PI_DEGREES / PI, static_cast<int>(is_crossingable)); if (snprint_return == 5) { /* Nothing to do. */ } else { LOG(ERROR) << "Could not get the complete information"; } string info(info_c); for (auto &c : info) { c += FILL_MISSING_PIXELS_DEBUGRMATIONS; } string return_value = info; /* * Check if string reallyhas the elements. * info == info_c for sure */ float float1, float2, float3, float4; int int1; if (sscanf(info_c, "%f %f %f %f %d", &float1, &float2, &float3, &float4, &int1) == 5) { /* Nothing to do. */ } else { LOG(WARNING) << "Info doesn't has all the information it should have"; } std::string log_message = "Ending EditableFloor get_information returning value: " + return_value; LOG(DEBUG) << log_message; return return_value; } /** * Select elements which will be edited. * * @param cis_selected [0,1] */ void EditableFloor::set_selected(bool cis_selected) { #ifndef NDEBUG std::string log_message = "Starting EditableFloor set_selected with cis_selected: " + static_cast<int>(cis_selected); LOG(DEBUG) << log_message; #endif is_selected = cis_selected; LOG(DEBUG) << "Ending EditableFloor set_selected"; } /** * Render selected box considering if it is selected. */ void EditableFloor::render() { // LOG(DEBUG) << "Starting EditableFloor render"; if (is_selected) { selected_sprite.render(box.get_draw_x(), box.get_draw_y(), rotation); } else { /* Nothing to do. */ } if (is_crossingable) { platform_sprite.render(box.get_draw_x(), box.get_draw_y(), rotation); } else { standard_sprite.render(box.get_draw_x(), box.get_draw_y(), rotation); } // LOG(DEBUG) << "Ending EditableFloor render"; } /** * Manages player interaction with the box. * * @param delta_time Difference in position of the box. */ void EditableFloor::update(float delta_time) { /* #ifndef NDEBUG char log_message_c[60]; snprintf(log_message_c, sizeof(log_message_c), "Starting EditableFloor update with delta_time: %.2f", delta_time); std::string log_message(log_message_c); LOG(DEBUG) << log_message; #endif */ handle_platforms_interaction(delta_time); // LOG(DEBUG) << "Ending EditableFloor update"; } /** * True if box has been deleted. * * @returns [0,1] */ bool EditableFloor::is_dead() { // LOG(DEBUG) << "Starting EditableFloor is_dead"; bool return_value = is_deleted; /* #ifndef NDEBUG std::string log_message = "Ending EditableFloor is_dead returning value: " + std::to_string(static_cast<int>(return_value)); LOG(DEBUG) << log_message; #endif */ return return_value; } /** * Will handle all interaction of the user with the platform. * * @param delta_time time spent on each frame of sprites */ void EditableFloor::handle_platforms_interaction(float delta_time) { // LOG(DEBUG) << "Starting EditableFloor handle_platforms_interaction // method"; InputManager *input_manager = InputManager::get_instance(); if (input_manager->mouse_press(InputManager::LEFT_MOUSE_BUTTON)) { int x = input_manager->get_mouse_x_position(); int y = input_manager->get_mouse_y_position(); Rectangle mouse = Rectangle(x, y, 1, 1); is_selected = Collision::is_colliding(box, mouse, rotation, 0); } else { /* Nothing to do. */ } if (is_selected) { static float acceleration = ACCELERATION; float delta_space = MOVE_SPEED * delta_time * acceleration; bool moved = false; handle_box_moving(moved, delta_space); handle_box_resizing(moved, delta_time); handle_box_rotating(acceleration, delta_space); handle_acceleration_increasing(moved, acceleration); /** * Toggle Floor. */ if (input_manager->key_press(InputManager::K_C)) { is_crossingable = not is_crossingable; } else { /* Nothing to do. */ } /** * Delete floor. */ if (input_manager->is_key_down(InputManager::K_DEL)) { is_deleted = true; } else { /* Nothing to do. */ } } else { /* Nothing to do. */ } // LOG(DEBUG) << "Ending EditableFloor handle_platforms_interaction method"; } /** * Handle platform player interaction with the platforms. * * @param moved will become true if platform move * @param delta_space how much platform will move */ void EditableFloor::handle_box_moving(bool &moved, float delta_space) { // LOG(DEBUG) << "Starting EditableFloor handle_box_moving method"; InputManager *input_manager = InputManager::get_instance(); if (input_manager->is_key_down(InputManager::K_ARROW_RIGHT)) { box.x += delta_space; moved = true; } else if (input_manager->is_key_down(InputManager::K_ARROW_LEFT)) { box.x -= delta_space; moved = true; } else { /* Nothing to do. */ } if (input_manager->is_key_down(InputManager::K_ARROW_UP)) { box.y -= delta_space; moved = true; } else if (input_manager->is_key_down(InputManager::K_ARROW_DOWN)) { box.y += delta_space; moved = true; } else { /* Nothing to do. */ } // LOG(DEBUG) << "Ending EditableFloor handle_box_moving method"; } /** * Handle platform player interaction with the platforms. * * @param moved will become true if platform move * @param delta_space how much platform will move */ void EditableFloor::handle_box_resizing(bool &moved, float delta_space) { // LOG(DEBUG) << "Starting EditableFloor handle_box_resizing method"; /** * Limit box sizes. */ if (box.x < 0) { box.x = 0; } else if (box.x > BACKGROUND_WIDTH) { box.x = BACKGROUND_WIDTH; } else if (box.y < 0) { box.y = 0; } else if (box.y > BACKGROUND_HEIGHT) { box.y = BACKGROUND_HEIGHT; } else { /* Nothing to do. */ } InputManager *input_manager = InputManager::get_instance(); /** * Resizing platform. */ if (input_manager->is_key_down(InputManager::K_INC_W)) { standard_sprite.update_scale_x(RESIZING_SPEED * delta_space); platform_sprite.update_scale_x(RESIZING_SPEED * delta_space); selected_sprite.update_scale_x(RESIZING_SPEED * delta_space); box.width = standard_sprite.get_width(); moved = true; } else if (input_manager->is_key_down(InputManager::K_DEC_W)) { standard_sprite.update_scale_x(-RESIZING_SPEED * delta_space); platform_sprite.update_scale_x(-RESIZING_SPEED * delta_space); selected_sprite.update_scale_x(-RESIZING_SPEED * delta_space); box.width = standard_sprite.get_width(); moved = true; } else { /* Nothing to do. */ } // LOG(DEBUG) << "Ending EditableFloor handle_box_resizing method"; } /** * Will handle rotation for both sides and reset. * * @param acceleration acceleration for rotating platform * @param delta_space intensifies rotating speed */ void EditableFloor::handle_box_rotating(float acceleration, float delta_space) { // LOG(DEBUG) << "Starting EditableFloor handle_box_rotating method"; InputManager *input_manager = InputManager::get_instance(); /** * Rotate box to corresponding direction or reset it. */ if (input_manager->is_key_down(InputManager::K_ROT_LEFT)) { rotation += ROTATING_SPEED * delta_space / acceleration; } else if (input_manager->is_key_down(InputManager::K_ROT_RIGHT)) { rotation -= ROTATING_SPEED * delta_space / acceleration; } else if (input_manager->is_key_down(InputManager::K_ROT_RESET)) { rotation = 0; } else { /* Nothing to do. */ } // LOG(DEBUG) << "Ending EditableFloor handle_box_rotating method"; } /** * Will handle if acceleration increase keeps ou reset * * @param moved if platform was moved, it will change behavior * @param acceleration acceleration that will be changed */ void EditableFloor::handle_acceleration_increasing(bool &moved, float &acceleration) { // LOG(DEBUG) << "Starting EditableFloor handle_acceleration_increasing // method"; if (moved) { acceleration = fmin(acceleration + ACCELERATION_INCREASE_STEP, MAXIMUM_ACCELERATION); } else { acceleration = ACCELERATION; } // LOG(DEBUG) << "Ending EditableFloor handle_acceleration_increasing // method"; } /** * Not implemented. * * @param unamed An game object. */ void EditableFloor::notify_collision(GameObject &) { } <|endoftext|>
<commit_before>/* * Raging MIDI (https://github.com/waddlesplash/ragingmidi). * * Copyright (c) 2012-2013 WaddleSplash & contributors (see AUTHORS.txt). * * 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 "PianoRoll.h" #include "ui_PianoRoll.h" #include "MainWind.h" #ifndef QT_NO_OPENGL # include <QGLWidget> #endif #include <QMenu> #include <math.h> // for pow() #define NOTE_HEIGHT 7 /* Static vars. */ bool PianoRoll::canMoveItems; /*******************************************************/ PianoRollLine::PianoRollLine(QObject* parent) : QObject(parent), QGraphicsRectItem(0) { setBrush(Qt::black); setRect(0,0,1,127*NOTE_HEIGHT); oldTick = 0; p = qobject_cast<QGraphicsView*>(parent); } void PianoRollLine::setTick(qint32 tick) { if(tick == oldTick) { return; } if(tick-oldTick < 15) { return; } oldTick = tick; int x = this->x(), y = this->y(), w = rect().width(), h = rect().height(); this->setPos(tick/2.0,0); if(!scene()) { return; } this->scene()->update(tick/2.0,0,1,scene()->height()); p->ensureVisible(this,p->viewport()->width()/2,0-scene()->height()); this->scene()->update(x,y,w,h); } /*******************************************************/ PianoRoll::PianoRoll(QWidget *parent) : QGraphicsView(parent), ui(new Ui::PianoRoll) { ui->setupUi(this); darker = QBrush(QColor("#c2e6ff")); lighter1 = QBrush(QColor("#eaf6ff")); lighter2 = QBrush(QColor("#daffd3")); this->setScene(new QGraphicsScene(this)); this->setRenderHints(QPainter::Antialiasing | QPainter::TextAntialiasing); tools = new QActionGroup(this); tools->addAction(ui->actionNavigationTool); tools->addAction(ui->actionMoveTool); connect(MainWind::settings,SIGNAL(somethingChanged(QString)),this,SLOT(handleChange(QString))); #ifndef QT_NO_OPENGL if(MainWind::settings->getHWA()) { this->setViewport(new QGLWidget(QGLFormat(QGL::SampleBuffers))); } #endif file = 0; line = 0; canMoveItems = false; } PianoRoll::~PianoRoll() { delete ui; } void PianoRoll::handleChange(QString a) { #ifndef QT_NO_OPENGL if(a == "HWA") { if(MainWind::settings->getHWA()) { this->setViewport(new QGLWidget(QGLFormat(QGL::SampleBuffers))); } else { this->setViewport(new QWidget()); } } #endif } void PianoRoll::handleNoteChange() { emit somethingChanged(); } PianoRollLine* PianoRoll::initLine(qint32 tick) { line = new PianoRollLine(this); line->setTick(tick); scene()->addItem((QGraphicsItem*)line); return line; } void PianoRoll::deleteLine() { scene()->removeItem((QGraphicsItem*)line); delete line; line = 0; } void PianoRoll::initEditor(QMidiFile* f) { scene()->clear(); file = f; PianoRollEvent* edEv = 0; QMidiEvent* noteOn = 0; QMap<int,QMidiEvent*> lastNoteOn; QList<QMidiEvent*>* events = file->events(); for(int i = 0;i<events->count(); i++) { QMidiEvent* e = events->at(i); if(e->isNoteEvent()) { if(e->type() == QMidiEvent::NoteOff) { noteOn = lastNoteOn.value(e->note(),0); if(!noteOn) { continue; } edEv = new PianoRollEvent(); edEv->setColor(MainWind::trackColors->value(e->track())); connect(edEv,SIGNAL(somethingChanged()), this,SLOT(handleNoteChange())); qreal y = (127 - e->note())*NOTE_HEIGHT; qreal w = (e->tick() - noteOn->tick())/2.0; edEv->setSize(noteOn->tick()/2.0,y,w,NOTE_HEIGHT); edEv->setNoteOnAndOff(noteOn,e); scene()->addItem((QGraphicsItem*)edEv); lastNoteOn.remove(e->note()); } else { lastNoteOn.insert(e->note(),e); } } } this->setSceneRect(QRect()); } void PianoRoll::wheelEvent(QWheelEvent* e) { // http://www.qtcentre.org/threads/35738#post174006 if(e->modifiers().testFlag(Qt::ControlModifier)) { int numSteps = e->delta() / 15 / 8; if(numSteps == 0) { e->ignore(); return; } qreal sc = pow(1.25, numSteps); zoom(sc, mapToScene(e->pos())); e->accept(); } else { QGraphicsView::wheelEvent(e); } } void PianoRoll::zoom(qreal factor, QPointF centerPoint) { scale(factor, factor); centerOn(centerPoint); } void PianoRoll::contextMenuEvent(QContextMenuEvent *event) { QMenu m(this); m.addAction(tr("Zoom 100%")); QAction* a = m.exec(mapToGlobal(event->pos())); if(!a) { return; } if(a->text() == tr("Zoom 100%")) { this->resetTransform(); } } static int pianoKeyColor[12] = { 0 /* white */, 1 /* black */, 0, 1, 0, 0, 1, 0, 1, 0, 1, 0 }; void PianoRoll::drawBackground(QPainter *painter, const QRectF &rect) { qreal width = this->scene()->width(); painter->setClipRect(rect); painter->setPen(Qt::NoPen); for(int i = 0; i < 128; i++) { if(i == 60) { // Middle C painter->setBrush(QBrush(QColor("#80ff80"))); } else { int octave = (i - 5) / 12; painter->setBrush(pianoKeyColor[i % 12] ? darker : ((octave % 2) ? lighter1 : lighter2)); } painter->drawRect(QRectF(0,i*NOTE_HEIGHT,width,NOTE_HEIGHT)); } } void PianoRoll::on_actionMoveTool_toggled(bool v) { canMoveItems = v; } /*******************************************************/ PianoRollEvent::PianoRollEvent(QObject *p) : QObject(p), QGraphicsRectItem(0) { setFlag(QGraphicsItem::ItemIsFocusable); setFlag(QGraphicsItem::ItemIsSelectable); setFlag(QGraphicsItem::ItemIsMovable); } void PianoRollEvent::mousePressEvent(QGraphicsSceneMouseEvent *e) { if(PianoRoll::canMoveItems) { QGraphicsRectItem::mousePressEvent(e); } } void PianoRollEvent::mouseMoveEvent(QGraphicsSceneMouseEvent *e) { if(PianoRoll::canMoveItems) { QGraphicsRectItem::mouseMoveEvent(e); } } void PianoRollEvent::mouseReleaseEvent(QGraphicsSceneMouseEvent *e) { if(!PianoRoll::canMoveItems) { return; } QGraphicsRectItem::mouseReleaseEvent(e); int note = 127-(y()/NOTE_HEIGHT); qint32 tick = x()*2; qint32 dur = myNoteOff->tick()-myNoteOn->tick(); if(tick == myNoteOn->tick()) { return; } else { emit somethingChanged(); } if(note > 127) { note = 127; } if(note < 0) { note = 0; } if(tick < 0) { tick = 0; } setY((127-note)*NOTE_HEIGHT); setX(tick/2.0); myNoteOn->setNote(note); myNoteOn->setTick(tick); myNoteOff->setNote(note); myNoteOff->setTick(tick+dur); } void PianoRollEvent::paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *) { painter->setBrush(myColor); if(this->rect().width() > 3) { painter->drawRoundedRect(rect(),3,3); } else { painter->drawRoundedRect(rect(),1,1); } } <commit_msg>Increase note height to 9px.<commit_after>/* * Raging MIDI (https://github.com/waddlesplash/ragingmidi). * * Copyright (c) 2012-2013 WaddleSplash & contributors (see AUTHORS.txt). * * 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 "PianoRoll.h" #include "ui_PianoRoll.h" #include "MainWind.h" #ifndef QT_NO_OPENGL # include <QGLWidget> #endif #include <QMenu> #include <math.h> // for pow() #define NOTE_HEIGHT 9 /* pixels */ /* Static vars. */ bool PianoRoll::canMoveItems; /*******************************************************/ PianoRollLine::PianoRollLine(QObject* parent) : QObject(parent), QGraphicsRectItem(0) { setBrush(Qt::black); setRect(0,0,1,127*NOTE_HEIGHT); oldTick = 0; p = qobject_cast<QGraphicsView*>(parent); } void PianoRollLine::setTick(qint32 tick) { if(tick == oldTick) { return; } if(tick-oldTick < 15) { return; } oldTick = tick; int x = this->x(), y = this->y(), w = rect().width(), h = rect().height(); this->setPos(tick/2.0,0); if(!scene()) { return; } this->scene()->update(tick/2.0,0,1,scene()->height()); p->ensureVisible(this,p->viewport()->width()/2,0-scene()->height()); this->scene()->update(x,y,w,h); } /*******************************************************/ PianoRoll::PianoRoll(QWidget *parent) : QGraphicsView(parent), ui(new Ui::PianoRoll) { ui->setupUi(this); darker = QBrush(QColor("#c2e6ff")); lighter1 = QBrush(QColor("#eaf6ff")); lighter2 = QBrush(QColor("#daffd3")); this->setScene(new QGraphicsScene(this)); this->setRenderHints(QPainter::Antialiasing | QPainter::TextAntialiasing); tools = new QActionGroup(this); tools->addAction(ui->actionNavigationTool); tools->addAction(ui->actionMoveTool); connect(MainWind::settings,SIGNAL(somethingChanged(QString)),this,SLOT(handleChange(QString))); #ifndef QT_NO_OPENGL if(MainWind::settings->getHWA()) { this->setViewport(new QGLWidget(QGLFormat(QGL::SampleBuffers))); } #endif file = 0; line = 0; canMoveItems = false; } PianoRoll::~PianoRoll() { delete ui; } void PianoRoll::handleChange(QString a) { #ifndef QT_NO_OPENGL if(a == "HWA") { if(MainWind::settings->getHWA()) { this->setViewport(new QGLWidget(QGLFormat(QGL::SampleBuffers))); } else { this->setViewport(new QWidget()); } } #endif } void PianoRoll::handleNoteChange() { emit somethingChanged(); } PianoRollLine* PianoRoll::initLine(qint32 tick) { line = new PianoRollLine(this); line->setTick(tick); scene()->addItem((QGraphicsItem*)line); return line; } void PianoRoll::deleteLine() { scene()->removeItem((QGraphicsItem*)line); delete line; line = 0; } void PianoRoll::initEditor(QMidiFile* f) { scene()->clear(); file = f; PianoRollEvent* edEv = 0; QMidiEvent* noteOn = 0; QMap<int,QMidiEvent*> lastNoteOn; QList<QMidiEvent*>* events = file->events(); for(int i = 0;i<events->count(); i++) { QMidiEvent* e = events->at(i); if(e->isNoteEvent()) { if(e->type() == QMidiEvent::NoteOff) { noteOn = lastNoteOn.value(e->note(),0); if(!noteOn) { continue; } edEv = new PianoRollEvent(); edEv->setColor(MainWind::trackColors->value(e->track())); connect(edEv,SIGNAL(somethingChanged()), this,SLOT(handleNoteChange())); qreal y = (127 - e->note())*NOTE_HEIGHT; qreal w = (e->tick() - noteOn->tick())/2.0; edEv->setSize(noteOn->tick()/2.0,y,w,NOTE_HEIGHT); edEv->setNoteOnAndOff(noteOn,e); scene()->addItem((QGraphicsItem*)edEv); lastNoteOn.remove(e->note()); } else { lastNoteOn.insert(e->note(),e); } } } this->setSceneRect(QRect()); } void PianoRoll::wheelEvent(QWheelEvent* e) { // http://www.qtcentre.org/threads/35738#post174006 if(e->modifiers().testFlag(Qt::ControlModifier)) { int numSteps = e->delta() / 15 / 8; if(numSteps == 0) { e->ignore(); return; } qreal sc = pow(1.25, numSteps); zoom(sc, mapToScene(e->pos())); e->accept(); } else { QGraphicsView::wheelEvent(e); } } void PianoRoll::zoom(qreal factor, QPointF centerPoint) { scale(factor, factor); centerOn(centerPoint); } void PianoRoll::contextMenuEvent(QContextMenuEvent *event) { QMenu m(this); m.addAction(tr("Zoom 100%")); QAction* a = m.exec(mapToGlobal(event->pos())); if(!a) { return; } if(a->text() == tr("Zoom 100%")) { this->resetTransform(); } } static int pianoKeyColor[12] = { 0 /* white */, 1 /* black */, 0, 1, 0, 0, 1, 0, 1, 0, 1, 0 }; void PianoRoll::drawBackground(QPainter *painter, const QRectF &rect) { qreal width = this->scene()->width(); painter->setClipRect(rect); painter->setPen(Qt::NoPen); for(int i = 0; i < 128; i++) { if(i == 60) { // Middle C painter->setBrush(QBrush(QColor("#80ff80"))); } else { int octave = (i - 5) / 12; painter->setBrush(pianoKeyColor[i % 12] ? darker : ((octave % 2) ? lighter1 : lighter2)); } painter->drawRect(QRectF(0,i*NOTE_HEIGHT,width,NOTE_HEIGHT)); } } void PianoRoll::on_actionMoveTool_toggled(bool v) { canMoveItems = v; } /*******************************************************/ PianoRollEvent::PianoRollEvent(QObject *p) : QObject(p), QGraphicsRectItem(0) { setFlag(QGraphicsItem::ItemIsFocusable); setFlag(QGraphicsItem::ItemIsSelectable); setFlag(QGraphicsItem::ItemIsMovable); } void PianoRollEvent::mousePressEvent(QGraphicsSceneMouseEvent *e) { if(PianoRoll::canMoveItems) { QGraphicsRectItem::mousePressEvent(e); } } void PianoRollEvent::mouseMoveEvent(QGraphicsSceneMouseEvent *e) { if(PianoRoll::canMoveItems) { QGraphicsRectItem::mouseMoveEvent(e); } } void PianoRollEvent::mouseReleaseEvent(QGraphicsSceneMouseEvent *e) { if(!PianoRoll::canMoveItems) { return; } QGraphicsRectItem::mouseReleaseEvent(e); int note = 127-(y()/NOTE_HEIGHT); qint32 tick = x()*2; qint32 dur = myNoteOff->tick()-myNoteOn->tick(); if(tick == myNoteOn->tick()) { return; } else { emit somethingChanged(); } if(note > 127) { note = 127; } if(note < 0) { note = 0; } if(tick < 0) { tick = 0; } setY((127-note)*NOTE_HEIGHT); setX(tick/2.0); myNoteOn->setNote(note); myNoteOn->setTick(tick); myNoteOff->setNote(note); myNoteOff->setTick(tick+dur); } void PianoRollEvent::paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *) { painter->setBrush(myColor); if(this->rect().width() > 3) { painter->drawRoundedRect(rect(),3,3); } else { painter->drawRoundedRect(rect(),1,1); } } <|endoftext|>
<commit_before>/** * * @file compiled_plugin_base.cpp * * @date Jan 15, 2013 * @author partio */ #include "compiled_plugin_base.h" #include <boost/thread.hpp> #include "plugin_factory.h" #include "logger_factory.h" #define HIMAN_AUXILIARY_INCLUDE #include "neons.h" #include "writer.h" #include "pcuda.h" #include "cache.h" #undef HIMAN_AUXILIARY_INCLUDE using namespace std; using namespace himan::plugin; const double kInterpolatedValueEpsilon = 0.00001; //<! Max difference between two grid points (if smaller, points are considered the same) mutex itsAdjustDimensionMutex; compiled_plugin_base::compiled_plugin_base() : itsPluginIsInitialized(false) { itsBaseLogger = std::unique_ptr<logger> (logger_factory::Instance()->GetLog("compiled_plugin_base")); } bool compiled_plugin_base::InterpolateToPoint(shared_ptr<const NFmiGrid> targetGrid, shared_ptr<NFmiGrid> sourceGrid, bool gridsAreEqual, double& value) { /* * Logic of interpolating values: * * 1) If source and target grids are equal, meaning that the grid AND the area * properties are effectively the same, do not interpolate. Instead return * the value of the source grid point that matches the ordering number of the * target grid point (ie. target grid point #1 --> source grid point #1 etc). * * 2) If actual interpolation is needed, first get the *grid* coordinates of the * latlon target point in the *source* grid. Then check if those grid coordinates * are very close to an actual grid point -- if so, return the value of the grid * point. This serves two purposes: * - We don't need to interpolate if the distance between requested grid point * and actual grid point is small enough, saving some CPU cycles * - Sometimes when the requested grid point is close to grid edge, floating * point inaccuracies might move it outside the grid. If this happens, the * interpolation fails even though the grid point is valid. * * 3) If requested source grid point is not near an actual grid point, interpolate * the value of the point. */ // Step 1) if (gridsAreEqual) { value = sourceGrid->FloatValue(targetGrid->GridPoint()); return true; } // Step 2) const NFmiPoint targetLatLonPoint = targetGrid->LatLon(); const NFmiPoint sourceGridPoint = sourceGrid->LatLonToGrid(targetLatLonPoint); bool noInterpolation = ( fabs(sourceGridPoint.X() - round(sourceGridPoint.X())) < kInterpolatedValueEpsilon && fabs(sourceGridPoint.Y() - round(sourceGridPoint.Y())) < kInterpolatedValueEpsilon ); if (noInterpolation) { value = sourceGrid->FloatValue(sourceGridPoint); return true; } // Step 3) return sourceGrid->InterpolateToGridPoint(sourceGridPoint, value); } bool compiled_plugin_base::AdjustLeadingDimension(shared_ptr<info> myTargetInfo) { lock_guard<mutex> lock(itsAdjustDimensionMutex); // Leading dimension can be: time or level if (itsLeadingDimension == kTimeDimension) { if (!itsInfo->NextTime()) { return false; } myTargetInfo->Time(itsInfo->Time()); } else if (itsLeadingDimension == kLevelDimension) { if (!itsInfo->NextLevel()) { return false; } myTargetInfo->Level(itsInfo->Level()); } else { throw runtime_error(ClassName() + ": Invalid dimension type: " + boost::lexical_cast<string> (itsLeadingDimension)); } return true; } bool compiled_plugin_base::AdjustNonLeadingDimension(shared_ptr<info> myTargetInfo) { if (itsLeadingDimension == kTimeDimension) { return myTargetInfo->NextLevel(); } else if (itsLeadingDimension == kLevelDimension) { return myTargetInfo->NextTime(); } else { throw runtime_error(ClassName() + ": unsupported leading dimension: " + boost::lexical_cast<string> (itsLeadingDimension)); } } void compiled_plugin_base::ResetNonLeadingDimension(shared_ptr<info> myTargetInfo) { if (itsLeadingDimension == kTimeDimension) { myTargetInfo->ResetLevel(); } else if (itsLeadingDimension == kLevelDimension) { myTargetInfo->ResetTime(); } else { throw runtime_error(ClassName() + ": unsupported leading dimension: " + boost::lexical_cast<string> (itsLeadingDimension)); } } bool compiled_plugin_base::SetAB(shared_ptr<info> myTargetInfo, shared_ptr<info> sourceInfo) { if (myTargetInfo->Level().Type() == kHybrid) { size_t index = myTargetInfo->ParamIndex(); myTargetInfo->Grid()->AB(sourceInfo->Grid()->AB()); myTargetInfo->ParamIndex(index); } return true; } bool compiled_plugin_base::SwapTo(shared_ptr<info> myTargetInfo, HPScanningMode targetScanningMode) { if (myTargetInfo->Grid()->ScanningMode() != targetScanningMode) { HPScanningMode originalMode = myTargetInfo->Grid()->ScanningMode(); myTargetInfo->Grid()->ScanningMode(targetScanningMode); myTargetInfo->Grid()->Swap(originalMode); } return true; } void compiled_plugin_base::WriteToFile(shared_ptr<const info> targetInfo) { shared_ptr<writer> aWriter = dynamic_pointer_cast <writer> (plugin_factory::Instance()->Plugin("writer")); // writing might modify iterator positions --> create a copy auto tempInfo = make_shared<info> (*targetInfo); if (itsConfiguration->FileWriteOption() == kNeons || itsConfiguration->FileWriteOption() == kMultipleFiles) { // If info holds multiple parameters, we must loop over them all // Note! We only loop over the parameters, not over the times or levels! tempInfo->ResetParam(); while (tempInfo->NextParam()) { aWriter->ToFile(tempInfo, itsConfiguration); } } else if (itsConfiguration->FileWriteOption() == kSingleFile) { aWriter->ToFile(tempInfo, itsConfiguration, itsConfiguration->ConfigurationFile()); } } bool compiled_plugin_base::GetAndSetCuda(shared_ptr<const configuration> conf, int threadIndex) { #ifdef HAVE_CUDA bool ret = conf->UseCuda() && conf->CudaDeviceId() < conf->CudaDeviceCount(); if (ret) { shared_ptr<pcuda> p = dynamic_pointer_cast <pcuda> (plugin_factory::Instance()->Plugin("pcuda")); ret = p->SetDevice(conf->CudaDeviceId()); } #else bool ret = false; #endif return ret; } void compiled_plugin_base::ResetCuda() const { #ifdef HAVE_CUDA shared_ptr<pcuda> p = dynamic_pointer_cast <pcuda> (plugin_factory::Instance()->Plugin("pcuda")); p->Reset(); #endif } void compiled_plugin_base::Start() { if (!itsPluginIsInitialized) { itsBaseLogger->Error("Start() called before Init()"); return; } boost::thread_group g; /* * Each thread will have a copy of the target info. */ for (short i = 0; i < itsThreadCount; i++) { printf("Info::compiled_plugin: Thread %d starting\n", (i + 1)); // Printf is thread safe boost::thread* t = new boost::thread(&compiled_plugin_base::Run, this, make_shared<info> (*itsInfo), i + 1); g.add_thread(t); } g.join_all(); Finish(); } void compiled_plugin_base::Init(shared_ptr<const plugin_configuration> conf) { const short MAX_THREADS = 12; //<! Max number of threads we allow itsConfiguration = conf; if (itsConfiguration->StatisticsEnabled()) { itsTimer = unique_ptr<timer> (timer_factory::Instance()->GetTimer()); itsTimer->Start(); itsConfiguration->Statistics()->UsedGPUCount(conf->CudaDeviceCount()); } // Determine thread count short coreCount = static_cast<short> (boost::thread::hardware_concurrency()); // Number of cores itsThreadCount = MAX_THREADS; // If user has specified thread count, always use that if (conf->ThreadCount() > 0) { itsThreadCount = conf->ThreadCount(); } // we don't want to use all cores in a server by default else if (MAX_THREADS > coreCount) { itsThreadCount = coreCount; } itsInfo = itsConfiguration->Info(); itsLeadingDimension = itsConfiguration->LeadingDimension(); itsPluginIsInitialized = true; } void compiled_plugin_base::Run(shared_ptr<info> myTargetInfo, unsigned short threadIndex) { while (AdjustLeadingDimension(myTargetInfo)) { Calculate(myTargetInfo, threadIndex); } } void compiled_plugin_base::Finish() { if (itsConfiguration->StatisticsEnabled()) { itsTimer->Stop(); itsConfiguration->Statistics()->AddToProcessingTime(itsTimer->GetTime()); } if (itsConfiguration->FileWriteOption() == kSingleFile) { WriteToFile(itsInfo); } } void compiled_plugin_base::Calculate(std::shared_ptr<info> myTargetInfo, unsigned short threadIndex) { itsBaseLogger->Fatal("Top level calculate called"); exit(1); } void compiled_plugin_base::SetParams(std::vector<param>& params) { if (params.empty()) { itsBaseLogger->Fatal("size of target parameter vector is zero"); exit(1); } // GRIB 1 if (itsConfiguration->OutputFileType() == kGRIB1) { auto n = dynamic_pointer_cast<plugin::neons> (plugin_factory::Instance()->Plugin("neons")); for (unsigned int i = 0; i < params.size(); i++) { long table2Version = itsInfo->Producer().TableVersion(); long parm_id = n->NeonsDB().GetGridParameterId(table2Version, params[i].Name()); if (parm_id == -1) { itsBaseLogger->Warning("Grib1 parameter definitions not found from Neons"); itsBaseLogger->Warning("table2Version is " + boost::lexical_cast<string> (table2Version) + ", parm_name is " + params[i].Name()); } params[i].GribIndicatorOfParameter(parm_id); params[i].GribTableVersion(table2Version); } } itsInfo->Params(params); /* * Create data structures. */ itsInfo->Create(); /* * Iterators must be reseted since they are at first position after Create() */ itsInfo->Reset(); /* * Do not launch more threads than there are things to calculate. */ if (itsLeadingDimension == kTimeDimension) { if (itsInfo->SizeTimes() < static_cast<size_t> (itsThreadCount)) { itsThreadCount = static_cast<short> (itsInfo->SizeTimes()); } } else if (itsLeadingDimension == kLevelDimension) { if (itsInfo->SizeLevels() < static_cast<size_t> (itsThreadCount)) { itsThreadCount = static_cast<short> (itsInfo->SizeLevels()); } } /* * From the timing perspective at this point plugin initialization is * considered to be done */ if (itsConfiguration->StatisticsEnabled()) { itsConfiguration->Statistics()->UsedThreadCount(itsThreadCount); itsTimer->Stop(); itsConfiguration->Statistics()->AddToInitTime(itsTimer->GetTime()); itsTimer->Start(); } } #ifdef HAVE_CUDA void compiled_plugin_base::Unpack(initializer_list<shared_ptr<info>> infos) { auto c = dynamic_pointer_cast<plugin::cache> (plugin_factory::Instance()->Plugin("cache")); for (auto it = infos.begin(); it != infos.end(); ++it) { shared_ptr<info> tempInfo = *it; if (!tempInfo->Grid()->PackedData() || tempInfo->Grid()->PackedData()->packedLength == 0) { // Safeguard: This particular info does not have packed data continue; } assert(tempInfo->Grid()->PackedData()->ClassName() == "simple_packed"); double* arr; size_t N = tempInfo->Grid()->PackedData()->unpackedLength; assert(N); CUDA_CHECK(cudaMallocHost(reinterpret_cast<void**> (&arr), sizeof(double) * N)); dynamic_pointer_cast<simple_packed> (tempInfo->Grid()->PackedData())->Unpack(arr, N); tempInfo->Data()->Set(arr, N); CUDA_CHECK(cudaFreeHost(arr)); tempInfo->Grid()->PackedData()->Clear(); if (itsConfiguration->UseCache()) { c->Insert(tempInfo); } } } void compiled_plugin_base::CopyDataFromSimpleInfo(shared_ptr<info> anInfo, info_simple* aSimpleInfo, bool writeToCache) { assert(aSimpleInfo); anInfo->Data()->Set(aSimpleInfo->values, aSimpleInfo->size_x * aSimpleInfo->size_y); if (anInfo->Grid()->IsPackedData()) { anInfo->Grid()->PackedData()->Clear(); } aSimpleInfo->free_values(); if (writeToCache && itsConfiguration->UseCache()) { auto c = dynamic_pointer_cast<plugin::cache> (plugin_factory::Instance()->Plugin("cache")); c->Insert(anInfo); } } #endif bool compiled_plugin_base::CompareGrids(initializer_list<shared_ptr<grid>> grids) { if (grids.size() <= 1) { throw kUnknownException; } auto it = grids.begin(); auto first = *it; for (++it; it != grids.end(); ++it) { if (*first != **it) { return false; } } return true; } bool compiled_plugin_base::IsMissingValue(initializer_list<double> values) { for (auto it = values.begin(); it != values.end(); ++it) { if (*it == kFloatMissing) { return true; } } return false; }<commit_msg>Skip null pointers<commit_after>/** * * @file compiled_plugin_base.cpp * * @date Jan 15, 2013 * @author partio */ #include "compiled_plugin_base.h" #include <boost/thread.hpp> #include "plugin_factory.h" #include "logger_factory.h" #define HIMAN_AUXILIARY_INCLUDE #include "neons.h" #include "writer.h" #include "pcuda.h" #include "cache.h" #undef HIMAN_AUXILIARY_INCLUDE using namespace std; using namespace himan::plugin; const double kInterpolatedValueEpsilon = 0.00001; //<! Max difference between two grid points (if smaller, points are considered the same) mutex itsAdjustDimensionMutex; compiled_plugin_base::compiled_plugin_base() : itsPluginIsInitialized(false) { itsBaseLogger = std::unique_ptr<logger> (logger_factory::Instance()->GetLog("compiled_plugin_base")); } bool compiled_plugin_base::InterpolateToPoint(shared_ptr<const NFmiGrid> targetGrid, shared_ptr<NFmiGrid> sourceGrid, bool gridsAreEqual, double& value) { /* * Logic of interpolating values: * * 1) If source and target grids are equal, meaning that the grid AND the area * properties are effectively the same, do not interpolate. Instead return * the value of the source grid point that matches the ordering number of the * target grid point (ie. target grid point #1 --> source grid point #1 etc). * * 2) If actual interpolation is needed, first get the *grid* coordinates of the * latlon target point in the *source* grid. Then check if those grid coordinates * are very close to an actual grid point -- if so, return the value of the grid * point. This serves two purposes: * - We don't need to interpolate if the distance between requested grid point * and actual grid point is small enough, saving some CPU cycles * - Sometimes when the requested grid point is close to grid edge, floating * point inaccuracies might move it outside the grid. If this happens, the * interpolation fails even though the grid point is valid. * * 3) If requested source grid point is not near an actual grid point, interpolate * the value of the point. */ // Step 1) if (gridsAreEqual) { value = sourceGrid->FloatValue(targetGrid->GridPoint()); return true; } // Step 2) const NFmiPoint targetLatLonPoint = targetGrid->LatLon(); const NFmiPoint sourceGridPoint = sourceGrid->LatLonToGrid(targetLatLonPoint); bool noInterpolation = ( fabs(sourceGridPoint.X() - round(sourceGridPoint.X())) < kInterpolatedValueEpsilon && fabs(sourceGridPoint.Y() - round(sourceGridPoint.Y())) < kInterpolatedValueEpsilon ); if (noInterpolation) { value = sourceGrid->FloatValue(sourceGridPoint); return true; } // Step 3) return sourceGrid->InterpolateToGridPoint(sourceGridPoint, value); } bool compiled_plugin_base::AdjustLeadingDimension(shared_ptr<info> myTargetInfo) { lock_guard<mutex> lock(itsAdjustDimensionMutex); // Leading dimension can be: time or level if (itsLeadingDimension == kTimeDimension) { if (!itsInfo->NextTime()) { return false; } myTargetInfo->Time(itsInfo->Time()); } else if (itsLeadingDimension == kLevelDimension) { if (!itsInfo->NextLevel()) { return false; } myTargetInfo->Level(itsInfo->Level()); } else { throw runtime_error(ClassName() + ": Invalid dimension type: " + boost::lexical_cast<string> (itsLeadingDimension)); } return true; } bool compiled_plugin_base::AdjustNonLeadingDimension(shared_ptr<info> myTargetInfo) { if (itsLeadingDimension == kTimeDimension) { return myTargetInfo->NextLevel(); } else if (itsLeadingDimension == kLevelDimension) { return myTargetInfo->NextTime(); } else { throw runtime_error(ClassName() + ": unsupported leading dimension: " + boost::lexical_cast<string> (itsLeadingDimension)); } } void compiled_plugin_base::ResetNonLeadingDimension(shared_ptr<info> myTargetInfo) { if (itsLeadingDimension == kTimeDimension) { myTargetInfo->ResetLevel(); } else if (itsLeadingDimension == kLevelDimension) { myTargetInfo->ResetTime(); } else { throw runtime_error(ClassName() + ": unsupported leading dimension: " + boost::lexical_cast<string> (itsLeadingDimension)); } } bool compiled_plugin_base::SetAB(shared_ptr<info> myTargetInfo, shared_ptr<info> sourceInfo) { if (myTargetInfo->Level().Type() == kHybrid) { size_t index = myTargetInfo->ParamIndex(); myTargetInfo->Grid()->AB(sourceInfo->Grid()->AB()); myTargetInfo->ParamIndex(index); } return true; } bool compiled_plugin_base::SwapTo(shared_ptr<info> myTargetInfo, HPScanningMode targetScanningMode) { if (myTargetInfo->Grid()->ScanningMode() != targetScanningMode) { HPScanningMode originalMode = myTargetInfo->Grid()->ScanningMode(); myTargetInfo->Grid()->ScanningMode(targetScanningMode); myTargetInfo->Grid()->Swap(originalMode); } return true; } void compiled_plugin_base::WriteToFile(shared_ptr<const info> targetInfo) { shared_ptr<writer> aWriter = dynamic_pointer_cast <writer> (plugin_factory::Instance()->Plugin("writer")); // writing might modify iterator positions --> create a copy auto tempInfo = make_shared<info> (*targetInfo); if (itsConfiguration->FileWriteOption() == kNeons || itsConfiguration->FileWriteOption() == kMultipleFiles) { // If info holds multiple parameters, we must loop over them all // Note! We only loop over the parameters, not over the times or levels! tempInfo->ResetParam(); while (tempInfo->NextParam()) { aWriter->ToFile(tempInfo, itsConfiguration); } } else if (itsConfiguration->FileWriteOption() == kSingleFile) { aWriter->ToFile(tempInfo, itsConfiguration, itsConfiguration->ConfigurationFile()); } } bool compiled_plugin_base::GetAndSetCuda(shared_ptr<const configuration> conf, int threadIndex) { #ifdef HAVE_CUDA bool ret = conf->UseCuda() && conf->CudaDeviceId() < conf->CudaDeviceCount(); if (ret) { shared_ptr<pcuda> p = dynamic_pointer_cast <pcuda> (plugin_factory::Instance()->Plugin("pcuda")); ret = p->SetDevice(conf->CudaDeviceId()); } #else bool ret = false; #endif return ret; } void compiled_plugin_base::ResetCuda() const { #ifdef HAVE_CUDA shared_ptr<pcuda> p = dynamic_pointer_cast <pcuda> (plugin_factory::Instance()->Plugin("pcuda")); p->Reset(); #endif } void compiled_plugin_base::Start() { if (!itsPluginIsInitialized) { itsBaseLogger->Error("Start() called before Init()"); return; } boost::thread_group g; /* * Each thread will have a copy of the target info. */ for (short i = 0; i < itsThreadCount; i++) { printf("Info::compiled_plugin: Thread %d starting\n", (i + 1)); // Printf is thread safe boost::thread* t = new boost::thread(&compiled_plugin_base::Run, this, make_shared<info> (*itsInfo), i + 1); g.add_thread(t); } g.join_all(); Finish(); } void compiled_plugin_base::Init(shared_ptr<const plugin_configuration> conf) { const short MAX_THREADS = 12; //<! Max number of threads we allow itsConfiguration = conf; if (itsConfiguration->StatisticsEnabled()) { itsTimer = unique_ptr<timer> (timer_factory::Instance()->GetTimer()); itsTimer->Start(); itsConfiguration->Statistics()->UsedGPUCount(conf->CudaDeviceCount()); } // Determine thread count short coreCount = static_cast<short> (boost::thread::hardware_concurrency()); // Number of cores itsThreadCount = MAX_THREADS; // If user has specified thread count, always use that if (conf->ThreadCount() > 0) { itsThreadCount = conf->ThreadCount(); } // we don't want to use all cores in a server by default else if (MAX_THREADS > coreCount) { itsThreadCount = coreCount; } itsInfo = itsConfiguration->Info(); itsLeadingDimension = itsConfiguration->LeadingDimension(); itsPluginIsInitialized = true; } void compiled_plugin_base::Run(shared_ptr<info> myTargetInfo, unsigned short threadIndex) { while (AdjustLeadingDimension(myTargetInfo)) { Calculate(myTargetInfo, threadIndex); } } void compiled_plugin_base::Finish() { if (itsConfiguration->StatisticsEnabled()) { itsTimer->Stop(); itsConfiguration->Statistics()->AddToProcessingTime(itsTimer->GetTime()); } if (itsConfiguration->FileWriteOption() == kSingleFile) { WriteToFile(itsInfo); } } void compiled_plugin_base::Calculate(std::shared_ptr<info> myTargetInfo, unsigned short threadIndex) { itsBaseLogger->Fatal("Top level calculate called"); exit(1); } void compiled_plugin_base::SetParams(std::vector<param>& params) { if (params.empty()) { itsBaseLogger->Fatal("size of target parameter vector is zero"); exit(1); } // GRIB 1 if (itsConfiguration->OutputFileType() == kGRIB1) { auto n = dynamic_pointer_cast<plugin::neons> (plugin_factory::Instance()->Plugin("neons")); for (unsigned int i = 0; i < params.size(); i++) { long table2Version = itsInfo->Producer().TableVersion(); long parm_id = n->NeonsDB().GetGridParameterId(table2Version, params[i].Name()); if (parm_id == -1) { itsBaseLogger->Warning("Grib1 parameter definitions not found from Neons"); itsBaseLogger->Warning("table2Version is " + boost::lexical_cast<string> (table2Version) + ", parm_name is " + params[i].Name()); } params[i].GribIndicatorOfParameter(parm_id); params[i].GribTableVersion(table2Version); } } itsInfo->Params(params); /* * Create data structures. */ itsInfo->Create(); /* * Iterators must be reseted since they are at first position after Create() */ itsInfo->Reset(); /* * Do not launch more threads than there are things to calculate. */ if (itsLeadingDimension == kTimeDimension) { if (itsInfo->SizeTimes() < static_cast<size_t> (itsThreadCount)) { itsThreadCount = static_cast<short> (itsInfo->SizeTimes()); } } else if (itsLeadingDimension == kLevelDimension) { if (itsInfo->SizeLevels() < static_cast<size_t> (itsThreadCount)) { itsThreadCount = static_cast<short> (itsInfo->SizeLevels()); } } /* * From the timing perspective at this point plugin initialization is * considered to be done */ if (itsConfiguration->StatisticsEnabled()) { itsConfiguration->Statistics()->UsedThreadCount(itsThreadCount); itsTimer->Stop(); itsConfiguration->Statistics()->AddToInitTime(itsTimer->GetTime()); // Start process timing itsTimer->Start(); } } #ifdef HAVE_CUDA void compiled_plugin_base::Unpack(initializer_list<shared_ptr<info>> infos) { auto c = dynamic_pointer_cast<plugin::cache> (plugin_factory::Instance()->Plugin("cache")); for (auto it = infos.begin(); it != infos.end(); ++it) { shared_ptr<info> tempInfo = *it; if (!tempInfo->Grid()->PackedData() || tempInfo->Grid()->PackedData()->packedLength == 0) { // Safeguard: This particular info does not have packed data continue; } assert(tempInfo->Grid()->PackedData()->ClassName() == "simple_packed"); double* arr; size_t N = tempInfo->Grid()->PackedData()->unpackedLength; assert(N); CUDA_CHECK(cudaMallocHost(reinterpret_cast<void**> (&arr), sizeof(double) * N)); dynamic_pointer_cast<simple_packed> (tempInfo->Grid()->PackedData())->Unpack(arr, N); tempInfo->Data()->Set(arr, N); CUDA_CHECK(cudaFreeHost(arr)); tempInfo->Grid()->PackedData()->Clear(); if (itsConfiguration->UseCache()) { c->Insert(tempInfo); } } } void compiled_plugin_base::CopyDataFromSimpleInfo(shared_ptr<info> anInfo, info_simple* aSimpleInfo, bool writeToCache) { assert(aSimpleInfo); anInfo->Data()->Set(aSimpleInfo->values, aSimpleInfo->size_x * aSimpleInfo->size_y); if (anInfo->Grid()->IsPackedData()) { anInfo->Grid()->PackedData()->Clear(); } aSimpleInfo->free_values(); if (writeToCache && itsConfiguration->UseCache()) { auto c = dynamic_pointer_cast<plugin::cache> (plugin_factory::Instance()->Plugin("cache")); c->Insert(anInfo); } } #endif bool compiled_plugin_base::CompareGrids(initializer_list<shared_ptr<grid>> grids) { if (grids.size() <= 1) { throw kUnknownException; } auto it = grids.begin(); auto first = *it; for (++it; it != grids.end(); ++it) { if (!*it) { continue; } if (*first != **it) { return false; } } return true; } bool compiled_plugin_base::IsMissingValue(initializer_list<double> values) { for (auto it = values.begin(); it != values.end(); ++it) { if (*it == kFloatMissing) { return true; } } return false; }<|endoftext|>
<commit_before> #include <Hord/LockFile.hpp> #include <cstdlib> #include <cstdio> #include <utility> #include <unistd.h> #include <sys/file.h> #include <Hord/detail/gr_ceformat.hpp> namespace Hord { // class LockFile implementation #define HORD_SCOPE_CLASS LockFile LockFile::~LockFile() { release(); } LockFile::LockFile( String path ) noexcept : m_path(std::move(path)) {} #define HORD_SCOPE_FUNC set_path namespace { HORD_DEF_FMT_FQN( s_err_immutable, "cannot change path to `%s` while lock is active" ); } // anonymous namespace void LockFile::set_path( String path ) { if (is_active()) { HORD_THROW_FMT( ErrorCode::lockfile_immutable, s_err_immutable, m_path ); } else { m_path.assign(std::move(path)); } } #undef HORD_SCOPE_FUNC #define HORD_SCOPE_FUNC acquire namespace { HORD_DEF_FMT_FQN( s_err_acquire_failed, "failed to acquire lock for `%s`" ); } // anonymous namespace void LockFile::acquire() { if (!is_active()) { handle_type const fd = ::open( m_path.c_str(), O_CREAT | O_RDONLY, S_IRUSR | S_IRGRP | S_IROTH // 444 ); if (NULL_HANDLE != fd) { if (0 == ::flock(fd, LOCK_EX | LOCK_NB)) { m_handle = fd; } else { ::close(fd); } } if (NULL_HANDLE == m_handle) { // TODO: add std::strerror() HORD_THROW_FMT( ErrorCode::lockfile_acquire_failed, s_err_acquire_failed, m_path ); } } } #undef HORD_SCOPE_FUNC #define HORD_SCOPE_FUNC release void LockFile::release() noexcept { if (is_active()) { // TODO: ::remove() on release? ::close(m_handle); m_handle = NULL_HANDLE; } } #undef HORD_SCOPE_FUNC #undef HORD_SCOPE_CLASS } // namespace Hord <commit_msg>LockFile: corrected immutability error message (was using path instead of m_path).<commit_after> #include <Hord/LockFile.hpp> #include <cstdlib> #include <cstdio> #include <utility> #include <unistd.h> #include <sys/file.h> #include <Hord/detail/gr_ceformat.hpp> namespace Hord { // class LockFile implementation #define HORD_SCOPE_CLASS LockFile LockFile::~LockFile() { release(); } LockFile::LockFile( String path ) noexcept : m_path(std::move(path)) {} #define HORD_SCOPE_FUNC set_path namespace { HORD_DEF_FMT_FQN( s_err_immutable, "cannot change path to `%s` while lock is active" ); } // anonymous namespace void LockFile::set_path( String path ) { if (is_active()) { HORD_THROW_FMT( ErrorCode::lockfile_immutable, s_err_immutable, path ); } else { m_path.assign(std::move(path)); } } #undef HORD_SCOPE_FUNC #define HORD_SCOPE_FUNC acquire namespace { HORD_DEF_FMT_FQN( s_err_acquire_failed, "failed to acquire lock for `%s`" ); } // anonymous namespace void LockFile::acquire() { if (!is_active()) { handle_type const fd = ::open( m_path.c_str(), O_CREAT | O_RDONLY, S_IRUSR | S_IRGRP | S_IROTH // 444 ); if (NULL_HANDLE != fd) { if (0 == ::flock(fd, LOCK_EX | LOCK_NB)) { m_handle = fd; } else { ::close(fd); } } if (NULL_HANDLE == m_handle) { // TODO: add std::strerror() HORD_THROW_FMT( ErrorCode::lockfile_acquire_failed, s_err_acquire_failed, m_path ); } } } #undef HORD_SCOPE_FUNC #define HORD_SCOPE_FUNC release void LockFile::release() noexcept { if (is_active()) { // TODO: ::remove() on release? ::close(m_handle); m_handle = NULL_HANDLE; } } #undef HORD_SCOPE_FUNC #undef HORD_SCOPE_CLASS } // namespace Hord <|endoftext|>
<commit_before>#ifndef ALEPH_PERSISTENT_HOMOLOGY_CONNECTED_COMPONENTS_HH__ #define ALEPH_PERSISTENT_HOMOLOGY_CONNECTED_COMPONENTS_HH__ #include "persistenceDiagrams/PersistenceDiagram.hh" #include "persistentHomology/PersistencePairing.hh" #include "topology/SimplicialComplex.hh" #include "topology/UnionFind.hh" #include <algorithm> #include <tuple> #include <unordered_map> #include <vector> namespace aleph { namespace traits { template <class Pairing> class PersistencePairingCalculation { public: PersistencePairingCalculation( Pairing& pairing ) : _pairing( pairing ) { } using IndexType = typename Pairing::IndexType; void add( IndexType u, IndexType v ) { _pairing.add( u, v ); } void add( IndexType u ) { _pairing.add( u ); } private: Pairing& _pairing; }; template <class Pairing> class NoPersistencePairingCalculation { public: NoPersistencePairingCalculation( Pairing& pairing ) : _pairing( pairing ) { } using IndexType = typename Pairing::IndexType; void add( IndexType /* u */, IndexType /* v */ ) const noexcept { } void add( IndexType /* u */ ) const noexcept { } private: Pairing& _pairing; }; class DiagonalElementCalculation { public: template <class T> bool operator()( T /* creation */, T /* destruction */ ) const noexcept { return true; } }; class NoDiagonalElementCalculation { public: template <class T> bool operator()( T creation, T destruction ) const noexcept { return creation != destruction; } }; } // namespace traits /** Calculates zero-dimensional persistent homology, i.e. tracking of connected components, for a given simplicial complex. This is highly-efficient, as it only requires a suitable 'Union--Find' data structure. As usual, the function assumes that the simplicial complex is in filtration order, meaning that faces are preceded by their cofaces. The function won't check this, though! */ template < class Simplex, class PairingCalculationTraits = traits::NoPersistencePairingCalculation< PersistencePairing<typename Simplex::VertexType> >, class ElementCalculationTraits = traits::NoDiagonalElementCalculation > std::tuple< PersistenceDiagram<typename Simplex::DataType>, PersistencePairing<typename Simplex::VertexType>, std::unordered_map<typename Simplex::VertexType, unsigned> > calculateZeroDimensionalPersistenceDiagram( const topology::SimplicialComplex<Simplex>& K ) { using DataType = typename Simplex::DataType; using VertexType = typename Simplex::VertexType; using namespace topology; std::vector<VertexType> vertices; K.vertices( std::back_inserter( vertices ) ); UnionFind<VertexType> uf( vertices.begin(), vertices.end() ); PersistenceDiagram<DataType> pd; // Persistence diagram PersistencePairing<VertexType> pp; // Persistence pairing std::unordered_map<VertexType, unsigned> cs; // Component sizes std::unordered_map<VertexType, std::vector<VertexType> > cc; // Connected components std::unordered_map<VertexType, DataType> ap; // Accumulated persistence PairingCalculationTraits ct( pp ); ElementCalculationTraits et; for( auto&& vertex : vertices ) { cs[vertex] = 1; cc[vertex] = { vertex }; } for( auto&& simplex : K ) { // Only edges can destroy a component; we may safely skip any other // simplex with a different dimension. if( simplex.dimension() != 1 ) continue; // Prepare component destruction ----------------------------------- VertexType u = *( simplex.begin() ); VertexType v = *( simplex.begin() + 1 ); auto youngerComponent = uf.find( u ); auto olderComponent = uf.find( v ); // If the component has already been merged by some other edge, we are // not interested in it any longer. if( youngerComponent == olderComponent ) continue; // Ensures that the younger component is always the first component. A // component is younger if it its parent vertex precedes the other one // in the current filtration. auto uIndex = K.index( Simplex( youngerComponent ) ); auto vIndex = K.index( Simplex( olderComponent ) ); // The younger component must have the _larger_ index as it is born // _later_ in the filtration. if( uIndex < vIndex ) { std::swap( youngerComponent, olderComponent ); std::swap( uIndex, vIndex ); } auto creation = K[uIndex].data(); auto destruction = simplex.data(); uf.merge( youngerComponent, olderComponent ); cs[olderComponent] += cs[youngerComponent]; cc[olderComponent].insert( cc[olderComponent].end(), cc[youngerComponent].begin(), cc[youngerComponent].end() ); for( auto&& vertex : cc[youngerComponent] ) ap[vertex] += DataType( destruction - creation ); cc.erase(youngerComponent); if( et( creation, destruction ) ) { pd.add( creation , destruction ); ct.add( static_cast<VertexType>( uIndex ), static_cast<VertexType>( K.index( simplex ) ) ); } else cs.erase( youngerComponent ); } // Store information about unpaired simplices ------------------------ // // All components in the Union--Find data structure now correspond to // essential 0-dimensional homology classes of the input complex. std::vector<VertexType> roots; uf.roots( std::back_inserter( roots ) ); for( auto&& root : roots ) { auto creator = *K.find( Simplex( root ) ); pd.add( creator.data() ); ct.add( static_cast<VertexType>( K.index( creator ) ) ); } return std::make_tuple( pd, pp, cs ); } } // namespace aleph #endif <commit_msg>Extended zero-dimensional persistent homology calculation with functors<commit_after>#ifndef ALEPH_PERSISTENT_HOMOLOGY_CONNECTED_COMPONENTS_HH__ #define ALEPH_PERSISTENT_HOMOLOGY_CONNECTED_COMPONENTS_HH__ #include "persistenceDiagrams/PersistenceDiagram.hh" #include "persistentHomology/PersistencePairing.hh" #include "topology/SimplicialComplex.hh" #include "topology/UnionFind.hh" #include "utilities/EmptyFunctor.hh" #include <algorithm> #include <tuple> #include <unordered_map> #include <vector> namespace aleph { namespace traits { template <class Pairing> class PersistencePairingCalculation { public: PersistencePairingCalculation( Pairing& pairing ) : _pairing( pairing ) { } using IndexType = typename Pairing::IndexType; void add( IndexType u, IndexType v ) { _pairing.add( u, v ); } void add( IndexType u ) { _pairing.add( u ); } private: Pairing& _pairing; }; template <class Pairing> class NoPersistencePairingCalculation { public: NoPersistencePairingCalculation( Pairing& pairing ) : _pairing( pairing ) { } using IndexType = typename Pairing::IndexType; void add( IndexType /* u */, IndexType /* v */ ) const noexcept { } void add( IndexType /* u */ ) const noexcept { } private: Pairing& _pairing; }; class DiagonalElementCalculation { public: template <class T> bool operator()( T /* creation */, T /* destruction */ ) const noexcept { return true; } }; class NoDiagonalElementCalculation { public: template <class T> bool operator()( T creation, T destruction ) const noexcept { return creation != destruction; } }; } // namespace traits /** Calculates zero-dimensional persistent homology, i.e. tracking of connected components, for a given simplicial complex. This is highly-efficient, as it only requires a suitable 'Union--Find' data structure. As usual, the function assumes that the simplicial complex is in filtration order, meaning that faces are preceded by their cofaces. The function won't check this, though! */ template < class Simplex, class PairingCalculationTraits = traits::NoPersistencePairingCalculation< PersistencePairing<typename Simplex::VertexType> >, class ElementCalculationTraits = traits::NoDiagonalElementCalculation, class Functor = aleph::utilities::EmptyFunctor > std::tuple< PersistenceDiagram<typename Simplex::DataType>, PersistencePairing<typename Simplex::VertexType>, std::unordered_map<typename Simplex::VertexType, unsigned> > calculateZeroDimensionalPersistenceDiagram( const topology::SimplicialComplex<Simplex>& K, Functor functor = Functor() ) { using DataType = typename Simplex::DataType; using VertexType = typename Simplex::VertexType; using namespace topology; std::vector<VertexType> vertices; K.vertices( std::back_inserter( vertices ) ); UnionFind<VertexType> uf( vertices.begin(), vertices.end() ); PersistenceDiagram<DataType> pd; // Persistence diagram PersistencePairing<VertexType> pp; // Persistence pairing std::unordered_map<VertexType, unsigned> cs; // Component sizes std::unordered_map<VertexType, std::vector<VertexType> > cc; // Connected components std::unordered_map<VertexType, DataType> ap; // Accumulated persistence PairingCalculationTraits ct( pp ); ElementCalculationTraits et; for( auto&& vertex : vertices ) { cs[vertex] = 1; cc[vertex] = { vertex }; functor.initialize( vertex ); } for( auto&& simplex : K ) { // Only edges can destroy a component; we may safely skip any other // simplex with a different dimension. if( simplex.dimension() != 1 ) continue; // Prepare component destruction ----------------------------------- VertexType u = *( simplex.begin() ); VertexType v = *( simplex.begin() + 1 ); auto youngerComponent = uf.find( u ); auto olderComponent = uf.find( v ); // If the component has already been merged by some other edge, we are // not interested in it any longer. if( youngerComponent == olderComponent ) continue; // Ensures that the younger component is always the first component. A // component is younger if it its parent vertex precedes the other one // in the current filtration. auto uIndex = K.index( Simplex( youngerComponent ) ); auto vIndex = K.index( Simplex( olderComponent ) ); // The younger component must have the _larger_ index as it is born // _later_ in the filtration. if( uIndex < vIndex ) { std::swap( youngerComponent, olderComponent ); std::swap( uIndex, vIndex ); } auto creation = K[uIndex].data(); auto destruction = simplex.data(); uf.merge( youngerComponent, olderComponent ); cs[olderComponent] += cs[youngerComponent]; cc[olderComponent].insert( cc[olderComponent].end(), cc[youngerComponent].begin(), cc[youngerComponent].end() ); functor( youngerComponent, olderComponent, creation, destruction ); for( auto&& vertex : cc[youngerComponent] ) ap[vertex] += DataType( destruction - creation ); cc.erase(youngerComponent); if( et( creation, destruction ) ) { pd.add( creation , destruction ); ct.add( static_cast<VertexType>( uIndex ), static_cast<VertexType>( K.index( simplex ) ) ); } else cs.erase( youngerComponent ); } // Store information about unpaired simplices ------------------------ // // All components in the Union--Find data structure now correspond to // essential 0-dimensional homology classes of the input complex. std::vector<VertexType> roots; uf.roots( std::back_inserter( roots ) ); for( auto&& root : roots ) { auto creator = *K.find( Simplex( root ) ); pd.add( creator.data() ); ct.add( static_cast<VertexType>( K.index( creator ) ) ); functor( root, creator.data() ); } return std::make_tuple( pd, pp, cs ); } } // namespace aleph #endif <|endoftext|>
<commit_before>#pragma once #include "common/SerializeCustom.hpp" #include "util/RapidjsonHelpers.hpp" #include <QRegularExpression> #include <QString> #include <memory> #include <pajlada/settings/serialize.hpp> namespace chatterino { class HighlightPhrase { QString pattern; bool alert; bool sound; bool _isRegex; QRegularExpression regex; public: bool operator==(const HighlightPhrase &other) const { return std::tie(this->pattern, this->sound, this->alert, this->_isRegex) == std::tie(other.pattern, other.sound, other.alert, other._isRegex); } HighlightPhrase(const QString &_pattern, bool _alert, bool _sound, bool isRegex) : pattern(_pattern) , alert(_alert) , sound(_sound) , _isRegex(isRegex) , regex(_isRegex ? _pattern : "\\b" + QRegularExpression::escape(_pattern) + "\\b", QRegularExpression::CaseInsensitiveOption | QRegularExpression::UseUnicodePropertiesOption) { } const QString &getPattern() const { return this->pattern; } bool getAlert() const { return this->alert; } bool getSound() const { return this->sound; } bool isRegex() const { return this->_isRegex; } bool isValid() const { return !this->pattern.isEmpty() && this->regex.isValid(); } bool isMatch(const QString &subject) const { return this->isValid() && this->regex.match(subject).hasMatch(); } // const QRegularExpression &getRegex() const // { // return this->regex; // } }; } // namespace chatterino namespace pajlada { namespace Settings { template <> struct Serialize<chatterino::HighlightPhrase> { static rapidjson::Value get(const chatterino::HighlightPhrase &value, rapidjson::Document::AllocatorType &a) { rapidjson::Value ret(rapidjson::kObjectType); AddMember(ret, "pattern", value.getPattern(), a); AddMember(ret, "alert", value.getAlert(), a); AddMember(ret, "sound", value.getSound(), a); AddMember(ret, "regex", value.isRegex(), a); return ret; } }; template <> struct Deserialize<chatterino::HighlightPhrase> { static chatterino::HighlightPhrase get(const rapidjson::Value &value) { if (!value.IsObject()) { return chatterino::HighlightPhrase(QString(), true, false, false); } QString _pattern; bool _alert = true; bool _sound = false; bool _isRegex = false; chatterino::rj::getSafe(value, "pattern", _pattern); chatterino::rj::getSafe(value, "alert", _alert); chatterino::rj::getSafe(value, "sound", _sound); chatterino::rj::getSafe(value, "regex", _isRegex); return chatterino::HighlightPhrase(_pattern, _alert, _sound, _isRegex); } }; } // namespace Settings } // namespace pajlada <commit_msg>Remove unused include<commit_after>#pragma once #include "common/SerializeCustom.hpp" #include "util/RapidjsonHelpers.hpp" #include <QRegularExpression> #include <QString> #include <pajlada/settings/serialize.hpp> namespace chatterino { class HighlightPhrase { QString pattern; bool alert; bool sound; bool _isRegex; QRegularExpression regex; public: bool operator==(const HighlightPhrase &other) const { return std::tie(this->pattern, this->sound, this->alert, this->_isRegex) == std::tie(other.pattern, other.sound, other.alert, other._isRegex); } HighlightPhrase(const QString &_pattern, bool _alert, bool _sound, bool isRegex) : pattern(_pattern) , alert(_alert) , sound(_sound) , _isRegex(isRegex) , regex(_isRegex ? _pattern : "\\b" + QRegularExpression::escape(_pattern) + "\\b", QRegularExpression::CaseInsensitiveOption | QRegularExpression::UseUnicodePropertiesOption) { } const QString &getPattern() const { return this->pattern; } bool getAlert() const { return this->alert; } bool getSound() const { return this->sound; } bool isRegex() const { return this->_isRegex; } bool isValid() const { return !this->pattern.isEmpty() && this->regex.isValid(); } bool isMatch(const QString &subject) const { return this->isValid() && this->regex.match(subject).hasMatch(); } // const QRegularExpression &getRegex() const // { // return this->regex; // } }; } // namespace chatterino namespace pajlada { namespace Settings { template <> struct Serialize<chatterino::HighlightPhrase> { static rapidjson::Value get(const chatterino::HighlightPhrase &value, rapidjson::Document::AllocatorType &a) { rapidjson::Value ret(rapidjson::kObjectType); AddMember(ret, "pattern", value.getPattern(), a); AddMember(ret, "alert", value.getAlert(), a); AddMember(ret, "sound", value.getSound(), a); AddMember(ret, "regex", value.isRegex(), a); return ret; } }; template <> struct Deserialize<chatterino::HighlightPhrase> { static chatterino::HighlightPhrase get(const rapidjson::Value &value) { if (!value.IsObject()) { return chatterino::HighlightPhrase(QString(), true, false, false); } QString _pattern; bool _alert = true; bool _sound = false; bool _isRegex = false; chatterino::rj::getSafe(value, "pattern", _pattern); chatterino::rj::getSafe(value, "alert", _alert); chatterino::rj::getSafe(value, "sound", _sound); chatterino::rj::getSafe(value, "regex", _isRegex); return chatterino::HighlightPhrase(_pattern, _alert, _sound, _isRegex); } }; } // namespace Settings } // namespace pajlada <|endoftext|>
<commit_before>#include <stdlib.h> #include <stdio.h> #include <string.h> #include <winscard.h> #include "CSmartCard.h" CSmartCard::CSmartCard() { } CSmartCard::~CSmartCard() { Uninit(); } bool CSmartCard::Init() { bool ret = false; LONG result; LPTSTR pReaders, pReader; // context result = SCardEstablishContext(SCARD_SCOPE_USER, NULL, NULL, &m_hContext); if(result != SCARD_S_SUCCESS) { fprintf(stderr,"error: SCardEstablishContext\n"); goto FINISH; } // get readers m_dwReaders = SCARD_AUTOALLOCATE; result = SCardListReaders(m_hContext, NULL, (LPTSTR)&pReaders, &m_dwReaders); if(result != SCARD_S_SUCCESS) { fprintf(stderr,"error: SCardListReaders\n"); goto FINISH; } pReader = pReaders; while(*pReader != '\0') { std::wstring tmp = (wchar_t*)pReaders; m_pReadersList.push_back(tmp); pReader = pReader + wcslen((wchar_t *)pReader) + 1; } // free the memory result = SCardFreeMemory(m_hContext, pReaders); if(result != SCARD_S_SUCCESS) { fprintf(stderr,"error: SCardFreeMemory\n"); goto FINISH; } ret = true; FINISH: return ret; } void CSmartCard::Uninit() { m_pReadersList.clear(); SCardReleaseContext(m_hContext); } std::vector<std::wstring> CSmartCard::GetReaders() { return m_pReadersList; } bool CSmartCard::Connect(std::wstring szReader) { if(SCardConnect(m_hContext, (LPCTSTR)szReader.c_str(), SCARD_SHARE_SHARED, SCARD_PROTOCOL_T0 | SCARD_PROTOCOL_T1, &m_hCard, &m_dwProtocol) != SCARD_S_SUCCESS) return false; return true; } void CSmartCard::Disconnect() { SCardDisconnect(m_hCard, SCARD_LEAVE_CARD); } // implementation of GP_ITransmitter virtual method for securing APDU request bool CSmartCard::Secure(GPAPI::GP_SecurityInfo* pSecurityInfo, const unsigned char* pInput, const unsigned long cInput, unsigned char* pOutput, unsigned long* cOutput) { fprintf(stderr,"SECURITY LEVEL: %d\r\n", pSecurityInfo->GetSecurityLevel()); fprintf(stderr,"KEY VERSION: %d\r\n", pSecurityInfo->GetKeyVersion()); fprintf(stderr,"KEY IDENTIFIER: %d\r\n", pSecurityInfo->GetKeyIdentifier()); // simulates C-MAC computation (will not work for real application) unsigned char CMAC[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; // add C-MAC *cOutput = cInput+sizeof(CMAC); memcpy(pOutput+cInput, CMAC, sizeof(CMAC)); memcpy(pOutput, pInput, cInput); // modify Lc pOutput[4] = (char)(*cOutput-5); return true; } // implementation of GP_ITransmitter virtual method for exchanging APDU messages bool CSmartCard::Exchange(const unsigned char* pInput, const unsigned long cInput, unsigned char* pOutput, unsigned long* cOutput) { // print request fprintf(stderr, ">> "); for(int i=0; i<(int)cInput; i++) fprintf(stderr,"%.2x ", pInput[i]); fprintf(stderr,"\r\n"); // send request to smart-card and get its response if(SCardTransmit(m_hCard, SCARD_PCI_T1, pInput, cInput, NULL, pOutput, cOutput) != SCARD_S_SUCCESS) return false; // print response fprintf(stderr, "<< "); for(int i=0; i<(int)cOutput; i++) fprintf(stderr,"%.2x ", pOutput[i]); fprintf(stderr,"\r\n"); return true; } <commit_msg>fixed bug of access to size of response data<commit_after>#include <stdlib.h> #include <stdio.h> #include <string.h> #include <winscard.h> #include "CSmartCard.h" CSmartCard::CSmartCard() { } CSmartCard::~CSmartCard() { Uninit(); } bool CSmartCard::Init() { bool ret = false; LONG result; LPTSTR pReaders, pReader; // context result = SCardEstablishContext(SCARD_SCOPE_USER, NULL, NULL, &m_hContext); if(result != SCARD_S_SUCCESS) { fprintf(stderr,"error: SCardEstablishContext\n"); goto FINISH; } // get readers m_dwReaders = SCARD_AUTOALLOCATE; result = SCardListReaders(m_hContext, NULL, (LPTSTR)&pReaders, &m_dwReaders); if(result != SCARD_S_SUCCESS) { fprintf(stderr,"error: SCardListReaders\n"); goto FINISH; } pReader = pReaders; while(*pReader != '\0') { std::wstring tmp = (wchar_t*)pReaders; m_pReadersList.push_back(tmp); pReader = pReader + wcslen((wchar_t *)pReader) + 1; } // free the memory result = SCardFreeMemory(m_hContext, pReaders); if(result != SCARD_S_SUCCESS) { fprintf(stderr,"error: SCardFreeMemory\n"); goto FINISH; } ret = true; FINISH: return ret; } void CSmartCard::Uninit() { m_pReadersList.clear(); SCardReleaseContext(m_hContext); } std::vector<std::wstring> CSmartCard::GetReaders() { return m_pReadersList; } bool CSmartCard::Connect(std::wstring szReader) { if(SCardConnect(m_hContext, (LPCTSTR)szReader.c_str(), SCARD_SHARE_SHARED, SCARD_PROTOCOL_T0 | SCARD_PROTOCOL_T1, &m_hCard, &m_dwProtocol) != SCARD_S_SUCCESS) return false; return true; } void CSmartCard::Disconnect() { SCardDisconnect(m_hCard, SCARD_LEAVE_CARD); } // implementation of GP_ITransmitter virtual method for securing APDU request bool CSmartCard::Secure(GPAPI::GP_SecurityInfo* pSecurityInfo, const unsigned char* pInput, const unsigned long cInput, unsigned char* pOutput, unsigned long* cOutput) { fprintf(stderr,"SECURITY LEVEL: %d\r\n", pSecurityInfo->GetSecurityLevel()); fprintf(stderr,"KEY VERSION: %d\r\n", pSecurityInfo->GetKeyVersion()); fprintf(stderr,"KEY IDENTIFIER: %d\r\n", pSecurityInfo->GetKeyIdentifier()); // simulates C-MAC computation (will not work for real application) unsigned char CMAC[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; // add C-MAC *cOutput = cInput+sizeof(CMAC); memcpy(pOutput+cInput, CMAC, sizeof(CMAC)); memcpy(pOutput, pInput, cInput); // modify Lc pOutput[4] = (char)(*cOutput-5); return true; } // implementation of GP_ITransmitter virtual method for exchanging APDU messages bool CSmartCard::Exchange(const unsigned char* pInput, const unsigned long cInput, unsigned char* pOutput, unsigned long* cOutput) { // print request fprintf(stderr, ">> "); for(int i=0; i<(int)cInput; i++) fprintf(stderr,"%.2x ", pInput[i]); fprintf(stderr,"\r\n"); // send request to smart-card and get its response if(SCardTransmit(m_hCard, SCARD_PCI_T1, pInput, cInput, NULL, pOutput, cOutput) != SCARD_S_SUCCESS) return false; // print response fprintf(stderr, "<< "); for(int i=0; i<(int)*cOutput; i++) fprintf(stderr,"%.2x ", pOutput[i]); fprintf(stderr,"\r\n"); return true; } <|endoftext|>
<commit_before>#include "OpenGLTexture.h" #include "TextureRef.h" #include "Image.h" #define GL_GLEXT_PROTOTYPES #if defined __APPLE__ #include <OpenGLES/ES3/gl.h> #include <OpenGLES/ES3/glext.h> #elsif defined GL_ES #include <GLES3/gl3.h> #include <EGL/egl.h> #include <EGL/eglext.h> #else #define GL_GLEXT_PROTOTYPES #ifdef _WIN32 #include <GL/glew.h> #include <windows.h> #endif #include <GL/gl.h> #ifdef _WIN32 #include "glext.h" #else #include <GL/glext.h> #endif #endif #include <cassert> using namespace std; using namespace canvas; size_t OpenGLTexture::total_textures = 0; vector<unsigned int> OpenGLTexture::freed_textures; static GLenum getOpenGLInternalFormat(InternalFormat internal_format) { switch (internal_format) { case RG8: return GL_RG8; case RGB565: return GL_RGB565; case RGBA4: return GL_RGBA4; case RGBA8: return GL_RGBA8; #ifdef __linux__ case COMPRESSED_RG: return GL_RG8; case COMPRESSED_RGB: return GL_RGB5; case COMPRESSED_RGBA: return GL_RGBA8; #else case COMPRESSED_RG: return GL_COMPRESSED_RG11_EAC; case COMPRESSED_RGB: return GL_COMPRESSED_RGB8_ETC2; case COMPRESSED_RGBA: return GL_COMPRESSED_RGBA8_ETC2_EAC; #endif case LUMINANCE_ALPHA: return GL_RG8; } return 0; } static GLenum getOpenGLFilterType(FilterMode mode) { switch (mode) { case NEAREST: return GL_NEAREST; case LINEAR: return GL_LINEAR; case LINEAR_MIPMAP_LINEAR: return GL_LINEAR_MIPMAP_LINEAR; } return 0; } void OpenGLTexture::updateData(const void * buffer) { updateData(buffer, 0, 0, getActualWidth(), getActualHeight()); } void OpenGLTexture::updateData(const void * buffer, unsigned int x, unsigned int y, unsigned int width, unsigned int height) { assert(buffer); bool initialize = false; if (!texture_id) { initialize = true; glGenTextures(1, &texture_id); if (texture_id >= 1) total_textures++; } assert(texture_id >= 1); glBindTexture(GL_TEXTURE_2D, texture_id); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); bool has_mipmaps = getMinFilter() == LINEAR_MIPMAP_LINEAR; if (initialize) { // glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, getWidth(), getHeight(), 0, GL_RGBA, GL_UNSIGNED_BYTE, 0); glTexStorage2D(GL_TEXTURE_2D, has_mipmaps ? getMipmapLevels() : 1, getOpenGLInternalFormat(getInternalFormat()), getActualWidth(), getActualHeight()); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, getOpenGLFilterType(getMinFilter())); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, getOpenGLFilterType(getMagFilter())); } if (getInternalFormat() == LUMINANCE_ALPHA) { Image tmp_image(width, height, (const unsigned char *)buffer, ImageFormat::RGBA32); auto tmp_image2 = tmp_image.changeFormat(ImageFormat::LUMALPHA8); glTexSubImage2D(GL_TEXTURE_2D, 0, x, y, width, height, GL_RG, GL_UNSIGNED_BYTE, tmp_image2->getData()); } else if (getInternalFormat() == RGB565) { Image tmp_image(width, height, (const unsigned char *)buffer, ImageFormat::RGBA32); auto tmp_image2 = tmp_image.changeFormat(ImageFormat::RGB565); glTexSubImage2D(GL_TEXTURE_2D, 0, x, y, width, height, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, tmp_image2->getData()); } else { #ifdef __APPLE__ glTexSubImage2D(GL_TEXTURE_2D, 0, x, y, width, height, GL_RGBA, GL_UNSIGNED_BYTE, buffer); #else glTexSubImage2D(GL_TEXTURE_2D, 0, x, y, width, height, GL_BGRA_EXT, GL_UNSIGNED_BYTE, buffer); #endif } if (has_mipmaps) { glGenerateMipmap(GL_TEXTURE_2D); } glBindTexture(GL_TEXTURE_2D, 0); } void OpenGLTexture::releaseTextures() { // cerr << "DELETING TEXTURES: " << OpenGLTexture::getFreedTextures().size() << "/" << OpenGLTexture::getNumTextures() << endl; for (vector<unsigned int>::const_iterator it = freed_textures.begin(); it != freed_textures.end(); it++) { GLuint texid = *it; glDeleteTextures(1, &texid); } freed_textures.clear(); } TextureRef OpenGLTexture::createTexture(unsigned int _logical_width, unsigned int _logical_height, unsigned int _actual_width, unsigned int _actual_height, FilterMode min_filter, FilterMode mag_filter, InternalFormat _internal_format, unsigned int mipmap_levels) { return TextureRef(_logical_width, _logical_height, _actual_width, _actual_height, new OpenGLTexture(_logical_width, _logical_height, _actual_width, _actual_height, min_filter, mag_filter, _internal_format, mipmap_levels)); } <commit_msg>test different compressed formats<commit_after>#include "OpenGLTexture.h" #include "TextureRef.h" #include "Image.h" #define GL_GLEXT_PROTOTYPES #if defined __APPLE__ #include <OpenGLES/ES3/gl.h> #include <OpenGLES/ES3/glext.h> #elif (defined GL_ES) #include <GLES3/gl3.h> #include <EGL/egl.h> #include <EGL/eglext.h> #else #define GL_GLEXT_PROTOTYPES #ifdef _WIN32 #include <GL/glew.h> #include <windows.h> #endif #include <GL/gl.h> #ifdef _WIN32 #include "glext.h" #else #include <GL/glext.h> #endif #endif #include <cassert> using namespace std; using namespace canvas; size_t OpenGLTexture::total_textures = 0; vector<unsigned int> OpenGLTexture::freed_textures; static GLenum getOpenGLInternalFormat(InternalFormat internal_format) { switch (internal_format) { case RG8: return GL_RG8; case RGB565: return GL_RGB565; case RGBA4: return GL_RGBA4; case RGBA8: return GL_RGBA8; #ifdef __linux__ case COMPRESSED_RG: return GL_RG8; case COMPRESSED_RGB: return GL_RGB5; case COMPRESSED_RGBA: return GL_RGBA8; #else case COMPRESSED_RG: return GL_COMPRESSED_RG11_EAC; case COMPRESSED_RGB: assert(0); return GL_COMPRESSED_RGB8_ETC2; // return GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG; case COMPRESSED_RGBA: // assert(0); // return GL_COMPRESSED_RGBA8_ETC2_EAC; return GL_COMPRESSED_RGBA_ASTC_4x4_KHR; #endif case LUMINANCE_ALPHA: return GL_RG8; } return 0; } static GLenum getOpenGLFilterType(FilterMode mode) { switch (mode) { case NEAREST: return GL_NEAREST; case LINEAR: return GL_LINEAR; case LINEAR_MIPMAP_LINEAR: return GL_LINEAR_MIPMAP_LINEAR; } return 0; } void OpenGLTexture::updateData(const void * buffer) { updateData(buffer, 0, 0, getActualWidth(), getActualHeight()); } void OpenGLTexture::updateData(const void * buffer, unsigned int x, unsigned int y, unsigned int width, unsigned int height) { assert(buffer); bool initialize = false; if (!texture_id) { initialize = true; glGenTextures(1, &texture_id); if (texture_id >= 1) total_textures++; } assert(texture_id >= 1); glBindTexture(GL_TEXTURE_2D, texture_id); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); bool has_mipmaps = getMinFilter() == LINEAR_MIPMAP_LINEAR; if (initialize) { // glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, getWidth(), getHeight(), 0, GL_RGBA, GL_UNSIGNED_BYTE, 0); glTexStorage2D(GL_TEXTURE_2D, has_mipmaps ? getMipmapLevels() : 1, getOpenGLInternalFormat(getInternalFormat()), getActualWidth(), getActualHeight()); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, getOpenGLFilterType(getMinFilter())); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, getOpenGLFilterType(getMagFilter())); } if (getInternalFormat() == LUMINANCE_ALPHA) { Image tmp_image(width, height, (const unsigned char *)buffer, ImageFormat::RGBA32); auto tmp_image2 = tmp_image.changeFormat(ImageFormat::LUMALPHA8); glTexSubImage2D(GL_TEXTURE_2D, 0, x, y, width, height, GL_RG, GL_UNSIGNED_BYTE, tmp_image2->getData()); } else if (getInternalFormat() == RGB565) { Image tmp_image(width, height, (const unsigned char *)buffer, ImageFormat::RGBA32); auto tmp_image2 = tmp_image.changeFormat(ImageFormat::RGB565); glTexSubImage2D(GL_TEXTURE_2D, 0, x, y, width, height, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, tmp_image2->getData()); } else { #ifdef __APPLE__ glTexSubImage2D(GL_TEXTURE_2D, 0, x, y, width, height, GL_RGBA, GL_UNSIGNED_BYTE, buffer); #else glTexSubImage2D(GL_TEXTURE_2D, 0, x, y, width, height, GL_BGRA_EXT, GL_UNSIGNED_BYTE, buffer); #endif } if (has_mipmaps) { glGenerateMipmap(GL_TEXTURE_2D); } glBindTexture(GL_TEXTURE_2D, 0); } void OpenGLTexture::releaseTextures() { // cerr << "DELETING TEXTURES: " << OpenGLTexture::getFreedTextures().size() << "/" << OpenGLTexture::getNumTextures() << endl; for (vector<unsigned int>::const_iterator it = freed_textures.begin(); it != freed_textures.end(); it++) { GLuint texid = *it; glDeleteTextures(1, &texid); } freed_textures.clear(); } TextureRef OpenGLTexture::createTexture(unsigned int _logical_width, unsigned int _logical_height, unsigned int _actual_width, unsigned int _actual_height, FilterMode min_filter, FilterMode mag_filter, InternalFormat _internal_format, unsigned int mipmap_levels) { return TextureRef(_logical_width, _logical_height, _actual_width, _actual_height, new OpenGLTexture(_logical_width, _logical_height, _actual_width, _actual_height, min_filter, mag_filter, _internal_format, mipmap_levels)); } <|endoftext|>
<commit_before>/* * OstringStream.cpp * * Copyright 2000, LifeLine Networks BV (www.lifeline.nl). All rights reserved. * Copyright 2000, Bastiaan Bakker. All rights reserved. * * See the COPYING file for the terms of usage and distribution. */ #include "log4cpp/Portability.hh" #include <stdio.h> #include "log4cpp/OstringStream.hh" #if defined(_MSC_VER) #define VSNPRINTF _vsnprintf #else #ifdef LOG4CPP_HAVE_SNPRINTF #define VSNPRINTF vsnprintf #else /* use alternative snprintf() from http://www.ijs.si/software/snprintf/ */ #define HAVE_SNPRINTF #define PREFER_PORTABLE_SNPRINTF #include "snprintf.c" #define VSNPRINTF portable_snprintf #endif // LOG4CPP_HAVE_SNPRINTF #endif // _MSC_VER namespace { std::string vstrprintf(const char* format, va_list args) { int size = 1024; char* buffer = new char[size]; while (1) { int n = VSNPRINTF(buffer, size, format, args); // If that worked, return a string. if (n > -1 && n < size) { std::string s(buffer); delete [] buffer; return s; } // Else try again with more space. if (n > -1) size = n+1; // ISO/IEC 9899:1999 else size *= 2; // twice the old size delete [] buffer; buffer = new char[size]; } } } namespace log4cpp { #ifndef LOG4CPP_HAVE_SSTREAM std::string OstringStream::str() { (*this) << '\0'; std::string msg(ostrstream::str()); ostrstream::freeze(false); //unfreeze stream return msg; } #endif void OstringStream::vform(const char* format, va_list args) { *this << vstrprintf(format, args); } } <commit_msg>Added some #includes for portable snprintf().<commit_after>/* * OstringStream.cpp * * Copyright 2000, LifeLine Networks BV (www.lifeline.nl). All rights reserved. * Copyright 2000, Bastiaan Bakker. All rights reserved. * * See the COPYING file for the terms of usage and distribution. */ #include "log4cpp/Portability.hh" #include <stdio.h> #include "log4cpp/OstringStream.hh" #if defined(_MSC_VER) #define VSNPRINTF _vsnprintf #else #ifdef LOG4CPP_HAVE_SNPRINTF #define VSNPRINTF vsnprintf #else /* use alternative snprintf() from http://www.ijs.si/software/snprintf/ */ #define HAVE_SNPRINTF #define PREFER_PORTABLE_SNPRINTF #include <stdlib.h> #include <stdarg.h> #include "snprintf.c" #define VSNPRINTF portable_snprintf #endif // LOG4CPP_HAVE_SNPRINTF #endif // _MSC_VER namespace { std::string vstrprintf(const char* format, va_list args) { int size = 1024; char* buffer = new char[size]; while (1) { int n = VSNPRINTF(buffer, size, format, args); // If that worked, return a string. if (n > -1 && n < size) { std::string s(buffer); delete [] buffer; return s; } // Else try again with more space. if (n > -1) size = n+1; // ISO/IEC 9899:1999 else size *= 2; // twice the old size delete [] buffer; buffer = new char[size]; } } } namespace log4cpp { #ifndef LOG4CPP_HAVE_SSTREAM std::string OstringStream::str() { (*this) << '\0'; std::string msg(ostrstream::str()); ostrstream::freeze(false); //unfreeze stream return msg; } #endif void OstringStream::vform(const char* format, va_list args) { *this << vstrprintf(format, args); } } <|endoftext|>
<commit_before>#include <iostream> #include <vector> void carr_func(int * vec) { std::cout << "carr_func - vec: " << vec << std::endl; } int main(void) { std::vector<int> v1 = {-1, 3, 5, -8, 0}; std::vector<int> v2; auto v3(v1); //initialize v3 via copy /** * Managing std::vector capacity */ //Unlike std::array, std::vector has a more sensible empty() function //v2 is currently empty std::cout << "v1.empty(): " << v1.empty() << std::endl; std::cout << "v2.empty(): " << v2.empty() << std::endl; // size() tells you the number of elements std::cout << "v1.size(): " << v1.size() << std::endl; std::cout << "v2.size(): " << v2.size() << std::endl; // max_size() is huuuuuuuuuge for my host machine std::cout << "v1.max_size(): " << v1.max_size() << std::endl; std::cout << "v2.max_size(): " << v2.max_size() << std::endl; // Capacity tells you how many elements can be stored in the currently allocated memory std::cout << "v1.capacity(): " << v1.capacity() << std::endl; std::cout << "v2.capacity(): " << v2.capacity() << std::endl; v2.reserve(10); std::cout << "v2.capacity() after reserve(10): " << v2.capacity() << std::endl; std::cout << "v2.size(): " << v2.size() << std::endl; //If you have reserved space greater than your current needs, you can shrink the buffer v2.shrink_to_fit(); std::cout << "v2.capacity() after shrink_to_fit(): " << v2.capacity() << std::endl; /** * Accessing std::vector elements */ std::cout << "v1.front(): " << v1.front() << std::endl; std::cout << "v1.back(): " << v1.back() << std::endl; std::cout << "v1[0]: " << v1[0] << std::endl; std::cout << "v1.at(4): " << v1.at(4) << std::endl; // Bounds checking will generate exceptions. Try: //auto b = v2.at(10); //However, operator [] is not bounds checked! //This may or may not seg fault //std::cout << "v2[6]: " << v2[6] << std::endl; /* * If you need to interface with legacy code or libraries requiring * a C-style array interface, you can get to the underlying array data ptr */ //Error: //carr_func(v1); //OK: carr_func(v1.data()); /** * Playing around with vectors */ v2 = v1; //copy std::cout << "v2.size() after copy: " << v2.size() << std::endl; v2.clear(); std::cout << "v2.size() after clear: " << v2.size() << std::endl; std::cout << "v2.capacity(): " << v2.capacity() << std::endl; v2.insert(v2.begin(), -1); //insert an element - you need an iterator v2.emplace(v2.end(), int(1000)); //construct and place an element at the iterator v2.push_back(0); //adds element to end v2.emplace_back(int(10)); //constructs an element in place at the end std::cout << std::endl << "v2: " << std::endl; for (const auto & t : v2) { std::cout << t << " "; } std::cout << std::endl; v2.resize(7); //resize to 7. The new elements will be 0-initialized v2.resize(10, -1); //resize to 10. New elements initialized with -1 v2.pop_back(); //removes last element std::cout << std::endl << "v2 resized: " << std::endl; for (const auto & t : v2) { std::cout << t << " "; } std::cout << std::endl; v2.resize(4); //shrink and strip off extra elements //Container operations work std::sort(v2.begin(), v2.end()); std::cout << std::endl << "v2 shrunk & sorted: " << std::endl; for (const auto & t : v2) { std::cout << t << " "; } std::cout << std::endl; return 0; } <commit_msg>Add erase to vector example<commit_after>#include <iostream> #include <vector> void carr_func(int * vec) { std::cout << "carr_func - vec: " << vec << std::endl; } int main(void) { std::vector<int> v1 = {-1, 3, 5, -8, 0}; //initialize with list std::vector<int> v2; //don't initialize auto v3(v1); //initialize v3 via copy /** * Managing std::vector capacity */ //Unlike std::array, std::vector has a more sensible empty() function //v2 is currently empty std::cout << "v1.empty(): " << v1.empty() << std::endl; std::cout << "v2.empty(): " << v2.empty() << std::endl; // size() tells you the number of elements std::cout << "v1.size(): " << v1.size() << std::endl; std::cout << "v2.size(): " << v2.size() << std::endl; // max_size() is huuuuuuuuuge for my host machine std::cout << "v1.max_size(): " << v1.max_size() << std::endl; std::cout << "v2.max_size(): " << v2.max_size() << std::endl; // Capacity tells you how many elements can be stored in the currently allocated memory std::cout << "v1.capacity(): " << v1.capacity() << std::endl; std::cout << "v2.capacity(): " << v2.capacity() << std::endl; v2.reserve(10); std::cout << "v2.capacity() after reserve(10): " << v2.capacity() << std::endl; std::cout << "v2.size(): " << v2.size() << std::endl; //If you have reserved space greater than your current needs, you can shrink the buffer v2.shrink_to_fit(); std::cout << "v2.capacity() after shrink_to_fit(): " << v2.capacity() << std::endl; /** * Accessing std::vector elements */ std::cout << "v1.front(): " << v1.front() << std::endl; std::cout << "v1.back(): " << v1.back() << std::endl; std::cout << "v1[0]: " << v1[0] << std::endl; std::cout << "v1.at(4): " << v1.at(4) << std::endl; // Bounds checking will generate exceptions. Try: //auto b = v2.at(10); //However, operator [] is not bounds checked! //This may or may not seg fault //std::cout << "v2[6]: " << v2[6] << std::endl; /* * If you need to interface with legacy code or libraries requiring * a C-style array interface, you can get to the underlying array data ptr */ //Error: //carr_func(v1); //OK: carr_func(v1.data()); /** * Playing around with vectors */ v2 = v1; //copy std::cout << "v2.size() after copy: " << v2.size() << std::endl; v2.clear(); std::cout << "v2.size() after clear: " << v2.size() << std::endl; std::cout << "v2.capacity(): " << v2.capacity() << std::endl; v2.insert(v2.begin(), -1); //insert an element - you need an iterator v2.emplace(v2.end(), int(1000)); //construct and place an element at the iterator v2.push_back(0); //adds element to end v2.emplace_back(int(10)); //constructs an element in place at the end std::cout << std::endl << "v2: " << std::endl; for (const auto & t : v2) { std::cout << t << " "; } std::cout << std::endl; v2.resize(7); //resize to 7. The new elements will be 0-initialized v2.resize(10, -1); //resize to 10. New elements initialized with -1 v2.pop_back(); //removes last element v2.erase(v2.begin()); //removes first element std::cout << std::endl << "v2 resized: " << std::endl; for (const auto & t : v2) { std::cout << t << " "; } std::cout << std::endl; v2.resize(4); //shrink and strip off extra elements //Container operations work std::sort(v2.begin(), v2.end()); std::cout << std::endl << "v2 shrunk & sorted: " << std::endl; for (const auto & t : v2) { std::cout << t << " "; } std::cout << std::endl; return 0; } <|endoftext|>
<commit_before>/** @file config.hpp @brief Configuration. @author Tim Howard @copyright 2013 Tim Howard under the MIT license; see @ref index or the accompanying LICENSE file for full text. */ #ifndef HORD_CONFIG_HPP_ #define HORD_CONFIG_HPP_ #include <cstddef> #include <cstdint> /** @addtogroup config @{ */ /** Allocator for auxiliary specializations. */ #define HORD_AUX_ALLOCATOR std::allocator /** @cond INTERNAL */ #define DUCT_CONFIG_ALLOCATOR HORD_AUX_ALLOCATOR #define MURK_AUX_ALLOCATOR HORD_AUX_ALLOCATOR #define HORD_STRINGIFY_INNER__(x) #x /** @endcond */ /** Stringify an identifier. */ #define HORD_STRINGIFY(x) \ HORD_STRINGIFY_INNER__(x) /** @name Error reporting These macros are for error reporting. A class implementation file should @code #define HORD_SCOPE_CLASS_IDENT__ ClassName @endcode and @code #undef HORD_SCOPE_CLASS_IDENT__ @endcode around its implementation space. Throwing functions should likewise define and undefine @c HORD_SCOPE_FUNC_IDENT__ within the body. All of these macros require these definitions. @note <Hord/String.hpp> and <Hord/Error.hpp> are required to use these. @note All throw macros except for #HORD_THROW_ERROR_S encapsulate the final message in #HORD_STR_LIT (that is, @a m__ needn't be #HORD_STR_LIT-ized). @remarks I quite despise this method, but there is no @c __fqn__. Luckily, a nice a side-effect of this method is that it cuts down on both implementation complexity and dynamic allocation -- both good in my book, even if the cost is paid in 2 gnarly preprocessing directives per throwing function. @{ */ #ifdef DOXYGEN_CONSISTS_SOLELY_OF_UNICORNS_AND_CONFETTI /** Current class identifier. This is defined surrounding class implementations. */ #define HORD_SCOPE_CLASS_IDENT__ /** Current function identifier. This is defined surrounding function implementations. */ #define HORD_SCOPE_FUNC_IDENT__ #endif /** Returns the string literal of @c HORD_SCOPE_CLASS_IDENT__. */ #define HORD_SCOPE_CLASS \ HORD_STRINGIFY(HORD_SCOPE_CLASS_IDENT__) /** Returns the string literal of @c HORD_SCOPE_FUNC_IDENT__. */ #define HORD_SCOPE_FUNC \ HORD_STRINGIFY(HORD_SCOPE_FUNC_IDENT__) /** Returns the fully-qualified name of the current function. */ #define HORD_SCOPE_FQN \ HORD_SCOPE_CLASS "::" HORD_SCOPE_FUNC /** @cond INTERNAL */ #define HORD_MSG_SCOPED_IMPL__(s__, m__) \ HORD_STR_LIT(s__ ": " m__) /** @endcond */ /** Build message string literal with class scope. @param m__ Message. */ #define HORD_MSG_SCOPED_CLASS(m__) \ HORD_MSG_SCOPED_IMPL__(HORD_SCOPE_CLASS, m__) /** Build message string literal with function scope. @param m__ Message. */ #define HORD_MSG_SCOPED_FUNC(m__) \ HORD_MSG_SCOPED_IMPL__(HORD_SCOPE_FUNC, m__) /** Build message string literal with fully-qualified scope. @param m__ Message. */ #define HORD_MSG_SCOPED_FQN(m__) \ HORD_MSG_SCOPED_IMPL__(HORD_SCOPE_FQN, m__) /** @cond INTERNAL */ #define HORD_THROW_ERROR_IMPL__(e__, m__) \ throw std::move(::Hord::Error{ \ e__, \ ::Hord::String{m__} \ }) /** @endcond */ /** Throw error with message. @param e__ ErrorCode. @param m__ Message (string literal). */ #define HORD_THROW_ERROR(e__, m__) \ HORD_THROW_ERROR_IMPL__(e__, HORD_STR_LIT(m__)) /** Throw error with message. @param e__ ErrorCode. @param m__ Message (String). */ #define HORD_THROW_ERROR_S(e__, m__) \ HORD_THROW_ERROR_IMPL__(e__, m__) /** Throw error with class scope. @param e__ ErrorCode. @param m__ Message (string literal). @sa HORD_THROW_ERROR_SCOPED_FUNC, HORD_THROW_ERROR_SCOPED_FQN */ #define HORD_THROW_ERROR_SCOPED_CLASS(e__, m__) \ HORD_THROW_ERROR_IMPL__( \ e__, \ HORD_MSG_SCOPED_CLASS(m__) \ ) /** Throw error with function scope. @param e__ ErrorCode. @param m__ Message (string literal). @sa HORD_THROW_ERROR_SCOPED_CLASS, HORD_THROW_ERROR_SCOPED_FQN */ #define HORD_THROW_ERROR_SCOPED_FUNC(e__, m__) \ HORD_THROW_ERROR_IMPL__( \ e__, \ HORD_MSG_SCOPED_FUNC(m__) \ ) /** Throw error with fully-qualified scope. @param e__ ErrorCode. @param m__ Message (string literal). @sa HORD_THROW_ERROR_SCOPED_CLASS, HORD_THROW_ERROR_SCOPED_FUNC */ #define HORD_THROW_ERROR_SCOPED_FQN(e__, m__) \ HORD_THROW_ERROR_IMPL__( \ e__, \ HORD_MSG_SCOPED_FQN(m__) \ ) /** @} */ // end of name-group Error reporting namespace Hord { } // namespace Hord /** @} */ // end of doc-group config #endif // HORD_CONFIG_HPP_ <commit_msg>config: added HORD_FMT_SCOPED_* and HORD_THROW_ERROR_F macros.<commit_after>/** @file config.hpp @brief Configuration. @author Tim Howard @copyright 2013 Tim Howard under the MIT license; see @ref index or the accompanying LICENSE file for full text. */ #ifndef HORD_CONFIG_HPP_ #define HORD_CONFIG_HPP_ #include <cstddef> #include <cstdint> /** @addtogroup config @{ */ /** Allocator for auxiliary specializations. */ #define HORD_AUX_ALLOCATOR std::allocator /** @cond INTERNAL */ #define DUCT_CONFIG_ALLOCATOR HORD_AUX_ALLOCATOR #define MURK_AUX_ALLOCATOR HORD_AUX_ALLOCATOR #define HORD_STRINGIFY_INNER__(x) #x /** @endcond */ /** Stringify an identifier. */ #define HORD_STRINGIFY(x) \ HORD_STRINGIFY_INNER__(x) /** @name Error reporting These macros are for error reporting. A class implementation file should @code #define HORD_SCOPE_CLASS_IDENT__ ClassName @endcode and @code #undef HORD_SCOPE_CLASS_IDENT__ @endcode around its implementation space. Throwing functions should likewise define and undefine @c HORD_SCOPE_FUNC_IDENT__ within the body. All of these macros require these definitions. @note <Hord/String.hpp> and <Hord/Error.hpp> are required to use these. @note <ceformat/Format.hpp> is required for the @c HORD_FMT_SCOPED_* macros, and <ceformat/print.hpp> is required for #HORD_THROW_ERROR_F. @note All throw macros except for #HORD_THROW_ERROR_S encapsulate the final message in #HORD_STR_LIT (that is, @a m__ needn't be #HORD_STR_LIT-ized). @remarks I quite despise this method, but there is no @c __fqn__. Luckily, a nice a side-effect of this method is that it cuts down on both implementation complexity and dynamic allocation -- both good in my book, even if the cost is paid in 2 gnarly preprocessing directives per throwing function. @{ */ #ifdef DOXYGEN_CONSISTS_SOLELY_OF_UNICORNS_AND_CONFETTI /** Current class identifier. This is defined surrounding class implementations. */ #define HORD_SCOPE_CLASS_IDENT__ /** Current function identifier. This is defined surrounding function implementations. */ #define HORD_SCOPE_FUNC_IDENT__ #endif /** Returns the string literal of #HORD_SCOPE_CLASS_IDENT__. */ #define HORD_SCOPE_CLASS \ HORD_STRINGIFY(HORD_SCOPE_CLASS_IDENT__) /** Returns the string literal of #HORD_SCOPE_FUNC_IDENT__. */ #define HORD_SCOPE_FUNC \ HORD_STRINGIFY(HORD_SCOPE_FUNC_IDENT__) /** Returns the fully-qualified name of the current function. */ #define HORD_SCOPE_FQN \ HORD_SCOPE_CLASS "::" HORD_SCOPE_FUNC /** @cond INTERNAL */ #define HORD_MSG_SCOPED_IMPL__(s__, m__) \ HORD_STR_LIT(s__ ": " m__) #define HORD_FMT_SCOPED_IMPL__(ident__, f__) \ static constexpr ceformat::Format const \ ident__{f__} /** @endcond */ // class scope /** Build message string literal with class scope. @param m__ Message. */ #define HORD_MSG_SCOPED_CLASS(m__) \ HORD_MSG_SCOPED_IMPL__(HORD_SCOPE_CLASS, m__) /** Define format message with class scope. @param ident__ Identifier for format message. @param f__ Format message. */ #define HORD_FMT_SCOPED_CLASS(ident__, f__) \ HORD_FMT_SCOPED_IMPL__(ident__, HORD_MSG_SCOPED_CLASS(f__)) // function scope /** Build message string literal with function scope. @param m__ Message. */ #define HORD_MSG_SCOPED_FUNC(m__) \ HORD_MSG_SCOPED_IMPL__(HORD_SCOPE_FUNC, m__) /** Define format message with function scope. @param ident__ Identifier for format message. @param f__ Format message. */ #define HORD_FMT_SCOPED_FUNC(ident__, f__) \ HORD_FMT_SCOPED_IMPL__(ident__, HORD_MSG_SCOPED_FUNC(f__)) // fully-qualified scope /** Build message string literal with fully-qualified scope. @param m__ Message. */ #define HORD_MSG_SCOPED_FQN(m__) \ HORD_MSG_SCOPED_IMPL__(HORD_SCOPE_FQN, m__) /** Define format message with fully-qualified scope. @param ident__ Identifier for format message. @param f__ Format message. */ #define HORD_FMT_SCOPED_FQN(ident__, f__) \ HORD_FMT_SCOPED_IMPL__(ident__, HORD_MSG_SCOPED_FQN(f__)) /** @cond INTERNAL */ #define HORD_THROW_ERROR_IMPL__(e__, m__) \ throw std::move(::Hord::Error{ \ e__, \ ::Hord::String{m__} \ }) /** @endcond */ /** Throw error with message. @param e__ ErrorCode. @param m__ Message (string literal). */ #define HORD_THROW_ERROR(e__, m__) \ HORD_THROW_ERROR_IMPL__(e__, HORD_STR_LIT(m__)) /** Throw error with message. @param e__ ErrorCode. @param m__ Message (String). */ #define HORD_THROW_ERROR_S(e__, m__) \ HORD_THROW_ERROR_IMPL__(e__, m__) /** Throw error with format message. @param e__ ErrorCode. @param f__ @c ceformat::Format message. @param ... Arguments. */ #define HORD_THROW_ERROR_F(e__, f__, ...) \ HORD_THROW_ERROR_IMPL__( \ e__, \ ceformat::print<f__>(__VA_ARGS__) \ ) /** Throw error with class scope. @param e__ ErrorCode. @param m__ Message (string literal). @sa HORD_THROW_ERROR_SCOPED_FUNC, HORD_THROW_ERROR_SCOPED_FQN */ #define HORD_THROW_ERROR_SCOPED_CLASS(e__, m__) \ HORD_THROW_ERROR_IMPL__( \ e__, \ HORD_MSG_SCOPED_CLASS(m__) \ ) /** Throw error with function scope. @param e__ ErrorCode. @param m__ Message (string literal). @sa HORD_THROW_ERROR_SCOPED_CLASS, HORD_THROW_ERROR_SCOPED_FQN */ #define HORD_THROW_ERROR_SCOPED_FUNC(e__, m__) \ HORD_THROW_ERROR_IMPL__( \ e__, \ HORD_MSG_SCOPED_FUNC(m__) \ ) /** Throw error with fully-qualified scope. @param e__ ErrorCode. @param m__ Message (string literal). @sa HORD_THROW_ERROR_SCOPED_CLASS, HORD_THROW_ERROR_SCOPED_FUNC */ #define HORD_THROW_ERROR_SCOPED_FQN(e__, m__) \ HORD_THROW_ERROR_IMPL__( \ e__, \ HORD_MSG_SCOPED_FQN(m__) \ ) /** @} */ // end of name-group Error reporting namespace Hord { } // namespace Hord /** @} */ // end of doc-group config #endif // HORD_CONFIG_HPP_ <|endoftext|>
<commit_before>/*========================================================================= Program: Medical Imaging & Interaction Toolkit Language: C++ Date: $Date$ Version: $Revision: 7837 $ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "mitkImageWriter.h" #include "mitkDataTreeNodeFactory.h" #include "mitkTestingMacros.h" #include <iostream> /** * Simple example for a test for the (non-existent) class "ImageWriter". * * argc and argv are the command line parameters which were passed to * the ADD_TEST command in the CMakeLists.txt file. For the automatic * tests, argv is either empty for the simple tests or contains the filename * of a test image for the image tests (see CMakeLists.txt). */ int mitkImageWriterTest(int argc , char* argv[]) { // always start with this! MITK_TEST_BEGIN("ImageWriter") // let's create an object of our class mitk::ImageWriter::Pointer myImageWriter = mitk::ImageWriter::New(); // first test: did this work? // using MITK_TEST_CONDITION_REQUIRED makes the test stop after failure, since // it makes no sense to continue without an object. MITK_TEST_CONDITION_REQUIRED(myImageWriter.IsNotNull(),"Testing instantiation") // write your own tests here and use the macros from mitkTestingMacros.h !!! // do not write to std::cout and do not return from this function yourself! // load image std::cout << "Loading file: " << std::flush; if(argc==0) { std::cout<<"no file specified [FAILED]"<<std::endl; return EXIT_FAILURE; } mitk::Image::Pointer image = NULL; mitk::DataTreeNodeFactory::Pointer factory = mitk::DataTreeNodeFactory::New(); try { std::cout<<argv[1]<<std::endl; factory->SetFileName( argv[1] ); factory->Update(); if(factory->GetNumberOfOutputs()<1) { std::cout<<"file could not be loaded [FAILED]"<<std::endl; return EXIT_FAILURE; } mitk::DataTreeNode::Pointer node = factory->GetOutput( 0 ); image = dynamic_cast<mitk::Image*>(node->GetData()); if(image.IsNull()) { std::cout<<"file "<< argv[1]<< "is not an image - test will not be applied [PASSED]"<<std::endl; std::cout<<"[TEST DONE]"<<std::endl; return EXIT_SUCCESS; } } catch ( itk::ExceptionObject & ex ) { std::cout << "Exception: " << ex << "[FAILED]" << std::endl; return EXIT_FAILURE; } MITK_TEST_CONDITION_REQUIRED(image.IsNotNull(),"loaded image not NULL") try{ // test for exception handling MITK_TEST_FOR_EXCEPTION_BEGIN(itk::ExceptionObject) myImageWriter->SetInput(image); myImageWriter->SetFileName("/usr/bin"); myImageWriter->Update(); MITK_TEST_FOR_EXCEPTION_END(itk::ExceptionObject) } catch(...) { //this means that a wrong exception (i.e. no itk:Exception) has been thrown std::cout << "Wrong exception (i.e. no itk:Exception) caught during write [FAILED]" << std::endl; return EXIT_FAILURE; } // always end with this! MITK_TEST_END() } <commit_msg>FIX (#3149): use testing macros consistently<commit_after>/*========================================================================= Program: Medical Imaging & Interaction Toolkit Language: C++ Date: $Date$ Version: $Revision: 7837 $ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "mitkImageWriter.h" #include "mitkDataTreeNodeFactory.h" #include "mitkTestingMacros.h" #include <iostream> /** * test for "ImageWriter". * * argc and argv are the command line parameters which were passed to * the ADD_TEST command in the CMakeLists.txt file. For the automatic * tests, argv is either empty for the simple tests or contains the filename * of a test image for the image tests (see CMakeLists.txt). */ int mitkImageWriterTest(int argc , char* argv[]) { // always start with this! MITK_TEST_BEGIN("ImageWriter") // let's create an object of our class mitk::ImageWriter::Pointer myImageWriter = mitk::ImageWriter::New(); // first test: did this work? // using MITK_TEST_CONDITION_REQUIRED makes the test stop after failure, since // it makes no sense to continue without an object. MITK_TEST_CONDITION_REQUIRED(myImageWriter.IsNotNull(),"Testing instantiation") // write your own tests here and use the macros from mitkTestingMacros.h !!! // do not write to std::cout and do not return from this function yourself! // load image MITK_TEST_CONDITION_REQUIRED(argc != 0, "File to load has been specified"); mitk::Image::Pointer image = NULL; mitk::DataTreeNodeFactory::Pointer factory = mitk::DataTreeNodeFactory::New(); try { MITK_TEST_OUTPUT(<< "Loading file: " << argv[1]); factory->SetFileName( argv[1] ); factory->Update(); MITK_TEST_CONDITION_REQUIRED(factory->GetNumberOfOutputs() > 0, "file loaded"); mitk::DataTreeNode::Pointer node = factory->GetOutput( 0 ); image = dynamic_cast<mitk::Image*>(node->GetData()); if(image.IsNull()) { std::cout<<"file "<< argv[1]<< "is not an image - test will not be applied."<<std::endl; std::cout<<"[TEST DONE]"<<std::endl; return EXIT_SUCCESS; } } catch (itk::ExceptionObject & ex) { MITK_TEST_FAILED_MSG(<< "Exception during file loading: " << ex.GetDescription()); } MITK_TEST_CONDITION_REQUIRED(image.IsNotNull(),"loaded image not NULL") // test for exception handling try { MITK_TEST_FOR_EXCEPTION_BEGIN(itk::ExceptionObject) myImageWriter->SetInput(image); myImageWriter->SetFileName("/usr/bin"); myImageWriter->Update(); MITK_TEST_FOR_EXCEPTION_END(itk::ExceptionObject) } catch(...) { //this means that a wrong exception (i.e. no itk:Exception) has been thrown MITK_TEST_FAILED_MSG(<< "Wrong exception (i.e. no itk:Exception) caught during write"); } // always end with this! MITK_TEST_END(); } <|endoftext|>
<commit_before>/*========================================================================= Program: Medical Imaging & Interaction Toolkit Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "mitkImageVtkMapper2D.h" //#include "mitkMapper.h" //#include "mitkDataNode.h" //#include "mitkBaseRenderer.h" //#include "mitkProperties.h" #include <vtkImageQuantizeRGBToIndex.h> #include <vtkImageToPolyDataFilter.h> #include <vtkTriangleFilter.h> #include <vtkImageDataGeometryFilter.h> #include <vtkImageCanvasSource2D.h> #include <vtkImageShiftScale.h> #include <vtkImageCast.h> #include <vtkImageReslice.h> #include <vtkLinearTransform.h> #include <vtkMatrix4x4.h> #include <vtkProperty2D.h> #include <vtkImageBlend.h> #include <vtkImage.h> #include <vtkImageProperty.h> #include <vtkOpenGLImageResliceMapper.h> #include <mitkVtkPropRenderer.h> mitk::ImageVtkMapper2D::ImageVtkMapper2D() { this->m_VtkBased = true; this->m_TimeStep = 0; this->m_VtkActor = vtkSmartPointer<vtkImage>::New(); this->m_VtkImage = vtkSmartPointer<vtkImageData>::New(); this->m_VtkMapper = vtkSmartPointer<vtkOpenGLImageResliceMapper>::New(); } mitk::ImageVtkMapper2D::~ImageVtkMapper2D() { } const mitk::Image* mitk::ImageVtkMapper2D::GetInput() { return static_cast<const mitk::Image* > ( GetData() ); } void mitk::ImageVtkMapper2D::GenerateData(mitk::BaseRenderer* renderer) { MITK_INFO << "Generate Data called"; if ( !this->IsVisible(renderer) ) { itkWarningMacro( << "Renderer not visible!" ); return; } mitk::Image::Pointer input = const_cast<mitk::Image*>( this->GetInput() ); if ( input.IsNull() ) return ; vtkSmartPointer<vtkImageData> image = input->GetVtkImageData(); // image->SetScalarTypeToUnsignedChar(); // vtkSmartPointer<vtkImageShiftScale> imageShiftSacle = vtkImageShiftScale::New(); // imageShiftSacle->SetOutputScalarTypeToUnsignedChar(); // imageShiftSacle->ClampOverflowOn(); // imageShiftSacle->SetInput(image); // vtkSmartPointer<vtkImageCast> imageCast = vtkSmartPointer<vtkImageCast>::New(); // imageCast->SetOutputScalarTypeToUnsignedChar(); // imageCast->ClampOverflowOn(); // imageCast->SetInput(image); // m_VtkImage->SetScalarTypeToUnsignedChar(); // m_VtkImage = imageCast->GetOutput(); m_VtkImage = image; // float opacity = 1.0f; // GetOpacity(opacity, renderer); // MITK_INFO << opacity; //// m_VtkActor->GetProperty()->SetOpacity(opacity); //// MITK_INFO << m_VtkActor->GetProperty()->GetOpacity(); // vtkSmartPointer<vtkImageBlend> blend = // vtkSmartPointer<vtkImageBlend>::New(); //// blend->AddInputConnection(image->GetOutputPort()); // blend->AddInputConnection(image->GetProducerPort()); // blend->SetOpacity(0,opacity); // m_VtkImage = blend->GetOutput(0); if( m_VtkImage ) { // mitk::LevelWindow levelWindow; // GetLevelWindow(levelWindow, renderer); // double range = // const mitk::VtkPropRenderer* glRenderer = dynamic_cast<const mitk::VtkPropRenderer*>(renderer); // if (glRenderer == NULL) // return; // vtkRenderer* vtkRenderer = glRenderer->GetVtkRenderer(); // vtkSmartPointer<vtkImageProperty> ip = vtkSmartPointer<vtkImageProperty>::New(); // ip->SetColorLevel(1000); // ip->SetColorWindow(2000); // ip->SetInterpolationTypeToLinear(); // vtkSmartPointer<vtkRenderWindowInteractor> renderWindowInteractor = vtkSmartPointer<vtkRenderWindowInteractor>::New(); // renderWindowInteractor->SetInteractorStyle(imageStyle); // renderWindowInteractor->SetRenderWindow(renderWindow); // m_VtkMapper->SetInputConnection(iExtended2Dmage->GetProducerPort()); m_VtkMapper->SetInput(m_VtkImage); // m_VtkMapper->SetInputConnection(blend->GetOutputPort()); // m_VtkMapper->SetColorLevel(levelWindow.GetLowerWindowBound()); // m_VtkMapper->SetColorWindow(levelWindow.GetUpperWindowBound()); m_VtkActor->SetMapper(m_VtkMapper); // m_VtkActor->SetProperty(ip); // m_VtkActor->SetVisibility(1); } else { itkWarningMacro( << "m_VtkImage is NULL!" ); return ; } } void mitk::ImageVtkMapper2D::MitkRenderOverlay(BaseRenderer* renderer) { if ( this->IsVisible(renderer)==false ) return; if ( this->GetVtkProp(renderer)->GetVisibility() ) { this->GetVtkProp(renderer)->RenderOverlay(renderer->GetVtkRenderer()); } } void mitk::ImageVtkMapper2D::MitkRenderOpaqueGeometry(BaseRenderer* renderer) { if ( this->IsVisible( renderer )==false ) return; if ( this->GetVtkProp(renderer)->GetVisibility() ) { this->GetVtkProp(renderer)->RenderOpaqueGeometry( renderer->GetVtkRenderer() ); } } void mitk::ImageVtkMapper2D::MitkRenderTranslucentGeometry(BaseRenderer* renderer) { if ( this->IsVisible(renderer)==false ) return; if ( this->GetVtkProp(renderer)->GetVisibility() ) //BUG (#1551) changed VTK_MINOR_VERSION FROM 3 to 2 cause RenderTranslucentGeometry was changed in minor version 2 #if ( ( VTK_MAJOR_VERSION >= 5 ) && ( VTK_MINOR_VERSION>=2) ) this->GetVtkProp(renderer)->RenderTranslucentPolygonalGeometry(renderer->GetVtkRenderer()); #else this->GetVtkProp(renderer)->RenderTranslucentGeometry(renderer->GetVtkRenderer()); #endif } void mitk::ImageVtkMapper2D::MitkRenderVolumetricGeometry(BaseRenderer* renderer) { if(IsVisible(renderer)==false) return; if ( GetVtkProp(renderer)->GetVisibility() ) GetVtkProp(renderer)->RenderVolumetricGeometry(renderer->GetVtkRenderer()); } vtkProp* mitk::ImageVtkMapper2D::GetVtkProp(mitk::BaseRenderer* renderer) { // m_VtkActor->GetProperty()->SetColor(0,1,0); return m_VtkActor; } vtkImageData *mitk::ImageVtkMapper2D::GenerateTestImageForTSFilter() { // a 2x2x2 image unsigned char myData[] = { 234,234, 123,565, // -213,800, // 1000,-20 }; vtkImageData *i = vtkImageData::New(); i->SetExtent(0,1,0,1,0,0); i->SetScalarTypeToUnsignedChar(); i->AllocateScalars(); unsigned char *p = (unsigned char*)i->GetScalarPointer(); memcpy(p,myData,2*2*1*sizeof(unsigned char)); return i; } <commit_msg>added 0,0 to GetVtkImageData<commit_after>/*========================================================================= Program: Medical Imaging & Interaction Toolkit Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "mitkImageVtkMapper2D.h" //#include "mitkMapper.h" //#include "mitkDataNode.h" //#include "mitkBaseRenderer.h" //#include "mitkProperties.h" #include <vtkImageQuantizeRGBToIndex.h> #include <vtkImageToPolyDataFilter.h> #include <vtkTriangleFilter.h> #include <vtkImageDataGeometryFilter.h> #include <vtkImageCanvasSource2D.h> #include <vtkImageShiftScale.h> #include <vtkImageCast.h> #include <vtkImageReslice.h> #include <vtkLinearTransform.h> #include <vtkMatrix4x4.h> #include <vtkProperty2D.h> #include <vtkImageBlend.h> #include <vtkImage.h> #include <vtkImageProperty.h> #include <vtkOpenGLImageResliceMapper.h> #include <mitkVtkPropRenderer.h> mitk::ImageVtkMapper2D::ImageVtkMapper2D() { this->m_VtkBased = true; this->m_TimeStep = 0; this->m_VtkActor = vtkSmartPointer<vtkImage>::New(); this->m_VtkImage = vtkSmartPointer<vtkImageData>::New(); this->m_VtkMapper = vtkSmartPointer<vtkOpenGLImageResliceMapper>::New(); } mitk::ImageVtkMapper2D::~ImageVtkMapper2D() { } const mitk::Image* mitk::ImageVtkMapper2D::GetInput() { return static_cast<const mitk::Image* > ( GetData() ); } void mitk::ImageVtkMapper2D::GenerateData(mitk::BaseRenderer* renderer) { MITK_INFO << "Generate Data called"; if ( !this->IsVisible(renderer) ) { itkWarningMacro( << "Renderer not visible!" ); return; } mitk::Image::Pointer input = const_cast<mitk::Image*>( this->GetInput() ); if ( input.IsNull() ) return ; vtkSmartPointer<vtkImageData> image = input->GetVtkImageData(0,0); // image->SetScalarTypeToUnsignedChar(); // vtkSmartPointer<vtkImageShiftScale> imageShiftSacle = vtkImageShiftScale::New(); // imageShiftSacle->SetOutputScalarTypeToUnsignedChar(); // imageShiftSacle->ClampOverflowOn(); // imageShiftSacle->SetInput(image); // vtkSmartPointer<vtkImageCast> imageCast = vtkSmartPointer<vtkImageCast>::New(); // imageCast->SetOutputScalarTypeToUnsignedChar(); // imageCast->ClampOverflowOn(); // imageCast->SetInput(image); // m_VtkImage->SetScalarTypeToUnsignedChar(); // m_VtkImage = imageCast->GetOutput(); m_VtkImage = image; // float opacity = 1.0f; // GetOpacity(opacity, renderer); // MITK_INFO << opacity; //// m_VtkActor->GetProperty()->SetOpacity(opacity); //// MITK_INFO << m_VtkActor->GetProperty()->GetOpacity(); // vtkSmartPointer<vtkImageBlend> blend = // vtkSmartPointer<vtkImageBlend>::New(); //// blend->AddInputConnection(image->GetOutputPort()); // blend->AddInputConnection(image->GetProducerPort()); // blend->SetOpacity(0,opacity); // m_VtkImage = blend->GetOutput(0); if( m_VtkImage ) { // mitk::LevelWindow levelWindow; // GetLevelWindow(levelWindow, renderer); // double range = // const mitk::VtkPropRenderer* glRenderer = dynamic_cast<const mitk::VtkPropRenderer*>(renderer); // if (glRenderer == NULL) // return; // vtkRenderer* vtkRenderer = glRenderer->GetVtkRenderer(); // vtkSmartPointer<vtkImageProperty> ip = vtkSmartPointer<vtkImageProperty>::New(); // ip->SetColorLevel(1000); // ip->SetColorWindow(2000); // ip->SetInterpolationTypeToLinear(); // vtkSmartPointer<vtkRenderWindowInteractor> renderWindowInteractor = vtkSmartPointer<vtkRenderWindowInteractor>::New(); // renderWindowInteractor->SetInteractorStyle(imageStyle); // renderWindowInteractor->SetRenderWindow(renderWindow); // m_VtkMapper->SetInputConnection(iExtended2Dmage->GetProducerPort()); m_VtkMapper->SetInput(m_VtkImage); // m_VtkMapper->SetInputConnection(blend->GetOutputPort()); // m_VtkMapper->SetColorLevel(levelWindow.GetLowerWindowBound()); // m_VtkMapper->SetColorWindow(levelWindow.GetUpperWindowBound()); m_VtkActor->SetMapper(m_VtkMapper); // m_VtkActor->SetProperty(ip); // m_VtkActor->SetVisibility(1); } else { itkWarningMacro( << "m_VtkImage is NULL!" ); return ; } } void mitk::ImageVtkMapper2D::MitkRenderOverlay(BaseRenderer* renderer) { if ( this->IsVisible(renderer)==false ) return; if ( this->GetVtkProp(renderer)->GetVisibility() ) { this->GetVtkProp(renderer)->RenderOverlay(renderer->GetVtkRenderer()); } } void mitk::ImageVtkMapper2D::MitkRenderOpaqueGeometry(BaseRenderer* renderer) { if ( this->IsVisible( renderer )==false ) return; if ( this->GetVtkProp(renderer)->GetVisibility() ) { this->GetVtkProp(renderer)->RenderOpaqueGeometry( renderer->GetVtkRenderer() ); } } void mitk::ImageVtkMapper2D::MitkRenderTranslucentGeometry(BaseRenderer* renderer) { if ( this->IsVisible(renderer)==false ) return; if ( this->GetVtkProp(renderer)->GetVisibility() ) //BUG (#1551) changed VTK_MINOR_VERSION FROM 3 to 2 cause RenderTranslucentGeometry was changed in minor version 2 #if ( ( VTK_MAJOR_VERSION >= 5 ) && ( VTK_MINOR_VERSION>=2) ) this->GetVtkProp(renderer)->RenderTranslucentPolygonalGeometry(renderer->GetVtkRenderer()); #else this->GetVtkProp(renderer)->RenderTranslucentGeometry(renderer->GetVtkRenderer()); #endif } void mitk::ImageVtkMapper2D::MitkRenderVolumetricGeometry(BaseRenderer* renderer) { if(IsVisible(renderer)==false) return; if ( GetVtkProp(renderer)->GetVisibility() ) GetVtkProp(renderer)->RenderVolumetricGeometry(renderer->GetVtkRenderer()); } vtkProp* mitk::ImageVtkMapper2D::GetVtkProp(mitk::BaseRenderer* renderer) { // m_VtkActor->GetProperty()->SetColor(0,1,0); return m_VtkActor; } vtkImageData *mitk::ImageVtkMapper2D::GenerateTestImageForTSFilter() { // a 2x2x2 image unsigned char myData[] = { 234,234, 123,565, // -213,800, // 1000,-20 }; vtkImageData *i = vtkImageData::New(); i->SetExtent(0,1,0,1,0,0); i->SetScalarTypeToUnsignedChar(); i->AllocateScalars(); unsigned char *p = (unsigned char*)i->GetScalarPointer(); memcpy(p,myData,2*2*1*sizeof(unsigned char)); return i; } <|endoftext|>
<commit_before>/*========================================================================= Program: Medical Imaging & Interaction Toolkit Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "mitkPointSet.h" #include "mitkPointSetWriter.h" #include "mitkPointSetReader.h" #include "mitkTestingMacros.h" #include <itksys/SystemTools.hxx> //unsigned int numberOfTestPointSets = 1; unsigned int numberOfTimeSeries = 5; // create one test PointSet class mitkPointSetFileIOTestClass { public: static mitk::PointSet::Pointer CreateTestPointSet(unsigned int which) { mitk::PointSet::Pointer pointSet = mitk::PointSet::New(); for(unsigned int t= 0; t<numberOfTimeSeries; t++) { unsigned int position(0); mitk::Point3D point; mitk::FillVector3D(point, 1.0+t+which, 2.0+t+which, 3.0+t+which); pointSet->SetPoint(position, point, t); mitk::FillVector3D(point, 2.0+t+which, 3.0+t+which, 4.0+t+which); ++position; pointSet->SetPoint(position, point, t); mitk::FillVector3D(point, 3.0+t+which, 4.0+t+which, 5.0+t+which); ++position; pointSet->SetPoint(position, point, t); } return pointSet; } static void PointSetCompare(mitk::PointSet::Pointer pointSet2, mitk::PointSet::Pointer pointSet1, bool& identical) { MITK_TEST_CONDITION(pointSet1->GetSize() == pointSet2->GetSize(), "Testing if PointSet size is correct" ); for (unsigned int t=0; t<numberOfTimeSeries; t++) { for (unsigned int i = 0; i < (unsigned int)pointSet1->GetSize(t); ++i) { mitk::Point3D p1 = pointSet1->GetPoint(i); mitk::Point3D p2 = pointSet2->GetPoint(i); double difference = ( (p1[0] - p2[0]) + (p1[1] - p2[1]) + (p1[2] - p2[2]) ); MITK_TEST_CONDITION(difference <= 0.0001, "Testing if Points are at the same Position" ); } } } static bool PointSetWrite(unsigned int numberOfPointSets) { try { mitk::PointSetWriter::Pointer pointSetWriter = mitk::PointSetWriter::New(); pointSetWriter->SetFileName("test_pointset_new.mps"); for(unsigned int i=0; i<numberOfPointSets; i++) { pointSetWriter->SetInput(i, CreateTestPointSet(i)); } pointSetWriter->Write(); } catch ( std::exception& e ) { return false; } return true; } static void PointSetLoadAndCompareTest(unsigned int numberOfPointSets) { try { mitk::PointSetReader::Pointer pointSetReader = mitk::PointSetReader::New(); mitk::PointSet::Pointer pointSet; pointSetReader->SetFileName("test_pointset_new.mps"); for(unsigned int i=0; i<numberOfPointSets; i++) { pointSetReader->Update(); pointSet = pointSetReader->GetOutput(i); MITK_TEST_CONDITION(pointSet.IsNotNull(), "Testing if the loaded Data are NULL" ); bool identical(true); PointSetCompare(pointSet.GetPointer(), CreateTestPointSet(i).GetPointer(), identical); } } catch ( std::exception& e ) { } } }; //mitkPointSetFileIOTestClass int mitkPointSetFileIOTest(int, char*[]) { MITK_TEST_BEGIN("PointSet"); unsigned int numberOfPointSets(1); // write MITK_TEST_CONDITION(mitkPointSetFileIOTestClass::PointSetWrite(numberOfPointSets), "Testing if the PointSetWriter writes Data" ); // load - compare mitkPointSetFileIOTestClass::PointSetLoadAndCompareTest(numberOfPointSets); MITK_TEST_END(); } <commit_msg>ENH (#1571): extended the test for reading and writing floating point number.<commit_after>/*========================================================================= Program: Medical Imaging & Interaction Toolkit Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "mitkPointSet.h" #include "mitkPointSetWriter.h" #include "mitkPointSetReader.h" #include "mitkTestingMacros.h" #include <vector> #include <itksys/SystemTools.hxx> #include <time.h> //unsigned int numberOfTestPointSets = 1; unsigned int numberOfTimeSeries = 5; // create one test PointSet class mitkPointSetFileIOTestClass { public: std::vector<mitk::PointSet::Pointer> m_SavedPointSet; mitkPointSetFileIOTestClass() { } mitk::PointSet::Pointer CreateTestPointSet() { mitk::PointSet::Pointer pointSet = mitk::PointSet::New(); for (unsigned int t = 0; t < numberOfTimeSeries; t++) { unsigned int position(0); mitk::Point3D point; mitk::FillVector3D(point, (rand()%1000) /1000.0 , (rand()%1000) /1000.0, (rand()%1000)/1000.0); pointSet->SetPoint(position, point, t); mitk::FillVector3D(point, (rand()%1000) /1000.0 , (rand()%1000) /1000.0, (rand()%1000)/1000.0); ++position; pointSet->SetPoint(position, point, t); mitk::FillVector3D(point, (rand()%1000) /1000.0 , (rand()%1000) /1000.0, (rand()%1000)/1000.0); ++position; pointSet->SetPoint(position, point, t); } m_SavedPointSet.push_back(pointSet); return pointSet; } void PointSetCompare(mitk::PointSet::Pointer pointSet2, mitk::PointSet::Pointer pointSet1, bool& identical) { MITK_TEST_CONDITION(pointSet1->GetSize() == pointSet2->GetSize(), "Testing if PointSet size is correct" ); for (unsigned int t = 0; t < numberOfTimeSeries; t++) { for (unsigned int i = 0; i < (unsigned int) pointSet1->GetSize(t); ++i) { mitk::Point3D p1 = pointSet1->GetPoint(i); mitk::Point3D p2 = pointSet2->GetPoint(i); //test std::cout << "r point: " << p2 << std::endl; std::cout << "w point: " << p1 << std::endl; //test end MITK_TEST_CONDITION((p1[0] - p2[0]) <= 0.0001, "Testing if X coordinates of the Point are at the same Position" ); MITK_TEST_CONDITION((p1[1] - p2[1]) <= 0.0001, "Testing if Y coordinates of the Point are at the same Position" ); MITK_TEST_CONDITION((p1[2] - p2[2]) <= 0.0001, "Testing if Z coordinates of the Point are at the same Position" ); } } } bool PointSetWrite(unsigned int numberOfPointSets) { try { m_SavedPointSet.clear(); mitk::PointSetWriter::Pointer pointSetWriter = mitk::PointSetWriter::New(); pointSetWriter->SetFileName("/home/wangxi/test_pointset_new.mps"); for (unsigned int i = 0; i < numberOfPointSets; i++) { pointSetWriter->SetInput(i, CreateTestPointSet()); } pointSetWriter->Write(); } catch (std::exception& e) { return false; } return true; } void PointSetLoadAndCompareTest(unsigned int numberOfPointSets) { try { mitk::PointSetReader::Pointer pointSetReader = mitk::PointSetReader::New(); mitk::PointSet::Pointer pointSet; pointSetReader->SetFileName("/home/wangxi/test_pointset_new.mps"); for (unsigned int i = 0; i < numberOfPointSets; i++) { pointSetReader->Update(); pointSet = pointSetReader->GetOutput(i); MITK_TEST_CONDITION(pointSet.IsNotNull(), "Testing if the loaded Data are NULL" ); bool identical(true); PointSetCompare(pointSet.GetPointer(), m_SavedPointSet.at(i).GetPointer(), identical); } } catch (std::exception& e) { } } }; //mitkPointSetFileIOTestClass int mitkPointSetFileIOTest(int, char*[]) { MITK_TEST_BEGIN("PointSet"); unsigned int numberOfPointSets(100); mitkPointSetFileIOTestClass* test = new mitkPointSetFileIOTestClass(); // write MITK_TEST_CONDITION(test->PointSetWrite(numberOfPointSets), "Testing if the PointSetWriter writes Data" ); // load - compare test->PointSetLoadAndCompareTest(numberOfPointSets); MITK_TEST_END(); } <|endoftext|>
<commit_before><commit_msg>adding chisquare output<commit_after><|endoftext|>
<commit_before><commit_msg>Doubles up on register mirroring. Will do for now. More to come.<commit_after><|endoftext|>
<commit_before><commit_msg>修改提示框字符高度计算<commit_after><|endoftext|>
<commit_before>//===-- AArch64TargetMachine.cpp - Define TargetMachine for AArch64 -------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // //===----------------------------------------------------------------------===// #include "AArch64.h" #include "AArch64TargetMachine.h" #include "llvm/PassManager.h" #include "llvm/CodeGen/Passes.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/TargetRegistry.h" #include "llvm/Target/TargetOptions.h" #include "llvm/Transforms/Scalar.h" using namespace llvm; static cl::opt<bool> EnableCCMP("aarch64-ccmp", cl::desc("Enable the CCMP formation pass"), cl::init(true), cl::Hidden); static cl::opt<bool> EnableStPairSuppress("aarch64-stp-suppress", cl::desc("Suppress STP for AArch64"), cl::init(true), cl::Hidden); static cl::opt<bool> EnableAdvSIMDScalar("aarch64-simd-scalar", cl::desc("Enable use of AdvSIMD scalar" " integer instructions"), cl::init(false), cl::Hidden); static cl::opt<bool> EnablePromoteConstant("aarch64-promote-const", cl::desc("Enable the promote " "constant pass"), cl::init(true), cl::Hidden); static cl::opt<bool> EnableCollectLOH("aarch64-collect-loh", cl::desc("Enable the pass that emits the" " linker optimization hints (LOH)"), cl::init(true), cl::Hidden); static cl::opt<bool> EnableDeadRegisterElimination("aarch64-dead-def-elimination", cl::Hidden, cl::desc("Enable the pass that removes dead" " definitons and replaces stores to" " them with stores to the zero" " register"), cl::init(true)); static cl::opt<bool> EnableLoadStoreOpt("aarch64-load-store-opt", cl::desc("Enable the load/store pair" " optimization pass"), cl::init(true), cl::Hidden); static cl::opt<bool> EnableAtomicTidy("aarch64-atomic-cfg-tidy", cl::Hidden, cl::desc("Run SimplifyCFG after expanding atomic operations" " to make use of cmpxchg flow-based information"), cl::init(true)); extern "C" void LLVMInitializeAArch64Target() { // Register the target. RegisterTargetMachine<AArch64leTargetMachine> X(TheAArch64leTarget); RegisterTargetMachine<AArch64beTargetMachine> Y(TheAArch64beTarget); RegisterTargetMachine<AArch64leTargetMachine> Z(TheARM64leTarget); RegisterTargetMachine<AArch64beTargetMachine> W(TheARM64beTarget); } /// TargetMachine ctor - Create an AArch64 architecture model. /// AArch64TargetMachine::AArch64TargetMachine(const Target &T, StringRef TT, StringRef CPU, StringRef FS, const TargetOptions &Options, Reloc::Model RM, CodeModel::Model CM, CodeGenOpt::Level OL, bool LittleEndian) : LLVMTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL), Subtarget(TT, CPU, FS, *this, LittleEndian) { initAsmInfo(); } void AArch64leTargetMachine::anchor() { } AArch64leTargetMachine:: AArch64leTargetMachine(const Target &T, StringRef TT, StringRef CPU, StringRef FS, const TargetOptions &Options, Reloc::Model RM, CodeModel::Model CM, CodeGenOpt::Level OL) : AArch64TargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, true) {} void AArch64beTargetMachine::anchor() { } AArch64beTargetMachine:: AArch64beTargetMachine(const Target &T, StringRef TT, StringRef CPU, StringRef FS, const TargetOptions &Options, Reloc::Model RM, CodeModel::Model CM, CodeGenOpt::Level OL) : AArch64TargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, false) {} namespace { /// AArch64 Code Generator Pass Configuration Options. class AArch64PassConfig : public TargetPassConfig { public: AArch64PassConfig(AArch64TargetMachine *TM, PassManagerBase &PM) : TargetPassConfig(TM, PM) {} AArch64TargetMachine &getAArch64TargetMachine() const { return getTM<AArch64TargetMachine>(); } void addIRPasses() override; bool addPreISel() override; bool addInstSelector() override; bool addILPOpts() override; bool addPreRegAlloc() override; bool addPostRegAlloc() override; bool addPreSched2() override; bool addPreEmitPass() override; }; } // namespace void AArch64TargetMachine::addAnalysisPasses(PassManagerBase &PM) { // Add first the target-independent BasicTTI pass, then our AArch64 pass. This // allows the AArch64 pass to delegate to the target independent layer when // appropriate. PM.add(createBasicTargetTransformInfoPass(this)); PM.add(createAArch64TargetTransformInfoPass(this)); } TargetPassConfig *AArch64TargetMachine::createPassConfig(PassManagerBase &PM) { return new AArch64PassConfig(this, PM); } void AArch64PassConfig::addIRPasses() { // Always expand atomic operations, we don't deal with atomicrmw or cmpxchg // ourselves. addPass(createAtomicExpandLoadLinkedPass(TM)); // Cmpxchg instructions are often used with a subsequent comparison to // determine whether it succeeded. We can exploit existing control-flow in // ldrex/strex loops to simplify this, but it needs tidying up. if (TM->getOptLevel() != CodeGenOpt::None && EnableAtomicTidy) addPass(createCFGSimplificationPass()); TargetPassConfig::addIRPasses(); } // Pass Pipeline Configuration bool AArch64PassConfig::addPreISel() { // Run promote constant before global merge, so that the promoted constants // get a chance to be merged if (TM->getOptLevel() != CodeGenOpt::None && EnablePromoteConstant) addPass(createAArch64PromoteConstantPass()); if (TM->getOptLevel() != CodeGenOpt::None) addPass(createGlobalMergePass(TM)); if (TM->getOptLevel() != CodeGenOpt::None) addPass(createAArch64AddressTypePromotionPass()); return false; } bool AArch64PassConfig::addInstSelector() { addPass(createAArch64ISelDag(getAArch64TargetMachine(), getOptLevel())); // For ELF, cleanup any local-dynamic TLS accesses (i.e. combine as many // references to _TLS_MODULE_BASE_ as possible. if (TM->getSubtarget<AArch64Subtarget>().isTargetELF() && getOptLevel() != CodeGenOpt::None) addPass(createAArch64CleanupLocalDynamicTLSPass()); return false; } bool AArch64PassConfig::addILPOpts() { if (EnableCCMP) addPass(createAArch64ConditionalCompares()); addPass(&EarlyIfConverterID); if (EnableStPairSuppress) addPass(createAArch64StorePairSuppressPass()); return true; } bool AArch64PassConfig::addPreRegAlloc() { // Use AdvSIMD scalar instructions whenever profitable. if (TM->getOptLevel() != CodeGenOpt::None && EnableAdvSIMDScalar) addPass(createAArch64AdvSIMDScalar()); return true; } bool AArch64PassConfig::addPostRegAlloc() { // Change dead register definitions to refer to the zero register. if (TM->getOptLevel() != CodeGenOpt::None && EnableDeadRegisterElimination) addPass(createAArch64DeadRegisterDefinitions()); return true; } bool AArch64PassConfig::addPreSched2() { // Expand some pseudo instructions to allow proper scheduling. addPass(createAArch64ExpandPseudoPass()); // Use load/store pair instructions when possible. if (TM->getOptLevel() != CodeGenOpt::None && EnableLoadStoreOpt) addPass(createAArch64LoadStoreOptimizationPass()); return true; } bool AArch64PassConfig::addPreEmitPass() { // Relax conditional branch instructions if they're otherwise out of // range of their destination. addPass(createAArch64BranchRelaxation()); if (TM->getOptLevel() != CodeGenOpt::None && EnableCollectLOH && TM->getSubtarget<AArch64Subtarget>().isTargetMachO()) addPass(createAArch64CollectLOHPass()); return true; } <commit_msg>AArch64: Temporarily disable AArch64AddressTypePromotion<commit_after>//===-- AArch64TargetMachine.cpp - Define TargetMachine for AArch64 -------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // //===----------------------------------------------------------------------===// #include "AArch64.h" #include "AArch64TargetMachine.h" #include "llvm/PassManager.h" #include "llvm/CodeGen/Passes.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/TargetRegistry.h" #include "llvm/Target/TargetOptions.h" #include "llvm/Transforms/Scalar.h" using namespace llvm; static cl::opt<bool> EnableCCMP("aarch64-ccmp", cl::desc("Enable the CCMP formation pass"), cl::init(true), cl::Hidden); static cl::opt<bool> EnableStPairSuppress("aarch64-stp-suppress", cl::desc("Suppress STP for AArch64"), cl::init(true), cl::Hidden); static cl::opt<bool> EnableAdvSIMDScalar("aarch64-simd-scalar", cl::desc("Enable use of AdvSIMD scalar" " integer instructions"), cl::init(false), cl::Hidden); static cl::opt<bool> EnablePromoteConstant("aarch64-promote-const", cl::desc("Enable the promote " "constant pass"), cl::init(true), cl::Hidden); static cl::opt<bool> EnableCollectLOH("aarch64-collect-loh", cl::desc("Enable the pass that emits the" " linker optimization hints (LOH)"), cl::init(true), cl::Hidden); static cl::opt<bool> EnableDeadRegisterElimination("aarch64-dead-def-elimination", cl::Hidden, cl::desc("Enable the pass that removes dead" " definitons and replaces stores to" " them with stores to the zero" " register"), cl::init(true)); static cl::opt<bool> EnableLoadStoreOpt("aarch64-load-store-opt", cl::desc("Enable the load/store pair" " optimization pass"), cl::init(true), cl::Hidden); static cl::opt<bool> EnableAtomicTidy("aarch64-atomic-cfg-tidy", cl::Hidden, cl::desc("Run SimplifyCFG after expanding atomic operations" " to make use of cmpxchg flow-based information"), cl::init(true)); extern "C" void LLVMInitializeAArch64Target() { // Register the target. RegisterTargetMachine<AArch64leTargetMachine> X(TheAArch64leTarget); RegisterTargetMachine<AArch64beTargetMachine> Y(TheAArch64beTarget); RegisterTargetMachine<AArch64leTargetMachine> Z(TheARM64leTarget); RegisterTargetMachine<AArch64beTargetMachine> W(TheARM64beTarget); } /// TargetMachine ctor - Create an AArch64 architecture model. /// AArch64TargetMachine::AArch64TargetMachine(const Target &T, StringRef TT, StringRef CPU, StringRef FS, const TargetOptions &Options, Reloc::Model RM, CodeModel::Model CM, CodeGenOpt::Level OL, bool LittleEndian) : LLVMTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL), Subtarget(TT, CPU, FS, *this, LittleEndian) { initAsmInfo(); } void AArch64leTargetMachine::anchor() { } AArch64leTargetMachine:: AArch64leTargetMachine(const Target &T, StringRef TT, StringRef CPU, StringRef FS, const TargetOptions &Options, Reloc::Model RM, CodeModel::Model CM, CodeGenOpt::Level OL) : AArch64TargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, true) {} void AArch64beTargetMachine::anchor() { } AArch64beTargetMachine:: AArch64beTargetMachine(const Target &T, StringRef TT, StringRef CPU, StringRef FS, const TargetOptions &Options, Reloc::Model RM, CodeModel::Model CM, CodeGenOpt::Level OL) : AArch64TargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, false) {} namespace { /// AArch64 Code Generator Pass Configuration Options. class AArch64PassConfig : public TargetPassConfig { public: AArch64PassConfig(AArch64TargetMachine *TM, PassManagerBase &PM) : TargetPassConfig(TM, PM) {} AArch64TargetMachine &getAArch64TargetMachine() const { return getTM<AArch64TargetMachine>(); } void addIRPasses() override; bool addPreISel() override; bool addInstSelector() override; bool addILPOpts() override; bool addPreRegAlloc() override; bool addPostRegAlloc() override; bool addPreSched2() override; bool addPreEmitPass() override; }; } // namespace void AArch64TargetMachine::addAnalysisPasses(PassManagerBase &PM) { // Add first the target-independent BasicTTI pass, then our AArch64 pass. This // allows the AArch64 pass to delegate to the target independent layer when // appropriate. PM.add(createBasicTargetTransformInfoPass(this)); PM.add(createAArch64TargetTransformInfoPass(this)); } TargetPassConfig *AArch64TargetMachine::createPassConfig(PassManagerBase &PM) { return new AArch64PassConfig(this, PM); } void AArch64PassConfig::addIRPasses() { // Always expand atomic operations, we don't deal with atomicrmw or cmpxchg // ourselves. addPass(createAtomicExpandLoadLinkedPass(TM)); // Cmpxchg instructions are often used with a subsequent comparison to // determine whether it succeeded. We can exploit existing control-flow in // ldrex/strex loops to simplify this, but it needs tidying up. if (TM->getOptLevel() != CodeGenOpt::None && EnableAtomicTidy) addPass(createCFGSimplificationPass()); TargetPassConfig::addIRPasses(); } // Pass Pipeline Configuration bool AArch64PassConfig::addPreISel() { // Run promote constant before global merge, so that the promoted constants // get a chance to be merged if (TM->getOptLevel() != CodeGenOpt::None && EnablePromoteConstant) addPass(createAArch64PromoteConstantPass()); if (TM->getOptLevel() != CodeGenOpt::None) addPass(createGlobalMergePass(TM)); return false; } bool AArch64PassConfig::addInstSelector() { addPass(createAArch64ISelDag(getAArch64TargetMachine(), getOptLevel())); // For ELF, cleanup any local-dynamic TLS accesses (i.e. combine as many // references to _TLS_MODULE_BASE_ as possible. if (TM->getSubtarget<AArch64Subtarget>().isTargetELF() && getOptLevel() != CodeGenOpt::None) addPass(createAArch64CleanupLocalDynamicTLSPass()); return false; } bool AArch64PassConfig::addILPOpts() { if (EnableCCMP) addPass(createAArch64ConditionalCompares()); addPass(&EarlyIfConverterID); if (EnableStPairSuppress) addPass(createAArch64StorePairSuppressPass()); return true; } bool AArch64PassConfig::addPreRegAlloc() { // Use AdvSIMD scalar instructions whenever profitable. if (TM->getOptLevel() != CodeGenOpt::None && EnableAdvSIMDScalar) addPass(createAArch64AdvSIMDScalar()); return true; } bool AArch64PassConfig::addPostRegAlloc() { // Change dead register definitions to refer to the zero register. if (TM->getOptLevel() != CodeGenOpt::None && EnableDeadRegisterElimination) addPass(createAArch64DeadRegisterDefinitions()); return true; } bool AArch64PassConfig::addPreSched2() { // Expand some pseudo instructions to allow proper scheduling. addPass(createAArch64ExpandPseudoPass()); // Use load/store pair instructions when possible. if (TM->getOptLevel() != CodeGenOpt::None && EnableLoadStoreOpt) addPass(createAArch64LoadStoreOptimizationPass()); return true; } bool AArch64PassConfig::addPreEmitPass() { // Relax conditional branch instructions if they're otherwise out of // range of their destination. addPass(createAArch64BranchRelaxation()); if (TM->getOptLevel() != CodeGenOpt::None && EnableCollectLOH && TM->getSubtarget<AArch64Subtarget>().isTargetMachO()) addPass(createAArch64CollectLOHPass()); return true; } <|endoftext|>
<commit_before>/* * Copyright (c) 2012-2021 Fredrik Mellbin * * This file is part of VapourSynth. * * VapourSynth 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. * * VapourSynth 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 VapourSynth; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "vscore.h" #include <cassert> #include <bitset> #ifdef VS_TARGET_CPU_X86 #include "x86utils.h" #endif #if defined(HAVE_SCHED_GETAFFINITY) #include <sched.h> #elif defined(HAVE_CPUSET_GETAFFINITY) #include <sys/param.h> #include <sys/_cpuset.h> #include <sys/cpuset.h> #endif size_t VSThreadPool::getNumAvailableThreads() { size_t nthreads = std::thread::hardware_concurrency(); #ifdef _WIN32 DWORD_PTR pAff = 0; DWORD_PTR sAff = 0; BOOL res = GetProcessAffinityMask(GetCurrentProcess(), &pAff, &sAff); if (res && pAff != 0) { std::bitset<sizeof(sAff) * 8> b(pAff); nthreads = b.count(); } #elif defined(HAVE_SCHED_GETAFFINITY) // Linux only. cpu_set_t affinity; if (sched_getaffinity(0, sizeof(cpu_set_t), &affinity) == 0) nthreads = CPU_COUNT(&affinity); #elif defined(HAVE_CPUSET_GETAFFINITY) // BSD only (FreeBSD only?) cpuset_t affinity; if (cpuset_getaffinity(CPU_LEVEL_WHICH, CPU_WHICH_PID, -1, sizeof(cpuset_t), &affinity) == 0) nthreads = CPU_COUNT(&affinity); #endif return nthreads; } bool VSThreadPool::taskCmp(const PVSFrameContext &a, const PVSFrameContext &b) { return (a->reqOrder < b->reqOrder) || (a->reqOrder == b->reqOrder && a->key.second < b->key.second); } void VSThreadPool::runTasksWrapper(VSThreadPool *owner, std::atomic<bool> &stop) { owner->runTasks(stop); } void VSThreadPool::runTasks(std::atomic<bool> &stop) { #ifdef VS_TARGET_OS_WINDOWS if (!vs_isSSEStateOk()) core->logFatal("Bad SSE state detected after creating new thread"); #endif std::unique_lock<std::mutex> lock(taskLock); while (true) { bool ranTask = false; ///////////////////////////////////////////////////////////////////////////////////////////// // Go through all tasks from the top (oldest) and process the first one possible std::set<VSNode *> seenNodes; for (auto iter = tasks.begin(); iter != tasks.end(); ++iter) { VSFrameContext *frameContext = iter->get(); VSNode *node = frameContext->key.first; ///////////////////////////////////////////////////////////////////////////////////////////// // Fast path if a frame is cached if (node->cacheEnabled) { PVSFrame f = node->getCachedFrameInternal(frameContext->key.second); if (f) { bool needsSort = false; for (size_t i = 0; i < frameContext->notifyCtxList.size(); i++) { PVSFrameContext &notify = frameContext->notifyCtxList[i]; notify->availableFrames.push_back({frameContext->key, f}); assert(notify->numFrameRequests > 0); if (--notify->numFrameRequests == 0) { queueTask(notify); needsSort = true; } } PVSFrameContext mainContextRef = std::move(*iter); if (frameContext->external) returnFrame(frameContext, f); allContexts.erase(frameContext->key); tasks.erase(iter); if (needsSort) tasks.sort(taskCmp); ranTask = true; break; } } ///////////////////////////////////////////////////////////////////////////////////////////// // This part handles the locking for the different filter modes int filterMode = node->filterMode; // Don't try to lock the same node twice since it's likely to fail and will produce more out of order requests as well if (filterMode != fmFrameState && !seenNodes.insert(node).second) continue; // Does the filter need the per instance mutex? fmFrameState, fmUnordered and fmParallelRequests (when in the arAllFramesReady state) use this bool useSerialLock = (filterMode == fmFrameState || filterMode == fmUnordered || (filterMode == fmParallelRequests && !frameContext->first)); if (useSerialLock) { if (!node->serialMutex.try_lock()) continue; if (filterMode == fmFrameState) { if (node->serialFrame == -1) { node->serialFrame = frameContext->key.second; // another frame already in progress? } else if (node->serialFrame != frameContext->key.second) { node->serialMutex.unlock(); continue; } } } ///////////////////////////////////////////////////////////////////////////////////////////// // Remove the context from the task list and keep references around until processing is done PVSFrameContext frameContextRef = std::move(*iter); tasks.erase(iter); ///////////////////////////////////////////////////////////////////////////////////////////// // Figure out the activation reason assert(frameContext->numFrameRequests == 0); int ar = arInitial; if (frameContext->hasError()) { ar = arError; } else if (!frameContext->first) { ar = (node->apiMajor == 3) ? static_cast<int>(vs3::arAllFramesReady) : static_cast<int>(arAllFramesReady); } else if (frameContext->first) { frameContext->first = false; } ///////////////////////////////////////////////////////////////////////////////////////////// // Do the actual processing lock.unlock(); PVSFrame f = node->getFrameInternal(frameContext->key.second, ar, frameContext); ranTask = true; bool frameProcessingDone = f || frameContext->hasError(); if (frameContext->hasError() && f) core->logFatal("A frame was returned by " + node->name + " but an error was also set, this is not allowed"); ///////////////////////////////////////////////////////////////////////////////////////////// // Unlock so the next job can run on the context if (useSerialLock) { if (frameProcessingDone && filterMode == fmFrameState) node->serialFrame = -1; node->serialMutex.unlock(); } ///////////////////////////////////////////////////////////////////////////////////////////// // Handle frames that were requested bool requestedFrames = frameContext->reqList.size() > 0 && !frameProcessingDone; bool needsSort = false; if (f && requestedFrames) core->logFatal("A frame was returned at the end of processing by " + node->name + " but there are still outstanding requests"); lock.lock(); if (requestedFrames) { assert(frameContext->numFrameRequests == 0); for (size_t i = 0; i < frameContext->reqList.size(); i++) startInternalRequest(frameContextRef, frameContext->reqList[i]); frameContext->numFrameRequests = frameContext->reqList.size(); frameContext->reqList.clear(); } if (frameProcessingDone) allContexts.erase(frameContext->key); ///////////////////////////////////////////////////////////////////////////////////////////// // Notify all dependent contexts if (frameContext->hasError()) { for (size_t i = 0; i < frameContextRef->notifyCtxList.size(); i++) { PVSFrameContext &notify = frameContextRef->notifyCtxList[i]; notify->setError(frameContextRef->getErrorMessage()); assert(notify->numFrameRequests > 0); if (--notify->numFrameRequests == 0) { queueTask(notify); needsSort = true; } } if (frameContext->external) returnFrame(frameContext, f); } else if (f) { for (size_t i = 0; i < frameContextRef->notifyCtxList.size(); i++) { PVSFrameContext &notify = frameContextRef->notifyCtxList[i]; notify->availableFrames.push_back({frameContextRef->key, f}); assert(notify->numFrameRequests > 0); if (--notify->numFrameRequests == 0) { queueTask(notify); needsSort = true; } } if (frameContext->external) returnFrame(frameContext, f); } else if (requestedFrames) { // already scheduled, do nothing } else { core->logFatal("No frame returned at the end of processing by " + node->name); } if (needsSort) tasks.sort(taskCmp); break; } if (!ranTask || activeThreads > maxThreads) { --activeThreads; if (stop) { lock.unlock(); break; } if (++idleThreads == allThreads.size()) allIdle.notify_one(); newWork.wait(lock); --idleThreads; ++activeThreads; } } } VSThreadPool::VSThreadPool(VSCore *core) : core(core), activeThreads(0), idleThreads(0), reqCounter(0), stopThreads(false), ticks(0) { setThreadCount(0); } size_t VSThreadPool::threadCount() { std::lock_guard<std::mutex> l(taskLock); return maxThreads; } void VSThreadPool::spawnThread() { std::thread *thread = new std::thread(runTasksWrapper, this, std::ref(stopThreads)); allThreads.insert(std::make_pair(thread->get_id(), thread)); ++activeThreads; } size_t VSThreadPool::setThreadCount(size_t threads) { std::lock_guard<std::mutex> l(taskLock); maxThreads = threads > 0 ? threads : getNumAvailableThreads(); if (maxThreads == 0) { maxThreads = 1; core->logMessage(mtWarning, "Couldn't detect optimal number of threads. Thread count set to 1."); } return maxThreads; } void VSThreadPool::queueTask(const PVSFrameContext &ctx) { tasks.push_front(ctx); wakeThread(); } void VSThreadPool::wakeThread() { if (activeThreads < maxThreads) { if (idleThreads == 0) // newly spawned threads are active so no need to notify an additional thread spawnThread(); else newWork.notify_one(); } } void VSThreadPool::releaseThread() { --activeThreads; } void VSThreadPool::reserveThread() { ++activeThreads; } void VSThreadPool::startExternal(const PVSFrameContext &context) { assert(context); std::lock_guard<std::mutex> l(taskLock); context->reqOrder = ++reqCounter; tasks.push_back(context); // external requests can't be combined so just add to queue wakeThread(); } void VSThreadPool::returnFrame(const VSFrameContext *rCtx, const PVSFrame &f) { assert(rCtx->frameDone); bool outputLock = rCtx->lockOnOutput; // we need to unlock here so the callback may request more frames without causing a deadlock // AND so that slow callbacks will only block operations in this thread, not all the others taskLock.unlock(); if (rCtx->hasError()) { if (outputLock) callbackLock.lock(); rCtx->frameDone(rCtx->userData, nullptr, rCtx->key.second, rCtx->key.first, rCtx->errorMessage.c_str()); if (outputLock) callbackLock.unlock(); } else { f->add_ref(); if (outputLock) callbackLock.lock(); rCtx->frameDone(rCtx->userData, f.get(), rCtx->key.second, rCtx->key.first, nullptr); if (outputLock) callbackLock.unlock(); } taskLock.lock(); } void VSThreadPool::startInternalRequest(const PVSFrameContext &notify, NodeOutputKey key) { //technically this could be done by walking up the context chain and add a new notification to the correct one //unfortunately this would probably be quite slow for deep scripts so just hope the cache catches it if (key.second < 0) core->logFatal("Negative frame request by: " + notify->key.first->getName()); // check to see if it's time to reevaluate cache sizes if (core->memory->isOverLimit()) { ticks = 0; core->notifyCaches(true); } else if (++ticks == 500) { // a normal tick for caches to adjust their sizes based on recent history ticks = 0; core->notifyCaches(false); } auto it = allContexts.find(key); if (it != allContexts.end()) { PVSFrameContext &ctx = it->second; ctx->notifyCtxList.push_back(notify); ctx->reqOrder = std::min(ctx->reqOrder, notify->reqOrder); } else { PVSFrameContext ctx = new VSFrameContext(key, notify); // create a new context and append it to the tasks allContexts.insert(std::make_pair(key, ctx)); queueTask(ctx); } } bool VSThreadPool::isWorkerThread() { std::lock_guard<std::mutex> m(taskLock); return allThreads.count(std::this_thread::get_id()) > 0; } void VSThreadPool::waitForDone() { std::unique_lock<std::mutex> m(taskLock); if (idleThreads < allThreads.size()) allIdle.wait(m); } VSThreadPool::~VSThreadPool() { std::unique_lock<std::mutex> m(taskLock); stopThreads = true; while (!allThreads.empty()) { auto iter = allThreads.begin(); auto thread = iter->second; newWork.notify_all(); m.unlock(); thread->join(); m.lock(); allThreads.erase(iter); delete thread; newWork.notify_all(); } assert(activeThreads == 0); assert(idleThreads == 0); }; <commit_msg>Fix threading bug<commit_after>/* * Copyright (c) 2012-2021 Fredrik Mellbin * * This file is part of VapourSynth. * * VapourSynth 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. * * VapourSynth 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 VapourSynth; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "vscore.h" #include <cassert> #include <bitset> #ifdef VS_TARGET_CPU_X86 #include "x86utils.h" #endif #if defined(HAVE_SCHED_GETAFFINITY) #include <sched.h> #elif defined(HAVE_CPUSET_GETAFFINITY) #include <sys/param.h> #include <sys/_cpuset.h> #include <sys/cpuset.h> #endif size_t VSThreadPool::getNumAvailableThreads() { size_t nthreads = std::thread::hardware_concurrency(); #ifdef _WIN32 DWORD_PTR pAff = 0; DWORD_PTR sAff = 0; BOOL res = GetProcessAffinityMask(GetCurrentProcess(), &pAff, &sAff); if (res && pAff != 0) { std::bitset<sizeof(sAff) * 8> b(pAff); nthreads = b.count(); } #elif defined(HAVE_SCHED_GETAFFINITY) // Linux only. cpu_set_t affinity; if (sched_getaffinity(0, sizeof(cpu_set_t), &affinity) == 0) nthreads = CPU_COUNT(&affinity); #elif defined(HAVE_CPUSET_GETAFFINITY) // BSD only (FreeBSD only?) cpuset_t affinity; if (cpuset_getaffinity(CPU_LEVEL_WHICH, CPU_WHICH_PID, -1, sizeof(cpuset_t), &affinity) == 0) nthreads = CPU_COUNT(&affinity); #endif return nthreads; } bool VSThreadPool::taskCmp(const PVSFrameContext &a, const PVSFrameContext &b) { return (a->reqOrder < b->reqOrder) || (a->reqOrder == b->reqOrder && a->key.second < b->key.second); } void VSThreadPool::runTasksWrapper(VSThreadPool *owner, std::atomic<bool> &stop) { owner->runTasks(stop); } void VSThreadPool::runTasks(std::atomic<bool> &stop) { #ifdef VS_TARGET_OS_WINDOWS if (!vs_isSSEStateOk()) core->logFatal("Bad SSE state detected after creating new thread"); #endif std::unique_lock<std::mutex> lock(taskLock); while (true) { bool ranTask = false; ///////////////////////////////////////////////////////////////////////////////////////////// // Go through all tasks from the top (oldest) and process the first one possible std::set<VSNode *> seenNodes; for (auto iter = tasks.begin(); iter != tasks.end(); ++iter) { VSFrameContext *frameContext = iter->get(); VSNode *node = frameContext->key.first; ///////////////////////////////////////////////////////////////////////////////////////////// // Fast path if a frame is cached if (node->cacheEnabled) { PVSFrame f = node->getCachedFrameInternal(frameContext->key.second); if (f) { bool needsSort = false; for (size_t i = 0; i < frameContext->notifyCtxList.size(); i++) { PVSFrameContext &notify = frameContext->notifyCtxList[i]; notify->availableFrames.push_back({frameContext->key, f}); assert(notify->numFrameRequests > 0); if (--notify->numFrameRequests == 0) { queueTask(notify); needsSort = true; } } PVSFrameContext mainContextRef = std::move(*iter); tasks.erase(iter); allContexts.erase(frameContext->key); if (frameContext->external) returnFrame(frameContext, f); if (needsSort) tasks.sort(taskCmp); ranTask = true; break; } } ///////////////////////////////////////////////////////////////////////////////////////////// // This part handles the locking for the different filter modes int filterMode = node->filterMode; // Don't try to lock the same node twice since it's likely to fail and will produce more out of order requests as well if (filterMode != fmFrameState && !seenNodes.insert(node).second) continue; // Does the filter need the per instance mutex? fmFrameState, fmUnordered and fmParallelRequests (when in the arAllFramesReady state) use this bool useSerialLock = (filterMode == fmFrameState || filterMode == fmUnordered || (filterMode == fmParallelRequests && !frameContext->first)); if (useSerialLock) { if (!node->serialMutex.try_lock()) continue; if (filterMode == fmFrameState) { if (node->serialFrame == -1) { node->serialFrame = frameContext->key.second; // another frame already in progress? } else if (node->serialFrame != frameContext->key.second) { node->serialMutex.unlock(); continue; } } } ///////////////////////////////////////////////////////////////////////////////////////////// // Remove the context from the task list and keep references around until processing is done PVSFrameContext frameContextRef = std::move(*iter); tasks.erase(iter); ///////////////////////////////////////////////////////////////////////////////////////////// // Figure out the activation reason assert(frameContext->numFrameRequests == 0); int ar = arInitial; if (frameContext->hasError()) { ar = arError; } else if (!frameContext->first) { ar = (node->apiMajor == 3) ? static_cast<int>(vs3::arAllFramesReady) : static_cast<int>(arAllFramesReady); } else if (frameContext->first) { frameContext->first = false; } ///////////////////////////////////////////////////////////////////////////////////////////// // Do the actual processing lock.unlock(); PVSFrame f = node->getFrameInternal(frameContext->key.second, ar, frameContext); ranTask = true; bool frameProcessingDone = f || frameContext->hasError(); if (frameContext->hasError() && f) core->logFatal("A frame was returned by " + node->name + " but an error was also set, this is not allowed"); ///////////////////////////////////////////////////////////////////////////////////////////// // Unlock so the next job can run on the context if (useSerialLock) { if (frameProcessingDone && filterMode == fmFrameState) node->serialFrame = -1; node->serialMutex.unlock(); } ///////////////////////////////////////////////////////////////////////////////////////////// // Handle frames that were requested bool requestedFrames = frameContext->reqList.size() > 0 && !frameProcessingDone; bool needsSort = false; if (f && requestedFrames) core->logFatal("A frame was returned at the end of processing by " + node->name + " but there are still outstanding requests"); lock.lock(); if (requestedFrames) { assert(frameContext->numFrameRequests == 0); for (size_t i = 0; i < frameContext->reqList.size(); i++) startInternalRequest(frameContextRef, frameContext->reqList[i]); frameContext->numFrameRequests = frameContext->reqList.size(); frameContext->reqList.clear(); } if (frameProcessingDone) allContexts.erase(frameContext->key); ///////////////////////////////////////////////////////////////////////////////////////////// // Notify all dependent contexts if (frameContext->hasError()) { for (size_t i = 0; i < frameContextRef->notifyCtxList.size(); i++) { PVSFrameContext &notify = frameContextRef->notifyCtxList[i]; notify->setError(frameContextRef->getErrorMessage()); assert(notify->numFrameRequests > 0); if (--notify->numFrameRequests == 0) { queueTask(notify); needsSort = true; } } if (frameContext->external) returnFrame(frameContext, f); } else if (f) { for (size_t i = 0; i < frameContextRef->notifyCtxList.size(); i++) { PVSFrameContext &notify = frameContextRef->notifyCtxList[i]; notify->availableFrames.push_back({frameContextRef->key, f}); assert(notify->numFrameRequests > 0); if (--notify->numFrameRequests == 0) { queueTask(notify); needsSort = true; } } if (frameContext->external) returnFrame(frameContext, f); } else if (requestedFrames) { // already scheduled, do nothing } else { core->logFatal("No frame returned at the end of processing by " + node->name); } if (needsSort) tasks.sort(taskCmp); break; } if (!ranTask || activeThreads > maxThreads) { --activeThreads; if (stop) { lock.unlock(); break; } if (++idleThreads == allThreads.size()) allIdle.notify_one(); newWork.wait(lock); --idleThreads; ++activeThreads; } } } VSThreadPool::VSThreadPool(VSCore *core) : core(core), activeThreads(0), idleThreads(0), reqCounter(0), stopThreads(false), ticks(0) { setThreadCount(0); } size_t VSThreadPool::threadCount() { std::lock_guard<std::mutex> l(taskLock); return maxThreads; } void VSThreadPool::spawnThread() { std::thread *thread = new std::thread(runTasksWrapper, this, std::ref(stopThreads)); allThreads.insert(std::make_pair(thread->get_id(), thread)); ++activeThreads; } size_t VSThreadPool::setThreadCount(size_t threads) { std::lock_guard<std::mutex> l(taskLock); maxThreads = threads > 0 ? threads : getNumAvailableThreads(); if (maxThreads == 0) { maxThreads = 1; core->logMessage(mtWarning, "Couldn't detect optimal number of threads. Thread count set to 1."); } return maxThreads; } void VSThreadPool::queueTask(const PVSFrameContext &ctx) { assert(ctx); tasks.push_front(ctx); wakeThread(); } void VSThreadPool::wakeThread() { if (activeThreads < maxThreads) { if (idleThreads == 0) // newly spawned threads are active so no need to notify an additional thread spawnThread(); else newWork.notify_one(); } } void VSThreadPool::releaseThread() { --activeThreads; } void VSThreadPool::reserveThread() { ++activeThreads; } void VSThreadPool::startExternal(const PVSFrameContext &context) { assert(context); std::lock_guard<std::mutex> l(taskLock); context->reqOrder = ++reqCounter; assert(context); tasks.push_back(context); // external requests can't be combined so just add to queue wakeThread(); } void VSThreadPool::returnFrame(const VSFrameContext *rCtx, const PVSFrame &f) { assert(rCtx->frameDone); bool outputLock = rCtx->lockOnOutput; // we need to unlock here so the callback may request more frames without causing a deadlock // AND so that slow callbacks will only block operations in this thread, not all the others taskLock.unlock(); if (rCtx->hasError()) { if (outputLock) callbackLock.lock(); rCtx->frameDone(rCtx->userData, nullptr, rCtx->key.second, rCtx->key.first, rCtx->errorMessage.c_str()); if (outputLock) callbackLock.unlock(); } else { f->add_ref(); if (outputLock) callbackLock.lock(); rCtx->frameDone(rCtx->userData, f.get(), rCtx->key.second, rCtx->key.first, nullptr); if (outputLock) callbackLock.unlock(); } taskLock.lock(); } void VSThreadPool::startInternalRequest(const PVSFrameContext &notify, NodeOutputKey key) { //technically this could be done by walking up the context chain and add a new notification to the correct one //unfortunately this would probably be quite slow for deep scripts so just hope the cache catches it if (key.second < 0) core->logFatal("Negative frame request by: " + notify->key.first->getName()); // check to see if it's time to reevaluate cache sizes if (core->memory->isOverLimit()) { ticks = 0; core->notifyCaches(true); } else if (++ticks == 500) { // a normal tick for caches to adjust their sizes based on recent history ticks = 0; core->notifyCaches(false); } auto it = allContexts.find(key); if (it != allContexts.end()) { PVSFrameContext &ctx = it->second; ctx->notifyCtxList.push_back(notify); ctx->reqOrder = std::min(ctx->reqOrder, notify->reqOrder); } else { PVSFrameContext ctx = new VSFrameContext(key, notify); // create a new context and append it to the tasks allContexts.insert(std::make_pair(key, ctx)); queueTask(ctx); } } bool VSThreadPool::isWorkerThread() { std::lock_guard<std::mutex> m(taskLock); return allThreads.count(std::this_thread::get_id()) > 0; } void VSThreadPool::waitForDone() { std::unique_lock<std::mutex> m(taskLock); if (idleThreads < allThreads.size()) allIdle.wait(m); } VSThreadPool::~VSThreadPool() { std::unique_lock<std::mutex> m(taskLock); stopThreads = true; while (!allThreads.empty()) { auto iter = allThreads.begin(); auto thread = iter->second; newWork.notify_all(); m.unlock(); thread->join(); m.lock(); allThreads.erase(iter); delete thread; newWork.notify_all(); } assert(activeThreads == 0); assert(idleThreads == 0); }; <|endoftext|>
<commit_before>/* * Copyright (c) 2012-2013 Fredrik Mellbin * * This file is part of VapourSynth. * * VapourSynth 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. * * VapourSynth 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 VapourSynth; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "vscore.h" #include <assert.h> #ifdef VS_TARGET_CPU_X86 #include "x86utils.h" #endif void VSThreadPool::runTasks(VSThreadPool *owner, std::atomic<bool> &stop) { #ifdef VS_TARGET_CPU_X86 if (!vs_isMMXStateOk()) vsFatal("Bad MMX state detected after creating new thread"); #endif #ifdef VS_TARGET_OS_WINDOWS if (!vs_isFPUStateOk()) vsWarning("Bad FPU state detected after creating new thread"); if (!vs_isSSEStateOk()) vsFatal("Bad SSE state detected after creating new thread"); #endif std::unique_lock<std::mutex> lock(owner->lock); while (true) { bool ranTask = false; ///////////////////////////////////////////////////////////////////////////////////////////// // Go through all tasks from the top (oldest) and process the first one possible for (std::list<PFrameContext>::iterator iter = owner->tasks.begin(); iter != owner->tasks.end(); ++iter) { FrameContext *mainContext = iter->get(); FrameContext *leafContext = NULL; ///////////////////////////////////////////////////////////////////////////////////////////// // Handle the output tasks if (mainContext->frameDone && mainContext->returnedFrame) { PFrameContext mainContextRef(*iter); owner->tasks.erase(iter); owner->returnFrame(mainContextRef, mainContext->returnedFrame); ranTask = true; break; } if (mainContext->frameDone && mainContext->hasError()) { PFrameContext mainContextRef(*iter); owner->tasks.erase(iter); owner->returnFrame(mainContextRef, mainContext->getErrorMessage()); ranTask = true; break; } bool hasLeafContext = mainContext->returnedFrame || mainContext->hasError(); if (hasLeafContext) { leafContext = mainContext; mainContext = mainContext->upstreamContext.get(); } VSNode *clip = mainContext->clip; int filterMode = clip->filterMode; ///////////////////////////////////////////////////////////////////////////////////////////// // This part handles the locking for the different filter modes bool parallelRequestsNeedsUnlock = false; if (filterMode == fmUnordered) { // already busy? if (!clip->serialMutex.try_lock()) continue; } else if (filterMode == fmSerial) { // already busy? if (!clip->serialMutex.try_lock()) continue; // no frame in progress? if (clip->serialFrame == -1) { clip->serialFrame = mainContext->n; // } else if (clip->serialFrame != mainContext->n) { clip->serialMutex.unlock(); continue; } // continue processing the already started frame } else if (filterMode == fmParallel) { std::lock_guard<std::mutex> lock(clip->concurrentFramesMutex); // is the filter already processing another call for this frame? if so move along if (clip->concurrentFrames.count(mainContext->n)) { continue; } else { clip->concurrentFrames.insert(mainContext->n); } } else if (filterMode == fmParallelRequests) { std::lock_guard<std::mutex> lock(clip->concurrentFramesMutex); // is the filter already processing another call for this frame? if so move along if (clip->concurrentFrames.count(mainContext->n)) { continue; } else { // do we need the serial lock since all frames will be ready this time? // check if we're in the arAllFramesReady state so we need additional locking if (mainContext->numFrameRequests == 1) { if (!clip->serialMutex.try_lock()) continue; parallelRequestsNeedsUnlock = true; clip->concurrentFrames.insert(mainContext->n); } } } ///////////////////////////////////////////////////////////////////////////////////////////// // Remove the context from the task list PFrameContext mainContextRef; PFrameContext leafContextRef; if (hasLeafContext) { leafContextRef = *iter; mainContextRef = leafContextRef->upstreamContext; } else { mainContextRef = *iter; } owner->tasks.erase(iter); ///////////////////////////////////////////////////////////////////////////////////////////// // Figure out the activation reason VSActivationReason ar = arInitial; bool skipCall = false; // Used to avoid multiple error calls for the same frame request going into a filter if (hasLeafContext && leafContext->hasError() || mainContext->hasError()) { ar = arError; skipCall = mainContext->setError(leafContext->getErrorMessage()); --mainContext->numFrameRequests; } else if (hasLeafContext && leafContext->returnedFrame) { if (--mainContext->numFrameRequests > 0) ar = arFrameReady; else ar = arAllFramesReady; mainContext->availableFrames.insert(std::make_pair(NodeOutputKey(leafContext->clip, leafContext->n, leafContext->index), leafContext->returnedFrame)); mainContext->lastCompletedN = leafContext->n; mainContext->lastCompletedNode = leafContext->node; } assert(mainContext->numFrameRequests >= 0); bool hasExistingRequests = !!mainContext->numFrameRequests; ///////////////////////////////////////////////////////////////////////////////////////////// // Do the actual processing lock.unlock(); VSFrameContext externalFrameCtx(mainContextRef); assert(ar == arError || !mainContext->hasError()); PVideoFrame f; if (!skipCall) f = clip->getFrameInternal(mainContext->n, ar, externalFrameCtx); ranTask = true; bool frameProcessingDone = f || mainContext->hasError(); ///////////////////////////////////////////////////////////////////////////////////////////// // Unlock so the next job can run on the context if (filterMode == fmUnordered) { clip->serialMutex.unlock(); } else if (filterMode == fmSerial) { if (frameProcessingDone) clip->serialFrame = -1; clip->serialMutex.unlock(); } else if (filterMode == fmParallel) { std::lock_guard<std::mutex> lock(clip->concurrentFramesMutex); clip->concurrentFrames.erase(mainContext->n); } else if (filterMode == fmParallelRequests) { std::lock_guard<std::mutex> lock(clip->concurrentFramesMutex); clip->concurrentFrames.erase(mainContext->n); if (parallelRequestsNeedsUnlock) clip->serialMutex.unlock(); } ///////////////////////////////////////////////////////////////////////////////////////////// // Handle frames that were requested bool requestedFrames = !externalFrameCtx.reqList.empty() && !frameProcessingDone; lock.lock(); if (requestedFrames) { for (auto &reqIter : externalFrameCtx.reqList) owner->startInternal(reqIter); externalFrameCtx.reqList.clear(); } if (frameProcessingDone) owner->allContexts.erase(NodeOutputKey(mainContext->clip, mainContext->n, mainContext->index)); ///////////////////////////////////////////////////////////////////////////////////////////// // Propagate status to other linked contexts // CHANGES mainContextRef!!! if (mainContext->hasError() && !hasExistingRequests && !requestedFrames) { PFrameContext n; do { n = mainContextRef->notificationChain; if (n) { mainContextRef->notificationChain.reset(); n->setError(mainContextRef->getErrorMessage()); } if (mainContextRef->upstreamContext) { owner->startInternal(mainContextRef); } if (mainContextRef->frameDone) { owner->returnFrame(mainContextRef, mainContextRef->getErrorMessage()); } } while ((mainContextRef = n)); } else if (f) { if (hasExistingRequests || requestedFrames) vsFatal("A frame was returned at the end of processing by %s but there are still outstanding requests", clip->name.c_str()); PFrameContext n; do { n = mainContextRef->notificationChain; if (n) mainContextRef->notificationChain.reset(); if (mainContextRef->upstreamContext) { mainContextRef->returnedFrame = f; owner->startInternal(mainContextRef); } if (mainContextRef->frameDone) owner->returnFrame(mainContextRef, f); } while ((mainContextRef = n)); } else if (hasExistingRequests || requestedFrames) { // already scheduled, do nothing } else { vsFatal("No frame returned at the end of processing by %s", clip->name.c_str()); } break; } if (!ranTask || owner->activeThreadCount() > owner->threadCount()) { --owner->activeThreads; if (stop) { lock.unlock(); break; } ++owner->idleThreads; owner->newWork.wait(lock); --owner->idleThreads; ++owner->activeThreads; } } } VSThreadPool::VSThreadPool(VSCore *core, int threads) : core(core), activeThreads(0), idleThreads(0), stopThreads(false), ticks(0) { setThreadCount(threads); } int VSThreadPool::activeThreadCount() const { return activeThreads; } int VSThreadPool::threadCount() const { return maxThreads; } void VSThreadPool::spawnThread() { std::thread *thread = new std::thread(runTasks, this, std::ref(stopThreads)); allThreads.insert(std::make_pair(thread->get_id(), thread)); ++activeThreads; } void VSThreadPool::setThreadCount(int threads) { maxThreads = threads > 0 ? threads : std::thread::hardware_concurrency(); if (maxThreads == 0) { maxThreads = 1; vsWarning("Couldn't detect optimal number of threads. Thread count set to 1."); } } void VSThreadPool::wakeThread() { if (activeThreads < maxThreads) { if (idleThreads == 0) // newly spawned threads are active so no need to notify an additional thread spawnThread(); else newWork.notify_one(); } } void VSThreadPool::releaseThread() { --activeThreads; } void VSThreadPool::reserveThread() { ++activeThreads; } void VSThreadPool::notifyCaches(bool needMemory) { std::lock_guard<std::mutex> lock(core->cacheLock); for (auto &cache : core->caches) cache->notifyCache(needMemory); } void VSThreadPool::start(const PFrameContext &context) { assert(context); std::lock_guard<std::mutex> l(lock); startInternal(context); } void VSThreadPool::returnFrame(const PFrameContext &rCtx, const PVideoFrame &f) { assert(rCtx->frameDone); // we need to unlock here so the callback may request more frames without causing a deadlock // AND so that slow callbacks will only block operations in this thread, not all the others lock.unlock(); VSFrameRef *ref = new VSFrameRef(f); callbackLock.lock(); rCtx->frameDone(rCtx->userData, ref, rCtx->n, rCtx->node, NULL); callbackLock.unlock(); lock.lock(); } void VSThreadPool::returnFrame(const PFrameContext &rCtx, const std::string &errMsg) { assert(rCtx->frameDone); // we need to unlock here so the callback may request more frames without causing a deadlock // AND so that slow callbacks will only block operations in this thread, not all the others lock.unlock(); callbackLock.lock(); rCtx->frameDone(rCtx->userData, NULL, rCtx->n, rCtx->node, errMsg.c_str()); callbackLock.unlock(); lock.lock(); } void VSThreadPool::startInternal(const PFrameContext &context) { //technically this could be done by walking up the context chain and add a new notification to the correct one //unfortunately this would probably be quite slow for deep scripts so just hope the cache catches it if (context->n < 0) vsFatal("Negative frame request by: %s", context->clip->getName().c_str()); // check to see if it's time to reevaluate cache sizes if (core->memory->isOverLimit()) { ticks = 0; notifyCaches(true); } // a normal tick for caches to adjust their sizes based on recent history if (!context->upstreamContext && ++ticks == 500) { ticks = 0; notifyCaches(false); } // add it immediately if the task is to return a completed frame or report an error since it never has an existing context if (context->returnedFrame || context->hasError()) { tasks.push_back(context); } else { if (context->upstreamContext) ++context->upstreamContext->numFrameRequests; NodeOutputKey p(context->clip, context->n, context->index); if (allContexts.count(p)) { PFrameContext &ctx = allContexts[p]; assert(context->clip == ctx->clip && context->n == ctx->n && context->index == ctx->index); if (ctx->returnedFrame) { // special case where the requested frame is encountered "by accident" context->returnedFrame = ctx->returnedFrame; tasks.push_back(context); } else { // add it to the list of contexts to notify when it's available context->notificationChain = ctx->notificationChain; ctx->notificationChain = context; } } else { // create a new context and append it to the tasks allContexts[p] = context; tasks.push_back(context); } } wakeThread(); } bool VSThreadPool::isWorkerThread() { std::lock_guard<std::mutex> m(lock); return allThreads.count(std::this_thread::get_id()) > 0; } void VSThreadPool::waitForDone() { // todo } VSThreadPool::~VSThreadPool() { std::unique_lock<std::mutex> m(lock); stopThreads = true; while (!allThreads.empty()) { auto iter = allThreads.begin(); auto thread = iter->second; newWork.notify_all(); m.unlock(); thread->join(); m.lock(); allThreads.erase(iter); delete thread; newWork.notify_all(); } assert(activeThreads == 0); assert(idleThreads == 0); }; <commit_msg>add parentheses around '&&'<commit_after>/* * Copyright (c) 2012-2013 Fredrik Mellbin * * This file is part of VapourSynth. * * VapourSynth 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. * * VapourSynth 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 VapourSynth; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "vscore.h" #include <assert.h> #ifdef VS_TARGET_CPU_X86 #include "x86utils.h" #endif void VSThreadPool::runTasks(VSThreadPool *owner, std::atomic<bool> &stop) { #ifdef VS_TARGET_CPU_X86 if (!vs_isMMXStateOk()) vsFatal("Bad MMX state detected after creating new thread"); #endif #ifdef VS_TARGET_OS_WINDOWS if (!vs_isFPUStateOk()) vsWarning("Bad FPU state detected after creating new thread"); if (!vs_isSSEStateOk()) vsFatal("Bad SSE state detected after creating new thread"); #endif std::unique_lock<std::mutex> lock(owner->lock); while (true) { bool ranTask = false; ///////////////////////////////////////////////////////////////////////////////////////////// // Go through all tasks from the top (oldest) and process the first one possible for (std::list<PFrameContext>::iterator iter = owner->tasks.begin(); iter != owner->tasks.end(); ++iter) { FrameContext *mainContext = iter->get(); FrameContext *leafContext = NULL; ///////////////////////////////////////////////////////////////////////////////////////////// // Handle the output tasks if (mainContext->frameDone && mainContext->returnedFrame) { PFrameContext mainContextRef(*iter); owner->tasks.erase(iter); owner->returnFrame(mainContextRef, mainContext->returnedFrame); ranTask = true; break; } if (mainContext->frameDone && mainContext->hasError()) { PFrameContext mainContextRef(*iter); owner->tasks.erase(iter); owner->returnFrame(mainContextRef, mainContext->getErrorMessage()); ranTask = true; break; } bool hasLeafContext = mainContext->returnedFrame || mainContext->hasError(); if (hasLeafContext) { leafContext = mainContext; mainContext = mainContext->upstreamContext.get(); } VSNode *clip = mainContext->clip; int filterMode = clip->filterMode; ///////////////////////////////////////////////////////////////////////////////////////////// // This part handles the locking for the different filter modes bool parallelRequestsNeedsUnlock = false; if (filterMode == fmUnordered) { // already busy? if (!clip->serialMutex.try_lock()) continue; } else if (filterMode == fmSerial) { // already busy? if (!clip->serialMutex.try_lock()) continue; // no frame in progress? if (clip->serialFrame == -1) { clip->serialFrame = mainContext->n; // } else if (clip->serialFrame != mainContext->n) { clip->serialMutex.unlock(); continue; } // continue processing the already started frame } else if (filterMode == fmParallel) { std::lock_guard<std::mutex> lock(clip->concurrentFramesMutex); // is the filter already processing another call for this frame? if so move along if (clip->concurrentFrames.count(mainContext->n)) { continue; } else { clip->concurrentFrames.insert(mainContext->n); } } else if (filterMode == fmParallelRequests) { std::lock_guard<std::mutex> lock(clip->concurrentFramesMutex); // is the filter already processing another call for this frame? if so move along if (clip->concurrentFrames.count(mainContext->n)) { continue; } else { // do we need the serial lock since all frames will be ready this time? // check if we're in the arAllFramesReady state so we need additional locking if (mainContext->numFrameRequests == 1) { if (!clip->serialMutex.try_lock()) continue; parallelRequestsNeedsUnlock = true; clip->concurrentFrames.insert(mainContext->n); } } } ///////////////////////////////////////////////////////////////////////////////////////////// // Remove the context from the task list PFrameContext mainContextRef; PFrameContext leafContextRef; if (hasLeafContext) { leafContextRef = *iter; mainContextRef = leafContextRef->upstreamContext; } else { mainContextRef = *iter; } owner->tasks.erase(iter); ///////////////////////////////////////////////////////////////////////////////////////////// // Figure out the activation reason VSActivationReason ar = arInitial; bool skipCall = false; // Used to avoid multiple error calls for the same frame request going into a filter if ((hasLeafContext && leafContext->hasError()) || mainContext->hasError()) { ar = arError; skipCall = mainContext->setError(leafContext->getErrorMessage()); --mainContext->numFrameRequests; } else if (hasLeafContext && leafContext->returnedFrame) { if (--mainContext->numFrameRequests > 0) ar = arFrameReady; else ar = arAllFramesReady; mainContext->availableFrames.insert(std::make_pair(NodeOutputKey(leafContext->clip, leafContext->n, leafContext->index), leafContext->returnedFrame)); mainContext->lastCompletedN = leafContext->n; mainContext->lastCompletedNode = leafContext->node; } assert(mainContext->numFrameRequests >= 0); bool hasExistingRequests = !!mainContext->numFrameRequests; ///////////////////////////////////////////////////////////////////////////////////////////// // Do the actual processing lock.unlock(); VSFrameContext externalFrameCtx(mainContextRef); assert(ar == arError || !mainContext->hasError()); PVideoFrame f; if (!skipCall) f = clip->getFrameInternal(mainContext->n, ar, externalFrameCtx); ranTask = true; bool frameProcessingDone = f || mainContext->hasError(); ///////////////////////////////////////////////////////////////////////////////////////////// // Unlock so the next job can run on the context if (filterMode == fmUnordered) { clip->serialMutex.unlock(); } else if (filterMode == fmSerial) { if (frameProcessingDone) clip->serialFrame = -1; clip->serialMutex.unlock(); } else if (filterMode == fmParallel) { std::lock_guard<std::mutex> lock(clip->concurrentFramesMutex); clip->concurrentFrames.erase(mainContext->n); } else if (filterMode == fmParallelRequests) { std::lock_guard<std::mutex> lock(clip->concurrentFramesMutex); clip->concurrentFrames.erase(mainContext->n); if (parallelRequestsNeedsUnlock) clip->serialMutex.unlock(); } ///////////////////////////////////////////////////////////////////////////////////////////// // Handle frames that were requested bool requestedFrames = !externalFrameCtx.reqList.empty() && !frameProcessingDone; lock.lock(); if (requestedFrames) { for (auto &reqIter : externalFrameCtx.reqList) owner->startInternal(reqIter); externalFrameCtx.reqList.clear(); } if (frameProcessingDone) owner->allContexts.erase(NodeOutputKey(mainContext->clip, mainContext->n, mainContext->index)); ///////////////////////////////////////////////////////////////////////////////////////////// // Propagate status to other linked contexts // CHANGES mainContextRef!!! if (mainContext->hasError() && !hasExistingRequests && !requestedFrames) { PFrameContext n; do { n = mainContextRef->notificationChain; if (n) { mainContextRef->notificationChain.reset(); n->setError(mainContextRef->getErrorMessage()); } if (mainContextRef->upstreamContext) { owner->startInternal(mainContextRef); } if (mainContextRef->frameDone) { owner->returnFrame(mainContextRef, mainContextRef->getErrorMessage()); } } while ((mainContextRef = n)); } else if (f) { if (hasExistingRequests || requestedFrames) vsFatal("A frame was returned at the end of processing by %s but there are still outstanding requests", clip->name.c_str()); PFrameContext n; do { n = mainContextRef->notificationChain; if (n) mainContextRef->notificationChain.reset(); if (mainContextRef->upstreamContext) { mainContextRef->returnedFrame = f; owner->startInternal(mainContextRef); } if (mainContextRef->frameDone) owner->returnFrame(mainContextRef, f); } while ((mainContextRef = n)); } else if (hasExistingRequests || requestedFrames) { // already scheduled, do nothing } else { vsFatal("No frame returned at the end of processing by %s", clip->name.c_str()); } break; } if (!ranTask || owner->activeThreadCount() > owner->threadCount()) { --owner->activeThreads; if (stop) { lock.unlock(); break; } ++owner->idleThreads; owner->newWork.wait(lock); --owner->idleThreads; ++owner->activeThreads; } } } VSThreadPool::VSThreadPool(VSCore *core, int threads) : core(core), activeThreads(0), idleThreads(0), stopThreads(false), ticks(0) { setThreadCount(threads); } int VSThreadPool::activeThreadCount() const { return activeThreads; } int VSThreadPool::threadCount() const { return maxThreads; } void VSThreadPool::spawnThread() { std::thread *thread = new std::thread(runTasks, this, std::ref(stopThreads)); allThreads.insert(std::make_pair(thread->get_id(), thread)); ++activeThreads; } void VSThreadPool::setThreadCount(int threads) { maxThreads = threads > 0 ? threads : std::thread::hardware_concurrency(); if (maxThreads == 0) { maxThreads = 1; vsWarning("Couldn't detect optimal number of threads. Thread count set to 1."); } } void VSThreadPool::wakeThread() { if (activeThreads < maxThreads) { if (idleThreads == 0) // newly spawned threads are active so no need to notify an additional thread spawnThread(); else newWork.notify_one(); } } void VSThreadPool::releaseThread() { --activeThreads; } void VSThreadPool::reserveThread() { ++activeThreads; } void VSThreadPool::notifyCaches(bool needMemory) { std::lock_guard<std::mutex> lock(core->cacheLock); for (auto &cache : core->caches) cache->notifyCache(needMemory); } void VSThreadPool::start(const PFrameContext &context) { assert(context); std::lock_guard<std::mutex> l(lock); startInternal(context); } void VSThreadPool::returnFrame(const PFrameContext &rCtx, const PVideoFrame &f) { assert(rCtx->frameDone); // we need to unlock here so the callback may request more frames without causing a deadlock // AND so that slow callbacks will only block operations in this thread, not all the others lock.unlock(); VSFrameRef *ref = new VSFrameRef(f); callbackLock.lock(); rCtx->frameDone(rCtx->userData, ref, rCtx->n, rCtx->node, NULL); callbackLock.unlock(); lock.lock(); } void VSThreadPool::returnFrame(const PFrameContext &rCtx, const std::string &errMsg) { assert(rCtx->frameDone); // we need to unlock here so the callback may request more frames without causing a deadlock // AND so that slow callbacks will only block operations in this thread, not all the others lock.unlock(); callbackLock.lock(); rCtx->frameDone(rCtx->userData, NULL, rCtx->n, rCtx->node, errMsg.c_str()); callbackLock.unlock(); lock.lock(); } void VSThreadPool::startInternal(const PFrameContext &context) { //technically this could be done by walking up the context chain and add a new notification to the correct one //unfortunately this would probably be quite slow for deep scripts so just hope the cache catches it if (context->n < 0) vsFatal("Negative frame request by: %s", context->clip->getName().c_str()); // check to see if it's time to reevaluate cache sizes if (core->memory->isOverLimit()) { ticks = 0; notifyCaches(true); } // a normal tick for caches to adjust their sizes based on recent history if (!context->upstreamContext && ++ticks == 500) { ticks = 0; notifyCaches(false); } // add it immediately if the task is to return a completed frame or report an error since it never has an existing context if (context->returnedFrame || context->hasError()) { tasks.push_back(context); } else { if (context->upstreamContext) ++context->upstreamContext->numFrameRequests; NodeOutputKey p(context->clip, context->n, context->index); if (allContexts.count(p)) { PFrameContext &ctx = allContexts[p]; assert(context->clip == ctx->clip && context->n == ctx->n && context->index == ctx->index); if (ctx->returnedFrame) { // special case where the requested frame is encountered "by accident" context->returnedFrame = ctx->returnedFrame; tasks.push_back(context); } else { // add it to the list of contexts to notify when it's available context->notificationChain = ctx->notificationChain; ctx->notificationChain = context; } } else { // create a new context and append it to the tasks allContexts[p] = context; tasks.push_back(context); } } wakeThread(); } bool VSThreadPool::isWorkerThread() { std::lock_guard<std::mutex> m(lock); return allThreads.count(std::this_thread::get_id()) > 0; } void VSThreadPool::waitForDone() { // todo } VSThreadPool::~VSThreadPool() { std::unique_lock<std::mutex> m(lock); stopThreads = true; while (!allThreads.empty()) { auto iter = allThreads.begin(); auto thread = iter->second; newWork.notify_all(); m.unlock(); thread->join(); m.lock(); allThreads.erase(iter); delete thread; newWork.notify_all(); } assert(activeThreads == 0); assert(idleThreads == 0); }; <|endoftext|>
<commit_before>// Copyright (c) 2015 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "atom/common/native_mate_converters/net_converter.h" #include <string> #include <vector> #include "atom/common/native_mate_converters/gurl_converter.h" #include "atom/common/native_mate_converters/value_converter.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_util.h" #include "base/values.h" #include "native_mate/dictionary.h" #include "net/base/upload_bytes_element_reader.h" #include "net/base/upload_data_stream.h" #include "net/base/upload_element_reader.h" #include "net/base/upload_file_element_reader.h" #include "net/cert/x509_certificate.h" #include "net/http/http_response_headers.h" #include "net/url_request/url_request.h" #include "storage/browser/blob/upload_blob_element_reader.h" #include "atom/common/node_includes.h" namespace mate { namespace { bool CertFromData(const std::string& data, scoped_refptr<net::X509Certificate>* out) { auto cert_list = net::X509Certificate::CreateCertificateListFromBytes( data.c_str(), data.length(), net::X509Certificate::FORMAT_SINGLE_CERTIFICATE); if (cert_list.empty()) return false; auto leaf_cert = cert_list.front(); if (!leaf_cert) return false; *out = leaf_cert; return true; } } // static v8::Local<v8::Value> Converter<const net::AuthChallengeInfo*>::ToV8( v8::Isolate* isolate, const net::AuthChallengeInfo* val) { mate::Dictionary dict = mate::Dictionary::CreateEmpty(isolate); dict.Set("isProxy", val->is_proxy); dict.Set("scheme", val->scheme); dict.Set("host", val->challenger.host()); dict.Set("port", static_cast<uint32_t>(val->challenger.port())); dict.Set("realm", val->realm); return mate::ConvertToV8(isolate, dict); } // static v8::Local<v8::Value> Converter<scoped_refptr<net::X509Certificate>>::ToV8( v8::Isolate* isolate, const scoped_refptr<net::X509Certificate>& val) { mate::Dictionary dict(isolate, v8::Object::New(isolate)); std::string encoded_data; net::X509Certificate::GetPEMEncoded( val->os_cert_handle(), &encoded_data); dict.Set("data", encoded_data); dict.Set("issuer", val->issuer()); dict.Set("issuerName", val->issuer().GetDisplayName()); dict.Set("subject", val->subject()); dict.Set("subjectName", val->subject().GetDisplayName()); dict.Set("serialNumber", base::HexEncode(val->serial_number().data(), val->serial_number().size())); dict.Set("validStart", val->valid_start().ToDoubleT()); dict.Set("validExpiry", val->valid_expiry().ToDoubleT()); dict.Set("fingerprint", net::HashValue( val->CalculateFingerprint256(val->os_cert_handle())).ToString()); if (!val->GetIntermediateCertificates().empty()) { net::X509Certificate::OSCertHandles issuer_intermediates( val->GetIntermediateCertificates().begin() + 1, val->GetIntermediateCertificates().end()); const scoped_refptr<net::X509Certificate>& issuer_cert = net::X509Certificate::CreateFromHandle( val->GetIntermediateCertificates().front(), issuer_intermediates); dict.Set("issuerCert", issuer_cert); } return dict.GetHandle(); } bool Converter<scoped_refptr<net::X509Certificate>>::FromV8( v8::Isolate* isolate, v8::Local<v8::Value> val, scoped_refptr<net::X509Certificate>* out) { mate::Dictionary dict; if (!ConvertFromV8(isolate, val, &dict)) return false; std::string data; dict.Get("data", &data); scoped_refptr<net::X509Certificate> leaf_cert; if (!CertFromData(data, &leaf_cert)) return false; scoped_refptr<net::X509Certificate> parent; if (dict.Get("issuerCert", &parent)) { auto parents = std::vector<net::X509Certificate::OSCertHandle>( parent->GetIntermediateCertificates()); parents.insert(parents.begin(), parent->os_cert_handle()); auto cert = net::X509Certificate::CreateFromHandle( leaf_cert->os_cert_handle(), parents); if (!cert) return false; *out = cert; } else { *out = leaf_cert; } return true; } // static v8::Local<v8::Value> Converter<net::CertPrincipal>::ToV8( v8::Isolate* isolate, const net::CertPrincipal& val) { mate::Dictionary dict(isolate, v8::Object::New(isolate)); dict.Set("commonName", val.common_name); dict.Set("organizations", val.organization_names); dict.Set("organizationUnits", val.organization_unit_names); dict.Set("locality", val.locality_name); dict.Set("state", val.state_or_province_name); dict.Set("country", val.country_name); return dict.GetHandle(); } // static v8::Local<v8::Value> Converter<net::HttpResponseHeaders*>::ToV8( v8::Isolate* isolate, net::HttpResponseHeaders* headers) { base::DictionaryValue response_headers; if (headers) { size_t iter = 0; std::string key; std::string value; while (headers->EnumerateHeaderLines(&iter, &key, &value)) { key = base::ToLowerASCII(key); if (response_headers.HasKey(key)) { base::ListValue* values = nullptr; if (response_headers.GetList(key, &values)) values->AppendString(value); } else { std::unique_ptr<base::ListValue> values(new base::ListValue()); values->AppendString(value); response_headers.Set(key, std::move(values)); } } } return ConvertToV8(isolate, response_headers); } } // namespace mate namespace atom { void FillRequestDetails(base::DictionaryValue* details, const net::URLRequest* request) { details->SetString("method", request->method()); std::string url; if (!request->url_chain().empty()) url = request->url().spec(); details->SetStringWithoutPathExpansion("url", url); details->SetString("referrer", request->referrer()); std::unique_ptr<base::ListValue> list(new base::ListValue); GetUploadData(list.get(), request); if (!list->empty()) details->Set("uploadData", std::move(list)); } void GetUploadData(base::ListValue* upload_data_list, const net::URLRequest* request) { const net::UploadDataStream* upload_data = request->get_upload(); if (!upload_data) return; const std::vector<std::unique_ptr<net::UploadElementReader>>* readers = upload_data->GetElementReaders(); for (const auto& reader : *readers) { std::unique_ptr<base::DictionaryValue> upload_data_dict( new base::DictionaryValue); if (reader->AsBytesReader()) { const net::UploadBytesElementReader* bytes_reader = reader->AsBytesReader(); std::unique_ptr<base::Value> bytes( base::BinaryValue::CreateWithCopiedBuffer(bytes_reader->bytes(), bytes_reader->length())); upload_data_dict->Set("bytes", std::move(bytes)); } else if (reader->AsFileReader()) { const net::UploadFileElementReader* file_reader = reader->AsFileReader(); auto file_path = file_reader->path().AsUTF8Unsafe(); upload_data_dict->SetStringWithoutPathExpansion("file", file_path); } else { const storage::UploadBlobElementReader* blob_reader = static_cast<storage::UploadBlobElementReader*>(reader.get()); upload_data_dict->SetString("blobUUID", blob_reader->uuid()); } upload_data_list->Append(std::move(upload_data_dict)); } } } // namespace atom <commit_msg>As you wish linter<commit_after>// Copyright (c) 2015 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "atom/common/native_mate_converters/net_converter.h" #include <string> #include <vector> #include "atom/common/native_mate_converters/gurl_converter.h" #include "atom/common/native_mate_converters/value_converter.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_util.h" #include "base/values.h" #include "native_mate/dictionary.h" #include "net/base/upload_bytes_element_reader.h" #include "net/base/upload_data_stream.h" #include "net/base/upload_element_reader.h" #include "net/base/upload_file_element_reader.h" #include "net/cert/x509_certificate.h" #include "net/http/http_response_headers.h" #include "net/url_request/url_request.h" #include "storage/browser/blob/upload_blob_element_reader.h" #include "atom/common/node_includes.h" namespace mate { namespace { bool CertFromData(const std::string& data, scoped_refptr<net::X509Certificate>* out) { auto cert_list = net::X509Certificate::CreateCertificateListFromBytes( data.c_str(), data.length(), net::X509Certificate::FORMAT_SINGLE_CERTIFICATE); if (cert_list.empty()) return false; auto leaf_cert = cert_list.front(); if (!leaf_cert) return false; *out = leaf_cert; return true; } } // namespace // static v8::Local<v8::Value> Converter<const net::AuthChallengeInfo*>::ToV8( v8::Isolate* isolate, const net::AuthChallengeInfo* val) { mate::Dictionary dict = mate::Dictionary::CreateEmpty(isolate); dict.Set("isProxy", val->is_proxy); dict.Set("scheme", val->scheme); dict.Set("host", val->challenger.host()); dict.Set("port", static_cast<uint32_t>(val->challenger.port())); dict.Set("realm", val->realm); return mate::ConvertToV8(isolate, dict); } // static v8::Local<v8::Value> Converter<scoped_refptr<net::X509Certificate>>::ToV8( v8::Isolate* isolate, const scoped_refptr<net::X509Certificate>& val) { mate::Dictionary dict(isolate, v8::Object::New(isolate)); std::string encoded_data; net::X509Certificate::GetPEMEncoded( val->os_cert_handle(), &encoded_data); dict.Set("data", encoded_data); dict.Set("issuer", val->issuer()); dict.Set("issuerName", val->issuer().GetDisplayName()); dict.Set("subject", val->subject()); dict.Set("subjectName", val->subject().GetDisplayName()); dict.Set("serialNumber", base::HexEncode(val->serial_number().data(), val->serial_number().size())); dict.Set("validStart", val->valid_start().ToDoubleT()); dict.Set("validExpiry", val->valid_expiry().ToDoubleT()); dict.Set("fingerprint", net::HashValue( val->CalculateFingerprint256(val->os_cert_handle())).ToString()); if (!val->GetIntermediateCertificates().empty()) { net::X509Certificate::OSCertHandles issuer_intermediates( val->GetIntermediateCertificates().begin() + 1, val->GetIntermediateCertificates().end()); const scoped_refptr<net::X509Certificate>& issuer_cert = net::X509Certificate::CreateFromHandle( val->GetIntermediateCertificates().front(), issuer_intermediates); dict.Set("issuerCert", issuer_cert); } return dict.GetHandle(); } bool Converter<scoped_refptr<net::X509Certificate>>::FromV8( v8::Isolate* isolate, v8::Local<v8::Value> val, scoped_refptr<net::X509Certificate>* out) { mate::Dictionary dict; if (!ConvertFromV8(isolate, val, &dict)) return false; std::string data; dict.Get("data", &data); scoped_refptr<net::X509Certificate> leaf_cert; if (!CertFromData(data, &leaf_cert)) return false; scoped_refptr<net::X509Certificate> parent; if (dict.Get("issuerCert", &parent)) { auto parents = std::vector<net::X509Certificate::OSCertHandle>( parent->GetIntermediateCertificates()); parents.insert(parents.begin(), parent->os_cert_handle()); auto cert = net::X509Certificate::CreateFromHandle( leaf_cert->os_cert_handle(), parents); if (!cert) return false; *out = cert; } else { *out = leaf_cert; } return true; } // static v8::Local<v8::Value> Converter<net::CertPrincipal>::ToV8( v8::Isolate* isolate, const net::CertPrincipal& val) { mate::Dictionary dict(isolate, v8::Object::New(isolate)); dict.Set("commonName", val.common_name); dict.Set("organizations", val.organization_names); dict.Set("organizationUnits", val.organization_unit_names); dict.Set("locality", val.locality_name); dict.Set("state", val.state_or_province_name); dict.Set("country", val.country_name); return dict.GetHandle(); } // static v8::Local<v8::Value> Converter<net::HttpResponseHeaders*>::ToV8( v8::Isolate* isolate, net::HttpResponseHeaders* headers) { base::DictionaryValue response_headers; if (headers) { size_t iter = 0; std::string key; std::string value; while (headers->EnumerateHeaderLines(&iter, &key, &value)) { key = base::ToLowerASCII(key); if (response_headers.HasKey(key)) { base::ListValue* values = nullptr; if (response_headers.GetList(key, &values)) values->AppendString(value); } else { std::unique_ptr<base::ListValue> values(new base::ListValue()); values->AppendString(value); response_headers.Set(key, std::move(values)); } } } return ConvertToV8(isolate, response_headers); } } // namespace mate namespace atom { void FillRequestDetails(base::DictionaryValue* details, const net::URLRequest* request) { details->SetString("method", request->method()); std::string url; if (!request->url_chain().empty()) url = request->url().spec(); details->SetStringWithoutPathExpansion("url", url); details->SetString("referrer", request->referrer()); std::unique_ptr<base::ListValue> list(new base::ListValue); GetUploadData(list.get(), request); if (!list->empty()) details->Set("uploadData", std::move(list)); } void GetUploadData(base::ListValue* upload_data_list, const net::URLRequest* request) { const net::UploadDataStream* upload_data = request->get_upload(); if (!upload_data) return; const std::vector<std::unique_ptr<net::UploadElementReader>>* readers = upload_data->GetElementReaders(); for (const auto& reader : *readers) { std::unique_ptr<base::DictionaryValue> upload_data_dict( new base::DictionaryValue); if (reader->AsBytesReader()) { const net::UploadBytesElementReader* bytes_reader = reader->AsBytesReader(); std::unique_ptr<base::Value> bytes( base::BinaryValue::CreateWithCopiedBuffer(bytes_reader->bytes(), bytes_reader->length())); upload_data_dict->Set("bytes", std::move(bytes)); } else if (reader->AsFileReader()) { const net::UploadFileElementReader* file_reader = reader->AsFileReader(); auto file_path = file_reader->path().AsUTF8Unsafe(); upload_data_dict->SetStringWithoutPathExpansion("file", file_path); } else { const storage::UploadBlobElementReader* blob_reader = static_cast<storage::UploadBlobElementReader*>(reader.get()); upload_data_dict->SetString("blobUUID", blob_reader->uuid()); } upload_data_list->Append(std::move(upload_data_dict)); } } } // namespace atom <|endoftext|>
<commit_before>#include "SkeletonSmoother.h" SkeletonSmoother::SkeletonSmoother(ICoordinateMapper *coordinateMapper) : m_CoordinateMapper(coordinateMapper) , m_SmoothScale(1.f) , m_PositionScale(1.f) { std::fill(m_JointPositions.at(0).begin(), m_JointPositions.at(0).end(), JointProp()); std::fill(m_JointPositions.at(1).begin(), m_JointPositions.at(1).end(), JointProp()); std::fill(m_JointPositions.at(2).begin(), m_JointPositions.at(2).end(), JointProp()); std::fill(m_JointPositions.at(3).begin(), m_JointPositions.at(3).end(), JointProp()); std::fill(m_JointPositions.at(4).begin(), m_JointPositions.at(4).end(), JointProp()); std::fill(m_JointPositions.at(5).begin(), m_JointPositions.at(5).end(), JointProp()); } void SkeletonSmoother::updateJointPositions(const unsigned int &bodyIndex, const float &delta, const PointF &screenSize, Joint *joints) { for (unsigned int jointIndex = 0; jointIndex < JointType_Count; jointIndex++) { const PointF jointRawPos = mapBodyPointToScreenPoint(joints[jointIndex].Position, screenSize.X, screenSize.Y); //Invert the Y-axis const PointF screenPos = {jointRawPos.X, screenSize.Y - jointRawPos.Y}; JointArray &jointPositions = m_JointPositions.at(bodyIndex); JointProp &prop = jointPositions.at(jointIndex); if (pointEquals(prop.pos, pointZero()) || prop.isDirty) { prop.pos.X = screenPos.X * m_PositionScale; prop.pos.Y = screenPos.Y * m_PositionScale; prop.isDirty = false; } prop.attractionPoint.X = screenPos.X * m_PositionScale; prop.attractionPoint.Y = screenPos.Y * m_PositionScale; } for (unsigned int jointIndex = 0; jointIndex < m_JointPositions.at(bodyIndex).size(); jointIndex++) { m_JointPositions.at(bodyIndex).at(jointIndex).updatePos(delta, m_SmoothScale); } } void SkeletonSmoother::reset(const unsigned int &bodyIndex) { for (unsigned int i = 0; i < JointType_Count; i++) { m_JointPositions.at(bodyIndex).at(i).reset(); } } void SkeletonSmoother::setSmoothScale(float scale) { if (scale <= 0) { return; } m_SmoothScale = scale; } float SkeletonSmoother::getSmoothScale() const { return m_SmoothScale; } void SkeletonSmoother::setPositionScale(float scale) { if (scale <= 0) { return; } m_PositionScale = scale; for (unsigned int bodyIndex = 0; bodyIndex < m_JointPositions.size(); bodyIndex++) { for (unsigned int i = 0; i < JointType_Count; i++) { m_JointPositions.at(bodyIndex).at(i).isDirty = true; } } } float SkeletonSmoother::getPositionScale() const { return m_PositionScale; } const std::array<SkeletonSmoother::JointProp, JointType_Count> &SkeletonSmoother::getJointProperties(const unsigned int &bodyIndex) const { return m_JointPositions.at(bodyIndex); } PointF SkeletonSmoother::getJointPosition(const unsigned int &bodyIndex, const unsigned int &type) const { return m_JointPositions.at(bodyIndex).at(type).pos; } void SkeletonSmoother::enableJointDrawing(unsigned int bodyIndex, JointType jointType, bool enable) { m_JointPositions.at(bodyIndex).at(jointType).isDraw = enable; } bool SkeletonSmoother::isJointDrew(unsigned int bodyIndex, JointType jointType) const { return m_JointPositions.at(bodyIndex).at(jointType).isDraw; } PointF SkeletonSmoother::mapBodyPointToScreenPoint(const CameraSpacePoint &bodyPoint, const int &width, const int &height) { // Calculate the body's position on the screen PointF screenPos = {0, 0}; DepthSpacePoint depthPoint = {0, 0}; if (m_CoordinateMapper) { m_CoordinateMapper->MapCameraPointToDepthSpace(bodyPoint, &depthPoint); screenPos.X = static_cast<float>(depthPoint.X * width) / SkeletonSmoother::DEPTH_WIDTH; screenPos.Y = static_cast<float>(depthPoint.Y * height) / SkeletonSmoother::DEPTH_HEIGHT; } return screenPos; } bool SkeletonSmoother::pointEquals(const PointF &p1, const PointF &p2) { return (p1.X == p2.X) && (p1.Y == p2.Y); } PointF SkeletonSmoother::pointZero() { PointF p = {0, 0}; return p; } <commit_msg>Check for nullptr and body index validity<commit_after>#include "SkeletonSmoother.h" SkeletonSmoother::SkeletonSmoother(ICoordinateMapper *coordinateMapper) : m_CoordinateMapper(coordinateMapper) , m_SmoothScale(1.f) , m_PositionScale(1.f) { std::fill(m_JointPositions.at(0).begin(), m_JointPositions.at(0).end(), JointProp()); std::fill(m_JointPositions.at(1).begin(), m_JointPositions.at(1).end(), JointProp()); std::fill(m_JointPositions.at(2).begin(), m_JointPositions.at(2).end(), JointProp()); std::fill(m_JointPositions.at(3).begin(), m_JointPositions.at(3).end(), JointProp()); std::fill(m_JointPositions.at(4).begin(), m_JointPositions.at(4).end(), JointProp()); std::fill(m_JointPositions.at(5).begin(), m_JointPositions.at(5).end(), JointProp()); } void SkeletonSmoother::updateJointPositions(const unsigned int &bodyIndex, const float &delta, const PointF &screenSize, Joint *joints) { if (joints == nullptr || bodyIndex >= BODY_COUNT) { return; } for (unsigned int jointIndex = 0; jointIndex < JointType_Count; jointIndex++) { const PointF jointRawPos = mapBodyPointToScreenPoint(joints[jointIndex].Position, screenSize.X, screenSize.Y); //Invert the Y-axis const PointF screenPos = {jointRawPos.X, screenSize.Y - jointRawPos.Y}; JointArray &jointPositions = m_JointPositions.at(bodyIndex); JointProp &prop = jointPositions.at(jointIndex); if (pointEquals(prop.pos, pointZero()) || prop.isDirty) { prop.pos.X = screenPos.X * m_PositionScale; prop.pos.Y = screenPos.Y * m_PositionScale; prop.isDirty = false; } prop.attractionPoint.X = screenPos.X * m_PositionScale; prop.attractionPoint.Y = screenPos.Y * m_PositionScale; } for (unsigned int jointIndex = 0; jointIndex < m_JointPositions.at(bodyIndex).size(); jointIndex++) { m_JointPositions.at(bodyIndex).at(jointIndex).updatePos(delta, m_SmoothScale); } } void SkeletonSmoother::reset(const unsigned int &bodyIndex) { for (unsigned int i = 0; i < JointType_Count; i++) { m_JointPositions.at(bodyIndex).at(i).reset(); } } void SkeletonSmoother::setSmoothScale(float scale) { if (scale <= 0) { return; } m_SmoothScale = scale; } float SkeletonSmoother::getSmoothScale() const { return m_SmoothScale; } void SkeletonSmoother::setPositionScale(float scale) { if (scale <= 0) { return; } m_PositionScale = scale; for (unsigned int bodyIndex = 0; bodyIndex < m_JointPositions.size(); bodyIndex++) { for (unsigned int i = 0; i < JointType_Count; i++) { m_JointPositions.at(bodyIndex).at(i).isDirty = true; } } } float SkeletonSmoother::getPositionScale() const { return m_PositionScale; } const std::array<SkeletonSmoother::JointProp, JointType_Count> &SkeletonSmoother::getJointProperties(const unsigned int &bodyIndex) const { return m_JointPositions.at(bodyIndex); } PointF SkeletonSmoother::getJointPosition(const unsigned int &bodyIndex, const unsigned int &type) const { return m_JointPositions.at(bodyIndex).at(type).pos; } void SkeletonSmoother::enableJointDrawing(unsigned int bodyIndex, JointType jointType, bool enable) { m_JointPositions.at(bodyIndex).at(jointType).isDraw = enable; } bool SkeletonSmoother::isJointDrew(unsigned int bodyIndex, JointType jointType) const { return m_JointPositions.at(bodyIndex).at(jointType).isDraw; } PointF SkeletonSmoother::mapBodyPointToScreenPoint(const CameraSpacePoint &bodyPoint, const int &width, const int &height) { // Calculate the body's position on the screen PointF screenPos = {0, 0}; DepthSpacePoint depthPoint = {0, 0}; if (m_CoordinateMapper) { m_CoordinateMapper->MapCameraPointToDepthSpace(bodyPoint, &depthPoint); screenPos.X = static_cast<float>(depthPoint.X * width) / SkeletonSmoother::DEPTH_WIDTH; screenPos.Y = static_cast<float>(depthPoint.Y * height) / SkeletonSmoother::DEPTH_HEIGHT; } return screenPos; } bool SkeletonSmoother::pointEquals(const PointF &p1, const PointF &p2) { return (p1.X == p2.X) && (p1.Y == p2.Y); } PointF SkeletonSmoother::pointZero() { PointF p = {0, 0}; return p; } <|endoftext|>
<commit_before>/* * FileLock.cpp * * Copyright (C) 2009-12 by RStudio, Inc. * * Unless you have received this program directly from RStudio pursuant * to the terms of a commercial license agreement with RStudio, then * this program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ #include <core/FileLock.hpp> // #define RSTUDIO_ENABLE_DEBUG_MACROS #include <core/Macros.hpp> #include <core/Settings.hpp> #include <core/Error.hpp> #include <core/Log.hpp> #include <core/FileSerializer.hpp> #include <boost/algorithm/string.hpp> namespace rstudio { namespace core { namespace file_lock { void initialize() { FileLock::initialize(); } } // end namespace file_lock namespace { const char * const kLocksConfPath = "/etc/rstudio/locks.conf"; #define kDefaultRefreshRate 20.0 #define kDefaultTimeoutInterval 30.0 std::string lockTypeToString(FileLock::LockType type) { switch (type) { case FileLock::LOCKTYPE_ADVISORY: return "advisory"; case FileLock::LOCKTYPE_LINKBASED: return "linkbased"; } // not reached return std::string(); } FileLock::LockType stringToLockType(const std::string& lockType) { using namespace boost::algorithm; if (boost::iequals(lockType, "advisory")) return FileLock::LOCKTYPE_ADVISORY; else if (boost::iequals(lockType, "linkbased")) return FileLock::LOCKTYPE_LINKBASED; LOG_WARNING_MESSAGE("unrecognized lock type '" + lockType + "'"); return FileLock::LOCKTYPE_ADVISORY; } double getFieldPositive(const Settings& settings, const std::string& name, double defaultValue) { double value = settings.getDouble(name, defaultValue); if (value < 0) { LOG_WARNING_MESSAGE("invalid field '" + name + "': must be positive"); return defaultValue; } return value; } } // end anonymous namespace bool s_isInitialized = false; void FileLock::ensureInitialized() { if (s_isInitialized) return; FileLock::initialize(); } void FileLock::initialize(FilePath locksConfPath) { s_isInitialized = true; if (locksConfPath.empty()) locksConfPath = FilePath(kLocksConfPath); if (!locksConfPath.exists()) return; Settings settings; Error error = settings.initialize(locksConfPath); if (error) { LOG_ERROR(error); return; } FileLock::initialize(settings); } void FileLock::initialize(const Settings& settings) { s_isInitialized = true; // default lock type FileLock::s_defaultType = stringToLockType(settings.get("lock-type", "advisory")); // timeout interval double timeoutInterval = getFieldPositive(settings, "timeout-interval", kDefaultTimeoutInterval); FileLock::s_timeoutInterval = boost::posix_time::seconds(timeoutInterval); // refresh rate double refreshRate = getFieldPositive(settings, "refresh-rate", kDefaultRefreshRate); FileLock::s_refreshRate = boost::posix_time::seconds(refreshRate); DEBUG_BLOCK("lock initialization") { std::cerr << "Type: " << lockTypeToString(FileLock::s_defaultType) << std::endl; std::cerr << "Timeout: " << FileLock::s_timeoutInterval.total_seconds() << std::endl; std::cerr << "Refresh: " << FileLock::s_refreshRate.total_seconds() << std::endl; } } // default values for static members FileLock::LockType FileLock::s_defaultType(FileLock::LOCKTYPE_ADVISORY); boost::posix_time::seconds FileLock::s_timeoutInterval(kDefaultTimeoutInterval); boost::posix_time::seconds FileLock::s_refreshRate(kDefaultRefreshRate); boost::shared_ptr<FileLock> FileLock::create(LockType type) { switch (type) { case LOCKTYPE_ADVISORY: return boost::shared_ptr<FileLock>(new AdvisoryFileLock()); case LOCKTYPE_LINKBASED: return boost::shared_ptr<FileLock>(new LinkBasedFileLock()); } // shouldn't be reached return boost::shared_ptr<FileLock>(new AdvisoryFileLock()); } boost::shared_ptr<FileLock> FileLock::createDefault() { return FileLock::create(s_defaultType); } void FileLock::refresh() { AdvisoryFileLock::refresh(); LinkBasedFileLock::refresh(); } void FileLock::cleanUp() { AdvisoryFileLock::cleanUp(); LinkBasedFileLock::cleanUp(); } namespace { void schedulePeriodicExecution( const boost::system::error_code& ec, boost::asio::deadline_timer& timer, boost::posix_time::seconds interval, boost::function<void()> callback) { try { // bail on boost errors (these are very unexpected) if (ec) { LOG_ERROR(core::Error(ec, ERROR_LOCATION)); return; } // execute callback callback(); // reschedule boost::system::error_code errc; timer.expires_at(timer.expires_at() + interval, errc); if (errc) { LOG_ERROR(Error(errc, ERROR_LOCATION)); return; } timer.async_wait(boost::bind( schedulePeriodicExecution, boost::asio::placeholders::error, boost::ref(timer), interval, callback)); } catch (...) { // swallow errors } } } // end anonymous namespace void FileLock::refreshPeriodically(boost::asio::io_service& service, boost::posix_time::seconds interval) { // protect against re-entrancy static bool s_isRefreshing = false; if (s_isRefreshing) return; s_isRefreshing = true; static boost::asio::deadline_timer timer(service, interval); timer.async_wait(boost::bind( schedulePeriodicExecution, boost::asio::placeholders::error, boost::ref(timer), interval, FileLock::refresh)); } } // end namespace core } // end namespace rstudio <commit_msg>follow naming convention (file-locks)<commit_after>/* * FileLock.cpp * * Copyright (C) 2009-12 by RStudio, Inc. * * Unless you have received this program directly from RStudio pursuant * to the terms of a commercial license agreement with RStudio, then * this program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ #include <core/FileLock.hpp> // #define RSTUDIO_ENABLE_DEBUG_MACROS #include <core/Macros.hpp> #include <core/Settings.hpp> #include <core/Error.hpp> #include <core/Log.hpp> #include <core/FileSerializer.hpp> #include <boost/algorithm/string.hpp> namespace rstudio { namespace core { namespace file_lock { void initialize() { FileLock::initialize(); } } // end namespace file_lock namespace { const char * const kLocksConfPath = "/etc/rstudio/file-locks"; #define kDefaultRefreshRate 20.0 #define kDefaultTimeoutInterval 30.0 std::string lockTypeToString(FileLock::LockType type) { switch (type) { case FileLock::LOCKTYPE_ADVISORY: return "advisory"; case FileLock::LOCKTYPE_LINKBASED: return "linkbased"; } // not reached return std::string(); } FileLock::LockType stringToLockType(const std::string& lockType) { using namespace boost::algorithm; if (boost::iequals(lockType, "advisory")) return FileLock::LOCKTYPE_ADVISORY; else if (boost::iequals(lockType, "linkbased")) return FileLock::LOCKTYPE_LINKBASED; LOG_WARNING_MESSAGE("unrecognized lock type '" + lockType + "'"); return FileLock::LOCKTYPE_ADVISORY; } double getFieldPositive(const Settings& settings, const std::string& name, double defaultValue) { double value = settings.getDouble(name, defaultValue); if (value < 0) { LOG_WARNING_MESSAGE("invalid field '" + name + "': must be positive"); return defaultValue; } return value; } } // end anonymous namespace bool s_isInitialized = false; void FileLock::ensureInitialized() { if (s_isInitialized) return; FileLock::initialize(); } void FileLock::initialize(FilePath locksConfPath) { s_isInitialized = true; if (locksConfPath.empty()) locksConfPath = FilePath(kLocksConfPath); if (!locksConfPath.exists()) return; Settings settings; Error error = settings.initialize(locksConfPath); if (error) { LOG_ERROR(error); return; } FileLock::initialize(settings); } void FileLock::initialize(const Settings& settings) { s_isInitialized = true; // default lock type FileLock::s_defaultType = stringToLockType(settings.get("lock-type", "advisory")); // timeout interval double timeoutInterval = getFieldPositive(settings, "timeout-interval", kDefaultTimeoutInterval); FileLock::s_timeoutInterval = boost::posix_time::seconds(timeoutInterval); // refresh rate double refreshRate = getFieldPositive(settings, "refresh-rate", kDefaultRefreshRate); FileLock::s_refreshRate = boost::posix_time::seconds(refreshRate); DEBUG_BLOCK("lock initialization") { std::cerr << "Type: " << lockTypeToString(FileLock::s_defaultType) << std::endl; std::cerr << "Timeout: " << FileLock::s_timeoutInterval.total_seconds() << std::endl; std::cerr << "Refresh: " << FileLock::s_refreshRate.total_seconds() << std::endl; } } // default values for static members FileLock::LockType FileLock::s_defaultType(FileLock::LOCKTYPE_ADVISORY); boost::posix_time::seconds FileLock::s_timeoutInterval(kDefaultTimeoutInterval); boost::posix_time::seconds FileLock::s_refreshRate(kDefaultRefreshRate); boost::shared_ptr<FileLock> FileLock::create(LockType type) { switch (type) { case LOCKTYPE_ADVISORY: return boost::shared_ptr<FileLock>(new AdvisoryFileLock()); case LOCKTYPE_LINKBASED: return boost::shared_ptr<FileLock>(new LinkBasedFileLock()); } // shouldn't be reached return boost::shared_ptr<FileLock>(new AdvisoryFileLock()); } boost::shared_ptr<FileLock> FileLock::createDefault() { return FileLock::create(s_defaultType); } void FileLock::refresh() { AdvisoryFileLock::refresh(); LinkBasedFileLock::refresh(); } void FileLock::cleanUp() { AdvisoryFileLock::cleanUp(); LinkBasedFileLock::cleanUp(); } namespace { void schedulePeriodicExecution( const boost::system::error_code& ec, boost::asio::deadline_timer& timer, boost::posix_time::seconds interval, boost::function<void()> callback) { try { // bail on boost errors (these are very unexpected) if (ec) { LOG_ERROR(core::Error(ec, ERROR_LOCATION)); return; } // execute callback callback(); // reschedule boost::system::error_code errc; timer.expires_at(timer.expires_at() + interval, errc); if (errc) { LOG_ERROR(Error(errc, ERROR_LOCATION)); return; } timer.async_wait(boost::bind( schedulePeriodicExecution, boost::asio::placeholders::error, boost::ref(timer), interval, callback)); } catch (...) { // swallow errors } } } // end anonymous namespace void FileLock::refreshPeriodically(boost::asio::io_service& service, boost::posix_time::seconds interval) { // protect against re-entrancy static bool s_isRefreshing = false; if (s_isRefreshing) return; s_isRefreshing = true; static boost::asio::deadline_timer timer(service, interval); timer.async_wait(boost::bind( schedulePeriodicExecution, boost::asio::placeholders::error, boost::ref(timer), interval, FileLock::refresh)); } } // end namespace core } // end namespace rstudio <|endoftext|>
<commit_before>#include <process.hpp> #include <vector> #include <glog/logging.h> #include <boost/lexical_cast.hpp> #include "config/config.hpp" #include "common/fatal.hpp" #include "common/foreach.hpp" #ifdef WITH_ZOOKEEPER #include "common/zookeeper.hpp" #endif #include "messaging/messages.hpp" #include "detector.hpp" #include "url_processor.hpp" using namespace mesos; using namespace mesos::internal; using boost::lexical_cast; using process::Process; using process::UPID; using std::pair; using std::string; using std::vector; #ifdef WITH_ZOOKEEPER class ZooKeeperMasterDetector : public MasterDetector, public Watcher { public: /** * Uses ZooKeeper for both detecting masters and contending to be a * master. * * @param server comma separated list of server host:port pairs * * @param znode top-level "ZooKeeper node" (directory) to use * @param pid libprocess pid to send messages/updates to (and to * use for contending to be a master) * @param contend true if should contend to be master (not needed * for slaves and frameworks) * @param quiet verbosity logging level for undelying ZooKeeper library */ ZooKeeperMasterDetector(const string& servers, const string& znode, const UPID& pid, bool contend = false, bool quiet = false); virtual ~ZooKeeperMasterDetector(); /** * ZooKeeper watcher callback. */ virtual void process(ZooKeeper *zk, int type, int state, const string &path); private: void connected(); void reconnecting(); void reconnected(); void expired(); void updated(const string& path); /** * @param s sequence id */ void setId(const string &s); /** * @return current sequence id if contending to be a master */ string getId(); /** * Attempts to detect a master. */ void detectMaster(); /** * @param seq sequence id of a master * @return PID corresponding to a master */ UPID lookupMasterPID(const string &seq) const; const string servers; const string znode; const UPID pid; bool contend; bool reconnect; ZooKeeper *zk; // Our sequence string if contending to be a master. string mySeq; string currentMasterSeq; UPID currentMasterPID; }; #endif // WITH_ZOOKEEPER MasterDetector::~MasterDetector() {} MasterDetector* MasterDetector::create(const string &url, const UPID &pid, bool contend, bool quiet) { if (url == "") if (contend) { return new BasicMasterDetector(pid); } else { fatal("cannot use specified url to detect master"); } MasterDetector *detector = NULL; // Parse the url. pair<UrlProcessor::URLType, string> urlPair = UrlProcessor::process(url); switch (urlPair.first) { // ZooKeeper URL. case UrlProcessor::ZOO: { #ifdef WITH_ZOOKEEPER // TODO(benh): Consider actually using the chroot feature of // ZooKeeper, rather than just using it's syntax. size_t index = urlPair.second.find("/"); if (index == string::npos) { fatal("expecting chroot path for ZooKeeper"); } const string &servers = urlPair.second.substr(0, index); const string &znode = urlPair.second.substr(index); if (znode == "/") { fatal("expecting chroot path for ZooKeeper ('/' is not supported)"); } detector = new ZooKeeperMasterDetector(servers, znode, pid, contend, quiet); #else fatal("Cannot detect masters with 'zoo://', " "ZooKeeper is not supported in this build"); #endif // WITH_ZOOKEEPER break; } // Mesos URL or libprocess pid. case UrlProcessor::MESOS: case UrlProcessor::UNKNOWN: { if (contend) { // TODO(benh): Wierdnesses like this makes it seem like there // should be a separate elector and detector. In particular, // it doesn't make sense to pass a libprocess pid and attempt // to contend (at least not right now). fatal("cannot contend to be a master with specified url"); } else { UPID master(urlPair.second); if (!master) fatal("cannot use specified url to detect master"); detector = new BasicMasterDetector(master, pid); } break; } } return detector; } void MasterDetector::destroy(MasterDetector *detector) { if (detector != NULL) delete detector; } BasicMasterDetector::BasicMasterDetector(const UPID& _master) : master(_master) { // Send a master token. { MSG<GOT_MASTER_TOKEN> msg; msg.set_token("0"); MesosProcess<class T>::post(master, msg); } // Elect the master. { MSG<NEW_MASTER_DETECTED> msg; msg.set_pid(master); MesosProcess<class T>::post(master, msg); } } BasicMasterDetector::BasicMasterDetector(const UPID& _master, const UPID& pid, bool elect) : master(_master) { if (elect) { // Send a master token. { MSG<GOT_MASTER_TOKEN> msg; msg.set_token("0"); MesosProcess<class T>::post(master, msg); } // Elect the master. { MSG<NEW_MASTER_DETECTED> msg; msg.set_pid(master); MesosProcess<class T>::post(master, msg); } } // Tell the pid about the master. MSG<NEW_MASTER_DETECTED> msg; msg.set_pid(master); MesosProcess<class T>::post(pid, msg); } BasicMasterDetector::BasicMasterDetector(const UPID& _master, const vector<UPID>& pids, bool elect) : master(_master) { if (elect) { // Send a master token. { MSG<GOT_MASTER_TOKEN> msg; msg.set_token("0"); MesosProcess<class T>::post(master, msg); } // Elect the master. { MSG<NEW_MASTER_DETECTED> msg; msg.set_pid(master); MesosProcess<class T>::post(master, msg); } } // Tell each pid about the master. foreach (const UPID& pid, pids) { MSG<NEW_MASTER_DETECTED> msg; msg.set_pid(master); MesosProcess<class T>::post(pid, msg); } } BasicMasterDetector::~BasicMasterDetector() {} #ifdef WITH_ZOOKEEPER ZooKeeperMasterDetector::ZooKeeperMasterDetector(const string& servers, const string& znode, const UPID& pid, bool contend, bool quiet) : servers(servers), znode(znode), pid(pid), contend(contend), reconnect(false) { // Set verbosity level for underlying ZooKeeper library logging. // TODO(benh): Put this in the C++ API. zoo_set_debug_level(quiet ? ZOO_LOG_LEVEL_ERROR : ZOO_LOG_LEVEL_DEBUG); // Start up the ZooKeeper connection! zk = new ZooKeeper(servers, 10000, this); } ZooKeeperMasterDetector::~ZooKeeperMasterDetector() { if (zk != NULL) { delete zk; } } void ZooKeeperMasterDetector::connected() { LOG(INFO) << "Master detector connected to ZooKeeper ..."; int ret; string result; static const string delimiter = "/"; // Assume the znode that was created does not end with a "/". CHECK(znode.at(znode.length() - 1) != '/'); // Create directory path znodes as necessary. size_t index = znode.find(delimiter, 0); while (index < string::npos) { // Get out the prefix to create. index = znode.find(delimiter, index + 1); string prefix = znode.substr(0, index); LOG(INFO) << "Trying to create znode '" << prefix << "' in ZooKeeper"; // Create the node (even if it already exists). ret = zk->create(prefix, "", ZOO_OPEN_ACL_UNSAFE, // ZOO_CREATOR_ALL_ACL, // needs authentication 0, &result); if (ret != ZOK && ret != ZNODEEXISTS) { fatal("failed to create ZooKeeper znode! (%s)", zk->error(ret)); } } // Wierdness in ZooKeeper timing, let's check that everything is created. ret = zk->get(znode, false, &result, NULL); if (ret != ZOK) { fatal("ZooKeeper not responding correctly (%s). " "Make sure ZooKeeper is running on: %s", zk->error(ret), servers.c_str()); } if (contend) { // We contend with the pid given in constructor. ret = zk->create(znode + "/", pid, ZOO_OPEN_ACL_UNSAFE, // ZOO_CREATOR_ALL_ACL, // needs authentication ZOO_SEQUENCE | ZOO_EPHEMERAL, &result); if (ret != ZOK) { fatal("ZooKeeper not responding correctly (%s). " "Make sure ZooKeeper is running on: %s", zk->error(ret), servers.c_str()); } setId(result); LOG(INFO) << "Created ephemeral/sequence:" << getId(); MSG<GOT_MASTER_TOKEN> msg; msg.set_token(getId()); MesosProcess<class T>::post(pid, msg); } // Now determine who the master is (it may be us). detectMaster(); } void ZooKeeperMasterDetector::reconnecting() { LOG(INFO) << "Master detector lost connection to ZooKeeper, " << "attempting to reconnect ..."; } void ZooKeeperMasterDetector::reconnected() { LOG(INFO) << "Master detector reconnected ..."; int ret; string result; static const string delimiter = "/"; if (contend) { // Contending for master, confirm our ephemeral sequence znode exists. ret = zk->get(znode + "/" + mySeq, false, &result, NULL); // We might no longer be the master! Commit suicide for now // (hoping another master is on standbye), but in the future // it would be nice if we could go back on standbye. if (ret == ZNONODE) { fatal("failed to reconnect to ZooKeeper quickly enough " "(our ephemeral sequence znode is gone), commiting suicide!"); } if (ret != ZOK) { fatal("ZooKeeper not responding correctly (%s). " "Make sure ZooKeeper is running on: %s", zk->error(ret), servers.c_str()); } // We are still the master! LOG(INFO) << "Still acting as master"; } else { // Reconnected, but maybe the master changed? detectMaster(); } } void ZooKeeperMasterDetector::expired() { LOG(WARNING) << "Master detector ZooKeeper session expired!"; CHECK(zk != NULL); delete zk; zk = new ZooKeeper(servers, 10000, this); } void ZooKeeperMasterDetector::updated(const string& path) { // A new master might have showed up and created a sequence // identifier or a master may have died, determine who the master is now! detectMaster(); } void ZooKeeperMasterDetector::process(ZooKeeper* zk, int type, int state, const string &path) { if ((state == ZOO_CONNECTED_STATE) && (type == ZOO_SESSION_EVENT)) { // Check if this is a reconnect. if (!reconnect) { // Initial connect. connected(); } else { // Reconnected. reconnected(); } } else if ((state == ZOO_CONNECTING_STATE) && (type == ZOO_SESSION_EVENT)) { // The client library automatically reconnects, taking into // account failed servers in the connection string, // appropriately handling the "herd effect", etc. reconnect = true; reconnecting(); } else if ((state == ZOO_EXPIRED_SESSION_STATE) && (type == ZOO_SESSION_EVENT)) { // Session expiration. Let the manager take care of it. expired(); // If this watcher is reused, the next connect won't be a reconnect. reconnect = false; } else if ((state == ZOO_CONNECTED_STATE) && (type == ZOO_CHILD_EVENT)) { updated(path); } else if ((state == ZOO_CONNECTED_STATE) && (type == ZOO_CHANGED_EVENT)) { updated(path); } else { LOG(WARNING) << "Unimplemented watch event: (state is " << state << " and type is " << type << ")"; } } void ZooKeeperMasterDetector::setId(const string& s) { string seq = s; // Converts "/path/to/znode/000000131" to "000000131". int pos; if ((pos = seq.find_last_of('/')) != string::npos) { mySeq = seq.erase(0, pos + 1); } else mySeq = ""; } string ZooKeeperMasterDetector::getId() { return mySeq; } void ZooKeeperMasterDetector::detectMaster() { vector<string> results; int ret = zk->getChildren(znode, true, &results); if (ret != ZOK) { LOG(ERROR) << "Master detector failed to get masters: " << zk->error(ret); } else { LOG(INFO) << "Master detector found " << results.size() << " registered masters"; } string masterSeq; long min = LONG_MAX; foreach (const string& result, results) { int i = lexical_cast<int>(result); if (i < min) { min = i; masterSeq = result; } } // No master present (lost or possibly hasn't come up yet). if (masterSeq.empty()) { process::post(pid, NO_MASTER_DETECTED); } else if (masterSeq != currentMasterSeq) { currentMasterSeq = masterSeq; currentMasterPID = lookupMasterPID(masterSeq); // While trying to get the master PID, master might have crashed, // so PID might be empty. if (currentMasterPID == UPID()) { process::post(pid, NO_MASTER_DETECTED); } else { MSG<NEW_MASTER_DETECTED> msg; msg.set_pid(currentMasterPID); MesosProcess<class T>::post(pid, msg); } } } UPID ZooKeeperMasterDetector::lookupMasterPID(const string& seq) const { CHECK(!seq.empty()); int ret; string result; ret = zk->get(znode + "/" + seq, false, &result, NULL); if (ret != ZOK) { LOG(ERROR) << "Master detector failed to fetch new master pid: " << zk->error(ret); } else { LOG(INFO) << "Master detector got new master pid: " << result; } return result; } #endif // WITH_ZOOKEEPER <commit_msg>Minor formating tweak.<commit_after>#include <process.hpp> #include <vector> #include <glog/logging.h> #include <boost/lexical_cast.hpp> #include "config/config.hpp" #include "common/fatal.hpp" #include "common/foreach.hpp" #ifdef WITH_ZOOKEEPER #include "common/zookeeper.hpp" #endif #include "messaging/messages.hpp" #include "detector.hpp" #include "url_processor.hpp" using namespace mesos; using namespace mesos::internal; using boost::lexical_cast; using process::Process; using process::UPID; using std::pair; using std::string; using std::vector; #ifdef WITH_ZOOKEEPER class ZooKeeperMasterDetector : public MasterDetector, public Watcher { public: /** * Uses ZooKeeper for both detecting masters and contending to be a * master. * * @param server comma separated list of server host:port pairs * * @param znode top-level "ZooKeeper node" (directory) to use * @param pid libprocess pid to send messages/updates to (and to * use for contending to be a master) * @param contend true if should contend to be master (not needed * for slaves and frameworks) * @param quiet verbosity logging level for undelying ZooKeeper library */ ZooKeeperMasterDetector(const string& servers, const string& znode, const UPID& pid, bool contend = false, bool quiet = false); virtual ~ZooKeeperMasterDetector(); /** * ZooKeeper watcher callback. */ virtual void process(ZooKeeper *zk, int type, int state, const string &path); private: void connected(); void reconnecting(); void reconnected(); void expired(); void updated(const string& path); /** * @param s sequence id */ void setId(const string &s); /** * @return current sequence id if contending to be a master */ string getId(); /** * Attempts to detect a master. */ void detectMaster(); /** * @param seq sequence id of a master * @return PID corresponding to a master */ UPID lookupMasterPID(const string &seq) const; const string servers; const string znode; const UPID pid; bool contend; bool reconnect; ZooKeeper *zk; // Our sequence string if contending to be a master. string mySeq; string currentMasterSeq; UPID currentMasterPID; }; #endif // WITH_ZOOKEEPER MasterDetector::~MasterDetector() {} MasterDetector* MasterDetector::create(const string &url, const UPID &pid, bool contend, bool quiet) { if (url == "") if (contend) { return new BasicMasterDetector(pid); } else { fatal("cannot use specified url to detect master"); } MasterDetector *detector = NULL; // Parse the url. pair<UrlProcessor::URLType, string> urlPair = UrlProcessor::process(url); switch (urlPair.first) { // ZooKeeper URL. case UrlProcessor::ZOO: { #ifdef WITH_ZOOKEEPER // TODO(benh): Consider actually using the chroot feature of // ZooKeeper, rather than just using it's syntax. size_t index = urlPair.second.find("/"); if (index == string::npos) { fatal("expecting chroot path for ZooKeeper"); } const string &servers = urlPair.second.substr(0, index); const string &znode = urlPair.second.substr(index); if (znode == "/") { fatal("expecting chroot path for ZooKeeper ('/' is not supported)"); } detector = new ZooKeeperMasterDetector(servers, znode, pid, contend, quiet); #else fatal("Cannot detect masters with 'zoo://', " "ZooKeeper is not supported in this build"); #endif // WITH_ZOOKEEPER break; } // Mesos URL or libprocess pid. case UrlProcessor::MESOS: case UrlProcessor::UNKNOWN: { if (contend) { // TODO(benh): Wierdnesses like this makes it seem like there // should be a separate elector and detector. In particular, // it doesn't make sense to pass a libprocess pid and attempt // to contend (at least not right now). fatal("cannot contend to be a master with specified url"); } else { UPID master(urlPair.second); if (!master) fatal("cannot use specified url to detect master"); detector = new BasicMasterDetector(master, pid); } break; } } return detector; } void MasterDetector::destroy(MasterDetector *detector) { if (detector != NULL) delete detector; } BasicMasterDetector::BasicMasterDetector(const UPID& _master) : master(_master) { // Send a master token. { MSG<GOT_MASTER_TOKEN> msg; msg.set_token("0"); MesosProcess<class T>::post(master, msg); } // Elect the master. { MSG<NEW_MASTER_DETECTED> msg; msg.set_pid(master); MesosProcess<class T>::post(master, msg); } } BasicMasterDetector::BasicMasterDetector(const UPID& _master, const UPID& pid, bool elect) : master(_master) { if (elect) { // Send a master token. { MSG<GOT_MASTER_TOKEN> msg; msg.set_token("0"); MesosProcess<class T>::post(master, msg); } // Elect the master. { MSG<NEW_MASTER_DETECTED> msg; msg.set_pid(master); MesosProcess<class T>::post(master, msg); } } // Tell the pid about the master. MSG<NEW_MASTER_DETECTED> msg; msg.set_pid(master); MesosProcess<class T>::post(pid, msg); } BasicMasterDetector::BasicMasterDetector(const UPID& _master, const vector<UPID>& pids, bool elect) : master(_master) { if (elect) { // Send a master token. { MSG<GOT_MASTER_TOKEN> msg; msg.set_token("0"); MesosProcess<class T>::post(master, msg); } // Elect the master. { MSG<NEW_MASTER_DETECTED> msg; msg.set_pid(master); MesosProcess<class T>::post(master, msg); } } // Tell each pid about the master. foreach (const UPID& pid, pids) { MSG<NEW_MASTER_DETECTED> msg; msg.set_pid(master); MesosProcess<class T>::post(pid, msg); } } BasicMasterDetector::~BasicMasterDetector() {} #ifdef WITH_ZOOKEEPER ZooKeeperMasterDetector::ZooKeeperMasterDetector(const string& servers, const string& znode, const UPID& pid, bool contend, bool quiet) : servers(servers), znode(znode), pid(pid), contend(contend), reconnect(false) { // Set verbosity level for underlying ZooKeeper library logging. // TODO(benh): Put this in the C++ API. zoo_set_debug_level(quiet ? ZOO_LOG_LEVEL_ERROR : ZOO_LOG_LEVEL_DEBUG); // Start up the ZooKeeper connection! zk = new ZooKeeper(servers, 10000, this); } ZooKeeperMasterDetector::~ZooKeeperMasterDetector() { if (zk != NULL) { delete zk; } } void ZooKeeperMasterDetector::connected() { LOG(INFO) << "Master detector connected to ZooKeeper ..."; int ret; string result; static const string delimiter = "/"; // Assume the znode that was created does not end with a "/". CHECK(znode.at(znode.length() - 1) != '/'); // Create directory path znodes as necessary. size_t index = znode.find(delimiter, 0); while (index < string::npos) { // Get out the prefix to create. index = znode.find(delimiter, index + 1); string prefix = znode.substr(0, index); LOG(INFO) << "Trying to create znode '" << prefix << "' in ZooKeeper"; // Create the node (even if it already exists). ret = zk->create(prefix, "", ZOO_OPEN_ACL_UNSAFE, // ZOO_CREATOR_ALL_ACL, // needs authentication 0, &result); if (ret != ZOK && ret != ZNODEEXISTS) { fatal("failed to create ZooKeeper znode! (%s)", zk->error(ret)); } } // Wierdness in ZooKeeper timing, let's check that everything is created. ret = zk->get(znode, false, &result, NULL); if (ret != ZOK) { fatal("ZooKeeper not responding correctly (%s). " "Make sure ZooKeeper is running on: %s", zk->error(ret), servers.c_str()); } if (contend) { // We contend with the pid given in constructor. ret = zk->create(znode + "/", pid, ZOO_OPEN_ACL_UNSAFE, // ZOO_CREATOR_ALL_ACL, // needs authentication ZOO_SEQUENCE | ZOO_EPHEMERAL, &result); if (ret != ZOK) { fatal("ZooKeeper not responding correctly (%s). " "Make sure ZooKeeper is running on: %s", zk->error(ret), servers.c_str()); } setId(result); LOG(INFO) << "Created ephemeral/sequence:" << getId(); MSG<GOT_MASTER_TOKEN> msg; msg.set_token(getId()); MesosProcess<class T>::post(pid, msg); } // Now determine who the master is (it may be us). detectMaster(); } void ZooKeeperMasterDetector::reconnecting() { LOG(INFO) << "Master detector lost connection to ZooKeeper, " << "attempting to reconnect ..."; } void ZooKeeperMasterDetector::reconnected() { LOG(INFO) << "Master detector reconnected ..."; int ret; string result; static const string delimiter = "/"; if (contend) { // Contending for master, confirm our ephemeral sequence znode exists. ret = zk->get(znode + "/" + mySeq, false, &result, NULL); // We might no longer be the master! Commit suicide for now // (hoping another master is on standbye), but in the future // it would be nice if we could go back on standbye. if (ret == ZNONODE) { fatal("failed to reconnect to ZooKeeper quickly enough " "(our ephemeral sequence znode is gone), commiting suicide!"); } if (ret != ZOK) { fatal("ZooKeeper not responding correctly (%s). " "Make sure ZooKeeper is running on: %s", zk->error(ret), servers.c_str()); } // We are still the master! LOG(INFO) << "Still acting as master"; } else { // Reconnected, but maybe the master changed? detectMaster(); } } void ZooKeeperMasterDetector::expired() { LOG(WARNING) << "Master detector ZooKeeper session expired!"; CHECK(zk != NULL); delete zk; zk = new ZooKeeper(servers, 10000, this); } void ZooKeeperMasterDetector::updated(const string& path) { // A new master might have showed up and created a sequence // identifier or a master may have died, determine who the master is now! detectMaster(); } void ZooKeeperMasterDetector::process(ZooKeeper* zk, int type, int state, const string& path) { if ((state == ZOO_CONNECTED_STATE) && (type == ZOO_SESSION_EVENT)) { // Check if this is a reconnect. if (!reconnect) { // Initial connect. connected(); } else { // Reconnected. reconnected(); } } else if ((state == ZOO_CONNECTING_STATE) && (type == ZOO_SESSION_EVENT)) { // The client library automatically reconnects, taking into // account failed servers in the connection string, // appropriately handling the "herd effect", etc. reconnect = true; reconnecting(); } else if ((state == ZOO_EXPIRED_SESSION_STATE) && (type == ZOO_SESSION_EVENT)) { // Session expiration. Let the manager take care of it. expired(); // If this watcher is reused, the next connect won't be a reconnect. reconnect = false; } else if ((state == ZOO_CONNECTED_STATE) && (type == ZOO_CHILD_EVENT)) { updated(path); } else if ((state == ZOO_CONNECTED_STATE) && (type == ZOO_CHANGED_EVENT)) { updated(path); } else { LOG(WARNING) << "Unimplemented watch event: (state is " << state << " and type is " << type << ")"; } } void ZooKeeperMasterDetector::setId(const string& s) { string seq = s; // Converts "/path/to/znode/000000131" to "000000131". int pos; if ((pos = seq.find_last_of('/')) != string::npos) { mySeq = seq.erase(0, pos + 1); } else mySeq = ""; } string ZooKeeperMasterDetector::getId() { return mySeq; } void ZooKeeperMasterDetector::detectMaster() { vector<string> results; int ret = zk->getChildren(znode, true, &results); if (ret != ZOK) { LOG(ERROR) << "Master detector failed to get masters: " << zk->error(ret); } else { LOG(INFO) << "Master detector found " << results.size() << " registered masters"; } string masterSeq; long min = LONG_MAX; foreach (const string& result, results) { int i = lexical_cast<int>(result); if (i < min) { min = i; masterSeq = result; } } // No master present (lost or possibly hasn't come up yet). if (masterSeq.empty()) { process::post(pid, NO_MASTER_DETECTED); } else if (masterSeq != currentMasterSeq) { currentMasterSeq = masterSeq; currentMasterPID = lookupMasterPID(masterSeq); // While trying to get the master PID, master might have crashed, // so PID might be empty. if (currentMasterPID == UPID()) { process::post(pid, NO_MASTER_DETECTED); } else { MSG<NEW_MASTER_DETECTED> msg; msg.set_pid(currentMasterPID); MesosProcess<class T>::post(pid, msg); } } } UPID ZooKeeperMasterDetector::lookupMasterPID(const string& seq) const { CHECK(!seq.empty()); int ret; string result; ret = zk->get(znode + "/" + seq, false, &result, NULL); if (ret != ZOK) { LOG(ERROR) << "Master detector failed to fetch new master pid: " << zk->error(ret); } else { LOG(INFO) << "Master detector got new master pid: " << result; } return result; } #endif // WITH_ZOOKEEPER <|endoftext|>
<commit_before>#include <cstring> #include <string> #include "halley/bytes/byte_serializer.h" #include "halley/text/halleystring.h" using namespace Halley; Serializer::Serializer(SerializerOptions options) : options(std::move(options)) , dryRun(true) {} Serializer::Serializer(gsl::span<gsl::byte> dst, SerializerOptions options) : options(std::move(options)) , dst(dst) , dryRun(false) {} Serializer& Serializer::operator<<(const std::string& str) { return *this << String(str); } Serializer& Serializer::operator<<(const String& str) { if (options.version == 0) { const uint32_t sz = static_cast<uint32_t>(str.size()); *this << sz; *this << gsl::as_bytes(gsl::span<const char>(str.c_str(), sz)); } else { if (options.stringToIndex) { auto idx = options.stringToIndex(str); if (idx) { // Found, store index with bit 0 set to 1 const uint64_t value = uint64_t(options.exhaustiveDictionary ? idx.value() : (size_t(1) | (idx.value() << 1))); *this << value; } else { if (options.exhaustiveDictionary) { throw Exception("String \"" + str + "\" not found in serialization dictionary, but it's marked as exhaustive.", HalleyExceptions::Utils); } // Not found, store it with bit 0 set to 0 const auto sz = str.size(); *this << (sz << 1); *this << gsl::as_bytes(gsl::span<const char>(str.c_str(), sz)); } } else { // No dictionary, just store it old style const auto sz = str.size(); *this << sz; *this << gsl::as_bytes(gsl::span<const char>(str.c_str(), sz)); } } return *this; } Serializer& Serializer::operator<<(const Path& path) { return (*this << path.string()); } Serializer& Serializer::operator<<(gsl::span<const gsl::byte> span) { if (!dryRun) { memcpy(dst.data() + size, span.data(), span.size_bytes()); } size += span.size_bytes(); return *this; } Serializer& Serializer::operator<<(const Bytes& bytes) { const uint32_t byteSize = static_cast<uint32_t>(bytes.size()); *this << byteSize; if (!dryRun) { memcpy(dst.data() + size, bytes.data(), bytes.size()); } size += bytes.size(); return *this; } void Serializer::serializeVariableInteger(uint64_t val, OptionalLite<bool> sign) { // 7 0sxxxxxx // 14 10sxxxxx xxxxxxxx // 21 110sxxxx xxxxxxxx xxxxxxxx // 28 1110sxxx xxxxxxxx xxxxxxxx xxxxxxxx // 35 11110sxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx // 42 111110sx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx // 49 1111110s xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx // 56 11111110 sxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx // 64 11111111 sxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx const size_t nBits = size_t(fastLog2Ceil(val)) + (sign ? 1 : 0); const size_t nBytes = std::min((nBits - 1) / 7, size_t(8)) + 1; // Total length of this sequence std::array<uint8_t, 9> buffer; buffer.fill(0); // Combine sign into value uint64_t toWrite = val; if (sign) { const size_t signPos = nBytes * 7 + (nBytes == 9 ? 0 : -1); // 9-byte version places it on pos 63, not 62 toWrite |= uint64_t(sign.value() ? 1 : 0) << signPos; } // Write header // To generate the mask, we get 9 - nBytes to see how many zeroes we need (8 at 1 byte, 7 at 2 bytes, etc), generate that many "1"s, then xor that with 255 (0b11111111) to flip those bits const size_t headerBits = std::min(nBytes, size_t(7)); buffer[0] = uint8_t(255) ^ (uint8_t((1 << (9 - headerBits)) - 1)); // Write bits size_t bitsAvailableOnByte = 8 - headerBits; size_t bitsToWrite = nBits; size_t curPos = 0; while (bitsToWrite > 0) { const size_t nBits = std::min(bitsToWrite, bitsAvailableOnByte); const uint64_t mask = (uint64_t(1) << bitsAvailableOnByte) - 1; buffer[curPos] |= toWrite & mask; toWrite >>= nBits; bitsAvailableOnByte = 8; curPos++; bitsToWrite -= nBits; } *this << gsl::as_bytes(gsl::span<const uint8_t>(buffer.data(), curPos)); } Deserializer::Deserializer(gsl::span<const gsl::byte> src, SerializerOptions options) : options(std::move(options)) , src(src) { } Deserializer::Deserializer(const Bytes& src, SerializerOptions options) : options(std::move(options)) , src(gsl::as_bytes(gsl::span<const Halley::Byte>(src))) { } Deserializer& Deserializer::operator>>(std::string& str) { String s; *this >> s; str = s.cppStr(); return *this; } Deserializer& Deserializer::operator>>(String& str) { auto readRawString = [&] (size_t size) { ensureSufficientBytesRemaining(size); str = String(reinterpret_cast<const char*>(src.data() + pos), size); pos += size; }; if (options.version == 0) { uint32_t size; *this >> size; readRawString(size); } else { uint64_t value; *this >> value; if (options.indexToString) { if (options.exhaustiveDictionary || (value & 0x1) != 0) { // Indexed string int shift = options.exhaustiveDictionary ? 0 : 1; str = options.indexToString(value >> shift); } else { // Not indexed readRawString(value >> 1); } } else { // No dictionary readRawString(value); } } return *this; } Deserializer& Deserializer::operator>>(Path& p) { std::string s; *this >> s; p = s; return *this; } Deserializer& Deserializer::operator>>(gsl::span<gsl::byte> span) { if (span.empty()) { return *this; } Expects(span.size_bytes() > 0); ensureSufficientBytesRemaining(size_t(span.size_bytes())); memcpy(span.data(), src.data() + pos, span.size_bytes()); pos += span.size_bytes(); return *this; } Deserializer& Deserializer::operator>>(Bytes& bytes) { uint32_t sz; *this >> sz; ensureSufficientBytesRemaining(sz); bytes.resize(sz); auto dst = gsl::as_writable_bytes(gsl::span<Byte>(bytes)); *this >> dst; return *this; } void Deserializer::setVersion(int v) { version = v; } int Deserializer::getVersion() const { return version; } void Deserializer::deserializeVariableInteger(uint64_t& val, bool& sign, bool isSigned) { // 7 0sxxxxxx // 14 10sxxxxx xxxxxxxx // 21 110sxxxx xxxxxxxx xxxxxxxx // 28 1110sxxx xxxxxxxx xxxxxxxx xxxxxxxx // 35 11110sxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx // 42 111110sx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx // 49 1111110s xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx // 56 11111110 sxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx // 64 11111111 sxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx // Read header uint8_t header; *this >> header; // Figure out which pattern we're dealing with size_t nBytes = 0; if ((header & 0x80) != 0x80) { nBytes = 1; } else if ((header & 0xC0) != 0xC0) { nBytes = 2; } else if ((header & 0xE0) != 0xE0) { nBytes = 3; } else if ((header & 0xF0) != 0xF0) { nBytes = 4; } else if ((header & 0xF8) != 0xF8) { nBytes = 5; } else if ((header & 0xFC) != 0xFC) { nBytes = 6; } else if ((header & 0xFE) != 0xFE) { nBytes = 7; } else if ((header & 0xFF) != 0xFF) { nBytes = 8; } else { nBytes = 9; } const size_t headerBits = std::min(nBytes, size_t(7)); // Read rest of the data std::array<uint8_t, 9> buffer; buffer[0] = header; if (nBytes > 1) { *this >> gsl::as_writable_bytes(gsl::span<uint8_t>(buffer.data(), nBytes - 1)); } // Convert to uint64_t size_t bitsAvailableOnByte = 8 - headerBits; size_t bitsRead = 0; uint64_t value = 0; for (size_t i = 0; i < nBytes; ++i) { const uint64_t byteMask = (uint64_t(1) << bitsAvailableOnByte) - 1; value |= (uint64_t(buffer[i]) & byteMask) << bitsRead; bitsRead += bitsAvailableOnByte; bitsAvailableOnByte = 8; } // Restore sign if (isSigned) { const size_t signPos = nBytes * 7 + (nBytes == 9 ? 0 : -1); // 9-byte version places it on pos 63, not 62 const uint64_t signMask = uint64_t(1) << signPos; sign = (value & signMask) != 0; value &= ~signMask; } else { sign = false; } // Output value val = value; } void Deserializer::ensureSufficientBytesRemaining(size_t bytes) { if (bytes > getBytesRemaining()) { throw Exception("Attempt to deserialize out of bounds", HalleyExceptions::File); } } size_t Deserializer::getBytesRemaining() const { if (pos > size_t(src.size_bytes())) { return 0; } else { return size_t(src.size_bytes()) - pos; } } <commit_msg>Remove more ambiguity.<commit_after>#include <cstring> #include <string> #include "halley/bytes/byte_serializer.h" #include "halley/text/halleystring.h" using namespace Halley; Serializer::Serializer(SerializerOptions options) : options(std::move(options)) , dryRun(true) {} Serializer::Serializer(gsl::span<gsl::byte> dst, SerializerOptions options) : options(std::move(options)) , dst(dst) , dryRun(false) {} Serializer& Serializer::operator<<(const std::string& str) { return *this << String(str); } Serializer& Serializer::operator<<(const String& str) { if (options.version == 0) { const uint32_t sz = static_cast<uint32_t>(str.size()); *this << sz; *this << gsl::as_bytes(gsl::span<const char>(str.c_str(), sz)); } else { if (options.stringToIndex) { auto idx = options.stringToIndex(str); if (idx) { // Found, store index with bit 0 set to 1 const uint64_t value = uint64_t(options.exhaustiveDictionary ? idx.value() : (size_t(1) | (idx.value() << 1))); *this << value; } else { if (options.exhaustiveDictionary) { throw Exception("String \"" + str + "\" not found in serialization dictionary, but it's marked as exhaustive.", HalleyExceptions::Utils); } // Not found, store it with bit 0 set to 0 const uint64_t sz = uint64_t(str.size()); *this << (sz << 1); *this << gsl::as_bytes(gsl::span<const char>(str.c_str(), sz)); } } else { // No dictionary, just store it old style const auto sz = str.size(); *this << sz; *this << gsl::as_bytes(gsl::span<const char>(str.c_str(), sz)); } } return *this; } Serializer& Serializer::operator<<(const Path& path) { return (*this << path.string()); } Serializer& Serializer::operator<<(gsl::span<const gsl::byte> span) { if (!dryRun) { memcpy(dst.data() + size, span.data(), span.size_bytes()); } size += span.size_bytes(); return *this; } Serializer& Serializer::operator<<(const Bytes& bytes) { const uint32_t byteSize = static_cast<uint32_t>(bytes.size()); *this << byteSize; if (!dryRun) { memcpy(dst.data() + size, bytes.data(), bytes.size()); } size += bytes.size(); return *this; } void Serializer::serializeVariableInteger(uint64_t val, OptionalLite<bool> sign) { // 7 0sxxxxxx // 14 10sxxxxx xxxxxxxx // 21 110sxxxx xxxxxxxx xxxxxxxx // 28 1110sxxx xxxxxxxx xxxxxxxx xxxxxxxx // 35 11110sxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx // 42 111110sx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx // 49 1111110s xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx // 56 11111110 sxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx // 64 11111111 sxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx const size_t nBits = size_t(fastLog2Ceil(val)) + (sign ? 1 : 0); const size_t nBytes = std::min((nBits - 1) / 7, size_t(8)) + 1; // Total length of this sequence std::array<uint8_t, 9> buffer; buffer.fill(0); // Combine sign into value uint64_t toWrite = val; if (sign) { const size_t signPos = nBytes * 7 + (nBytes == 9 ? 0 : -1); // 9-byte version places it on pos 63, not 62 toWrite |= uint64_t(sign.value() ? 1 : 0) << signPos; } // Write header // To generate the mask, we get 9 - nBytes to see how many zeroes we need (8 at 1 byte, 7 at 2 bytes, etc), generate that many "1"s, then xor that with 255 (0b11111111) to flip those bits const size_t headerBits = std::min(nBytes, size_t(7)); buffer[0] = uint8_t(255) ^ (uint8_t((1 << (9 - headerBits)) - 1)); // Write bits size_t bitsAvailableOnByte = 8 - headerBits; size_t bitsToWrite = nBits; size_t curPos = 0; while (bitsToWrite > 0) { const size_t nBits = std::min(bitsToWrite, bitsAvailableOnByte); const uint64_t mask = (uint64_t(1) << bitsAvailableOnByte) - 1; buffer[curPos] |= toWrite & mask; toWrite >>= nBits; bitsAvailableOnByte = 8; curPos++; bitsToWrite -= nBits; } *this << gsl::as_bytes(gsl::span<const uint8_t>(buffer.data(), curPos)); } Deserializer::Deserializer(gsl::span<const gsl::byte> src, SerializerOptions options) : options(std::move(options)) , src(src) { } Deserializer::Deserializer(const Bytes& src, SerializerOptions options) : options(std::move(options)) , src(gsl::as_bytes(gsl::span<const Halley::Byte>(src))) { } Deserializer& Deserializer::operator>>(std::string& str) { String s; *this >> s; str = s.cppStr(); return *this; } Deserializer& Deserializer::operator>>(String& str) { auto readRawString = [&] (size_t size) { ensureSufficientBytesRemaining(size); str = String(reinterpret_cast<const char*>(src.data() + pos), size); pos += size; }; if (options.version == 0) { uint32_t size; *this >> size; readRawString(size); } else { uint64_t value; *this >> value; if (options.indexToString) { if (options.exhaustiveDictionary || (value & 0x1) != 0) { // Indexed string int shift = options.exhaustiveDictionary ? 0 : 1; str = options.indexToString(value >> shift); } else { // Not indexed readRawString(value >> 1); } } else { // No dictionary readRawString(value); } } return *this; } Deserializer& Deserializer::operator>>(Path& p) { std::string s; *this >> s; p = s; return *this; } Deserializer& Deserializer::operator>>(gsl::span<gsl::byte> span) { if (span.empty()) { return *this; } Expects(span.size_bytes() > 0); ensureSufficientBytesRemaining(size_t(span.size_bytes())); memcpy(span.data(), src.data() + pos, span.size_bytes()); pos += span.size_bytes(); return *this; } Deserializer& Deserializer::operator>>(Bytes& bytes) { uint32_t sz; *this >> sz; ensureSufficientBytesRemaining(sz); bytes.resize(sz); auto dst = gsl::as_writable_bytes(gsl::span<Byte>(bytes)); *this >> dst; return *this; } void Deserializer::setVersion(int v) { version = v; } int Deserializer::getVersion() const { return version; } void Deserializer::deserializeVariableInteger(uint64_t& val, bool& sign, bool isSigned) { // 7 0sxxxxxx // 14 10sxxxxx xxxxxxxx // 21 110sxxxx xxxxxxxx xxxxxxxx // 28 1110sxxx xxxxxxxx xxxxxxxx xxxxxxxx // 35 11110sxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx // 42 111110sx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx // 49 1111110s xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx // 56 11111110 sxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx // 64 11111111 sxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx // Read header uint8_t header; *this >> header; // Figure out which pattern we're dealing with size_t nBytes = 0; if ((header & 0x80) != 0x80) { nBytes = 1; } else if ((header & 0xC0) != 0xC0) { nBytes = 2; } else if ((header & 0xE0) != 0xE0) { nBytes = 3; } else if ((header & 0xF0) != 0xF0) { nBytes = 4; } else if ((header & 0xF8) != 0xF8) { nBytes = 5; } else if ((header & 0xFC) != 0xFC) { nBytes = 6; } else if ((header & 0xFE) != 0xFE) { nBytes = 7; } else if ((header & 0xFF) != 0xFF) { nBytes = 8; } else { nBytes = 9; } const size_t headerBits = std::min(nBytes, size_t(7)); // Read rest of the data std::array<uint8_t, 9> buffer; buffer[0] = header; if (nBytes > 1) { *this >> gsl::as_writable_bytes(gsl::span<uint8_t>(buffer.data(), nBytes - 1)); } // Convert to uint64_t size_t bitsAvailableOnByte = 8 - headerBits; size_t bitsRead = 0; uint64_t value = 0; for (size_t i = 0; i < nBytes; ++i) { const uint64_t byteMask = (uint64_t(1) << bitsAvailableOnByte) - 1; value |= (uint64_t(buffer[i]) & byteMask) << bitsRead; bitsRead += bitsAvailableOnByte; bitsAvailableOnByte = 8; } // Restore sign if (isSigned) { const size_t signPos = nBytes * 7 + (nBytes == 9 ? 0 : -1); // 9-byte version places it on pos 63, not 62 const uint64_t signMask = uint64_t(1) << signPos; sign = (value & signMask) != 0; value &= ~signMask; } else { sign = false; } // Output value val = value; } void Deserializer::ensureSufficientBytesRemaining(size_t bytes) { if (bytes > getBytesRemaining()) { throw Exception("Attempt to deserialize out of bounds", HalleyExceptions::File); } } size_t Deserializer::getBytesRemaining() const { if (pos > size_t(src.size_bytes())) { return 0; } else { return size_t(src.size_bytes()) - pos; } } <|endoftext|>
<commit_before>#ifndef COZMO_COZMO_HPP_ #define COZMO_COZMO_HPP_ #include "dart/dart.hpp" using BodyNodePtr = dart::dynamics::BodyNodePtr; using SkeletonPtr = dart::dynamics::SkeletonPtr; using InverseKinematicsPtr = dart::dynamics::InverseKinematicsPtr; class Cozmo { private: SkeletonPtr cozmo; BodyNodePtr head; BodyNodePtr base; BodyNodePtr forklift; BodyNodePtr ghost_strut; BodyNodePtr lower_forklift_strut_left; BodyNodePtr lower_forklift_strut_right; BodyNodePtr upper_forklift_strut_left; BodyNodePtr upper_forklift_strut_right; InverseKinematicsPtr ik; BodyNodePtr makeRootBody(const SkeletonPtr& cozmo, const std::string& name, const std::string& mesh_dir); BodyNodePtr addBody(const SkeletonPtr& cozmo, BodyNodePtr parent, const std::string& name, const std::string& mesh_dir, Eigen::Vector3d transformFromParent, Eigen::Vector3d transformFromChild); SkeletonPtr createCozmo(const std::string& mesh_dir); void createIKModule(); public: Cozmo(const std::string& mesh_dir); void setPosition(double pos); SkeletonPtr getCozmoSkeleton() { return cozmo; }; }; #endif // COZMO_COZMO_HPP_ <commit_msg>Fixed issues<commit_after>#ifndef COZMO_COZMO_HPP_ #define COZMO_COZMO_HPP_ #include "dart/dart.hpp" namespace libcozmo { using BodyNodePtr = dart::dynamics::BodyNodePtr; using SkeletonPtr = dart::dynamics::SkeletonPtr; using InverseKinematicsPtr = dart::dynamics::InverseKinematicsPtr; class Cozmo { public: Cozmo(const std::string& mesh_dir); void setForkliftPosition(double pos); SkeletonPtr getCozmoSkeleton() { return cozmo; }; private: SkeletonPtr cozmo; BodyNodePtr head; BodyNodePtr base; BodyNodePtr forklift; BodyNodePtr ghost_strut; BodyNodePtr lower_forklift_strut_left; BodyNodePtr lower_forklift_strut_right; BodyNodePtr upper_forklift_strut_left; BodyNodePtr upper_forklift_strut_right; InverseKinematicsPtr ik; BodyNodePtr makeRootBody(const SkeletonPtr& cozmo, const std::string& name, const std::string& mesh_dir); BodyNodePtr addBody(const SkeletonPtr& cozmo, BodyNodePtr parent, const std::string& name, const std::string& mesh_dir, Eigen::Vector3d transformFromParent, Eigen::Vector3d transformFromChild); SkeletonPtr createCozmo(const std::string& mesh_dir); void createIKModule(); }; } #endif // COZMO_COZMO_HPP_ <|endoftext|>
<commit_before>/* * expressions.hpp * Author: Radu Cotescu ([email protected]) * * Part 2: Expression Templates * Write C++ templates which allow you to use types to represent arithmetic * expressions over the four basic operations (addition, subtraction, * multiplication and division), a single variable, and integer exponentiation: * (e.g. x^2+(x-2)^3/5). For the purposes of this assignment we refer to the * single variable as x. * * The types representing the expressions should contain a function named "eval" * that provides code for evaluating the expression. This function should accept * a double parameter that will be used as the value for the single variable x. */ #ifndef EXPRESSIONS_HPP_ #define EXPRESSIONS_HPP_ #include <functional> #include <typeinfo> #include <math.h> using namespace std; /* * Class defining Literals (scalars). */ class Literal { public: Literal(const double v) : value(v) {} /* * Returns the expression evaluation for a Literal. * @param dummy value to keep the function's consistency over the * expressions' implementation */ double eval(double) const { return value; } /* * Returns the derivative of a Literal. * @param dummy value to keep the function's consistency over the * expressions' implementation */ double der(double) const { return 0; } private: const double value; }; /* * Class defining double variables. */ class Variable { public: /* * Returns the expression evaluation for a Variable (its value). * @param d the value for which the variable should be evaluated */ double eval(double d) const { return d; } /* * Returns the derivative of a variable. * @param d dummy value to keep the function's consistency over the * expressions' implementation */ double der(double d) const { return 1; } }; /* * Expression traits used to convert constants of numerical types to objects * of type Literal, without changing expressions. */ template <class Expression> struct expressionTrait { typedef Expression expressionType; }; template <> struct expressionTrait<unsigned int> { typedef Literal expressionType; }; template <> struct expressionTrait<int> { typedef Literal expressionType; }; template <> struct expressionTrait<float> { typedef Literal expressionType; }; template <> struct expressionTrait<double> { typedef Literal expressionType; }; template <> struct expressionTrait<long> { typedef Literal expressionType; }; /* * Exponentiation function object class. */ template <class T> struct exponentiation : binary_function <T, T, T> { T operator() (const T& m, const T& n) const { return pow(m, n); } }; /* * Template defining a binary expression. */ template <class LHS, class RHS, class BinaryOperation> class BinaryExpression { public: BinaryExpression( LHS _lhs, RHS _rhs, BinaryOperation _operation = BinaryOperation() ) : lhs(_lhs), rhs(_rhs), operation(_operation) {} /* * Returns the result of the expression's operation for a specified value. * @param d the value for which the expression is evaluated */ double eval(double d) const { return operation(lhs.eval(d), rhs.eval(d)); } /* * Returns the derivative of the expression, evaluated for a certain value. * @param d the value at which the derivative of the expression is evaluated */ double der(double d) const { if (typeid(operation) == typeid(plus<double>)) { return (lhs.der(d) + rhs.der(d)); } else if (typeid(operation) == typeid(minus<double>)) { return (lhs.der(d) - rhs.der(d)); } else if (typeid(operation) == typeid(multiplies<double>)) { return (lhs.eval(d) * rhs.der(d) + lhs.der(d) * rhs.eval(d)); } else if (typeid(operation) == typeid(divides<double>)) { return ((rhs.eval(d) * lhs.der(d) - lhs.eval(d) * rhs.der(d)) / (rhs^2).eval(d)); } else if (typeid(operation) == typeid(exponentiation<double>)) { return (rhs.eval(d) * (lhs^(rhs.eval(d) - 1)).eval(d) * lhs.der(d)); } else { assert (false); return 0; } } private: typename expressionTrait<LHS>::expressionType lhs; typename expressionTrait<RHS>::expressionType rhs; BinaryOperation operation; }; /* * Operator + overloading. */ template <class LHS, class RHS> BinaryExpression<LHS, RHS, plus<double> > operator+(LHS lhs, RHS rhs) { return BinaryExpression<LHS, RHS, plus<double> >(lhs, rhs); } /* * Operator - overloading. */ template <class LHS, class RHS> BinaryExpression<LHS, RHS, minus<double> > operator-(LHS lhs, RHS rhs) { return BinaryExpression<LHS, RHS, minus<double> >(lhs, rhs); } /* * Operator * overloading. */ template <class LHS, class RHS> BinaryExpression<LHS, RHS, multiplies<double> > operator*(LHS lhs, RHS rhs) { return BinaryExpression<LHS, RHS, multiplies<double> >(lhs, rhs); } /* * Operator / overloading. */ template <class LHS, class RHS> BinaryExpression<LHS, RHS, divides<double> > operator/(LHS lhs, RHS rhs) { return BinaryExpression<LHS, RHS, divides<double> >(lhs, rhs); } /* * Template for defining the exponentiation operation. */ template <class LHS, class RHS> BinaryExpression<LHS, RHS, exponentiation<double> > operator^(LHS lhs, RHS rhs) { return BinaryExpression<LHS, RHS, exponentiation<double> >(lhs, rhs); } #endif /* EXPRESSIONS_HPP_ */ <commit_msg>added acknowledgements<commit_after>/* * expressions.hpp * Author: Radu Cotescu ([email protected]) * * The implementation is based on an article written by Angelika Langer and * published on her web site at the following address: * * http://www.angelikalanger.com/Articles/Cuj/ExpressionTemplates/ExpressionTemplates.htm * * Part 2: Expression Templates * Write C++ templates which allow you to use types to represent arithmetic * expressions over the four basic operations (addition, subtraction, * multiplication and division), a single variable, and integer exponentiation: * (e.g. x^2+(x-2)^3/5). For the purposes of this assignment we refer to the * single variable as x. * * The types representing the expressions should contain a function named "eval" * that provides code for evaluating the expression. This function should accept * a double parameter that will be used as the value for the single variable x. */ #ifndef EXPRESSIONS_HPP_ #define EXPRESSIONS_HPP_ #include <functional> #include <typeinfo> #include <math.h> using namespace std; /* * Class defining Literals (scalars). */ class Literal { public: Literal(const double v) : value(v) {} /* * Returns the expression evaluation for a Literal. * @param dummy value to keep the function's consistency over the * expressions' implementation */ double eval(double) const { return value; } /* * Returns the derivative of a Literal. * @param dummy value to keep the function's consistency over the * expressions' implementation */ double der(double) const { return 0; } private: const double value; }; /* * Class defining double variables. */ class Variable { public: /* * Returns the expression evaluation for a Variable (its value). * @param d the value for which the variable should be evaluated */ double eval(double d) const { return d; } /* * Returns the derivative of a variable. * @param d dummy value to keep the function's consistency over the * expressions' implementation */ double der(double d) const { return 1; } }; /* * Expression traits used to convert constants of numerical types to objects * of type Literal, without changing expressions. */ template <class Expression> struct expressionTrait { typedef Expression expressionType; }; template <> struct expressionTrait<unsigned int> { typedef Literal expressionType; }; template <> struct expressionTrait<int> { typedef Literal expressionType; }; template <> struct expressionTrait<float> { typedef Literal expressionType; }; template <> struct expressionTrait<double> { typedef Literal expressionType; }; template <> struct expressionTrait<long> { typedef Literal expressionType; }; /* * Exponentiation function object class. */ template <class T> struct exponentiation : binary_function <T, T, T> { T operator() (const T& m, const T& n) const { return pow(m, n); } }; /* * Template defining a binary expression. */ template <class LHS, class RHS, class BinaryOperation> class BinaryExpression { public: BinaryExpression( LHS _lhs, RHS _rhs, BinaryOperation _operation = BinaryOperation() ) : lhs(_lhs), rhs(_rhs), operation(_operation) {} /* * Returns the result of the expression's operation for a specified value. * @param d the value for which the expression is evaluated */ double eval(double d) const { return operation(lhs.eval(d), rhs.eval(d)); } /* * Returns the derivative of the expression, evaluated for a certain value. * @param d the value at which the derivative of the expression is evaluated */ double der(double d) const { if (typeid(operation) == typeid(plus<double>)) { return (lhs.der(d) + rhs.der(d)); } else if (typeid(operation) == typeid(minus<double>)) { return (lhs.der(d) - rhs.der(d)); } else if (typeid(operation) == typeid(multiplies<double>)) { return (lhs.eval(d) * rhs.der(d) + lhs.der(d) * rhs.eval(d)); } else if (typeid(operation) == typeid(divides<double>)) { return ((rhs.eval(d) * lhs.der(d) - lhs.eval(d) * rhs.der(d)) / (rhs^2).eval(d)); } else if (typeid(operation) == typeid(exponentiation<double>)) { return (rhs.eval(d) * (lhs^(rhs.eval(d) - 1)).eval(d) * lhs.der(d)); } else { assert (false); return 0; } } private: typename expressionTrait<LHS>::expressionType lhs; typename expressionTrait<RHS>::expressionType rhs; BinaryOperation operation; }; /* * Operator + overloading. */ template <class LHS, class RHS> BinaryExpression<LHS, RHS, plus<double> > operator+(LHS lhs, RHS rhs) { return BinaryExpression<LHS, RHS, plus<double> >(lhs, rhs); } /* * Operator - overloading. */ template <class LHS, class RHS> BinaryExpression<LHS, RHS, minus<double> > operator-(LHS lhs, RHS rhs) { return BinaryExpression<LHS, RHS, minus<double> >(lhs, rhs); } /* * Operator * overloading. */ template <class LHS, class RHS> BinaryExpression<LHS, RHS, multiplies<double> > operator*(LHS lhs, RHS rhs) { return BinaryExpression<LHS, RHS, multiplies<double> >(lhs, rhs); } /* * Operator / overloading. */ template <class LHS, class RHS> BinaryExpression<LHS, RHS, divides<double> > operator/(LHS lhs, RHS rhs) { return BinaryExpression<LHS, RHS, divides<double> >(lhs, rhs); } /* * Template for defining the exponentiation operation. */ template <class LHS, class RHS> BinaryExpression<LHS, RHS, exponentiation<double> > operator^(LHS lhs, RHS rhs) { return BinaryExpression<LHS, RHS, exponentiation<double> >(lhs, rhs); } #endif /* EXPRESSIONS_HPP_ */ <|endoftext|>
<commit_before>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield * * This application is open source and may be redistributed and/or modified * freely and without restriction, both in commericial and non commericial applications, * as long as this copyright notice is maintained. * * This application 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. */ #include <osgDB/ReadFile> #include <osgUtil/Optimizer> #include <osg/CoordinateSystemNode> /////////////////////////////////////////////////////////////////////////// // // osgProducer version (see osgViewer version in next section below) #include <osgProducer/Viewer> int main_osgProducer(osg::ArgumentParser& arguments) { // set up the usage document, in case we need to print out how to use this program. arguments.getApplicationUsage()->setApplicationName(arguments.getApplicationName()); arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the standard OpenSceneGraph example which loads and visualises 3d models."); arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ..."); arguments.getApplicationUsage()->addCommandLineOption("--image <filename>","Load an image and render it on a quad"); arguments.getApplicationUsage()->addCommandLineOption("--dem <filename>","Load an image/DEM and render it on a HeightField"); arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display command line parameters"); arguments.getApplicationUsage()->addCommandLineOption("--help-env","Display environmental variables available"); arguments.getApplicationUsage()->addCommandLineOption("--help-keys","Display keyboard & mouse bindings available"); arguments.getApplicationUsage()->addCommandLineOption("--help-all","Display all command line, env vars and keyboard & mouse bindings."); // construct the viewer. osgProducer::Viewer viewer(arguments); // set up the value with sensible default event handlers. viewer.setUpViewer(osgProducer::Viewer::STANDARD_SETTINGS); // get details on keyboard and mouse bindings used by the viewer. viewer.getUsage(*arguments.getApplicationUsage()); // if user request help write it out to cout. bool helpAll = arguments.read("--help-all"); unsigned int helpType = ((helpAll || arguments.read("-h") || arguments.read("--help"))? osg::ApplicationUsage::COMMAND_LINE_OPTION : 0 ) | ((helpAll || arguments.read("--help-env"))? osg::ApplicationUsage::ENVIRONMENTAL_VARIABLE : 0 ) | ((helpAll || arguments.read("--help-keys"))? osg::ApplicationUsage::KEYBOARD_MOUSE_BINDING : 0 ); if (helpType) { arguments.getApplicationUsage()->write(std::cout, helpType); return 1; } // report any errors if they have occurred when parsing the program arguments. if (arguments.errors()) { arguments.writeErrorMessages(std::cout); return 1; } if (arguments.argc()<=1) { arguments.getApplicationUsage()->write(std::cout,osg::ApplicationUsage::COMMAND_LINE_OPTION); return 1; } osg::Timer_t start_tick = osg::Timer::instance()->tick(); // read the scene from the list of file specified command line args. osg::ref_ptr<osg::Node> loadedModel = osgDB::readNodeFiles(arguments); // if no model has been successfully loaded report failure. if (!loadedModel) { std::cout << arguments.getApplicationName() <<": No data loaded" << std::endl; return 1; } // any option left unread are converted into errors to write out later. arguments.reportRemainingOptionsAsUnrecognized(); // report any errors if they have occurred when parsing the program arguments. if (arguments.errors()) { arguments.writeErrorMessages(std::cout); } osg::Timer_t end_tick = osg::Timer::instance()->tick(); std::cout << "Time to load = "<<osg::Timer::instance()->delta_s(start_tick,end_tick)<<std::endl; // optimize the scene graph, remove redundant nodes and state etc. osgUtil::Optimizer optimizer; optimizer.optimize(loadedModel.get()); // pass the loaded scene graph to the viewer. viewer.setSceneData(loadedModel.get()); // create the windows and run the threads. viewer.realize(); while( !viewer.done() ) { // wait for all cull and draw threads to complete. viewer.sync(); // update the scene by traversing it with the the update visitor which will // call all node update callbacks and animations. viewer.update(); // fire off the cull and draw traversals of the scene. viewer.frame(); } // wait for all cull and draw threads to complete. viewer.sync(); // run a clean up frame to delete all OpenGL objects. viewer.cleanup_frame(); // wait for all the clean up frame to complete. viewer.sync(); return 0; } /////////////////////////////////////////////////////////////////////////// // // osgViewer version #include <osgViewer/Viewer> #include <osgGA/TrackballManipulator> #include <osgGA/FlightManipulator> #include <osgGA/DriveManipulator> #include <osgGA/KeySwitchMatrixManipulator> #include <osgGA/StateSetManipulator> int main_osgViewer(osg::ArgumentParser& arguments) { osgViewer::Viewer viewer; // set up the camera manipulators. { osg::ref_ptr<osgGA::KeySwitchMatrixManipulator> keyswitchManipulator = new osgGA::KeySwitchMatrixManipulator; keyswitchManipulator->addMatrixManipulator( '1', "Trackball", new osgGA::TrackballManipulator() ); keyswitchManipulator->addMatrixManipulator( '2', "Flight", new osgGA::FlightManipulator() ); keyswitchManipulator->addMatrixManipulator( '3', "Drive", new osgGA::DriveManipulator() ); viewer.setCameraManipulator( keyswitchManipulator.get() ); } // add the state manipulator { osg::ref_ptr<osgGA::StateSetManipulator> statesetManipulator = new osgGA::StateSetManipulator; statesetManipulator->setStateSet(viewer.getCamera()->getOrCreateStateSet()); viewer.addEventHandler( statesetManipulator.get() ); } viewer.setSceneData( osgDB::readNodeFiles(arguments) ); return viewer.run(); } int main( int argc, char **argv ) { // use an ArgumentParser object to manage the program arguments. osg::ArgumentParser arguments(&argc,argv); if (arguments.read("--osgProducer")) { return main_osgProducer(arguments); } else { return main_osgViewer(arguments); } } <commit_msg>Added support for animation path manipulator to osgViewer path<commit_after>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield * * This application is open source and may be redistributed and/or modified * freely and without restriction, both in commericial and non commericial applications, * as long as this copyright notice is maintained. * * This application 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. */ #include <osgDB/ReadFile> #include <osgUtil/Optimizer> #include <osg/CoordinateSystemNode> /////////////////////////////////////////////////////////////////////////// // // osgProducer version (see osgViewer version in next section below) #include <osgProducer/Viewer> int main_osgProducer(osg::ArgumentParser& arguments) { // set up the usage document, in case we need to print out how to use this program. arguments.getApplicationUsage()->setApplicationName(arguments.getApplicationName()); arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the standard OpenSceneGraph example which loads and visualises 3d models."); arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ..."); arguments.getApplicationUsage()->addCommandLineOption("--image <filename>","Load an image and render it on a quad"); arguments.getApplicationUsage()->addCommandLineOption("--dem <filename>","Load an image/DEM and render it on a HeightField"); arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display command line parameters"); arguments.getApplicationUsage()->addCommandLineOption("--help-env","Display environmental variables available"); arguments.getApplicationUsage()->addCommandLineOption("--help-keys","Display keyboard & mouse bindings available"); arguments.getApplicationUsage()->addCommandLineOption("--help-all","Display all command line, env vars and keyboard & mouse bindings."); // construct the viewer. osgProducer::Viewer viewer(arguments); // set up the value with sensible default event handlers. viewer.setUpViewer(osgProducer::Viewer::STANDARD_SETTINGS); // get details on keyboard and mouse bindings used by the viewer. viewer.getUsage(*arguments.getApplicationUsage()); // if user request help write it out to cout. bool helpAll = arguments.read("--help-all"); unsigned int helpType = ((helpAll || arguments.read("-h") || arguments.read("--help"))? osg::ApplicationUsage::COMMAND_LINE_OPTION : 0 ) | ((helpAll || arguments.read("--help-env"))? osg::ApplicationUsage::ENVIRONMENTAL_VARIABLE : 0 ) | ((helpAll || arguments.read("--help-keys"))? osg::ApplicationUsage::KEYBOARD_MOUSE_BINDING : 0 ); if (helpType) { arguments.getApplicationUsage()->write(std::cout, helpType); return 1; } // report any errors if they have occurred when parsing the program arguments. if (arguments.errors()) { arguments.writeErrorMessages(std::cout); return 1; } if (arguments.argc()<=1) { arguments.getApplicationUsage()->write(std::cout,osg::ApplicationUsage::COMMAND_LINE_OPTION); return 1; } osg::Timer_t start_tick = osg::Timer::instance()->tick(); // read the scene from the list of file specified command line args. osg::ref_ptr<osg::Node> loadedModel = osgDB::readNodeFiles(arguments); // if no model has been successfully loaded report failure. if (!loadedModel) { std::cout << arguments.getApplicationName() <<": No data loaded" << std::endl; return 1; } // any option left unread are converted into errors to write out later. arguments.reportRemainingOptionsAsUnrecognized(); // report any errors if they have occurred when parsing the program arguments. if (arguments.errors()) { arguments.writeErrorMessages(std::cout); } osg::Timer_t end_tick = osg::Timer::instance()->tick(); std::cout << "Time to load = "<<osg::Timer::instance()->delta_s(start_tick,end_tick)<<std::endl; // optimize the scene graph, remove redundant nodes and state etc. osgUtil::Optimizer optimizer; optimizer.optimize(loadedModel.get()); // pass the loaded scene graph to the viewer. viewer.setSceneData(loadedModel.get()); // create the windows and run the threads. viewer.realize(); while( !viewer.done() ) { // wait for all cull and draw threads to complete. viewer.sync(); // update the scene by traversing it with the the update visitor which will // call all node update callbacks and animations. viewer.update(); // fire off the cull and draw traversals of the scene. viewer.frame(); } // wait for all cull and draw threads to complete. viewer.sync(); // run a clean up frame to delete all OpenGL objects. viewer.cleanup_frame(); // wait for all the clean up frame to complete. viewer.sync(); return 0; } /////////////////////////////////////////////////////////////////////////// // // osgViewer version #include <osgViewer/Viewer> #include <osgGA/TrackballManipulator> #include <osgGA/FlightManipulator> #include <osgGA/DriveManipulator> #include <osgGA/KeySwitchMatrixManipulator> #include <osgGA/StateSetManipulator> #include <osgGA/AnimationPathManipulator> int main_osgViewer(osg::ArgumentParser& arguments) { osgViewer::Viewer viewer; // set up the camera manipulators. { osg::ref_ptr<osgGA::KeySwitchMatrixManipulator> keyswitchManipulator = new osgGA::KeySwitchMatrixManipulator; keyswitchManipulator->addMatrixManipulator( '1', "Trackball", new osgGA::TrackballManipulator() ); keyswitchManipulator->addMatrixManipulator( '2', "Flight", new osgGA::FlightManipulator() ); keyswitchManipulator->addMatrixManipulator( '3', "Drive", new osgGA::DriveManipulator() ); std::string pathfile; osg::ref_ptr<osgGA::AnimationPathManipulator> apm = 0; while (arguments.read("-p",pathfile)) { osgGA::AnimationPathManipulator* apm = new osgGA::AnimationPathManipulator(pathfile); if (apm || !apm->valid()) { unsigned int num = keyswitchManipulator->getNumMatrixManipulators(); keyswitchManipulator->addMatrixManipulator( '4', "Path", apm ); keyswitchManipulator->selectMatrixManipulator(num); } } viewer.setCameraManipulator( keyswitchManipulator.get() ); } // add the state manipulator { osg::ref_ptr<osgGA::StateSetManipulator> statesetManipulator = new osgGA::StateSetManipulator; statesetManipulator->setStateSet(viewer.getCamera()->getOrCreateStateSet()); viewer.addEventHandler( statesetManipulator.get() ); } viewer.setSceneData( osgDB::readNodeFiles(arguments) ); return viewer.run(); } int main( int argc, char **argv ) { // use an ArgumentParser object to manage the program arguments. osg::ArgumentParser arguments(&argc,argv); if (arguments.read("--osgProducer")) { return main_osgProducer(arguments); } else { return main_osgViewer(arguments); } } <|endoftext|>
<commit_before>/*========================================================================= * * Copyright RTK 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. * *=========================================================================*/ #include "rtkmedian_ggo.h" #include "rtkGgoFunctions.h" #include "rtkThreeDCircularProjectionGeometryXMLFile.h" #include "rtkRayEllipsoidIntersectionImageFilter.h" #include "rtkMedianImageFilter.h" #include "rtkProjectionsReader.h" #include <itkImageFileReader.h> #include <itkImageFileWriter.h> #include <itkRegularExpressionSeriesFileNames.h> #include <itkTimeProbe.h> int main(int argc, char * argv[]) { GGO(rtkmedian, args_info); typedef unsigned short OutputPixelType; const unsigned int Dimension = 2; unsigned int medianWindow[2]; typedef itk::Image< OutputPixelType, Dimension > OutputImageType; // Input reader if(args_info.verbose_flag) std::cout << "Reading input volume " << args_info.input_arg << "..." << std::flush; itk::TimeProbe readerProbe; typedef itk::ImageFileReader< OutputImageType > ReaderType; ReaderType::Pointer reader = ReaderType::New(); reader->SetFileName( args_info.input_arg ); readerProbe.Start(); TRY_AND_EXIT_ON_ITK_EXCEPTION( reader->Update() ) readerProbe.Stop(); if(args_info.verbose_flag) std::cout << " done in " << readerProbe.GetMean() << ' ' << readerProbe.GetUnit() << '.' << std::endl; // Reading median Window if(args_info.median_given<Dimension) { for(unsigned int i=0; i<Dimension; i++) medianWindow[i] = args_info.median_arg[0]; } else for(unsigned int i=0; i<Dimension; i++) medianWindow[i] = args_info.median_arg[i]; // Median filter typedef rtk::MedianImageFilter MEDFilterType; MEDFilterType::Pointer median=MEDFilterType::New(); median->SetInput(reader->GetOutput()); median->SetMedianWindow(medianWindow); median->Update(); // Write typedef itk::ImageFileWriter< OutputImageType > WriterType; WriterType::Pointer writer = WriterType::New(); writer->SetFileName( args_info.output_arg ); writer->SetInput( median->GetOutput() ); if(args_info.verbose_flag) std::cout << "Projecting and writing... " << std::flush; TRY_AND_EXIT_ON_ITK_EXCEPTION( writer->Update() ); writer->SetFileName( "orginal.mha" ); writer->SetInput( reader->GetOutput() ); if(args_info.verbose_flag) std::cout << "Projecting and writing... " << std::flush; TRY_AND_EXIT_ON_ITK_EXCEPTION( writer->Update() ); return EXIT_SUCCESS; } <commit_msg>Added missing IO factories<commit_after>/*========================================================================= * * Copyright RTK 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. * *=========================================================================*/ #include "rtkmedian_ggo.h" #include "rtkGgoFunctions.h" #include "rtkThreeDCircularProjectionGeometryXMLFile.h" #include "rtkRayEllipsoidIntersectionImageFilter.h" #include "rtkMedianImageFilter.h" #include "rtkProjectionsReader.h" #include <itkImageFileReader.h> #include <itkImageFileWriter.h> #include <itkRegularExpressionSeriesFileNames.h> #include <itkTimeProbe.h> int main(int argc, char * argv[]) { GGO(rtkmedian, args_info); rtk::RegisterIOFactories(); typedef unsigned short OutputPixelType; const unsigned int Dimension = 2; unsigned int medianWindow[2]; typedef itk::Image< OutputPixelType, Dimension > OutputImageType; // Input reader if(args_info.verbose_flag) std::cout << "Reading input volume " << args_info.input_arg << "..." << std::flush; itk::TimeProbe readerProbe; typedef itk::ImageFileReader< OutputImageType > ReaderType; ReaderType::Pointer reader = ReaderType::New(); reader->SetFileName( args_info.input_arg ); readerProbe.Start(); TRY_AND_EXIT_ON_ITK_EXCEPTION( reader->Update() ) readerProbe.Stop(); if(args_info.verbose_flag) std::cout << " done in " << readerProbe.GetMean() << ' ' << readerProbe.GetUnit() << '.' << std::endl; // Reading median Window if(args_info.median_given<Dimension) { for(unsigned int i=0; i<Dimension; i++) medianWindow[i] = args_info.median_arg[0]; } else for(unsigned int i=0; i<Dimension; i++) medianWindow[i] = args_info.median_arg[i]; // Median filter typedef rtk::MedianImageFilter MEDFilterType; MEDFilterType::Pointer median=MEDFilterType::New(); median->SetInput(reader->GetOutput()); median->SetMedianWindow(medianWindow); median->Update(); // Write typedef itk::ImageFileWriter< OutputImageType > WriterType; WriterType::Pointer writer = WriterType::New(); writer->SetFileName( args_info.output_arg ); writer->SetInput( median->GetOutput() ); if(args_info.verbose_flag) std::cout << "Projecting and writing... " << std::flush; TRY_AND_EXIT_ON_ITK_EXCEPTION( writer->Update() ); writer->SetFileName( "orginal.mha" ); writer->SetInput( reader->GetOutput() ); if(args_info.verbose_flag) std::cout << "Projecting and writing... " << std::flush; TRY_AND_EXIT_ON_ITK_EXCEPTION( writer->Update() ); return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/**********************************************************************/ /* Copyright 2014 RCF */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, */ /* software distributed under the License is distributed on an */ /* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, */ /* either express or implied. */ /* See the License for the specific language governing permissions */ /* and limitations under the License. */ /**********************************************************************/ #ifndef TCC_GRAPH_STREE_DEFINED #define TCC_GRAPH_STREE_DEFINED // Default libraries #include <vector> #include <utility> #include <iostream> #include <initializer_list> // Libraries #include "Arc.tcc" #include "Cycle.tcc" #include "Vertex.tcc" namespace graph { template< typename Vertex = graph::Vertex<>, typename Arc = graph::Arc<Vertex>, typename Cycle = graph::Cycle<Arc> >class STree { public: typedef Vertex vertex_type; typedef Arc arc_type; typedef typename Vertex::id_type vertex_id; private: std::vector<vertex_id> parnt; std::vector<int> depth; vertex_id radix; int max_depth; public: STree(size_t num_vertices, vertex_id radix, std::initializer_list<Arc> arcs) : parnt(num_vertices), depth(num_vertices,-1), radix{}, max_depth{-1} { for(const Arc& arc : arcs) { if(depth[arc.beg] == -1 && depth[arc.end] != -1) { radix = arc.beg; parnt[arc.beg] = arc.end; depth[arc.beg] = depth[arc.end]+1; } else if(depth[arc.beg] != -1 && depth[arc.end] == -1) { parnt[arc.end] = arc.beg; depth[arc.end] = depth[arc.beg]+1; } else if(depth[arc.beg] == -1 && depth[arc.end] == -1) { parnt[arc.end] = arc.beg; depth[arc.beg] = 0; depth[arc.end] = 1; } for(int d : depth) if(d > max_depth) max_depth = d; } } Cycle fundamental_cycle(const Arc& inserted) { Cycle cycle { inserted }; vertex_id l { inserted.beg }; vertex_id r { inserted.end }; int depth = depth[inserted.beg()]; if(depth[inserted.end()] > depth) depth = depth[inserted.beg()]; l = inserted.beg; r = inserted.end; // Intermediate arcs // (when with different depths) for(vertex_id lp = parnt[l]; depth[l] != depth; l = lp) cycle.push_back( Arc{lp,l} ); for(vertex_id rp = parnt[r]; depth[r] != depth; r = rp) cycle.push_front( Arc{rp,r} ); while(r != l) { // Intermediate arcs // (when with the same depth) vertex_id lp = parnt[l]; vertex_id rp = parnt[r]; cycle.push_back ( Arc{lp,l} ); cycle.push_front( Arc{rp,r} ); r = rp; l = lp; } // Last arc cycle.push_back({parnt[l],l}); return cycle; } friend std::ostream& operator<<(std::ostream& os, const STree& st) { for(int i = 0; i <= st.max_depth; i++) { for(int d : st.depth) if(d == i) os << d << " "; os << std::endl; } return os; } }; } #endif <commit_msg>Correcting internal references<commit_after>/**********************************************************************/ /* Copyright 2014 RCF */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, */ /* software distributed under the License is distributed on an */ /* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, */ /* either express or implied. */ /* See the License for the specific language governing permissions */ /* and limitations under the License. */ /**********************************************************************/ #ifndef TCC_GRAPH_STREE_DEFINED #define TCC_GRAPH_STREE_DEFINED // Default libraries #include <vector> #include <utility> #include <iostream> #include <initializer_list> // Libraries #include "Arc.tcc" #include "Cycle.tcc" #include "Vertex.tcc" namespace graph { template< typename Graph, typename Cycle = graph::Cycle<typename Graph::arc_type> >class STree { public: typedef typename Graph::arc_type arc_type; typedef typename Graph::arc_list arc_list; typedef typename Graph::vertex_id vertex_id; typedef typename Graph::vertex_type vertex_type; private: Graph* base; std::vector<vertex_id> parnt; std::vector<int> depth; vertex_id radix; int max_depth; public: STree(Graph& base, size_t num_vertices, vertex_id radix, arc_list arcs) : base{&base}, parnt(num_vertices), depth(num_vertices,-1), radix{}, max_depth{-1} { for(const arc_type& arc : arcs) { if(depth[arc.beg] == -1 && depth[arc.end] != -1) { radix = arc.beg; parnt[arc.beg] = arc.end; depth[arc.beg] = depth[arc.end]+1; } else if(depth[arc.beg] != -1 && depth[arc.end] == -1) { parnt[arc.end] = arc.beg; depth[arc.end] = depth[arc.beg]+1; } else if(depth[arc.beg] == -1 && depth[arc.end] == -1) { parnt[arc.end] = arc.beg; depth[arc.beg] = 0; depth[arc.end] = 1; } for(int d : depth) if(d > max_depth) max_depth = d; } } Cycle fundamental_cycle(const arc_type& inserted) { Cycle cycle { inserted }; vertex_id l { inserted.beg }; vertex_id r { inserted.end }; int depth = depth[inserted.beg()]; if(depth[inserted.end()] > depth) depth = depth[inserted.beg()]; l = inserted.beg; r = inserted.end; // Intermediate arcs // (when with different depths) for(vertex_id lp = parnt[l]; depth[l] != depth; l = lp) cycle.push_back( arc_type{lp,l} ); for(vertex_id rp = parnt[r]; depth[r] != depth; r = rp) cycle.push_front( arc_type{rp,r} ); while(r != l) { // Intermediate arcs // (when with the same depth) vertex_id lp = parnt[l]; vertex_id rp = parnt[r]; cycle.push_back ( arc_type{lp,l} ); cycle.push_front( arc_type{rp,r} ); r = rp; l = lp; } // Last arc cycle.push_back({parnt[l],l}); return cycle; } friend std::ostream& operator<<(std::ostream& os, const STree& st) { for(int i = 0; i <= st.max_depth; i++) { for(int d : st.depth) if(d == i) os << d << " "; os << std::endl; } return os; } }; } #endif <|endoftext|>
<commit_before>#define CATCH_CONFIG_MAIN // This tells Catch to provide a main() - only do this in one cpp file #include "catch.hpp" #include "audiobuffer.h" TEST_CASE( "RingBuffer", "[AudioBuffer]" ) { SECTION("Allocation") { AudioBuffer buffer; buffer.allocateRingbuffers(1024); REQUIRE(buffer.numberOfChannels() == 0); REQUIRE(buffer.ringBufferContainer.size() == 0); REQUIRE(buffer.ringBufferSize == 1024); } SECTION("Channels") { AudioBuffer buffer; QList<unsigned int> channels({1,5}); buffer.allocateRingbuffers(1024, channels); REQUIRE(buffer.numberOfChannels() == channels.size()); REQUIRE(buffer.ringBufferContainer.size() == channels.size()); REQUIRE(buffer.activeChannelId(1) == channels.at(1)); REQUIRE(buffer.activeChannelId(2) == 2); } SECTION("Rotation") { AudioBuffer buffer; QList<unsigned int> channels({0}); buffer.allocateRingbuffers(10, channels); // Initialize buffer with values for( unsigned int ch=0; ch<buffer.numberOfChannels(); ch++ ) { QVector<double> *frames = &buffer.ringBufferContainer[ch]; for( unsigned int i=0; i<buffer.ringBufferSize; i++ ) { (*frames)[i] = i; } } // Test buffer initialization foreach (QVector<double> frames, buffer.ringBufferContainer) { //for( int i=0; i<frames.size(); i++ ) { std::cerr << frames.at(i) << ", "; } REQUIRE(frames.at(3) == 3); } // Rotate and test frames unsigned int delta = 5; REQUIRE(buffer.rotateRingbuffers(delta) == true ); foreach (QVector<double> frames, buffer.ringBufferContainer) { //for( int i=0; i<frames.size(); i++ ) { std::cerr << frames.at(i) << ", "; } REQUIRE(frames.at(delta) == 0); } REQUIRE(buffer.rotateRingbuffers(buffer.ringBufferSize+1) == false); } } <commit_msg>Restructured audiobuffer test cases<commit_after>#define CATCH_CONFIG_MAIN // This tells Catch to provide a main() - only do this in one cpp file #include "catch.hpp" #include "audiobuffer.h" TEST_CASE( "RingBuffer", "[AudioBuffer]" ) { AudioBuffer* buffer = new AudioBuffer(); SECTION("Allocation") { buffer->allocateRingbuffers(1024); REQUIRE(buffer->numberOfChannels() == 0); REQUIRE(buffer->ringBufferContainer.size() == 0); REQUIRE(buffer->ringBufferSize == 1024); } SECTION("Channels") { QList<unsigned int> channels({1,5}); buffer->allocateRingbuffers(1024, channels); REQUIRE(buffer->numberOfChannels() == channels.size()); REQUIRE(buffer->ringBufferContainer.size() == channels.size()); REQUIRE(buffer->activeChannelId(1) == channels.at(1)); REQUIRE(buffer->activeChannelId(2) == 2); } SECTION("Rotation") { QList<unsigned int> channels({0}); buffer->allocateRingbuffers(10, channels); // Initialize buffer with values for( unsigned int ch=0; ch<buffer->numberOfChannels(); ch++ ) { QVector<double> *frames = &buffer->ringBufferContainer[ch]; for( unsigned int i=0; i<buffer->ringBufferSize; i++ ) { (*frames)[i] = i; } } // Test buffer initialization foreach (QVector<double> frames, buffer->ringBufferContainer) { //for( int i=0; i<frames.size(); i++ ) { std::cerr << frames.at(i) << ", "; } REQUIRE(frames.at(3) == 3); } // Rotate and test frames unsigned int delta = 5; REQUIRE(buffer->rotateRingbuffers(delta) == true ); foreach (QVector<double> frames, buffer->ringBufferContainer) { //for( int i=0; i<frames.size(); i++ ) { std::cerr << frames.at(i) << ", "; } REQUIRE(frames.at(delta) == 0); } REQUIRE(buffer->rotateRingbuffers(buffer->ringBufferSize+1) == false); } delete buffer; } <|endoftext|>
<commit_before>// // inpal_prime.hpp // inpalprime // // Created by bryan triana on 7/13/16. // Copyright © 2016 Inverse Palindrome. All rights reserved. // #ifndef inpal_prime_hpp #define inpal_prime_hpp #include <vector> #include <string> namespace inpal { class prime { public: static std::size_t max_prime(std::size_t range); static std::size_t prime_count(std::size_t range); static double prime_density(double range); static bool prime_test(std::size_t num); static bool twin_test(std::size_t num); static bool cousin_test(std::size_t num); static bool sexy_test(std::size_t num); static std::size_t max_palprime(std::size_t range); static std::size_t max_factor(std::size_t num); static std::size_t count_factors(std::size_t num); private: static std::vector<bool> prime_sieve(std::size_t range); static std::vector<std::size_t> factorizer(std::size_t num); static bool pal_test(std::size_t num); }; } #endif /* inpal_prime_hpp */ <commit_msg>Update inpal_prime.hpp<commit_after>// // inpal_prime.hpp // InversePalindrome // // Created by Bryan Triana on 7/13/16. // Copyright © 2016 Inverse Palindrome. All rights reserved. // #ifndef inpal_prime_hpp #define inpal_prime_hpp #include <vector> #include <string> namespace inpal { class prime { public: static std::size_t max_prime(std::size_t range); static std::size_t prime_count(std::size_t range); static double prime_density(double range); static bool prime_test(std::size_t num); static bool twin_test(std::size_t num); static bool cousin_test(std::size_t num); static bool sexy_test(std::size_t num); static std::size_t max_palprime(std::size_t range); static std::size_t max_factor(std::size_t num); static std::size_t count_factors(std::size_t num); private: static std::vector<bool> prime_sieve(std::size_t range); static std::vector<std::size_t> factorizer(std::size_t num); static bool pal_test(std::size_t num); }; } #endif /* inpal_prime_hpp */ <|endoftext|>
<commit_before>/* +------------------------------------------------------------------------+ | Mobile Robot Programming Toolkit (MRPT) | | https://www.mrpt.org/ | | | | Copyright (c) 2005-2020, Individual contributors, see AUTHORS file | | See: https://www.mrpt.org/Authors - All rights reserved. | | Released under BSD License. See: https://www.mrpt.org/License | +------------------------------------------------------------------------+ */ #if defined(__GNUC__) // Needed for ffmpeg headers. Only allowed here when not // using precomp. headers #define __STDC_CONSTANT_MACROS // Needed for having "UINT64_C" and so #endif #include <mrpt/config.h> #include "hwdrivers-precomp.h" // Precompiled headers #if MRPT_HAS_FFMPEG extern "C" { #define _MSC_STDINT_H_ // We already have pstdint.h in MRPT #include <libavcodec/avcodec.h> #include <libavformat/avformat.h> #include <libavutil/imgutils.h> #include <libswscale/swscale.h> } #endif #include <mrpt/hwdrivers/CFFMPEG_InputStream.h> using namespace mrpt; using namespace mrpt::hwdrivers; // JLBC: This file takes portions of code from the example // "avcodec_sample.0.4.9.cpp" // // Minimum ffmpeg libs versions we want to support: // Ubuntu 16.04 LTS: avcodec 56.60.100, avutil 54.31.100, avformat 56.40.101 // Ubuntu 20.04 LTS: avcodec 58.54.100, avutil 56.31.100, avformat 58.29.100 // #if MRPT_HAS_FFMPEG namespace mrpt::hwdrivers { // All context for ffmpeg: struct TFFMPEGContext { AVFormatContext* pFormatCtx{nullptr}; int videoStream{0}; #if LIBAVFORMAT_VERSION_MAJOR >= 58 AVCodecParameters* pCodecPars{nullptr}; #endif AVCodec* pCodec{nullptr}; AVCodecContext* pCodecCtx{nullptr}; AVFrame* pFrame{nullptr}; AVFrame* pFrameRGB{nullptr}; SwsContext* img_convert_ctx{nullptr}; std::vector<uint8_t> buffer; }; } // namespace mrpt::hwdrivers #endif struct CFFMPEG_InputStream::Impl { #if MRPT_HAS_FFMPEG TFFMPEGContext m_state; #endif }; /* -------------------------------------------------------- Ctor -------------------------------------------------------- */ CFFMPEG_InputStream::CFFMPEG_InputStream() #if MRPT_HAS_FFMPEG : m_impl(mrpt::make_impl<CFFMPEG_InputStream::Impl>()) { // av_register_all() not needed in ffmpeg >=4.0 #if LIBAVFORMAT_VERSION_MAJOR < 58 // Register all formats and codecs av_register_all(); #endif } #else { THROW_EXCEPTION("MRPT has been compiled without FFMPEG libraries."); } #endif /* -------------------------------------------------------- Dtor -------------------------------------------------------- */ CFFMPEG_InputStream::~CFFMPEG_InputStream() { #if MRPT_HAS_FFMPEG // Close everything: this->close(); #endif } /* -------------------------------------------------------- isOpen -------------------------------------------------------- */ bool CFFMPEG_InputStream::isOpen() const { #if MRPT_HAS_FFMPEG const TFFMPEGContext* ctx = &m_impl->m_state; return ctx->pFormatCtx != nullptr; #else return false; #endif } /* -------------------------------------------------------- openURL -------------------------------------------------------- */ bool CFFMPEG_InputStream::openURL( const std::string& url, bool grab_as_grayscale, bool verbose) { #if MRPT_HAS_FFMPEG this->close(); // Close first TFFMPEGContext* ctx = &m_impl->m_state; this->m_url = url; this->m_grab_as_grayscale = grab_as_grayscale; // Open video file if (avformat_open_input(&ctx->pFormatCtx, url.c_str(), nullptr, nullptr) != 0) { ctx->pFormatCtx = nullptr; std::cerr << "[CFFMPEG_InputStream::openURL] Cannot open video: " << url << std::endl; return false; } // Retrieve stream information if (avformat_find_stream_info(ctx->pFormatCtx, nullptr) < 0) { std::cerr << "[CFFMPEG_InputStream::openURL] Couldn't find stream " "information: " << url << std::endl; return false; } // Dump information about file onto standard error if (verbose) { av_dump_format(ctx->pFormatCtx, 0, url.c_str(), false); } // Find the first video stream ctx->videoStream = -1; for (unsigned int i = 0; i < ctx->pFormatCtx->nb_streams; i++) { #if LIBAVFORMAT_VERSION_MAJOR >= 58 auto codecType = ctx->pFormatCtx->streams[i]->codecpar->codec_type; #else auto codecType = ctx->pFormatCtx->streams[i]->codec->codec_type; #endif if (codecType == AVMEDIA_TYPE_VIDEO) { ctx->videoStream = (int)i; break; } } if (ctx->videoStream == -1) { std::cerr << "[CFFMPEG_InputStream::openURL] Didn't find a video stream: " << url << std::endl; return false; } // Get a pointer to the codec context for the video stream #if LIBAVFORMAT_VERSION_MAJOR >= 58 ctx->pCodecPars = ctx->pFormatCtx->streams[ctx->videoStream]->codecpar; // Find the decoder for the video stream ctx->pCodec = avcodec_find_decoder(ctx->pCodecPars->codec_id); #else ctx->pCodecCtx = ctx->pFormatCtx->streams[ctx->videoStream]->codec; // Find the decoder for the video stream ctx->pCodec = avcodec_find_decoder(ctx->pCodecCtx->codec_id); #endif if (ctx->pCodec == nullptr) { std::cerr << "[CFFMPEG_InputStream::openURL] Codec not found: " << url << std::endl; return false; } #if LIBAVFORMAT_VERSION_MAJOR >= 58 ctx->pCodecCtx = avcodec_alloc_context3(nullptr /*ctx->pCodec*/); if (!ctx->pCodecCtx) { std::cerr << "[CFFMPEG_InputStream::openURL] Cannot alloc avcodec " "context for: " << url << std::endl; return false; } // Add stream parameters to context if (avcodec_parameters_to_context( ctx->pCodecCtx, ctx->pFormatCtx->streams[ctx->videoStream]->codecpar)) { std::cerr << "[CFFMPEG_InputStream::openURL] Failed " "avcodec_parameters_to_context() for: " << url << std::endl; return false; } // Make sure that Codecs are identical or avcodec_open2 fails. ctx->pCodecCtx->codec_id = ctx->pCodec->id; #endif // Open codec if (avcodec_open2(ctx->pCodecCtx, ctx->pCodec, nullptr) < 0) { std::cerr << "[CFFMPEG_InputStream::openURL] avcodec_open2() failed for: " << url << std::endl; return false; } // Allocate video frame ctx->pFrame = av_frame_alloc(); // Allocate an AVFrame structure ctx->pFrameRGB = av_frame_alloc(); if (ctx->pFrameRGB == nullptr || ctx->pFrame == nullptr) { std::cerr << "[CFFMPEG_InputStream::openURL] Could not alloc memory " "for frame buffers: " << url << std::endl; return false; } // Determine required buffer size and allocate buffer #if LIBAVFORMAT_VERSION_MAJOR >= 58 const auto width = ctx->pCodecPars->width, height = ctx->pCodecPars->height; #else const auto width = ctx->pCodecCtx->width, height = ctx->pCodecCtx->height; #endif int numBytes = av_image_get_buffer_size( m_grab_as_grayscale ? AV_PIX_FMT_GRAY8 : AV_PIX_FMT_BGR24, width, height, 1); if (numBytes < 0) { std::cerr << "[CFFMPEG_InputStream::openURL] av_image_get_buffer_size " "error code: " << numBytes << std::endl; return false; } ctx->buffer.resize(numBytes); // Assign appropriate parts of buffer to image planes in pFrameRGB av_image_fill_arrays( ctx->pFrameRGB->data, ctx->pFrameRGB->linesize, &ctx->buffer[0], m_grab_as_grayscale ? AV_PIX_FMT_GRAY8 : AV_PIX_FMT_BGR24, width, height, 1); return true; // OK. #else return false; #endif } /* -------------------------------------------------------- close -------------------------------------------------------- */ void CFFMPEG_InputStream::close() { #if MRPT_HAS_FFMPEG if (!this->isOpen()) return; TFFMPEGContext* ctx = &m_impl->m_state; // Close the codec if (ctx->pCodecCtx) { avcodec_close(ctx->pCodecCtx); ctx->pCodecCtx = nullptr; } // Close the video file if (ctx->pFormatCtx) { avformat_close_input(&ctx->pFormatCtx); ctx->pFormatCtx = nullptr; } // Free frames memory: ctx->buffer.clear(); if (ctx->pFrameRGB) { av_frame_free(&ctx->pFrameRGB); ctx->pFrameRGB = nullptr; } if (ctx->pFrame) { av_frame_free(&ctx->pFrame); ctx->pFrame = nullptr; } if (ctx->img_convert_ctx) { sws_freeContext(ctx->img_convert_ctx); ctx->img_convert_ctx = nullptr; } #endif } /* -------------------------------------------------------- retrieveFrame -------------------------------------------------------- */ bool CFFMPEG_InputStream::retrieveFrame(mrpt::img::CImage& out_img) { #if MRPT_HAS_FFMPEG if (!this->isOpen()) return false; TFFMPEGContext* ctx = &m_impl->m_state; AVPacket packet; #if LIBAVFORMAT_VERSION_MAJOR < 58 int frameFinished; #endif #if LIBAVFORMAT_VERSION_MAJOR >= 58 const auto width = ctx->pCodecPars->width, height = ctx->pCodecPars->height; #else const auto width = ctx->pCodecCtx->width, height = ctx->pCodecCtx->height; #endif while (av_read_frame(ctx->pFormatCtx, &packet) >= 0) { // Is this a packet from the video stream? if (packet.stream_index != ctx->videoStream) { av_packet_unref(&packet); continue; } // Decode video frame #if LIBAVFORMAT_VERSION_MAJOR >= 58 int ret = avcodec_send_packet(ctx->pCodecCtx, &packet); if (ret < 0) { std::cerr << "[CFFMPEG_InputStream] avcodec_send_packet error code=" << ret << std::endl; return false; } // while (ret >= 0) ret = avcodec_receive_frame(ctx->pCodecCtx, ctx->pFrame); if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) return false; else if (ret < 0) { std::cerr << "[CFFMPEG_InputStream] avcodec_receive_frame " "error code=" << ret << std::endl; return false; } #else avcodec_decode_video2( ctx->pCodecCtx, ctx->pFrame, &frameFinished, &packet); if (!frameFinished) { // Free the packet that was allocated by av_read_frame av_packet_unref(&packet); continue; } #endif // Convert the image from its native format to RGB: ctx->img_convert_ctx = sws_getCachedContext( ctx->img_convert_ctx, width, height, ctx->pCodecCtx->pix_fmt, width, height, m_grab_as_grayscale ? // BGR vs. RGB for OpenCV AV_PIX_FMT_GRAY8 : AV_PIX_FMT_BGR24, SWS_BICUBIC, nullptr, nullptr, nullptr); sws_scale( ctx->img_convert_ctx, ctx->pFrame->data, ctx->pFrame->linesize, 0, height, ctx->pFrameRGB->data, ctx->pFrameRGB->linesize); // std::cout << "[retrieveFrame] Generating image: " << // ctx->pCodecPars->width << "x" << ctx->pCodecPars->height // << std::endl; std::cout << " linsize: " << // ctx->pFrameRGB->linesize[0] << std::endl; if (ctx->pFrameRGB->linesize[0] != ((m_grab_as_grayscale ? 1 : 3) * width)) THROW_EXCEPTION("FIXME: linesize!=width case not handled yet."); out_img.loadFromMemoryBuffer( width, height, !m_grab_as_grayscale, ctx->pFrameRGB->data[0]); // Free the packet that was allocated by av_read_frame av_packet_unref(&packet); return true; // Free the packet that was allocated by av_read_frame av_packet_unref(&packet); } return false; // Error reading/ EOF #else return false; #endif } /* -------------------------------------------------------- getVideoFPS -------------------------------------------------------- */ double CFFMPEG_InputStream::getVideoFPS() const { #if MRPT_HAS_FFMPEG if (!this->isOpen()) return -1; const TFFMPEGContext* ctx = &m_impl->m_state; if (!ctx) return -1; if (!ctx->pCodecCtx) return -1; return static_cast<double>(ctx->pCodecCtx->time_base.den) / ctx->pCodecCtx->time_base.num; #else return false; #endif } <commit_msg>ffmpeg: fix version check<commit_after>/* +------------------------------------------------------------------------+ | Mobile Robot Programming Toolkit (MRPT) | | https://www.mrpt.org/ | | | | Copyright (c) 2005-2020, Individual contributors, see AUTHORS file | | See: https://www.mrpt.org/Authors - All rights reserved. | | Released under BSD License. See: https://www.mrpt.org/License | +------------------------------------------------------------------------+ */ #if defined(__GNUC__) // Needed for ffmpeg headers. Only allowed here when not // using precomp. headers #define __STDC_CONSTANT_MACROS // Needed for having "UINT64_C" and so #endif #include <mrpt/config.h> #include "hwdrivers-precomp.h" // Precompiled headers #if MRPT_HAS_FFMPEG extern "C" { #define _MSC_STDINT_H_ // We already have pstdint.h in MRPT #include <libavcodec/avcodec.h> #include <libavformat/avformat.h> #include <libavutil/imgutils.h> #include <libswscale/swscale.h> } #endif #include <mrpt/hwdrivers/CFFMPEG_InputStream.h> using namespace mrpt; using namespace mrpt::hwdrivers; // JLBC: This file takes portions of code from the example // "avcodec_sample.0.4.9.cpp" // // Minimum ffmpeg libs versions we want to support: // Ubuntu 16.04 LTS: avcodec 56.60.100, avutil 54.31.100, avformat 56.40.101 // Ubuntu 20.04 LTS: avcodec 58.54.100, avutil 56.31.100, avformat 58.29.100 // #if MRPT_HAS_FFMPEG namespace mrpt::hwdrivers { // All context for ffmpeg: struct TFFMPEGContext { AVFormatContext* pFormatCtx{nullptr}; int videoStream{0}; #if LIBAVFORMAT_VERSION_MAJOR >= 57 AVCodecParameters* pCodecPars{nullptr}; #endif AVCodec* pCodec{nullptr}; AVCodecContext* pCodecCtx{nullptr}; AVFrame* pFrame{nullptr}; AVFrame* pFrameRGB{nullptr}; SwsContext* img_convert_ctx{nullptr}; std::vector<uint8_t> buffer; }; } // namespace mrpt::hwdrivers #endif struct CFFMPEG_InputStream::Impl { #if MRPT_HAS_FFMPEG TFFMPEGContext m_state; #endif }; /* -------------------------------------------------------- Ctor -------------------------------------------------------- */ CFFMPEG_InputStream::CFFMPEG_InputStream() #if MRPT_HAS_FFMPEG : m_impl(mrpt::make_impl<CFFMPEG_InputStream::Impl>()) { // av_register_all() not needed in ffmpeg >=4.0 #if LIBAVFORMAT_VERSION_MAJOR < 58 // Register all formats and codecs av_register_all(); #endif } #else { THROW_EXCEPTION("MRPT has been compiled without FFMPEG libraries."); } #endif /* -------------------------------------------------------- Dtor -------------------------------------------------------- */ CFFMPEG_InputStream::~CFFMPEG_InputStream() { #if MRPT_HAS_FFMPEG // Close everything: this->close(); #endif } /* -------------------------------------------------------- isOpen -------------------------------------------------------- */ bool CFFMPEG_InputStream::isOpen() const { #if MRPT_HAS_FFMPEG const TFFMPEGContext* ctx = &m_impl->m_state; return ctx->pFormatCtx != nullptr; #else return false; #endif } /* -------------------------------------------------------- openURL -------------------------------------------------------- */ bool CFFMPEG_InputStream::openURL( const std::string& url, bool grab_as_grayscale, bool verbose) { #if MRPT_HAS_FFMPEG this->close(); // Close first TFFMPEGContext* ctx = &m_impl->m_state; this->m_url = url; this->m_grab_as_grayscale = grab_as_grayscale; // Open video file if (avformat_open_input(&ctx->pFormatCtx, url.c_str(), nullptr, nullptr) != 0) { ctx->pFormatCtx = nullptr; std::cerr << "[CFFMPEG_InputStream::openURL] Cannot open video: " << url << std::endl; return false; } // Retrieve stream information if (avformat_find_stream_info(ctx->pFormatCtx, nullptr) < 0) { std::cerr << "[CFFMPEG_InputStream::openURL] Couldn't find stream " "information: " << url << std::endl; return false; } // Dump information about file onto standard error if (verbose) { av_dump_format(ctx->pFormatCtx, 0, url.c_str(), false); } // Find the first video stream ctx->videoStream = -1; for (unsigned int i = 0; i < ctx->pFormatCtx->nb_streams; i++) { #if LIBAVFORMAT_VERSION_MAJOR >= 57 auto codecType = ctx->pFormatCtx->streams[i]->codecpar->codec_type; #else auto codecType = ctx->pFormatCtx->streams[i]->codec->codec_type; #endif if (codecType == AVMEDIA_TYPE_VIDEO) { ctx->videoStream = (int)i; break; } } if (ctx->videoStream == -1) { std::cerr << "[CFFMPEG_InputStream::openURL] Didn't find a video stream: " << url << std::endl; return false; } // Get a pointer to the codec context for the video stream #if LIBAVFORMAT_VERSION_MAJOR >= 57 ctx->pCodecPars = ctx->pFormatCtx->streams[ctx->videoStream]->codecpar; // Find the decoder for the video stream ctx->pCodec = avcodec_find_decoder(ctx->pCodecPars->codec_id); #else ctx->pCodecCtx = ctx->pFormatCtx->streams[ctx->videoStream]->codec; // Find the decoder for the video stream ctx->pCodec = avcodec_find_decoder(ctx->pCodecCtx->codec_id); #endif if (ctx->pCodec == nullptr) { std::cerr << "[CFFMPEG_InputStream::openURL] Codec not found: " << url << std::endl; return false; } #if LIBAVFORMAT_VERSION_MAJOR >= 57 ctx->pCodecCtx = avcodec_alloc_context3(nullptr /*ctx->pCodec*/); if (!ctx->pCodecCtx) { std::cerr << "[CFFMPEG_InputStream::openURL] Cannot alloc avcodec " "context for: " << url << std::endl; return false; } // Add stream parameters to context if (avcodec_parameters_to_context( ctx->pCodecCtx, ctx->pFormatCtx->streams[ctx->videoStream]->codecpar)) { std::cerr << "[CFFMPEG_InputStream::openURL] Failed " "avcodec_parameters_to_context() for: " << url << std::endl; return false; } // Make sure that Codecs are identical or avcodec_open2 fails. ctx->pCodecCtx->codec_id = ctx->pCodec->id; #endif // Open codec if (avcodec_open2(ctx->pCodecCtx, ctx->pCodec, nullptr) < 0) { std::cerr << "[CFFMPEG_InputStream::openURL] avcodec_open2() failed for: " << url << std::endl; return false; } // Allocate video frame ctx->pFrame = av_frame_alloc(); // Allocate an AVFrame structure ctx->pFrameRGB = av_frame_alloc(); if (ctx->pFrameRGB == nullptr || ctx->pFrame == nullptr) { std::cerr << "[CFFMPEG_InputStream::openURL] Could not alloc memory " "for frame buffers: " << url << std::endl; return false; } // Determine required buffer size and allocate buffer #if LIBAVFORMAT_VERSION_MAJOR >= 57 const auto width = ctx->pCodecPars->width, height = ctx->pCodecPars->height; #else const auto width = ctx->pCodecCtx->width, height = ctx->pCodecCtx->height; #endif int numBytes = av_image_get_buffer_size( m_grab_as_grayscale ? AV_PIX_FMT_GRAY8 : AV_PIX_FMT_BGR24, width, height, 1); if (numBytes < 0) { std::cerr << "[CFFMPEG_InputStream::openURL] av_image_get_buffer_size " "error code: " << numBytes << std::endl; return false; } ctx->buffer.resize(numBytes); // Assign appropriate parts of buffer to image planes in pFrameRGB av_image_fill_arrays( ctx->pFrameRGB->data, ctx->pFrameRGB->linesize, &ctx->buffer[0], m_grab_as_grayscale ? AV_PIX_FMT_GRAY8 : AV_PIX_FMT_BGR24, width, height, 1); return true; // OK. #else return false; #endif } /* -------------------------------------------------------- close -------------------------------------------------------- */ void CFFMPEG_InputStream::close() { #if MRPT_HAS_FFMPEG if (!this->isOpen()) return; TFFMPEGContext* ctx = &m_impl->m_state; // Close the codec if (ctx->pCodecCtx) { avcodec_close(ctx->pCodecCtx); ctx->pCodecCtx = nullptr; } // Close the video file if (ctx->pFormatCtx) { avformat_close_input(&ctx->pFormatCtx); ctx->pFormatCtx = nullptr; } // Free frames memory: ctx->buffer.clear(); if (ctx->pFrameRGB) { av_frame_free(&ctx->pFrameRGB); ctx->pFrameRGB = nullptr; } if (ctx->pFrame) { av_frame_free(&ctx->pFrame); ctx->pFrame = nullptr; } if (ctx->img_convert_ctx) { sws_freeContext(ctx->img_convert_ctx); ctx->img_convert_ctx = nullptr; } #endif } /* -------------------------------------------------------- retrieveFrame -------------------------------------------------------- */ bool CFFMPEG_InputStream::retrieveFrame(mrpt::img::CImage& out_img) { #if MRPT_HAS_FFMPEG if (!this->isOpen()) return false; TFFMPEGContext* ctx = &m_impl->m_state; AVPacket packet; #if LIBAVFORMAT_VERSION_MAJOR < 58 int frameFinished; #endif #if LIBAVFORMAT_VERSION_MAJOR >= 57 const auto width = ctx->pCodecPars->width, height = ctx->pCodecPars->height; #else const auto width = ctx->pCodecCtx->width, height = ctx->pCodecCtx->height; #endif while (av_read_frame(ctx->pFormatCtx, &packet) >= 0) { // Is this a packet from the video stream? if (packet.stream_index != ctx->videoStream) { av_packet_unref(&packet); continue; } // Decode video frame #if LIBAVFORMAT_VERSION_MAJOR >= 57 int ret = avcodec_send_packet(ctx->pCodecCtx, &packet); if (ret < 0) { std::cerr << "[CFFMPEG_InputStream] avcodec_send_packet error code=" << ret << std::endl; return false; } // while (ret >= 0) ret = avcodec_receive_frame(ctx->pCodecCtx, ctx->pFrame); if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) return false; else if (ret < 0) { std::cerr << "[CFFMPEG_InputStream] avcodec_receive_frame " "error code=" << ret << std::endl; return false; } #else avcodec_decode_video2( ctx->pCodecCtx, ctx->pFrame, &frameFinished, &packet); if (!frameFinished) { // Free the packet that was allocated by av_read_frame av_packet_unref(&packet); continue; } #endif // Convert the image from its native format to RGB: ctx->img_convert_ctx = sws_getCachedContext( ctx->img_convert_ctx, width, height, ctx->pCodecCtx->pix_fmt, width, height, m_grab_as_grayscale ? // BGR vs. RGB for OpenCV AV_PIX_FMT_GRAY8 : AV_PIX_FMT_BGR24, SWS_BICUBIC, nullptr, nullptr, nullptr); sws_scale( ctx->img_convert_ctx, ctx->pFrame->data, ctx->pFrame->linesize, 0, height, ctx->pFrameRGB->data, ctx->pFrameRGB->linesize); // std::cout << "[retrieveFrame] Generating image: " << // ctx->pCodecPars->width << "x" << ctx->pCodecPars->height // << std::endl; std::cout << " linsize: " << // ctx->pFrameRGB->linesize[0] << std::endl; if (ctx->pFrameRGB->linesize[0] != ((m_grab_as_grayscale ? 1 : 3) * width)) THROW_EXCEPTION("FIXME: linesize!=width case not handled yet."); out_img.loadFromMemoryBuffer( width, height, !m_grab_as_grayscale, ctx->pFrameRGB->data[0]); // Free the packet that was allocated by av_read_frame av_packet_unref(&packet); return true; // Free the packet that was allocated by av_read_frame av_packet_unref(&packet); } return false; // Error reading/ EOF #else return false; #endif } /* -------------------------------------------------------- getVideoFPS -------------------------------------------------------- */ double CFFMPEG_InputStream::getVideoFPS() const { #if MRPT_HAS_FFMPEG if (!this->isOpen()) return -1; const TFFMPEGContext* ctx = &m_impl->m_state; if (!ctx) return -1; if (!ctx->pCodecCtx) return -1; return static_cast<double>(ctx->pCodecCtx->time_base.den) / ctx->pCodecCtx->time_base.num; #else return false; #endif } <|endoftext|>
<commit_before>/* +---------------------------------------------------------------------------+ | Mobile Robot Programming Toolkit (MRPT) | | http://www.mrpt.org/ | | | | Copyright (c) 2005-2017, Individual contributors, see AUTHORS file | | See: http://www.mrpt.org/Authors - All rights reserved. | | Released under BSD License. See details in http://www.mrpt.org/License | +---------------------------------------------------------------------------+ */ #if defined(__GNUC__) // Needed for ffmpeg headers. Only allowed here when not using precomp. headers #define __STDC_CONSTANT_MACROS // Needed for having "UINT64_C" and so #endif #include "hwdrivers-precomp.h" // Precompiled headers #include <mrpt/config.h> #include <mrpt/utils/utils_defs.h> #if MRPT_HAS_FFMPEG extern "C" { #define _MSC_STDINT_H_ // We already have pstdint.h in MRPT #include <libavformat/avformat.h> #include <libavcodec/avcodec.h> #include <libswscale/swscale.h> #include <libavutil/imgutils.h> } #endif #include <mrpt/hwdrivers/CFFMPEG_InputStream.h> using namespace mrpt; using namespace mrpt::hwdrivers; // JLBC: This file takes portions of code from the example "avcodec_sample.0.4.9.cpp" #if MRPT_HAS_FFMPEG namespace mrpt { namespace hwdrivers { // All context for ffmpeg: struct TFFMPEGContext { AVFormatContext *pFormatCtx; int videoStream; AVCodecContext *pCodecCtx; AVCodec *pCodec; AVFrame *pFrame; AVFrame *pFrameRGB; SwsContext *img_convert_ctx; std::vector<uint8_t> buffer; }; } } #endif #define MY_FFMPEG_STATE const_cast<TFFMPEGContext*>(static_cast<const TFFMPEGContext*>(m_state.get())) /* -------------------------------------------------------- Ctor -------------------------------------------------------- */ CFFMPEG_InputStream::CFFMPEG_InputStream() { #if MRPT_HAS_FFMPEG m_state.set( new TFFMPEGContext[1] ); TFFMPEGContext *ctx = MY_FFMPEG_STATE; ctx->pFormatCtx = nullptr; ctx->pCodecCtx = nullptr; ctx->pCodec = nullptr; ctx->videoStream = 0; ctx->pFrame = nullptr; ctx->pFrameRGB = nullptr; ctx->img_convert_ctx = nullptr; // Register all formats and codecs av_register_all(); #else THROW_EXCEPTION("MRPT has been compiled without FFMPEG libraries.") #endif } /* -------------------------------------------------------- Dtor -------------------------------------------------------- */ CFFMPEG_InputStream::~CFFMPEG_InputStream() { #if MRPT_HAS_FFMPEG // Close everything: this->close(); // Free context struct. memory delete[] MY_FFMPEG_STATE; m_state.set(nullptr); #endif } /* -------------------------------------------------------- isOpen -------------------------------------------------------- */ bool CFFMPEG_InputStream::isOpen() const { #if MRPT_HAS_FFMPEG TFFMPEGContext *ctx = MY_FFMPEG_STATE; return ctx->pFormatCtx != nullptr; #else return false; #endif } /* -------------------------------------------------------- openURL -------------------------------------------------------- */ bool CFFMPEG_InputStream::openURL( const std::string &url, bool grab_as_grayscale, bool verbose ) { #if MRPT_HAS_FFMPEG this->close(); // Close first TFFMPEGContext *ctx = MY_FFMPEG_STATE; this->m_url = url; this->m_grab_as_grayscale = grab_as_grayscale; // Open video file #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(53,2,0) if(avformat_open_input( &ctx->pFormatCtx, url.c_str(), nullptr, nullptr)!=0) #else if(av_open_input_file( &ctx->pFormatCtx, url.c_str(), nullptr, 0, nullptr)!=0) #endif { ctx->pFormatCtx = nullptr; std::cerr << "[CFFMPEG_InputStream::openURL] Cannot open video: " << url << std::endl; return false; } // Retrieve stream information if ( #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(53,35,0) avformat_find_stream_info(ctx->pFormatCtx, nullptr)<0 #else av_find_stream_info(ctx->pFormatCtx)<0 #endif ) { std::cerr << "[CFFMPEG_InputStream::openURL] Couldn't find stream information: " << url << std::endl; return false; } // Dump information about file onto standard error if (verbose) { #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(53,2,0) av_dump_format(ctx->pFormatCtx, 0, url.c_str(), false); #else dump_format(ctx->pFormatCtx, 0, url.c_str(), false); #endif } // Find the first video stream ctx->videoStream=-1; for(unsigned int i=0; i<ctx->pFormatCtx->nb_streams; i++) { if(ctx->pFormatCtx->streams[i]->codec->codec_type== #if LIBAVCODEC_VERSION_INT<AV_VERSION_INT(53,0,0) CODEC_TYPE_VIDEO #else AVMEDIA_TYPE_VIDEO #endif ) { ctx->videoStream=(int)i; break; } } if(ctx->videoStream==-1) { std::cerr << "[CFFMPEG_InputStream::openURL] Didn't find a video stream: " << url << std::endl; return false; } // Get a pointer to the codec context for the video stream ctx->pCodecCtx= ctx->pFormatCtx->streams[ctx->videoStream]->codec; // Find the decoder for the video stream ctx->pCodec=avcodec_find_decoder(ctx->pCodecCtx->codec_id); if(ctx->pCodec==nullptr) { std::cerr << "[CFFMPEG_InputStream::openURL] Codec not found: " << url << std::endl; return false; } // Open codec #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(53,6,0) if(avcodec_open2(ctx->pCodecCtx, ctx->pCodec,nullptr)<0) #else if(avcodec_open(ctx->pCodecCtx, ctx->pCodec)<0) #endif { std::cerr << "[CFFMPEG_InputStream::openURL] Could not open codec: " << url << std::endl; return false; } #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(55,46,0) // Allocate video frame ctx->pFrame=av_frame_alloc(); // Allocate an AVFrame structure ctx->pFrameRGB=av_frame_alloc(); #else // Allocate video frame ctx->pFrame=avcodec_alloc_frame(); // Allocate an AVFrame structure ctx->pFrameRGB=avcodec_alloc_frame(); #endif if(ctx->pFrameRGB==nullptr || ctx->pFrame==nullptr) { std::cerr << "[CFFMPEG_InputStream::openURL] Could not alloc memory for frame buffers: " << url << std::endl; return false; } // Determine required buffer size and allocate buffer size_t numBytes = av_image_get_buffer_size( m_grab_as_grayscale ? // BGR vs. RGB for OpenCV #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(55,00,0) AV_PIX_FMT_GRAY8 : AV_PIX_FMT_BGR24, #else PIX_FMT_GRAY8 : PIX_FMT_BGR24, #endif ctx->pCodecCtx->width, ctx->pCodecCtx->height, 1); ctx->buffer.resize(numBytes); // Assign appropriate parts of buffer to image planes in pFrameRGB avpicture_fill( (AVPicture *)ctx->pFrameRGB, &ctx->buffer[0], m_grab_as_grayscale ? // BGR vs. RGB for OpenCV #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(55,00,0) AV_PIX_FMT_GRAY8 : AV_PIX_FMT_BGR24, #else PIX_FMT_GRAY8 : PIX_FMT_BGR24, #endif ctx->pCodecCtx->width, ctx->pCodecCtx->height); return true; // OK. #else return false; #endif } /* -------------------------------------------------------- close -------------------------------------------------------- */ void CFFMPEG_InputStream::close() { #if MRPT_HAS_FFMPEG if (!this->isOpen()) return; TFFMPEGContext *ctx = MY_FFMPEG_STATE; // Close the codec if (ctx->pCodecCtx) { avcodec_close(ctx->pCodecCtx); ctx->pCodecCtx=nullptr; } // Close the video file if (ctx->pFormatCtx) { #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(53,35,0) avformat_close_input(&ctx->pFormatCtx); #else av_close_input_file(ctx->pFormatCtx); #endif ctx->pFormatCtx = nullptr; } // Free frames memory: ctx->buffer.clear(); if (ctx->pFrameRGB) { #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(55,46,0) av_frame_free(&ctx->pFrameRGB); #else av_free(ctx->pFrameRGB); #endif ctx->pFrameRGB=nullptr; } if (ctx->pFrame) { #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(55,46,0) av_frame_free(&ctx->pFrame); #else av_free(ctx->pFrame); #endif ctx->pFrame = nullptr; } if (ctx->img_convert_ctx) { sws_freeContext( ctx->img_convert_ctx ); ctx->img_convert_ctx = nullptr; } #endif } /* -------------------------------------------------------- retrieveFrame -------------------------------------------------------- */ bool CFFMPEG_InputStream::retrieveFrame( mrpt::utils::CImage &out_img ) { #if MRPT_HAS_FFMPEG if (!this->isOpen()) return false; TFFMPEGContext *ctx = MY_FFMPEG_STATE; AVPacket packet; int frameFinished; while(av_read_frame(ctx->pFormatCtx, &packet)>=0) { // Is this a packet from the video stream? if(packet.stream_index==ctx->videoStream) { // Decode video frame #if LIBAVCODEC_VERSION_MAJOR>52 || (LIBAVCODEC_VERSION_MAJOR==52 && LIBAVCODEC_VERSION_MINOR>=72) avcodec_decode_video2( ctx->pCodecCtx, ctx->pFrame, &frameFinished, &packet); #else avcodec_decode_video( ctx->pCodecCtx, ctx->pFrame, &frameFinished, packet.data, packet.size); #endif // Did we get a video frame? if(frameFinished) { // Convert the image from its native format to RGB: ctx->img_convert_ctx = sws_getCachedContext( ctx->img_convert_ctx, ctx->pCodecCtx->width, ctx->pCodecCtx->height, ctx->pCodecCtx->pix_fmt, ctx->pCodecCtx->width, ctx->pCodecCtx->height, m_grab_as_grayscale ? // BGR vs. RGB for OpenCV #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(55,00,0) AV_PIX_FMT_GRAY8 : AV_PIX_FMT_BGR24, #else PIX_FMT_GRAY8 : PIX_FMT_BGR24, #endif SWS_BICUBIC, nullptr, nullptr, nullptr); sws_scale( ctx->img_convert_ctx, ctx->pFrame->data, ctx->pFrame->linesize,0, ctx->pCodecCtx->height, ctx->pFrameRGB->data, ctx->pFrameRGB->linesize); //std::cout << "[retrieveFrame] Generating image: " << ctx->pCodecCtx->width << "x" << ctx->pCodecCtx->height << std::endl; //std::cout << " linsize: " << ctx->pFrameRGB->linesize[0] << std::endl; if( ctx->pFrameRGB->linesize[0]!= ((m_grab_as_grayscale ? 1:3)*ctx->pCodecCtx->width) ) THROW_EXCEPTION("FIXME: linesize!=width case not handled yet.") out_img.loadFromMemoryBuffer( ctx->pCodecCtx->width, ctx->pCodecCtx->height, !m_grab_as_grayscale, // Color ctx->pFrameRGB->data[0] ); // Free the packet that was allocated by av_read_frame av_packet_unref(&packet); return true; } } // Free the packet that was allocated by av_read_frame av_packet_unref(&packet); } return false; // Error reading/ EOF #else return false; #endif } /* -------------------------------------------------------- getVideoFPS -------------------------------------------------------- */ double CFFMPEG_InputStream::getVideoFPS() const { #if MRPT_HAS_FFMPEG if (!this->isOpen()) return -1; TFFMPEGContext *ctx = MY_FFMPEG_STATE; if (!ctx) return -1; if (!ctx->pCodecCtx) return -1; return static_cast<double>(ctx->pCodecCtx->time_base.den) / ctx->pCodecCtx->time_base.num; #else return false; #endif } <commit_msg>Add version checks for previous libav commit<commit_after>/* +---------------------------------------------------------------------------+ | Mobile Robot Programming Toolkit (MRPT) | | http://www.mrpt.org/ | | | | Copyright (c) 2005-2017, Individual contributors, see AUTHORS file | | See: http://www.mrpt.org/Authors - All rights reserved. | | Released under BSD License. See details in http://www.mrpt.org/License | +---------------------------------------------------------------------------+ */ #if defined(__GNUC__) // Needed for ffmpeg headers. Only allowed here when not using precomp. headers #define __STDC_CONSTANT_MACROS // Needed for having "UINT64_C" and so #endif #include "hwdrivers-precomp.h" // Precompiled headers #include <mrpt/config.h> #include <mrpt/utils/utils_defs.h> #if MRPT_HAS_FFMPEG extern "C" { #define _MSC_STDINT_H_ // We already have pstdint.h in MRPT #include <libavformat/avformat.h> #include <libavcodec/avcodec.h> #include <libswscale/swscale.h> #include <libavutil/imgutils.h> } #endif #include <mrpt/hwdrivers/CFFMPEG_InputStream.h> using namespace mrpt; using namespace mrpt::hwdrivers; // JLBC: This file takes portions of code from the example "avcodec_sample.0.4.9.cpp" #if MRPT_HAS_FFMPEG namespace mrpt { namespace hwdrivers { // All context for ffmpeg: struct TFFMPEGContext { AVFormatContext *pFormatCtx; int videoStream; AVCodecContext *pCodecCtx; AVCodec *pCodec; AVFrame *pFrame; AVFrame *pFrameRGB; SwsContext *img_convert_ctx; std::vector<uint8_t> buffer; }; } } #endif #define MY_FFMPEG_STATE const_cast<TFFMPEGContext*>(static_cast<const TFFMPEGContext*>(m_state.get())) /* -------------------------------------------------------- Ctor -------------------------------------------------------- */ CFFMPEG_InputStream::CFFMPEG_InputStream() { #if MRPT_HAS_FFMPEG m_state.set( new TFFMPEGContext[1] ); TFFMPEGContext *ctx = MY_FFMPEG_STATE; ctx->pFormatCtx = nullptr; ctx->pCodecCtx = nullptr; ctx->pCodec = nullptr; ctx->videoStream = 0; ctx->pFrame = nullptr; ctx->pFrameRGB = nullptr; ctx->img_convert_ctx = nullptr; // Register all formats and codecs av_register_all(); #else THROW_EXCEPTION("MRPT has been compiled without FFMPEG libraries.") #endif } /* -------------------------------------------------------- Dtor -------------------------------------------------------- */ CFFMPEG_InputStream::~CFFMPEG_InputStream() { #if MRPT_HAS_FFMPEG // Close everything: this->close(); // Free context struct. memory delete[] MY_FFMPEG_STATE; m_state.set(nullptr); #endif } /* -------------------------------------------------------- isOpen -------------------------------------------------------- */ bool CFFMPEG_InputStream::isOpen() const { #if MRPT_HAS_FFMPEG TFFMPEGContext *ctx = MY_FFMPEG_STATE; return ctx->pFormatCtx != nullptr; #else return false; #endif } /* -------------------------------------------------------- openURL -------------------------------------------------------- */ bool CFFMPEG_InputStream::openURL( const std::string &url, bool grab_as_grayscale, bool verbose ) { #if MRPT_HAS_FFMPEG this->close(); // Close first TFFMPEGContext *ctx = MY_FFMPEG_STATE; this->m_url = url; this->m_grab_as_grayscale = grab_as_grayscale; // Open video file #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(53,2,0) if(avformat_open_input( &ctx->pFormatCtx, url.c_str(), nullptr, nullptr)!=0) #else if(av_open_input_file( &ctx->pFormatCtx, url.c_str(), nullptr, 0, nullptr)!=0) #endif { ctx->pFormatCtx = nullptr; std::cerr << "[CFFMPEG_InputStream::openURL] Cannot open video: " << url << std::endl; return false; } // Retrieve stream information if ( #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(53,35,0) avformat_find_stream_info(ctx->pFormatCtx, nullptr)<0 #else av_find_stream_info(ctx->pFormatCtx)<0 #endif ) { std::cerr << "[CFFMPEG_InputStream::openURL] Couldn't find stream information: " << url << std::endl; return false; } // Dump information about file onto standard error if (verbose) { #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(53,2,0) av_dump_format(ctx->pFormatCtx, 0, url.c_str(), false); #else dump_format(ctx->pFormatCtx, 0, url.c_str(), false); #endif } // Find the first video stream ctx->videoStream=-1; for(unsigned int i=0; i<ctx->pFormatCtx->nb_streams; i++) { if(ctx->pFormatCtx->streams[i]->codec->codec_type== #if LIBAVCODEC_VERSION_INT<AV_VERSION_INT(53,0,0) CODEC_TYPE_VIDEO #else AVMEDIA_TYPE_VIDEO #endif ) { ctx->videoStream=(int)i; break; } } if(ctx->videoStream==-1) { std::cerr << "[CFFMPEG_InputStream::openURL] Didn't find a video stream: " << url << std::endl; return false; } // Get a pointer to the codec context for the video stream ctx->pCodecCtx= ctx->pFormatCtx->streams[ctx->videoStream]->codec; // Find the decoder for the video stream ctx->pCodec=avcodec_find_decoder(ctx->pCodecCtx->codec_id); if(ctx->pCodec==nullptr) { std::cerr << "[CFFMPEG_InputStream::openURL] Codec not found: " << url << std::endl; return false; } // Open codec #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(53,6,0) if(avcodec_open2(ctx->pCodecCtx, ctx->pCodec,nullptr)<0) #else if(avcodec_open(ctx->pCodecCtx, ctx->pCodec)<0) #endif { std::cerr << "[CFFMPEG_InputStream::openURL] Could not open codec: " << url << std::endl; return false; } #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(55,46,0) // Allocate video frame ctx->pFrame=av_frame_alloc(); // Allocate an AVFrame structure ctx->pFrameRGB=av_frame_alloc(); #else // Allocate video frame ctx->pFrame=avcodec_alloc_frame(); // Allocate an AVFrame structure ctx->pFrameRGB=avcodec_alloc_frame(); #endif if(ctx->pFrameRGB==nullptr || ctx->pFrame==nullptr) { std::cerr << "[CFFMPEG_InputStream::openURL] Could not alloc memory for frame buffers: " << url << std::endl; return false; } // Determine required buffer size and allocate buffer #if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(54, 6, 0) size_t numBytes=avpicture_get_size( #else size_t numBytes = av_image_get_buffer_size( #endif m_grab_as_grayscale ? // BGR vs. RGB for OpenCV #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(55,00,0) AV_PIX_FMT_GRAY8 : AV_PIX_FMT_BGR24, #else PIX_FMT_GRAY8 : PIX_FMT_BGR24, #endif ctx->pCodecCtx->width, ctx->pCodecCtx->height #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(54, 6, 0) , 1 #endif ); ctx->buffer.resize(numBytes); // Assign appropriate parts of buffer to image planes in pFrameRGB avpicture_fill( (AVPicture *)ctx->pFrameRGB, &ctx->buffer[0], m_grab_as_grayscale ? // BGR vs. RGB for OpenCV #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(55,00,0) AV_PIX_FMT_GRAY8 : AV_PIX_FMT_BGR24, #else PIX_FMT_GRAY8 : PIX_FMT_BGR24, #endif ctx->pCodecCtx->width, ctx->pCodecCtx->height); return true; // OK. #else return false; #endif } /* -------------------------------------------------------- close -------------------------------------------------------- */ void CFFMPEG_InputStream::close() { #if MRPT_HAS_FFMPEG if (!this->isOpen()) return; TFFMPEGContext *ctx = MY_FFMPEG_STATE; // Close the codec if (ctx->pCodecCtx) { avcodec_close(ctx->pCodecCtx); ctx->pCodecCtx=nullptr; } // Close the video file if (ctx->pFormatCtx) { #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(53,35,0) avformat_close_input(&ctx->pFormatCtx); #else av_close_input_file(ctx->pFormatCtx); #endif ctx->pFormatCtx = nullptr; } // Free frames memory: ctx->buffer.clear(); if (ctx->pFrameRGB) { #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(55,46,0) av_frame_free(&ctx->pFrameRGB); #else av_free(ctx->pFrameRGB); #endif ctx->pFrameRGB=nullptr; } if (ctx->pFrame) { #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(55,46,0) av_frame_free(&ctx->pFrame); #else av_free(ctx->pFrame); #endif ctx->pFrame = nullptr; } if (ctx->img_convert_ctx) { sws_freeContext( ctx->img_convert_ctx ); ctx->img_convert_ctx = nullptr; } #endif } /* -------------------------------------------------------- retrieveFrame -------------------------------------------------------- */ bool CFFMPEG_InputStream::retrieveFrame( mrpt::utils::CImage &out_img ) { #if MRPT_HAS_FFMPEG if (!this->isOpen()) return false; TFFMPEGContext *ctx = MY_FFMPEG_STATE; AVPacket packet; int frameFinished; while(av_read_frame(ctx->pFormatCtx, &packet)>=0) { // Is this a packet from the video stream? if(packet.stream_index==ctx->videoStream) { // Decode video frame #if LIBAVCODEC_VERSION_MAJOR>52 || (LIBAVCODEC_VERSION_MAJOR==52 && LIBAVCODEC_VERSION_MINOR>=72) avcodec_decode_video2( ctx->pCodecCtx, ctx->pFrame, &frameFinished, &packet); #else avcodec_decode_video( ctx->pCodecCtx, ctx->pFrame, &frameFinished, packet.data, packet.size); #endif // Did we get a video frame? if(frameFinished) { // Convert the image from its native format to RGB: ctx->img_convert_ctx = sws_getCachedContext( ctx->img_convert_ctx, ctx->pCodecCtx->width, ctx->pCodecCtx->height, ctx->pCodecCtx->pix_fmt, ctx->pCodecCtx->width, ctx->pCodecCtx->height, m_grab_as_grayscale ? // BGR vs. RGB for OpenCV #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(55,00,0) AV_PIX_FMT_GRAY8 : AV_PIX_FMT_BGR24, #else PIX_FMT_GRAY8 : PIX_FMT_BGR24, #endif SWS_BICUBIC, nullptr, nullptr, nullptr); sws_scale( ctx->img_convert_ctx, ctx->pFrame->data, ctx->pFrame->linesize,0, ctx->pCodecCtx->height, ctx->pFrameRGB->data, ctx->pFrameRGB->linesize); //std::cout << "[retrieveFrame] Generating image: " << ctx->pCodecCtx->width << "x" << ctx->pCodecCtx->height << std::endl; //std::cout << " linsize: " << ctx->pFrameRGB->linesize[0] << std::endl; if( ctx->pFrameRGB->linesize[0]!= ((m_grab_as_grayscale ? 1:3)*ctx->pCodecCtx->width) ) THROW_EXCEPTION("FIXME: linesize!=width case not handled yet.") out_img.loadFromMemoryBuffer( ctx->pCodecCtx->width, ctx->pCodecCtx->height, !m_grab_as_grayscale, // Color ctx->pFrameRGB->data[0] ); // Free the packet that was allocated by av_read_frame #if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(55, 16, 0) av_free_packet(&packet); #else av_packet_unref(&packet); #endif return true; } } // Free the packet that was allocated by av_read_frame #if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(55, 16, 0) av_free_packet(&packet); #else av_packet_unref(&packet); #endif } return false; // Error reading/ EOF #else return false; #endif } /* -------------------------------------------------------- getVideoFPS -------------------------------------------------------- */ double CFFMPEG_InputStream::getVideoFPS() const { #if MRPT_HAS_FFMPEG if (!this->isOpen()) return -1; TFFMPEGContext *ctx = MY_FFMPEG_STATE; if (!ctx) return -1; if (!ctx->pCodecCtx) return -1; return static_cast<double>(ctx->pCodecCtx->time_base.den) / ctx->pCodecCtx->time_base.num; #else return false; #endif } <|endoftext|>
<commit_before>#ifndef MESOS_SCHED_HPP #define MESOS_SCHED_HPP #include <string> #include <map> #include <vector> #include <mesos.hpp> namespace mesos { class SchedulerDriver; namespace internal { class SchedulerProcess; class MasterDetector; class Configuration; } /** * Callback interface to be implemented by new frameworks' schedulers. */ class Scheduler { public: virtual ~Scheduler() {} // Callbacks for getting framework properties. virtual std::string getFrameworkName(SchedulerDriver* driver) = 0; virtual ExecutorInfo getExecutorInfo(SchedulerDriver* driver) = 0; // Callbacks for various Mesos events. virtual void registered(SchedulerDriver* driver, const FrameworkID& frameworkId) = 0; virtual void resourceOffer(SchedulerDriver* driver, const OfferID& offerId, const std::vector<SlaveOffer>& offers) = 0; virtual void offerRescinded(SchedulerDriver* driver, const OfferID& offerId) = 0; virtual void statusUpdate(SchedulerDriver* driver, const TaskStatus& status) = 0; virtual void frameworkMessage(SchedulerDriver* driver, const FrameworkMessage& message) = 0; virtual void slaveLost(SchedulerDriver* driver, const SlaveID& sid) = 0; virtual void error(SchedulerDriver* driver, int code, const std::string& message) = 0; }; /** * Abstract interface for driving a scheduler connected to Mesos. * This interface is used both to manage the scheduler's lifecycle (start it, * stop it, or wait for it to finish) and to send commands from the user * framework to Mesos (such as replies to offers). Concrete implementations * of SchedulerDriver will take a Scheduler as a parameter in order to make * callbacks into it on various events. */ class SchedulerDriver { public: virtual ~SchedulerDriver() {} // Lifecycle methods. virtual int start() = 0; virtual int stop() = 0; virtual int join() = 0; virtual int run() = 0; // Start and then join driver. // Communication methods. virtual int sendFrameworkMessage(const FrameworkMessage& message) = 0; virtual int killTask(const TaskID& taskId) = 0; virtual int replyToOffer(const OfferID& offerId, const std::vector<TaskDescription>& tasks, const std::map<std::string, std::string>& params) = 0; virtual int replyToOffer(const OfferID& offerId, const std::vector<TaskDescription>& tasks) { return replyToOffer(offerId, tasks, std::map<std::string, std::string>()); } virtual int reviveOffers() = 0; }; /** * Concrete implementation of SchedulerDriver that communicates with * a Mesos master. */ class MesosSchedulerDriver : public SchedulerDriver { public: /** * Create a scheduler driver with a given Mesos master URL. * Additional Mesos config options are read from the environment, as well * as any config files found through it. * * @param sched scheduler to make callbacks into * @param url Mesos master URL * @param frameworkId optional framework ID for registering * redundant schedulers for the same framework */ MesosSchedulerDriver(Scheduler* sched, const std::string& url, const FrameworkID& frameworkId = FrameworkID()); /** * Create a scheduler driver with a configuration, which the master URL * and possibly other options are read from. * Additional Mesos config options are read from the environment, as well * as any config files given through conf or found in the environment. * * @param sched scheduler to make callbacks into * @param params Map containing configuration options * @param frameworkId optional framework ID for registering * redundant schedulers for the same framework */ MesosSchedulerDriver(Scheduler* sched, const std::map<std::string, std::string>& params, const FrameworkID& frameworkId = FrameworkID()); #ifndef SWIG /** * Create a scheduler driver with a config read from command-line arguments. * Additional Mesos config options are read from the environment, as well * as any config files given through conf or found in the environment. * * This constructor is not available through SWIG since it's difficult * for it to properly map arrays to an argc/argv pair. * * @param sched scheduler to make callbacks into * @param argc argument count * @param argv argument values (argument 0 is expected to be program name * and will not be looked at for options) * @param frameworkId optional framework ID for registering * redundant schedulers for the same framework */ MesosSchedulerDriver(Scheduler* sched, int argc, char** argv, const FrameworkID& frameworkId = FrameworkID()); #endif virtual ~MesosSchedulerDriver(); // Lifecycle methods. virtual int start(); virtual int stop(); virtual int join(); virtual int run(); // Start and then join driver. // Communication methods. virtual int sendFrameworkMessage(const FrameworkMessage& message); virtual int killTask(const TaskID& taskId); virtual int replyToOffer(const OfferID& offerId, const std::vector<TaskDescription>& tasks, const std::map<std::string, std::string>& params); virtual int replyToOffer(const OfferID& offerId, const std::vector<TaskDescription>& tasks) { return replyToOffer(offerId, tasks, std::map<std::string, std::string>()); } virtual int reviveOffers(); private: // Initialization method used by constructors void init(Scheduler* sched, internal::Configuration* conf, const FrameworkID& frameworkId); // Internal utility method to report an error to the scheduler void error(int code, const std::string& message); Scheduler* sched; std::string url; FrameworkID frameworkId; // Libprocess process for communicating with master internal::SchedulerProcess* process; // Coordination between masters internal::MasterDetector* detector; // Configuration options. // TODO(benh|matei): Does this still need to be a pointer? internal::Configuration* conf; // Are we currently registered with the master bool running; // Mutex to enforce all non-callbacks are execute serially pthread_mutex_t mutex; // Condition variable for waiting until driver terminates pthread_cond_t cond; }; } /* namespace mesos { */ #endif /* MESOS_SCHED_HPP */ <commit_msg>Fixed some tabs<commit_after>#ifndef MESOS_SCHED_HPP #define MESOS_SCHED_HPP #include <string> #include <map> #include <vector> #include <mesos.hpp> namespace mesos { class SchedulerDriver; namespace internal { class SchedulerProcess; class MasterDetector; class Configuration; } /** * Callback interface to be implemented by new frameworks' schedulers. */ class Scheduler { public: virtual ~Scheduler() {} // Callbacks for getting framework properties. virtual std::string getFrameworkName(SchedulerDriver* driver) = 0; virtual ExecutorInfo getExecutorInfo(SchedulerDriver* driver) = 0; // Callbacks for various Mesos events. virtual void registered(SchedulerDriver* driver, const FrameworkID& frameworkId) = 0; virtual void resourceOffer(SchedulerDriver* driver, const OfferID& offerId, const std::vector<SlaveOffer>& offers) = 0; virtual void offerRescinded(SchedulerDriver* driver, const OfferID& offerId) = 0; virtual void statusUpdate(SchedulerDriver* driver, const TaskStatus& status) = 0; virtual void frameworkMessage(SchedulerDriver* driver, const FrameworkMessage& message) = 0; virtual void slaveLost(SchedulerDriver* driver, const SlaveID& sid) = 0; virtual void error(SchedulerDriver* driver, int code, const std::string& message) = 0; }; /** * Abstract interface for driving a scheduler connected to Mesos. * This interface is used both to manage the scheduler's lifecycle (start it, * stop it, or wait for it to finish) and to send commands from the user * framework to Mesos (such as replies to offers). Concrete implementations * of SchedulerDriver will take a Scheduler as a parameter in order to make * callbacks into it on various events. */ class SchedulerDriver { public: virtual ~SchedulerDriver() {} // Lifecycle methods. virtual int start() = 0; virtual int stop() = 0; virtual int join() = 0; virtual int run() = 0; // Start and then join driver. // Communication methods. virtual int sendFrameworkMessage(const FrameworkMessage& message) = 0; virtual int killTask(const TaskID& taskId) = 0; virtual int replyToOffer(const OfferID& offerId, const std::vector<TaskDescription>& tasks, const std::map<std::string, std::string>& params) = 0; virtual int replyToOffer(const OfferID& offerId, const std::vector<TaskDescription>& tasks) { return replyToOffer(offerId, tasks, std::map<std::string, std::string>()); } virtual int reviveOffers() = 0; }; /** * Concrete implementation of SchedulerDriver that communicates with * a Mesos master. */ class MesosSchedulerDriver : public SchedulerDriver { public: /** * Create a scheduler driver with a given Mesos master URL. * Additional Mesos config options are read from the environment, as well * as any config files found through it. * * @param sched scheduler to make callbacks into * @param url Mesos master URL * @param frameworkId optional framework ID for registering * redundant schedulers for the same framework */ MesosSchedulerDriver(Scheduler* sched, const std::string& url, const FrameworkID& frameworkId = FrameworkID()); /** * Create a scheduler driver with a configuration, which the master URL * and possibly other options are read from. * Additional Mesos config options are read from the environment, as well * as any config files given through conf or found in the environment. * * @param sched scheduler to make callbacks into * @param params Map containing configuration options * @param frameworkId optional framework ID for registering * redundant schedulers for the same framework */ MesosSchedulerDriver(Scheduler* sched, const std::map<std::string, std::string>& params, const FrameworkID& frameworkId = FrameworkID()); #ifndef SWIG /** * Create a scheduler driver with a config read from command-line arguments. * Additional Mesos config options are read from the environment, as well * as any config files given through conf or found in the environment. * * This constructor is not available through SWIG since it's difficult * for it to properly map arrays to an argc/argv pair. * * @param sched scheduler to make callbacks into * @param argc argument count * @param argv argument values (argument 0 is expected to be program name * and will not be looked at for options) * @param frameworkId optional framework ID for registering * redundant schedulers for the same framework */ MesosSchedulerDriver(Scheduler* sched, int argc, char** argv, const FrameworkID& frameworkId = FrameworkID()); #endif virtual ~MesosSchedulerDriver(); // Lifecycle methods. virtual int start(); virtual int stop(); virtual int join(); virtual int run(); // Start and then join driver. // Communication methods. virtual int sendFrameworkMessage(const FrameworkMessage& message); virtual int killTask(const TaskID& taskId); virtual int replyToOffer(const OfferID& offerId, const std::vector<TaskDescription>& tasks, const std::map<std::string, std::string>& params); virtual int replyToOffer(const OfferID& offerId, const std::vector<TaskDescription>& tasks) { return replyToOffer(offerId, tasks, std::map<std::string, std::string>()); } virtual int reviveOffers(); private: // Initialization method used by constructors void init(Scheduler* sched, internal::Configuration* conf, const FrameworkID& frameworkId); // Internal utility method to report an error to the scheduler void error(int code, const std::string& message); Scheduler* sched; std::string url; FrameworkID frameworkId; // Libprocess process for communicating with master internal::SchedulerProcess* process; // Coordination between masters internal::MasterDetector* detector; // Configuration options. // TODO(benh|matei): Does this still need to be a pointer? internal::Configuration* conf; // Are we currently registered with the master bool running; // Mutex to enforce all non-callbacks are execute serially pthread_mutex_t mutex; // Condition variable for waiting until driver terminates pthread_cond_t cond; }; } /* namespace mesos { */ #endif /* MESOS_SCHED_HPP */ <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * 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 "Util.hxx" #include <rtl/ustrbuf.hxx> using namespace ::connectivity; using namespace ::rtl; using namespace ::com::sun::star; using namespace ::com::sun::star::sdbc; using namespace ::com::sun::star::uno; OUString firebird::sanitizeIdentifier(const OUString& rIdentifier) { OUString sRet = rIdentifier.trim(); assert(sRet.getLength() <= 31); // Firebird identifiers cannot be longer than this. return sRet; } void firebird::evaluateStatusVector(ISC_STATUS_ARRAY& aStatusVector, const OUString& aCause, const uno::Reference< XInterface >& _rxContext) throw(SQLException) { if (aStatusVector[0]==1 && aStatusVector[1]) // indicates error { OUStringBuffer buf; char msg[512]; // Size is based on suggestion in docs. const ISC_STATUS* pStatus = (const ISC_STATUS*) &aStatusVector; buf.appendAscii("firebird_sdbc error:"); while(fb_interpret(msg, sizeof(msg), &pStatus)) { // TODO: verify encoding buf.appendAscii("\n*"); buf.append(OUString(msg, strlen(msg), RTL_TEXTENCODING_UTF8)); } buf.appendAscii("\ncaused by\n'").append(aCause).appendAscii("'\n"); OUString error = buf.makeStringAndClear(); SAL_WARN("connectivity.firebird", error); throw SQLException( error, _rxContext, OUString(), 1, Any() ); } } sal_Int32 firebird::getColumnTypeFromFBType(short aType) { aType &= ~1; // Remove last bit -- it is used to denote whether column // can store Null, not needed for type determination switch (aType) { case SQL_TEXT: return DataType::CHAR; case SQL_VARYING: return DataType::VARCHAR; case SQL_SHORT: return DataType::SMALLINT; case SQL_LONG: return DataType::INTEGER; case SQL_FLOAT: return DataType::FLOAT; case SQL_DOUBLE: return DataType::DOUBLE; case SQL_D_FLOAT: return DataType::DOUBLE; case SQL_TIMESTAMP: return DataType::TIMESTAMP; case SQL_BLOB: return DataType::BLOB; case SQL_ARRAY: return DataType::ARRAY; case SQL_TYPE_TIME: return DataType::TIME; case SQL_TYPE_DATE: return DataType::DATE; case SQL_INT64: return DataType::BIGINT; case SQL_NULL: return DataType::SQLNULL; case SQL_QUAD: // Is a "Blob ID" according to the docs return 0; // TODO: verify default: assert(false); // Should never happen return 0; } } OUString firebird::getColumnTypeNameFromFBType(short aType) { aType &= ~1; // Remove last bit -- it is used to denote whether column // can store Null, not needed for type determination switch (aType) { case SQL_TEXT: return OUString("SQL_TEXT"); case SQL_VARYING: return OUString("SQL_VARYING"); case SQL_SHORT: return OUString("SQL_SHORT"); case SQL_LONG: return OUString("SQL_LONG"); case SQL_FLOAT: return OUString("SQL_FLOAT"); case SQL_DOUBLE: return OUString("SQL_DOUBLE"); case SQL_D_FLOAT: return OUString("SQL_D_FLOAT"); case SQL_TIMESTAMP: return OUString("SQL_TIMESTAMP"); case SQL_BLOB: return OUString("SQL_BLOB"); case SQL_ARRAY: return OUString("SQL_ARRAY"); case SQL_TYPE_TIME: return OUString("SQL_TYPE_TIME"); case SQL_TYPE_DATE: return OUString("SQL_TYPE_DATE"); case SQL_INT64: return OUString("SQL_INT64"); case SQL_NULL: return OUString("SQL_NULL"); case SQL_QUAD: return OUString("SQL_QUAD"); default: assert(false); // Should never happen return OUString(); } } short firebird::getFBTypeFromBlrType(short blrType) { switch (blrType) { case blr_text: return SQL_TEXT; case blr_text2: assert(false); return 0; // No idea if this should be supported case blr_varying: return SQL_VARYING; case blr_varying2: assert(false); return 0; // No idea if this should be supported case blr_short: return SQL_SHORT; case blr_long: return SQL_LONG; case blr_float: return SQL_FLOAT; case blr_double: return SQL_DOUBLE; case blr_d_float: return SQL_D_FLOAT; case blr_timestamp: return SQL_TIMESTAMP; case blr_blob: return SQL_BLOB; // case blr_SQL_ARRAY: // return OUString("SQL_ARRAY"); case blr_sql_time: return SQL_TYPE_TIME; case blr_sql_date: return SQL_TYPE_DATE; case blr_int64: return SQL_INT64; // case SQL_NULL: // return OUString("SQL_NULL"); case blr_quad: return SQL_QUAD; default: // If this happens we have hit one of the extra types in ibase.h // look up blr_* for a list, e.g. blr_domain_name, blr_not_nullable etc. assert(false); return 0; } } void firebird::mallocSQLVAR(XSQLDA* pSqlda) { // TODO: confirm the sizings below. XSQLVAR* pVar = pSqlda->sqlvar; for (int i=0; i < pSqlda->sqld; i++, pVar++) { int dtype = (pVar->sqltype & ~1); /* drop flag bit for now */ switch(dtype) { case SQL_TEXT: pVar->sqldata = (char *)malloc(sizeof(char)*pVar->sqllen); break; case SQL_VARYING: pVar->sqldata = (char *)malloc(sizeof(char)*pVar->sqllen + 2); break; case SQL_SHORT: pVar->sqldata = (char *)malloc(sizeof(short)); break; case SQL_LONG: pVar->sqldata = (char *)malloc(sizeof(long)); break; case SQL_FLOAT: pVar->sqldata = (char *)malloc(sizeof(float)); break; case SQL_DOUBLE: pVar->sqldata = (char *)malloc(sizeof(double)); break; case SQL_D_FLOAT: pVar->sqldata = (char *)malloc(sizeof(double)); break; case SQL_TIMESTAMP: pVar->sqldata = (char*) malloc(sizeof(ISC_TIMESTAMP)); break; case SQL_BLOB: pVar->sqldata = (char*) malloc(sizeof(ISC_QUAD)); break; case SQL_ARRAY: assert(false); // TODO: implement break; case SQL_TYPE_TIME: pVar->sqldata = (char*) malloc(sizeof(ISC_TIME)); break; case SQL_TYPE_DATE: pVar->sqldata = (char*) malloc(sizeof(ISC_DATE)); break; case SQL_INT64: pVar->sqldata = (char *)malloc(sizeof(sal_Int64)); break; case SQL_NULL: assert(false); // TODO: implement break; case SQL_QUAD: assert(false); // TODO: implement break; default: SAL_WARN("connectivity.firebird", "Unknown type: " << dtype); assert(false); break; } if (pVar->sqltype & 1) { /* allocate variable to hold NULL status */ pVar->sqlind = (short *)malloc(sizeof(short)); } } } void firebird::freeSQLVAR(XSQLDA* pSqlda) { XSQLVAR* pVar = pSqlda->sqlvar; for (int i=0; i < pSqlda->sqld; i++, pVar++) { int dtype = (pVar->sqltype & ~1); /* drop flag bit for now */ switch(dtype) { case SQL_TEXT: case SQL_VARYING: case SQL_SHORT: case SQL_LONG: case SQL_FLOAT: case SQL_DOUBLE: case SQL_D_FLOAT: case SQL_TIMESTAMP: case SQL_BLOB: case SQL_INT64: case SQL_TYPE_TIME: case SQL_TYPE_DATE: free(pVar->sqldata); break; case SQL_ARRAY: assert(false); // TODO: implement break; case SQL_NULL: assert(false); // TODO: implement break; case SQL_QUAD: assert(false); // TODO: implement break; default: SAL_WARN("connectivity.firebird", "Unknown type: " << dtype); assert(false); break; } if (pVar->sqltype & 1) { free(pVar->sqlind); } } } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>Firebird: Use explicit integer sizes.<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * 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 "Util.hxx" #include <rtl/ustrbuf.hxx> using namespace ::connectivity; using namespace ::rtl; using namespace ::com::sun::star; using namespace ::com::sun::star::sdbc; using namespace ::com::sun::star::uno; OUString firebird::sanitizeIdentifier(const OUString& rIdentifier) { OUString sRet = rIdentifier.trim(); assert(sRet.getLength() <= 31); // Firebird identifiers cannot be longer than this. return sRet; } void firebird::evaluateStatusVector(ISC_STATUS_ARRAY& aStatusVector, const OUString& aCause, const uno::Reference< XInterface >& _rxContext) throw(SQLException) { if (aStatusVector[0]==1 && aStatusVector[1]) // indicates error { OUStringBuffer buf; char msg[512]; // Size is based on suggestion in docs. const ISC_STATUS* pStatus = (const ISC_STATUS*) &aStatusVector; buf.appendAscii("firebird_sdbc error:"); while(fb_interpret(msg, sizeof(msg), &pStatus)) { // TODO: verify encoding buf.appendAscii("\n*"); buf.append(OUString(msg, strlen(msg), RTL_TEXTENCODING_UTF8)); } buf.appendAscii("\ncaused by\n'").append(aCause).appendAscii("'\n"); OUString error = buf.makeStringAndClear(); SAL_WARN("connectivity.firebird", error); throw SQLException( error, _rxContext, OUString(), 1, Any() ); } } sal_Int32 firebird::getColumnTypeFromFBType(short aType) { aType &= ~1; // Remove last bit -- it is used to denote whether column // can store Null, not needed for type determination switch (aType) { case SQL_TEXT: return DataType::CHAR; case SQL_VARYING: return DataType::VARCHAR; case SQL_SHORT: return DataType::SMALLINT; case SQL_LONG: return DataType::INTEGER; case SQL_FLOAT: return DataType::FLOAT; case SQL_DOUBLE: return DataType::DOUBLE; case SQL_D_FLOAT: return DataType::DOUBLE; case SQL_TIMESTAMP: return DataType::TIMESTAMP; case SQL_BLOB: return DataType::BLOB; case SQL_ARRAY: return DataType::ARRAY; case SQL_TYPE_TIME: return DataType::TIME; case SQL_TYPE_DATE: return DataType::DATE; case SQL_INT64: return DataType::BIGINT; case SQL_NULL: return DataType::SQLNULL; case SQL_QUAD: // Is a "Blob ID" according to the docs return 0; // TODO: verify default: assert(false); // Should never happen return 0; } } OUString firebird::getColumnTypeNameFromFBType(short aType) { aType &= ~1; // Remove last bit -- it is used to denote whether column // can store Null, not needed for type determination switch (aType) { case SQL_TEXT: return OUString("SQL_TEXT"); case SQL_VARYING: return OUString("SQL_VARYING"); case SQL_SHORT: return OUString("SQL_SHORT"); case SQL_LONG: return OUString("SQL_LONG"); case SQL_FLOAT: return OUString("SQL_FLOAT"); case SQL_DOUBLE: return OUString("SQL_DOUBLE"); case SQL_D_FLOAT: return OUString("SQL_D_FLOAT"); case SQL_TIMESTAMP: return OUString("SQL_TIMESTAMP"); case SQL_BLOB: return OUString("SQL_BLOB"); case SQL_ARRAY: return OUString("SQL_ARRAY"); case SQL_TYPE_TIME: return OUString("SQL_TYPE_TIME"); case SQL_TYPE_DATE: return OUString("SQL_TYPE_DATE"); case SQL_INT64: return OUString("SQL_INT64"); case SQL_NULL: return OUString("SQL_NULL"); case SQL_QUAD: return OUString("SQL_QUAD"); default: assert(false); // Should never happen return OUString(); } } short firebird::getFBTypeFromBlrType(short blrType) { switch (blrType) { case blr_text: return SQL_TEXT; case blr_text2: assert(false); return 0; // No idea if this should be supported case blr_varying: return SQL_VARYING; case blr_varying2: assert(false); return 0; // No idea if this should be supported case blr_short: return SQL_SHORT; case blr_long: return SQL_LONG; case blr_float: return SQL_FLOAT; case blr_double: return SQL_DOUBLE; case blr_d_float: return SQL_D_FLOAT; case blr_timestamp: return SQL_TIMESTAMP; case blr_blob: return SQL_BLOB; // case blr_SQL_ARRAY: // return OUString("SQL_ARRAY"); case blr_sql_time: return SQL_TYPE_TIME; case blr_sql_date: return SQL_TYPE_DATE; case blr_int64: return SQL_INT64; // case SQL_NULL: // return OUString("SQL_NULL"); case blr_quad: return SQL_QUAD; default: // If this happens we have hit one of the extra types in ibase.h // look up blr_* for a list, e.g. blr_domain_name, blr_not_nullable etc. assert(false); return 0; } } void firebird::mallocSQLVAR(XSQLDA* pSqlda) { // TODO: confirm the sizings below. XSQLVAR* pVar = pSqlda->sqlvar; for (int i=0; i < pSqlda->sqld; i++, pVar++) { int dtype = (pVar->sqltype & ~1); /* drop flag bit for now */ switch(dtype) { case SQL_TEXT: pVar->sqldata = (char *)malloc(sizeof(char)*pVar->sqllen); break; case SQL_VARYING: pVar->sqldata = (char *)malloc(sizeof(char)*pVar->sqllen + 2); break; case SQL_SHORT: pVar->sqldata = (char*) malloc(sizeof(sal_Int16)); break; case SQL_LONG: pVar->sqldata = (char*) malloc(sizeof(sal_Int32)); break; case SQL_FLOAT: pVar->sqldata = (char *)malloc(sizeof(float)); break; case SQL_DOUBLE: pVar->sqldata = (char *)malloc(sizeof(double)); break; case SQL_D_FLOAT: pVar->sqldata = (char *)malloc(sizeof(double)); break; case SQL_TIMESTAMP: pVar->sqldata = (char*) malloc(sizeof(ISC_TIMESTAMP)); break; case SQL_BLOB: pVar->sqldata = (char*) malloc(sizeof(ISC_QUAD)); break; case SQL_ARRAY: assert(false); // TODO: implement break; case SQL_TYPE_TIME: pVar->sqldata = (char*) malloc(sizeof(ISC_TIME)); break; case SQL_TYPE_DATE: pVar->sqldata = (char*) malloc(sizeof(ISC_DATE)); break; case SQL_INT64: pVar->sqldata = (char *)malloc(sizeof(sal_Int64)); break; case SQL_NULL: assert(false); // TODO: implement break; case SQL_QUAD: assert(false); // TODO: implement break; default: SAL_WARN("connectivity.firebird", "Unknown type: " << dtype); assert(false); break; } if (pVar->sqltype & 1) { /* allocate variable to hold NULL status */ pVar->sqlind = (short *)malloc(sizeof(short)); } } } void firebird::freeSQLVAR(XSQLDA* pSqlda) { XSQLVAR* pVar = pSqlda->sqlvar; for (int i=0; i < pSqlda->sqld; i++, pVar++) { int dtype = (pVar->sqltype & ~1); /* drop flag bit for now */ switch(dtype) { case SQL_TEXT: case SQL_VARYING: case SQL_SHORT: case SQL_LONG: case SQL_FLOAT: case SQL_DOUBLE: case SQL_D_FLOAT: case SQL_TIMESTAMP: case SQL_BLOB: case SQL_INT64: case SQL_TYPE_TIME: case SQL_TYPE_DATE: free(pVar->sqldata); break; case SQL_ARRAY: assert(false); // TODO: implement break; case SQL_NULL: assert(false); // TODO: implement break; case SQL_QUAD: assert(false); // TODO: implement break; default: SAL_WARN("connectivity.firebird", "Unknown type: " << dtype); assert(false); break; } if (pVar->sqltype & 1) { free(pVar->sqlind); } } } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: YTables.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: rt $ $Date: 2004-10-22 08:44:24 $ * * 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): _______________________________________ * * ************************************************************************/ #ifndef CONNECTIVITY_MYSQL_TABLES_HXX #include "mysql/YTables.hxx" #endif #ifndef _CONNECTIVITY_MYSQL_VIEWS_HXX_ #include "mysql/YViews.hxx" #endif #ifndef CONNECTIVITY_MYSQL_TABLE_HXX #include "mysql/YTable.hxx" #endif #ifndef _COM_SUN_STAR_SDBC_XROW_HPP_ #include <com/sun/star/sdbc/XRow.hpp> #endif #ifndef _COM_SUN_STAR_SDBC_XRESULTSET_HPP_ #include <com/sun/star/sdbc/XResultSet.hpp> #endif #ifndef _COM_SUN_STAR_SDBC_COLUMNVALUE_HPP_ #include <com/sun/star/sdbc/ColumnValue.hpp> #endif #ifndef _COM_SUN_STAR_SDBCX_PRIVILEGE_HPP_ #include <com/sun/star/sdbcx/Privilege.hpp> #endif #ifndef _COM_SUN_STAR_SDBC_KEYRULE_HPP_ #include <com/sun/star/sdbc/KeyRule.hpp> #endif #ifndef _COM_SUN_STAR_SDBCX_KEYTYPE_HPP_ #include <com/sun/star/sdbcx/KeyType.hpp> #endif #ifndef CONNECTIVITY_MYSQL_CATALOG_HXX #include "mysql/YCatalog.hxx" #endif #ifndef _COMPHELPER_EXTRACT_HXX_ #include <comphelper/extract.hxx> #endif #ifndef _CONNECTIVITY_DBTOOLS_HXX_ #include "connectivity/dbtools.hxx" #endif #ifndef _DBHELPER_DBEXCEPTION_HXX_ #include "connectivity/dbexception.hxx" #endif #ifndef _CPPUHELPER_INTERFACECONTAINER_H_ #include <cppuhelper/interfacecontainer.h> #endif #ifndef _COMPHELPER_TYPES_HXX_ #include <comphelper/types.hxx> #endif #ifndef CONNECTIVITY_CONNECTION_HXX #include "TConnection.hxx" #endif using namespace ::comphelper; using namespace ::cppu; using namespace connectivity::mysql; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::beans; using namespace ::com::sun::star::sdbcx; using namespace ::com::sun::star::sdbc; using namespace ::com::sun::star::container; using namespace ::com::sun::star::lang; using namespace dbtools; typedef connectivity::sdbcx::OCollection OCollection_TYPE; Reference< XNamed > OTables::createObject(const ::rtl::OUString& _rName) { ::rtl::OUString sCatalog,sSchema,sTable; ::dbtools::qualifiedNameComponents(m_xMetaData,_rName,sCatalog,sSchema,sTable,::dbtools::eInDataManipulation); static const ::rtl::OUString s_sTableTypeView(RTL_CONSTASCII_USTRINGPARAM("VIEW")); static const ::rtl::OUString s_sTableTypeTable(RTL_CONSTASCII_USTRINGPARAM("TABLE")); static const ::rtl::OUString s_sAll(RTL_CONSTASCII_USTRINGPARAM("%")); Sequence< ::rtl::OUString > sTableTypes(3); sTableTypes[0] = s_sTableTypeView; sTableTypes[1] = s_sTableTypeTable; sTableTypes[2] = s_sAll; // just to be sure to include anything else .... Any aCatalog; if ( sCatalog.getLength() ) aCatalog <<= sCatalog; Reference< XResultSet > xResult = m_xMetaData->getTables(aCatalog,sSchema,sTable,sTableTypes); Reference< XNamed > xRet = NULL; if ( xResult.is() ) { Reference< XRow > xRow(xResult,UNO_QUERY); if ( xResult->next() ) // there can be only one table with this name { // Reference<XStatement> xStmt = m_xConnection->createStatement(); // if ( xStmt.is() ) // { // Reference< XResultSet > xPrivRes = xStmt->executeQuery(); // Reference< XRow > xPrivRow(xPrivRes,UNO_QUERY); // while ( xPrivRes.is() && xPrivRes->next() ) // { // if ( xPrivRow->getString(1) ) // { // } // } // } sal_Int32 nPrivileges = Privilege::DROP | Privilege::REFERENCE | Privilege::ALTER | Privilege::CREATE | Privilege::READ | Privilege::DELETE | Privilege::UPDATE | Privilege::INSERT | Privilege::SELECT; OMySQLTable* pRet = new OMySQLTable( this ,static_cast<OMySQLCatalog&>(m_rParent).getConnection() ,sTable ,xRow->getString(4) ,xRow->getString(5) ,sSchema ,sCatalog ,nPrivileges); xRet = pRet; } ::comphelper::disposeComponent(xResult); } return xRet; } // ------------------------------------------------------------------------- void OTables::impl_refresh( ) throw(RuntimeException) { static_cast<OMySQLCatalog&>(m_rParent).refreshTables(); } // ------------------------------------------------------------------------- void OTables::disposing(void) { m_xMetaData = NULL; OCollection::disposing(); } // ------------------------------------------------------------------------- Reference< XPropertySet > OTables::createEmptyObject() { return new OMySQLTable(this,static_cast<OMySQLCatalog&>(m_rParent).getConnection()); } // ----------------------------------------------------------------------------- Reference< XNamed > OTables::cloneObject(const Reference< XPropertySet >& _xDescriptor) { Reference< XNamed > xName(_xDescriptor,UNO_QUERY); OSL_ENSURE(xName.is(),"Must be a XName interface here !"); return xName.is() ? createObject(xName->getName()) : Reference< XNamed >(); } // ------------------------------------------------------------------------- // XAppend void OTables::appendObject( const Reference< XPropertySet >& descriptor ) { ::rtl::OUString aName = getString(descriptor->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_NAME))); if(!aName.getLength()) ::dbtools::throwFunctionSequenceException(static_cast<XTypeProvider*>(this)); createTable(descriptor); } // ------------------------------------------------------------------------- // XDrop void OTables::dropObject(sal_Int32 _nPos,const ::rtl::OUString _sElementName) { Reference< ::com::sun::star::lang::XUnoTunnel> xTunnel(getObject(_nPos),UNO_QUERY); sal_Bool bIsNew = sal_False; if(xTunnel.is()) { connectivity::sdbcx::ODescriptor* pTable = (connectivity::sdbcx::ODescriptor*)xTunnel->getSomething(connectivity::sdbcx::ODescriptor::getUnoTunnelImplementationId()); if(pTable) bIsNew = pTable->isNew(); } if (!bIsNew) { Reference< XConnection > xConnection = static_cast<OMySQLCatalog&>(m_rParent).getConnection(); ::rtl::OUString sCatalog,sSchema,sTable; ::dbtools::qualifiedNameComponents(m_xMetaData,_sElementName,sCatalog,sSchema,sTable,::dbtools::eInDataManipulation); ::rtl::OUString aSql = ::rtl::OUString::createFromAscii("DROP "); Reference<XPropertySet> xProp(xTunnel,UNO_QUERY); sal_Bool bIsView; if(bIsView = (xProp.is() && ::comphelper::getString(xProp->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_TYPE))) == ::rtl::OUString::createFromAscii("VIEW"))) // here we have a view aSql += ::rtl::OUString::createFromAscii("VIEW "); else aSql += ::rtl::OUString::createFromAscii("TABLE "); ::rtl::OUString sComposedName; ::dbtools::composeTableName(m_xMetaData,sCatalog,sSchema,sTable,sComposedName,sal_True,::dbtools::eInDataManipulation); aSql += sComposedName; Reference< XStatement > xStmt = xConnection->createStatement( ); if ( xStmt.is() ) { xStmt->execute(aSql); ::comphelper::disposeComponent(xStmt); } // if no exception was thrown we must delete it from the views if ( bIsView ) { OViews* pViews = static_cast<OViews*>(static_cast<OMySQLCatalog&>(m_rParent).getPrivateViews()); if ( pViews && pViews->hasByName(_sElementName) ) pViews->dropByNameImpl(_sElementName); } } } // ------------------------------------------------------------------------- void OTables::createTable( const Reference< XPropertySet >& descriptor ) { Reference< XConnection > xConnection = static_cast<OMySQLCatalog&>(m_rParent).getConnection(); ::rtl::OUString aSql = ::dbtools::createSqlCreateTableStatement(descriptor,xConnection); Reference< XStatement > xStmt = xConnection->createStatement( ); if ( xStmt.is() ) { xStmt->execute(aSql); ::comphelper::disposeComponent(xStmt); } } // ----------------------------------------------------------------------------- void OTables::appendNew(const ::rtl::OUString& _rsNewTable) { insertElement(_rsNewTable,NULL); // notify our container listeners ContainerEvent aEvent(static_cast<XContainer*>(this), makeAny(_rsNewTable), Any(), Any()); OInterfaceIteratorHelper aListenerLoop(m_aContainerListeners); while (aListenerLoop.hasMoreElements()) static_cast<XContainerListener*>(aListenerLoop.next())->elementInserted(aEvent); } // ----------------------------------------------------------------------------- <commit_msg>INTEGRATION: CWS dba24 (1.5.32); FILE MERGED 2005/02/09 08:07:47 oj 1.5.32.1: #i26950# remove the need for XNamed<commit_after>/************************************************************************* * * $RCSfile: YTables.cxx,v $ * * $Revision: 1.6 $ * * last change: $Author: vg $ $Date: 2005-03-10 15:31:32 $ * * 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): _______________________________________ * * ************************************************************************/ #ifndef CONNECTIVITY_MYSQL_TABLES_HXX #include "mysql/YTables.hxx" #endif #ifndef _CONNECTIVITY_MYSQL_VIEWS_HXX_ #include "mysql/YViews.hxx" #endif #ifndef CONNECTIVITY_MYSQL_TABLE_HXX #include "mysql/YTable.hxx" #endif #ifndef _COM_SUN_STAR_SDBC_XROW_HPP_ #include <com/sun/star/sdbc/XRow.hpp> #endif #ifndef _COM_SUN_STAR_SDBC_XRESULTSET_HPP_ #include <com/sun/star/sdbc/XResultSet.hpp> #endif #ifndef _COM_SUN_STAR_SDBC_COLUMNVALUE_HPP_ #include <com/sun/star/sdbc/ColumnValue.hpp> #endif #ifndef _COM_SUN_STAR_SDBCX_PRIVILEGE_HPP_ #include <com/sun/star/sdbcx/Privilege.hpp> #endif #ifndef _COM_SUN_STAR_SDBC_KEYRULE_HPP_ #include <com/sun/star/sdbc/KeyRule.hpp> #endif #ifndef _COM_SUN_STAR_SDBCX_KEYTYPE_HPP_ #include <com/sun/star/sdbcx/KeyType.hpp> #endif #ifndef CONNECTIVITY_MYSQL_CATALOG_HXX #include "mysql/YCatalog.hxx" #endif #ifndef _COMPHELPER_EXTRACT_HXX_ #include <comphelper/extract.hxx> #endif #ifndef _CONNECTIVITY_DBTOOLS_HXX_ #include "connectivity/dbtools.hxx" #endif #ifndef _DBHELPER_DBEXCEPTION_HXX_ #include "connectivity/dbexception.hxx" #endif #ifndef _CPPUHELPER_INTERFACECONTAINER_H_ #include <cppuhelper/interfacecontainer.h> #endif #ifndef _COMPHELPER_TYPES_HXX_ #include <comphelper/types.hxx> #endif #ifndef CONNECTIVITY_CONNECTION_HXX #include "TConnection.hxx" #endif using namespace ::comphelper; using namespace connectivity; using namespace ::cppu; using namespace connectivity::mysql; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::beans; using namespace ::com::sun::star::sdbcx; using namespace ::com::sun::star::sdbc; using namespace ::com::sun::star::container; using namespace ::com::sun::star::lang; using namespace dbtools; typedef connectivity::sdbcx::OCollection OCollection_TYPE; sdbcx::ObjectType OTables::createObject(const ::rtl::OUString& _rName) { ::rtl::OUString sCatalog,sSchema,sTable; ::dbtools::qualifiedNameComponents(m_xMetaData,_rName,sCatalog,sSchema,sTable,::dbtools::eInDataManipulation); static const ::rtl::OUString s_sTableTypeView(RTL_CONSTASCII_USTRINGPARAM("VIEW")); static const ::rtl::OUString s_sTableTypeTable(RTL_CONSTASCII_USTRINGPARAM("TABLE")); static const ::rtl::OUString s_sAll(RTL_CONSTASCII_USTRINGPARAM("%")); Sequence< ::rtl::OUString > sTableTypes(3); sTableTypes[0] = s_sTableTypeView; sTableTypes[1] = s_sTableTypeTable; sTableTypes[2] = s_sAll; // just to be sure to include anything else .... Any aCatalog; if ( sCatalog.getLength() ) aCatalog <<= sCatalog; Reference< XResultSet > xResult = m_xMetaData->getTables(aCatalog,sSchema,sTable,sTableTypes); sdbcx::ObjectType xRet = NULL; if ( xResult.is() ) { Reference< XRow > xRow(xResult,UNO_QUERY); if ( xResult->next() ) // there can be only one table with this name { // Reference<XStatement> xStmt = m_xConnection->createStatement(); // if ( xStmt.is() ) // { // Reference< XResultSet > xPrivRes = xStmt->executeQuery(); // Reference< XRow > xPrivRow(xPrivRes,UNO_QUERY); // while ( xPrivRes.is() && xPrivRes->next() ) // { // if ( xPrivRow->getString(1) ) // { // } // } // } sal_Int32 nPrivileges = Privilege::DROP | Privilege::REFERENCE | Privilege::ALTER | Privilege::CREATE | Privilege::READ | Privilege::DELETE | Privilege::UPDATE | Privilege::INSERT | Privilege::SELECT; OMySQLTable* pRet = new OMySQLTable( this ,static_cast<OMySQLCatalog&>(m_rParent).getConnection() ,sTable ,xRow->getString(4) ,xRow->getString(5) ,sSchema ,sCatalog ,nPrivileges); xRet = pRet; } ::comphelper::disposeComponent(xResult); } return xRet; } // ------------------------------------------------------------------------- void OTables::impl_refresh( ) throw(RuntimeException) { static_cast<OMySQLCatalog&>(m_rParent).refreshTables(); } // ------------------------------------------------------------------------- void OTables::disposing(void) { m_xMetaData = NULL; OCollection::disposing(); } // ------------------------------------------------------------------------- Reference< XPropertySet > OTables::createEmptyObject() { return new OMySQLTable(this,static_cast<OMySQLCatalog&>(m_rParent).getConnection()); } // ------------------------------------------------------------------------- // XAppend void OTables::appendObject( const Reference< XPropertySet >& descriptor ) { ::rtl::OUString aName = getString(descriptor->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_NAME))); if(!aName.getLength()) ::dbtools::throwFunctionSequenceException(static_cast<XTypeProvider*>(this)); createTable(descriptor); } // ------------------------------------------------------------------------- // XDrop void OTables::dropObject(sal_Int32 _nPos,const ::rtl::OUString _sElementName) { Reference< ::com::sun::star::lang::XUnoTunnel> xTunnel(getObject(_nPos),UNO_QUERY); sal_Bool bIsNew = sal_False; if(xTunnel.is()) { connectivity::sdbcx::ODescriptor* pTable = (connectivity::sdbcx::ODescriptor*)xTunnel->getSomething(connectivity::sdbcx::ODescriptor::getUnoTunnelImplementationId()); if(pTable) bIsNew = pTable->isNew(); } if (!bIsNew) { Reference< XConnection > xConnection = static_cast<OMySQLCatalog&>(m_rParent).getConnection(); ::rtl::OUString sCatalog,sSchema,sTable; ::dbtools::qualifiedNameComponents(m_xMetaData,_sElementName,sCatalog,sSchema,sTable,::dbtools::eInDataManipulation); ::rtl::OUString aSql = ::rtl::OUString::createFromAscii("DROP "); Reference<XPropertySet> xProp(xTunnel,UNO_QUERY); sal_Bool bIsView; if(bIsView = (xProp.is() && ::comphelper::getString(xProp->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_TYPE))) == ::rtl::OUString::createFromAscii("VIEW"))) // here we have a view aSql += ::rtl::OUString::createFromAscii("VIEW "); else aSql += ::rtl::OUString::createFromAscii("TABLE "); ::rtl::OUString sComposedName; ::dbtools::composeTableName(m_xMetaData,sCatalog,sSchema,sTable,sComposedName,sal_True,::dbtools::eInDataManipulation); aSql += sComposedName; Reference< XStatement > xStmt = xConnection->createStatement( ); if ( xStmt.is() ) { xStmt->execute(aSql); ::comphelper::disposeComponent(xStmt); } // if no exception was thrown we must delete it from the views if ( bIsView ) { OViews* pViews = static_cast<OViews*>(static_cast<OMySQLCatalog&>(m_rParent).getPrivateViews()); if ( pViews && pViews->hasByName(_sElementName) ) pViews->dropByNameImpl(_sElementName); } } } // ------------------------------------------------------------------------- void OTables::createTable( const Reference< XPropertySet >& descriptor ) { Reference< XConnection > xConnection = static_cast<OMySQLCatalog&>(m_rParent).getConnection(); ::rtl::OUString aSql = ::dbtools::createSqlCreateTableStatement(descriptor,xConnection); Reference< XStatement > xStmt = xConnection->createStatement( ); if ( xStmt.is() ) { xStmt->execute(aSql); ::comphelper::disposeComponent(xStmt); } } // ----------------------------------------------------------------------------- void OTables::appendNew(const ::rtl::OUString& _rsNewTable) { insertElement(_rsNewTable,NULL); // notify our container listeners ContainerEvent aEvent(static_cast<XContainer*>(this), makeAny(_rsNewTable), Any(), Any()); OInterfaceIteratorHelper aListenerLoop(m_aContainerListeners); while (aListenerLoop.hasMoreElements()) static_cast<XContainerListener*>(aListenerLoop.next())->elementInserted(aEvent); } // ----------------------------------------------------------------------------- ::rtl::OUString OTables::getNameForObject(const sdbcx::ObjectType& _xObject) { OSL_ENSURE(_xObject.is(),"OTables::getNameForObject: Object is NULL!"); return ::dbtools::composeTableName(m_xMetaData,_xObject,sal_False,::dbtools::eInDataManipulation); } // ----------------------------------------------------------------------------- <|endoftext|>
<commit_before>/* * trie_buffer.hpp * * Created on: Feb 17, 2015 * Author: masha */ #ifndef INCLUDE_POOL_BUFFER_HPP_ #define INCLUDE_POOL_BUFFER_HPP_ #include "abaptr.hpp" #include <atomic> #include <cassert> #include <algorithm> namespace lfds { namespace { template<class T> struct pool_node { typedef pool_node<T> this_type; this_type* m_next; T m_data; static this_type* recover(T* p) { static constexpr int offset = reinterpret_cast<char*>(&reinterpret_cast<this_type*>(0)->m_data) - reinterpret_cast<char*>(0); return reinterpret_cast<this_type*>(reinterpret_cast<char*>(p) - offset); } }; template<class T, class Allocator> struct pool_chunk { typedef pool_chunk<T, Allocator> this_type; typedef pool_node<T> node_type; typedef std::size_t size_type; typedef T value_type; typedef typename Allocator::template rebind<value_type>::other allocator_type; this_type* m_next; size_type m_size; node_type m_data[1]; //-- trailing array of nodes pool_chunk(size_type size) : m_next(), m_size(size) { } void construct(allocator_type & a) { for (size_type i = 0; i < m_size; ++i) { a.construct(&m_data[i]); } } void destroy(allocator_type & a) { for (size_type i = 0; i < m_size; ++i) { a.destroy(&m_data[i]); } } static size_type getByteSize(size_type chunkSize) { return sizeof(this_type) + sizeof(node_type) * (chunkSize - 1); } }; template<class T> inline void atomic_push(std::atomic<T*> & list, T* head, T* tail) { bool success; do { tail->m_next = list.load(std::memory_order_relaxed); success = list.compare_exchange_weak(tail->m_next, tail->m_next, std::memory_order_relaxed, std::memory_order_relaxed); } while (!success); } template<class T> inline void atomic_push(std::atomic<T*> & list, T* val) { atomic_push(list, val, val); } template<class T> inline void atomic_push(volatile abaptr<T> & list, T* head, T* tail) { bool success; do { abaptr<T> old_ptr = list; tail->m_next = old_ptr.m_ptr; abaptr<T> new_ptr = { head, old_ptr.m_counter + 1 }; success = list.atomic_cas(old_ptr, new_ptr); } while (!success); } template<class T> inline void atomic_push(volatile abaptr<T> & list, T* val) { atomic_push(list, val, val); } } template<class T, class Allocator> class pool_buffer { public: typedef pool_buffer<T, Allocator> this_type; typedef T value_type; typedef pool_chunk<value_type, Allocator> chunk_type; typedef typename Allocator::template rebind<char>::other byte_allocator_type; typedef typename Allocator::template rebind<chunk_type>::other chunk_allocator_type; typedef typename chunk_type::node_type node_type; typedef typename chunk_type::allocator_type node_allocator_type; typedef std::size_t size_type; static constexpr unsigned int MIN_SIZE = 32; private: pool_buffer(const this_type&) = delete; this_type& operator=(const this_type&) = delete; public: pool_buffer(size_type initialCapacity) : m_reserved(0), m_freeNodes(nullptr), m_chunks(nullptr), m_byte_allocator(), m_node_allocator(), m_chunk_allocator() { m_freeNodes.m_ptr = reserve(initialCapacity).first; } ~pool_buffer() { chunk_type* chunk = m_chunks.load(std::memory_order_relaxed); while (chunk) { chunk_type* next = chunk->m_next; deallocate_chunk(chunk); chunk = next; } } T* allocate() { // pop node bool success = false; node_type* node; do { abaptr<node_type> old_val = m_freeNodes; node = old_val.m_ptr; if (!node) { auto headtail = reserve(size()); node = headtail.first; node_type* head = node->m_next; node_type* tail = headtail.second; atomic_push(m_freeNodes, head, tail); break; } else { abaptr<node_type> new_val = { node->m_next, old_val.m_counter + 1 }; success = m_freeNodes.atomic_cas(old_val, new_val); } } while (!success); return &node->m_data; } void deallocate(T* p) { node_type* node = node_type::recover(p); atomic_push(m_freeNodes, node); } size_type size() const { return m_reserved.load(std::memory_order_relaxed); } private: std::pair<node_type*, node_type*> reserve(size_type size) { static constexpr size_type min_size = MIN_SIZE; size_type chunk_size = std::max(size, min_size); chunk_type* chunk = allocate_chunk(chunk_size); node_type* data = chunk->m_data; node_type* head = data; head->m_next = nullptr; for (size_type i = 1; i < chunk->m_size; ++i) { node_type* node = &data[i]; node->m_next = head; head = node; } atomic_push(m_chunks, chunk); m_reserved.fetch_add(chunk_size, std::memory_order_relaxed); return std::make_pair(head, data); } chunk_type* allocate_chunk(size_type chunk_size) { size_type byte_size = chunk_type::getByteSize(chunk_size); char* raw_ptr = m_byte_allocator.allocate(byte_size); chunk_type* chunk = reinterpret_cast<chunk_type*>(raw_ptr); m_chunk_allocator.construct(chunk, chunk_size); chunk->construct(m_node_allocator); return chunk; } void deallocate_chunk(chunk_type* chunk) { size_type byte_size = chunk_type::getByteSize(chunk->m_size); char* raw_ptr = reinterpret_cast<char*>(chunk); chunk->destroy(m_node_allocator); m_chunk_allocator.destroy(chunk); m_byte_allocator.deallocate(raw_ptr, byte_size); } private: std::atomic<size_type> m_reserved; volatile abaptr<node_type> m_freeNodes; std::atomic<chunk_type*> m_chunks; byte_allocator_type m_byte_allocator; node_allocator_type m_node_allocator; chunk_allocator_type m_chunk_allocator; }; } #endif /* INCLUDE_POOL_BUFFER_HPP_ */ <commit_msg>Warning fixed<commit_after>/* * trie_buffer.hpp * * Created on: Feb 17, 2015 * Author: masha */ #ifndef INCLUDE_POOL_BUFFER_HPP_ #define INCLUDE_POOL_BUFFER_HPP_ #include "abaptr.hpp" #include <atomic> #include <cassert> #include <cstddef> #include <algorithm> namespace lfds { namespace { template<class T> struct pool_node { typedef pool_node<T> this_type; this_type* m_next; T m_data; static this_type* recover(T* p) { static constexpr int offset = offsetof(this_type, m_data); return reinterpret_cast<this_type*>(reinterpret_cast<char*>(p) - offset); } }; template<class T, class Allocator> struct pool_chunk { typedef pool_chunk<T, Allocator> this_type; typedef pool_node<T> node_type; typedef std::size_t size_type; typedef T value_type; typedef typename Allocator::template rebind<value_type>::other allocator_type; this_type* m_next; size_type m_size; node_type m_data[1]; //-- trailing array of nodes pool_chunk(size_type size) : m_next(), m_size(size) { } void construct(allocator_type & a) { for (size_type i = 0; i < m_size; ++i) { a.construct(&m_data[i]); } } void destroy(allocator_type & a) { for (size_type i = 0; i < m_size; ++i) { a.destroy(&m_data[i]); } } static size_type getByteSize(size_type chunkSize) { return sizeof(this_type) + sizeof(node_type) * (chunkSize - 1); } }; template<class T> inline void atomic_push(std::atomic<T*> & list, T* head, T* tail) { bool success; do { tail->m_next = list.load(std::memory_order_relaxed); success = list.compare_exchange_weak(tail->m_next, tail->m_next, std::memory_order_relaxed, std::memory_order_relaxed); } while (!success); } template<class T> inline void atomic_push(std::atomic<T*> & list, T* val) { atomic_push(list, val, val); } template<class T> inline void atomic_push(volatile abaptr<T> & list, T* head, T* tail) { bool success; do { abaptr<T> old_ptr = list; tail->m_next = old_ptr.m_ptr; abaptr<T> new_ptr = { head, old_ptr.m_counter + 1 }; success = list.atomic_cas(old_ptr, new_ptr); } while (!success); } template<class T> inline void atomic_push(volatile abaptr<T> & list, T* val) { atomic_push(list, val, val); } } template<class T, class Allocator> class pool_buffer { public: typedef pool_buffer<T, Allocator> this_type; typedef T value_type; typedef pool_chunk<value_type, Allocator> chunk_type; typedef typename Allocator::template rebind<char>::other byte_allocator_type; typedef typename Allocator::template rebind<chunk_type>::other chunk_allocator_type; typedef typename chunk_type::node_type node_type; typedef typename chunk_type::allocator_type node_allocator_type; typedef std::size_t size_type; static constexpr unsigned int MIN_SIZE = 32; private: pool_buffer(const this_type&) = delete; this_type& operator=(const this_type&) = delete; public: pool_buffer(size_type initialCapacity) : m_reserved(0), m_freeNodes(nullptr), m_chunks(nullptr), m_byte_allocator(), m_node_allocator(), m_chunk_allocator() { m_freeNodes.m_ptr = reserve(initialCapacity).first; } ~pool_buffer() { chunk_type* chunk = m_chunks.load(std::memory_order_relaxed); while (chunk) { chunk_type* next = chunk->m_next; deallocate_chunk(chunk); chunk = next; } } T* allocate() { // pop node bool success = false; node_type* node; do { abaptr<node_type> old_val = m_freeNodes; node = old_val.m_ptr; if (!node) { auto headtail = reserve(size()); node = headtail.first; node_type* head = node->m_next; node_type* tail = headtail.second; atomic_push(m_freeNodes, head, tail); break; } else { abaptr<node_type> new_val = { node->m_next, old_val.m_counter + 1 }; success = m_freeNodes.atomic_cas(old_val, new_val); } } while (!success); return &node->m_data; } void deallocate(T* p) { node_type* node = node_type::recover(p); atomic_push(m_freeNodes, node); } size_type size() const { return m_reserved.load(std::memory_order_relaxed); } private: std::pair<node_type*, node_type*> reserve(size_type size) { static constexpr size_type min_size = MIN_SIZE; size_type chunk_size = std::max(size, min_size); chunk_type* chunk = allocate_chunk(chunk_size); node_type* data = chunk->m_data; node_type* head = data; head->m_next = nullptr; for (size_type i = 1; i < chunk->m_size; ++i) { node_type* node = &data[i]; node->m_next = head; head = node; } atomic_push(m_chunks, chunk); m_reserved.fetch_add(chunk_size, std::memory_order_relaxed); return std::make_pair(head, data); } chunk_type* allocate_chunk(size_type chunk_size) { size_type byte_size = chunk_type::getByteSize(chunk_size); char* raw_ptr = m_byte_allocator.allocate(byte_size); chunk_type* chunk = reinterpret_cast<chunk_type*>(raw_ptr); m_chunk_allocator.construct(chunk, chunk_size); chunk->construct(m_node_allocator); return chunk; } void deallocate_chunk(chunk_type* chunk) { size_type byte_size = chunk_type::getByteSize(chunk->m_size); char* raw_ptr = reinterpret_cast<char*>(chunk); chunk->destroy(m_node_allocator); m_chunk_allocator.destroy(chunk); m_byte_allocator.deallocate(raw_ptr, byte_size); } private: std::atomic<size_type> m_reserved; volatile abaptr<node_type> m_freeNodes; std::atomic<chunk_type*> m_chunks; byte_allocator_type m_byte_allocator; node_allocator_type m_node_allocator; chunk_allocator_type m_chunk_allocator; }; } #endif /* INCLUDE_POOL_BUFFER_HPP_ */ <|endoftext|>
<commit_before>#ifndef __RANK_FILTER__ #define __RANK_FILTER__ #include <deque> #include <cassert> #include <functional> #include <iostream> #include <iterator> #include <boost/array.hpp> #include <boost/container/set.hpp> #include <boost/container/node_allocator.hpp> #include <boost/math/special_functions/round.hpp> #include <boost/static_assert.hpp> #include <boost/type_traits.hpp> namespace rank_filter { template<class I1, class I2> inline void lineRankOrderFilter1D(const I1& src_begin, const I1& src_end, I2& dest_begin, I2& dest_end, size_t half_length, double rank) { // Types in use. typedef typename std::iterator_traits<I1>::value_type T1; typedef typename std::iterator_traits<I2>::value_type T2; typedef typename std::iterator_traits<I1>::difference_type I1_diff_t; typedef typename std::iterator_traits<I2>::difference_type I2_diff_t; // Establish common types to work with source and destination values. BOOST_STATIC_ASSERT((boost::is_same<T1, T2>::value)); typedef T1 T; typedef typename boost::common_type<I1_diff_t, I2_diff_t>::type I_diff_t; // Define container types that will be used. typedef boost::container::multiset< T, std::less<T>, boost::container::node_allocator<T>, boost::container::tree_assoc_options< boost::container::tree_type<boost::container::scapegoat_tree> >::type> multiset; typedef std::deque< typename multiset::iterator > deque; // Lengths. const I_diff_t src_size = std::distance(src_begin, src_end); const I_diff_t dest_size = std::distance(dest_begin, dest_end); // Ensure the result will fit. assert(src_size <= dest_size); // Window length cannot exceed input data with reflection. assert((half_length + 1) <= src_size); // Rank must be in the range 0 to 1. assert((0 <= rank) && (rank <= 1)); // The position of the window. I_diff_t window_begin = 0; // Find window offset corresponding to this rank. const I_diff_t rank_pos = static_cast<I_diff_t>(boost::math::round(rank * (2 * half_length))); typename multiset::iterator rank_point; // Track values in window both in sorted and sequential order. multiset sorted_window; deque window_iters(2 * half_length + 1); // Get the initial sorted window. // Include the reflection. for (I_diff_t j = 0; j < half_length; j++) { window_iters[j] = sorted_window.insert(src_begin[window_begin + half_length - j]); } for (I_diff_t j = half_length; j < (2 * half_length + 1); j++) { window_iters[j] = sorted_window.insert(src_begin[window_begin + j - half_length]); } rank_point = sorted_window.begin(); for (I_diff_t i = 0; i < rank_pos; i++) { rank_point++; } typename multiset::iterator prev_iter; T prev_value; T next_value; while ( window_begin < src_size ) { dest_begin[window_begin] = *rank_point; prev_iter = window_iters.front(); prev_value = *prev_iter; window_iters.pop_front(); window_begin++; if ( window_begin == src_size ) { next_value = prev_value; } else if ( window_begin < (src_size - half_length) ) { next_value = src_begin[window_begin + half_length]; } else { next_value = *(window_iters[(2 * (src_size - (window_begin + 1)))]); } if ( ( *rank_point < prev_value ) && ( *rank_point <= next_value ) ) { sorted_window.erase(prev_iter); window_iters.push_back(sorted_window.insert(next_value)); } else if ( ( *rank_point >= prev_value ) && ( *rank_point > next_value ) ) { if ( rank_point == prev_iter ) { window_iters.push_back(sorted_window.insert(next_value)); rank_point--; sorted_window.erase(prev_iter); } else { sorted_window.erase(prev_iter); window_iters.push_back(sorted_window.insert(next_value)); } } else if ( ( *rank_point < prev_value ) && ( *rank_point > next_value ) ) { sorted_window.erase(prev_iter); window_iters.push_back(sorted_window.insert(next_value)); rank_point--; } else if ( ( *rank_point >= prev_value ) && ( *rank_point <= next_value ) ) { if (rank_point == prev_iter) { window_iters.push_back(sorted_window.insert(next_value)); rank_point++; sorted_window.erase(prev_iter); } else { sorted_window.erase(prev_iter); window_iters.push_back(sorted_window.insert(next_value)); rank_point++; } } } } } namespace std { template <class T, size_t N> ostream& operator<<(ostream& out, const boost::array<T, N>& that) { out << "{ "; for (unsigned int i = 0; i < (N - 1); i++) { out << that[i] << ", "; } out << that[N - 1] << " }"; return(out); } } #endif //__RANK_FILTER__ <commit_msg>Adjust window rank comment<commit_after>#ifndef __RANK_FILTER__ #define __RANK_FILTER__ #include <deque> #include <cassert> #include <functional> #include <iostream> #include <iterator> #include <boost/array.hpp> #include <boost/container/set.hpp> #include <boost/container/node_allocator.hpp> #include <boost/math/special_functions/round.hpp> #include <boost/static_assert.hpp> #include <boost/type_traits.hpp> namespace rank_filter { template<class I1, class I2> inline void lineRankOrderFilter1D(const I1& src_begin, const I1& src_end, I2& dest_begin, I2& dest_end, size_t half_length, double rank) { // Types in use. typedef typename std::iterator_traits<I1>::value_type T1; typedef typename std::iterator_traits<I2>::value_type T2; typedef typename std::iterator_traits<I1>::difference_type I1_diff_t; typedef typename std::iterator_traits<I2>::difference_type I2_diff_t; // Establish common types to work with source and destination values. BOOST_STATIC_ASSERT((boost::is_same<T1, T2>::value)); typedef T1 T; typedef typename boost::common_type<I1_diff_t, I2_diff_t>::type I_diff_t; // Define container types that will be used. typedef boost::container::multiset< T, std::less<T>, boost::container::node_allocator<T>, boost::container::tree_assoc_options< boost::container::tree_type<boost::container::scapegoat_tree> >::type> multiset; typedef std::deque< typename multiset::iterator > deque; // Lengths. const I_diff_t src_size = std::distance(src_begin, src_end); const I_diff_t dest_size = std::distance(dest_begin, dest_end); // Ensure the result will fit. assert(src_size <= dest_size); // Window length cannot exceed input data with reflection. assert((half_length + 1) <= src_size); // Rank must be in the range 0 to 1. assert((0 <= rank) && (rank <= 1)); // The position of the window. I_diff_t window_begin = 0; // Window position corresponding to this rank. const I_diff_t rank_pos = static_cast<I_diff_t>(boost::math::round(rank * (2 * half_length))); typename multiset::iterator rank_point; // Track values in window both in sorted and sequential order. multiset sorted_window; deque window_iters(2 * half_length + 1); // Get the initial sorted window. // Include the reflection. for (I_diff_t j = 0; j < half_length; j++) { window_iters[j] = sorted_window.insert(src_begin[window_begin + half_length - j]); } for (I_diff_t j = half_length; j < (2 * half_length + 1); j++) { window_iters[j] = sorted_window.insert(src_begin[window_begin + j - half_length]); } rank_point = sorted_window.begin(); for (I_diff_t i = 0; i < rank_pos; i++) { rank_point++; } typename multiset::iterator prev_iter; T prev_value; T next_value; while ( window_begin < src_size ) { dest_begin[window_begin] = *rank_point; prev_iter = window_iters.front(); prev_value = *prev_iter; window_iters.pop_front(); window_begin++; if ( window_begin == src_size ) { next_value = prev_value; } else if ( window_begin < (src_size - half_length) ) { next_value = src_begin[window_begin + half_length]; } else { next_value = *(window_iters[(2 * (src_size - (window_begin + 1)))]); } if ( ( *rank_point < prev_value ) && ( *rank_point <= next_value ) ) { sorted_window.erase(prev_iter); window_iters.push_back(sorted_window.insert(next_value)); } else if ( ( *rank_point >= prev_value ) && ( *rank_point > next_value ) ) { if ( rank_point == prev_iter ) { window_iters.push_back(sorted_window.insert(next_value)); rank_point--; sorted_window.erase(prev_iter); } else { sorted_window.erase(prev_iter); window_iters.push_back(sorted_window.insert(next_value)); } } else if ( ( *rank_point < prev_value ) && ( *rank_point > next_value ) ) { sorted_window.erase(prev_iter); window_iters.push_back(sorted_window.insert(next_value)); rank_point--; } else if ( ( *rank_point >= prev_value ) && ( *rank_point <= next_value ) ) { if (rank_point == prev_iter) { window_iters.push_back(sorted_window.insert(next_value)); rank_point++; sorted_window.erase(prev_iter); } else { sorted_window.erase(prev_iter); window_iters.push_back(sorted_window.insert(next_value)); rank_point++; } } } } } namespace std { template <class T, size_t N> ostream& operator<<(ostream& out, const boost::array<T, N>& that) { out << "{ "; for (unsigned int i = 0; i < (N - 1); i++) { out << that[i] << ", "; } out << that[N - 1] << " }"; return(out); } } #endif //__RANK_FILTER__ <|endoftext|>
<commit_before>/* * Copyright 2016-2017 deepstreamHub GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef DEEPSTREAM_SCOPEGUARD_HPP #define DEEPSTREAM_SCOPEGUARD_HPP #include <functional> #include <boost/preprocessor/cat.hpp> #include <use.hpp> namespace deepstream { // A. Alexandrescu, P. Marginean: // "Generic: Change the Way You Write Exception-Safe Code -- Forever" // Dr. Dobbs Journal, 2000 // www.drdobbs.com/cpp/generic-change-the-way-you-write-excepti/184403758 struct ScopeGuard { typedef std::function<void(void)> FunT; ScopeGuard(FunT f) : f_(f) {}; ~ScopeGuard() { f_(); } FunT f_; }; } #define DEEPSTREAM_ON_EXIT(...) \ const ::deepstream::ScopeGuard BOOST_PP_CAT(deepstream_guard,__LINE__)(__VA_ARGS__); \ ::deepstream::use( BOOST_PP_CAT(deepstream_guard, __LINE__) ) #endif <commit_msg>Src: fix a Clang warning<commit_after>/* * Copyright 2016-2017 deepstreamHub GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef DEEPSTREAM_SCOPEGUARD_HPP #define DEEPSTREAM_SCOPEGUARD_HPP #include <functional> #include <boost/preprocessor/cat.hpp> #include <use.hpp> namespace deepstream { // A. Alexandrescu, P. Marginean: // "Generic: Change the Way You Write Exception-Safe Code -- Forever" // Dr. Dobbs Journal, 2000 // www.drdobbs.com/cpp/generic-change-the-way-you-write-excepti/184403758 struct ScopeGuard { typedef std::function<void(void)> FunT; ScopeGuard(FunT f) : f_(f) {} ~ScopeGuard() { f_(); } FunT f_; }; } #define DEEPSTREAM_ON_EXIT(...) \ const ::deepstream::ScopeGuard BOOST_PP_CAT(deepstream_guard,__LINE__)(__VA_ARGS__); \ ::deepstream::use( BOOST_PP_CAT(deepstream_guard, __LINE__) ) #endif <|endoftext|>
<commit_before><commit_msg>These function members does not need to be virtual<commit_after><|endoftext|>
<commit_before>#pragma once #include <xcb/xcb.h> #include "common.hpp" #include "config.hpp" #include "utils/socket.hpp" #include "utils/string.hpp" LEMONBUDDY_NS namespace bspwm_util { struct payload; using subscriber_t = unique_ptr<socket_util::unix_connection>; using payload_t = unique_ptr<payload>; /** * bspwm payload */ struct payload { char data[BUFSIZ]{'\0'}; size_t len = 0; }; /** * Get path to the bspwm socket by the following order * * 1. Value of environment variable BSPWM_SOCKET * 2. Value built from the bspwm socket path template * 3. Value of the macro BSPWM_SOCKET_PATH */ string get_socket_path() { string env_path{read_env("BSPWM_SOCKET")}; if (!env_path.empty()) return env_path; struct sockaddr_un sa; char* tpl_path = nullptr; char* host = nullptr; int dsp = 0; int scr = 0; if (xcb_parse_display(nullptr, &host, &dsp, &scr) != 0) std::snprintf(tpl_path, sizeof(sa.sun_path), "/tmp/bspwm%s_%i_%i-socket", host, dsp, scr); if (tpl_path != nullptr) return tpl_path; return BSPWM_SOCKET_PATH; } /** * Generate a payload object with properly formatted data * ready to be sent to the bspwm ipc controller */ unique_ptr<payload> make_payload(string cmd) { auto pl = make_unique<payload>(); auto size = sizeof(pl->data); int offset = 0; int chars = 0; for (auto&& word : string_util::split(cmd, ' ')) { chars = snprintf(pl->data + offset, size - offset, "%s%c", word.c_str(), 0); pl->len += chars; offset += chars; } return pl; } /** * Create a connection and subscribe to events * on the bspwm socket * * Example usage: * @code cpp * auto ipc = bspwm_util::make_subscriber(); * * while (!ipc->poll(POLLHUP, 0)) { * ssize_t bytes_received = 0; * auto data = ipc->receive(BUFSIZ-1, bytes_received, 0); * std::cout << data << std::endl; * } * @endcode */ subscriber_t make_subscriber() { auto conn = socket_util::make_unix_connection(BSPWM_SOCKET_PATH); auto payload = make_payload("subscribe report"); if (conn->send(payload->data, payload->len, 0) == 0) throw system_error("Failed to initialize subscriber"); return conn; } } LEMONBUDDY_NS_END <commit_msg>refactor(bspwm): Use defined socket path for ipc connections<commit_after>#pragma once #include <xcb/xcb.h> #include "common.hpp" #include "config.hpp" #include "utils/socket.hpp" #include "utils/string.hpp" LEMONBUDDY_NS namespace bspwm_util { struct payload; using connection_t = unique_ptr<socket_util::unix_connection>; using payload_t = unique_ptr<payload>; /** * bspwm payload */ struct payload { char data[BUFSIZ]{'\0'}; size_t len = 0; }; /** * Get path to the bspwm socket by the following order * * 1. Value of environment variable BSPWM_SOCKET * 2. Value built from the bspwm socket path template * 3. Value of the macro BSPWM_SOCKET_PATH */ string get_socket_path() { string env_path; if ((env_path = read_env("BSPWM_SOCKET")).empty() == false) return env_path; struct sockaddr_un sa; char* host = nullptr; int dsp = 0; int scr = 0; if (xcb_parse_display(nullptr, &host, &dsp, &scr) == 0) return BSPWM_SOCKET_PATH; snprintf(sa.sun_path, sizeof(sa.sun_path), "/tmp/bspwm%s_%i_%i-socket", host, dsp, scr); return sa.sun_path; } /** * Generate a payload object with properly formatted data * ready to be sent to the bspwm ipc controller */ unique_ptr<payload> make_payload(string cmd) { auto pl = make_unique<payload>(); auto size = sizeof(pl->data); int offset = 0; int chars = 0; for (auto&& word : string_util::split(cmd, ' ')) { chars = snprintf(pl->data + offset, size - offset, "%s%c", word.c_str(), 0); pl->len += chars; offset += chars; } return pl; } /** * Create an ipc socket connection * * Example usage: * @code cpp * auto ipc = bspwm_util::make_connection(); * ipc->send(bspwm_util::make_payload("desktop -f eDP-1:^1")); * @endcode */ connection_t make_connection() { return socket_util::make_unix_connection(get_socket_path()); } /** * Create a connection and subscribe to events * on the bspwm socket * * Example usage: * @code cpp * auto ipc = bspwm_util::make_subscriber(); * * while (!ipc->poll(POLLHUP, 0)) { * ssize_t bytes_received = 0; * auto data = ipc->receive(BUFSIZ-1, bytes_received, 0); * std::cout << data << std::endl; * } * @endcode */ connection_t make_subscriber() { auto conn = make_connection(); auto payload = make_payload("subscribe report"); if (conn->send(payload->data, payload->len, 0) == 0) throw system_error("Failed to initialize subscriber"); return conn; } } LEMONBUDDY_NS_END <|endoftext|>
<commit_before>/************************************************************************/ /* */ /* Copyright 2001-2002 by Gunnar Kedenburg */ /* Cognitive Systems Group, University of Hamburg, Germany */ /* */ /* This file is part of the VIGRA computer vision library. */ /* You may use, modify, and distribute this software according */ /* to the terms stated in the LICENSE file included in */ /* the VIGRA distribution. */ /* */ /* The VIGRA Website is */ /* http://kogs-www.informatik.uni-hamburg.de/~koethe/vigra/ */ /* Please direct questions, bug reports, and contributions to */ /* [email protected] */ /* */ /* THIS SOFTWARE IS PROVIDED AS IS AND WITHOUT ANY EXPRESS OR */ /* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED */ /* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ /* */ /************************************************************************/ #ifndef VIGRA_CODEC_HXX #define VIGRA_CODEC_HXX #include <memory> #include <string> #include <vector> // possible pixel types: // "undefined", "UINT8", "INT16", "INT32", "FLOAT", "DOUBLE" // possible compression types: // "undefined", "RLE", "LZW", "LOSSLESS", "JPEG" // possible file types: // "undefined", "TIFF", "VIFF", "JPEG", "PNG", "PNM", "BMP", "SUN", "XPM" // possible name extensions: // "undefined", "tif", "tiff", "jpg", "jpeg", "png", "pnm", "bmp", "sun", // "xpm" (also capital forms) namespace vigra { // codec description struct CodecDesc { std::string fileType; std::vector<std::string> pixelTypes; std::vector<std::string> compressionTypes; std::vector<std::vector<char> > magicStrings; std::vector<std::string> fileExtensions; std::vector<int> bandNumbers; }; // Decoder and Encoder are pure virtual types that define a common // interface for all image file formats impex supports. struct Decoder { virtual ~Decoder() {}; virtual void init( const std::string & ) = 0; virtual void close() = 0; virtual void abort() = 0; virtual std::string getFileType() const = 0; virtual std::string getPixelType() const = 0; virtual unsigned int getWidth() const = 0; virtual unsigned int getHeight() const = 0; virtual unsigned int getNumBands() const = 0; virtual unsigned int getOffset() const = 0; virtual const void * currentScanlineOfBand( unsigned int ) const = 0; virtual void nextScanline() = 0; }; struct Encoder { virtual ~Encoder() {}; virtual void init( const std::string & ) = 0; virtual void close() = 0; virtual void abort() = 0; virtual std::string getFileType() const = 0; virtual unsigned int getOffset() const = 0; virtual void setWidth( unsigned int ) = 0; virtual void setHeight( unsigned int ) = 0; virtual void setNumBands( unsigned int ) = 0; virtual void setCompressionType( const std::string &, int = -1 ) = 0; virtual void setPixelType( const std::string & ) = 0; virtual void finalizeSettings() = 0; virtual void * currentScanlineOfBand( unsigned int ) = 0; virtual void nextScanline() = 0; }; // codec factory for registration at the codec manager struct CodecFactory { virtual CodecDesc getCodecDesc() const = 0; virtual std::auto_ptr<Decoder> getDecoder() const = 0; virtual std::auto_ptr<Encoder> getEncoder() const = 0; }; // factory functions to encapsulate the codec managers // // codecs are selected according to the following order: // - (if provided) the FileType // - (in case of decoders) the file's magic string // - the filename extension std::auto_ptr<Decoder> getDecoder( const std::string &, const std::string & = "undefined" ); std::auto_ptr<Encoder> getEncoder( const std::string &, const std::string & = "undefined" ); // functions to query the capabilities of certain codecs std::vector<std::string> queryCodecPixelTypes( const std::string & ); bool isPixelTypeSupported( const std::string &, const std::string & ); bool isBandNumberSupported( const std::string &, int bands ); } #endif // VIGRA_CODEC_HXX <commit_msg>added TIFFNoLZWException<commit_after>/************************************************************************/ /* */ /* Copyright 2001-2002 by Gunnar Kedenburg */ /* Cognitive Systems Group, University of Hamburg, Germany */ /* */ /* This file is part of the VIGRA computer vision library. */ /* You may use, modify, and distribute this software according */ /* to the terms stated in the LICENSE file included in */ /* the VIGRA distribution. */ /* */ /* The VIGRA Website is */ /* http://kogs-www.informatik.uni-hamburg.de/~koethe/vigra/ */ /* Please direct questions, bug reports, and contributions to */ /* [email protected] */ /* */ /* THIS SOFTWARE IS PROVIDED AS IS AND WITHOUT ANY EXPRESS OR */ /* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED */ /* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ /* */ /************************************************************************/ #ifndef VIGRA_CODEC_HXX #define VIGRA_CODEC_HXX #include <memory> #include <string> #include <vector> // possible pixel types: // "undefined", "UINT8", "INT16", "INT32", "FLOAT", "DOUBLE" // possible compression types: // "undefined", "RLE", "LZW", "LOSSLESS", "JPEG" // possible file types: // "undefined", "TIFF", "VIFF", "JPEG", "PNG", "PNM", "BMP", "SUN", "XPM" // possible name extensions: // "undefined", "tif", "tiff", "jpg", "jpeg", "png", "pnm", "bmp", "sun", // "xpm" (also capital forms) namespace vigra { // codec description struct CodecDesc { std::string fileType; std::vector<std::string> pixelTypes; std::vector<std::string> compressionTypes; std::vector<std::vector<char> > magicStrings; std::vector<std::string> fileExtensions; std::vector<int> bandNumbers; }; // Decoder and Encoder are pure virtual types that define a common // interface for all image file formats impex supports. struct Decoder { virtual ~Decoder() {}; virtual void init( const std::string & ) = 0; virtual void close() = 0; virtual void abort() = 0; virtual std::string getFileType() const = 0; virtual std::string getPixelType() const = 0; virtual unsigned int getWidth() const = 0; virtual unsigned int getHeight() const = 0; virtual unsigned int getNumBands() const = 0; virtual unsigned int getOffset() const = 0; virtual const void * currentScanlineOfBand( unsigned int ) const = 0; virtual void nextScanline() = 0; }; struct Encoder { virtual ~Encoder() {}; virtual void init( const std::string & ) = 0; virtual void close() = 0; virtual void abort() = 0; virtual std::string getFileType() const = 0; virtual unsigned int getOffset() const = 0; virtual void setWidth( unsigned int ) = 0; virtual void setHeight( unsigned int ) = 0; virtual void setNumBands( unsigned int ) = 0; virtual void setCompressionType( const std::string &, int = -1 ) = 0; virtual void setPixelType( const std::string & ) = 0; virtual void finalizeSettings() = 0; virtual void * currentScanlineOfBand( unsigned int ) = 0; virtual void nextScanline() = 0; struct TIFFNoLZWException {}; }; // codec factory for registration at the codec manager struct CodecFactory { virtual CodecDesc getCodecDesc() const = 0; virtual std::auto_ptr<Decoder> getDecoder() const = 0; virtual std::auto_ptr<Encoder> getEncoder() const = 0; }; // factory functions to encapsulate the codec managers // // codecs are selected according to the following order: // - (if provided) the FileType // - (in case of decoders) the file's magic string // - the filename extension std::auto_ptr<Decoder> getDecoder( const std::string &, const std::string & = "undefined" ); std::auto_ptr<Encoder> getEncoder( const std::string &, const std::string & = "undefined" ); // functions to query the capabilities of certain codecs std::vector<std::string> queryCodecPixelTypes( const std::string & ); bool isPixelTypeSupported( const std::string &, const std::string & ); bool isBandNumberSupported( const std::string &, int bands ); } #endif // VIGRA_CODEC_HXX <|endoftext|>
<commit_before>#include <iostream> #include <filesystem> #include <vector> #include <map> #include <string> #include <fstream> using namespace std; #if (__cplusplus >= 201703L && (!defined(__GNUC__) || (__GNUC__*100+__GNUC_MINOR__) >= 800)) #include <filesystem> namespace fs = std::filesystem; #define USE_FILESYSTEM #elif !defined(__MINGW32__) && !defined(__ANDROID__) && (!defined(__GNUC__) || (__GNUC__*100+__GNUC_MINOR__) >= 503) #define USE_FILESYSTEM #ifdef WIN32 #include <filesystem> namespace fs = std::experimental::filesystem; #else #include <experimental/filesystem> namespace fs = std::experimental::filesystem; #endif #else //for mac #include <filesystem> namespace fs = std::__fs::filesystem; #endif enum class Platform { platform_windows, // platform_ prefix to avoid #define subsitutions on linux platform_osx, platform_linux, }; constexpr Platform buildPlatform = #if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(__NT__) Platform::platform_windows #elif __APPLE__ #include <TargetConditionals.h> #if TARGET_OS_MAC Platform::platform_osx #endif #elif __linux__ Platform::platform_linux #endif ; // error here: platform not detected from supported list bool build = false; bool setup = false; bool removeUnusedPorts = false; bool noPkgConfig = false; fs::path portsFile; fs::path sdkRootPath; fs::path patchPath; string triplet; map<string, string> ports; map<string, fs::path> patches; fs::path initialDir = fs::current_path(); fs::path vcpkgDir = fs::current_path() / "vcpkg"; fs::path cloneDir = fs::current_path() / "vcpkg_clone"; string platformToString(Platform p); bool readCommandLine(int argc, char* argv[]); void execute(string command); int main(int argc, char* argv[]) try { if (readCommandLine(argc, argv)) { if (setup) { if (!fs::is_directory("vcpkg")) { execute("git clone https://github.com/microsoft/vcpkg.git"); execute("git clone --progress -v vcpkg vcpkg_clone"); fs::current_path("vcpkg"); #ifdef WIN32 execute(".\\bootstrap-vcpkg.bat -disableMetrics"); #else execute("./bootstrap-vcpkg.sh -disableMetrics"); #endif } else { fs::current_path("vcpkg"); } if (fs::exists(sdkRootPath / "contrib" / "cmake" / "vcpkg_extra_triplets" / (triplet + ".cmake"))) { if (fs::exists(vcpkgDir / "triplets" / (triplet + ".cmake"))) { fs::remove(vcpkgDir / "triplets" / (triplet + ".cmake")); } cout << "Copying triplet from SDK: " << triplet << endl; fs::copy(sdkRootPath / "contrib" / "cmake" / "vcpkg_extra_triplets" / (triplet+".cmake"), vcpkgDir / "triplets" / (triplet + ".cmake")); } else if (!fs::exists(vcpkgDir / "triplets" / (triplet + ".cmake"))) { cout << "triplet not found in the SDK or in vcpkg: " << triplet << endl; exit(1); } for (auto portPair : ports) { const string& portname = portPair.first; const string& portversion = portPair.second; if (fs::is_directory(fs::path("ports") / portname)) { cout << "Removing " << (vcpkgDir / "ports" / portname).u8string() << endl; fs::remove_all(vcpkgDir / "ports" / portname); } if (portversion.size() == 40) { fs::current_path(cloneDir); execute("git checkout --quiet " + portversion); cout << "Copying port for " << portname << " from vcpkg commit " << portversion << endl; fs::copy(cloneDir / "ports" / portname, vcpkgDir / "ports" / portname, fs::copy_options::recursive); fs::current_path(vcpkgDir); auto patch = patches.find(portname); if (patch != patches.end()) { cout << "Applying patch " << patch->second.u8string() << " for port " << portname << "\n"; execute("git apply " + (patchPath / patch->second).u8string()); } } else { cout << "Copying port for " << portname << " from SDK customized port " << portversion << endl; fs::copy(sdkRootPath / "contrib" / "cmake" / "vcpkg_extra_ports" / portname / portversion, vcpkgDir / "ports" / portname, fs::copy_options::recursive); } } if (removeUnusedPorts) { for (auto dir = fs::directory_iterator(vcpkgDir / "ports"); dir != fs::directory_iterator(); ++dir) { if (ports.find(dir->path().filename().u8string()) == ports.end()) { fs::remove_all(dir->path()); } } } if (noPkgConfig) { cout << "Performing no-op substitution of vcpkg_fixup_pkgconfig and PKGCONFIG to skip pkgconfig integration/checks\n"; ofstream vcpkg_fixup_pkgconfig(vcpkgDir / "scripts" / "cmake" / "vcpkg_fixup_pkgconfig.cmake", std::ios::trunc); if (!vcpkg_fixup_pkgconfig) { cout << "Could not open vcpkg script file to suppress pkgconfig\n"; return 1; } vcpkg_fixup_pkgconfig << "function(vcpkg_fixup_pkgconfig)\n" "endfunction()\n" "set(PKGCONFIG \":\")\n"; // i.e., use no-op : operator } } else if (build) { if (!fs::is_directory("vcpkg")) { cout << "This command should be run from just outside 'vcpkg' folder - maybe it is not set up?" << endl; return 1; } else { fs::current_path("vcpkg"); } for (auto portPair : ports) { #ifdef WIN32 execute("vcpkg install --triplet " + triplet + " " + portPair.first); #else execute("./vcpkg install --triplet " + triplet + " " + portPair.first); #endif } } } return 0; } catch (exception& e) { cout << "exception: " << e.what() << endl; return 1; } string platformToString(Platform p) { switch (p) { case Platform::platform_windows: return "windows"; case Platform::platform_osx: return "osx"; case Platform::platform_linux: return "linux"; default: throw std::logic_error("Unhandled platform enumerator"); } } void execute(string command) { cout << "Executing: " << command << endl; int result = system(command.c_str()); if (result != 0) { cout << "Command failed with result code " << result << " ( command was " << command << ")" <<endl; exit(1); } } bool showSyntax() { cout << "build3rdParty --setup [--removeunusedports] [--nopkgconfig] --ports <ports override file> --triplet <triplet> --sdkroot <path>" << endl; cout << "build3rdParty --build --ports <ports override file> --triplet <triplet>" << endl; return false; } bool readCommandLine(int argc, char* argv[]) { if (argc <= 1) return showSyntax(); std::vector<char*> myargv1(argv + 1, argv + argc); std::vector<char*> myargv2; for (auto it = myargv1.begin(); it != myargv1.end(); ++it) { if (std::string(*it) == "--ports") { if (++it == myargv1.end()) return showSyntax(); portsFile = *it; } else if (std::string(*it) == "--triplet") { if (++it == myargv1.end()) return showSyntax(); triplet = *it; } else if (std::string(*it) == "--sdkroot") { if (++it == myargv1.end()) return showSyntax(); sdkRootPath = *it; } else if (std::string(*it) == "--setup") { setup = true; } else if (std::string(*it) == "--removeunusedports" && setup) { removeUnusedPorts = true; } else if (std::string(*it) == "--nopkgconfig" && setup) { noPkgConfig = true; } else if (std::string(*it) == "--build") { build = true; } else { myargv2.push_back(*it); } } if (!myargv2.empty()) { cout << "unknown parameter: " << myargv2[0] << endl; return false; } if (!(setup || build) || portsFile.empty() || triplet.empty()) { return showSyntax(); } if (setup && sdkRootPath.empty()) { return showSyntax(); } patchPath = sdkRootPath / "contrib" / "cmake" / "vcpkg_patches"; ifstream portsIn(portsFile.string().c_str()); while (portsIn) { string s; getline(portsIn, s); // remove comments auto hashpos = s.find("#"); if (hashpos != string::npos) s.erase(hashpos); // remove whitespace while (!s.empty() && (s.front() == ' ' || s.front() == '\t')) s.erase(0, 1); while (!s.empty() && (s.back() == ' ' || s.back() == '\t')) s.pop_back(); if (s.empty()) continue; // check if port should be skipped for this platform if (s.find(" ") != string::npos) { string platformTest = s.substr(s.find_last_of(' ') + 1); s.erase(s.find_first_of(' ')); if (!platformTest.empty() && platformTest[0] == '!') { if (platformTest.substr(1) == platformToString(buildPlatform)) { cout << "Skipping " << s << " because " << platformTest <<"\n"; continue; } } else { if (platformTest != platformToString(buildPlatform)) { cout << "Skipping " << s << " because " << platformTest << "\n"; continue; } } } // if not, extract the exclude expressions so we don't have to worry about them s = s.substr(0, s.find("!")); // extract port/version map auto slashpos = s.find("/"); if (slashpos == string::npos) { cout << "bad port: " << s << endl; return 1; } string portname = s.substr(0, slashpos); auto colonpos = s.find(':'); string portversion = s.substr(slashpos + 1, colonpos - (slashpos + 1)); auto existing = ports.find(portname); if (existing != ports.end() && existing->second != portversion) { cout << "conflicting port versions: " << portname << " " << existing->second << " " << portversion << endl; return 1; } ports[portname] = portversion; if (build) continue; if (colonpos != string::npos) { fs::path patch = s.substr(colonpos + 1); auto existingPatch = patches.find(patch.u8string()); if (existingPatch != patches.end() && existingPatch->second != patch) { cout << "Conflicting patch files: " << patch << " and " << existingPatch->second << " for " << portname << "\n"; return 1; } if (!fs::exists(patchPath / patch)) { cout << "Nonexistent patch " << patch << " for " << portname << ", patches must be in " << patchPath.u8string() << "\n"; } cout << "Got patch " << patch << " for " << portname << "\n"; patches[portname] = patch; } } return true; } <commit_msg>fix typo in check for existing patch<commit_after>#include <iostream> #include <filesystem> #include <vector> #include <map> #include <string> #include <fstream> using namespace std; #if (__cplusplus >= 201703L && (!defined(__GNUC__) || (__GNUC__*100+__GNUC_MINOR__) >= 800)) #include <filesystem> namespace fs = std::filesystem; #define USE_FILESYSTEM #elif !defined(__MINGW32__) && !defined(__ANDROID__) && (!defined(__GNUC__) || (__GNUC__*100+__GNUC_MINOR__) >= 503) #define USE_FILESYSTEM #ifdef WIN32 #include <filesystem> namespace fs = std::experimental::filesystem; #else #include <experimental/filesystem> namespace fs = std::experimental::filesystem; #endif #else //for mac #include <filesystem> namespace fs = std::__fs::filesystem; #endif enum class Platform { platform_windows, // platform_ prefix to avoid #define subsitutions on linux platform_osx, platform_linux, }; constexpr Platform buildPlatform = #if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(__NT__) Platform::platform_windows #elif __APPLE__ #include <TargetConditionals.h> #if TARGET_OS_MAC Platform::platform_osx #endif #elif __linux__ Platform::platform_linux #endif ; // error here: platform not detected from supported list bool build = false; bool setup = false; bool removeUnusedPorts = false; bool noPkgConfig = false; fs::path portsFile; fs::path sdkRootPath; fs::path patchPath; string triplet; map<string, string> ports; map<string, fs::path> patches; fs::path initialDir = fs::current_path(); fs::path vcpkgDir = fs::current_path() / "vcpkg"; fs::path cloneDir = fs::current_path() / "vcpkg_clone"; string platformToString(Platform p); bool readCommandLine(int argc, char* argv[]); void execute(string command); int main(int argc, char* argv[]) try { if (readCommandLine(argc, argv)) { if (setup) { if (!fs::is_directory("vcpkg")) { execute("git clone https://github.com/microsoft/vcpkg.git"); execute("git clone --progress -v vcpkg vcpkg_clone"); fs::current_path("vcpkg"); #ifdef WIN32 execute(".\\bootstrap-vcpkg.bat -disableMetrics"); #else execute("./bootstrap-vcpkg.sh -disableMetrics"); #endif } else { fs::current_path("vcpkg"); } if (fs::exists(sdkRootPath / "contrib" / "cmake" / "vcpkg_extra_triplets" / (triplet + ".cmake"))) { if (fs::exists(vcpkgDir / "triplets" / (triplet + ".cmake"))) { fs::remove(vcpkgDir / "triplets" / (triplet + ".cmake")); } cout << "Copying triplet from SDK: " << triplet << endl; fs::copy(sdkRootPath / "contrib" / "cmake" / "vcpkg_extra_triplets" / (triplet+".cmake"), vcpkgDir / "triplets" / (triplet + ".cmake")); } else if (!fs::exists(vcpkgDir / "triplets" / (triplet + ".cmake"))) { cout << "triplet not found in the SDK or in vcpkg: " << triplet << endl; exit(1); } for (auto portPair : ports) { const string& portname = portPair.first; const string& portversion = portPair.second; if (fs::is_directory(fs::path("ports") / portname)) { cout << "Removing " << (vcpkgDir / "ports" / portname).u8string() << endl; fs::remove_all(vcpkgDir / "ports" / portname); } if (portversion.size() == 40) { fs::current_path(cloneDir); execute("git checkout --quiet " + portversion); cout << "Copying port for " << portname << " from vcpkg commit " << portversion << endl; fs::copy(cloneDir / "ports" / portname, vcpkgDir / "ports" / portname, fs::copy_options::recursive); fs::current_path(vcpkgDir); auto patch = patches.find(portname); if (patch != patches.end()) { cout << "Applying patch " << patch->second.u8string() << " for port " << portname << "\n"; execute("git apply " + (patchPath / patch->second).u8string()); } } else { cout << "Copying port for " << portname << " from SDK customized port " << portversion << endl; fs::copy(sdkRootPath / "contrib" / "cmake" / "vcpkg_extra_ports" / portname / portversion, vcpkgDir / "ports" / portname, fs::copy_options::recursive); } } if (removeUnusedPorts) { for (auto dir = fs::directory_iterator(vcpkgDir / "ports"); dir != fs::directory_iterator(); ++dir) { if (ports.find(dir->path().filename().u8string()) == ports.end()) { fs::remove_all(dir->path()); } } } if (noPkgConfig) { cout << "Performing no-op substitution of vcpkg_fixup_pkgconfig and PKGCONFIG to skip pkgconfig integration/checks\n"; ofstream vcpkg_fixup_pkgconfig(vcpkgDir / "scripts" / "cmake" / "vcpkg_fixup_pkgconfig.cmake", std::ios::trunc); if (!vcpkg_fixup_pkgconfig) { cout << "Could not open vcpkg script file to suppress pkgconfig\n"; return 1; } vcpkg_fixup_pkgconfig << "function(vcpkg_fixup_pkgconfig)\n" "endfunction()\n" "set(PKGCONFIG \":\")\n"; // i.e., use no-op : operator } } else if (build) { if (!fs::is_directory("vcpkg")) { cout << "This command should be run from just outside 'vcpkg' folder - maybe it is not set up?" << endl; return 1; } else { fs::current_path("vcpkg"); } for (auto portPair : ports) { #ifdef WIN32 execute("vcpkg install --triplet " + triplet + " " + portPair.first); #else execute("./vcpkg install --triplet " + triplet + " " + portPair.first); #endif } } } return 0; } catch (exception& e) { cout << "exception: " << e.what() << endl; return 1; } string platformToString(Platform p) { switch (p) { case Platform::platform_windows: return "windows"; case Platform::platform_osx: return "osx"; case Platform::platform_linux: return "linux"; default: throw std::logic_error("Unhandled platform enumerator"); } } void execute(string command) { cout << "Executing: " << command << endl; int result = system(command.c_str()); if (result != 0) { cout << "Command failed with result code " << result << " ( command was " << command << ")" <<endl; exit(1); } } bool showSyntax() { cout << "build3rdParty --setup [--removeunusedports] [--nopkgconfig] --ports <ports override file> --triplet <triplet> --sdkroot <path>" << endl; cout << "build3rdParty --build --ports <ports override file> --triplet <triplet>" << endl; return false; } bool readCommandLine(int argc, char* argv[]) { if (argc <= 1) return showSyntax(); std::vector<char*> myargv1(argv + 1, argv + argc); std::vector<char*> myargv2; for (auto it = myargv1.begin(); it != myargv1.end(); ++it) { if (std::string(*it) == "--ports") { if (++it == myargv1.end()) return showSyntax(); portsFile = *it; } else if (std::string(*it) == "--triplet") { if (++it == myargv1.end()) return showSyntax(); triplet = *it; } else if (std::string(*it) == "--sdkroot") { if (++it == myargv1.end()) return showSyntax(); sdkRootPath = *it; } else if (std::string(*it) == "--setup") { setup = true; } else if (std::string(*it) == "--removeunusedports" && setup) { removeUnusedPorts = true; } else if (std::string(*it) == "--nopkgconfig" && setup) { noPkgConfig = true; } else if (std::string(*it) == "--build") { build = true; } else { myargv2.push_back(*it); } } if (!myargv2.empty()) { cout << "unknown parameter: " << myargv2[0] << endl; return false; } if (!(setup || build) || portsFile.empty() || triplet.empty()) { return showSyntax(); } if (setup && sdkRootPath.empty()) { return showSyntax(); } patchPath = sdkRootPath / "contrib" / "cmake" / "vcpkg_patches"; ifstream portsIn(portsFile.string().c_str()); while (portsIn) { string s; getline(portsIn, s); // remove comments auto hashpos = s.find("#"); if (hashpos != string::npos) s.erase(hashpos); // remove whitespace while (!s.empty() && (s.front() == ' ' || s.front() == '\t')) s.erase(0, 1); while (!s.empty() && (s.back() == ' ' || s.back() == '\t')) s.pop_back(); if (s.empty()) continue; // check if port should be skipped for this platform if (s.find(" ") != string::npos) { string platformTest = s.substr(s.find_last_of(' ') + 1); s.erase(s.find_first_of(' ')); if (!platformTest.empty() && platformTest[0] == '!') { if (platformTest.substr(1) == platformToString(buildPlatform)) { cout << "Skipping " << s << " because " << platformTest <<"\n"; continue; } } else { if (platformTest != platformToString(buildPlatform)) { cout << "Skipping " << s << " because " << platformTest << "\n"; continue; } } } // if not, extract the exclude expressions so we don't have to worry about them s = s.substr(0, s.find("!")); // extract port/version map auto slashpos = s.find("/"); if (slashpos == string::npos) { cout << "bad port: " << s << endl; return 1; } string portname = s.substr(0, slashpos); auto colonpos = s.find(':'); string portversion = s.substr(slashpos + 1, colonpos - (slashpos + 1)); auto existing = ports.find(portname); if (existing != ports.end() && existing->second != portversion) { cout << "conflicting port versions: " << portname << " " << existing->second << " " << portversion << endl; return 1; } ports[portname] = portversion; if (build) continue; if (colonpos != string::npos) { fs::path patch = s.substr(colonpos + 1); auto existingPatch = patches.find(portname); if (existingPatch != patches.end() && existingPatch->second != patch) { cout << "Conflicting patch files: " << patch << " and " << existingPatch->second << " for " << portname << "\n"; return 1; } if (!fs::exists(patchPath / patch)) { cout << "Nonexistent patch " << patch << " for " << portname << ", patches must be in " << patchPath.u8string() << "\n"; } cout << "Got patch " << patch << " for " << portname << "\n"; patches[portname] = patch; } } return true; } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: ik_singleton.hxx,v $ * * $Revision: 1.1 $ * * last change: $Author: np $ $Date: 2002-11-01 17:12:04 $ * * 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): _______________________________________ * * ************************************************************************/ #ifndef ARY_IDL_IK_SINGLETON_HXX #define ARY_IDL_IK_SINGLETON_HXX // USED SERVICES // BASE CLASSES #include <ary/idl/ik_ce.hxx> // COMPONENTS // PARAMETERS namespace ary { namespace idl { namespace ifc_singleton { using ifc_ce::Dyn_CeIterator; using ifc_ce::DocText; struct attr: public ifc_ce::attr { static Type_id AssociatedService( const CodeEntity & i_ce ); }; struct xref : public ifc_ce::xref { }; struct doc : public ifc_ce::doc { }; } // namespace ifc_singleton } // namespace idl } // namespace ary #endif <commit_msg>INTEGRATION: CWS ooo19126 (1.1.132); FILE MERGED 2005/09/05 13:09:27 rt 1.1.132.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: ik_singleton.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: rt $ $Date: 2005-09-07 16:17:13 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef ARY_IDL_IK_SINGLETON_HXX #define ARY_IDL_IK_SINGLETON_HXX // USED SERVICES // BASE CLASSES #include <ary/idl/ik_ce.hxx> // COMPONENTS // PARAMETERS namespace ary { namespace idl { namespace ifc_singleton { using ifc_ce::Dyn_CeIterator; using ifc_ce::DocText; struct attr: public ifc_ce::attr { static Type_id AssociatedService( const CodeEntity & i_ce ); }; struct xref : public ifc_ce::xref { }; struct doc : public ifc_ce::doc { }; } // namespace ifc_singleton } // namespace idl } // namespace ary #endif <|endoftext|>
<commit_before>/**************************************************************************** * * Copyright (c) 2018 PX4 Development Team. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name PX4 nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ /** * @file FlightTaskManual.cpp */ #include "FlightTaskManual.hpp" #include <mathlib/mathlib.h> #include <float.h> using namespace matrix; bool FlightTaskManual::initializeSubscriptions(SubscriptionArray &subscription_array) { if (!FlightTask::initializeSubscriptions(subscription_array)) { return false; } if (!subscription_array.get(ORB_ID(manual_control_setpoint), _sub_manual_control_setpoint)) { return false; } return true; } bool FlightTaskManual::updateInitialize() { bool ret = FlightTask::updateInitialize(); const bool sticks_available = _evaluateSticks(); if (_sticks_data_required) { ret = ret && sticks_available; } return ret; } bool FlightTaskManual::activate() { bool ret = FlightTask::activate(); if (_sticks_data_required) { // need valid stick inputs ret = ret && PX4_ISFINITE(_sticks(0)) && PX4_ISFINITE(_sticks(1)) && PX4_ISFINITE(_sticks(2)) && PX4_ISFINITE(_sticks(3)); } return ret; } bool FlightTaskManual::_evaluateSticks() { /* Sticks are rescaled linearly and exponentially to [-1,1] */ if ((_time_stamp_current - _sub_manual_control_setpoint->get().timestamp) < _timeout) { /* Linear scale */ _sticks(0) = _sub_manual_control_setpoint->get().x; /* NED x, "pitch" [-1,1] */ _sticks(1) = _sub_manual_control_setpoint->get().y; /* NED y, "roll" [-1,1] */ _sticks(2) = -(_sub_manual_control_setpoint->get().z - 0.5f) * 2.f; /* NED z, "thrust" resacaled from [0,1] to [-1,1] */ _sticks(3) = _sub_manual_control_setpoint->get().r; /* "yaw" [-1,1] */ /* Exponential scale */ _sticks_expo(0) = math::expo_deadzone(_sticks(0), _xy_vel_man_expo.get(), _stick_dz.get()); _sticks_expo(1) = math::expo_deadzone(_sticks(1), _xy_vel_man_expo.get(), _stick_dz.get()); _sticks_expo(2) = math::expo_deadzone(_sticks(2), _z_vel_man_expo.get(), _stick_dz.get()); _sticks_expo(3) = math::expo_deadzone(_sticks(3), _yaw_expo.get(), _stick_dz.get()); // Only switch the landing gear up if the user switched from gear down to gear up. // If the user had the switch in the gear up position and took off ignore it // until he toggles the switch to avoid retracting the gear immediately on takeoff. int8_t gear_switch = _sub_manual_control_setpoint->get().gear_switch; if (!_constraints.landing_gear) { if (gear_switch == manual_control_setpoint_s::SWITCH_POS_OFF) { _applyGearSwitch(gear_switch); } } else { _applyGearSwitch(gear_switch); } return true; } else { /* Timeout: set all sticks to zero */ _sticks.zero(); _sticks_expo.zero(); _constraints.landing_gear = vehicle_constraints_s::GEAR_KEEP; return false; } } void FlightTaskManual::_applyGearSwitch(uint8_t gswitch) { if (gswitch == manual_control_setpoint_s::SWITCH_POS_OFF) { _constraints.landing_gear = vehicle_constraints_s::GEAR_DOWN; } if (gswitch == manual_control_setpoint_s::SWITCH_POS_ON) { _constraints.landing_gear = vehicle_constraints_s::GEAR_UP; } } <commit_msg>FlightTaskManual: sticks not to be finite activation method not needed<commit_after>/**************************************************************************** * * Copyright (c) 2018 PX4 Development Team. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name PX4 nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ /** * @file FlightTaskManual.cpp */ #include "FlightTaskManual.hpp" #include <mathlib/mathlib.h> #include <float.h> using namespace matrix; bool FlightTaskManual::initializeSubscriptions(SubscriptionArray &subscription_array) { if (!FlightTask::initializeSubscriptions(subscription_array)) { return false; } if (!subscription_array.get(ORB_ID(manual_control_setpoint), _sub_manual_control_setpoint)) { return false; } return true; } bool FlightTaskManual::updateInitialize() { bool ret = FlightTask::updateInitialize(); const bool sticks_available = _evaluateSticks(); if (_sticks_data_required) { ret = ret && sticks_available; } return ret; } bool FlightTaskManual::_evaluateSticks() { /* Sticks are rescaled linearly and exponentially to [-1,1] */ if ((_time_stamp_current - _sub_manual_control_setpoint->get().timestamp) < _timeout) { /* Linear scale */ _sticks(0) = _sub_manual_control_setpoint->get().x; /* NED x, "pitch" [-1,1] */ _sticks(1) = _sub_manual_control_setpoint->get().y; /* NED y, "roll" [-1,1] */ _sticks(2) = -(_sub_manual_control_setpoint->get().z - 0.5f) * 2.f; /* NED z, "thrust" resacaled from [0,1] to [-1,1] */ _sticks(3) = _sub_manual_control_setpoint->get().r; /* "yaw" [-1,1] */ /* Exponential scale */ _sticks_expo(0) = math::expo_deadzone(_sticks(0), _xy_vel_man_expo.get(), _stick_dz.get()); _sticks_expo(1) = math::expo_deadzone(_sticks(1), _xy_vel_man_expo.get(), _stick_dz.get()); _sticks_expo(2) = math::expo_deadzone(_sticks(2), _z_vel_man_expo.get(), _stick_dz.get()); _sticks_expo(3) = math::expo_deadzone(_sticks(3), _yaw_expo.get(), _stick_dz.get()); // Only switch the landing gear up if the user switched from gear down to gear up. // If the user had the switch in the gear up position and took off ignore it // until he toggles the switch to avoid retracting the gear immediately on takeoff. int8_t gear_switch = _sub_manual_control_setpoint->get().gear_switch; if (!_constraints.landing_gear) { if (gear_switch == manual_control_setpoint_s::SWITCH_POS_OFF) { _applyGearSwitch(gear_switch); } } else { _applyGearSwitch(gear_switch); } // valid stick inputs are required const bool valid_sticks = PX4_ISFINITE(_sticks(0)) && PX4_ISFINITE(_sticks(1)) && PX4_ISFINITE(_sticks(2)) && PX4_ISFINITE(_sticks(3)); return valid_sticks; } else { /* Timeout: set all sticks to zero */ _sticks.zero(); _sticks_expo.zero(); _constraints.landing_gear = vehicle_constraints_s::GEAR_KEEP; return false; } } void FlightTaskManual::_applyGearSwitch(uint8_t gswitch) { if (gswitch == manual_control_setpoint_s::SWITCH_POS_OFF) { _constraints.landing_gear = vehicle_constraints_s::GEAR_DOWN; } if (gswitch == manual_control_setpoint_s::SWITCH_POS_ON) { _constraints.landing_gear = vehicle_constraints_s::GEAR_UP; } } <|endoftext|>
<commit_before>/**************************************************************************** * * Copyright (c) 2017 PX4 Development Team. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name PX4 nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ /** * @file FlightTaskManual.hpp * * Linear and exponential map from stick inputs to range -1 and 1. * */ #pragma once #include "FlightTask.hpp" #include <uORB/topics/manual_control_setpoint.h> #include <platforms/px4_defines.h> class FlightTaskManual : public FlightTask { public: FlightTaskManual(control::SuperBlock *parent, const char *name); virtual ~FlightTaskManual() = default; bool initializeSubscriptions(SubscriptionArray &subscription_array) override; bool activate() override; bool applyCommandParameters(const vehicle_command_s &command) override { return FlightTask::applyCommandParameters(command); }; bool updateInitialize() override; protected: bool _sticks_data_required = true; /**< let inherited task-class define if it depends on stick data */ matrix::Vector<float, 4> _sticks; /**< unmodified manual stick inputs */ matrix::Vector3f _sticks_expo; /**< modified manual sticks using expo function*/ control::BlockParamFloat _stick_dz; /**< 0-deadzone around the center for the sticks */ private: uORB::Subscription<manual_control_setpoint_s> *_sub_manual_control_setpoint{nullptr}; control::BlockParamFloat _xy_vel_man_expo; /**< ratio of exponential curve for stick input in xy direction */ control::BlockParamFloat _z_vel_man_expo; /**< ratio of exponential curve for stick input in z direction */ bool _evaluateSticks(); /**< checks and sets stick inputs */ }; <commit_msg>FlightTaskManual: remove #include px4_defines.h<commit_after>/**************************************************************************** * * Copyright (c) 2017 PX4 Development Team. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name PX4 nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ /** * @file FlightTaskManual.hpp * * Linear and exponential map from stick inputs to range -1 and 1. * */ #pragma once #include "FlightTask.hpp" #include <uORB/topics/manual_control_setpoint.h> class FlightTaskManual : public FlightTask { public: FlightTaskManual(control::SuperBlock *parent, const char *name); virtual ~FlightTaskManual() = default; bool initializeSubscriptions(SubscriptionArray &subscription_array) override; bool activate() override; bool applyCommandParameters(const vehicle_command_s &command) override { return FlightTask::applyCommandParameters(command); }; bool updateInitialize() override; protected: bool _sticks_data_required = true; /**< let inherited task-class define if it depends on stick data */ matrix::Vector<float, 4> _sticks; /**< unmodified manual stick inputs */ matrix::Vector3f _sticks_expo; /**< modified manual sticks using expo function*/ control::BlockParamFloat _stick_dz; /**< 0-deadzone around the center for the sticks */ private: uORB::Subscription<manual_control_setpoint_s> *_sub_manual_control_setpoint{nullptr}; control::BlockParamFloat _xy_vel_man_expo; /**< ratio of exponential curve for stick input in xy direction */ control::BlockParamFloat _z_vel_man_expo; /**< ratio of exponential curve for stick input in z direction */ bool _evaluateSticks(); /**< checks and sets stick inputs */ }; <|endoftext|>
<commit_before>/* * Copyright 2007 Stephen Liu * For license terms, see the file COPYING along with this library. */ #include <stdio.h> #include <fcntl.h> #include <errno.h> #include <string.h> #include "spporting.hpp" #include "spioutils.hpp" void SP_IOUtils :: inetNtoa( in_addr * addr, char * ip, int size ) { #if defined (linux) || defined (__sgi) || defined (__hpux) || defined (__FreeBSD__) const unsigned char *p = ( const unsigned char *) addr; snprintf( ip, size, "%i.%i.%i.%i", p[0], p[1], p[2], p[3] ); #else snprintf( ip, size, "%i.%i.%i.%i", addr->s_net, addr->s_host, addr->s_lh, addr->s_impno ); #endif } int SP_IOUtils :: setNonblock( int fd ) { #ifdef WIN32 unsigned long nonblocking = 1; ioctlsocket( fd, FIONBIO, (unsigned long*) &nonblocking ); #else int flags; flags = fcntl( fd, F_GETFL ); if( flags < 0 ) return flags; flags |= O_NONBLOCK; if( fcntl( fd, F_SETFL, flags ) < 0 ) return -1; #endif return 0; } int SP_IOUtils :: setBlock( int fd ) { #ifdef WIN32 unsigned long nonblocking = 0; ioctlsocket( fd, FIONBIO, (unsigned long*) &nonblocking ); #else int flags; flags = fcntl( fd, F_GETFL ); if( flags < 0 ) return flags; flags &= ~O_NONBLOCK; if( fcntl( fd, F_SETFL, flags ) < 0 ) return -1; #endif return 0; } int SP_IOUtils :: tcpListen( const char * ip, int port, int * fd, int blocking ) { int ret = 0; int listenFd = socket( AF_INET, SOCK_STREAM, 0 ); if( listenFd < 0 ) { sp_syslog( LOG_WARNING, "listen failed, errno %d, %s", errno, strerror( errno ) ); ret = -1; } if( 0 == ret && 0 == blocking ) { if( setNonblock( listenFd ) < 0 ) { sp_syslog( LOG_WARNING, "failed to set socket to non-blocking" ); ret = -1; } } if( 0 == ret ) { int flags = 1; if( setsockopt( listenFd, SOL_SOCKET, SO_REUSEADDR, (char*)&flags, sizeof( flags ) ) < 0 ) { sp_syslog( LOG_WARNING, "failed to set setsock to reuseaddr" ); ret = -1; } if( setsockopt( listenFd, IPPROTO_TCP, TCP_NODELAY, (char*)&flags, sizeof(flags) ) < 0 ) { sp_syslog( LOG_WARNING, "failed to set socket to nodelay" ); ret = -1; } } struct sockaddr_in addr; if( 0 == ret ) { memset( &addr, 0, sizeof( addr ) ); addr.sin_family = AF_INET; addr.sin_port = htons( port ); addr.sin_addr.s_addr = INADDR_ANY; if( '\0' != *ip ) { if( 0 == sp_inet_aton( ip, &addr.sin_addr ) ) { sp_syslog( LOG_WARNING, "failed to convert %s to inet_addr", ip ); ret = -1; } } } if( 0 == ret ) { if( bind( listenFd, (struct sockaddr*)&addr, sizeof( addr ) ) < 0 ) { sp_syslog( LOG_WARNING, "bind failed, errno %d, %s", errno, strerror( errno ) ); ret = -1; } } if( 0 == ret ) { if( ::listen( listenFd, 1024 ) < 0 ) { sp_syslog( LOG_WARNING, "listen failed, errno %d, %s", errno, strerror( errno ) ); ret = -1; } } if( 0 != ret && listenFd >= 0 ) sp_close( listenFd ); if( 0 == ret ) { * fd = listenFd; sp_syslog( LOG_NOTICE, "Listen on port [%d]", port ); } return ret; } <commit_msg>porting to MacOS<commit_after>/* * Copyright 2007 Stephen Liu * For license terms, see the file COPYING along with this library. */ #include <stdio.h> #include <fcntl.h> #include <errno.h> #include <string.h> #include "spporting.hpp" #include "spioutils.hpp" void SP_IOUtils :: inetNtoa( in_addr * addr, char * ip, int size ) { #if defined (linux) || defined (__sgi) || defined (__hpux) \ || defined (__FreeBSD__) || defined (__APPLE__) const unsigned char *p = ( const unsigned char *) addr; snprintf( ip, size, "%i.%i.%i.%i", p[0], p[1], p[2], p[3] ); #else snprintf( ip, size, "%i.%i.%i.%i", addr->s_net, addr->s_host, addr->s_lh, addr->s_impno ); #endif } int SP_IOUtils :: setNonblock( int fd ) { #ifdef WIN32 unsigned long nonblocking = 1; ioctlsocket( fd, FIONBIO, (unsigned long*) &nonblocking ); #else int flags; flags = fcntl( fd, F_GETFL ); if( flags < 0 ) return flags; flags |= O_NONBLOCK; if( fcntl( fd, F_SETFL, flags ) < 0 ) return -1; #endif return 0; } int SP_IOUtils :: setBlock( int fd ) { #ifdef WIN32 unsigned long nonblocking = 0; ioctlsocket( fd, FIONBIO, (unsigned long*) &nonblocking ); #else int flags; flags = fcntl( fd, F_GETFL ); if( flags < 0 ) return flags; flags &= ~O_NONBLOCK; if( fcntl( fd, F_SETFL, flags ) < 0 ) return -1; #endif return 0; } int SP_IOUtils :: tcpListen( const char * ip, int port, int * fd, int blocking ) { int ret = 0; int listenFd = socket( AF_INET, SOCK_STREAM, 0 ); if( listenFd < 0 ) { sp_syslog( LOG_WARNING, "listen failed, errno %d, %s", errno, strerror( errno ) ); ret = -1; } if( 0 == ret && 0 == blocking ) { if( setNonblock( listenFd ) < 0 ) { sp_syslog( LOG_WARNING, "failed to set socket to non-blocking" ); ret = -1; } } if( 0 == ret ) { int flags = 1; if( setsockopt( listenFd, SOL_SOCKET, SO_REUSEADDR, (char*)&flags, sizeof( flags ) ) < 0 ) { sp_syslog( LOG_WARNING, "failed to set setsock to reuseaddr" ); ret = -1; } if( setsockopt( listenFd, IPPROTO_TCP, TCP_NODELAY, (char*)&flags, sizeof(flags) ) < 0 ) { sp_syslog( LOG_WARNING, "failed to set socket to nodelay" ); ret = -1; } } struct sockaddr_in addr; if( 0 == ret ) { memset( &addr, 0, sizeof( addr ) ); addr.sin_family = AF_INET; addr.sin_port = htons( port ); addr.sin_addr.s_addr = INADDR_ANY; if( '\0' != *ip ) { if( 0 == sp_inet_aton( ip, &addr.sin_addr ) ) { sp_syslog( LOG_WARNING, "failed to convert %s to inet_addr", ip ); ret = -1; } } } if( 0 == ret ) { if( bind( listenFd, (struct sockaddr*)&addr, sizeof( addr ) ) < 0 ) { sp_syslog( LOG_WARNING, "bind failed, errno %d, %s", errno, strerror( errno ) ); ret = -1; } } if( 0 == ret ) { if( ::listen( listenFd, 1024 ) < 0 ) { sp_syslog( LOG_WARNING, "listen failed, errno %d, %s", errno, strerror( errno ) ); ret = -1; } } if( 0 != ret && listenFd >= 0 ) sp_close( listenFd ); if( 0 == ret ) { * fd = listenFd; sp_syslog( LOG_NOTICE, "Listen on port [%d]", port ); } return ret; } <|endoftext|>
<commit_before>//===- SymbolTable.cpp ----------------------------------------------------===// // // The LLVM Linker // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "Config.h" #include "Driver.h" #include "Error.h" #include "SymbolTable.h" #include "Symbols.h" #include "lld/Core/Parallel.h" #include "llvm/LTO/LTOCodeGenerator.h" #include "llvm/Support/Debug.h" #include "llvm/Support/raw_ostream.h" #include <utility> using namespace llvm; namespace lld { namespace coff { void SymbolTable::addFile(std::unique_ptr<InputFile> FileP) { InputFile *File = FileP.get(); Files.push_back(std::move(FileP)); if (auto *F = dyn_cast<ArchiveFile>(File)) { ArchiveQueue.push_back( std::async(std::launch::async, [=]() { F->parse(); return F; })); return; } ObjectQueue.push_back( std::async(std::launch::async, [=]() { File->parse(); return File; })); if (auto *F = dyn_cast<ObjectFile>(File)) { ObjectFiles.push_back(F); } else if (auto *F = dyn_cast<BitcodeFile>(File)) { BitcodeFiles.push_back(F); } else { ImportFiles.push_back(cast<ImportFile>(File)); } } void SymbolTable::step() { if (queueEmpty()) return; readObjects(); readArchives(); } void SymbolTable::run() { while (!queueEmpty()) step(); } void SymbolTable::readArchives() { if (ArchiveQueue.empty()) return; // Add lazy symbols to the symbol table. Lazy symbols that conflict // with existing undefined symbols are accumulated in LazySyms. std::vector<Symbol *> LazySyms; for (std::future<ArchiveFile *> &Future : ArchiveQueue) { ArchiveFile *File = Future.get(); if (Config->Verbose) llvm::outs() << "Reading " << File->getShortName() << "\n"; for (Lazy &Sym : File->getLazySymbols()) addLazy(&Sym, &LazySyms); } ArchiveQueue.clear(); // Add archive member files to ObjectQueue that should resolve // existing undefined symbols. for (Symbol *Sym : LazySyms) addMemberFile(cast<Lazy>(Sym->Body)); } void SymbolTable::readObjects() { if (ObjectQueue.empty()) return; // Add defined and undefined symbols to the symbol table. std::vector<StringRef> Directives; for (size_t I = 0; I < ObjectQueue.size(); ++I) { InputFile *File = ObjectQueue[I].get(); if (Config->Verbose) llvm::outs() << "Reading " << File->getShortName() << "\n"; // Adding symbols may add more files to ObjectQueue // (but not to ArchiveQueue). for (SymbolBody *Sym : File->getSymbols()) if (Sym->isExternal()) addSymbol(Sym); StringRef S = File->getDirectives(); if (!S.empty()) { Directives.push_back(S); if (Config->Verbose) llvm::outs() << "Directives: " << File->getShortName() << ": " << S << "\n"; } } ObjectQueue.clear(); // Parse directive sections. This may add files to // ArchiveQueue and ObjectQueue. for (StringRef S : Directives) Driver->parseDirectives(S); } bool SymbolTable::queueEmpty() { return ArchiveQueue.empty() && ObjectQueue.empty(); } void SymbolTable::reportRemainingUndefines(bool Resolve) { llvm::SmallPtrSet<SymbolBody *, 8> Undefs; for (auto &I : Symtab) { Symbol *Sym = I.second; auto *Undef = dyn_cast<Undefined>(Sym->Body); if (!Undef) continue; StringRef Name = Undef->getName(); // A weak alias may have been resolved, so check for that. if (Defined *D = Undef->getWeakAlias()) { if (Resolve) Sym->Body = D; continue; } // If we can resolve a symbol by removing __imp_ prefix, do that. // This odd rule is for compatibility with MSVC linker. if (Name.startswith("__imp_")) { Symbol *Imp = find(Name.substr(strlen("__imp_"))); if (Imp && isa<Defined>(Imp->Body)) { if (!Resolve) continue; auto *D = cast<Defined>(Imp->Body); auto *S = new (Alloc) DefinedLocalImport(Name, D); LocalImportChunks.push_back(S->getChunk()); Sym->Body = S; continue; } } // Remaining undefined symbols are not fatal if /force is specified. // They are replaced with dummy defined symbols. if (Config->Force && Resolve) Sym->Body = new (Alloc) DefinedAbsolute(Name, 0); Undefs.insert(Sym->Body); } if (Undefs.empty()) return; for (Undefined *U : Config->GCRoot) if (Undefs.count(U->repl())) llvm::errs() << "<root>: undefined symbol: " << U->getName() << "\n"; for (std::unique_ptr<InputFile> &File : Files) if (!isa<ArchiveFile>(File.get())) for (SymbolBody *Sym : File->getSymbols()) if (Undefs.count(Sym->repl())) llvm::errs() << File->getShortName() << ": undefined symbol: " << Sym->getName() << "\n"; if (!Config->Force) error("Link failed"); } void SymbolTable::addLazy(Lazy *New, std::vector<Symbol *> *Accum) { Symbol *Sym = insert(New); if (Sym->Body == New) return; SymbolBody *Existing = Sym->Body; if (isa<Defined>(Existing)) return; if (Lazy *L = dyn_cast<Lazy>(Existing)) if (L->getFileIndex() < New->getFileIndex()) return; Sym->Body = New; New->setBackref(Sym); if (isa<Undefined>(Existing)) Accum->push_back(Sym); } void SymbolTable::addSymbol(SymbolBody *New) { // Find an existing symbol or create and insert a new one. assert(isa<Defined>(New) || isa<Undefined>(New)); Symbol *Sym = insert(New); if (Sym->Body == New) return; SymbolBody *Existing = Sym->Body; // If we have an undefined symbol and a lazy symbol, // let the lazy symbol to read a member file. if (auto *L = dyn_cast<Lazy>(Existing)) { // Undefined symbols with weak aliases need not to be resolved, // since they would be replaced with weak aliases if they remain // undefined. if (auto *U = dyn_cast<Undefined>(New)) { if (!U->WeakAlias) { addMemberFile(L); return; } } Sym->Body = New; return; } // compare() returns -1, 0, or 1 if the lhs symbol is less preferable, // equivalent (conflicting), or more preferable, respectively. int Comp = Existing->compare(New); if (Comp == 0) error(Twine("duplicate symbol: ") + Existing->getDebugName() + " and " + New->getDebugName()); if (Comp < 0) Sym->Body = New; } Symbol *SymbolTable::insert(SymbolBody *New) { Symbol *&Sym = Symtab[New->getName()]; if (Sym) { New->setBackref(Sym); return Sym; } Sym = new (Alloc) Symbol(New); New->setBackref(Sym); return Sym; } // Reads an archive member file pointed by a given symbol. void SymbolTable::addMemberFile(Lazy *Body) { std::unique_ptr<InputFile> File = Body->getMember(); // getMember returns an empty buffer if the member was already // read from the library. if (!File) return; if (Config->Verbose) llvm::outs() << "Loaded " << File->getShortName() << " for " << Body->getName() << "\n"; addFile(std::move(File)); } std::vector<Chunk *> SymbolTable::getChunks() { std::vector<Chunk *> Res; for (ObjectFile *File : ObjectFiles) { std::vector<Chunk *> &V = File->getChunks(); Res.insert(Res.end(), V.begin(), V.end()); } return Res; } Symbol *SymbolTable::find(StringRef Name) { auto It = Symtab.find(Name); if (It == Symtab.end()) return nullptr; return It->second; } Symbol *SymbolTable::findUnderscore(StringRef Name) { if (Config->Machine == I386) return find(("_" + Name).str()); return find(Name); } StringRef SymbolTable::findByPrefix(StringRef Prefix) { for (auto Pair : Symtab) { StringRef Name = Pair.first; if (Name.startswith(Prefix)) return Name; } return ""; } StringRef SymbolTable::findMangle(StringRef Name) { if (Symbol *Sym = find(Name)) if (!isa<Undefined>(Sym->Body)) return Name; if (Config->Machine != I386) return findByPrefix(("?" + Name + "@@Y").str()); if (!Name.startswith("_")) return ""; // Search for x86 C function. StringRef S = findByPrefix((Name + "@").str()); if (!S.empty()) return S; // Search for x86 C++ non-member function. return findByPrefix(("?" + Name.substr(1) + "@@Y").str()); } void SymbolTable::mangleMaybe(Undefined *U) { if (U->WeakAlias) return; if (!isa<Undefined>(U->repl())) return; StringRef Alias = findMangle(U->getName()); if (!Alias.empty()) U->WeakAlias = addUndefined(Alias); } Undefined *SymbolTable::addUndefined(StringRef Name) { auto *New = new (Alloc) Undefined(Name); addSymbol(New); if (auto *U = dyn_cast<Undefined>(New->repl())) return U; return New; } DefinedRelative *SymbolTable::addRelative(StringRef Name, uint64_t VA) { auto *New = new (Alloc) DefinedRelative(Name, VA); addSymbol(New); return New; } DefinedAbsolute *SymbolTable::addAbsolute(StringRef Name, uint64_t VA) { auto *New = new (Alloc) DefinedAbsolute(Name, VA); addSymbol(New); return New; } void SymbolTable::printMap(llvm::raw_ostream &OS) { for (ObjectFile *File : ObjectFiles) { OS << File->getShortName() << ":\n"; for (SymbolBody *Body : File->getSymbols()) if (auto *R = dyn_cast<DefinedRegular>(Body)) if (R->getChunk()->isLive()) OS << Twine::utohexstr(Config->ImageBase + R->getRVA()) << " " << R->getName() << "\n"; } } void SymbolTable::addCombinedLTOObject(ObjectFile *Obj) { for (SymbolBody *Body : Obj->getSymbols()) { if (!Body->isExternal()) continue; // We should not see any new undefined symbols at this point, but we'll // diagnose them later in reportRemainingUndefines(). StringRef Name = Body->getName(); Symbol *Sym = insert(Body); if (isa<DefinedBitcode>(Sym->Body)) { Sym->Body = Body; continue; } if (auto *L = dyn_cast<Lazy>(Sym->Body)) { // We may see new references to runtime library symbols such as __chkstk // here. These symbols must be wholly defined in non-bitcode files. addMemberFile(L); continue; } SymbolBody *Existing = Sym->Body; int Comp = Existing->compare(Body); if (Comp == 0) error(Twine("LTO: unexpected duplicate symbol: ") + Name); if (Comp < 0) Sym->Body = Body; } } void SymbolTable::addCombinedLTOObjects() { if (BitcodeFiles.empty()) return; // Diagnose any undefined symbols early, but do not resolve weak externals, // as resolution breaks the invariant that each Symbol points to a unique // SymbolBody, which we rely on to replace DefinedBitcode symbols correctly. reportRemainingUndefines(/*Resolve=*/false); // Create an object file and add it to the symbol table by replacing any // DefinedBitcode symbols with the definitions in the object file. LTOCodeGenerator CG; CG.setOptLevel(Config->LTOOptLevel); std::vector<ObjectFile *> Objs = createLTOObjects(&CG); for (ObjectFile *Obj : Objs) addCombinedLTOObject(Obj); size_t NumBitcodeFiles = BitcodeFiles.size(); run(); if (BitcodeFiles.size() != NumBitcodeFiles) error("LTO: late loaded symbol created new bitcode reference"); } // Combine and compile bitcode files and then return the result // as a vector of regular COFF object files. std::vector<ObjectFile *> SymbolTable::createLTOObjects(LTOCodeGenerator *CG) { // All symbols referenced by non-bitcode objects must be preserved. for (ObjectFile *File : ObjectFiles) for (SymbolBody *Body : File->getSymbols()) if (auto *S = dyn_cast<DefinedBitcode>(Body->repl())) CG->addMustPreserveSymbol(S->getName()); // Likewise for bitcode symbols which we initially resolved to non-bitcode. for (BitcodeFile *File : BitcodeFiles) for (SymbolBody *Body : File->getSymbols()) if (isa<DefinedBitcode>(Body) && !isa<DefinedBitcode>(Body->repl())) CG->addMustPreserveSymbol(Body->getName()); // Likewise for other symbols that must be preserved. for (Undefined *U : Config->GCRoot) { if (auto *S = dyn_cast<DefinedBitcode>(U->repl())) CG->addMustPreserveSymbol(S->getName()); else if (auto *S = dyn_cast_or_null<DefinedBitcode>(U->getWeakAlias())) CG->addMustPreserveSymbol(S->getName()); } CG->setModule(BitcodeFiles[0]->takeModule()); for (unsigned I = 1, E = BitcodeFiles.size(); I != E; ++I) CG->addModule(BitcodeFiles[I]->getModule()); bool DisableVerify = true; #ifdef NDEBUG DisableVerify = false; #endif std::string ErrMsg; if (!CG->optimize(DisableVerify, false, false, false, ErrMsg)) error(ErrMsg); Objs.resize(Config->LTOJobs); // Use std::list to avoid invalidation of pointers in OSPtrs. std::list<raw_svector_ostream> OSs; std::vector<raw_pwrite_stream *> OSPtrs; for (SmallVector<char, 0> &Obj : Objs) { OSs.emplace_back(Obj); OSPtrs.push_back(&OSs.back()); } if (!CG->compileOptimized(OSPtrs, ErrMsg)) error(ErrMsg); std::vector<ObjectFile *> ObjFiles; for (SmallVector<char, 0> &Obj : Objs) { auto *ObjFile = new ObjectFile( MemoryBufferRef(StringRef(Obj.data(), Obj.size()), "<LTO object>")); Files.emplace_back(ObjFile); ObjectFiles.push_back(ObjFile); ObjFile->parse(); ObjFiles.push_back(ObjFile); } return ObjFiles; } } // namespace coff } // namespace lld <commit_msg>COFF: Do not call std::async with std::launch::async if multithreading is disabled.<commit_after>//===- SymbolTable.cpp ----------------------------------------------------===// // // The LLVM Linker // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "Config.h" #include "Driver.h" #include "Error.h" #include "SymbolTable.h" #include "Symbols.h" #include "lld/Core/Parallel.h" #include "llvm/LTO/LTOCodeGenerator.h" #include "llvm/Support/Debug.h" #include "llvm/Support/raw_ostream.h" #include <utility> using namespace llvm; namespace lld { namespace coff { void SymbolTable::addFile(std::unique_ptr<InputFile> FileP) { #if LLVM_ENABLE_THREADS std::launch Policy = std::launch::async; #else std::launch Policy = std::launch::deferred; #endif InputFile *File = FileP.get(); Files.push_back(std::move(FileP)); if (auto *F = dyn_cast<ArchiveFile>(File)) { ArchiveQueue.push_back( std::async(Policy, [=]() { F->parse(); return F; })); return; } ObjectQueue.push_back( std::async(Policy, [=]() { File->parse(); return File; })); if (auto *F = dyn_cast<ObjectFile>(File)) { ObjectFiles.push_back(F); } else if (auto *F = dyn_cast<BitcodeFile>(File)) { BitcodeFiles.push_back(F); } else { ImportFiles.push_back(cast<ImportFile>(File)); } } void SymbolTable::step() { if (queueEmpty()) return; readObjects(); readArchives(); } void SymbolTable::run() { while (!queueEmpty()) step(); } void SymbolTable::readArchives() { if (ArchiveQueue.empty()) return; // Add lazy symbols to the symbol table. Lazy symbols that conflict // with existing undefined symbols are accumulated in LazySyms. std::vector<Symbol *> LazySyms; for (std::future<ArchiveFile *> &Future : ArchiveQueue) { ArchiveFile *File = Future.get(); if (Config->Verbose) llvm::outs() << "Reading " << File->getShortName() << "\n"; for (Lazy &Sym : File->getLazySymbols()) addLazy(&Sym, &LazySyms); } ArchiveQueue.clear(); // Add archive member files to ObjectQueue that should resolve // existing undefined symbols. for (Symbol *Sym : LazySyms) addMemberFile(cast<Lazy>(Sym->Body)); } void SymbolTable::readObjects() { if (ObjectQueue.empty()) return; // Add defined and undefined symbols to the symbol table. std::vector<StringRef> Directives; for (size_t I = 0; I < ObjectQueue.size(); ++I) { InputFile *File = ObjectQueue[I].get(); if (Config->Verbose) llvm::outs() << "Reading " << File->getShortName() << "\n"; // Adding symbols may add more files to ObjectQueue // (but not to ArchiveQueue). for (SymbolBody *Sym : File->getSymbols()) if (Sym->isExternal()) addSymbol(Sym); StringRef S = File->getDirectives(); if (!S.empty()) { Directives.push_back(S); if (Config->Verbose) llvm::outs() << "Directives: " << File->getShortName() << ": " << S << "\n"; } } ObjectQueue.clear(); // Parse directive sections. This may add files to // ArchiveQueue and ObjectQueue. for (StringRef S : Directives) Driver->parseDirectives(S); } bool SymbolTable::queueEmpty() { return ArchiveQueue.empty() && ObjectQueue.empty(); } void SymbolTable::reportRemainingUndefines(bool Resolve) { llvm::SmallPtrSet<SymbolBody *, 8> Undefs; for (auto &I : Symtab) { Symbol *Sym = I.second; auto *Undef = dyn_cast<Undefined>(Sym->Body); if (!Undef) continue; StringRef Name = Undef->getName(); // A weak alias may have been resolved, so check for that. if (Defined *D = Undef->getWeakAlias()) { if (Resolve) Sym->Body = D; continue; } // If we can resolve a symbol by removing __imp_ prefix, do that. // This odd rule is for compatibility with MSVC linker. if (Name.startswith("__imp_")) { Symbol *Imp = find(Name.substr(strlen("__imp_"))); if (Imp && isa<Defined>(Imp->Body)) { if (!Resolve) continue; auto *D = cast<Defined>(Imp->Body); auto *S = new (Alloc) DefinedLocalImport(Name, D); LocalImportChunks.push_back(S->getChunk()); Sym->Body = S; continue; } } // Remaining undefined symbols are not fatal if /force is specified. // They are replaced with dummy defined symbols. if (Config->Force && Resolve) Sym->Body = new (Alloc) DefinedAbsolute(Name, 0); Undefs.insert(Sym->Body); } if (Undefs.empty()) return; for (Undefined *U : Config->GCRoot) if (Undefs.count(U->repl())) llvm::errs() << "<root>: undefined symbol: " << U->getName() << "\n"; for (std::unique_ptr<InputFile> &File : Files) if (!isa<ArchiveFile>(File.get())) for (SymbolBody *Sym : File->getSymbols()) if (Undefs.count(Sym->repl())) llvm::errs() << File->getShortName() << ": undefined symbol: " << Sym->getName() << "\n"; if (!Config->Force) error("Link failed"); } void SymbolTable::addLazy(Lazy *New, std::vector<Symbol *> *Accum) { Symbol *Sym = insert(New); if (Sym->Body == New) return; SymbolBody *Existing = Sym->Body; if (isa<Defined>(Existing)) return; if (Lazy *L = dyn_cast<Lazy>(Existing)) if (L->getFileIndex() < New->getFileIndex()) return; Sym->Body = New; New->setBackref(Sym); if (isa<Undefined>(Existing)) Accum->push_back(Sym); } void SymbolTable::addSymbol(SymbolBody *New) { // Find an existing symbol or create and insert a new one. assert(isa<Defined>(New) || isa<Undefined>(New)); Symbol *Sym = insert(New); if (Sym->Body == New) return; SymbolBody *Existing = Sym->Body; // If we have an undefined symbol and a lazy symbol, // let the lazy symbol to read a member file. if (auto *L = dyn_cast<Lazy>(Existing)) { // Undefined symbols with weak aliases need not to be resolved, // since they would be replaced with weak aliases if they remain // undefined. if (auto *U = dyn_cast<Undefined>(New)) { if (!U->WeakAlias) { addMemberFile(L); return; } } Sym->Body = New; return; } // compare() returns -1, 0, or 1 if the lhs symbol is less preferable, // equivalent (conflicting), or more preferable, respectively. int Comp = Existing->compare(New); if (Comp == 0) error(Twine("duplicate symbol: ") + Existing->getDebugName() + " and " + New->getDebugName()); if (Comp < 0) Sym->Body = New; } Symbol *SymbolTable::insert(SymbolBody *New) { Symbol *&Sym = Symtab[New->getName()]; if (Sym) { New->setBackref(Sym); return Sym; } Sym = new (Alloc) Symbol(New); New->setBackref(Sym); return Sym; } // Reads an archive member file pointed by a given symbol. void SymbolTable::addMemberFile(Lazy *Body) { std::unique_ptr<InputFile> File = Body->getMember(); // getMember returns an empty buffer if the member was already // read from the library. if (!File) return; if (Config->Verbose) llvm::outs() << "Loaded " << File->getShortName() << " for " << Body->getName() << "\n"; addFile(std::move(File)); } std::vector<Chunk *> SymbolTable::getChunks() { std::vector<Chunk *> Res; for (ObjectFile *File : ObjectFiles) { std::vector<Chunk *> &V = File->getChunks(); Res.insert(Res.end(), V.begin(), V.end()); } return Res; } Symbol *SymbolTable::find(StringRef Name) { auto It = Symtab.find(Name); if (It == Symtab.end()) return nullptr; return It->second; } Symbol *SymbolTable::findUnderscore(StringRef Name) { if (Config->Machine == I386) return find(("_" + Name).str()); return find(Name); } StringRef SymbolTable::findByPrefix(StringRef Prefix) { for (auto Pair : Symtab) { StringRef Name = Pair.first; if (Name.startswith(Prefix)) return Name; } return ""; } StringRef SymbolTable::findMangle(StringRef Name) { if (Symbol *Sym = find(Name)) if (!isa<Undefined>(Sym->Body)) return Name; if (Config->Machine != I386) return findByPrefix(("?" + Name + "@@Y").str()); if (!Name.startswith("_")) return ""; // Search for x86 C function. StringRef S = findByPrefix((Name + "@").str()); if (!S.empty()) return S; // Search for x86 C++ non-member function. return findByPrefix(("?" + Name.substr(1) + "@@Y").str()); } void SymbolTable::mangleMaybe(Undefined *U) { if (U->WeakAlias) return; if (!isa<Undefined>(U->repl())) return; StringRef Alias = findMangle(U->getName()); if (!Alias.empty()) U->WeakAlias = addUndefined(Alias); } Undefined *SymbolTable::addUndefined(StringRef Name) { auto *New = new (Alloc) Undefined(Name); addSymbol(New); if (auto *U = dyn_cast<Undefined>(New->repl())) return U; return New; } DefinedRelative *SymbolTable::addRelative(StringRef Name, uint64_t VA) { auto *New = new (Alloc) DefinedRelative(Name, VA); addSymbol(New); return New; } DefinedAbsolute *SymbolTable::addAbsolute(StringRef Name, uint64_t VA) { auto *New = new (Alloc) DefinedAbsolute(Name, VA); addSymbol(New); return New; } void SymbolTable::printMap(llvm::raw_ostream &OS) { for (ObjectFile *File : ObjectFiles) { OS << File->getShortName() << ":\n"; for (SymbolBody *Body : File->getSymbols()) if (auto *R = dyn_cast<DefinedRegular>(Body)) if (R->getChunk()->isLive()) OS << Twine::utohexstr(Config->ImageBase + R->getRVA()) << " " << R->getName() << "\n"; } } void SymbolTable::addCombinedLTOObject(ObjectFile *Obj) { for (SymbolBody *Body : Obj->getSymbols()) { if (!Body->isExternal()) continue; // We should not see any new undefined symbols at this point, but we'll // diagnose them later in reportRemainingUndefines(). StringRef Name = Body->getName(); Symbol *Sym = insert(Body); if (isa<DefinedBitcode>(Sym->Body)) { Sym->Body = Body; continue; } if (auto *L = dyn_cast<Lazy>(Sym->Body)) { // We may see new references to runtime library symbols such as __chkstk // here. These symbols must be wholly defined in non-bitcode files. addMemberFile(L); continue; } SymbolBody *Existing = Sym->Body; int Comp = Existing->compare(Body); if (Comp == 0) error(Twine("LTO: unexpected duplicate symbol: ") + Name); if (Comp < 0) Sym->Body = Body; } } void SymbolTable::addCombinedLTOObjects() { if (BitcodeFiles.empty()) return; // Diagnose any undefined symbols early, but do not resolve weak externals, // as resolution breaks the invariant that each Symbol points to a unique // SymbolBody, which we rely on to replace DefinedBitcode symbols correctly. reportRemainingUndefines(/*Resolve=*/false); // Create an object file and add it to the symbol table by replacing any // DefinedBitcode symbols with the definitions in the object file. LTOCodeGenerator CG; CG.setOptLevel(Config->LTOOptLevel); std::vector<ObjectFile *> Objs = createLTOObjects(&CG); for (ObjectFile *Obj : Objs) addCombinedLTOObject(Obj); size_t NumBitcodeFiles = BitcodeFiles.size(); run(); if (BitcodeFiles.size() != NumBitcodeFiles) error("LTO: late loaded symbol created new bitcode reference"); } // Combine and compile bitcode files and then return the result // as a vector of regular COFF object files. std::vector<ObjectFile *> SymbolTable::createLTOObjects(LTOCodeGenerator *CG) { // All symbols referenced by non-bitcode objects must be preserved. for (ObjectFile *File : ObjectFiles) for (SymbolBody *Body : File->getSymbols()) if (auto *S = dyn_cast<DefinedBitcode>(Body->repl())) CG->addMustPreserveSymbol(S->getName()); // Likewise for bitcode symbols which we initially resolved to non-bitcode. for (BitcodeFile *File : BitcodeFiles) for (SymbolBody *Body : File->getSymbols()) if (isa<DefinedBitcode>(Body) && !isa<DefinedBitcode>(Body->repl())) CG->addMustPreserveSymbol(Body->getName()); // Likewise for other symbols that must be preserved. for (Undefined *U : Config->GCRoot) { if (auto *S = dyn_cast<DefinedBitcode>(U->repl())) CG->addMustPreserveSymbol(S->getName()); else if (auto *S = dyn_cast_or_null<DefinedBitcode>(U->getWeakAlias())) CG->addMustPreserveSymbol(S->getName()); } CG->setModule(BitcodeFiles[0]->takeModule()); for (unsigned I = 1, E = BitcodeFiles.size(); I != E; ++I) CG->addModule(BitcodeFiles[I]->getModule()); bool DisableVerify = true; #ifdef NDEBUG DisableVerify = false; #endif std::string ErrMsg; if (!CG->optimize(DisableVerify, false, false, false, ErrMsg)) error(ErrMsg); Objs.resize(Config->LTOJobs); // Use std::list to avoid invalidation of pointers in OSPtrs. std::list<raw_svector_ostream> OSs; std::vector<raw_pwrite_stream *> OSPtrs; for (SmallVector<char, 0> &Obj : Objs) { OSs.emplace_back(Obj); OSPtrs.push_back(&OSs.back()); } if (!CG->compileOptimized(OSPtrs, ErrMsg)) error(ErrMsg); std::vector<ObjectFile *> ObjFiles; for (SmallVector<char, 0> &Obj : Objs) { auto *ObjFile = new ObjectFile( MemoryBufferRef(StringRef(Obj.data(), Obj.size()), "<LTO object>")); Files.emplace_back(ObjFile); ObjectFiles.push_back(ObjFile); ObjFile->parse(); ObjFiles.push_back(ObjFile); } return ObjFiles; } } // namespace coff } // namespace lld <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////////// // Name: shell.cpp // Purpose: Implementation of class wxExSTCShell // Author: Anton van Wezenbeek // Copyright: (c) 2012 Anton van Wezenbeek //////////////////////////////////////////////////////////////////////////////// #include <wx/wxprec.h> #ifndef WX_PRECOMP #include <wx/wx.h> #endif #include <numeric> #include <functional> #include <wx/config.h> #include <wx/tokenzr.h> #include <wx/extension/shell.h> #include <wx/extension/defs.h> // for ID_SHELL_COMMAND #include <wx/extension/util.h> #if wxUSE_GUI BEGIN_EVENT_TABLE(wxExSTCShell, wxExSTC) EVT_CHAR(wxExSTCShell::OnChar) EVT_KEY_DOWN(wxExSTCShell::OnKey) EVT_STC_CHARADDED(wxID_ANY, wxExSTCShell::OnStyledText) END_EVENT_TABLE() wxExSTCShell::wxExSTCShell( wxWindow* parent, const wxString& prompt, const wxString& command_end, bool echo, int commands_save_in_config, const wxString& lexer, long menu_flags, wxWindowID id, const wxPoint& pos, const wxSize& size, long style) : wxExSTC( parent, wxEmptyString, STC_WIN_NO_INDICATOR, wxEmptyString, // title menu_flags, id, pos, size, style) , m_Command(wxEmptyString) , m_CommandEnd((command_end == wxEmptyString ? GetEOL(): command_end)) , m_CommandStartPosition(0) , m_Echo(echo) // take a char that is not likely to appear inside commands , m_CommandsInConfigDelimiter(wxUniChar(0x03)) , m_CommandsSaveInConfig(commands_save_in_config) , m_Prompt(prompt) , m_Handler(parent) , m_Enabled(true) { // Override defaults from config. SetEdgeMode(wxSTC_EDGE_NONE); ResetMargins(false); // do not reset divider margin SetName("SHELL"); // Start with a prompt. Prompt(); if (m_CommandsSaveInConfig > 0) { // Get all previous commands. wxStringTokenizer tkz(wxConfigBase::Get()->Read("Shell"), m_CommandsInConfigDelimiter); while (tkz.HasMoreTokens()) { const wxString val = tkz.GetNextToken(); m_Commands.push_front(val); } } // Take care that m_CommandsIterator is valid. m_CommandsIterator = m_Commands.end(); EnableShell(true); SetLexer(lexer); } wxExSTCShell::~wxExSTCShell() { if (m_CommandsSaveInConfig > 0) { wxString values; int items = 0; for ( #ifdef wxExUSE_CPP0X auto it = m_Commands.rbegin(); #else std::list < wxString >::reverse_iterator it = m_Commands.rbegin(); #endif it != m_Commands.rend() && items < m_CommandsSaveInConfig; ++it) { values += *it + m_CommandsInConfigDelimiter; items++; } wxConfigBase::Get()->Write("Shell", values); } } void wxExSTCShell::AddText(const wxString& text) { wxExSTC::AddText(text); EnsureCaretVisible(); m_CommandStartPosition = GetCurrentPos(); } void wxExSTCShell::EnableShell(bool enabled) { m_Enabled = enabled; if (!m_Enabled) { // A disabled shell follows STC vi mode. GetVi().Use(wxConfigBase::Get()->ReadBool(_("vi mode"), true)); } else { // An enabled shell does not use vi mode. GetVi().Use(false); } } void wxExSTCShell::Expand() { wxDir dir(wxGetCwd()); wxString filename; const wxString word(m_Command.AfterLast(' ')); if (dir.GetFirst(&filename, word + "*")) { const wxString expansion = filename.Mid(word.length()); AddText(expansion); m_Command += expansion; } } const wxString wxExSTCShell::GetCommand() const { if (!m_Commands.empty()) { return m_Commands.back(); } else { return wxEmptyString; } } const wxString wxExSTCShell::GetHistory() const { return accumulate(m_Commands.begin(), m_Commands.end(), wxString()); } void wxExSTCShell::KeepCommand() { m_Commands.remove(m_Command); m_Commands.push_back(m_Command); } // No longer used, for the moment. void wxExSTCShell::OnCommand(wxCommandEvent& command) { if (!m_Enabled) { command.Skip(); return; } switch (command.GetId()) { default: wxFAIL; break; } } void wxExSTCShell::OnChar(wxKeyEvent& event) { if (m_Enabled) { ProcessChar(event.GetKeyCode()); } if (m_Echo) { event.Skip(); } } void wxExSTCShell::OnKey(wxKeyEvent& event) { if (!m_Enabled) { event.Skip(); return; } const int key = event.GetKeyCode(); if (key == WXK_RETURN || key == WXK_TAB) { ProcessChar(key); } // Up or down key pressed, and at the end of document. else if ((key == WXK_UP || key == WXK_DOWN) && GetCurrentPos() == GetTextLength()) { ShowCommand(key); } // Home key pressed. else if (key == WXK_HOME) { Home(); const wxString line = GetLine(GetCurrentLine()); if (line.StartsWith(m_Prompt)) { GotoPos(GetCurrentPos() + m_Prompt.length()); } } // Ctrl-Q pressed, used to stop processing. // Ctrl-C pressed and no text selected (otherwise copy), also used to stop processing. else if ( event.GetModifiers() == wxMOD_CONTROL && ( key == 'Q' || (key == 'C' && GetSelectedText().empty()))) { wxCommandEvent event(wxEVT_COMMAND_MENU_SELECTED, ID_SHELL_COMMAND_STOP); wxPostEvent(m_Handler, event); } // Ctrl-V pressed, used for pasting as well. else if (event.GetModifiers() == wxMOD_CONTROL && key == 'V') { Paste(); } // Backspace or delete key pressed. else if (key == WXK_BACK || key == WXK_DELETE) { if (GetCurrentPos() <= m_CommandStartPosition) { // Ignore, so do nothing. } else { // Allow. ProcessChar(key); if (m_Echo) event.Skip(); } } // The rest. else { // If we enter regular text and not already building a command, first goto end. if (event.GetModifiers() == wxMOD_NONE && key < WXK_START && GetCurrentPos() < m_CommandStartPosition) { DocumentEnd(); } m_CommandsIterator = m_Commands.end(); if (m_Echo) event.Skip(); } } void wxExSTCShell::OnStyledText(wxStyledTextEvent& event) { if (!m_Enabled) { event.Skip(); return; } // do nothing, keep event from sent to wxExSTC. } void wxExSTCShell::Paste() { if (!CanPaste()) { return; } // Take care that we cannot paste somewhere inside. if (GetCurrentPos() < m_CommandStartPosition) { DocumentEnd(); } wxExSTC::Paste(); m_Command += wxExClipboardGet(); } void wxExSTCShell::ProcessChar(int key) { // No need to check m_Enabled, already done by calling this method. if (key == WXK_RETURN) { if (m_Command.empty()) { wxCommandEvent event(wxEVT_COMMAND_MENU_SELECTED, ID_SHELL_COMMAND); event.SetString(m_Command); wxPostEvent(m_Handler, event); } else if ( m_CommandEnd == GetEOL() || m_Command.EndsWith(m_CommandEnd)) { // We have a command. EmptyUndoBuffer(); // History command. if (m_Command == wxString("history") + (m_CommandEnd == GetEOL() ? wxString(wxEmptyString): m_CommandEnd)) { KeepCommand(); ShowHistory(); Prompt(); } // !.. command, get it from history. else if (m_Command.StartsWith("!")) { if (SetCommandFromHistory(m_Command.substr(1))) { AppendText(GetEOL() + m_Command); // We don't keep the command, so commands are not rearranged and // repeatingly calling !5 always gives the same command, just as bash does. wxCommandEvent event(wxEVT_COMMAND_MENU_SELECTED, ID_SHELL_COMMAND); event.SetString(m_Command); wxPostEvent(m_Handler, event); } else { Prompt(GetEOL() + m_Command + ": " + _("event not found")); } } // Other command, send to parent. else { KeepCommand(); wxCommandEvent event(wxEVT_COMMAND_MENU_SELECTED, ID_SHELL_COMMAND); event.SetString(m_Command); wxPostEvent(m_Handler, event); } m_Command.clear(); } m_CommandsIterator = m_Commands.end(); } else if (key == WXK_BACK) { // Delete the key at current position (-1 because of WXK_BACK). const int index = GetCurrentPos() - m_CommandStartPosition - 1; if (index >= 0 && index < m_Command.length() && m_Command.length() > 0) { m_Command.erase(index, 1); } } else if (key == WXK_TAB) { Expand(); } else { // Insert the key at current position. const int index = GetCurrentPos() - m_CommandStartPosition; if (index >= 0 && index < m_Command.size()) { m_Command.insert(index, wxChar(key)); } else { m_Command += wxChar(key); } } } bool wxExSTCShell::Prompt(const wxString& text, bool add_eol) { if (!m_Enabled) { return false; } if (!text.empty()) { AppendText(text); } if (!m_Prompt.empty()) { if (GetTextLength() > 0 && add_eol) { AppendText(GetEOL()); } AppendText(m_Prompt); } DocumentEnd(); m_CommandStartPosition = GetCurrentPos(); EmptyUndoBuffer(); return true; } bool wxExSTCShell::SetCommandFromHistory(const wxString& short_command) { const int no_asked_for = atoi(short_command.c_str()); if (no_asked_for > 0) { int no = 1; for ( #ifdef wxExUSE_CPP0X auto it = m_Commands.begin(); #else std::list < wxString >::iterator it = m_Commands.begin(); #endif it != m_Commands.end(); ++it) { if (no == no_asked_for) { m_Command = *it; return true; } no++; } } else { wxString short_command_check; if (m_CommandEnd == GetEOL()) { short_command_check = short_command; } else { short_command_check = short_command.substr( 0, short_command.length() - m_CommandEnd.length()); } for ( #ifdef wxExUSE_CPP0X auto it = m_Commands.rbegin(); #else std::list < wxString >::reverse_iterator it = m_Commands.rbegin(); #endif it != m_Commands.rend(); ++it) { const wxString command = *it; if (command.StartsWith(short_command_check)) { m_Command = command; return true; } } } return false; } bool wxExSTCShell::SetPrompt(const wxString& prompt, bool do_prompt) { if (!m_Enabled) { return false; } m_Prompt = prompt; if (do_prompt) { Prompt(); } return true; } void wxExSTCShell::ShowCommand(int key) { SetTargetStart(m_CommandStartPosition); SetTargetEnd(GetTextLength()); if (key == WXK_UP) { if (m_CommandsIterator != m_Commands.begin()) { m_CommandsIterator--; } } else { if (m_CommandsIterator != m_Commands.end()) { m_CommandsIterator++; } } if (m_CommandsIterator != m_Commands.end()) { m_Command = *m_CommandsIterator; ReplaceTarget(m_Command); } DocumentEnd(); } void wxExSTCShell::ShowHistory() { int command_no = 1; for ( #ifdef wxExUSE_CPP0X auto it = m_Commands.begin(); #else std::list < wxString >::iterator it = m_Commands.begin(); #endif it != m_Commands.end(); ++it) { const wxString command = *it; AppendText(wxString::Format("\n%d %s", command_no++, command.c_str())); } } #endif // wxUSE_GUI <commit_msg>fixed using backspace after tab expand<commit_after>//////////////////////////////////////////////////////////////////////////////// // Name: shell.cpp // Purpose: Implementation of class wxExSTCShell // Author: Anton van Wezenbeek // Copyright: (c) 2012 Anton van Wezenbeek //////////////////////////////////////////////////////////////////////////////// #include <wx/wxprec.h> #ifndef WX_PRECOMP #include <wx/wx.h> #endif #include <numeric> #include <functional> #include <wx/config.h> #include <wx/tokenzr.h> #include <wx/extension/shell.h> #include <wx/extension/defs.h> // for ID_SHELL_COMMAND #include <wx/extension/util.h> #if wxUSE_GUI BEGIN_EVENT_TABLE(wxExSTCShell, wxExSTC) EVT_CHAR(wxExSTCShell::OnChar) EVT_KEY_DOWN(wxExSTCShell::OnKey) EVT_STC_CHARADDED(wxID_ANY, wxExSTCShell::OnStyledText) END_EVENT_TABLE() wxExSTCShell::wxExSTCShell( wxWindow* parent, const wxString& prompt, const wxString& command_end, bool echo, int commands_save_in_config, const wxString& lexer, long menu_flags, wxWindowID id, const wxPoint& pos, const wxSize& size, long style) : wxExSTC( parent, wxEmptyString, STC_WIN_NO_INDICATOR, wxEmptyString, // title menu_flags, id, pos, size, style) , m_Command(wxEmptyString) , m_CommandEnd((command_end == wxEmptyString ? GetEOL(): command_end)) , m_CommandStartPosition(0) , m_Echo(echo) // take a char that is not likely to appear inside commands , m_CommandsInConfigDelimiter(wxUniChar(0x03)) , m_CommandsSaveInConfig(commands_save_in_config) , m_Prompt(prompt) , m_Handler(parent) , m_Enabled(true) { // Override defaults from config. SetEdgeMode(wxSTC_EDGE_NONE); ResetMargins(false); // do not reset divider margin SetName("SHELL"); // Start with a prompt. Prompt(); if (m_CommandsSaveInConfig > 0) { // Get all previous commands. wxStringTokenizer tkz(wxConfigBase::Get()->Read("Shell"), m_CommandsInConfigDelimiter); while (tkz.HasMoreTokens()) { const wxString val = tkz.GetNextToken(); m_Commands.push_front(val); } } // Take care that m_CommandsIterator is valid. m_CommandsIterator = m_Commands.end(); EnableShell(true); SetLexer(lexer); } wxExSTCShell::~wxExSTCShell() { if (m_CommandsSaveInConfig > 0) { wxString values; int items = 0; for ( #ifdef wxExUSE_CPP0X auto it = m_Commands.rbegin(); #else std::list < wxString >::reverse_iterator it = m_Commands.rbegin(); #endif it != m_Commands.rend() && items < m_CommandsSaveInConfig; ++it) { values += *it + m_CommandsInConfigDelimiter; items++; } wxConfigBase::Get()->Write("Shell", values); } } void wxExSTCShell::AddText(const wxString& text) { wxExSTC::AddText(text); EnsureCaretVisible(); m_CommandStartPosition = GetCurrentPos(); } void wxExSTCShell::EnableShell(bool enabled) { m_Enabled = enabled; if (!m_Enabled) { // A disabled shell follows STC vi mode. GetVi().Use(wxConfigBase::Get()->ReadBool(_("vi mode"), true)); } else { // An enabled shell does not use vi mode. GetVi().Use(false); } } void wxExSTCShell::Expand() { wxDir dir(wxGetCwd()); wxString filename; const wxString word(m_Command.AfterLast(' ')); if (dir.GetFirst(&filename, word + "*")) { const wxString expansion = filename.Mid(word.length()); // We cannot use our AddText, as command start pos // should not be changed. wxExSTC::AddText(expansion); m_Command += expansion; } } const wxString wxExSTCShell::GetCommand() const { if (!m_Commands.empty()) { return m_Commands.back(); } else { return wxEmptyString; } } const wxString wxExSTCShell::GetHistory() const { return accumulate(m_Commands.begin(), m_Commands.end(), wxString()); } void wxExSTCShell::KeepCommand() { m_Commands.remove(m_Command); m_Commands.push_back(m_Command); } // No longer used, for the moment. void wxExSTCShell::OnCommand(wxCommandEvent& command) { if (!m_Enabled) { command.Skip(); return; } switch (command.GetId()) { default: wxFAIL; break; } } void wxExSTCShell::OnChar(wxKeyEvent& event) { if (m_Enabled) { ProcessChar(event.GetKeyCode()); } if (m_Echo) { event.Skip(); } } void wxExSTCShell::OnKey(wxKeyEvent& event) { if (!m_Enabled) { event.Skip(); return; } const int key = event.GetKeyCode(); if (key == WXK_RETURN || key == WXK_TAB) { ProcessChar(key); } // Up or down key pressed, and at the end of document. else if ((key == WXK_UP || key == WXK_DOWN) && GetCurrentPos() == GetTextLength()) { ShowCommand(key); } // Home key pressed. else if (key == WXK_HOME) { Home(); const wxString line = GetLine(GetCurrentLine()); if (line.StartsWith(m_Prompt)) { GotoPos(GetCurrentPos() + m_Prompt.length()); } } // Ctrl-Q pressed, used to stop processing. // Ctrl-C pressed and no text selected (otherwise copy), also used to stop processing. else if ( event.GetModifiers() == wxMOD_CONTROL && ( key == 'Q' || (key == 'C' && GetSelectedText().empty()))) { wxCommandEvent event(wxEVT_COMMAND_MENU_SELECTED, ID_SHELL_COMMAND_STOP); wxPostEvent(m_Handler, event); } // Ctrl-V pressed, used for pasting as well. else if (event.GetModifiers() == wxMOD_CONTROL && key == 'V') { Paste(); } // Backspace or delete key pressed. else if (key == WXK_BACK || key == WXK_DELETE) { if (GetCurrentPos() <= m_CommandStartPosition) { // Ignore, so do nothing. } else { // Allow. ProcessChar(key); if (m_Echo) event.Skip(); } } // The rest. else { // If we enter regular text and not already building a command, first goto end. if (event.GetModifiers() == wxMOD_NONE && key < WXK_START && GetCurrentPos() < m_CommandStartPosition) { DocumentEnd(); } m_CommandsIterator = m_Commands.end(); if (m_Echo) event.Skip(); } } void wxExSTCShell::OnStyledText(wxStyledTextEvent& event) { if (!m_Enabled) { event.Skip(); return; } // do nothing, keep event from sent to wxExSTC. } void wxExSTCShell::Paste() { if (!CanPaste()) { return; } // Take care that we cannot paste somewhere inside. if (GetCurrentPos() < m_CommandStartPosition) { DocumentEnd(); } wxExSTC::Paste(); m_Command += wxExClipboardGet(); } void wxExSTCShell::ProcessChar(int key) { // No need to check m_Enabled, already done by calling this method. if (key == WXK_RETURN) { if (m_Command.empty()) { wxCommandEvent event(wxEVT_COMMAND_MENU_SELECTED, ID_SHELL_COMMAND); event.SetString(m_Command); wxPostEvent(m_Handler, event); } else if ( m_CommandEnd == GetEOL() || m_Command.EndsWith(m_CommandEnd)) { // We have a command. EmptyUndoBuffer(); // History command. if (m_Command == wxString("history") + (m_CommandEnd == GetEOL() ? wxString(wxEmptyString): m_CommandEnd)) { KeepCommand(); ShowHistory(); Prompt(); } // !.. command, get it from history. else if (m_Command.StartsWith("!")) { if (SetCommandFromHistory(m_Command.substr(1))) { AppendText(GetEOL() + m_Command); // We don't keep the command, so commands are not rearranged and // repeatingly calling !5 always gives the same command, just as bash does. wxCommandEvent event(wxEVT_COMMAND_MENU_SELECTED, ID_SHELL_COMMAND); event.SetString(m_Command); wxPostEvent(m_Handler, event); } else { Prompt(GetEOL() + m_Command + ": " + _("event not found")); } } // Other command, send to parent. else { KeepCommand(); wxCommandEvent event(wxEVT_COMMAND_MENU_SELECTED, ID_SHELL_COMMAND); event.SetString(m_Command); wxPostEvent(m_Handler, event); } m_Command.clear(); } m_CommandsIterator = m_Commands.end(); } else if (key == WXK_BACK) { // Delete the key at current position (-1 because of WXK_BACK). const int index = GetCurrentPos() - m_CommandStartPosition - 1; if (index >= 0 && index < m_Command.length() && m_Command.length() > 0) { m_Command.erase(index, 1); } } else if (key == WXK_TAB) { Expand(); } else { // Insert the key at current position. const int index = GetCurrentPos() - m_CommandStartPosition; if (index >= 0 && index < m_Command.size()) { m_Command.insert(index, wxChar(key)); } else { m_Command += wxChar(key); } } } bool wxExSTCShell::Prompt(const wxString& text, bool add_eol) { if (!m_Enabled) { return false; } if (!text.empty()) { AppendText(text); } if (!m_Prompt.empty()) { if (GetTextLength() > 0 && add_eol) { AppendText(GetEOL()); } AppendText(m_Prompt); } DocumentEnd(); m_CommandStartPosition = GetCurrentPos(); EmptyUndoBuffer(); return true; } bool wxExSTCShell::SetCommandFromHistory(const wxString& short_command) { const int no_asked_for = atoi(short_command.c_str()); if (no_asked_for > 0) { int no = 1; for ( #ifdef wxExUSE_CPP0X auto it = m_Commands.begin(); #else std::list < wxString >::iterator it = m_Commands.begin(); #endif it != m_Commands.end(); ++it) { if (no == no_asked_for) { m_Command = *it; return true; } no++; } } else { wxString short_command_check; if (m_CommandEnd == GetEOL()) { short_command_check = short_command; } else { short_command_check = short_command.substr( 0, short_command.length() - m_CommandEnd.length()); } for ( #ifdef wxExUSE_CPP0X auto it = m_Commands.rbegin(); #else std::list < wxString >::reverse_iterator it = m_Commands.rbegin(); #endif it != m_Commands.rend(); ++it) { const wxString command = *it; if (command.StartsWith(short_command_check)) { m_Command = command; return true; } } } return false; } bool wxExSTCShell::SetPrompt(const wxString& prompt, bool do_prompt) { if (!m_Enabled) { return false; } m_Prompt = prompt; if (do_prompt) { Prompt(); } return true; } void wxExSTCShell::ShowCommand(int key) { SetTargetStart(m_CommandStartPosition); SetTargetEnd(GetTextLength()); if (key == WXK_UP) { if (m_CommandsIterator != m_Commands.begin()) { m_CommandsIterator--; } } else { if (m_CommandsIterator != m_Commands.end()) { m_CommandsIterator++; } } if (m_CommandsIterator != m_Commands.end()) { m_Command = *m_CommandsIterator; ReplaceTarget(m_Command); } DocumentEnd(); } void wxExSTCShell::ShowHistory() { int command_no = 1; for ( #ifdef wxExUSE_CPP0X auto it = m_Commands.begin(); #else std::list < wxString >::iterator it = m_Commands.begin(); #endif it != m_Commands.end(); ++it) { const wxString command = *it; AppendText(wxString::Format("\n%d %s", command_no++, command.c_str())); } } #endif // wxUSE_GUI <|endoftext|>
<commit_before>// Copyright (c) 2015 Felix Rieseberg <[email protected]> and Jason Poon <[email protected]>. All rights reserved. // Copyright (c) 2015 Ryan McShane <[email protected]> and Brandon Smith <[email protected]> // Thanks to both of those folks mentioned above who first thought up a bunch of this code // and released it as MIT to the world. #include "browser/win/windows_toast_notification.h" #include <shlobj.h> #include "base/strings/utf_string_conversions.h" #include "browser/notification_delegate.h" #include "browser/win/scoped_hstring.h" #include "browser/win/notification_presenter_win.h" #include "common/application_info.h" using namespace ABI::Windows::Data::Xml::Dom; namespace brightray { namespace { bool GetAppUserModelId(ScopedHString* app_id) { PWSTR current_app_id; if (SUCCEEDED(GetCurrentProcessExplicitAppUserModelID(&current_app_id))) { app_id->Reset(current_app_id); CoTaskMemFree(current_app_id); } else { app_id->Reset(base::UTF8ToUTF16(GetApplicationName())); } return app_id->success(); } } // namespace // static Notification* Notification::Create(NotificationDelegate* delegate, NotificationPresenter* presenter) { return new WindowsToastNotification(delegate, presenter); } // static ComPtr<ABI::Windows::UI::Notifications::IToastNotificationManagerStatics> WindowsToastNotification::toast_manager_; // static ComPtr<ABI::Windows::UI::Notifications::IToastNotifier> WindowsToastNotification::toast_notifier_; // static bool WindowsToastNotification::Initialize() { // Just initialize, don't care if it fails or already initialized. Windows::Foundation::Initialize(RO_INIT_MULTITHREADED); ScopedHString toast_manager_str( RuntimeClass_Windows_UI_Notifications_ToastNotificationManager); if (!toast_manager_str.success()) return false; if (FAILED(Windows::Foundation::GetActivationFactory(toast_manager_str, &toast_manager_))) return false; ScopedHString app_id; if (!GetAppUserModelId(&app_id)) return false; return SUCCEEDED( toast_manager_->CreateToastNotifierWithId(app_id, &toast_notifier_)); } WindowsToastNotification::WindowsToastNotification( NotificationDelegate* delegate, NotificationPresenter* presenter) : Notification(delegate, presenter) { } WindowsToastNotification::~WindowsToastNotification() { // Remove the notification on exit. if (toast_notification_) { RemoveCallbacks(toast_notification_.Get()); Dismiss(); } } void WindowsToastNotification::Show( const base::string16& title, const base::string16& msg, const std::string& tag, const GURL& icon_url, const SkBitmap& icon, const bool silent) { auto presenter_win = static_cast<NotificationPresenterWin*>(presenter()); std::wstring icon_path = presenter_win->SaveIconToFilesystem(icon, icon_url); ComPtr<IXmlDocument> toast_xml; if(FAILED(GetToastXml(toast_manager_.Get(), title, msg, icon_path, silent, &toast_xml))) { NotificationFailed(); return; } ScopedHString toast_str( RuntimeClass_Windows_UI_Notifications_ToastNotification); if (!toast_str.success()) { NotificationFailed(); return; } ComPtr<ABI::Windows::UI::Notifications::IToastNotificationFactory> toast_factory; if (FAILED(Windows::Foundation::GetActivationFactory(toast_str, &toast_factory))) { NotificationFailed(); return; } if (FAILED(toast_factory->CreateToastNotification(toast_xml.Get(), &toast_notification_))) { NotificationFailed(); return; } if (!SetupCallbacks(toast_notification_.Get())) { NotificationFailed(); return; } if (FAILED(toast_notifier_->Show(toast_notification_.Get()))) { NotificationFailed(); return; } delegate()->NotificationDisplayed(); } void WindowsToastNotification::Dismiss() { toast_notifier_->Hide(toast_notification_.Get()); } bool WindowsToastNotification::GetToastXml( ABI::Windows::UI::Notifications::IToastNotificationManagerStatics* toastManager, const std::wstring& title, const std::wstring& msg, const std::wstring& icon_path, const bool silent, IXmlDocument** toast_xml) { ABI::Windows::UI::Notifications::ToastTemplateType template_type; if (title.empty() || msg.empty()) { // Single line toast. template_type = icon_path.empty() ? ABI::Windows::UI::Notifications::ToastTemplateType_ToastText01 : ABI::Windows::UI::Notifications::ToastTemplateType_ToastImageAndText01; if (FAILED(toast_manager_->GetTemplateContent(template_type, toast_xml))) return false; if (!SetXmlText(*toast_xml, title.empty() ? msg : title)) return false; } else { // Title and body toast. template_type = icon_path.empty() ? ABI::Windows::UI::Notifications::ToastTemplateType_ToastText02 : ABI::Windows::UI::Notifications::ToastTemplateType_ToastImageAndText02; if (FAILED(toastManager->GetTemplateContent(template_type, toast_xml))) return false; if (!SetXmlText(*toast_xml, title, msg)) return false; } // Configure the toast's notification sound if (silent) { if (FAILED(SetXmlAudioSilent(*toast_xml))) return false; } // Configure the toast's image if (!icon_path.empty()) return SetXmlImage(*toast_xml, icon_path); return true; } bool WindowsToastNotification::SetXmlAudioSilent( IXmlDocument* doc) { ScopedHString tag(L"toast"); if (!tag.success()) return false; ComPtr<IXmlNodeList> node_list; if (FAILED(doc->GetElementsByTagName(tag, &node_list))) return false; ComPtr<IXmlNode> root; if (FAILED(node_list->Item(0, &root))) return false; ComPtr<IXmlElement> audio_element; ScopedHString audio_str(L"audio"); if (FAILED(doc->CreateElement(audio_str, &audio_element))) return false; ComPtr<IXmlNode> audio_node_tmp; if (FAILED(audio_element.As(&audio_node_tmp))) return false; // Append audio node to toast xml ComPtr<IXmlNode> audio_node; if (FAILED(root->AppendChild(audio_node_tmp.Get(), &audio_node))) return false; // Create silent attribute ComPtr<IXmlNamedNodeMap> attributes; if (FAILED(audio_node->get_Attributes(&attributes))) return false; ComPtr<IXmlAttribute> silent_attribute; ScopedHString silent_str(L"silent"); if (FAILED(doc->CreateAttribute(silent_str, &silent_attribute))) return false; ComPtr<IXmlNode> silent_attribute_node; if (FAILED(silent_attribute.As(&silent_attribute_node))) return false; // Set silent attribute to true ScopedHString silent_value(L"true"); if (!silent_value.success()) return false; ComPtr<IXmlText> silent_text; if (FAILED(doc->CreateTextNode(silent_value, &silent_text))) return false; ComPtr<IXmlNode> silent_node; if (FAILED(silent_text.As(&silent_node))) return false; ComPtr<IXmlNode> child_node; if (FAILED(silent_attribute_node->AppendChild(silent_node.Get(), &child_node))) return false; ComPtr<IXmlNode> silent_attribute_pnode; return SUCCEEDED(attributes.Get()->SetNamedItem(silent_attribute_node.Get(), &silent_attribute_pnode)); } bool WindowsToastNotification::SetXmlText( IXmlDocument* doc, const std::wstring& text) { ScopedHString tag; ComPtr<IXmlNodeList> node_list; if (!GetTextNodeList(&tag, doc, &node_list, 1)) return false; ComPtr<IXmlNode> node; if (FAILED(node_list->Item(0, &node))) return false; return AppendTextToXml(doc, node.Get(), text); } bool WindowsToastNotification::SetXmlText( IXmlDocument* doc, const std::wstring& title, const std::wstring& body) { ScopedHString tag; ComPtr<IXmlNodeList> node_list; if (!GetTextNodeList(&tag, doc, &node_list, 2)) return false; ComPtr<IXmlNode> node; if (FAILED(node_list->Item(0, &node))) return false; if (!AppendTextToXml(doc, node.Get(), title)) return false; if (FAILED(node_list->Item(1, &node))) return false; return AppendTextToXml(doc, node.Get(), body); } bool WindowsToastNotification::SetXmlImage( IXmlDocument* doc, const std::wstring& icon_path) { ScopedHString tag(L"image"); if (!tag.success()) return false; ComPtr<IXmlNodeList> node_list; if (FAILED(doc->GetElementsByTagName(tag, &node_list))) return false; ComPtr<IXmlNode> image_node; if (FAILED(node_list->Item(0, &image_node))) return false; ComPtr<IXmlNamedNodeMap> attrs; if (FAILED(image_node->get_Attributes(&attrs))) return false; ScopedHString src(L"src"); if (!src.success()) return false; ComPtr<IXmlNode> src_attr; if (FAILED(attrs->GetNamedItem(src, &src_attr))) return false; ScopedHString img_path(icon_path.c_str()); if (!img_path.success()) return false; ComPtr<IXmlText> src_text; if (FAILED(doc->CreateTextNode(img_path, &src_text))) return false; ComPtr<IXmlNode> src_node; if (FAILED(src_text.As(&src_node))) return false; ComPtr<IXmlNode> child_node; return SUCCEEDED(src_attr->AppendChild(src_node.Get(), &child_node)); } bool WindowsToastNotification::GetTextNodeList( ScopedHString* tag, IXmlDocument* doc, IXmlNodeList** node_list, uint32_t req_length) { tag->Reset(L"text"); if (!tag->success()) return false; if (FAILED(doc->GetElementsByTagName(*tag, node_list))) return false; uint32_t node_length; if (FAILED((*node_list)->get_Length(&node_length))) return false; return node_length >= req_length; } bool WindowsToastNotification::AppendTextToXml( IXmlDocument* doc, IXmlNode* node, const std::wstring& text) { ScopedHString str(text); if (!str.success()) return false; ComPtr<IXmlText> xml_text; if (FAILED(doc->CreateTextNode(str, &xml_text))) return false; ComPtr<IXmlNode> text_node; if (FAILED(xml_text.As(&text_node))) return false; ComPtr<IXmlNode> append_node; return SUCCEEDED(node->AppendChild(text_node.Get(), &append_node)); } bool WindowsToastNotification::SetupCallbacks( ABI::Windows::UI::Notifications::IToastNotification* toast) { event_handler_ = Make<ToastEventHandler>(this); if (FAILED(toast->add_Activated(event_handler_.Get(), &activated_token_))) return false; if (FAILED(toast->add_Dismissed(event_handler_.Get(), &dismissed_token_))) return false; return SUCCEEDED(toast->add_Failed(event_handler_.Get(), &failed_token_)); } bool WindowsToastNotification::RemoveCallbacks( ABI::Windows::UI::Notifications::IToastNotification* toast) { if (FAILED(toast->remove_Activated(activated_token_))) return false; if (FAILED(toast->remove_Dismissed(dismissed_token_))) return false; return SUCCEEDED(toast->remove_Failed(failed_token_)); } /* / Toast Event Handler */ ToastEventHandler::ToastEventHandler(Notification* notification) : notification_(notification->GetWeakPtr()) { } ToastEventHandler::~ToastEventHandler() { } IFACEMETHODIMP ToastEventHandler::Invoke( ABI::Windows::UI::Notifications::IToastNotification* sender, IInspectable* args) { notification_->NotificationClicked(); return S_OK; } IFACEMETHODIMP ToastEventHandler::Invoke( ABI::Windows::UI::Notifications::IToastNotification* sender, ABI::Windows::UI::Notifications::IToastDismissedEventArgs* e) { notification_->NotificationDismissed(); return S_OK; } IFACEMETHODIMP ToastEventHandler::Invoke( ABI::Windows::UI::Notifications::IToastNotification* sender, ABI::Windows::UI::Notifications::IToastFailedEventArgs* e) { notification_->NotificationFailed(); return S_OK; } } // namespace brightray <commit_msg>Delay notification events to next tick<commit_after>// Copyright (c) 2015 Felix Rieseberg <[email protected]> and Jason Poon <[email protected]>. All rights reserved. // Copyright (c) 2015 Ryan McShane <[email protected]> and Brandon Smith <[email protected]> // Thanks to both of those folks mentioned above who first thought up a bunch of this code // and released it as MIT to the world. #include "browser/win/windows_toast_notification.h" #include <shlobj.h> #include "base/strings/utf_string_conversions.h" #include "browser/notification_delegate.h" #include "browser/win/scoped_hstring.h" #include "browser/win/notification_presenter_win.h" #include "common/application_info.h" #include "content/public/browser/browser_thread.h" using namespace ABI::Windows::Data::Xml::Dom; namespace brightray { namespace { bool GetAppUserModelId(ScopedHString* app_id) { PWSTR current_app_id; if (SUCCEEDED(GetCurrentProcessExplicitAppUserModelID(&current_app_id))) { app_id->Reset(current_app_id); CoTaskMemFree(current_app_id); } else { app_id->Reset(base::UTF8ToUTF16(GetApplicationName())); } return app_id->success(); } } // namespace // static Notification* Notification::Create(NotificationDelegate* delegate, NotificationPresenter* presenter) { return new WindowsToastNotification(delegate, presenter); } // static ComPtr<ABI::Windows::UI::Notifications::IToastNotificationManagerStatics> WindowsToastNotification::toast_manager_; // static ComPtr<ABI::Windows::UI::Notifications::IToastNotifier> WindowsToastNotification::toast_notifier_; // static bool WindowsToastNotification::Initialize() { // Just initialize, don't care if it fails or already initialized. Windows::Foundation::Initialize(RO_INIT_MULTITHREADED); ScopedHString toast_manager_str( RuntimeClass_Windows_UI_Notifications_ToastNotificationManager); if (!toast_manager_str.success()) return false; if (FAILED(Windows::Foundation::GetActivationFactory(toast_manager_str, &toast_manager_))) return false; ScopedHString app_id; if (!GetAppUserModelId(&app_id)) return false; return SUCCEEDED( toast_manager_->CreateToastNotifierWithId(app_id, &toast_notifier_)); } WindowsToastNotification::WindowsToastNotification( NotificationDelegate* delegate, NotificationPresenter* presenter) : Notification(delegate, presenter) { } WindowsToastNotification::~WindowsToastNotification() { // Remove the notification on exit. if (toast_notification_) { RemoveCallbacks(toast_notification_.Get()); Dismiss(); } } void WindowsToastNotification::Show( const base::string16& title, const base::string16& msg, const std::string& tag, const GURL& icon_url, const SkBitmap& icon, const bool silent) { auto presenter_win = static_cast<NotificationPresenterWin*>(presenter()); std::wstring icon_path = presenter_win->SaveIconToFilesystem(icon, icon_url); ComPtr<IXmlDocument> toast_xml; if(FAILED(GetToastXml(toast_manager_.Get(), title, msg, icon_path, silent, &toast_xml))) { NotificationFailed(); return; } ScopedHString toast_str( RuntimeClass_Windows_UI_Notifications_ToastNotification); if (!toast_str.success()) { NotificationFailed(); return; } ComPtr<ABI::Windows::UI::Notifications::IToastNotificationFactory> toast_factory; if (FAILED(Windows::Foundation::GetActivationFactory(toast_str, &toast_factory))) { NotificationFailed(); return; } if (FAILED(toast_factory->CreateToastNotification(toast_xml.Get(), &toast_notification_))) { NotificationFailed(); return; } if (!SetupCallbacks(toast_notification_.Get())) { NotificationFailed(); return; } if (FAILED(toast_notifier_->Show(toast_notification_.Get()))) { NotificationFailed(); return; } delegate()->NotificationDisplayed(); } void WindowsToastNotification::Dismiss() { toast_notifier_->Hide(toast_notification_.Get()); } bool WindowsToastNotification::GetToastXml( ABI::Windows::UI::Notifications::IToastNotificationManagerStatics* toastManager, const std::wstring& title, const std::wstring& msg, const std::wstring& icon_path, const bool silent, IXmlDocument** toast_xml) { ABI::Windows::UI::Notifications::ToastTemplateType template_type; if (title.empty() || msg.empty()) { // Single line toast. template_type = icon_path.empty() ? ABI::Windows::UI::Notifications::ToastTemplateType_ToastText01 : ABI::Windows::UI::Notifications::ToastTemplateType_ToastImageAndText01; if (FAILED(toast_manager_->GetTemplateContent(template_type, toast_xml))) return false; if (!SetXmlText(*toast_xml, title.empty() ? msg : title)) return false; } else { // Title and body toast. template_type = icon_path.empty() ? ABI::Windows::UI::Notifications::ToastTemplateType_ToastText02 : ABI::Windows::UI::Notifications::ToastTemplateType_ToastImageAndText02; if (FAILED(toastManager->GetTemplateContent(template_type, toast_xml))) return false; if (!SetXmlText(*toast_xml, title, msg)) return false; } // Configure the toast's notification sound if (silent) { if (FAILED(SetXmlAudioSilent(*toast_xml))) return false; } // Configure the toast's image if (!icon_path.empty()) return SetXmlImage(*toast_xml, icon_path); return true; } bool WindowsToastNotification::SetXmlAudioSilent( IXmlDocument* doc) { ScopedHString tag(L"toast"); if (!tag.success()) return false; ComPtr<IXmlNodeList> node_list; if (FAILED(doc->GetElementsByTagName(tag, &node_list))) return false; ComPtr<IXmlNode> root; if (FAILED(node_list->Item(0, &root))) return false; ComPtr<IXmlElement> audio_element; ScopedHString audio_str(L"audio"); if (FAILED(doc->CreateElement(audio_str, &audio_element))) return false; ComPtr<IXmlNode> audio_node_tmp; if (FAILED(audio_element.As(&audio_node_tmp))) return false; // Append audio node to toast xml ComPtr<IXmlNode> audio_node; if (FAILED(root->AppendChild(audio_node_tmp.Get(), &audio_node))) return false; // Create silent attribute ComPtr<IXmlNamedNodeMap> attributes; if (FAILED(audio_node->get_Attributes(&attributes))) return false; ComPtr<IXmlAttribute> silent_attribute; ScopedHString silent_str(L"silent"); if (FAILED(doc->CreateAttribute(silent_str, &silent_attribute))) return false; ComPtr<IXmlNode> silent_attribute_node; if (FAILED(silent_attribute.As(&silent_attribute_node))) return false; // Set silent attribute to true ScopedHString silent_value(L"true"); if (!silent_value.success()) return false; ComPtr<IXmlText> silent_text; if (FAILED(doc->CreateTextNode(silent_value, &silent_text))) return false; ComPtr<IXmlNode> silent_node; if (FAILED(silent_text.As(&silent_node))) return false; ComPtr<IXmlNode> child_node; if (FAILED(silent_attribute_node->AppendChild(silent_node.Get(), &child_node))) return false; ComPtr<IXmlNode> silent_attribute_pnode; return SUCCEEDED(attributes.Get()->SetNamedItem(silent_attribute_node.Get(), &silent_attribute_pnode)); } bool WindowsToastNotification::SetXmlText( IXmlDocument* doc, const std::wstring& text) { ScopedHString tag; ComPtr<IXmlNodeList> node_list; if (!GetTextNodeList(&tag, doc, &node_list, 1)) return false; ComPtr<IXmlNode> node; if (FAILED(node_list->Item(0, &node))) return false; return AppendTextToXml(doc, node.Get(), text); } bool WindowsToastNotification::SetXmlText( IXmlDocument* doc, const std::wstring& title, const std::wstring& body) { ScopedHString tag; ComPtr<IXmlNodeList> node_list; if (!GetTextNodeList(&tag, doc, &node_list, 2)) return false; ComPtr<IXmlNode> node; if (FAILED(node_list->Item(0, &node))) return false; if (!AppendTextToXml(doc, node.Get(), title)) return false; if (FAILED(node_list->Item(1, &node))) return false; return AppendTextToXml(doc, node.Get(), body); } bool WindowsToastNotification::SetXmlImage( IXmlDocument* doc, const std::wstring& icon_path) { ScopedHString tag(L"image"); if (!tag.success()) return false; ComPtr<IXmlNodeList> node_list; if (FAILED(doc->GetElementsByTagName(tag, &node_list))) return false; ComPtr<IXmlNode> image_node; if (FAILED(node_list->Item(0, &image_node))) return false; ComPtr<IXmlNamedNodeMap> attrs; if (FAILED(image_node->get_Attributes(&attrs))) return false; ScopedHString src(L"src"); if (!src.success()) return false; ComPtr<IXmlNode> src_attr; if (FAILED(attrs->GetNamedItem(src, &src_attr))) return false; ScopedHString img_path(icon_path.c_str()); if (!img_path.success()) return false; ComPtr<IXmlText> src_text; if (FAILED(doc->CreateTextNode(img_path, &src_text))) return false; ComPtr<IXmlNode> src_node; if (FAILED(src_text.As(&src_node))) return false; ComPtr<IXmlNode> child_node; return SUCCEEDED(src_attr->AppendChild(src_node.Get(), &child_node)); } bool WindowsToastNotification::GetTextNodeList( ScopedHString* tag, IXmlDocument* doc, IXmlNodeList** node_list, uint32_t req_length) { tag->Reset(L"text"); if (!tag->success()) return false; if (FAILED(doc->GetElementsByTagName(*tag, node_list))) return false; uint32_t node_length; if (FAILED((*node_list)->get_Length(&node_length))) return false; return node_length >= req_length; } bool WindowsToastNotification::AppendTextToXml( IXmlDocument* doc, IXmlNode* node, const std::wstring& text) { ScopedHString str(text); if (!str.success()) return false; ComPtr<IXmlText> xml_text; if (FAILED(doc->CreateTextNode(str, &xml_text))) return false; ComPtr<IXmlNode> text_node; if (FAILED(xml_text.As(&text_node))) return false; ComPtr<IXmlNode> append_node; return SUCCEEDED(node->AppendChild(text_node.Get(), &append_node)); } bool WindowsToastNotification::SetupCallbacks( ABI::Windows::UI::Notifications::IToastNotification* toast) { event_handler_ = Make<ToastEventHandler>(this); if (FAILED(toast->add_Activated(event_handler_.Get(), &activated_token_))) return false; if (FAILED(toast->add_Dismissed(event_handler_.Get(), &dismissed_token_))) return false; return SUCCEEDED(toast->add_Failed(event_handler_.Get(), &failed_token_)); } bool WindowsToastNotification::RemoveCallbacks( ABI::Windows::UI::Notifications::IToastNotification* toast) { if (FAILED(toast->remove_Activated(activated_token_))) return false; if (FAILED(toast->remove_Dismissed(dismissed_token_))) return false; return SUCCEEDED(toast->remove_Failed(failed_token_)); } /* / Toast Event Handler */ ToastEventHandler::ToastEventHandler(Notification* notification) : notification_(notification->GetWeakPtr()) { } ToastEventHandler::~ToastEventHandler() { } IFACEMETHODIMP ToastEventHandler::Invoke( ABI::Windows::UI::Notifications::IToastNotification* sender, IInspectable* args) { content::BrowserThread::PostTask( content::BrowserThread::UI, FROM_HERE, base::Bind(&Notification::NotificationClicked, notification_)); return S_OK; } IFACEMETHODIMP ToastEventHandler::Invoke( ABI::Windows::UI::Notifications::IToastNotification* sender, ABI::Windows::UI::Notifications::IToastDismissedEventArgs* e) { content::BrowserThread::PostTask( content::BrowserThread::UI, FROM_HERE, base::Bind(&Notification::NotificationDismissed, notification_)); return S_OK; } IFACEMETHODIMP ToastEventHandler::Invoke( ABI::Windows::UI::Notifications::IToastNotification* sender, ABI::Windows::UI::Notifications::IToastFailedEventArgs* e) { content::BrowserThread::PostTask( content::BrowserThread::UI, FROM_HERE, base::Bind(&Notification::NotificationFailed, notification_)); return S_OK; } } // namespace brightray <|endoftext|>
<commit_before>/****************************************************************************** The MIT License(MIT) Embedded Template Library. Copyright(c) 2014 jwellbelove 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 <UnitTest++/UnitTest++.h> #include <iterator> #include <string> #include <vector> #include <cstdint> #include "../crc8_ccitt.h" #include "../crc16.h" #include "../crc16_ccitt.h" #include "../crc16_kermit.h" #include "../crc32.h" #include "../crc64_ecma.h" #include "../endian.h" namespace { SUITE(test_crc) { //************************************************************************* TEST(test_crc8_ccitt_constructor) { std::string data("123456789"); uint8_t crc = etl::crc8_ccitt<>(data.begin(), data.end()); CHECK_EQUAL(0xF4, int(crc)); } //************************************************************************* TEST(test_crc8_ccitt_add_values) { std::string data("123456789"); etl::crc8_ccitt<> crc_calculator; for (size_t i = 0; i < data.size(); ++i) { crc_calculator += data[i]; } uint8_t crc = crc_calculator; CHECK_EQUAL(0xF4, crc); } //************************************************************************* TEST(test_crc8_ccitt_add_range) { std::string data("123456789"); etl::crc8_ccitt<> crc_calculator; crc_calculator.add(data.begin(), data.end()); uint8_t crc = crc_calculator.value(); CHECK_EQUAL(0xF4, crc); } //************************************************************************* TEST(test_crc8_ccitt_add_range_endian) { std::vector<uint8_t> data1 = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08 }; std::vector<uint32_t> data2 = { 0x04030201, 0x08070605 }; std::vector<uint32_t> data3 = { 0x01020304, 0x05060708 }; uint8_t crc1 = etl::crc8_ccitt<etl::endian::little>(data1.begin(), data1.end()); uint8_t crc2 = etl::crc8_ccitt<etl::endian::little>(data2.begin(), data2.end()); CHECK_EQUAL(int(crc1), int(crc2)); uint8_t crc3 = etl::crc8_ccitt<etl::endian::big>(data3.begin(), data3.end()); CHECK_EQUAL(int(crc1), int(crc3)); } //************************************************************************* TEST(test_crc16) { std::string data("123456789"); uint16_t crc = etl::crc16<>(data.begin(), data.end()); CHECK_EQUAL(0xBB3D, crc); } //************************************************************************* TEST(test_crc16_add_values) { std::string data("123456789"); etl::crc16<> crc_calculator; for (size_t i = 0; i < data.size(); ++i) { crc_calculator += data[i]; } uint16_t crc = crc_calculator; CHECK_EQUAL(0xBB3D, crc); } //************************************************************************* TEST(test_crc16_add_range) { std::string data("123456789"); etl::crc16<> crc_calculator; crc_calculator.add(data.begin(), data.end()); uint16_t crc = crc_calculator.value(); CHECK_EQUAL(0xBB3D, crc); } //************************************************************************* TEST(test_crc16_add_range_endian) { std::vector<uint8_t> data1 = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08 }; std::vector<uint32_t> data2 = { 0x04030201, 0x08070605 }; std::vector<uint32_t> data3 = { 0x01020304, 0x05060708 }; uint16_t crc1 = etl::crc16<etl::endian::little>(data1.begin(), data1.end()); uint16_t crc2 = etl::crc16<etl::endian::little>(data2.begin(), data2.end()); CHECK_EQUAL(crc1, crc2); uint16_t crc3 = etl::crc16<etl::endian::big>(data3.begin(), data3.end()); CHECK_EQUAL(crc1, crc3); } //************************************************************************* TEST(test_crc16_ccitt) { std::string data("123456789"); uint16_t crc = etl::crc16_ccitt<>(data.begin(), data.end()); CHECK_EQUAL(0x29B1, crc); } //************************************************************************* TEST(test_crc16_ccitt_add_values) { std::string data("123456789"); etl::crc16_ccitt<> crc_calculator; for (size_t i = 0; i < data.size(); ++i) { crc_calculator += data[i]; } uint16_t crc = crc_calculator; CHECK_EQUAL(0x29B1, crc); } //************************************************************************* TEST(test_crc16_ccitt_add_range) { std::string data("123456789"); etl::crc16_ccitt<> crc_calculator; crc_calculator.add(data.begin(), data.end()); uint16_t crc = crc_calculator.value(); CHECK_EQUAL(0x29B1, crc); } //************************************************************************* TEST(test_crc16_ccitt_add_range_endian) { std::vector<uint8_t> data1 = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08 }; std::vector<uint32_t> data2 = { 0x04030201, 0x08070605 }; std::vector<uint32_t> data3 = { 0x01020304, 0x05060708 }; uint16_t crc1 = etl::crc16_ccitt<etl::endian::little>(data1.begin(), data1.end()); uint16_t crc2 = etl::crc16_ccitt<etl::endian::little>(data2.begin(), data2.end()); CHECK_EQUAL(crc1, crc2); uint16_t crc3 = etl::crc16_ccitt<etl::endian::big>(data3.begin(), data3.end()); CHECK_EQUAL(crc1, crc3); } //************************************************************************* TEST(test_crc16_kermit) { std::string data("123456789"); uint16_t crc = etl::crc16_kermit<>(data.begin(), data.end()); CHECK_EQUAL(0x2189, crc); } //************************************************************************* TEST(test_crc16_kermit_add_values) { std::string data("123456789"); etl::crc16_kermit<> crc_calculator; for (size_t i = 0; i < data.size(); ++i) { crc_calculator += data[i]; } uint16_t crc = crc_calculator; CHECK_EQUAL(0x2189, crc); } //************************************************************************* TEST(test_crc16_kermit_add_range) { std::string data("123456789"); etl::crc16_kermit<> crc_calculator; crc_calculator.add(data.begin(), data.end()); uint16_t crc = crc_calculator.value(); CHECK_EQUAL(0x2189, crc); } //************************************************************************* TEST(test_crc16_kermit_add_range_endian) { std::vector<uint8_t> data1 = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08 }; std::vector<uint32_t> data2 = { 0x04030201, 0x08070605 }; std::vector<uint32_t> data3 = { 0x01020304, 0x05060708 }; uint16_t crc1 = etl::crc16_kermit<etl::endian::little>(data1.begin(), data1.end()); uint16_t crc2 = etl::crc16_kermit<etl::endian::little>(data2.begin(), data2.end()); CHECK_EQUAL(crc1, crc2); uint16_t crc3 = etl::crc16_kermit<etl::endian::big>(data3.begin(), data3.end()); CHECK_EQUAL(crc1, crc3); } //************************************************************************* TEST(test_crc32) { std::string data("123456789"); uint32_t crc = etl::crc32<>(data.begin(), data.end()); CHECK_EQUAL(0xCBF43926, crc); } //************************************************************************* TEST(test_crc32_add_values) { std::string data("123456789"); etl::crc32<> crc_calculator; for (size_t i = 0; i < data.size(); ++i) { crc_calculator += data[i]; } uint32_t crc = crc_calculator; CHECK_EQUAL(0xCBF43926, crc); } //************************************************************************* TEST(test_crc32_add_range) { std::string data("123456789"); etl::crc32<> crc_calculator; crc_calculator.add(data.begin(), data.end()); uint32_t crc = crc_calculator.value(); CHECK_EQUAL(0xCBF43926, crc); } //************************************************************************* TEST(test_crc32_add_range_endian) { std::vector<uint8_t> data1 = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08 }; std::vector<uint32_t> data2 = { 0x04030201, 0x08070605 }; std::vector<uint32_t> data3 = { 0x01020304, 0x05060708 }; uint32_t crc1 = etl::crc32<etl::endian::little>(data1.begin(), data1.end()); uint32_t crc2 = etl::crc32<etl::endian::little>(data2.begin(), data2.end()); CHECK_EQUAL(crc1, crc2); uint32_t crc3 = etl::crc32<etl::endian::big>(data3.begin(), data3.end()); CHECK_EQUAL(crc1, crc3); } //************************************************************************* TEST(test_crc64_ecma) { std::string data("123456789"); uint64_t crc = etl::crc64_ecma<>(data.begin(), data.end()); CHECK_EQUAL(0x6C40DF5F0B497347, crc); } //************************************************************************* TEST(test_crc64_ecma_add_values) { std::string data("123456789"); etl::crc64_ecma<> crc_calculator; for (size_t i = 0; i < data.size(); ++i) { crc_calculator += data[i]; } uint64_t crc = crc_calculator; CHECK_EQUAL(0x6C40DF5F0B497347, crc); } //************************************************************************* TEST(test_crc64_ecma_add_range) { std::string data("123456789"); etl::crc64_ecma<> crc_calculator; crc_calculator.add(data.begin(), data.end()); uint64_t crc = crc_calculator.value(); CHECK_EQUAL(0x6C40DF5F0B497347, crc); } //************************************************************************* TEST(test_crc64_ecma_add_range_endian) { std::vector<uint8_t> data1 = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08 }; std::vector<uint32_t> data2 = { 0x04030201, 0x08070605 }; std::vector<uint32_t> data3 = { 0x01020304, 0x05060708 }; uint64_t crc1 = etl::crc64_ecma<etl::endian::little>(data1.begin(), data1.end()); uint64_t crc2 = etl::crc64_ecma<etl::endian::little>(data2.begin(), data2.end()); CHECK_EQUAL(crc1, crc2); uint64_t crc3 = etl::crc64_ecma<etl::endian::big>(data3.begin(), data3.end()); CHECK_EQUAL(crc1, crc3); } }; } <commit_msg>Changed to stddef.h<commit_after>/****************************************************************************** The MIT License(MIT) Embedded Template Library. Copyright(c) 2014 jwellbelove 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 <UnitTest++/UnitTest++.h> #include <iterator> #include <string> #include <vector> #include <stdint.h> #include "../crc8_ccitt.h" #include "../crc16.h" #include "../crc16_ccitt.h" #include "../crc16_kermit.h" #include "../crc32.h" #include "../crc64_ecma.h" #include "../endian.h" namespace { SUITE(test_crc) { //************************************************************************* TEST(test_crc8_ccitt_constructor) { std::string data("123456789"); uint8_t crc = etl::crc8_ccitt<>(data.begin(), data.end()); CHECK_EQUAL(0xF4, int(crc)); } //************************************************************************* TEST(test_crc8_ccitt_add_values) { std::string data("123456789"); etl::crc8_ccitt<> crc_calculator; for (size_t i = 0; i < data.size(); ++i) { crc_calculator += data[i]; } uint8_t crc = crc_calculator; CHECK_EQUAL(0xF4, crc); } //************************************************************************* TEST(test_crc8_ccitt_add_range) { std::string data("123456789"); etl::crc8_ccitt<> crc_calculator; crc_calculator.add(data.begin(), data.end()); uint8_t crc = crc_calculator.value(); CHECK_EQUAL(0xF4, crc); } //************************************************************************* TEST(test_crc8_ccitt_add_range_endian) { std::vector<uint8_t> data1 = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08 }; std::vector<uint32_t> data2 = { 0x04030201, 0x08070605 }; std::vector<uint32_t> data3 = { 0x01020304, 0x05060708 }; uint8_t crc1 = etl::crc8_ccitt<etl::endian::little>(data1.begin(), data1.end()); uint8_t crc2 = etl::crc8_ccitt<etl::endian::little>(data2.begin(), data2.end()); CHECK_EQUAL(int(crc1), int(crc2)); uint8_t crc3 = etl::crc8_ccitt<etl::endian::big>(data3.begin(), data3.end()); CHECK_EQUAL(int(crc1), int(crc3)); } //************************************************************************* TEST(test_crc16) { std::string data("123456789"); uint16_t crc = etl::crc16<>(data.begin(), data.end()); CHECK_EQUAL(0xBB3D, crc); } //************************************************************************* TEST(test_crc16_add_values) { std::string data("123456789"); etl::crc16<> crc_calculator; for (size_t i = 0; i < data.size(); ++i) { crc_calculator += data[i]; } uint16_t crc = crc_calculator; CHECK_EQUAL(0xBB3D, crc); } //************************************************************************* TEST(test_crc16_add_range) { std::string data("123456789"); etl::crc16<> crc_calculator; crc_calculator.add(data.begin(), data.end()); uint16_t crc = crc_calculator.value(); CHECK_EQUAL(0xBB3D, crc); } //************************************************************************* TEST(test_crc16_add_range_endian) { std::vector<uint8_t> data1 = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08 }; std::vector<uint32_t> data2 = { 0x04030201, 0x08070605 }; std::vector<uint32_t> data3 = { 0x01020304, 0x05060708 }; uint16_t crc1 = etl::crc16<etl::endian::little>(data1.begin(), data1.end()); uint16_t crc2 = etl::crc16<etl::endian::little>(data2.begin(), data2.end()); CHECK_EQUAL(crc1, crc2); uint16_t crc3 = etl::crc16<etl::endian::big>(data3.begin(), data3.end()); CHECK_EQUAL(crc1, crc3); } //************************************************************************* TEST(test_crc16_ccitt) { std::string data("123456789"); uint16_t crc = etl::crc16_ccitt<>(data.begin(), data.end()); CHECK_EQUAL(0x29B1, crc); } //************************************************************************* TEST(test_crc16_ccitt_add_values) { std::string data("123456789"); etl::crc16_ccitt<> crc_calculator; for (size_t i = 0; i < data.size(); ++i) { crc_calculator += data[i]; } uint16_t crc = crc_calculator; CHECK_EQUAL(0x29B1, crc); } //************************************************************************* TEST(test_crc16_ccitt_add_range) { std::string data("123456789"); etl::crc16_ccitt<> crc_calculator; crc_calculator.add(data.begin(), data.end()); uint16_t crc = crc_calculator.value(); CHECK_EQUAL(0x29B1, crc); } //************************************************************************* TEST(test_crc16_ccitt_add_range_endian) { std::vector<uint8_t> data1 = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08 }; std::vector<uint32_t> data2 = { 0x04030201, 0x08070605 }; std::vector<uint32_t> data3 = { 0x01020304, 0x05060708 }; uint16_t crc1 = etl::crc16_ccitt<etl::endian::little>(data1.begin(), data1.end()); uint16_t crc2 = etl::crc16_ccitt<etl::endian::little>(data2.begin(), data2.end()); CHECK_EQUAL(crc1, crc2); uint16_t crc3 = etl::crc16_ccitt<etl::endian::big>(data3.begin(), data3.end()); CHECK_EQUAL(crc1, crc3); } //************************************************************************* TEST(test_crc16_kermit) { std::string data("123456789"); uint16_t crc = etl::crc16_kermit<>(data.begin(), data.end()); CHECK_EQUAL(0x2189, crc); } //************************************************************************* TEST(test_crc16_kermit_add_values) { std::string data("123456789"); etl::crc16_kermit<> crc_calculator; for (size_t i = 0; i < data.size(); ++i) { crc_calculator += data[i]; } uint16_t crc = crc_calculator; CHECK_EQUAL(0x2189, crc); } //************************************************************************* TEST(test_crc16_kermit_add_range) { std::string data("123456789"); etl::crc16_kermit<> crc_calculator; crc_calculator.add(data.begin(), data.end()); uint16_t crc = crc_calculator.value(); CHECK_EQUAL(0x2189, crc); } //************************************************************************* TEST(test_crc16_kermit_add_range_endian) { std::vector<uint8_t> data1 = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08 }; std::vector<uint32_t> data2 = { 0x04030201, 0x08070605 }; std::vector<uint32_t> data3 = { 0x01020304, 0x05060708 }; uint16_t crc1 = etl::crc16_kermit<etl::endian::little>(data1.begin(), data1.end()); uint16_t crc2 = etl::crc16_kermit<etl::endian::little>(data2.begin(), data2.end()); CHECK_EQUAL(crc1, crc2); uint16_t crc3 = etl::crc16_kermit<etl::endian::big>(data3.begin(), data3.end()); CHECK_EQUAL(crc1, crc3); } //************************************************************************* TEST(test_crc32) { std::string data("123456789"); uint32_t crc = etl::crc32<>(data.begin(), data.end()); CHECK_EQUAL(0xCBF43926, crc); } //************************************************************************* TEST(test_crc32_add_values) { std::string data("123456789"); etl::crc32<> crc_calculator; for (size_t i = 0; i < data.size(); ++i) { crc_calculator += data[i]; } uint32_t crc = crc_calculator; CHECK_EQUAL(0xCBF43926, crc); } //************************************************************************* TEST(test_crc32_add_range) { std::string data("123456789"); etl::crc32<> crc_calculator; crc_calculator.add(data.begin(), data.end()); uint32_t crc = crc_calculator.value(); CHECK_EQUAL(0xCBF43926, crc); } //************************************************************************* TEST(test_crc32_add_range_endian) { std::vector<uint8_t> data1 = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08 }; std::vector<uint32_t> data2 = { 0x04030201, 0x08070605 }; std::vector<uint32_t> data3 = { 0x01020304, 0x05060708 }; uint32_t crc1 = etl::crc32<etl::endian::little>(data1.begin(), data1.end()); uint32_t crc2 = etl::crc32<etl::endian::little>(data2.begin(), data2.end()); CHECK_EQUAL(crc1, crc2); uint32_t crc3 = etl::crc32<etl::endian::big>(data3.begin(), data3.end()); CHECK_EQUAL(crc1, crc3); } //************************************************************************* TEST(test_crc64_ecma) { std::string data("123456789"); uint64_t crc = etl::crc64_ecma<>(data.begin(), data.end()); CHECK_EQUAL(0x6C40DF5F0B497347, crc); } //************************************************************************* TEST(test_crc64_ecma_add_values) { std::string data("123456789"); etl::crc64_ecma<> crc_calculator; for (size_t i = 0; i < data.size(); ++i) { crc_calculator += data[i]; } uint64_t crc = crc_calculator; CHECK_EQUAL(0x6C40DF5F0B497347, crc); } //************************************************************************* TEST(test_crc64_ecma_add_range) { std::string data("123456789"); etl::crc64_ecma<> crc_calculator; crc_calculator.add(data.begin(), data.end()); uint64_t crc = crc_calculator.value(); CHECK_EQUAL(0x6C40DF5F0B497347, crc); } //************************************************************************* TEST(test_crc64_ecma_add_range_endian) { std::vector<uint8_t> data1 = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08 }; std::vector<uint32_t> data2 = { 0x04030201, 0x08070605 }; std::vector<uint32_t> data3 = { 0x01020304, 0x05060708 }; uint64_t crc1 = etl::crc64_ecma<etl::endian::little>(data1.begin(), data1.end()); uint64_t crc2 = etl::crc64_ecma<etl::endian::little>(data2.begin(), data2.end()); CHECK_EQUAL(crc1, crc2); uint64_t crc3 = etl::crc64_ecma<etl::endian::big>(data3.begin(), data3.end()); CHECK_EQUAL(crc1, crc3); } }; } <|endoftext|>
<commit_before>#include "BenchmarkStack.h" #include "StackAllocator.h" BenchmarkStack::BenchmarkStack(const int runtime) : Benchmark(runtime) { } BenchmarkResults BenchmarkStack::allocation() { setStartTimer(); StackAllocator stackAllocator(1e10); int operations = 0; while(!outOfTime()){ stackAllocator.Allocate(sizeof(int), alignof(int)); // 4 -> 4 stackAllocator.Allocate(sizeof(bool), alignof(bool)); // 1 -> 5 // 3 -> 8 stackAllocator.Allocate(sizeof(foo), alignof(foo)); // 16 -> 24 ++operations; } BenchmarkResults results = buildResults(operations, m_runtime, 0, 0); printResults(results); stackAllocator.Reset(); return results; } BenchmarkResults BenchmarkStack::freeing() { return buildResults(0, 0, 0, 0); } BenchmarkResults BenchmarkStack::read() { return buildResults(0, 0, 0, 0); } BenchmarkResults BenchmarkStack::write() { return buildResults(0, 0, 0, 0); } BenchmarkResults BenchmarkStack::all() { return buildResults(0, 0, 0, 0); }<commit_msg>Added freeing benchmark<commit_after>#include "BenchmarkStack.h" #include "StackAllocator.h" BenchmarkStack::BenchmarkStack(const int runtime) : Benchmark(runtime) { } BenchmarkResults BenchmarkStack::allocation() { setStartTimer(); StackAllocator stackAllocator(1e10); int operations = 0; while(!outOfTime()){ stackAllocator.Allocate(sizeof(int), alignof(int)); // 4 -> 4 stackAllocator.Allocate(sizeof(bool), alignof(bool)); // 1 -> 5 // 3 -> 8 stackAllocator.Allocate(sizeof(foo), alignof(foo)); // 16 -> 24 ++operations; } BenchmarkResults results = buildResults(operations, m_runtime, 0, 0); printResults(results); stackAllocator.Reset(); return results; } BenchmarkResults BenchmarkStack::freeing() { setStartTimer(); StackAllocator stackAllocator(1e10); std::size_t operations = 0; double elapsedTime = 0; while(elapsedTime < (m_runtime * 1e3)){ if (operations % 2 == 0){ stackAllocator.Allocate(sizeof(int), alignof(int)); // 4 -> 4 stackAllocator.Allocate(sizeof(bool), alignof(bool)); // 1 -> 5 // 3 -> 8 stackAllocator.Allocate(sizeof(foo), alignof(foo)); // 16 -> 24 }else { timespec before_free, after_free; setTimer(before_free); stackAllocator.Free(sizeof(foo)); stackAllocator.Free(sizeof(bool)); stackAllocator.Free(sizeof(int)); setTimer(after_free); elapsedTime += calculateElapsedTime(before_free, after_free); } ++operations; } BenchmarkResults results = buildResults(operations/2, m_runtime, 0, 0); printResults(results); stackAllocator.Reset(); return results;} BenchmarkResults BenchmarkStack::read() { return buildResults(0, 0, 0, 0); } BenchmarkResults BenchmarkStack::write() { return buildResults(0, 0, 0, 0); } BenchmarkResults BenchmarkStack::all() { return buildResults(0, 0, 0, 0); }<|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: AsynchronousTask.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: kz $ $Date: 2006-04-26 20:46:22 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef SD_ASYNCHRONOUS_TASK_HXX #define SD_ASYNCHRONOUS_TASK_HXX namespace sd { namespace tools { /** Interface for the asynchronous execution of a task. This interface allows an controller to run the task either timer based with a fixed amount of time between the steps or thread based one step right after the other. */ class AsynchronousTask { public: /** Run the next step of the task. After HasNextStep() returns false this method should ignore further calls. */ virtual void RunNextStep (void) = 0; /** Return <TRUE/> when there is at least one more step to execute. When the task has been executed completely then <FALSE/> is returned. */ virtual bool HasNextStep (void) = 0; }; } } // end of namespace ::sd::tools #endif <commit_msg>INTEGRATION: CWS changefileheader (1.2.452); FILE MERGED 2008/03/31 13:58:41 rt 1.2.452.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: AsynchronousTask.hxx,v $ * $Revision: 1.3 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef SD_ASYNCHRONOUS_TASK_HXX #define SD_ASYNCHRONOUS_TASK_HXX namespace sd { namespace tools { /** Interface for the asynchronous execution of a task. This interface allows an controller to run the task either timer based with a fixed amount of time between the steps or thread based one step right after the other. */ class AsynchronousTask { public: /** Run the next step of the task. After HasNextStep() returns false this method should ignore further calls. */ virtual void RunNextStep (void) = 0; /** Return <TRUE/> when there is at least one more step to execute. When the task has been executed completely then <FALSE/> is returned. */ virtual bool HasNextStep (void) = 0; }; } } // end of namespace ::sd::tools #endif <|endoftext|>
<commit_before>// Copyright (c) 2010 The Native Client 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 "ppapi/proxy/plugin_file_ref.h" #include "native_client/src/include/portability.h" #include "ppapi/proxy/plugin_globals.h" namespace ppapi_proxy { namespace { PP_Resource Create(PP_Resource file_system, const char* path) { UNREFERENCED_PARAMETER(file_system); UNREFERENCED_PARAMETER(path); return kInvalidResourceId; } PP_Resource CreateTemporaryFileRef(PP_Instance instance, const char* path) { UNREFERENCED_PARAMETER(instance); UNREFERENCED_PARAMETER(path); return kInvalidResourceId; } bool IsFileRef(PP_Resource resource) { UNREFERENCED_PARAMETER(resource); return false; } PP_FileSystemType_Dev GetFileSystemType(PP_Resource file_ref) { UNREFERENCED_PARAMETER(file_ref); return PP_FILESYSTEMTYPE_EXTERNAL; } PP_Var GetName(PP_Resource file_ref) { UNREFERENCED_PARAMETER(file_ref); return PP_MakeUndefined(); } PP_Var GetPath(PP_Resource file_ref) { UNREFERENCED_PARAMETER(file_ref); return PP_MakeUndefined(); } PP_Resource GetParent(PP_Resource file_ref) { UNREFERENCED_PARAMETER(file_ref); return kInvalidResourceId; } } // namespace const PPB_FileRef_Dev* PluginFileRef::GetInterface() { static const PPB_FileRef_Dev intf = { Create, IsFileRef, GetFileSystemType, GetName, GetPath, GetParent }; return &intf; } } // namespace ppapi_proxy <commit_msg>Remove an unused function I forgot to remove. Clang complains about it...<commit_after>// Copyright (c) 2010 The Native Client 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 "ppapi/proxy/plugin_file_ref.h" #include "native_client/src/include/portability.h" #include "ppapi/proxy/plugin_globals.h" namespace ppapi_proxy { namespace { PP_Resource Create(PP_Resource file_system, const char* path) { UNREFERENCED_PARAMETER(file_system); UNREFERENCED_PARAMETER(path); return kInvalidResourceId; } bool IsFileRef(PP_Resource resource) { UNREFERENCED_PARAMETER(resource); return false; } PP_FileSystemType_Dev GetFileSystemType(PP_Resource file_ref) { UNREFERENCED_PARAMETER(file_ref); return PP_FILESYSTEMTYPE_EXTERNAL; } PP_Var GetName(PP_Resource file_ref) { UNREFERENCED_PARAMETER(file_ref); return PP_MakeUndefined(); } PP_Var GetPath(PP_Resource file_ref) { UNREFERENCED_PARAMETER(file_ref); return PP_MakeUndefined(); } PP_Resource GetParent(PP_Resource file_ref) { UNREFERENCED_PARAMETER(file_ref); return kInvalidResourceId; } } // namespace const PPB_FileRef_Dev* PluginFileRef::GetInterface() { static const PPB_FileRef_Dev intf = { Create, IsFileRef, GetFileSystemType, GetName, GetPath, GetParent }; return &intf; } } // namespace ppapi_proxy <|endoftext|>
<commit_before>/* Copyright (c) 2012, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "libtorrent/config.hpp" #include "libtorrent/rss.hpp" #include "libtorrent/fingerprint.hpp" #include "libtorrent/aux_/session_impl.hpp" #include "libtorrent/http_parser.hpp" #include "test.hpp" using namespace libtorrent; void print_feed(feed_status const& f) { fprintf(stderr, "FEED: %s\n",f.url.c_str()); if (f.error) fprintf(stderr, "ERROR: %s\n", f.error.message().c_str()); fprintf(stderr, " %s\n %s\n", f.title.c_str(), f.description.c_str()); fprintf(stderr, " ttl: %d minutes\n", f.ttl); fprintf(stderr, " num items: %d\n", int(f.items.size())); for (std::vector<feed_item>::const_iterator i = f.items.begin() , end(f.items.end()); i != end; ++i) { fprintf(stderr, "\033[32m%s\033[0m\n------------------------------------------------------\n" " url: %s\n size: %"PRId64"\n info-hash: %s\n uuid: %s\n description: %s\n" " comment: %s\n category: %s\n" , i->title.c_str(), i->url.c_str(), i->size , i->info_hash.is_all_zeros() ? "" : to_hex(i->info_hash.to_string()).c_str() , i->uuid.c_str(), i->description.c_str(), i->comment.c_str(), i->category.c_str()); } } struct rss_expect { rss_expect(int nitems, std::string url, std::string title, size_type size) : num_items(nitems), first_url(url), first_title(title), first_size(size) {} int num_items; std::string first_url; std::string first_title; size_type first_size; }; void test_feed(std::string const& filename, rss_expect const& expect) { std::vector<char> buffer; error_code ec; load_file(filename, buffer, ec); if (ec) { fprintf(stderr, "failed to load file \"%s\": %s\n", filename.c_str(), ec.message().c_str()); } TEST_CHECK(!ec); char* buf = buffer.size() ? &buffer[0] : NULL; int len = buffer.size(); char const header[] = "HTTP/1.1 200 OK\r\n" "\r\n"; boost::shared_ptr<aux::session_impl> s = boost::shared_ptr<aux::session_impl>(new aux::session_impl( std::make_pair(100, 200), fingerprint("TT", 0, 0, 0 ,0), NULL, 0)); s->start_session(); feed_settings sett; sett.auto_download = false; sett.auto_map_handles = false; boost::shared_ptr<feed> f = boost::shared_ptr<feed>(new feed(*s, sett)); http_parser parser; bool err = false; parser.incoming(buffer::const_interval(header, header + sizeof(header)-1), err); TEST_CHECK(err == false); f->on_feed(error_code(), parser, buf, len); feed_status st; f->get_feed_status(&st); TEST_CHECK(!st.error); print_feed(st); TEST_CHECK(st.items.size() == expect.num_items); if (st.items.size() > 0) { TEST_CHECK(st.items[0].url == expect.first_url); TEST_CHECK(st.items[0].size == expect.first_size); TEST_CHECK(st.items[0].title == expect.first_title); } entry state; f->save_state(state); fprintf(stderr, "feed_state:\n"); #ifdef TORRENT_DEBUG state.print(std::cerr); #endif // TODO: verify some key state is saved in 'state' } int test_main() { test_feed(combine_path("..", "eztv.xml"), rss_expect(30, "http://torrent.zoink.it/The.Daily.Show.2012.02.16.(HDTV-LMAO)[VTV].torrent", "The Daily Show 2012-02-16 [HDTV - LMAO]", 183442338)); test_feed(combine_path("..", "cb.xml"), rss_expect(50, "http://www.clearbits.net/get/1911-norbergfestival-2011.torrent", "Norbergfestival 2011", 1160773632)); test_feed(combine_path("..", "kat.xml"), rss_expect(25, "http://kat.ph/torrents/benito-di-paula-1975-benito-di-paula-lp-rip-ogg-at-500-jarax4u-t6194897/", "Benito Di Paula - 1975 - Benito Di Paula (LP Rip OGG at 500) [jarax4u]", 168773863)); test_feed(combine_path("..", "mn.xml"), rss_expect(20, "http://www.mininova.org/get/13203100", "Dexcell - January TwentyTwelve Mix", 137311179)); test_feed(combine_path("..", "pb.xml"), rss_expect(60, "magnet:?xt=urn:btih:FD4CDDB7BBE722D17A018EFD875EB0695ED7159C&dn=Thompson+Twins+-+1989+-+Big+Trash+%5BMP3%5D", "Thompson Twins - 1989 - Big Trash [MP3]", 100160904)); return 0; } <commit_msg>fix test_rss for windows<commit_after>/* Copyright (c) 2012, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "libtorrent/config.hpp" #include "libtorrent/rss.hpp" #include "libtorrent/fingerprint.hpp" #include "libtorrent/aux_/session_impl.hpp" #include "libtorrent/http_parser.hpp" #include "test.hpp" using namespace libtorrent; void print_feed(feed_status const& f) { fprintf(stderr, "FEED: %s\n",f.url.c_str()); if (f.error) fprintf(stderr, "ERROR: %s\n", f.error.message().c_str()); fprintf(stderr, " %s\n %s\n", f.title.c_str(), f.description.c_str()); fprintf(stderr, " ttl: %d minutes\n", f.ttl); fprintf(stderr, " num items: %d\n", int(f.items.size())); for (std::vector<feed_item>::const_iterator i = f.items.begin() , end(f.items.end()); i != end; ++i) { fprintf(stderr, "\033[32m%s\033[0m\n------------------------------------------------------\n" " url: %s\n size: %"PRId64"\n info-hash: %s\n uuid: %s\n description: %s\n" " comment: %s\n category: %s\n" , i->title.c_str(), i->url.c_str(), i->size , i->info_hash.is_all_zeros() ? "" : to_hex(i->info_hash.to_string()).c_str() , i->uuid.c_str(), i->description.c_str(), i->comment.c_str(), i->category.c_str()); } } struct rss_expect { rss_expect(int nitems, std::string url, std::string title, size_type size) : num_items(nitems), first_url(url), first_title(title), first_size(size) {} int num_items; std::string first_url; std::string first_title; size_type first_size; }; void test_feed(std::string const& filename, rss_expect const& expect) { std::vector<char> buffer; error_code ec; load_file(filename, buffer, ec); if (ec) { fprintf(stderr, "failed to load file \"%s\": %s\n", filename.c_str(), ec.message().c_str()); } TEST_CHECK(!ec); char* buf = buffer.size() ? &buffer[0] : NULL; int len = buffer.size(); char const header[] = "HTTP/1.1 200 OK\r\n" "\r\n"; boost::shared_ptr<aux::session_impl> s = boost::shared_ptr<aux::session_impl>(new aux::session_impl( std::make_pair(100, 200), fingerprint("TT", 0, 0, 0 ,0), NULL, 0)); s->start_session(); feed_settings sett; sett.auto_download = false; sett.auto_map_handles = false; boost::shared_ptr<feed> f = boost::shared_ptr<feed>(new feed(*s, sett)); http_parser parser; bool err = false; parser.incoming(buffer::const_interval(header, header + sizeof(header)-1), err); TEST_CHECK(err == false); f->on_feed(error_code(), parser, buf, len); feed_status st; f->get_feed_status(&st); TEST_CHECK(!st.error); print_feed(st); TEST_CHECK(st.items.size() == expect.num_items); if (st.items.size() > 0) { TEST_CHECK(st.items[0].url == expect.first_url); TEST_CHECK(st.items[0].size == expect.first_size); TEST_CHECK(st.items[0].title == expect.first_title); } entry state; f->save_state(state); fprintf(stderr, "feed_state:\n"); #ifdef TORRENT_DEBUG state.print(std::cerr); #endif // TODO: verify some key state is saved in 'state' } int test_main() { std::string root_dir = parent_path(current_working_directory()); test_feed(combine_path(root_dir, "eztv.xml"), rss_expect(30, "http://torrent.zoink.it/The.Daily.Show.2012.02.16.(HDTV-LMAO)[VTV].torrent", "The Daily Show 2012-02-16 [HDTV - LMAO]", 183442338)); test_feed(combine_path(root_dir, "cb.xml"), rss_expect(50, "http://www.clearbits.net/get/1911-norbergfestival-2011.torrent", "Norbergfestival 2011", 1160773632)); test_feed(combine_path(root_dir, "kat.xml"), rss_expect(25, "http://kat.ph/torrents/benito-di-paula-1975-benito-di-paula-lp-rip-ogg-at-500-jarax4u-t6194897/", "Benito Di Paula - 1975 - Benito Di Paula (LP Rip OGG at 500) [jarax4u]", 168773863)); test_feed(combine_path(root_dir, "mn.xml"), rss_expect(20, "http://www.mininova.org/get/13203100", "Dexcell - January TwentyTwelve Mix", 137311179)); test_feed(combine_path(root_dir, "pb.xml"), rss_expect(60, "magnet:?xt=urn:btih:FD4CDDB7BBE722D17A018EFD875EB0695ED7159C&dn=Thompson+Twins+-+1989+-+Big+Trash+%5BMP3%5D", "Thompson Twins - 1989 - Big Trash [MP3]", 100160904)); return 0; } <|endoftext|>
<commit_before>#ifndef DISSENT_CRYPTO_INTEGER_H_GUARD #define DISSENT_CRYPTO_INTEGER_H_GUARD #include <QByteArray> #include <QSharedData> #include <QString> #include "Utils/Utils.hpp" namespace Dissent { namespace Crypto { class IIntegerImpl : public QSharedData { public: virtual ~IIntegerImpl() {} virtual QByteArray GetByteArray() const = 0; virtual bool IsPrime() const = 0; virtual IIntegerImpl *Add(const IIntegerImpl * const term) const = 0; virtual IIntegerImpl *Subtract(const IIntegerImpl * const subtrahend) const = 0; virtual IIntegerImpl *Multiply(const IIntegerImpl * const multiplicand) const = 0; virtual IIntegerImpl *Multiply(const IIntegerImpl * const multiplicand, const IIntegerImpl * const modulus) const = 0; virtual IIntegerImpl *Divide(const IIntegerImpl * const divisor) const = 0; virtual IIntegerImpl *Modulo(const IIntegerImpl * const mod) const = 0; virtual IIntegerImpl *Pow(const IIntegerImpl * const pow, const IIntegerImpl * const mod) const = 0; virtual IIntegerImpl *PowCascade(const IIntegerImpl * const x0, const IIntegerImpl * const e0, const IIntegerImpl * const x1, const IIntegerImpl * const e1) const = 0; virtual IIntegerImpl *Inverse(const IIntegerImpl * const mod) const = 0; virtual bool Equals(const IIntegerImpl * const other) const = 0; virtual bool LessThan(const IIntegerImpl * const other) const = 0; virtual bool LessThanOrEqual(const IIntegerImpl * const other) const = 0; virtual int GetBitCount() const = 0; virtual int GetByteCount() const = 0; virtual int GetInt32() const = 0; }; /** * "Big" Integer wrapper */ class Integer { public: /** * Construct using an int * @param value the int value */ Integer(int value = 0); /** * Construct using an byte array * @param value the byte array */ explicit Integer(const QByteArray &value); /** * Construct using a base64 string * @param value the string */ explicit Integer(const QString &value); /** * Returns the byte array representation of the number */ inline QByteArray GetByteArray() const { return m_data->GetByteArray(); } /** * Returns the string representation */ inline QString ToString() const { return Utils::ToUrlSafeBase64(m_data->GetByteArray()); } /** * Returns true if integer is greater than zero and is prime */ inline bool IsPrime() const { return m_data->IsPrime(); } /** * Add operator, produces a new Integer * @param other the Integer to add */ inline Integer Add(const Integer &term) const { return Integer(m_data->Add(term.m_data.constData())); } /** * Subtraction operator, produces a new Integer * @param other the Integer to subtract (subtrahend) */ inline Integer Subtract(const Integer &subtrahend) const { return Integer(m_data->Subtract(subtrahend.m_data.constData())); } /** * Multiply operator, produces a new Integer * @param multiplicand the Integer to multiply this */ inline Integer Multiply(const Integer &multiplicand) const { return Integer(m_data->Multiply(multiplicand.m_data.constData())); } /** * Multiply operator with modulo, produces a new Integer * @param multiplicand multiplicand * @param mod modulus */ Integer Multiply(const Integer &other, const Integer &mod) const { return Integer(m_data->Multiply(other.m_data.constData(), mod.m_data.constData())); } /** * Division operator, produces a new Integer * @param divisor the Integer to divide into this */ inline Integer Divide(const Integer &divisor) const { return Integer(m_data->Divide(divisor.m_data.constData())); } /** * Modulo operator, produces a new Integer * @param modulus the modulus to use */ inline Integer Modulo(const Integer &mod) const { return Integer(m_data->Modulo(mod.m_data.constData())); } /** * Exponentiating operator * @param pow raise this to other * @param mod modulus for the exponentiation */ Integer Pow(const Integer &pow, const Integer &mod) const { return Integer(m_data->Pow(pow.m_data.constData(), mod.m_data.constData())); } /** * Cascade exponentiation modulo n * For integer n, compute ((x1^e1 * x2^e2) mod n) * This can be much faster than the naive way. * @param x1 first base * @param e1 first exponent * @param x2 second base * @param e2 second exponent */ Integer PowCascade(const Integer &x1, const Integer &e1, const Integer &x2, const Integer &e2) const { return Integer(m_data->PowCascade(x1.m_data.constData(), e1.m_data.constData(), x2.m_data.constData(), e2.m_data.constData())); } /** * Compute x such that ax == 1 mod p * @param mod inverse modulo this group */ Integer Inverse(const Integer &mod) const { return Integer(m_data->Inverse(mod.m_data.constData())); } /** * Assignment operator * @param other the other Integer */ inline Integer &operator=(const Integer &other) { m_data = other.m_data; return *this; } /** * Add operator, adds to current * @param other the Integer to add */ inline Integer &operator+=(const Integer &other) { m_data = Add(other).m_data; return *this; } /** * Subtraction operator, subtracts from current * @param other the Integer to subtract */ Integer &operator-=(const Integer &other) { m_data = Subtract(other).m_data; return *this; } /** * Equality operator * @param other the Integer to compare */ bool operator==(const Integer &other) const { return m_data->Equals(other.m_data.constData()); } /** * Not qquality operator * @param other the Integer to compare */ bool operator!=(const Integer &other) const { return ! m_data->Equals(other.m_data.constData()); } /** * Greater than * @param other the Integer to compare */ bool operator>(const Integer &other) const { return other.m_data->LessThan(m_data.constData()); } /** * Greater than or equal * @param other the Integer to compare */ bool operator>=(const Integer &other) const { return other.m_data->LessThanOrEqual(m_data.constData()); } /** * Less than * @param other the Integer to compare */ bool operator<(const Integer &other) const { return m_data->LessThan(other.m_data.constData()); } /** * Less than or equal * @param other the Integer to compare */ bool operator<=(const Integer &other) const { return m_data->LessThanOrEqual(other.m_data.constData()); } /** * Returns the integer's count in bits */ inline int GetBitCount() const { return m_data->GetBitCount(); } /** * Returns the integer's count in bytes */ inline int GetByteCount() const { return m_data->GetByteCount(); } /** * Returns int32 rep */ int GetInt32() const { return m_data->GetInt32(); } Integer(IIntegerImpl *value) : m_data(value) { } const IIntegerImpl *GetHandle() const { return m_data.constData(); } private: QSharedDataPointer<IIntegerImpl> m_data; /** * Convert a base64 number into a clean byte array * @param string input base64 string */ static QByteArray FromBase64(const QString &string) { const QChar *chs = string.constData(); QByteArray tmp; int idx = 0; for(; chs[idx] != '\0'; idx++) { tmp.append(chs[idx].cell()); } return Utils::FromUrlSafeBase64(tmp); } }; /** * Add operator, produces a new Integer * @param lhs first term * @param rhs second term */ inline Integer operator+(const Integer &lhs, const Integer &rhs) { return Integer(lhs.Add(rhs)); } /** * Subtraction operator, produces a new Integer * @param lhs minuend * @param rhs subtrahend */ inline Integer operator-(const Integer &lhs, const Integer &rhs) { return Integer(lhs.Subtract(rhs)); } /** * Multiplication operator, produces a new Integer * @param lhs left multiplicand * @param rhs right multiplicand */ inline Integer operator*(const Integer &lhs, const Integer &rhs) { return lhs.Multiply(rhs); } /** * Division operator, produces a new Integer (quotient) * @param lhs dividend * @param rhs divisor */ inline Integer operator/(const Integer &lhs, const Integer &rhs) { return lhs.Divide(rhs); } inline Integer operator%(const Integer &value, const Integer &mod) { return value.Modulo(mod); } /** * Serialize an Integer * @param stream where to store the serialized integer * @param value the integer to serialize */ inline QDataStream &operator<<(QDataStream &stream, const Integer &value) { return stream << value.GetByteArray(); } /** * Deserialize an integer * @param stream where to read data from * @param value where to store the deserialized integer */ inline QDataStream &operator>>(QDataStream &stream, Integer &value) { QByteArray tvalue; stream >> tvalue; value = Integer(tvalue); return stream; } } } #endif <commit_msg>add missing inplace operators to Integer<commit_after>#ifndef DISSENT_CRYPTO_INTEGER_H_GUARD #define DISSENT_CRYPTO_INTEGER_H_GUARD #include <QByteArray> #include <QSharedData> #include <QString> #include "Utils/Utils.hpp" namespace Dissent { namespace Crypto { class IIntegerImpl : public QSharedData { public: virtual ~IIntegerImpl() {} virtual QByteArray GetByteArray() const = 0; virtual bool IsPrime() const = 0; virtual IIntegerImpl *Add(const IIntegerImpl * const term) const = 0; virtual IIntegerImpl *Subtract(const IIntegerImpl * const subtrahend) const = 0; virtual IIntegerImpl *Multiply(const IIntegerImpl * const multiplicand) const = 0; virtual IIntegerImpl *Multiply(const IIntegerImpl * const multiplicand, const IIntegerImpl * const modulus) const = 0; virtual IIntegerImpl *Divide(const IIntegerImpl * const divisor) const = 0; virtual IIntegerImpl *Modulo(const IIntegerImpl * const mod) const = 0; virtual IIntegerImpl *Pow(const IIntegerImpl * const pow, const IIntegerImpl * const mod) const = 0; virtual IIntegerImpl *PowCascade(const IIntegerImpl * const x0, const IIntegerImpl * const e0, const IIntegerImpl * const x1, const IIntegerImpl * const e1) const = 0; virtual IIntegerImpl *Inverse(const IIntegerImpl * const mod) const = 0; virtual bool Equals(const IIntegerImpl * const other) const = 0; virtual bool LessThan(const IIntegerImpl * const other) const = 0; virtual bool LessThanOrEqual(const IIntegerImpl * const other) const = 0; virtual int GetBitCount() const = 0; virtual int GetByteCount() const = 0; virtual int GetInt32() const = 0; }; /** * "Big" Integer wrapper */ class Integer { public: /** * Construct using an int * @param value the int value */ Integer(int value = 0); /** * Construct using an byte array * @param value the byte array */ explicit Integer(const QByteArray &value); /** * Construct using a base64 string * @param value the string */ explicit Integer(const QString &value); /** * Returns the byte array representation of the number */ inline QByteArray GetByteArray() const { return m_data->GetByteArray(); } /** * Returns the string representation */ inline QString ToString() const { return Utils::ToUrlSafeBase64(m_data->GetByteArray()); } /** * Returns true if integer is greater than zero and is prime */ inline bool IsPrime() const { return m_data->IsPrime(); } /** * Add operator, produces a new Integer * @param other the Integer to add */ inline Integer Add(const Integer &term) const { return Integer(m_data->Add(term.m_data.constData())); } /** * Subtraction operator, produces a new Integer * @param other the Integer to subtract (subtrahend) */ inline Integer Subtract(const Integer &subtrahend) const { return Integer(m_data->Subtract(subtrahend.m_data.constData())); } /** * Multiply operator, produces a new Integer * @param multiplicand the Integer to multiply this */ inline Integer Multiply(const Integer &multiplicand) const { return Integer(m_data->Multiply(multiplicand.m_data.constData())); } /** * Multiply operator with modulo, produces a new Integer * @param multiplicand multiplicand * @param mod modulus */ Integer Multiply(const Integer &other, const Integer &mod) const { return Integer(m_data->Multiply(other.m_data.constData(), mod.m_data.constData())); } /** * Division operator, produces a new Integer * @param divisor the Integer to divide into this */ inline Integer Divide(const Integer &divisor) const { return Integer(m_data->Divide(divisor.m_data.constData())); } /** * Modulo operator, produces a new Integer * @param modulus the modulus to use */ inline Integer Modulo(const Integer &mod) const { return Integer(m_data->Modulo(mod.m_data.constData())); } /** * Exponentiating operator * @param pow raise this to other * @param mod modulus for the exponentiation */ Integer Pow(const Integer &pow, const Integer &mod) const { return Integer(m_data->Pow(pow.m_data.constData(), mod.m_data.constData())); } /** * Cascade exponentiation modulo n * For integer n, compute ((x1^e1 * x2^e2) mod n) * This can be much faster than the naive way. * @param x1 first base * @param e1 first exponent * @param x2 second base * @param e2 second exponent */ Integer PowCascade(const Integer &x1, const Integer &e1, const Integer &x2, const Integer &e2) const { return Integer(m_data->PowCascade(x1.m_data.constData(), e1.m_data.constData(), x2.m_data.constData(), e2.m_data.constData())); } /** * Compute x such that ax == 1 mod p * @param mod inverse modulo this group */ Integer Inverse(const Integer &mod) const { return Integer(m_data->Inverse(mod.m_data.constData())); } /** * Assignment operator * @param other the other Integer */ inline Integer &operator=(const Integer &other) { m_data = other.m_data; return *this; } /** * Add operator, adds to current * @param other the Integer to add */ inline Integer &operator+=(const Integer &other) { m_data = Add(other).m_data; return *this; } /** * Subtraction operator, subtracts from current * @param other the Integer to subtract */ Integer &operator-=(const Integer &other) { m_data = Subtract(other).m_data; return *this; } /** * Multiplication operator, multiplies with current * @param other the Integer to multiply by */ Integer &operator*=(const Integer &other) { m_data = Multiply(other).m_data; return *this; } /** * Division operator, divides current * @param other the Integer to divide by */ Integer &operator/=(const Integer &other) { m_data = Divide(other).m_data; return *this; } /** * Remainder operator, computes the remainder of current * @param other the Integer representing the modulus */ Integer &operator%=(const Integer &modulus) { m_data = Modulo(modulus).m_data; return *this; } /** * Equality operator * @param other the Integer to compare */ bool operator==(const Integer &other) const { return m_data->Equals(other.m_data.constData()); } /** * Not qquality operator * @param other the Integer to compare */ bool operator!=(const Integer &other) const { return ! m_data->Equals(other.m_data.constData()); } /** * Greater than * @param other the Integer to compare */ bool operator>(const Integer &other) const { return other.m_data->LessThan(m_data.constData()); } /** * Greater than or equal * @param other the Integer to compare */ bool operator>=(const Integer &other) const { return other.m_data->LessThanOrEqual(m_data.constData()); } /** * Less than * @param other the Integer to compare */ bool operator<(const Integer &other) const { return m_data->LessThan(other.m_data.constData()); } /** * Less than or equal * @param other the Integer to compare */ bool operator<=(const Integer &other) const { return m_data->LessThanOrEqual(other.m_data.constData()); } /** * Returns the integer's count in bits */ inline int GetBitCount() const { return m_data->GetBitCount(); } /** * Returns the integer's count in bytes */ inline int GetByteCount() const { return m_data->GetByteCount(); } /** * Returns int32 rep */ int GetInt32() const { return m_data->GetInt32(); } Integer(IIntegerImpl *value) : m_data(value) { } const IIntegerImpl *GetHandle() const { return m_data.constData(); } private: QSharedDataPointer<IIntegerImpl> m_data; /** * Convert a base64 number into a clean byte array * @param string input base64 string */ static QByteArray FromBase64(const QString &string) { const QChar *chs = string.constData(); QByteArray tmp; int idx = 0; for(; chs[idx] != '\0'; idx++) { tmp.append(chs[idx].cell()); } return Utils::FromUrlSafeBase64(tmp); } }; /** * Add operator, produces a new Integer * @param lhs first term * @param rhs second term */ inline Integer operator+(const Integer &lhs, const Integer &rhs) { return Integer(lhs.Add(rhs)); } /** * Subtraction operator, produces a new Integer * @param lhs minuend * @param rhs subtrahend */ inline Integer operator-(const Integer &lhs, const Integer &rhs) { return Integer(lhs.Subtract(rhs)); } /** * Multiplication operator, produces a new Integer * @param lhs left multiplicand * @param rhs right multiplicand */ inline Integer operator*(const Integer &lhs, const Integer &rhs) { return lhs.Multiply(rhs); } /** * Division operator, produces a new Integer (quotient) * @param lhs dividend * @param rhs divisor */ inline Integer operator/(const Integer &lhs, const Integer &rhs) { return lhs.Divide(rhs); } inline Integer operator%(const Integer &value, const Integer &mod) { return value.Modulo(mod); } /** * Serialize an Integer * @param stream where to store the serialized integer * @param value the integer to serialize */ inline QDataStream &operator<<(QDataStream &stream, const Integer &value) { return stream << value.GetByteArray(); } /** * Deserialize an integer * @param stream where to read data from * @param value where to store the deserialized integer */ inline QDataStream &operator>>(QDataStream &stream, Integer &value) { QByteArray tvalue; stream >> tvalue; value = Integer(tvalue); return stream; } } } #endif <|endoftext|>
<commit_before>#include <ros/ros.h> #include <quirkd/Alert.h> #include <nav_msgs/GetMap.h> #include <sensor_msgs/LaserScan.h> class DataController { public: DataController() { alert_pub_ = n_.advertise<quirkd::Alert>("/quirkd/alert/notification", 1); laser_sub_ = n_.subscribe("/base_scan", 1, &DataController::laserScanCB, this); static_map_client_ = n_.serviceClient<nav_msgs::GetMap>("static_map"); dynamic_map_client_ = n_.serviceClient<nav_msgs::GetMap>("dynamic_map"); } void laserScanCB(const sensor_msgs::LaserScan msg) { ROS_INFO("Laser Scan Callback"); updated = true; last_data = msg; } void update() { ROS_INFO("Update Data Processor"); nav_msgs::GetMap srv; if (static_map_client_.call(srv)) { ROS_INFO("Successfull call static map"); } else { ROS_WARN("Failed to get static map"); } if (dynamic_map_client_.call(srv)) { ROS_INFO("Successfull call dynamic map"); } else { ROS_WARN("Failed to get dynamic map"); } updated = false; } void pub_alert_status() { quirkd::Alert msg; alert_pub_.publish(msg); } bool updated; sensor_msgs::LaserScan last_data; private: ros::NodeHandle n_; ros::Publisher alert_pub_; ros::Subscriber laser_sub_; ros::ServiceClient dynamic_map_client_; ros::ServiceClient static_map_client_; }; int main(int argc, char** argv) { ros::init(argc, argv, "DataController"); ROS_INFO("1"); DataController dp; ROS_INFO("2"); dp.updated = false; ROS_INFO("3"); ros::Rate r(30); ROS_INFO("4"); dp.update(); while(ros::ok()) { ros::spinOnce(); if (dp.updated) { dp.update(); ROS_INFO("Processed message data in loop"); } dp.pub_alert_status(); r.sleep(); } ROS_INFO("Data Processor Exited."); return 0; } <commit_msg>DC gets callback, updates, makes the service calls<commit_after>#include <ros/ros.h> #include <nav_msgs/GetMap.h> #include <quirkd/Alert.h> #include <sensor_msgs/LaserScan.h> #include <tf/transform_listener.h> class DataController { public: DataController() { alert_pub_ = n_.advertise<quirkd::Alert>("/quirkd/alert/notification", 1); laser_sub_ = n_.subscribe("/base_scan", 1, &DataController::laserScanCB, this); // ros::service::waitForService("static_map"); static_map_client_ = n_.serviceClient<nav_msgs::GetMap>("static_map"); // ros::service::waitForService("dynamic_map"); dynamic_map_client_ = n_.serviceClient<nav_msgs::GetMap>("dynamic_map"); } void laserScanCB(const sensor_msgs::LaserScan msg) { ROS_INFO("Laser Scan Callback"); updated = true; last_data = msg; try { tf_.lookupTransform("/map", "/base_laser_link", ros::Time(0), last_tf); } catch (tf::TransformException &ex) { ROS_WARN("tf fetch failed. %s", ex.what()); } } void update() { ROS_INFO("Update Data Processor"); nav_msgs::GetMap srv; if (static_map_client_.call(srv)) { ROS_INFO("Successfull call static map"); } else { ROS_WARN("Failed to get static map"); } if (dynamic_map_client_.call(srv)) { ROS_INFO("Successfull call dynamic map"); } else { ROS_WARN("Failed to get dynamic map"); } updated = false; } void pub_alert_status() { quirkd::Alert msg; alert_pub_.publish(msg); } bool updated; sensor_msgs::LaserScan last_data; tf::StampedTransform last_tf; private: ros::NodeHandle n_; ros::Publisher alert_pub_; ros::Subscriber laser_sub_; ros::ServiceClient dynamic_map_client_; ros::ServiceClient static_map_client_; tf::TransformListener tf_; }; int main(int argc, char** argv) { ros::init(argc, argv, "DataController"); ROS_INFO("1"); DataController dp; ROS_INFO("2"); dp.updated = false; ROS_INFO("3"); ros::Rate r(30); ROS_INFO("4"); dp.update(); while(ros::ok()) { ros::spinOnce(); if (dp.updated) { dp.update(); ROS_INFO("Processed message data in loop"); } dp.pub_alert_status(); r.sleep(); } ROS_INFO("Data Processor Exited."); return 0; } <|endoftext|>
<commit_before>#include <TGUI/TGUI.hpp> #include <vili/Vili.hpp> #include "System/Window.hpp" #include <Editor/MapEditor.hpp> #include <Modes/Game.hpp> #include <Modes/Menu.hpp> #include <Modes/Toolkit.hpp> #include <System/Config.hpp> #include <System/Loaders.hpp> #include <System/Path.hpp> #include <Utils/StringUtils.hpp> #include <thread> namespace obe::Modes { void scrollPanel(tgui::Panel::Ptr panel, tgui::Scrollbar::Ptr scrollbar) { static int previousScrolbarValue = 0; const int distanceToMove = previousScrolbarValue - scrollbar->getValue(); for (auto& widget : panel->getWidgets()) widget->setPosition(widget->getPosition().x, widget->getPosition().y + distanceToMove); previousScrolbarValue = scrollbar->getValue(); } void chooseMapAddMaps(tgui::Panel::Ptr middlePanel, tgui::Scrollbar::Ptr scrollbar, tgui::Theme& baseTheme, std::string& currentMap) { int scrollBoxSize = 0; scrollbar->setLowValue(middlePanel->getSize().y); scrollbar->setMaximum(scrollBoxSize); middlePanel->removeAllWidgets(); std::vector<std::string> allMapsTemp; System::Path("Data/Maps") .loadAll(System::Loaders::filePathLoader, allMapsTemp); std::vector<std::string> allMaps; for (int i = 0; i < allMapsTemp.size(); i++) { if (Utils::String::endsWith(allMapsTemp[i], ".map.vili")) allMaps.push_back(allMapsTemp[i]); } for (int i = 0; i < allMaps.size(); i++) { vili::ViliParser mapInfoParser; mapInfoParser.setQuickLookAttributes({"Meta"}); System::Path("Data/Maps") .add(allMaps[i]) .load(System::Loaders::dataLoader, mapInfoParser); const std::string filename = allMaps[i]; std::string levelName = "???"; if (mapInfoParser->contains(vili::NodeType::ComplexNode, "Meta")) { if (mapInfoParser.at("Meta").contains(vili::NodeType::DataNode, "name")) levelName = mapInfoParser.at("Meta") .getDataNode("name") .get<std::string>(); } tgui::Button::Ptr selectMapButton = tgui::Button::create(); middlePanel->add(selectMapButton); selectMapButton->setText( levelName + " (" + filename.substr(0, allMapsTemp[i].size() - 9) + ")"); selectMapButton->setRenderer( baseTheme.getRenderer("MapSelectButton")); selectMapButton->setSize("100%", "20%"); selectMapButton->setPosition("0", i * selectMapButton->getSize().y); selectMapButton->connect( "pressed", [&currentMap, filename] { currentMap = filename; }); scrollBoxSize += selectMapButton->getSize().y - 1; } scrollbar->setLowValue(middlePanel->getSize().y); scrollbar->setMaximum(scrollBoxSize); } void createLevel(tgui::EditBox::Ptr input) { const std::string newLevelName = input->getText(); if (newLevelName != "") { if (!Utils::File::fileExists(System::Path("Data/Maps") .add(newLevelName + ".map.vili") .getPath(0) .toString())) { Debug::Log->info( "<Menu:createLevel> Creating new Map file : '{0}'", newLevelName); vili::ViliParser newFileParser; newFileParser.addFlag("Map"); newFileParser.addFlag("Lock"); newFileParser.includeFile("Obe"); newFileParser->createComplexNode("Meta"); newFileParser.at("Meta").createDataNode("name", newLevelName); newFileParser->createComplexNode("View"); newFileParser.at("View").createComplexNode("pos"); newFileParser.at("View", "pos") .createDataNode("unit", "SceneUnits"); newFileParser.at("View", "pos").createDataNode("x", 0); newFileParser.at("View", "pos").createDataNode("y", 0); newFileParser.at("View", "pos") .useTemplate( newFileParser.getTemplate("Vector2<SceneUnits>")); newFileParser.at("View").createDataNode("size", 1); newFileParser.writeFile(System::Path("Data/Maps") .add(newLevelName + ".map.vili") .getPath(0) .toString(), true); input->setText(""); } else Debug::Log->warn("<Menu:createLevel> Map file : '{0}' already " "exists, cancelling operation", newLevelName); } } std::string chooseMapMenu() { unsigned windowSize = sf::VideoMode::getDesktopMode().height / 1.5; sf::RenderWindow window({windowSize, windowSize}, "ObEngine Map Selector", sf::Style::None); tgui::Gui gui(window); gui.setFont("Data/Fonts/weblysleekuil.ttf"); tgui::Theme baseTheme; baseTheme.load("Data/GUI/obe.style"); std::string currentMap; tgui::Panel::Ptr topPanel = tgui::Panel::create(); tgui::Panel::Ptr bottomPanel = tgui::Panel::create(); tgui::Panel::Ptr middlePanel = tgui::Panel::create(); tgui::Scrollbar::Ptr scrollbar = tgui::Scrollbar::create(); tgui::Label::Ptr titleLabel = tgui::Label::create(); tgui::Label::Ptr mapEditorLabel = tgui::Label::create(); tgui::Button::Ptr closeButton = tgui::Button::create(); tgui::Label::Ptr createMapLabel = tgui::Label::create(); tgui::Button::Ptr createMapButton = tgui::Button::create(); tgui::EditBox::Ptr createMapInput = tgui::EditBox::create(); topPanel->setRenderer(baseTheme.getRenderer("Panel")); topPanel->setSize("100%", "10%"); topPanel->setPosition("0", "0"); bottomPanel->setRenderer(baseTheme.getRenderer("Panel")); bottomPanel->setSize("100%", "10%"); bottomPanel->setPosition("0", "90%"); middlePanel->setRenderer(baseTheme.getRenderer("LightPanel")); middlePanel->setSize("100%", "80%"); middlePanel->setPosition("0", "10%"); scrollbar->setPosition("620", "10% - 1"); scrollbar->setSize("16", "80% + 1"); scrollbar->connect("ValueChanged", scrollPanel, middlePanel, scrollbar); titleLabel->setRenderer(baseTheme.getRenderer("Label")); titleLabel->setText("ObEngine"); titleLabel->setTextSize(windowSize * 0.06); titleLabel->setPosition("2.5%", "15=5%"); mapEditorLabel->setRenderer(baseTheme.getRenderer("Label")); mapEditorLabel->setText("<Map Editor>"); mapEditorLabel->setTextSize(windowSize * 0.035); mapEditorLabel->setPosition(tgui::bindRight(titleLabel) + 20, "40%"); closeButton->setRenderer(baseTheme.getRenderer("CloseButton")); closeButton->setSize("height", "50%"); closeButton->setPosition("92%", "25%"); closeButton->connect("pressed", [&window]() { window.close(); }); createMapLabel->setRenderer(baseTheme.getRenderer("Label")); createMapLabel->setText("Create Level : "); createMapLabel->setTextSize(windowSize * 0.045); createMapLabel->setPosition("2.5%", "20%"); auto createMapLambda = [createMapInput, middlePanel, scrollbar, &baseTheme, &currentMap]() { createLevel(createMapInput); chooseMapAddMaps(middlePanel, scrollbar, baseTheme, currentMap); }; createMapButton->setRenderer(baseTheme.getRenderer("AddButton")); createMapButton->setSize("height", "50%"); createMapButton->setPosition("90%", "25%"); createMapButton->connect("pressed", createMapLambda); createMapInput->setRenderer(baseTheme.getRenderer("TextBox")); createMapInput->setSize("47%", "50%"); createMapInput->setPosition("35%", "25%"); createMapInput->connect("returnkeypressed", createMapLambda); gui.add(topPanel); gui.add(bottomPanel); gui.add(middlePanel); gui.add(scrollbar); topPanel->add(closeButton); topPanel->add(titleLabel); topPanel->add(mapEditorLabel); bottomPanel->add(createMapButton); bottomPanel->add(createMapLabel); bottomPanel->add(createMapInput); sf::Vector2i grabbedOffset; bool grabbedWindow = false; chooseMapAddMaps(middlePanel, scrollbar, baseTheme, currentMap); while (window.isOpen() && currentMap == "") { sf::Event event; while (window.pollEvent(event)) { if (event.type == sf::Event::Closed) window.close(); else if (event.type == sf::Event::MouseButtonPressed) { if (sf::Mouse::getPosition().y - window.getPosition().y < 60 && sf::Mouse::getPosition().x - window.getPosition().x < 580) { if (event.mouseButton.button == sf::Mouse::Left) { grabbedOffset = window.getPosition() - sf::Mouse::getPosition(); grabbedWindow = true; } } } else if (event.type == sf::Event::MouseButtonReleased) { if (event.mouseButton.button == sf::Mouse::Left) grabbedWindow = false; } else if (event.type == sf::Event::MouseWheelScrolled) { scrollbar->mouseWheelScrolled( event.mouseWheelScroll.delta * 30, sf::Vector2f(0, 0)); } else if (event.type == sf::Event::MouseMoved) { if (grabbedWindow) window.setPosition(sf::Mouse::getPosition() + grabbedOffset); } gui.handleEvent(event); } window.clear(); gui.draw(); window.display(); } return currentMap; } void startDevMenu() { unsigned windowSize = sf::VideoMode::getDesktopMode().height / 1.5; sf::RenderWindow window({ windowSize, windowSize }, "ObEngine Development Window", sf::Style::None); tgui::Gui gui(window); gui.setFont("Data/Fonts/weblysleekuil.ttf"); tgui::Theme baseTheme; baseTheme.load("Data/GUI/obe.style"); tgui::Panel::Ptr topPanel = tgui::Panel::create(); tgui::Panel::Ptr middlePanel = tgui::Panel::create(); tgui::Label::Ptr titleLabel = tgui::Label::create(); tgui::Button::Ptr closeButton = tgui::Button::create(); tgui::Button::Ptr playButton = tgui::Button::create(); tgui::Button::Ptr editButton = tgui::Button::create(); tgui::Button::Ptr toolkitButton = tgui::Button::create(); tgui::Button::Ptr helpButton = tgui::Button::create(); topPanel->setRenderer(baseTheme.getRenderer("Panel")); topPanel->setSize("100%", "10%"); topPanel->setPosition("0", "0"); middlePanel->setRenderer(baseTheme.getRenderer("LightPanel")); middlePanel->setSize("100%", "90%"); middlePanel->setPosition("0", "10%"); titleLabel->setRenderer(baseTheme.getRenderer("Label")); titleLabel->setText("ObEngine Development Menu"); titleLabel->setTextSize(float(windowSize) * 0.06); titleLabel->setPosition("2.5%", "15%"); closeButton->setRenderer(baseTheme.getRenderer("CloseButton")); closeButton->setSize("height", "50%"); closeButton->setPosition("92%", "25%"); closeButton->connect("pressed", [&window]() { window.close(); }); auto checkBootFile = [playButton]() { if (System::Path("boot.lua").find() == "") { playButton->disable(); } else { playButton->enable(); } }; auto checkMapFolder = [editButton]() { if (System::Path("Data/Maps").find(System::PathType::Directory) == "") { editButton->disable(); } else { editButton->enable(); } }; checkBootFile(); checkMapFolder(); playButton->setRenderer(baseTheme.getRenderer("PlaySquareButton")); playButton->setSize("50%", "50%"); playButton->setPosition("0", "0"); playButton->connect("pressed", [&checkBootFile, &checkMapFolder]() { startGame(); checkBootFile(); checkMapFolder(); }); editButton->setRenderer(baseTheme.getRenderer("EditSquareButton")); editButton->setSize("50%", "50%"); editButton->setPosition(tgui::bindRight(playButton), "0"); editButton->connect("pressed", [&checkBootFile, &checkMapFolder]() { std::string editMapName = chooseMapMenu(); if (editMapName != "") Editor::editMap(editMapName); checkBootFile(); checkMapFolder(); }); toolkitButton->setRenderer( baseTheme.getRenderer("ToolkitSquareButton")); toolkitButton->setSize("50%", "50%"); toolkitButton->setPosition("0", tgui::bindBottom(playButton)); toolkitButton->connect("pressed", [&window, &checkBootFile, &checkMapFolder]() { startToolkitMode(); checkBootFile(); checkMapFolder(); System::InitConfiguration(); }); helpButton->setRenderer(baseTheme.getRenderer("HelpSquareButton")); helpButton->setSize("50%", "50%"); helpButton->setPosition(tgui::bindLeft(editButton), tgui::bindBottom(playButton)); // helpButton->connect("pressed", [&window]() gui.add(topPanel); gui.add(middlePanel); topPanel->add(closeButton); topPanel->add(titleLabel); middlePanel->add(playButton); middlePanel->add(editButton); middlePanel->add(toolkitButton); middlePanel->add(helpButton); sf::Vector2i grabbedOffset; bool grabbedWindow = false; while (window.isOpen()) { sf::Event event; while (window.pollEvent(event)) { if (event.type == sf::Event::Closed) window.close(); else if (event.type == sf::Event::MouseButtonPressed) { if (sf::Mouse::getPosition().y - window.getPosition().y < 60 && sf::Mouse::getPosition().x - window.getPosition().x < 580) { if (event.mouseButton.button == sf::Mouse::Left) { grabbedOffset = window.getPosition() - sf::Mouse::getPosition(); grabbedWindow = true; } } } else if (event.type == sf::Event::MouseButtonReleased) { if (event.mouseButton.button == sf::Mouse::Left) grabbedWindow = false; } else if (event.type == sf::Event::MouseMoved) { if (grabbedWindow) { window.setPosition(sf::Mouse::getPosition() + grabbedOffset); } } gui.handleEvent(event); } window.clear(); gui.draw(); window.display(); } } } // namespace obe::Modes <commit_msg>Fixed map selector<commit_after>#include <TGUI/TGUI.hpp> #include <vili/Vili.hpp> #include "System/Window.hpp" #include <Editor/MapEditor.hpp> #include <Modes/Game.hpp> #include <Modes/Menu.hpp> #include <Modes/Toolkit.hpp> #include <System/Config.hpp> #include <System/Loaders.hpp> #include <System/Path.hpp> #include <Utils/StringUtils.hpp> #include <thread> namespace obe::Modes { void scrollPanel(tgui::Panel::Ptr panel, tgui::Scrollbar::Ptr scrollbar) { static int previousScrolbarValue = 0; const int distanceToMove = previousScrolbarValue - scrollbar->getValue(); for (auto& widget : panel->getWidgets()) widget->setPosition(widget->getPosition().x, widget->getPosition().y + distanceToMove); previousScrolbarValue = scrollbar->getValue(); } void chooseMapAddMaps(tgui::Panel::Ptr middlePanel, tgui::Scrollbar::Ptr scrollbar, tgui::Theme& baseTheme, std::string& currentMap) { int scrollBoxSize = 0; scrollbar->setLowValue(middlePanel->getSize().y); scrollbar->setMaximum(scrollBoxSize); middlePanel->removeAllWidgets(); std::vector<std::string> allMapsTemp; System::Path("Data/Maps") .loadAll(System::Loaders::filePathLoader, allMapsTemp); std::vector<std::string> allMaps; for (int i = 0; i < allMapsTemp.size(); i++) { if (Utils::String::endsWith(allMapsTemp[i], ".map.vili")) allMaps.push_back(allMapsTemp[i]); } for (int i = 0; i < allMaps.size(); i++) { vili::ViliParser mapInfoParser; mapInfoParser.setQuickLookAttributes({"Meta"}); System::Path("Data/Maps") .add(allMaps[i]) .load(System::Loaders::dataLoader, mapInfoParser); const std::string filename = allMaps[i]; std::string levelName = "???"; if (mapInfoParser->contains(vili::NodeType::ComplexNode, "Meta")) { if (mapInfoParser.at("Meta").contains(vili::NodeType::DataNode, "name")) levelName = mapInfoParser.at("Meta") .getDataNode("name") .get<std::string>(); } tgui::Button::Ptr selectMapButton = tgui::Button::create(); middlePanel->add(selectMapButton); selectMapButton->setText( levelName + " (" + filename.substr(0, allMapsTemp[i].size() - 9) + ")"); selectMapButton->setRenderer( baseTheme.getRenderer("MapSelectButton")); selectMapButton->setSize("100%", "20%"); middlePanel->add(selectMapButton); selectMapButton->setPosition("0", i * selectMapButton->getSize().y); selectMapButton->connect( "pressed", [&currentMap, filename] { currentMap = filename; }); scrollBoxSize += selectMapButton->getSize().y - 1; } scrollbar->setLowValue(middlePanel->getSize().y); scrollbar->setMaximum(scrollBoxSize); } void createLevel(tgui::EditBox::Ptr input) { const std::string newLevelName = input->getText(); if (newLevelName != "") { if (!Utils::File::fileExists(System::Path("Data/Maps") .add(newLevelName + ".map.vili") .getPath(0) .toString())) { Debug::Log->info( "<Menu:createLevel> Creating new Map file : '{0}'", newLevelName); vili::ViliParser newFileParser; newFileParser.addFlag("Map"); newFileParser.addFlag("Lock"); newFileParser.includeFile("Obe"); newFileParser->createComplexNode("Meta"); newFileParser.at("Meta").createDataNode("name", newLevelName); newFileParser->createComplexNode("View"); newFileParser.at("View").createComplexNode("pos"); newFileParser.at("View", "pos") .createDataNode("unit", "SceneUnits"); newFileParser.at("View", "pos").createDataNode("x", 0); newFileParser.at("View", "pos").createDataNode("y", 0); newFileParser.at("View", "pos") .useTemplate( newFileParser.getTemplate("Vector2<SceneUnits>")); newFileParser.at("View").createDataNode("size", 1); newFileParser.writeFile(System::Path("Data/Maps") .add(newLevelName + ".map.vili") .getPath(0) .toString(), true); input->setText(""); } else Debug::Log->warn("<Menu:createLevel> Map file : '{0}' already " "exists, cancelling operation", newLevelName); } } std::string chooseMapMenu() { unsigned windowSize = sf::VideoMode::getDesktopMode().height / 1.5; sf::RenderWindow window({windowSize, windowSize}, "ObEngine Map Selector", sf::Style::None); tgui::Gui gui(window); gui.setFont("Data/Fonts/weblysleekuil.ttf"); tgui::Theme baseTheme; baseTheme.load("Data/GUI/obe.style"); std::string currentMap; tgui::Panel::Ptr topPanel = tgui::Panel::create(); tgui::Panel::Ptr bottomPanel = tgui::Panel::create(); tgui::Panel::Ptr middlePanel = tgui::Panel::create(); tgui::Scrollbar::Ptr scrollbar = tgui::Scrollbar::create(); tgui::Label::Ptr titleLabel = tgui::Label::create(); tgui::Label::Ptr mapEditorLabel = tgui::Label::create(); tgui::Button::Ptr closeButton = tgui::Button::create(); tgui::Label::Ptr createMapLabel = tgui::Label::create(); tgui::Button::Ptr createMapButton = tgui::Button::create(); tgui::EditBox::Ptr createMapInput = tgui::EditBox::create(); topPanel->setRenderer(baseTheme.getRenderer("Panel")); topPanel->setSize("100%", "10%"); topPanel->setPosition("0", "0"); bottomPanel->setRenderer(baseTheme.getRenderer("Panel")); bottomPanel->setSize("100%", "10%"); bottomPanel->setPosition("0", "90%"); middlePanel->setRenderer(baseTheme.getRenderer("LightPanel")); middlePanel->setSize("100%", "80%"); middlePanel->setPosition("0", "10%"); scrollbar->setPosition("620", "10% - 1"); scrollbar->setSize("16", "80% + 1"); scrollbar->connect("ValueChanged", scrollPanel, middlePanel, scrollbar); titleLabel->setRenderer(baseTheme.getRenderer("Label")); titleLabel->setText("ObEngine"); titleLabel->setTextSize(windowSize * 0.06); titleLabel->setPosition("2.5%", "15=5%"); mapEditorLabel->setRenderer(baseTheme.getRenderer("Label")); mapEditorLabel->setText("<Map Editor>"); mapEditorLabel->setTextSize(windowSize * 0.035); mapEditorLabel->setPosition(tgui::bindRight(titleLabel) + 20, "40%"); closeButton->setRenderer(baseTheme.getRenderer("CloseButton")); closeButton->setSize("height", "50%"); closeButton->setPosition("92%", "25%"); closeButton->connect("pressed", [&window]() { window.close(); }); createMapLabel->setRenderer(baseTheme.getRenderer("Label")); createMapLabel->setText("Create Level : "); createMapLabel->setTextSize(windowSize * 0.045); createMapLabel->setPosition("2.5%", "20%"); auto createMapLambda = [createMapInput, middlePanel, scrollbar, &baseTheme, &currentMap]() { createLevel(createMapInput); chooseMapAddMaps(middlePanel, scrollbar, baseTheme, currentMap); }; createMapButton->setRenderer(baseTheme.getRenderer("AddButton")); createMapButton->setSize("height", "50%"); createMapButton->setPosition("90%", "25%"); createMapButton->connect("pressed", createMapLambda); createMapInput->setRenderer(baseTheme.getRenderer("TextBox")); createMapInput->setSize("47%", "50%"); createMapInput->setPosition("35%", "25%"); createMapInput->connect("returnkeypressed", createMapLambda); gui.add(topPanel); gui.add(bottomPanel); gui.add(middlePanel); gui.add(scrollbar); topPanel->add(closeButton); topPanel->add(titleLabel); topPanel->add(mapEditorLabel); bottomPanel->add(createMapButton); bottomPanel->add(createMapLabel); bottomPanel->add(createMapInput); sf::Vector2i grabbedOffset; bool grabbedWindow = false; chooseMapAddMaps(middlePanel, scrollbar, baseTheme, currentMap); while (window.isOpen() && currentMap == "") { sf::Event event; while (window.pollEvent(event)) { if (event.type == sf::Event::Closed) window.close(); else if (event.type == sf::Event::MouseButtonPressed) { if (sf::Mouse::getPosition().y - window.getPosition().y < 60 && sf::Mouse::getPosition().x - window.getPosition().x < 580) { if (event.mouseButton.button == sf::Mouse::Left) { grabbedOffset = window.getPosition() - sf::Mouse::getPosition(); grabbedWindow = true; } } } else if (event.type == sf::Event::MouseButtonReleased) { if (event.mouseButton.button == sf::Mouse::Left) grabbedWindow = false; } else if (event.type == sf::Event::MouseWheelScrolled) { scrollbar->mouseWheelScrolled( event.mouseWheelScroll.delta * 30, sf::Vector2f(0, 0)); } else if (event.type == sf::Event::MouseMoved) { if (grabbedWindow) window.setPosition(sf::Mouse::getPosition() + grabbedOffset); } gui.handleEvent(event); } window.clear(); gui.draw(); window.display(); } return currentMap; } void startDevMenu() { unsigned windowSize = sf::VideoMode::getDesktopMode().height / 1.5; sf::RenderWindow window({ windowSize, windowSize }, "ObEngine Development Window", sf::Style::None); tgui::Gui gui(window); gui.setFont("Data/Fonts/weblysleekuil.ttf"); tgui::Theme baseTheme; baseTheme.load("Data/GUI/obe.style"); tgui::Panel::Ptr topPanel = tgui::Panel::create(); tgui::Panel::Ptr middlePanel = tgui::Panel::create(); tgui::Label::Ptr titleLabel = tgui::Label::create(); tgui::Button::Ptr closeButton = tgui::Button::create(); tgui::Button::Ptr playButton = tgui::Button::create(); tgui::Button::Ptr editButton = tgui::Button::create(); tgui::Button::Ptr toolkitButton = tgui::Button::create(); tgui::Button::Ptr helpButton = tgui::Button::create(); topPanel->setRenderer(baseTheme.getRenderer("Panel")); topPanel->setSize("100%", "10%"); topPanel->setPosition("0", "0"); middlePanel->setRenderer(baseTheme.getRenderer("LightPanel")); middlePanel->setSize("100%", "90%"); middlePanel->setPosition("0", "10%"); titleLabel->setRenderer(baseTheme.getRenderer("Label")); titleLabel->setText("ObEngine Development Menu"); titleLabel->setTextSize(float(windowSize) * 0.06); titleLabel->setPosition("2.5%", "15%"); closeButton->setRenderer(baseTheme.getRenderer("CloseButton")); closeButton->setSize("height", "50%"); closeButton->setPosition("92%", "25%"); closeButton->connect("pressed", [&window]() { window.close(); }); auto checkBootFile = [playButton]() { if (System::Path("boot.lua").find() == "") { playButton->disable(); } else { playButton->enable(); } }; auto checkMapFolder = [editButton]() { if (System::Path("Data/Maps").find(System::PathType::Directory) == "") { editButton->disable(); } else { editButton->enable(); } }; checkBootFile(); checkMapFolder(); playButton->setRenderer(baseTheme.getRenderer("PlaySquareButton")); playButton->setSize("50%", "50%"); playButton->setPosition("0", "0"); playButton->connect("pressed", [&checkBootFile, &checkMapFolder]() { startGame(); checkBootFile(); checkMapFolder(); }); editButton->setRenderer(baseTheme.getRenderer("EditSquareButton")); editButton->setSize("50%", "50%"); editButton->setPosition(tgui::bindRight(playButton), "0"); editButton->connect("pressed", [&checkBootFile, &checkMapFolder]() { std::string editMapName = chooseMapMenu(); if (editMapName != "") Editor::editMap(editMapName); checkBootFile(); checkMapFolder(); }); toolkitButton->setRenderer( baseTheme.getRenderer("ToolkitSquareButton")); toolkitButton->setSize("50%", "50%"); toolkitButton->setPosition("0", tgui::bindBottom(playButton)); toolkitButton->connect("pressed", [&window, &checkBootFile, &checkMapFolder]() { startToolkitMode(); checkBootFile(); checkMapFolder(); System::InitConfiguration(); }); helpButton->setRenderer(baseTheme.getRenderer("HelpSquareButton")); helpButton->setSize("50%", "50%"); helpButton->setPosition(tgui::bindLeft(editButton), tgui::bindBottom(playButton)); // helpButton->connect("pressed", [&window]() gui.add(topPanel); gui.add(middlePanel); topPanel->add(closeButton); topPanel->add(titleLabel); middlePanel->add(playButton); middlePanel->add(editButton); middlePanel->add(toolkitButton); middlePanel->add(helpButton); sf::Vector2i grabbedOffset; bool grabbedWindow = false; while (window.isOpen()) { sf::Event event; while (window.pollEvent(event)) { if (event.type == sf::Event::Closed) window.close(); else if (event.type == sf::Event::MouseButtonPressed) { if (sf::Mouse::getPosition().y - window.getPosition().y < 60 && sf::Mouse::getPosition().x - window.getPosition().x < 580) { if (event.mouseButton.button == sf::Mouse::Left) { grabbedOffset = window.getPosition() - sf::Mouse::getPosition(); grabbedWindow = true; } } } else if (event.type == sf::Event::MouseButtonReleased) { if (event.mouseButton.button == sf::Mouse::Left) grabbedWindow = false; } else if (event.type == sf::Event::MouseMoved) { if (grabbedWindow) { window.setPosition(sf::Mouse::getPosition() + grabbedOffset); } } gui.handleEvent(event); } window.clear(); gui.draw(); window.display(); } } } // namespace obe::Modes <|endoftext|>
<commit_before>/* * Copyright (c) 2016 dresden elektronik ingenieurtechnik gmbh. * All rights reserved. * * The software in this package is published under the terms of the BSD * style license a copy of which has been included with this distribution in * the LICENSE.txt file. * */ #include <QApplication> #include <QDesktopServices> #include <QString> #include <QTcpSocket> #include <QVariantMap> #include <QNetworkInterface> #include "de_web_plugin.h" #include "de_web_plugin_private.h" #include "json.h" #include <stdlib.h> /*! Configuration REST API broker. \param req - request data \param rsp - response data \return REQ_READY_SEND REQ_NOT_HANDLED */ int DeRestPluginPrivate::handleUserparameterApi(const ApiRequest &req, ApiResponse &rsp) { if (req.path[2] != QLatin1String("userparameter")) { return REQ_NOT_HANDLED; } // POST /api/<apikey>/userparameter/ if ((req.path.size() == 3) && (req.hdr.method() == "POST")) { return createUserParameter(req, rsp); } // POST /api/<apikey>/userparameter/<parameter> else if ((req.path.size() == 4) && (req.hdr.method() == "POST")) { return addUserParameter(req, rsp); } // PUT /api/<apikey>/userparameter/<parameter> else if ((req.path.size() == 4) && (req.hdr.method() == "PUT")) { return modifyUserParameter(req, rsp); } // GET /api/<apikey>/userparameter else if ((req.path.size() == 3) && (req.hdr.method() == "GET")) { return getAllUserParameter(req, rsp); } // GET /api/<apikey>/userparameter/<parameter> else if ((req.path.size() == 4) && (req.hdr.method() == "GET")) { return getUserParameter(req, rsp); } // DELETE /api/<apikey>/userparameter/<parameter> else if ((req.path.size() == 4) && (req.hdr.method() == "DELETE")) { return deleteUserParameter(req, rsp); } return REQ_NOT_HANDLED; } /*! POST /api/<apikey>/userparameter \return REQ_READY_SEND REQ_NOT_HANDLED */ int DeRestPluginPrivate::createUserParameter(const ApiRequest &req, ApiResponse &rsp) { if(!checkApikeyAuthentification(req, rsp)) { return REQ_READY_SEND; } if (req.content.isEmpty()) { rsp.list.append(errorToMap(ERR_INVALID_VALUE, QString("/userparameter"), QString("invalid value for userparameter"))); rsp.httpStatus = HttpStatusBadRequest; return REQ_READY_SEND; } rsp.httpStatus = HttpStatusOk; // generate id int i = 1; while (gwUserParameter.contains(QString::number(i))) { i++; } QString id = QString::number(i); QVariantMap rspItem; QVariantMap rspItemState; gwUserParameter.insert(id, req.content); rspItemState["id"] = id; rspItem["success"] = rspItemState; rsp.list.append(rspItem); queSaveDb(DB_USERPARAM, DB_SHORT_SAVE_DELAY); return REQ_READY_SEND; } /*! POST /api/<apikey>/userparameter/<parameter> \return REQ_READY_SEND REQ_NOT_HANDLED */ int DeRestPluginPrivate::addUserParameter(const ApiRequest &req, ApiResponse &rsp) { if(!checkApikeyAuthentification(req, rsp)) { return REQ_READY_SEND; } DBG_Assert(req.path.size() == 4); if (req.path.size() != 4) { return -1; } const QString &key = req.path[3]; rsp.httpStatus = HttpStatusOk; //don't overwrite existing parameters if POST request if (gwUserParameter.contains(key)) { rsp.httpStatus = HttpStatusBadRequest; rsp.list.append(errorToMap(ERR_DUPLICATE_EXIST , QString("config/userparameter"), QString("key %1 already exists").arg(key))); return REQ_READY_SEND; } QVariantMap rspItem; QVariantMap rspItemState; gwUserParameter.insert(key, req.content); rspItemState["/config/userparameter"] = QString("added new %1").arg(key); rspItem["success"] = rspItemState; rsp.list.append(rspItem); queSaveDb(DB_USERPARAM, DB_SHORT_SAVE_DELAY); return REQ_READY_SEND; } /*! PUT /api/<apikey>/userparameter/<parameter> \return REQ_READY_SEND REQ_NOT_HANDLED */ int DeRestPluginPrivate::modifyUserParameter(const ApiRequest &req, ApiResponse &rsp) { if(!checkApikeyAuthentification(req, rsp)) { return REQ_READY_SEND; } DBG_Assert(req.path.size() == 4); if (req.path.size() != 4) { return -1; } const QString &key = req.path[3]; rsp.httpStatus = HttpStatusOk; QVariantMap rspItem; QVariantMap rspItemState; //overwrite existing parameters if PUT request if (gwUserParameter.contains(key)) { QVariantMap::iterator it = gwUserParameter.find(key); if (*it != req.content) { gwUserParameter.erase(it); gwUserParameter.insert(key, req.content); queSaveDb(DB_USERPARAM, DB_SHORT_SAVE_DELAY); } rspItemState["/config/userparameter"] = QString("updated %1").arg(key); rspItem["success"] = rspItemState; rsp.list.append(rspItem); } else { gwUserParameter.insert(key, req.content); rspItemState["/config/userparameter"] = QString("added new %1").arg(key); rspItem["success"] = rspItemState; rsp.list.append(rspItem); queSaveDb(DB_USERPARAM, DB_SHORT_SAVE_DELAY); } return REQ_READY_SEND; } /*! GET /api/<apikey>/userparameter \return REQ_READY_SEND REQ_NOT_HANDLED */ int DeRestPluginPrivate::getAllUserParameter(const ApiRequest &req, ApiResponse &rsp) { Q_UNUSED(req); if(!checkApikeyAuthentification(req, rsp)) { return REQ_READY_SEND; } rsp.httpStatus = HttpStatusOk; QVariantMap::const_iterator k = gwUserParameter.begin(); QVariantMap::const_iterator kend = gwUserParameter.end(); for (; k != kend; ++k) { rsp.map[k.key()] = gwUserParameter.value(k.key()); } if (rsp.map.isEmpty()) { rsp.str = "{}"; // return empty object } return REQ_READY_SEND; } /*! GET /api/<apikey>/userparameter/<parameter> \return REQ_READY_SEND REQ_NOT_HANDLED */ int DeRestPluginPrivate::getUserParameter(const ApiRequest &req, ApiResponse &rsp) { Q_UNUSED(req); if(!checkApikeyAuthentification(req, rsp)) { return REQ_READY_SEND; } DBG_Assert(req.path.size() == 4); if (req.path.size() != 4) { return -1; } const QString &key = req.path[3]; rsp.httpStatus = HttpStatusOk; if (gwUserParameter.contains(key)) { rsp.map[key] = gwUserParameter.value(key); } else { QVariantMap rspItem; QVariantMap rspItemState; rspItemState["/config/userparameter"] = QString("key %1 not found").arg(key); rspItem["error"] = rspItemState; rsp.list.append(rspItem); rsp.httpStatus = HttpStatusNotFound; } return REQ_READY_SEND; } /*! DELETE /api/<apikey>/userparameter/<parameter> \return REQ_READY_SEND REQ_NOT_HANDLED */ int DeRestPluginPrivate::deleteUserParameter(const ApiRequest &req, ApiResponse &rsp) { if(!checkApikeyAuthentification(req, rsp)) { return REQ_READY_SEND; } DBG_Assert(req.path.size() == 4); if (req.path.size() != 4) { return -1; } const QString &key = req.path[3]; QVariantMap rspItem; QVariantMap rspItemState; if (gwUserParameter.contains(key)) { gwUserParameter.remove(key); gwUserParameterToDelete.push_back(key); rspItemState["/config/userparameter"] = QString("key %1 removed").arg(key); rspItem["success"] = rspItemState; rsp.list.append(rspItem); rsp.httpStatus = HttpStatusOk; queSaveDb(DB_USERPARAM, DB_SHORT_SAVE_DELAY); } else { rspItemState["/config/userparameter"] = QString("key %1 not found").arg(key); rspItem["error"] = rspItemState; rsp.list.append(rspItem); rsp.httpStatus = HttpStatusNotFound; } return REQ_READY_SEND; } <commit_msg>Support PATCH method for userparameters<commit_after>/* * Copyright (c) 2016 dresden elektronik ingenieurtechnik gmbh. * All rights reserved. * * The software in this package is published under the terms of the BSD * style license a copy of which has been included with this distribution in * the LICENSE.txt file. * */ #include <QApplication> #include <QDesktopServices> #include <QString> #include <QTcpSocket> #include <QVariantMap> #include <QNetworkInterface> #include "de_web_plugin.h" #include "de_web_plugin_private.h" #include "json.h" #include <stdlib.h> /*! Configuration REST API broker. \param req - request data \param rsp - response data \return REQ_READY_SEND REQ_NOT_HANDLED */ int DeRestPluginPrivate::handleUserparameterApi(const ApiRequest &req, ApiResponse &rsp) { if (req.path[2] != QLatin1String("userparameter")) { return REQ_NOT_HANDLED; } // POST /api/<apikey>/userparameter/ if ((req.path.size() == 3) && (req.hdr.method() == "POST")) { return createUserParameter(req, rsp); } // POST /api/<apikey>/userparameter/<parameter> else if ((req.path.size() == 4) && (req.hdr.method() == "POST")) { return addUserParameter(req, rsp); } // PUT /api/<apikey>/userparameter/<parameter> else if ((req.path.size() == 4) && (req.hdr.method() == "PUT" || req.hdr.method() == "PATCH")) { return modifyUserParameter(req, rsp); } // GET /api/<apikey>/userparameter else if ((req.path.size() == 3) && (req.hdr.method() == "GET")) { return getAllUserParameter(req, rsp); } // GET /api/<apikey>/userparameter/<parameter> else if ((req.path.size() == 4) && (req.hdr.method() == "GET")) { return getUserParameter(req, rsp); } // DELETE /api/<apikey>/userparameter/<parameter> else if ((req.path.size() == 4) && (req.hdr.method() == "DELETE")) { return deleteUserParameter(req, rsp); } return REQ_NOT_HANDLED; } /*! POST /api/<apikey>/userparameter \return REQ_READY_SEND REQ_NOT_HANDLED */ int DeRestPluginPrivate::createUserParameter(const ApiRequest &req, ApiResponse &rsp) { if(!checkApikeyAuthentification(req, rsp)) { return REQ_READY_SEND; } if (req.content.isEmpty()) { rsp.list.append(errorToMap(ERR_INVALID_VALUE, QString("/userparameter"), QString("invalid value for userparameter"))); rsp.httpStatus = HttpStatusBadRequest; return REQ_READY_SEND; } rsp.httpStatus = HttpStatusOk; // generate id int i = 1; while (gwUserParameter.contains(QString::number(i))) { i++; } QString id = QString::number(i); QVariantMap rspItem; QVariantMap rspItemState; gwUserParameter.insert(id, req.content); rspItemState["id"] = id; rspItem["success"] = rspItemState; rsp.list.append(rspItem); queSaveDb(DB_USERPARAM, DB_SHORT_SAVE_DELAY); return REQ_READY_SEND; } /*! POST /api/<apikey>/userparameter/<parameter> \return REQ_READY_SEND REQ_NOT_HANDLED */ int DeRestPluginPrivate::addUserParameter(const ApiRequest &req, ApiResponse &rsp) { if(!checkApikeyAuthentification(req, rsp)) { return REQ_READY_SEND; } DBG_Assert(req.path.size() == 4); if (req.path.size() != 4) { return -1; } const QString &key = req.path[3]; rsp.httpStatus = HttpStatusOk; //don't overwrite existing parameters if POST request if (gwUserParameter.contains(key)) { rsp.httpStatus = HttpStatusBadRequest; rsp.list.append(errorToMap(ERR_DUPLICATE_EXIST , QString("config/userparameter"), QString("key %1 already exists").arg(key))); return REQ_READY_SEND; } QVariantMap rspItem; QVariantMap rspItemState; gwUserParameter.insert(key, req.content); rspItemState["/config/userparameter"] = QString("added new %1").arg(key); rspItem["success"] = rspItemState; rsp.list.append(rspItem); queSaveDb(DB_USERPARAM, DB_SHORT_SAVE_DELAY); return REQ_READY_SEND; } /*! PUT /api/<apikey>/userparameter/<parameter> \return REQ_READY_SEND REQ_NOT_HANDLED */ int DeRestPluginPrivate::modifyUserParameter(const ApiRequest &req, ApiResponse &rsp) { if(!checkApikeyAuthentification(req, rsp)) { return REQ_READY_SEND; } DBG_Assert(req.path.size() == 4); if (req.path.size() != 4) { return -1; } const QString &key = req.path[3]; rsp.httpStatus = HttpStatusOk; QVariantMap rspItem; QVariantMap rspItemState; //overwrite existing parameters if PUT request if (gwUserParameter.contains(key)) { QVariantMap::iterator it = gwUserParameter.find(key); if (*it != req.content) { gwUserParameter.erase(it); gwUserParameter.insert(key, req.content); queSaveDb(DB_USERPARAM, DB_SHORT_SAVE_DELAY); } rspItemState["/config/userparameter"] = QString("updated %1").arg(key); rspItem["success"] = rspItemState; rsp.list.append(rspItem); } else { gwUserParameter.insert(key, req.content); rspItemState["/config/userparameter"] = QString("added new %1").arg(key); rspItem["success"] = rspItemState; rsp.list.append(rspItem); queSaveDb(DB_USERPARAM, DB_SHORT_SAVE_DELAY); } return REQ_READY_SEND; } /*! GET /api/<apikey>/userparameter \return REQ_READY_SEND REQ_NOT_HANDLED */ int DeRestPluginPrivate::getAllUserParameter(const ApiRequest &req, ApiResponse &rsp) { Q_UNUSED(req); if(!checkApikeyAuthentification(req, rsp)) { return REQ_READY_SEND; } rsp.httpStatus = HttpStatusOk; QVariantMap::const_iterator k = gwUserParameter.begin(); QVariantMap::const_iterator kend = gwUserParameter.end(); for (; k != kend; ++k) { rsp.map[k.key()] = gwUserParameter.value(k.key()); } if (rsp.map.isEmpty()) { rsp.str = "{}"; // return empty object } return REQ_READY_SEND; } /*! GET /api/<apikey>/userparameter/<parameter> \return REQ_READY_SEND REQ_NOT_HANDLED */ int DeRestPluginPrivate::getUserParameter(const ApiRequest &req, ApiResponse &rsp) { Q_UNUSED(req); if(!checkApikeyAuthentification(req, rsp)) { return REQ_READY_SEND; } DBG_Assert(req.path.size() == 4); if (req.path.size() != 4) { return -1; } const QString &key = req.path[3]; rsp.httpStatus = HttpStatusOk; if (gwUserParameter.contains(key)) { rsp.map[key] = gwUserParameter.value(key); } else { QVariantMap rspItem; QVariantMap rspItemState; rspItemState["/config/userparameter"] = QString("key %1 not found").arg(key); rspItem["error"] = rspItemState; rsp.list.append(rspItem); rsp.httpStatus = HttpStatusNotFound; } return REQ_READY_SEND; } /*! DELETE /api/<apikey>/userparameter/<parameter> \return REQ_READY_SEND REQ_NOT_HANDLED */ int DeRestPluginPrivate::deleteUserParameter(const ApiRequest &req, ApiResponse &rsp) { if(!checkApikeyAuthentification(req, rsp)) { return REQ_READY_SEND; } DBG_Assert(req.path.size() == 4); if (req.path.size() != 4) { return -1; } const QString &key = req.path[3]; QVariantMap rspItem; QVariantMap rspItemState; if (gwUserParameter.contains(key)) { gwUserParameter.remove(key); gwUserParameterToDelete.push_back(key); rspItemState["/config/userparameter"] = QString("key %1 removed").arg(key); rspItem["success"] = rspItemState; rsp.list.append(rspItem); rsp.httpStatus = HttpStatusOk; queSaveDb(DB_USERPARAM, DB_SHORT_SAVE_DELAY); } else { rspItemState["/config/userparameter"] = QString("key %1 not found").arg(key); rspItem["error"] = rspItemState; rsp.list.append(rspItem); rsp.httpStatus = HttpStatusNotFound; } return REQ_READY_SEND; } <|endoftext|>
<commit_before>#ifndef WIN32 #pragma clang diagnostic ignored "-Wpotentially-evaluated-expression" #include <string> #include <catch.hpp> #include "chemfiles.hpp" #include "chemfiles/TrajectoryFactory.hpp" #include "chemfiles/Error.hpp" #include "chemfiles/formats/XYZ.hpp" #include "chemfiles/Frame.hpp" using namespace chemfiles; // Dummy format clase class DummyFormat : public Format { public: DummyFormat(File& file) : Format(file){} std::string description() const override {return "";} size_t nsteps() override {return 42;} }; // Dummy file clase class DummyFile : public BinaryFile { public: DummyFile(const std::string&, File::Mode) : BinaryFile("", File::READ) {} bool is_open() override {return true;} void sync() override {} }; class DummyFormat2 : public Format { public: DummyFormat2(File& file) : Format(file){} std::string description() const override {return "";} size_t nsteps() override {return 42;} using file_t = DummyFile; }; TEST_CASE("Registering a new format", "[Trajectory factory]"){ TrajectoryFactory::get().register_extension(".testing", {nullptr, nullptr}); // We can not register the same format twice CHECK_THROWS_AS( TrajectoryFactory::get().register_extension(".testing", {nullptr, nullptr}), FormatError ); TrajectoryFactory::get().register_format("Testing", {nullptr, nullptr}); // We can not register the same format twice CHECK_THROWS_AS( TrajectoryFactory::get().register_format("Testing", {nullptr, nullptr}), FormatError ); } TEST_CASE("Geting registered format", "[Trajectory factory]"){ TrajectoryFactory::get().register_extension(".dummy", {new_format<DummyFormat>, new_file<typename DummyFormat::file_t>}); TrajectoryFactory::get().register_format("Dummy", {new_format<DummyFormat>, new_file<typename DummyFormat::file_t>}); BasicFile file("tmp.dat", File::WRITE); DummyFormat dummy(file); auto format = TrajectoryFactory::get().by_extension(".dummy").format_creator(file); CHECK(typeid(dummy) == typeid(*format)); format = TrajectoryFactory::get().format("Dummy").format_creator(file); CHECK(typeid(dummy) == typeid(*format)); XYZFormat XYZ(file); format = TrajectoryFactory::get().by_extension(".xyz").format_creator(file); CHECK(typeid(XYZ) == typeid(*format)); format = TrajectoryFactory::get().format("XYZ").format_creator(file); CHECK(typeid(XYZ) == typeid(*format)); CHECK_THROWS_AS(TrajectoryFactory::get().format("UNKOWN"), FormatError); CHECK_THROWS_AS(TrajectoryFactory::get().by_extension(".UNKOWN"), FormatError); } TEST_CASE("Geting file type associated to a format", "[Trajectory factory]"){ TrajectoryFactory::get().register_extension(".dummy2", {new_format<DummyFormat2>, new_file<typename DummyFormat2::file_t>}); DummyFile dummy("", File::READ); auto file = TrajectoryFactory::get().by_extension(".dummy2").file_creator; CHECK(typeid(dummy) == typeid(*file("", File::READ))); } TEST_CASE("Check error throwing in formats", "[Format errors]"){ // Create a dummy file std::string filename = "test-file.dummy"; std::ofstream out(filename); out << "hey !" << std::endl; out.close(); Frame frame; Trajectory traj(filename, 'a'); CHECK_THROWS_AS(traj.read(), FormatError); CHECK_THROWS_AS(traj.read_step(2), FormatError); CHECK_THROWS_AS(traj.write(frame), FormatError); remove(filename.c_str()); } #endif <commit_msg>Don't ignore the factory test on WIN32<commit_after>#pragma clang diagnostic ignored "-Wpotentially-evaluated-expression" #include <string> #include <catch.hpp> #include "chemfiles.hpp" #include "chemfiles/TrajectoryFactory.hpp" #include "chemfiles/Error.hpp" #include "chemfiles/formats/XYZ.hpp" #include "chemfiles/Frame.hpp" using namespace chemfiles; // Dummy format clase class DummyFormat : public Format { public: DummyFormat(File& file) : Format(file){} std::string description() const override {return "";} size_t nsteps() override {return 42;} }; // Dummy file clase class DummyFile : public BinaryFile { public: DummyFile(const std::string&, File::Mode) : BinaryFile("", File::READ) {} bool is_open() override {return true;} void sync() override {} }; class DummyFormat2 : public Format { public: DummyFormat2(File& file) : Format(file){} std::string description() const override {return "";} size_t nsteps() override {return 42;} using file_t = DummyFile; }; TEST_CASE("Registering a new format", "[Trajectory factory]"){ TrajectoryFactory::get().register_extension(".testing", {nullptr, nullptr}); // We can not register the same format twice CHECK_THROWS_AS( TrajectoryFactory::get().register_extension(".testing", {nullptr, nullptr}), FormatError ); TrajectoryFactory::get().register_format("Testing", {nullptr, nullptr}); // We can not register the same format twice CHECK_THROWS_AS( TrajectoryFactory::get().register_format("Testing", {nullptr, nullptr}), FormatError ); } TEST_CASE("Geting registered format", "[Trajectory factory]"){ TrajectoryFactory::get().register_extension(".dummy", {new_format<DummyFormat>, new_file<typename DummyFormat::file_t>}); TrajectoryFactory::get().register_format("Dummy", {new_format<DummyFormat>, new_file<typename DummyFormat::file_t>}); BasicFile file("tmp.dat", File::WRITE); DummyFormat dummy(file); auto format = TrajectoryFactory::get().by_extension(".dummy").format_creator(file); CHECK(typeid(dummy) == typeid(*format)); format = TrajectoryFactory::get().format("Dummy").format_creator(file); CHECK(typeid(dummy) == typeid(*format)); XYZFormat XYZ(file); format = TrajectoryFactory::get().by_extension(".xyz").format_creator(file); CHECK(typeid(XYZ) == typeid(*format)); format = TrajectoryFactory::get().format("XYZ").format_creator(file); CHECK(typeid(XYZ) == typeid(*format)); CHECK_THROWS_AS(TrajectoryFactory::get().format("UNKOWN"), FormatError); CHECK_THROWS_AS(TrajectoryFactory::get().by_extension(".UNKOWN"), FormatError); } TEST_CASE("Geting file type associated to a format", "[Trajectory factory]"){ TrajectoryFactory::get().register_extension(".dummy2", {new_format<DummyFormat2>, new_file<typename DummyFormat2::file_t>}); DummyFile dummy("", File::READ); auto file = TrajectoryFactory::get().by_extension(".dummy2").file_creator; CHECK(typeid(dummy) == typeid(*file("", File::READ))); } TEST_CASE("Check error throwing in formats", "[Format errors]"){ // Create a dummy file std::string filename = "test-file.dummy"; std::ofstream out(filename); out << "hey !" << std::endl; out.close(); Frame frame; Trajectory traj(filename, 'a'); CHECK_THROWS_AS(traj.read(), FormatError); CHECK_THROWS_AS(traj.read_step(2), FormatError); CHECK_THROWS_AS(traj.write(frame), FormatError); remove(filename.c_str()); } <|endoftext|>
<commit_before>// // rule.cpp // Parse // // Created by Andrew Hunter on 30/04/2011. // Copyright 2011 __MyCompanyName__. All rights reserved. // #include "rule.h" #include "standard_items.h" using namespace contextfree; /// \brief Creates a copy of a rule rule::rule(const rule& copyFrom) : m_NonTerminal(copyFrom.m_NonTerminal) , m_Items(copyFrom.m_Items) { } /// \brief Creates a copy of a rule with an alternative nonterminal rule::rule(const rule& copyFrom, const item_container& nonTerminal) : m_NonTerminal(nonTerminal) , m_Items(copyFrom.m_Items) { } /// \brief Creates an empty rule, which reduces to the specified item rule::rule(const item_container& nonTerminal) : m_NonTerminal(nonTerminal) { } /// \brief Creates an empty rule with a nonterminal identifier rule::rule(const int nonTerminal) { contextfree::nonterminal nt(nonTerminal); m_NonTerminal = item_container(nt); } /// \brief Copies the content of a rule into this one rule& rule::operator=(const rule& copyFrom) { m_NonTerminal = copyFrom.m_NonTerminal; m_Items = copyFrom.m_Items; return *this; } /// \brief Orders this rule relative to another bool rule::operator<(const rule& compareTo) const { // Number of items is the fastest thing to compare, so check that first if (m_Items.size() < compareTo.m_Items.size()) return true; if (m_Items.size() > compareTo.m_Items.size()) return false; // The nonterminal should be reasonably fast to compare if (m_NonTerminal < compareTo.m_NonTerminal) return true; // Need to compare each item in turn item_list::const_iterator ourItem = m_Items.begin(); item_list::const_iterator theirItem = compareTo.begin(); for (;ourItem != m_Items.end() && theirItem != compareTo.end(); ourItem++, theirItem++) { if (*ourItem < *theirItem) return true; } return false; } /// \brief Determines if this rule is the same as another bool rule::operator==(const rule& compareTo) const { // Number of items is the fastest thing to compare, so check that first if (m_Items.size() != compareTo.m_Items.size()) return false; // The nonterminal should be reasonably fast to compare if (m_NonTerminal != compareTo.m_NonTerminal) return false; // Need to compare each item in turn item_list::const_iterator ourItem = m_Items.begin(); item_list::const_iterator theirItem = compareTo.begin(); for (;ourItem != m_Items.end() && theirItem != compareTo.end(); ourItem++, theirItem++) { if (*ourItem != *theirItem) return false; } return true; } /// \brief Appends the specified item to this rule rule& rule::operator<<(const item_container& item) { // Add this item to the list of items m_Items.push_back(item); return *this; } <commit_msg>Added a method for retrieving the identifier of a rule (with caching for perfomance)<commit_after>// // rule.cpp // Parse // // Created by Andrew Hunter on 30/04/2011. // Copyright 2011 __MyCompanyName__. All rights reserved. // #include "rule.h" #include "standard_items.h" using namespace contextfree; /// \brief Creates a copy of a rule rule::rule(const rule& copyFrom) : m_NonTerminal(copyFrom.m_NonTerminal) , m_Items(copyFrom.m_Items) { } /// \brief Creates a copy of a rule with an alternative nonterminal rule::rule(const rule& copyFrom, const item_container& nonTerminal) : m_NonTerminal(nonTerminal) , m_Items(copyFrom.m_Items) { } /// \brief Creates an empty rule, which reduces to the specified item rule::rule(const item_container& nonTerminal) : m_NonTerminal(nonTerminal) { } /// \brief Creates an empty rule with a nonterminal identifier rule::rule(const int nonTerminal) { contextfree::nonterminal nt(nonTerminal); m_NonTerminal = item_container(nt); } /// \brief Copies the content of a rule into this one rule& rule::operator=(const rule& copyFrom) { m_NonTerminal = copyFrom.m_NonTerminal; m_Items = copyFrom.m_Items; return *this; } /// \brief Orders this rule relative to another bool rule::operator<(const rule& compareTo) const { // Number of items is the fastest thing to compare, so check that first if (m_Items.size() < compareTo.m_Items.size()) return true; if (m_Items.size() > compareTo.m_Items.size()) return false; // The nonterminal should be reasonably fast to compare if (m_NonTerminal < compareTo.m_NonTerminal) return true; // Need to compare each item in turn item_list::const_iterator ourItem = m_Items.begin(); item_list::const_iterator theirItem = compareTo.begin(); for (;ourItem != m_Items.end() && theirItem != compareTo.end(); ourItem++, theirItem++) { if (*ourItem < *theirItem) return true; } return false; } /// \brief Determines if this rule is the same as another bool rule::operator==(const rule& compareTo) const { // Number of items is the fastest thing to compare, so check that first if (m_Items.size() != compareTo.m_Items.size()) return false; // The nonterminal should be reasonably fast to compare if (m_NonTerminal != compareTo.m_NonTerminal) return false; // Need to compare each item in turn item_list::const_iterator ourItem = m_Items.begin(); item_list::const_iterator theirItem = compareTo.begin(); for (;ourItem != m_Items.end() && theirItem != compareTo.end(); ourItem++, theirItem++) { if (*ourItem != *theirItem) return false; } return true; } /// \brief Appends the specified item to this rule rule& rule::operator<<(const item_container& item) { // Add this item to the list of items m_Items.push_back(item); return *this; } /// \brief Returns the identifier for this rule in the specified grammar int rule::identifier(const grammar& gram) const { if (&gram == m_LastGrammar) return m_Identifier; m_LastGrammar = &gram; return m_Identifier = gram.identifier_for_rule(*this); } <|endoftext|>
<commit_before>/* JcMess: A simple utility so save your jack-audio mess. Copyright (C) 2007-2010 Juan-Pablo Caceres. 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. */ /* * jcmess.cpp */ #include "jcmess.h" #include <stdlib.h> #include <fstream> #include <sstream> #include <sys/stat.h> #define SEPARATOR " -#- " //------------------------------------------------------------------------------- /*! \brief Constructs a JcMess object that has a jack client. * */ //------------------------------------------------------------------------------- JcMess::JcMess() { //Open a client connection to the JACK server. Starting a //new server only to list its ports seems pointless, so we //specify JackNoStartServer. mClient = jack_client_open ("lsp", JackNoStartServer, &mStatus); if (mClient == NULL) { if (mStatus & JackServerFailed) { cerr << "JACK server not running" << endl; } else { cerr << "jack_client_open() failed, " << "status = 0x%2.0x\n" << mStatus << endl; } exit(1); } } //------------------------------------------------------------------------------- /*! \brief Distructor closes the jcmess jack audio client. * */ //------------------------------------------------------------------------------- JcMess::~JcMess() { if (jack_client_close(mClient)) cerr << "ERROR: Could not close the hidden jcmess jack client." << endl; } //------------------------------------------------------------------------------- /*! \brief Write an XML file with the name specified at OutFile. * */ //------------------------------------------------------------------------------- // Function: fileExists /** Check if a file exists @param[in] filename - the name of the file to check @return true if the file exists, else false */ bool fileExists(const std::string& filename) { struct stat buf; if (stat(filename.c_str(), &buf) != -1) { return true; } return false; } void JcMess::writeOutput(string OutFile) { stringstream ss; vector<string> OutputInput(2); this->setConnectedPorts(); for (vector<vector<string> >::iterator it = mConnectedPorts.begin(); it != mConnectedPorts.end(); ++it) { OutputInput = *it; //cout << "Output ===> " << OutputInput[0] << endl; //cout << "Input ===> " << OutputInput[1] << endl; cout << OutputInput[0] << SEPARATOR << OutputInput[1] << endl; ss << OutputInput[0] << SEPARATOR << OutputInput[1] << endl; } ofstream file; file.clear(file.failbit); file.clear(file.badbit); //Write output file string answer = ""; //Check for existing file first, and confirm before overwriting if (fileExists(OutFile)) { while ((answer != "yes") && (answer != "no")) { cout << "WARNING: The File " << OutFile << " exists. Do you want to overwrite it? (yes/no): "; cin >> answer; } } else { answer = "yes"; } if (answer == "yes") { //file.open(OutFile.c_str(),fstream::out); file.open(OutFile.c_str()); if (file.fail()) { cerr << "Cannot open file for writing: " << endl; exit(1); } //TODO save the file file << ss.rdbuf(); file.close(); cout << OutFile << " written." << endl; } } //------------------------------------------------------------------------------- /*! \brief Set list of ouput ports that have connections. * */ //------------------------------------------------------------------------------- void JcMess::setConnectedPorts() { mConnectedPorts.clear(); const char **ports, **connections; //vector of ports and connections vector<string> OutputInput(2); //helper variable //Get active output ports. ports = jack_get_ports (mClient, NULL, NULL, JackPortIsOutput); for (unsigned int out_i = 0; ports[out_i]; ++out_i) { if ((connections = jack_port_get_all_connections (mClient, jack_port_by_name(mClient, ports[out_i]))) != 0) { for (unsigned int in_i = 0; connections[in_i]; ++in_i) { OutputInput[0] = ports[out_i]; //cout << "Output ===> " << OutputInput[0] << endl; OutputInput[1] = connections[in_i]; //cout << "Input ===> " << OutputInput[1] << endl; mConnectedPorts.push_back(OutputInput); } } } free(ports); } //------------------------------------------------------------------------------- /*! \brief Disconnect all the clients. * */ //------------------------------------------------------------------------------- void JcMess::disconnectAll() { vector<string> OutputInput(2); this->setConnectedPorts(); for (vector<vector<string> >::iterator it = mConnectedPorts.begin(); it != mConnectedPorts.end(); ++it) { OutputInput = *it; if (jack_disconnect(mClient, OutputInput[0].c_str(), OutputInput[1].c_str())) { cerr << "WARNING! port| " << OutputInput[0] << " |and port| " << OutputInput[1] << " |could not be disconnected.\n"; } } } //------------------------------------------------------------------------------- /*! \brief Parse the XML input file. * * Returns 0 on success, or 1 if the file has an incorrect format or cannot * read the file. */ //------------------------------------------------------------------------------- int JcMess::parseTextFile(string InFile) { mPortsToConnect.clear(); string errorStr; ifstream file; file.clear(file.failbit); file.clear(file.badbit); file.open(InFile.c_str()); if (file.fail()) { cerr << "Cannot open file for reading: " << endl; return 1; } vector<string> OutputInput(2); const string delimiter = SEPARATOR ; while (!file.eof()) { string line; getline(file,line); size_t pos = 0; pos = line.find(delimiter); OutputInput[0] = line.substr(0, pos); cout << OutputInput[0] << endl; line.erase(0, pos + delimiter.length()); OutputInput[1] = line ; mPortsToConnect.push_back(OutputInput); } file.close(); return 0; } //------------------------------------------------------------------------------- /*! \brief Connect ports specified in input XML file InFile * */ //------------------------------------------------------------------------------- void JcMess::connectPorts(string InFile) { vector<string> OutputInput(2); if ( !(this->parseTextFile(InFile)) ) { for (vector<vector<string> >::iterator it = mPortsToConnect.begin(); it != mPortsToConnect.end(); ++it) { OutputInput = *it; if (jack_connect(mClient, OutputInput[0].c_str(), OutputInput[1].c_str())) { //Display a warining only if the error is not because the ports are already //connected, in case the program doesn't display anyting. if (EEXIST != jack_connect(mClient, OutputInput[0].c_str(), OutputInput[1].c_str())) { cerr << "WARNING: port: " << OutputInput[0] << "and port: " << OutputInput[1] << " could not be connected.\n"; } } } } } <commit_msg>tested basic functionality for save/load jcmess file, will have to port other changes i have carried out from jmess 1.0.2.<commit_after>/* JcMess: A simple utility so save your jack-audio mess. Copyright (C) 2007-2010 Juan-Pablo Caceres. 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. */ /* * jcmess.cpp */ #include "jcmess.h" #include <stdlib.h> #include <fstream> #include <sstream> #include <sys/stat.h> #define SEPARATOR " -#- " //------------------------------------------------------------------------------- /*! \brief Constructs a JcMess object that has a jack client. * */ //------------------------------------------------------------------------------- JcMess::JcMess() { //Open a client connection to the JACK server. Starting a //new server only to list its ports seems pointless, so we //specify JackNoStartServer. mClient = jack_client_open ("lsp", JackNoStartServer, &mStatus); if (mClient == NULL) { if (mStatus & JackServerFailed) { cerr << "JACK server not running" << endl; } else { cerr << "jack_client_open() failed, " << "status = 0x%2.0x\n" << mStatus << endl; } exit(1); } } //------------------------------------------------------------------------------- /*! \brief Distructor closes the jcmess jack audio client. * */ //------------------------------------------------------------------------------- JcMess::~JcMess() { if (jack_client_close(mClient)) cerr << "ERROR: Could not close the hidden jcmess jack client." << endl; } //------------------------------------------------------------------------------- /*! \brief Write an XML file with the name specified at OutFile. * */ //------------------------------------------------------------------------------- // Function: fileExists /** Check if a file exists @param[in] filename - the name of the file to check @return true if the file exists, else false */ bool fileExists(const std::string& filename) { struct stat buf; if (stat(filename.c_str(), &buf) != -1) { return true; } return false; } void JcMess::writeOutput(string OutFile) { stringstream ss; vector<string> OutputInput(2); this->setConnectedPorts(); for (vector<vector<string> >::iterator it = mConnectedPorts.begin(); it != mConnectedPorts.end(); ++it) { OutputInput = *it; //cout << "Output ===> " << OutputInput[0] << endl; //cout << "Input ===> " << OutputInput[1] << endl; cout << OutputInput[0] << SEPARATOR << OutputInput[1] << endl; ss << OutputInput[0] << SEPARATOR << OutputInput[1] << endl; } ofstream file; file.clear(file.failbit); file.clear(file.badbit); //Write output file string answer = ""; //Check for existing file first, and confirm before overwriting if (fileExists(OutFile)) { while ((answer != "yes") && (answer != "no")) { cout << "WARNING: The File " << OutFile << " exists. Do you want to overwrite it? (yes/no): "; cin >> answer; } } else { answer = "yes"; } if (answer == "yes") { //file.open(OutFile.c_str(),fstream::out); file.open(OutFile.c_str()); if (file.fail()) { cerr << "Cannot open file for writing: " << endl; exit(1); } file << ss.rdbuf(); file.close(); cout << OutFile << " written." << endl; } } //------------------------------------------------------------------------------- /*! \brief Set list of ouput ports that have connections. * */ //------------------------------------------------------------------------------- void JcMess::setConnectedPorts() { mConnectedPorts.clear(); const char **ports, **connections; //vector of ports and connections vector<string> OutputInput(2); //helper variable //Get active output ports. ports = jack_get_ports (mClient, NULL, NULL, JackPortIsOutput); for (unsigned int out_i = 0; ports[out_i]; ++out_i) { if ((connections = jack_port_get_all_connections (mClient, jack_port_by_name(mClient, ports[out_i]))) != 0) { for (unsigned int in_i = 0; connections[in_i]; ++in_i) { OutputInput[0] = ports[out_i]; //cout << "Output ===> " << OutputInput[0] << endl; OutputInput[1] = connections[in_i]; //cout << "Input ===> " << OutputInput[1] << endl; mConnectedPorts.push_back(OutputInput); } } } free(ports); } //------------------------------------------------------------------------------- /*! \brief Disconnect all the clients. * */ //------------------------------------------------------------------------------- void JcMess::disconnectAll() { vector<string> OutputInput(2); this->setConnectedPorts(); for (vector<vector<string> >::iterator it = mConnectedPorts.begin(); it != mConnectedPorts.end(); ++it) { OutputInput = *it; if (jack_disconnect(mClient, OutputInput[0].c_str(), OutputInput[1].c_str())) { cerr << "WARNING! port| " << OutputInput[0] << " |and port| " << OutputInput[1] << " |could not be disconnected.\n"; } } } //------------------------------------------------------------------------------- /*! \brief Parse the XML input file. * * Returns 0 on success, or 1 if the file has an incorrect format or cannot * read the file. */ //------------------------------------------------------------------------------- int JcMess::parseTextFile(string InFile) { mPortsToConnect.clear(); string errorStr; ifstream file; file.clear(file.failbit); file.clear(file.badbit); file.open(InFile.c_str()); if (file.fail()) { cerr << "Cannot open file for reading: " << endl; return 1; } vector<string> OutputInput(2); const string delimiter = SEPARATOR ; //TODO add error checking in getline and string operations while (!file.eof()) { string line; getline(file,line); if (line.length() > 0) { size_t pos = 0; pos = line.find(delimiter); OutputInput[0] = line.substr(0, pos); line.erase(0, pos + delimiter.length()); OutputInput[1] = line ; mPortsToConnect.push_back(OutputInput); //cout << OutputInput[0] << endl; //cout << OutputInput[1] << endl; } } file.close(); //cout << "vec size = " << mPortsToConnect.size() << endl; return 0; } //------------------------------------------------------------------------------- /*! \brief Connect ports specified in input XML file InFile * */ //------------------------------------------------------------------------------- void JcMess::connectPorts(string InFile) { vector<string> OutputInput(2); if ( !(this->parseTextFile(InFile)) ) { for (vector<vector<string> >::iterator it = mPortsToConnect.begin(); it != mPortsToConnect.end(); ++it) { OutputInput = *it; //cout << "CON: " << OutputInput[0] << " <TO> " << OutputInput[1] << endl; if (jack_connect(mClient, OutputInput[0].c_str(), OutputInput[1].c_str())) { //Display a warining only if the error is not because the ports are already //connected, in case the program doesn't display anyting. if (EEXIST != jack_connect(mClient, OutputInput[0].c_str(), OutputInput[1].c_str())) { cerr << "WARNING: port: " << OutputInput[0] << "and port: " << OutputInput[1] << " could not be connected.\n"; } } } } } <|endoftext|>
<commit_before>/** * Distgen * Multi-threaded memory access pattern generator * * Every thread traverses its own nested series of arrays * with array sizes as specified. Array sizes correlate * to distances in a reuse distance histogram, and fit into * given layers (caches) of the memory hierarchy. * The idea is to approximate the access pattern of real codes. * * Compile with: * gcc -o distgen distgen.c distgen_internal.c -fopenmp -O3 * * Copyright 2016 by LRR-TUM * Jens Breitbart <[email protected]> * Josef Weidendorfer <[email protected]> * * Licensed under GNU Lesser General Public License 2.1 or later. * Some rights reserved. See LICENSE */ #include "distgen_internal.h" #include "distgend.h" #include <assert.h> #include <malloc.h> #include <stdio.h> #include <stdlib.h> #include <omp.h> static u64 clockFreq = 0; // assumed frequency for printing cycles static u64 iters_perstat = 0; static char *clockFreqDef = "2.4G"; static u64 toU64(char *s, int isSize) { u64 num = 0, denom = 1; u64 f = isSize ? 1024 : 1000; while ((*s >= '0') && (*s <= '9')) { num = 10 * num + (*s - '0'); s++; } if (*s == '.') { s++; while ((*s >= '0') && (*s <= '9')) { num = 10 * num + (*s - '0'); denom = 10 * denom; s++; } } if ((*s == 'k') || (*s == 'K')) num = num * f; else if ((*s == 'm') || (*s == 'M')) num = num * f * f; else if ((*s == 'g') || (*s == 'G')) num = num * f * f * f; num = num / denom; return num; } static void printStats(size_t ii, double tDiff, u64 rDiff, u64 wDiff) { u64 aDiff = rDiff + wDiff; double avg = tDiff * tcount / aDiff * 1000000000.0; double cTime = 1000.0 / clockFreq; fprintf(stderr, " at%5zu: ", ii); fprintf(stderr, " %5.3fs for %4.1f GB => %5.3f GB/s" " (per core: %6.3f GB/s)\n", tDiff, aDiff * 64.0 / 1000000000.0, aDiff * 64.0 / tDiff / 1000000000.0, aDiff * 64.0 / (tDiff * tcount) / 1000000000.0); if (verbose > 1) fprintf(stderr, " per access (%llu accesses): %.3f ns (%.1f cycles @ %.1f GHz)\n", aDiff, avg, avg / cTime, 1.0 / 1000.0 * clockFreq); } static size_t get_tcount() { static size_t tc = 0; if (tc > 0) return tc; #ifdef _OPENMP #pragma omp parallel #pragma omp master tc = (size_t)omp_get_num_threads(); #else tc = 1; #endif return tc; } __attribute__((noreturn)) static void usage(char *argv0) { fprintf(stderr, "Benchmark with threads accessing their own nested arrays at cache-line granularity\n\n" "Usage: %s [Options] [-<iter>] [<dist1> [<dist2> ... ]]\n" "\nParameters:\n" " <iter> number of times (iterations) accessing arrays (def: 1000)\n" " <dist1>, ... different reuse distances (def: 1 dist with 16MB)\n" "\nOptions:\n" " -h show this help\n" " -p use pseudo-random access pattern\n" " -d traversal by dependency chain\n" " -w write after read on each access\n" " -c <freq> clock frequency in Hz to show cycles per access (def: %s)\n" " -t <count> set number of threads to use (def: %zu)\n" " -s <iter> print perf.stats every few iterations (def: 0 = none)\n" " -v be verbose\n", argv0, clockFreqDef, get_tcount()); fprintf(stderr, "\nNumbers can end in k/m/g for Kilo/Mega/Giga factor\n"); exit(1); } // this sets global options void parseOptions(int argc, char *argv[]) { int arg; u64 dist; for (arg = 1; arg < argc; arg++) { if (argv[arg][0] == '-') { if (argv[arg][1] == 'h') usage(argv[0]); if (argv[arg][1] == 'v') { verbose++; continue; } if (argv[arg][1] == 'p') { pseudoRandom = 1; continue; } if (argv[arg][1] == 'd') { depChain = 1; continue; } if (argv[arg][1] == 'w') { doWrite = 1; continue; } if (argv[arg][1] == 'c') { if (arg + 1 < argc) { clockFreq = toU64(argv[arg + 1], 0); arg++; } continue; } if (argv[arg][1] == 't') { if (arg + 1 < argc) { tcount = atoi(argv[arg + 1]); arg++; } continue; } if (argv[arg][1] == 's') { if (arg + 1 < argc) { iters_perstat = toU64(argv[arg + 1], 0); arg++; } continue; } iter = (int)toU64(argv[arg] + 1, 0); if (iter == 0) { fprintf(stderr, "ERROR: expected iteration count, got '%s'\n", argv[arg] + 1); usage(argv[0]); } continue; } dist = toU64(argv[arg], 1); if (dist == 0) { fprintf(stderr, "ERROR: expected distance, got '%s'\n", argv[arg]); usage(argv[0]); } addDist(dist); } // set to defaults if values were not provided if (distsUsed == 0) addDist(16 * 1024 * 1024); if (iter == 0) iter = 1000; if (clockFreq == 0) clockFreq = toU64(clockFreqDef, 0); if (tcount == 0) { // thread count is the default as given by OpenMP runtime tcount = get_tcount(); } else { // overwrite thread count of OpenMP runtime #ifdef _OPENMP omp_set_num_threads(tcount); #else // compiled without OpenMP, cannot use more than 1 thread if (tcount > 1) { fprintf(stderr, "WARNING: OpenMP not available, running sequentially.\n"); tcount = 1; } #endif } if (iters_perstat == 0) { // no intermediate output iters_perstat = iter; } } int main(int argc, char *argv[]) { u64 aCount = 0, aCount1; double sum = 0.0; double tt, t1, t2; double avg, cTime, gData, gFlops, flopsPA; parseOptions(argc, argv); if (verbose) fprintf(stderr, "Multi-threaded Distance Generator (C) 2015 LRR-TUM\n"); //-------------------------- // Initialization //-------------------------- initBufs(); //-------------------------- // Run benchmark //-------------------------- fprintf(stderr, "Running %zu iterations, %zu thread(s) ...\n", iter, tcount); if (verbose) fprintf(stderr, " printing statistics every %llu iterations\n", iters_perstat); aCount = 0; tt = wtime(); t1 = tt; size_t ii = 0; // loop over chunks of iterations after which statistics are printed while (1) { aCount1 = aCount; #pragma omp parallel reduction(+ : sum) reduction(+ : aCount) { double tsum = 0.0; u64 taCount = 0; runBench(buffer[omp_get_thread_num()], iters_perstat, depChain, doWrite, &tsum, &taCount); sum += tsum; aCount += taCount; } t2 = wtime(); ii += iters_perstat; if (ii >= iter) break; printStats(ii, t2 - t1, aCount - aCount1, doWrite ? (aCount - aCount1) : 0); t1 = t2; } tt = t2 - tt; //-------------------------- // Summary //-------------------------- flopsPA = 1.0; if (doWrite) { aCount = 2 * aCount; flopsPA = .5; } avg = tt * tcount / aCount * 1000000000.0; cTime = 1000000000.0 / clockFreq; gData = aCount * 64.0 / 1024.0 / 1024.0 / 1024.0; gFlops = aCount * flopsPA / 1000000000.0; fprintf(stderr, "Summary: throughput %7.3f GB in %.3f s (per core: %.3f GB)\n", gData, tt, gData / tcount); fprintf(stderr, " bandwidth %7.3f GB/s (per core: %.3f GB/s)\n", gData / tt, gData / tt / tcount); fprintf(stderr, " GFlop/s %7.3f GF/s (per core: %.3f GF/s)\n", gFlops / tt, gFlops / tt / tcount); fprintf(stderr, " per acc. %7.3f ns (%.1f cycles @ %.2f GHz)\n", avg, avg / cTime, 1.0 / 1000000000.0 * clockFreq); if (verbose) fprintf(stderr, " accesses %llu, sum: %g\n", aCount, sum); return 0; } <commit_msg>Just some more C++.<commit_after>/** * Distgen * Multi-threaded memory access pattern generator * * Every thread traverses its own nested series of arrays * with array sizes as specified. Array sizes correlate * to distances in a reuse distance histogram, and fit into * given layers (caches) of the memory hierarchy. * The idea is to approximate the access pattern of real codes. * * Compile with: * gcc -o distgen distgen.c distgen_internal.c -fopenmp -O3 * * Copyright 2016 by LRR-TUM * Jens Breitbart <[email protected]> * Josef Weidendorfer <[email protected]> * * Licensed under GNU Lesser General Public License 2.1 or later. * Some rights reserved. See LICENSE */ #include "distgen_internal.h" #include "distgend.h" #include <cassert> #include <cstdio> #include <cstdlib> #include <omp.h> #include <malloc.h> static u64 clockFreq = 0; // assumed frequency for printing cycles static u64 iters_perstat = 0; static const char *clockFreqDef = "2.4G"; static u64 toU64(const char *s, int isSize) { u64 num = 0, denom = 1; u64 f = isSize ? 1024 : 1000; while ((*s >= '0') && (*s <= '9')) { num = 10 * num + (*s - '0'); s++; } if (*s == '.') { s++; while ((*s >= '0') && (*s <= '9')) { num = 10 * num + (*s - '0'); denom = 10 * denom; s++; } } if ((*s == 'k') || (*s == 'K')) num = num * f; else if ((*s == 'm') || (*s == 'M')) num = num * f * f; else if ((*s == 'g') || (*s == 'G')) num = num * f * f * f; num = num / denom; return num; } static void printStats(size_t ii, double tDiff, u64 rDiff, u64 wDiff) { u64 aDiff = rDiff + wDiff; double avg = tDiff * tcount / aDiff * 1000000000.0; double cTime = 1000.0 / clockFreq; fprintf(stderr, " at%5zu: ", ii); fprintf(stderr, " %5.3fs for %4.1f GB => %5.3f GB/s" " (per core: %6.3f GB/s)\n", tDiff, aDiff * 64.0 / 1000000000.0, aDiff * 64.0 / tDiff / 1000000000.0, aDiff * 64.0 / (tDiff * tcount) / 1000000000.0); if (verbose > 1) fprintf(stderr, " per access (%llu accesses): %.3f ns (%.1f cycles @ %.1f GHz)\n", aDiff, avg, avg / cTime, 1.0 / 1000.0 * clockFreq); } static size_t get_tcount() { static size_t tc = 0; if (tc > 0) return tc; #ifdef _OPENMP #pragma omp parallel #pragma omp master tc = (size_t)omp_get_num_threads(); #else tc = 1; #endif return tc; } __attribute__((noreturn)) static void usage(char *argv0) { fprintf(stderr, "Benchmark with threads accessing their own nested arrays at cache-line granularity\n\n" "Usage: %s [Options] [-<iter>] [<dist1> [<dist2> ... ]]\n" "\nParameters:\n" " <iter> number of times (iterations) accessing arrays (def: 1000)\n" " <dist1>, ... different reuse distances (def: 1 dist with 16MB)\n" "\nOptions:\n" " -h show this help\n" " -p use pseudo-random access pattern\n" " -d traversal by dependency chain\n" " -w write after read on each access\n" " -c <freq> clock frequency in Hz to show cycles per access (def: %s)\n" " -t <count> set number of threads to use (def: %zu)\n" " -s <iter> print perf.stats every few iterations (def: 0 = none)\n" " -v be verbose\n", argv0, clockFreqDef, get_tcount()); fprintf(stderr, "\nNumbers can end in k/m/g for Kilo/Mega/Giga factor\n"); exit(1); } // this sets global options void parseOptions(int argc, char *argv[]) { int arg; u64 dist; for (arg = 1; arg < argc; arg++) { if (argv[arg][0] == '-') { if (argv[arg][1] == 'h') usage(argv[0]); if (argv[arg][1] == 'v') { verbose++; continue; } if (argv[arg][1] == 'p') { pseudoRandom = 1; continue; } if (argv[arg][1] == 'd') { depChain = 1; continue; } if (argv[arg][1] == 'w') { doWrite = 1; continue; } if (argv[arg][1] == 'c') { if (arg + 1 < argc) { clockFreq = toU64(argv[arg + 1], 0); arg++; } continue; } if (argv[arg][1] == 't') { if (arg + 1 < argc) { tcount = atoi(argv[arg + 1]); arg++; } continue; } if (argv[arg][1] == 's') { if (arg + 1 < argc) { iters_perstat = toU64(argv[arg + 1], 0); arg++; } continue; } iter = (int)toU64(argv[arg] + 1, 0); if (iter == 0) { fprintf(stderr, "ERROR: expected iteration count, got '%s'\n", argv[arg] + 1); usage(argv[0]); } continue; } dist = toU64(argv[arg], 1); if (dist == 0) { fprintf(stderr, "ERROR: expected distance, got '%s'\n", argv[arg]); usage(argv[0]); } addDist(dist); } // set to defaults if values were not provided if (distsUsed == 0) addDist(16 * 1024 * 1024); if (iter == 0) iter = 1000; if (clockFreq == 0) clockFreq = toU64(clockFreqDef, 0); if (tcount == 0) { // thread count is the default as given by OpenMP runtime tcount = get_tcount(); } else { // overwrite thread count of OpenMP runtime #ifdef _OPENMP omp_set_num_threads(tcount); #else // compiled without OpenMP, cannot use more than 1 thread if (tcount > 1) { fprintf(stderr, "WARNING: OpenMP not available, running sequentially.\n"); tcount = 1; } #endif } if (iters_perstat == 0) { // no intermediate output iters_perstat = iter; } } int main(int argc, char *argv[]) { u64 aCount = 0, aCount1; double sum = 0.0; double tt, t1, t2; double avg, cTime, gData, gFlops, flopsPA; parseOptions(argc, argv); if (verbose) fprintf(stderr, "Multi-threaded Distance Generator (C) 2015 LRR-TUM\n"); //-------------------------- // Initialization //-------------------------- initBufs(); //-------------------------- // Run benchmark //-------------------------- fprintf(stderr, "Running %zu iterations, %zu thread(s) ...\n", iter, tcount); if (verbose) fprintf(stderr, " printing statistics every %llu iterations\n", iters_perstat); aCount = 0; tt = wtime(); t1 = tt; size_t ii = 0; // loop over chunks of iterations after which statistics are printed while (1) { aCount1 = aCount; #pragma omp parallel reduction(+ : sum) reduction(+ : aCount) { double tsum = 0.0; u64 taCount = 0; runBench(buffer[omp_get_thread_num()], iters_perstat, depChain, doWrite, &tsum, &taCount); sum += tsum; aCount += taCount; } t2 = wtime(); ii += iters_perstat; if (ii >= iter) break; printStats(ii, t2 - t1, aCount - aCount1, doWrite ? (aCount - aCount1) : 0); t1 = t2; } tt = t2 - tt; //-------------------------- // Summary //-------------------------- flopsPA = 1.0; if (doWrite) { aCount = 2 * aCount; flopsPA = .5; } avg = tt * tcount / aCount * 1000000000.0; cTime = 1000000000.0 / clockFreq; gData = aCount * 64.0 / 1024.0 / 1024.0 / 1024.0; gFlops = aCount * flopsPA / 1000000000.0; fprintf(stderr, "Summary: throughput %7.3f GB in %.3f s (per core: %.3f GB)\n", gData, tt, gData / tcount); fprintf(stderr, " bandwidth %7.3f GB/s (per core: %.3f GB/s)\n", gData / tt, gData / tt / tcount); fprintf(stderr, " GFlop/s %7.3f GF/s (per core: %.3f GF/s)\n", gFlops / tt, gFlops / tt / tcount); fprintf(stderr, " per acc. %7.3f ns (%.1f cycles @ %.2f GHz)\n", avg, avg / cTime, 1.0 / 1000000000.0 * clockFreq); if (verbose) fprintf(stderr, " accesses %llu, sum: %g\n", aCount, sum); return 0; } <|endoftext|>
<commit_before>/* Copyright (C) 2007 <SWGEmu> This File is part of Core3. This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Linking Engine3 statically or dynamically with other modules is making a combined work based on Engine3. Thus, the terms and conditions of the GNU Lesser General Public License cover the whole combination. In addition, as a special exception, the copyright holders of Engine3 give you permission to combine Engine3 program with free software programs or libraries that are released under the GNU LGPL and with code included in the standard release of Core3 under the GNU LGPL license (or modified versions of such code, with unchanged license). You may copy and distribute such a system following the terms of the GNU LGPL for Engine3 and the licenses of the other code concerned, provided that you include the source code of that other code when and as the GNU LGPL requires distribution of source code. Note that people who make modified versions of Engine3 are not obligated to grant this special exception for their modified versions; it is their choice whether to do so. The GNU Lesser General Public License gives permission to release a modified version without this exception; this exception also makes it possible to release a modified version which carries forward this exception. */ #include "LairObserver.h" #include "server/zone/objects/scene/ObserverEventType.h" #include "server/zone/objects/creature/NonPlayerCreatureObject.h" #include "server/zone/packets/object/PlayClientEffectObjectMessage.h" #include "server/zone/packets/scene/PlayClientEffectLocMessage.h" #include "server/zone/managers/player/PlayerManager.h" #include "server/zone/objects/tangible/weapon/WeaponObject.h" #include "server/zone/objects/tangible/threat/ThreatMap.h" #include "server/zone/Zone.h" #include "HealLairObserverEvent.h" #include "server/zone/managers/creature/CreatureManager.h" #include "server/zone/managers/templates/TemplateManager.h" #include "LairAggroTask.h" int LairObserverImplementation::notifyObserverEvent(unsigned int eventType, Observable* observable, ManagedObject* arg1, int64 arg2) { switch (eventType) { case ObserverEventType::OBJECTDESTRUCTION: notifyDestruction(cast<TangibleObject*>(observable), cast<TangibleObject*>(arg1), (int)arg2); return 1; break; case ObserverEventType::DAMAGERECEIVED: int livingCreatureCount = getLivingCreatureCount(); // if there are living creatures, make them aggro if(livingCreatureCount > 0 ){ Reference<LairAggroTask*> task = new LairAggroTask(cast<TangibleObject*>(observable), cast<TangibleObject*>(arg1), _this.get()); task->execute(); } // if new creatures have spawned or there are live creatures near the lair if( checkForNewSpawns(cast<TangibleObject*>(observable)) || livingCreatureCount > 0 ) checkForHeal(cast<TangibleObject*>(observable), cast<TangibleObject*>(arg1)); break; } return 0; } void LairObserverImplementation::notifyDestruction(TangibleObject* lair, TangibleObject* attacker, int condition) { ThreatMap* threatMap = lair->getThreatMap(); ThreatMap copyThreatMap(*threatMap); threatMap->removeObservers(); threatMap->removeAll(); // we can clear the original one if (lair->getZone() == NULL) { spawnedCreatures.removeAll(); return; } PlayClientEffectObjectMessage* explode = new PlayClientEffectObjectMessage(lair, "clienteffect/lair_damage_heavy.cef", ""); lair->broadcastMessage(explode, false); PlayClientEffectLoc* explodeLoc = new PlayClientEffectLoc("clienteffect/lair_damage_heavy.cef", lair->getZone()->getZoneName(), lair->getPositionX(), lair->getPositionZ(), lair->getPositionY()); lair->broadcastMessage(explodeLoc, false); lair->destroyObjectFromWorld(true); for (int i = 0; i < spawnedCreatures.size(); ++i) { CreatureObject* obj = spawnedCreatures.get(i); if (obj->isAiAgent()) (cast<AiAgent*>(obj))->setDespawnOnNoPlayerInRange(true); } spawnedCreatures.removeAll(); PlayerManager* playerManager = lair->getZoneServer()->getPlayerManager(); playerManager->disseminateExperience(lair, &copyThreatMap); } void LairObserverImplementation::doAggro(TangibleObject* lair, TangibleObject* attacker){ for (int i = 0; i < spawnedCreatures.size() ; ++i) { CreatureObject* creo = spawnedCreatures.get(i); if (creo->isDead() || creo->getZone() == NULL) continue; if (creo->isAiAgent() && (System::random(1) == 1) && attacker != NULL) { // TODO: only set defender if needed AiAgent* ai = cast<AiAgent*>( creo); Locker clocker(creo, lair); creo->setDefender(attacker); } } } void LairObserverImplementation::checkForHeal(TangibleObject* lair, TangibleObject* attacker, bool forceNewUpdate) { if (lair->isDestroyed() || getLairType() == LairTemplate::NPC) return; if (!(getLivingCreatureCount() > 0 && lair->getConditionDamage() > 0)) return; if (healLairEvent == NULL) { healLairEvent = new HealLairObserverEvent(lair, attacker, _this.get()); healLairEvent->schedule(1000); } else if (!healLairEvent->isScheduled()) { healLairEvent->schedule(1000); } else if (attacker != NULL) healLairEvent->setAttacker(attacker); } void LairObserverImplementation::healLair(TangibleObject* lair, TangibleObject* attacker){ Locker locker(lair); if (lair->getZone() == NULL) return; int damageToHeal = 0; for (int i = 0; i < spawnedCreatures.size() ; ++i) { CreatureObject* creo = spawnedCreatures.get(i); if (creo->isDead() || creo->getZone() == NULL) continue; // TODO: Range check damageToHeal += 100; } if (damageToHeal == 0) return; if (lair->getZone() == NULL) return; lair->healDamage(lair, 0, damageToHeal, true); PlayClientEffectObjectMessage* heal = new PlayClientEffectObjectMessage(lair, "clienteffect/healing_healdamage.cef", ""); lair->broadcastMessage(heal, false); PlayClientEffectLoc* healLoc = new PlayClientEffectLoc("clienteffect/healing_healdamage.cef", lair->getZone()->getZoneName(), lair->getPositionX(), lair->getPositionZ(), lair->getPositionY()); lair->broadcastMessage(healLoc, false); } bool LairObserverImplementation::checkForNewSpawns(TangibleObject* lair, bool forceSpawn) { if (lair->getZone() == NULL) return false; if (spawnedCreatures.size() >= lairTemplate->getSpawnLimit()) return false; if (forceSpawn) { spawnNumber++; } else if (lairTemplate->getLairType() == LairTemplate::NPC) { return false; } else { int conditionDamage = lair->getConditionDamage(); int maxCondition = lair->getMaxCondition(); switch (spawnNumber) { case 0: spawnNumber++; break; case 1: if (conditionDamage > (maxCondition / 4)) { spawnNumber++; } else { return false; } break; case 2: if (conditionDamage > (maxCondition / 2)) { spawnNumber++; } else { return false; } break; case 3: return false; break; } } //SortedVector<uint32>* objectsToSpawn = getObjectsToSpawn(); VectorMap<String, int>* objectsToSpawn = lairTemplate->getMobiles(); int amountToSpawn = 0; if (lairTemplate->getLairType() == LairTemplate::CREATURE) { amountToSpawn = System::random(3) + ((lairTemplate->getSpawnLimit() / 3) - 2); } else { amountToSpawn = System::random(lairTemplate->getSpawnLimit() / 2) + (lairTemplate->getSpawnLimit() / 2); } if (amountToSpawn < 1) amountToSpawn = 1; for(int i = 0; i < amountToSpawn; ++i) { if (spawnedCreatures.size() >= lairTemplate->getSpawnLimit()) return true; String templateToSpawn = objectsToSpawn->elementAt((int)System::random(objectsToSpawn->size() - 1)).getKey(); CreatureManager* creatureManager = lair->getZone()->getCreatureManager(); float x = lair->getPositionX() + (20.0f - System::random(400) / 10.0f); float y = lair->getPositionY() + (20.0f - System::random(400) / 10.0f); float z = lair->getZone()->getHeight(x, y); int levelDiff = objectsToSpawn->get(templateToSpawn); ManagedReference<CreatureObject*> creature = creatureManager->spawnCreatureWithLevel(templateToSpawn.hashCode(), difficulty + levelDiff, x, z, y); if (creature == NULL) return true; if (!creature->isAiAgent()) { error("spawned non player creature with template " + templateToSpawn); } else { AiAgent* npc = cast<AiAgent*>( creature.get()); //Locker clocker(npc, lair); npc->setDespawnOnNoPlayerInRange(false); npc->setHomeLocation(x, z, y); npc->setRespawnTimer(0); spawnedCreatures.add(creature); } } return amountToSpawn > 0; } <commit_msg>[Changed] The amount that creatures heal their lair for to be based on the level of the lair instead of a static amount<commit_after>/* Copyright (C) 2007 <SWGEmu> This File is part of Core3. This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Linking Engine3 statically or dynamically with other modules is making a combined work based on Engine3. Thus, the terms and conditions of the GNU Lesser General Public License cover the whole combination. In addition, as a special exception, the copyright holders of Engine3 give you permission to combine Engine3 program with free software programs or libraries that are released under the GNU LGPL and with code included in the standard release of Core3 under the GNU LGPL license (or modified versions of such code, with unchanged license). You may copy and distribute such a system following the terms of the GNU LGPL for Engine3 and the licenses of the other code concerned, provided that you include the source code of that other code when and as the GNU LGPL requires distribution of source code. Note that people who make modified versions of Engine3 are not obligated to grant this special exception for their modified versions; it is their choice whether to do so. The GNU Lesser General Public License gives permission to release a modified version without this exception; this exception also makes it possible to release a modified version which carries forward this exception. */ #include "LairObserver.h" #include "server/zone/objects/scene/ObserverEventType.h" #include "server/zone/objects/creature/NonPlayerCreatureObject.h" #include "server/zone/packets/object/PlayClientEffectObjectMessage.h" #include "server/zone/packets/scene/PlayClientEffectLocMessage.h" #include "server/zone/managers/player/PlayerManager.h" #include "server/zone/objects/tangible/weapon/WeaponObject.h" #include "server/zone/objects/tangible/threat/ThreatMap.h" #include "server/zone/Zone.h" #include "HealLairObserverEvent.h" #include "server/zone/managers/creature/CreatureManager.h" #include "server/zone/managers/templates/TemplateManager.h" #include "LairAggroTask.h" int LairObserverImplementation::notifyObserverEvent(unsigned int eventType, Observable* observable, ManagedObject* arg1, int64 arg2) { switch (eventType) { case ObserverEventType::OBJECTDESTRUCTION: notifyDestruction(cast<TangibleObject*>(observable), cast<TangibleObject*>(arg1), (int)arg2); return 1; break; case ObserverEventType::DAMAGERECEIVED: int livingCreatureCount = getLivingCreatureCount(); // if there are living creatures, make them aggro if(livingCreatureCount > 0 ){ Reference<LairAggroTask*> task = new LairAggroTask(cast<TangibleObject*>(observable), cast<TangibleObject*>(arg1), _this.get()); task->execute(); } // if new creatures have spawned or there are live creatures near the lair if( checkForNewSpawns(cast<TangibleObject*>(observable)) || livingCreatureCount > 0 ) checkForHeal(cast<TangibleObject*>(observable), cast<TangibleObject*>(arg1)); break; } return 0; } void LairObserverImplementation::notifyDestruction(TangibleObject* lair, TangibleObject* attacker, int condition) { ThreatMap* threatMap = lair->getThreatMap(); ThreatMap copyThreatMap(*threatMap); threatMap->removeObservers(); threatMap->removeAll(); // we can clear the original one if (lair->getZone() == NULL) { spawnedCreatures.removeAll(); return; } PlayClientEffectObjectMessage* explode = new PlayClientEffectObjectMessage(lair, "clienteffect/lair_damage_heavy.cef", ""); lair->broadcastMessage(explode, false); PlayClientEffectLoc* explodeLoc = new PlayClientEffectLoc("clienteffect/lair_damage_heavy.cef", lair->getZone()->getZoneName(), lair->getPositionX(), lair->getPositionZ(), lair->getPositionY()); lair->broadcastMessage(explodeLoc, false); lair->destroyObjectFromWorld(true); for (int i = 0; i < spawnedCreatures.size(); ++i) { CreatureObject* obj = spawnedCreatures.get(i); if (obj->isAiAgent()) (cast<AiAgent*>(obj))->setDespawnOnNoPlayerInRange(true); } spawnedCreatures.removeAll(); PlayerManager* playerManager = lair->getZoneServer()->getPlayerManager(); playerManager->disseminateExperience(lair, &copyThreatMap); } void LairObserverImplementation::doAggro(TangibleObject* lair, TangibleObject* attacker){ for (int i = 0; i < spawnedCreatures.size() ; ++i) { CreatureObject* creo = spawnedCreatures.get(i); if (creo->isDead() || creo->getZone() == NULL) continue; if (creo->isAiAgent() && (System::random(1) == 1) && attacker != NULL) { // TODO: only set defender if needed AiAgent* ai = cast<AiAgent*>( creo); Locker clocker(creo, lair); creo->setDefender(attacker); } } } void LairObserverImplementation::checkForHeal(TangibleObject* lair, TangibleObject* attacker, bool forceNewUpdate) { if (lair->isDestroyed() || getLairType() == LairTemplate::NPC) return; if (!(getLivingCreatureCount() > 0 && lair->getConditionDamage() > 0)) return; if (healLairEvent == NULL) { healLairEvent = new HealLairObserverEvent(lair, attacker, _this.get()); healLairEvent->schedule(1000); } else if (!healLairEvent->isScheduled()) { healLairEvent->schedule(1000); } else if (attacker != NULL) healLairEvent->setAttacker(attacker); } void LairObserverImplementation::healLair(TangibleObject* lair, TangibleObject* attacker){ Locker locker(lair); if (lair->getZone() == NULL) return; int damageToHeal = 0; int lairMaxCondition = lair->getMaxCondition(); for (int i = 0; i < spawnedCreatures.size() ; ++i) { CreatureObject* creo = spawnedCreatures.get(i); if (creo->isDead() || creo->getZone() == NULL) continue; // TODO: Range check damageToHeal += lairMaxCondition / 100; } if (damageToHeal == 0) return; if (lair->getZone() == NULL) return; lair->healDamage(lair, 0, damageToHeal, true); PlayClientEffectObjectMessage* heal = new PlayClientEffectObjectMessage(lair, "clienteffect/healing_healdamage.cef", ""); lair->broadcastMessage(heal, false); PlayClientEffectLoc* healLoc = new PlayClientEffectLoc("clienteffect/healing_healdamage.cef", lair->getZone()->getZoneName(), lair->getPositionX(), lair->getPositionZ(), lair->getPositionY()); lair->broadcastMessage(healLoc, false); } bool LairObserverImplementation::checkForNewSpawns(TangibleObject* lair, bool forceSpawn) { if (lair->getZone() == NULL) return false; if (spawnedCreatures.size() >= lairTemplate->getSpawnLimit()) return false; if (forceSpawn) { spawnNumber++; } else if (lairTemplate->getLairType() == LairTemplate::NPC) { return false; } else { int conditionDamage = lair->getConditionDamage(); int maxCondition = lair->getMaxCondition(); switch (spawnNumber) { case 0: spawnNumber++; break; case 1: if (conditionDamage > (maxCondition / 4)) { spawnNumber++; } else { return false; } break; case 2: if (conditionDamage > (maxCondition / 2)) { spawnNumber++; } else { return false; } break; case 3: return false; break; } } //SortedVector<uint32>* objectsToSpawn = getObjectsToSpawn(); VectorMap<String, int>* objectsToSpawn = lairTemplate->getMobiles(); int amountToSpawn = 0; if (lairTemplate->getLairType() == LairTemplate::CREATURE) { amountToSpawn = System::random(3) + ((lairTemplate->getSpawnLimit() / 3) - 2); } else { amountToSpawn = System::random(lairTemplate->getSpawnLimit() / 2) + (lairTemplate->getSpawnLimit() / 2); } if (amountToSpawn < 1) amountToSpawn = 1; for(int i = 0; i < amountToSpawn; ++i) { if (spawnedCreatures.size() >= lairTemplate->getSpawnLimit()) return true; String templateToSpawn = objectsToSpawn->elementAt((int)System::random(objectsToSpawn->size() - 1)).getKey(); CreatureManager* creatureManager = lair->getZone()->getCreatureManager(); float x = lair->getPositionX() + (20.0f - System::random(400) / 10.0f); float y = lair->getPositionY() + (20.0f - System::random(400) / 10.0f); float z = lair->getZone()->getHeight(x, y); int levelDiff = objectsToSpawn->get(templateToSpawn); ManagedReference<CreatureObject*> creature = creatureManager->spawnCreatureWithLevel(templateToSpawn.hashCode(), difficulty + levelDiff, x, z, y); if (creature == NULL) return true; if (!creature->isAiAgent()) { error("spawned non player creature with template " + templateToSpawn); } else { AiAgent* npc = cast<AiAgent*>( creature.get()); //Locker clocker(npc, lair); npc->setDespawnOnNoPlayerInRange(false); npc->setHomeLocation(x, z, y); npc->setRespawnTimer(0); spawnedCreatures.add(creature); } } return amountToSpawn > 0; } <|endoftext|>
<commit_before>/* * VehicleObjectImplementation.cpp * * Created on: 10/04/2010 * Author: victor */ #include "server/zone/objects/creature/VehicleObject.h" #include "server/zone/packets/object/ObjectMenuResponse.h" #include "server/zone/objects/creature/CreatureObject.h" #include "server/zone/objects/player/PlayerObject.h" #include "server/zone/objects/intangible/VehicleControlDevice.h" #include "server/zone/objects/building/BuildingObject.h" #include "server/zone/Zone.h" #include "server/zone/objects/player/sui/listbox/SuiListBox.h" #include "server/zone/managers/planet/PlanetManager.h" #include "server/zone/managers/structure/StructureManager.h" #include "server/zone/objects/area/ActiveArea.h" #include "server/zone/objects/region/CityRegion.h" #include "server/zone/objects/creature/sui/RepairVehicleSuiCallback.h" #include "server/zone/objects/region/CityRegion.h" #include "server/zone/templates/customization/AssetCustomizationManagerTemplate.h" void VehicleObjectImplementation::fillObjectMenuResponse(ObjectMenuResponse* menuResponse, CreatureObject* player) { if (!player->getPlayerObject()->isPrivileged() && linkedCreature != player) return; menuResponse->addRadialMenuItem(205, 1, "@pet/pet_menu:menu_enter_exit"); menuResponse->addRadialMenuItem(61, 3, ""); if (player->getPlayerObject()->isPrivileged() || (checkInRangeGarage() && !isDestroyed())) menuResponse->addRadialMenuItem(62, 3, "@pet/pet_menu:menu_repair_vehicle"); //Repair Vehicle } void VehicleObjectImplementation::fillAttributeList(AttributeListMessage* msg, CreatureObject* object){ ManagedReference<CreatureObject* > linkedCreature = this->linkedCreature.get(); if( linkedCreature == NULL ) return; msg->insertAttribute("@obj_attr_n:owner", linkedCreature->getFirstName()); } void VehicleObjectImplementation::notifyInsertToZone(Zone* zone) { SceneObjectImplementation::notifyInsertToZone(zone); if( this->linkedCreature == NULL ) return; ManagedReference<CreatureObject* > linkedCreature = this->linkedCreature.get(); if( linkedCreature == NULL ) return; // Decay customized paint (if any) if (paintCount > 0){ // Paint starts to fade when there are 4 calls left if (paintCount <= 4){ // Send player notification of decay if( paintCount == 1 ){ linkedCreature->sendSystemMessage("@pet/pet_menu:customization_gone_veh"); // "Your vehicle's customization has completely faded away." } else{ linkedCreature->sendSystemMessage("@pet/pet_menu:customization_fading_veh"); // "Your vehicle's customization is fading away." } // Fade color to white String appearanceFilename = getObjectTemplate()->getAppearanceFilename(); VectorMap<String, Reference<CustomizationVariable*> > variables; AssetCustomizationManagerTemplate::instance()->getCustomizationVariables(appearanceFilename.hashCode(), variables, false); for(int i = 0; i< variables.size(); ++i){ String varkey = variables.elementAt(i).getKey(); if (varkey.contains("color")){ setCustomizationVariable(varkey, paintCount-1, true); // Palette values 3,2,1,0 are grey->white } } } --paintCount; } } bool VehicleObjectImplementation::checkInRangeGarage() { ManagedReference<SceneObject*> garage = StructureManager::instance()->getInRangeParkingGarage(_this.get()); if (garage == NULL) return false; return true; } int VehicleObjectImplementation::handleObjectMenuSelect(CreatureObject* player, byte selectedID) { if (selectedID == 61 && linkedCreature == player) { unlock(); try { ManagedReference<ControlDevice* > strongRef = controlDevice.get(); if (strongRef != NULL) strongRef->storeObject(player); } catch (Exception& e) { } catch (...) { wlock(player); throw; } wlock(player); } else if (selectedID == 62) { repairVehicle(player); } return 0; } void VehicleObjectImplementation::repairVehicle(CreatureObject* player) { if (!player->getPlayerObject()->isPrivileged()) { //Need to check if they are city banned. ManagedReference<ActiveArea*> activeArea = getActiveRegion(); if (activeArea != NULL && activeArea->isRegion()) { Region* region = cast<Region*>( activeArea.get()); ManagedReference<CityRegion*> gb = region->getCityRegion(); if (gb == NULL) return; if (gb->isBanned(player->getObjectID())) { player->sendSystemMessage("@city/city:garage_banned"); //You are city banned and cannot use this garage. return; } if (getConditionDamage() == 0) { player->sendSystemMessage("@pet/pet_menu:undamaged_vehicle"); //The targeted vehicle does not require any repairs at the moment. return; } if (isDestroyed()) { player->sendSystemMessage("@pet/pet_menu:cannot_repair_disabled"); //You may not repair a disabled vehicle. return; } if (!checkInRangeGarage()) { player->sendSystemMessage("@pet/pet_menu:repair_unrecognized_garages"); //Your vehicle does not recognize any local garages. Try again in a garage repair zone. return; } } } sendRepairConfirmTo(player); } void VehicleObjectImplementation::sendRepairConfirmTo(CreatureObject* player) { ManagedReference<SuiListBox*> listbox = new SuiListBox(player, SuiWindowType::GARAGE_REPAIR); listbox->setCallback(new RepairVehicleSuiCallback(server->getZoneServer())); listbox->setPromptTitle("@pet/pet_menu:confirm_repairs_t"); //Confirm Vehicle Repairs listbox->setPromptText("@pet/pet_menu:vehicle_repair_d"); //You have chosen to repair your vehicle. Please review the listed details and confirm your selection. listbox->setUsingObject(_this.get()); listbox->setCancelButton(true, "@cancel"); int repairCost = calculateRepairCost(player); int totalFunds = player->getBankCredits(); int tax = 0; ManagedReference<CityRegion*> city = getCityRegion(); if(city != NULL && city->getGarageTax() > 0){ repairCost += repairCost * city->getGarageTax() / 100; } listbox->addMenuItem("@pet/pet_menu:vehicle_prompt " + getDisplayedName()); //Vehicle: listbox->addMenuItem("@pet/pet_menu:repair_cost_prompt " + String::valueOf(repairCost)); //Repair Cost: listbox->addMenuItem("@pet/pet_menu:total_funds_prompt " + String::valueOf(totalFunds)); //Total Funds Available: player->getPlayerObject()->addSuiBox(listbox); player->sendMessage(listbox->generateMessage()); } int VehicleObjectImplementation::calculateRepairCost(CreatureObject* player) { if (player->getPlayerObject()->isPrivileged()) return 0; return getConditionDamage() * 5; } int VehicleObjectImplementation::inflictDamage(TangibleObject* attacker, int damageType, float damage, bool destroy, bool notifyClient) { return TangibleObjectImplementation::inflictDamage(attacker, damageType, damage, destroy, notifyClient); } int VehicleObjectImplementation::inflictDamage(TangibleObject* attacker, int damageType, float damage, bool destroy, const String& xp, bool notifyClient) { return TangibleObjectImplementation::inflictDamage(attacker, damageType, damage, destroy, xp, notifyClient); } int VehicleObjectImplementation::healDamage(TangibleObject* healer, int damageType, int damage, bool notifyClient) { return TangibleObjectImplementation::healDamage(healer, damageType, damage, notifyClient); } int VehicleObjectImplementation::notifyObjectDestructionObservers(TangibleObject* attacker, int condition) { unlock(); ManagedReference<CreatureObject* > linkedCreature = this->linkedCreature.get(); if (linkedCreature != NULL) { linkedCreature->sendSystemMessage("@pet/pet_menu:veh_disabled"); try { if (attacker != _this.get()) { Locker clocker(linkedCreature, attacker); linkedCreature->executeObjectControllerAction(String("dismount").hashCode()); } else { Locker locker(linkedCreature); linkedCreature->executeObjectControllerAction(String("dismount").hashCode()); } } catch (Exception& e) { } } if (attacker != _this.get()) wlock(attacker); else wlock(); return CreatureObjectImplementation::notifyObjectDestructionObservers(attacker, condition); } void VehicleObjectImplementation::sendMessage(BasePacket* msg) { ManagedReference<CreatureObject* > linkedCreature = this->linkedCreature.get(); if (linkedCreature != NULL && linkedCreature->getParent().get() == _this.get()) linkedCreature->sendMessage(msg); else delete msg; } <commit_msg>[Fixed] Vehicle repair prices 0002611<commit_after>/* * VehicleObjectImplementation.cpp * * Created on: 10/04/2010 * Author: victor */ #include "server/zone/objects/creature/VehicleObject.h" #include "server/zone/packets/object/ObjectMenuResponse.h" #include "server/zone/objects/creature/CreatureObject.h" #include "server/zone/objects/player/PlayerObject.h" #include "server/zone/objects/intangible/VehicleControlDevice.h" #include "server/zone/objects/building/BuildingObject.h" #include "server/zone/Zone.h" #include "server/zone/objects/player/sui/listbox/SuiListBox.h" #include "server/zone/managers/planet/PlanetManager.h" #include "server/zone/managers/structure/StructureManager.h" #include "server/zone/objects/area/ActiveArea.h" #include "server/zone/objects/region/CityRegion.h" #include "server/zone/objects/creature/sui/RepairVehicleSuiCallback.h" #include "server/zone/objects/region/CityRegion.h" #include "server/zone/templates/customization/AssetCustomizationManagerTemplate.h" void VehicleObjectImplementation::fillObjectMenuResponse(ObjectMenuResponse* menuResponse, CreatureObject* player) { if (!player->getPlayerObject()->isPrivileged() && linkedCreature != player) return; menuResponse->addRadialMenuItem(205, 1, "@pet/pet_menu:menu_enter_exit"); menuResponse->addRadialMenuItem(61, 3, ""); if (player->getPlayerObject()->isPrivileged() || (checkInRangeGarage() && !isDestroyed())) menuResponse->addRadialMenuItem(62, 3, "@pet/pet_menu:menu_repair_vehicle"); //Repair Vehicle } void VehicleObjectImplementation::fillAttributeList(AttributeListMessage* msg, CreatureObject* object){ ManagedReference<CreatureObject* > linkedCreature = this->linkedCreature.get(); if( linkedCreature == NULL ) return; msg->insertAttribute("@obj_attr_n:owner", linkedCreature->getFirstName()); } void VehicleObjectImplementation::notifyInsertToZone(Zone* zone) { SceneObjectImplementation::notifyInsertToZone(zone); if( this->linkedCreature == NULL ) return; ManagedReference<CreatureObject* > linkedCreature = this->linkedCreature.get(); if( linkedCreature == NULL ) return; // Decay customized paint (if any) if (paintCount > 0){ // Paint starts to fade when there are 4 calls left if (paintCount <= 4){ // Send player notification of decay if( paintCount == 1 ){ linkedCreature->sendSystemMessage("@pet/pet_menu:customization_gone_veh"); // "Your vehicle's customization has completely faded away." } else{ linkedCreature->sendSystemMessage("@pet/pet_menu:customization_fading_veh"); // "Your vehicle's customization is fading away." } // Fade color to white String appearanceFilename = getObjectTemplate()->getAppearanceFilename(); VectorMap<String, Reference<CustomizationVariable*> > variables; AssetCustomizationManagerTemplate::instance()->getCustomizationVariables(appearanceFilename.hashCode(), variables, false); for(int i = 0; i< variables.size(); ++i){ String varkey = variables.elementAt(i).getKey(); if (varkey.contains("color")){ setCustomizationVariable(varkey, paintCount-1, true); // Palette values 3,2,1,0 are grey->white } } } --paintCount; } } bool VehicleObjectImplementation::checkInRangeGarage() { ManagedReference<SceneObject*> garage = StructureManager::instance()->getInRangeParkingGarage(_this.get()); if (garage == NULL) return false; return true; } int VehicleObjectImplementation::handleObjectMenuSelect(CreatureObject* player, byte selectedID) { if (selectedID == 61 && linkedCreature == player) { unlock(); try { ManagedReference<ControlDevice* > strongRef = controlDevice.get(); if (strongRef != NULL) strongRef->storeObject(player); } catch (Exception& e) { } catch (...) { wlock(player); throw; } wlock(player); } else if (selectedID == 62) { repairVehicle(player); } return 0; } void VehicleObjectImplementation::repairVehicle(CreatureObject* player) { if (!player->getPlayerObject()->isPrivileged()) { //Need to check if they are city banned. ManagedReference<ActiveArea*> activeArea = getActiveRegion(); if (activeArea != NULL && activeArea->isRegion()) { Region* region = cast<Region*>( activeArea.get()); ManagedReference<CityRegion*> gb = region->getCityRegion(); if (gb == NULL) return; if (gb->isBanned(player->getObjectID())) { player->sendSystemMessage("@city/city:garage_banned"); //You are city banned and cannot use this garage. return; } if (getConditionDamage() == 0) { player->sendSystemMessage("@pet/pet_menu:undamaged_vehicle"); //The targeted vehicle does not require any repairs at the moment. return; } if (isDestroyed()) { player->sendSystemMessage("@pet/pet_menu:cannot_repair_disabled"); //You may not repair a disabled vehicle. return; } if (!checkInRangeGarage()) { player->sendSystemMessage("@pet/pet_menu:repair_unrecognized_garages"); //Your vehicle does not recognize any local garages. Try again in a garage repair zone. return; } } } sendRepairConfirmTo(player); } void VehicleObjectImplementation::sendRepairConfirmTo(CreatureObject* player) { ManagedReference<SuiListBox*> listbox = new SuiListBox(player, SuiWindowType::GARAGE_REPAIR); listbox->setCallback(new RepairVehicleSuiCallback(server->getZoneServer())); listbox->setPromptTitle("@pet/pet_menu:confirm_repairs_t"); //Confirm Vehicle Repairs listbox->setPromptText("@pet/pet_menu:vehicle_repair_d"); //You have chosen to repair your vehicle. Please review the listed details and confirm your selection. listbox->setUsingObject(_this.get()); listbox->setCancelButton(true, "@cancel"); int repairCost = calculateRepairCost(player); int totalFunds = player->getBankCredits(); int tax = 0; ManagedReference<CityRegion*> city = getCityRegion(); if(city != NULL && city->getGarageTax() > 0){ repairCost += repairCost * city->getGarageTax() / 100; } listbox->addMenuItem("@pet/pet_menu:vehicle_prompt " + getDisplayedName()); //Vehicle: listbox->addMenuItem("@pet/pet_menu:repair_cost_prompt " + String::valueOf(repairCost)); //Repair Cost: listbox->addMenuItem("@pet/pet_menu:total_funds_prompt " + String::valueOf(totalFunds)); //Total Funds Available: player->getPlayerObject()->addSuiBox(listbox); player->sendMessage(listbox->generateMessage()); } int VehicleObjectImplementation::calculateRepairCost(CreatureObject* player) { if (player->getPlayerObject()->isPrivileged()) return 0; return getConditionDamage() * 4; } int VehicleObjectImplementation::inflictDamage(TangibleObject* attacker, int damageType, float damage, bool destroy, bool notifyClient) { return TangibleObjectImplementation::inflictDamage(attacker, damageType, damage, destroy, notifyClient); } int VehicleObjectImplementation::inflictDamage(TangibleObject* attacker, int damageType, float damage, bool destroy, const String& xp, bool notifyClient) { return TangibleObjectImplementation::inflictDamage(attacker, damageType, damage, destroy, xp, notifyClient); } int VehicleObjectImplementation::healDamage(TangibleObject* healer, int damageType, int damage, bool notifyClient) { return TangibleObjectImplementation::healDamage(healer, damageType, damage, notifyClient); } int VehicleObjectImplementation::notifyObjectDestructionObservers(TangibleObject* attacker, int condition) { unlock(); ManagedReference<CreatureObject* > linkedCreature = this->linkedCreature.get(); if (linkedCreature != NULL) { linkedCreature->sendSystemMessage("@pet/pet_menu:veh_disabled"); try { if (attacker != _this.get()) { Locker clocker(linkedCreature, attacker); linkedCreature->executeObjectControllerAction(String("dismount").hashCode()); } else { Locker locker(linkedCreature); linkedCreature->executeObjectControllerAction(String("dismount").hashCode()); } } catch (Exception& e) { } } if (attacker != _this.get()) wlock(attacker); else wlock(); return CreatureObjectImplementation::notifyObjectDestructionObservers(attacker, condition); } void VehicleObjectImplementation::sendMessage(BasePacket* msg) { ManagedReference<CreatureObject* > linkedCreature = this->linkedCreature.get(); if (linkedCreature != NULL && linkedCreature->getParent().get() == _this.get()) linkedCreature->sendMessage(msg); else delete msg; } <|endoftext|>
<commit_before>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkPlanarFigureSegmentationController.h" #include "mitkSurfaceToImageFilter.h" #include <vtkPolyData.h> #include <vtkPoints.h> #include <vtkPolygon.h> #include <vtkCellArray.h> #include <vtkSmartPointer.h> #include <vtkImageData.h> #include "mitkImageWriter.h" #include "mitkSurfaceVtkWriter.h" #include "mitkImageToSurfaceFilter.h" #include "mitkImageAccessByItk.h" #include "mitkImageCast.h" mitk::PlanarFigureSegmentationController::PlanarFigureSegmentationController() : itk::Object() , m_ReduceFilter( NULL ) , m_NormalsFilter( NULL ) , m_DistanceImageCreator( NULL ) , m_ReferenceImage( NULL ) , m_SegmentationAsImage( NULL ) { InitializeFilters(); } mitk::PlanarFigureSegmentationController::~PlanarFigureSegmentationController() { } void mitk::PlanarFigureSegmentationController::SetReferenceImage( mitk::Image::Pointer referenceImage ) { m_ReferenceImage = referenceImage; } void mitk::PlanarFigureSegmentationController::AddPlanarFigure( mitk::PlanarFigure::Pointer planarFigure ) { if ( planarFigure.IsNull() ) return; bool newFigure = true; int indexOfFigure = -1; for( int i=0; i<m_PlanarFigureList.size(); i++ ) { if( m_PlanarFigureList.at(i) == planarFigure ) { indexOfFigure = i; newFigure = false; break; } } mitk::Surface::Pointer figureAsSurface = NULL; if ( newFigure ) { m_PlanarFigureList.push_back( planarFigure ); figureAsSurface = this->CreateSurfaceFromPlanarFigure( planarFigure ); m_SurfaceList.push_back( figureAsSurface ); indexOfFigure = m_PlanarFigureList.size() -1 ; } else { figureAsSurface = this->CreateSurfaceFromPlanarFigure( planarFigure ); m_SurfaceList.at(indexOfFigure) = figureAsSurface; } m_ReduceFilter->SetInput( indexOfFigure, figureAsSurface ); m_NormalsFilter->SetInput( indexOfFigure, m_ReduceFilter->GetOutput( indexOfFigure ) ); m_DistanceImageCreator->SetInput( indexOfFigure, m_NormalsFilter->GetOutput( indexOfFigure ) ); } void mitk::PlanarFigureSegmentationController::RemovePlanarFigure( mitk::PlanarFigure::Pointer planarFigure ) { if ( planarFigure.IsNull() ) return; bool figureFound = false; int indexOfFigure = -1; for( int i=0; i<m_PlanarFigureList.size(); i++ ) { if( m_PlanarFigureList.at(i) == planarFigure ) { indexOfFigure = i; figureFound = true; break; } } if ( !figureFound ) return; if ( indexOfFigure == m_PlanarFigureList.size()-1 ) { // Ff the removed figure was the last one in the list, we can simply // remove the last input from each filter. m_DistanceImageCreator->RemoveInputs( m_NormalsFilter->GetOutput( indexOfFigure ) ); m_NormalsFilter->RemoveInputs( m_ReduceFilter->GetOutput( indexOfFigure ) ); m_ReduceFilter->RemoveInputs( const_cast<mitk::Surface*>(m_ReduceFilter->GetInput(indexOfFigure)) ); } else { // this is not very nice! If the figure that has been removed is NOT the last // one in the list we have to create new filters and add all remaining // inputs again. // // Has to be done as the filters do not work when removing an input // other than the last one. // create new filters InitializeFilters(); // and add all existing surfaces SurfaceListType::iterator surfaceIter = m_SurfaceList.begin(); for ( surfaceIter = m_SurfaceList.begin(); surfaceIter!=m_SurfaceList.end(); surfaceIter++ ) { m_ReduceFilter->SetInput( indexOfFigure, (*surfaceIter) ); m_NormalsFilter->SetInput( indexOfFigure, m_ReduceFilter->GetOutput( indexOfFigure ) ); m_DistanceImageCreator->SetInput( indexOfFigure, m_NormalsFilter->GetOutput( indexOfFigure ) ); } } PlanarFigureListType::iterator whereIter = m_PlanarFigureList.begin(); whereIter += indexOfFigure; m_PlanarFigureList.erase( whereIter ); SurfaceListType::iterator surfaceIter = m_SurfaceList.begin(); surfaceIter += indexOfFigure; m_SurfaceList.erase( surfaceIter ); } template<typename TPixel, unsigned int VImageDimension> void mitk::PlanarFigureSegmentationController::GetImageBase(itk::Image<TPixel, VImageDimension>* input, itk::ImageBase<3>::Pointer& result) { result = input; } mitk::Image::Pointer mitk::PlanarFigureSegmentationController::GetInterpolationResult() { m_SegmentationAsImage = NULL; if ( m_PlanarFigureList.size() == 0 ) { m_SegmentationAsImage = mitk::Image::New(); m_SegmentationAsImage->Initialize(mitk::MakeScalarPixelType<unsigned char>() , *m_ReferenceImage->GetTimeSlicedGeometry()); return m_SegmentationAsImage; } itk::ImageBase<3>::Pointer itkImage; AccessFixedDimensionByItk_1( m_ReferenceImage.GetPointer(), GetImageBase, 3, itkImage ); m_DistanceImageCreator->SetReferenceImage( itkImage.GetPointer() ); m_ReduceFilter->Update(); m_NormalsFilter->Update(); m_DistanceImageCreator->Update(); mitk::Image::Pointer distanceImage = m_DistanceImageCreator->GetOutput(); // Cleanup the pipeline distanceImage->DisconnectPipeline(); m_DistanceImageCreator = NULL; m_NormalsFilter = NULL; m_ReduceFilter = NULL; itkImage = NULL; // If this bool flag is true, the distanceImage will be written to the // filesystem as nrrd-image and as surface-representation. bool debugOutput(false); if ( debugOutput ) { mitk::ImageWriter::Pointer imageWriter = mitk::ImageWriter::New(); imageWriter->SetInput( distanceImage ); imageWriter->SetExtension( ".nrrd" ); imageWriter->SetFileName( "v:/DistanceImage" ); imageWriter->Update(); } mitk::ImageToSurfaceFilter::Pointer imageToSurfaceFilter = mitk::ImageToSurfaceFilter::New(); imageToSurfaceFilter->SetInput( distanceImage ); imageToSurfaceFilter->SetThreshold( 0 ); imageToSurfaceFilter->Update(); mitk::Surface::Pointer segmentationAsSurface = imageToSurfaceFilter->GetOutput(); // Cleanup the pipeline segmentationAsSurface->DisconnectPipeline(); imageToSurfaceFilter = NULL; if ( debugOutput ) { mitk::SurfaceVtkWriter<vtkPolyDataWriter>::Pointer surfaceWriter = mitk::SurfaceVtkWriter<vtkPolyDataWriter>::New(); surfaceWriter->SetInput( segmentationAsSurface ); surfaceWriter->SetExtension( ".vtk" ); surfaceWriter->SetFileName( "v:/DistanceImageAsSurface.vtk" ); surfaceWriter->Update(); } mitk::SurfaceToImageFilter::Pointer surfaceToImageFilter = mitk::SurfaceToImageFilter::New(); surfaceToImageFilter->SetInput( segmentationAsSurface ); surfaceToImageFilter->SetImage( m_ReferenceImage ); surfaceToImageFilter->SetMakeOutputBinary(true); surfaceToImageFilter->Update(); m_SegmentationAsImage = surfaceToImageFilter->GetOutput(); // Cleanup the pipeline m_SegmentationAsImage->DisconnectPipeline(); return m_SegmentationAsImage; } mitk::Surface::Pointer mitk::PlanarFigureSegmentationController::CreateSurfaceFromPlanarFigure( mitk::PlanarFigure::Pointer figure ) { if ( figure.IsNull() ) { MITK_ERROR << "Given PlanarFigure is NULL. Please provide valid PlanarFigure."; return NULL; } mitk::Surface::Pointer newSurface = mitk::Surface::New(); vtkSmartPointer<vtkPoints> points = vtkSmartPointer<vtkPoints>::New(); vtkSmartPointer<vtkPolygon> polygon = vtkSmartPointer<vtkPolygon>::New(); vtkSmartPointer<vtkCellArray> cells = vtkSmartPointer<vtkCellArray>::New(); vtkSmartPointer<vtkPolyData> polyData = vtkSmartPointer<vtkPolyData>::New(); const mitk::Geometry2D* figureGeometry = figure->GetGeometry2D(); // Get the polyline mitk::PlanarFigure::PolyLineType planarPolyLine = figure->GetPolyLine(0); mitk::PlanarFigure::PolyLineType::iterator iter; // iterate over the polyline, ... int pointCounter = 0; for( iter = planarPolyLine.begin(); iter != planarPolyLine.end(); iter++ ) { // ... determine the world-coordinates mitk::Point2D polyLinePoint = iter->Point; mitk::Point3D pointInWorldCoordiantes; figureGeometry->Map( polyLinePoint, pointInWorldCoordiantes ); // and add them as new points to the vtkPoints points->InsertNextPoint( pointInWorldCoordiantes[0], pointInWorldCoordiantes[1], pointInWorldCoordiantes[2] ); ++pointCounter; } // create a polygon with the points of the polyline polygon->GetPointIds()->SetNumberOfIds( pointCounter ); for(unsigned int i = 0; i < pointCounter; i++) { polygon->GetPointIds()->SetId(i,i); } // initialize the vtkCellArray and vtkPolyData cells->InsertNextCell(polygon); polyData->SetPoints(points); polyData->SetPolys( cells ); // set the polydata to the surface newSurface->SetVtkPolyData( polyData ); return newSurface; } mitk::PlanarFigureSegmentationController::PlanarFigureListType mitk::PlanarFigureSegmentationController::GetAllPlanarFigures() { return m_PlanarFigureList; } void mitk::PlanarFigureSegmentationController::InitializeFilters() { m_ReduceFilter = mitk::ReduceContourSetFilter::New(); m_ReduceFilter->SetReductionType(ReduceContourSetFilter::NTH_POINT); m_ReduceFilter->SetStepSize( 10 ); m_NormalsFilter = mitk::ComputeContourSetNormalsFilter::New(); m_DistanceImageCreator = mitk::CreateDistanceImageFromSurfaceFilter::New(); } <commit_msg>commented code that uses deprecated ITK methods<commit_after>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkPlanarFigureSegmentationController.h" #include "mitkSurfaceToImageFilter.h" #include <vtkPolyData.h> #include <vtkPoints.h> #include <vtkPolygon.h> #include <vtkCellArray.h> #include <vtkSmartPointer.h> #include <vtkImageData.h> #include "mitkImageWriter.h" #include "mitkSurfaceVtkWriter.h" #include "mitkImageToSurfaceFilter.h" #include "mitkImageAccessByItk.h" #include "mitkImageCast.h" mitk::PlanarFigureSegmentationController::PlanarFigureSegmentationController() : itk::Object() , m_ReduceFilter( NULL ) , m_NormalsFilter( NULL ) , m_DistanceImageCreator( NULL ) , m_ReferenceImage( NULL ) , m_SegmentationAsImage( NULL ) { InitializeFilters(); } mitk::PlanarFigureSegmentationController::~PlanarFigureSegmentationController() { } void mitk::PlanarFigureSegmentationController::SetReferenceImage( mitk::Image::Pointer referenceImage ) { m_ReferenceImage = referenceImage; } void mitk::PlanarFigureSegmentationController::AddPlanarFigure( mitk::PlanarFigure::Pointer planarFigure ) { if ( planarFigure.IsNull() ) return; bool newFigure = true; int indexOfFigure = -1; for( int i=0; i<m_PlanarFigureList.size(); i++ ) { if( m_PlanarFigureList.at(i) == planarFigure ) { indexOfFigure = i; newFigure = false; break; } } mitk::Surface::Pointer figureAsSurface = NULL; if ( newFigure ) { m_PlanarFigureList.push_back( planarFigure ); figureAsSurface = this->CreateSurfaceFromPlanarFigure( planarFigure ); m_SurfaceList.push_back( figureAsSurface ); indexOfFigure = m_PlanarFigureList.size() -1 ; } else { figureAsSurface = this->CreateSurfaceFromPlanarFigure( planarFigure ); m_SurfaceList.at(indexOfFigure) = figureAsSurface; } m_ReduceFilter->SetInput( indexOfFigure, figureAsSurface ); m_NormalsFilter->SetInput( indexOfFigure, m_ReduceFilter->GetOutput( indexOfFigure ) ); m_DistanceImageCreator->SetInput( indexOfFigure, m_NormalsFilter->GetOutput( indexOfFigure ) ); } void mitk::PlanarFigureSegmentationController::RemovePlanarFigure( mitk::PlanarFigure::Pointer planarFigure ) { if ( planarFigure.IsNull() ) return; bool figureFound = false; int indexOfFigure = -1; for( int i=0; i<m_PlanarFigureList.size(); i++ ) { if( m_PlanarFigureList.at(i) == planarFigure ) { indexOfFigure = i; figureFound = true; break; } } if ( !figureFound ) return; // TODO: fix this! The following code had to be removed as the method // RemoveInputs() has been removed in ITK 4 // The remaining code works correctly but is slower if ( false && indexOfFigure == m_PlanarFigureList.size()-1 ) { // Ff the removed figure was the last one in the list, we can simply // remove the last input from each filter. // m_DistanceImageCreator->RemoveInputs( m_NormalsFilter->GetOutput( indexOfFigure ) ); // m_NormalsFilter->RemoveInput( m_ReduceFilter->GetOutput( indexOfFigure ) ); // m_ReduceFilter->RemoveInput( const_cast<mitk::Surface*>(m_ReduceFilter->GetInput(indexOfFigure)) ); } else { // this is not very nice! If the figure that has been removed is NOT the last // one in the list we have to create new filters and add all remaining // inputs again. // // Has to be done as the filters do not work when removing an input // other than the last one. // create new filters InitializeFilters(); // and add all existing surfaces SurfaceListType::iterator surfaceIter = m_SurfaceList.begin(); for ( surfaceIter = m_SurfaceList.begin(); surfaceIter!=m_SurfaceList.end(); surfaceIter++ ) { m_ReduceFilter->SetInput( indexOfFigure, (*surfaceIter) ); m_NormalsFilter->SetInput( indexOfFigure, m_ReduceFilter->GetOutput( indexOfFigure ) ); m_DistanceImageCreator->SetInput( indexOfFigure, m_NormalsFilter->GetOutput( indexOfFigure ) ); } } PlanarFigureListType::iterator whereIter = m_PlanarFigureList.begin(); whereIter += indexOfFigure; m_PlanarFigureList.erase( whereIter ); SurfaceListType::iterator surfaceIter = m_SurfaceList.begin(); surfaceIter += indexOfFigure; m_SurfaceList.erase( surfaceIter ); } template<typename TPixel, unsigned int VImageDimension> void mitk::PlanarFigureSegmentationController::GetImageBase(itk::Image<TPixel, VImageDimension>* input, itk::ImageBase<3>::Pointer& result) { result = input; } mitk::Image::Pointer mitk::PlanarFigureSegmentationController::GetInterpolationResult() { m_SegmentationAsImage = NULL; if ( m_PlanarFigureList.size() == 0 ) { m_SegmentationAsImage = mitk::Image::New(); m_SegmentationAsImage->Initialize(mitk::MakeScalarPixelType<unsigned char>() , *m_ReferenceImage->GetTimeSlicedGeometry()); return m_SegmentationAsImage; } itk::ImageBase<3>::Pointer itkImage; AccessFixedDimensionByItk_1( m_ReferenceImage.GetPointer(), GetImageBase, 3, itkImage ); m_DistanceImageCreator->SetReferenceImage( itkImage.GetPointer() ); m_ReduceFilter->Update(); m_NormalsFilter->Update(); m_DistanceImageCreator->Update(); mitk::Image::Pointer distanceImage = m_DistanceImageCreator->GetOutput(); // Cleanup the pipeline distanceImage->DisconnectPipeline(); m_DistanceImageCreator = NULL; m_NormalsFilter = NULL; m_ReduceFilter = NULL; itkImage = NULL; // If this bool flag is true, the distanceImage will be written to the // filesystem as nrrd-image and as surface-representation. bool debugOutput(false); if ( debugOutput ) { mitk::ImageWriter::Pointer imageWriter = mitk::ImageWriter::New(); imageWriter->SetInput( distanceImage ); imageWriter->SetExtension( ".nrrd" ); imageWriter->SetFileName( "v:/DistanceImage" ); imageWriter->Update(); } mitk::ImageToSurfaceFilter::Pointer imageToSurfaceFilter = mitk::ImageToSurfaceFilter::New(); imageToSurfaceFilter->SetInput( distanceImage ); imageToSurfaceFilter->SetThreshold( 0 ); imageToSurfaceFilter->Update(); mitk::Surface::Pointer segmentationAsSurface = imageToSurfaceFilter->GetOutput(); // Cleanup the pipeline segmentationAsSurface->DisconnectPipeline(); imageToSurfaceFilter = NULL; if ( debugOutput ) { mitk::SurfaceVtkWriter<vtkPolyDataWriter>::Pointer surfaceWriter = mitk::SurfaceVtkWriter<vtkPolyDataWriter>::New(); surfaceWriter->SetInput( segmentationAsSurface ); surfaceWriter->SetExtension( ".vtk" ); surfaceWriter->SetFileName( "v:/DistanceImageAsSurface.vtk" ); surfaceWriter->Update(); } mitk::SurfaceToImageFilter::Pointer surfaceToImageFilter = mitk::SurfaceToImageFilter::New(); surfaceToImageFilter->SetInput( segmentationAsSurface ); surfaceToImageFilter->SetImage( m_ReferenceImage ); surfaceToImageFilter->SetMakeOutputBinary(true); surfaceToImageFilter->Update(); m_SegmentationAsImage = surfaceToImageFilter->GetOutput(); // Cleanup the pipeline m_SegmentationAsImage->DisconnectPipeline(); return m_SegmentationAsImage; } mitk::Surface::Pointer mitk::PlanarFigureSegmentationController::CreateSurfaceFromPlanarFigure( mitk::PlanarFigure::Pointer figure ) { if ( figure.IsNull() ) { MITK_ERROR << "Given PlanarFigure is NULL. Please provide valid PlanarFigure."; return NULL; } mitk::Surface::Pointer newSurface = mitk::Surface::New(); vtkSmartPointer<vtkPoints> points = vtkSmartPointer<vtkPoints>::New(); vtkSmartPointer<vtkPolygon> polygon = vtkSmartPointer<vtkPolygon>::New(); vtkSmartPointer<vtkCellArray> cells = vtkSmartPointer<vtkCellArray>::New(); vtkSmartPointer<vtkPolyData> polyData = vtkSmartPointer<vtkPolyData>::New(); const mitk::Geometry2D* figureGeometry = figure->GetGeometry2D(); // Get the polyline mitk::PlanarFigure::PolyLineType planarPolyLine = figure->GetPolyLine(0); mitk::PlanarFigure::PolyLineType::iterator iter; // iterate over the polyline, ... int pointCounter = 0; for( iter = planarPolyLine.begin(); iter != planarPolyLine.end(); iter++ ) { // ... determine the world-coordinates mitk::Point2D polyLinePoint = iter->Point; mitk::Point3D pointInWorldCoordiantes; figureGeometry->Map( polyLinePoint, pointInWorldCoordiantes ); // and add them as new points to the vtkPoints points->InsertNextPoint( pointInWorldCoordiantes[0], pointInWorldCoordiantes[1], pointInWorldCoordiantes[2] ); ++pointCounter; } // create a polygon with the points of the polyline polygon->GetPointIds()->SetNumberOfIds( pointCounter ); for(unsigned int i = 0; i < pointCounter; i++) { polygon->GetPointIds()->SetId(i,i); } // initialize the vtkCellArray and vtkPolyData cells->InsertNextCell(polygon); polyData->SetPoints(points); polyData->SetPolys( cells ); // set the polydata to the surface newSurface->SetVtkPolyData( polyData ); return newSurface; } mitk::PlanarFigureSegmentationController::PlanarFigureListType mitk::PlanarFigureSegmentationController::GetAllPlanarFigures() { return m_PlanarFigureList; } void mitk::PlanarFigureSegmentationController::InitializeFilters() { m_ReduceFilter = mitk::ReduceContourSetFilter::New(); m_ReduceFilter->SetReductionType(ReduceContourSetFilter::NTH_POINT); m_ReduceFilter->SetStepSize( 10 ); m_NormalsFilter = mitk::ComputeContourSetNormalsFilter::New(); m_DistanceImageCreator = mitk::CreateDistanceImageFromSurfaceFilter::New(); } <|endoftext|>
<commit_before>/* * CUDArrays is a library for easy multi-GPU program development. * * The MIT License (MIT) * * Copyright (c) 2013-2015 Barcelona Supercomputing Center and * University of Illinois * * Developed by: Javier Cabezas <[email protected]> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #pragma once #ifndef CUDARRAYS_DETAIL_DYNARRAY_HELPERS_HPP_ #define CUDARRAYS_DETAIL_DYNARRAY_HELPERS_HPP_ #include <array> #include <vector> #include "../../storage.hpp" #include "../../compute.hpp" namespace cudarrays { /** * Create a DimsComp-dimensional GPU grid the lowest order dimensions are maximized */ template <unsigned DimsComp> static std::array<unsigned, DimsComp> helper_distribution_get_gpu_grid(const cudarrays::compute_conf<DimsComp> &comp) { std::array<unsigned, DimsComp> gpuGrid; // Check if we can map the arrayPartitionGrid on the GPUs std::vector<unsigned> factorsGpus = utils::get_factors(comp.procs); utils::sort(factorsGpus, std::greater<unsigned>()); #if 0 if (factorsGPUs.size() < compPartDims) FATAL("CUDArrays cannot partition %u dimensions into %u GPUs", arrayPartDims, comp.procs); #endif // Create the GPU grid unsigned j = 0; for (unsigned i : utils::make_range(DimsComp)) { if (comp.procs > 1) { unsigned partition = 1; if (comp.is_dim_part(i)) { ASSERT(j < factorsGpus.size()); std::vector<unsigned>::iterator pos = factorsGpus.begin() + j; size_t inc = (j == 0)? factorsGpus.size() - comp.get_part_dims() + 1: 1; // DEBUG("Reshape> ALLOC: Collapsing%u: %zd:%zd", i, j, j + inc); partition = std::accumulate(pos, pos + inc, 1, std::multiplies<unsigned>()); j += inc; } gpuGrid[i] = partition; } else { gpuGrid[i] = 1; } } return gpuGrid; } template <size_t DimsComp, size_t Dims> static std::array<unsigned, Dims> helper_distribution_get_array_grid(const std::array<unsigned, DimsComp> &gpuGrid, const std::array<int, Dims> &arrayDimToCompDim) { std::array<unsigned, Dims> ret; // Compute the array grid and the local sizes for (unsigned i : utils::make_range(Dims)) { int compDim = arrayDimToCompDim[i]; unsigned partition = 1; if (compDim != DimInvalid) { partition = gpuGrid[compDim]; } else { // TODO: REPLICATION } ret[i] = partition; } return ret; } template <size_t Dims> static std::array<array_size_t, Dims> helper_distribution_get_local_dims(const std::array<array_size_t, Dims> &dims, const std::array<unsigned, Dims> &arrayGrid) { std::array<array_size_t, Dims> ret; // Compute the array grid and the local sizes for (unsigned i : utils::make_range(Dims)) { // TODO: REPLICATION ret[i] = utils::div_ceil(dims[i], arrayGrid[i]); } return ret; } template <size_t Dims> static array_size_t helper_distribution_get_local_elems(const std::array<array_size_t, Dims> &dims, array_size_t boundary = 1) { array_size_t ret; ret = utils::accumulate(dims, 1, std::multiplies<array_size_t>()); // ... adjusting the tile size to VM SIZE ret = utils::round_next(ret, boundary); return ret; } template <size_t Dims> static std::array<array_size_t, Dims - 1> helper_distribution_get_local_offs(const std::array<array_size_t, Dims> &dims) { std::array<array_size_t, Dims - 1> ret; array_size_t off = 1; for (ssize_t dim = ssize_t(Dims) - 2; dim >= 0; --dim) { off *= dims[dim + 1]; ret[dim] = off; } return ret; } template <size_t Dims> static std::array<array_size_t, Dims> helper_distribution_get_intergpu_offs(array_size_t elemsLocal, const std::array<unsigned, Dims> &arrayGrid, const std::array<int, Dims> &arrayDimToCompDim) { std::array<array_size_t, Dims> ret; array_size_t off = 1; for (ssize_t dim = Dims - 1; dim >= 0; --dim) { if (arrayDimToCompDim[dim] != DimInvalid) { ret[dim] = off * elemsLocal; off *= arrayGrid[dim]; } else { ret[dim] = 0; } } return ret; } template <size_t DimsComp> static std::array<unsigned, DimsComp> helper_distribution_gpu_get_offs(const std::array<unsigned, DimsComp> &gpuGrid) { std::array<unsigned, DimsComp> ret; unsigned gridOff = 1; for (ssize_t dim = DimsComp - 1; dim >= 0; --dim) { ret[dim] = gridOff; if (dim < ssize_t(DimsComp)) { gridOff *= gpuGrid[dim]; } } return ret; } template <size_t DimsComp, size_t Dims> static std::array<unsigned, Dims> helper_distribution_get_array_dim_to_gpus(const std::array<unsigned, DimsComp> &gpuGridOffs, const std::array<int, Dims> &arrayDimToCompDim) { std::array<unsigned, Dims> ret; for (unsigned dim : utils::make_range(Dims)) { int compDim = arrayDimToCompDim[dim]; ret[dim] = (compDim != DimInvalid)? gpuGridOffs[compDim]: 0; } return ret; } } #endif <commit_msg>Add initializer for arrays in helpers<commit_after>/* * CUDArrays is a library for easy multi-GPU program development. * * The MIT License (MIT) * * Copyright (c) 2013-2015 Barcelona Supercomputing Center and * University of Illinois * * Developed by: Javier Cabezas <[email protected]> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #pragma once #ifndef CUDARRAYS_DETAIL_DYNARRAY_HELPERS_HPP_ #define CUDARRAYS_DETAIL_DYNARRAY_HELPERS_HPP_ #include <array> #include <vector> #include "../../storage.hpp" #include "../../compute.hpp" namespace cudarrays { /** * Create a DimsComp-dimensional GPU grid the lowest order dimensions are maximized */ template <unsigned DimsComp> static std::array<unsigned, DimsComp> helper_distribution_get_gpu_grid(const cudarrays::compute_conf<DimsComp> &comp) { std::array<unsigned, DimsComp> gpuGrid = {{}}; // Check if we can map the arrayPartitionGrid on the GPUs std::vector<unsigned> factorsGpus = utils::get_factors(comp.procs); utils::sort(factorsGpus, std::greater<unsigned>()); #if 0 if (factorsGPUs.size() < compPartDims) FATAL("CUDArrays cannot partition %u dimensions into %u GPUs", arrayPartDims, comp.procs); #endif // Create the GPU grid unsigned j = 0; for (unsigned i : utils::make_range(DimsComp)) { if (comp.procs > 1) { unsigned partition = 1; if (comp.is_dim_part(i)) { ASSERT(j < factorsGpus.size()); std::vector<unsigned>::iterator pos = factorsGpus.begin() + j; size_t inc = (j == 0)? factorsGpus.size() - comp.get_part_dims() + 1: 1; // DEBUG("Reshape> ALLOC: Collapsing%u: %zd:%zd", i, j, j + inc); partition = std::accumulate(pos, pos + inc, 1, std::multiplies<unsigned>()); j += inc; } gpuGrid[i] = partition; } else { gpuGrid[i] = 1; } } return gpuGrid; } template <size_t DimsComp, size_t Dims> static std::array<unsigned, Dims> helper_distribution_get_array_grid(const std::array<unsigned, DimsComp> &gpuGrid, const std::array<int, Dims> &arrayDimToCompDim) { std::array<unsigned, Dims> ret{{}}; // Compute the array grid and the local sizes for (unsigned i : utils::make_range(Dims)) { int compDim = arrayDimToCompDim[i]; unsigned partition = 1; if (compDim != DimInvalid) { partition = gpuGrid[compDim]; } else { // TODO: REPLICATION } ret[i] = partition; } return ret; } template <size_t Dims> static std::array<array_size_t, Dims> helper_distribution_get_local_dims(const std::array<array_size_t, Dims> &dims, const std::array<unsigned, Dims> &arrayGrid) { std::array<array_size_t, Dims> ret{{}}; // Compute the array grid and the local sizes for (unsigned i : utils::make_range(Dims)) { // TODO: REPLICATION ret[i] = utils::div_ceil(dims[i], arrayGrid[i]); } return ret; } template <size_t Dims> static array_size_t helper_distribution_get_local_elems(const std::array<array_size_t, Dims> &dims, array_size_t boundary = 1) { array_size_t ret; ret = utils::accumulate(dims, 1, std::multiplies<array_size_t>()); // ... adjusting the tile size to VM SIZE ret = utils::round_next(ret, boundary); return ret; } template <size_t Dims> static std::array<array_size_t, Dims - 1> helper_distribution_get_local_offs(const std::array<array_size_t, Dims> &dims) { std::array<array_size_t, Dims - 1> ret{{}}; array_size_t off = 1; for (ssize_t dim = ssize_t(Dims) - 2; dim >= 0; --dim) { off *= dims[dim + 1]; ret[dim] = off; } return ret; } template <size_t Dims> static std::array<array_size_t, Dims> helper_distribution_get_intergpu_offs(array_size_t elemsLocal, const std::array<unsigned, Dims> &arrayGrid, const std::array<int, Dims> &arrayDimToCompDim) { std::array<array_size_t, Dims> ret{{}}; array_size_t off = 1; for (ssize_t dim = Dims - 1; dim >= 0; --dim) { if (arrayDimToCompDim[dim] != DimInvalid) { ret[dim] = off * elemsLocal; off *= arrayGrid[dim]; } else { ret[dim] = 0; } } return ret; } template <size_t DimsComp> static std::array<unsigned, DimsComp> helper_distribution_gpu_get_offs(const std::array<unsigned, DimsComp> &gpuGrid) { std::array<unsigned, DimsComp> ret{{}}; unsigned gridOff = 1; for (ssize_t dim = DimsComp - 1; dim >= 0; --dim) { ret[dim] = gridOff; if (dim < ssize_t(DimsComp)) { gridOff *= gpuGrid[dim]; } } return ret; } template <size_t DimsComp, size_t Dims> static std::array<unsigned, Dims> helper_distribution_get_array_dim_to_gpus(const std::array<unsigned, DimsComp> &gpuGridOffs, const std::array<int, Dims> &arrayDimToCompDim) { std::array<unsigned, Dims> ret{{}}; for (unsigned dim : utils::make_range(Dims)) { int compDim = arrayDimToCompDim[dim]; ret[dim] = (compDim != DimInvalid)? gpuGridOffs[compDim]: 0; } return ret; } } #endif <|endoftext|>
<commit_before>// /////////////////////////////////////////////////////////////////////////// // tenh/conceptual/conceptualinheritancegraph.hpp by Vector Dods, created 2013/09/12 // Copyright Leap Motion Inc. // /////////////////////////////////////////////////////////////////////////// #ifndef TENH_CONCEPTUAL_CONCEPTUALINHERITANCEGRAPH_HPP_ #define TENH_CONCEPTUAL_CONCEPTUALINHERITANCEGRAPH_HPP_ #include "tenh/core.hpp" #include <cassert> #include <map> #include <ostream> #include <set> #include <sstream> #include <string> #include "tenh/conceptual/concept.hpp" namespace Tenh { struct Graph { struct Node { std::string m_shortified_name; std::string m_full_name; Node (std::string const &shortified_name, std::string const &full_name) : m_shortified_name(shortified_name), m_full_name(full_name) { assert(!m_shortified_name.empty()); assert(!m_full_name.empty()); } bool operator == (Node const &r) const { return this->m_shortified_name == r.m_shortified_name && this->m_full_name == r.m_full_name; } bool operator < (Node const &r) const { return this->m_shortified_name < r.m_shortified_name || (this->m_shortified_name == r.m_shortified_name && this->m_full_name < r.m_full_name); } struct Order { bool operator () (Node const &l, Node const &r) { return l < r; } }; }; struct Edge { Node m_source; Node m_target; Edge (Node const &source, Node const &target) : m_source(source), m_target(target) { } bool operator < (Edge const &r) const { return this->m_source < r.m_source || (this->m_source == r.m_source && this->m_target < r.m_target); } struct Order { bool operator () (Edge const &l, Edge const &r) { return l < r; } }; }; typedef std::set<Node> Nodes; typedef std::set<Edge> Edges; // constructs an empty graph Graph () { } void clear () { m_nodes.clear(); m_edges.clear(); } void add_node (Node const &node) { m_nodes.insert(node); } void add_edge (Node const &source, Node const &target) { assert(m_nodes.find(source) != m_nodes.end() && "the source node must already be in the graph"); assert(m_nodes.find(target) != m_nodes.end() && "the target node must already be in the graph"); m_edges.insert(Edge(source, target)); } Nodes const &nodes () const { return m_nodes; } Edges const &edges () const { return m_edges; } Edges edges_having_source_node (Node const &node) const { Edges retval; for (Edges::const_iterator it = m_edges.begin(), it_end = m_edges.end(); it != it_end; ++it) { Edge const &edge = *it; if (edge.m_source == node) retval.insert(edge); } return retval; } Edges edges_having_target_node (Node const &node) const { Edges retval; for (Edges::const_iterator it = m_edges.begin(), it_end = m_edges.end(); it != it_end; ++it) { Edge const &edge = *it; if (edge.m_target == node) retval.insert(edge); } return retval; } void print_as_dot_graph (std::ostream &out) const { // have to use identifiers instead of the full strings for the node names in dot, // so this part is to construct a map from nodes to identifiers (and back) typedef std::map<Node,std::string> NodeIdentifierMap; NodeIdentifierMap node_identifier_map; Uint32 id_number = 0; for (Nodes::const_iterator it = m_nodes.begin(), it_end = m_nodes.end(); it != it_end; ++it) { Node const &n = *it; std::string id(FORMAT("id" << id_number++)); node_identifier_map[n] = id; } // generate the dot graph out << "digraph {\n"; for (Nodes::const_iterator it = m_nodes.begin(), it_end = m_nodes.end(); it != it_end; ++it) { Node const &n = *it; out << " " << node_identifier_map[n] << " [label=\""; print_string_with_newlines_as_char_literals(out, n.m_shortified_name); out << "\", fontname=\"courier\", labeljust=\"l\", shape=box];\n"; } out << '\n'; for (Edges::const_iterator it = m_edges.begin(), it_end = m_edges.end(); it != it_end; ++it) { Edge const &e = *it; out << " " << node_identifier_map[e.m_source] << " -> " << node_identifier_map[e.m_target] << ";\n"; } out << "}\n"; } private: static void print_string_with_newlines_as_char_literals (std::ostream &out, std::string const &s) { for (std::string::const_iterator it = s.begin(), it_end = s.end(); it != it_end; ++it) { char const &c = *it; if (c == '\n') out << "\\n"; else out << c; } } Nodes m_nodes; Edges m_edges; }; std::ostream &operator << (std::ostream &out, Graph::Node const &n) { if (n.m_shortified_name == n.m_full_name) return out << "Node(" << n.m_full_name << ')'; else return out << "Node(" << n.m_shortified_name << ',' << n.m_full_name << ')'; } std::ostream &operator << (std::ostream &out, Graph::Edge const &e) { return out << "Edge(" << e.m_source << " -> " << e.m_target << ')'; } std::ostream &operator << (std::ostream &out, Graph const &g) { out << "Graph(\n"; for (Graph::Nodes::const_iterator it = g.nodes().begin(), it_end = g.nodes().end(); it != it_end; ++it) { Graph::Node const &n = *it; out << '\t' << n << '\n'; } out << '\n'; for (Graph::Edges::const_iterator it = g.edges().begin(), it_end = g.edges().end(); it != it_end; ++it) { Graph::Edge const &e = *it; out << '\t' << e << '\n'; } return out << ")\n"; } template <Uint32 SHORTIFY_DEPTH_, typename Concept_, typename HeadType_, typename BodyTypeList_> void add_parent_concept_type_list_to_graph_recursive (Concept_ const &concept, TypeList_t<HeadType_,BodyTypeList_> const &parent_concept_type_list, Graph &g) { // add the parent nodes and edges connecting concept to them Graph::Node concept_node(FORMAT((Pretty<TypeStringOf_t<Concept_>,SHORTIFY_DEPTH_>())), FORMAT((Pretty<TypeStringOf_t<Concept_>,0>()))); assert(g.nodes().find(concept_node) != g.nodes().end()); Graph::Node parent_node(FORMAT((Pretty<TypeStringOf_t<HeadType_>,SHORTIFY_DEPTH_>())), FORMAT((Pretty<TypeStringOf_t<HeadType_>,0>()))); g.add_node(parent_node); g.add_edge(concept_node, parent_node); add_parent_concept_type_list_to_graph_recursive<SHORTIFY_DEPTH_>(concept, BodyTypeList_(), g); // call this function recursively on each parent add_parent_concept_type_list_to_graph_recursive<SHORTIFY_DEPTH_>(HeadType_(), typename HeadType_::ParentTypeList(), g); } template <Uint32 SHORTIFY_DEPTH_, typename Concept_> void add_parent_concept_type_list_to_graph_recursive (Concept_ const &, EmptyTypeList const &, Graph &g) { // nothing to add } template <Uint32 SHORTIFY_DEPTH_, typename Concept_> void add_concept_hierarchy_to_graph (Concept_ const &root, Graph &g) { Graph::Node n(FORMAT((Pretty<TypeStringOf_t<Concept_>,SHORTIFY_DEPTH_>())), FORMAT((Pretty<TypeStringOf_t<Concept_>,0>()))); g.add_node(n); add_parent_concept_type_list_to_graph_recursive<SHORTIFY_DEPTH_>(root, typename Concept_::ParentTypeList(), g); } } // end of namespace Tenh #endif // TENH_CONCEPTUAL_CONCEPTUALINHERITANCEGRAPH_HPP_<commit_msg>Fixed an ordering issue in the definition of a templatized conceptual hierarchy graphing function, which GCC was complaining about.<commit_after>// /////////////////////////////////////////////////////////////////////////// // tenh/conceptual/conceptualinheritancegraph.hpp by Vector Dods, created 2013/09/12 // Copyright Leap Motion Inc. // /////////////////////////////////////////////////////////////////////////// #ifndef TENH_CONCEPTUAL_CONCEPTUALINHERITANCEGRAPH_HPP_ #define TENH_CONCEPTUAL_CONCEPTUALINHERITANCEGRAPH_HPP_ #include "tenh/core.hpp" #include <cassert> #include <map> #include <ostream> #include <set> #include <sstream> #include <string> #include "tenh/conceptual/concept.hpp" namespace Tenh { struct Graph { struct Node { std::string m_shortified_name; std::string m_full_name; Node (std::string const &shortified_name, std::string const &full_name) : m_shortified_name(shortified_name), m_full_name(full_name) { assert(!m_shortified_name.empty()); assert(!m_full_name.empty()); } bool operator == (Node const &r) const { return this->m_shortified_name == r.m_shortified_name && this->m_full_name == r.m_full_name; } bool operator < (Node const &r) const { return this->m_shortified_name < r.m_shortified_name || (this->m_shortified_name == r.m_shortified_name && this->m_full_name < r.m_full_name); } struct Order { bool operator () (Node const &l, Node const &r) { return l < r; } }; }; struct Edge { Node m_source; Node m_target; Edge (Node const &source, Node const &target) : m_source(source), m_target(target) { } bool operator < (Edge const &r) const { return this->m_source < r.m_source || (this->m_source == r.m_source && this->m_target < r.m_target); } struct Order { bool operator () (Edge const &l, Edge const &r) { return l < r; } }; }; typedef std::set<Node> Nodes; typedef std::set<Edge> Edges; // constructs an empty graph Graph () { } void clear () { m_nodes.clear(); m_edges.clear(); } void add_node (Node const &node) { m_nodes.insert(node); } void add_edge (Node const &source, Node const &target) { assert(m_nodes.find(source) != m_nodes.end() && "the source node must already be in the graph"); assert(m_nodes.find(target) != m_nodes.end() && "the target node must already be in the graph"); m_edges.insert(Edge(source, target)); } Nodes const &nodes () const { return m_nodes; } Edges const &edges () const { return m_edges; } Edges edges_having_source_node (Node const &node) const { Edges retval; for (Edges::const_iterator it = m_edges.begin(), it_end = m_edges.end(); it != it_end; ++it) { Edge const &edge = *it; if (edge.m_source == node) retval.insert(edge); } return retval; } Edges edges_having_target_node (Node const &node) const { Edges retval; for (Edges::const_iterator it = m_edges.begin(), it_end = m_edges.end(); it != it_end; ++it) { Edge const &edge = *it; if (edge.m_target == node) retval.insert(edge); } return retval; } void print_as_dot_graph (std::ostream &out) const { // have to use identifiers instead of the full strings for the node names in dot, // so this part is to construct a map from nodes to identifiers (and back) typedef std::map<Node,std::string> NodeIdentifierMap; NodeIdentifierMap node_identifier_map; Uint32 id_number = 0; for (Nodes::const_iterator it = m_nodes.begin(), it_end = m_nodes.end(); it != it_end; ++it) { Node const &n = *it; std::string id(FORMAT("id" << id_number++)); node_identifier_map[n] = id; } // generate the dot graph out << "digraph {\n"; for (Nodes::const_iterator it = m_nodes.begin(), it_end = m_nodes.end(); it != it_end; ++it) { Node const &n = *it; out << " " << node_identifier_map[n] << " [label=\""; print_string_with_newlines_as_char_literals(out, n.m_shortified_name); out << "\", fontname=\"courier\", labeljust=\"l\", shape=box];\n"; } out << '\n'; for (Edges::const_iterator it = m_edges.begin(), it_end = m_edges.end(); it != it_end; ++it) { Edge const &e = *it; out << " " << node_identifier_map[e.m_source] << " -> " << node_identifier_map[e.m_target] << ";\n"; } out << "}\n"; } private: static void print_string_with_newlines_as_char_literals (std::ostream &out, std::string const &s) { for (std::string::const_iterator it = s.begin(), it_end = s.end(); it != it_end; ++it) { char const &c = *it; if (c == '\n') out << "\\n"; else out << c; } } Nodes m_nodes; Edges m_edges; }; std::ostream &operator << (std::ostream &out, Graph::Node const &n) { if (n.m_shortified_name == n.m_full_name) return out << "Node(" << n.m_full_name << ')'; else return out << "Node(" << n.m_shortified_name << ',' << n.m_full_name << ')'; } std::ostream &operator << (std::ostream &out, Graph::Edge const &e) { return out << "Edge(" << e.m_source << " -> " << e.m_target << ')'; } std::ostream &operator << (std::ostream &out, Graph const &g) { out << "Graph(\n"; for (Graph::Nodes::const_iterator it = g.nodes().begin(), it_end = g.nodes().end(); it != it_end; ++it) { Graph::Node const &n = *it; out << '\t' << n << '\n'; } out << '\n'; for (Graph::Edges::const_iterator it = g.edges().begin(), it_end = g.edges().end(); it != it_end; ++it) { Graph::Edge const &e = *it; out << '\t' << e << '\n'; } return out << ")\n"; } // base case template <Uint32 SHORTIFY_DEPTH_, typename Concept_> void add_parent_concept_type_list_to_graph_recursive (Concept_ const &, EmptyTypeList const &, Graph &g) { // nothing to add } template <Uint32 SHORTIFY_DEPTH_, typename Concept_, typename HeadType_, typename BodyTypeList_> void add_parent_concept_type_list_to_graph_recursive ( Concept_ const &concept, TypeList_t<HeadType_,BodyTypeList_> const &parent_concept_type_list, Graph &g) { // add the parent nodes and edges connecting concept to them Graph::Node concept_node(FORMAT((Pretty<TypeStringOf_t<Concept_>,SHORTIFY_DEPTH_>())), FORMAT((Pretty<TypeStringOf_t<Concept_>,0>()))); assert(g.nodes().find(concept_node) != g.nodes().end()); Graph::Node parent_node(FORMAT((Pretty<TypeStringOf_t<HeadType_>,SHORTIFY_DEPTH_>())), FORMAT((Pretty<TypeStringOf_t<HeadType_>,0>()))); g.add_node(parent_node); g.add_edge(concept_node, parent_node); add_parent_concept_type_list_to_graph_recursive<SHORTIFY_DEPTH_>(concept, BodyTypeList_(), g); // call this function recursively on each parent add_parent_concept_type_list_to_graph_recursive<SHORTIFY_DEPTH_>(HeadType_(), typename HeadType_::ParentTypeList(), g); } template <Uint32 SHORTIFY_DEPTH_, typename Concept_> void add_concept_hierarchy_to_graph (Concept_ const &root, Graph &g) { Graph::Node n(FORMAT((Pretty<TypeStringOf_t<Concept_>,SHORTIFY_DEPTH_>())), FORMAT((Pretty<TypeStringOf_t<Concept_>,0>()))); g.add_node(n); add_parent_concept_type_list_to_graph_recursive<SHORTIFY_DEPTH_>(root, typename Concept_::ParentTypeList(), g); } } // end of namespace Tenh #endif // TENH_CONCEPTUAL_CONCEPTUALINHERITANCEGRAPH_HPP_<|endoftext|>
<commit_before>#pragma once // std #include <cstdint> #include <unordered_map> // project #include "depthai-shared/common/UsbSpeed.hpp" #include "depthai-shared/common/optional.hpp" #include "depthai-shared/device/BoardConfig.hpp" #include "depthai-shared/utility/Serialization.hpp" #include "depthai-shared/xlink/XLinkConstants.hpp" namespace dai { constexpr static uint32_t BOARD_CONFIG_MAGIC1 = 0x78010000U; constexpr static uint32_t BOARD_CONFIG_MAGIC2 = 0x21ea17e6U; struct BoardConfig { // USB related config struct USB { uint16_t vid = 0x03e7, pid = 0xf63b; uint16_t flashBootedVid = 0x03e7, flashBootedPid = 0xf63d; UsbSpeed maxSpeed = UsbSpeed::SUPER; }; USB usb; // Watchdog config tl::optional<uint32_t> watchdogTimeoutMs; tl::optional<uint32_t> watchdogInitialDelayMs; // GPIO config struct GPIO { enum Mode : std::int8_t { ALT_MODE_0 = 0, ALT_MODE_1, ALT_MODE_2, ALT_MODE_3, ALT_MODE_4, ALT_MODE_5, ALT_MODE_6, DIRECT }; Mode mode = Mode::DIRECT; enum Direction : std::int8_t { INPUT = 0, OUTPUT = 1 }; Direction direction = Direction::INPUT; enum Level : std::int8_t { LOW = 0, HIGH = 1 }; Level level = Level::LOW; enum Pull : std::int8_t { NO_PULL = 0, PULL_UP = 1, PULL_DOWN = 2, BUS_KEEPER = 3 }; Pull pull = Pull::NO_PULL; /// Drive strength in mA (2, 4, 8 and 12mA) std::int8_t drive = 0; bool schmitt = false, slewFast = false; GPIO() = default; GPIO(Direction direction) : direction(direction) {} GPIO(Direction direction, Level level) : direction(direction), level(level) {} GPIO(Direction direction, Level level, Pull pull) : direction(direction), level(level), pull(pull) {} GPIO(Direction direction, Mode mode) : mode(mode), direction(direction) {} GPIO(Direction direction, Mode mode, Pull pull) : mode(mode), direction(direction), pull(pull) {} }; std::unordered_map<std::int8_t, GPIO> gpio; // Uart config /// UART instance config struct UART { // TBD // std::int8_t tx, rx; std::int8_t tmp; }; /// UART instance map std::unordered_map<std::int8_t, UART> uart; }; DEPTHAI_SERIALIZE_EXT(BoardConfig::USB, vid, pid, flashBootedVid, flashBootedPid, maxSpeed); DEPTHAI_SERIALIZE_EXT(BoardConfig::GPIO, mode, direction, level, pull, drive, schmitt, slewFast); DEPTHAI_SERIALIZE_EXT(BoardConfig::UART, tmp); DEPTHAI_SERIALIZE_EXT(BoardConfig, usb, watchdogTimeoutMs, watchdogInitialDelayMs, gpio, uart); } // namespace dai <commit_msg>Added GPIO drive as enum<commit_after>#pragma once // std #include <cstdint> #include <unordered_map> // project #include "depthai-shared/common/UsbSpeed.hpp" #include "depthai-shared/common/optional.hpp" #include "depthai-shared/device/BoardConfig.hpp" #include "depthai-shared/utility/Serialization.hpp" #include "depthai-shared/xlink/XLinkConstants.hpp" namespace dai { constexpr static uint32_t BOARD_CONFIG_MAGIC1 = 0x78010000U; constexpr static uint32_t BOARD_CONFIG_MAGIC2 = 0x21ea17e6U; struct BoardConfig { // USB related config struct USB { uint16_t vid = 0x03e7, pid = 0xf63b; uint16_t flashBootedVid = 0x03e7, flashBootedPid = 0xf63d; UsbSpeed maxSpeed = UsbSpeed::SUPER; }; USB usb; // Watchdog config tl::optional<uint32_t> watchdogTimeoutMs; tl::optional<uint32_t> watchdogInitialDelayMs; // GPIO config struct GPIO { enum Mode : std::int8_t { ALT_MODE_0 = 0, ALT_MODE_1, ALT_MODE_2, ALT_MODE_3, ALT_MODE_4, ALT_MODE_5, ALT_MODE_6, DIRECT }; Mode mode = Mode::DIRECT; enum Direction : std::int8_t { INPUT = 0, OUTPUT = 1 }; Direction direction = Direction::INPUT; enum Level : std::int8_t { LOW = 0, HIGH = 1 }; Level level = Level::LOW; enum Pull : std::int8_t { NO_PULL = 0, PULL_UP = 1, PULL_DOWN = 2, BUS_KEEPER = 3 }; Pull pull = Pull::NO_PULL; /// Drive strength in mA (2, 4, 8 and 12mA) enum Drive : std::int8_t { MA_2 = 2, MA_4 = 4, MA_8 = 8, MA_12 = 12 }; Drive drive = MA_2; bool schmitt = false, slewFast = false; GPIO() = default; GPIO(Direction direction) : direction(direction) {} GPIO(Direction direction, Level level) : direction(direction), level(level) {} GPIO(Direction direction, Level level, Pull pull) : direction(direction), level(level), pull(pull) {} GPIO(Direction direction, Mode mode) : mode(mode), direction(direction) {} GPIO(Direction direction, Mode mode, Pull pull) : mode(mode), direction(direction), pull(pull) {} }; std::unordered_map<std::int8_t, GPIO> gpio; // Uart config /// UART instance config struct UART { // TBD // std::int8_t tx, rx; std::int8_t tmp; }; /// UART instance map std::unordered_map<std::int8_t, UART> uart; }; DEPTHAI_SERIALIZE_EXT(BoardConfig::USB, vid, pid, flashBootedVid, flashBootedPid, maxSpeed); DEPTHAI_SERIALIZE_EXT(BoardConfig::GPIO, mode, direction, level, pull, drive, schmitt, slewFast); DEPTHAI_SERIALIZE_EXT(BoardConfig::UART, tmp); DEPTHAI_SERIALIZE_EXT(BoardConfig, usb, watchdogTimeoutMs, watchdogInitialDelayMs, gpio, uart); } // namespace dai <|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2014 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #include <mapnik/json/topojson_grammar.hpp> namespace mapnik { namespace topojson { namespace qi = boost::spirit::qi; namespace phoenix = boost::phoenix; namespace fusion = boost::fusion; template <typename Iterator, typename ErrorHandler> topojson_grammar<Iterator, ErrorHandler>::topojson_grammar() : topojson_grammar::base_type(topology, "topojson") { qi::lit_type lit; qi::double_type double_; qi::int_type int_; qi::omit_type omit; qi::_val_type _val; qi::_1_type _1; qi::_2_type _2; qi::_3_type _3; qi::_4_type _4; qi::_r1_type _r1; using qi::fail; using qi::on_error; using phoenix::push_back; using phoenix::construct; // generic json types json_.value = json_.object | json_.array | json_.string_ | json_.number ; json_.pairs = json_.key_value % lit(',') ; json_.key_value = (json_.string_ >> lit(':') >> json_.value) ; json_.object = lit('{') >> *json_.pairs >> lit('}') ; json_.array = lit('[') >> json_.value >> *(lit(',') >> json_.value) >> lit(']') ; json_.number = json_.strict_double[_val = json_.double_converter(_1)] | json_.int__[_val = json_.integer_converter(_1)] | lit("true")[_val = true] | lit("false")[_val = false] | lit("null")[_val = construct<value_null>()] ; // topo json topology = lit('{') >> lit("\"type\"") >> lit(':') >> lit("\"Topology\"") >> ( (lit(',') >> objects) ^ ( lit(',') >> arcs) ^ (lit(',') >> transform) ^ (lit(',') >> bbox)) >> lit('}') ; transform = lit("\"transform\"") >> lit(':') >> lit('{') >> lit("\"scale\"") >> lit(':') >> lit('[') >> double_ >> lit(',') >> double_ >> lit(']') >> lit(',') >> lit("\"translate\"") >> lit(':') >> lit('[') >> double_ >> lit(',') >> double_ >> lit(']') >> lit('}') ; bbox = lit("\"bbox\"") >> lit(':') >> lit('[') >> double_ >> lit(',') >> double_ >> lit(',') >> double_ >> lit(',') >> double_ >> lit(']') ; objects = lit("\"objects\"") >> lit(':') >> lit('{') >> -((omit[json_.string_] >> lit(':') >> (geometry_collection(_val) | geometry)) % lit(',')) >> lit('}') ; geometry = point | linestring | polygon | multi_point | multi_linestring | multi_polygon | omit[json_.object] ; geometry_collection = lit('{') >> lit("\"type\"") >> lit(':') >> lit("\"GeometryCollection\"") >> lit(',') >> lit("\"geometries\"") >> lit(':') >> lit('[') >> -(geometry[push_back(_r1, _1)] % lit(',')) >> lit(']') >> lit('}') ; point = lit('{') >> lit("\"type\"") >> lit(':') >> lit("\"Point\"") >> ((lit(',') >> lit("\"coordinates\"") >> lit(':') >> coordinate) ^ (lit(',') >> properties) /*^ (lit(',') >> omit[id])*/) >> lit('}') ; multi_point = lit('{') >> lit("\"type\"") >> lit(':') >> lit("\"MultiPoint\"") >> ((lit(',') >> lit("\"coordinates\"") >> lit(':') >> lit('[') >> -(coordinate % lit(',')) >> lit(']')) ^ (lit(',') >> properties) ^ (lit(',') >> omit[id])) >> lit('}') ; linestring = lit('{') >> lit("\"type\"") >> lit(':') >> lit("\"LineString\"") >> ((lit(',') >> lit("\"arcs\"") >> lit(':') >> lit('[') >> int_ >> lit(']')) ^ (lit(',') >> properties) ^ (lit(',') >> omit[id])) >> lit('}') ; multi_linestring = lit('{') >> lit("\"type\"") >> lit(':') >> lit("\"MultiLineString\"") >> ((lit(',') >> lit("\"arcs\"") >> lit(':') >> lit('[') >> -((lit('[') >> int_ >> lit(']')) % lit(',')) >> lit(']')) ^ (lit(',') >> properties) ^ (lit(',') >> omit[id])) >> lit('}') ; polygon = lit('{') >> lit("\"type\"") >> lit(':') >> lit("\"Polygon\"") >> ((lit(',') >> lit("\"arcs\"") >> lit(':') >> lit('[') >> -(ring % lit(',')) >> lit(']')) ^ (lit(',') >> properties) ^ (lit(',') >> omit[id])) >> lit('}') ; multi_polygon = lit('{') >> lit("\"type\"") >> lit(':') >> lit("\"MultiPolygon\"") >> ((lit(',') >> lit("\"arcs\"") >> lit(':') >> lit('[') >> -((lit('[') >> -(ring % lit(',')) >> lit(']')) % lit(',')) >> lit(']')) ^ (lit(',') >> properties) ^ (lit(',') >> omit[id])) >> lit('}') ; id = lit("\"id\"") >> lit(':') >> omit[json_.value] ; ring = lit('[') >> -(int_ % lit(',')) >> lit(']') ; properties = lit("\"properties\"") >> lit(':') >> (( lit('{') >> attributes >> lit('}')) | json_.object) ; attributes = (json_.string_ >> lit(':') >> attribute_value) % lit(',') ; attribute_value %= json_.number | json_.string_ ; arcs = lit("\"arcs\"") >> lit(':') >> lit('[') >> -( arc % lit(',')) >> lit(']') ; arc = lit('[') >> -(coordinate % lit(',')) >> lit(']') ; coordinate = lit('[') >> double_ >> lit(',') >> double_ >> lit(']'); topology.name("topology"); transform.name("transform"); objects.name("objects"); arc.name("arc"); arcs.name("arcs"); json_.value.name("value"); coordinate.name("coordinate"); point.name("point"); multi_point.name("multi_point"); linestring.name("linestring"); polygon.name("polygon"); multi_polygon.name("multi_polygon"); geometry_collection.name("geometry_collection"); // error handler on_error<fail>(topology, error_handler(_1, _2, _3, _4)); } }} <commit_msg>topojson grammar - add optional bbox element which is omitted<commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2014 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #include <mapnik/json/topojson_grammar.hpp> namespace mapnik { namespace topojson { namespace qi = boost::spirit::qi; namespace phoenix = boost::phoenix; namespace fusion = boost::fusion; template <typename Iterator, typename ErrorHandler> topojson_grammar<Iterator, ErrorHandler>::topojson_grammar() : topojson_grammar::base_type(topology, "topojson") { qi::lit_type lit; qi::double_type double_; qi::int_type int_; qi::omit_type omit; qi::_val_type _val; qi::_1_type _1; qi::_2_type _2; qi::_3_type _3; qi::_4_type _4; qi::_r1_type _r1; using qi::fail; using qi::on_error; using phoenix::push_back; using phoenix::construct; // generic json types json_.value = json_.object | json_.array | json_.string_ | json_.number ; json_.pairs = json_.key_value % lit(',') ; json_.key_value = (json_.string_ >> lit(':') >> json_.value) ; json_.object = lit('{') >> *json_.pairs >> lit('}') ; json_.array = lit('[') >> json_.value >> *(lit(',') >> json_.value) >> lit(']') ; json_.number = json_.strict_double[_val = json_.double_converter(_1)] | json_.int__[_val = json_.integer_converter(_1)] | lit("true")[_val = true] | lit("false")[_val = false] | lit("null")[_val = construct<value_null>()] ; // topo json topology = lit('{') >> lit("\"type\"") >> lit(':') >> lit("\"Topology\"") >> ( (lit(',') >> objects) ^ ( lit(',') >> arcs) ^ (lit(',') >> transform) ^ (lit(',') >> bbox)) >> lit('}') ; transform = lit("\"transform\"") >> lit(':') >> lit('{') >> lit("\"scale\"") >> lit(':') >> lit('[') >> double_ >> lit(',') >> double_ >> lit(']') >> lit(',') >> lit("\"translate\"") >> lit(':') >> lit('[') >> double_ >> lit(',') >> double_ >> lit(']') >> lit('}') ; bbox = lit("\"bbox\"") >> lit(':') >> lit('[') >> double_ >> lit(',') >> double_ >> lit(',') >> double_ >> lit(',') >> double_ >> lit(']') ; objects = lit("\"objects\"") >> lit(':') >> lit('{') >> -((omit[json_.string_] >> lit(':') >> (geometry_collection(_val) | geometry)) % lit(',')) >> lit('}') ; geometry = point | linestring | polygon | multi_point | multi_linestring | multi_polygon | omit[json_.object] ; geometry_collection = lit('{') >> lit("\"type\"") >> lit(':') >> lit("\"GeometryCollection\"") >> -(lit(',') >> omit[bbox]) >> lit(',') >> lit("\"geometries\"") >> lit(':') >> lit('[') >> -(geometry[push_back(_r1, _1)] % lit(',')) >> lit(']') >> lit('}') ; point = lit('{') >> lit("\"type\"") >> lit(':') >> lit("\"Point\"") >> -(lit(',') >> omit[bbox]) >> ((lit(',') >> lit("\"coordinates\"") >> lit(':') >> coordinate) ^ (lit(',') >> properties) /*^ (lit(',') >> omit[id])*/) >> lit('}') ; multi_point = lit('{') >> lit("\"type\"") >> lit(':') >> lit("\"MultiPoint\"") >> -(lit(',') >> omit[bbox]) >> ((lit(',') >> lit("\"coordinates\"") >> lit(':') >> lit('[') >> -(coordinate % lit(',')) >> lit(']')) ^ (lit(',') >> properties) ^ (lit(',') >> omit[id])) >> lit('}') ; linestring = lit('{') >> lit("\"type\"") >> lit(':') >> lit("\"LineString\"") >> ((lit(',') >> lit("\"arcs\"") >> lit(':') >> lit('[') >> int_ >> lit(']')) ^ (lit(',') >> properties) ^ (lit(',') >> omit[id])) >> lit('}') ; multi_linestring = lit('{') >> lit("\"type\"") >> lit(':') >> lit("\"MultiLineString\"") >> -(lit(',') >> omit[bbox]) >> ((lit(',') >> lit("\"arcs\"") >> lit(':') >> lit('[') >> -((lit('[') >> int_ >> lit(']')) % lit(',')) >> lit(']')) ^ (lit(',') >> properties) ^ (lit(',') >> omit[id])) >> lit('}') ; polygon = lit('{') >> lit("\"type\"") >> lit(':') >> lit("\"Polygon\"") >> -(lit(',') >> omit[bbox]) >> ((lit(',') >> lit("\"arcs\"") >> lit(':') >> lit('[') >> -(ring % lit(',')) >> lit(']')) ^ (lit(',') >> properties) ^ (lit(',') >> omit[id])) >> lit('}') ; multi_polygon = lit('{') >> lit("\"type\"") >> lit(':') >> lit("\"MultiPolygon\"") >> -(lit(',') >> omit[bbox]) >> ((lit(',') >> lit("\"arcs\"") >> lit(':') >> lit('[') >> -((lit('[') >> -(ring % lit(',')) >> lit(']')) % lit(',')) >> lit(']')) ^ (lit(',') >> properties) ^ (lit(',') >> omit[id])) >> lit('}') ; id = lit("\"id\"") >> lit(':') >> omit[json_.value] ; ring = lit('[') >> -(int_ % lit(',')) >> lit(']') ; properties = lit("\"properties\"") >> lit(':') >> (( lit('{') >> attributes >> lit('}')) | json_.object) ; attributes = (json_.string_ >> lit(':') >> attribute_value) % lit(',') ; attribute_value %= json_.number | json_.string_ ; arcs = lit("\"arcs\"") >> lit(':') >> lit('[') >> -( arc % lit(',')) >> lit(']') ; arc = lit('[') >> -(coordinate % lit(',')) >> lit(']') ; coordinate = lit('[') >> double_ >> lit(',') >> double_ >> lit(']'); topology.name("topology"); transform.name("transform"); objects.name("objects"); arc.name("arc"); arcs.name("arcs"); json_.value.name("value"); coordinate.name("coordinate"); point.name("point"); multi_point.name("multi_point"); linestring.name("linestring"); polygon.name("polygon"); multi_polygon.name("multi_polygon"); geometry_collection.name("geometry_collection"); // error handler on_error<fail>(topology, error_handler(_1, _2, _3, _4)); } }} <|endoftext|>
<commit_before>#pragma once #include <cstddef> #include <boost/iterator/counting_iterator.hpp> #include <boost/iterator/transform_iterator.hpp> #include <boost/iterator/iterator_facade.hpp> #include "andres/graph/grid-graph.hxx" #include "nifty/tools/runtime_check.hxx" #include "nifty/graph/undirected_graph_base.hxx" #include "nifty/graph/detail/adjacency.hxx" #include "nifty/graph/graph_tags.hxx" #include "nifty/parallel/threadpool.hxx" #include "nifty/array/arithmetic_array.hxx" namespace nifty{ namespace graph{ namespace detail_graph{ template<std::size_t DIM, bool SIMPLE_NH> class UndirectedGridGraphIter{ public: typedef andres::graph::GridGraph<DIM> AGridGraph; typedef typename AGridGraph::AdjacencyIterator AGridGraphAdjacencyIter; typedef UndirectedAdjacency<int64_t,int64_t,int64_t,int64_t> NodeAdjacency; struct UnaryFunction{ typedef NodeAdjacency value_type; template<class ADJ> NodeAdjacency operator()(const ADJ & adjacency)const{ return NodeAdjacency(adjacency.vertex(), adjacency.vertex()); } }; typedef boost::transform_iterator< UnaryFunction, typename AGridGraph::AdjacencyIterator, NodeAdjacency, NodeAdjacency > OldAdjacencyIter; class AdjacencyIter : public boost::iterator_facade< AdjacencyIter, NodeAdjacency, std::random_access_iterator_tag, const NodeAdjacency & > { public: AdjacencyIter(const AGridGraphAdjacencyIter & iter) : iter_(iter), adjacency_(){ } bool equal(const AdjacencyIter & other)const{ return iter_ == other.iter_; } void increment(){ ++iter_; } void dencrement(){ --iter_; } void advance(const std::size_t n){ iter_+=n; } std::ptrdiff_t distance_to(const AdjacencyIter & other)const{ return std::distance(iter_, other.iter_); } const NodeAdjacency & dereference()const{ adjacency_ = NodeAdjacency(iter_->vertex(), iter_->edge()); return adjacency_; } private: mutable AGridGraphAdjacencyIter iter_; mutable NodeAdjacency adjacency_; }; class NodeIter : public boost::counting_iterator<int64_t>{ using boost::counting_iterator<int64_t>::counting_iterator; using boost::counting_iterator<int64_t>::operator=; }; class EdgeIter : public boost::counting_iterator<int64_t>{ using boost::counting_iterator<int64_t>::counting_iterator; using boost::counting_iterator<int64_t>::operator=; }; }; }; template<std::size_t DIM, bool SIMPLE_NH> class UndirectedGridGraph; template<std::size_t DIM> class UndirectedGridGraph<DIM,true> : public UndirectedGraphBase< UndirectedGridGraph<DIM, true>, typename detail_graph::UndirectedGridGraphIter<DIM,true>::NodeIter, typename detail_graph::UndirectedGridGraphIter<DIM,true>::EdgeIter, typename detail_graph::UndirectedGridGraphIter<DIM,true>::AdjacencyIter > { private: typedef andres::graph::GridGraph<DIM> AndresGridGraphType; typedef typename AndresGridGraphType::VertexCoordinate AndresVertexCoordinate; public: typedef nifty::array::StaticArray<int64_t, DIM> ShapeType; typedef nifty::array::StaticArray<int64_t, DIM> CoordinateType; typedef typename detail_graph::UndirectedGridGraphIter<DIM,true>::NodeIter NodeIter; typedef typename detail_graph::UndirectedGridGraphIter<DIM,true>::EdgeIter EdgeIter; typedef typename detail_graph::UndirectedGridGraphIter<DIM,true>::AdjacencyIter AdjacencyIter; typedef ContiguousTag EdgeIdTag; typedef ContiguousTag NodeIdTag; typedef SortedTag EdgeIdOrderTag; typedef SortedTag NodeIdOrderTag; UndirectedGridGraph() : gridGraph_(){ } template<class T> UndirectedGridGraph(const nifty::array::StaticArray<T, DIM> & shape) : gridGraph_(){ AndresVertexCoordinate ashape; std::copy(shape.rbegin(), shape.rend(), ashape.begin()); gridGraph_.assign(ashape); } template<class T> void assign(const nifty::array::StaticArray<T, DIM> & shape){ AndresVertexCoordinate ashape; std::copy(shape.rbegin(), shape.rend(), ashape.begin()); gridGraph_.assign(ashape); } //void assign(const uint64_t numberOfNodes = 0, const uint64_t reserveNumberOfEdges = 0); // MUST IMPL INTERFACE int64_t u(const int64_t e)const{ return gridGraph_.vertexOfEdge(e,0); } int64_t v(const int64_t e)const{ return gridGraph_.vertexOfEdge(e,1); } int64_t findEdge(const int64_t u, const int64_t v)const{ const auto r = gridGraph_.findEdge(u,v); if(r.first) return r.second; else return -1; } int64_t nodeIdUpperBound() const{ return numberOfNodes() == 0 ? 0 : numberOfNodes()-1; } int64_t edgeIdUpperBound() const{ return numberOfEdges() == 0 ? 0 : numberOfEdges()-1; } uint64_t numberOfEdges() const{ return gridGraph_.numberOfEdges(); } uint64_t numberOfNodes() const{ return gridGraph_.numberOfVertices(); } NodeIter nodesBegin()const{ return NodeIter(0); } NodeIter nodesEnd()const{ return NodeIter(this->numberOfNodes()); } EdgeIter edgesBegin()const{ return EdgeIter(0); } EdgeIter edgesEnd()const{ return EdgeIter(this->numberOfEdges()); } AdjacencyIter adjacencyBegin(const int64_t node)const{ return AdjacencyIter(gridGraph_.adjacenciesFromVertexBegin(node)); } AdjacencyIter adjacencyEnd(const int64_t node)const{ return AdjacencyIter(gridGraph_.adjacenciesFromVertexEnd(node)); } AdjacencyIter adjacencyOutBegin(const int64_t node)const{ return AdjacencyIter(gridGraph_.adjacenciesFromVertexBegin(node)); } AdjacencyIter adjacencyOutEnd(const int64_t node)const{ return AdjacencyIter(gridGraph_.adjacenciesFromVertexEnd(node)); } // optional (with default impl in base) //std::pair<int64_t,int64_t> uv(const int64_t e)const; template<class F> void forEachEdge(F && f)const{ for(uint64_t edge=0; edge< numberOfEdges(); ++edge){ f(edge); } } template<class F> void forEachNode(F && f)const{ for(uint64_t node=0; node< numberOfNodes(); ++node){ f(node); } } // serialization de-serialization uint64_t serializationSize() const{ return DIM + 1; } template<class ITER> void serialize(ITER iter) const{ for(auto d=0; d<DIM; ++d){ *iter = gridGraph_.shape(d); ++iter; } // simple nh? *iter = true; ++iter; } template<class ITER> void deserialize(ITER iter); /** * @brief convert an image with DIM dimension to an edge map * @details convert an image with DIM dimension to an edge map * by applying a binary functor to the values of a node map at * the endpoints of an edge. * * @param image the input image * @param binaryFunctor a binary functor * @param[out] the result edge map * * @return [description] */ template<class IMAGE, class BINARY_FUNCTOR, class EDGE_MAP> void imageToEdgeMap( const IMAGE & image, BINARY_FUNCTOR binaryFunctor, EDGE_MAP & edgeMap )const{ for(const auto edge : this->edges()){ const auto uv = this->uv(edge); CoordinateType cU,cV; nodeToCoordinate(uv.first, cU); nodeToCoordinate(uv.second, cV); const auto uVal = image(cU.asStdArray()); const auto vVal = image(cU.asStdArray()); edgeMap[edge] = binaryFunctor(uVal, vVal); } } // FIXME this can probably be done more effiicently /** * @brief convert an affinity map with DIM+1 dimension to an edge map * @details convert an affinity map with DIM+1 dimension to an edge map * by assining the affinity values to corresponding affinity values * * @param image the input affinities * @param[out] the result edge map * * @return [description] */ template<class AFFINITIES, class EDGE_MAP> void affinitiesToEdgeMap( const AFFINITIES & affinities, EDGE_MAP & edgeMap )const{ NIFTY_CHECK_OP(affinities.shape(0), ==, DIM, "wrong number of affinity channels") for(auto d=1; d<DIM+1; ++d){ NIFTY_CHECK_OP(shape(d-1), ==, affinities.shape(d), "wrong shape") } typedef nifty::array::StaticArray<int64_t, DIM+1> AffinityCoordType; CoordinateType cU,cV; for(const auto edge : this->edges()){ const auto uv = this->uv(edge); nodeToCoordinate(uv.first, cU); nodeToCoordinate(uv.second, cV); // find the correct affinity edge AffinityCoordType affCoord; for(size_t d = 0; d < DIM; ++d) { auto diff = cU[d] - cV[d]; if(diff == 0) { affCoord[d + 1] = cU[d]; } else { // TODO max for different direction convention affCoord[d + 1] = std::min(cU[d], cV[d]); affCoord[0] = d; } } edgeMap[edge] = affinities(affCoord.asStdArray()); } } template<class AFFINITIES, class EDGE_MAP, class ITER> void longRangeAffinitiesToLiftedEdges( const AFFINITIES & affinities, EDGE_MAP & edgeMap, ITER rangesBegin, // iterator to the ranges of the affinities ITER axesBegin // iterator to the axes of the affinities ) const { typedef nifty::array::StaticArray<int64_t, DIM+1> AffinityCoordType; for(auto d=1; d<DIM+1; ++d){ NIFTY_CHECK_OP(shape(d-1), ==, affinities.shape(d), "wrong shape") } size_t affLen = affinities.shape(0); std::vector<int> ranges(rangesBegin, rangesBegin + affLen); std::vector<int> axes(axesBegin, axesBegin + affLen); AffinityCoordType affCoord; CoordinateType cU, cV; size_t axis, range; // iterate over the affinties for(size_t edgeId = 0; edgeId < affinities.size(); ++edgeId) { affinities.indexToCoordinates(edgeId, affCoord.begin()); axis = axes[affCoord[0]]; range = ranges[affCoord[0]]; // for(size_t d = 0; d < DIM; ++d) { cU[d] = affCoord[d+1]; if(d == axis) { cV[d] = affCoord[d+1] + range; // range check if(cV[d] >= shape(d) || cV[d] < 0) { continue; } } else { cV[d] = affCoord[d+1]; } auto u = coordianteToNode(cU); auto v = coordianteToNode(cV); edgeMap.emplace(std::make_pair(std::min(u,v), std::max(u,v)), affinities(affCoord.asStdArray())); } } } /** * @brief convert an image with DIM dimension to an edge map * @details convert an image with DIM dimension to an edge map * by taking the values of the image at the * interpixel coordinates. * The shape of the image must be 2*shape-1 * * * @param image the input image * @param binaryFunctor a binary functor * @param[out] the result edge map * * @return [description] */ template<class IMAGE, class EDGE_MAP> void imageToInterpixelEdgeMap( const IMAGE & image, EDGE_MAP & edgeMap )const{ for(auto d=0; d<DIM; ++d){ NIFTY_CHECK_OP(shape(d)*2-1, ==, image.shape(d), "wrong shape foer image to interpixel edge map") } for(const auto edge : this->edges()){ const auto uv = this->uv(edge); CoordinateType cU,cV; nodeToCoordinate(uv.first, cU); nodeToCoordinate(uv.second, cV); const auto uVal = image(cU.asStdArray()); cU += cV; edgeMap[edge] = image(cU.asStdArray()); } } uint64_t shape(const std::size_t d)const{ return gridGraph_.shape(DIM-1-d); } // COORDINATE RELATED CoordinateType nodeToCoordinate(const uint64_t node)const{ CoordinateType ret; nodeToCoordinate(node, ret); return ret; } template<class NODE_COORDINATE> void nodeToCoordinate( const uint64_t node, NODE_COORDINATE & coordinate )const{ AndresVertexCoordinate aCoordinate; gridGraph_.vertex(node, aCoordinate); for(auto d=0; d<DIM; ++d){ coordinate[d] = aCoordinate[DIM-1-d]; } } template<class NODE_COORDINATE> uint64_t coordianteToNode(const NODE_COORDINATE & coordinate)const{ AndresVertexCoordinate aCoordinate; for(auto d=0; d<DIM; ++d){ aCoordinate[DIM-1-d] = coordinate[d]; } return gridGraph_.vertex(aCoordinate); } private: andres::graph::GridGraph<DIM> gridGraph_; }; } // namespace nifty::graph } // namespace nifty <commit_msg>Fix lifted affinities in grid rag<commit_after>#pragma once #include <cstddef> #include <boost/iterator/counting_iterator.hpp> #include <boost/iterator/transform_iterator.hpp> #include <boost/iterator/iterator_facade.hpp> #include "andres/graph/grid-graph.hxx" #include "nifty/tools/runtime_check.hxx" #include "nifty/graph/undirected_graph_base.hxx" #include "nifty/graph/detail/adjacency.hxx" #include "nifty/graph/graph_tags.hxx" #include "nifty/parallel/threadpool.hxx" #include "nifty/array/arithmetic_array.hxx" namespace nifty{ namespace graph{ namespace detail_graph{ template<std::size_t DIM, bool SIMPLE_NH> class UndirectedGridGraphIter{ public: typedef andres::graph::GridGraph<DIM> AGridGraph; typedef typename AGridGraph::AdjacencyIterator AGridGraphAdjacencyIter; typedef UndirectedAdjacency<int64_t,int64_t,int64_t,int64_t> NodeAdjacency; struct UnaryFunction{ typedef NodeAdjacency value_type; template<class ADJ> NodeAdjacency operator()(const ADJ & adjacency)const{ return NodeAdjacency(adjacency.vertex(), adjacency.vertex()); } }; typedef boost::transform_iterator< UnaryFunction, typename AGridGraph::AdjacencyIterator, NodeAdjacency, NodeAdjacency > OldAdjacencyIter; class AdjacencyIter : public boost::iterator_facade< AdjacencyIter, NodeAdjacency, std::random_access_iterator_tag, const NodeAdjacency & > { public: AdjacencyIter(const AGridGraphAdjacencyIter & iter) : iter_(iter), adjacency_(){ } bool equal(const AdjacencyIter & other)const{ return iter_ == other.iter_; } void increment(){ ++iter_; } void dencrement(){ --iter_; } void advance(const std::size_t n){ iter_+=n; } std::ptrdiff_t distance_to(const AdjacencyIter & other)const{ return std::distance(iter_, other.iter_); } const NodeAdjacency & dereference()const{ adjacency_ = NodeAdjacency(iter_->vertex(), iter_->edge()); return adjacency_; } private: mutable AGridGraphAdjacencyIter iter_; mutable NodeAdjacency adjacency_; }; class NodeIter : public boost::counting_iterator<int64_t>{ using boost::counting_iterator<int64_t>::counting_iterator; using boost::counting_iterator<int64_t>::operator=; }; class EdgeIter : public boost::counting_iterator<int64_t>{ using boost::counting_iterator<int64_t>::counting_iterator; using boost::counting_iterator<int64_t>::operator=; }; }; }; template<std::size_t DIM, bool SIMPLE_NH> class UndirectedGridGraph; template<std::size_t DIM> class UndirectedGridGraph<DIM,true> : public UndirectedGraphBase< UndirectedGridGraph<DIM, true>, typename detail_graph::UndirectedGridGraphIter<DIM,true>::NodeIter, typename detail_graph::UndirectedGridGraphIter<DIM,true>::EdgeIter, typename detail_graph::UndirectedGridGraphIter<DIM,true>::AdjacencyIter > { private: typedef andres::graph::GridGraph<DIM> AndresGridGraphType; typedef typename AndresGridGraphType::VertexCoordinate AndresVertexCoordinate; public: typedef nifty::array::StaticArray<int64_t, DIM> ShapeType; typedef nifty::array::StaticArray<int64_t, DIM> CoordinateType; typedef typename detail_graph::UndirectedGridGraphIter<DIM,true>::NodeIter NodeIter; typedef typename detail_graph::UndirectedGridGraphIter<DIM,true>::EdgeIter EdgeIter; typedef typename detail_graph::UndirectedGridGraphIter<DIM,true>::AdjacencyIter AdjacencyIter; typedef ContiguousTag EdgeIdTag; typedef ContiguousTag NodeIdTag; typedef SortedTag EdgeIdOrderTag; typedef SortedTag NodeIdOrderTag; UndirectedGridGraph() : gridGraph_(){ } template<class T> UndirectedGridGraph(const nifty::array::StaticArray<T, DIM> & shape) : gridGraph_(){ AndresVertexCoordinate ashape; std::copy(shape.rbegin(), shape.rend(), ashape.begin()); gridGraph_.assign(ashape); } template<class T> void assign(const nifty::array::StaticArray<T, DIM> & shape){ AndresVertexCoordinate ashape; std::copy(shape.rbegin(), shape.rend(), ashape.begin()); gridGraph_.assign(ashape); } //void assign(const uint64_t numberOfNodes = 0, const uint64_t reserveNumberOfEdges = 0); // MUST IMPL INTERFACE int64_t u(const int64_t e)const{ return gridGraph_.vertexOfEdge(e,0); } int64_t v(const int64_t e)const{ return gridGraph_.vertexOfEdge(e,1); } int64_t findEdge(const int64_t u, const int64_t v)const{ const auto r = gridGraph_.findEdge(u,v); if(r.first) return r.second; else return -1; } int64_t nodeIdUpperBound() const{ return numberOfNodes() == 0 ? 0 : numberOfNodes()-1; } int64_t edgeIdUpperBound() const{ return numberOfEdges() == 0 ? 0 : numberOfEdges()-1; } uint64_t numberOfEdges() const{ return gridGraph_.numberOfEdges(); } uint64_t numberOfNodes() const{ return gridGraph_.numberOfVertices(); } NodeIter nodesBegin()const{ return NodeIter(0); } NodeIter nodesEnd()const{ return NodeIter(this->numberOfNodes()); } EdgeIter edgesBegin()const{ return EdgeIter(0); } EdgeIter edgesEnd()const{ return EdgeIter(this->numberOfEdges()); } AdjacencyIter adjacencyBegin(const int64_t node)const{ return AdjacencyIter(gridGraph_.adjacenciesFromVertexBegin(node)); } AdjacencyIter adjacencyEnd(const int64_t node)const{ return AdjacencyIter(gridGraph_.adjacenciesFromVertexEnd(node)); } AdjacencyIter adjacencyOutBegin(const int64_t node)const{ return AdjacencyIter(gridGraph_.adjacenciesFromVertexBegin(node)); } AdjacencyIter adjacencyOutEnd(const int64_t node)const{ return AdjacencyIter(gridGraph_.adjacenciesFromVertexEnd(node)); } // optional (with default impl in base) //std::pair<int64_t,int64_t> uv(const int64_t e)const; template<class F> void forEachEdge(F && f)const{ for(uint64_t edge=0; edge< numberOfEdges(); ++edge){ f(edge); } } template<class F> void forEachNode(F && f)const{ for(uint64_t node=0; node< numberOfNodes(); ++node){ f(node); } } // serialization de-serialization uint64_t serializationSize() const{ return DIM + 1; } template<class ITER> void serialize(ITER iter) const{ for(auto d=0; d<DIM; ++d){ *iter = gridGraph_.shape(d); ++iter; } // simple nh? *iter = true; ++iter; } template<class ITER> void deserialize(ITER iter); /** * @brief convert an image with DIM dimension to an edge map * @details convert an image with DIM dimension to an edge map * by applying a binary functor to the values of a node map at * the endpoints of an edge. * * @param image the input image * @param binaryFunctor a binary functor * @param[out] the result edge map * * @return [description] */ template<class IMAGE, class BINARY_FUNCTOR, class EDGE_MAP> void imageToEdgeMap( const IMAGE & image, BINARY_FUNCTOR binaryFunctor, EDGE_MAP & edgeMap )const{ for(const auto edge : this->edges()){ const auto uv = this->uv(edge); CoordinateType cU,cV; nodeToCoordinate(uv.first, cU); nodeToCoordinate(uv.second, cV); const auto uVal = image(cU.asStdArray()); const auto vVal = image(cU.asStdArray()); edgeMap[edge] = binaryFunctor(uVal, vVal); } } // FIXME this can probably be done more effiicently /** * @brief convert an affinity map with DIM+1 dimension to an edge map * @details convert an affinity map with DIM+1 dimension to an edge map * by assining the affinity values to corresponding affinity values * * @param image the input affinities * @param[out] the result edge map * * @return [description] */ template<class AFFINITIES, class EDGE_MAP> void affinitiesToEdgeMap( const AFFINITIES & affinities, EDGE_MAP & edgeMap )const{ NIFTY_CHECK_OP(affinities.shape(0), ==, DIM, "wrong number of affinity channels") for(auto d=1; d<DIM+1; ++d){ NIFTY_CHECK_OP(shape(d-1), ==, affinities.shape(d), "wrong shape") } typedef nifty::array::StaticArray<int64_t, DIM+1> AffinityCoordType; CoordinateType cU,cV; for(const auto edge : this->edges()){ const auto uv = this->uv(edge); nodeToCoordinate(uv.first, cU); nodeToCoordinate(uv.second, cV); // find the correct affinity edge AffinityCoordType affCoord; for(size_t d = 0; d < DIM; ++d) { auto diff = cU[d] - cV[d]; if(diff == 0) { affCoord[d + 1] = cU[d]; } else { // TODO max for different direction convention affCoord[d + 1] = std::min(cU[d], cV[d]); affCoord[0] = d; } } edgeMap[edge] = affinities(affCoord.asStdArray()); } } template<class AFFINITIES, class EDGE_MAP, class ITER> void longRangeAffinitiesToLiftedEdges( const AFFINITIES & affinities, EDGE_MAP & edgeMap, ITER rangesBegin, // iterator to the ranges of the affinities ITER axesBegin // iterator to the axes of the affinities ) const { typedef nifty::array::StaticArray<int64_t, DIM+1> AffinityCoordType; for(auto d=1; d<DIM+1; ++d){ NIFTY_CHECK_OP(shape(d-1), ==, affinities.shape(d), "wrong shape") } size_t affLen = affinities.shape(0); std::vector<int> ranges(rangesBegin, rangesBegin + affLen); std::vector<int> axes(axesBegin, axesBegin + affLen); AffinityCoordType affCoord; CoordinateType cU, cV; size_t axis, range; // iterate over the affinties for(size_t edgeId = 0; edgeId < affinities.size(); ++edgeId) { affinities.indexToCoordinates(edgeId, affCoord.begin()); axis = axes[affCoord[0]]; range = ranges[affCoord[0]]; for(size_t d = 0; d < DIM; ++d) { cU[d] = affCoord[d+1]; cV[d] = affCoord[d+1]; } cV[axis] += range; // range check if(cV[axis] >= shape(axis) || cV[axis] < 0) { continue; } auto u = coordianteToNode(cU); auto v = coordianteToNode(cV); edgeMap.emplace( std::make_pair(std::min(u,v), std::max(u,v)), affinities(affCoord.asStdArray()) ); } } /** * @brief convert an image with DIM dimension to an edge map * @details convert an image with DIM dimension to an edge map * by taking the values of the image at the * interpixel coordinates. * The shape of the image must be 2*shape-1 * * * @param image the input image * @param binaryFunctor a binary functor * @param[out] the result edge map * * @return [description] */ template<class IMAGE, class EDGE_MAP> void imageToInterpixelEdgeMap( const IMAGE & image, EDGE_MAP & edgeMap )const{ for(auto d=0; d<DIM; ++d){ NIFTY_CHECK_OP(shape(d)*2-1, ==, image.shape(d), "wrong shape foer image to interpixel edge map") } for(const auto edge : this->edges()){ const auto uv = this->uv(edge); CoordinateType cU,cV; nodeToCoordinate(uv.first, cU); nodeToCoordinate(uv.second, cV); const auto uVal = image(cU.asStdArray()); cU += cV; edgeMap[edge] = image(cU.asStdArray()); } } uint64_t shape(const std::size_t d)const{ return gridGraph_.shape(DIM-1-d); } // COORDINATE RELATED CoordinateType nodeToCoordinate(const uint64_t node)const{ CoordinateType ret; nodeToCoordinate(node, ret); return ret; } template<class NODE_COORDINATE> void nodeToCoordinate( const uint64_t node, NODE_COORDINATE & coordinate )const{ AndresVertexCoordinate aCoordinate; gridGraph_.vertex(node, aCoordinate); for(auto d=0; d<DIM; ++d){ coordinate[d] = aCoordinate[DIM-1-d]; } } template<class NODE_COORDINATE> uint64_t coordianteToNode(const NODE_COORDINATE & coordinate)const{ AndresVertexCoordinate aCoordinate; for(auto d=0; d<DIM; ++d){ aCoordinate[DIM-1-d] = coordinate[d]; } return gridGraph_.vertex(aCoordinate); } private: andres::graph::GridGraph<DIM> gridGraph_; }; } // namespace nifty::graph } // namespace nifty <|endoftext|>
<commit_before>// Copyright (c) 2017 Dr. Colin Hirsch and Daniel Frey // Please see LICENSE for license or visit https://github.com/taocpp/PEGTL/ #ifndef TAOCPP_PEGTL_INCLUDE_CONTRIB_REP_ONE_MIN_MAX_HPP #define TAOCPP_PEGTL_INCLUDE_CONTRIB_REP_ONE_MIN_MAX_HPP #include <algorithm> #include "../config.hpp" #include "../analysis/counted.hpp" #include "../internal/bump_help.hpp" #include "../internal/skip_control.hpp" namespace tao { namespace TAOCPP_PEGTL_NAMESPACE { namespace internal { template< unsigned Min, unsigned Max, char C > struct rep_one_min_max { using analyze_t = analysis::counted< analysis::rule_type::ANY, Min >; static_assert( Min <= Max, "invalid rep_one_min_max rule (maximum number of repetitions smaller than minimum)" ); template< typename Input > static bool match( Input& in ) { const auto size = in.size( Max + 1 ); if( size < Min ) { return false; } std::size_t i = 0; while( ( i < size ) && ( in.peek_char( i ) == C ) ) { ++i; } if( ( Min <= i ) && ( i <= Max ) ) { bump_help< result_on_found::SUCCESS, Input, char, C >( in, i ); return true; } return false; } }; template< unsigned Min, unsigned Max, char C > struct skip_control< rep_one_min_max< Min, Max, C > > : std::true_type { }; } // namespace internal inline namespace ascii { template< unsigned Min, unsigned Max, char C > struct rep_one_min_max : internal::rep_one_min_max< Min, Max, C > { }; struct ellipsis : internal::rep_one_min_max< 3, 3, '.' > { }; } // namespace ascii } // namespace TAOCPP_PEGTL_NAMESPACE } // namespace tao #endif <commit_msg>Style<commit_after>// Copyright (c) 2017 Dr. Colin Hirsch and Daniel Frey // Please see LICENSE for license or visit https://github.com/taocpp/PEGTL/ #ifndef TAOCPP_PEGTL_INCLUDE_CONTRIB_REP_ONE_MIN_MAX_HPP #define TAOCPP_PEGTL_INCLUDE_CONTRIB_REP_ONE_MIN_MAX_HPP #include <algorithm> #include "../config.hpp" #include "../analysis/counted.hpp" #include "../internal/bump_help.hpp" #include "../internal/skip_control.hpp" namespace tao { namespace TAOCPP_PEGTL_NAMESPACE { namespace internal { template< unsigned Min, unsigned Max, char C > struct rep_one_min_max { using analyze_t = analysis::counted< analysis::rule_type::ANY, Min >; static_assert( Min <= Max, "invalid rep_one_min_max rule (maximum number of repetitions smaller than minimum)" ); template< typename Input > static bool match( Input& in ) { const auto size = in.size( Max + 1 ); if( size < Min ) { return false; } std::size_t i = 0; while( ( i < size ) && ( in.peek_char( i ) == C ) ) { ++i; } if( ( Min <= i ) && ( i <= Max ) ) { bump_help< result_on_found::SUCCESS, Input, char, C >( in, i ); return true; } return false; } }; template< unsigned Min, unsigned Max, char C > struct skip_control< rep_one_min_max< Min, Max, C > > : std::true_type { }; } // namespace internal inline namespace ascii { template< unsigned Min, unsigned Max, char C > struct rep_one_min_max : internal::rep_one_min_max< Min, Max, C > { }; struct ellipsis : internal::rep_one_min_max< 3, 3, '.' > { }; } // namespace ascii } // namespace TAOCPP_PEGTL_NAMESPACE } // namespace tao #endif <|endoftext|>
<commit_before>//! \file ************************************************************** //! \brief Source Gestion des action/raccourcis //! //! - Compilateur : GCC,MinGW //! //! \author Antoine Maleyrie //! \version 1.13 //! \date 20.03.2013 //! //! ******************************************************************** /* * Copyright © 2013 - Antoine Maleyrie. */ #include "actionManager.hpp" //TEST #include <iostream> // ********************************************************************* // Class ActionManager // ********************************************************************* ActionManager::ActionManager() : _shortcut(this) { } ActionManager::~ActionManager() { removeAll(); } bool ActionManager::add(ShortcutKey const &shortcut, Action* act) { //Ajout à la liste des actions. if(!ManagerBase<ShortcutKey, Action>::add(shortcut, act)) return false; //Et on l'ajouter à la liste des raccourcis. int id = _shortcut.creat(shortcut); Bind(EVT_SHORTCUT, &ActionManager::OnShortcut, this, id); return true; } bool ActionManager::remove(ShortcutKey const& shortcut) { if(ManagerBase<ShortcutKey, Action>::remove(shortcut)) { //Suppression du accourcie. _shortcut.remove(shortcut); return true; } return false; } void ActionManager::removeAll() { //Désinstalle les raccourcis. _shortcut.removeAll(); //Suppression des actions. ManagerBase<ShortcutKey, Action>::removeAll(); } void ActionManager::load(wxFileConfig& fileConfig) { wxString stringShortcut; long lIndex; //Avent de charger quoi que se soi on supprime tout les raccourcis/actions removeAll(); //On positionne le path fileConfig.SetPath("/ActionManager"); //On récupère le premier raccourci if(!fileConfig.GetFirstGroup(stringShortcut, lIndex)) { //On positionne le path a la racine. fileConfig.SetPath("/"); return; } do { //On positionne le path fileConfig.SetPath(stringShortcut); //Récupérer le type de l'action. wxString actTypeName; fileConfig.Read("ActTypeName", &actTypeName); //Création d'une action a parte de son nom. Action* tmpAct = Action::newAction(actTypeName); //Chargement des préférence de l'action à partir du fichier de configuration. tmpAct->load(fileConfig); //Ajout de l'action. add(ShortcutKey::stringToShortcutKey(stringShortcut), tmpAct); //On positionne le path fileConfig.SetPath("../"); }//Puis tous les autres while(fileConfig.GetNextGroup(stringShortcut, lIndex)); //On positionne le path a la racine. fileConfig.SetPath("/"); } void ActionManager::save(wxFileConfig& fileConfig)const { for(auto &it: _data) { //Obtenir la version string du raccourci. wxString stringShortcut = ShortcutKey::shortcutKeyToString(it.first); //Crée un groupe pour ce raccourci. fileConfig.SetPath("/ActionManager/"+stringShortcut); //Sauvegarde de l'action it.second->save(fileConfig); } } void ActionManager::enableShortcuts(bool val) { _shortcut.enable(val); } void ActionManager::OnShortcut(ShortcutEvent& event) { _data[event.getShortcutKey()]->execute(); } // ********************************************************************* // Class EditActionManager // ********************************************************************* EditActionManager::EditActionManager() { } EditActionManager::~EditActionManager() { } void EditActionManager::init() { auto act = ActionManager::getInstance()->getData(); //Copie de tout les actions. for(auto it : act) add(it.first, Action::newAction(it.second)); } void EditActionManager::apply() { ActionManager* actionManager = ActionManager::getInstance(); //On supprime tout actionManager->removeAll(); //Et on remplie en copient tout les actions. for(auto it : _data) actionManager->add(it.first, Action::newAction(it.second)); } std::vector<ShortcutKey> EditActionManager::getShortcutUsedList(wxString const& listName) { std::vector<ShortcutKey> shortcuts; //Parcoure de tout les raccourcis/actions for(auto it: _data) { if(it.second->getListNameUsed() == listName) shortcuts.push_back(it.first); } return shortcuts; } <commit_msg>fix bug do not charging action if no know<commit_after>//! \file ************************************************************** //! \brief Source Gestion des action/raccourcis //! //! - Compilateur : GCC,MinGW //! //! \author Antoine Maleyrie //! \version 1.13 //! \date 20.03.2013 //! //! ******************************************************************** /* * Copyright © 2013 - Antoine Maleyrie. */ #include "actionManager.hpp" //TEST #include <iostream> // ********************************************************************* // Class ActionManager // ********************************************************************* ActionManager::ActionManager() : _shortcut(this) { } ActionManager::~ActionManager() { removeAll(); } bool ActionManager::add(ShortcutKey const &shortcut, Action* act) { //Ajout à la liste des actions. if(!ManagerBase<ShortcutKey, Action>::add(shortcut, act)) return false; //Et on l'ajouter à la liste des raccourcis. int id = _shortcut.creat(shortcut); Bind(EVT_SHORTCUT, &ActionManager::OnShortcut, this, id); return true; } bool ActionManager::remove(ShortcutKey const& shortcut) { if(ManagerBase<ShortcutKey, Action>::remove(shortcut)) { //Suppression du accourcie. _shortcut.remove(shortcut); return true; } return false; } void ActionManager::removeAll() { //Désinstalle les raccourcis. _shortcut.removeAll(); //Suppression des actions. ManagerBase<ShortcutKey, Action>::removeAll(); } void ActionManager::load(wxFileConfig& fileConfig) { wxString stringShortcut; long lIndex; //Avent de charger quoi que se soi on supprime tout les raccourcis/actions removeAll(); //On positionne le path fileConfig.SetPath("/ActionManager"); //On récupère le premier raccourci if(!fileConfig.GetFirstGroup(stringShortcut, lIndex)) { //On positionne le path a la racine. fileConfig.SetPath("/"); return; } do { //On positionne le path fileConfig.SetPath(stringShortcut); //Récupérer le type de l'action. wxString actTypeName; fileConfig.Read("ActTypeName", &actTypeName); //Création d'une action a parte de son nom. Action* tmpAct = Action::newAction(actTypeName); //Si la création de l'action a réussie, alor on l'ajoute. if(tmpAct) { //Chargement des préférence de l'action à partir du fichier de configuration. tmpAct->load(fileConfig); //Ajout de l'action. add(ShortcutKey::stringToShortcutKey(stringShortcut), tmpAct); } //On positionne le path fileConfig.SetPath("../"); }//Puis tous les autres while(fileConfig.GetNextGroup(stringShortcut, lIndex)); //On positionne le path a la racine. fileConfig.SetPath("/"); } void ActionManager::save(wxFileConfig& fileConfig)const { for(auto &it: _data) { //Obtenir la version string du raccourci. wxString stringShortcut = ShortcutKey::shortcutKeyToString(it.first); //Crée un groupe pour ce raccourci. fileConfig.SetPath("/ActionManager/"+stringShortcut); //Sauvegarde de l'action it.second->save(fileConfig); } } void ActionManager::enableShortcuts(bool val) { _shortcut.enable(val); } void ActionManager::OnShortcut(ShortcutEvent& event) { _data[event.getShortcutKey()]->execute(); } // ********************************************************************* // Class EditActionManager // ********************************************************************* EditActionManager::EditActionManager() { } EditActionManager::~EditActionManager() { } void EditActionManager::init() { auto act = ActionManager::getInstance()->getData(); //Copie de tout les actions. for(auto it : act) add(it.first, Action::newAction(it.second)); } void EditActionManager::apply() { ActionManager* actionManager = ActionManager::getInstance(); //On supprime tout actionManager->removeAll(); //Et on remplie en copient tout les actions. for(auto it : _data) actionManager->add(it.first, Action::newAction(it.second)); } std::vector<ShortcutKey> EditActionManager::getShortcutUsedList(wxString const& listName) { std::vector<ShortcutKey> shortcuts; //Parcoure de tout les raccourcis/actions for(auto it: _data) { if(it.second->getListNameUsed() == listName) shortcuts.push_back(it.first); } return shortcuts; } <|endoftext|>
<commit_before>/* * Copyright (C) 2004-2013 ZNC, see the NOTICE file for details. * * 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 <znc/FileUtils.h> #include <znc/Client.h> #include <znc/Chan.h> #include <znc/Modules.h> class CBacklogMod : public CModule { public: MODCONSTRUCTOR(CBacklogMod) {} /* AddHelpCommand(); AddCommand("LogPath", static_cast<CModCommand::ModCmdFunc>(&CBacklogMod::SetLogPath), "<path>"); AddCommand("Get", static_cast<CModCommand::ModCmdFunc>(&CBacklogMod::SetLogPath), } */ virtual bool OnLoad(const CString& sArgs, CString& sMessage); virtual ~CBacklogMod(); virtual void OnModCommand(const CString& sCommand); virtual void SetLogPath(const CString& Path); private: CString LogPath; }; bool CBacklogMod::OnLoad(const CString& sArgs, CString& sMessage) { LogPath = sArgs; PutModule("I'm being loaded with the arguments: [" + sArgs + "]"); if(LogPath.empty()) { LogPath = GetNV("LogPath"); if(LogPath.empty()) { // TODO: guess logpath } } else { SetNV("LogPath", LogPath); } return true; } CBacklogMod::~CBacklogMod() { PutModule("I'm being unloaded!"); } void CBacklogMod::OnModCommand(const CString& sCommand) { if (sCommand.Token(0).CaseCmp("help") == 0) { // TODO: help text, look how AddHelpCommand() does it in other ZNC code PutModule("Help"); return; } else if (sCommand.Token(0).CaseCmp("logpath") == 0) { CString Args = sCommand.Token(1, true); SetNV("LogPath", Args); PutModule("LogPath set to: " + Args); return; } CString User; CString Network; CString Channel; CFile LogFile(sCommand); CString Line; if (LogFile.Open()) { while (LogFile.ReadLine(Line)) { PutModule(Line); } } else { PutModule("Could not open log file [" + sCommand + "]: " + strerror(errno)); } LogFile.Close(); } void CBacklogMod::SetLogPath(const CString& Path) { SetNV("LogPath", LogPath); } template<> void TModInfo<CBacklogMod>(CModInfo& Info) { Info.AddType(CModInfo::NetworkModule); Info.AddType(CModInfo::GlobalModule); Info.SetWikiPage("backlog"); Info.SetArgsHelpText("Takes as optional argument (and if given, sets) the log path, use keywords: $USER, $NETWORK and $WINDOW"); Info.SetHasArgs(true); } NETWORKMODULEDEFS(CBacklogMod, "Module for getting the last X lines of a channels log.") <commit_msg>tell user when setting logpath<commit_after>/* * Copyright (C) 2004-2013 ZNC, see the NOTICE file for details. * * 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 <znc/FileUtils.h> #include <znc/Client.h> #include <znc/Chan.h> #include <znc/Modules.h> class CBacklogMod : public CModule { public: MODCONSTRUCTOR(CBacklogMod) {} /* AddHelpCommand(); AddCommand("LogPath", static_cast<CModCommand::ModCmdFunc>(&CBacklogMod::SetLogPath), "<path>"); AddCommand("Get", static_cast<CModCommand::ModCmdFunc>(&CBacklogMod::SetLogPath), } */ virtual bool OnLoad(const CString& sArgs, CString& sMessage); virtual ~CBacklogMod(); virtual void OnModCommand(const CString& sCommand); private: CString LogPath; }; bool CBacklogMod::OnLoad(const CString& sArgs, CString& sMessage) { LogPath = sArgs; PutModule("I'm being loaded with the arguments: [" + sArgs + "]"); if(LogPath.empty()) { LogPath = GetNV("LogPath"); if(LogPath.empty()) { // TODO: guess logpath } } else { SetNV("LogPath", LogPath); PutModule("LogPath set to: " + LogPath); } return true; } CBacklogMod::~CBacklogMod() { PutModule("I'm being unloaded!"); } void CBacklogMod::OnModCommand(const CString& sCommand) { if (sCommand.Token(0).CaseCmp("help") == 0) { // TODO: help text, look how AddHelpCommand() does it in other ZNC code PutModule("Help"); return; } else if (sCommand.Token(0).CaseCmp("logpath") == 0) { LogPath = sCommand.Token(1, true); SetNV("LogPath", LogPath); PutModule("LogPath set to: " + LogPath); return; } CString User; CString Network; CString Channel; CFile LogFile(sCommand); CString Line; if (LogFile.Open()) { while (LogFile.ReadLine(Line)) { PutModule(Line); } } else { PutModule("Could not open log file [" + sCommand + "]: " + strerror(errno)); } LogFile.Close(); } template<> void TModInfo<CBacklogMod>(CModInfo& Info) { Info.AddType(CModInfo::NetworkModule); Info.AddType(CModInfo::GlobalModule); Info.SetWikiPage("backlog"); Info.SetArgsHelpText("Takes as optional argument (and if given, sets) the log path, use keywords: $USER, $NETWORK and $WINDOW"); Info.SetHasArgs(true); } NETWORKMODULEDEFS(CBacklogMod, "Module for getting the last X lines of a channels log.") <|endoftext|>
<commit_before>#include <iostream> #include <boost/smart_ptr.hpp> using namespace std; int main(){ boost::shared_ptr<int> p(new int); *p = 10; cout << *p << endl; cout << "Count of p is " << p.use_count() << endl; int* int_ptr = new int; boost::shared_ptr<int> p2(p); *int_ptr = 20; cout << *p2 << endl; cout << "Count of p is " << p2.use_count() << endl; return 0; } <commit_msg> Update 03_shared_ptr_example.cpp<commit_after>#include <iostream> #include <boost/smart_ptr.hpp> #include <boost/make_shared.hpp> #include <vector> using namespace std; int main(){ boost::shared_ptr<int> p(new int); *p = 10; cout << *p << endl; cout << "Count of p is " << p.use_count() << endl; int* int_ptr = new int; boost::shared_ptr<int> p2(p); *int_ptr = 20; cout << *p2 << endl; cout << "Count of p is " << p2.use_count() << endl; auto sp = boost::make_shared<string>("make_shared"); auto spv= boost::make_shared<vector<int> >(10,2); for(auto i = spv->begin(); i != spv->end(); ++i) cout << *i << endl; return 0; } <|endoftext|>
<commit_before>// This is free and unencumbered software released into the public domain. // For more information, please refer to <http://unlicense.org/> #include "GeometricShapes.h" #include <cmath> #include "SupportLibrary.h" Cylinder::Cylinder() { diameter_ = -999999; length_ = -999999; } Cylinder::~Cylinder() {} double Cylinder::AreaCrossSection() { return (pi / 4) * pow(diameter_, 2); } bool Cylinder::Validate(bool is_included_warnings, std::list<std::string>* messages_error) const { bool is_valid = true; // validate diameter if (diameter_ <= 0 || ((100 < diameter_) && (is_included_warnings == true))) { is_valid = false; if (messages_error != nullptr) { messages_error->push_back("CYLINDER - Invalid diameter"); } } // validate length if (length_ <= 0 || ((120 < length_) && (is_included_warnings == true))) { is_valid = false; if (messages_error != nullptr) { messages_error->push_back("CYLINDER - Invalid length"); } } return is_valid; } double Cylinder::Volume() { return AreaCrossSection() * length_; } double Cylinder::diameter() { return diameter_; } double Cylinder::length() { return length_; } void Cylinder::set_diameter(const double& diameter) { diameter_ = diameter; } void Cylinder::set_length(const double& length) { length_ = length; } <commit_msg>Updated code formatting<commit_after>// This is free and unencumbered software released into the public domain. // For more information, please refer to <http://unlicense.org/> #include "GeometricShapes.h" #include <cmath> #include "SupportLibrary.h" Cylinder::Cylinder() { diameter_ = -999999; length_ = -999999; } Cylinder::~Cylinder() {} double Cylinder::AreaCrossSection() { return (pi / 4) * pow(diameter_, 2); } bool Cylinder::Validate(bool is_included_warnings, std::list<std::string>* messages_error) const { bool is_valid = true; // validate diameter if (diameter_ <= 0 || ((100 < diameter_) && (is_included_warnings == true))) { is_valid = false; if (messages_error != nullptr) { messages_error->push_back("CYLINDER - Invalid diameter"); } } // validate length if (length_ <= 0 || ((120 < length_) && (is_included_warnings == true))) { is_valid = false; if (messages_error != nullptr) { messages_error->push_back("CYLINDER - Invalid length"); } } return is_valid; } double Cylinder::Volume() { return AreaCrossSection() * length_; } double Cylinder::diameter() { return diameter_; } double Cylinder::length() { return length_; } void Cylinder::set_diameter(const double& diameter) { diameter_ = diameter; } void Cylinder::set_length(const double& length) { length_ = length; } <|endoftext|>
<commit_before>//Implementation of a Forest Fire Simulation #include <cassert> #include <random> #include "forest.hpp" #include "tclap/ValueArg.h" WARPED_REGISTER_POLYMORPHIC_SERIALIZABLE_CLASS(ForestEvent) std::vector<std::shared_ptr<warped::Event> > Forest::initializeLP() { // Register random number generator //this->registerRNG<std::default_random_engine>(this->rng_); std::default_random_engine rng; uniform_int_distribution<int> LPS(0, this->width * this->height); std::vector<std::shared_ptr<warped::Event> > events; events.emplace_back(new ForestEvent {lp_name(LPS(rng), IGNITION, 1}); return events; } inline std::string Forest::lp_name(const unsigned int lp_index){ return std::string("Forest_") + std::to_string(lp_index); } std::vector<std::shared_ptr<warped::Event> > Forest::receiveEvent(const warped::Event& event) { std::vector<std::shared_ptr<warped::Event> > response_events; auto received_event = static_cast<const ForestEvent&>(event); switch (received_event.type_) { case RADIATION: { this->state_.heat_content_=this->state_.heat_content_ + recieved_event.heat_content; // if there is enough heat and the vegtation is unburnt Schedule ignition if(this->state_.heat_content_ >= this->ignition_threshold && this->state_burn_status == UNBURNT){ unsigned int ignition_time = recieved_event.ts+1; response_events.emplace_back(new ForestEvent {this->name_, IGNITION, ignition_time }); } break; } case RADIATION_TIMER: { unsigned int radiation_heat=this->state_.heat_content_ /100 * 5 this->state_.heat_content_ /100 * 95; // Schedule Radiation events for each of the eight surrounding LPs /*begin for loop*/ unsigned int radiation_time = received_event.ts_ + 1; response_events.emplace_back(new ForestEvent { this->name_, RADIATION, radiation_time }); /*end for loop*/ if(this->state_.heat_content_ <= this->burnout_threshold){ this->state_.burn_status_ = BURNOUT } else{ unsigned int radiation_timer = recieved_event.ts + 5; response_events.emplace_back(new ForestEvent {this->name_, RADIATION_TIMER, radiation_timer }); } break; } case IGNITION: { this->state_.burn_status_=GROWTH; // Schedule Peak Event unsigned int peak_time = received_event.ts + ((this->peak_threshold-this->ignition_threshold)/this->heat_rate); response_events.emplace_back(new ForestEvent {this->name_, PEAK, peak_time }); break; } case PEAK: { this->state_.burn_status_=DECAY; this->state_.heat_content_=this->state_.heat_content_ + (this->peak_threshold - this->ignition_threshold); // Schedule first Radiation Timer unsigned int radiation_timer = recieved_event.ts + 5; response_events.emplace_back(new ForestEvent {this->name_, RADIATION_TIMER, radiation_timer }); break; } } return response_events; } std::queue<int> ignition_threshold_vector; std::queue<int> peak_threshold_vector; unsigned int width,height; unsigned char *read_bmp( std::string img_name, unsigned int heat_rate, unsigned int radiation_percent, unsigned int burnout_threshold){ FILE *fp = fopen(img_name.c_str(), "rb"); if(!fp) throw "Argument Exception"; // Read the 54-byte header unsigned char info[54]; fread(info, sizeof(unsigned char), 54, fp); // Extract image height and width from header width = *(unsigned int *)&info[18]; height = *(unsigned int *)&info[22]; std::cout << "Width : " << width << std::endl; std::cout << "Height : " << height << std::endl; unsigned int row_padded = (width*3 + 3) & (~3); unsigned char *data = new unsigned char[row_padded]; for( unsigned int i = 0; i < height; i++ ) { fread(data, sizeof(unsigned char), row_padded, fp); for(unsigned int j = 0; j < width*3; j += 3) { //std::cout << "B: "<< (int)data[j] // << " G: " << (int)data[j+1] // << " R: " << (int)data[j+2] // << std::endl; unsigned int index_num = i*j; //Placeholder equations for threshold calculation unsigned int ignition_threshold = (int)data[j] + (int)data[j+1] + (int)data[j+2]; unsigned int peak_threshold = ((int)data[j] + (int)data[j+1] + (int)data[j+2]) * 2; std::string name = Forest::lp_name(index_num) lps.emplace_back(name, width, height,ignition_threshold, heat_rate, peak_threshold, burnout_threshold, index_num); } } fclose(fp); return data; } int main(int argc, char *argv[],){ std::string config_filename = "map_hawaii.bmp"; unsigned int heat_rate = 100; unsigned int radiation_percent = 5; unsigned int burnout_threshold = 50; TCLAP::ValueArg<std::string> config_arg("m", "map", "Forest model vegetation config", false, config_filename, "string"); TCLAP::ValueArg<unsigned int> heat_rate_arg("h", "heat-rate", "Speed of growth of the fire", false, heat_rate, "unsigned int"); TCLAP::ValueArg<unsigned int> radition_percent_arg("r", "radiation-percent", "Percent of Heat released every timstamp", false, radiation_percent, "unsigned int"); TCLAP::ValueArg<unsigned int> burnout_threshold_arg("b", "burnout-threshold", "Amount of heat needed for a cell to burn out", false, burnout_threshold, "unsigned int"); std::vector<TCLAP::Arg*> args = {&config_arg, &heat_rate_arg, &radiation_percent_arg, &burnout_threshold_arg}; config_filename = config_arg.getValue(); heat_rate = heat_rate_arg.getValue(); radiation_percent = radiation_percent_arg.getValue(); burnout_threshold = burnout_threshold.getValue(); warped::Simulation forest_sim {"Forest Simulation", argc, argv, args}; std::vector<Forest> lps; (void) read_bmp(config_filename, heat_rate, radiation_percent, burnout_threshold); std::vector<warped::LogicalProcess*> lp_pointers; for (auto& lp : lps) { lp_pointers.push_back(&lp); } forest_sim.simulate(lp_pointers); return 0; } <commit_msg>Created compute spread skeleton function<commit_after>//Implementation of a Forest Fire Simulation #include <cassert> #include <random> #include "forest.hpp" #include "tclap/ValueArg.h" WARPED_REGISTER_POLYMORPHIC_SERIALIZABLE_CLASS(ForestEvent) std::vector<std::shared_ptr<warped::Event> > Forest::initializeLP() { std::vector<std::shared_ptr<warped::Event> > events; for (unsigned int i = 0; i < this->index_; i++){ //For all of the cells in the forest if(this->state.heat_content_ >= this->ignition_threshold){ //If heat content > ignition threshold events.emplace_back(new ForestEvent {this->name_, IGNITION,ts_} // Then start an ignition event } } return events; } inline std::string Forest::lp_name(const unsigned int lp_index){ return std::string("Forest_") + std::to_string(lp_index); } std::vector<std::shared_ptr<warped::Event> > Forest::receiveEvent(const warped::Event& event) { std::vector<std::shared_ptr<warped::Event> > response_events; auto received_event = static_cast<const ForestEvent&>(event); switch (received_event.type_) { case RADIATION: { this->state_.heat_content_=this->state_.heat_content_ + recieved_event.heat_content; // if there is enough heat and the vegtation is unburnt Schedule ignition if(this->state_.heat_content_ >= this->ignition_threshold && this->state_burn_status == UNBURNT){ unsigned int ignition_time = recieved_event.ts+1; response_events.emplace_back(new ForestEvent {this->name_, IGNITION, ignition_time }); } break; } case RADIATION_TIMER: { unsigned int radiation_heat=this->state_.heat_content_ /100 * 5 this->state_.heat_content_ /100 * 95; // Schedule Radiation events for each of the eight surrounding LPs /*begin for loop*/ unsigned int radiation_time = received_event.ts_ + 1; response_events.emplace_back(new ForestEvent { this->name_, RADIATION, radiation_time }); /*end for loop*/ if(this->state_.heat_content_ <= this->burnout_threshold){ this->state_.burn_status_ = BURNOUT } else{ unsigned int radiation_timer = recieved_event.ts + 5; response_events.emplace_back(new ForestEvent {this->name_, RADIATION_TIMER, radiation_timer }); } break; } case IGNITION: { this->state_.burn_status_=GROWTH; // Schedule Peak Event unsigned int peak_time = received_event.ts + ((this->peak_threshold-this->ignition_threshold)/this->heat_rate); response_events.emplace_back(new ForestEvent {this->name_, PEAK, peak_time }); break; } case PEAK: { this->state_.burn_status_=DECAY; this->state_.heat_content_=this->state_.heat_content_ + (this->peak_threshold - this->ignition_threshold); // Schedule first Radiation Timer unsigned int radiation_timer = recieved_event.ts + 5; response_events.emplace_back(new ForestEvent {this->name_, RADIATION_TIMER, radiation_timer }); break; } } return response_events; } unsigned char *read_bmp( std::string img_name, unsigned int heat_rate, unsigned int radiation_percent, unsigned int burnout_threshold unsigned int burn_start_x, unsigned int burn_start_y){ FILE *fp = fopen(img_name.c_str(), "rb"); if(!fp) throw "Argument Exception"; // Read the 54-byte header unsigned char info[54]; fread(info, sizeof(unsigned char), 54, fp); // Extract image height and width from header width = *(unsigned int *)&info[18]; height = *(unsigned int *)&info[22]; std::cout << "Width : " << width << std::endl; std::cout << "Height : " << height << std::endl; unsigned int row_padded = (width*3 + 3) & (~3); unsigned char *data = new unsigned char[row_padded]; for( unsigned int i = 0; i < height; i++ ) { fread(data, sizeof(unsigned char), row_padded, fp); for(unsigned int j = 0; j < width*3; j += 3) { //std::cout << "B: "<< (int)data[j] // << " G: " << (int)data[j+1] // << " R: " << (int)data[j+2] // << std::endl; unsigned int index_num = i*j; //Placeholder equations for threshold calculation unsigned int ignition_threshold = (int)data[j] + (int)data[j+1] + (int)data[j+2]; unsigned int peak_threshold = ((int)data[j] + (int)data[j+1] + (int)data[j+2]) * 2; std::string name = Forest::lp_name(index_num) lps.emplace_back(name, width, height,ignition_threshold, heat_rate, peak_threshold, burnout_threshold, index_num); /* If the LP being created is the start of the fire then give it intial heat content */ if(i == burn_start_x && j == burn_start_y){ this->state.heat_content_ = 400 } } } fclose(fp); return data; } std::string Forest::compute_spread(direction_t direction) { unsigned int new_x = 0, new_y = 0; unsigned int current_y = index_ / size_x_; unsigned int current_x = index_ % size_x_; switch (direction) { case NORTH: { new_x = current_x; new_y = (current_y + 1) % size_y_; } break; case NORTH_EAST: { new_x = (current_x + 1) % size_x_; new_y = (current_y + 1) % size_y_; } break; case EAST: { new_x = (current_x + 1) % size_x_; new_y = current_y; } break; case SOUTH_EAST: { new_x = (current_x + 1) % size_x_; new_y = (current_y + size_y_ - 1) % size_y_; } break; case SOUTH: { new_x = current_x; new_y = (current_y + size_y_ - 1) % size_y_; } break; case SOUTH_WEST: { new_x = (current_x + size_x_ - 1) % size_x_; new_y = (current_y + size_y_ - 1) % size_y_; } break; case WEST: { new_x = (current_x + size_x_ - 1) % size_x_; new_y = current_y; } break; case NORTH_WEST: { new_x = (current_x + size_x_ - 1) % size_x_; new_y = (current_y + 1) % size_y_; } break; default: { std::cerr << "Invalid move direction " << direction << std::endl; assert(0); } } return lp_name(new_x + new_y * size_x_); } int main(int argc, char *argv[],){ std::string config_filename = "map_hawaii.bmp"; unsigned int heat_rate = 100; unsigned int radiation_percent = 5; unsigned int burnout_threshold = 50; unsigned int burn_start_x = 500; unsigned int burn_start_y = 501; TCLAP::ValueArg<std::string> config_arg("m", "map", "Forest model vegetation config", false, config_filename, "string"); TCLAP::ValueArg<unsigned int> heat_rate_arg("h", "heat-rate", "Speed of growth of the fire", false, heat_rate, "unsigned int"); TCLAP::ValueArg<unsigned int> radition_percent_arg("r", "radiation-percent", "Percent of Heat released every timstamp", false, radiation_percent, "unsigned int"); TCLAP::ValueArg<unsigned int> burnout_threshold_arg("b", "burnout-threshold", "Amount of heat needed for a cell to burn out", false, burnout_threshold, "unsigned int"); TCLAP::ValueArg<unsigned int> burn_start_x_arg("x", "burn-start-x", "x coordinate of the start of fire", false, burn_start_x, "unsigned int"); TCLAP::ValueArg<unsigned int> burn_start_y_arg("y", "burn-start-y", "y coordinate of the start of fire", false, burn_start_y, "unsigned int"); std::vector<TCLAP::Arg*> args = {&config_arg, &heat_rate_arg, &radiation_percent_arg, &burnout_threshold_arg, &burn_start_x_arg, &burn_start_y_arg}; config_filename = config_arg.getValue(); heat_rate = heat_rate_arg.getValue(); radiation_percent = radiation_percent_arg.getValue(); burnout_threshold = burnout_threshold.getValue(); burn_start_x = burn_start_x.getValue(); burn_start_y = burn_start_y.getValue(); warped::Simulation forest_sim {"Forest Simulation", argc, argv, args}; std::vector<Forest> lps; (void) read_bmp(config_filename, heat_rate, radiation_percent, burnout_threshold, burn_start_x, burn_start_y); std::vector<warped::LogicalProcess*> lp_pointers; for (auto& lp : lps) { lp_pointers.push_back(&lp); } forest_sim.simulate(lp_pointers); return 0; } <|endoftext|>
<commit_before>/* -*- mode: c++; c-basic-offset:4 -*- commands/refreshx509certscommand.cpp This file is part of Kleopatra, the KDE keymanager Copyright (c) 2008 Klarälvdalens Datakonsult AB Kleopatra is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. Kleopatra is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #include <config-kleopatra.h> #include "refreshx509certscommand.h" #include <KLocale> #include <KMessageBox> using namespace Kleo; using namespace Kleo::Commands; RefreshX509CertsCommand::RefreshX509CertsCommand( KeyListController * c ) : GnuPGProcessCommand( c ) { } RefreshX509CertsCommand::RefreshX509CertsCommand( QAbstractItemView * v, KeyListController * c ) : GnuPGProcessCommand( v, c ) { } RefreshX509CertsCommand::~RefreshX509CertsCommand() {} bool RefreshX509CertsCommand::preStartHook( QWidget * parent ) const { return KMessageBox::warningContinueCancel( parent, i18n("Refreshing X.509 certificates implies downloading CRLs for all certificates, " "even if they might otherwise still be valid. " "This can put a severe strain on your own as well as other people's network " "connection, and can take up to an hour or more to complete, depending on " "your network connection, and the number of certificates to check. " "Are you sure you want to continue?"), i18n("X.509 Certitifcate Refresh"), KStandardGuiItem::cont(), KStandardGuiItem::cancel(), QLatin1String( "warn-refresh-x509-expensive" ) ) == KMessageBox::Continue; } QStringList RefreshX509CertsCommand::arguments() const { return QStringList() << "gpgsm" << "-k" << "--with-validation" << "--force-crl-refresh" << "--enable-crl-checks"; } QString RefreshX509CertsCommand::errorCaption() const { return i18n( "X.509 Certificate Refresh Error" ); } QString RefreshX509CertsCommand::successCaption() const { return i18n( "X.509 Certificate Refresh Finished" ); } QString RefreshX509CertsCommand::crashExitMessage( const QStringList & args ) const { return i18n( "The GpgSM process that tried to refresh X.509 certificates " "ended prematurely because of an unexpected error. " "Please check the output of %1 for details.", args.join( " " ) ) ; } QString RefreshX509CertsCommand::errorExitMessage( const QStringList & args ) const { return i18n( "An error occurred while trying to refresh X.509 certificates. " "The output from %1 was:\n%2", args[0], errorString() ); } QString RefreshX509CertsCommand::successMessage( const QStringList & ) const { return i18n( "X.509 certificates refreshed successfully." ); } #include "moc_refreshx509certscommand.cpp" <commit_msg>Use gpgSmPath() instead of "gpgsm"<commit_after>/* -*- mode: c++; c-basic-offset:4 -*- commands/refreshx509certscommand.cpp This file is part of Kleopatra, the KDE keymanager Copyright (c) 2008 Klarälvdalens Datakonsult AB Kleopatra is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. Kleopatra is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #include <config-kleopatra.h> #include "refreshx509certscommand.h" #include <utils/gnupg-helper.h> #include <KLocale> #include <KMessageBox> using namespace Kleo; using namespace Kleo::Commands; RefreshX509CertsCommand::RefreshX509CertsCommand( KeyListController * c ) : GnuPGProcessCommand( c ) { } RefreshX509CertsCommand::RefreshX509CertsCommand( QAbstractItemView * v, KeyListController * c ) : GnuPGProcessCommand( v, c ) { } RefreshX509CertsCommand::~RefreshX509CertsCommand() {} bool RefreshX509CertsCommand::preStartHook( QWidget * parent ) const { return KMessageBox::warningContinueCancel( parent, i18n("Refreshing X.509 certificates implies downloading CRLs for all certificates, " "even if they might otherwise still be valid. " "This can put a severe strain on your own as well as other people's network " "connection, and can take up to an hour or more to complete, depending on " "your network connection, and the number of certificates to check. " "Are you sure you want to continue?"), i18n("X.509 Certitifcate Refresh"), KStandardGuiItem::cont(), KStandardGuiItem::cancel(), QLatin1String( "warn-refresh-x509-expensive" ) ) == KMessageBox::Continue; } QStringList RefreshX509CertsCommand::arguments() const { return QStringList() << gpgSmPath() << "-k" << "--with-validation" << "--force-crl-refresh" << "--enable-crl-checks"; } QString RefreshX509CertsCommand::errorCaption() const { return i18n( "X.509 Certificate Refresh Error" ); } QString RefreshX509CertsCommand::successCaption() const { return i18n( "X.509 Certificate Refresh Finished" ); } QString RefreshX509CertsCommand::crashExitMessage( const QStringList & args ) const { return i18n( "The GpgSM process that tried to refresh X.509 certificates " "ended prematurely because of an unexpected error. " "Please check the output of %1 for details.", args.join( " " ) ) ; } QString RefreshX509CertsCommand::errorExitMessage( const QStringList & args ) const { return i18n( "An error occurred while trying to refresh X.509 certificates. " "The output from %1 was:\n%2", args[0], errorString() ); } QString RefreshX509CertsCommand::successMessage( const QStringList & ) const { return i18n( "X.509 certificates refreshed successfully." ); } #include "moc_refreshx509certscommand.cpp" <|endoftext|>
<commit_before><commit_msg>do not make default suffix lower case<commit_after><|endoftext|>
<commit_before><commit_msg>remove whitespace<commit_after><|endoftext|>
<commit_before>/* This file is part of nSkinz by namazso, licensed under the MIT license: * * MIT License * * Copyright (c) namazso 2018 * * 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 "hooks.hpp" #include "../nSkinz.hpp" #include "../config.hpp" static auto random_sequence(const int low, const int high) -> int { return rand() % (high - low + 1) + low; } // This only fixes if the original knife was a default knife. // The best would be having a function that converts original knife's sequence // into some generic enum, then another function that generates a sequence // from the sequences of the new knife. I won't write that. static auto get_new_animation(const fnv::hash model, const int sequence) -> int { enum ESequence { SEQUENCE_DEFAULT_DRAW = 0, SEQUENCE_DEFAULT_IDLE1 = 1, SEQUENCE_DEFAULT_IDLE2 = 2, SEQUENCE_DEFAULT_LIGHT_MISS1 = 3, SEQUENCE_DEFAULT_LIGHT_MISS2 = 4, SEQUENCE_DEFAULT_HEAVY_MISS1 = 9, SEQUENCE_DEFAULT_HEAVY_HIT1 = 10, SEQUENCE_DEFAULT_HEAVY_BACKSTAB = 11, SEQUENCE_DEFAULT_LOOKAT01 = 12, SEQUENCE_BUTTERFLY_DRAW = 0, SEQUENCE_BUTTERFLY_DRAW2 = 1, SEQUENCE_BUTTERFLY_LOOKAT01 = 13, SEQUENCE_BUTTERFLY_LOOKAT03 = 15, SEQUENCE_FALCHION_IDLE1 = 1, SEQUENCE_FALCHION_HEAVY_MISS1 = 8, SEQUENCE_FALCHION_HEAVY_MISS1_NOFLIP = 9, SEQUENCE_FALCHION_LOOKAT01 = 12, SEQUENCE_FALCHION_LOOKAT02 = 13, SEQUENCE_CSS_LOOKAT01 = 14, SEQUENCE_CSS_LOOKAT02 = 15, SEQUENCE_DAGGERS_IDLE1 = 1, SEQUENCE_DAGGERS_LIGHT_MISS1 = 2, SEQUENCE_DAGGERS_LIGHT_MISS5 = 6, SEQUENCE_DAGGERS_HEAVY_MISS2 = 11, SEQUENCE_DAGGERS_HEAVY_MISS1 = 12, SEQUENCE_BOWIE_IDLE1 = 1, }; // Hashes for best performance. switch(model) { case FNV("models/weapons/v_knife_butterfly.mdl"): { switch(sequence) { case SEQUENCE_DEFAULT_DRAW: return random_sequence(SEQUENCE_BUTTERFLY_DRAW, SEQUENCE_BUTTERFLY_DRAW2); case SEQUENCE_DEFAULT_LOOKAT01: return random_sequence(SEQUENCE_BUTTERFLY_LOOKAT01, SEQUENCE_BUTTERFLY_LOOKAT03); default: return sequence + 1; } } case FNV("models/weapons/v_knife_falchion_advanced.mdl"): { switch(sequence) { case SEQUENCE_DEFAULT_IDLE2: return SEQUENCE_FALCHION_IDLE1; case SEQUENCE_DEFAULT_HEAVY_MISS1: return random_sequence(SEQUENCE_FALCHION_HEAVY_MISS1, SEQUENCE_FALCHION_HEAVY_MISS1_NOFLIP); case SEQUENCE_DEFAULT_LOOKAT01: return random_sequence(SEQUENCE_FALCHION_LOOKAT01, SEQUENCE_FALCHION_LOOKAT02); case SEQUENCE_DEFAULT_DRAW: case SEQUENCE_DEFAULT_IDLE1: return sequence; default: return sequence - 1; } } case FNV("models/weapons/v_knife_css.mdl"): { switch (sequence) { case SEQUENCE_DEFAULT_LOOKAT01: return random_sequence(SEQUENCE_CSS_LOOKAT01, SEQUENCE_CSS_LOOKAT02); default: return sequence; } } case FNV("models/weapons/v_knife_push.mdl"): { switch(sequence) { case SEQUENCE_DEFAULT_IDLE2: return SEQUENCE_DAGGERS_IDLE1; case SEQUENCE_DEFAULT_LIGHT_MISS1: case SEQUENCE_DEFAULT_LIGHT_MISS2: return random_sequence(SEQUENCE_DAGGERS_LIGHT_MISS1, SEQUENCE_DAGGERS_LIGHT_MISS5); case SEQUENCE_DEFAULT_HEAVY_MISS1: return random_sequence(SEQUENCE_DAGGERS_HEAVY_MISS2, SEQUENCE_DAGGERS_HEAVY_MISS1); case SEQUENCE_DEFAULT_HEAVY_HIT1: case SEQUENCE_DEFAULT_HEAVY_BACKSTAB: case SEQUENCE_DEFAULT_LOOKAT01: return sequence + 3; case SEQUENCE_DEFAULT_DRAW: case SEQUENCE_DEFAULT_IDLE1: return sequence; default: return sequence + 2; } } case FNV("models/weapons/v_knife_survival_bowie.mdl"): { switch(sequence) { case SEQUENCE_DEFAULT_DRAW: case SEQUENCE_DEFAULT_IDLE1: return sequence; case SEQUENCE_DEFAULT_IDLE2: return SEQUENCE_BOWIE_IDLE1; default: return sequence - 1; } } case FNV("models/weapons/v_knife_ursus.mdl"): { switch (sequence) { case SEQUENCE_DEFAULT_DRAW: return random_sequence(SEQUENCE_BUTTERFLY_DRAW, SEQUENCE_BUTTERFLY_DRAW2); case SEQUENCE_DEFAULT_LOOKAT01: return random_sequence(SEQUENCE_BUTTERFLY_LOOKAT01, 14); default: return sequence + 1; } } case FNV("models/weapons/v_knife_stiletto.mdl"): { switch (sequence) { case SEQUENCE_DEFAULT_LOOKAT01: return random_sequence(12, 13); } } case FNV("models/weapons/v_knife_widowmaker.mdl"): { switch (sequence) { case SEQUENCE_DEFAULT_LOOKAT01: return random_sequence(14, 15); } } default: return sequence; } } static auto do_sequence_remapping(sdk::CRecvProxyData* data, sdk::C_BaseViewModel* entity) -> void { const auto local = static_cast<sdk::C_BasePlayer*>(g_entity_list->GetClientEntity(g_engine->GetLocalPlayer())); if(!local) return; if(local->GetLifeState() != sdk::LifeState::ALIVE) return; const auto owner = get_entity_from_handle<sdk::C_BasePlayer>(entity->GetOwner()); if(owner != local) return; const auto view_model_weapon = get_entity_from_handle<sdk::C_BaseAttributableItem>(entity->GetWeapon()); if(!view_model_weapon) return; const auto weapon_info = game_data::get_weapon_info(view_model_weapon->GetItemDefinitionIndex()); if(!weapon_info) return; const auto override_model = weapon_info->model; auto& sequence = data->m_Value.m_Int; sequence = get_new_animation(fnv::hash_runtime(override_model), sequence); } // Replacement function that will be called when the view model animation sequence changes. auto __cdecl hooks::sequence_proxy_fn(const sdk::CRecvProxyData* proxy_data_const, void* entity, void* output) -> void { // Ensure our other dynamic object hooks are in place. // Must do this from a game thread. ensure_dynamic_hooks(); static auto original_fn = g_sequence_hook->get_original_function(); // Remove the constness from the proxy data allowing us to make changes. const auto proxy_data = const_cast<sdk::CRecvProxyData*>(proxy_data_const); const auto view_model = static_cast<sdk::C_BaseViewModel*>(entity); do_sequence_remapping(proxy_data, view_model); // Call the original function with our edited data. original_fn(proxy_data_const, entity, output); } <commit_msg>fix a sequence bug that was here for who knows how long<commit_after>/* This file is part of nSkinz by namazso, licensed under the MIT license: * * MIT License * * Copyright (c) namazso 2018 * * 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 "hooks.hpp" #include "../nSkinz.hpp" #include "../config.hpp" static auto random_sequence(const int low, const int high) -> int { return rand() % (high - low + 1) + low; } // This only fixes if the original knife was a default knife. // The best would be having a function that converts original knife's sequence // into some generic enum, then another function that generates a sequence // from the sequences of the new knife. I won't write that. static auto get_new_animation(const fnv::hash model, const int sequence) -> int { enum ESequence { SEQUENCE_DEFAULT_DRAW = 0, SEQUENCE_DEFAULT_IDLE1 = 1, SEQUENCE_DEFAULT_IDLE2 = 2, SEQUENCE_DEFAULT_LIGHT_MISS1 = 3, SEQUENCE_DEFAULT_LIGHT_MISS2 = 4, SEQUENCE_DEFAULT_HEAVY_MISS1 = 9, SEQUENCE_DEFAULT_HEAVY_HIT1 = 10, SEQUENCE_DEFAULT_HEAVY_BACKSTAB = 11, SEQUENCE_DEFAULT_LOOKAT01 = 12, SEQUENCE_BUTTERFLY_DRAW = 0, SEQUENCE_BUTTERFLY_DRAW2 = 1, SEQUENCE_BUTTERFLY_LOOKAT01 = 13, SEQUENCE_BUTTERFLY_LOOKAT03 = 15, SEQUENCE_FALCHION_IDLE1 = 1, SEQUENCE_FALCHION_HEAVY_MISS1 = 8, SEQUENCE_FALCHION_HEAVY_MISS1_NOFLIP = 9, SEQUENCE_FALCHION_LOOKAT01 = 12, SEQUENCE_FALCHION_LOOKAT02 = 13, SEQUENCE_CSS_LOOKAT01 = 14, SEQUENCE_CSS_LOOKAT02 = 15, SEQUENCE_DAGGERS_IDLE1 = 1, SEQUENCE_DAGGERS_LIGHT_MISS1 = 2, SEQUENCE_DAGGERS_LIGHT_MISS5 = 6, SEQUENCE_DAGGERS_HEAVY_MISS2 = 11, SEQUENCE_DAGGERS_HEAVY_MISS1 = 12, SEQUENCE_BOWIE_IDLE1 = 1, }; // Hashes for best performance. switch(model) { case FNV("models/weapons/v_knife_butterfly.mdl"): { switch(sequence) { case SEQUENCE_DEFAULT_DRAW: return random_sequence(SEQUENCE_BUTTERFLY_DRAW, SEQUENCE_BUTTERFLY_DRAW2); case SEQUENCE_DEFAULT_LOOKAT01: return random_sequence(SEQUENCE_BUTTERFLY_LOOKAT01, SEQUENCE_BUTTERFLY_LOOKAT03); default: return sequence + 1; } } case FNV("models/weapons/v_knife_falchion_advanced.mdl"): { switch(sequence) { case SEQUENCE_DEFAULT_IDLE2: return SEQUENCE_FALCHION_IDLE1; case SEQUENCE_DEFAULT_HEAVY_MISS1: return random_sequence(SEQUENCE_FALCHION_HEAVY_MISS1, SEQUENCE_FALCHION_HEAVY_MISS1_NOFLIP); case SEQUENCE_DEFAULT_LOOKAT01: return random_sequence(SEQUENCE_FALCHION_LOOKAT01, SEQUENCE_FALCHION_LOOKAT02); case SEQUENCE_DEFAULT_DRAW: case SEQUENCE_DEFAULT_IDLE1: return sequence; default: return sequence - 1; } } case FNV("models/weapons/v_knife_css.mdl"): { switch (sequence) { case SEQUENCE_DEFAULT_LOOKAT01: return random_sequence(SEQUENCE_CSS_LOOKAT01, SEQUENCE_CSS_LOOKAT02); default: return sequence; } } case FNV("models/weapons/v_knife_push.mdl"): { switch(sequence) { case SEQUENCE_DEFAULT_IDLE2: return SEQUENCE_DAGGERS_IDLE1; case SEQUENCE_DEFAULT_LIGHT_MISS1: case SEQUENCE_DEFAULT_LIGHT_MISS2: return random_sequence(SEQUENCE_DAGGERS_LIGHT_MISS1, SEQUENCE_DAGGERS_LIGHT_MISS5); case SEQUENCE_DEFAULT_HEAVY_MISS1: return random_sequence(SEQUENCE_DAGGERS_HEAVY_MISS2, SEQUENCE_DAGGERS_HEAVY_MISS1); case SEQUENCE_DEFAULT_HEAVY_HIT1: case SEQUENCE_DEFAULT_HEAVY_BACKSTAB: case SEQUENCE_DEFAULT_LOOKAT01: return sequence + 3; case SEQUENCE_DEFAULT_DRAW: case SEQUENCE_DEFAULT_IDLE1: return sequence; default: return sequence + 2; } } case FNV("models/weapons/v_knife_survival_bowie.mdl"): { switch(sequence) { case SEQUENCE_DEFAULT_DRAW: case SEQUENCE_DEFAULT_IDLE1: return sequence; case SEQUENCE_DEFAULT_IDLE2: return SEQUENCE_BOWIE_IDLE1; default: return sequence - 1; } } case FNV("models/weapons/v_knife_ursus.mdl"): { switch (sequence) { case SEQUENCE_DEFAULT_DRAW: return random_sequence(SEQUENCE_BUTTERFLY_DRAW, SEQUENCE_BUTTERFLY_DRAW2); case SEQUENCE_DEFAULT_LOOKAT01: return random_sequence(SEQUENCE_BUTTERFLY_LOOKAT01, 14); default: return sequence + 1; } } case FNV("models/weapons/v_knife_stiletto.mdl"): { switch (sequence) { case SEQUENCE_DEFAULT_LOOKAT01: return random_sequence(12, 13); default: return sequence; } } case FNV("models/weapons/v_knife_widowmaker.mdl"): { switch (sequence) { case SEQUENCE_DEFAULT_LOOKAT01: return random_sequence(14, 15); default: return sequence; } } default: return sequence; } } static auto do_sequence_remapping(sdk::CRecvProxyData* data, sdk::C_BaseViewModel* entity) -> void { const auto local = static_cast<sdk::C_BasePlayer*>(g_entity_list->GetClientEntity(g_engine->GetLocalPlayer())); if(!local) return; if(local->GetLifeState() != sdk::LifeState::ALIVE) return; const auto owner = get_entity_from_handle<sdk::C_BasePlayer>(entity->GetOwner()); if(owner != local) return; const auto view_model_weapon = get_entity_from_handle<sdk::C_BaseAttributableItem>(entity->GetWeapon()); if(!view_model_weapon) return; const auto weapon_info = game_data::get_weapon_info(view_model_weapon->GetItemDefinitionIndex()); if(!weapon_info) return; const auto override_model = weapon_info->model; auto& sequence = data->m_Value.m_Int; sequence = get_new_animation(fnv::hash_runtime(override_model), sequence); } // Replacement function that will be called when the view model animation sequence changes. auto __cdecl hooks::sequence_proxy_fn(const sdk::CRecvProxyData* proxy_data_const, void* entity, void* output) -> void { // Ensure our other dynamic object hooks are in place. // Must do this from a game thread. ensure_dynamic_hooks(); static auto original_fn = g_sequence_hook->get_original_function(); // Remove the constness from the proxy data allowing us to make changes. const auto proxy_data = const_cast<sdk::CRecvProxyData*>(proxy_data_const); const auto view_model = static_cast<sdk::C_BaseViewModel*>(entity); do_sequence_remapping(proxy_data, view_model); // Call the original function with our edited data. original_fn(proxy_data_const, entity, output); } <|endoftext|>
<commit_before>#include "AtomTable_wrap.h" #include <opencog/atomspace/AtomTable.h> #include <boost/python/class.hpp> using namespace opencog; using namespace boost::python; void init_AtomTable_py() { class_<AtomTable, boost::noncopyable>("AtomTable", no_init) .def(init<optional<bool> >()) .def("getSize", &AtomTable::getSize) ; } <commit_msg>Exposed getHandle() methods of AtomTable class.<commit_after>#include "AtomTable_wrap.h" #include <opencog/atomspace/AtomTable.h> #include <boost/python/class.hpp> #include <boost/python/return_value_policy.hpp> #include <boost/python/manage_new_object.hpp> using namespace opencog; using namespace boost::python; void init_AtomTable_py() { class_<AtomTable, boost::noncopyable>("AtomTable", no_init) .def(init<optional<bool> >()) .def("getSize", &AtomTable::getSize) .def("getHandle", (Handle (AtomTable::*)(const char*, Type) const) &AtomTable::getHandle) .def("getHandle", (Handle (AtomTable::*)(const Node*) const) &AtomTable::getHandle) .def("getHandle", (Handle (AtomTable::*)(Type, const HandleSeq &seq) const) &AtomTable::getHandle) .def("getHandle", (Handle (AtomTable::*)(const Link*) const) &AtomTable::getHandle) .def("getHandleSet", (HandleEntry* (AtomTable::*)(Type, bool) const) &AtomTable::getHandleSet, return_value_policy<manage_new_object>()) ; } <|endoftext|>
<commit_before>#pragma once #include <rapidjson/document.h> #include "blackhole/repository/config/parser.hpp" namespace blackhole { namespace repository { namespace config { // Converter adapter specializations for rapidjson value. template<> struct transformer_t<rapidjson::Value> { typedef rapidjson::Value value_type; static dynamic_t transform(const value_type& value) { switch (value.GetType()) { case rapidjson::kNullType: std::cout << "null" << std::endl; throw blackhole::error_t("null values are not supported"); case rapidjson::kFalseType: case rapidjson::kTrueType: return value.GetBool(); case rapidjson::kNumberType: { if (value.IsInt()) { std::cout << "number: " << value.GetInt() << std::endl; return value.GetInt(); } else if (value.IsInt64()) { std::cout << "number: " << value.GetInt64() << std::endl; return value.GetInt64(); } else if (value.IsUint()) { std::cout << "number: " << value.GetUint() << std::endl; return value.GetUint(); } else if (value.IsUint64()) { std::cout << "number: " << value.GetUint64() << std::endl; return value.GetUint64(); } else { std::cout << "number: " << value.GetDouble() << std::endl; return value.GetDouble(); } } case rapidjson::kStringType: std::cout << "string: " << value.GetString() << std::endl; return value.GetString(); case rapidjson::kArrayType: { std::cout << "begin array" << std::endl; dynamic_t::array_t array; for (auto it = value.Begin(); it != value.End(); ++it) { array.push_back(transformer_t<value_type>::transform(*it)); } std::cout << "end array" << std::endl; return array; } case rapidjson::kObjectType: { std::cout << "begin object" << std::endl; dynamic_t::object_t object; for (auto it = value.MemberBegin(); it != value.MemberEnd(); ++it) { std::string name = it->name.GetString(); dynamic_t value = transformer_t<value_type>::transform(it->value); std::cout << "key: " << name << std::endl; object[name] = value; } std::cout << "end object" << std::endl; return object; } default: BOOST_ASSERT(false); } } }; } // namespace config } // namespace repository } // namespace blackhole <commit_msg>[Code Clean] Removing debug output.<commit_after>#pragma once #include <rapidjson/document.h> #include "blackhole/repository/config/parser.hpp" namespace blackhole { namespace repository { namespace config { // Converter adapter specializations for rapidjson value. template<> struct transformer_t<rapidjson::Value> { typedef rapidjson::Value value_type; static dynamic_t transform(const value_type& value) { switch (value.GetType()) { case rapidjson::kNullType: throw blackhole::error_t("null values are not supported"); case rapidjson::kFalseType: case rapidjson::kTrueType: return value.GetBool(); case rapidjson::kNumberType: { if (value.IsInt()) { return value.GetInt(); } else if (value.IsInt64()) { return value.GetInt64(); } else if (value.IsUint()) { return value.GetUint(); } else if (value.IsUint64()) { return value.GetUint64(); } else { return value.GetDouble(); } } case rapidjson::kStringType: return value.GetString(); case rapidjson::kArrayType: { dynamic_t::array_t array; for (auto it = value.Begin(); it != value.End(); ++it) { array.push_back(transformer_t<value_type>::transform(*it)); } return array; } case rapidjson::kObjectType: { dynamic_t::object_t object; for (auto it = value.MemberBegin(); it != value.MemberEnd(); ++it) { std::string name = it->name.GetString(); dynamic_t value = transformer_t<value_type>::transform(it->value); object[name] = value; } return object; } default: BOOST_ASSERT(false); } } }; } // namespace config } // namespace repository } // namespace blackhole <|endoftext|>
<commit_before>/* * The Apache Software License, Version 1.1 * * * Copyright (c) 1999 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xalan" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact [email protected]. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ // Class header file... #include "XalanStdOutputStream.hpp" #include <cerrno> #if defined(XALAN_OLD_STREAM_HEADERS) #include <iostream.h> #include <strstream.h> #else #include <iostream> #include <strstream> #endif #include <PlatformSupport/DOMStringHelper.hpp> #if !defined(XALAN_NO_NAMESPACES) using std::ostream; using std::cerr; #endif XalanStdOutputStream::XalanStdOutputStream(ostream& theOutputStream) : XalanOutputStream(), m_outputStream(theOutputStream) { // This will make sure that cerr is not buffered... if (&m_outputStream == &cerr) { setBufferSize(0); } } XalanStdOutputStream::~XalanStdOutputStream() { } void XalanStdOutputStream::doFlush() { // Don't try to flush if the stream is in a bad state... if(m_outputStream) { m_outputStream.flush(); if(!m_outputStream) { throw XalanStdOutputStreamWriteException(errno); } } } void XalanStdOutputStream::writeData( const char* theBuffer, size_type theBufferLength) { assert(StreamSizeType(theBufferLength) == theBufferLength); m_outputStream.write(theBuffer, StreamSizeType(theBufferLength)); if(!m_outputStream) { throw XalanStdOutputStreamWriteException(errno); } } static XalanDOMString FormatMessageLocal( const char* theMessage, int theErrorCode) { #if !defined(XALAN_NO_NAMESPACES) using std::ostrstream; #endif XalanDOMString theResult(TranscodeFromLocalCodePage(theMessage)); ostrstream theFormatter; theFormatter << ". The error code was " << theErrorCode << "." << '\0'; append(theResult, theFormatter.str()); delete theFormatter.str(); return theResult; } XalanStdOutputStream::XalanStdOutputStreamWriteException::XalanStdOutputStreamWriteException( int theErrorCode) : XalanOutputStreamException(FormatMessageLocal("Error writing to standard stream!", theErrorCode), TranscodeFromLocalCodePage("XercesStdOutputStreamWriteException")) { } XalanStdOutputStream::XalanStdOutputStreamWriteException::~XalanStdOutputStreamWriteException() { } <commit_msg>Added using declaration.<commit_after>/* * The Apache Software License, Version 1.1 * * * Copyright (c) 1999 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xalan" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact [email protected]. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ // Class header file... #include "XalanStdOutputStream.hpp" #include <cerrno> #if defined(XALAN_OLD_STREAM_HEADERS) #include <iostream.h> #include <strstream.h> #else #include <iostream> #include <strstream> #endif #include <PlatformSupport/DOMStringHelper.hpp> #if !defined(XALAN_NO_NAMESPACES) using std::ostream; using std::cerr; #endif XalanStdOutputStream::XalanStdOutputStream(ostream& theOutputStream) : XalanOutputStream(), m_outputStream(theOutputStream) { // This will make sure that cerr is not buffered... if (&m_outputStream == &cerr) { setBufferSize(0); } } XalanStdOutputStream::~XalanStdOutputStream() { } void XalanStdOutputStream::doFlush() { // Don't try to flush if the stream is in a bad state... if(m_outputStream) { m_outputStream.flush(); if(!m_outputStream) { #if defined(XALAN_STRICT_ANSI_HEADERS) using namespace std; #endif throw XalanStdOutputStreamWriteException(errno); } } } void XalanStdOutputStream::writeData( const char* theBuffer, size_type theBufferLength) { assert(StreamSizeType(theBufferLength) == theBufferLength); m_outputStream.write(theBuffer, StreamSizeType(theBufferLength)); if(!m_outputStream) { #if defined(XALAN_STRICT_ANSI_HEADERS) using namespace std; #endif throw XalanStdOutputStreamWriteException(errno); } } static XalanDOMString FormatMessageLocal( const char* theMessage, int theErrorCode) { #if !defined(XALAN_NO_NAMESPACES) using std::ostrstream; #endif XalanDOMString theResult(TranscodeFromLocalCodePage(theMessage)); ostrstream theFormatter; theFormatter << ". The error code was " << theErrorCode << "." << '\0'; append(theResult, theFormatter.str()); delete theFormatter.str(); return theResult; } XalanStdOutputStream::XalanStdOutputStreamWriteException::XalanStdOutputStreamWriteException( int theErrorCode) : XalanOutputStreamException(FormatMessageLocal("Error writing to standard stream!", theErrorCode), TranscodeFromLocalCodePage("XercesStdOutputStreamWriteException")) { } XalanStdOutputStream::XalanStdOutputStreamWriteException::~XalanStdOutputStreamWriteException() { } <|endoftext|>
<commit_before>// Copyright (c) 2015 Baidu, 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. // Authors: Zhangyi Chen ([email protected]) #include <algorithm> // std::set_union #include <gflags/gflags.h> #include "butil/containers/flat_map.h" #include "butil/errno.h" #include "butil/strings/string_number_conversions.h" #include "brpc/socket.h" #include "brpc/policy/consistent_hashing_load_balancer.h" #include "brpc/policy/hasher.h" namespace brpc { namespace policy { // TODO: or 160? DEFINE_int32(chash_num_replicas, 100, "default number of replicas per server in chash"); class ReplicaPolicy { public: ReplicaPolicy() : _hash_func(nullptr) {} ReplicaPolicy(HashFunc hash) : _hash_func(hash) {} virtual ~ReplicaPolicy(); virtual bool Build(ServerId server, size_t num_replicas, std::vector<ConsistentHashingLoadBalancer::Node>* replicas) const = 0; static const ReplicaPolicy* GetReplicaPolicy(const std::string& name) { auto iter = _policy_map.find(name); if (iter != _policy_map.end()) { return iter->second; } return nullptr; } protected: HashFunc _hash_func = nullptr; private: static const std::map<std::string, const ReplicaPolicy*> _policy_map; }; class DefaultReplicaPolicy : public ReplicaPolicy { public: DefaultReplicaPolicy(HashFunc hash) : ReplicaPolicy(hash) {} virtual bool Build(ServerId server, size_t num_replicas, std::vector<ConsistentHashingLoadBalancer::Node>* replicas) const; }; bool DefaultReplicaPolicy::Build(ServerId server, size_t num_replicas, std::vector<ConsistentHashingLoadBalancer::Node>* replicas) const { SocketUniquePtr ptr; if (Socket::AddressFailedAsWell(server.id, &ptr) == -1) { return false; } replicas->clear(); for (size_t i = 0; i < num_replicas; ++i) { char host[32]; int len = snprintf(host, sizeof(host), "%s-%lu", endpoint2str(ptr->remote_side()).c_str(), i); ConsistentHashingLoadBalancer::Node node; node.hash = _hash_func(host, len); node.server_sock = server; node.server_addr = ptr->remote_side(); replicas->push_back(node); } return true; } class KetamaReplicaPolicy : public ReplicaPolicy { public: virtual bool Build(ServerId server, size_t num_replicas, std::vector<ConsistentHashingLoadBalancer::Node>* replicas) const; }; bool KetamaReplicaPolicy::Build(ServerId server, size_t num_replicas, std::vector<ConsistentHashingLoadBalancer::Node>* replicas) const { SocketUniquePtr ptr; if (Socket::AddressFailedAsWell(server.id, &ptr) == -1) { return false; } replicas->clear(); const size_t points_per_hash = 4; CHECK(num_replicas % points_per_hash == 0) << "Ketam hash replicas number(" << num_replicas << ") should be n*4"; for (size_t i = 0; i < num_replicas / points_per_hash; ++i) { char host[32]; int len = snprintf(host, sizeof(host), "%s-%lu", endpoint2str(ptr->remote_side()).c_str(), i); unsigned char digest[16]; MD5HashSignature(host, len, digest); for (size_t j = 0; j < points_per_hash; ++j) { ConsistentHashingLoadBalancer::Node node; node.server_sock = server; node.server_addr = ptr->remote_side(); node.hash = ((uint32_t) (digest[3 + j * 4] & 0xFF) << 24) | ((uint32_t) (digest[2 + j * 4] & 0xFF) << 16) | ((uint32_t) (digest[1 + j * 4] & 0xFF) << 8) | (digest[0 + j * 4] & 0xFF); replicas->push_back(node); } } return true; } const std::map<std::string, const ReplicaPolicy*> ReplicaPolicy::_policy_map = { {"murmurhash3", new DefaultReplicaPolicy(MurmurHash32)}, {"md5", new DefaultReplicaPolicy(MD5Hash32)}, {"ketama", new KetamaReplicaPolicy} }; ConsistentHashingLoadBalancer::ConsistentHashingLoadBalancer(const char* name) : _num_replicas(FLAGS_chash_num_replicas), _name(name) { _replicas_policy = ReplicaPolicy::GetReplicaPolicy(name); CHECK(_replicas_policy) << "Fail to find replica policy for consistency lb: '" << name << '\''; } size_t ConsistentHashingLoadBalancer::AddBatch( std::vector<Node> &bg, const std::vector<Node> &fg, const std::vector<Node> &servers, bool *executed) { if (*executed) { // Hack DBD return fg.size() - bg.size(); } *executed = true; bg.resize(fg.size() + servers.size()); bg.resize(std::set_union(fg.begin(), fg.end(), servers.begin(), servers.end(), bg.begin()) - bg.begin()); return bg.size() - fg.size(); } size_t ConsistentHashingLoadBalancer::RemoveBatch( std::vector<Node> &bg, const std::vector<Node> &fg, const std::vector<ServerId> &servers, bool *executed) { if (*executed) { return bg.size() - fg.size(); } *executed = true; if (servers.empty()) { bg = fg; return 0; } butil::FlatSet<ServerId> id_set; bool use_set = true; if (id_set.init(servers.size() * 2) == 0) { for (size_t i = 0; i < servers.size(); ++i) { if (id_set.insert(servers[i]) == NULL) { use_set = false; break; } } } else { use_set = false; } CHECK(use_set) << "Fail to construct id_set, " << berror(); bg.clear(); for (size_t i = 0; i < fg.size(); ++i) { const bool removed = use_set ? (id_set.seek(fg[i].server_sock) != NULL) : (std::find(servers.begin(), servers.end(), fg[i].server_sock) != servers.end()); if (!removed) { bg.push_back(fg[i]); } } return fg.size() - bg.size(); } size_t ConsistentHashingLoadBalancer::Remove( std::vector<Node> &bg, const std::vector<Node> &fg, const ServerId& server, bool *executed) { if (*executed) { return bg.size() - fg.size(); } *executed = true; bg.clear(); for (size_t i = 0; i < fg.size(); ++i) { if (fg[i].server_sock != server) { bg.push_back(fg[i]); } } return fg.size() - bg.size(); } bool ConsistentHashingLoadBalancer::AddServer(const ServerId& server) { std::vector<Node> add_nodes; add_nodes.reserve(_num_replicas); if (!_replicas_policy->Build(server, _num_replicas, &add_nodes)) { return false; } std::sort(add_nodes.begin(), add_nodes.end()); bool executed = false; const size_t ret = _db_hash_ring.ModifyWithForeground( AddBatch, add_nodes, &executed); CHECK(ret == 0 || ret == _num_replicas) << ret; return ret != 0; } size_t ConsistentHashingLoadBalancer::AddServersInBatch( const std::vector<ServerId> &servers) { std::vector<Node> add_nodes; add_nodes.reserve(servers.size() * _num_replicas); std::vector<Node> replicas; replicas.reserve(_num_replicas); for (size_t i = 0; i < servers.size(); ++i) { replicas.clear(); if (_replicas_policy->Build(servers[i], _num_replicas, &replicas)) { add_nodes.insert(add_nodes.end(), replicas.begin(), replicas.end()); } } std::sort(add_nodes.begin(), add_nodes.end()); bool executed = false; const size_t ret = _db_hash_ring.ModifyWithForeground(AddBatch, add_nodes, &executed); CHECK(ret % _num_replicas == 0); const size_t n = ret / _num_replicas; LOG_IF(ERROR, n != servers.size()) << "Fail to AddServersInBatch, expected " << servers.size() << " actually " << n; return n; } bool ConsistentHashingLoadBalancer::RemoveServer(const ServerId& server) { bool executed = false; const size_t ret = _db_hash_ring.ModifyWithForeground(Remove, server, &executed); CHECK(ret == 0 || ret == _num_replicas); return ret != 0; } size_t ConsistentHashingLoadBalancer::RemoveServersInBatch( const std::vector<ServerId> &servers) { bool executed = false; const size_t ret = _db_hash_ring.ModifyWithForeground(RemoveBatch, servers, &executed); CHECK(ret % _num_replicas == 0); const size_t n = ret / _num_replicas; LOG_IF(ERROR, n != servers.size()) << "Fail to RemoveServersInBatch, expected " << servers.size() << " actually " << n; return n; } LoadBalancer *ConsistentHashingLoadBalancer::New() const { return new (std::nothrow) ConsistentHashingLoadBalancer(_name.c_str()); } void ConsistentHashingLoadBalancer::Destroy() { delete this; } int ConsistentHashingLoadBalancer::SelectServer( const SelectIn &in, SelectOut *out) { if (!in.has_request_code) { LOG(ERROR) << "Controller.set_request_code() is required"; return EINVAL; } if (in.request_code > UINT_MAX) { LOG(ERROR) << "request_code must be 32-bit currently"; return EINVAL; } butil::DoublyBufferedData<std::vector<Node> >::ScopedPtr s; if (_db_hash_ring.Read(&s) != 0) { return ENOMEM; } if (s->empty()) { return ENODATA; } std::vector<Node>::const_iterator choice = std::lower_bound(s->begin(), s->end(), (uint32_t)in.request_code); if (choice == s->end()) { choice = s->begin(); } for (size_t i = 0; i < s->size(); ++i) { if (((i + 1) == s->size() // always take last chance || !ExcludedServers::IsExcluded(in.excluded, choice->server_sock.id)) && Socket::Address(choice->server_sock.id, out->ptr) == 0 && !(*out->ptr)->IsLogOff()) { return 0; } else { if (++choice == s->end()) { choice = s->begin(); } } } return EHOSTDOWN; } void ConsistentHashingLoadBalancer::Describe( std::ostream &os, const DescribeOptions& options) { if (!options.verbose) { os << "c_hash"; return; } os << "ConsistentHashingLoadBalancer {\n" << " hash function: " << _name << '\n' << " replica per host: " << _num_replicas << '\n'; std::map<butil::EndPoint, double> load_map; GetLoads(&load_map); os << " number of hosts: " << load_map.size() << '\n'; os << " load of hosts: {\n"; double expected_load_per_server = 1.0 / load_map.size(); double load_sum = 0; double load_sqr_sum = 0; for (std::map<butil::EndPoint, double>::iterator it = load_map.begin(); it!= load_map.end(); ++it) { os << " " << it->first << ": " << it->second << '\n'; double normalized_load = it->second / expected_load_per_server; load_sum += normalized_load; load_sqr_sum += normalized_load * normalized_load; } os << " }\n"; os << "deviation: " << sqrt(load_sqr_sum * load_map.size() - load_sum * load_sum) / load_map.size(); os << "}\n"; } void ConsistentHashingLoadBalancer::GetLoads( std::map<butil::EndPoint, double> *load_map) { load_map->clear(); std::map<butil::EndPoint, uint32_t> count_map; do { butil::DoublyBufferedData<std::vector<Node> >::ScopedPtr s; if (_db_hash_ring.Read(&s) != 0) { break; } if (s->empty()) { break; } count_map[s->begin()->server_addr] += s->begin()->hash + (UINT_MAX - (s->end() - 1)->hash); for (size_t i = 1; i < s->size(); ++i) { count_map[(*s.get())[i].server_addr] += (*s.get())[i].hash - (*s.get())[i - 1].hash; } } while (0); for (std::map<butil::EndPoint, uint32_t>::iterator it = count_map.begin(); it!= count_map.end(); ++it) { (*load_map)[it->first] = (double)it->second / UINT_MAX; } } bool ConsistentHashingLoadBalancer::SetParameters(const butil::StringPiece& params) { butil::StringPairs param_vec; if (!SplitParameters(params, &param_vec)) { return false; } for (const std::pair<std::string, std::string>& param : param_vec) { if (param.first == "replicas") { size_t replicas = 0; if (butil::StringToSizeT(param.second, &replicas)) { _num_replicas = replicas; } else { return false; } continue; } LOG(ERROR) << "Failed to set this unknown parameters " << param.first << '=' << param.second; } return true; } } // namespace policy } // namespace brpc <commit_msg>move GetReplicaPolicy out of class ReplicaPolicy<commit_after>// Copyright (c) 2015 Baidu, 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. // Authors: Zhangyi Chen ([email protected]) #include <algorithm> // std::set_union #include <gflags/gflags.h> #include "butil/containers/flat_map.h" #include "butil/errno.h" #include "butil/strings/string_number_conversions.h" #include "brpc/socket.h" #include "brpc/policy/consistent_hashing_load_balancer.h" #include "brpc/policy/hasher.h" namespace brpc { namespace policy { // TODO: or 160? DEFINE_int32(chash_num_replicas, 100, "default number of replicas per server in chash"); class ReplicaPolicy { public: ReplicaPolicy() : _hash_func(nullptr) {} ReplicaPolicy(HashFunc hash) : _hash_func(hash) {} virtual ~ReplicaPolicy(); virtual bool Build(ServerId server, size_t num_replicas, std::vector<ConsistentHashingLoadBalancer::Node>* replicas) const = 0; protected: HashFunc _hash_func; }; class DefaultReplicaPolicy : public ReplicaPolicy { public: DefaultReplicaPolicy(HashFunc hash) : ReplicaPolicy(hash) {} virtual bool Build(ServerId server, size_t num_replicas, std::vector<ConsistentHashingLoadBalancer::Node>* replicas) const; }; bool DefaultReplicaPolicy::Build(ServerId server, size_t num_replicas, std::vector<ConsistentHashingLoadBalancer::Node>* replicas) const { SocketUniquePtr ptr; if (Socket::AddressFailedAsWell(server.id, &ptr) == -1) { return false; } replicas->clear(); for (size_t i = 0; i < num_replicas; ++i) { char host[32]; int len = snprintf(host, sizeof(host), "%s-%lu", endpoint2str(ptr->remote_side()).c_str(), i); ConsistentHashingLoadBalancer::Node node; node.hash = _hash_func(host, len); node.server_sock = server; node.server_addr = ptr->remote_side(); replicas->push_back(node); } return true; } class KetamaReplicaPolicy : public ReplicaPolicy { public: virtual bool Build(ServerId server, size_t num_replicas, std::vector<ConsistentHashingLoadBalancer::Node>* replicas) const; }; bool KetamaReplicaPolicy::Build(ServerId server, size_t num_replicas, std::vector<ConsistentHashingLoadBalancer::Node>* replicas) const { SocketUniquePtr ptr; if (Socket::AddressFailedAsWell(server.id, &ptr) == -1) { return false; } replicas->clear(); const size_t points_per_hash = 4; CHECK(num_replicas % points_per_hash == 0) << "Ketam hash replicas number(" << num_replicas << ") should be n*4"; for (size_t i = 0; i < num_replicas / points_per_hash; ++i) { char host[32]; int len = snprintf(host, sizeof(host), "%s-%lu", endpoint2str(ptr->remote_side()).c_str(), i); unsigned char digest[16]; MD5HashSignature(host, len, digest); for (size_t j = 0; j < points_per_hash; ++j) { ConsistentHashingLoadBalancer::Node node; node.server_sock = server; node.server_addr = ptr->remote_side(); node.hash = ((uint32_t) (digest[3 + j * 4] & 0xFF) << 24) | ((uint32_t) (digest[2 + j * 4] & 0xFF) << 16) | ((uint32_t) (digest[1 + j * 4] & 0xFF) << 8) | (digest[0 + j * 4] & 0xFF); replicas->push_back(node); } } return true; } namespace { const std::map<std::string, const ReplicaPolicy*> g_replica_policy_map = { {"murmurhash3", new DefaultReplicaPolicy(MurmurHash32)}, {"md5", new DefaultReplicaPolicy(MD5Hash32)}, {"ketama", new KetamaReplicaPolicy} }; const ReplicaPolicy* GetReplicaPolicy(const std::string& name) { auto iter = g_replica_policy_map.find(name); if (iter != g_replica_policy_map.end()) { return iter->second; } return nullptr; } } // namespace ConsistentHashingLoadBalancer::ConsistentHashingLoadBalancer(const char* name) : _num_replicas(FLAGS_chash_num_replicas), _name(name) { _replicas_policy = GetReplicaPolicy(name); CHECK(_replicas_policy) << "Fail to find replica policy for consistency lb: '" << name << '\''; } size_t ConsistentHashingLoadBalancer::AddBatch( std::vector<Node> &bg, const std::vector<Node> &fg, const std::vector<Node> &servers, bool *executed) { if (*executed) { // Hack DBD return fg.size() - bg.size(); } *executed = true; bg.resize(fg.size() + servers.size()); bg.resize(std::set_union(fg.begin(), fg.end(), servers.begin(), servers.end(), bg.begin()) - bg.begin()); return bg.size() - fg.size(); } size_t ConsistentHashingLoadBalancer::RemoveBatch( std::vector<Node> &bg, const std::vector<Node> &fg, const std::vector<ServerId> &servers, bool *executed) { if (*executed) { return bg.size() - fg.size(); } *executed = true; if (servers.empty()) { bg = fg; return 0; } butil::FlatSet<ServerId> id_set; bool use_set = true; if (id_set.init(servers.size() * 2) == 0) { for (size_t i = 0; i < servers.size(); ++i) { if (id_set.insert(servers[i]) == NULL) { use_set = false; break; } } } else { use_set = false; } CHECK(use_set) << "Fail to construct id_set, " << berror(); bg.clear(); for (size_t i = 0; i < fg.size(); ++i) { const bool removed = use_set ? (id_set.seek(fg[i].server_sock) != NULL) : (std::find(servers.begin(), servers.end(), fg[i].server_sock) != servers.end()); if (!removed) { bg.push_back(fg[i]); } } return fg.size() - bg.size(); } size_t ConsistentHashingLoadBalancer::Remove( std::vector<Node> &bg, const std::vector<Node> &fg, const ServerId& server, bool *executed) { if (*executed) { return bg.size() - fg.size(); } *executed = true; bg.clear(); for (size_t i = 0; i < fg.size(); ++i) { if (fg[i].server_sock != server) { bg.push_back(fg[i]); } } return fg.size() - bg.size(); } bool ConsistentHashingLoadBalancer::AddServer(const ServerId& server) { std::vector<Node> add_nodes; add_nodes.reserve(_num_replicas); if (!_replicas_policy->Build(server, _num_replicas, &add_nodes)) { return false; } std::sort(add_nodes.begin(), add_nodes.end()); bool executed = false; const size_t ret = _db_hash_ring.ModifyWithForeground( AddBatch, add_nodes, &executed); CHECK(ret == 0 || ret == _num_replicas) << ret; return ret != 0; } size_t ConsistentHashingLoadBalancer::AddServersInBatch( const std::vector<ServerId> &servers) { std::vector<Node> add_nodes; add_nodes.reserve(servers.size() * _num_replicas); std::vector<Node> replicas; replicas.reserve(_num_replicas); for (size_t i = 0; i < servers.size(); ++i) { replicas.clear(); if (_replicas_policy->Build(servers[i], _num_replicas, &replicas)) { add_nodes.insert(add_nodes.end(), replicas.begin(), replicas.end()); } } std::sort(add_nodes.begin(), add_nodes.end()); bool executed = false; const size_t ret = _db_hash_ring.ModifyWithForeground(AddBatch, add_nodes, &executed); CHECK(ret % _num_replicas == 0); const size_t n = ret / _num_replicas; LOG_IF(ERROR, n != servers.size()) << "Fail to AddServersInBatch, expected " << servers.size() << " actually " << n; return n; } bool ConsistentHashingLoadBalancer::RemoveServer(const ServerId& server) { bool executed = false; const size_t ret = _db_hash_ring.ModifyWithForeground(Remove, server, &executed); CHECK(ret == 0 || ret == _num_replicas); return ret != 0; } size_t ConsistentHashingLoadBalancer::RemoveServersInBatch( const std::vector<ServerId> &servers) { bool executed = false; const size_t ret = _db_hash_ring.ModifyWithForeground(RemoveBatch, servers, &executed); CHECK(ret % _num_replicas == 0); const size_t n = ret / _num_replicas; LOG_IF(ERROR, n != servers.size()) << "Fail to RemoveServersInBatch, expected " << servers.size() << " actually " << n; return n; } LoadBalancer *ConsistentHashingLoadBalancer::New() const { return new (std::nothrow) ConsistentHashingLoadBalancer(_name.c_str()); } void ConsistentHashingLoadBalancer::Destroy() { delete this; } int ConsistentHashingLoadBalancer::SelectServer( const SelectIn &in, SelectOut *out) { if (!in.has_request_code) { LOG(ERROR) << "Controller.set_request_code() is required"; return EINVAL; } if (in.request_code > UINT_MAX) { LOG(ERROR) << "request_code must be 32-bit currently"; return EINVAL; } butil::DoublyBufferedData<std::vector<Node> >::ScopedPtr s; if (_db_hash_ring.Read(&s) != 0) { return ENOMEM; } if (s->empty()) { return ENODATA; } std::vector<Node>::const_iterator choice = std::lower_bound(s->begin(), s->end(), (uint32_t)in.request_code); if (choice == s->end()) { choice = s->begin(); } for (size_t i = 0; i < s->size(); ++i) { if (((i + 1) == s->size() // always take last chance || !ExcludedServers::IsExcluded(in.excluded, choice->server_sock.id)) && Socket::Address(choice->server_sock.id, out->ptr) == 0 && !(*out->ptr)->IsLogOff()) { return 0; } else { if (++choice == s->end()) { choice = s->begin(); } } } return EHOSTDOWN; } void ConsistentHashingLoadBalancer::Describe( std::ostream &os, const DescribeOptions& options) { if (!options.verbose) { os << "c_hash"; return; } os << "ConsistentHashingLoadBalancer {\n" << " hash function: " << _name << '\n' << " replica per host: " << _num_replicas << '\n'; std::map<butil::EndPoint, double> load_map; GetLoads(&load_map); os << " number of hosts: " << load_map.size() << '\n'; os << " load of hosts: {\n"; double expected_load_per_server = 1.0 / load_map.size(); double load_sum = 0; double load_sqr_sum = 0; for (std::map<butil::EndPoint, double>::iterator it = load_map.begin(); it!= load_map.end(); ++it) { os << " " << it->first << ": " << it->second << '\n'; double normalized_load = it->second / expected_load_per_server; load_sum += normalized_load; load_sqr_sum += normalized_load * normalized_load; } os << " }\n"; os << "deviation: " << sqrt(load_sqr_sum * load_map.size() - load_sum * load_sum) / load_map.size(); os << "}\n"; } void ConsistentHashingLoadBalancer::GetLoads( std::map<butil::EndPoint, double> *load_map) { load_map->clear(); std::map<butil::EndPoint, uint32_t> count_map; do { butil::DoublyBufferedData<std::vector<Node> >::ScopedPtr s; if (_db_hash_ring.Read(&s) != 0) { break; } if (s->empty()) { break; } count_map[s->begin()->server_addr] += s->begin()->hash + (UINT_MAX - (s->end() - 1)->hash); for (size_t i = 1; i < s->size(); ++i) { count_map[(*s.get())[i].server_addr] += (*s.get())[i].hash - (*s.get())[i - 1].hash; } } while (0); for (std::map<butil::EndPoint, uint32_t>::iterator it = count_map.begin(); it!= count_map.end(); ++it) { (*load_map)[it->first] = (double)it->second / UINT_MAX; } } bool ConsistentHashingLoadBalancer::SetParameters(const butil::StringPiece& params) { butil::StringPairs param_vec; if (!SplitParameters(params, &param_vec)) { return false; } for (const std::pair<std::string, std::string>& param : param_vec) { if (param.first == "replicas") { size_t replicas = 0; if (butil::StringToSizeT(param.second, &replicas)) { _num_replicas = replicas; } else { return false; } continue; } LOG(ERROR) << "Failed to set this unknown parameters " << param.first << '=' << param.second; } return true; } } // namespace policy } // namespace brpc <|endoftext|>
<commit_before>// Copyright Daniel Wallin 2006. Use, modification and distribution is // subject to 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 <boost/python.hpp> #include <libtorrent/torrent_info.hpp> #include "libtorrent/intrusive_ptr_base.hpp" using namespace boost::python; using namespace libtorrent; namespace { std::vector<announce_entry>::const_iterator begin_trackers(torrent_info& i) { return i.trackers().begin(); } std::vector<announce_entry>::const_iterator end_trackers(torrent_info& i) { return i.trackers().end(); } void add_node(torrent_info& ti, char const* hostname, int port) { ti.add_node(std::make_pair(hostname, port)); } list nodes(torrent_info const& ti) { list result; typedef std::vector<std::pair<std::string, int> > list_type; for (list_type::const_iterator i = ti.nodes().begin(); i != ti.nodes().end(); ++i) { result.append(make_tuple(i->first, i->second)); } return result; } file_storage::iterator begin_files(torrent_info& i) { return i.begin_files(); } file_storage::iterator end_files(torrent_info& i) { return i.end_files(); } //list files(torrent_info const& ti, bool storage) { list files(torrent_info const& ti, bool storage) { list result; typedef torrent_info::file_iterator iter; for (iter i = ti.begin_files(); i != ti.end_files(); ++i) result.append(ti.files().at(i)); return result; } std::string metadata(torrent_info const& ti) { std::string result(ti.metadata().get(), ti.metadata_size()); return result; } torrent_info construct0(std::string path) { return torrent_info(path); } list map_block(torrent_info& ti, int piece, size_type offset, int size) { std::vector<file_slice> p = ti.map_block(piece, offset, size); list result; for (std::vector<file_slice>::iterator i(p.begin()), e(p.end()); i != e; ++i) result.append(*i); return result; } bool get_tier(announce_entry const& ae) { return ae.tier; } bool get_fail_limit(announce_entry const& ae) { return ae.fail_limit; } bool get_fails(announce_entry const& ae) { return ae.fails; } bool get_source(announce_entry const& ae) { return ae.source; } bool get_verified(announce_entry const& ae) { return ae.verified; } bool get_updating(announce_entry const& ae) { return ae.updating; } bool get_start_sent(announce_entry const& ae) { return ae.start_sent; } bool get_complete_sent(announce_entry const& ae) { return ae.complete_sent; } bool get_send_stats(announce_entry const& ae) { return ae.send_stats; } size_type get_size(file_entry const& fe) { return fe.size; } size_type get_offset(file_entry const& fe) { return fe.offset; } bool get_pad_file(file_entry const& fe) { return fe.pad_file; } bool get_executable_attribute(file_entry const& fe) { return fe.executable_attribute; } bool get_hidden_attribute(file_entry const& fe) { return fe.hidden_attribute; } bool get_symlink_attribute(file_entry const& fe) { return fe.symlink_attribute; } } // namespace unnamed void bind_torrent_info() { return_value_policy<copy_const_reference> copy; void (torrent_info::*rename_file0)(int, std::string const&) = &torrent_info::rename_file; #if TORRENT_USE_WSTRING void (torrent_info::*rename_file1)(int, std::wstring const&) = &torrent_info::rename_file; #endif class_<file_slice>("file_slice") .def_readwrite("file_index", &file_slice::file_index) .def_readwrite("offset", &file_slice::offset) .def_readwrite("size", &file_slice::size) ; class_<torrent_info, boost::intrusive_ptr<torrent_info> >("torrent_info", no_init) #ifndef TORRENT_NO_DEPRECATE .def(init<entry const&>(arg("e"))) #endif .def(init<sha1_hash const&, int>((arg("info_hash"), arg("flags") = 0))) .def(init<char const*, int, int>((arg("buffer"), arg("length"), arg("flags") = 0))) .def(init<std::string, int>((arg("file"), arg("flags") = 0))) .def(init<torrent_info const&, int>((arg("ti"), arg("flags") = 0))) #if TORRENT_USE_WSTRING .def(init<std::wstring, int>((arg("file"), arg("flags") = 0))) #endif .def("add_tracker", &torrent_info::add_tracker, arg("url")) .def("add_url_seed", &torrent_info::add_url_seed) .def("name", &torrent_info::name, copy) .def("comment", &torrent_info::comment, copy) .def("creator", &torrent_info::creator, copy) .def("total_size", &torrent_info::total_size) .def("piece_length", &torrent_info::piece_length) .def("num_pieces", &torrent_info::num_pieces) #ifndef TORRENT_NO_DEPRECATE .def("info_hash", &torrent_info::info_hash, copy) #endif .def("hash_for_piece", &torrent_info::hash_for_piece) .def("piece_size", &torrent_info::piece_size) .def("num_files", &torrent_info::num_files, (arg("storage")=false)) .def("file_at", &torrent_info::file_at) .def("file_at_offset", &torrent_info::file_at_offset) .def("files", &files, (arg("storage")=false)) .def("rename_file", rename_file0) #if TORRENT_USE_WSTRING .def("rename_file", rename_file1) #endif .def("priv", &torrent_info::priv) .def("trackers", range(begin_trackers, end_trackers)) .def("creation_date", &torrent_info::creation_date) .def("add_node", &add_node) .def("nodes", &nodes) .def("metadata", &metadata) .def("metadata_size", &torrent_info::metadata_size) .def("map_block", map_block) .def("map_file", &torrent_info::map_file) ; class_<file_entry>("file_entry") .def_readwrite("path", &file_entry::path) .def_readwrite("symlink_path", &file_entry::symlink_path) .def_readwrite("filehash", &file_entry::filehash) .def_readwrite("mtime", &file_entry::mtime) .add_property("pad_file", &get_pad_file) .add_property("executable_attribute", &get_executable_attribute) .add_property("hidden_attribute", &get_hidden_attribute) .add_property("symlink_attribute", &get_symlink_attribute) .add_property("offset", &get_offset) .add_property("size", &get_size) ; class_<announce_entry>("announce_entry", init<std::string const&>()) .def_readwrite("url", &announce_entry::url) .add_property("tier", &get_tier) .add_property("fail_limit", &get_fail_limit) .add_property("fails", &get_fails) .add_property("source", &get_source) .add_property("verified", &get_verified) .add_property("updating", &get_updating) .add_property("start_sent", &get_start_sent) .add_property("complete_sent", &get_complete_sent) .add_property("send_stats", &get_send_stats) .def("reset", &announce_entry::reset) .def("failed", &announce_entry::failed, arg("retry_interval") = 0) .def("can_announce", &announce_entry::can_announce) .def("is_working", &announce_entry::is_working) .def("trim", &announce_entry::trim) ; enum_<announce_entry::tracker_source>("tracker_source") .value("source_torrent", announce_entry::source_torrent) .value("source_client", announce_entry::source_client) .value("source_magnet_link", announce_entry::source_magnet_link) .value("source_tex", announce_entry::source_tex) ; } <commit_msg>fix tier and fail_limit to be writeable in the python binding<commit_after>// Copyright Daniel Wallin 2006. Use, modification and distribution is // subject to 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 <boost/python.hpp> #include <libtorrent/torrent_info.hpp> #include "libtorrent/intrusive_ptr_base.hpp" using namespace boost::python; using namespace libtorrent; namespace { std::vector<announce_entry>::const_iterator begin_trackers(torrent_info& i) { return i.trackers().begin(); } std::vector<announce_entry>::const_iterator end_trackers(torrent_info& i) { return i.trackers().end(); } void add_node(torrent_info& ti, char const* hostname, int port) { ti.add_node(std::make_pair(hostname, port)); } list nodes(torrent_info const& ti) { list result; typedef std::vector<std::pair<std::string, int> > list_type; for (list_type::const_iterator i = ti.nodes().begin(); i != ti.nodes().end(); ++i) { result.append(make_tuple(i->first, i->second)); } return result; } file_storage::iterator begin_files(torrent_info& i) { return i.begin_files(); } file_storage::iterator end_files(torrent_info& i) { return i.end_files(); } //list files(torrent_info const& ti, bool storage) { list files(torrent_info const& ti, bool storage) { list result; typedef torrent_info::file_iterator iter; for (iter i = ti.begin_files(); i != ti.end_files(); ++i) result.append(ti.files().at(i)); return result; } std::string metadata(torrent_info const& ti) { std::string result(ti.metadata().get(), ti.metadata_size()); return result; } torrent_info construct0(std::string path) { return torrent_info(path); } list map_block(torrent_info& ti, int piece, size_type offset, int size) { std::vector<file_slice> p = ti.map_block(piece, offset, size); list result; for (std::vector<file_slice>::iterator i(p.begin()), e(p.end()); i != e; ++i) result.append(*i); return result; } bool get_tier(announce_entry const& ae) { return ae.tier; } void set_tier(announce_entry& ae, bool v) { ae.tier = v; } bool get_fail_limit(announce_entry const& ae) { return ae.fail_limit; } void set_fail_limit(announce_entry& ae, int l) { ae.fail_limit = l; } bool get_fails(announce_entry const& ae) { return ae.fails; } bool get_source(announce_entry const& ae) { return ae.source; } bool get_verified(announce_entry const& ae) { return ae.verified; } bool get_updating(announce_entry const& ae) { return ae.updating; } bool get_start_sent(announce_entry const& ae) { return ae.start_sent; } bool get_complete_sent(announce_entry const& ae) { return ae.complete_sent; } bool get_send_stats(announce_entry const& ae) { return ae.send_stats; } size_type get_size(file_entry const& fe) { return fe.size; } size_type get_offset(file_entry const& fe) { return fe.offset; } bool get_pad_file(file_entry const& fe) { return fe.pad_file; } bool get_executable_attribute(file_entry const& fe) { return fe.executable_attribute; } bool get_hidden_attribute(file_entry const& fe) { return fe.hidden_attribute; } bool get_symlink_attribute(file_entry const& fe) { return fe.symlink_attribute; } } // namespace unnamed void bind_torrent_info() { return_value_policy<copy_const_reference> copy; void (torrent_info::*rename_file0)(int, std::string const&) = &torrent_info::rename_file; #if TORRENT_USE_WSTRING void (torrent_info::*rename_file1)(int, std::wstring const&) = &torrent_info::rename_file; #endif class_<file_slice>("file_slice") .def_readwrite("file_index", &file_slice::file_index) .def_readwrite("offset", &file_slice::offset) .def_readwrite("size", &file_slice::size) ; class_<torrent_info, boost::intrusive_ptr<torrent_info> >("torrent_info", no_init) #ifndef TORRENT_NO_DEPRECATE .def(init<entry const&>(arg("e"))) #endif .def(init<sha1_hash const&, int>((arg("info_hash"), arg("flags") = 0))) .def(init<char const*, int, int>((arg("buffer"), arg("length"), arg("flags") = 0))) .def(init<std::string, int>((arg("file"), arg("flags") = 0))) .def(init<torrent_info const&, int>((arg("ti"), arg("flags") = 0))) #if TORRENT_USE_WSTRING .def(init<std::wstring, int>((arg("file"), arg("flags") = 0))) #endif .def("add_tracker", &torrent_info::add_tracker, arg("url")) .def("add_url_seed", &torrent_info::add_url_seed) .def("name", &torrent_info::name, copy) .def("comment", &torrent_info::comment, copy) .def("creator", &torrent_info::creator, copy) .def("total_size", &torrent_info::total_size) .def("piece_length", &torrent_info::piece_length) .def("num_pieces", &torrent_info::num_pieces) #ifndef TORRENT_NO_DEPRECATE .def("info_hash", &torrent_info::info_hash, copy) #endif .def("hash_for_piece", &torrent_info::hash_for_piece) .def("piece_size", &torrent_info::piece_size) .def("num_files", &torrent_info::num_files, (arg("storage")=false)) .def("file_at", &torrent_info::file_at) .def("file_at_offset", &torrent_info::file_at_offset) .def("files", &files, (arg("storage")=false)) .def("rename_file", rename_file0) #if TORRENT_USE_WSTRING .def("rename_file", rename_file1) #endif .def("priv", &torrent_info::priv) .def("trackers", range(begin_trackers, end_trackers)) .def("creation_date", &torrent_info::creation_date) .def("add_node", &add_node) .def("nodes", &nodes) .def("metadata", &metadata) .def("metadata_size", &torrent_info::metadata_size) .def("map_block", map_block) .def("map_file", &torrent_info::map_file) ; class_<file_entry>("file_entry") .def_readwrite("path", &file_entry::path) .def_readwrite("symlink_path", &file_entry::symlink_path) .def_readwrite("filehash", &file_entry::filehash) .def_readwrite("mtime", &file_entry::mtime) .add_property("pad_file", &get_pad_file) .add_property("executable_attribute", &get_executable_attribute) .add_property("hidden_attribute", &get_hidden_attribute) .add_property("symlink_attribute", &get_symlink_attribute) .add_property("offset", &get_offset) .add_property("size", &get_size) ; class_<announce_entry>("announce_entry", init<std::string const&>()) .def_readwrite("url", &announce_entry::url) .add_property("tier", &get_tier, &set_tier) .add_property("fail_limit", &get_fail_limit, &set_fail_limit) .add_property("fails", &get_fails) .add_property("source", &get_source) .add_property("verified", &get_verified) .add_property("updating", &get_updating) .add_property("start_sent", &get_start_sent) .add_property("complete_sent", &get_complete_sent) .add_property("send_stats", &get_send_stats) .def("reset", &announce_entry::reset) .def("failed", &announce_entry::failed, arg("retry_interval") = 0) .def("can_announce", &announce_entry::can_announce) .def("is_working", &announce_entry::is_working) .def("trim", &announce_entry::trim) ; enum_<announce_entry::tracker_source>("tracker_source") .value("source_torrent", announce_entry::source_torrent) .value("source_client", announce_entry::source_client) .value("source_magnet_link", announce_entry::source_magnet_link) .value("source_tex", announce_entry::source_tex) ; } <|endoftext|>
<commit_before>// Copyright Daniel Wallin 2006. Use, modification and distribution is // subject to 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 <boost/python.hpp> #include <libtorrent/torrent_info.hpp> #include "libtorrent/intrusive_ptr_base.hpp" using namespace boost::python; using namespace libtorrent; namespace { std::vector<announce_entry>::const_iterator begin_trackers(torrent_info& i) { return i.trackers().begin(); } std::vector<announce_entry>::const_iterator end_trackers(torrent_info& i) { return i.trackers().end(); } void add_node(torrent_info& ti, char const* hostname, int port) { ti.add_node(std::make_pair(hostname, port)); } list nodes(torrent_info const& ti) { list result; typedef std::vector<std::pair<std::string, int> > list_type; for (list_type::const_iterator i = ti.nodes().begin(); i != ti.nodes().end(); ++i) { result.append(make_tuple(i->first, i->second)); } return result; } file_storage::iterator begin_files(torrent_info& i) { return i.begin_files(); } file_storage::iterator end_files(torrent_info& i) { return i.end_files(); } //list files(torrent_info const& ti, bool storage) { list files(torrent_info const& ti, bool storage) { list result; typedef std::vector<file_entry> list_type; for (list_type::const_iterator i = ti.begin_files(); i != ti.end_files(); ++i) result.append(*i); return result; } std::string metadata(torrent_info const& ti) { std::string result(ti.metadata().get(), ti.metadata_size()); return result; } torrent_info construct0(std::string path) { return torrent_info(fs::path(path)); } list map_block(torrent_info& ti, int piece, size_type offset, int size) { std::vector<file_slice> p = ti.map_block(piece, offset, size); list result; for (std::vector<file_slice>::iterator i(p.begin()), e(p.end()); i != e; ++i) result.append(*i); return result; } } // namespace unnamed void bind_torrent_info() { return_value_policy<copy_const_reference> copy; class_<file_slice>("file_slice") .def_readwrite("file_index", &file_slice::file_index) .def_readwrite("offset", &file_slice::offset) .def_readwrite("size", &file_slice::size) ; class_<torrent_info, boost::intrusive_ptr<torrent_info> >("torrent_info", no_init) #ifndef TORRENT_NO_DEPRECATE .def(init<entry const&>()) #endif .def(init<sha1_hash const&>()) .def(init<char const*, int>()) .def(init<boost::filesystem::path>()) .def(init<boost::filesystem::wpath>()) .def("add_tracker", &torrent_info::add_tracker, (arg("url"), arg("tier")=0)) .def("add_url_seed", &torrent_info::add_url_seed) .def("name", &torrent_info::name, copy) .def("comment", &torrent_info::comment, copy) .def("creator", &torrent_info::creator, copy) .def("total_size", &torrent_info::total_size) .def("piece_length", &torrent_info::piece_length) .def("num_pieces", &torrent_info::num_pieces) #ifndef TORRENT_NO_DEPRECATE .def("info_hash", &torrent_info::info_hash, copy) #endif .def("hash_for_piece", &torrent_info::hash_for_piece) .def("piece_size", &torrent_info::piece_size) .def("num_files", &torrent_info::num_files, (arg("storage")=false)) .def("file_at", &torrent_info::file_at, return_internal_reference<>()) .def("file_at_offset", &torrent_info::file_at_offset) .def("files", &files, (arg("storage")=false)) .def("priv", &torrent_info::priv) .def("trackers", range(begin_trackers, end_trackers)) .def("creation_date", &torrent_info::creation_date) .def("add_node", &add_node) .def("nodes", &nodes) .def("metadata", &metadata) .def("metadata_size", &torrent_info::metadata_size) .def("map_block", map_block) .def("map_file", &torrent_info::map_file) ; class_<file_entry>("file_entry") .add_property( "path" , make_getter( &file_entry::path, return_value_policy<copy_non_const_reference>() ) ) .def_readonly("offset", &file_entry::offset) .def_readonly("size", &file_entry::size) .def_readonly("file_base", &file_entry::file_base) ; class_<announce_entry>("announce_entry", init<std::string const&>()) .def_readwrite("url", &announce_entry::url) .def_readwrite("tier", &announce_entry::tier) ; } <commit_msg>Add torrent_info.rename_file() to the python bindings<commit_after>// Copyright Daniel Wallin 2006. Use, modification and distribution is // subject to 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 <boost/python.hpp> #include <libtorrent/torrent_info.hpp> #include "libtorrent/intrusive_ptr_base.hpp" using namespace boost::python; using namespace libtorrent; namespace { std::vector<announce_entry>::const_iterator begin_trackers(torrent_info& i) { return i.trackers().begin(); } std::vector<announce_entry>::const_iterator end_trackers(torrent_info& i) { return i.trackers().end(); } void add_node(torrent_info& ti, char const* hostname, int port) { ti.add_node(std::make_pair(hostname, port)); } list nodes(torrent_info const& ti) { list result; typedef std::vector<std::pair<std::string, int> > list_type; for (list_type::const_iterator i = ti.nodes().begin(); i != ti.nodes().end(); ++i) { result.append(make_tuple(i->first, i->second)); } return result; } file_storage::iterator begin_files(torrent_info& i) { return i.begin_files(); } file_storage::iterator end_files(torrent_info& i) { return i.end_files(); } //list files(torrent_info const& ti, bool storage) { list files(torrent_info const& ti, bool storage) { list result; typedef std::vector<file_entry> list_type; for (list_type::const_iterator i = ti.begin_files(); i != ti.end_files(); ++i) result.append(*i); return result; } std::string metadata(torrent_info const& ti) { std::string result(ti.metadata().get(), ti.metadata_size()); return result; } torrent_info construct0(std::string path) { return torrent_info(fs::path(path)); } list map_block(torrent_info& ti, int piece, size_type offset, int size) { std::vector<file_slice> p = ti.map_block(piece, offset, size); list result; for (std::vector<file_slice>::iterator i(p.begin()), e(p.end()); i != e; ++i) result.append(*i); return result; } } // namespace unnamed void bind_torrent_info() { return_value_policy<copy_const_reference> copy; class_<file_slice>("file_slice") .def_readwrite("file_index", &file_slice::file_index) .def_readwrite("offset", &file_slice::offset) .def_readwrite("size", &file_slice::size) ; class_<torrent_info, boost::intrusive_ptr<torrent_info> >("torrent_info", no_init) #ifndef TORRENT_NO_DEPRECATE .def(init<entry const&>()) #endif .def(init<sha1_hash const&>()) .def(init<char const*, int>()) .def(init<boost::filesystem::path>()) .def(init<boost::filesystem::wpath>()) .def("add_tracker", &torrent_info::add_tracker, (arg("url"), arg("tier")=0)) .def("add_url_seed", &torrent_info::add_url_seed) .def("name", &torrent_info::name, copy) .def("comment", &torrent_info::comment, copy) .def("creator", &torrent_info::creator, copy) .def("total_size", &torrent_info::total_size) .def("piece_length", &torrent_info::piece_length) .def("num_pieces", &torrent_info::num_pieces) #ifndef TORRENT_NO_DEPRECATE .def("info_hash", &torrent_info::info_hash, copy) #endif .def("hash_for_piece", &torrent_info::hash_for_piece) .def("piece_size", &torrent_info::piece_size) .def("num_files", &torrent_info::num_files, (arg("storage")=false)) .def("file_at", &torrent_info::file_at, return_internal_reference<>()) .def("file_at_offset", &torrent_info::file_at_offset) .def("files", &files, (arg("storage")=false)) .def("rename_file", &torrent_info::rename_file) .def("priv", &torrent_info::priv) .def("trackers", range(begin_trackers, end_trackers)) .def("creation_date", &torrent_info::creation_date) .def("add_node", &add_node) .def("nodes", &nodes) .def("metadata", &metadata) .def("metadata_size", &torrent_info::metadata_size) .def("map_block", map_block) .def("map_file", &torrent_info::map_file) ; class_<file_entry>("file_entry") .add_property( "path" , make_getter( &file_entry::path, return_value_policy<copy_non_const_reference>() ) ) .def_readonly("offset", &file_entry::offset) .def_readonly("size", &file_entry::size) .def_readonly("file_base", &file_entry::file_base) ; class_<announce_entry>("announce_entry", init<std::string const&>()) .def_readwrite("url", &announce_entry::url) .def_readwrite("tier", &announce_entry::tier) ; } <|endoftext|>
<commit_before>#include <iostream> #include <algorithm> #include <cmath> #include <iomanip> #include <vector> using namespace std; struct reg { int Y; double R; bool operator <(const reg& right) const { return Y < right.Y; } reg(int y, double r) { Y = y; R = r; } }; int main() { int N, M; cin >> N >> M; vector<reg> V[110]; int x, y; double r; for (int i=0; i<M; i++) { cin >> x >> y >> r; x--; y--; reg temp = reg(y, r); vector<reg>::iterator itr = V[x].begin(); for (; itr != V[x].end(); itr++) { if ((*itr).Y == y) break; } if (itr != V[x].end()) { V[x].push_back(temp); } else { double rr = (*itr).R; (*itr).R = r * rr / (r + rr); } } bool next = true; while (next) { next = false; for (int i=0; i<N; i++) { for (unsigned int j=0; j<V[i].size(); j++) { int y = V[i][j].Y; if (!V[y].empty()) { next = true; int ny = V[y][0].Y; reg temp = reg(ny, V[i][j].R + V[y][0].R); } } } } cout << fixed << setprecision(2) << round(S[0][N-1] * 100)/100 << endl; } <commit_msg>方針が間違っている<commit_after>// http://poj.org/problem?id=3532 // 合成公式:直列で R_1 + R_2 、 並列で R_1 R_2 / (R_1 + R_2) を使おうと思っていた。 // しかし、この方針では絶対解けないことがわかった。以下のプログラムは不正解です。 /* たとえば 4 6 1 2 1 1 3 1 1 4 1 2 3 1 2 4 1 4 3 1 という入力では失敗する。どの区間でも合成できない。 予備校の東大物理の講義で「合成の公式は覚えておく必要もないし、合成する必要もない」と言われた。私も、東大入試を解くときに合成公式を使ったことはない。 その教訓が7年めぐってきて私に襲いかかった。 これは電位の関係式と電流保存の関係式を立てて、連立1次方程式を解くしかなさそうですね…… */ #include <iostream> #include <algorithm> #include <cmath> #include <iomanip> #include <vector> #include <queue> using namespace std; struct reg { int Y; double R; /* bool operator <(const reg& right) const { return Y < right.Y; } */ reg(int y, double r) { Y = y; R = r; } }; struct pass { int X; double R; bool used; pass(int x, double r) { X = x; R = r; used = false; } }; int main() { int N, M; cin >> N >> M; vector<reg> V[110]; vector<pass> W[110]; int x, y; double r; for (int i=0; i<M; i++) { cin >> x >> y >> r; x--; y--; if (x > y) { swap(x, y); } W[y].push_back(pass(x, r)); } bool visited[110]; fill(visited, visited+N, false); queue<int> Q; Q.push(N-1); while (!Q.empty()) { int v = Q.front(); Q.pop(); if (!visited[v]) { visited[v] = true; for (unsigned int i=0; i<W[v].size(); i++) { int w = W[v][i].X; if (!visited[w]) { Q.push(w); } } } } for (int i=0; i<N; i++) { if (!visited[i]) { W[i].clear(); } else { int y = i; for (unsigned int j=0; j<W[i].size(); j++) { int x = W[i][j].X; int r = W[i][j].R; reg temp = reg(y, r); vector<reg>::iterator itr = V[x].begin(); for (; itr != V[x].end(); itr++) { if ((*itr).Y == y) break; } if (itr == V[x].end()) { V[x].push_back(temp); } else { double rr = (*itr).R; (*itr).R = r * rr / (r + rr); } } } } bool next = true; while (next) { next = false; for (int i=0; i<N; i++) { for (unsigned int j=0; j<V[i].size(); j++) { int y = V[i][j].Y; if (V[y].size() == 1) { next = true; int ny = V[y][0].Y; double nr = V[i][j].R + V[y][0].R; // cerr << "nr = " << nr << ", V[y][0].R = " << V[y][0].R << endl; cerr << i << " - " << y << " - " << ny << endl; reg temp = reg(ny, nr); V[i].erase(V[i].begin()+j); V[y].erase(V[y].begin()); vector<reg>::iterator itr = V[i].begin(); for ( ; itr != V[i].end(); itr++) { if ((*itr).Y == ny) break; } if (itr == V[i].end()) { V[i].push_back(temp); cerr << "reg = " << temp.R << endl; } else { cerr << "merged" << endl; double rr = (*itr).R; (*itr).R = nr * rr / (nr + rr); cerr << "reg = " << (*itr).R << endl; } goto EXIT; } } } EXIT: continue; } for (unsigned i=0; i<V[0].size(); i++) { if (V[0][i].Y == N-1) { cout << fixed << setprecision(2) << round(V[0][i].R * 100)/100 << endl; return 0; } } return 1; } <|endoftext|>
<commit_before>#include "Pic.h" static const u16 PIC1 = 0x20; static const u16 PIC2 = 0xA0; static const u16 PIC1_COMMAND = PIC1; static const u16 PIC1_DATA = PIC1+1; static const u16 PIC2_COMMAND = PIC2; static const u16 PIC2_DATA = PIC2+1; Pic::Pic() { //see http://web.archive.org/web/20041023230527/http://users.win.be/W0005997/GI/pic.html const u8 ICW1_ICW4 = 0x01; //const u8 ICW1_SINGLE = 0x02; //const u8 ICW1_LEVEL = 0x08; const u8 ICW1_INIT = 0x10; const u8 ICW4_8086 = 0x01; //const u8 ICW4_AUTO = 0x02; //ICW1 const u8 ICW1 = ICW1_INIT | ICW1_ICW4; outb(PIC1_COMMAND, ICW1); outb(PIC2_COMMAND, ICW1); const u8 OFFSET1 = 0x20; const u8 OFFSET2 = 0x28; //ICW2 outb(PIC1_DATA, OFFSET1); outb(PIC2_DATA, OFFSET2); //ICW3 outb(PIC1_DATA, 0x4); outb(PIC2_DATA, 0x2); //ICW4 const u8 ICW4 = ICW4_8086; outb(PIC1_DATA, ICW4); outb(PIC2_DATA, ICW4); setMask(0xFFFF); } void Pic::endOfInterrupt(u8 irq) { const u8 PIC_EOI = 0x20; if(irq >= 8) { outb(PIC2_COMMAND, PIC_EOI); } outb(PIC1_COMMAND, PIC_EOI); } u16 Pic::getMask() { return _mask; } void Pic::setMask(u16 mask) { _mask = mask; outb(PIC1_DATA, _mask&0x00FF); outb(PIC2_DATA, _mask&0xFF00 >> 8); } void Pic::activate(u8 irq) { setMask(getMask() & ~(1<<irq)); } void Pic::desactivate(u8 irq) { setMask(getMask() | (1<<irq)); } Pic pic; <commit_msg>Fix stupid old bug because of fucking bitwise operator precedence<commit_after>#include "Pic.h" static const u16 PIC1 = 0x20; static const u16 PIC2 = 0xA0; static const u16 PIC1_COMMAND = PIC1; static const u16 PIC1_DATA = PIC1+1; static const u16 PIC2_COMMAND = PIC2; static const u16 PIC2_DATA = PIC2+1; Pic::Pic() { //see http://web.archive.org/web/20041023230527/http://users.win.be/W0005997/GI/pic.html const u8 ICW1_ICW4 = 0x01; //const u8 ICW1_SINGLE = 0x02; //const u8 ICW1_LEVEL = 0x08; const u8 ICW1_INIT = 0x10; const u8 ICW4_8086 = 0x01; //const u8 ICW4_AUTO = 0x02; //ICW1 const u8 ICW1 = ICW1_INIT | ICW1_ICW4; outb(PIC1_COMMAND, ICW1); outb(PIC2_COMMAND, ICW1); const u8 OFFSET1 = 0x20; const u8 OFFSET2 = 0x28; //ICW2 outb(PIC1_DATA, OFFSET1); outb(PIC2_DATA, OFFSET2); //ICW3 outb(PIC1_DATA, 0x4); outb(PIC2_DATA, 0x2); //ICW4 const u8 ICW4 = ICW4_8086; outb(PIC1_DATA, ICW4); outb(PIC2_DATA, ICW4); setMask(0xFFFF); } void Pic::endOfInterrupt(u8 irq) { const u8 PIC_EOI = 0x20; if(irq >= 8) { outb(PIC2_COMMAND, PIC_EOI); } outb(PIC1_COMMAND, PIC_EOI); } u16 Pic::getMask() { return _mask; } void Pic::setMask(u16 mask) { _mask = mask; outb(PIC1_DATA, _mask&0x00FF); outb(PIC2_DATA, (_mask&0xFF00) >> 8); } void Pic::activate(u8 irq) { setMask(getMask() & ~(1<<irq)); } void Pic::desactivate(u8 irq) { setMask(getMask() | (1<<irq)); } Pic pic; <|endoftext|>
<commit_before>#include <iostream> using std::cin; using std::cout; using std::endl; int registers[10]; int ram[1000]; int ip = 0; bool runNextInstruction() { int instruction = ram[ip]; if (instruction == 100) return false; else { int o1 = instruction / 10 % 10; int o2 = instruction % 10; switch (instruction / 100) { case 2: registers[o1] = o2; break; case 3: registers[o1] = (registers[o1] + o2) % 1000; break; case 4: registers[o1] = (registers[o1] * o2) % 1000; break; case 5: registers[o1] = registers[o2]; break; case 6: registers[o1] = (registers[o1] + registers[o2]) % 1000; break; case 7: registers[o1] = (registers[o1] * registers[o2]) % 1000; break; case 8: registers[o1] = ram[registers[o2]]; break; case 9: ram[registers[o2]] = registers[o1]; break; case 0: if (registers[o2] != 0) ip = registers[o1] - 1; break; } ip++; return true; } } int main() { int testcases; cin >> testcases; cin.ignore(); char line[10]; cin.getline(line, 9); // skip the blank line for (int testcase = 0; testcase < testcases; testcase++) { int addr = 0; while ((cin.getline(line, 9)) && line[0] != '\0') { ram[addr++] = (line[0] - '0') * 100 + (line[1] - '0') * 10 + (line[2] - '0'); } while (addr < 1000) ram[addr++] = 0; ip = 0; int numInstructions = 1; while (runNextInstruction()) numInstructions++; cout << numInstructions << endl; } return 0; }<commit_msg>Accepted. I found the problem: missing new line, and not resetting registers.<commit_after>#include <iostream> using std::cin; using std::cout; using std::endl; int registers[10]; int ram[1000]; int ip = 0; bool runNextInstruction() { int instruction = ram[ip]; if (instruction == 100) return false; else { int o1 = instruction / 10 % 10; int o2 = instruction % 10; switch (instruction / 100) { case 2: registers[o1] = o2; break; case 3: registers[o1] = (registers[o1] + o2) % 1000; break; case 4: registers[o1] = (registers[o1] * o2) % 1000; break; case 5: registers[o1] = registers[o2]; break; case 6: registers[o1] = (registers[o1] + registers[o2]) % 1000; break; case 7: registers[o1] = (registers[o1] * registers[o2]) % 1000; break; case 8: registers[o1] = ram[registers[o2]]; break; case 9: ram[registers[o2]] = registers[o1]; break; case 0: if (registers[o2] != 0) ip = registers[o1] - 1; break; } ip++; return true; } } int main() { int testcases; cin >> testcases; cin.ignore(); char line[10]; cin.getline(line, 9); // skip the blank line for (int testcase = 0; testcase < testcases; testcase++) { int addr = 0; while (addr < 1000 && (cin.getline(line, 9)) && line[0] != '\0') { ram[addr++] = (line[0] - '0') * 100 + (line[1] - '0') * 10 + (line[2] - '0'); } while (addr < 1000) ram[addr++] = 0; for (int i = 0; i < 10; i++) registers[i] = 0; ip = 0; int numInstructions = 1; while (runNextInstruction()) numInstructions++; if (testcase > 0) cout << endl; cout << numInstructions << endl; } return 0; }<|endoftext|>
<commit_before>//===- DataStructureAA.cpp - Data Structure Based Alias Analysis ----------===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This pass uses the top-down data structure graphs to implement a simple // context sensitive alias analysis. // //===----------------------------------------------------------------------===// #include "llvm/Constants.h" #include "llvm/DerivedTypes.h" #include "llvm/Module.h" #include "llvm/Analysis/AliasAnalysis.h" #include "llvm/Analysis/Passes.h" #include "llvm/Analysis/DataStructure/DataStructure.h" #include "llvm/Analysis/DataStructure/DSGraph.h" using namespace llvm; namespace { class DSAA : public ModulePass, public AliasAnalysis { TDDataStructures *TD; BUDataStructures *BU; // These members are used to cache mod/ref information to make us return // results faster, particularly for aa-eval. On the first request of // mod/ref information for a particular call site, we compute and store the // calculated nodemap for the call site. Any time DSA info is updated we // free this information, and when we move onto a new call site, this // information is also freed. CallSite MapCS; std::multimap<DSNode*, const DSNode*> CallerCalleeMap; public: DSAA() : TD(0) {} ~DSAA() { InvalidateCache(); } void InvalidateCache() { MapCS = CallSite(); CallerCalleeMap.clear(); } //------------------------------------------------ // Implement the Pass API // // run - Build up the result graph, representing the pointer graph for the // program. // bool runOnModule(Module &M) { InitializeAliasAnalysis(this); TD = &getAnalysis<TDDataStructures>(); BU = &getAnalysis<BUDataStructures>(); return false; } virtual void getAnalysisUsage(AnalysisUsage &AU) const { AliasAnalysis::getAnalysisUsage(AU); AU.setPreservesAll(); // Does not transform code AU.addRequiredTransitive<TDDataStructures>(); // Uses TD Datastructures AU.addRequiredTransitive<BUDataStructures>(); // Uses BU Datastructures } //------------------------------------------------ // Implement the AliasAnalysis API // AliasResult alias(const Value *V1, unsigned V1Size, const Value *V2, unsigned V2Size); ModRefResult getModRefInfo(CallSite CS, Value *P, unsigned Size); ModRefResult getModRefInfo(CallSite CS1, CallSite CS2) { return AliasAnalysis::getModRefInfo(CS1,CS2); } virtual void deleteValue(Value *V) { InvalidateCache(); BU->deleteValue(V); TD->deleteValue(V); } virtual void copyValue(Value *From, Value *To) { if (From == To) return; InvalidateCache(); BU->copyValue(From, To); TD->copyValue(From, To); } private: DSGraph *getGraphForValue(const Value *V); }; // Register the pass... RegisterOpt<DSAA> X("ds-aa", "Data Structure Graph Based Alias Analysis"); // Register as an implementation of AliasAnalysis RegisterAnalysisGroup<AliasAnalysis, DSAA> Y; } ModulePass *llvm::createDSAAPass() { return new DSAA(); } // getGraphForValue - Return the DSGraph to use for queries about the specified // value... // DSGraph *DSAA::getGraphForValue(const Value *V) { if (const Instruction *I = dyn_cast<Instruction>(V)) return &TD->getDSGraph(*I->getParent()->getParent()); else if (const Argument *A = dyn_cast<Argument>(V)) return &TD->getDSGraph(*A->getParent()); else if (const BasicBlock *BB = dyn_cast<BasicBlock>(V)) return &TD->getDSGraph(*BB->getParent()); return 0; } AliasAnalysis::AliasResult DSAA::alias(const Value *V1, unsigned V1Size, const Value *V2, unsigned V2Size) { if (V1 == V2) return MustAlias; DSGraph *G1 = getGraphForValue(V1); DSGraph *G2 = getGraphForValue(V2); assert((!G1 || !G2 || G1 == G2) && "Alias query for 2 different functions?"); // Get the graph to use... DSGraph &G = *(G1 ? G1 : (G2 ? G2 : &TD->getGlobalsGraph())); const DSGraph::ScalarMapTy &GSM = G.getScalarMap(); DSGraph::ScalarMapTy::const_iterator I = GSM.find((Value*)V1); if (I == GSM.end()) return NoAlias; DSGraph::ScalarMapTy::const_iterator J = GSM.find((Value*)V2); if (J == GSM.end()) return NoAlias; DSNode *N1 = I->second.getNode(), *N2 = J->second.getNode(); unsigned O1 = I->second.getOffset(), O2 = J->second.getOffset(); if (N1 == 0 || N2 == 0) return MayAlias; // Can't tell whether anything aliases null. // We can only make a judgment of one of the nodes is complete... if (N1->isComplete() || N2->isComplete()) { if (N1 != N2) return NoAlias; // Completely different nodes. // See if they point to different offsets... if so, we may be able to // determine that they do not alias... if (O1 != O2) { if (O2 < O1) { // Ensure that O1 <= O2 std::swap(V1, V2); std::swap(O1, O2); std::swap(V1Size, V2Size); } if (O1+V1Size <= O2) return NoAlias; } } // FIXME: we could improve on this by checking the globals graph for aliased // global queries... return AliasAnalysis::alias(V1, V1Size, V2, V2Size); } /// getModRefInfo - does a callsite modify or reference a value? /// AliasAnalysis::ModRefResult DSAA::getModRefInfo(CallSite CS, Value *P, unsigned Size) { DSNode *N = 0; // First step, check our cache. if (CS.getInstruction() == MapCS.getInstruction()) { { const Function *Caller = CS.getInstruction()->getParent()->getParent(); DSGraph &CallerTDGraph = TD->getDSGraph(*Caller); // Figure out which node in the TD graph this pointer corresponds to. DSScalarMap &CallerSM = CallerTDGraph.getScalarMap(); DSScalarMap::iterator NI = CallerSM.find(P); if (NI == CallerSM.end()) { InvalidateCache(); return DSAA::getModRefInfo(CS, P, Size); } N = NI->second.getNode(); } HaveMappingInfo: assert(N && "Null pointer in scalar map??"); typedef std::multimap<DSNode*, const DSNode*>::iterator NodeMapIt; std::pair<NodeMapIt, NodeMapIt> Range = CallerCalleeMap.equal_range(N); // Loop over all of the nodes in the callee that correspond to "N", keeping // track of aggregate mod/ref info. bool NeverReads = true, NeverWrites = true; for (; Range.first != Range.second; ++Range.first) { if (Range.first->second->isModified()) NeverWrites = false; if (Range.first->second->isRead()) NeverReads = false; if (NeverReads == false && NeverWrites == false) return AliasAnalysis::getModRefInfo(CS, P, Size); } ModRefResult Result = ModRef; if (NeverWrites) // We proved it was not modified. Result = ModRefResult(Result & ~Mod); if (NeverReads) // We proved it was not read. Result = ModRefResult(Result & ~Ref); return ModRefResult(Result & AliasAnalysis::getModRefInfo(CS, P, Size)); } // Any cached info we have is for the wrong function. InvalidateCache(); Function *F = CS.getCalledFunction(); if (!F) return AliasAnalysis::getModRefInfo(CS, P, Size); if (F->isExternal()) { // If we are calling an external function, and if this global doesn't escape // the portion of the program we have analyzed, we can draw conclusions // based on whether the global escapes the program. Function *Caller = CS.getInstruction()->getParent()->getParent(); DSGraph *G = &TD->getDSGraph(*Caller); DSScalarMap::iterator NI = G->getScalarMap().find(P); if (NI == G->getScalarMap().end()) { // If it wasn't in the local function graph, check the global graph. This // can occur for globals who are locally reference but hoisted out to the // globals graph despite that. G = G->getGlobalsGraph(); NI = G->getScalarMap().find(P); if (NI == G->getScalarMap().end()) return AliasAnalysis::getModRefInfo(CS, P, Size); } // If we found a node and it's complete, it cannot be passed out to the // called function. if (NI->second.getNode()->isComplete()) return NoModRef; return AliasAnalysis::getModRefInfo(CS, P, Size); } // Get the graphs for the callee and caller. Note that we want the BU graph // for the callee because we don't want all caller's effects incorporated! const Function *Caller = CS.getInstruction()->getParent()->getParent(); DSGraph &CallerTDGraph = TD->getDSGraph(*Caller); DSGraph &CalleeBUGraph = BU->getDSGraph(*F); // Figure out which node in the TD graph this pointer corresponds to. DSScalarMap &CallerSM = CallerTDGraph.getScalarMap(); DSScalarMap::iterator NI = CallerSM.find(P); if (NI == CallerSM.end()) { ModRefResult Result = ModRef; if (isa<ConstantPointerNull>(P) || isa<UndefValue>(P)) return NoModRef; // null is never modified :) else { assert(isa<GlobalVariable>(P) && cast<GlobalVariable>(P)->getType()->getElementType()->isFirstClassType() && "This isn't a global that DSA inconsiderately dropped " "from the graph?"); DSGraph &GG = *CallerTDGraph.getGlobalsGraph(); DSScalarMap::iterator NI = GG.getScalarMap().find(P); if (NI != GG.getScalarMap().end() && !NI->second.isNull()) { // Otherwise, if the node is only M or R, return this. This can be // useful for globals that should be marked const but are not. DSNode *N = NI->second.getNode(); if (!N->isModified()) Result = (ModRefResult)(Result & ~Mod); if (!N->isRead()) Result = (ModRefResult)(Result & ~Ref); } } if (Result == NoModRef) return Result; return ModRefResult(Result & AliasAnalysis::getModRefInfo(CS, P, Size)); } // Compute the mapping from nodes in the callee graph to the nodes in the // caller graph for this call site. DSGraph::NodeMapTy CalleeCallerMap; DSCallSite DSCS = CallerTDGraph.getDSCallSiteForCallSite(CS); CallerTDGraph.computeCalleeCallerMapping(DSCS, *F, CalleeBUGraph, CalleeCallerMap); // Remember the mapping and the call site for future queries. MapCS = CS; // Invert the mapping into CalleeCallerInvMap. for (DSGraph::NodeMapTy::iterator I = CalleeCallerMap.begin(), E = CalleeCallerMap.end(); I != E; ++I) CallerCalleeMap.insert(std::make_pair(I->second.getNode(), I->first)); N = NI->second.getNode(); goto HaveMappingInfo; } <commit_msg>Don't give up completely, maybe other AA can say something about this.<commit_after>//===- DataStructureAA.cpp - Data Structure Based Alias Analysis ----------===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This pass uses the top-down data structure graphs to implement a simple // context sensitive alias analysis. // //===----------------------------------------------------------------------===// #include "llvm/Constants.h" #include "llvm/DerivedTypes.h" #include "llvm/Module.h" #include "llvm/Analysis/AliasAnalysis.h" #include "llvm/Analysis/Passes.h" #include "llvm/Analysis/DataStructure/DataStructure.h" #include "llvm/Analysis/DataStructure/DSGraph.h" using namespace llvm; namespace { class DSAA : public ModulePass, public AliasAnalysis { TDDataStructures *TD; BUDataStructures *BU; // These members are used to cache mod/ref information to make us return // results faster, particularly for aa-eval. On the first request of // mod/ref information for a particular call site, we compute and store the // calculated nodemap for the call site. Any time DSA info is updated we // free this information, and when we move onto a new call site, this // information is also freed. CallSite MapCS; std::multimap<DSNode*, const DSNode*> CallerCalleeMap; public: DSAA() : TD(0) {} ~DSAA() { InvalidateCache(); } void InvalidateCache() { MapCS = CallSite(); CallerCalleeMap.clear(); } //------------------------------------------------ // Implement the Pass API // // run - Build up the result graph, representing the pointer graph for the // program. // bool runOnModule(Module &M) { InitializeAliasAnalysis(this); TD = &getAnalysis<TDDataStructures>(); BU = &getAnalysis<BUDataStructures>(); return false; } virtual void getAnalysisUsage(AnalysisUsage &AU) const { AliasAnalysis::getAnalysisUsage(AU); AU.setPreservesAll(); // Does not transform code AU.addRequiredTransitive<TDDataStructures>(); // Uses TD Datastructures AU.addRequiredTransitive<BUDataStructures>(); // Uses BU Datastructures } //------------------------------------------------ // Implement the AliasAnalysis API // AliasResult alias(const Value *V1, unsigned V1Size, const Value *V2, unsigned V2Size); ModRefResult getModRefInfo(CallSite CS, Value *P, unsigned Size); ModRefResult getModRefInfo(CallSite CS1, CallSite CS2) { return AliasAnalysis::getModRefInfo(CS1,CS2); } virtual void deleteValue(Value *V) { InvalidateCache(); BU->deleteValue(V); TD->deleteValue(V); } virtual void copyValue(Value *From, Value *To) { if (From == To) return; InvalidateCache(); BU->copyValue(From, To); TD->copyValue(From, To); } private: DSGraph *getGraphForValue(const Value *V); }; // Register the pass... RegisterOpt<DSAA> X("ds-aa", "Data Structure Graph Based Alias Analysis"); // Register as an implementation of AliasAnalysis RegisterAnalysisGroup<AliasAnalysis, DSAA> Y; } ModulePass *llvm::createDSAAPass() { return new DSAA(); } // getGraphForValue - Return the DSGraph to use for queries about the specified // value... // DSGraph *DSAA::getGraphForValue(const Value *V) { if (const Instruction *I = dyn_cast<Instruction>(V)) return &TD->getDSGraph(*I->getParent()->getParent()); else if (const Argument *A = dyn_cast<Argument>(V)) return &TD->getDSGraph(*A->getParent()); else if (const BasicBlock *BB = dyn_cast<BasicBlock>(V)) return &TD->getDSGraph(*BB->getParent()); return 0; } AliasAnalysis::AliasResult DSAA::alias(const Value *V1, unsigned V1Size, const Value *V2, unsigned V2Size) { if (V1 == V2) return MustAlias; DSGraph *G1 = getGraphForValue(V1); DSGraph *G2 = getGraphForValue(V2); assert((!G1 || !G2 || G1 == G2) && "Alias query for 2 different functions?"); // Get the graph to use... DSGraph &G = *(G1 ? G1 : (G2 ? G2 : &TD->getGlobalsGraph())); const DSGraph::ScalarMapTy &GSM = G.getScalarMap(); DSGraph::ScalarMapTy::const_iterator I = GSM.find((Value*)V1); if (I == GSM.end()) return NoAlias; DSGraph::ScalarMapTy::const_iterator J = GSM.find((Value*)V2); if (J == GSM.end()) return NoAlias; DSNode *N1 = I->second.getNode(), *N2 = J->second.getNode(); unsigned O1 = I->second.getOffset(), O2 = J->second.getOffset(); if (N1 == 0 || N2 == 0) // Can't tell whether anything aliases null. return AliasAnalysis::alias(V1, V1Size, V2, V2Size); // We can only make a judgment of one of the nodes is complete... if (N1->isComplete() || N2->isComplete()) { if (N1 != N2) return NoAlias; // Completely different nodes. // See if they point to different offsets... if so, we may be able to // determine that they do not alias... if (O1 != O2) { if (O2 < O1) { // Ensure that O1 <= O2 std::swap(V1, V2); std::swap(O1, O2); std::swap(V1Size, V2Size); } if (O1+V1Size <= O2) return NoAlias; } } // FIXME: we could improve on this by checking the globals graph for aliased // global queries... return AliasAnalysis::alias(V1, V1Size, V2, V2Size); } /// getModRefInfo - does a callsite modify or reference a value? /// AliasAnalysis::ModRefResult DSAA::getModRefInfo(CallSite CS, Value *P, unsigned Size) { DSNode *N = 0; // First step, check our cache. if (CS.getInstruction() == MapCS.getInstruction()) { { const Function *Caller = CS.getInstruction()->getParent()->getParent(); DSGraph &CallerTDGraph = TD->getDSGraph(*Caller); // Figure out which node in the TD graph this pointer corresponds to. DSScalarMap &CallerSM = CallerTDGraph.getScalarMap(); DSScalarMap::iterator NI = CallerSM.find(P); if (NI == CallerSM.end()) { InvalidateCache(); return DSAA::getModRefInfo(CS, P, Size); } N = NI->second.getNode(); } HaveMappingInfo: assert(N && "Null pointer in scalar map??"); typedef std::multimap<DSNode*, const DSNode*>::iterator NodeMapIt; std::pair<NodeMapIt, NodeMapIt> Range = CallerCalleeMap.equal_range(N); // Loop over all of the nodes in the callee that correspond to "N", keeping // track of aggregate mod/ref info. bool NeverReads = true, NeverWrites = true; for (; Range.first != Range.second; ++Range.first) { if (Range.first->second->isModified()) NeverWrites = false; if (Range.first->second->isRead()) NeverReads = false; if (NeverReads == false && NeverWrites == false) return AliasAnalysis::getModRefInfo(CS, P, Size); } ModRefResult Result = ModRef; if (NeverWrites) // We proved it was not modified. Result = ModRefResult(Result & ~Mod); if (NeverReads) // We proved it was not read. Result = ModRefResult(Result & ~Ref); return ModRefResult(Result & AliasAnalysis::getModRefInfo(CS, P, Size)); } // Any cached info we have is for the wrong function. InvalidateCache(); Function *F = CS.getCalledFunction(); if (!F) return AliasAnalysis::getModRefInfo(CS, P, Size); if (F->isExternal()) { // If we are calling an external function, and if this global doesn't escape // the portion of the program we have analyzed, we can draw conclusions // based on whether the global escapes the program. Function *Caller = CS.getInstruction()->getParent()->getParent(); DSGraph *G = &TD->getDSGraph(*Caller); DSScalarMap::iterator NI = G->getScalarMap().find(P); if (NI == G->getScalarMap().end()) { // If it wasn't in the local function graph, check the global graph. This // can occur for globals who are locally reference but hoisted out to the // globals graph despite that. G = G->getGlobalsGraph(); NI = G->getScalarMap().find(P); if (NI == G->getScalarMap().end()) return AliasAnalysis::getModRefInfo(CS, P, Size); } // If we found a node and it's complete, it cannot be passed out to the // called function. if (NI->second.getNode()->isComplete()) return NoModRef; return AliasAnalysis::getModRefInfo(CS, P, Size); } // Get the graphs for the callee and caller. Note that we want the BU graph // for the callee because we don't want all caller's effects incorporated! const Function *Caller = CS.getInstruction()->getParent()->getParent(); DSGraph &CallerTDGraph = TD->getDSGraph(*Caller); DSGraph &CalleeBUGraph = BU->getDSGraph(*F); // Figure out which node in the TD graph this pointer corresponds to. DSScalarMap &CallerSM = CallerTDGraph.getScalarMap(); DSScalarMap::iterator NI = CallerSM.find(P); if (NI == CallerSM.end()) { ModRefResult Result = ModRef; if (isa<ConstantPointerNull>(P) || isa<UndefValue>(P)) return NoModRef; // null is never modified :) else { assert(isa<GlobalVariable>(P) && cast<GlobalVariable>(P)->getType()->getElementType()->isFirstClassType() && "This isn't a global that DSA inconsiderately dropped " "from the graph?"); DSGraph &GG = *CallerTDGraph.getGlobalsGraph(); DSScalarMap::iterator NI = GG.getScalarMap().find(P); if (NI != GG.getScalarMap().end() && !NI->second.isNull()) { // Otherwise, if the node is only M or R, return this. This can be // useful for globals that should be marked const but are not. DSNode *N = NI->second.getNode(); if (!N->isModified()) Result = (ModRefResult)(Result & ~Mod); if (!N->isRead()) Result = (ModRefResult)(Result & ~Ref); } } if (Result == NoModRef) return Result; return ModRefResult(Result & AliasAnalysis::getModRefInfo(CS, P, Size)); } // Compute the mapping from nodes in the callee graph to the nodes in the // caller graph for this call site. DSGraph::NodeMapTy CalleeCallerMap; DSCallSite DSCS = CallerTDGraph.getDSCallSiteForCallSite(CS); CallerTDGraph.computeCalleeCallerMapping(DSCS, *F, CalleeBUGraph, CalleeCallerMap); // Remember the mapping and the call site for future queries. MapCS = CS; // Invert the mapping into CalleeCallerInvMap. for (DSGraph::NodeMapTy::iterator I = CalleeCallerMap.begin(), E = CalleeCallerMap.end(); I != E; ++I) CallerCalleeMap.insert(std::make_pair(I->second.getNode(), I->first)); N = NI->second.getNode(); goto HaveMappingInfo; } <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2016 ArangoDB GmbH, Cologne, Germany /// /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. /// You may obtain a copy of the License at /// /// http://www.apache.org/licenses/LICENSE-2.0 /// /// Unless required by applicable law or agreed to in writing, software /// distributed under the License is distributed on an "AS IS" BASIS, /// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. /// See the License for the specific language governing permissions and /// limitations under the License. /// /// Copyright holder is ArangoDB GmbH, Cologne, Germany /// /// @author Jan Steemann //////////////////////////////////////////////////////////////////////////////// #include "MaxMapCountFeature.h" #include "ApplicationFeatures/ApplicationServer.h" #include "Basics/process-utils.h" #include "Basics/FileUtils.h" #include "Basics/Mutex.h" #include "Basics/MutexLocker.h" #include "Basics/StringBuffer.h" #include "Basics/StringUtils.h" #include "Basics/Thread.h" #include "Logger/Logger.h" #include "ProgramOptions/ProgramOptions.h" #include "ProgramOptions/Section.h" #include <algorithm> using namespace arangodb; using namespace arangodb::basics; using namespace arangodb::options; namespace { static bool checkMaxMappings = arangodb::MaxMapCountFeature::needsChecking(); static uint64_t maxMappings = UINT64_MAX; static std::string mapsFilename; static StringBuffer fileBuffer(8192, false); // cache for the current number of mappings for this process // (read from /proc/<pid>/maps static Mutex mutex; static double lastStamp = 0.0; static bool lastValue = false; static bool checkInFlight = false; static constexpr double cacheLifetime = 7.5; static double lastLogStamp = 0.0; static constexpr double logFrequency = 10.0; } MaxMapCountFeature::MaxMapCountFeature( application_features::ApplicationServer* server) : ApplicationFeature(server, "MaxMapCount") { setOptional(false); requiresElevatedPrivileges(false); maxMappings = UINT64_MAX; mapsFilename.clear(); lastStamp = 0.0; lastValue = false; checkInFlight = false; lastLogStamp = 0.0; } MaxMapCountFeature::~MaxMapCountFeature() { // reset values maxMappings = UINT64_MAX; mapsFilename.clear(); lastStamp = 0.0; lastValue = false; checkInFlight = false; lastLogStamp = 0.0; } void MaxMapCountFeature::collectOptions(std::shared_ptr<options::ProgramOptions> options) { options->addSection("server", "Server Options"); if (needsChecking()) { options->addHiddenOption("--server.check-max-memory-mappings, mappings", "check the maximum number of memory mappings at runtime", new BooleanParameter(&checkMaxMappings)); } else { options->addObsoleteOption("--server.check-max-memory-mappings", "check the maximum number of memory mappings at runtime", true); } } void MaxMapCountFeature::prepare() { if (!needsChecking() || !checkMaxMappings) { return; } mapsFilename = "/proc/" + std::to_string(Thread::currentProcessId()) + "/maps"; if (!FileUtils::exists(mapsFilename)) { mapsFilename.clear(); } else { try { basics::FileUtils::slurp(mapsFilename); } catch (...) { // maps file not readable mapsFilename.clear(); } } LOG_TOPIC(DEBUG, Logger::MEMORY) << "using process maps filename '" << mapsFilename << "'"; // in case we cannot determine the number of max_map_count, we will // assume an effectively unlimited number of mappings TRI_ASSERT(maxMappings == UINT64_MAX); #ifdef __linux__ // test max_map_count value in /proc/sys/vm try { std::string value = basics::FileUtils::slurp("/proc/sys/vm/max_map_count"); maxMappings = basics::StringUtils::uint64(value); } catch (...) { // file not found or values not convertible into integers } #endif } uint64_t MaxMapCountFeature::actualMaxMappings() { return maxMappings; } uint64_t MaxMapCountFeature::minimumExpectedMaxMappings() { TRI_ASSERT(needsChecking()); uint64_t expected = 65530; // kernel default uint64_t nproc = TRI_numberProcessors(); // we expect at most 8 times the number of cores as the effective number of threads, // and we want to allow at least 8000 mmaps per thread if (nproc * 8 * 8000 > expected) { expected = nproc * 8 * 8000; } return expected; } bool MaxMapCountFeature::isNearMaxMappings() { if (!needsChecking() || !checkMaxMappings || mapsFilename.empty()) { return false; } double const now = TRI_microtime(); { // we do not want any cache stampede MUTEX_LOCKER(locker, mutex); if (lastStamp >= now || checkInFlight) { // serve value from cache return lastValue; } checkInFlight = true; } // check current maps count without holding the mutex double cacheTime; bool const value = isNearMaxMappingsInternal(cacheTime); { // update cache MUTEX_LOCKER(locker, mutex); lastValue = value; lastStamp = now + cacheTime; checkInFlight = false; } return value; } bool MaxMapCountFeature::isNearMaxMappingsInternal(double& suggestedCacheTime) noexcept { try { // recycle the same buffer for reading the maps file basics::FileUtils::slurp(mapsFilename, fileBuffer); size_t const nmaps = std::count(fileBuffer.begin(), fileBuffer.end(), '\n'); if (nmaps + 1024 < maxMappings) { if (nmaps > maxMappings * 0.90) { // more than 90% of the max mappings are in use. don't cache for too long suggestedCacheTime = 0.001; } else if (nmaps >= maxMappings / 2.0) { // we're above half of the max mappings. reduce cache time a bit suggestedCacheTime = cacheLifetime / 2.0; } else { suggestedCacheTime = cacheLifetime; } return false; } // we're near the maximum number of mappings. don't cache for too long suggestedCacheTime = 0.001; double now = TRI_microtime(); if (lastLogStamp + logFrequency < now) { // do not log too often to avoid log spamming lastLogStamp = now; LOG_TOPIC(WARN, Logger::MEMORY) << "process is near the maximum number of memory mappings. current: " << nmaps << ", maximum: " << maxMappings << ". it may be sensible to increase the maximum number of mappings per process"; } return true; } catch (...) { // something went wrong. don't cache for too long suggestedCacheTime = 0.001; return false; } } <commit_msg>increase message level to ERR for max mappings (#3426)<commit_after>//////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2016 ArangoDB GmbH, Cologne, Germany /// /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. /// You may obtain a copy of the License at /// /// http://www.apache.org/licenses/LICENSE-2.0 /// /// Unless required by applicable law or agreed to in writing, software /// distributed under the License is distributed on an "AS IS" BASIS, /// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. /// See the License for the specific language governing permissions and /// limitations under the License. /// /// Copyright holder is ArangoDB GmbH, Cologne, Germany /// /// @author Jan Steemann //////////////////////////////////////////////////////////////////////////////// #include "MaxMapCountFeature.h" #include "ApplicationFeatures/ApplicationServer.h" #include "Basics/process-utils.h" #include "Basics/FileUtils.h" #include "Basics/Mutex.h" #include "Basics/MutexLocker.h" #include "Basics/StringBuffer.h" #include "Basics/StringUtils.h" #include "Basics/Thread.h" #include "Logger/Logger.h" #include "ProgramOptions/ProgramOptions.h" #include "ProgramOptions/Section.h" #include <algorithm> using namespace arangodb; using namespace arangodb::basics; using namespace arangodb::options; namespace { static bool checkMaxMappings = arangodb::MaxMapCountFeature::needsChecking(); static uint64_t maxMappings = UINT64_MAX; static std::string mapsFilename; static StringBuffer fileBuffer(8192, false); // cache for the current number of mappings for this process // (read from /proc/<pid>/maps static Mutex mutex; static double lastStamp = 0.0; static bool lastValue = false; static bool checkInFlight = false; static constexpr double cacheLifetime = 7.5; static double lastLogStamp = 0.0; static constexpr double logFrequency = 10.0; } MaxMapCountFeature::MaxMapCountFeature( application_features::ApplicationServer* server) : ApplicationFeature(server, "MaxMapCount") { setOptional(false); requiresElevatedPrivileges(false); maxMappings = UINT64_MAX; mapsFilename.clear(); lastStamp = 0.0; lastValue = false; checkInFlight = false; lastLogStamp = 0.0; } MaxMapCountFeature::~MaxMapCountFeature() { // reset values maxMappings = UINT64_MAX; mapsFilename.clear(); lastStamp = 0.0; lastValue = false; checkInFlight = false; lastLogStamp = 0.0; } void MaxMapCountFeature::collectOptions(std::shared_ptr<options::ProgramOptions> options) { options->addSection("server", "Server Options"); if (needsChecking()) { options->addHiddenOption("--server.check-max-memory-mappings, mappings", "check the maximum number of memory mappings at runtime", new BooleanParameter(&checkMaxMappings)); } else { options->addObsoleteOption("--server.check-max-memory-mappings", "check the maximum number of memory mappings at runtime", true); } } void MaxMapCountFeature::prepare() { if (!needsChecking() || !checkMaxMappings) { return; } mapsFilename = "/proc/" + std::to_string(Thread::currentProcessId()) + "/maps"; if (!FileUtils::exists(mapsFilename)) { mapsFilename.clear(); } else { try { basics::FileUtils::slurp(mapsFilename); } catch (...) { // maps file not readable mapsFilename.clear(); } } LOG_TOPIC(DEBUG, Logger::MEMORY) << "using process maps filename '" << mapsFilename << "'"; // in case we cannot determine the number of max_map_count, we will // assume an effectively unlimited number of mappings TRI_ASSERT(maxMappings == UINT64_MAX); #ifdef __linux__ // test max_map_count value in /proc/sys/vm try { std::string value = basics::FileUtils::slurp("/proc/sys/vm/max_map_count"); maxMappings = basics::StringUtils::uint64(value); } catch (...) { // file not found or values not convertible into integers } #endif } uint64_t MaxMapCountFeature::actualMaxMappings() { return maxMappings; } uint64_t MaxMapCountFeature::minimumExpectedMaxMappings() { TRI_ASSERT(needsChecking()); uint64_t expected = 65530; // kernel default uint64_t nproc = TRI_numberProcessors(); // we expect at most 8 times the number of cores as the effective number of threads, // and we want to allow at least 8000 mmaps per thread if (nproc * 8 * 8000 > expected) { expected = nproc * 8 * 8000; } return expected; } bool MaxMapCountFeature::isNearMaxMappings() { if (!needsChecking() || !checkMaxMappings || mapsFilename.empty()) { return false; } double const now = TRI_microtime(); { // we do not want any cache stampede MUTEX_LOCKER(locker, mutex); if (lastStamp >= now || checkInFlight) { // serve value from cache return lastValue; } checkInFlight = true; } // check current maps count without holding the mutex double cacheTime; bool const value = isNearMaxMappingsInternal(cacheTime); { // update cache MUTEX_LOCKER(locker, mutex); lastValue = value; lastStamp = now + cacheTime; checkInFlight = false; } return value; } bool MaxMapCountFeature::isNearMaxMappingsInternal(double& suggestedCacheTime) noexcept { try { // recycle the same buffer for reading the maps file basics::FileUtils::slurp(mapsFilename, fileBuffer); size_t const nmaps = std::count(fileBuffer.begin(), fileBuffer.end(), '\n'); if (nmaps + 1024 < maxMappings) { if (nmaps > maxMappings * 0.90) { // more than 90% of the max mappings are in use. don't cache for too long suggestedCacheTime = 0.001; } else if (nmaps >= maxMappings / 2.0) { // we're above half of the max mappings. reduce cache time a bit suggestedCacheTime = cacheLifetime / 2.0; } else { suggestedCacheTime = cacheLifetime; } return false; } // we're near the maximum number of mappings. don't cache for too long suggestedCacheTime = 0.001; double now = TRI_microtime(); if (lastLogStamp + logFrequency < now) { // do not log too often to avoid log spamming lastLogStamp = now; LOG_TOPIC(ERR, Logger::MEMORY) << "process is near the maximum number of memory mappings. current: " << nmaps << ", maximum: " << maxMappings << ". it may be sensible to increase the maximum number of mappings per process"; } return true; } catch (...) { // something went wrong. don't cache for too long suggestedCacheTime = 0.001; return false; } } <|endoftext|>
<commit_before>/* This file is part of HadesMem. Copyright 2010 RaptorFactor (aka Cypherjb, Cypher, Chazwazza). <http://www.raptorfactor.com/> <[email protected]> HadesMem is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. HadesMem is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with HadesMem. If not, see <http://www.gnu.org/licenses/>. */ // C++ Standard Library #include <fstream> #include <sstream> // Boost #pragma warning(push, 1) #include <boost/lexical_cast.hpp> #pragma warning(pop) // RapidXML #pragma warning(push, 1) #include <RapidXML/rapidxml.hpp> #pragma warning(pop) // Hades #include "PeFile.h" #include "Module.h" #include "Scanner.h" #include "DosHeader.h" #include "NtHeaders.h" #include "FindPattern.h" #include "Hades-Common/I18n.h" namespace Hades { namespace Memory { // Constructor FindPattern::FindPattern(MemoryMgr const& MyMemory) : m_Memory(MyMemory), m_Start(nullptr), m_End(nullptr), m_Addresses() { // Get pointer to image headers ModuleListIter ModIter(m_Memory); PBYTE const pBase = reinterpret_cast<PBYTE>((*ModIter)->GetBase()); PeFile MyPeFile(m_Memory, pBase); DosHeader const MyDosHeader(MyPeFile); NtHeaders const MyNtHeaders(MyPeFile); // Get base of code section m_Start = pBase + MyNtHeaders.GetBaseOfCode(); // Calculate end of code section m_End = m_Start + MyNtHeaders.GetSizeOfCode(); } // Constructor FindPattern::FindPattern(MemoryMgr const& MyMemory, HMODULE Module) : m_Memory(MyMemory), m_Start(nullptr), m_End(nullptr), m_Addresses() { // Ensure file is a valid PE file PBYTE const pBase = reinterpret_cast<PBYTE>(Module); PeFile MyPeFile(m_Memory, pBase); DosHeader const MyDosHeader(MyPeFile); NtHeaders const MyNtHeaders(MyPeFile); // Get base of code section m_Start = pBase + MyNtHeaders.GetBaseOfCode(); // Calculate end of code section m_End = m_Start + MyNtHeaders.GetSizeOfCode(); } // Find pattern PVOID FindPattern::Find(std::basic_string<TCHAR> const& Data, std::basic_string<TCHAR> const& Mask) const { // Ensure pattern attributes are valid if (Data.empty() || Mask.empty()) { BOOST_THROW_EXCEPTION(Error() << ErrorFunction("FindPattern::Find") << ErrorString("Empty pattern or mask data.")); } // Ensure data is valid if (Data.size() % 2) { BOOST_THROW_EXCEPTION(Error() << ErrorFunction("FindPattern::Find") << ErrorString("Data size invalid.")); } // Ensure mask is valid if (Mask.size() * 2 != Data.size()) { BOOST_THROW_EXCEPTION(Error() << ErrorFunction("FindPattern::Find") << ErrorString("Mask size invalid.")); } // Convert data to byte buffer std::vector<std::pair<BYTE, bool>> DataBuf; for (auto i = Data.cbegin(), j = Mask.cbegin(); i != Data.cend(); i += 2, ++j) { std::basic_string<TCHAR> const CurrentStr(i, i + 2); std::basic_stringstream<TCHAR> Converter(CurrentStr); int Current(0); if (!(Converter >> std::hex >> Current >> std::dec)) { BOOST_THROW_EXCEPTION(Error() << ErrorFunction("FindPattern::Find") << ErrorString("Invalid data conversion.")); } BYTE CurrentReal = static_cast<BYTE>(Current); bool MaskFlag = *j == _T('x'); DataBuf.push_back(std::make_pair(CurrentReal, MaskFlag)); } // Search memory for pattern return Find(DataBuf); } // Search memory // Note: Previous implementation used modified Boyer-Moore-Horspool, but // this was dropped as the C++ 'search' algorithm provided with MSVC // performs equally if not slightly better than my custom search. PVOID FindPattern::Find(std::vector<std::pair<BYTE, bool>> const& Data) const { // Cache all memory to be scanned std::size_t MemSize = m_End - m_Start; std::vector<BYTE> Buffer(m_Memory.Read<std::vector<BYTE>>(m_Start, MemSize)); // Scan memory auto Iter = std::search(Buffer.begin(), Buffer.end(), Data.begin(), Data.end(), [&] (BYTE HCur, std::pair<BYTE, bool> NCur) { return (!NCur.second) || (HCur == NCur.first); }); // Return address if found or null if not found return (Iter != Buffer.end()) ? (m_Start + std::distance(Buffer.begin(), Iter)) : nullptr; } // Load patterns from XML file void FindPattern::LoadFromXML(boost::filesystem::path const& Path) { // Open current file std::wifstream PatternFile(Path.string<std::basic_string<TCHAR>>(). c_str()); if (!PatternFile) { BOOST_THROW_EXCEPTION(Error() << ErrorFunction("FindPattern::LoadFromXML") << ErrorString("Could not open pattern file.")); } // Copy file to buffer std::istreambuf_iterator<wchar_t> const PatFileBeg(PatternFile); std::istreambuf_iterator<wchar_t> const PatFileEnd; std::vector<wchar_t> PatFileBuf(PatFileBeg, PatFileEnd); PatFileBuf.push_back(L'\0'); // Open XML document std::shared_ptr<rapidxml::xml_document<wchar_t>> const AccountsDoc( std::make_shared<rapidxml::xml_document<wchar_t>>()); AccountsDoc->parse<0>(&PatFileBuf[0]); // Ensure pattern tag is found rapidxml::xml_node<wchar_t>* PatternsTag = AccountsDoc->first_node( L"Patterns"); if (!PatternsTag) { BOOST_THROW_EXCEPTION(Error() << ErrorFunction("FindPattern::LoadFromXML") << ErrorString("Invalid pattern file format.")); } // Loop over all patterns for (rapidxml::xml_node<wchar_t>* Pattern(PatternsTag->first_node( L"Pattern")); Pattern; Pattern = Pattern->next_sibling(L"Pattern")) { // Get pattern attributes rapidxml::xml_attribute<wchar_t> const* NameNode = Pattern-> first_attribute(L"Name"); rapidxml::xml_attribute<wchar_t> const* MaskNode = Pattern-> first_attribute(L"Mask"); rapidxml::xml_attribute<wchar_t> const* DataNode = Pattern-> first_attribute(L"Data"); std::wstring const Name(NameNode ? NameNode->value() : L""); std::wstring const Mask(MaskNode ? MaskNode->value() : L""); std::wstring const Data(DataNode ? DataNode->value() : L""); std::string const DataReal(boost::lexical_cast<std::string>(Data)); // Ensure pattern attributes are valid if (Name.empty()) { BOOST_THROW_EXCEPTION(Error() << ErrorFunction("FindPattern::LoadFromXML") << ErrorString("Empty pattern name.")); } // Find pattern PBYTE Address = static_cast<PBYTE>(Find( boost::lexical_cast<std::basic_string<TCHAR>>(Data), boost::lexical_cast<std::basic_string<TCHAR>>(Mask))); // Only apply options if pattern was found if (Address != 0) { // Loop over all pattern options for (rapidxml::xml_node<wchar_t> const* PatOpts = Pattern-> first_node(); PatOpts; PatOpts = PatOpts->next_sibling()) { // Get option name std::wstring const OptionName(PatOpts->name()); // Handle 'Add' and 'Sub' options bool const IsAdd = (OptionName == L"Add"); bool const IsSub = (OptionName == L"Sub"); if (IsAdd || IsSub) { // Get the modification value rapidxml::xml_attribute<wchar_t> const* ModVal = PatOpts-> first_attribute(L"Value"); if (!ModVal) { BOOST_THROW_EXCEPTION(Error() << ErrorFunction("FindPattern::LoadFromXML") << ErrorString("No value specified for 'Add' option.")); } // Convert value to usable form std::wstringstream Converter(ModVal->value()); DWORD_PTR AddValReal = 0; if (!(Converter >> std::hex >> AddValReal >> std::dec)) { BOOST_THROW_EXCEPTION(Error() << ErrorFunction("FindPattern::LoadFromXML") << ErrorString("Invalid conversion for 'Add' option.")); } // Perform modification if (IsAdd) { Address += AddValReal; } else if (IsSub) { Address -= AddValReal; } else { BOOST_THROW_EXCEPTION(Error() << ErrorFunction("FindPattern::LoadFromXML") << ErrorString("Unsupported pattern option.")); } } // Handle 'Lea' option (abs deref) else if (OptionName == L"Lea") { // Perform absolute 'dereference' Address = m_Memory.Read<PBYTE>(Address); } // Handle 'Rel' option (rel deref) else if (OptionName == L"Rel") { // Get instruction size rapidxml::xml_attribute<wchar_t> const* SizeAttr = PatOpts-> first_attribute(L"Size"); if (!SizeAttr) { BOOST_THROW_EXCEPTION(Error() << ErrorFunction("FindPattern::LoadFromXML") << ErrorString("No size specified for 'Size' in 'Rel' " "option.")); } // Convert instruction size to usable format std::wstringstream SizeConverter(SizeAttr->value()); DWORD_PTR Size(0); if (!(SizeConverter >> std::hex >> Size >> std::dec)) { BOOST_THROW_EXCEPTION(Error() << ErrorFunction("FindPattern::LoadFromXML") << ErrorString("Invalid conversion for 'Size' in 'Rel' " "option.")); } // Get instruction offset rapidxml::xml_attribute<wchar_t> const* OffsetAttr = PatOpts-> first_attribute(L"Offset"); if (!OffsetAttr) { BOOST_THROW_EXCEPTION(Error() << ErrorFunction("FindPattern::LoadFromXML") << ErrorString("No value specified for 'Offset' in 'Rel' " "option.")); } // Convert instruction offset to usable format std::wstringstream OffsetConverter(OffsetAttr->value()); DWORD_PTR Offset(0); if (!(OffsetConverter >> std::hex >> Offset >> std::dec)) { BOOST_THROW_EXCEPTION(Error() << ErrorFunction("FindPattern::LoadFromXML") << ErrorString("Invalid conversion for 'Offset' in 'Rel' " "option.")); } // Perform relative 'dereference' Address = m_Memory.Read<PBYTE>(Address) + reinterpret_cast<DWORD_PTR>(Address) + Size - Offset; } else { // Unknown pattern option BOOST_THROW_EXCEPTION(Error() << ErrorFunction("FindPattern::LoadFromXML") << ErrorString("Unknown pattern option.")); } } } // Check for duplicate entry auto const Iter = m_Addresses.find(boost::lexical_cast<std:: basic_string<TCHAR>>(Name)); if (Iter != m_Addresses.end()) { BOOST_THROW_EXCEPTION(Error() << ErrorFunction("FindPattern::LoadFromXML") << ErrorString("Duplicate pattern name.")); } // Add address to map m_Addresses[boost::lexical_cast<std::basic_string<TCHAR>>(Name)] = Address; } } // Get address map std::map<std::basic_string<TCHAR>, PVOID> FindPattern::GetAddresses() const { return m_Addresses; } // Operator[] overload to allow retrieving addresses by name PVOID FindPattern::operator[](std::basic_string<TCHAR> const& Name) const { auto const Iter = m_Addresses.find(Name); return Iter != m_Addresses.end() ? Iter->second : nullptr; } } } <commit_msg>* Started FindPattern 'rewrite'.<commit_after>/* This file is part of HadesMem. Copyright 2010 RaptorFactor (aka Cypherjb, Cypher, Chazwazza). <http://www.raptorfactor.com/> <[email protected]> HadesMem is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. HadesMem is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with HadesMem. If not, see <http://www.gnu.org/licenses/>. */ // C++ Standard Library #include <fstream> #include <sstream> // Boost #pragma warning(push, 1) #include <boost/lexical_cast.hpp> #include <boost/spirit/include/qi.hpp> #include <boost/spirit/include/phoenix.hpp> #include <boost/spirit/include/support.hpp> #pragma warning(pop) // RapidXML #pragma warning(push, 1) #include <RapidXML/rapidxml.hpp> #pragma warning(pop) // Hades #include "PeFile.h" #include "Module.h" #include "Scanner.h" #include "DosHeader.h" #include "NtHeaders.h" #include "FindPattern.h" #include "Hades-Common/I18n.h" namespace Hades { namespace Memory { // Constructor FindPattern::FindPattern(MemoryMgr const& MyMemory) : m_Memory(MyMemory), m_Start(nullptr), m_End(nullptr), m_Addresses() { // Get pointer to image headers ModuleListIter ModIter(m_Memory); PBYTE const pBase = reinterpret_cast<PBYTE>((*ModIter)->GetBase()); PeFile MyPeFile(m_Memory, pBase); DosHeader const MyDosHeader(MyPeFile); NtHeaders const MyNtHeaders(MyPeFile); // Get base of code section m_Start = pBase + MyNtHeaders.GetBaseOfCode(); // Calculate end of code section m_End = m_Start + MyNtHeaders.GetSizeOfCode(); } // Constructor FindPattern::FindPattern(MemoryMgr const& MyMemory, HMODULE Module) : m_Memory(MyMemory), m_Start(nullptr), m_End(nullptr), m_Addresses() { // Ensure file is a valid PE file PBYTE const pBase = reinterpret_cast<PBYTE>(Module); PeFile MyPeFile(m_Memory, pBase); DosHeader const MyDosHeader(MyPeFile); NtHeaders const MyNtHeaders(MyPeFile); // Get base of code section m_Start = pBase + MyNtHeaders.GetBaseOfCode(); // Calculate end of code section m_End = m_Start + MyNtHeaders.GetSizeOfCode(); } // Find pattern PVOID FindPattern::Find(std::basic_string<TCHAR> const& Data, std::basic_string<TCHAR> const& Mask) const { // Ensure pattern attributes are valid if (Data.empty() || Mask.empty()) { BOOST_THROW_EXCEPTION(Error() << ErrorFunction("FindPattern::Find") << ErrorString("Empty pattern or mask data.")); } // Convert data to byte buffer // Todo: Ensure each 'byte' is two characters long std::vector<BYTE> Bytes; auto DataBeg = Data.cbegin(); auto DataEnd = Data.cend(); if (!boost::spirit::qi::phrase_parse(DataBeg, DataEnd, *boost::spirit::qi::hex, boost::spirit::qi::space, Bytes) || DataBeg != DataEnd) { BOOST_THROW_EXCEPTION(Error() << ErrorFunction("FindPattern::Find") << ErrorString("Failed to parse bytes.")); } // Convert mask to bit flag std::vector<bool> MaskFlags; auto MaskBeg = Mask.cbegin(); auto MaskEnd = Mask.cend(); if (!boost::spirit::qi::parse(MaskBeg, MaskEnd, *((boost::spirit::qi::lit("x") >> boost::spirit::qi::attr(true)) | (boost::spirit::qi::lit("?") >> boost::spirit::qi::attr(false))), MaskFlags) || MaskBeg != MaskEnd) { BOOST_THROW_EXCEPTION(Error() << ErrorFunction("FindPattern::Find") << ErrorString("Failed to parse mask.")); } // Sanity check if (Bytes.size() != MaskFlags.size()) { BOOST_THROW_EXCEPTION(Error() << ErrorFunction("FindPattern::Find") << ErrorString("Parsed data differs in size to parsed mask.")); } // Convert to required format // Todo: Do this as part of the parsing process std::vector<std::pair<BYTE, bool>> DataBuf; for (std::size_t i = 0; i != Bytes.size(); ++i) { DataBuf.push_back(std::make_pair(Bytes[i], MaskFlags[i])); } // Search memory for pattern return Find(DataBuf); } // Search memory // Note: Previous implementation used modified Boyer-Moore-Horspool, but // this was dropped as the C++ 'search' algorithm provided with MSVC // performs equally if not slightly better than my custom search. PVOID FindPattern::Find(std::vector<std::pair<BYTE, bool>> const& Data) const { // Cache all memory to be scanned std::size_t MemSize = m_End - m_Start; std::vector<BYTE> Buffer(m_Memory.Read<std::vector<BYTE>>(m_Start, MemSize)); // Scan memory auto Iter = std::search(Buffer.begin(), Buffer.end(), Data.begin(), Data.end(), [&] (BYTE HCur, std::pair<BYTE, bool> NCur) { return (!NCur.second) || (HCur == NCur.first); }); // Return address if found or null if not found return (Iter != Buffer.end()) ? (m_Start + std::distance(Buffer.begin(), Iter)) : nullptr; } // Load patterns from XML file void FindPattern::LoadFromXML(boost::filesystem::path const& Path) { // Open current file std::wifstream PatternFile(Path.string<std::basic_string<TCHAR>>(). c_str()); if (!PatternFile) { BOOST_THROW_EXCEPTION(Error() << ErrorFunction("FindPattern::LoadFromXML") << ErrorString("Could not open pattern file.")); } // Copy file to buffer std::istreambuf_iterator<wchar_t> const PatFileBeg(PatternFile); std::istreambuf_iterator<wchar_t> const PatFileEnd; std::vector<wchar_t> PatFileBuf(PatFileBeg, PatFileEnd); PatFileBuf.push_back(L'\0'); // Open XML document std::shared_ptr<rapidxml::xml_document<wchar_t>> const AccountsDoc( std::make_shared<rapidxml::xml_document<wchar_t>>()); AccountsDoc->parse<0>(&PatFileBuf[0]); // Ensure pattern tag is found rapidxml::xml_node<wchar_t>* PatternsTag = AccountsDoc->first_node( L"Patterns"); if (!PatternsTag) { BOOST_THROW_EXCEPTION(Error() << ErrorFunction("FindPattern::LoadFromXML") << ErrorString("Invalid pattern file format.")); } // Loop over all patterns for (rapidxml::xml_node<wchar_t>* Pattern(PatternsTag->first_node( L"Pattern")); Pattern; Pattern = Pattern->next_sibling(L"Pattern")) { // Get pattern attributes rapidxml::xml_attribute<wchar_t> const* NameNode = Pattern-> first_attribute(L"Name"); rapidxml::xml_attribute<wchar_t> const* MaskNode = Pattern-> first_attribute(L"Mask"); rapidxml::xml_attribute<wchar_t> const* DataNode = Pattern-> first_attribute(L"Data"); std::wstring const Name(NameNode ? NameNode->value() : L""); std::wstring const Mask(MaskNode ? MaskNode->value() : L""); std::wstring const Data(DataNode ? DataNode->value() : L""); std::string const DataReal(boost::lexical_cast<std::string>(Data)); // Ensure pattern attributes are valid if (Name.empty()) { BOOST_THROW_EXCEPTION(Error() << ErrorFunction("FindPattern::LoadFromXML") << ErrorString("Empty pattern name.")); } // Find pattern PBYTE Address = static_cast<PBYTE>(Find( boost::lexical_cast<std::basic_string<TCHAR>>(Data), boost::lexical_cast<std::basic_string<TCHAR>>(Mask))); // Only apply options if pattern was found if (Address != 0) { // Loop over all pattern options for (rapidxml::xml_node<wchar_t> const* PatOpts = Pattern-> first_node(); PatOpts; PatOpts = PatOpts->next_sibling()) { // Get option name std::wstring const OptionName(PatOpts->name()); // Handle 'Add' and 'Sub' options bool const IsAdd = (OptionName == L"Add"); bool const IsSub = (OptionName == L"Sub"); if (IsAdd || IsSub) { // Get the modification value rapidxml::xml_attribute<wchar_t> const* ModVal = PatOpts-> first_attribute(L"Value"); if (!ModVal) { BOOST_THROW_EXCEPTION(Error() << ErrorFunction("FindPattern::LoadFromXML") << ErrorString("No value specified for 'Add' option.")); } // Convert value to usable form std::wstringstream Converter(ModVal->value()); DWORD_PTR AddValReal = 0; if (!(Converter >> std::hex >> AddValReal >> std::dec)) { BOOST_THROW_EXCEPTION(Error() << ErrorFunction("FindPattern::LoadFromXML") << ErrorString("Invalid conversion for 'Add' option.")); } // Perform modification if (IsAdd) { Address += AddValReal; } else if (IsSub) { Address -= AddValReal; } else { BOOST_THROW_EXCEPTION(Error() << ErrorFunction("FindPattern::LoadFromXML") << ErrorString("Unsupported pattern option.")); } } // Handle 'Lea' option (abs deref) else if (OptionName == L"Lea") { // Perform absolute 'dereference' Address = m_Memory.Read<PBYTE>(Address); } // Handle 'Rel' option (rel deref) else if (OptionName == L"Rel") { // Get instruction size rapidxml::xml_attribute<wchar_t> const* SizeAttr = PatOpts-> first_attribute(L"Size"); if (!SizeAttr) { BOOST_THROW_EXCEPTION(Error() << ErrorFunction("FindPattern::LoadFromXML") << ErrorString("No size specified for 'Size' in 'Rel' " "option.")); } // Convert instruction size to usable format std::wstringstream SizeConverter(SizeAttr->value()); DWORD_PTR Size(0); if (!(SizeConverter >> std::hex >> Size >> std::dec)) { BOOST_THROW_EXCEPTION(Error() << ErrorFunction("FindPattern::LoadFromXML") << ErrorString("Invalid conversion for 'Size' in 'Rel' " "option.")); } // Get instruction offset rapidxml::xml_attribute<wchar_t> const* OffsetAttr = PatOpts-> first_attribute(L"Offset"); if (!OffsetAttr) { BOOST_THROW_EXCEPTION(Error() << ErrorFunction("FindPattern::LoadFromXML") << ErrorString("No value specified for 'Offset' in 'Rel' " "option.")); } // Convert instruction offset to usable format std::wstringstream OffsetConverter(OffsetAttr->value()); DWORD_PTR Offset(0); if (!(OffsetConverter >> std::hex >> Offset >> std::dec)) { BOOST_THROW_EXCEPTION(Error() << ErrorFunction("FindPattern::LoadFromXML") << ErrorString("Invalid conversion for 'Offset' in 'Rel' " "option.")); } // Perform relative 'dereference' Address = m_Memory.Read<PBYTE>(Address) + reinterpret_cast<DWORD_PTR>(Address) + Size - Offset; } else { // Unknown pattern option BOOST_THROW_EXCEPTION(Error() << ErrorFunction("FindPattern::LoadFromXML") << ErrorString("Unknown pattern option.")); } } } // Check for duplicate entry auto const Iter = m_Addresses.find(boost::lexical_cast<std:: basic_string<TCHAR>>(Name)); if (Iter != m_Addresses.end()) { BOOST_THROW_EXCEPTION(Error() << ErrorFunction("FindPattern::LoadFromXML") << ErrorString("Duplicate pattern name.")); } // Add address to map m_Addresses[boost::lexical_cast<std::basic_string<TCHAR>>(Name)] = Address; } } // Get address map std::map<std::basic_string<TCHAR>, PVOID> FindPattern::GetAddresses() const { return m_Addresses; } // Operator[] overload to allow retrieving addresses by name PVOID FindPattern::operator[](std::basic_string<TCHAR> const& Name) const { auto const Iter = m_Addresses.find(Name); return Iter != m_Addresses.end() ? Iter->second : nullptr; } } } <|endoftext|>
<commit_before>// Copyright (c) 2012 Intel Corp // Copyright (c) 2012 The Chromium Authors // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell co // pies 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 al // l copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM // PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES // S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS // OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH // ETHER 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. #define V8_USE_UNSAFE_HANDLES #include "content/nw/src/api/dispatcher.h" #include "content/nw/src/api/api_messages.h" #include "content/public/renderer/render_view.h" #include "content/renderer/v8_value_converter_impl.h" #include "third_party/node/src/node.h" #undef CHECK #include "third_party/node/src/req_wrap.h" #include "third_party/WebKit/public/web/WebDocument.h" #include "third_party/WebKit/public/web/WebFrame.h" #include "third_party/WebKit/public/web/WebView.h" #include "v8/include/v8.h" #undef LOG #undef ASSERT #undef FROM_HERE #if defined(OS_WIN) #define _USE_MATH_DEFINES #include <math.h> #endif #include "third_party/WebKit/Source/config.h" #include "third_party/WebKit/Source/core/frame/Frame.h" #include "third_party/WebKit/Source/web/WebFrameImpl.h" #include "V8HTMLElement.h" namespace nwapi { static inline v8::Local<v8::String> v8_str(const char* x) { v8::Isolate* isolate = v8::Isolate::GetCurrent(); return v8::String::NewFromUtf8(isolate, x); } Dispatcher::Dispatcher(content::RenderView* render_view) : content::RenderViewObserver(render_view) { } Dispatcher::~Dispatcher() { } bool Dispatcher::OnMessageReceived(const IPC::Message& message) { bool handled = true; IPC_BEGIN_MESSAGE_MAP(Dispatcher, message) IPC_MESSAGE_HANDLER(ShellViewMsg_Object_On_Event, OnEvent) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() return handled; } void Dispatcher::DraggableRegionsChanged(blink::WebFrame* frame) { blink::WebVector<blink::WebDraggableRegion> webregions = frame->document().draggableRegions(); std::vector<extensions::DraggableRegion> regions; for (size_t i = 0; i < webregions.size(); ++i) { extensions::DraggableRegion region; region.bounds = webregions[i].bounds; region.draggable = webregions[i].draggable; regions.push_back(region); } Send(new ShellViewHostMsg_UpdateDraggableRegions(routing_id(), regions)); } void Dispatcher::OnEvent(int object_id, std::string event, const base::ListValue& arguments) { v8::Isolate* isolate = v8::Isolate::GetCurrent(); v8::HandleScope scope(isolate); blink::WebView* web_view = render_view()->GetWebView(); if (web_view == NULL) return; DVLOG(1) << "Dispatcher::OnEvent(object_id=" << object_id << ", event=\"" << event << "\")"; content::V8ValueConverterImpl converter; v8::Local<v8::Context> context = v8::Local<v8::Context>::New(isolate, node::g_context); v8::Handle<v8::Value> args = converter.ToV8Value(&arguments, context); DCHECK(!args.IsEmpty()) << "Invalid 'arguments' in Dispatcher::OnEvent"; v8::Handle<v8::Value> argv[] = { v8::Integer::New(isolate, object_id), v8_str(event.c_str()), args }; // __nwObjectsRegistry.handleEvent(object_id, event, arguments); v8::Handle<v8::Value> val = context->Global()->Get(v8_str("__nwObjectsRegistry")); if (val->IsNull() || val->IsUndefined()) return; // need to find out why it's undefined here in debugger v8::Handle<v8::Object> objects_registry = val->ToObject(); DVLOG(1) << "handleEvent(object_id=" << object_id << ", event=\"" << event << "\")"; node::MakeCallback(isolate, objects_registry, "handleEvent", 3, argv); } v8::Handle<v8::Object> Dispatcher::GetObjectRegistry() { v8::Isolate* isolate = v8::Isolate::GetCurrent(); v8::Local<v8::Context> context = v8::Local<v8::Context>::New(isolate, node::g_context); // need to enter node context to access the registry in // some cases, e.g. normal frame in #1519 context->Enter(); v8::Handle<v8::Value> registry = context->Global()->Get(v8_str("__nwObjectsRegistry")); context->Exit(); ASSERT(!(registry->IsNull() || registry->IsUndefined())); // if (registry->IsNull() || registry->IsUndefined()) // return v8::Undefined(); return registry->ToObject(); } v8::Handle<v8::Value> Dispatcher::GetWindowId(blink::WebFrame* frame) { v8::Handle<v8::Value> v8win = frame->mainWorldScriptContext()->Global(); v8::Handle<v8::Value> val = v8win->ToObject()->Get(v8_str("__nwWindowId")); return val; } void Dispatcher::ZoomLevelChanged() { v8::Isolate* isolate = v8::Isolate::GetCurrent(); v8::HandleScope scope(isolate); blink::WebView* web_view = render_view()->GetWebView(); float zoom_level = web_view->zoomLevel(); v8::Handle<v8::Value> val = GetWindowId(web_view->mainFrame()); if (val->IsNull() || val->IsUndefined()) return; v8::Handle<v8::Object> objects_registry = GetObjectRegistry(); if (objects_registry->IsUndefined()) return; v8::Local<v8::Array> args = v8::Array::New(isolate); args->Set(0, v8::Number::New(isolate, zoom_level)); v8::Handle<v8::Value> argv[] = {val, v8_str("zoom"), args }; node::MakeCallback(isolate, objects_registry, "handleEvent", 3, argv); } void Dispatcher::DidCreateDocumentElement(blink::WebFrame* frame) { documentCallback("document-start", frame); } void Dispatcher::DidFinishDocumentLoad(blink::WebFrame* frame) { documentCallback("document-end", frame); } void Dispatcher::documentCallback(const char* ev, blink::WebFrame* frame) { v8::Isolate* isolate = v8::Isolate::GetCurrent(); blink::WebView* web_view = render_view()->GetWebView(); v8::HandleScope scope(isolate); if (!web_view) return; v8::Context::Scope cscope (web_view->mainFrame()->mainWorldScriptContext()); v8::Handle<v8::Value> val = GetWindowId(web_view->mainFrame()); if (val->IsNull() || val->IsUndefined()) return; v8::Handle<v8::Object> objects_registry = GetObjectRegistry(); if (objects_registry->IsUndefined()) return; v8::Local<v8::Array> args = v8::Array::New(isolate); v8::Handle<v8::Value> element = v8::Null(isolate); WebCore::LocalFrame* core_frame = blink::toWebFrameImpl(frame)->frame(); if (core_frame->ownerElement()) { element = WebCore::toV8((WebCore::HTMLElement*)core_frame->ownerElement(), frame->mainWorldScriptContext()->Global(), frame->mainWorldScriptContext()->GetIsolate()); } args->Set(0, element); v8::Handle<v8::Value> argv[] = {val, v8_str(ev), args }; node::MakeCallback(isolate, objects_registry, "handleEvent", 3, argv); } void Dispatcher::willHandleNavigationPolicy( content::RenderView* rv, blink::WebFrame* frame, const blink::WebURLRequest& request, blink::WebNavigationPolicy* policy) { blink::WebView* web_view = rv->GetWebView(); if (!web_view) return; v8::Isolate* isolate = v8::Isolate::GetCurrent(); v8::Handle<v8::Value> id_val = nwapi::Dispatcher::GetWindowId(web_view->mainFrame()); if (id_val->IsNull() || id_val->IsUndefined()) return; v8::Handle<v8::Object> objects_registry = nwapi::Dispatcher::GetObjectRegistry(); if (objects_registry->IsUndefined()) return; v8::Context::Scope cscope (web_view->mainFrame()->mainWorldScriptContext()); v8::Local<v8::Array> args = v8::Array::New(isolate); v8::Handle<v8::Value> element = v8::Null(isolate); v8::Handle<v8::Object> policy_obj = v8::Object::New(isolate); WebCore::LocalFrame* core_frame = blink::toWebFrameImpl(frame)->frame(); if (core_frame->ownerElement()) { element = WebCore::toV8((WebCore::HTMLElement*)core_frame->ownerElement(), frame->mainWorldScriptContext()->Global(), frame->mainWorldScriptContext()->GetIsolate()); } args->Set(0, element); args->Set(1, v8_str(request.url().string().utf8().c_str())); args->Set(2, policy_obj); v8::Handle<v8::Value> argv[] = {id_val, v8_str("new-win-policy"), args }; node::MakeCallback(isolate, objects_registry, "handleEvent", 3, argv); v8::Local<v8::Value> val = policy_obj->Get(v8_str("val")); if (!val->IsString()) return; v8::String::Utf8Value policy_str(val); if (!strcmp(*policy_str, "ignore")) *policy = blink::WebNavigationPolicyIgnore; else if (!strcmp(*policy_str, "download")) *policy = blink::WebNavigationPolicyDownload; else if (!strcmp(*policy_str, "current")) *policy = blink::WebNavigationPolicyCurrentTab; else if (!strcmp(*policy_str, "new-window")) *policy = blink::WebNavigationPolicyNewWindow; else if (!strcmp(*policy_str, "new-popup")) *policy = blink::WebNavigationPolicyNewPopup; } } // namespace nwapi <commit_msg>handle empty id value in dispatcher callbacks<commit_after>// Copyright (c) 2012 Intel Corp // Copyright (c) 2012 The Chromium Authors // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell co // pies 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 al // l copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM // PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES // S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS // OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH // ETHER 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. #define V8_USE_UNSAFE_HANDLES #include "content/nw/src/api/dispatcher.h" #include "content/nw/src/api/api_messages.h" #include "content/public/renderer/render_view.h" #include "content/renderer/v8_value_converter_impl.h" #include "third_party/node/src/node.h" #undef CHECK #include "third_party/node/src/req_wrap.h" #include "third_party/WebKit/public/web/WebDocument.h" #include "third_party/WebKit/public/web/WebFrame.h" #include "third_party/WebKit/public/web/WebView.h" #include "v8/include/v8.h" #undef LOG #undef ASSERT #undef FROM_HERE #if defined(OS_WIN) #define _USE_MATH_DEFINES #include <math.h> #endif #include "third_party/WebKit/Source/config.h" #include "third_party/WebKit/Source/core/frame/Frame.h" #include "third_party/WebKit/Source/web/WebFrameImpl.h" #include "V8HTMLElement.h" namespace nwapi { static inline v8::Local<v8::String> v8_str(const char* x) { v8::Isolate* isolate = v8::Isolate::GetCurrent(); return v8::String::NewFromUtf8(isolate, x); } Dispatcher::Dispatcher(content::RenderView* render_view) : content::RenderViewObserver(render_view) { } Dispatcher::~Dispatcher() { } bool Dispatcher::OnMessageReceived(const IPC::Message& message) { bool handled = true; IPC_BEGIN_MESSAGE_MAP(Dispatcher, message) IPC_MESSAGE_HANDLER(ShellViewMsg_Object_On_Event, OnEvent) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() return handled; } void Dispatcher::DraggableRegionsChanged(blink::WebFrame* frame) { blink::WebVector<blink::WebDraggableRegion> webregions = frame->document().draggableRegions(); std::vector<extensions::DraggableRegion> regions; for (size_t i = 0; i < webregions.size(); ++i) { extensions::DraggableRegion region; region.bounds = webregions[i].bounds; region.draggable = webregions[i].draggable; regions.push_back(region); } Send(new ShellViewHostMsg_UpdateDraggableRegions(routing_id(), regions)); } void Dispatcher::OnEvent(int object_id, std::string event, const base::ListValue& arguments) { v8::Isolate* isolate = v8::Isolate::GetCurrent(); v8::HandleScope scope(isolate); blink::WebView* web_view = render_view()->GetWebView(); if (web_view == NULL) return; DVLOG(1) << "Dispatcher::OnEvent(object_id=" << object_id << ", event=\"" << event << "\")"; content::V8ValueConverterImpl converter; v8::Local<v8::Context> context = v8::Local<v8::Context>::New(isolate, node::g_context); v8::Handle<v8::Value> args = converter.ToV8Value(&arguments, context); DCHECK(!args.IsEmpty()) << "Invalid 'arguments' in Dispatcher::OnEvent"; v8::Handle<v8::Value> argv[] = { v8::Integer::New(isolate, object_id), v8_str(event.c_str()), args }; // __nwObjectsRegistry.handleEvent(object_id, event, arguments); v8::Handle<v8::Value> val = context->Global()->Get(v8_str("__nwObjectsRegistry")); if (val->IsNull() || val->IsUndefined()) return; // need to find out why it's undefined here in debugger v8::Handle<v8::Object> objects_registry = val->ToObject(); DVLOG(1) << "handleEvent(object_id=" << object_id << ", event=\"" << event << "\")"; node::MakeCallback(isolate, objects_registry, "handleEvent", 3, argv); } v8::Handle<v8::Object> Dispatcher::GetObjectRegistry() { v8::Isolate* isolate = v8::Isolate::GetCurrent(); v8::Local<v8::Context> context = v8::Local<v8::Context>::New(isolate, node::g_context); // need to enter node context to access the registry in // some cases, e.g. normal frame in #1519 context->Enter(); v8::Handle<v8::Value> registry = context->Global()->Get(v8_str("__nwObjectsRegistry")); context->Exit(); ASSERT(!(registry->IsNull() || registry->IsUndefined())); // if (registry->IsNull() || registry->IsUndefined()) // return v8::Undefined(); return registry->ToObject(); } v8::Handle<v8::Value> Dispatcher::GetWindowId(blink::WebFrame* frame) { v8::Handle<v8::Value> v8win = frame->mainWorldScriptContext()->Global(); v8::Handle<v8::Value> val = v8win->ToObject()->Get(v8_str("__nwWindowId")); return val; } void Dispatcher::ZoomLevelChanged() { v8::Isolate* isolate = v8::Isolate::GetCurrent(); v8::HandleScope scope(isolate); blink::WebView* web_view = render_view()->GetWebView(); float zoom_level = web_view->zoomLevel(); v8::Handle<v8::Value> val = GetWindowId(web_view->mainFrame()); if (id_val.IsEmpty()) return; if (val->IsNull() || val->IsUndefined()) return; v8::Handle<v8::Object> objects_registry = GetObjectRegistry(); if (objects_registry->IsUndefined()) return; v8::Local<v8::Array> args = v8::Array::New(isolate); args->Set(0, v8::Number::New(isolate, zoom_level)); v8::Handle<v8::Value> argv[] = {val, v8_str("zoom"), args }; node::MakeCallback(isolate, objects_registry, "handleEvent", 3, argv); } void Dispatcher::DidCreateDocumentElement(blink::WebFrame* frame) { documentCallback("document-start", frame); } void Dispatcher::DidFinishDocumentLoad(blink::WebFrame* frame) { documentCallback("document-end", frame); } void Dispatcher::documentCallback(const char* ev, blink::WebFrame* frame) { v8::Isolate* isolate = v8::Isolate::GetCurrent(); blink::WebView* web_view = render_view()->GetWebView(); v8::HandleScope scope(isolate); if (!web_view) return; v8::Context::Scope cscope (web_view->mainFrame()->mainWorldScriptContext()); v8::Handle<v8::Value> val = GetWindowId(web_view->mainFrame()); if (id_val.IsEmpty()) return; if (val->IsNull() || val->IsUndefined()) return; v8::Handle<v8::Object> objects_registry = GetObjectRegistry(); if (objects_registry->IsUndefined()) return; v8::Local<v8::Array> args = v8::Array::New(isolate); v8::Handle<v8::Value> element = v8::Null(isolate); WebCore::LocalFrame* core_frame = blink::toWebFrameImpl(frame)->frame(); if (core_frame->ownerElement()) { element = WebCore::toV8((WebCore::HTMLElement*)core_frame->ownerElement(), frame->mainWorldScriptContext()->Global(), frame->mainWorldScriptContext()->GetIsolate()); } args->Set(0, element); v8::Handle<v8::Value> argv[] = {val, v8_str(ev), args }; node::MakeCallback(isolate, objects_registry, "handleEvent", 3, argv); } void Dispatcher::willHandleNavigationPolicy( content::RenderView* rv, blink::WebFrame* frame, const blink::WebURLRequest& request, blink::WebNavigationPolicy* policy) { blink::WebView* web_view = rv->GetWebView(); if (!web_view) return; v8::Isolate* isolate = v8::Isolate::GetCurrent(); v8::Handle<v8::Value> id_val = nwapi::Dispatcher::GetWindowId(web_view->mainFrame()); if (id_val.IsEmpty()) return; if (id_val->IsUndefined() || id_val->IsNull()) return; v8::Handle<v8::Object> objects_registry = nwapi::Dispatcher::GetObjectRegistry(); if (objects_registry->IsUndefined()) return; v8::Context::Scope cscope (web_view->mainFrame()->mainWorldScriptContext()); v8::Local<v8::Array> args = v8::Array::New(isolate); v8::Handle<v8::Value> element = v8::Null(isolate); v8::Handle<v8::Object> policy_obj = v8::Object::New(isolate); WebCore::LocalFrame* core_frame = blink::toWebFrameImpl(frame)->frame(); if (core_frame->ownerElement()) { element = WebCore::toV8((WebCore::HTMLElement*)core_frame->ownerElement(), frame->mainWorldScriptContext()->Global(), frame->mainWorldScriptContext()->GetIsolate()); } args->Set(0, element); args->Set(1, v8_str(request.url().string().utf8().c_str())); args->Set(2, policy_obj); v8::Handle<v8::Value> argv[] = {id_val, v8_str("new-win-policy"), args }; node::MakeCallback(isolate, objects_registry, "handleEvent", 3, argv); v8::Local<v8::Value> val = policy_obj->Get(v8_str("val")); if (!val->IsString()) return; v8::String::Utf8Value policy_str(val); if (!strcmp(*policy_str, "ignore")) *policy = blink::WebNavigationPolicyIgnore; else if (!strcmp(*policy_str, "download")) *policy = blink::WebNavigationPolicyDownload; else if (!strcmp(*policy_str, "current")) *policy = blink::WebNavigationPolicyCurrentTab; else if (!strcmp(*policy_str, "new-window")) *policy = blink::WebNavigationPolicyNewWindow; else if (!strcmp(*policy_str, "new-popup")) *policy = blink::WebNavigationPolicyNewPopup; } } // namespace nwapi <|endoftext|>
<commit_before>/* The goal of these tests is to verify the behavior of all blob commands given * the current state is updateStarted. This state is achieved as an exit from * updatePending. */ #include "firmware_handler.hpp" #include "firmware_unittest.hpp" #include "status.hpp" #include "util.hpp" #include <cstdint> #include <string> #include <vector> #include <gtest/gtest.h> namespace ipmi_flash { namespace { using ::testing::Return; /* * There are the following calls (parameters may vary): * canHandleBlob(blob) * getBlobIds * deleteBlob(blob) * stat(blob) * stat(session) * open(blob) * close(session) * writemeta(session) * write(session) * read(session) * commit(session) */ class FirmwareHandlerUpdateStartedTest : public IpmiOnlyFirmwareStaticTest { }; /* * open(blob) */ TEST_F(FirmwareHandlerUpdateStartedTest, AttemptToOpenFilesReturnsFailure) { /* In state updateStarted a file is open, which means no others can be. */ getToUpdateStarted(); auto blobsToOpen = handler->getBlobIds(); for (const auto& blob : blobsToOpen) { EXPECT_FALSE(handler->open(session + 1, flags, blob)); } } /* canHandleBlob(blob) * getBlobIds */ /* * TODO: deleteBlob(blob) */ /* * stat(blob) */ /* * stat(session) */ /* * close(session) */ /* * writemeta(session) */ /* * write(session) */ /* * read(session) */ /* * commit(session) */ } // namespace } // namespace ipmi_flash <commit_msg>test: firmware updateStarted: getBlobIds()<commit_after>/* The goal of these tests is to verify the behavior of all blob commands given * the current state is updateStarted. This state is achieved as an exit from * updatePending. */ #include "firmware_handler.hpp" #include "firmware_unittest.hpp" #include "status.hpp" #include "util.hpp" #include <cstdint> #include <string> #include <vector> #include <gtest/gtest.h> namespace ipmi_flash { namespace { using ::testing::Return; using ::testing::UnorderedElementsAreArray; /* * There are the following calls (parameters may vary): * canHandleBlob(blob) * getBlobIds * deleteBlob(blob) * stat(blob) * stat(session) * open(blob) * close(session) * writemeta(session) * write(session) * read(session) * commit(session) */ class FirmwareHandlerUpdateStartedTest : public IpmiOnlyFirmwareStaticTest { }; /* * open(blob) */ TEST_F(FirmwareHandlerUpdateStartedTest, AttemptToOpenFilesReturnsFailure) { /* In state updateStarted a file is open, which means no others can be. */ getToUpdateStarted(); auto blobsToOpen = handler->getBlobIds(); for (const auto& blob : blobsToOpen) { EXPECT_FALSE(handler->open(session + 1, flags, blob)); } } /* canHandleBlob(blob) * getBlobIds */ TEST_F(FirmwareHandlerUpdateStartedTest, VerifyListOfBlobs) { getToUpdateStarted(); std::vector<std::string> expected = {updateBlobId, hashBlobId, activeImageBlobId, staticLayoutBlobId}; EXPECT_THAT(handler->getBlobIds(), UnorderedElementsAreArray(expected)); } /* * TODO: deleteBlob(blob) */ /* * stat(blob) */ /* * stat(session) */ /* * close(session) */ /* * writemeta(session) */ /* * write(session) */ /* * read(session) */ /* * commit(session) */ } // namespace } // namespace ipmi_flash <|endoftext|>
<commit_before>//===- ScalarReplAggregates.cpp - Scalar Replacement of Aggregates --------===// // // This transformation implements the well known scalar replacement of // aggregates transformation. This xform breaks up alloca instructions of // aggregate type (structure or array) into individual alloca instructions for // each member (if possible). // //===----------------------------------------------------------------------===// #include "llvm/Transforms/Scalar.h" #include "llvm/Function.h" #include "llvm/Pass.h" #include "llvm/iMemory.h" #include "llvm/DerivedTypes.h" #include "llvm/Constants.h" #include "Support/StringExtras.h" #include "Support/Statistic.h" namespace { Statistic<> NumReplaced("scalarrepl", "Number of alloca's broken up"); struct SROA : public FunctionPass { bool runOnFunction(Function &F); private: AllocaInst *AddNewAlloca(Function &F, const Type *Ty, AllocationInst *Base); }; RegisterOpt<SROA> X("scalarrepl", "Scalar Replacement of Aggregates"); } Pass *createScalarReplAggregatesPass() { return new SROA(); } // runOnFunction - This algorithm is a simple worklist driven algorithm, which // runs on all of the malloc/alloca instructions in the function, removing them // if they are only used by getelementptr instructions. // bool SROA::runOnFunction(Function &F) { std::vector<AllocationInst*> WorkList; // Scan the entry basic block, adding any alloca's and mallocs to the worklist BasicBlock &BB = F.getEntryNode(); for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I) if (AllocationInst *A = dyn_cast<AllocationInst>(I)) WorkList.push_back(A); // Process the worklist bool Changed = false; while (!WorkList.empty()) { AllocationInst *AI = WorkList.back(); WorkList.pop_back(); // We cannot transform the allocation instruction if it is an array // allocation (allocations OF arrays are ok though), and an allocation of a // scalar value cannot be decomposed at all. // if (AI->isArrayAllocation() || (!isa<StructType>(AI->getAllocatedType()) && !isa<ArrayType>(AI->getAllocatedType()))) continue; const ArrayType *AT = dyn_cast<ArrayType>(AI->getAllocatedType()); // Loop over the use list of the alloca. We can only transform it if there // are only getelementptr instructions (with a zero first index) and free // instructions. // bool CannotTransform = false; for (Value::use_iterator I = AI->use_begin(), E = AI->use_end(); I != E; ++I) { Instruction *User = cast<Instruction>(*I); if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) { // The GEP is safe to transform if it is of the form GEP <ptr>, 0, <cst> if (GEPI->getNumOperands() <= 2 || GEPI->getOperand(1) != Constant::getNullValue(Type::LongTy) || !isa<Constant>(GEPI->getOperand(2)) || isa<ConstantExpr>(GEPI->getOperand(2))) { DEBUG(std::cerr << "Cannot transform: " << *AI << " due to user: " << User); CannotTransform = true; break; } // If this is an array access, check to make sure that index falls // within the array. If not, something funny is going on, so we won't // do the optimization. if (AT && cast<ConstantSInt>(GEPI->getOperand(2))->getValue() >= AT->getNumElements()) { DEBUG(std::cerr << "Cannot transform: " << *AI << " due to user: " << User); CannotTransform = true; break; } } else { DEBUG(std::cerr << "Cannot transform: " << *AI << " due to user: " << User); CannotTransform = true; break; } } if (CannotTransform) continue; DEBUG(std::cerr << "Found inst to xform: " << *AI); Changed = true; std::vector<AllocaInst*> ElementAllocas; if (const StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) { ElementAllocas.reserve(ST->getNumContainedTypes()); for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) { AllocaInst *NA = new AllocaInst(ST->getContainedType(i), 0, AI->getName() + "." + utostr(i), AI); ElementAllocas.push_back(NA); WorkList.push_back(NA); // Add to worklist for recursive processing } } else { ElementAllocas.reserve(AT->getNumElements()); const Type *ElTy = AT->getElementType(); for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) { AllocaInst *NA = new AllocaInst(ElTy, 0, AI->getName() + "." + utostr(i), AI); ElementAllocas.push_back(NA); WorkList.push_back(NA); // Add to worklist for recursive processing } } // Now that we have created the alloca instructions that we want to use, // expand the getelementptr instructions to use them. // for (Value::use_iterator I = AI->use_begin(), E = AI->use_end(); I != E; ++I) { Instruction *User = cast<Instruction>(*I); if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) { // We now know that the GEP is of the form: GEP <ptr>, 0, <cst> uint64_t Idx; if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(GEPI->getOperand(2))) Idx = CSI->getValue(); else Idx = cast<ConstantUInt>(GEPI->getOperand(2))->getValue(); assert(Idx < ElementAllocas.size() && "Index out of range?"); AllocaInst *AllocaToUse = ElementAllocas[Idx]; Value *RepValue; if (GEPI->getNumOperands() == 3) { // Do not insert a new getelementptr instruction with zero indices, // only to have it optimized out later. RepValue = AllocaToUse; } else { // We are indexing deeply into the structure, so we still need a // getelement ptr instruction to finish the indexing. This may be // expanded itself once the worklist is rerun. // std::string OldName = GEPI->getName(); // Steal the old name... GEPI->setName(""); RepValue = new GetElementPtrInst(AllocaToUse, std::vector<Value*>(GEPI->op_begin()+3, GEPI->op_end()), OldName, GEPI); } // Move all of the users over to the new GEP. GEPI->replaceAllUsesWith(RepValue); // Delete the old GEP GEPI->getParent()->getInstList().erase(GEPI); } else { assert(0 && "Unexpected instruction type!"); } } // Finally, delete the Alloca instruction AI->getParent()->getInstList().erase(AI); NumReplaced++; } return Changed; } <commit_msg>Fix bug: ScalarRepl/2003-05-29-ArrayFail.ll<commit_after>//===- ScalarReplAggregates.cpp - Scalar Replacement of Aggregates --------===// // // This transformation implements the well known scalar replacement of // aggregates transformation. This xform breaks up alloca instructions of // aggregate type (structure or array) into individual alloca instructions for // each member (if possible). // //===----------------------------------------------------------------------===// #include "llvm/Transforms/Scalar.h" #include "llvm/Function.h" #include "llvm/Pass.h" #include "llvm/iMemory.h" #include "llvm/DerivedTypes.h" #include "llvm/Constants.h" #include "Support/StringExtras.h" #include "Support/Statistic.h" namespace { Statistic<> NumReplaced("scalarrepl", "Number of alloca's broken up"); struct SROA : public FunctionPass { bool runOnFunction(Function &F); private: bool isSafeArrayElementUse(Value *Ptr); bool isSafeUseOfAllocation(Instruction *User); bool isSafeStructAllocaToPromote(AllocationInst *AI); bool isSafeArrayAllocaToPromote(AllocationInst *AI); AllocaInst *AddNewAlloca(Function &F, const Type *Ty, AllocationInst *Base); }; RegisterOpt<SROA> X("scalarrepl", "Scalar Replacement of Aggregates"); } Pass *createScalarReplAggregatesPass() { return new SROA(); } // runOnFunction - This algorithm is a simple worklist driven algorithm, which // runs on all of the malloc/alloca instructions in the function, removing them // if they are only used by getelementptr instructions. // bool SROA::runOnFunction(Function &F) { std::vector<AllocationInst*> WorkList; // Scan the entry basic block, adding any alloca's and mallocs to the worklist BasicBlock &BB = F.getEntryNode(); for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I) if (AllocationInst *A = dyn_cast<AllocationInst>(I)) WorkList.push_back(A); // Process the worklist bool Changed = false; while (!WorkList.empty()) { AllocationInst *AI = WorkList.back(); WorkList.pop_back(); // We cannot transform the allocation instruction if it is an array // allocation (allocations OF arrays are ok though), and an allocation of a // scalar value cannot be decomposed at all. // if (AI->isArrayAllocation() || (!isa<StructType>(AI->getAllocatedType()) && !isa<ArrayType>(AI->getAllocatedType()))) continue; // Check that all of the users of the allocation are capable of being // transformed. if (isa<StructType>(AI->getAllocatedType())) { if (!isSafeStructAllocaToPromote(AI)) continue; } else if (!isSafeArrayAllocaToPromote(AI)) continue; DEBUG(std::cerr << "Found inst to xform: " << *AI); Changed = true; std::vector<AllocaInst*> ElementAllocas; if (const StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) { ElementAllocas.reserve(ST->getNumContainedTypes()); for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) { AllocaInst *NA = new AllocaInst(ST->getContainedType(i), 0, AI->getName() + "." + utostr(i), AI); ElementAllocas.push_back(NA); WorkList.push_back(NA); // Add to worklist for recursive processing } } else { const ArrayType *AT = cast<ArrayType>(AI->getAllocatedType()); ElementAllocas.reserve(AT->getNumElements()); const Type *ElTy = AT->getElementType(); for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) { AllocaInst *NA = new AllocaInst(ElTy, 0, AI->getName() + "." + utostr(i), AI); ElementAllocas.push_back(NA); WorkList.push_back(NA); // Add to worklist for recursive processing } } // Now that we have created the alloca instructions that we want to use, // expand the getelementptr instructions to use them. // for (Value::use_iterator I = AI->use_begin(), E = AI->use_end(); I != E; ++I) { Instruction *User = cast<Instruction>(*I); if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) { // We now know that the GEP is of the form: GEP <ptr>, 0, <cst> uint64_t Idx; if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(GEPI->getOperand(2))) Idx = CSI->getValue(); else Idx = cast<ConstantUInt>(GEPI->getOperand(2))->getValue(); assert(Idx < ElementAllocas.size() && "Index out of range?"); AllocaInst *AllocaToUse = ElementAllocas[Idx]; Value *RepValue; if (GEPI->getNumOperands() == 3) { // Do not insert a new getelementptr instruction with zero indices, // only to have it optimized out later. RepValue = AllocaToUse; } else { // We are indexing deeply into the structure, so we still need a // getelement ptr instruction to finish the indexing. This may be // expanded itself once the worklist is rerun. // std::string OldName = GEPI->getName(); // Steal the old name... GEPI->setName(""); RepValue = new GetElementPtrInst(AllocaToUse, std::vector<Value*>(GEPI->op_begin()+3, GEPI->op_end()), OldName, GEPI); } // Move all of the users over to the new GEP. GEPI->replaceAllUsesWith(RepValue); // Delete the old GEP GEPI->getParent()->getInstList().erase(GEPI); } else { assert(0 && "Unexpected instruction type!"); } } // Finally, delete the Alloca instruction AI->getParent()->getInstList().erase(AI); NumReplaced++; } return Changed; } /// isSafeUseOfAllocation - Check to see if this user is an allowed use for an /// aggregate allocation. /// bool SROA::isSafeUseOfAllocation(Instruction *User) { if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) { // The GEP is safe to transform if it is of the form GEP <ptr>, 0, <cst> if (GEPI->getNumOperands() <= 2 || GEPI->getOperand(1) != Constant::getNullValue(Type::LongTy) || !isa<Constant>(GEPI->getOperand(2)) || isa<ConstantExpr>(GEPI->getOperand(2))) return false; } else { return false; } return true; } /// isSafeArrayElementUse - Check to see if this use is an allowed use for a /// getelementptr instruction of an array aggregate allocation. /// bool SROA::isSafeArrayElementUse(Value *Ptr) { for (Value::use_iterator I = Ptr->use_begin(), E = Ptr->use_end(); I != E; ++I) { Instruction *User = cast<Instruction>(*I); switch (User->getOpcode()) { case Instruction::Load: return true; case Instruction::Store: return User->getOperand(0) != Ptr; case Instruction::GetElementPtr: { GetElementPtrInst *GEP = cast<GetElementPtrInst>(User); if (GEP->getNumOperands() > 1) { if (!isa<Constant>(GEP->getOperand(1)) || !cast<Constant>(GEP->getOperand(1))->isNullValue()) return false; // Using pointer arithmetic to navigate the array... // Check to see if there are any structure indexes involved in this GEP. // If so, then we can safely break the array up until at least the // structure. for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i) if (GEP->getOperand(i)->getType()->isUnsigned()) break; } return isSafeArrayElementUse(GEP); } default: DEBUG(std::cerr << " Transformation preventing inst: " << *User); return false; } } return true; // All users look ok :) } /// isSafeStructAllocaToPromote - Check to see if the specified allocation of a /// structure can be broken down into elements. /// bool SROA::isSafeStructAllocaToPromote(AllocationInst *AI) { // Loop over the use list of the alloca. We can only transform it if all of // the users are safe to transform. // for (Value::use_iterator I = AI->use_begin(), E = AI->use_end(); I != E; ++I) if (!isSafeUseOfAllocation(cast<Instruction>(*I))) { DEBUG(std::cerr << "Cannot transform: " << *AI << " due to user: " << *I); return false; } return true; } /// isSafeArrayAllocaToPromote - Check to see if the specified allocation of a /// structure can be broken down into elements. /// bool SROA::isSafeArrayAllocaToPromote(AllocationInst *AI) { const ArrayType *AT = cast<ArrayType>(AI->getAllocatedType()); int64_t NumElements = AT->getNumElements(); // Loop over the use list of the alloca. We can only transform it if all of // the users are safe to transform. Array allocas have extra constraints to // meet though. // for (Value::use_iterator I = AI->use_begin(), E = AI->use_end(); I != E; ++I) { Instruction *User = cast<Instruction>(*I); if (!isSafeUseOfAllocation(User)) { DEBUG(std::cerr << "Cannot transform: " << *AI << " due to user: " << User); return false; } // Check to make sure that getelementptr follow the extra rules for arrays: if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) { // Check to make sure that index falls within the array. If not, // something funny is going on, so we won't do the optimization. // if (cast<ConstantSInt>(GEPI->getOperand(2))->getValue() >= NumElements) return false; // Check to make sure that the only thing that uses the resultant pointer // is safe for an array access. For example, code that looks like: // P = &A[0]; P = P + 1 // is legal, and should prevent promotion. // if (!isSafeArrayElementUse(GEPI)) { DEBUG(std::cerr << "Cannot transform: " << *AI << " due to uses of user: " << *GEPI); return false; } } } return true; } <|endoftext|>
<commit_before>// Copyright © 2017-2018 Dmitriy Khaustov // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // Author: Dmitriy Khaustov aka xDimon // Contacts: [email protected] // File created on: 2017.07.02 // Application.hpp #pragma once #include "../utils/Shareable.hpp" #include "../configs/Setting.hpp" #include <string> class Application : public Shareable<Application> { protected: std::string _type; std::string _appId; bool _isProduction; public: Application() = delete; Application(const Application&) = delete; Application& operator=(Application const&) = delete; Application(Application&&) noexcept = delete; Application& operator=(Application&&) noexcept = delete; explicit Application(const Setting& setting); ~Application() override = default; const std::string& type() const { return _type; } const std::string& appId() const { return _appId; } bool isProduction() const { return _isProduction; } }; #include "ApplicationFactory.hpp" #define REGISTER_APPLICATION(Type,Class) const Dummy Class::__dummy = \ ApplicationFactory::reg( \ #Type, \ [](const Setting& setting){ \ return std::shared_ptr<::Application>(new Class(setting)); \ } \ ); #define DECLARE_APPLICATION(Class) \ public: \ Class() = delete; \ Class(const Class&) = delete; \ Class& operator=(Class const&) = delete; \ Class(Class&&) noexcept = delete; \ Class& operator=(Class&&) noexcept = delete; \ ~Class() override = default; \ \ private: \ Class(const Setting& setting); \ \ private: \ static const Dummy __dummy; <commit_msg>Add type for id of Applications'<commit_after>// Copyright © 2017-2018 Dmitriy Khaustov // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // Author: Dmitriy Khaustov aka xDimon // Contacts: [email protected] // File created on: 2017.07.02 // Application.hpp #pragma once #include "../utils/Shareable.hpp" #include "../configs/Setting.hpp" #include <string> class Application : public Shareable<Application> { public: typedef std::string Type; typedef std::string Id; protected: Type _type; Id _appId; bool _isProduction; public: Application() = delete; Application(const Application&) = delete; Application& operator=(Application const&) = delete; Application(Application&&) noexcept = delete; Application& operator=(Application&&) noexcept = delete; explicit Application(const Setting& setting); ~Application() override = default; const Type& type() const { return _type; } const Id& appId() const { return _appId; } bool isProduction() const { return _isProduction; } }; #include "ApplicationFactory.hpp" #define REGISTER_APPLICATION(Type,Class) const Dummy Class::__dummy = \ ApplicationFactory::reg( \ #Type, \ [](const Setting& setting){ \ return std::shared_ptr<::Application>(new Class(setting)); \ } \ ); #define DECLARE_APPLICATION(Class) \ public: \ Class() = delete; \ Class(const Class&) = delete; \ Class& operator=(Class const&) = delete; \ Class(Class&&) noexcept = delete; \ Class& operator=(Class&&) noexcept = delete; \ ~Class() override = default; \ \ private: \ Class(const Setting& setting); \ \ private: \ static const Dummy __dummy; <|endoftext|>
<commit_before>#include "pch.h" #include "MyPropertyPage.h" #include "DspMatrix.h" namespace SaneAudioRenderer { namespace { void Write(std::vector<char>& out, void* src, size_t size) { assert(src); assert(size > 0); out.insert(out.end(), size, 0); memcpy(&out[out.size() - size], src, size); } template <typename T> void Write(std::vector<char>& out, T t) { Write(out, &t, sizeof(T)); } void WriteString(std::vector<char>& out, const std::wstring& str) { Write(out, (void*)str.c_str(), sizeof(wchar_t) * (str.length() + 1)); } void WriteDialogHeader(std::vector<char>& out, const std::wstring& font, WORD fontSize) { assert(out.empty()); Write<DWORD>(out, DS_SETFONT | DS_FIXEDSYS | WS_CHILD); Write<DWORD>(out, 0); Write<WORD>(out, 0); Write<short>(out, 0); Write<short>(out, 0); Write<short>(out, 0); Write<short>(out, 0); Write<WORD>(out, 0); Write<WORD>(out, 0); WriteString(out, L""); Write<WORD>(out, fontSize); WriteString(out, font); } void WriteDialogItem(std::vector<char>& out, DWORD style, DWORD control, short x, short y, short w, short h, const std::wstring& text) { assert(!out.empty()); if (out.size() % 4) out.insert(out.end(), out.size() % 4, 0); Write<DWORD>(out, style | WS_CHILD | WS_VISIBLE); Write<DWORD>(out, 0); Write<short>(out, x); Write<short>(out, y); Write<short>(out, w); Write<short>(out, h); Write<WORD>(out, 0); Write<DWORD>(out, control); WriteString(out, text); Write<WORD>(out, 0); *(WORD*)(&out[8]) += 1; } std::wstring GetFormatString(const WAVEFORMATEX& format) { DspFormat dspFormat = DspFormatFromWaveFormat(format); const WAVEFORMATEXTENSIBLE* pFormatExt = (format.wFormatTag == WAVE_FORMAT_EXTENSIBLE) ? reinterpret_cast<const WAVEFORMATEXTENSIBLE*>(&format) : nullptr; bool pcm24in32 = (dspFormat == DspFormat::Pcm32 && pFormatExt && pFormatExt->Samples.wValidBitsPerSample == 24); switch (dspFormat) { case DspFormat::Pcm8: return L"PCM-8"; case DspFormat::Pcm16: return L"PCM-16"; case DspFormat::Pcm24: return L"PCM-24"; case DspFormat::Pcm32: return pcm24in32 ? L"PCM-24 (Padded)" : L"PCM-32"; case DspFormat::Float: return L"Float"; case DspFormat::Double: return L"Double"; } assert(dspFormat == DspFormat::Unknown); if (format.wFormatTag == WAVE_FORMAT_DOLBY_AC3_SPDIF) return L"AC3/DTS"; if (pFormatExt) { if (pFormatExt->SubFormat == KSDATAFORMAT_SUBTYPE_IEC61937_DTS_HD) return L"DTS-HD"; if (pFormatExt->SubFormat == KSDATAFORMAT_SUBTYPE_IEC61937_DOLBY_MLP) return L"TrueHD"; if (pFormatExt->SubFormat == KSDATAFORMAT_SUBTYPE_IEC61937_WMA_PRO) return L"WMA Pro"; } return L"Unknown"; } } MyPropertyPage::MyPropertyPage(SharedWaveFormat inputFormat, AudioDevice const* pDevice, std::vector<std::wstring> processors) : CUnknown(L"SaneAudioRenderer::MyPropertyPage", nullptr) { std::wstring adapterField = (pDevice && pDevice->GetAdapterName()) ? *pDevice->GetAdapterName() : L"-"; std::wstring endpointField = (pDevice && pDevice->GetEndpointName()) ? *pDevice->GetEndpointName() : L"-"; std::wstring exclusiveField = (pDevice ? (pDevice->IsExclusive() ? L"Yes" : L"No") : L"-"); std::wstring bufferField = (pDevice ? std::to_wstring(pDevice->GetBufferDuration()) + L"ms" : L"-"); std::wstring bitstreamingField = (inputFormat ? (DspFormatFromWaveFormat(*inputFormat) == DspFormat::Unknown ? L"Yes" : L"No") : L"-"); std::wstring externalClockField = L"N/A"; std::wstring channelsInputField = (inputFormat ? std::to_wstring(inputFormat->nChannels) + L" (" + GetHexString(DspMatrix::GetChannelMask(*inputFormat)) + L")" : L"-"); std::wstring channelsDeviceField = (pDevice ? std::to_wstring(pDevice->GetWaveFormat()->nChannels) + L" (" + GetHexString(DspMatrix::GetChannelMask(*pDevice->GetWaveFormat())) + L")" : L"-"); std::wstring channelsField = (channelsInputField == channelsDeviceField) ? channelsInputField : channelsInputField + L" -> " + channelsDeviceField; std::wstring formatInputField = (inputFormat ? GetFormatString(*inputFormat) : L"-"); std::wstring formatDeviceField = (pDevice ? GetFormatString(*pDevice->GetWaveFormat()) : L"-"); std::wstring formatField = (formatInputField == formatDeviceField) ? formatInputField : formatInputField + L" -> " + formatDeviceField; std::wstring rateInputField = (inputFormat ? std::to_wstring(inputFormat->nSamplesPerSec) : L"-"); std::wstring rateDeviceField = (pDevice ? std::to_wstring(pDevice->GetWaveFormat()->nSamplesPerSec) : L"-"); std::wstring rateField = (rateInputField == rateDeviceField) ? rateInputField : rateInputField + L" -> " + rateDeviceField; std::wstring processorsField; for (const auto& s : processors) { if (!processorsField.empty()) processorsField += L", "; processorsField += s; } if (processorsField.empty()) processorsField = L"-"; WriteDialogHeader(m_dialogData, L"MS Shell Dlg", 8); WriteDialogItem(m_dialogData, BS_GROUPBOX, 0x0080FFFF, 5, 5, 200, 150, L"Renderer Status"); WriteDialogItem(m_dialogData, BS_TEXT | SS_RIGHT, 0x0082FFFF, 10, 20, 60, 8, L"Adapter:"); WriteDialogItem(m_dialogData, BS_TEXT | SS_LEFT, 0x0082FFFF, 73, 20, 120, 8, adapterField); WriteDialogItem(m_dialogData, BS_TEXT | SS_RIGHT, 0x0082FFFF, 10, 32, 60, 8, L"Endpoint:"); WriteDialogItem(m_dialogData, BS_TEXT | SS_LEFT, 0x0082FFFF, 73, 32, 120, 8, endpointField); WriteDialogItem(m_dialogData, BS_TEXT | SS_RIGHT, 0x0082FFFF, 10, 44, 60, 8, L"Exclusive:"); WriteDialogItem(m_dialogData, BS_TEXT | SS_LEFT, 0x0082FFFF, 73, 44, 120, 8, exclusiveField); WriteDialogItem(m_dialogData, BS_TEXT | SS_RIGHT, 0x0082FFFF, 10, 56, 60, 8, L"Buffer:"); WriteDialogItem(m_dialogData, BS_TEXT | SS_LEFT, 0x0082FFFF, 73, 56, 120, 8, bufferField); WriteDialogItem(m_dialogData, BS_TEXT | SS_RIGHT, 0x0082FFFF, 10, 68, 60, 8, L"Bitstreaming:"); WriteDialogItem(m_dialogData, BS_TEXT | SS_LEFT, 0x0082FFFF, 73, 68, 120, 8, bitstreamingField); WriteDialogItem(m_dialogData, BS_TEXT | SS_RIGHT, 0x0082FFFF, 10, 80, 60, 8, L"External Clock:"); WriteDialogItem(m_dialogData, BS_TEXT | SS_LEFT, 0x0082FFFF, 73, 80, 120, 8, externalClockField); WriteDialogItem(m_dialogData, BS_TEXT | SS_RIGHT, 0x0082FFFF, 10, 92, 60, 8, L"Format:"); WriteDialogItem(m_dialogData, BS_TEXT | SS_LEFT, 0x0082FFFF, 73, 92, 120, 8, formatField); WriteDialogItem(m_dialogData, BS_TEXT | SS_RIGHT, 0x0082FFFF, 10, 104, 60, 8, L"Channels:"); WriteDialogItem(m_dialogData, BS_TEXT | SS_LEFT, 0x0082FFFF, 73, 104, 120, 8, channelsField); WriteDialogItem(m_dialogData, BS_TEXT | SS_RIGHT, 0x0082FFFF, 10, 116, 60, 8, L"Rate:"); WriteDialogItem(m_dialogData, BS_TEXT | SS_LEFT, 0x0082FFFF, 73, 116, 120, 8, rateField); WriteDialogItem(m_dialogData, BS_TEXT | SS_RIGHT, 0x0082FFFF, 10, 128, 60, 8, L"Processors:"); WriteDialogItem(m_dialogData, BS_TEXT | SS_LEFT, 0x0082FFFF, 73, 128, 120, 24, processorsField); } STDMETHODIMP MyPropertyPage::NonDelegatingQueryInterface(REFIID riid, void** ppv) { return (riid == __uuidof(IPropertyPage)) ? GetInterface(static_cast<IPropertyPage*>(this), ppv) : CUnknown::NonDelegatingQueryInterface(riid, ppv); } STDMETHODIMP MyPropertyPage::SetPageSite(IPropertyPageSite* pPageSite) { if (!m_pageSite && !pPageSite) return E_UNEXPECTED; m_pageSite = nullptr; CheckPointer(pPageSite, S_OK); return pPageSite->QueryInterface(IID_PPV_ARGS(&m_pageSite)); } STDMETHODIMP MyPropertyPage::Activate(HWND hParent, LPCRECT pRect, BOOL bModal) { CheckPointer(pRect, E_POINTER); m_hWindow = CreateDialogIndirect(GetModuleHandle(nullptr), (LPCDLGTEMPLATE)m_dialogData.data(), hParent, nullptr); return (m_hWindow != NULL) ? S_OK : E_UNEXPECTED; } STDMETHODIMP MyPropertyPage::Deactivate() { DestroyWindow(m_hWindow); m_hWindow = NULL; return S_OK; } STDMETHODIMP MyPropertyPage::GetPageInfo(PROPPAGEINFO* pPageInfo) { CheckPointer(pPageInfo, E_POINTER); pPageInfo->cb = sizeof(PROPPAGEINFO); const wchar_t title[] = L"Status"; pPageInfo->pszTitle = (LPOLESTR)CoTaskMemAlloc(sizeof(title)); CheckPointer(pPageInfo->pszTitle, E_OUTOFMEMORY); memcpy(pPageInfo->pszTitle, title, sizeof(title)); pPageInfo->size = {0, 0}; pPageInfo->pszDocString = nullptr; pPageInfo->pszHelpFile = nullptr; pPageInfo->dwHelpContext = 0; return S_OK; } STDMETHODIMP MyPropertyPage::Show(UINT cmdShow) { ShowWindow(m_hWindow, cmdShow); return S_OK; } STDMETHODIMP MyPropertyPage::Move(LPCRECT pRect) { MoveWindow(m_hWindow, pRect->left, pRect->top, pRect->right - pRect->left, pRect->bottom - pRect->top, TRUE); return S_OK; } } <commit_msg>Add "Rate Matching" field to MyPropertyPage<commit_after>#include "pch.h" #include "MyPropertyPage.h" #include "DspMatrix.h" namespace SaneAudioRenderer { namespace { void Write(std::vector<char>& out, void* src, size_t size) { assert(src); assert(size > 0); out.insert(out.end(), size, 0); memcpy(&out[out.size() - size], src, size); } template <typename T> void Write(std::vector<char>& out, T t) { Write(out, &t, sizeof(T)); } void WriteString(std::vector<char>& out, const std::wstring& str) { Write(out, (void*)str.c_str(), sizeof(wchar_t) * (str.length() + 1)); } void WriteDialogHeader(std::vector<char>& out, const std::wstring& font, WORD fontSize) { assert(out.empty()); Write<DWORD>(out, DS_SETFONT | DS_FIXEDSYS | WS_CHILD); Write<DWORD>(out, 0); Write<WORD>(out, 0); Write<short>(out, 0); Write<short>(out, 0); Write<short>(out, 0); Write<short>(out, 0); Write<WORD>(out, 0); Write<WORD>(out, 0); WriteString(out, L""); Write<WORD>(out, fontSize); WriteString(out, font); } void WriteDialogItem(std::vector<char>& out, DWORD style, DWORD control, short x, short y, short w, short h, const std::wstring& text) { assert(!out.empty()); if (out.size() % 4) out.insert(out.end(), out.size() % 4, 0); Write<DWORD>(out, style | WS_CHILD | WS_VISIBLE); Write<DWORD>(out, 0); Write<short>(out, x); Write<short>(out, y); Write<short>(out, w); Write<short>(out, h); Write<WORD>(out, 0); Write<DWORD>(out, control); WriteString(out, text); Write<WORD>(out, 0); *(WORD*)(&out[8]) += 1; } std::wstring GetFormatString(const WAVEFORMATEX& format) { DspFormat dspFormat = DspFormatFromWaveFormat(format); const WAVEFORMATEXTENSIBLE* pFormatExt = (format.wFormatTag == WAVE_FORMAT_EXTENSIBLE) ? reinterpret_cast<const WAVEFORMATEXTENSIBLE*>(&format) : nullptr; bool pcm24in32 = (dspFormat == DspFormat::Pcm32 && pFormatExt && pFormatExt->Samples.wValidBitsPerSample == 24); switch (dspFormat) { case DspFormat::Pcm8: return L"PCM-8"; case DspFormat::Pcm16: return L"PCM-16"; case DspFormat::Pcm24: return L"PCM-24"; case DspFormat::Pcm32: return pcm24in32 ? L"PCM-24 (Padded)" : L"PCM-32"; case DspFormat::Float: return L"Float"; case DspFormat::Double: return L"Double"; } assert(dspFormat == DspFormat::Unknown); if (format.wFormatTag == WAVE_FORMAT_DOLBY_AC3_SPDIF) return L"AC3/DTS"; if (pFormatExt) { if (pFormatExt->SubFormat == KSDATAFORMAT_SUBTYPE_IEC61937_DTS_HD) return L"DTS-HD"; if (pFormatExt->SubFormat == KSDATAFORMAT_SUBTYPE_IEC61937_DOLBY_MLP) return L"TrueHD"; if (pFormatExt->SubFormat == KSDATAFORMAT_SUBTYPE_IEC61937_WMA_PRO) return L"WMA Pro"; } return L"Unknown"; } } MyPropertyPage::MyPropertyPage(SharedWaveFormat inputFormat, AudioDevice const* pDevice, std::vector<std::wstring> processors) : CUnknown(L"SaneAudioRenderer::MyPropertyPage", nullptr) { std::wstring adapterField = (pDevice && pDevice->GetAdapterName()) ? *pDevice->GetAdapterName() : L"-"; std::wstring endpointField = (pDevice && pDevice->GetEndpointName()) ? *pDevice->GetEndpointName() : L"-"; std::wstring exclusiveField = (pDevice ? (pDevice->IsExclusive() ? L"Yes" : L"No") : L"-"); std::wstring bufferField = (pDevice ? std::to_wstring(pDevice->GetBufferDuration()) + L"ms" : L"-"); std::wstring bitstreamingField = (inputFormat ? (DspFormatFromWaveFormat(*inputFormat) == DspFormat::Unknown ? L"Yes" : L"No") : L"-"); std::wstring rateMatchingField = (pDevice && pDevice->IsLive()) ? L"Yes" : L"No"; std::wstring channelsInputField = (inputFormat ? std::to_wstring(inputFormat->nChannels) + L" (" + GetHexString(DspMatrix::GetChannelMask(*inputFormat)) + L")" : L"-"); std::wstring channelsDeviceField = (pDevice ? std::to_wstring(pDevice->GetWaveFormat()->nChannels) + L" (" + GetHexString(DspMatrix::GetChannelMask(*pDevice->GetWaveFormat())) + L")" : L"-"); std::wstring channelsField = (channelsInputField == channelsDeviceField) ? channelsInputField : channelsInputField + L" -> " + channelsDeviceField; std::wstring formatInputField = (inputFormat ? GetFormatString(*inputFormat) : L"-"); std::wstring formatDeviceField = (pDevice ? GetFormatString(*pDevice->GetWaveFormat()) : L"-"); std::wstring formatField = (formatInputField == formatDeviceField) ? formatInputField : formatInputField + L" -> " + formatDeviceField; std::wstring rateInputField = (inputFormat ? std::to_wstring(inputFormat->nSamplesPerSec) : L"-"); std::wstring rateDeviceField = (pDevice ? std::to_wstring(pDevice->GetWaveFormat()->nSamplesPerSec) : L"-"); std::wstring rateField = (rateInputField == rateDeviceField) ? rateInputField : rateInputField + L" -> " + rateDeviceField; std::wstring processorsField; for (const auto& s : processors) { if (!processorsField.empty()) processorsField += L", "; processorsField += s; } if (processorsField.empty()) processorsField = L"-"; WriteDialogHeader(m_dialogData, L"MS Shell Dlg", 8); WriteDialogItem(m_dialogData, BS_GROUPBOX, 0x0080FFFF, 5, 5, 200, 150, L"Renderer Status"); WriteDialogItem(m_dialogData, BS_TEXT | SS_RIGHT, 0x0082FFFF, 10, 20, 60, 8, L"Adapter:"); WriteDialogItem(m_dialogData, BS_TEXT | SS_LEFT, 0x0082FFFF, 73, 20, 120, 8, adapterField); WriteDialogItem(m_dialogData, BS_TEXT | SS_RIGHT, 0x0082FFFF, 10, 32, 60, 8, L"Endpoint:"); WriteDialogItem(m_dialogData, BS_TEXT | SS_LEFT, 0x0082FFFF, 73, 32, 120, 8, endpointField); WriteDialogItem(m_dialogData, BS_TEXT | SS_RIGHT, 0x0082FFFF, 10, 44, 60, 8, L"Exclusive:"); WriteDialogItem(m_dialogData, BS_TEXT | SS_LEFT, 0x0082FFFF, 73, 44, 120, 8, exclusiveField); WriteDialogItem(m_dialogData, BS_TEXT | SS_RIGHT, 0x0082FFFF, 10, 56, 60, 8, L"Buffer:"); WriteDialogItem(m_dialogData, BS_TEXT | SS_LEFT, 0x0082FFFF, 73, 56, 120, 8, bufferField); WriteDialogItem(m_dialogData, BS_TEXT | SS_RIGHT, 0x0082FFFF, 10, 68, 60, 8, L"Bitstreaming:"); WriteDialogItem(m_dialogData, BS_TEXT | SS_LEFT, 0x0082FFFF, 73, 68, 120, 8, bitstreamingField); WriteDialogItem(m_dialogData, BS_TEXT | SS_RIGHT, 0x0082FFFF, 10, 80, 60, 8, L"Rate Matching:"); WriteDialogItem(m_dialogData, BS_TEXT | SS_LEFT, 0x0082FFFF, 73, 80, 120, 8, rateMatchingField); WriteDialogItem(m_dialogData, BS_TEXT | SS_RIGHT, 0x0082FFFF, 10, 92, 60, 8, L"Format:"); WriteDialogItem(m_dialogData, BS_TEXT | SS_LEFT, 0x0082FFFF, 73, 92, 120, 8, formatField); WriteDialogItem(m_dialogData, BS_TEXT | SS_RIGHT, 0x0082FFFF, 10, 104, 60, 8, L"Channels:"); WriteDialogItem(m_dialogData, BS_TEXT | SS_LEFT, 0x0082FFFF, 73, 104, 120, 8, channelsField); WriteDialogItem(m_dialogData, BS_TEXT | SS_RIGHT, 0x0082FFFF, 10, 116, 60, 8, L"Rate:"); WriteDialogItem(m_dialogData, BS_TEXT | SS_LEFT, 0x0082FFFF, 73, 116, 120, 8, rateField); WriteDialogItem(m_dialogData, BS_TEXT | SS_RIGHT, 0x0082FFFF, 10, 128, 60, 8, L"Processors:"); WriteDialogItem(m_dialogData, BS_TEXT | SS_LEFT, 0x0082FFFF, 73, 128, 120, 24, processorsField); } STDMETHODIMP MyPropertyPage::NonDelegatingQueryInterface(REFIID riid, void** ppv) { return (riid == __uuidof(IPropertyPage)) ? GetInterface(static_cast<IPropertyPage*>(this), ppv) : CUnknown::NonDelegatingQueryInterface(riid, ppv); } STDMETHODIMP MyPropertyPage::SetPageSite(IPropertyPageSite* pPageSite) { if (!m_pageSite && !pPageSite) return E_UNEXPECTED; m_pageSite = nullptr; CheckPointer(pPageSite, S_OK); return pPageSite->QueryInterface(IID_PPV_ARGS(&m_pageSite)); } STDMETHODIMP MyPropertyPage::Activate(HWND hParent, LPCRECT pRect, BOOL bModal) { CheckPointer(pRect, E_POINTER); m_hWindow = CreateDialogIndirect(GetModuleHandle(nullptr), (LPCDLGTEMPLATE)m_dialogData.data(), hParent, nullptr); return (m_hWindow != NULL) ? S_OK : E_UNEXPECTED; } STDMETHODIMP MyPropertyPage::Deactivate() { DestroyWindow(m_hWindow); m_hWindow = NULL; return S_OK; } STDMETHODIMP MyPropertyPage::GetPageInfo(PROPPAGEINFO* pPageInfo) { CheckPointer(pPageInfo, E_POINTER); pPageInfo->cb = sizeof(PROPPAGEINFO); const wchar_t title[] = L"Status"; pPageInfo->pszTitle = (LPOLESTR)CoTaskMemAlloc(sizeof(title)); CheckPointer(pPageInfo->pszTitle, E_OUTOFMEMORY); memcpy(pPageInfo->pszTitle, title, sizeof(title)); pPageInfo->size = {0, 0}; pPageInfo->pszDocString = nullptr; pPageInfo->pszHelpFile = nullptr; pPageInfo->dwHelpContext = 0; return S_OK; } STDMETHODIMP MyPropertyPage::Show(UINT cmdShow) { ShowWindow(m_hWindow, cmdShow); return S_OK; } STDMETHODIMP MyPropertyPage::Move(LPCRECT pRect) { MoveWindow(m_hWindow, pRect->left, pRect->top, pRect->right - pRect->left, pRect->bottom - pRect->top, TRUE); return S_OK; } } <|endoftext|>
<commit_before>#include <iostream> using namespace std; int main() { int x, y; cin >> x; if (x >= y) {cout << x;} else {cout << y; } return 0; }<commit_msg>Delete task21.cpp<commit_after><|endoftext|>