<commit_before>/* Copyright © 2001-2014, Canal TP and/or its affiliates. All rights reserved.

This file is part of Navitia,
    the software to build cool stuff with public transport.

Hope you'll enjoy and contribute to this project,
    powered by Canal TP (www.canaltp.fr).
Help us simplify mobility and open public transport:
    a non ending quest to the responsive locomotion way of traveling!

LICENCE: This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.

Stay tuned using
twitter @navitia
IRC #navitia on freenode
https://groups.google.com/d/forum/navitia
www.navitia.io
*/

#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE data_manager_test
#include <boost/test/unit_test.hpp>
#include <boost/optional.hpp>

#include "kraken/data_manager.h"
#include <atomic>

namespace navitia { namespace type {

// Wrong data version
struct wrong_version : public navitia::exception {
    wrong_version(const std::string& msg): navitia::exception(msg){}
    wrong_version(const wrong_version&) = default;
    wrong_version& operator=(const wrong_version&) = default;
    virtual ~wrong_version() noexcept;
};

// Data loading exceptions handler
struct data_loading_error : public navitia::exception {
    data_loading_error(const std::string& msg): navitia::exception(msg){}
    data_loading_error(const data_loading_error&) = default;
    data_loading_error& operator=(const data_loading_error&) = default;
    virtual ~data_loading_error() noexcept;
};

// Disruptions exceptions handler. Broken connection
struct disruptions_broken_connection : public navitia::exception {
    disruptions_broken_connection(const std::string& msg): navitia::exception(msg){}
    disruptions_broken_connection(const disruptions_broken_connection&) = default;
    disruptions_broken_connection& operator=(const disruptions_broken_connection&) = default;
    virtual ~disruptions_broken_connection() noexcept;
};

// Disruptions exceptions handler. Loading error
struct disruptions_loading_error : public navitia::exception {
    disruptions_loading_error(const std::string& msg): navitia::exception(msg){}
    disruptions_loading_error(const disruptions_loading_error&) = default;
    disruptions_loading_error& operator=(const disruptions_loading_error&) = default;
    virtual ~disruptions_loading_error() noexcept;
};

// Raptor building exceptions handler
struct raptor_building_error : public navitia::exception {
    raptor_building_error(const std::string& msg): navitia::exception(msg){}
    raptor_building_error(const raptor_building_error&) = default;
    raptor_building_error& operator=(const raptor_building_error&) = default;
    virtual ~raptor_building_error() noexcept;
};

//mock of navitia::type::Data class
class Data{
    public:
        void load_nav(const std::string& filename);
        void load_disruptions(const std::string& database,
                          const std::vector<std::string>& contributors = {});
        void build_raptor(size_t cache_size = 10);
        mutable std::atomic<bool> loading;
        mutable std::atomic<bool> is_connected_to_rabbitmq;
        static bool load_status;
        static bool last_load;
        static bool destructor_called;
        size_t data_identifier;

        Data(size_t data_identifier=0):
            data_identifier(data_identifier)
        {is_connected_to_rabbitmq = false;}

        ~Data(){Data::destructor_called = true;}
};
bool Data::load_status = true;
bool Data::last_load = true;
bool Data::destructor_called = false;

}} //namespace navitia::type

struct fixture{
    fixture(){
        navitia::type::Data::load_status = true;
        navitia::type::Data::destructor_called = false;
    }
};

BOOST_FIXTURE_TEST_SUITE(s, fixture)

BOOST_AUTO_TEST_CASE(get_data) {
    DataManager<navitia::type::Data> data_manager;
    auto data = data_manager.get_data();
    BOOST_REQUIRE(data);
    BOOST_CHECK_EQUAL(navitia::type::Data::destructor_called, false);
}

BOOST_AUTO_TEST_CASE(load_failed) {
    DataManager<navitia::type::Data> data_manager;
    BOOST_CHECK(data_manager.get_data());
    auto first_data = data_manager.get_data();

    // Same pointer
    BOOST_CHECK_EQUAL(first_data, data_manager.get_data());

    // Fake data : Loading failed
    BOOST_CHECK(!data_manager.load("fake path"));

    // Load failed, so the internal shared pointer no change.
    // Data has not changed.
    BOOST_CHECK_EQUAL(first_data, data_manager.get_data());
}

BOOST_AUTO_TEST_CASE(destructor_called) {
    DataManager<navitia::type::Data> data_manager;
    {
        auto first_data = data_manager.get_data();
        BOOST_CHECK(!data_manager.load("fake path"));
        BOOST_CHECK_EQUAL(first_data, data_manager.get_data());
    }
    // type::Data destructor is called because when load function is called,
    // new shared pointer is not used.
    BOOST_CHECK_EQUAL(navitia::type::Data::destructor_called, true);
    BOOST_CHECK(data_manager.get_data());
}

BOOST_AUTO_TEST_CASE(destructor_not_called) {
    DataManager<navitia::type::Data> data_manager;
    {
        auto first_data = data_manager.get_data();
        BOOST_CHECK_EQUAL(first_data, data_manager.get_data());
    }
    // type::Data destructor is called because when load function is called,
    // new shared pointer is not used.
    BOOST_CHECK_EQUAL(navitia::type::Data::destructor_called, false);
    BOOST_CHECK(data_manager.get_data());
}

BOOST_AUTO_TEST_SUITE_END()
<commit_msg>Fix for boost<commit_after>/* Copyright © 2001-2014, Canal TP and/or its affiliates. All rights reserved.

This file is part of Navitia,
    the software to build cool stuff with public transport.

Hope you'll enjoy and contribute to this project,
    powered by Canal TP (www.canaltp.fr).
Help us simplify mobility and open public transport:
    a non ending quest to the responsive locomotion way of traveling!

LICENCE: This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.

Stay tuned using
twitter @navitia
IRC #navitia on freenode
https://groups.google.com/d/forum/navitia
www.navitia.io
*/

#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE data_manager_test

#include "kraken/data_manager.h"

#include <boost/test/unit_test.hpp>
#include <atomic>

namespace navitia { namespace type {

// Wrong data version
struct wrong_version : public navitia::exception {
    wrong_version(const std::string& msg): navitia::exception(msg){}
    wrong_version(const wrong_version&) = default;
    wrong_version& operator=(const wrong_version&) = default;
    virtual ~wrong_version() noexcept;
};

// Data loading exceptions handler
struct data_loading_error : public navitia::exception {
    data_loading_error(const std::string& msg): navitia::exception(msg){}
    data_loading_error(const data_loading_error&) = default;
    data_loading_error& operator=(const data_loading_error&) = default;
    virtual ~data_loading_error() noexcept;
};

// Disruptions exceptions handler. Broken connection
struct disruptions_broken_connection : public navitia::exception {
    disruptions_broken_connection(const std::string& msg): navitia::exception(msg){}
    disruptions_broken_connection(const disruptions_broken_connection&) = default;
    disruptions_broken_connection& operator=(const disruptions_broken_connection&) = default;
    virtual ~disruptions_broken_connection() noexcept;
};

// Disruptions exceptions handler. Loading error
struct disruptions_loading_error : public navitia::exception {
    disruptions_loading_error(const std::string& msg): navitia::exception(msg){}
    disruptions_loading_error(const disruptions_loading_error&) = default;
    disruptions_loading_error& operator=(const disruptions_loading_error&) = default;
    virtual ~disruptions_loading_error() noexcept;
};

// Raptor building exceptions handler
struct raptor_building_error : public navitia::exception {
    raptor_building_error(const std::string& msg): navitia::exception(msg){}
    raptor_building_error(const raptor_building_error&) = default;
    raptor_building_error& operator=(const raptor_building_error&) = default;
    virtual ~raptor_building_error() noexcept;
};

//mock of navitia::type::Data class
class Data{
    public:
        void load_nav(const std::string& filename);
        void load_disruptions(const std::string& database,
                          const std::vector<std::string>& contributors = {});
        void build_raptor(size_t cache_size = 10);
        mutable std::atomic<bool> loading;
        mutable std::atomic<bool> is_connected_to_rabbitmq;
        static bool load_status;
        static bool last_load;
        static bool destructor_called;
        size_t data_identifier;

        Data(size_t data_identifier=0):
            data_identifier(data_identifier)
        {is_connected_to_rabbitmq = false;}

        ~Data(){Data::destructor_called = true;}
};
bool Data::load_status = true;
bool Data::last_load = true;
bool Data::destructor_called = false;

}} //namespace navitia::type

struct fixture{
    fixture(){
        navitia::type::Data::load_status = true;
        navitia::type::Data::destructor_called = false;
    }
};

BOOST_FIXTURE_TEST_CASE(get_data, fixture) {
    DataManager<navitia::type::Data> data_manager;
    auto data = data_manager.get_data();
    BOOST_REQUIRE(data);
    BOOST_CHECK_EQUAL(navitia::type::Data::destructor_called, false);
}

BOOST_FIXTURE_TEST_CASE(load_failed, fixture) {
    DataManager<navitia::type::Data> data_manager;
    BOOST_CHECK(data_manager.get_data());
    auto first_data = data_manager.get_data();

    // Same pointer
    BOOST_CHECK_EQUAL(first_data, data_manager.get_data());

    // Fake data : Loading failed
    BOOST_CHECK(!data_manager.load("fake path"));

    // Load failed, so the internal shared pointer no change.
    // Data has not changed.
    BOOST_CHECK_EQUAL(first_data, data_manager.get_data());
}

BOOST_FIXTURE_TEST_CASE(destructor_called, fixture) {
    DataManager<navitia::type::Data> data_manager;
    {
        auto first_data = data_manager.get_data();
        BOOST_CHECK(!data_manager.load("fake path"));
        BOOST_CHECK_EQUAL(first_data, data_manager.get_data());
    }
    // type::Data destructor is called because when load function is called,
    // new shared pointer is not used.
    BOOST_CHECK_EQUAL(navitia::type::Data::destructor_called, true);
    BOOST_CHECK(data_manager.get_data());
}

BOOST_FIXTURE_TEST_CASE(destructor_not_called, fixture) {
    DataManager<navitia::type::Data> data_manager;
    {
        auto first_data = data_manager.get_data();
        BOOST_CHECK_EQUAL(first_data, data_manager.get_data());
    }
    // type::Data destructor is called because when load function is called,
    // new shared pointer is not used.
    BOOST_CHECK_EQUAL(navitia::type::Data::destructor_called, false);
    BOOST_CHECK(data_manager.get_data());
}
<|endoftext|>


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

  Program:   Visualization Toolkit
  Module:    TestWin32OpenGLRenderWindow.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

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

#include "vtkTestUtilities.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkRenderWindow.h"
#include "vtkRenderer.h"
#include "vtkActor.h"
#include "vtkConeSource.h"
#include "vtkWin32OpenGLRenderWindow.h"
#include <vtkConeSource.h>
#include <vtkPolyData.h>
#include <vtkPolyDataMapper.h>
#include <vtkNew.h>

//This tests if the offscreen rendering works
static bool TestWin32OpenGLRenderWindowOffScreen(vtkWin32OpenGLRenderWindow* renderWindow)
{
  //Create a cone
  vtkNew<vtkConeSource> coneSource;
  coneSource->Update();

  //Create a mapper and actor
  vtkNew<vtkPolyDataMapper> mapper;
  mapper->SetInputConnection(coneSource->GetOutputPort());

  vtkNew<vtkActor> actor;
  actor->SetMapper(mapper.GetPointer());

  //Create a renderer, render window, and interactor
  vtkNew<vtkRenderer> renderer;
  renderWindow->AddRenderer(renderer.GetPointer());

  //Add the actors to the scene
  renderer->AddActor(actor.GetPointer());
  renderer->SetBackground(.3, .2, .1); // Background color dark red

  //Render and interact
  renderWindow->SetOffScreenRendering(1);
  renderWindow->SetSize(100,100);
  renderWindow->Render();
  return 1;
}
int TestWin32OpenGLRenderWindow(int argc, char* argv[])
{
  vtkWin32OpenGLRenderWindow* renderWindow(NULL);

  vtkNew<vtkRenderWindow> renderWindowBase;
  renderWindow = vtkWin32OpenGLRenderWindow::SafeDownCast(renderWindowBase.GetPointer());

  TestWin32OpenGLRenderWindowOffScreen(renderWindow);

  return EXIT_SUCCESS;
}
<commit_msg>COMP: Fix unused param in TestWin32OpenGLRenderWindow.<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    TestWin32OpenGLRenderWindow.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

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

