<commit_before>/* GG is a GUI for SDL and OpenGL.
   Copyright (C) 2003 T. Zachary Laine

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

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

   You should have received a copy of the GNU Lesser General Public
   License along with this library; if not, write to the Free
   Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
   02111-1307 USA

   If you do not wish to comply with the terms of the LGPL please
   contact the author as other terms are available for a fee.

   Zach Laine
   whatwasthataddress@hotmail.com */

/* $Header$ */

#include "SDL/SDLGGApp.h"
#include "GGEventPump.h"

using std::string;

// member functions
SDLGGApp::SDLGGApp(int w/* = 1024*/, int h/* = 768*/, bool calc_FPS/* = false*/, const std::string& app_name/* = "GG"*/) :
    App(app_name),
    m_app_width(w),
    m_app_height(h)
{
}

SDLGGApp::~SDLGGApp()
{
    SDLQuit();
}

SDLGGApp* SDLGGApp::GetApp()
{
    return dynamic_cast<SDLGGApp*>(App::GetApp());
}

void SDLGGApp::Exit(int code)
{
    if (code)
        Logger().fatalStream() << "Initiating Exit (code " << code << " - error termination)";
    else
        Logger().debugStream() << "Initiating Exit (normal termination)";
    SDLQuit();
    exit(code);
}

void SDLGGApp::Wait(int ms)
{
    SDL_Delay(ms);
}

GG::Key SDLGGApp::GGKeyFromSDLKey(const SDL_keysym& key)
{
    GG::Key retval = GG::Key(key.sym);
    bool shift = key.mod & KMOD_SHIFT;
    bool caps_lock = key.mod & KMOD_CAPS;

    // this code works because both SDLKey and GG::Key map (at least
    // partially) to the printable ASCII characters
    if (shift || caps_lock) {
        if (shift != caps_lock && (retval >= 'a' && retval <= 'z')) {
            retval = GG::Key(toupper(retval));
        } else if (shift) { // the caps lock key should not affect these
            // this assumes a US keyboard layout
            switch (retval) {
            case '`': retval = GG::Key('~'); break;
            case '1': retval = GG::Key('!'); break;
            case '2': retval = GG::Key('@'); break;
            case '3': retval = GG::Key('#'); break;
            case '4': retval = GG::Key('$'); break;
            case '5': retval = GG::Key('%'); break;
            case '6': retval = GG::Key('^'); break;
            case '7': retval = GG::Key('&'); break;
            case '8': retval = GG::Key('*'); break;
            case '9': retval = GG::Key('('); break;
            case '0': retval = GG::Key(')'); break;
            case '-': retval = GG::Key('_'); break;
            case '=': retval = GG::Key('+'); break;
            case '[': retval = GG::Key('{'); break;
            case ']': retval = GG::Key('}'); break;
            case '\\': retval = GG::Key('|'); break;
            case ';': retval = GG::Key(':'); break;
            case '\'': retval = GG::Key('"'); break;
            case ',': retval = GG::Key('<'); break;
            case '.': retval = GG::Key('>'); break;
            case '/': retval = GG::Key('?'); break;
            default: break;
            }
        }
    }
    return retval;
}

void SDLGGApp::SDLInit()
{
    const SDL_VideoInfo* vid_info = 0;

    if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_NOPARACHUTE) < 0) {
        Logger().errorStream() << "SDL initialization failed: " << SDL_GetError();
        Exit(1);
    }

#if defined(GG_USE_NET) && GG_USE_NET
    if (SDLNet_Init() < 0) {
        Logger().errorStream() << "SDL Net initialization failed: " << SDLNet_GetError();
        Exit(1);
    }

    if (FE_Init() < 0) {
        Logger().errorStream() << "FastEvents initialization failed: " << FE_GetError();
        Exit(1);
    }
#endif // GG_USE_NET

    vid_info = SDL_GetVideoInfo();

    if (!vid_info) {
        Logger().errorStream() << "Video info query failed: " << SDL_GetError();
        Exit(1);
    }

    SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);

    if (SDL_SetVideoMode(m_app_width, m_app_height, 16, SDL_OPENGL) == 0) {
        Logger().errorStream() << "Video mode set failed: " << SDL_GetError();
        Exit(1);
    }

#if defined(GG_USE_NET) && GG_USE_NET
    if (NET2_Init() < 0) {
        Logger().errorStream() << "SDL Net2 initialization failed: " << NET2_GetError();
        Exit(1);
    }
#endif // GG_USE_NET

    SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL);
    EnableMouseDragRepeat(SDL_DEFAULT_REPEAT_DELAY / 2, SDL_DEFAULT_REPEAT_INTERVAL / 2);

    Logger().debugStream() << "SDLInit() complete.";
    GLInit();
}

void SDLGGApp::GLInit()
{
    double ratio = m_app_width / (float)(m_app_height);

    glEnable(GL_LIGHTING);
    glEnable(GL_LIGHT0);
    glEnable(GL_DEPTH_TEST);
    glEnable(GL_CULL_FACE);
    glEnable(GL_BLEND);
    glShadeModel(GL_SMOOTH);
    glClearColor(0, 0, 0, 0);
    glViewport(0, 0, m_app_width, m_app_height);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluPerspective(50.0, ratio, 1.0, 10.0);

    Logger().debugStream() << "GLInit() complete.";
}

void SDLGGApp::HandleSystemEvents(int& last_mouse_event_time)
{
    // handle events
    SDL_Event event;
#if defined(GG_USE_NET) && GG_USE_NET
    while (0 < FE_PollEvent(&event)) {
#else
    while (0 < SDL_PollEvent(&event)) {
#endif // GG_USE_NET
        if (event.type  == SDL_MOUSEBUTTONDOWN || event.type  == SDL_MOUSEBUTTONUP || event.type == SDL_MOUSEMOTION)
            last_mouse_event_time = Ticks();

        bool send_to_gg = false;
        EventType gg_event;
        GG::Key key = GGKeyFromSDLKey(event.key.keysym);
        Uint32 key_mods = SDL_GetModState();
#ifdef __APPLE__
        GG::Pt mouse_pos(event.motion.x, m_app_height - event.motion.y);
        GG::Pt mouse_rel(event.motion.xrel, -event.motion.yrel);
#else
        GG::Pt mouse_pos(event.motion.x, event.motion.y);
        GG::Pt mouse_rel(event.motion.xrel, event.motion.yrel);
#endif

        switch (event.type) {
        case SDL_KEYDOWN:
            if (key < GG::GGK_NUMLOCK)
                send_to_gg = true;
            gg_event = KEYPRESS;
            break;
        case SDL_MOUSEMOTION:
            send_to_gg = true;
            gg_event = MOUSEMOVE;
            break;
        case SDL_MOUSEBUTTONDOWN:
            send_to_gg = true;
            switch (event.button.button) {
                case SDL_BUTTON_LEFT:      gg_event = LPRESS; break;
                case SDL_BUTTON_MIDDLE:    gg_event = MPRESS; break;
                case SDL_BUTTON_RIGHT:     gg_event = RPRESS; break;
                case SDL_BUTTON_WHEELUP:   gg_event = MOUSEWHEEL; mouse_rel = GG::Pt(0, 1); break;
                case SDL_BUTTON_WHEELDOWN: gg_event = MOUSEWHEEL; mouse_rel = GG::Pt(0, -1); break;
            }
            key_mods = SDL_GetModState();
            break;
        case SDL_MOUSEBUTTONUP:
            send_to_gg = true;
            switch (event.button.button) {
                case SDL_BUTTON_LEFT:   gg_event = LRELEASE; break;
                case SDL_BUTTON_MIDDLE: gg_event = MRELEASE; break;
                case SDL_BUTTON_RIGHT:  gg_event = RRELEASE; break;
            }
            key_mods = SDL_GetModState();
            break;
        }

        if (send_to_gg)
            HandleGGEvent(gg_event, key, key_mods, mouse_pos, mouse_rel);
        else
            HandleNonGGEvent(event);
    }
}

void SDLGGApp::HandleNonGGEvent(const SDL_Event& event)
{
    switch (event.type) {
    case SDL_QUIT:
        Exit(0);
        break;
    }
}

void SDLGGApp::RenderBegin()
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
}

void SDLGGApp::RenderEnd()
{
    SDL_GL_SwapBuffers();
}

void SDLGGApp::SDLQuit()
{
    FinalCleanup();
#if defined(GG_USE_NET) && GG_USE_NET
    NET2_Quit();
    FE_Quit();
    SDLNet_Quit();
#endif // GG_USE_NET
    SDL_Quit();
    Logger().debugStream() << "SDLQuit() complete.";
}

void SDLGGApp::Run()
{
    try {
        SDLInit();
        Initialize();
        GG::EventPump pump;
        pump();
    } catch (const std::invalid_argument& exception) {
        Logger().fatal("std::invalid_argument Exception caught in App::Run(): " + string(exception.what()));
        Exit(1);
    } catch (const std::runtime_error& exception) {
        Logger().fatal("std::runtime_error Exception caught in App::Run(): " + string(exception.what()));
        Exit(1);
    } catch (const GG::GGException& exception) {
        Logger().fatal("GG::GGException (subclass " + string(exception.what()) + ") caught in App::Run(): " + exception.Message());
        Exit(1);
    }
}

<commit_msg>Added an unnecessary initial value for gg_event in order to quiet a warning.<commit_after>/* GG is a GUI for SDL and OpenGL.
   Copyright (C) 2003 T. Zachary Laine

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

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

   You should have received a copy of the GNU Lesser General Public
   License along with this library; if not, write to the Free
   Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
   02111-1307 USA

   If you do not wish to comply with the terms of the LGPL please
   contact the author as other terms are available for a fee.

   Zach Laine
   whatwasthataddress@hotmail.com */

/* $Header$ */

#include "SDL/SDLGGApp.h"
#include "GGEventPump.h"

using std::string;

// member functions
SDLGGApp::SDLGGApp(int w/* = 1024*/, int h/* = 768*/, bool calc_FPS/* = false*/, const std::string& app_name/* = "GG"*/) :
    App(app_name),
    m_app_width(w),
    m_app_height(h)
{
}

SDLGGApp::~SDLGGApp()
{
    SDLQuit();
}

SDLGGApp* SDLGGApp::GetApp()
{
    return dynamic_cast<SDLGGApp*>(App::GetApp());
}

void SDLGGApp::Exit(int code)
{
    if (code)
        Logger().fatalStream() << "Initiating Exit (code " << code << " - error termination)";
    else
        Logger().debugStream() << "Initiating Exit (normal termination)";
    SDLQuit();
    exit(code);
}

void SDLGGApp::Wait(int ms)
{
    SDL_Delay(ms);
}

GG::Key SDLGGApp::GGKeyFromSDLKey(const SDL_keysym& key)
{
    GG::Key retval = GG::Key(key.sym);
    bool shift = key.mod & KMOD_SHIFT;
    bool caps_lock = key.mod & KMOD_CAPS;

    // this code works because both SDLKey and GG::Key map (at least
    // partially) to the printable ASCII characters
    if (shift || caps_lock) {
        if (shift != caps_lock && (retval >= 'a' && retval <= 'z')) {
            retval = GG::Key(toupper(retval));
        } else if (shift) { // the caps lock key should not affect these
            // this assumes a US keyboard layout
            switch (retval) {
            case '`': retval = GG::Key('~'); break;
            case '1': retval = GG::Key('!'); break;
            case '2': retval = GG::Key('@'); break;
            case '3': retval = GG::Key('#'); break;
            case '4': retval = GG::Key('$'); break;
            case '5': retval = GG::Key('%'); break;
            case '6': retval = GG::Key('^'); break;
            case '7': retval = GG::Key('&'); break;
            case '8': retval = GG::Key('*'); break;
            case '9': retval = GG::Key('('); break;
            case '0': retval = GG::Key(')'); break;
            case '-': retval = GG::Key('_'); break;
            case '=': retval = GG::Key('+'); break;
            case '[': retval = GG::Key('{'); break;
            case ']': retval = GG::Key('}'); break;
            case '\\': retval = GG::Key('|'); break;
            case ';': retval = GG::Key(':'); break;
            case '\'': retval = GG::Key('"'); break;
            case ',': retval = GG::Key('<'); break;
            case '.': retval = GG::Key('>'); break;
            case '/': retval = GG::Key('?'); break;
            default: break;
            }
        }
    }
    return retval;
}

