<commit_before>#ifndef GLM_FORCE_RADIANS
#define GLM_FORCE_RADIANS
#define DEGREES_TO_RADIANS(x) (x * PI / 180.0f)
#endif

#include "ascii_grid_loader.hpp"
#include "code/ylikuutio/triangulation/quad_triangulation.hpp"
#include "code/ylikuutio/string/ylikuutio_string.hpp"
#include "code/ylikuutio/common/globals.hpp"
#include "code/ylikuutio/common/global_variables.hpp"

// Include GLM
#ifndef __GLM_GLM_HPP_INCLUDED
#define __GLM_GLM_HPP_INCLUDED
#include <glm/glm.hpp> // glm
#endif

// Include standard headers
#include <cmath>    // NAN, std::isnan, std::pow
#include <cstdio>   // std::FILE, std::fclose, std::fopen, std::fread, std::getchar, std::printf etc.
#include <iostream> // std::cout, std::cin, std::cerr
#include <stdint.h> // uint32_t etc.
#include <string>   // std::string, std::stoi
#include <vector>   // std::vector

namespace loaders
{
    bool load_ascii_grid(
            std::string ascii_grid_file_name,
            std::vector<glm::vec3>& out_vertices,
            std::vector<glm::vec2>& out_UVs,
            std::vector<glm::vec3>& out_normals,
            std::string triangulation_type)
    {
        // Beginning of `L4133D.asc`.
        //
        // ncols        3000
        // nrows        3000
        // xllcorner    386000.000000000000
        // yllcorner    6672000.000000000000
        // cellsize     2.000000000000
        // NODATA_value  -9999.000
        // 34.315 34.467 34.441 34.260 33.972 33.564 33.229 33.130 33.102 33.024 32.902 32.669 32.305 32.013 31.937 31.893 31.831 31.832

        std::cout << "Loading ascii grid file " << ascii_grid_file_name << " ...\n";

        // Open the file
        const char* char_ascii_grid_file_name = ascii_grid_file_name.c_str();
        std::FILE* file = std::fopen(char_ascii_grid_file_name, "rb");
        if (!file)
        {
            std::cerr << ascii_grid_file_name << " could not be opened.\n";
            return false;
        }

        // Find out file size.
        if (std::fseek(file, 0, SEEK_END) != 0)
        {
            std::cerr << "moving file pointer of file " << ascii_grid_file_name << " failed!\n";
            std::fclose(file);
            return false;
        }

        uint64_t file_size = std::ftell(file);

        // Move file pointer to the beginning of file.
        if (fseek(file, 0, SEEK_SET) != 0)
        {
            std::cerr << "moving file pointer of file " << ascii_grid_file_name << " failed!\n";
            std::fclose(file);
            return false;
        }

        // Reserve enough memory.
        char* point_data = new char[file_size];

        if (point_data == nullptr)
        {
            std::cerr << "Reserving memory for point data failed.\n";
            std::fclose(file);
            return false;
        }

        char* point_data_pointer = point_data;

        // Read the point data from the file into the buffer.
        std::fread(point_data, 1, file_size, file);

        // Everything is in memory now, the file can be closed
        std::fclose(file);

        // All possible block identifier strings.
        std::vector<std::string> number_strings_vector = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };

        while (!string::check_and_report_if_some_string_matches(point_data, point_data_pointer, number_strings_vector))
        {
            point_data_pointer++;
        }
        int32_t image_width = string::extract_int32_t_value_from_string(point_data_pointer, (char*) " \n", (const char*) "ncols");

        while (!string::check_and_report_if_some_string_matches(point_data, point_data_pointer, number_strings_vector))
        {
            point_data_pointer++;
        }
        int32_t image_height = string::extract_int32_t_value_from_string(point_data_pointer, (char*) " \n", (const char*) "nrows");

        while (!string::check_and_report_if_some_string_matches(point_data, point_data_pointer, number_strings_vector))
        {
            point_data_pointer++;
        }
        float xllcorner = string::extract_float_value_from_string(point_data_pointer, (char*) " \n", (const char*) "xllcorner");

        while (!string::check_and_report_if_some_string_matches(point_data, point_data_pointer, number_strings_vector))
        {
            point_data_pointer++;
        }
        float yllcorner = string::extract_float_value_from_string(point_data_pointer, (char*) " \n", (const char*) "yllcorner");

        while (!string::check_and_report_if_some_string_matches(point_data, point_data_pointer, number_strings_vector))
        {
            point_data_pointer++;
        }
        float cellsize = string::extract_float_value_from_string(point_data_pointer, (char*) " \n", (const char*) "cellsize");

        while (!string::check_and_report_if_some_string_matches(point_data, point_data_pointer, number_strings_vector))
        {
            point_data_pointer++;
        }
        float nodata_value = string::extract_float_value_from_string(point_data_pointer, (char*) " \n", (const char*) "nodata_value");

        uint32_t image_width_in_use = 3000; // should be 3000.
        uint32_t image_height_in_use = 2000;

        float* vertex_data;
        vertex_data = new float[image_width_in_use * image_height_in_use];

        if (vertex_data == nullptr)
        {
            std::cerr << "Reserving memory for vertex data failed.\n";
            delete point_data;
            return false;
        }

        float* vertex_pointer;
        vertex_pointer = vertex_data;

        // start processing image_data.

        for (uint32_t z = 0; z < image_height_in_use; z++)
        {
            for (uint32_t x = 0; x < image_width_in_use; x++)
            {
                while (!string::check_and_report_if_some_string_matches(point_data, point_data_pointer, number_strings_vector))
                {
                    point_data_pointer++;
                }
                *vertex_pointer++ = string::extract_float_value_from_string(point_data_pointer, (char*) " \n", (const char*) nullptr);
            }
        }

        delete point_data;

        std::cout << "Triangulating ascii grid data.\n";

        TriangulateQuadsStruct triangulate_quads_struct;
        // triangulate_quads_struct.image_width = image_width;
        triangulate_quads_struct.image_width = image_width_in_use;
        triangulate_quads_struct.image_height = image_height_in_use;
        triangulate_quads_struct.triangulation_type = triangulation_type;
        triangulate_quads_struct.sphere_radius = NAN;
        triangulate_quads_struct.spherical_world_struct = SphericalWorldStruct(); // not used, but is needed in the function call.

        bool result = geometry::triangulate_quads(vertex_data, triangulate_quads_struct, out_vertices, out_UVs, out_normals);
        delete vertex_data;
        return true;
    }
}
<commit_msg>Bugfix: Read image width (`ncols` in `*.asc` file) correctly.<commit_after>#ifndef GLM_FORCE_RADIANS
#define GLM_FORCE_RADIANS
#define DEGREES_TO_RADIANS(x) (x * PI / 180.0f)
#endif

#include "ascii_grid_loader.hpp"
#include "code/ylikuutio/triangulation/quad_triangulation.hpp"
#include "code/ylikuutio/string/ylikuutio_string.hpp"
#include "code/ylikuutio/common/globals.hpp"
#include "code/ylikuutio/common/global_variables.hpp"

// Include GLM
#ifndef __GLM_GLM_HPP_INCLUDED
#define __GLM_GLM_HPP_INCLUDED
#include <glm/glm.hpp> // glm
#endif

// Include standard headers
#include <cmath>    // NAN, std::isnan, std::pow
#include <cstdio>   // std::FILE, std::fclose, std::fopen, std::fread, std::getchar, std::printf etc.
#include <iostream> // std::cout, std::cin, std::cerr
#include <stdint.h> // uint32_t etc.
#include <string>   // std::string, std::stoi
#include <vector>   // std::vector

namespace loaders
{
    bool load_ascii_grid(
            std::string ascii_grid_file_name,
            std::vector<glm::vec3>& out_vertices,
            std::vector<glm::vec2>& out_UVs,
            std::vector<glm::vec3>& out_normals,
            std::string triangulation_type)
    {
        // Beginning of `L4133D.asc`.
        //
        // ncols        3000
        // nrows        3000
        // xllcorner    386000.000000000000
        // yllcorner    6672000.000000000000
        // cellsize     2.000000000000
        // NODATA_value  -9999.000
        // 34.315 34.467 34.441 34.260 33.972 33.564 33.229 33.130 33.102 33.024 32.902 32.669 32.305 32.013 31.937 31.893 31.831 31.832

        std::cout << "Loading ascii grid file " << ascii_grid_file_name << " ...\n";

        // Open the file
        const char* char_ascii_grid_file_name = ascii_grid_file_name.c_str();
        std::FILE* file = std::fopen(char_ascii_grid_file_name, "rb");
        if (!file)
        {
            std::cerr << ascii_grid_file_name << " could not be opened.\n";
            return false;
        }

        // Find out file size.
        if (std::fseek(file, 0, SEEK_END) != 0)
        {
            std::cerr << "moving file pointer of file " << ascii_grid_file_name << " failed!\n";
            std::fclose(file);
            return false;
        }

        uint64_t file_size = std::ftell(file);

        // Move file pointer to the beginning of file.
        if (fseek(file, 0, SEEK_SET) != 0)
        {
            std::cerr << "moving file pointer of file " << ascii_grid_file_name << " failed!\n";
            std::fclose(file);
            return false;
        }

        // Reserve enough memory.
        char* point_data = new char[file_size];

        if (point_data == nullptr)
        {
            std::cerr << "Reserving memory for point data failed.\n";
            std::fclose(file);
            return false;
        }

        char* point_data_pointer = point_data;

        // Read the point data from the file into the buffer.
        std::fread(point_data, 1, file_size, file);

        // Everything is in memory now, the file can be closed
        std::fclose(file);

        // All possible block identifier strings.
        std::vector<std::string> number_strings_vector = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };

        while (!string::check_and_report_if_some_string_matches(point_data, point_data_pointer, number_strings_vector))
        {
            point_data_pointer++;
        }
        int32_t image_width = string::extract_int32_t_value_from_string(--point_data_pointer, (char*) " \n", (const char*) "ncols");

        while (!string::check_and_report_if_some_string_matches(point_data, point_data_pointer, number_strings_vector))
        {
            point_data_pointer++;
        }
        int32_t image_height = string::extract_int32_t_value_from_string(point_data_pointer, (char*) " \n", (const char*) "nrows");

        while (!string::check_and_report_if_some_string_matches(point_data, point_data_pointer, number_strings_vector))
        {
            point_data_pointer++;
        }
        float xllcorner = string::extract_float_value_from_string(point_data_pointer, (char*) " \n", (const char*) "xllcorner");

        while (!string::check_and_report_if_some_string_matches(point_data, point_data_pointer, number_strings_vector))
        {
            point_data_pointer++;
        }
        float yllcorner = string::extract_float_value_from_string(point_data_pointer, (char*) " \n", (const char*) "yllcorner");

        while (!string::check_and_report_if_some_string_matches(point_data, point_data_pointer, number_strings_vector))
        {
            point_data_pointer++;
        }
        float cellsize = string::extract_float_value_from_string(point_data_pointer, (char*) " \n", (const char*) "cellsize");