#include "vtkTestUtilities.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkRenderWindow.h"
#include "vtkRenderer.h"
#include "vtkActor.h"
#include "vtkConeSource.h"
#include "vtkWin32OpenGLRenderWindow.h"
#include <vtkConeSource.h>
#include <vtkPolyData.h>
#include <vtkPolyDataMapper.h>
#include <vtkNew.h>

//This tests if the offscreen rendering works
static bool TestWin32OpenGLRenderWindowOffScreen(vtkWin32OpenGLRenderWindow* renderWindow)
{
  //Create a cone
  vtkNew<vtkConeSource> coneSource;
  coneSource->Update();

  //Create a mapper and actor
  vtkNew<vtkPolyDataMapper> mapper;
  mapper->SetInputConnection(coneSource->GetOutputPort());

  vtkNew<vtkActor> actor;
  actor->SetMapper(mapper.GetPointer());

  //Create a renderer, render window, and interactor
  vtkNew<vtkRenderer> renderer;
  renderWindow->AddRenderer(renderer.GetPointer());

  //Add the actors to the scene
  renderer->AddActor(actor.GetPointer());
  renderer->SetBackground(.3, .2, .1); // Background color dark red

  //Render and interact
  renderWindow->SetOffScreenRendering(1);
  renderWindow->SetSize(100,100);
  renderWindow->Render();
  return 1;
}