void SDLGGApp::SDLInit()
{
    const SDL_VideoInfo* vid_info = 0;

    if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_NOPARACHUTE) < 0) {
        Logger().errorStream() << "SDL initialization failed: " << SDL_GetError();
        Exit(1);
    }

#if defined(GG_USE_NET) && GG_USE_NET
    if (SDLNet_Init() < 0) {
        Logger().errorStream() << "SDL Net initialization failed: " << SDLNet_GetError();
        Exit(1);
    }

    if (FE_Init() < 0) {
        Logger().errorStream() << "FastEvents initialization failed: " << FE_GetError();
        Exit(1);
    }
#endif // GG_USE_NET

    vid_info = SDL_GetVideoInfo();

    if (!vid_info) {
        Logger().errorStream() << "Video info query failed: " << SDL_GetError();
        Exit(1);
    }

    SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);

    if (SDL_SetVideoMode(m_app_width, m_app_height, 16, SDL_OPENGL) == 0) {
        Logger().errorStream() << "Video mode set failed: " << SDL_GetError();
        Exit(1);
    }

#if defined(GG_USE_NET) && GG_USE_NET
    if (NET2_Init() < 0) {
        Logger().errorStream() << "SDL Net2 initialization failed: " << NET2_GetError();
        Exit(1);
    }
#endif // GG_USE_NET

    SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL);
    EnableMouseDragRepeat(SDL_DEFAULT_REPEAT_DELAY / 2, SDL_DEFAULT_REPEAT_INTERVAL / 2);

    Logger().debugStream() << "SDLInit() complete.";
    GLInit();
}

void SDLGGApp::GLInit()
{
    double ratio = m_app_width / (float)(m_app_height);

    glEnable(GL_LIGHTING);
    glEnable(GL_LIGHT0);
    glEnable(GL_DEPTH_TEST);
    glEnable(GL_CULL_FACE);
    glEnable(GL_BLEND);
    glShadeModel(GL_SMOOTH);
    glClearColor(0, 0, 0, 0);
    glViewport(0, 0, m_app_width, m_app_height);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluPerspective(50.0, ratio, 1.0, 10.0);

    Logger().debugStream() << "GLInit() complete.";
}

void SDLGGApp::HandleSystemEvents(int& last_mouse_event_time)
{
    // handle events
    SDL_Event event;
#if defined(GG_USE_NET) && GG_USE_NET
    while (0 < FE_PollEvent(&event)) {
#else
    while (0 < SDL_PollEvent(&event)) {
#endif // GG_USE_NET
        if (event.type  == SDL_MOUSEBUTTONDOWN || event.type  == SDL_MOUSEBUTTONUP || event.type == SDL_MOUSEMOTION)
            last_mouse_event_time = Ticks();

        bool send_to_gg = false;
        EventType gg_event = MOUSEMOVE;
        GG::Key key = GGKeyFromSDLKey(event.key.keysym);
        Uint32 key_mods = SDL_GetModState();
#ifdef __APPLE__
        GG::Pt mouse_pos(event.motion.x, m_app_height - event.motion.y);
        GG::Pt mouse_rel(event.motion.xrel, -event.motion.yrel);
#else
        GG::Pt mouse_pos(event.motion.x, event.motion.y);
        GG::Pt mouse_rel(event.motion.xrel, event.motion.yrel);
#endif

        switch (event.type) {
        case SDL_KEYDOWN:
            if (key < GG::GGK_NUMLOCK)
                send_to_gg = true;
            gg_event = KEYPRESS;
            break;
        case SDL_MOUSEMOTION:
            send_to_gg = true;
            gg_event = MOUSEMOVE;
            break;
        case SDL_MOUSEBUTTONDOWN:
            send_to_gg = true;
            switch (event.button.button) {
                case SDL_BUTTON_LEFT:      gg_event = LPRESS; break;
                case SDL_BUTTON_MIDDLE:    gg_event = MPRESS; break;
                case SDL_BUTTON_RIGHT:     gg_event = RPRESS; break;
                case SDL_BUTTON_WHEELUP:   gg_event = MOUSEWHEEL; mouse_rel = GG::Pt(0, 1); break;
                case SDL_BUTTON_WHEELDOWN: gg_event = MOUSEWHEEL; mouse_rel = GG::Pt(0, -1); break;
            }
            key_mods = SDL_GetModState();
            break;
        case SDL_MOUSEBUTTONUP:
            send_to_gg = true;
            switch (event.button.button) {
                case SDL_BUTTON_LEFT:   gg_event = LRELEASE; break;
                case SDL_BUTTON_MIDDLE: gg_event = MRELEASE; break;
                case SDL_BUTTON_RIGHT:  gg_event = RRELEASE; break;
            }
            key_mods = SDL_GetModState();
            break;
        }

        if (send_to_gg)
            HandleGGEvent(gg_event, key, key_mods, mouse_pos, mouse_rel);
        else
            HandleNonGGEvent(event);
    }
}

void SDLGGApp::HandleNonGGEvent(const SDL_Event& event)
{
    switch (event.type) {
    case SDL_QUIT:
        Exit(0);
        break;
    }
}

void SDLGGApp::RenderBegin()
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
}

void SDLGGApp::RenderEnd()
{
    SDL_GL_SwapBuffers();
}

void SDLGGApp::SDLQuit()
{
    FinalCleanup();
#if defined(GG_USE_NET) && GG_USE_NET
    NET2_Quit();
    FE_Quit();
    SDLNet_Quit();
#endif // GG_USE_NET
    SDL_Quit();
    Logger().debugStream() << "SDLQuit() complete.";
}

void SDLGGApp::Run()
{
    try {
        SDLInit();
        Initialize();
        GG::EventPump pump;
        pump();
    } catch (const std::invalid_argument& exception) {
        Logger().fatal("std::invalid_argument Exception caught in App::Run(): " + string(exception.what()));
        Exit(1);
    } catch (const std::runtime_error& exception) {
        Logger().fatal("std::runtime_error Exception caught in App::Run(): " + string(exception.what()));
        Exit(1);
    } catch (const GG::GGException& exception) {
        Logger().fatal("GG::GGException (subclass " + string(exception.what()) + ") caught in App::Run(): " + exception.Message());
        Exit(1);
    }
}

<|endoftext|>


<commit_before>#pragma once

#include "Properties.hpp"

class Serializable
{
public:

  virtual void
  save(Properties & p) const = 0;

  virtual void
  restore(Properties const &p) {}
};
<commit_msg>Add virtual destructor to Serializable<commit_after>#pragma once

#include "Properties.hpp"

class Serializable
{
public:

  virtual ~Serializable() = default;

  virtual void
  save(Properties & p) const = 0;

  virtual void
  restore(Properties const &p) {}
};
<|endoftext|>


<commit_before>/*
 * VariableList.cpp
 *
 *  Created on: 18.04.2016
 *      Author: Marc Hartung
 */

#include "../include/VariableList.hpp"
#include "../include/network_impl/SimNetworkFunctions.hpp"

#include <ostream>
#include <string>
#include <algorithm>

namespace NetOff
{
    VariableList::VariableList(const std::shared_ptr<char>& data)
    {
        _vars = getVariableListFromData(data.get())._vars;
    }

    VariableList::VariableList()
            : _vars(std::vector<std::vector<std::string>>(3))
    {
    }

    VariableList::VariableList(const std::vector<std::string>& realVars, const std::vector<std::string>& intVars, const std::vector<std::string>& boolVars)
            : _vars(std::vector<std::vector<std::string>>(3))
    {
        _vars[0] = realVars;
        _vars[1] = intVars;
        _vars[2] = boolVars;
    }

    void VariableList::addReal(const std::string& varName)
    {
        _vars[0].push_back(varName);
    }

    void VariableList::addInt(const std::string& varName)
    {
        _vars[1].push_back(varName);
    }

    void VariableList::addBool(const std::string& varName)
    {
        _vars[2].push_back(varName);
    }

    void VariableList::addReals(const std::vector<std::string>& varNames)
    {
        _vars[0].insert(_vars[0].end(), varNames.begin(), varNames.end());
    }

    void VariableList::addInts(const std::vector<std::string>& varNames)
    {
        _vars[1].insert(_vars[1].end(), varNames.begin(), varNames.end());
    }

    void VariableList::addBools(const std::vector<std::string>& varNames)
    {
        _vars[2].insert(_vars[2].end(), varNames.begin(), varNames.end());
    }

    const std::vector<std::string>& VariableList::getReals() const
    {
        return _vars[0];
    }

    const std::vector<std::string>& VariableList::getInts() const
    {
        return _vars[1];
    }

    const std::vector<std::string>& VariableList::getBools() const
    {
        return _vars[2];
    }

    size_t VariableList::dataSize() const
    {
        size_t res = 0;
        res += 3 * sizeof(size_t);  // safe data as: [numReal,numInt,numBool,[numChars,chars]]
        for (size_t i = 0; i < 3; ++i)
            for (size_t j = 0; j < _vars[i].size(); ++j)
                res += getStringDataSize(_vars[i][j]);
        return res;
    }

    bool VariableList::empty() const
    {
        return _vars[0].empty() && _vars[1].empty() && _vars[2].empty();
    }

    std::shared_ptr<const char> VariableList::data() const
    {
        std::shared_ptr<char> res(new char[dataSize()]);
        saveVariablesTo(res.get());
        return res;
    }

    std::shared_ptr<char> VariableList::data()
    {
        std::shared_ptr<char> res(new char[dataSize()]);
        saveVariablesTo(res.get());
        return res;
    }

    void VariableList::saveVariablesTo(char * data) const
    {
        // safe data as: [numReal,numInt,numBool,[numChars,chars]]
        char * curPos = data;
        for (size_t i = 0; i < 3; ++i)
        {
            curPos = saveShiftIntegralInData<size_t>(_vars[i].size(), curPos);
        }
        for (size_t i = 0; i < 3; ++i)
            for (size_t j = 0; j < _vars[i].size(); ++j)
            {
                saveStringInData(_vars[i][j], curPos);
                curPos += getStringDataSize(_vars[i][j]);
            }
    }

    VariableList VariableList::getVariableListFromData(const char * data)
    {
        VariableList res;
        std::vector<std::vector<std::string>> & vars = res._vars;

        vars = std::vector<std::vector<std::string>>(3);
        const char * curPos = data;
        for (size_t i = 0; i < 3; ++i)
        {
            vars[i] = std::vector<std::string>(getIntegralFromData<size_t>(curPos));
            curPos = shift<size_t>(curPos);
        }
        for (size_t i = 0; i < 3; ++i)
            for (size_t j = 0; j < vars[i].size(); ++j)
            {
                vars[i][j] = createStringFromData(curPos);
                curPos += getStringDataSize(vars[i][j]);
            }
        return res;
    }