        while (!string::check_and_report_if_some_string_matches(point_data, point_data_pointer, number_strings_vector))
        {
            point_data_pointer++;
        }
        float nodata_value = string::extract_float_value_from_string(point_data_pointer, (char*) " \n", (const char*) "nodata_value");

        uint32_t image_width_in_use = 3000; // should be 3000.
        uint32_t image_height_in_use = 2000;

        float* vertex_data;
        vertex_data = new float[image_width_in_use * image_height_in_use];

        if (vertex_data == nullptr)
        {
            std::cerr << "Reserving memory for vertex data failed.\n";
            delete point_data;
            return false;
        }

        float* vertex_pointer;
        vertex_pointer = vertex_data;

        // start processing image_data.

        for (uint32_t z = 0; z < image_height_in_use; z++)
        {
            for (uint32_t x = 0; x < image_width_in_use; x++)
            {
                while (!string::check_and_report_if_some_string_matches(point_data, point_data_pointer, number_strings_vector))
                {
                    point_data_pointer++;
                }
                *vertex_pointer++ = string::extract_float_value_from_string(point_data_pointer, (char*) " \n", (const char*) nullptr);
            }
        }

        delete point_data;

        std::cout << "Triangulating ascii grid data.\n";

        TriangulateQuadsStruct triangulate_quads_struct;
        // triangulate_quads_struct.image_width = image_width;
        triangulate_quads_struct.image_width = image_width_in_use;
        triangulate_quads_struct.image_height = image_height_in_use;
        triangulate_quads_struct.triangulation_type = triangulation_type;
        triangulate_quads_struct.sphere_radius = NAN;
        triangulate_quads_struct.spherical_world_struct = SphericalWorldStruct(); // not used, but is needed in the function call.

        bool result = geometry::triangulate_quads(vertex_data, triangulate_quads_struct, out_vertices, out_UVs, out_normals);
        delete vertex_data;
        return true;
    }
}
<|endoftext|>


<commit_before>#include <boost/format.hpp>

#include <string>

static boost::format ENVELOPE_FORMAT {
    "{  \"id\" : %1%,"
    "   \"message_type\" : %2%,"
    "   \"expires\" : %3%,"
    "   \"targets\" : [\"client_1\", \"client_2\"],"
    "   \"sender\" : %4%,"
    "   \"destination_report\" : false"
    "}"
};

static boost::format DATA_FORMAT {
    "{  \"transaction_id\" : %1%,"
    "   \"module\" : %2%,"
    "   \"action\" : %3%,"
    "   \"params\" : %4%"
    "}"
};

static boost::format NON_BLOCKING_DATA_FORMAT {
    "{  \"transaction_id\" : %1%,"
    "   \"module\" : %2%,"
    "   \"action\" : %3%,"
    "   \"params\" : %4%,"
    "   \"notify_outcome\" : %5%"
    "}"
};

static const std::string ENVELOPE_TXT {
    (ENVELOPE_FORMAT % "\"123456\""
                     % "\"test_message\""
                     % "\"2015-06-26T22:57:09Z\""
                     % "\"pcp://controller/test_controller\"").str() };
<commit_msg>(maint) Remove unused header from tests directory<commit_after><|endoftext|>


<commit_before>/*=====================================================================

PIXHAWK Micro Air Vehicle Flying Robotics Toolkit

(c) 2009, 2010 PIXHAWK PROJECT  <http://pixhawk.ethz.ch>

This file is part of the PIXHAWK project

    PIXHAWK 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.

    PIXHAWK 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 PIXHAWK. If not, see <http://www.gnu.org/licenses/>.

======================================================================*/

/**
 * @file
 *   @brief Waypoint list widget
 *
 *   @author Lorenz Meier <mavteam@student.ethz.ch>
 *   @author Benjamin Knecht <mavteam@student.ethz.ch>
 *   @author Petri Tanskanen <mavteam@student.ethz.ch>
 *
 */

#include "WaypointList.h"
#include "ui_WaypointList.h"
#include <UASInterface.h>
#include <UASManager.h>
#include <QDebug>
#include <QFileDialog>

WaypointList::WaypointList(QWidget *parent, UASInterface* uas) :
        QWidget(parent),
        uas(NULL),
        m_ui(new Ui::WaypointList)
{
    m_ui->setupUi(this);

    listLayout = new QVBoxLayout(m_ui->listWidget);
    listLayout->setSpacing(6);
    listLayout->setMargin(0);
    listLayout->setAlignment(Qt::AlignTop);
    m_ui->listWidget->setLayout(listLayout);

    wpViews = QMap<Waypoint*, WaypointView*>();

    this->uas = NULL;

    // ADD WAYPOINT
    // Connect add action, set right button icon and connect action to this class
    connect(m_ui->addButton, SIGNAL(clicked()), m_ui->actionAddWaypoint, SIGNAL(triggered()));
    connect(m_ui->actionAddWaypoint, SIGNAL(triggered()), this, SLOT(add()));

    // SEND WAYPOINTS
    connect(m_ui->transmitButton, SIGNAL(clicked()), this, SLOT(transmit()));

    // REQUEST WAYPOINTS
    connect(m_ui->readButton, SIGNAL(clicked()), this, SLOT(read()));

    // SAVE/LOAD WAYPOINTS
    connect(m_ui->saveButton, SIGNAL(clicked()), this, SLOT(saveWaypoints()));
    connect(m_ui->loadButton, SIGNAL(clicked()), this, SLOT(loadWaypoints()));

    connect(UASManager::instance(), SIGNAL(activeUASSet(UASInterface*)), this, SLOT(setUAS(UASInterface*)));

    // STATUS LABEL
    updateStatusLabel("");

    // SET UAS AFTER ALL SIGNALS/SLOTS ARE CONNECTED
    setUAS(uas);
}

WaypointList::~WaypointList()
{
    delete m_ui;
}

void WaypointList::updateStatusLabel(const QString &string)
{
    m_ui->statusLabel->setText(string);
}

void WaypointList::setUAS(UASInterface* uas)
{
    if (this->uas == NULL && uas != NULL)
    {
        this->uas = uas;

        connect(&uas->getWaypointManager(), SIGNAL(updateStatusString(const QString &)),                                this, SLOT(updateStatusLabel(const QString &)));
        connect(&uas->getWaypointManager(), SIGNAL(waypointUpdated(int,quint16,double,double,double,double,bool,bool)), this, SLOT(setWaypoint(int,quint16,double,double,double,double,bool,bool)));
        connect(&uas->getWaypointManager(), SIGNAL(currentWaypointChanged(quint16)),                                    this, SLOT(currentWaypointChanged(quint16)));

        connect(this, SIGNAL(sendWaypoints(const QVector<Waypoint*> &)),    &uas->getWaypointManager(), SLOT(sendWaypoints(const QVector<Waypoint*> &)));
        connect(this, SIGNAL(requestWaypoints()),                           &uas->getWaypointManager(), SLOT(requestWaypoints()));
        connect(this, SIGNAL(clearWaypointList()),                          &uas->getWaypointManager(), SLOT(clearWaypointList()));
    }
}

void WaypointList::setWaypoint(int uasId, quint16 id, double x, double y, double z, double yaw, bool autocontinue, bool current)
{
    if (uasId == this->uas->getUASID())
    {
        Waypoint* wp = new Waypoint(id, x, y, z, yaw, autocontinue, current);
        addWaypoint(wp);
    }
}

void WaypointList::waypointReached(UASInterface* uas, quint16 waypointId)
{
    Q_UNUSED(uas);
    qDebug() << "Waypoint reached: " << waypointId;

    updateStatusLabel(QString("Waypoint %1 reached.").arg(waypointId));
}

void WaypointList::currentWaypointChanged(quint16 seq)
{
    if (seq < waypoints.size())
    {
        for(int i = 0; i < waypoints.size(); i++)
        {
            WaypointView* widget = wpViews.find(waypoints[i]).value();

            if (waypoints[i]->getId() == seq)
            {
                waypoints[i]->setCurrent(true);
                widget->setCurrent(true);
            }
            else
            {
                waypoints[i]->setCurrent(false);
                widget->setCurrent(false);
            }
        }
        redrawList();
    }
}

void WaypointList::read()
{
    while(waypoints.size()>0)
    {
        removeWaypoint(waypoints[0]);
    }

    emit requestWaypoints();
}

void WaypointList::transmit()
{
    emit sendWaypoints(waypoints);
    //emit requestWaypoints(); FIXME
}

void WaypointList::add()
{
    // Only add waypoints if UAS is present
    if (uas)
    {
        if (waypoints.size() > 0)
        {
            addWaypoint(new Waypoint(waypoints.size(), 0.0, 0.0, -0.0, 0.0, false, false));
        }
        else
        {
            addWaypoint(new Waypoint(waypoints.size(), 0.0, 0.0, -0.0, 0.0, false, true));
        }
    }
}

void WaypointList::addWaypoint(Waypoint* wp)
{
    waypoints.push_back(wp);
    if (!wpViews.contains(wp))
    {
        WaypointView* wpview = new WaypointView(wp, this);
        wpViews.insert(wp, wpview);
        listLayout->addWidget(wpViews.value(wp));
        connect(wpview, SIGNAL(moveDownWaypoint(Waypoint*)), this, SLOT(moveDown(Waypoint*)));
        connect(wpview, SIGNAL(moveUpWaypoint(Waypoint*)), this, SLOT(moveUp(Waypoint*)));
        connect(wpview, SIGNAL(removeWaypoint(Waypoint*)), this, SLOT(removeWaypoint(Waypoint*)));
        connect(wpview, SIGNAL(currentWaypointChanged(quint16)), this, SLOT(currentWaypointChanged(quint16)));
    }
}

void WaypointList::redrawList()
{
    // Clear list layout
    if (!wpViews.empty())
    {
        QMapIterator<Waypoint*,WaypointView*> viewIt(wpViews);
        viewIt.toFront();
        while(viewIt.hasNext())
        {
            viewIt.next();
            listLayout->removeWidget(viewIt.value());
        }
        // Re-add waypoints
        for(int i = 0; i < waypoints.size(); i++)
        {
            listLayout->addWidget(wpViews.value(waypoints[i]));
        }
    }
}

void WaypointList::moveUp(Waypoint* wp)
{
    int id = wp->getId();
    if (waypoints.size() > 1 && waypoints.size() > id)
    {
        Waypoint* temp = waypoints[id];
        if (id > 0)
        {
            waypoints[id] = waypoints[id-1];
            waypoints[id-1] = temp;
            waypoints[id-1]->setId(id-1);
            waypoints[id]->setId(id);
        }
        else
        {
            waypoints[id] = waypoints[waypoints.size()-1];
            waypoints[waypoints.size()-1] = temp;
            waypoints[waypoints.size()-1]->setId(waypoints.size()-1);
            waypoints[id]->setId(id);
        }
        redrawList();
    }
}