int TestWin32OpenGLRenderWindow(int vtkNotUsed(argc), char* vtkNotUsed(argv)[])
{
  vtkWin32OpenGLRenderWindow* renderWindow(NULL);

  vtkNew<vtkRenderWindow> renderWindowBase;
  renderWindow = vtkWin32OpenGLRenderWindow::SafeDownCast(renderWindowBase.GetPointer());

  TestWin32OpenGLRenderWindowOffScreen(renderWindow);

  return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>#include <orm/SOCIDriver.h>
#include <util/str_utils.hpp>
#include <ctime>
#include <cstring>

using namespace std;
using Yb::StrUtils::str_to_upper;

namespace Yb {

SOCICursorBackend::SOCICursorBackend(SOCIDatabase *conn)
    :conn_(conn), stmt_(NULL), exec_count_(0)
{}

SOCICursorBackend::~SOCICursorBackend()
{
    close();
}

void
SOCICursorBackend::close()
{
    try {
        if (stmt_) {
            delete stmt_;
            stmt_ = NULL;
            exec_count_ = 0;
            sql_.empty();
        }
    }
    catch (const soci::soci_error &e) {
        throw DBError(WIDEN(e.what()));
    }
}

void
SOCICursorBackend::exec_direct(const String &sql)
{
    try {
        conn_->once << NARROW(sql);
    }
    catch (const soci::soci_error &e) {
        throw DBError(WIDEN(e.what()));
    }
}

void
SOCICursorBackend::prepare(const String &sql)
{
    close();
    std::vector<int> pos_list;
    String first_word;
    if (!find_subst_signs(sql, pos_list, first_word))
        throw DBError(_T("SQL syntax error"));
    std::vector<String> parts;
    split_by_subst_sign(sql, pos_list, parts);
    String sql2 = parts[0];
    for (int i = 1; i < parts.size(); ++i) {
        sql2 += _T(":") + to_string(i);
        sql2 += parts[i];
    }
    sql_ = NARROW(sql2);
    is_select_ = str_to_upper(first_word) == _T("SELECT");
    try {
        stmt_ = new soci::statement(*conn_);
        stmt_->alloc();
        stmt_->prepare(sql_);
    }
    catch (const soci::soci_error &e) {
        throw DBError(WIDEN(e.what()));
    }
}

void
SOCICursorBackend::exec(const Values &params)
{
    try {
        if (!exec_count_) {
            in_params_.resize(params.size());
            in_flags_.resize(params.size());
        }
        else {
            delete stmt_;
            stmt_ = new soci::statement(*conn_);
            stmt_->alloc();
            stmt_->prepare(sql_);
        }
        ++exec_count_;
        for (size_t i = 0; i < params.size(); ++i) {
            const Value &param = params[i];
            in_flags_[i] = soci::i_ok;
            if (param.get_type() == Value::INVALID) {
                if (in_params_[i].size() < sizeof(int))
                    in_params_[i].resize(sizeof(int));
                std::strcpy(&(in_params_[i][0]), "");
                in_flags_[i] = soci::i_null;
                stmt_->exchange(soci::use(in_params_[i], in_flags_[i]));
            }
            else if (param.get_type() == Value::INTEGER) {
                if (in_params_[i].size() < sizeof(int))
                    in_params_[i].resize(sizeof(int));
                int &x = *(int *)&(in_params_[i][0]);
                x = param.as_integer();
                stmt_->exchange(soci::use(x));
            }
            else if (param.get_type() == Value::LONGINT) {
                if (in_params_[i].size() < sizeof(LongInt))
                    in_params_[i].resize(sizeof(LongInt));
                LongInt &x = *(LongInt *)&(in_params_[i][0]);
                x = param.as_longint();
                stmt_->exchange(soci::use(x));
            }
            else if (param.get_type() == Value::DATETIME) {
                if (in_params_[i].size() < sizeof(std::tm))
                    in_params_[i].resize(sizeof(std::tm));
                std::tm &when = *(std::tm *)&(in_params_[i][0]);
                std::memset(&when, 0, sizeof(when));
                DateTime d = param.as_date_time();
                when.tm_year = dt_year(d) - 1900;
                when.tm_mon = dt_month(d) - 1;
                when.tm_mday = dt_day(d);
                when.tm_hour = dt_hour(d);
                when.tm_min = dt_minute(d);
                when.tm_sec = dt_second(d);
                stmt_->exchange(soci::use(when));
            }
            else {
                std::string s = NARROW(param.as_string());
                if (in_params_[i].size() < s.size())
                    in_params_[i].resize(s.size());
                std::strcpy(&(in_params_[i][0]), s.c_str());
                stmt_->exchange(soci::use(in_params_[i]));
            }
        }
        if (is_select_)
            stmt_->exchange(soci::into(row_));
        stmt_->define_and_bind();
        stmt_->execute(!is_select_);
    }
    catch (const soci::soci_error &e) {
        throw DBError(WIDEN(e.what()));
    }
}

RowPtr SOCICursorBackend::fetch_row()
{
    try {
        if (!stmt_->fetch())
            return RowPtr();
        RowPtr result(new Row);
        int col_count = row_.size();
        for (int i = 0; i < col_count; ++i) {
            const soci::column_properties &props = row_.get_properties(i);
            String name = str_to_upper(WIDEN(props.get_name()));
            Value v;
            if (row_.get_indicator(i) != soci::i_null) {
                std::tm when;
                switch (props.get_data_type()) {
                case soci::dt_string:
                    v = Value(WIDEN(row_.get<std::string>(i)));
                    break;
                case soci::dt_double:
                    v = Value(Decimal(row_.get<double>(i)));
                    break;
                case soci::dt_integer:
                    v = Value(row_.get<int>(i));
                    break;
                case soci::dt_unsigned_long:
                case soci::dt_long_long:
                    v = Value(row_.get<long long>(i));
                    break;
                case soci::dt_date:
                    when = row_.get<std::tm>(i);
                    v = Value(dt_make(when.tm_year + 1900, when.tm_mon + 1,
                                when.tm_mday, when.tm_hour,
                                when.tm_min, when.tm_sec));
                    break;
                }
            }
            result->push_back(make_pair(name, v));
        }
        return result;
    }
    catch (const soci::soci_error &e) {
        throw DBError(WIDEN(e.what()));
    }
}

SOCIConnectionBackend::SOCIConnectionBackend(SOCIDriver *drv)
    : conn_(NULL), drv_(drv)
{}

SOCIConnectionBackend::~SOCIConnectionBackend()
{
    close();
}

static const std::string soci_convert_dialect(const String &dialect_name)
{
    if (dialect_name == _T("POSTGRES"))
        return "postgresql";
    if (dialect_name == _T("MYSQL"))
        return "mysql";
    if (dialect_name == _T("ORACLE"))
        return "oracle";
    if (dialect_name == _T("SQLITE"))
        return "sqlite3";
    if (dialect_name == _T("INTERBASE"))
        return "firebird";
    throw SqlDialectError(_T("Unsupported dialect: ") + dialect_name);
}

void
SOCIConnectionBackend::open(SqlDialect *dialect, const SqlSource &source)
{
    close();
    ScopedLock lock(drv_->conn_mux_);
    try {
        conn_ = new SOCIDatabase(soci_convert_dialect(dialect->get_name()),
                NARROW(source.db()));
        //conn_->set_log_stream(&std::cerr);
    }
    catch (const soci::soci_error &e) {
        throw DBError(WIDEN(e.what()));
    }
}

auto_ptr<SqlCursorBackend>
SOCIConnectionBackend::new_cursor()
{
    auto_ptr<SqlCursorBackend> p(
            (SqlCursorBackend *)new SOCICursorBackend(conn_));
    return p;
}

void SOCIConnectionBackend::close()
{
    ScopedLock lock(drv_->conn_mux_);
    try {
        if (conn_) {
            delete conn_;
            conn_ = NULL;
        }
    }
    catch (const soci::soci_error &e) {
        throw DBError(WIDEN(e.what()));
    }
}

void
SOCIConnectionBackend::commit()
{
    try {
        conn_->commit();
    }
    catch (const soci::soci_error &e) {
        throw DBError(WIDEN(e.what()));
    }
}

void
SOCIConnectionBackend::rollback()
{
    try {
        conn_->rollback();
    }
    catch (const soci::soci_error &e) {
        throw DBError(WIDEN(e.what()));
    }
}

SOCIDriver::SOCIDriver():
    SqlDriver(_T("SOCI"))
{}

auto_ptr<SqlConnectionBackend>
SOCIDriver::create_backend()
{
    auto_ptr<SqlConnectionBackend> p(
            (SqlConnectionBackend *)new SOCIConnectionBackend(this));
    return p;
}

void
SOCIDriver::parse_url_tail(const String &dialect_name,
        const String &url_tail, StringDict &source)
{
    source.set(_T("&db"), url_tail);
}

} //namespace Yb

// vim:ts=4:sts=4:sw=4:et:
<commit_msg>YB_SOCI_DEBUG: debugging SOCI backend<commit_after>#include <orm/SOCIDriver.h>
#include <util/str_utils.hpp>
#include <ctime>
#include <cstring>

using namespace std;
using Yb::StrUtils::str_to_upper;

//#define YB_SOCI_DEBUG

namespace Yb {

SOCICursorBackend::SOCICursorBackend(SOCIDatabase *conn)
    :conn_(conn), stmt_(NULL), exec_count_(0)
{}

SOCICursorBackend::~SOCICursorBackend()
{
    close();
}

void
SOCICursorBackend::close()
{
    try {
        if (stmt_) {
            delete stmt_;
            stmt_ = NULL;
            exec_count_ = 0;
            sql_.empty();
        }
    }
    catch (const soci::soci_error &e) {
        throw DBError(WIDEN(e.what()));
    }
}

void
SOCICursorBackend::exec_direct(const String &sql)
{
    try {
        conn_->once << NARROW(sql);
    }
    catch (const soci::soci_error &e) {
        throw DBError(WIDEN(e.what()));
    }
}

void
SOCICursorBackend::prepare(const String &sql)
{
    close();
    vector<int> pos_list;
    String first_word;
    if (!find_subst_signs(sql, pos_list, first_word))
        throw DBError(_T("SQL syntax error"));
    vector<String> parts;
    split_by_subst_sign(sql, pos_list, parts);
    String sql2 = parts[0];
    for (int i = 1; i < parts.size(); ++i) {
        sql2 += _T(":") + to_string(i);
        sql2 += parts[i];
    }
    sql_ = NARROW(sql2);
    is_select_ = str_to_upper(first_word) == _T("SELECT");
    try {
        stmt_ = new soci::statement(*conn_);
        stmt_->alloc();
        stmt_->prepare(sql_);
    }
    catch (const soci::soci_error &e) {
        throw DBError(WIDEN(e.what()));
    }
}

void
SOCICursorBackend::exec(const Values &params)
{
    try {
        if (!exec_count_) {
            in_params_.resize(params.size());
            in_flags_.resize(params.size());
        }
        else {
            delete stmt_;
            stmt_ = new soci::statement(*conn_);
            stmt_->alloc();
            stmt_->prepare(sql_);
        }
        ++exec_count_;
        for (size_t i = 0; i < params.size(); ++i) {
            const Value &param = params[i];
            in_flags_[i] = soci::i_ok;
            if (param.get_type() == Value::INVALID) {
                if (in_params_[i].size() < sizeof(int))
                    in_params_[i].resize(sizeof(int));
                strcpy(&(in_params_[i][0]), "");
                in_flags_[i] = soci::i_null;
                stmt_->exchange(soci::use(in_params_[i], in_flags_[i]));
            }
            else if (param.get_type() == Value::INTEGER) {
                if (in_params_[i].size() < sizeof(int))
                    in_params_[i].resize(sizeof(int));
                int &x = *(int *)&(in_params_[i][0]);
                x = param.as_integer();
                stmt_->exchange(soci::use(x));
            }
            else if (param.get_type() == Value::LONGINT) {
                if (in_params_[i].size() < sizeof(LongInt))
                    in_params_[i].resize(sizeof(LongInt));
                LongInt &x = *(LongInt *)&(in_params_[i][0]);
                x = param.as_longint();
                stmt_->exchange(soci::use(x));
            }
            else if (param.get_type() == Value::DATETIME) {
                if (in_params_[i].size() < sizeof(std::tm))
                    in_params_[i].resize(sizeof(std::tm));
                std::tm &when = *(std::tm *)&(in_params_[i][0]);
                memset(&when, 0, sizeof(when));
                DateTime d = param.as_date_time();
                when.tm_year = dt_year(d) - 1900;
                when.tm_mon = dt_month(d) - 1;
                when.tm_mday = dt_day(d);
                when.tm_hour = dt_hour(d);
                when.tm_min = dt_minute(d);
                when.tm_sec = dt_second(d);
                stmt_->exchange(soci::use(when));
            }
            else {
                string s = NARROW(param.as_string());
                if (in_params_[i].size() < s.size())
                    in_params_[i].resize(s.size());
                strcpy(&(in_params_[i][0]), s.c_str());
                stmt_->exchange(soci::use(in_params_[i]));
            }
        }
        if (is_select_)
            stmt_->exchange(soci::into(row_));
        stmt_->define_and_bind();
        stmt_->execute(!is_select_);
    }
    catch (const soci::soci_error &e) {
        throw DBError(WIDEN(e.what()));
    }
}

RowPtr SOCICursorBackend::fetch_row()
{
    try {
        if (!stmt_->fetch()) {
#ifdef YB_SOCI_DEBUG
            cerr << "fetch(): false" << endl;
#endif
            return RowPtr();
        }
        RowPtr result(new Row);
        int col_count = row_.size();
#ifdef YB_SOCI_DEBUG
        cerr << "fetch(): col_count=" << col_count << endl;
#endif
        for (int i = 0; i < col_count; ++i) {
            const soci::column_properties &props = row_.get_properties(i);
            String name = str_to_upper(WIDEN(props.get_name()));
            Value v;
            if (row_.get_indicator(i) != soci::i_null) {
                std::tm when;
                unsigned long long x;
                switch (props.get_data_type()) {
                case soci::dt_string:
                    v = Value(WIDEN(row_.get<string>(i)));
                    break;
                case soci::dt_double:
                    v = Value(Decimal(row_.get<double>(i)));
                    break;
                case soci::dt_integer:
                    v = Value(row_.get<int>(i));
                    break;
#if 0
                case soci::dt_unsigned_long:
                    x = row_.get<unsigned long>(i);
                    v = Value((LongInt)x);
                    break;
#endif
                case soci::dt_long_long:
                    x = row_.get<long long>(i);
                    v = Value((LongInt)x);
                    break;
                case soci::dt_unsigned_long_long:
                    x = row_.get<unsigned long long>(i);
                    v = Value((LongInt)x);
                    break;
                case soci::dt_date:
                    when = row_.get<std::tm>(i);
                    v = Value(dt_make(when.tm_year + 1900, when.tm_mon + 1,
                                when.tm_mday, when.tm_hour,
                                when.tm_min, when.tm_sec));
                    break;
                }
            }
#ifdef YB_SOCI_DEBUG
            cerr << "fetch(): col[" << i << "]: name=" << props.get_name()
                << " type=" << props.get_data_type()
                << " value=" << NARROW(v.sql_str()) << endl;
#endif
            result->push_back(make_pair(name, v));
        }
        return result;
    }
    catch (const soci::soci_error &e) {
        throw DBError(WIDEN(e.what()));
    }
}

SOCIConnectionBackend::SOCIConnectionBackend(SOCIDriver *drv)
    : conn_(NULL), drv_(drv)
{}

SOCIConnectionBackend::~SOCIConnectionBackend()
{
    close();
}

static const string soci_convert_dialect(const String &dialect_name)
{
    if (dialect_name == _T("POSTGRES"))
        return "postgresql";
    if (dialect_name == _T("MYSQL"))
        return "mysql";
    if (dialect_name == _T("ORACLE"))
        return "oracle";
    if (dialect_name == _T("SQLITE"))
        return "sqlite3";
    if (dialect_name == _T("INTERBASE"))
        return "firebird";
    throw SqlDialectError(_T("Unsupported dialect: ") + dialect_name);
}

void
SOCIConnectionBackend::open(SqlDialect *dialect, const SqlSource &source)
{
    close();
    ScopedLock lock(drv_->conn_mux_);
    try {
        conn_ = new SOCIDatabase(soci_convert_dialect(dialect->get_name()),
                NARROW(source.db()));
#ifdef YB_SOCI_DEBUG
        conn_->set_log_stream(&cerr);
#endif
    }
    catch (const soci::soci_error &e) {
        throw DBError(WIDEN(e.what()));
    }
}

auto_ptr<SqlCursorBackend>
SOCIConnectionBackend::new_cursor()
{
    auto_ptr<SqlCursorBackend> p(
            (SqlCursorBackend *)new SOCICursorBackend(conn_));
    return p;
}

void SOCIConnectionBackend::close()
{
    ScopedLock lock(drv_->conn_mux_);
    try {
        if (conn_) {
            delete conn_;
            conn_ = NULL;
        }
    }
    catch (const soci::soci_error &e) {
        throw DBError(WIDEN(e.what()));
    }
}

void
SOCIConnectionBackend::commit()
{
    try {
        conn_->commit();
    }
    catch (const soci::soci_error &e) {
        throw DBError(WIDEN(e.what()));
    }
}

void
SOCIConnectionBackend::rollback()
{
    try {
        conn_->rollback();
    }
    catch (const soci::soci_error &e) {
        throw DBError(WIDEN(e.what()));
    }
}

SOCIDriver::SOCIDriver():
    SqlDriver(_T("SOCI"))
{}

auto_ptr<SqlConnectionBackend>
SOCIDriver::create_backend()
{
    auto_ptr<SqlConnectionBackend> p(
            (SqlConnectionBackend *)new SOCIConnectionBackend(this));
    return p;
}

void
SOCIDriver::parse_url_tail(const String &dialect_name,
        const String &url_tail, StringDict &source)
{
    source.set(_T("&db"), url_tail);
}

} //namespace Yb

// vim:ts=4:sts=4:sw=4:et:
<|endoftext|>


<commit_before><commit_msg>Resolves: fdo#85590 'Pick a color' circle location is incorrect when opened<commit_after><|endoftext|>


<commit_before>namespace ImGui
{
//    const char* title;
//    if (Begin(title, &Open))
//    {
//        End();
//    }

    void MemoryEditor::Draw(void* mem_data_void, int mem_size, int base_display_addr)
    {
        PushFont(Font::Mono);

        unsigned char* mem_data = (unsigned char*)mem_data_void;

        BeginChild("##scrolling", ImVec2(0, -GetItemsLineHeightWithSpacing()));

        if (ImGui::BeginPopupContextWindow() )
        {
            ImGui::Checkbox("HexII", &HexII);
            ImGui::EndPopup();
        }

        PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0.0f, 0.0f) );
        PushStyleVar(ImGuiStyleVar_ItemSpacing,  ImVec2(0.0f, 0.0f) );

        int addr_digits_count = 0;
        for (int n = base_display_addr + mem_size - 1; n > 0; n >>= 4)
        {
            addr_digits_count++;
        }

        float glyph_width = CalcTextSize("F").x;
        float cell_width = glyph_width * 3; // "FF " we include trailing space in the width to easily catch clicks everywhere

        float line_height = GetTextLineHeight();
        int line_total_count = (int)((mem_size + Rows-1) / Rows);
        ImGuiListClipper clipper(line_total_count, line_height);
        int visible_start_addr = clipper.DisplayStart * Rows;
        int visible_end_addr = clipper.DisplayEnd * Rows;

        bool data_next = false;

        if (!AllowEdits || DataEditingAddr >= mem_size)
        {
            DataEditingAddr = -1;
        }

        int data_editing_addr_backup = DataEditingAddr;
        if (DataEditingAddr != -1)
        {
            if (IsKeyPressed(GetKeyIndex(ImGuiKey_UpArrow)) && DataEditingAddr >= Rows)                    { DataEditingAddr -= Rows; DataEditingTakeFocus = true; }
            else if (IsKeyPressed(GetKeyIndex(ImGuiKey_DownArrow))  && DataEditingAddr < mem_size - Rows)  { DataEditingAddr += Rows; DataEditingTakeFocus = true; }
            else if (IsKeyPressed(GetKeyIndex(ImGuiKey_LeftArrow))  && DataEditingAddr > 0)                { DataEditingAddr -= 1;    DataEditingTakeFocus = true; }
            else if (IsKeyPressed(GetKeyIndex(ImGuiKey_RightArrow)) && DataEditingAddr < mem_size - 1)     { DataEditingAddr += 1;    DataEditingTakeFocus = true; }
        }

        if ((DataEditingAddr / Rows) != (data_editing_addr_backup / Rows))
        {
            // Track cursor movements
            float scroll_offset = ((DataEditingAddr / Rows) - (data_editing_addr_backup / Rows)) * line_height;
            bool scroll_desired = (scroll_offset < 0.0f && DataEditingAddr < visible_start_addr + Rows*2) || (scroll_offset > 0.0f && DataEditingAddr > visible_end_addr - Rows*2);
            if (scroll_desired)
            {
                SetScrollY(GetScrollY() + scroll_offset);
            }
        }

        bool draw_separator = true;
        for (int line_i = clipper.DisplayStart; line_i < clipper.DisplayEnd; line_i++) // display only visible items
        {
            int addr = line_i * Rows;
            Text("%0*x: ", addr_digits_count, base_display_addr+addr);
            SameLine();

            // Draw Hexadecimal
            float line_start_x = GetCursorPosX();
            for (int n = 0; n < Rows && addr < mem_size; n++, addr++)
            {
                SameLine(line_start_x + cell_width * n);

                if (DataEditingAddr == addr)
                {
                    // Display text input on current byte
                    PushID(addr);
                    struct FuncHolder
                    {
                        // FIXME: We should have a way to retrieve the text edit cursor position more easily in the API, this is rather tedious.
                        static int Callback(ImGuiTextEditCallbackData* data)
                        {
                            int* p_cursor_pos = (int*)data->UserData;
                            if (!data->HasSelection())
                            {
                                *p_cursor_pos = data->CursorPos;
                            }
                            return 0;
                        }
                    };
                    int cursor_pos = -1;
                    bool data_write = false;
                    if (DataEditingTakeFocus)
                    {
                        SetKeyboardFocusHere();
                        snprintf(AddrInput, sizeof(AddrInput), "%0*x", addr_digits_count, base_display_addr+addr);
                        snprintf(DataInput, sizeof(DataInput), "%02x", mem_data[addr]);
                    }

                    PushItemWidth(CalcTextSize("FF").x);
                    ImGuiInputTextFlags flags = ImGuiInputTextFlags_CharsHexadecimal|ImGuiInputTextFlags_EnterReturnsTrue|ImGuiInputTextFlags_AutoSelectAll|ImGuiInputTextFlags_NoHorizontalScroll|ImGuiInputTextFlags_AlwaysInsertMode|ImGuiInputTextFlags_CallbackAlways;
                    if (InputText("##data", DataInput, 32, flags, FuncHolder::Callback, &cursor_pos))
                    {
                        data_write = data_next = true;
                    }
                    else if (!DataEditingTakeFocus && !IsItemActive())
                    {
                        DataEditingAddr = -1;
                    }

                    DataEditingTakeFocus = false;
                    PopItemWidth();
                    if (cursor_pos >= 2)
                    {
                        data_write = data_next = true;
                    }

                    if (data_write)
                    {
                        int data;
                        if (sscanf(DataInput, "%X", &data) == 1)
                        {
                            mem_data[addr] = (unsigned char)data;
                        }
                    }
                    PopID();
                }
                else
                {
                    if (HexII)
                    {
                        unsigned char byte = mem_data[addr];
                        if (isprint(byte) )
                        {
                            Text(".%c ", byte);
                        }
                        else if (0x00 == byte)
                        {
                            Text("   ");
                        }
                        else if (0xff == byte)
                        {
                            Text("## ");
                        }
                        else
                        {
                            Text("%02x ", byte);
                        }
                    }
                    else
                    {
                        Text("%02x ", mem_data[addr]);
                    }

                    if (AllowEdits && IsItemHovered() && IsMouseClicked(0))
                    {
                        DataEditingTakeFocus = true;
                        DataEditingAddr = addr;
                    }
                }
            }

            SameLine(line_start_x + cell_width * Rows + glyph_width * 2);

            if (draw_separator)
            {
                ImVec2 screen_pos = GetCursorScreenPos();
                GetWindowDrawList()->AddLine(ImVec2(screen_pos.x - glyph_width, screen_pos.y - 9999), ImVec2(screen_pos.x - glyph_width, screen_pos.y + 9999), ImColor(GetStyle().Colors[ImGuiCol_Border]));
                draw_separator = false;
            }

            // Draw ASCII values
            addr = line_i * Rows;
            for (int n = 0; n < Rows && addr < mem_size; n++, addr++)
            {
                if (n > 0) { SameLine(); }
                int c = mem_data[addr];
                Text("%c", (c >= 32 && c < 128) ? c : '.');
            }
        }
        clipper.End();
        PopStyleVar(2);

        EndChild();

        if (data_next && DataEditingAddr < mem_size)
        {
            DataEditingAddr = DataEditingAddr + 1;
            DataEditingTakeFocus = true;
        }

        Separator();

        AlignFirstTextHeightToWidgets();
        PushItemWidth(50);
        PushAllowKeyboardFocus(false);
        int rows_backup = Rows;
        if (DragInt("##rows", &Rows, 0.2f, 4, 32, "%.0f rows"))
        {
            ImVec2 new_window_size = GetWindowSize();
            new_window_size.x += (Rows - rows_backup) * (cell_width + glyph_width);
            SetWindowSize(new_window_size);
        }

        PopAllowKeyboardFocus();
        PopItemWidth();
        SameLine();
        Text("Range %0*x..%0*x", addr_digits_count, (int)base_display_addr, addr_digits_count, (int)base_display_addr+mem_size-1);
        SameLine();
        PushItemWidth(70);
        if (InputText("##addr", AddrInput, 32, ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_EnterReturnsTrue))
        {
            int goto_addr;
            if (sscanf(AddrInput, "%X", &goto_addr) == 1)
            {
                goto_addr -= base_display_addr;
                if (goto_addr >= 0 && goto_addr < mem_size)
                {
                    BeginChild("##scrolling");
                    SetScrollFromPosY(GetCursorStartPos().y + (goto_addr / Rows) * GetTextLineHeight());
                    EndChild();
                    DataEditingAddr = goto_addr;
                    DataEditingTakeFocus = true;
                }
            }
        }

        PopItemWidth();

        PopFont();
    }

    void MemoryEditor::Draw(const void* mem_data, int mem_size, int base_display_addr)
    {
        Draw(const_cast<void*>(mem_data), mem_size, base_display_addr);
    }

} // namespace ImGui
<commit_msg>Fixed VS build.<commit_after>#ifdef _MSC_VER
#   define snprintf _snprintf
#endif