    std::ostream & operator<<(std::ostream & out, const VariableList & in)
    {
        out << "Real:[";
        for (auto & str : in.getReals())
        {
            out << str << " ";
        }
        out << "]Ints:[";
        for (auto & str : in.getInts())
        {
            out << str << " ";
        }
        out << "]Bools:[";
        for (auto & str : in.getBools())
        {
            out << str << " ";
        }
        out << "]";
        return out;
    }

    bool VariableList::isSubsetOf(const VariableList& in) const
    {
        bool abort = true;
        for (size_t i = 0; i < _vars.size(); ++i)
        {
            for (const auto & str1 : _vars[i])
            {
                bool abort = true;
                for (const auto & str2 : in._vars[i])
                    if (str1 == str2)
                    {
                        abort = false;
                        break;
                    }

                if (abort)
                    return false;
            }
        }
        return true;
    }

    size_t VariableList::sizeReals() const
    {
        return _vars[0].size();
    }

    size_t VariableList::sizeInts() const
    {
        return _vars[1].size();
    }

    size_t VariableList::sizeBools() const
    {
        return _vars[2].size();
    }

    size_t VariableList::findRealVariableNameIndex(const std::string& varName) const
    {
        size_t res = 0;
        auto pos = std::find(_vars[0].begin(),_vars[0].end(),varName);
        if(pos != _vars[0].end())
            res = std::distance(_vars[0].begin(),pos);
        return res;
    }

}  // End namespace

<commit_msg>Make use of default constructor<commit_after>/*
 * VariableList.cpp
 *
 *  Created on: 18.04.2016
 *      Author: Marc Hartung
 */

#include "../include/VariableList.hpp"
#include "../include/network_impl/SimNetworkFunctions.hpp"

#include <ostream>
#include <string>
#include <algorithm>

namespace NetOff
{
    VariableList::VariableList(const std::shared_ptr<char>& data)
        :  VariableList()
    {
        _vars = getVariableListFromData(data.get())._vars;
    }

    VariableList::VariableList()
            : _vars(std::vector<std::vector<std::string>>(3))
    {
    }

    VariableList::VariableList(const std::vector<std::string>& realVars, const std::vector<std::string>& intVars, const std::vector<std::string>& boolVars)
            : _vars(std::vector<std::vector<std::string>>(3))
    {
        _vars[0] = realVars;
        _vars[1] = intVars;
        _vars[2] = boolVars;
    }

    void VariableList::addReal(const std::string& varName)
    {
        _vars[0].push_back(varName);
    }

    void VariableList::addInt(const std::string& varName)
    {
        _vars[1].push_back(varName);
    }

    void VariableList::addBool(const std::string& varName)
    {
        _vars[2].push_back(varName);
    }

    void VariableList::addReals(const std::vector<std::string>& varNames)
    {
        _vars[0].insert(_vars[0].end(), varNames.begin(), varNames.end());
    }

    void VariableList::addInts(const std::vector<std::string>& varNames)
    {
        _vars[1].insert(_vars[1].end(), varNames.begin(), varNames.end());
    }

    void VariableList::addBools(const std::vector<std::string>& varNames)
    {
        _vars[2].insert(_vars[2].end(), varNames.begin(), varNames.end());
    }

    const std::vector<std::string>& VariableList::getReals() const
    {
        return _vars[0];
    }

    const std::vector<std::string>& VariableList::getInts() const
    {
        return _vars[1];
    }

    const std::vector<std::string>& VariableList::getBools() const
    {
        return _vars[2];
    }

    size_t VariableList::dataSize() const
    {
        size_t res = 0;
        res += 3 * sizeof(size_t);  // safe data as: [numReal,numInt,numBool,[numChars,chars]]
        for (size_t i = 0; i < 3; ++i)
            for (size_t j = 0; j < _vars[i].size(); ++j)
                res += getStringDataSize(_vars[i][j]);
        return res;
    }

    bool VariableList::empty() const
    {
        return _vars[0].empty() && _vars[1].empty() && _vars[2].empty();
    }

    std::shared_ptr<const char> VariableList::data() const
    {
        std::shared_ptr<char> res(new char[dataSize()]);
        saveVariablesTo(res.get());
        return res;
    }

    std::shared_ptr<char> VariableList::data()
    {
        std::shared_ptr<char> res(new char[dataSize()]);
        saveVariablesTo(res.get());
        return res;
    }

    void VariableList::saveVariablesTo(char * data) const
    {
        // safe data as: [numReal,numInt,numBool,[numChars,chars]]
        char * curPos = data;
        for (size_t i = 0; i < 3; ++i)
        {
            curPos = saveShiftIntegralInData<size_t>(_vars[i].size(), curPos);
        }
        for (size_t i = 0; i < 3; ++i)
            for (size_t j = 0; j < _vars[i].size(); ++j)
            {
                saveStringInData(_vars[i][j], curPos);
                curPos += getStringDataSize(_vars[i][j]);
            }
    }

    VariableList VariableList::getVariableListFromData(const char * data)
    {
        VariableList res;
        std::vector<std::vector<std::string>> & vars = res._vars;

        vars = std::vector<std::vector<std::string>>(3);
        const char * curPos = data;
        for (size_t i = 0; i < 3; ++i)
        {
            vars[i] = std::vector<std::string>(getIntegralFromData<size_t>(curPos));
            curPos = shift<size_t>(curPos);
        }
        for (size_t i = 0; i < 3; ++i)
            for (size_t j = 0; j < vars[i].size(); ++j)
            {
                vars[i][j] = createStringFromData(curPos);
                curPos += getStringDataSize(vars[i][j]);
            }
        return res;
    }

    std::ostream & operator<<(std::ostream & out, const VariableList & in)
    {
        out << "Real:[";
        for (auto & str : in.getReals())
        {
            out << str << " ";
        }
        out << "]Ints:[";
        for (auto & str : in.getInts())
        {
            out << str << " ";
        }
        out << "]Bools:[";
        for (auto & str : in.getBools())
        {
            out << str << " ";
        }
        out << "]";
        return out;
    }

    bool VariableList::isSubsetOf(const VariableList& in) const
    {
        bool abort;
        for (size_t i = 0; i < _vars.size(); ++i)
        {
            for (const auto & str1 : _vars[i])
            {
                abort = true;
                for (const auto & str2 : in._vars[i])
                    if (str1 == str2)
                    {
                        abort = false;
                        break;
                    }

                if (abort)
                    return false;
            }
        }
        return true;
    }

    size_t VariableList::sizeReals() const
    {
        return _vars[0].size();
    }

    size_t VariableList::sizeInts() const
    {
        return _vars[1].size();
    }

    size_t VariableList::sizeBools() const
    {
        return _vars[2].size();
    }

    size_t VariableList::findRealVariableNameIndex(const std::string& varName) const
    {
        size_t res = 0;
        auto pos = std::find(_vars[0].begin(),_vars[0].end(),varName);
        if(pos != _vars[0].end())
            res = std::distance(_vars[0].begin(),pos);
        return res;
    }

}  // End namespace

<|endoftext|>


<commit_before>/**************************************************************************
 * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

/* $Id$ */

///////////////////////////////////////////////////////////////////////////////
//                                                                           //
//  Alice external volume                                                    //
//  This class contains the description of the Alice external volume         //
//                                                                           //
//Begin_Html
/*

The responsible person for this module is
Andreas Morsch.

*/
//End_Html
//                                                                           //
//                                                                           //
///////////////////////////////////////////////////////////////////////////////

#include <TGeoGlobalMagField.h>
#include <TVirtualMC.h>

#include "AliBODY.h"
#include "AliMagF.h"
#include "AliRun.h"

ClassImp(AliBODY)

//_____________________________________________________________________________
AliBODY::AliBODY()
{
  //
  // Default constructor
  //
}

//_____________________________________________________________________________
AliBODY::AliBODY(const char *name, const char *title)
       : AliModule(name,title)
{
  //
  // Standard constructor of the Alice external volume
  //
  //PH  SetMarkerColor(7);
  //PH  SetMarkerStyle(2);
  //PH  SetMarkerSize(0.4);
}

//_____________________________________________________________________________
void AliBODY::CreateGeometry()
{
  //
  // Create the geometry of the Alice external body
  //
  //Begin_Html
  /*

  */
  //End_Html
  //
  // If the ZDC is present we have an asymmetric box
  // made by a four sides polygone
  //
  //Begin_Html
  /*

  */
  //End_Html
  //
  // If the ZDC is not present make just a BOX
  //
  //Begin_Html
  /*

  */
  //End_Html

  Float_t dALIC[10];
  Int_t *idtmed = fIdtmed->GetArray()+1;
  //
  if(gAlice->GetModule("ZDC")) {
    //
    // If the ZDC is present we have an asymmetric box
    // made by a four sides polygone
    //
    dALIC[0]=45;
    dALIC[1]=360;
    dALIC[2]=4;
    dALIC[3]=2;

    dALIC[4]=-15000;
    dALIC[5]=0;
    dALIC[6]=2500;

    dALIC[7]=15000;
    dALIC[8]=0;
    dALIC[9]=2500;
    gMC->Gsvolu("ALIC","PGON",idtmed[1],dALIC,10);
  } else if ( gAlice->GetModule("ACORDE")) {
    //
    // If the Cosmic Ray Trigger  is present we need a large box
    //
    //
    dALIC[0]=13000.;
    dALIC[1]=5000.;
    dALIC[2]=13000.;
    gMC->Gsvolu("ALIC","BOX ",idtmed[1],dALIC,3);

  } else {
    //
    // If the ZDC and ACORDE are not present make just a BOX
    //
    dALIC[0]=2000;
    dALIC[1]=2000;
    dALIC[2]=3000;
    gMC->Gsvolu("ALIC","BOX ",idtmed[1],dALIC,3);
  }
}

//_____________________________________________________________________________
void AliBODY::CreateMaterials()
{
// Create materials and media
  Int_t isxfld = ((AliMagF*)TGeoGlobalMagField::Instance()->GetField())->Integ();
  Float_t sxmgmx = ((AliMagF*)TGeoGlobalMagField::Instance()->GetField())->Max();

  // AIR

  Float_t aAir[4]={12.0107,14.0067,15.9994,39.948};
  Float_t zAir[4]={6.,7.,8.,18.};
  Float_t wAir[4]={0.000124,0.755267,0.231781,0.012827};
  Float_t dAir = 1.20479E-3;
  Float_t dAir1 = 1.20479E-10;
  //
  AliMixture(1,"Vacuum  $",aAir,zAir,dAir1,4,wAir);
  AliMixture(2,"Air     $",aAir,zAir,dAir,4,wAir);
  AliMaterial(3,"Be      $", 9.01,4 ,1.848   ,35.30,36.70);
  //
  AliMedium(1,"Vacuum  $",1,0,isxfld,sxmgmx,10,1,0.1,0.1,10);
  AliMedium(2,"Air     $",2,0,isxfld,sxmgmx,10,-1,-0.1,0.1 ,-10);
  AliMedium(3,"Be pipe $",3,0,isxfld,sxmgmx,10,0.1,0.1,0.01,0.01);
}

//_____________________________________________________________________________
void AliBODY::DrawModule() const
{
  //
  // Draw a view of the Alice outside box
  //
  // Set everything unseen
  gMC->Gsatt("*", "seen", -1);
  //
  // Set ALIC mother visible
  gMC->Gsatt("ALIC","SEEN",1);
  //
  // Set the volumes visible
  //
  gMC->Gdopt("hide","off");
  if(gAlice->GetModule("ZDC")) {
    //
    // ZDC is present
    //
    gMC->DefaultRange();
    gMC->Gdraw("alic", 40, 30, 0, 15, 10, .0014, .0014);
    gMC->Gdhead(1111, "Aice Main body with Zero Degree Calorimeter");
  } else {
    //
    // ZDC is not present
    //
    gMC->Gdraw("alic", 40, 30, 0, 10, 9, .0027, .0027);
    gMC->Gdhead(1111, "Aice Main body");
  }
  gMC->Gdman(18, 4, "MAN");
}