void WaypointList::moveDown(Waypoint* wp)
{
    int id = wp->getId();
    if (waypoints.size() > 1 && waypoints.size() > id)
    {
        Waypoint* temp = waypoints[id];
        if (id != waypoints.size()-1)
        {
            waypoints[id] = waypoints[id+1];
            waypoints[id+1] = temp;
            waypoints[id+1]->setId(id+1);
            waypoints[id]->setId(id);
        }
        else
        {
            waypoints[id] = waypoints[0];
            waypoints[0] = temp;
            waypoints[0]->setId(0);
            waypoints[id]->setId(id);
        }
        redrawList();
    }
}

void WaypointList::removeWaypoint(Waypoint* wp)
{
    // Delete from list
    if (wp != NULL)
    {
        waypoints.remove(wp->getId());
        for(int i = wp->getId(); i < waypoints.size(); i++)
        {
            waypoints[i]->setId(i);
        }

        // Remove from view
        WaypointView* widget = wpViews.find(wp).value();
        wpViews.remove(wp);
        widget->hide();
        listLayout->removeWidget(widget);
        delete wp;
    }
}

void WaypointList::changeEvent(QEvent *e)
{
    switch (e->type()) {
    case QEvent::LanguageChange:
        m_ui->retranslateUi(this);
        break;
    default:
        break;
    }
}

void WaypointList::saveWaypoints()
{
    QString fileName = QFileDialog::getSaveFileName(this, tr("Save File"), "./waypoints.txt", tr("Waypoint File (*.txt)"));
    QFile file(fileName);
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
        return;

    QTextStream in(&file);
    for (int i = 0; i < waypoints.size(); i++)
    {
        Waypoint* wp = waypoints[i];
        in << "~" << wp->getId() << "~" << wp->getX() << "~" << wp->getY()  << "~" << wp->getZ()  << "~" << wp->getYaw()  << "~" << wp->getAutoContinue() << "~" << wp->getCurrent() << "\n";
        in.flush();
    }
    file.close();
}

void WaypointList::loadWaypoints()
{
    QString fileName = QFileDialog::getOpenFileName(this, tr("Load File"), ".", tr("Waypoint File (*.txt)"));
    QFile file(fileName);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
        return;

    while(waypoints.size()>0)
    {
        removeWaypoint(waypoints[0]);
    }

    QTextStream in(&file);
    while (!in.atEnd())
    {
        QStringList wpParams = in.readLine().split("~");
        if (wpParams.size() == 8)
            addWaypoint(new Waypoint(wpParams[1].toInt(), wpParams[2].toDouble(), wpParams[3].toDouble(), wpParams[4].toDouble(), wpParams[5].toDouble(), (wpParams[6].toInt() == 1 ? true : false), (wpParams[7].toInt() == 1 ? true : false)));
    }
    file.close();
}

<commit_msg>changed standard values for new waypoints<commit_after>/*=====================================================================

PIXHAWK Micro Air Vehicle Flying Robotics Toolkit

(c) 2009, 2010 PIXHAWK PROJECT  <http://pixhawk.ethz.ch>

This file is part of the PIXHAWK project

    PIXHAWK 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.

    PIXHAWK 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 PIXHAWK. If not, see <http://www.gnu.org/licenses/>.

======================================================================*/

/**
 * @file
 *   @brief Waypoint list widget
 *
 *   @author Lorenz Meier <mavteam@student.ethz.ch>
 *   @author Benjamin Knecht <mavteam@student.ethz.ch>
 *   @author Petri Tanskanen <mavteam@student.ethz.ch>
 *
 */

#include "WaypointList.h"
#include "ui_WaypointList.h"
#include <UASInterface.h>
#include <UASManager.h>
#include <QDebug>
#include <QFileDialog>

WaypointList::WaypointList(QWidget *parent, UASInterface* uas) :
        QWidget(parent),
        uas(NULL),
        m_ui(new Ui::WaypointList)
{
    m_ui->setupUi(this);

    listLayout = new QVBoxLayout(m_ui->listWidget);
    listLayout->setSpacing(6);
    listLayout->setMargin(0);
    listLayout->setAlignment(Qt::AlignTop);
    m_ui->listWidget->setLayout(listLayout);

    wpViews = QMap<Waypoint*, WaypointView*>();

    this->uas = NULL;

    // ADD WAYPOINT
    // Connect add action, set right button icon and connect action to this class
    connect(m_ui->addButton, SIGNAL(clicked()), m_ui->actionAddWaypoint, SIGNAL(triggered()));
    connect(m_ui->actionAddWaypoint, SIGNAL(triggered()), this, SLOT(add()));

    // SEND WAYPOINTS
    connect(m_ui->transmitButton, SIGNAL(clicked()), this, SLOT(transmit()));

    // REQUEST WAYPOINTS
    connect(m_ui->readButton, SIGNAL(clicked()), this, SLOT(read()));

    // SAVE/LOAD WAYPOINTS
    connect(m_ui->saveButton, SIGNAL(clicked()), this, SLOT(saveWaypoints()));
    connect(m_ui->loadButton, SIGNAL(clicked()), this, SLOT(loadWaypoints()));

    connect(UASManager::instance(), SIGNAL(activeUASSet(UASInterface*)), this, SLOT(setUAS(UASInterface*)));

    // STATUS LABEL
    updateStatusLabel("");

    // SET UAS AFTER ALL SIGNALS/SLOTS ARE CONNECTED
    setUAS(uas);
}

WaypointList::~WaypointList()
{
    delete m_ui;
}

void WaypointList::updateStatusLabel(const QString &string)
{
    m_ui->statusLabel->setText(string);
}

void WaypointList::setUAS(UASInterface* uas)
{
    if (this->uas == NULL && uas != NULL)
    {
        this->uas = uas;

        connect(&uas->getWaypointManager(), SIGNAL(updateStatusString(const QString &)),                                this, SLOT(updateStatusLabel(const QString &)));
        connect(&uas->getWaypointManager(), SIGNAL(waypointUpdated(int,quint16,double,double,double,double,bool,bool)), this, SLOT(setWaypoint(int,quint16,double,double,double,double,bool,bool)));
        connect(&uas->getWaypointManager(), SIGNAL(currentWaypointChanged(quint16)),                                    this, SLOT(currentWaypointChanged(quint16)));

        connect(this, SIGNAL(sendWaypoints(const QVector<Waypoint*> &)),    &uas->getWaypointManager(), SLOT(sendWaypoints(const QVector<Waypoint*> &)));
        connect(this, SIGNAL(requestWaypoints()),                           &uas->getWaypointManager(), SLOT(requestWaypoints()));
        connect(this, SIGNAL(clearWaypointList()),                          &uas->getWaypointManager(), SLOT(clearWaypointList()));
    }
}

void WaypointList::setWaypoint(int uasId, quint16 id, double x, double y, double z, double yaw, bool autocontinue, bool current)
{
    if (uasId == this->uas->getUASID())
    {
        Waypoint* wp = new Waypoint(id, x, y, z, yaw, autocontinue, current);
        addWaypoint(wp);
    }
}

void WaypointList::waypointReached(UASInterface* uas, quint16 waypointId)
{
    Q_UNUSED(uas);
    qDebug() << "Waypoint reached: " << waypointId;

    updateStatusLabel(QString("Waypoint %1 reached.").arg(waypointId));
}

void WaypointList::currentWaypointChanged(quint16 seq)
{
    if (seq < waypoints.size())
    {
        for(int i = 0; i < waypoints.size(); i++)
        {
            WaypointView* widget = wpViews.find(waypoints[i]).value();

            if (waypoints[i]->getId() == seq)
            {
                waypoints[i]->setCurrent(true);
                widget->setCurrent(true);
            }
            else
            {
                waypoints[i]->setCurrent(false);
                widget->setCurrent(false);
            }
        }
        redrawList();
    }
}

void WaypointList::read()
{
    while(waypoints.size()>0)
    {
        removeWaypoint(waypoints[0]);
    }

    emit requestWaypoints();
}

void WaypointList::transmit()
{
    emit sendWaypoints(waypoints);
    //emit requestWaypoints(); FIXME
}

void WaypointList::add()
{
    // Only add waypoints if UAS is present
    if (uas)
    {
        if (waypoints.size() > 0)
        {
            addWaypoint(new Waypoint(waypoints.size(), 1.1, 1.1, -0.6, 0.0, true, false));
        }
        else
        {
            addWaypoint(new Waypoint(waypoints.size(), 0.0, 0.0, -0.0, 0.0, true, true));
        }
    }
}

void WaypointList::addWaypoint(Waypoint* wp)
{
    waypoints.push_back(wp);
    if (!wpViews.contains(wp))
    {
        WaypointView* wpview = new WaypointView(wp, this);
        wpViews.insert(wp, wpview);
        listLayout->addWidget(wpViews.value(wp));
        connect(wpview, SIGNAL(moveDownWaypoint(Waypoint*)), this, SLOT(moveDown(Waypoint*)));
        connect(wpview, SIGNAL(moveUpWaypoint(Waypoint*)), this, SLOT(moveUp(Waypoint*)));
        connect(wpview, SIGNAL(removeWaypoint(Waypoint*)), this, SLOT(removeWaypoint(Waypoint*)));
        connect(wpview, SIGNAL(currentWaypointChanged(quint16)), this, SLOT(currentWaypointChanged(quint16)));
    }
}

void WaypointList::redrawList()
{
    // Clear list layout
    if (!wpViews.empty())
    {
        QMapIterator<Waypoint*,WaypointView*> viewIt(wpViews);
        viewIt.toFront();
        while(viewIt.hasNext())
        {
            viewIt.next();
            listLayout->removeWidget(viewIt.value());
        }
        // Re-add waypoints
        for(int i = 0; i < waypoints.size(); i++)
        {
            listLayout->addWidget(wpViews.value(waypoints[i]));
        }
    }
}

void WaypointList::moveUp(Waypoint* wp)
{
    int id = wp->getId();
    if (waypoints.size() > 1 && waypoints.size() > id)
    {
        Waypoint* temp = waypoints[id];
        if (id > 0)
        {
            waypoints[id] = waypoints[id-1];
            waypoints[id-1] = temp;
            waypoints[id-1]->setId(id-1);
            waypoints[id]->setId(id);
        }
        else
        {
            waypoints[id] = waypoints[waypoints.size()-1];
            waypoints[waypoints.size()-1] = temp;
            waypoints[waypoints.size()-1]->setId(waypoints.size()-1);
            waypoints[id]->setId(id);
        }
        redrawList();
    }
}

void WaypointList::moveDown(Waypoint* wp)
{
    int id = wp->getId();
    if (waypoints.size() > 1 && waypoints.size() > id)
    {
        Waypoint* temp = waypoints[id];
        if (id != waypoints.size()-1)
        {
            waypoints[id] = waypoints[id+1];
            waypoints[id+1] = temp;
            waypoints[id+1]->setId(id+1);
            waypoints[id]->setId(id);
        }
        else
        {
            waypoints[id] = waypoints[0];
            waypoints[0] = temp;
            waypoints[0]->setId(0);
            waypoints[id]->setId(id);
        }
        redrawList();
    }
}