namespace ImGui
{
//    const char* title;
//    if (Begin(title, &Open))
//    {
//        End();
//    }

    void MemoryEditor::Draw(void* mem_data_void, int mem_size, int base_display_addr)
    {
        PushFont(Font::Mono);

        unsigned char* mem_data = (unsigned char*)mem_data_void;

        BeginChild("##scrolling", ImVec2(0, -GetItemsLineHeightWithSpacing()));

        if (ImGui::BeginPopupContextWindow() )
        {
            ImGui::Checkbox("HexII", &HexII);
            ImGui::EndPopup();
        }

        PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0.0f, 0.0f) );
        PushStyleVar(ImGuiStyleVar_ItemSpacing,  ImVec2(0.0f, 0.0f) );

        int addr_digits_count = 0;
        for (int n = base_display_addr + mem_size - 1; n > 0; n >>= 4)
        {
            addr_digits_count++;
        }

        float glyph_width = CalcTextSize("F").x;
        float cell_width = glyph_width * 3; // "FF " we include trailing space in the width to easily catch clicks everywhere

        float line_height = GetTextLineHeight();
        int line_total_count = (int)((mem_size + Rows-1) / Rows);
        ImGuiListClipper clipper(line_total_count, line_height);
        int visible_start_addr = clipper.DisplayStart * Rows;
        int visible_end_addr = clipper.DisplayEnd * Rows;

        bool data_next = false;

        if (!AllowEdits || DataEditingAddr >= mem_size)
        {
            DataEditingAddr = -1;
        }

        int data_editing_addr_backup = DataEditingAddr;
        if (DataEditingAddr != -1)
        {
            if (IsKeyPressed(GetKeyIndex(ImGuiKey_UpArrow)) && DataEditingAddr >= Rows)                    { DataEditingAddr -= Rows; DataEditingTakeFocus = true; }
            else if (IsKeyPressed(GetKeyIndex(ImGuiKey_DownArrow))  && DataEditingAddr < mem_size - Rows)  { DataEditingAddr += Rows; DataEditingTakeFocus = true; }
            else if (IsKeyPressed(GetKeyIndex(ImGuiKey_LeftArrow))  && DataEditingAddr > 0)                { DataEditingAddr -= 1;    DataEditingTakeFocus = true; }
            else if (IsKeyPressed(GetKeyIndex(ImGuiKey_RightArrow)) && DataEditingAddr < mem_size - 1)     { DataEditingAddr += 1;    DataEditingTakeFocus = true; }
        }

        if ((DataEditingAddr / Rows) != (data_editing_addr_backup / Rows))
        {
            // Track cursor movements
            float scroll_offset = ((DataEditingAddr / Rows) - (data_editing_addr_backup / Rows)) * line_height;
            bool scroll_desired = (scroll_offset < 0.0f && DataEditingAddr < visible_start_addr + Rows*2) || (scroll_offset > 0.0f && DataEditingAddr > visible_end_addr - Rows*2);
            if (scroll_desired)
            {
                SetScrollY(GetScrollY() + scroll_offset);
            }
        }

        bool draw_separator = true;
        for (int line_i = clipper.DisplayStart; line_i < clipper.DisplayEnd; line_i++) // display only visible items
        {
            int addr = line_i * Rows;
            Text("%0*x: ", addr_digits_count, base_display_addr+addr);
            SameLine();

            // Draw Hexadecimal
            float line_start_x = GetCursorPosX();
            for (int n = 0; n < Rows && addr < mem_size; n++, addr++)
            {
                SameLine(line_start_x + cell_width * n);

                if (DataEditingAddr == addr)
                {
                    // Display text input on current byte
                    PushID(addr);
                    struct FuncHolder
                    {
                        // FIXME: We should have a way to retrieve the text edit cursor position more easily in the API, this is rather tedious.
                        static int Callback(ImGuiTextEditCallbackData* data)
                        {
                            int* p_cursor_pos = (int*)data->UserData;
                            if (!data->HasSelection())
                            {
                                *p_cursor_pos = data->CursorPos;
                            }
                            return 0;
                        }
                    };
                    int cursor_pos = -1;
                    bool data_write = false;
                    if (DataEditingTakeFocus)
                    {
                        SetKeyboardFocusHere();
                        snprintf(AddrInput, sizeof(AddrInput), "%0*x", addr_digits_count, base_display_addr+addr);
                        snprintf(DataInput, sizeof(DataInput), "%02x", mem_data[addr]);
                    }

                    PushItemWidth(CalcTextSize("FF").x);
                    ImGuiInputTextFlags flags = ImGuiInputTextFlags_CharsHexadecimal|ImGuiInputTextFlags_EnterReturnsTrue|ImGuiInputTextFlags_AutoSelectAll|ImGuiInputTextFlags_NoHorizontalScroll|ImGuiInputTextFlags_AlwaysInsertMode|ImGuiInputTextFlags_CallbackAlways;
                    if (InputText("##data", DataInput, 32, flags, FuncHolder::Callback, &cursor_pos))
                    {
                        data_write = data_next = true;
                    }
                    else if (!DataEditingTakeFocus && !IsItemActive())
                    {
                        DataEditingAddr = -1;
                    }

                    DataEditingTakeFocus = false;
                    PopItemWidth();
                    if (cursor_pos >= 2)
                    {
                        data_write = data_next = true;
                    }

                    if (data_write)
                    {
                        int data;
                        if (sscanf(DataInput, "%X", &data) == 1)
                        {
                            mem_data[addr] = (unsigned char)data;
                        }
                    }
                    PopID();
                }
                else
                {
                    if (HexII)
                    {
                        unsigned char byte = mem_data[addr];
                        if (isprint(byte) )
                        {
                            Text(".%c ", byte);
                        }
                        else if (0x00 == byte)
                        {
                            Text("   ");
                        }
                        else if (0xff == byte)
                        {
                            Text("## ");
                        }
                        else
                        {
                            Text("%02x ", byte);
                        }
                    }
                    else
                    {
                        Text("%02x ", mem_data[addr]);
                    }

                    if (AllowEdits && IsItemHovered() && IsMouseClicked(0))
                    {
                        DataEditingTakeFocus = true;
                        DataEditingAddr = addr;
                    }
                }
            }

            SameLine(line_start_x + cell_width * Rows + glyph_width * 2);

            if (draw_separator)
            {
                ImVec2 screen_pos = GetCursorScreenPos();
                GetWindowDrawList()->AddLine(ImVec2(screen_pos.x - glyph_width, screen_pos.y - 9999), ImVec2(screen_pos.x - glyph_width, screen_pos.y + 9999), ImColor(GetStyle().Colors[ImGuiCol_Border]));
                draw_separator = false;
            }

            // Draw ASCII values
            addr = line_i * Rows;
            for (int n = 0; n < Rows && addr < mem_size; n++, addr++)
            {
                if (n > 0) { SameLine(); }
                int c = mem_data[addr];
                Text("%c", (c >= 32 && c < 128) ? c : '.');
            }
        }
        clipper.End();
        PopStyleVar(2);

        EndChild();

        if (data_next && DataEditingAddr < mem_size)
        {
            DataEditingAddr = DataEditingAddr + 1;
            DataEditingTakeFocus = true;
        }

        Separator();

        AlignFirstTextHeightToWidgets();
        PushItemWidth(50);
        PushAllowKeyboardFocus(false);
        int rows_backup = Rows;
        if (DragInt("##rows", &Rows, 0.2f, 4, 32, "%.0f rows"))
        {
            ImVec2 new_window_size = GetWindowSize();
            new_window_size.x += (Rows - rows_backup) * (cell_width + glyph_width);
            SetWindowSize(new_window_size);
        }

        PopAllowKeyboardFocus();
        PopItemWidth();
        SameLine();
        Text("Range %0*x..%0*x", addr_digits_count, (int)base_display_addr, addr_digits_count, (int)base_display_addr+mem_size-1);
        SameLine();
        PushItemWidth(70);
        if (InputText("##addr", AddrInput, 32, ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_EnterReturnsTrue))
        {
            int goto_addr;
            if (sscanf(AddrInput, "%X", &goto_addr) == 1)
            {
                goto_addr -= base_display_addr;
                if (goto_addr >= 0 && goto_addr < mem_size)
                {
                    BeginChild("##scrolling");
                    SetScrollFromPosY(GetCursorStartPos().y + (goto_addr / Rows) * GetTextLineHeight());
                    EndChild();
                    DataEditingAddr = goto_addr;
                    DataEditingTakeFocus = true;
                }
            }
        }

        PopItemWidth();

        PopFont();
    }

    void MemoryEditor::Draw(const void* mem_data, int mem_size, int base_display_addr)
    {
        Draw(const_cast<void*>(mem_data), mem_size, base_display_addr);
    }

} // namespace ImGui
<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/*
 * The contents of this file are subject to the Netscape Public License
 * Version 1.1 (the "NPL"); you may not use this file except in
 * compliance with the NPL.  You may obtain a copy of the NPL at
 * http://www.mozilla.org/NPL/
 *
 * Software distributed under the NPL is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
 * for the specific language governing rights and limitations under the
 * NPL.
 *
 * The Initial Developer of this code under the NPL is Netscape
 * Communications Corporation.  Portions created by Netscape are
 * Copyright (C) 1998 Netscape Communications Corporation.  All Rights
 * Reserved.
 */