<commit_msg>Density of air scaled to 960 mbar (thanks to Ana Marin)<commit_after>/**************************************************************************
 * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

/* $Id$ */

///////////////////////////////////////////////////////////////////////////////
//                                                                           //
//  Alice external volume                                                    //
//  This class contains the description of the Alice external volume         //
//                                                                           //
//Begin_Html
/*

The responsible person for this module is
Andreas Morsch.

*/
//End_Html
//                                                                           //
//                                                                           //
///////////////////////////////////////////////////////////////////////////////

#include <TGeoGlobalMagField.h>
#include <TVirtualMC.h>

#include "AliBODY.h"
#include "AliMagF.h"
#include "AliRun.h"

ClassImp(AliBODY)

//_____________________________________________________________________________
AliBODY::AliBODY()
{
  //
  // Default constructor
  //
}

//_____________________________________________________________________________
AliBODY::AliBODY(const char *name, const char *title)
       : AliModule(name,title)
{
  //
  // Standard constructor of the Alice external volume
  //
  //PH  SetMarkerColor(7);
  //PH  SetMarkerStyle(2);
  //PH  SetMarkerSize(0.4);
}

//_____________________________________________________________________________
void AliBODY::CreateGeometry()
{
  //
  // Create the geometry of the Alice external body
  //
  //Begin_Html
  /*

  */
  //End_Html
  //
  // If the ZDC is present we have an asymmetric box
  // made by a four sides polygone
  //
  //Begin_Html
  /*

  */
  //End_Html
  //
  // If the ZDC is not present make just a BOX
  //
  //Begin_Html
  /*

  */
  //End_Html

  Float_t dALIC[10];
  Int_t *idtmed = fIdtmed->GetArray()+1;
  //
  if(gAlice->GetModule("ZDC")) {
    //
    // If the ZDC is present we have an asymmetric box
    // made by a four sides polygone
    //
    dALIC[0]=45;
    dALIC[1]=360;
    dALIC[2]=4;
    dALIC[3]=2;

    dALIC[4]=-15000;
    dALIC[5]=0;
    dALIC[6]=2500;

    dALIC[7]=15000;
    dALIC[8]=0;
    dALIC[9]=2500;
    gMC->Gsvolu("ALIC","PGON",idtmed[1],dALIC,10);
  } else if ( gAlice->GetModule("ACORDE")) {
    //
    // If the Cosmic Ray Trigger  is present we need a large box
    //
    //
    dALIC[0]=13000.;
    dALIC[1]=5000.;
    dALIC[2]=13000.;
    gMC->Gsvolu("ALIC","BOX ",idtmed[1],dALIC,3);

  } else {
    //
    // If the ZDC and ACORDE are not present make just a BOX
    //
    dALIC[0]=2000;
    dALIC[1]=2000;
    dALIC[2]=3000;
    gMC->Gsvolu("ALIC","BOX ",idtmed[1],dALIC,3);
  }
}

//_____________________________________________________________________________
void AliBODY::CreateMaterials()
{
// Create materials and media
  Int_t isxfld = ((AliMagF*)TGeoGlobalMagField::Instance()->GetField())->Integ();
  Float_t sxmgmx = ((AliMagF*)TGeoGlobalMagField::Instance()->GetField())->Max();

  // AIR

  Float_t aAir[4]={12.0107,14.0067,15.9994,39.948};
  Float_t zAir[4]={6.,7.,8.,18.};
  Float_t wAir[4]={0.000124,0.755267,0.231781,0.012827};
  Float_t dAir = 1.20479E-3 * 960./1014.;
  Float_t dAir1 = 1.20479E-10;
  //
  AliMixture(1,"Vacuum  $",aAir,zAir,dAir1,4,wAir);
  AliMixture(2,"Air     $",aAir,zAir,dAir,4,wAir);
  AliMaterial(3,"Be      $", 9.01,4 ,1.848   ,35.30,36.70);
  //
  AliMedium(1,"Vacuum  $",1,0,isxfld,sxmgmx,10,1,0.1,0.1,10);
  AliMedium(2,"Air     $",2,0,isxfld,sxmgmx,10,-1,-0.1,0.1 ,-10);
  AliMedium(3,"Be pipe $",3,0,isxfld,sxmgmx,10,0.1,0.1,0.01,0.01);
}

//_____________________________________________________________________________
void AliBODY::DrawModule() const
{
  //
  // Draw a view of the Alice outside box
  //
  // Set everything unseen
  gMC->Gsatt("*", "seen", -1);
  //
  // Set ALIC mother visible
  gMC->Gsatt("ALIC","SEEN",1);
  //
  // Set the volumes visible
  //
  gMC->Gdopt("hide","off");
  if(gAlice->GetModule("ZDC")) {
    //
    // ZDC is present
    //
    gMC->DefaultRange();
    gMC->Gdraw("alic", 40, 30, 0, 15, 10, .0014, .0014);
    gMC->Gdhead(1111, "Aice Main body with Zero Degree Calorimeter");
  } else {
    //
    // ZDC is not present
    //
    gMC->Gdraw("alic", 40, 30, 0, 10, 9, .0027, .0027);
    gMC->Gdhead(1111, "Aice Main body");
  }
  gMC->Gdman(18, 4, "MAN");
}

<|endoftext|>


<commit_before>#include "opencv2/imgcodecs.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"

#include <iostream>

using namespace std;
using namespace cv;

static void help()
{
    cout << "\nThis program demonstrates GrabCut segmentation -- select an object in a region\n"
            "and then grabcut will attempt to segment it out.\n"
            "Call:\n"
            "./grabcut <image_name>\n"
        "\nSelect a rectangular area around the object you want to segment\n" <<
        "\nHot keys: \n"
        "\tESC - quit the program\n"
        "\tr - restore the original image\n"
        "\tn - next iteration\n"
        "\n"
        "\tleft mouse button - set rectangle\n"
        "\n"
        "\tCTRL+left mouse button - set GC_BGD pixels\n"
        "\tSHIFT+left mouse button - set GC_FGD pixels\n"
        "\n"
        "\tCTRL+right mouse button - set GC_PR_BGD pixels\n"
        "\tSHIFT+right mouse button - set GC_PR_FGD pixels\n" << endl;
}

const Scalar RED = Scalar(0,0,255);
const Scalar PINK = Scalar(230,130,255);
const Scalar BLUE = Scalar(255,0,0);
const Scalar LIGHTBLUE = Scalar(255,255,160);
const Scalar GREEN = Scalar(0,255,0);

const int BGD_KEY = EVENT_FLAG_CTRLKEY;
const int FGD_KEY = EVENT_FLAG_SHIFTKEY;

static void getBinMask( const Mat& comMask, Mat& binMask )
{
    if( comMask.empty() || comMask.type()!=CV_8UC1 )
        CV_Error( Error::StsBadArg, "comMask is empty or has incorrect type (not CV_8UC1)" );
    if( binMask.empty() || binMask.rows!=comMask.rows || binMask.cols!=comMask.cols )
        binMask.create( comMask.size(), CV_8UC1 );
    binMask = comMask & 1;
}

class GCApplication
{
public:
    enum{ NOT_SET = 0, IN_PROCESS = 1, SET = 2 };
    static const int radius = 2;
    static const int thickness = -1;

    void reset();
    void setImageAndWinName( const Mat& _image, const string& _winName );
    void showImage() const;
    void mouseClick( int event, int x, int y, int flags, void* param );
    int nextIter();
    int getIterCount() const { return iterCount; }
private:
    void setRectInMask();
    void setLblsInMask( int flags, Point p, bool isPr );

    const string* winName;
    const Mat* image;
    Mat mask;
    Mat bgdModel, fgdModel;

    uchar rectState, lblsState, prLblsState;
    bool isInitialized;

    Rect rect;
    vector<Point> fgdPxls, bgdPxls, prFgdPxls, prBgdPxls;
    int iterCount;
};

void GCApplication::reset()
{
    if( !mask.empty() )
        mask.setTo(Scalar::all(GC_BGD));
    bgdPxls.clear(); fgdPxls.clear();
    prBgdPxls.clear();  prFgdPxls.clear();

    isInitialized = false;
    rectState = NOT_SET;
    lblsState = NOT_SET;
    prLblsState = NOT_SET;
    iterCount = 0;
}

void GCApplication::setImageAndWinName( const Mat& _image, const string& _winName  )
{
    if( _image.empty() || _winName.empty() )
        return;
    image = &_image;
    winName = &_winName;
    mask.create( image->size(), CV_8UC1);
    reset();
}

void GCApplication::showImage() const
{
    if( image->empty() || winName->empty() )
        return;

    Mat res;
    Mat binMask;
    if( !isInitialized )
        image->copyTo( res );
    else
    {
        getBinMask( mask, binMask );
        image->copyTo( res, binMask );
    }

    vector<Point>::const_iterator it;
    for( it = bgdPxls.begin(); it != bgdPxls.end(); ++it )
        circle( res, *it, radius, BLUE, thickness );
    for( it = fgdPxls.begin(); it != fgdPxls.end(); ++it )
        circle( res, *it, radius, RED, thickness );
    for( it = prBgdPxls.begin(); it != prBgdPxls.end(); ++it )
        circle( res, *it, radius, LIGHTBLUE, thickness );
    for( it = prFgdPxls.begin(); it != prFgdPxls.end(); ++it )
        circle( res, *it, radius, PINK, thickness );

    if( rectState == IN_PROCESS || rectState == SET )
        rectangle( res, Point( rect.x, rect.y ), Point(rect.x + rect.width, rect.y + rect.height ), GREEN, 2);

    imshow( *winName, res );
}

void GCApplication::setRectInMask()
{
    CV_Assert( !mask.empty() );
    mask.setTo( GC_BGD );
    rect.x = max(0, rect.x);
    rect.y = max(0, rect.y);
    rect.width = min(rect.width, image->cols-rect.x);
    rect.height = min(rect.height, image->rows-rect.y);
    (mask(rect)).setTo( Scalar(GC_PR_FGD) );
}

void GCApplication::setLblsInMask( int flags, Point p, bool isPr )
{
    vector<Point> *bpxls, *fpxls;
    uchar bvalue, fvalue;
    if( !isPr )
    {
        bpxls = &bgdPxls;
        fpxls = &fgdPxls;
        bvalue = GC_BGD;
        fvalue = GC_FGD;
    }
    else
    {
        bpxls = &prBgdPxls;
        fpxls = &prFgdPxls;
        bvalue = GC_PR_BGD;
        fvalue = GC_PR_FGD;
    }
    if( flags & BGD_KEY )
    {
        bpxls->push_back(p);
        circle( mask, p, radius, bvalue, thickness );
    }
    if( flags & FGD_KEY )
    {
        fpxls->push_back(p);
        circle( mask, p, radius, fvalue, thickness );
    }
}