void WaypointList::removeWaypoint(Waypoint* wp)
{
    // Delete from list
    if (wp != NULL)
    {
        waypoints.remove(wp->getId());
        for(int i = wp->getId(); i < waypoints.size(); i++)
        {
            waypoints[i]->setId(i);
        }

        // Remove from view
        WaypointView* widget = wpViews.find(wp).value();
        wpViews.remove(wp);
        widget->hide();
        listLayout->removeWidget(widget);
        delete wp;
    }
}

void WaypointList::changeEvent(QEvent *e)
{
    switch (e->type()) {
    case QEvent::LanguageChange:
        m_ui->retranslateUi(this);
        break;
    default:
        break;
    }
}

void WaypointList::saveWaypoints()
{
    QString fileName = QFileDialog::getSaveFileName(this, tr("Save File"), "./waypoints.txt", tr("Waypoint File (*.txt)"));
    QFile file(fileName);
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
        return;

    QTextStream in(&file);
    for (int i = 0; i < waypoints.size(); i++)
    {
        Waypoint* wp = waypoints[i];
        in << "~" << wp->getId() << "~" << wp->getX() << "~" << wp->getY()  << "~" << wp->getZ()  << "~" << wp->getYaw()  << "~" << wp->getAutoContinue() << "~" << wp->getCurrent() << "\n";
        in.flush();
    }
    file.close();
}

void WaypointList::loadWaypoints()
{
    QString fileName = QFileDialog::getOpenFileName(this, tr("Load File"), ".", tr("Waypoint File (*.txt)"));
    QFile file(fileName);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
        return;

    while(waypoints.size()>0)
    {
        removeWaypoint(waypoints[0]);
    }

    QTextStream in(&file);
    while (!in.atEnd())
    {
        QStringList wpParams = in.readLine().split("~");
        if (wpParams.size() == 8)
            addWaypoint(new Waypoint(wpParams[1].toInt(), wpParams[2].toDouble(), wpParams[3].toDouble(), wpParams[4].toDouble(), wpParams[5].toDouble(), (wpParams[6].toInt() == 1 ? true : false), (wpParams[7].toInt() == 1 ? true : false)));
    }
    file.close();
}

<|endoftext|>


<commit_before>/******************************************************************************
 *                       ____    _    _____                                   *
 *                      / ___|  / \  |  ___|    C++                           *
 *                     | |     / _ \ | |_       Actor                         *
 *                     | |___ / ___ \|  _|      Framework                     *
 *                      \____/_/   \_|_|                                      *
 *                                                                            *
 * Copyright (C) 2011 - 2014                                                  *
 * Dominik Charousset <dominik.charousset (at) haw-hamburg.de>                *
 *                                                                            *
 * Distributed under the terms and conditions of the BSD 3-Clause License or  *
 * (at your option) under the terms and conditions of the Boost Software      *
 * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE.       *
 *                                                                            *
 * If you did not receive a copy of the license files, see                    *
 * http://opensource.org/licenses/BSD-3-Clause and                            *
 * http://www.boost.org/LICENSE_1_0.txt.                                      *
 ******************************************************************************/

#ifndef CAF_OPTIONAL_HPP
#define CAF_OPTIONAL_HPP

#include <new>
#include <utility>

#include "caf/none.hpp"
#include "caf/unit.hpp"
#include "caf/config.hpp"

#include "caf/detail/safe_equal.hpp"
#include "caf/detail/scope_guard.hpp"

namespace caf {

/// A C++17 compatible `optional` implementation.
template <class T>
class optional {
 public:
  /// Typdef for `T`.
  using type = T;

  /// Creates an instance without value.
  optional(const none_t& = none) : m_valid(false) {
    // nop
  }

  /// Creates an valid instance from `value`.
  template <class U,
            class E = typename std::enable_if<
                        std::is_convertible<U, T>::value
                      >::type>
  optional(U x) : m_valid(false) {
    cr(std::move(x));
  }

  optional(const optional& other) : m_valid(false) {
    if (other.m_valid) {
      cr(other.m_value);
    }
  }

  optional(optional&& other) : m_valid(false) {
    if (other.m_valid) {
      cr(std::move(other.m_value));
    }
  }

  ~optional() {
    destroy();
  }

  optional& operator=(const optional& other) {
    if (m_valid) {
      if (other.m_valid) m_value = other.m_value;
      else destroy();
    }
    else if (other.m_valid) {
      cr(other.m_value);
    }
    return *this;
  }

  optional& operator=(optional&& other) {
    if (m_valid) {
      if (other.m_valid) m_value = std::move(other.m_value);
      else destroy();
    }
    else if (other.m_valid) {
      cr(std::move(other.m_value));
    }
    return *this;
  }

  /// Checks whether this object contains a value.
  explicit operator bool() const {
    return m_valid;
  }

  /// Checks whether this object does not contain a value.
  bool operator!() const {
    return ! m_valid;
  }

  /// Returns the value.
  T& operator*() {
    CAF_ASSERT(m_valid);
    return m_value;
  }

  /// Returns the value.
  const T& operator*() const {
    CAF_ASSERT(m_valid);
    return m_value;
  }

  /// Returns the value.
  const T* operator->() const {
    CAF_ASSERT(m_valid);
    return &m_value;
  }

  /// Returns the value.
  T* operator->() {
    CAF_ASSERT(m_valid);
    return &m_value;
  }

  /// Returns the value.
  T& value() {
    CAF_ASSERT(m_valid);
    return m_value;
  }

  /// Returns the value.
  const T& value() const {
    CAF_ASSERT(m_valid);
    return m_value;
  }

  /// Returns the value if `m_valid`, otherwise returns `default_value`.
  const T& value_or(const T& default_value) const {
    return m_valid ? value() : default_value;
  }

 private:
  void destroy() {
    if (m_valid) {
      m_value.~T();
      m_valid = false;
    }
  }

  template <class V>
  void cr(V&& x) {
    CAF_ASSERT(! m_valid);
    m_valid = true;
    new (&m_value) T(std::forward<V>(x));
  }

  bool m_valid;
  union { T m_value; };
};

/// Template specialization to allow `optional` to hold a reference
/// rather than an actual value with minimal overhead.
template <class T>
class optional<T&> {
 public:
  using type = T;

  optional(const none_t& = none) : m_value(nullptr) {
    // nop
  }

  optional(T& x) : m_value(&x) {
    // nop
  }

  optional(const optional& other) = default;

  optional& operator=(const optional& other) = default;

  explicit operator bool() const {
    return m_value != nullptr;
  }

  bool operator!() const {
    return ! m_value;
  }

  T& operator*() {
    CAF_ASSERT(m_value);
    return *m_value;
  }

  const T& operator*() const {
    CAF_ASSERT(m_value);
    return *m_value;
  }

  T* operator->() {
    CAF_ASSERT(m_value);
    return m_value;
  }

  const T* operator->() const {
    CAF_ASSERT(m_value);
    return m_value;
  }

  T& value() {
    CAF_ASSERT(m_value);
    return *m_value;
  }

  const T& value() const {
    CAF_ASSERT(m_value);
    return *m_value;
  }

  const T& value_or(const T& default_value) const {
    if (m_value)
      return value();
    return default_value;
  }

 private:
  T* m_value;
};

template <>
class optional<void> {
 public:
  using type = unit_t;

  optional(none_t = none) : m_value(false) {
    // nop
  }

  optional(unit_t) : m_value(true) {
    // nop
  }

  optional(const optional& other) = default;

  optional& operator=(const optional& other) = default;

  explicit operator bool() const {
    return m_value;
  }

  bool operator!() const {
    return ! m_value;
  }

 private:
  bool m_value;
};

template <class Inspector, class T>
typename std::enable_if<Inspector::is_saving::value,
                        typename Inspector::result_type>::type
inspect(Inspector& f, optional<T>& x) {
  return x ? f(false) : f(true, *x);
}

template <class T>
struct optional_inspect_helper {
  bool& enabled;
  T& storage;
  template <class Inspector>
  friend typename Inspector::result_type inspect(Inspector& f,
                                                 optional_inspect_helper& x) {
    return x.enabled ? f(x.storage) : f();
  }
};

template <class Inspector, class T>
typename std::enable_if<Inspector::is_loading::value,
                        typename Inspector::result_type>::type
inspect(Inspector& f, optional<T>& x) {
  bool flag;
  typename optional<T>::type tmp;
  optional_inspect_helper<T> helper{flag, tmp};
  auto guard = detail::make_scope_guard([&] {
    if (flag)
      x = std::move(tmp);
    else
      x = none;
  });
  return f(flag, helper);
}

/// @relates optional
template <class T>
auto to_string(const optional<T>& x) -> decltype(to_string(*x)) {
  return x ? "*" + to_string(*x) : "<null>";
}

// -- [X.Y.8] comparison with optional ----------------------------------------

/// @relates optional
template <class T>
bool operator==(const optional<T>& lhs, const optional<T>& rhs) {
  return static_cast<bool>(lhs) == static_cast<bool>(rhs)
      && (! lhs || *lhs == *rhs);
}

/// @relates optional
template <class T>
bool operator!=(const optional<T>& lhs, const optional<T>& rhs) {
  return ! (lhs == rhs);
}

/// @relates optional
template <class T>
bool operator<(const optional<T>& lhs, const optional<T>& rhs) {
  return static_cast<bool>(rhs) && (! lhs || *lhs < *rhs);
}

/// @relates optional
template <class T>
bool operator<=(const optional<T>& lhs, const optional<T>& rhs) {
  return ! (rhs < lhs);
}

/// @relates optional
template <class T>
bool operator>=(const optional<T>& lhs, const optional<T>& rhs) {
  return ! (lhs < rhs);
}

/// @relates optional
template <class T>
bool operator>(const optional<T>& lhs, const optional<T>& rhs) {
  return rhs < lhs;
}

// -- [X.Y.9] comparison with none_t (aka. nullopt_t) -------------------------

/// @relates optional
template <class T>
bool operator==(const optional<T>& lhs, none_t) {
  return ! lhs;
}

/// @relates optional
template <class T>
bool operator==(none_t, const optional<T>& rhs) {
  return ! rhs;
}

/// @relates optional
template <class T>
bool operator!=(const optional<T>& lhs, none_t) {
  return static_cast<bool>(lhs);
}

/// @relates optional
template <class T>
bool operator!=(none_t, const optional<T>& rhs) {
  return static_cast<bool>(rhs);
}

/// @relates optional
template <class T>
bool operator<(const optional<T>&, none_t) {
  return false;
}

/// @relates optional
template <class T>
bool operator<(none_t, const optional<T>& rhs) {
  return static_cast<bool>(rhs);
}

/// @relates optional
template <class T>
bool operator<=(const optional<T>& lhs, none_t) {
  return ! lhs;
}

/// @relates optional
template <class T>
bool operator<=(none_t, const optional<T>&) {
  return true;
}

/// @relates optional
template <class T>
bool operator>(const optional<T>& lhs, none_t) {
  return static_cast<bool>(lhs);
}

/// @relates optional
template <class T>
bool operator>(none_t, const optional<T>&) {
  return false;
}

/// @relates optional
template <class T>
bool operator>=(const optional<T>&, none_t) {
  return true;
}

/// @relates optional
template <class T>
bool operator>=(none_t, const optional<T>&) {
  return true;
}

// -- [X.Y.10] comparison with value type ------------------------------------

/// @relates optional
template <class T>
bool operator==(const optional<T>& lhs, const T& rhs) {
  return lhs && *lhs == rhs;
}

/// @relates optional
template <class T>
bool operator==(const T& lhs, const optional<T>& rhs) {
  return rhs && lhs == *rhs;
}

/// @relates optional
template <class T>
bool operator!=(const optional<T>& lhs, const T& rhs) {
  return ! lhs || ! (*lhs == rhs);
}

/// @relates optional
template <class T>
bool operator!=(const T& lhs, const optional<T>& rhs) {
  return ! rhs || ! (lhs == *rhs);
}

/// @relates optional
template <class T>
bool operator<(const optional<T>& lhs, const T& rhs) {
  return ! lhs || *lhs < rhs;
}

/// @relates optional
template <class T>
bool operator<(const T& lhs, const optional<T>& rhs) {
  return rhs && lhs < *rhs;
}

/// @relates optional
template <class T>
bool operator<=(const optional<T>& lhs, const T& rhs) {
  return ! lhs || ! (rhs < *lhs);
}

/// @relates optional
template <class T>
bool operator<=(const T& lhs, const optional<T>& rhs) {
  return rhs && ! (rhs < lhs);
}

/// @relates optional
template <class T>
bool operator>(const optional<T>& lhs, const T& rhs) {
  return lhs && rhs < *lhs;
}

/// @relates optional
template <class T>
bool operator>(const T& lhs, const optional<T>& rhs) {
  return ! rhs || *rhs < lhs;
}

/// @relates optional
template <class T>
bool operator>=(const optional<T>& lhs, const T& rhs) {
  return lhs && ! (*lhs < rhs);
}

/// @relates optional
template <class T>
bool operator>=(const T& lhs, const optional<T>& rhs) {
  return ! rhs || ! (lhs < *rhs);
}

} // namespace caf