/*
** Base class implementation for network access functions (ref: prnetdb.h)
*/

#include "rclock.h"
#include "rcnetdb.h"

#include <prmem.h>
#include <prlog.h>
#include <string.h>

RCNetAddr::RCNetAddr(const RCNetAddr& his): RCBase()
    { address = his.address; }

RCNetAddr::RCNetAddr(const RCNetAddr& his, PRUint16 port): RCBase()
{
    address = his.address;
    switch (address.raw.family)
    {
        case PR_AF_INET: address.inet.port = port; break;
#if defined(_PR_INET6)
        case PR_AF_INET6: address.ipv6.port = port; break;
#endif
        default: break;
    }
}  /* RCNetAddr::RCNetAddr */

RCNetAddr::RCNetAddr(RCNetAddr::HostValue host, PRUint16 port): RCBase()
{
    PRNetAddrValue how;
    switch (host)
    {
        case RCNetAddr::any: how = PR_IpAddrAny; break;
        case RCNetAddr::loopback: how = PR_IpAddrLoopback; break;
        default: PR_ASSERT(!"This can't happen -- and did!");
    }
    (void)PR_InitializeNetAddr(how, port, &address);
}  /* RCNetAddr::RCNetAddr */

RCNetAddr::~RCNetAddr() { }

void RCNetAddr::operator=(const RCNetAddr& his) { address = his.address; }

PRStatus RCNetAddr::FromString(const char* string)
    { return PR_StringToNetAddr(string, &address); }

void RCNetAddr::operator=(const PRNetAddr* addr) { address = *addr; }

PRBool RCNetAddr::operator==(const RCNetAddr& his) const
{
    PRBool rv = EqualHost(his);
    if (rv)
    {
        switch (address.raw.family)
        {
            case PR_AF_INET:
                rv = (address.inet.port == his.address.inet.port); break;
#if defined(_PR_INET6)
            case PR_AF_INET6:
                rv = (address.ipv6.port == his.address.ipv6.port); break;
#endif
            case PR_AF_LOCAL:
            default: break;
        }
    }
    return rv;
}  /* RCNetAddr::operator== */

PRBool RCNetAddr::EqualHost(const RCNetAddr& his) const
{
    PRBool rv;
    switch (address.raw.family)
    {
        case PR_AF_INET:
            rv = (address.inet.ip == his.address.inet.ip); break;
#if defined(_PR_INET6)
        case PR_AF_INET6:
            rv = (address.ipv6.ip == his.address.ipv6.ip); break;
#endif
#if defined(XP_UNIX)
        case PR_AF_LOCAL:
            rv = (0 == strncmp(
                address.local.path, his.address.local.path,
                sizeof(address.local.path)));
 #endif
            break;
        default: break;
    }
    return rv;
}  /* RCNetAddr::operator== */

PRStatus RCNetAddr::ToString(char *string, PRSize size) const
    { return PR_NetAddrToString(&address, string, size); }

/*
** RCHostLookup
*/

RCHostLookup::~RCHostLookup()
{
    if (NULL != address) delete [] address;
}  /* RCHostLookup::~RCHostLookup */

RCHostLookup::RCHostLookup(): RCBase()
{
    address = NULL;
    max_index = 0;
}  /* RCHostLookup::RCHostLookup */

PRStatus RCHostLookup::ByName(const char* name)
{
    PRStatus rv;
    PRNetAddr addr;
    PRHostEnt hostentry;
    PRIntn index = 0, max;
    RCNetAddr* vector = NULL;
    RCNetAddr* old_vector = NULL;
    void* buffer = PR_Malloc(PR_NETDB_BUF_SIZE);
    if (NULL == buffer) return PR_FAILURE;
    rv = PR_GetHostByName(name, (char*)buffer, PR_NETDB_BUF_SIZE, &hostentry);
    if (PR_SUCCESS == rv)
    {
        for (max = 0, index = 0;; ++max)
        {
            index = PR_EnumerateHostEnt(index, &hostentry, 0, &addr);
            if (0 == index) break;
        }
        if (max > 0)
        {
            vector = new RCNetAddr[max];
            while (--max > 0)
            {
                index = PR_EnumerateHostEnt(index, &hostentry, 0, &addr);
                if (0 == index) break;
                vector[index] = &addr;
            }
            {
                RCEnter entry(&ml);
                old_vector = address;
                address = vector;
                max_index = max;
            }
            if (NULL != old_vector) delete [] old_vector;
        }
    }
    if (NULL != buffer) PR_DELETE(buffer);
    return PR_SUCCESS;
}  /* RCHostLookup::ByName */

PRStatus RCHostLookup::ByAddress(const RCNetAddr& host_addr)
{
    PRStatus rv;
    PRNetAddr addr;
    PRHostEnt hostentry;
    PRIntn index = 0, max;
    RCNetAddr* vector = NULL;
    RCNetAddr* old_vector = NULL;
    char *buffer = (char*)PR_Malloc(PR_NETDB_BUF_SIZE);
    if (NULL == buffer) return PR_FAILURE;
    rv = PR_GetHostByAddr(host_addr, buffer, PR_NETDB_BUF_SIZE, &hostentry);
    if (PR_SUCCESS == rv)
    {
        for (max = 0, index = 0;; ++max)
        {
            index = PR_EnumerateHostEnt(index, &hostentry, 0, &addr);
            if (0 == index) break;
        }
        if (max > 0)
        {
            vector = new RCNetAddr[max];
            while (--max > 0)
            {
                index = PR_EnumerateHostEnt(index, &hostentry, 0, &addr);
                if (0 == index) break;
                vector[index] = &addr;
            }
            {
                RCEnter entry(&ml);
                old_vector = address;
                address = vector;
                max_index = max;
            }
            if (NULL != old_vector) delete [] old_vector;
        }
    }
    if (NULL != buffer) PR_DELETE(buffer);
    return PR_SUCCESS;
}  /* RCHostLookup::ByAddress */

const RCNetAddr* RCHostLookup::operator[](PRUintn which)
{
    RCNetAddr* addr = NULL;
    if (which < max_index)
        addr = &address[which];
    return addr;
}  /* RCHostLookup::operator[] */

/* RCNetdb.cpp */
<commit_msg>Bugzilla bug #35405: use memcmp, as opposed to ==, to compare two structs. Thanks to Braden N. McDaniel <braden@endoframe.com> for the bug report.<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/*
 * The contents of this file are subject to the Netscape Public License
 * Version 1.1 (the "NPL"); you may not use this file except in
 * compliance with the NPL.  You may obtain a copy of the NPL at
 * http://www.mozilla.org/NPL/
 *
 * Software distributed under the NPL is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
 * for the specific language governing rights and limitations under the
 * NPL.
 *
 * The Initial Developer of this code under the NPL is Netscape
 * Communications Corporation.  Portions created by Netscape are
 * Copyright (C) 1998 Netscape Communications Corporation.  All Rights
 * Reserved.
 */

/*
** Base class implementation for network access functions (ref: prnetdb.h)
*/

#include "rclock.h"
#include "rcnetdb.h"

#include <prmem.h>
#include <prlog.h>
#include <string.h>

RCNetAddr::RCNetAddr(const RCNetAddr& his): RCBase()
    { address = his.address; }

RCNetAddr::RCNetAddr(const RCNetAddr& his, PRUint16 port): RCBase()
{
    address = his.address;
    switch (address.raw.family)
    {
        case PR_AF_INET: address.inet.port = port; break;
        case PR_AF_INET6: address.ipv6.port = port; break;
        default: break;
    }
}  /* RCNetAddr::RCNetAddr */

RCNetAddr::RCNetAddr(RCNetAddr::HostValue host, PRUint16 port): RCBase()
{
    PRNetAddrValue how;
    switch (host)
    {
        case RCNetAddr::any: how = PR_IpAddrAny; break;
        case RCNetAddr::loopback: how = PR_IpAddrLoopback; break;
        default: PR_ASSERT(!"This can't happen -- and did!");
    }
    (void)PR_InitializeNetAddr(how, port, &address);
}  /* RCNetAddr::RCNetAddr */

RCNetAddr::~RCNetAddr() { }

void RCNetAddr::operator=(const RCNetAddr& his) { address = his.address; }

PRStatus RCNetAddr::FromString(const char* string)
    { return PR_StringToNetAddr(string, &address); }

void RCNetAddr::operator=(const PRNetAddr* addr) { address = *addr; }

PRBool RCNetAddr::operator==(const RCNetAddr& his) const
{
    PRBool rv = EqualHost(his);
    if (rv)
    {
        switch (address.raw.family)
        {
            case PR_AF_INET:
                rv = (address.inet.port == his.address.inet.port); break;
            case PR_AF_INET6:
                rv = (address.ipv6.port == his.address.ipv6.port); break;
            case PR_AF_LOCAL:
            default: break;
        }
    }
    return rv;
}  /* RCNetAddr::operator== */

PRBool RCNetAddr::EqualHost(const RCNetAddr& his) const
{
    PRBool rv;
    switch (address.raw.family)
    {
        case PR_AF_INET:
            rv = (address.inet.ip == his.address.inet.ip); break;
        case PR_AF_INET6:
            rv = (0 == memcmp(
                &address.ipv6.ip, &his.address.ipv6.ip,
                sizeof(address.ipv6.ip)));
            break;
#if defined(XP_UNIX)
        case PR_AF_LOCAL:
            rv = (0 == strncmp(
                address.local.path, his.address.local.path,
                sizeof(address.local.path)));
            break;
#endif
        default: break;
    }
    return rv;
}  /* RCNetAddr::operator== */

PRStatus RCNetAddr::ToString(char *string, PRSize size) const
    { return PR_NetAddrToString(&address, string, size); }

/*
** RCHostLookup
*/

RCHostLookup::~RCHostLookup()
{
    if (NULL != address) delete [] address;
}  /* RCHostLookup::~RCHostLookup */

RCHostLookup::RCHostLookup(): RCBase()
{
    address = NULL;
    max_index = 0;
}  /* RCHostLookup::RCHostLookup */

PRStatus RCHostLookup::ByName(const char* name)
{
    PRStatus rv;
    PRNetAddr addr;
    PRHostEnt hostentry;
    PRIntn index = 0, max;
    RCNetAddr* vector = NULL;
    RCNetAddr* old_vector = NULL;
    void* buffer = PR_Malloc(PR_NETDB_BUF_SIZE);
    if (NULL == buffer) return PR_FAILURE;
    rv = PR_GetHostByName(name, (char*)buffer, PR_NETDB_BUF_SIZE, &hostentry);
    if (PR_SUCCESS == rv)
    {
        for (max = 0, index = 0;; ++max)
        {
            index = PR_EnumerateHostEnt(index, &hostentry, 0, &addr);
            if (0 == index) break;
        }
        if (max > 0)
        {
            vector = new RCNetAddr[max];
            while (--max > 0)
            {
                index = PR_EnumerateHostEnt(index, &hostentry, 0, &addr);
                if (0 == index) break;
                vector[index] = &addr;
            }
            {
                RCEnter entry(&ml);
                old_vector = address;
                address = vector;
                max_index = max;
            }
            if (NULL != old_vector) delete [] old_vector;
        }
    }
    if (NULL != buffer) PR_DELETE(buffer);
    return PR_SUCCESS;
}  /* RCHostLookup::ByName */