void GCApplication::mouseClick( int event, int x, int y, int flags, void* )
{
    // TODO add bad args check
    switch( event )
    {
    case EVENT_LBUTTONDOWN: // set rect or GC_BGD(GC_FGD) labels
        {
            bool isb = (flags & BGD_KEY) != 0,
                 isf = (flags & FGD_KEY) != 0;
            if( rectState == NOT_SET && !isb && !isf )
            {
                rectState = IN_PROCESS;
                rect = Rect( x, y, 1, 1 );
            }
            if ( (isb || isf) && rectState == SET )
                lblsState = IN_PROCESS;
        }
        break;
    case EVENT_RBUTTONDOWN: // set GC_PR_BGD(GC_PR_FGD) labels
        {
            bool isb = (flags & BGD_KEY) != 0,
                 isf = (flags & FGD_KEY) != 0;
            if ( (isb || isf) && rectState == SET )
                prLblsState = IN_PROCESS;
        }
        break;
    case EVENT_LBUTTONUP:
        if( rectState == IN_PROCESS )
        {
            rect = Rect( Point(rect.x, rect.y), Point(x,y) );
            rectState = SET;
            setRectInMask();
            CV_Assert( bgdPxls.empty() && fgdPxls.empty() && prBgdPxls.empty() && prFgdPxls.empty() );
            showImage();
        }
        if( lblsState == IN_PROCESS )
        {
            setLblsInMask(flags, Point(x,y), false);
            lblsState = SET;
            showImage();
        }
        break;
    case EVENT_RBUTTONUP:
        if( prLblsState == IN_PROCESS )
        {
            setLblsInMask(flags, Point(x,y), true);
            prLblsState = SET;
            showImage();
        }
        break;
    case EVENT_MOUSEMOVE:
        if( rectState == IN_PROCESS )
        {
            rect = Rect( Point(rect.x, rect.y), Point(x,y) );
            CV_Assert( bgdPxls.empty() && fgdPxls.empty() && prBgdPxls.empty() && prFgdPxls.empty() );
            showImage();
        }
        else if( lblsState == IN_PROCESS )
        {
            setLblsInMask(flags, Point(x,y), false);
            showImage();
        }
        else if( prLblsState == IN_PROCESS )
        {
            setLblsInMask(flags, Point(x,y), true);
            showImage();
        }
        break;
    }
}

int GCApplication::nextIter()
{
    if( isInitialized )
        grabCut( *image, mask, rect, bgdModel, fgdModel, 1 );
    else
    {
        if( rectState != SET )
            return iterCount;

        if( lblsState == SET || prLblsState == SET )
            grabCut( *image, mask, rect, bgdModel, fgdModel, 1, GC_INIT_WITH_MASK );
        else
            grabCut( *image, mask, rect, bgdModel, fgdModel, 1, GC_INIT_WITH_RECT );

        isInitialized = true;
    }
    iterCount++;

    bgdPxls.clear(); fgdPxls.clear();
    prBgdPxls.clear(); prFgdPxls.clear();

    return iterCount;
}

GCApplication gcapp;

static void on_mouse( int event, int x, int y, int flags, void* param )
{
    gcapp.mouseClick( event, x, y, flags, param );
}

int main( int argc, char** argv )
{
    cv::CommandLineParser parser(argc, argv, "{help h||}{@input||}");
    if (parser.has("help"))
    {
        help();
        return 0;
    }
    string filename = parser.get<string>("@input");
    if( filename.empty() )
    {
        cout << "\nDurn, empty filename" << endl;
        return 1;
    }
    Mat image = imread( filename, 1 );
    if( image.empty() )
    {
        cout << "\n Durn, couldn't read image filename " << filename << endl;
        return 1;
    }

    help();

    const string winName = "image";
    namedWindow( winName, WINDOW_AUTOSIZE );
    setMouseCallback( winName, on_mouse, 0 );

    gcapp.setImageAndWinName( image, winName );
    gcapp.showImage();

    for(;;)
    {
        int c = waitKey(0);
        switch( (char) c )
        {
        case '\x1b':
            cout << "Exiting ..." << endl;
            goto exit_main;
        case 'r':
            cout << endl;
            gcapp.reset();
            gcapp.showImage();
            break;
        case 'n':
            int iterCount = gcapp.getIterCount();
            cout << "<" << iterCount << "... ";
            int newIterCount = gcapp.nextIter();
            if( newIterCount > iterCount )
            {
                gcapp.showImage();
                cout << iterCount << ">" << endl;
            }
            else
                cout << "rect must be determined>" << endl;
            break;
        }
    }

exit_main:
    destroyWindow( winName );
    return 0;
}
<commit_msg>Added contour highlight and rotated bounding box<commit_after>#include "opencv2/imgcodecs.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"

#include <iostream>

using namespace std;
using namespace cv;

static void help()
{
    cout << "\nThis program demonstrates GrabCut segmentation -- select an object in a region\n"
            "and then grabcut will attempt to segment it out.\n"
            "Call:\n"
            "./grabcut <image_name>\n"
        "\nSelect a rectangular area around the object you want to segment\n" <<
        "\nHot keys: \n"
        "\tESC - quit the program\n"
        "\tr - restore the original image\n"
        "\tn - next iteration\n"
        "\n"
        "\tleft mouse button - set rectangle\n"
        "\n"
        "\tCTRL+left mouse button - set GC_BGD pixels\n"
        "\tSHIFT+left mouse button - set GC_FGD pixels\n"
        "\n"
        "\tCTRL+right mouse button - set GC_PR_BGD pixels\n"
        "\tSHIFT+right mouse button - set GC_PR_FGD pixels\n" << endl;
}

const Scalar RED = Scalar(0,0,255);
const Scalar PINK = Scalar(230,130,255);
const Scalar BLUE = Scalar(255,0,0);
const Scalar LIGHTBLUE = Scalar(255,255,160);
const Scalar GREEN = Scalar(0,255,0);

const int BGD_KEY = EVENT_FLAG_CTRLKEY;
const int FGD_KEY = EVENT_FLAG_SHIFTKEY;

static void getBinMask( const Mat& comMask, Mat& binMask )
{
    if( comMask.empty() || comMask.type()!=CV_8UC1 )
        CV_Error( Error::StsBadArg, "comMask is empty or has incorrect type (not CV_8UC1)" );
    if( binMask.empty() || binMask.rows!=comMask.rows || binMask.cols!=comMask.cols )
        binMask.create( comMask.size(), CV_8UC1 );
    binMask = comMask & 1;
}

class GCApplication
{
public:
    enum{ NOT_SET = 0, IN_PROCESS = 1, SET = 2 };
    static const int radius = 2;
    static const int thickness = -1;

    void reset();
    void setImageAndWinName( const Mat& _image, const string& _winName );
    void showImage() const;
    void mouseClick( int event, int x, int y, int flags, void* param );
    int nextIter();
    int getIterCount() const { return iterCount; }
private:
    void setRectInMask();
    void setLblsInMask( int flags, Point p, bool isPr );

    const string* winName;
    const Mat* image;
    Mat mask;
    Mat bgdModel, fgdModel;

    uchar rectState, lblsState, prLblsState;
    bool isInitialized;

    Rect rect;
    vector<Point> fgdPxls, bgdPxls, prFgdPxls, prBgdPxls;
    int iterCount;
};

void GCApplication::reset()
{
    if( !mask.empty() )
        mask.setTo(Scalar::all(GC_BGD));
    bgdPxls.clear(); fgdPxls.clear();
    prBgdPxls.clear();  prFgdPxls.clear();

    isInitialized = false;
    rectState = NOT_SET;
    lblsState = NOT_SET;
    prLblsState = NOT_SET;
    iterCount = 0;
}

void GCApplication::setImageAndWinName( const Mat& _image, const string& _winName  )
{
    if( _image.empty() || _winName.empty() )
        return;
    image = &_image;
    winName = &_winName;
    mask.create( image->size(), CV_8UC1);
    reset();
}

void GCApplication::showImage() const
{
    if( image->empty() || winName->empty() )
        return;

    // Treat the image
    Mat res;
    Mat binMask;
    if( !isInitialized )
        image->copyTo( res );
    else
    {
        getBinMask( mask, binMask );
        image->copyTo( res, binMask );
    }

    /// Set a contour and its rotated bounding box
    vector<vector<Point> > contours;
    vector<Vec4i> hierarchy;
    if( isInitialized ){
        findContours( binMask, contours, hierarchy, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE );
    }
    if( isInitialized )
    {
        std::cout << "num of contours: " << contours.size() << "->";
        // eliminate small contours
        contours.erase(
                std::remove_if(
                    contours.begin(), contours.end(),
                    [](const vector<Point>& c)
                    { const int min_size = 200; return c.size() < min_size; }
                    // or a functor/plain function/Boost.Lambda expression
                    ), contours.end()
                );
        std::cout << contours.size() << " ...";
    }

    /// Find the rotated rectangles for each contour
    vector<RotatedRect> minRect( contours.size() );
    for( size_t i = 0; i < contours.size(); i++ )
        minRect[i] = minAreaRect( Mat(contours[i]) );

    for( size_t i = 0; i< contours.size(); i++ )
        {
        Scalar color( rand()&255, rand()&255, rand()&255 );
        // contour
        drawContours( res, contours, (int)i, color, 1, 8, vector<Vec4i>(), 0, Point() );
        // rotated rectangle
        Point2f rect_points[4]; minRect[i].points( rect_points );
        for( int j = 0; j < 4; j++ )
            line( res, rect_points[j], rect_points[(j+1)%4], color, 1, 8 );
        }

    vector<Point>::const_iterator it;
    for( it = bgdPxls.begin(); it != bgdPxls.end(); ++it )
        circle( res, *it, radius, BLUE, thickness );
    for( it = fgdPxls.begin(); it != fgdPxls.end(); ++it )
        circle( res, *it, radius, RED, thickness );
    for( it = prBgdPxls.begin(); it != prBgdPxls.end(); ++it )
        circle( res, *it, radius, LIGHTBLUE, thickness );
    for( it = prFgdPxls.begin(); it != prFgdPxls.end(); ++it )
        circle( res, *it, radius, PINK, thickness );

    if( rectState == IN_PROCESS || rectState == SET )
        rectangle( res, Point( rect.x, rect.y ), Point(rect.x + rect.width, rect.y + rect.height ), GREEN, 2);

    imshow( *winName, res );
}

void GCApplication::setRectInMask()
{
    CV_Assert( !mask.empty() );
    mask.setTo( GC_BGD );
    rect.x = max(0, rect.x);
    rect.y = max(0, rect.y);
    rect.width = min(rect.width, image->cols-rect.x);
    rect.height = min(rect.height, image->rows-rect.y);
    (mask(rect)).setTo( Scalar(GC_PR_FGD) );
}

void GCApplication::setLblsInMask( int flags, Point p, bool isPr )
{
    vector<Point> *bpxls, *fpxls;
    uchar bvalue, fvalue;
    if( !isPr )
    {
        bpxls = &bgdPxls;
        fpxls = &fgdPxls;
        bvalue = GC_BGD;
        fvalue = GC_FGD;
    }
    else
    {
        bpxls = &prBgdPxls;
        fpxls = &prFgdPxls;
        bvalue = GC_PR_BGD;
        fvalue = GC_PR_FGD;
    }
    if( flags & BGD_KEY )
    {
        bpxls->push_back(p);
        circle( mask, p, radius, bvalue, thickness );
    }
    if( flags & FGD_KEY )
    {
        fpxls->push_back(p);
        circle( mask, p, radius, fvalue, thickness );
    }
}