#endif // CAF_OPTIONAL_HPP
<commit_msg>Fix visit of optional<T><commit_after>/******************************************************************************
 *                       ____    _    _____                                   *
 *                      / ___|  / \  |  ___|    C++                           *
 *                     | |     / _ \ | |_       Actor                         *
 *                     | |___ / ___ \|  _|      Framework                     *
 *                      \____/_/   \_|_|                                      *
 *                                                                            *
 * Copyright (C) 2011 - 2014                                                  *
 * Dominik Charousset <dominik.charousset (at) haw-hamburg.de>                *
 *                                                                            *
 * Distributed under the terms and conditions of the BSD 3-Clause License or  *
 * (at your option) under the terms and conditions of the Boost Software      *
 * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE.       *
 *                                                                            *
 * If you did not receive a copy of the license files, see                    *
 * http://opensource.org/licenses/BSD-3-Clause and                            *
 * http://www.boost.org/LICENSE_1_0.txt.                                      *
 ******************************************************************************/

#ifndef CAF_OPTIONAL_HPP
#define CAF_OPTIONAL_HPP

#include <new>
#include <utility>

#include "caf/none.hpp"
#include "caf/unit.hpp"
#include "caf/config.hpp"

#include "caf/detail/safe_equal.hpp"
#include "caf/detail/scope_guard.hpp"

namespace caf {

/// A C++17 compatible `optional` implementation.
template <class T>
class optional {
 public:
  /// Typdef for `T`.
  using type = T;

  /// Creates an instance without value.
  optional(const none_t& = none) : m_valid(false) {
    // nop
  }

  /// Creates an valid instance from `value`.
  template <class U,
            class E = typename std::enable_if<
                        std::is_convertible<U, T>::value
                      >::type>
  optional(U x) : m_valid(false) {
    cr(std::move(x));
  }

  optional(const optional& other) : m_valid(false) {
    if (other.m_valid) {
      cr(other.m_value);
    }
  }

  optional(optional&& other) : m_valid(false) {
    if (other.m_valid) {
      cr(std::move(other.m_value));
    }
  }

  ~optional() {
    destroy();
  }

  optional& operator=(const optional& other) {
    if (m_valid) {
      if (other.m_valid) m_value = other.m_value;
      else destroy();
    }
    else if (other.m_valid) {
      cr(other.m_value);
    }
    return *this;
  }

  optional& operator=(optional&& other) {
    if (m_valid) {
      if (other.m_valid) m_value = std::move(other.m_value);
      else destroy();
    }
    else if (other.m_valid) {
      cr(std::move(other.m_value));
    }
    return *this;
  }

  /// Checks whether this object contains a value.
  explicit operator bool() const {
    return m_valid;
  }

  /// Checks whether this object does not contain a value.
  bool operator!() const {
    return ! m_valid;
  }

  /// Returns the value.
  T& operator*() {
    CAF_ASSERT(m_valid);
    return m_value;
  }

  /// Returns the value.
  const T& operator*() const {
    CAF_ASSERT(m_valid);
    return m_value;
  }

  /// Returns the value.
  const T* operator->() const {
    CAF_ASSERT(m_valid);
    return &m_value;
  }

  /// Returns the value.
  T* operator->() {
    CAF_ASSERT(m_valid);
    return &m_value;
  }

  /// Returns the value.
  T& value() {
    CAF_ASSERT(m_valid);
    return m_value;
  }

  /// Returns the value.
  const T& value() const {
    CAF_ASSERT(m_valid);
    return m_value;
  }

  /// Returns the value if `m_valid`, otherwise returns `default_value`.
  const T& value_or(const T& default_value) const {
    return m_valid ? value() : default_value;
  }

 private:
  void destroy() {
    if (m_valid) {
      m_value.~T();
      m_valid = false;
    }
  }

  template <class V>
  void cr(V&& x) {
    CAF_ASSERT(! m_valid);
    m_valid = true;
    new (&m_value) T(std::forward<V>(x));
  }

  bool m_valid;
  union { T m_value; };
};

/// Template specialization to allow `optional` to hold a reference
/// rather than an actual value with minimal overhead.
template <class T>
class optional<T&> {
 public:
  using type = T;

  optional(const none_t& = none) : m_value(nullptr) {
    // nop
  }

  optional(T& x) : m_value(&x) {
    // nop
  }

  optional(const optional& other) = default;

  optional& operator=(const optional& other) = default;

  explicit operator bool() const {
    return m_value != nullptr;
  }

  bool operator!() const {
    return ! m_value;
  }

  T& operator*() {
    CAF_ASSERT(m_value);
    return *m_value;
  }

  const T& operator*() const {
    CAF_ASSERT(m_value);
    return *m_value;
  }

  T* operator->() {
    CAF_ASSERT(m_value);
    return m_value;
  }

  const T* operator->() const {
    CAF_ASSERT(m_value);
    return m_value;
  }

  T& value() {
    CAF_ASSERT(m_value);
    return *m_value;
  }

  const T& value() const {
    CAF_ASSERT(m_value);
    return *m_value;
  }

  const T& value_or(const T& default_value) const {
    if (m_value)
      return value();
    return default_value;
  }

 private:
  T* m_value;
};

template <>
class optional<void> {
 public:
  using type = unit_t;

  optional(none_t = none) : m_value(false) {
    // nop
  }

  optional(unit_t) : m_value(true) {
    // nop
  }

  optional(const optional& other) = default;

  optional& operator=(const optional& other) = default;

  explicit operator bool() const {
    return m_value;
  }

  bool operator!() const {
    return ! m_value;
  }

 private:
  bool m_value;
};

template <class Inspector, class T>
typename std::enable_if<Inspector::is_saving::value,
                        typename Inspector::result_type>::type
inspect(Inspector& f, optional<T>& x) {
  return x ? f(true, *x) : f(false);
}

template <class T>
struct optional_inspect_helper {
  bool& enabled;
  T& storage;
  template <class Inspector>
  friend typename Inspector::result_type inspect(Inspector& f,
                                                 optional_inspect_helper& x) {
    return x.enabled ? f(x.storage) : f();
  }
};

template <class Inspector, class T>
typename std::enable_if<Inspector::is_loading::value,
                        typename Inspector::result_type>::type
inspect(Inspector& f, optional<T>& x) {
  bool flag;
  typename optional<T>::type tmp;
  optional_inspect_helper<T> helper{flag, tmp};
  auto guard = detail::make_scope_guard([&] {
    if (flag)
      x = std::move(tmp);
    else
      x = none;
  });
  return f(flag, helper);
}

/// @relates optional
template <class T>
auto to_string(const optional<T>& x) -> decltype(to_string(*x)) {
  return x ? "*" + to_string(*x) : "<null>";
}

// -- [X.Y.8] comparison with optional ----------------------------------------

/// @relates optional
template <class T>
bool operator==(const optional<T>& lhs, const optional<T>& rhs) {
  return static_cast<bool>(lhs) == static_cast<bool>(rhs)
      && (! lhs || *lhs == *rhs);
}

/// @relates optional
template <class T>
bool operator!=(const optional<T>& lhs, const optional<T>& rhs) {
  return ! (lhs == rhs);
}

/// @relates optional
template <class T>
bool operator<(const optional<T>& lhs, const optional<T>& rhs) {
  return static_cast<bool>(rhs) && (! lhs || *lhs < *rhs);
}

/// @relates optional
template <class T>
bool operator<=(const optional<T>& lhs, const optional<T>& rhs) {
  return ! (rhs < lhs);
}

/// @relates optional
template <class T>
bool operator>=(const optional<T>& lhs, const optional<T>& rhs) {
  return ! (lhs < rhs);
}

/// @relates optional
template <class T>
bool operator>(const optional<T>& lhs, const optional<T>& rhs) {
  return rhs < lhs;
}

// -- [X.Y.9] comparison with none_t (aka. nullopt_t) -------------------------

/// @relates optional
template <class T>
bool operator==(const optional<T>& lhs, none_t) {
  return ! lhs;
}

/// @relates optional
template <class T>
bool operator==(none_t, const optional<T>& rhs) {
  return ! rhs;
}

/// @relates optional
template <class T>
bool operator!=(const optional<T>& lhs, none_t) {
  return static_cast<bool>(lhs);
}

/// @relates optional
template <class T>
bool operator!=(none_t, const optional<T>& rhs) {
  return static_cast<bool>(rhs);
}

/// @relates optional
template <class T>
bool operator<(const optional<T>&, none_t) {
  return false;
}

/// @relates optional
template <class T>
bool operator<(none_t, const optional<T>& rhs) {
  return static_cast<bool>(rhs);
}

/// @relates optional
template <class T>
bool operator<=(const optional<T>& lhs, none_t) {
  return ! lhs;
}

/// @relates optional
template <class T>
bool operator<=(none_t, const optional<T>&) {
  return true;
}

/// @relates optional
template <class T>
bool operator>(const optional<T>& lhs, none_t) {
  return static_cast<bool>(lhs);
}

/// @relates optional
template <class T>
bool operator>(none_t, const optional<T>&) {
  return false;
}

/// @relates optional
template <class T>
bool operator>=(const optional<T>&, none_t) {
  return true;
}

/// @relates optional
template <class T>
bool operator>=(none_t, const optional<T>&) {
  return true;
}

// -- [X.Y.10] comparison with value type ------------------------------------

/// @relates optional
template <class T>
bool operator==(const optional<T>& lhs, const T& rhs) {
  return lhs && *lhs == rhs;
}

/// @relates optional
template <class T>
bool operator==(const T& lhs, const optional<T>& rhs) {
  return rhs && lhs == *rhs;
}

/// @relates optional
template <class T>
bool operator!=(const optional<T>& lhs, const T& rhs) {
  return ! lhs || ! (*lhs == rhs);
}

/// @relates optional
template <class T>
bool operator!=(const T& lhs, const optional<T>& rhs) {
  return ! rhs || ! (lhs == *rhs);
}

/// @relates optional
template <class T>
bool operator<(const optional<T>& lhs, const T& rhs) {
  return ! lhs || *lhs < rhs;
}

/// @relates optional
template <class T>
bool operator<(const T& lhs, const optional<T>& rhs) {
  return rhs && lhs < *rhs;
}

/// @relates optional
template <class T>
bool operator<=(const optional<T>& lhs, const T& rhs) {
  return ! lhs || ! (rhs < *lhs);
}

/// @relates optional
template <class T>
bool operator<=(const T& lhs, const optional<T>& rhs) {
  return rhs && ! (rhs < lhs);
}

/// @relates optional
template <class T>
bool operator>(const optional<T>& lhs, const T& rhs) {
  return lhs && rhs < *lhs;
}

/// @relates optional
template <class T>
bool operator>(const T& lhs, const optional<T>& rhs) {
  return ! rhs || *rhs < lhs;
}

/// @relates optional
template <class T>
bool operator>=(const optional<T>& lhs, const T& rhs) {
  return lhs && ! (*lhs < rhs);
}

/// @relates optional
template <class T>
bool operator>=(const T& lhs, const optional<T>& rhs) {
  return ! rhs || ! (lhs < *rhs);
}

} // namespace caf