PRStatus RCHostLookup::ByAddress(const RCNetAddr& host_addr)
{
    PRStatus rv;
    PRNetAddr addr;
    PRHostEnt hostentry;
    PRIntn index = 0, max;
    RCNetAddr* vector = NULL;
    RCNetAddr* old_vector = NULL;
    char *buffer = (char*)PR_Malloc(PR_NETDB_BUF_SIZE);
    if (NULL == buffer) return PR_FAILURE;
    rv = PR_GetHostByAddr(host_addr, buffer, PR_NETDB_BUF_SIZE, &hostentry);
    if (PR_SUCCESS == rv)
    {
        for (max = 0, index = 0;; ++max)
        {
            index = PR_EnumerateHostEnt(index, &hostentry, 0, &addr);
            if (0 == index) break;
        }
        if (max > 0)
        {
            vector = new RCNetAddr[max];
            while (--max > 0)
            {
                index = PR_EnumerateHostEnt(index, &hostentry, 0, &addr);
                if (0 == index) break;
                vector[index] = &addr;
            }
            {
                RCEnter entry(&ml);
                old_vector = address;
                address = vector;
                max_index = max;
            }
            if (NULL != old_vector) delete [] old_vector;
        }
    }
    if (NULL != buffer) PR_DELETE(buffer);
    return PR_SUCCESS;
}  /* RCHostLookup::ByAddress */

const RCNetAddr* RCHostLookup::operator[](PRUintn which)
{
    RCNetAddr* addr = NULL;
    if (which < max_index)
        addr = &address[which];
    return addr;
}  /* RCHostLookup::operator[] */

/* RCNetdb.cpp */
<|endoftext|>


<commit_before>#include <cmath>

#include "drake/Path.h"
#include "drake/systems/LCMSystem.h"
#include "drake/systems/plants/BotVisualizer.h"
#include "drake/systems/plants/RigidBodySystem.h"
#include "drake/util/testUtil.h"
#include "lcmtypes/bot_core/planar_lidar_t.hpp"

using Eigen::VectorXd;
using std::make_shared;

namespace Drake {
namespace {

int do_main(int argc, char* argv[]) {
  auto rigid_body_sys = make_shared<RigidBodySystem>();
  rigid_body_sys->addRobotFromFile(
      getDrakePath() + "/systems/plants/test/lidarTest.sdf", DrakeJoint::FIXED);

  // Verifies that the RigidBodyDepthSensor accessors return the correct values.
  auto sensors = rigid_body_sys->GetSensors();
  if (sensors.size() != 1) {
    std::stringstream error_msg;
    error_msg << "ERROR: Unexpected number of sensors! Got " << sensors.size()
              << " expected 1.";
    throw std::runtime_error(error_msg.str());
  }

  auto lidar_sensor =
      dynamic_cast<const Drake::RigidBodyDepthSensor*>(sensors[0]);
  if (lidar_sensor == nullptr) {
    throw std::runtime_error(
        "ERROR: Unable to obtain pointer to the LIDAR sensor.");
  }

  if (!lidar_sensor->is_horizontal_scanner())
    throw std::runtime_error(
      "ERROR: LIDAR scanner says it is not horizontal but it is!");

  if (lidar_sensor->is_vertical_scanner())
    throw std::runtime_error(
      "ERROR: LIDAR scanner says it is vertical but is not!");

  valuecheck(static_cast<size_t>(1), lidar_sensor->num_pixel_rows(),
             std::string("Problems with num_pixel_rows(). "));
  valuecheck(static_cast<size_t>(640), lidar_sensor->num_pixel_cols(),
             std::string("Problems with num_pixel_cols(). "));

  valuecheck(0, lidar_sensor->min_pitch(),
             std::numeric_limits<double>::epsilon());

  valuecheck(0, lidar_sensor->max_pitch(),
             std::numeric_limits<double>::epsilon());

  valuecheck(-1.7, lidar_sensor->min_yaw(),
             std::numeric_limits<double>::epsilon());

  valuecheck(1.7, lidar_sensor->max_yaw(),
             std::numeric_limits<double>::epsilon());

  valuecheck(0.08, lidar_sensor->min_range(),
             std::numeric_limits<double>::epsilon());

  valuecheck(25, lidar_sensor->max_range(),
             std::numeric_limits<double>::epsilon());

  double t = 0;
  VectorXd x = VectorXd::Zero(rigid_body_sys->getNumStates());
  VectorXd u = VectorXd::Zero(rigid_body_sys->getNumInputs());

  //  rigid_body_sys->getRigidBodyTree()->drawKinematicTree("/tmp/lidar.dot");

  auto distances = rigid_body_sys->output(t, x, u);

  valuecheck(640, static_cast<int>(distances.size()),
             std::string("Problem with number of distances. "));

  const double min_yaw = lidar_sensor->min_yaw();
  const double max_yaw = lidar_sensor->max_yaw();
  const double max_range = lidar_sensor->max_range();
  const double tol = 1.0e-6;

  for (int i = 0; i < distances.size(); i++) {
    double theta = min_yaw + (max_yaw - min_yaw) * i / (distances.size() - 1);

    // We've implicitly hard-coded the box geometry from the SDF for the
    // computation of the analytical distances.
    if (std::abs(theta) >=
        M_PI / 2.0 + tol) {  // Should not be hitting any wall.
      valuecheck(max_range, distances(i));
    } else if (theta <= -M_PI / 4) {  // hitting the right wall
      valuecheck(-1.0 / std::sin(theta), distances(i), tol);
    } else if (theta >= M_PI / 4) {  // hitting the left wall
      valuecheck(1.0 / std::sin(theta), distances(i), tol);
    } else {  // hitting the front wall
      valuecheck(1 / std::cos(theta), distances(i), tol);
    }
  }

  // Tells Drake Visualizer to render the environment for debugging purposes.
  // This needs to be done before publishing LIDAR data so the visualizer knows
  // the sensor's position.
  auto lcm = make_shared<lcm::LCM>();
  auto visualizer = make_shared<BotVisualizer<RigidBodySystem::StateVector>>(
      lcm, rigid_body_sys->getRigidBodyTree());
  visualizer->output(t, x, u);

  // Publishes the LIDAR message.
  bot_core::planar_lidar_t msg;
  msg.utime = -1;
  msg.nintensities = 0;
  msg.rad0 = min_yaw;
  msg.radstep = (max_yaw - min_yaw) / (distances.size() - 1);

  msg.nranges = distances.size();
  for (int i = 0; i < distances.size(); i++) msg.ranges.push_back(distances(i));

  lcm->publish("DRAKE_PLANAR_LIDAR_0_rear_wall", &msg);

  return 0;
}

}  // namespace
}  // namespace Drake

/**
 * This unit test sets up a LIDAR in a box room and verifies the returns.
 */
int main(int argc, char* argv[]) {
  return Drake::do_main(argc, argv);
}
<commit_msg>Added curly braces for multi-line `if` statement.<commit_after>#include <cmath>

#include "drake/Path.h"
#include "drake/systems/LCMSystem.h"
#include "drake/systems/plants/BotVisualizer.h"
#include "drake/systems/plants/RigidBodySystem.h"
#include "drake/util/testUtil.h"
#include "lcmtypes/bot_core/planar_lidar_t.hpp"

using Eigen::VectorXd;
using std::make_shared;

namespace Drake {
namespace {

int do_main(int argc, char* argv[]) {
  auto rigid_body_sys = make_shared<RigidBodySystem>();
  rigid_body_sys->addRobotFromFile(
      getDrakePath() + "/systems/plants/test/lidarTest.sdf", DrakeJoint::FIXED);

  // Verifies that the RigidBodyDepthSensor accessors return the correct values.
  auto sensors = rigid_body_sys->GetSensors();
  if (sensors.size() != 1) {
    std::stringstream error_msg;
    error_msg << "ERROR: Unexpected number of sensors! Got " << sensors.size()
              << " expected 1.";
    throw std::runtime_error(error_msg.str());
  }

  auto lidar_sensor =
      dynamic_cast<const Drake::RigidBodyDepthSensor*>(sensors[0]);
  if (lidar_sensor == nullptr) {
    throw std::runtime_error(
        "ERROR: Unable to obtain pointer to the LIDAR sensor.");
  }

  if (!lidar_sensor->is_horizontal_scanner()) {
    throw std::runtime_error(
      "ERROR: LIDAR scanner says it is not horizontal but it is!");
  }

  if (lidar_sensor->is_vertical_scanner()) {
    throw std::runtime_error(
      "ERROR: LIDAR scanner says it is vertical but is not!");
  }

  valuecheck(static_cast<size_t>(1), lidar_sensor->num_pixel_rows(),
             std::string("Problems with num_pixel_rows(). "));
  valuecheck(static_cast<size_t>(640), lidar_sensor->num_pixel_cols(),
             std::string("Problems with num_pixel_cols(). "));

  valuecheck(0, lidar_sensor->min_pitch(),
             std::numeric_limits<double>::epsilon());

  valuecheck(0, lidar_sensor->max_pitch(),
             std::numeric_limits<double>::epsilon());

  valuecheck(-1.7, lidar_sensor->min_yaw(),
             std::numeric_limits<double>::epsilon());

  valuecheck(1.7, lidar_sensor->max_yaw(),
             std::numeric_limits<double>::epsilon());

  valuecheck(0.08, lidar_sensor->min_range(),
             std::numeric_limits<double>::epsilon());

  valuecheck(25, lidar_sensor->max_range(),
             std::numeric_limits<double>::epsilon());

  double t = 0;
  VectorXd x = VectorXd::Zero(rigid_body_sys->getNumStates());
  VectorXd u = VectorXd::Zero(rigid_body_sys->getNumInputs());

  //  rigid_body_sys->getRigidBodyTree()->drawKinematicTree("/tmp/lidar.dot");

  auto distances = rigid_body_sys->output(t, x, u);

  valuecheck(640, static_cast<int>(distances.size()),
             std::string("Problem with number of distances. "));

  const double min_yaw = lidar_sensor->min_yaw();
  const double max_yaw = lidar_sensor->max_yaw();
  const double max_range = lidar_sensor->max_range();
  const double tol = 1.0e-6;

  for (int i = 0; i < distances.size(); i++) {
    double theta = min_yaw + (max_yaw - min_yaw) * i / (distances.size() - 1);

    // We've implicitly hard-coded the box geometry from the SDF for the
    // computation of the analytical distances.
    if (std::abs(theta) >=
        M_PI / 2.0 + tol) {  // Should not be hitting any wall.
      valuecheck(max_range, distances(i));
    } else if (theta <= -M_PI / 4) {  // hitting the right wall
      valuecheck(-1.0 / std::sin(theta), distances(i), tol);
    } else if (theta >= M_PI / 4) {  // hitting the left wall
      valuecheck(1.0 / std::sin(theta), distances(i), tol);
    } else {  // hitting the front wall
      valuecheck(1 / std::cos(theta), distances(i), tol);
    }
  }

  // Tells Drake Visualizer to render the environment for debugging purposes.
  // This needs to be done before publishing LIDAR data so the visualizer knows
  // the sensor's position.
  auto lcm = make_shared<lcm::LCM>();
  auto visualizer = make_shared<BotVisualizer<RigidBodySystem::StateVector>>(
      lcm, rigid_body_sys->getRigidBodyTree());
  visualizer->output(t, x, u);

  // Publishes the LIDAR message.
  bot_core::planar_lidar_t msg;
  msg.utime = -1;
  msg.nintensities = 0;
  msg.rad0 = min_yaw;
  msg.radstep = (max_yaw - min_yaw) / (distances.size() - 1);

  msg.nranges = distances.size();
  for (int i = 0; i < distances.size(); i++) msg.ranges.push_back(distances(i));

  lcm->publish("DRAKE_PLANAR_LIDAR_0_rear_wall", &msg);

  return 0;
}

}  // namespace
}  // namespace Drake

/**
 * This unit test sets up a LIDAR in a box room and verifies the returns.
 */
int main(int argc, char* argv[]) {
  return Drake::do_main(argc, argv);
}
<|endoftext|>


<commit_before>#include "NL_LuaBindings.h"
#include "NL_Globals.h"
#include "NL_ConsoleQueue.h"
#include "NL_Game.h"
#include "NL_ScriptingContext.h"