void GCApplication::mouseClick( int event, int x, int y, int flags, void* )
{
    // TODO add bad args check
    switch( event )
    {
    case EVENT_LBUTTONDOWN: // set rect or GC_BGD(GC_FGD) labels
        {
            bool isb = (flags & BGD_KEY) != 0,
                 isf = (flags & FGD_KEY) != 0;
            if( rectState == NOT_SET && !isb && !isf )
            {
                rectState = IN_PROCESS;
                rect = Rect( x, y, 1, 1 );
            }
            if ( (isb || isf) && rectState == SET )
                lblsState = IN_PROCESS;
        }
        break;
    case EVENT_RBUTTONDOWN: // set GC_PR_BGD(GC_PR_FGD) labels
        {
            bool isb = (flags & BGD_KEY) != 0,
                 isf = (flags & FGD_KEY) != 0;
            if ( (isb || isf) && rectState == SET )
                prLblsState = IN_PROCESS;
        }
        break;
    case EVENT_LBUTTONUP:
        if( rectState == IN_PROCESS )
        {
            rect = Rect( Point(rect.x, rect.y), Point(x,y) );
            rectState = SET;
            setRectInMask();
            CV_Assert( bgdPxls.empty() && fgdPxls.empty() && prBgdPxls.empty() && prFgdPxls.empty() );
            showImage();
        }
        if( lblsState == IN_PROCESS )
        {
            setLblsInMask(flags, Point(x,y), false);
            lblsState = SET;
            showImage();
        }
        break;
    case EVENT_RBUTTONUP:
        if( prLblsState == IN_PROCESS )
        {
            setLblsInMask(flags, Point(x,y), true);
            prLblsState = SET;
            showImage();
        }
        break;
    case EVENT_MOUSEMOVE:
        if( rectState == IN_PROCESS )
        {
            rect = Rect( Point(rect.x, rect.y), Point(x,y) );
            CV_Assert( bgdPxls.empty() && fgdPxls.empty() && prBgdPxls.empty() && prFgdPxls.empty() );
            showImage();
        }
        else if( lblsState == IN_PROCESS )
        {
            setLblsInMask(flags, Point(x,y), false);
            showImage();
        }
        else if( prLblsState == IN_PROCESS )
        {
            setLblsInMask(flags, Point(x,y), true);
            showImage();
        }
        break;
    }
}

int GCApplication::nextIter()
{
    if( isInitialized )
        grabCut( *image, mask, rect, bgdModel, fgdModel, 1 );
    else
    {
        if( rectState != SET )
            return iterCount;

        if( lblsState == SET || prLblsState == SET )
            grabCut( *image, mask, rect, bgdModel, fgdModel, 1, GC_INIT_WITH_MASK );
        else
            grabCut( *image, mask, rect, bgdModel, fgdModel, 1, GC_INIT_WITH_RECT );

        isInitialized = true;
    }
    iterCount++;

    bgdPxls.clear(); fgdPxls.clear();
    prBgdPxls.clear(); prFgdPxls.clear();

    return iterCount;
}

GCApplication gcapp;

static void on_mouse( int event, int x, int y, int flags, void* param )
{
    gcapp.mouseClick( event, x, y, flags, param );
}

int main( int argc, char** argv )
{
    cv::CommandLineParser parser(argc, argv, "{help h||}{@input||}");
    if (parser.has("help"))
    {
        help();
        return 0;
    }
    string filename = parser.get<string>("@input");
    if( filename.empty() )
    {
        /*
        cout << "\nDurn, empty filename" << endl;
        return 1;
        */
        filename = "../../testdata/A/A05_38.bmp";
    }
    Mat image = imread( filename, 1 );
    if( image.empty() )
    {
        cout << "\n Durn, couldn't read image filename " << filename << endl;
        return 1;
    }

    // TODO: check size and reduce it only if needed
    cv::resize(image, image, cv::Size(), 0.28, 0.28);
    help();

    const string winName = "image";
    namedWindow( winName, WINDOW_AUTOSIZE );
    setMouseCallback( winName, on_mouse, 0 );

    gcapp.setImageAndWinName( image, winName );
    gcapp.showImage();

    for(;;)
    {
        int c = waitKey(0);
        switch( (char) c )
        {
        case '\x1b':
            cout << "Exiting ..." << endl;
            goto exit_main;
        case 'r':
            cout << endl;
            gcapp.reset();
            gcapp.showImage();
            break;
        case 'n':
            int iterCount = gcapp.getIterCount();
            cout << "<" << iterCount << "... ";
            int newIterCount = gcapp.nextIter();
            if( newIterCount > iterCount )
            {
                gcapp.showImage();
                cout << iterCount << ">" << endl;
            }
            else
                cout << "rect must be determined>" << endl;
            break;
        }
    }

exit_main:
    destroyWindow( winName );
    return 0;
}
<|endoftext|>


<commit_before>/**
 *  @copyright Copyright 2016 The J-PET Framework Authors. All rights reserved.
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may find a copy of the License in the LICENCE file.
 *
 * 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.
 *
 *  @file JPetScopeConfigParser.h
 */

#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE JPetScopeConfigParser
#include <boost/test/unit_test.hpp>
#include "JPetScopeConfigParser.h"
#include <algorithm>

std::string gInputConfigJsonFilenameTest = "../../unitTestData/JPetScopeConfigParser/example.json";

BOOST_AUTO_TEST_SUITE(JPetScopeConfigParserTestSuite)

BOOST_AUTO_TEST_CASE(defaultConstructor)
{
  JPetScopeConfigParser parser;
  BOOST_REQUIRE(parser.getLoadedConfigData().empty());
}

BOOST_AUTO_TEST_CASE(transformToNumbers)
{
  using VecOfStrings = std::vector<std::string>;
  using VecOfNums = std::vector<int>;
  JPetScopeConfigParser parser;
  BOOST_REQUIRE(parser.transformToNumbers(VecOfStrings {""}).empty());
  BOOST_REQUIRE(parser.transformToNumbers(VecOfStrings {"1"}) == (VecOfNums {1}));
  BOOST_REQUIRE(parser.transformToNumbers(VecOfStrings {"1", "2"}) == (VecOfNums {1, 2}));
  BOOST_REQUIRE(parser.transformToNumbers(VecOfStrings {"1", "2", "10"}) == (VecOfNums {1, 2, 10}));
  BOOST_REQUIRE(parser.transformToNumbers(VecOfStrings {"a"}).empty());
  BOOST_REQUIRE(parser.transformToNumbers(VecOfStrings {"1", "a", "10"}) == (VecOfNums {1, 10}));
  BOOST_REQUIRE(parser.transformToNumbers(VecOfStrings {"a", "2", "5"}) == (VecOfNums {2, 5}));
  BOOST_REQUIRE(parser.transformToNumbers(VecOfStrings {"1 2", "3", "7 a 3", "1.2"}) == (VecOfNums {1, 2, 3, 7,1}));
}

BOOST_AUTO_TEST_CASE(generateFileNames)
{
  using VecOfNums = std::vector<int>;
  using VecOfStrings = std::vector<std::string>;
  JPetScopeConfigParser parser;
  BOOST_REQUIRE(parser.generateFileNames("", "", (VecOfNums {})).empty());
  BOOST_REQUIRE(parser.generateFileNames("example", "config1", (VecOfNums {1})) == (VecOfStrings {"example_config1_1"}));
  BOOST_REQUIRE(parser.generateFileNames("example", "config2", (VecOfNums {1, 3})) == (VecOfStrings {"example_config2_1", "example_config2_3"}));
}

BOOST_AUTO_TEST_CASE(getJsonContent)
{
  JPetScopeConfigParser parser;
  BOOST_REQUIRE(parser.getJsonContent("").empty());
  BOOST_REQUIRE(parser.getJsonContent("blabla.iki").empty());
  BOOST_REQUIRE(parser.getJsonContent("nonexistent.json").empty());
  BOOST_REQUIRE(!parser.getJsonContent(gInputConfigJsonFilenameTest).empty());
}

BOOST_AUTO_TEST_CASE(loadConfigFile)
{
  JPetScopeConfigParser parser;
  BOOST_REQUIRE(!parser.loadConfigFile(""));
  BOOST_REQUIRE(parser.getLoadedConfigData().empty());
  BOOST_REQUIRE(parser.loadConfigFile(gInputConfigJsonFilenameTest));
  BOOST_REQUIRE(!parser.getLoadedConfigData().empty());
}

BOOST_AUTO_TEST_CASE(getInputFileNames)
{
  using VecOfStrings = std::vector<std::string>;
  JPetScopeConfigParser parser;
  BOOST_REQUIRE(parser.getInputFileNames("").empty());
  VecOfStrings expectedRes {"config1_1", "config1_5",
                            "config1_2", "config1_12",
                            "config1_6"};
  std::transform(expectedRes.begin(), expectedRes.end(),expectedRes.begin(),
                [&](std::string name) {
                  return gInputConfigJsonFilenameTest+"_"+name;
                });
  BOOST_REQUIRE(parser.getInputFileNames(gInputConfigJsonFilenameTest) == expectedRes);
}

BOOST_AUTO_TEST_CASE(getConfigs)
{
  using VecOfStrings = std::vector<std::string>;
  JPetScopeConfigParser parser;
  BOOST_REQUIRE(parser.getConfigs("").empty());

  JPetScopeConfigParser::Config config;
  config.fLocation="data";
  config.fCollimatorPositions = VecOfStrings { "1 5 2", "12", "6"};
  config.fBSlots= std::vector<JPetScopeConfigParser::BSlot>{ JPetScopeConfigParser::BSlot(-1,false,"",-1., -1), JPetScopeConfigParser::BSlot(-1,false,"",-1., -1)};
  config.fPMs = std::vector<JPetScopeConfigParser::PM>{JPetScopeConfigParser::PM(3,"C2"), JPetScopeConfigParser::PM(98, "C4"), JPetScopeConfigParser::PM(32, "C1"), JPetScopeConfigParser::PM(42, "C3")};
  config.fScins=std::vector<JPetScopeConfigParser::Scin>{JPetScopeConfigParser::Scin(32), JPetScopeConfigParser::Scin(12)};
  config.fName="config1";

  BOOST_REQUIRE(!parser.getConfigs(gInputConfigJsonFilenameTest).empty());
  auto res = parser.getConfigs(gInputConfigJsonFilenameTest).front();

  BOOST_REQUIRE(res.fName == config.fName);
  BOOST_REQUIRE(res.fLocation == config.fLocation);
  BOOST_REQUIRE(res.fCollimatorPositions == config.fCollimatorPositions);

  BOOST_REQUIRE(res.fPMs.size() == config.fPMs.size());
  for (auto i = 0u ; i < config.fPMs.size(); i++)
  {
    BOOST_REQUIRE(config.fPMs[i].fId == res.fPMs[i].fId);
    BOOST_REQUIRE(config.fPMs[i].fPrefix == res.fPMs[i].fPrefix);
  }

  BOOST_REQUIRE(res.fScins.size() == config.fScins.size());
  for (auto i = 0u ; i < config.fScins.size(); i++)
  {
    BOOST_REQUIRE(config.fScins[i].fId == res.fScins[i].fId);
  }

  BOOST_REQUIRE(res.fBSlots.size() == config.fBSlots.size());
  for (auto i = 0u ; i < config.fBSlots.size(); i++)
  {
    BOOST_REQUIRE(config.fBSlots[i].fId == res.fBSlots[i].fId);
    BOOST_REQUIRE(config.fBSlots[i].fActive == res.fBSlots[i].fActive);
    BOOST_REQUIRE(config.fBSlots[i].fName == res.fBSlots[i].fName);
    BOOST_REQUIRE_CLOSE(config.fBSlots[i].fTheta,  res.fBSlots[i].fTheta, 0.00001);
    BOOST_REQUIRE(config.fBSlots[i].fFrame == res.fBSlots[i].fFrame);
  }
}

BOOST_AUTO_TEST_SUITE_END()
<commit_msg>Cosmetic changes in JPetScopeConfigParserTest.cpp<commit_after>/**
 *  @copyright Copyright 2016 The J-PET Framework Authors. All rights reserved.
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may find a copy of the License in the LICENCE file.
 *
 * 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.
 *
 *  @file JPetScopeConfigParser.h
 */

#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE JPetScopeConfigParser
#include <boost/test/unit_test.hpp>
#include "JPetScopeConfigParser.h"
#include <algorithm>

std::string gInputConfigJsonFilenameTest = "../../unitTestData/JPetScopeConfigParser/example.json";