#endif // CAF_OPTIONAL_HPP
<|endoftext|>


<commit_before>/*
Copyright (c) 2013 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.

Author: Leonardo de Moura
*/
#include <pthread.h>
#include <memory.h>
#include <iostream>
#include "util/exception.h"

#define LEAN_MIN_STACK_SPACE 128*1024  // 128 Kb

namespace lean {
#ifdef LEAN_WINDOWS
size_t get_stack_size() {
    return LEAN_WIN_STACK_SIZE
}
#else
size_t get_stack_size() {
    pthread_attr_t attr;
    memset (&attr, 0, sizeof(attr));
    pthread_getattr_np (pthread_self(), &attr);
    void * ptr;
    size_t result;
    pthread_attr_getstack (&attr, &ptr, &result);
    return result;
}
#endif

static thread_local size_t g_stack_size;
static thread_local size_t g_stack_base;

void save_stack_info() {
    g_stack_size = get_stack_size();
    char x;
    g_stack_base = reinterpret_cast<size_t>(&x);
}

size_t get_used_stack_size() {
    char y;
    size_t curr_stack = reinterpret_cast<size_t>(&y);
    return g_stack_base - curr_stack;
}

size_t get_available_stack_size() {
    size_t sz = get_used_stack_size();
    if (sz > g_stack_size)
        return 0;
    else
        return g_stack_size - sz;
}

void check_stack() {
    if (get_used_stack_size() + LEAN_MIN_STACK_SPACE > g_stack_size)
        throw stack_space_exception();
}
}
<commit_msg>fix(util/stackinfo): memory leak at get_stack_size<commit_after>/*
Copyright (c) 2013 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.

Author: Leonardo de Moura
*/
#include <pthread.h>
#include <memory.h>
#include <iostream>
#include "util/exception.h"

#define LEAN_MIN_STACK_SPACE 128*1024  // 128 Kb

namespace lean {
#ifdef LEAN_WINDOWS
size_t get_stack_size() {
    return LEAN_WIN_STACK_SIZE
}
#else
size_t get_stack_size() {
    pthread_attr_t attr;
    memset (&attr, 0, sizeof(attr));
    pthread_getattr_np (pthread_self(), &attr);
    void * ptr;
    size_t result;
    pthread_attr_getstack (&attr, &ptr, &result);
    pthread_attr_destroy(&attr);
    return result;
}
#endif

static thread_local size_t g_stack_size;
static thread_local size_t g_stack_base;

void save_stack_info() {
    g_stack_size = get_stack_size();
    char x;
    g_stack_base = reinterpret_cast<size_t>(&x);
}

size_t get_used_stack_size() {
    char y;
    size_t curr_stack = reinterpret_cast<size_t>(&y);
    return g_stack_base - curr_stack;
}

size_t get_available_stack_size() {
    size_t sz = get_used_stack_size();
    if (sz > g_stack_size)
        return 0;
    else
        return g_stack_size - sz;
}

void check_stack() {
    if (get_used_stack_size() + LEAN_MIN_STACK_SPACE > g_stack_size)
        throw stack_space_exception();
}
}
<|endoftext|>


<commit_before>#include <string>
#include <iostream>
#include "logging1.hpp"

using namespace std;

namespace util {

LogLevel gLogLevel;

int LoggingInit() {
  char* lvlc = getenv("TRAJOPT_LOG_THRESH");
  string lvlstr;
  if (lvlc == NULL) {
    printf("you can set logging level with TRAJOPT_LOG_THRESH. defaulting to INFO\n");
    lvlstr = "INFO";
  }
  else lvlstr = string(lvlc);
  if (lvlstr == "FATAL") gLogLevel = LevelFatal;
  else if (lvlstr == "ERROR") gLogLevel =  LevelError;
  else if (lvlstr == "INFO") gLogLevel = LevelInfo;
  else if (lvlstr == "DEBUG") gLogLevel = LevelDebug;
  else if (lvlstr == "TRACE") gLogLevel = LevelTrace;
  else {
    printf("Invalid value for environment variable TRAJOPT_LOG_THRESH: %s\n", lvlstr.c_str());
    printf("Valid values: FATAL ERROR INFO DEBUG TRACE\n");
    abort();
  }
  return 1;
}
int rhs_executes_before_main = LoggingInit();

LogLevel GetLogLevel() {return gLogLevel;}
}

<commit_msg>make it compile on linux<commit_after>#include <string>
#include <iostream>
#include "logging1.hpp"
#include <cstdlib>
using namespace std;

namespace util {

LogLevel gLogLevel;

int LoggingInit() {
  char* lvlc = getenv("TRAJOPT_LOG_THRESH");
  string lvlstr;
  if (lvlc == NULL) {
    printf("you can set logging level with TRAJOPT_LOG_THRESH. defaulting to INFO\n");
    lvlstr = "INFO";
  }
  else lvlstr = string(lvlc);
  if (lvlstr == "FATAL") gLogLevel = LevelFatal;
  else if (lvlstr == "ERROR") gLogLevel =  LevelError;
  else if (lvlstr == "INFO") gLogLevel = LevelInfo;
  else if (lvlstr == "DEBUG") gLogLevel = LevelDebug;
  else if (lvlstr == "TRACE") gLogLevel = LevelTrace;
  else {
    printf("Invalid value for environment variable TRAJOPT_LOG_THRESH: %s\n", lvlstr.c_str());
    printf("Valid values: FATAL ERROR INFO DEBUG TRACE\n");
    abort();
  }
  return 1;
}
int rhs_executes_before_main = LoggingInit();

LogLevel GetLogLevel() {return gLogLevel;}
}

<|endoftext|>


<commit_before>#include "lib_tilemap.h"
#include <stdio.h>

namespace TileMap {
    static bool isRectIntersectingRect(int ax1,int ay1,int ax2,int ay2, int bx1, int by1, int bx2, int by2) {
        return !(ax2 <= bx1 || bx2 <= ax1 || ay2 <= by1 || by2 <= ay1);
    }

    template<class TColor>
    bool Scene<TColor>::isRectFree(const int x1, const int y1, const int x2, const int y2) const {
        if (!flagmap.isValid()) return true;
        const uint8_t tileSizeBits = tileset.tileSizeBits;
        const uint8_t tileSize = 1 << tileSizeBits;
        const int16_t tileX1 = x1 >> tileSizeBits;
        const int16_t tileY1 = y1 >> tileSizeBits;
        const int16_t tileX2 = x2 >> tileSizeBits;
        const int16_t tileY2 = y2 >> tileSizeBits;

        const uint8_t width = tilemaps[0].getWidth();
        const uint8_t height = tilemaps[0].getHeight();

        for (int tileX = tileX1;tileX <= tileX2; tileX+=1)
        {
            for (int tileY = tileY1;tileY <= tileY2; tileY+=1)
            {
                if (tileX < 0 || tileY < 0 || tileX >= width || tileY >= height) {
                    continue;
                }

                const uint8_t tileIndex = flagmap.get(tileX,tileY);
                if (tileIndex != 255)
                {
                    int16_t left= tileX << tileSizeBits;
                    int16_t top = tileY << tileSizeBits;
                    switch(tileIndex) {
                    case 0:
                        return false;
                    case 5: // top half blocked
                        //printf("%d,%d : %d,%d  |  %d,%d : %d,%d\n",x1,y1,x2,y2, left,top,left+tileSize,top+tileSize/2);
                        if (isRectIntersectingRect(x1,y1,x2,y2, left,top,left+tileSize,top+tileSize/2)) {
                            return false;
                        }
                        break;
                    case 6: // bottom half blocked
                        if (isRectIntersectingRect(x1,y1,x2,y2, left,top+tileSize/2,left+tileSize,top+tileSize)) {
                            return false;
                        }
                        break;
                    case 7: // left half blocked
                        if (isRectIntersectingRect(x1,y1,x2,y2, left,top,left+tileSize/2,top+tileSize)) {
                            return false;
                        }
                        break;
                    case 8: // right half blocked
                        if (isRectIntersectingRect(x1,y1,x2,y2, left+tileSize/2,top,left+tileSize,top+tileSize)) {
                            return false;
                        }
                        break;
                    default:
                        #ifdef WIN32
                        printf("unhandled flagmap id: %d\n",tileIndex);
                        #endif
                        break;
                    }
                }
            }
        }
        return true;
    }
    template<class TColor>
    bool Scene<TColor>::findLineIntersection(int x1, int y1, int x2, int y2, int &resultX, int &resultY) const {
        int dx = x2 - x1;
        int dy = y2 - y1;
        const bool followHorizontal = abs(dx) >= abs(dy);

        if ((followHorizontal && x2 < x1) || (!followHorizontal && y2 < y1)) {
            int tmp = x1;
            x1 = x2;
            x2 = tmp;
            tmp = y1;
            y1 = y2;
            y2 = tmp;
            dx = -dx;
            dy = -dy;
        }

        const uint8_t tileSizeBits = tileset.tileSizeBits;
        const uint8_t width = tilemaps[0].getWidth();
        const uint8_t height = tilemaps[0].getHeight();
        const int tileX1 = x1 >> tileSizeBits;
        const int tileX2 = x2 >> tileSizeBits;
        const int tileY1 = y1 >> tileSizeBits;
        const int tileY2 = y2 >> tileSizeBits;

        int x = x1;
        int y = y1;
        int tileX = tileX1;
        int tileY = tileY1;
        do {
            if (tileX >= 0 && tileY >= 0 && tileX < width && tileY < height) {
                const uint8_t tileIndex = flagmap.get(tileX,tileY);
                switch (tileIndex) {
                    case 255: break; // empty
                }
            }
            if (followHorizontal) {

            } else {

            }
        } while (tileX != tileX2 || tileY != tileY2);
        return false;
    }