#include "lua.hpp"
#include <LuaIntf.h>

namespace NLE
{
	namespace SCRIPT
	{
		void Bindings::attach(lua_State* state)
		{
			auto module = LuaIntf::LuaBinding(state).beginModule("nle");

			CONSOLE::attachBindings(module);
			GAME::Game::attachBindings(module);
			ScriptingContext::attachBindings(module);

			module.endModule();
		}
	}
}<commit_msg>added scene bindings<commit_after>#include "NL_LuaBindings.h"
#include "NL_Globals.h"
#include "NL_ConsoleQueue.h"
#include "NL_Game.h"
#include "NL_Scene.h"
#include "NL_ScriptingContext.h"

#include "lua.hpp"
#include <LuaIntf.h>

namespace NLE
{
	namespace SCRIPT
	{
		void Bindings::attach(lua_State* state)
		{
			auto module = LuaIntf::LuaBinding(state).beginModule("nle");

			CONSOLE::attachBindings(module);
			GAME::Game::attachBindings(module);
			GAME::Scene::attachBindings(module);
			ScriptingContext::attachBindings(module);

			module.endModule();
		}
	}
}<|endoftext|>


<commit_before>
#include <togo/assert.hpp>
#include <togo/system.hpp>
#include <togo/gfx/init.hpp>
#include <togo/gfx/display.hpp>

#include "../common/helpers.hpp"

using namespace togo;

signed
main() {
	core_init();
	gfx::init(3, 2);

	gfx::Config config{};
	config.color_bits = {8, 8, 8, 0};
	config.depth_bits = 16;
	config.stencil_bits = 0;
	config.msaa_num_buffers = 0;
	config.msaa_num_samples = 0;
	config.flags = gfx::ConfigFlags::double_buffered;

	gfx::Display* const display = gfx::display::create(
		"togo display",
		1024, 768,
		gfx::DisplayFlags::borderless,
		config
	);
	system::sleep_ms(1000);
	gfx::display::destroy(display);

	gfx::shutdown();
	return 0;
}
<commit_msg>test/gfx/display: replaced dead-sleep with input polling.<commit_after>
#include <togo/assert.hpp>
#include <togo/system.hpp>
#include <togo/gfx/init.hpp>
#include <togo/gfx/display.hpp>
#include <togo/input_buffer.hpp>

#include "../common/helpers.hpp"

using namespace togo;

signed
main() {
	core_init();
	gfx::init(3, 2);

	gfx::Config config{};
	config.color_bits = {8, 8, 8, 0};
	config.depth_bits = 16;
	config.stencil_bits = 0;
	config.msaa_num_buffers = 0;
	config.msaa_num_samples = 0;
	config.flags = gfx::ConfigFlags::double_buffered;

	gfx::Display* const display = gfx::display::create(
		"togo display",
		1024, 768,
		gfx::DisplayFlags::borderless,
		config
	);
	InputBuffer ib{memory::default_allocator()};
	input_buffer::add_display(ib, display);

	bool quit = false;
	InputEventType event_type{};
	void const* event_ptr = nullptr;
	while (!quit) {
		while (input_buffer::poll(ib, event_type, event_ptr)) {
			TOGO_ASSERTE(static_cast<BaseInputEvent const*>(event_ptr)->display == display);
			switch (event_type) {
			case InputEventType::key: {
				auto ev_key = static_cast<KeyEvent const*>(event_ptr);
				if (ev_key->code == KeyCode::escape) {
					quit = true;
				}
			}	break;

			case InputEventType::display_close_request:
				quit = true;
				break;
			default: break;
			}
		}
		system::sleep_ms(50);
	}
	input_buffer::remove_display(ib, display);
	gfx::display::destroy(display);
	gfx::shutdown();
	return 0;
}
<|endoftext|>


<commit_before>//-----------------------------------------------
//
//	This file is part of the Siv3D Engine.
//
//	Copyright (c) 2008-2019 Ryo Suzuki
//	Copyright (c) 2016-2019 OpenSiv3D Project
//
//	Licensed under the MIT License.
//
//-----------------------------------------------

# include <crtdbg.h>
# include <future>
# include <Siv3D/ScopeGuard.hpp>
# include <Siv3D/Windows.hpp>
# include <Siv3D/EngineError.hpp>
# include <Siv3D/EngineLog.hpp>
# include <Siv3D/EngineMessageBox.hpp>
# include <Siv3DEngine.hpp>
# include


<commit_before>// This file is a part of the OpenSurgSim project.
// Copyright 2013-2016, SimQuest Solutions Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "SurgSim/DataStructures/TriangleMesh.h"
#include "SurgSim/Framework/ObjectFactory.h"
#include "SurgSim/Framework/Runtime.h"
#include "SurgSim/Framework/SceneElement.h"
#include "SurgSim/Math/MathConvert.h"
#include "SurgSim/Math/MeshShape.h"
#include "SurgSim/Math/OdeState.h"
#include "SurgSim/Math/RigidTransform.h"
#include "SurgSim/Math/SegmentMeshShape.h"
#include "SurgSim/Math/Shape.h"
#include "SurgSim/Physics/DeformableCollisionRepresentation.h"
#include "SurgSim/Physics/DeformableRepresentation.h"

namespace SurgSim
{
namespace Physics
{
SURGSIM_REGISTER(SurgSim::Framework::Component, SurgSim::Physics::DeformableCollisionRepresentation,
				 DeformableCollisionRepresentation);

DeformableCollisionRepresentation::DeformableCollisionRepresentation(const std::string& name) :
	SurgSim::Collision::Representation(name)
{
	SURGSIM_ADD_SERIALIZABLE_PROPERTY(DeformableCollisionRepresentation, std::shared_ptr<SurgSim::Math::Shape>,
									  Shape, getShape, setShape);
}

DeformableCollisionRepresentation::~DeformableCollisionRepresentation()
{
}

namespace
{
bool updateShapeFromOdeState(const Math::OdeState& odeState, SurgSim::Math::Shape* shape)
{
	bool result = false;
	const size_t numNodes = odeState.getNumNodes();

	if (shape->getType() == SurgSim::Math::SHAPE_TYPE_MESH)
	{
		auto meshShape = dynamic_cast<SurgSim::Math::MeshShape*>(shape);
		SURGSIM_ASSERT(meshShape != nullptr) << "The shape is of type mesh but is not a mesh";
		SURGSIM_ASSERT(meshShape->getNumVertices() == numNodes) <<
				"The number of nodes in the deformable does not match the number of vertices in the mesh.";

		for (size_t nodeId = 0; nodeId < numNodes; ++nodeId)
		{
			meshShape->setVertexPosition(nodeId, odeState.getPosition(nodeId));
		}
		result = meshShape->update();
	}
	else if (shape->getType() == SurgSim::Math::SHAPE_TYPE_SEGMENTMESH)
	{
		auto meshShape = dynamic_cast<SurgSim::Math::SegmentMeshShape*>(shape);
		SURGSIM_ASSERT(meshShape != nullptr) << "The shape is of type mesh but is not a mesh";
		SURGSIM_ASSERT(meshShape->getNumVertices() == numNodes) <<
				"The number of nodes in the deformable does not match the number of vertices in the mesh.";

		for (size_t nodeId = 0; nodeId < numNodes; ++nodeId)
		{
			meshShape->setVertexPosition(nodeId, odeState.getPosition(nodeId));
		}
		result = meshShape->update();
	}

	return result;
}
}

bool DeformableCollisionRepresentation::doInitialize()
{
	bool result = false;
	if (nullptr != m_shape && m_shape->isValid())
	{
		result = true;
	}

	return result;
}

bool DeformableCollisionRepresentation::doWakeUp()
{
	auto physicsRepresentation = m_deformable.lock();
	SURGSIM_ASSERT(nullptr != physicsRepresentation)
			<< "The Physics::Representation referred by this DeformableCollisionRepresentation has expired.";

	auto state = physicsRepresentation->getCurrentState();
	SURGSIM_ASSERT(nullptr != state)
			<< "DeformableRepresentation " << physicsRepresentation->getName() << " holds an empty OdeState.";
	auto shape = std::dynamic_pointer_cast<DataStructures::VerticesPlain>(m_shape);
	SURGSIM_ASSERT(shape != nullptr)
			<< "The shape object is not inherited from DataStructures::VerticesPlain, but should be.";
	SURGSIM_ASSERT(shape->getNumVertices() == state->getNumNodes())
			<< "The number of nodes in the deformable does not match the number of vertices in the mesh.";

	update(0.0);
	return true;
}

int DeformableCollisionRepresentation::getShapeType() const
{
	SURGSIM_ASSERT(nullptr != m_shape) << "No mesh/shape assigned to DeformableCollisionRepresentation " << getName();
	return m_shape->getType();
}

void DeformableCollisionRepresentation::setShape(std::shared_ptr<SurgSim::Math::Shape> shape)
{
	SURGSIM_ASSERT(shape->getType() == SurgSim::Math::SHAPE_TYPE_MESH ||
				   shape->getType() == SurgSim::Math::SHAPE_TYPE_SEGMENTMESH)
			<< "Deformable collision shape has to be a mesh.  But what passed in is " << shape->getType();

	m_shape = shape;
}

const std::shared_ptr<SurgSim::Math::Shape> DeformableCollisionRepresentation::getShape() const
{
	return m_shape;
}

void DeformableCollisionRepresentation::setDeformableRepresentation(
	std::shared_ptr<SurgSim::Physics::DeformableRepresentation>representation)
{
	m_deformable = representation;
}

const std::shared_ptr<SurgSim::Physics::DeformableRepresentation>
DeformableCollisionRepresentation::getDeformableRepresentation() const
{
	auto physicsRepresentation = m_deformable.lock();
	SURGSIM_ASSERT(physicsRepresentation != nullptr) <<
			"Failed to get the deformable representation.  The DeformableCollisionRepresentation either was not "
			"attached to a Physics::Representation or the Physics::Representation has expired.";

	return physicsRepresentation;
}

void DeformableCollisionRepresentation::updateShapeData()
{
	auto physicsRepresentation = m_deformable.lock();
	SURGSIM_ASSERT(nullptr != physicsRepresentation) <<
			"Failed to update. The DeformableCollisionRepresentation either was not attached to a "
			"Physics::Representation or the Physics::Representation has expired.";

	// Write current shape
	if (!updateShapeFromOdeState(*physicsRepresentation->getCurrentState().get(), m_shape.get()))
	{
		setLocalActive(false);
		SURGSIM_LOG_SEVERE(Framework::Logger::getLogger("Collision/DeformableCollisionRepresentation")) <<
				"CollisionRepresentation '" << getFullName() << "' went inactive because its shape failed to update.";
	}
}

void DeformableCollisionRepresentation::updateDcdData()
{
	// HS-2-Mar-2016
	// #todo should only have to build the AABB tree here
}

void DeformableCollisionRepresentation::updateCcdData(double interval)
{
	auto physicsRepresentation = m_deformable.lock();
	SURGSIM_ASSERT(nullptr != physicsRepresentation) <<
			"Failed to update. The DeformableCollisionRepresentation either was not attached to a "
			"Physics::Representation or the Physics::Representation has expired.";

	if (m_previousShape == nullptr)
	{
		if (m_shape->getType() == SurgSim::Math::SHAPE_TYPE_MESH ||
			m_shape->getType() == SurgSim::Math::SHAPE_TYPE_SEGMENTMESH)
		{
			m_previousShape = m_shape->getTransformed(Math::RigidTransform3d::Identity());
		}
		else
		{
			SURGSIM_FAILURE() << "Invalid type, should be MeshShape(" << SurgSim::Math::SHAPE_TYPE_MESH <<
							  ") or SegmentMeshShape(" << SurgSim::Math::SHAPE_TYPE_SEGMENTMESH << "), but it is " <<
							  m_shape->getType();
		}
	}

	if (!updateShapeFromOdeState(*physicsRepresentation->getPreviousState().get(), m_previousShape.get()))
	{
		setLocalActive(false);
		SURGSIM_LOG_SEVERE(SurgSim::Framework::Logger::getLogger("Collision/DeformableCollisionRepresentation")) <<
				"CollisionRepresentation '" << getFullName() << "' went inactive because its shape failed to update.";
	}

	// Write current shape
	if (!updateShapeFromOdeState(*physicsRepresentation->getCurrentState().get(), m_shape.get()))
	{
		setLocalActive(false);
		SURGSIM_LOG_SEVERE(Framework::Logger::getLogger("Collision/DeformableCollisionRepresentation")) <<
				"CollisionRepresentation '" << getFullName() << "' went inactive because its shape failed to update.";
	}

	Math::PosedShape<std::shared_ptr<Math::Shape>> posedShapeFirst(m_previousShape, Math::RigidTransform3d::Identity());
	Math::PosedShape<std::shared_ptr<Math::Shape>> posedShapeSecond(m_shape, Math::RigidTransform3d::Identity());
	Math::PosedShapeMotion<std::shared_ptr<Math::Shape>> posedShapeMotion(posedShapeFirst, posedShapeSecond);
	setPosedShapeMotion(posedShapeMotion);

	// HS-2-Mar-2016
	// #todo Add AABB tree for the posedShapeMotion (i.e. that is the tree where each bounding box consists of the
	// corresponding elements from posedShape1 and posedShape2
}

} // namespace Physics
} // namespace SurgSim
<commit_msg>DeformableCollisionRepresentation supports SurfaceMeshShape.<commit_after>// This file is a part of the OpenSurgSim project.
// Copyright 2013-2016, SimQuest Solutions Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "SurgSim/DataStructures/TriangleMesh.h"
#include "SurgSim/Framework/ObjectFactory.h"
#include "SurgSim/Framework/Runtime.h"
#include "SurgSim/Framework/SceneElement.h"
#include "SurgSim/Math/MathConvert.h"
#include "SurgSim/Math/MeshShape.h"
#include "SurgSim/Math/OdeState.h"
#include "SurgSim/Math/RigidTransform.h"
#include "SurgSim/Math/SegmentMeshShape.h"
#include "SurgSim/Math/Shape.h"
#include "SurgSim/Math/SurfaceMeshShape.h"
#include "SurgSim/Physics/DeformableCollisionRepresentation.h"
#include "SurgSim/Physics/DeformableRepresentation.h"