BOOST_AUTO_TEST_SUITE(JPetScopeConfigParserTestSuite)

BOOST_AUTO_TEST_CASE(defaultConstructor)
{
  JPetScopeConfigParser parser;
  BOOST_REQUIRE(parser.getLoadedConfigData().empty());
}

BOOST_AUTO_TEST_CASE(transformToNumbers)
{
  using VecOfStrings = std::vector<std::string>;
  using VecOfNums = std::vector<int>;
  JPetScopeConfigParser parser;
  BOOST_REQUIRE(parser.transformToNumbers(VecOfStrings {""}).empty());
  BOOST_REQUIRE(parser.transformToNumbers(VecOfStrings {"1"}) == (VecOfNums {1}));
  BOOST_REQUIRE(parser.transformToNumbers(VecOfStrings {"1", "2"}) == (VecOfNums {1, 2}));
  BOOST_REQUIRE(parser.transformToNumbers(VecOfStrings {"1", "2", "10"}) == (VecOfNums {1, 2, 10}));
  BOOST_REQUIRE(parser.transformToNumbers(VecOfStrings {"a"}).empty());
  BOOST_REQUIRE(parser.transformToNumbers(VecOfStrings {"1", "a", "10"}) == (VecOfNums {1, 10}));
  BOOST_REQUIRE(parser.transformToNumbers(VecOfStrings {"a", "2", "5"}) == (VecOfNums {2, 5}));
  BOOST_REQUIRE(parser.transformToNumbers(VecOfStrings {"1 2", "3", "7 a 3", "1.2"}) == (VecOfNums {1, 2, 3, 7,1}));
}

BOOST_AUTO_TEST_CASE(generateFileNames)
{
  using VecOfNums = std::vector<int>;
  using VecOfStrings = std::vector<std::string>;
  JPetScopeConfigParser parser;
  BOOST_REQUIRE(parser.generateFileNames("", "", (VecOfNums {})).empty());
  BOOST_REQUIRE(parser.generateFileNames("example", "config1", (VecOfNums {1})) == (VecOfStrings {"example_config1_1"}));
  BOOST_REQUIRE(parser.generateFileNames("example", "config2", (VecOfNums {1, 3})) == (VecOfStrings {"example_config2_1", "example_config2_3"}));
}

BOOST_AUTO_TEST_CASE(getJsonContent)
{
  JPetScopeConfigParser parser;
  BOOST_REQUIRE(parser.getJsonContent("").empty());
  BOOST_REQUIRE(parser.getJsonContent("blabla.iki").empty());
  BOOST_REQUIRE(parser.getJsonContent("nonexistent.json").empty());
  BOOST_REQUIRE(!parser.getJsonContent(gInputConfigJsonFilenameTest).empty());
}

BOOST_AUTO_TEST_CASE(loadConfigFile)
{
  JPetScopeConfigParser parser;
  BOOST_REQUIRE(!parser.loadConfigFile(""));
  BOOST_REQUIRE(parser.getLoadedConfigData().empty());
  BOOST_REQUIRE(parser.loadConfigFile(gInputConfigJsonFilenameTest));
  BOOST_REQUIRE(!parser.getLoadedConfigData().empty());
}

BOOST_AUTO_TEST_CASE(getInputFileNames)
{
  using VecOfStrings = std::vector<std::string>;
  JPetScopeConfigParser parser;
  BOOST_REQUIRE(parser.getInputFileNames("").empty());
  VecOfStrings expectedRes {"config1_1", "config1_5",
                            "config1_2", "config1_12",
                            "config1_6"};
  std::transform(expectedRes.begin(), expectedRes.end(),expectedRes.begin(),
                [&](std::string name) {
                  return gInputConfigJsonFilenameTest+"_"+name;
                });
  BOOST_REQUIRE(parser.getInputFileNames(gInputConfigJsonFilenameTest) == expectedRes);
}

BOOST_AUTO_TEST_CASE(getConfigs)
{
  using VecOfStrings = std::vector<std::string>;
  JPetScopeConfigParser parser;
  BOOST_REQUIRE(parser.getConfigs("").empty());

  JPetScopeConfigParser::Config config;
  config.fLocation="data";
  config.fCollimatorPositions = VecOfStrings { "1 5 2", "12", "6"};
  config.fBSlots= std::vector<JPetScopeConfigParser::BSlot>{ JPetScopeConfigParser::BSlot(-1,false,"",-1., -1), JPetScopeConfigParser::BSlot(-1,false,"",-1., -1)};
  config.fPMs = std::vector<JPetScopeConfigParser::PM>{JPetScopeConfigParser::PM(3,"C2"), JPetScopeConfigParser::PM(98, "C4"), JPetScopeConfigParser::PM(32, "C1"), JPetScopeConfigParser::PM(42, "C3")};
  config.fScins=std::vector<JPetScopeConfigParser::Scin>{JPetScopeConfigParser::Scin(32), JPetScopeConfigParser::Scin(12)};
  config.fName="config1";

  BOOST_REQUIRE(!parser.getConfigs(gInputConfigJsonFilenameTest).empty());
  auto res = parser.getConfigs(gInputConfigJsonFilenameTest).front();

  BOOST_REQUIRE(res.fName == config.fName);
  BOOST_REQUIRE(res.fLocation == config.fLocation);
  BOOST_REQUIRE(res.fCollimatorPositions == config.fCollimatorPositions);

  BOOST_REQUIRE(res.fPMs.size() == config.fPMs.size());
  for (auto i = 0u ; i < config.fPMs.size(); i++)
  {
    BOOST_REQUIRE(config.fPMs[i].fId == res.fPMs[i].fId);
    BOOST_REQUIRE(config.fPMs[i].fPrefix == res.fPMs[i].fPrefix);
  }

  BOOST_REQUIRE(res.fScins.size() == config.fScins.size());
  for (auto i = 0u ; i < config.fScins.size(); i++)
  {
    BOOST_REQUIRE(config.fScins[i].fId == res.fScins[i].fId);
  }

  BOOST_REQUIRE(res.fBSlots.size() == config.fBSlots.size());
  for (auto i = 0u ; i < config.fBSlots.size(); i++)
  {
    BOOST_REQUIRE(config.fBSlots[i].fId == res.fBSlots[i].fId);
    BOOST_REQUIRE(config.fBSlots[i].fActive == res.fBSlots[i].fActive);
    BOOST_REQUIRE(config.fBSlots[i].fName == res.fBSlots[i].fName);
    BOOST_REQUIRE_CLOSE(config.fBSlots[i].fTheta,  res.fBSlots[i].fTheta, 0.00001);
    BOOST_REQUIRE(config.fBSlots[i].fFrame == res.fBSlots[i].fFrame);
  }
}

BOOST_AUTO_TEST_SUITE_END()
<|endoftext|>


<commit_before>#include "testz.h"

#include <QTimeZone>
#include <QString>
#include <QDebug>

void test_timezone()
{
    qDebug() << Q_FUNC_INFO << QTimeZone::systemTimeZoneId();
}
<commit_msg>b64: list availiable iana timezone id<commit_after>#include "testz.h"

#include <QList>
#include <QByteArray>
#include <QTimeZone>
#include <QString>
#include <QDebug>

void test_timezone()
{
    qDebug() << Q_FUNC_INFO << QTimeZone::systemTimeZoneId();

    QList<QByteArray> array = QTimeZone::availableTimeZoneIds();
    foreach (QByteArray aa, array) {
        qDebug() << aa;
    }
}
<|endoftext|>


<commit_before>#include "drake/examples/SimpleCar/simple_car.h"

#include <cmath>

#include "drake/Path.h"

#include "drake/examples/Cars/gen/euler_floating_joint_state.h"
#include "drake/systems/LCMSystem.h"
#include "drake/systems/LinearSystem.h"
#include "drake/systems/plants/BotVisualizer.h"
#include "lcmtypes/drake/lcmt_driving_command_t.hpp"

// TODO(rpoyner-tri): move this to somewhere common; it is useful.
/// LCMTap -- a system that wires input to output, and publishes input to LCM.
template <template <typename> class Vector>
class LCMTap {
 public:
  template <typename ScalarType>
  using StateVector = Drake::NullVector<ScalarType>;
  template <typename ScalarType>
  using InputVector = Vector<ScalarType>;
  template <typename ScalarType>
  using OutputVector = Vector<ScalarType>;

  explicit LCMTap(std::shared_ptr<lcm::LCM> lcm) : lcm(lcm) {}

  StateVector<double> dynamics(const double& t, const StateVector<double>& x,
                               const InputVector<double>& u) const {
    return StateVector<double>();
  }

  OutputVector<double> output(const double& t, const StateVector<double>& x,
                              const InputVector<double>& u) const {
    typename Vector<double>::LCMMessageType msg;
    if (!encode(t, u, msg))
      throw std::runtime_error(std::string("failed to encode") +
                               msg.getTypeName());
    lcm->publish(u.channel(), &msg);
    return u;
  }

  bool isTimeVarying() const { return false; }
  bool isDirectFeedthrough() const { return true; }

 private:
  const std::shared_ptr<lcm::LCM> lcm;
};

namespace Drake {
namespace {

int do_main(int argc, const char* argv[]) {
  std::shared_ptr<lcm::LCM> lcm = std::make_shared<lcm::LCM>();

  auto car = std::make_shared<SimpleCar>();

  //
  // Make a linear system to map simple car state to the state vector of a
  // floating joint, allowing motion and steering in the x-y plane only.
  //
  const int insize = SimpleCarState<double>().size();
  const int outsize = EulerFloatingJointState<double>().size();
  Eigen::MatrixXd D;
  D.setZero(outsize, insize);
  D(EulerFloatingJointStateIndices::kX, SimpleCarStateIndices::kX) = 1;
  D(EulerFloatingJointStateIndices::kY, SimpleCarStateIndices::kY) = 1;
  D(EulerFloatingJointStateIndices::kYaw, SimpleCarStateIndices::kHeading) = -1;
  EulerFloatingJointState<double> y0;
  y0.set_yaw(M_PI / 2);
  auto adapter = std::make_shared<
      AffineSystem<
        NullVector,
        SimpleCarState,
        EulerFloatingJointState> >(
            Eigen::MatrixXd::Zero(0, 0),
            Eigen::MatrixXd::Zero(0, insize),
            Eigen::VectorXd::Zero(0),
            Eigen::MatrixXd::Zero(outsize, 0), D,
            toEigen(y0));

  //
  // Load a simplistic rendering from accompanying URDF file.
  //
  auto tree = std::make_shared<RigidBodyTree>(
      getDrakePath() + "/examples/SimpleCar/boxcar.urdf");

  auto viz =
      std::make_shared<BotVisualizer<EulerFloatingJointState> >(
          lcm, tree);

  // Make some taps to publish intermediate states to LCM.
  auto car_tap = std::make_shared<LCMTap<SimpleCarState> >(lcm);
  auto adapter_tap = std::make_shared<LCMTap<EulerFloatingJointState> >(lcm);

  // Assemble car, adapter, and visualizer, with intervening taps.
  auto car_tapped = cascade(car, car_tap);
  auto adapter_tapped = cascade(adapter, adapter_tap);
  auto adapt_viz = cascade(adapter_tapped, viz);
  auto sys = cascade(car_tapped, adapt_viz);

  SimpleCarState<double> initial_state;
  runLCM(sys, lcm, 0, std::numeric_limits<double>::infinity(), initial_state);

  return 0;
}

}  // namespace
}  // namespace Drake

int main(int argc, const char* argv[]) {
  return Drake::do_main(argc, argv);
}
<commit_msg>Fix up the new path to boxcar.<commit_after>#include "drake/examples/SimpleCar/simple_car.h"