    template<class TColor>
    bool Scene<TColor>::isPixelFree(const int x, const int y, uint8_t& tileIndexOut) const {
        if (!flagmap.isValid()) return true;
        const uint8_t tileSizeBits = tileset.tileSizeBits;
        const int16_t tileX = x >> tileSizeBits;
        const int16_t tileY = y >> tileSizeBits;
        const uint8_t width = tilemaps[0].getWidth();
        const uint8_t height = tilemaps[0].getHeight();

        if (tileX < 0 || tileY < 0 || tileX >= width || tileY >= height) {
            return true;
        }

        const uint8_t tileIndex = flagmap.get(tileX,tileY);

        /*const uint8_t tileIndex = foreground.get(tileX,tileY);
        if (tileIndex == 255) {
            return true;
        }

        const uint8_t subX = x & ((1<<tileSizeBits)-1);
        const uint8_t subY = y & ((1<<tileSizeBits)-1);
        const bool transparent = tileset.foreground.isTransparent(
                                         ((tileIndex & 0xf) << tileSizeBits) + subX,
                                         ((tileIndex >> 4) << tileSizeBits) + subY);
        if (transparent) return true;
        tileIndexOut = tileIndex;*/
        return tileIndex == 255;
    }

    template<class TColor>
    Math::Vector2D16 Scene<TColor>::moveOut(const Math::Vector2D16& pos, const uint8_t distleft, const uint8_t distright, const uint8_t disttop, const uint8_t distbottom) const {
        uint8_t tileIndex;
        if (isPixelFree(pos.x,pos.y,tileIndex)) return pos;

        uint8_t right = 0, left = 0, up = 0, down = 0;
        uint8_t rightIndex = 0, leftIndex = 0, upIndex = 0, downIndex = 0;
        while (right < 32 && !isPixelFree(pos.x + right, pos.y, rightIndex)) right += 1;
        while (left < 32 && !isPixelFree(pos.x - left, pos.y, leftIndex)) left += 1;
        while (up < 32 && !isPixelFree(pos.x, pos.y - up, upIndex)) up += 1;
        while (down < 32 && !isPixelFree(pos.x, pos.y + down, downIndex)) down += 1;

        if (right - distleft < left - distright && right - distleft < down - disttop && right - distleft < up - distbottom) return pos + Math::Vector2D16(right, 0);
        if (left - distright < down - disttop && left - distright < up - distbottom) return pos + Math::Vector2D16(-left, 0);
        if (up - distbottom <= down - disttop) return pos + Math::Vector2D16(0, -up);
        return pos + Math::Vector2D16(0, down);
    }

    template<class TColor>
    Math::Vector2D16 Scene<TColor>::moveOut(const Math::Vector2D16& pos) const {
        return moveOut(pos,0,0,0,0);
    }
    template class Scene<uint8_t>;
    template class Scene<uint16_t>;
}
<commit_msg>Fixing bug with wrong rectangle boundary check<commit_after>#include "lib_tilemap.h"
#include <stdio.h>

namespace TileMap {
    static bool isRectIntersectingRect(int ax1,int ay1,int ax2,int ay2, int bx1, int by1, int bx2, int by2) {
        return !(ax2 < bx1 || bx2 < ax1 || ay2 < by1 || by2 < ay1);
    }

    template<class TColor>
    bool Scene<TColor>::isRectFree(const int x1, const int y1, const int x2, const int y2) const {
        if (!flagmap.isValid()) return true;
        const uint8_t tileSizeBits = tileset.tileSizeBits;
        const uint8_t tileSize = 1 << tileSizeBits;
        const int16_t tileX1 = x1 >> tileSizeBits;
        const int16_t tileY1 = y1 >> tileSizeBits;
        const int16_t tileX2 = x2 >> tileSizeBits;
        const int16_t tileY2 = y2 >> tileSizeBits;

        const uint8_t width = tilemaps[0].getWidth();
        const uint8_t height = tilemaps[0].getHeight();

        for (int tileX = tileX1;tileX <= tileX2; tileX+=1)
        {
            for (int tileY = tileY1;tileY <= tileY2; tileY+=1)
            {
                if (tileX < 0 || tileY < 0 || tileX >= width || tileY >= height) {
                    continue;
                }

                const uint8_t tileIndex = flagmap.get(tileX,tileY);
                if (tileIndex != 255)
                {
                    int16_t left= tileX << tileSizeBits;
                    int16_t top = tileY << tileSizeBits;
                    switch(tileIndex) {
                    case 0:
                        return false;
                    case 5: // top half blocked
                        //printf("%d,%d : %d,%d  |  %d,%d : %d,%d\n",x1,y1,x2,y2, left,top,left+tileSize,top+tileSize/2);
                        if (isRectIntersectingRect(x1,y1,x2,y2, left,top,left+tileSize,top+tileSize/2)) {
                            return false;
                        }
                        break;
                    case 6: // bottom half blocked
                        if (isRectIntersectingRect(x1,y1,x2,y2, left,top+tileSize/2,left+tileSize,top+tileSize)) {
                            return false;
                        }
                        break;
                    case 7: // left half blocked
                        if (isRectIntersectingRect(x1,y1,x2,y2, left,top,left+tileSize/2,top+tileSize)) {
                            return false;
                        }
                        break;
                    case 8: // right half blocked
                        if (isRectIntersectingRect(x1,y1,x2,y2, left+tileSize/2,top,left+tileSize,top+tileSize)) {
                            return false;
                        }
                        break;
                    default:
                        #ifdef WIN32
                        printf("unhandled flagmap id: %d\n",tileIndex);
                        #endif
                        break;
                    }
                }
            }
        }
        return true;
    }
    template<class TColor>
    bool Scene<TColor>::findLineIntersection(int x1, int y1, int x2, int y2, int &resultX, int &resultY) const {
        int dx = x2 - x1;
        int dy = y2 - y1;
        const bool followHorizontal = abs(dx) >= abs(dy);

        if ((followHorizontal && x2 < x1) || (!followHorizontal && y2 < y1)) {
            int tmp = x1;
            x1 = x2;
            x2 = tmp;
            tmp = y1;
            y1 = y2;
            y2 = tmp;
            dx = -dx;
            dy = -dy;
        }

        const uint8_t tileSizeBits = tileset.tileSizeBits;
        const uint8_t width = tilemaps[0].getWidth();
        const uint8_t height = tilemaps[0].getHeight();
        const int tileX1 = x1 >> tileSizeBits;
        const int tileX2 = x2 >> tileSizeBits;
        const int tileY1 = y1 >> tileSizeBits;
        const int tileY2 = y2 >> tileSizeBits;

        int x = x1;
        int y = y1;
        int tileX = tileX1;
        int tileY = tileY1;
        do {
            if (tileX >= 0 && tileY >= 0 && tileX < width && tileY < height) {
                const uint8_t tileIndex = flagmap.get(tileX,tileY);
                switch (tileIndex) {
                    case 255: break; // empty
                }
            }
            if (followHorizontal) {

            } else {

            }
        } while (tileX != tileX2 || tileY != tileY2);
        return false;
    }

    template<class TColor>
    bool Scene<TColor>::isPixelFree(const int x, const int y, uint8_t& tileIndexOut) const {
        if (!flagmap.isValid()) return true;
        const uint8_t tileSizeBits = tileset.tileSizeBits;
        const int16_t tileX = x >> tileSizeBits;
        const int16_t tileY = y >> tileSizeBits;
        const uint8_t width = tilemaps[0].getWidth();
        const uint8_t height = tilemaps[0].getHeight();

        if (tileX < 0 || tileY < 0 || tileX >= width || tileY >= height) {
            return true;
        }

        const uint8_t tileIndex = flagmap.get(tileX,tileY);

        /*const uint8_t tileIndex = foreground.get(tileX,tileY);
        if (tileIndex == 255) {
            return true;
        }

        const uint8_t subX = x & ((1<<tileSizeBits)-1);
        const uint8_t subY = y & ((1<<tileSizeBits)-1);
        const bool transparent = tileset.foreground.isTransparent(
                                         ((tileIndex & 0xf) << tileSizeBits) + subX,
                                         ((tileIndex >> 4) << tileSizeBits) + subY);
        if (transparent) return true;
        tileIndexOut = tileIndex;*/
        return tileIndex == 255;
    }

    template<class TColor>
    Math::Vector2D16 Scene<TColor>::moveOut(const Math::Vector2D16& pos, const uint8_t distleft, const uint8_t distright, const uint8_t disttop, const uint8_t distbottom) const {
        uint8_t tileIndex;
        if (isPixelFree(pos.x,pos.y,tileIndex)) return pos;

        uint8_t right = 0, left = 0, up = 0, down = 0;
        uint8_t rightIndex = 0, leftIndex = 0, upIndex = 0, downIndex = 0;
        while (right < 32 && !isPixelFree(pos.x + right, pos.y, rightIndex)) right += 1;
        while (left < 32 && !isPixelFree(pos.x - left, pos.y, leftIndex)) left += 1;
        while (up < 32 && !isPixelFree(pos.x, pos.y - up, upIndex)) up += 1;
        while (down < 32 && !isPixelFree(pos.x, pos.y + down, downIndex)) down += 1;

        if (right - distleft < left - distright && right - distleft < down - disttop && right - distleft < up - distbottom) return pos + Math::Vector2D16(right, 0);
        if (left - distright < down - disttop && left - distright < up - distbottom) return pos + Math::Vector2D16(-left, 0);
        if (up - distbottom <= down - disttop) return pos + Math::Vector2D16(0, -up);
        return pos + Math::Vector2D16(0, down);
    }

    template<class TColor>
    Math::Vector2D16 Scene<TColor>::moveOut(const Math::Vector2D16& pos) const {
        return moveOut(pos,0,0,0,0);
    }
    template class Scene<uint8_t>;
    template class Scene<uint16_t>;
}
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2015 Cloudius Systems, Ltd.
 *
 */

/*
 * This file is part of Scylla.
 *
 * Scylla is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Scylla is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Scylla.  If not, see <http://www.gnu.org/licenses/>.
 */