namespace SurgSim
{
namespace Physics
{
SURGSIM_REGISTER(SurgSim::Framework::Component, SurgSim::Physics::DeformableCollisionRepresentation,
				 DeformableCollisionRepresentation);

DeformableCollisionRepresentation::DeformableCollisionRepresentation(const std::string& name) :
	SurgSim::Collision::Representation(name)
{
	SURGSIM_ADD_SERIALIZABLE_PROPERTY(DeformableCollisionRepresentation, std::shared_ptr<SurgSim::Math::Shape>,
									  Shape, getShape, setShape);
}

DeformableCollisionRepresentation::~DeformableCollisionRepresentation()
{
}

namespace
{
bool updateShapeFromOdeState(const Math::OdeState& odeState, SurgSim::Math::Shape* shape)
{
	bool result = false;
	const size_t numNodes = odeState.getNumNodes();

	if (shape->getType() == SurgSim::Math::SHAPE_TYPE_MESH)
	{
		auto meshShape = dynamic_cast<SurgSim::Math::MeshShape*>(shape);
		SURGSIM_ASSERT(meshShape != nullptr) << "The shape is of type mesh but is not a mesh";
		SURGSIM_ASSERT(meshShape->getNumVertices() == numNodes) <<
				"The number of nodes in the deformable does not match the number of vertices in the mesh.";

		for (size_t nodeId = 0; nodeId < numNodes; ++nodeId)
		{
			meshShape->setVertexPosition(nodeId, odeState.getPosition(nodeId));
		}
		result = meshShape->update();
	}
	else if (shape->getType() == SurgSim::Math::SHAPE_TYPE_SEGMENTMESH)
	{
		auto meshShape = dynamic_cast<SurgSim::Math::SegmentMeshShape*>(shape);
		SURGSIM_ASSERT(meshShape != nullptr) << "The shape is of type mesh but is not a mesh";
		SURGSIM_ASSERT(meshShape->getNumVertices() == numNodes) <<
				"The number of nodes in the deformable does not match the number of vertices in the mesh.";

		for (size_t nodeId = 0; nodeId < numNodes; ++nodeId)
		{
			meshShape->setVertexPosition(nodeId, odeState.getPosition(nodeId));
		}
		result = meshShape->update();
	}
	else if (shape->getType() == SurgSim::Math::SHAPE_TYPE_SURFACEMESH)
	{
		auto meshShape = dynamic_cast<SurgSim::Math::SurfaceMeshShape*>(shape);
		SURGSIM_ASSERT(meshShape != nullptr) << "The shape is of type mesh but is not a surface mesh";
		SURGSIM_ASSERT(meshShape->getNumVertices() == numNodes) <<
				"The number of nodes in the deformable does not match the number of vertices in the mesh.";

		for (size_t nodeId = 0; nodeId < numNodes; ++nodeId)
		{
			meshShape->setVertexPosition(nodeId, odeState.getPosition(nodeId));
		}
		result = meshShape->update();
	}

	return result;
}
}

bool DeformableCollisionRepresentation::doInitialize()
{
	bool result = false;
	if (nullptr != m_shape && m_shape->isValid())
	{
		result = true;
	}

	return result;
}

bool DeformableCollisionRepresentation::doWakeUp()
{
	auto physicsRepresentation = m_deformable.lock();
	SURGSIM_ASSERT(nullptr != physicsRepresentation)
			<< "The Physics::Representation referred by this DeformableCollisionRepresentation has expired.";

	auto state = physicsRepresentation->getCurrentState();
	SURGSIM_ASSERT(nullptr != state)
			<< "DeformableRepresentation " << physicsRepresentation->getName() << " holds an empty OdeState.";
	auto shape = std::dynamic_pointer_cast<DataStructures::VerticesPlain>(m_shape);
	SURGSIM_ASSERT(shape != nullptr)
			<< "The shape object is not inherited from DataStructures::VerticesPlain, but should be.";
	SURGSIM_ASSERT(shape->getNumVertices() == state->getNumNodes())
			<< "The number of nodes in the deformable does not match the number of vertices in the mesh.";

	update(0.0);
	return true;
}

int DeformableCollisionRepresentation::getShapeType() const
{
	SURGSIM_ASSERT(nullptr != m_shape) << "No mesh/shape assigned to DeformableCollisionRepresentation " << getName();
	return m_shape->getType();
}

void DeformableCollisionRepresentation::setShape(std::shared_ptr<SurgSim::Math::Shape> shape)
{
	SURGSIM_ASSERT(shape->getType() == SurgSim::Math::SHAPE_TYPE_MESH ||
				   shape->getType() == SurgSim::Math::SHAPE_TYPE_SEGMENTMESH ||
				   shape->getType() == SurgSim::Math::SHAPE_TYPE_SURFACEMESH)
			<< "Deformable collision shape has to be a mesh.  But what passed in is " << shape->getType();

	m_shape = shape;
}

const std::shared_ptr<SurgSim::Math::Shape> DeformableCollisionRepresentation::getShape() const
{
	return m_shape;
}

void DeformableCollisionRepresentation::setDeformableRepresentation(
	std::shared_ptr<SurgSim::Physics::DeformableRepresentation>representation)
{
	m_deformable = representation;
}

const std::shared_ptr<SurgSim::Physics::DeformableRepresentation>
DeformableCollisionRepresentation::getDeformableRepresentation() const
{
	auto physicsRepresentation = m_deformable.lock();
	SURGSIM_ASSERT(physicsRepresentation != nullptr) <<
			"Failed to get the deformable representation.  The DeformableCollisionRepresentation either was not "
			"attached to a Physics::Representation or the Physics::Representation has expired.";

	return physicsRepresentation;
}

void DeformableCollisionRepresentation::updateShapeData()
{
	auto physicsRepresentation = m_deformable.lock();
	SURGSIM_ASSERT(nullptr != physicsRepresentation) <<
			"Failed to update. The DeformableCollisionRepresentation either was not attached to a "
			"Physics::Representation or the Physics::Representation has expired.";

	// Write current shape
	if (!updateShapeFromOdeState(*physicsRepresentation->getCurrentState().get(), m_shape.get()))
	{
		setLocalActive(false);
		SURGSIM_LOG_SEVERE(Framework::Logger::getLogger("Collision/DeformableCollisionRepresentation")) <<
				"CollisionRepresentation '" << getFullName() << "' went inactive because its shape failed to update.";
	}
}

void DeformableCollisionRepresentation::updateDcdData()
{
	// HS-2-Mar-2016
	// #todo should only have to build the AABB tree here
}

void DeformableCollisionRepresentation::updateCcdData(double interval)
{
	auto physicsRepresentation = m_deformable.lock();
	SURGSIM_ASSERT(nullptr != physicsRepresentation) <<
			"Failed to update. The DeformableCollisionRepresentation either was not attached to a "
			"Physics::Representation or the Physics::Representation has expired.";

	if (m_previousShape == nullptr)
	{
		if (m_shape->getType() == SurgSim::Math::SHAPE_TYPE_MESH ||
			m_shape->getType() == SurgSim::Math::SHAPE_TYPE_SEGMENTMESH ||
			m_shape->getType() == SurgSim::Math::SHAPE_TYPE_SURFACEMESH)
		{
			m_previousShape = m_shape->getTransformed(Math::RigidTransform3d::Identity());
		}
		else
		{
			SURGSIM_FAILURE() << "Invalid type, should be MeshShape(" << SurgSim::Math::SHAPE_TYPE_MESH <<
							  ") or SegmentMeshShape(" << SurgSim::Math::SHAPE_TYPE_SEGMENTMESH <<
							  ") or SurfaceMeshShape(" << SurgSim::Math::SHAPE_TYPE_SURFACEMESH <<"), but it is " <<
							  m_shape->getType();
		}
	}

	if (!updateShapeFromOdeState(*physicsRepresentation->getPreviousState().get(), m_previousShape.get()))
	{
		setLocalActive(false);
		SURGSIM_LOG_SEVERE(SurgSim::Framework::Logger::getLogger("Collision/DeformableCollisionRepresentation")) <<
				"CollisionRepresentation '" << getFullName() << "' went inactive because its shape failed to update.";
	}

	// Write current shape
	if (!updateShapeFromOdeState(*physicsRepresentation->getCurrentState().get(), m_shape.get()))
	{
		setLocalActive(false);
		SURGSIM_LOG_SEVERE(Framework::Logger::getLogger("Collision/DeformableCollisionRepresentation")) <<
				"CollisionRepresentation '" << getFullName() << "' went inactive because its shape failed to update.";
	}

	Math::PosedShape<std::shared_ptr<Math::Shape>> posedShapeFirst(m_previousShape, Math::RigidTransform3d::Identity());
	Math::PosedShape<std::shared_ptr<Math::Shape>> posedShapeSecond(m_shape, Math::RigidTransform3d::Identity());
	Math::PosedShapeMotion<std::shared_ptr<Math::Shape>> posedShapeMotion(posedShapeFirst, posedShapeSecond);
	setPosedShapeMotion(posedShapeMotion);

	// HS-2-Mar-2016
	// #todo Add AABB tree for the posedShapeMotion (i.e. that is the tree where each bounding box consists of the
	// corresponding elements from posedShape1 and posedShape2
}

} // namespace Physics
} // namespace SurgSim
<|endoftext|>


<commit_before>
#include "bridgelistener.h"
#include <iostream>

using namespace bridge;

int main()
{
    Driver driver;
    IPv6Endpoint remoteEndpoint{"192.168.56.1", OFP_DEFAULT_PORT};

    log::set(&std::cerr);

    driver.listen(Driver::Bridge, nullptr, IPv6Endpoint{OFP_DEFAULT_PORT},
                  ProtocolVersions::All,
                  [remoteEndpoint]() { return new BridgeListener(remoteEndpoint); });

    driver.run();

    return 0;
}<commit_msg>Formatting change.<commit_after>
#include "bridgelistener.h"
#include <iostream>

using namespace bridge;

int main()
{
    Driver driver;
    IPv6Endpoint remoteEndpoint{"192.168.56.1", OFP_DEFAULT_PORT};

    log::set(&std::cerr);

    driver.listen(Driver::Bridge, nullptr, IPv6Endpoint{OFP_DEFAULT_PORT},
                  ProtocolVersions::All, [remoteEndpoint]() {
        return new BridgeListener(remoteEndpoint);
    });

    driver.run();

    return 0;
}<|endoftext|>