#include <cmath>

#include "drake/Path.h"

#include "drake/examples/Cars/gen/euler_floating_joint_state.h"
#include "drake/systems/LCMSystem.h"
#include "drake/systems/LinearSystem.h"
#include "drake/systems/plants/BotVisualizer.h"
#include "lcmtypes/drake/lcmt_driving_command_t.hpp"

// TODO(rpoyner-tri): move this to somewhere common; it is useful.
/// LCMTap -- a system that wires input to output, and publishes input to LCM.
template <template <typename> class Vector>
class LCMTap {
 public:
  template <typename ScalarType>
  using StateVector = Drake::NullVector<ScalarType>;
  template <typename ScalarType>
  using InputVector = Vector<ScalarType>;
  template <typename ScalarType>
  using OutputVector = Vector<ScalarType>;

  explicit LCMTap(std::shared_ptr<lcm::LCM> lcm) : lcm(lcm) {}

  StateVector<double> dynamics(const double& t, const StateVector<double>& x,
                               const InputVector<double>& u) const {
    return StateVector<double>();
  }

  OutputVector<double> output(const double& t, const StateVector<double>& x,
                              const InputVector<double>& u) const {
    typename Vector<double>::LCMMessageType msg;
    if (!encode(t, u, msg))
      throw std::runtime_error(std::string("failed to encode") +
                               msg.getTypeName());
    lcm->publish(u.channel(), &msg);
    return u;
  }

  bool isTimeVarying() const { return false; }
  bool isDirectFeedthrough() const { return true; }

 private:
  const std::shared_ptr<lcm::LCM> lcm;
};

namespace Drake {
namespace {

int do_main(int argc, const char* argv[]) {
  std::shared_ptr<lcm::LCM> lcm = std::make_shared<lcm::LCM>();

  auto car = std::make_shared<SimpleCar>();

  //
  // Make a linear system to map simple car state to the state vector of a
  // floating joint, allowing motion and steering in the x-y plane only.
  //
  const int insize = SimpleCarState<double>().size();
  const int outsize = EulerFloatingJointState<double>().size();
  Eigen::MatrixXd D;
  D.setZero(outsize, insize);
  D(EulerFloatingJointStateIndices::kX, SimpleCarStateIndices::kX) = 1;
  D(EulerFloatingJointStateIndices::kY, SimpleCarStateIndices::kY) = 1;
  D(EulerFloatingJointStateIndices::kYaw, SimpleCarStateIndices::kHeading) = -1;
  EulerFloatingJointState<double> y0;
  y0.set_yaw(M_PI / 2);
  auto adapter = std::make_shared<
      AffineSystem<
        NullVector,
        SimpleCarState,
        EulerFloatingJointState> >(
            Eigen::MatrixXd::Zero(0, 0),
            Eigen::MatrixXd::Zero(0, insize),
            Eigen::VectorXd::Zero(0),
            Eigen::MatrixXd::Zero(outsize, 0), D,
            toEigen(y0));

  //
  // Load a simplistic rendering from accompanying URDF file.
  //
  auto tree = std::make_shared<RigidBodyTree>(
      getDrakePath() + "/examples/Cars/models/boxcar.urdf");

  auto viz =
      std::make_shared<BotVisualizer<EulerFloatingJointState> >(
          lcm, tree);

  // Make some taps to publish intermediate states to LCM.
  auto car_tap = std::make_shared<LCMTap<SimpleCarState> >(lcm);
  auto adapter_tap = std::make_shared<LCMTap<EulerFloatingJointState> >(lcm);

  // Assemble car, adapter, and visualizer, with intervening taps.
  auto car_tapped = cascade(car, car_tap);
  auto adapter_tapped = cascade(adapter, adapter_tap);
  auto adapt_viz = cascade(adapter_tapped, viz);
  auto sys = cascade(car_tapped, adapt_viz);

  SimpleCarState<double> initial_state;
  runLCM(sys, lcm, 0, std::numeric_limits<double>::infinity(), initial_state);

  return 0;
}

}  // namespace
}  // namespace Drake

int main(int argc, const char* argv[]) {
  return Drake::do_main(argc, argv);
}
<|endoftext|>


<commit_before>#include "ros/ros.h"

#include "drake/examples/Cars/car_simulation.h"
#include "drake/examples/Cars/gen/driving_command.h"
#include "drake/systems/LCMSystem.h"
#include "drake/systems/LinearSystem.h"
#include "drake/systems/pd_control_system.h"
#include "drake/systems/plants/BotVisualizer.h"
#include "drake/systems/plants/RigidBodySystem.h"
#include "drake/util/drakeAppUtil.h"
#include "drake_ros/ros_tf_publisher.h"
#include "drake_ros/ros_vehicle_system.h"
#include "drake_ros/ros_sensor_publisher_joint_state.h"
#include "drake_ros/ros_sensor_publisher_lidar.h"
#include "drake_ros/ros_sensor_publisher_odometry.h"

using drake::BotVisualizer;
using drake::SimulationOptions;
using drake::cascade;

using Eigen::VectorXd;

namespace drake {
namespace ros {
namespace cars {
namespace {

using drake::examples::cars::CreateRigidBodySystem;
using drake::examples::cars::CreateVehicleSystem;
using drake::examples::cars::GetCarSimulationDefaultOptions;

/** Driving Simulator
 * Usage:  car_sim_lcm_and_ros vehicle_model_file [world_model files ...]
 */
int do_main(int argc, const char* argv[]) {
  ::ros::init(argc, const_cast<char**>(argv), "single_car_sim_in_stata_garage");

  // Initializes the communication layer.
  std::shared_ptr<lcm::LCM> lcm = std::make_shared<lcm::LCM>();

  // Instantiates a duration variable that will be set by the call to
  // CreateRigidBodySystem() below.
  double duration = std::numeric_limits<double>::infinity();

  // Initializes the rigid body system.
  auto rigid_body_sys = CreateRigidBodySystem(argc, argv, &duration);
  auto const& tree = rigid_body_sys->getRigidBodyTree();

  // Initializes and cascades all of the other systems.
  auto vehicle_sys = CreateVehicleSystem(rigid_body_sys);

  auto visualizer =
      std::make_shared<BotVisualizer<RigidBodySystem::StateVector>>(lcm, tree);

  auto lidar_publisher = std::make_shared<
      ::drake::ros::SensorPublisherLidar<RigidBodySystem::StateVector>>(
      rigid_body_sys);

  auto odometry_publisher = std::make_shared<
      ::drake::ros::SensorPublisherOdometry<RigidBodySystem::StateVector>>(
      rigid_body_sys);

  auto tf_publisher = std::make_shared<
      ::drake::ros::DrakeRosTfPublisher<RigidBodySystem::StateVector>>(tree);

  auto joint_state_publisher = std::make_shared<
      ::drake::ros::SensorPublisherJointState<RigidBodySystem::StateVector>>(
      rigid_body_sys);

  auto sys =
      cascade(
        cascade(
          cascade(
            cascade(
              cascade(
                vehicle_sys, visualizer),
              lidar_publisher),
            odometry_publisher),
          tf_publisher),
        joint_state_publisher);

  // Initializes the simulation options.
  SimulationOptions options = GetCarSimulationDefaultOptions();
  options.should_stop = [](double sim_time) {
    return !::ros::ok();
  };

  // Obtains a valid zero configuration for the vehicle.
  VectorXd x0 = VectorXd::Zero(rigid_body_sys->getNumStates());
  x0.head(tree->number_of_positions()) = tree->getZeroConfiguration();

  // Defines the start time of the simulation.
  const double kStartTime = 0;

  drake::ros::run_ros_vehicle_sim(sys, kStartTime, duration, x0, options);

  return 0;
}

}  // namespace
}  // namespace cars
}  // namespace ros
}  // namespace drake

int main(int argc, const char* argv[]) {
  return drake::ros::cars::do_main(argc, argv);
}
<commit_msg>Updated name of node to equal file and binary name.<commit_after>#include "ros/ros.h"

#include "drake/examples/Cars/car_simulation.h"
#include "drake/examples/Cars/gen/driving_command.h"
#include "drake/systems/LCMSystem.h"
#include "drake/systems/LinearSystem.h"
#include "drake/systems/pd_control_system.h"
#include "drake/systems/plants/BotVisualizer.h"
#include "drake/systems/plants/RigidBodySystem.h"
#include "drake/util/drakeAppUtil.h"
#include "drake_ros/ros_tf_publisher.h"
#include "drake_ros/ros_vehicle_system.h"
#include "drake_ros/ros_sensor_publisher_joint_state.h"
#include "drake_ros/ros_sensor_publisher_lidar.h"
#include "drake_ros/ros_sensor_publisher_odometry.h"

using drake::BotVisualizer;
using drake::SimulationOptions;
using drake::cascade;

using Eigen::VectorXd;

namespace drake {
namespace ros {
namespace cars {
namespace {

using drake::examples::cars::CreateRigidBodySystem;
using drake::examples::cars::CreateVehicleSystem;
using drake::examples::cars::GetCarSimulationDefaultOptions;

/** Driving Simulator
 * Usage:  car_sim_lcm_and_ros vehicle_model_file [world_model files ...]
 */
int do_main(int argc, const char* argv[]) {
  ::ros::init(argc, const_cast<char**>(argv), "single_car_in_stata_garage");

  // Initializes the communication layer.
  std::shared_ptr<lcm::LCM> lcm = std::make_shared<lcm::LCM>();

  // Instantiates a duration variable that will be set by the call to
  // CreateRigidBodySystem() below.
  double duration = std::numeric_limits<double>::infinity();

  // Initializes the rigid body system.
  auto rigid_body_sys = CreateRigidBodySystem(argc, argv, &duration);
  auto const& tree = rigid_body_sys->getRigidBodyTree();

  // Initializes and cascades all of the other systems.
  auto vehicle_sys = CreateVehicleSystem(rigid_body_sys);

  auto visualizer =
      std::make_shared<BotVisualizer<RigidBodySystem::StateVector>>(lcm, tree);

  auto lidar_publisher = std::make_shared<
      ::drake::ros::SensorPublisherLidar<RigidBodySystem::StateVector>>(
      rigid_body_sys);

  auto odometry_publisher = std::make_shared<
      ::drake::ros::SensorPublisherOdometry<RigidBodySystem::StateVector>>(
      rigid_body_sys);

  auto tf_publisher = std::make_shared<
      ::drake::ros::DrakeRosTfPublisher<RigidBodySystem::StateVector>>(tree);

  auto joint_state_publisher = std::make_shared<
      ::drake::ros::SensorPublisherJointState<RigidBodySystem::StateVector>>(
      rigid_body_sys);

  auto sys =
      cascade(
        cascade(
          cascade(
            cascade(
              cascade(
                vehicle_sys, visualizer),
              lidar_publisher),
            odometry_publisher),
          tf_publisher),
        joint_state_publisher);

  // Initializes the simulation options.
  SimulationOptions options = GetCarSimulationDefaultOptions();
  options.should_stop = [](double sim_time) {
    return !::ros::ok();
  };

  // Obtains a valid zero configuration for the vehicle.
  VectorXd x0 = VectorXd::Zero(rigid_body_sys->getNumStates());
  x0.head(tree->number_of_positions()) = tree->getZeroConfiguration();

  // Defines the start time of the simulation.
  const double kStartTime = 0;

  drake::ros::run_ros_vehicle_sim(sys, kStartTime, duration, x0, options);

  return 0;
}

}  // namespace
}  // namespace cars
}  // namespace ros
}  // namespace drake

int main(int argc, const char* argv[]) {
  return drake::ros::cars::do_main(argc, argv);
}
<|endoftext|>