#pragma once
namespace sstables {
class malformed_sstable_exception : public std::exception {
    sstring _msg;
public:
    malformed_sstable_exception(sstring s) : _msg(s) {}
    const char *what() const noexcept {
        return _msg.c_str();
    }
};

struct bufsize_mismatch_exception : malformed_sstable_exception {
    bufsize_mismatch_exception(size_t size, size_t expected) :
        malformed_sstable_exception(sprint("Buffer improperly sized to hold requested data. Got: %ld. Expected: %ld", size, expected))
    {}
};
}
<commit_msg>sstable: Initialize super class of malformed_sstable_exception<commit_after>/*
 * Copyright (C) 2015 Cloudius Systems, Ltd.
 *
 */

/*
 * This file is part of Scylla.
 *
 * Scylla is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Scylla is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Scylla.  If not, see <http://www.gnu.org/licenses/>.
 */

#pragma once
namespace sstables {
class malformed_sstable_exception : public std::exception {
    sstring _msg;
public:
    malformed_sstable_exception(sstring s)
        : std::exception()
        , _msg(s) {}
    const char *what() const noexcept {
        return _msg.c_str();
    }
};

struct bufsize_mismatch_exception : malformed_sstable_exception {
    bufsize_mismatch_exception(size_t size, size_t expected) :
        malformed_sstable_exception(sprint("Buffer improperly sized to hold requested data. Got: %ld. Expected: %ld", size, expected))
    {}
};
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: ACatalog.cxx,v $
 *
 *  $Revision: 1.9 $
 *
 *  last change: $Author: fs $ $Date: 2002-01-18 16:33:01 $
 *
 *  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_ADO_CATALOG_HXX_
#include "ado/ACatalog.hxx"
#endif
#ifndef _CONNECTIVITY_ADO_BCONNECTION_HXX_
#include "ado/AConnection.hxx"
#endif
#ifndef _CONNECTIVITY_ADO_GROUPS_HXX_
#include "ado/AGroups.hxx"
#endif
#ifndef _CONNECTIVITY_ADO_USERS_HXX_
#include "ado/AUsers.hxx"
#endif
#ifndef _CONNECTIVITY_ADO_TABLES_HXX_
#include "ado/ATables.hxx"
#endif
#ifndef _CONNECTIVITY_ADO_VIEWS_HXX_
#include "ado/AViews.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

// -------------------------------------------------------------------------
using namespace connectivity;
using namespace connectivity::ado;
// -------------------------------------------------------------------------
OCatalog::OCatalog(_ADOCatalog* _pCatalog,OConnection* _pCon) : connectivity::sdbcx::OCatalog(_pCon)
                ,m_pConnection(_pCon)
                ,m_aCatalog(_pCatalog)
{
}
// -----------------------------------------------------------------------------
OCatalog::~OCatalog()
{
    if(m_aCatalog.IsValid())
        m_aCatalog.putref_ActiveConnection(NULL);
    m_aCatalog.clear();
}
// -----------------------------------------------------------------------------
void OCatalog::refreshTables()
{
    TStringVector aVector;

    WpADOTables aTables(m_aCatalog.get_Tables());
    aTables.fillElementNames(aVector);

    if(m_pTables)
        m_pTables->reFill(aVector);
    else
        m_pTables = new OTables(this,m_aMutex,aVector,aTables,m_pConnection->getMetaData()->storesMixedCaseQuotedIdentifiers());
}
// -------------------------------------------------------------------------
void OCatalog::refreshViews()
{
    TStringVector aVector;

    WpADOViews aViews = m_aCatalog.get_Views();
    aViews.fillElementNames(aVector);

    if(m_pViews)
        m_pViews->reFill(aVector);
    else
        m_pViews = new OViews(this,m_aMutex,aVector,aViews,m_pConnection->getMetaData()->storesMixedCaseQuotedIdentifiers());
}
// -------------------------------------------------------------------------
void OCatalog::refreshGroups()
{
    TStringVector aVector;

    WpADOGroups aGroups = m_aCatalog.get_Groups();
    aGroups.fillElementNames(aVector);

    if(m_pGroups)
        m_pGroups->reFill(aVector);
    else
        m_pGroups = new OGroups(this,m_aMutex,aVector,aGroups,m_pConnection->getMetaData()->storesMixedCaseQuotedIdentifiers());
}
// -------------------------------------------------------------------------
void OCatalog::refreshUsers()
{
    TStringVector aVector;

    WpADOUsers aUsers = m_aCatalog.get_Users();
    aUsers.fillElementNames(aVector);

    if(m_pUsers)
        m_pUsers->reFill(aVector);
    else
        m_pUsers = new OUsers(this,m_aMutex,aVector,aUsers,m_pConnection->getMetaData()->storesMixedCaseQuotedIdentifiers());
}
// -------------------------------------------------------------------------

<commit_msg>INTEGRATION: CWS ooo19126 (1.9.332); FILE MERGED 2005/09/05 17:23:11 rt 1.9.332.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: ACatalog.cxx,v $
 *
 *  $Revision: 1.10 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 05:26:06 $
 *
 *  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 _CONNECTIVITY_ADO_CATALOG_HXX_
#include "ado/ACatalog.hxx"
#endif
#ifndef _CONNECTIVITY_ADO_BCONNECTION_HXX_
#include "ado/AConnection.hxx"
#endif
#ifndef _CONNECTIVITY_ADO_GROUPS_HXX_
#include "ado/AGroups.hxx"
#endif
#ifndef _CONNECTIVITY_ADO_USERS_HXX_
#include "ado/AUsers.hxx"
#endif
#ifndef _CONNECTIVITY_ADO_TABLES_HXX_
#include "ado/ATables.hxx"
#endif
#ifndef _CONNECTIVITY_ADO_VIEWS_HXX_
#include "ado/AViews.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

// -------------------------------------------------------------------------
using namespace connectivity;
using namespace connectivity::ado;
// -------------------------------------------------------------------------
OCatalog::OCatalog(_ADOCatalog* _pCatalog,OConnection* _pCon) : connectivity::sdbcx::OCatalog(_pCon)
                ,m_pConnection(_pCon)
                ,m_aCatalog(_pCatalog)
{
}
// -----------------------------------------------------------------------------
OCatalog::~OCatalog()
{
    if(m_aCatalog.IsValid())
        m_aCatalog.putref_ActiveConnection(NULL);
    m_aCatalog.clear();
}
// -----------------------------------------------------------------------------
void OCatalog::refreshTables()
{
    TStringVector aVector;

    WpADOTables aTables(m_aCatalog.get_Tables());
    aTables.fillElementNames(aVector);

    if(m_pTables)
        m_pTables->reFill(aVector);
    else
        m_pTables = new OTables(this,m_aMutex,aVector,aTables,m_pConnection->getMetaData()->storesMixedCaseQuotedIdentifiers());
}
// -------------------------------------------------------------------------
void OCatalog::refreshViews()
{
    TStringVector aVector;

    WpADOViews aViews = m_aCatalog.get_Views();
    aViews.fillElementNames(aVector);

    if(m_pViews)
        m_pViews->reFill(aVector);
    else
        m_pViews = new OViews(this,m_aMutex,aVector,aViews,m_pConnection->getMetaData()->storesMixedCaseQuotedIdentifiers());
}
// -------------------------------------------------------------------------
void OCatalog::refreshGroups()
{
    TStringVector aVector;

    WpADOGroups aGroups = m_aCatalog.get_Groups();
    aGroups.fillElementNames(aVector);

    if(m_pGroups)
        m_pGroups->reFill(aVector);
    else
        m_pGroups = new OGroups(this,m_aMutex,aVector,aGroups,m_pConnection->getMetaData()->storesMixedCaseQuotedIdentifiers());
}
// -------------------------------------------------------------------------
void OCatalog::refreshUsers()
{
    TStringVector aVector;

    WpADOUsers aUsers = m_aCatalog.get_Users();
    aUsers.fillElementNames(aVector);

    if(m_pUsers)
        m_pUsers->reFill(aVector);
    else
        m_pUsers = new OUsers(this,m_aMutex,aVector,aUsers,m_pConnection->getMetaData()->storesMixedCaseQuotedIdentifiers());
}
// -------------------------------------------------------------------------

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: CTables.cxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: oj $ $Date: 2001-10-12 11:45:09 $
 *
 *  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_CALC_TABLES_HXX_
#include "calc/CTables.hxx"
#endif
#ifndef _CONNECTIVITY_CALC_TABLE_HXX_
#include "calc/CTable.hxx"
#endif
#ifndef _CONNECTIVITY_FILE_CATALOG_HXX_
#include "file/FCatalog.hxx"
#endif
#ifndef _CONNECTIVITY_FILE_BCONNECTION_HXX_
#include "file/FConnection.hxx"
#endif
#ifndef _CONNECTIVITY_CALC_CATALOG_HXX_
#include "calc/CCatalog.hxx"
#endif
#ifndef _COMPHELPER_TYPES_HXX_
#include <comphelper/types.hxx>
#endif

using namespace ::comphelper;

using namespace connectivity::calc;
using namespace connectivity::file;
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::lang;
using namespace ::com::sun::star::container;
namespace starutil      = ::com::sun::star::util;

Reference< XNamed > OCalcTables::createObject(const ::rtl::OUString& _rName)
{
    return new OCalcTable(this,(OCalcConnection*)static_cast<OFileCatalog&>(m_rParent).getConnection(),
                                        _rName,::rtl::OUString::createFromAscii("TABLE"));
}
// -------------------------------------------------------------------------

<commit_msg>INTEGRATION: CWS dba24 (1.7.262); FILE MERGED 2005/02/09 08:07:41 oj 1.7.262.1: #i26950# remove the need for XNamed<commit_after>/*************************************************************************
 *
 *  $RCSfile: CTables.cxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: vg $ $Date: 2005-03-10 15:24:44 $
 *
 *  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_CALC_TABLES_HXX_
#include "calc/CTables.hxx"
#endif
#ifndef _CONNECTIVITY_CALC_TABLE_HXX_
#include "calc/CTable.hxx"
#endif
#ifndef _CONNECTIVITY_FILE_CATALOG_HXX_
#include "file/FCatalog.hxx"
#endif
#ifndef _CONNECTIVITY_FILE_BCONNECTION_HXX_
#include "file/FConnection.hxx"
#endif
#ifndef _CONNECTIVITY_CALC_CATALOG_HXX_
#include "calc/CCatalog.hxx"
#endif
#ifndef _COMPHELPER_TYPES_HXX_
#include <comphelper/types.hxx>
#endif

using namespace ::comphelper;
using namespace connectivity;
using namespace connectivity::calc;
using namespace connectivity::file;
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::lang;
using namespace ::com::sun::star::container;
namespace starutil      = ::com::sun::star::util;

sdbcx::ObjectType OCalcTables::createObject(const ::rtl::OUString& _rName)
{
    return new OCalcTable(this,(OCalcConnection*)static_cast<OFileCatalog&>(m_rParent).getConnection(),
                                        _rName,::rtl::OUString::createFromAscii("TABLE"));
}
// -------------------------------------------------------------------------

<|endoftext|>