<commit_before>
#include "CubeScape.h"

#include <array>
#include <iostream>

#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>

#include <glbinding/gl/enum.h>
#include <glbinding/gl/bitfield.h>

#include <globjects/globjects.h>
#include <globjects/logging.h>
#include <globjects/DebugMessage.h>
#include <globjects/VertexAttributeBinding.h>

#include <gloperate/resources/RawFile.h>

#include <gloperate/base/RenderTargetType.h>

#include <gloperate/painter/Camera.h>
#include <gloperate/painter/TargetFramebufferCapability.h>
#include <gloperate/painter/ViewportCapability.h>
#include <gloperate/painter/PerspectiveProjectionCapability.h>
#include <gloperate/painter/CameraCapability.h>
#include <gloperate/painter/TypedRenderTargetCapability.h>
#include <gloperate/painter/VirtualTimeCapability.h>

using namespace gl;
using namespace glm;
using namespace globjects;

CubeScape::CubeScape(gloperate::ResourceManager & resourceManager, const std::string & relDataPath)
: Painter("CubeScape", resourceManager, relDataPath)
, m_animation{true}
, m_numCubes{25}
, a_vertex{-1}
, u_transform{-1}
, u_time{-1}
, u_numcubes{-1}
{
    // Setup painter
    m_targetFramebufferCapability = addCapability(new gloperate::TargetFramebufferCapability());
    m_viewportCapability = addCapability(new gloperate::ViewportCapability());
    m_projectionCapability = addCapability(new gloperate::PerspectiveProjectionCapability(m_viewportCapability));
    m_typedRenderTargetCapability = addCapability(new gloperate::TypedRenderTargetCapability());
    m_cameraCapability = addCapability(new gloperate::CameraCapability());
    m_timeCapability = addCapability(new gloperate::VirtualTimeCapability());

    m_timeCapability->setLoopDuration(20.0f * pi<float>());

    m_targetFramebufferCapability->changed.connect([this](){ this->onTargetFramebufferChanged();});

    // Register properties
    addProperty<bool>("Animation", this, &CubeScape::animation, &CubeScape::setAnimation);

    auto * propNumCubes = addProperty<int>("NumCubes", this, &CubeScape::numberOfCubes, &CubeScape::setNumberOfCubes);
    propNumCubes->setOption("minimum", 0);

    // Register scripting functions
    addFunction("randomize", this, &CubeScape::randomize);
}

CubeScape::~CubeScape()
{
}

void CubeScape::setupProjection()
{
    m_projectionCapability->setZNear(0.3f);
    m_projectionCapability->setZFar(15.f);
    m_projectionCapability->setFovy(radians(50.f));
}

void CubeScape::onInitialize()
{
    // create program

    globjects::init();
    onTargetFramebufferChanged();

#ifdef __APPLE__
    Shader::clearGlobalReplacements();
    Shader::globalReplace("#version 140", "#version 150");

    debug() << "Using global OS X shader replacement '#version 140' -> '#version 150'" << std::endl;
#endif

    m_program = new globjects::Program;
    m_program->attach(
        globjects::Shader::fromFile(GL_VERTEX_SHADER,   m_relDataPath + "data/cubescape/cubescape.vert"),
        globjects::Shader::fromFile(GL_GEOMETRY_SHADER, m_relDataPath + "data/cubescape/cubescape.geom"),
        globjects::Shader::fromFile(GL_FRAGMENT_SHADER, m_relDataPath + "data/cubescape/cubescape.frag")
    );

    // create textures

    m_textures[0] = new globjects::Texture;
    m_textures[1] = new globjects::Texture;

    for (int i=0; i < 2; ++i)
    {
        m_textures[i]->setParameter(GL_TEXTURE_WRAP_S, GL_REPEAT);
        m_textures[i]->setParameter(GL_TEXTURE_WRAP_T, GL_REPEAT);

        m_textures[i]->setParameter(GL_TEXTURE_MIN_FILTER, GL_LINEAR);
        m_textures[i]->setParameter(GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    }

    {
        gloperate::RawFile terrain(m_relDataPath + "data/cubescape/terrain.512.512.r.ub.raw");
        if (!terrain.isValid())
            std::cout << "warning: loading texture from " << terrain.filePath() << " failed.";

        m_textures[0]->image2D(0, GL_RED_NV, 512, 512, 0, GL_RED, GL_UNSIGNED_BYTE, terrain.data());
    }

    {
        gloperate::RawFile patches(m_relDataPath + "data/cubescape/patches.64.16.rgb.ub.raw");
        if (!patches.isValid())
            std::cout << "warning: loading texture from " << patches.filePath() << " failed.";

        m_textures[1]->image2D(0, GL_RGB8, 64, 16, 0, GL_RGB, GL_UNSIGNED_BYTE, patches.data());
    }

    m_vao = new globjects::VertexArray;
    m_vao->bind();

    m_vertices = new globjects::Buffer;
    m_indices = new globjects::Buffer;

    const std::array<vec3, 8> vertices =
    {
        vec3(-1.f, -1.f, -1.f ), // 0
        vec3(-1.f, -1.f,  1.f ), // 1
        vec3(-1.f,  1.f, -1.f ), // 2
        vec3(-1.f,  1.f,  1.f ), // 3
        vec3( 1.f, -1.f, -1.f ), // 4
        vec3( 1.f, -1.f,  1.f ), // 5
        vec3( 1.f,  1.f, -1.f ), // 6
        vec3( 1.f,  1.f,  1.f )  // 7
    };

    m_vertices->setData(vertices, GL_STATIC_DRAW);

    const std::array<unsigned char, 18> indices =
        { 2, 3, 6, 0, 1, 2, 1, 5, 3, 5, 4, 7, 4, 0, 6, 5, 1, 4 };

    m_indices->setData(indices, GL_STATIC_DRAW);
    m_indices->bind(GL_ELEMENT_ARRAY_BUFFER);

    // setup uniforms

    a_vertex = m_program->getAttributeLocation("a_vertex");

    m_vao->binding(0)->setAttribute(a_vertex);
    m_vao->binding(0)->setBuffer(m_vertices, 0, sizeof(vec3));
    m_vao->binding(0)->setFormat(3, GL_FLOAT, GL_FALSE, 0);

    m_vao->enable(a_vertex);

    u_transform = m_program->getUniformLocation("modelViewProjection");
    u_time = m_program->getUniformLocation("time");
    u_numcubes = m_program->getUniformLocation("numcubes");

    GLint terrain = m_program->getUniformLocation("terrain");
    GLint patches = m_program->getUniformLocation("patches");

    // since only single program and single data is used, bind only once

    glClearColor(0.f, 0.f, 0.f, 1.0f);

    m_program->setUniform(terrain, 0);
    m_program->setUniform(patches, 1);

    setupProjection();
}

void CubeScape::onPaint()
{
    if (m_viewportCapability->hasChanged())
    {
        glViewport(m_viewportCapability->x(), m_viewportCapability->y(), m_viewportCapability->width(), m_viewportCapability->height());

        m_viewportCapability->setChanged(false);
    }

    globjects::Framebuffer * fbo = m_targetFramebufferCapability->framebuffer();

    if (!fbo)
    {
        fbo = globjects::Framebuffer::defaultFBO();
    }

    fbo->bind(GL_FRAMEBUFFER);

    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glEnable(GL_DEPTH_TEST);

    mat4 transform = m_projectionCapability->projection() * m_cameraCapability->view();

    m_vao->bind();

    m_indices->bind(GL_ELEMENT_ARRAY_BUFFER);

    m_program->use();

    m_program->setUniform(u_transform, transform);
    m_program->setUniform(u_time, m_timeCapability->time());
    m_program->setUniform(u_numcubes, m_numCubes);

    m_textures[0]->bindActive(GL_TEXTURE0);
    m_textures[1]->bindActive(GL_TEXTURE1);

    m_vao->drawElementsInstanced(GL_TRIANGLES, 18, GL_UNSIGNED_BYTE, nullptr, m_numCubes * m_numCubes);

    m_program->release();
    m_vao->unbind();

    globjects::Framebuffer::unbind(GL_FRAMEBUFFER);
}

bool CubeScape::animation() const
{
    return m_animation;
}

void CubeScape::setAnimation(const bool & enabled)
{
    m_animation = enabled;

    m_timeCapability->setEnabled(m_animation);
}

int CubeScape::numberOfCubes() const
{
    return m_numCubes;
}

void CubeScape::setNumberOfCubes(const int & number)
{
    m_numCubes = number;
}

void CubeScape::onTargetFramebufferChanged()
{
    globjects::Framebuffer * fbo = m_targetFramebufferCapability->framebuffer();
    if (!fbo)
    {
        fbo = globjects::Framebuffer::defaultFBO();
    }
    m_typedRenderTargetCapability->setRenderTarget(gloperate::RenderTargetType::Depth, fbo, gl::GLenum::GL_DEPTH_ATTACHMENT, gl::GLenum::GL_DEPTH_COMPONENT);
}

void CubeScape::randomize()
{
    setNumberOfCubes(rand() % 40 + 1);
}
<commit_msg>Adjust default camera for cubescape example<commit_after>
#include "CubeScape.h"

#include <array>
#include <iostream>

#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>

#include <glbinding/gl/enum.h>
#include <glbinding/gl/bitfield.h>

#include <globjects/globjects.h>
#include <globjects/logging.h>
#include <globjects/DebugMessage.h>
#include <globjects/VertexAttributeBinding.h>

#include <gloperate/resources/RawFile.h>

#include <gloperate/base/RenderTargetType.h>

#include <gloperate/painter/Camera.h>
#include <gloperate/painter/TargetFramebufferCapability.h>
#include <gloperate/painter/ViewportCapability.h>
#include <gloperate/painter/PerspectiveProjectionCapability.h>
#include <gloperate/painter/CameraCapability.h>
#include <gloperate/painter/TypedRenderTargetCapability.h>
#include <gloperate/painter/VirtualTimeCapability.h>

using namespace gl;
using namespace glm;
using namespace globjects;

CubeScape::CubeScape(gloperate::ResourceManager & resourceManager, const std::string & relDataPath)
: Painter("CubeScape", resourceManager, relDataPath)
, m_animation{true}
, m_numCubes{25}
, a_vertex{-1}
, u_transform{-1}
, u_time{-1}
, u_numcubes{-1}
{
    // Setup painter
    m_targetFramebufferCapability = addCapability(new gloperate::TargetFramebufferCapability());
    m_viewportCapability = addCapability(new gloperate::ViewportCapability());
    m_projectionCapability = addCapability(new gloperate::PerspectiveProjectionCapability(m_viewportCapability));
    m_typedRenderTargetCapability = addCapability(new gloperate::TypedRenderTargetCapability());
    m_cameraCapability = addCapability(new gloperate::CameraCapability(glm::vec3(0.0, 2.0, 1.5), glm::vec3(0.0, 0.0, 0.5), glm::vec3(0.0, 1.0, 0.0)));
    m_timeCapability = addCapability(new gloperate::VirtualTimeCapability());

    m_timeCapability->setLoopDuration(20.0f * pi<float>());

    m_targetFramebufferCapability->changed.connect([this](){ this->onTargetFramebufferChanged();});

    // Register properties
    addProperty<bool>("Animation", this, &CubeScape::animation, &CubeScape::setAnimation);

    auto * propNumCubes = addProperty<int>("NumCubes", this, &CubeScape::numberOfCubes, &CubeScape::setNumberOfCubes);
    propNumCubes->setOption("minimum", 0);

    // Register scripting functions
    addFunction("randomize", this, &CubeScape::randomize);
}

CubeScape::~CubeScape()
{
}

void CubeScape::setupProjection()
{
    m_projectionCapability->setZNear(0.3f);
    m_projectionCapability->setZFar(15.f);
    m_projectionCapability->setFovy(radians(50.f));
}

void CubeScape::onInitialize()
{
    // create program

    globjects::init();
    onTargetFramebufferChanged();

#ifdef __APPLE__
    Shader::clearGlobalReplacements();
    Shader::globalReplace("#version 140", "#version 150");

    debug() << "Using global OS X shader replacement '#version 140' -> '#version 150'" << std::endl;
#endif

    m_program = new globjects::Program;
    m_program->attach(
        globjects::Shader::fromFile(GL_VERTEX_SHADER,   m_relDataPath + "data/cubescape/cubescape.vert"),
        globjects::Shader::fromFile(GL_GEOMETRY_SHADER, m_relDataPath + "data/cubescape/cubescape.geom"),
        globjects::Shader::fromFile(GL_FRAGMENT_SHADER, m_relDataPath + "data/cubescape/cubescape.frag")
    );

    // create textures

    m_textures[0] = new globjects::Texture;
    m_textures[1] = new globjects::Texture;

    for (int i=0; i < 2; ++i)
    {
        m_textures[i]->setParameter(GL_TEXTURE_WRAP_S, GL_REPEAT);
        m_textures[i]->setParameter(GL_TEXTURE_WRAP_T, GL_REPEAT);

        m_textures[i]->setParameter(GL_TEXTURE_MIN_FILTER, GL_LINEAR);
        m_textures[i]->setParameter(GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    }

    {
        gloperate::RawFile terrain(m_relDataPath + "data/cubescape/terrain.512.512.r.ub.raw");
        if (!terrain.isValid())
            std::cout << "warning: loading texture from " << terrain.filePath() << " failed.";

        m_textures[0]->image2D(0, GL_RED_NV, 512, 512, 0, GL_RED, GL_UNSIGNED_BYTE, terrain.data());
    }

    {
        gloperate::RawFile patches(m_relDataPath + "data/cubescape/patches.64.16.rgb.ub.raw");
        if (!patches.isValid())
            std::cout << "warning: loading texture from " << patches.filePath() << " failed.";

        m_textures[1]->image2D(0, GL_RGB8, 64, 16, 0, GL_RGB, GL_UNSIGNED_BYTE, patches.data());
    }

    m_vao = new globjects::VertexArray;
    m_vao->bind();

    m_vertices = new globjects::Buffer;
    m_indices = new globjects::Buffer;

    const std::array<vec3, 8> vertices =
    {
        vec3(-1.f, -1.f, -1.f ), // 0
        vec3(-1.f, -1.f,  1.f ), // 1
        vec3(-1.f,  1.f, -1.f ), // 2
        vec3(-1.f,  1.f,  1.f ), // 3
        vec3( 1.f, -1.f, -1.f ), // 4
        vec3( 1.f, -1.f,  1.f ), // 5
        vec3( 1.f,  1.f, -1.f ), // 6
        vec3( 1.f,  1.f,  1.f )  // 7
    };

    m_vertices->setData(vertices, GL_STATIC_DRAW);

    const std::array<unsigned char, 18> indices =
        { 2, 3, 6, 0, 1, 2, 1, 5, 3, 5, 4, 7, 4, 0, 6, 5, 1, 4 };

    m_indices->setData(indices, GL_STATIC_DRAW);
    m_indices->bind(GL_ELEMENT_ARRAY_BUFFER);

    // setup uniforms

    a_vertex = m_program->getAttributeLocation("a_vertex");

    m_vao->binding(0)->setAttribute(a_vertex);
    m_vao->binding(0)->setBuffer(m_vertices, 0, sizeof(vec3));
    m_vao->binding(0)->setFormat(3, GL_FLOAT, GL_FALSE, 0);

    m_vao->enable(a_vertex);

    u_transform = m_program->getUniformLocation("modelViewProjection");
    u_time = m_program->getUniformLocation("time");
    u_numcubes = m_program->getUniformLocation("numcubes");

    GLint terrain = m_program->getUniformLocation("terrain");
    GLint patches = m_program->getUniformLocation("patches");

    // since only single program and single data is used, bind only once

    glClearColor(0.f, 0.f, 0.f, 1.0f);

    m_program->setUniform(terrain, 0);
    m_program->setUniform(patches, 1);

    setupProjection();
}

void CubeScape::onPaint()
{
    if (m_viewportCapability->hasChanged())
    {
        glViewport(m_viewportCapability->x(), m_viewportCapability->y(), m_viewportCapability->width(), m_viewportCapability->height());

        m_viewportCapability->setChanged(false);
    }

    globjects::Framebuffer * fbo = m_targetFramebufferCapability->framebuffer();

    if (!fbo)
    {
        fbo = globjects::Framebuffer::defaultFBO();
    }

    fbo->bind(GL_FRAMEBUFFER);

    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glEnable(GL_DEPTH_TEST);

    mat4 transform = m_projectionCapability->projection() * m_cameraCapability->view();

    m_vao->bind();

    m_indices->bind(GL_ELEMENT_ARRAY_BUFFER);

    m_program->use();

    m_program->setUniform(u_transform, transform);
    m_program->setUniform(u_time, m_timeCapability->time());
    m_program->setUniform(u_numcubes, m_numCubes);

    m_textures[0]->bindActive(GL_TEXTURE0);
    m_textures[1]->bindActive(GL_TEXTURE1);

    m_vao->drawElementsInstanced(GL_TRIANGLES, 18, GL_UNSIGNED_BYTE, nullptr, m_numCubes * m_numCubes);

    m_program->release();
    m_vao->unbind();

    globjects::Framebuffer::unbind(GL_FRAMEBUFFER);
}

bool CubeScape::animation() const
{
    return m_animation;
}

void CubeScape::setAnimation(const bool & enabled)
{
    m_animation = enabled;

    m_timeCapability->setEnabled(m_animation);
}

int CubeScape::numberOfCubes() const
{
    return m_numCubes;
}

void CubeScape::setNumberOfCubes(const int & number)
{
    m_numCubes = number;
}

void CubeScape::onTargetFramebufferChanged()
{
    globjects::Framebuffer * fbo = m_targetFramebufferCapability->framebuffer();
    if (!fbo)
    {
        fbo = globjects::Framebuffer::defaultFBO();
    }
    m_typedRenderTargetCapability->setRenderTarget(gloperate::RenderTargetType::Depth, fbo, gl::GLenum::GL_DEPTH_ATTACHMENT, gl::GLenum::GL_DEPTH_COMPONENT);
}

void CubeScape::randomize()
{
    setNumberOfCubes(rand() % 40 + 1);
}
<|endoftext|>


<commit_before>#include <spdlog/spdlog.h>
#include <Gateway.hh>
#include <Babble.hh>
#include <Authenticator.hh>

static const std::string welcomeMsg =
        "\n\n"
        "              . .    .. ............,.,...,.,..,...,..........  .                         \n"
        "                     ......... ......,...,,,,,.,,,,,,,,,,,,...,..........  .  .                    \n"
        "                  .. .... ..........,..,,,,,,,,,,,,***,,,,,,,,,,..........   .                     \n"
        "                   . ................,,,,,,,*****////////**,,,,,.,.......... . .                   \n"
        "               ..  ......,......,.,,,,*,*****//((&@@&((//****,,,,,,,............                   \n"
        "               ........,.......,,,,,,,*****/%@@@@#((((///******,*,,..,,............ .  .           \n"
        "                 . .........,,,,,,,,******/@@@@@@@&%(((/////******,,,,.,,.......,...               \n"
        "                . ........,.,,,,*********///((#&@@@@@@@@(///*****,,,,......... . .. .            \n"
        "          .  .............,,,,,,,,,****////(((#%@@@@@@@@@@@@///****,,*,,............ . .           \n"
        "         . . ..........,,,,,,,,,,,****///((#@@@@@@@@@@@(((////***,,,,,,..,......... .            \n"
        "            ..........,,,,,,,,,,,****//((#@@@@@@@@@@@###((((////******,,*,,,,......... .           \n"
        "       .   . .. ......,.,,,,,,,*****//(((#%@@@@@@@@@@@@#((((///*****,,*,,,.....,....  .          \n"
        "       . .. .. ......,.,,,,,,*****///((#@@@@@@@@@@@@@@@@@@@#(((////***,,,,,,,.,,....   . .         \n"
        "     .   . .. . ....,.,,,,,,******//(#@@@@@@@@@@@@@@@@@@@@@@@#((///****,,,,,,,,......... .         \n"
        "          ............,,,,,******//(#@@@@@@@@@@@@@@@@@@@@@@@@@%((//*****,,,,,...,....  .           \n"
        "         . .. .........,,,,*****//(#@@@@@@@@@@@@@@@@@@@@@@@@@@@%(//*****,,,,,,.......              \n"
        "      .  . ...........,,,,,,****/((@@@@@@@@@@@@@@@@@@@@@@@@@@@@@(//*****,,,,.,...... ..            \n"
        "        . . ...........,,,,,,***/(#@@@@@@@@@@@@@@@@@@@@@@@@@@@@@(//****,,,,,,.......               \n"
        "     . ..  ...........,,,,,,,***//(@@@@@@@@@@@@@@@@@@@@@@@@@@@@@(//*****,,,.,..... ..              \n"
        "          .. .........,.,,,,,***//(&@@@@@@@@@@@@@@@@@@@@@@@@@@@%(//*****,,,,,..........            \n"
        "             . ........,,,,,,****//(&@@@@@@@@@@@@@@@@@@@@@@@@@&(//****,,,,...........              \n"
        "              ...........,,,,,****//(@@@@@@@@@@@@@@@@@@@@@@@@%///****,,,,,,........                \n"
        "            .. ...........,,,,,****///#@@@@@@@@@@@@@@@@@@@@&(//*****,,,,,........                  \n"
        "              .. ..........,,,,,,****//((&@@@@@@@@@@@@@@@#(//*****,,,,.......... .                 \n"
        "            .  ............,,,,,,,,*****///(#&@@@@@@&%(////*****,,,,,,,........ .                  \n"
        "                . ........,.,,,,,,,,,*******//////////*******,,,,,,,,,,..........                  \n"
        "                      .......,,,,,,,,,,,,,,*************,,,,,,,,,,,.......... .  .                 \n\n"
        "oooooooooooo                             .oooooo.                  .                                                    \n"
        "`888'     `8                            d8P'  `Y8b               .o8                                                    \n"
        " 888         oooo    ooo  .oooo.o      888            .oooo.   .o888oo  .ooooo.  oooo oooo    ooo  .oooo.   oooo    ooo \n"
        " 888oooo8     `88.  .8'  d88(  \"8      888           `P  )88b    888   d88' `88b  `88. `88.  .8'  `P  )88b   `88.  .8'  \n"
        " 888    \"      `88..8'   `\"Y88b.       888     ooooo  .oP\"888    888   888ooo888   `88..]88..8'    .oP\"888    `88..8'   \n"
        " 888            `888'    o.  )88b      `88.    .88'  d8(  888    888 . 888    .o    `888'`888'    d8(  888     `888'    \n"
        "o888o            .8'     8\"\"888P'       `Y8bood8P'   `Y888\"\"8o   \"888\" `Y8bod8P'     `8'  `8'     `Y888\"\"8o     .8'     \n"
        "             .o..P'                                                                                .o..P'      \n"
        "             `Y8P'                                                                                `Y8P'       \n"
        "                                                                                \n\n\n";

void welcome(bool verbose) {
    spdlog::set_async_mode(1024, spdlog::async_overflow_policy::discard_log_msg);

    std::vector<spdlog::sink_ptr> sinks;

    if (verbose) {
        auto stdout_sink = spdlog::sinks::stdout_sink_mt::instance();
        auto color_sink = std::make_shared<spdlog::sinks::ansicolor_sink>(stdout_sink);
        sinks.push_back(color_sink);
    }
    auto sys_logger = std::make_shared<spdlog::logger>("c", begin(sinks), end(sinks));
#ifdef DEBUG_LEVEL
    sys_logger->set_level(spdlog::level::debug);
#else
    sys_logger->set_level(spdlog::level::debug);
#endif
    spdlog::register_logger(sys_logger);
    spdlog::set_pattern("[%x %H:%M:%S] [%t] [%l] %v");
    sys_logger->info("Logger set to level {}\n>> log formatting>> [time] [thread] [logLevel] message logged", spdlog::get("c")->level());
    spdlog::get("c")->info(welcomeMsg);
}

int main(int argc, const char * const *argv) {
    GOOGLE_PROTOBUF_VERIFY_VERSION;
    fys::gateway::Context ctx(argc, argv);
    welcome(ctx.isVerbose());
    ctx.logContext();
    fys::gateway::Gateway::start(ctx);
    google::protobuf::ShutdownProtobufLibrary();
    return 0;
}
<commit_msg>fix spdlog<commit_after>#include <spdlog/spdlog.h>
#include <Gateway.hh>
#include <memory>
#include <Babble.hh>
#include <Authenticator.hh>

static const std::string welcomeMsg =
        "\n\n"
        "              . .    .. ............,.,...,.,..,...,..........  .                         \n"
        "                     ......... ......,...,,,,,.,,,,,,,,,,,,...,..........  .  .                    \n"
        "                  .. .... ..........,..,,,,,,,,,,,,***,,,,,,,,,,..........   .                     \n"
        "                   . ................,,,,,,,*****////////**,,,,,.,.......... . .                   \n"
        "               ..  ......,......,.,,,,*,*****//((&@@&((//****,,,,,,,............                   \n"
        "               ........,.......,,,,,,,*****/%@@@@#((((///******,*,,..,,............ .  .           \n"
        "                 . .........,,,,,,,,******/@@@@@@@&%(((/////******,,,,.,,.......,...               \n"
        "                . ........,.,,,,*********///((#&@@@@@@@@(///*****,,,,......... . .. .            \n"
        "          .  .............,,,,,,,,,****////(((#%@@@@@@@@@@@@///****,,*,,............ . .           \n"
        "         . . ..........,,,,,,,,,,,****///((#@@@@@@@@@@@(((////***,,,,,,..,......... .            \n"
        "            ..........,,,,,,,,,,,****//((#@@@@@@@@@@@###((((////******,,*,,,,......... .           \n"
        "       .   . .. ......,.,,,,,,,*****//(((#%@@@@@@@@@@@@#((((///*****,,*,,,.....,....  .          \n"
        "       . .. .. ......,.,,,,,,*****///((#@@@@@@@@@@@@@@@@@@@#(((////***,,,,,,,.,,....   . .         \n"
        "     .   . .. . ....,.,,,,,,******//(#@@@@@@@@@@@@@@@@@@@@@@@#((///****,,,,,,,,......... .         \n"
        "          ............,,,,,******//(#@@@@@@@@@@@@@@@@@@@@@@@@@%((//*****,,,,,...,....  .           \n"
        "         . .. .........,,,,*****//(#@@@@@@@@@@@@@@@@@@@@@@@@@@@%(//*****,,,,,,.......              \n"
        "      .  . ...........,,,,,,****/((@@@@@@@@@@@@@@@@@@@@@@@@@@@@@(//*****,,,,.,...... ..            \n"
        "        . . ...........,,,,,,***/(#@@@@@@@@@@@@@@@@@@@@@@@@@@@@@(//****,,,,,,.......               \n"
        "     . ..  ...........,,,,,,,***//(@@@@@@@@@@@@@@@@@@@@@@@@@@@@@(//*****,,,.,..... ..              \n"
        "          .. .........,.,,,,,***//(&@@@@@@@@@@@@@@@@@@@@@@@@@@@%(//*****,,,,,..........            \n"
        "             . ........,,,,,,****//(&@@@@@@@@@@@@@@@@@@@@@@@@@&(//****,,,,...........              \n"
        "              ...........,,,,,****//(@@@@@@@@@@@@@@@@@@@@@@@@%///****,,,,,,........                \n"
        "            .. ...........,,,,,****///#@@@@@@@@@@@@@@@@@@@@&(//*****,,,,,........                  \n"
        "              .. ..........,,,,,,****//((&@@@@@@@@@@@@@@@#(//*****,,,,.......... .                 \n"
        "            .  ............,,,,,,,,*****///(#&@@@@@@&%(////*****,,,,,,,........ .                  \n"
        "                . ........,.,,,,,,,,,*******//////////*******,,,,,,,,,,..........                  \n"
        "                      .......,,,,,,,,,,,,,,*************,,,,,,,,,,,.......... .  .                 \n\n"
        "oooooooooooo                             .oooooo.                  .                                                    \n"
        "`888'     `8                            d8P'  `Y8b               .o8                                                    \n"
        " 888         oooo    ooo  .oooo.o      888            .oooo.   .o888oo  .ooooo.  oooo oooo    ooo  .oooo.   oooo    ooo \n"
        " 888oooo8     `88.  .8'  d88(  \"8      888           `P  )88b    888   d88' `88b  `88. `88.  .8'  `P  )88b   `88.  .8'  \n"
        " 888    \"      `88..8'   `\"Y88b.       888     ooooo  .oP\"888    888   888ooo888   `88..]88..8'    .oP\"888    `88..8'   \n"
        " 888            `888'    o.  )88b      `88.    .88'  d8(  888    888 . 888    .o    `888'`888'    d8(  888     `888'    \n"
        "o888o            .8'     8\"\"888P'       `Y8bood8P'   `Y888\"\"8o   \"888\" `Y8bod8P'     `8'  `8'     `Y888\"\"8o     .8'     \n"
        "             .o..P'                                                                                .o..P'      \n"
        "             `Y8P'                                                                                `Y8P'       \n"
        "                                                                                \n\n\n";

void welcome(bool verbose) {
    spdlog::set_async_mode(1024, spdlog::async_overflow_policy::discard_log_msg);

    std::vector<spdlog::sink_ptr> sinks;

    auto sys_logger = spdlog::stdout_color_mt("c");
#ifdef DEBUG_LEVEL
    sys_logger->set_level(spdlog::level::debug);
#else
    sys_logger->set_level(spdlog::level::debug);
#endif
//    spdlog::register_logger(sys_logger);
    spdlog::set_pattern("[%x %H:%M:%S] [%t] [%l] %v");
    sys_logger->info("Logger set to level {}\n>> log formatting>> [time] [thread] [logLevel] message logged", spdlog::get("c")->level());
    spdlog::get("c")->info(welcomeMsg);
}

int main(int argc, const char * const *argv) {
    GOOGLE_PROTOBUF_VERIFY_VERSION;
    fys::gateway::Context ctx(argc, argv);
    welcome(ctx.isVerbose());
    ctx.logContext();
    fys::gateway::Gateway::start(ctx);
    google::protobuf::ShutdownProtobufLibrary();
    return 0;
}
<|endoftext|>


<commit_before>/* Copyright 2021 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/compiler/tf2tensorrt/convert/weights.h"

#include <functional>
#include <numeric>

#include "absl/strings/str_cat.h"
#include "tensorflow/compiler/tf2tensorrt/convert/utils.h"

#if GOOGLE_CUDA && GOOGLE_TENSORRT

namespace tensorflow {
namespace tensorrt {

namespace convert {

TRT_ShapedWeights::TRT_ShapedWeights(nvinfer1::DataType type)
    : shape_(0, DimsAdapter::StorageType{}), type_(type), volume_(0) {}

StatusOr<TRT_ShapedWeights> TRT_ShapedWeights::CreateWithTensor(
    nvinfer1::DataType type, DimsAdapter dims, Tensor tensor) {
  TRT_ShapedWeights weights(type);
  weights.shape_ = dims;
  weights.tensor_ = std::forward<Tensor>(tensor);
  weights.volume_ = weights.shape_.Volume();
  if (weights.shape_.NumDims() == 0) {
    DCHECK(weights.shape_.IsEmpty() || weights.shape_.IsScalar());
  }
  return weights;
}

nvinfer1::Weights TRT_ShapedWeights::GetTrtWeights() const {
  return nvinfer1::Weights{type_, GetPointer<int8>(), volume_};
}

Status TRT_ShapedWeights::SetShape(DimsAdapter dims) {
  if (volume_ != dims.Volume()) {
    VLOG(2) << "Changing shape from " << shape_.DebugString() << ", to "
            << dims.DebugString();
    return errors::Internal("SetShape would change number of elements");
  }
  shape_ = std::move(dims);
  return OkStatus();
}

size_t TRT_ShapedWeights::size_bytes() const {
  size_t data_type_size = -1;
  switch (type_) {
    case nvinfer1::DataType::kFLOAT:
    case nvinfer1::DataType::kINT32:
      data_type_size = 4;
      break;
    case nvinfer1::DataType::kHALF:
      data_type_size = 2;
      break;
#if IS_TRT_VERSION_GE(8, 5, 0, 0)
    case nvinfer1::DataType::kUINT8:
#endif
    case nvinfer1::DataType::kINT8:
    case nvinfer1::DataType::kBOOL:
      data_type_size = 1;
      break;
  }
  return volume_ * data_type_size;
}

string TRT_ShapedWeights::DebugString() const {
  return absl::StrCat(
      "TRT_ShapedWeights(shape=", shape_.DebugString(),
      ", type=", tensorflow::tensorrt::DebugString(type_),
      ", values=", reinterpret_cast<uintptr_t>(GetPointer<int8>()), ")");
}

TRT_TensorOrWeights::TRT_TensorOrWeights(ITensorProxyPtr tensor)
    : tensor_proxy_ptr_(tensor),
      initialized_(true),
      arg_type_(TRT_ArgumentType::TENSOR) {}

TRT_TensorOrWeights::TRT_TensorOrWeights(ITensorProxyPtr tensor, int batch_size)
    : tensor_proxy_ptr_(tensor),
      batch_size_(batch_size),
      initialized_(true),
      arg_type_(TRT_ArgumentType::TENSOR) {}

TRT_TensorOrWeights::TRT_TensorOrWeights(nvinfer1::ITensor* tensor,
                                         int batch_size)
    : tensor_proxy_ptr_(tensor),
      batch_size_(batch_size),
      initialized_(true),
      arg_type_(TRT_ArgumentType::TENSOR) {}

TRT_TensorOrWeights::TRT_TensorOrWeights(nvinfer1::DataType trt_dtype,
                                         const nvinfer1::Dims& trt_dims,
                                         int batch_size)
    : tensor_proxy_ptr_(new SimpleITensor(trt_dtype, trt_dims)),
      batch_size_(batch_size),
      initialized_(true),
      arg_type_(TRT_ArgumentType::TENSOR) {}

TRT_TensorOrWeights::TRT_TensorOrWeights(const TRT_ShapedWeights& weights)
    : weights_(weights),
      initialized_(true),
      arg_type_(TRT_ArgumentType::WEIGHTS) {}

TRT_TensorOrWeights::TRT_TensorOrWeights(const ResourceHandle& resource)
    : resource_(resource),
      initialized_(true),
      arg_type_(TRT_ArgumentType::RESOURCE) {}

TRT_TensorOrWeights::TRT_TensorOrWeights(const TRT_TensorOrWeights& rhs)
    : tensor_proxy_ptr_(rhs.tensor_proxy_ptr_),
      batch_size_(rhs.batch_size_),
      resource_(rhs.resource_),
      weights_(rhs.weights_),
      initialized_(rhs.initialized_),
      arg_type_(rhs.arg_type_) {}

void TRT_TensorOrWeights::operator=(const TRT_TensorOrWeights& rhs) {
  tensor_proxy_ptr_ = rhs.tensor_proxy_ptr_;
  batch_size_ = rhs.batch_size_;
  weights_ = rhs.weights_;
  resource_ = rhs.resource_;
  initialized_ = rhs.initialized_;
  arg_type_ = rhs.arg_type_;
}

ITensorProxyPtr TRT_TensorOrWeights::tensor() const {
  DCHECK(is_tensor());
  return tensor_proxy_ptr_;
}

ResourceHandle TRT_TensorOrWeights::resource() const {
  DCHECK(is_resource());
  return resource_;
}

nvinfer1::Dims TRT_TensorOrWeights::GetTrtDims() const {
  switch (arg_type_) {
    case TRT_ArgumentType::TENSOR:
      return tensor()->getDimensions();
    case TRT_ArgumentType::WEIGHTS:
      return weights().Shape().AsTrtDims();
    case TRT_ArgumentType::RESOURCE:
      return {0, {}};  // Scalar.
  }
}

Status TRT_TensorOrWeights::GetTfType(DataType* tf_type) const {
  if (!initialized_) {
    return errors::Internal("The object is not initialized");
  }
  switch (arg_type_) {
    case TRT_ArgumentType::TENSOR: {
      nvinfer1::DataType trt_type = tensor()->getType();
      return TrtTypeToTfType(trt_type, tf_type);
    }
    case TRT_ArgumentType::WEIGHTS:
      *tf_type = weights().GetTensor().dtype();
      return OkStatus();
    case TRT_ArgumentType::RESOURCE:
      *tf_type = DataType::DT_RESOURCE;
      return OkStatus();
  }
}

string TRT_TensorOrWeights::DebugString() const {
  string output = "TRT_TensorOrWeights(type=";
  if (is_tensor()) {
    absl::StrAppend(&output,
                    "tensor=", tensorflow::tensorrt::DebugString(tensor()),
                    ", batch_size=", batch_size_);
  } else {
    absl::StrAppend(&output, "weights=", weights_.DebugString());
  }
  absl::StrAppend(&output, ")");
  return output;
}

StatusOr<TRT_ShapedWeights> TrtWeightStore::GetTempWeights(
    nvinfer1::DataType trt_dtype, const DimsAdapter& dims) {
  DataType tf_dtype;
  TF_RETURN_IF_ERROR(TrtTypeToTfType(trt_dtype, &tf_dtype));
  TensorShape shape;
  TF_RETURN_IF_ERROR(dims.TensorShape(&shape));
  // TODO(jie): check weights size_bytes. 0 means type error
  Tensor tensor(tf_dtype, shape);
  StatusOr<TRT_ShapedWeights> weights =
      TRT_ShapedWeights::CreateWithTensor(trt_dtype, dims, tensor);
  TRT_ENSURE_OK(weights);
  store_.emplace_back(std::move(tensor));
  return weights;
}

}  // namespace convert
}  // namespace tensorrt
}  // namespace tensorflow

#endif  // GOOGLE_CUDA && GOOGLE_TENSORRT
<commit_msg>Hotfix tftrt compile error<commit_after>/* Copyright 2021 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/compiler/tf2tensorrt/convert/weights.h"

#include <functional>
#include <numeric>

#include "absl/strings/str_cat.h"
#include "tensorflow/compiler/tf2tensorrt/convert/utils.h"

#if GOOGLE_CUDA && GOOGLE_TENSORRT

namespace tensorflow {
namespace tensorrt {

namespace convert {

TRT_ShapedWeights::TRT_ShapedWeights(nvinfer1::DataType type)
    : shape_(0, DimsAdapter::StorageType{}), type_(type), volume_(0) {}

StatusOr<TRT_ShapedWeights> TRT_ShapedWeights::CreateWithTensor(
    nvinfer1::DataType type, DimsAdapter dims, Tensor tensor) {
  TRT_ShapedWeights weights(type);
  weights.shape_ = dims;
  weights.tensor_ = std::forward<Tensor>(tensor);
  weights.volume_ = weights.shape_.Volume();
  if (weights.shape_.NumDims() == 0) {
    DCHECK(weights.shape_.IsEmpty() || weights.shape_.IsScalar());
  }
  return weights;
}

nvinfer1::Weights TRT_ShapedWeights::GetTrtWeights() const {
  return nvinfer1::Weights{type_, GetPointer<int8>(), volume_};
}

Status TRT_ShapedWeights::SetShape(DimsAdapter dims) {
  if (volume_ != dims.Volume()) {
    VLOG(2) << "Changing shape from " << shape_.DebugString() << ", to "
            << dims.DebugString();
    return errors::Internal("SetShape would change number of elements");
  }
  shape_ = std::move(dims);
  return OkStatus();
}

size_t TRT_ShapedWeights::size_bytes() const {
  size_t data_type_size = -1;
  switch (type_) {
    case nvinfer1::DataType::kFLOAT:
    case nvinfer1::DataType::kINT32:
      data_type_size = 4;
      break;
    case nvinfer1::DataType::kHALF:
      data_type_size = 2;
      break;
#if IS_TRT_VERSION_GE(8, 5, 0, 0)
    case nvinfer1::DataType::kUINT8:
#endif
    case nvinfer1::DataType::kINT8:
    case nvinfer1::DataType::kBOOL:
      data_type_size = 1;
      break;
    default: break;
  }
  return volume_ * data_type_size;
}

string TRT_ShapedWeights::DebugString() const {
  return absl::StrCat(
      "TRT_ShapedWeights(shape=", shape_.DebugString(),
      ", type=", tensorflow::tensorrt::DebugString(type_),
      ", values=", reinterpret_cast<uintptr_t>(GetPointer<int8>()), ")");
}

TRT_TensorOrWeights::TRT_TensorOrWeights(ITensorProxyPtr tensor)
    : tensor_proxy_ptr_(tensor),
      initialized_(true),
      arg_type_(TRT_ArgumentType::TENSOR) {}

TRT_TensorOrWeights::TRT_TensorOrWeights(ITensorProxyPtr tensor, int batch_size)
    : tensor_proxy_ptr_(tensor),
      batch_size_(batch_size),
      initialized_(true),
      arg_type_(TRT_ArgumentType::TENSOR) {}

TRT_TensorOrWeights::TRT_TensorOrWeights(nvinfer1::ITensor* tensor,
                                         int batch_size)
    : tensor_proxy_ptr_(tensor),
      batch_size_(batch_size),
      initialized_(true),
      arg_type_(TRT_ArgumentType::TENSOR) {}

TRT_TensorOrWeights::TRT_TensorOrWeights(nvinfer1::DataType trt_dtype,
                                         const nvinfer1::Dims& trt_dims,
                                         int batch_size)
    : tensor_proxy_ptr_(new SimpleITensor(trt_dtype, trt_dims)),
      batch_size_(batch_size),
      initialized_(true),
      arg_type_(TRT_ArgumentType::TENSOR) {}

TRT_TensorOrWeights::TRT_TensorOrWeights(const TRT_ShapedWeights& weights)
    : weights_(weights),
      initialized_(true),
      arg_type_(TRT_ArgumentType::WEIGHTS) {}

TRT_TensorOrWeights::TRT_TensorOrWeights(const ResourceHandle& resource)
    : resource_(resource),
      initialized_(true),
      arg_type_(TRT_ArgumentType::RESOURCE) {}

TRT_TensorOrWeights::TRT_TensorOrWeights(const TRT_TensorOrWeights& rhs)
    : tensor_proxy_ptr_(rhs.tensor_proxy_ptr_),
      batch_size_(rhs.batch_size_),
      resource_(rhs.resource_),
      weights_(rhs.weights_),
      initialized_(rhs.initialized_),
      arg_type_(rhs.arg_type_) {}

void TRT_TensorOrWeights::operator=(const TRT_TensorOrWeights& rhs) {
  tensor_proxy_ptr_ = rhs.tensor_proxy_ptr_;
  batch_size_ = rhs.batch_size_;
  weights_ = rhs.weights_;
  resource_ = rhs.resource_;
  initialized_ = rhs.initialized_;
  arg_type_ = rhs.arg_type_;
}

ITensorProxyPtr TRT_TensorOrWeights::tensor() const {
  DCHECK(is_tensor());
  return tensor_proxy_ptr_;
}

ResourceHandle TRT_TensorOrWeights::resource() const {
  DCHECK(is_resource());
  return resource_;
}

nvinfer1::Dims TRT_TensorOrWeights::GetTrtDims() const {
  switch (arg_type_) {
    case TRT_ArgumentType::TENSOR:
      return tensor()->getDimensions();
    case TRT_ArgumentType::WEIGHTS:
      return weights().Shape().AsTrtDims();
    case TRT_ArgumentType::RESOURCE:
      return {0, {}};  // Scalar.
  }
}

Status TRT_TensorOrWeights::GetTfType(DataType* tf_type) const {
  if (!initialized_) {
    return errors::Internal("The object is not initialized");
  }
  switch (arg_type_) {
    case TRT_ArgumentType::TENSOR: {
      nvinfer1::DataType trt_type = tensor()->getType();
      return TrtTypeToTfType(trt_type, tf_type);
    }
    case TRT_ArgumentType::WEIGHTS:
      *tf_type = weights().GetTensor().dtype();
      return OkStatus();
    case TRT_ArgumentType::RESOURCE:
      *tf_type = DataType::DT_RESOURCE;
      return OkStatus();
  }
}

string TRT_TensorOrWeights::DebugString() const {
  string output = "TRT_TensorOrWeights(type=";
  if (is_tensor()) {
    absl::StrAppend(&output,
                    "tensor=", tensorflow::tensorrt::DebugString(tensor()),
                    ", batch_size=", batch_size_);
  } else {
    absl::StrAppend(&output, "weights=", weights_.DebugString());
  }
  absl::StrAppend(&output, ")");
  return output;
}

StatusOr<TRT_ShapedWeights> TrtWeightStore::GetTempWeights(
    nvinfer1::DataType trt_dtype, const DimsAdapter& dims) {
  DataType tf_dtype;
  TF_RETURN_IF_ERROR(TrtTypeToTfType(trt_dtype, &tf_dtype));
  TensorShape shape;
  TF_RETURN_IF_ERROR(dims.TensorShape(&shape));
  // TODO(jie): check weights size_bytes. 0 means type error
  Tensor tensor(tf_dtype, shape);
  StatusOr<TRT_ShapedWeights> weights =
      TRT_ShapedWeights::CreateWithTensor(trt_dtype, dims, tensor);
  TRT_ENSURE_OK(weights);
  store_.emplace_back(std::move(tensor));
  return weights;
}

}  // namespace convert
}  // namespace tensorrt
}  // namespace tensorflow

#endif  // GOOGLE_CUDA && GOOGLE_TENSORRT
<|endoftext|>


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

#include "syzygy/kasko/reporter.h"

#include <Windows.h>  // NOLINT
#include <Dbgeng.h>
#include <Rpc.h>

#include <set>
#include <string>

#include "base/bind.h"
#include "base/callback.h"
#include "base/file_util.h"
#include "base/location.h"
#include "base/files/file_enumerator.h"
#include "base/files/file_path.h"
#include "base/files/file_path_watcher.h"
#include "base/files/scoped_temp_dir.h"
#include "base/memory/scoped_ptr.h"
#include "base/message_loop/message_loop.h"
#include "base/strings/string16.h"
#include "base/strings/string_number_conversions.h"
#include "base/time/time.h"
#include "gtest/gtest.h"
#include "syzygy/common/rpc/helpers.h"
#include "syzygy/kasko/crash_keys_serialization.h"
#include "syzygy/kasko/kasko_rpc.h"
#include "syzygy/kasko/testing/minidump_unittest_helpers.h"
#include "syzygy/kasko/testing/test_server.h"

// The test server will respond to POSTs to /crash by writing all parameters to
// a report directory. Each file in the directory has the name of a parameter
// and the parameter value as its contents.
//
// This test instantiates a reporter process, points it at a test server, and
// then monitors the server's "incoming" director for new files named
// Reporter::kMinidumpUploadFilePart.
namespace kasko {

namespace {

// Invokes the diagnostic report RPC service at |endpoint|, requesting a dump of
// the current process, and including |protobuf|.
void DoInvokeService(const base::string16& endpoint,
                     const std::string& protobuf) {
  common::rpc::ScopedRpcBinding rpc_binding;
  ASSERT_TRUE(rpc_binding.Open(L"ncalrpc", endpoint));

  common::rpc::RpcStatus status = common::rpc::InvokeRpc(
      KaskoClient_SendDiagnosticReport, rpc_binding.Get(), NULL, 0,
      protobuf.length(),
      reinterpret_cast<const signed char*>(protobuf.c_str()));
  ASSERT_FALSE(status.exception_occurred);
  ASSERT_TRUE(status.succeeded());
}

// Verifies that the uploaded minidump is plausibly a dump of this test process.
void ValidateMinidump(IDebugClient4* debug_client,
                      IDebugControl* debug_control,
                      IDebugSymbols* debug_symbols) {
  ASSERT_HRESULT_SUCCEEDED(
      debug_symbols->GetModuleByModuleName("kasko_unittests", 0, NULL, NULL));
}

// Observes changes to the test server's 'incoming' directory. Notifications do
// not specify the individual file changed; for each notification we must scan
// for new minidump files. Once one is found, we verify that it is plausibly a
// crash report from this process and then quit the current message loop.
void WatchForUpload(const base::FilePath& path, bool error) {
  if (error) {
    ADD_FAILURE() << "Failure in path watching.";
    base::MessageLoop::current()->Quit();
    return;
  }

  base::FileEnumerator enumerator(path, true, base::FileEnumerator::FILES);
  for (base::FilePath candidate = enumerator.Next(); !candidate.empty();
       candidate = enumerator.Next()) {
    if (candidate.BaseName() !=
        base::FilePath(Reporter::kMinidumpUploadFilePart)) {
      continue;
    }

    EXPECT_HRESULT_SUCCEEDED(
        testing::VisitMinidump(candidate, base::Bind(&ValidateMinidump)));
    base::MessageLoop::current()->Quit();
  }
}

// Observes changes to the permanent failure destination. Once a complete report
// is found, validates that the report is plausibly a crash report from this
// process and then quits the current message loop.
void WatchForPermanentFailure(const base::FilePath& path, bool error) {
  if (error) {
    ADD_FAILURE() << "Failure in path watching.";
    base::MessageLoop::current()->Quit();
    return;
  }

  base::FileEnumerator enumerator(path, true, base::FileEnumerator::FILES);
  for (base::FilePath candidate = enumerator.Next(); !candidate.empty();
       candidate = enumerator.Next()) {
    LOG(ERROR) << "Candidate: " << candidate.value();
    if (candidate.FinalExtension() !=
        Reporter::kPermanentFailureMinidumpExtension) {
      LOG(ERROR) << "0";
      continue;
    }
    base::FilePath crash_keys_file = candidate.ReplaceExtension(
        Reporter::kPermanentFailureCrashKeysExtension);
    if (!base::PathExists(crash_keys_file)) {
      LOG(ERROR) << "No crash keys at " << crash_keys_file.value();
      continue;
    }
    EXPECT_HRESULT_SUCCEEDED(
        testing::VisitMinidump(candidate, base::Bind(&ValidateMinidump)));
    std::map<base::string16, base::string16> crash_keys;
    EXPECT_TRUE(ReadCrashKeysFromFile(crash_keys_file, &crash_keys));

    base::MessageLoop::current()->Quit();
  }
}

// Starts watching |path| using |watcher|. Must be invoked inside the IO message
// loop. |callback| will be invoked when a change to |path| or its contents is
// detected.
void StartWatch(base::FilePathWatcher* watcher,
                const base::FilePath& path,
                const base::FilePathWatcher::Callback& callback) {
  if (!watcher->Watch(path, true, callback)) {
    ADD_FAILURE() << "Failed to initiate file path watch.";
    base::MessageLoop::current()->Quit();
    return;
  }
}

}  // namespace

TEST(ReporterTest, BasicTest) {
  testing::TestServer server;
  ASSERT_TRUE(server.Start());

  base::ScopedTempDir data_directory;
  base::ScopedTempDir permanent_failure_directory;
  ASSERT_TRUE(data_directory.CreateUniqueTempDir());
  ASSERT_TRUE(permanent_failure_directory.CreateUniqueTempDir());

  scoped_ptr<Reporter> instance(Reporter::Create(
      L"test_endpoint",
      L"http://127.0.0.1:" + base::UintToString16(server.port()) + L"/crash",
      data_directory.path(), permanent_failure_directory.path(),
      base::TimeDelta::FromMilliseconds(1),
      base::TimeDelta::FromMilliseconds(1)));

  ASSERT_TRUE(instance);

  base::FilePathWatcher watcher;
  base::MessageLoop watcher_loop(base::MessageLoop::TYPE_IO);
  watcher_loop.PostTask(
      FROM_HERE, base::Bind(&DoInvokeService, base::string16(L"test_endpoint"),
                            std::string("protobuf")));
  watcher_loop.PostTask(
      FROM_HERE,
      base::Bind(&StartWatch, base::Unretained(&watcher),
                 server.incoming_directory(), base::Bind(&WatchForUpload)));
  watcher_loop.Run();

  Reporter::Shutdown(instance.Pass());
}

TEST(ReporterTest, PermanentFailureTest) {
  testing::TestServer server;
  ASSERT_TRUE(server.Start());

  base::ScopedTempDir data_directory;
  base::ScopedTempDir permanent_failure_directory;
  ASSERT_TRUE(data_directory.CreateUniqueTempDir());
  ASSERT_TRUE(permanent_failure_directory.CreateUniqueTempDir());

  scoped_ptr<Reporter> instance(Reporter::Create(
      L"test_endpoint",
      L"http://127.0.0.1:" + base::UintToString16(server.port()) +
          L"/crash_failure",
      data_directory.path(), permanent_failure_directory.path(),
      base::TimeDelta::FromMilliseconds(1),
      base::TimeDelta::FromMilliseconds(1)));

  ASSERT_TRUE(instance);

  base::FilePathWatcher watcher;
  base::MessageLoop watcher_loop(base::MessageLoop::TYPE_IO);
  watcher_loop.PostTask(
      FROM_HERE, base::Bind(&DoInvokeService, base::string16(L"test_endpoint"),
                            std::string("protobuf")));
  watcher_loop.PostTask(FROM_HERE,
                        base::Bind(&StartWatch, base::Unretained(&watcher),
                                   permanent_failure_directory.path(),
                                   base::Bind(&WatchForPermanentFailure)));
  watcher_loop.Run();

  Reporter::Shutdown(instance.Pass());
}

}  // namespace kasko
<commit_msg>Disable two flaky tests.<commit_after>// Copyright 2014 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "syzygy/kasko/reporter.h"

#include <Windows.h>  // NOLINT
#include <Dbgeng.h>
#include <Rpc.h>

#include <set>
#include <string>

#include "base/bind.h"
#include "base/callback.h"
#include "base/file_util.h"
#include "base/location.h"
#include "base/files/file_enumerator.h"
#include "base/files/file_path.h"
#include "base/files/file_path_watcher.h"
#include "base/files/scoped_temp_dir.h"
#include "base/memory/scoped_ptr.h"
#include "base/message_loop/message_loop.h"
#include "base/strings/string16.h"
#include "base/strings/string_number_conversions.h"
#include "base/time/time.h"
#include "gtest/gtest.h"
#include "syzygy/common/rpc/helpers.h"
#include "syzygy/kasko/crash_keys_serialization.h"
#include "syzygy/kasko/kasko_rpc.h"
#include "syzygy/kasko/testing/minidump_unittest_helpers.h"
#include "syzygy/kasko/testing/test_server.h"

// The test server will respond to POSTs to /crash by writing all parameters to
// a report directory. Each file in the directory has the name of a parameter
// and the parameter value as its contents.
//
// This test instantiates a reporter process, points it at a test server, and
// then monitors the server's "incoming" director for new files named
// Reporter::kMinidumpUploadFilePart.
namespace kasko {

namespace {

// Invokes the diagnostic report RPC service at |endpoint|, requesting a dump of
// the current process, and including |protobuf|.
void DoInvokeService(const base::string16& endpoint,
                     const std::string& protobuf) {
  common::rpc::ScopedRpcBinding rpc_binding;
  ASSERT_TRUE(rpc_binding.Open(L"ncalrpc", endpoint));

  common::rpc::RpcStatus status = common::rpc::InvokeRpc(
      KaskoClient_SendDiagnosticReport, rpc_binding.Get(), NULL, 0,
      protobuf.length(),
      reinterpret_cast<const signed char*>(protobuf.c_str()));
  ASSERT_FALSE(status.exception_occurred);
  ASSERT_TRUE(status.succeeded());
}

// Verifies that the uploaded minidump is plausibly a dump of this test process.
void ValidateMinidump(IDebugClient4* debug_client,
                      IDebugControl* debug_control,
                      IDebugSymbols* debug_symbols) {
  ASSERT_HRESULT_SUCCEEDED(
      debug_symbols->GetModuleByModuleName("kasko_unittests", 0, NULL, NULL));
}

// Observes changes to the test server's 'incoming' directory. Notifications do
// not specify the individual file changed; for each notification we must scan
// for new minidump files. Once one is found, we verify that it is plausibly a
// crash report from this process and then quit the current message loop.
void WatchForUpload(const base::FilePath& path, bool error) {
  if (error) {
    ADD_FAILURE() << "Failure in path watching.";
    base::MessageLoop::current()->Quit();
    return;
  }

  base::FileEnumerator enumerator(path, true, base::FileEnumerator::FILES);
  for (base::FilePath candidate = enumerator.Next(); !candidate.empty();
       candidate = enumerator.Next()) {
    if (candidate.BaseName() !=
        base::FilePath(Reporter::kMinidumpUploadFilePart)) {
      continue;
    }

    EXPECT_HRESULT_SUCCEEDED(
        testing::VisitMinidump(candidate, base::Bind(&ValidateMinidump)));
    base::MessageLoop::current()->Quit();
  }
}

// Observes changes to the permanent failure destination. Once a complete report
// is found, validates that the report is plausibly a crash report from this
// process and then quits the current message loop.
void WatchForPermanentFailure(const base::FilePath& path, bool error) {
  if (error) {
    ADD_FAILURE() << "Failure in path watching.";
    base::MessageLoop::current()->Quit();
    return;
  }

  base::FileEnumerator enumerator(path, true, base::FileEnumerator::FILES);
  for (base::FilePath candidate = enumerator.Next(); !candidate.empty();
       candidate = enumerator.Next()) {
    LOG(ERROR) << "Candidate: " << candidate.value();
    if (candidate.FinalExtension() !=
        Reporter::kPermanentFailureMinidumpExtension) {
      LOG(ERROR) << "0";
      continue;
    }
    base::FilePath crash_keys_file = candidate.ReplaceExtension(
        Reporter::kPermanentFailureCrashKeysExtension);
    if (!base::PathExists(crash_keys_file)) {
      LOG(ERROR) << "No crash keys at " << crash_keys_file.value();
      continue;
    }
    EXPECT_HRESULT_SUCCEEDED(
        testing::VisitMinidump(candidate, base::Bind(&ValidateMinidump)));
    std::map<base::string16, base::string16> crash_keys;
    EXPECT_TRUE(ReadCrashKeysFromFile(crash_keys_file, &crash_keys));

    base::MessageLoop::current()->Quit();
  }
}

// Starts watching |path| using |watcher|. Must be invoked inside the IO message
// loop. |callback| will be invoked when a change to |path| or its contents is
// detected.
void StartWatch(base::FilePathWatcher* watcher,
                const base::FilePath& path,
                const base::FilePathWatcher::Callback& callback) {
  if (!watcher->Watch(path, true, callback)) {
    ADD_FAILURE() << "Failed to initiate file path watch.";
    base::MessageLoop::current()->Quit();
    return;
  }
}

}  // namespace

TEST(ReporterTest, DISABLED_BasicTest) {
  testing::TestServer server;
  ASSERT_TRUE(server.Start());

  base::ScopedTempDir data_directory;
  base::ScopedTempDir permanent_failure_directory;
  ASSERT_TRUE(data_directory.CreateUniqueTempDir());
  ASSERT_TRUE(permanent_failure_directory.CreateUniqueTempDir());

  scoped_ptr<Reporter> instance(Reporter::Create(
      L"test_endpoint",
      L"http://127.0.0.1:" + base::UintToString16(server.port()) + L"/crash",
      data_directory.path(), permanent_failure_directory.path(),
      base::TimeDelta::FromMilliseconds(1),
      base::TimeDelta::FromMilliseconds(1)));

  ASSERT_TRUE(instance);

  base::FilePathWatcher watcher;
  base::MessageLoop watcher_loop(base::MessageLoop::TYPE_IO);
  watcher_loop.PostTask(
      FROM_HERE, base::Bind(&DoInvokeService, base::string16(L"test_endpoint"),
                            std::string("protobuf")));
  watcher_loop.PostTask(
      FROM_HERE,
      base::Bind(&StartWatch, base::Unretained(&watcher),
                 server.incoming_directory(), base::Bind(&WatchForUpload)));
  watcher_loop.Run();

  Reporter::Shutdown(instance.Pass());
}

TEST(ReporterTest, DISABLED_PermanentFailureTest) {
  testing::TestServer server;
  ASSERT_TRUE(server.Start());

  base::ScopedTempDir data_directory;
  base::ScopedTempDir permanent_failure_directory;
  ASSERT_TRUE(data_directory.CreateUniqueTempDir());
  ASSERT_TRUE(permanent_failure_directory.CreateUniqueTempDir());

  scoped_ptr<Reporter> instance(Reporter::Create(
      L"test_endpoint",
      L"http://127.0.0.1:" + base::UintToString16(server.port()) +
          L"/crash_failure",
      data_directory.path(), permanent_failure_directory.path(),
      base::TimeDelta::FromMilliseconds(1),
      base::TimeDelta::FromMilliseconds(1)));

  ASSERT_TRUE(instance);

  base::FilePathWatcher watcher;
  base::MessageLoop watcher_loop(base::MessageLoop::TYPE_IO);
  watcher_loop.PostTask(
      FROM_HERE, base::Bind(&DoInvokeService, base::string16(L"test_endpoint"),
                            std::string("protobuf")));
  watcher_loop.PostTask(FROM_HERE,
                        base::Bind(&StartWatch, base::Unretained(&watcher),
                                   permanent_failure_directory.path(),
                                   base::Bind(&WatchForPermanentFailure)));
  watcher_loop.Run();

  Reporter::Shutdown(instance.Pass());
}

}  // namespace kasko
<|endoftext|>


<commit_before>/*! @file crp.cc
 *  @brief Chroma DCT-Reduced Log Pitch calculation.
 *  @author Markovtsev Vadim <v.markovtsev@samsung.com>
 *  @version 1.0
 *
 *  @section Notes
 *  This code partially conforms to Google C++ Style Guide.
 *
 *  @section Copyright
 *  Copyright 2013 Samsung R&D Institute Russia
 */

#include <gtest/gtest.h>
#include "src/transform_tree.h"
#include "src/transform_registry.h"
#include "src/formats/array_format.h"
#include "tests/speech_sample.inc"

using sound_feature_extraction::TransformTree;
using sound_feature_extraction::BuffersBase;

TEST(Features, CRP) {
  TransformTree tt( { 48000, 22050 } );
  tt.set_validate_after_each_transform(true);
  tt.AddFeature("CRP", { { "Window", "length=4096,step=2048" },{ "RDFT", "" },
      { "SpectralEnergy", "" }, { "FilterBank", "type=midi,number=100,"
          "frequency_min=7.946364,frequency_max=8137.0754,squared=true" },
      { "Log", "add1=true,scale=1000" }, { "DCT", "" },
      { "Selector", "select=70,from=right" }, { "IDCT", "" },
      { "Reorder", "algorithm=chroma" },
      { "Stats", "types=average,interval=10" }
  });
  int16_t* buffers = new int16_t[48000];
  memcpy(buffers, data, sizeof(data));
  tt.PrepareForExecution();
  auto res = tt.Execute(buffers);
  delete[] buffers;
  ASSERT_EQ(1U, res.size());
  res["CRP"]->Validate();
  tt.Dump("/tmp/crp.dot");
  auto report = tt.ExecutionTimeReport();
  for (auto r : report) {
    printf("%s:\t%f\n", r.first.c_str(), r.second);
  }
}

#include "tests/google/src/gtest_main.cc"
<commit_msg>Fixed bug in CRP test<commit_after>/*! @file crp.cc
 *  @brief Chroma DCT-Reduced Log Pitch calculation.
 *  @author Markovtsev Vadim <v.markovtsev@samsung.com>
 *  @version 1.0
 *
 *  @section Notes
 *  This code partially conforms to Google C++ Style Guide.
 *
 *  @section Copyright
 *  Copyright 2013 Samsung R&D Institute Russia
 */

#include <gtest/gtest.h>
#include "src/transform_tree.h"
#include "src/transform_registry.h"
#include "src/formats/array_format.h"
#include "tests/speech_sample.inc"

using sound_feature_extraction::TransformTree;
using sound_feature_extraction::BuffersBase;

TEST(Features, CRP) {
  TransformTree tt( { 48000, 22050 } );
  tt.set_validate_after_each_transform(true);
  tt.AddFeature("CRP", { { "Window", "length=4096,step=2048" },{ "RDFT", "" },
      { "SpectralEnergy", "" }, { "FilterBank", "type=midi,number=108,"
          "frequency_min=7.946364,frequency_max=8137.0754,squared=true" },
      { "Log", "add1=true,scale=1000" }, { "DCT", "" },
      { "Selector", "select=70,from=right" }, { "IDCT", "" },
      { "Reorder", "algorithm=chroma" },
      { "Stats", "types=average,interval=10" }
  });
  int16_t* buffers = new int16_t[48000];
  memcpy(buffers, data, sizeof(data));
  tt.PrepareForExecution();
  auto res = tt.Execute(buffers);
  delete[] buffers;
  ASSERT_EQ(1U, res.size());
  res["CRP"]->Validate();
  tt.Dump("/tmp/crp.dot");
  auto report = tt.ExecutionTimeReport();
  for (auto r : report) {
    printf("%s:\t%f\n", r.first.c_str(), r.second);
  }
}

#include "tests/google/src/gtest_main.cc"
<|endoftext|>


<commit_before>/**
 * \file
 * \brief StaticThread class header
 *
 * \author Copyright (C) 2014 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
 *
 * \par License
 * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
 * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * \date 2014-11-11
 */

#ifndef INCLUDE_DISTORTOS_STATICTHREAD_HPP_
#define INCLUDE_DISTORTOS_STATICTHREAD_HPP_

#include "distortos/Thread.hpp"

namespace distortos
{

/**
 * \brief StaticThread class is a templated interface for thread that has automatic storage of stack.
 *
 * \param StackSize is the size of stack, bytes
 * \param Function is the function that will be executed in separate thread
 * \param Args are the arguments for Function
 */

template<size_t StackSize, typename Function, typename... Args>
class StaticThread : private Thread<Function, Args...>
{
public:

	/// base of StaticThread
	using Base = Thread<Function, Args...>;

	/**
	 * \brief StaticThread's constructor
	 *
	 * \param [in] priority is the thread's priority, 0 - lowest, UINT8_MAX - highest
	 * \param [in] function is a function that will be executed in separate thread
	 * \param [in] args are arguments for function
	 */

	StaticThread(const uint8_t priority, Function&& function, Args&&... args) :
			Base{&stack_, sizeof(stack_), priority, std::forward<Function>(function), std::forward<Args>(args)...}
	{

	}

	using Base::getEffectivePriority;

	using Base::getPriority;

	using Base::join;

	using Base::setPriority;

	using Base::start;

private:

	/// stack buffer
	typename std::aligned_storage<StackSize>::type stack_;
};

/**
 * \brief Helper factory function to make StaticThread object with partially deduced template arguments
 *
 * \param StackSize is the size of stack, bytes
 * \param Function is the function that will be executed
 * \param Args are the arguments for Function
 *
 * \param [in] priority is the thread's priority, 0 - lowest, UINT8_MAX - highest
 * \param [in] function is a function that will be executed in separate thread
 * \param [in] args are arguments for function
 *
 * \return StaticThread object with partially deduced template arguments
 */

template<size_t StackSize, typename Function, typename... Args>
StaticThread<StackSize, Function, Args...> makeStaticThread(const uint8_t priority, Function&& function, Args&&... args)
{
	return {priority, std::forward<Function>(function), std::forward<Args>(args)...};
}

}	// namespace distortos

#endif	// INCLUDE_DISTORTOS_STATICTHREAD_HPP_
<commit_msg>StaticThread: expose ThreadControlBlock::getSchedulingPolicy() and ThreadControlBlock::setSchedulingPolicy()<commit_after>/**
 * \file
 * \brief StaticThread class header
 *
 * \author Copyright (C) 2014 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
 *
 * \par License
 * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
 * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * \date 2014-11-16
 */

#ifndef INCLUDE_DISTORTOS_STATICTHREAD_HPP_
#define INCLUDE_DISTORTOS_STATICTHREAD_HPP_

#include "distortos/Thread.hpp"

namespace distortos
{

/**
 * \brief StaticThread class is a templated interface for thread that has automatic storage of stack.
 *
 * \param StackSize is the size of stack, bytes
 * \param Function is the function that will be executed in separate thread
 * \param Args are the arguments for Function
 */

template<size_t StackSize, typename Function, typename... Args>
class StaticThread : private Thread<Function, Args...>
{
public:

	/// base of StaticThread
	using Base = Thread<Function, Args...>;

	/**
	 * \brief StaticThread's constructor
	 *
	 * \param [in] priority is the thread's priority, 0 - lowest, UINT8_MAX - highest
	 * \param [in] function is a function that will be executed in separate thread
	 * \param [in] args are arguments for function
	 */

	StaticThread(const uint8_t priority, Function&& function, Args&&... args) :
			Base{&stack_, sizeof(stack_), priority, std::forward<Function>(function), std::forward<Args>(args)...}
	{

	}

	using Base::getEffectivePriority;

	using Base::getPriority;

	using Base::getSchedulingPolicy;

	using Base::join;

	using Base::setPriority;

	using Base::setSchedulingPolicy;

	using Base::start;

private:

	/// stack buffer
	typename std::aligned_storage<StackSize>::type stack_;
};

/**
 * \brief Helper factory function to make StaticThread object with partially deduced template arguments
 *
 * \param StackSize is the size of stack, bytes
 * \param Function is the function that will be executed
 * \param Args are the arguments for Function
 *
 * \param [in] priority is the thread's priority, 0 - lowest, UINT8_MAX - highest
 * \param [in] function is a function that will be executed in separate thread
 * \param [in] args are arguments for function
 *
 * \return StaticThread object with partially deduced template arguments
 */

template<size_t StackSize, typename Function, typename... Args>
StaticThread<StackSize, Function, Args...> makeStaticThread(const uint8_t priority, Function&& function, Args&&... args)
{
	return {priority, std::forward<Function>(function), std::forward<Args>(args)...};
}

}	// namespace distortos

#endif	// INCLUDE_DISTORTOS_STATICTHREAD_HPP_
<|endoftext|>


<commit_before>/*********************************************************************
 * Software License Agreement (BSD License)
 *
 *  Copyright (c) 2012, Willow Garage, Inc.
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above
 *     copyright notice, this list of conditions and the following
 *     disclaimer in the documentation and/or other materials provided
 *     with the distribution.
 *   * Neither the name of Willow Garage nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *  POSSIBILITY OF SUCH DAMAGE.
 *********************************************************************/

/* Author: Dan Greenwalducan */

#include <moveit/warehouse/planning_scene_storage.h>
#include <moveit/warehouse/constraints_storage.h>
#include <moveit/warehouse/state_storage.h>
#include <moveit/planning_scene_monitor/planning_scene_monitor.h>
#include <boost/algorithm/string/join.hpp>
#include <boost/program_options/cmdline.hpp>
#include <boost/program_options/options_description.hpp>
#include <boost/program_options/parsers.hpp>
#include <boost/program_options/variables_map.hpp>
#include <ros/ros.h>
#include <moveit_msgs/SaveRobotStateToWarehouse.h>
#include <moveit_msgs/ListRobotStatesInWarehouse.h>
#include <moveit_msgs/GetRobotStateFromWarehouse.h>
#include <moveit_msgs/CheckIfRobotStateExistsInWarehouse.h>

static const std::string ROBOT_DESCRIPTION="robot_description";

bool store_state(moveit_msgs::SaveRobotStateToWarehouse::Request&  request,
                 moveit_msgs::SaveRobotStateToWarehouse::Response& response,
                 moveit_warehouse::RobotStateStorage* rs)
{
  const moveit_msgs::RobotState& state = request.state;
  if ("" == request.name)
  {
    ROS_ERROR("You must specify a name to store a state");
    return response.success = false;
  }
  rs->addRobotState(request.state, request.name, request.robot);
  return response.success = true;
}

bool list_states(moveit_msgs::ListRobotStatesInWarehouse::Request&  request,
                  moveit_msgs::ListRobotStatesInWarehouse::Response& response,
                  moveit_warehouse::RobotStateStorage* rs)
{
  if ("" == request.regex)
  {
    rs->getKnownRobotStates(response.states, request.robot);
  }
  else
  {
    rs->getKnownRobotStates(request.regex, response.states, request.robot);
  }
  return true;
}

bool has_state(moveit_msgs::CheckIfRobotStateExistsInWarehouse::Request&  request,
               moveit_msgs::CheckIfRobotStateExistsInWarehouse::Response& response,
               moveit_warehouse::RobotStateStorage* rs)
{
  response.exists = rs->hasRobotState(request.name, request.robot);
  return true;
}

bool get_state(moveit_msgs::GetRobotStateFromWarehouse::Request&  request,
               moveit_msgs::GetRobotStateFromWarehouse::Response& response,
               moveit_warehouse::RobotStateStorage* rs)
{
  moveit_warehouse::RobotStateWithMetadata state_buffer;
  rs->getRobotState(state_buffer, request.name, request.robot);
  response.state = static_cast<const moveit_msgs::RobotState&>(*state_buffer);
  return true;
}

int main(int argc, char **argv)
{
  ros::init(argc, argv, "moveit_warehouse_services");

  boost::program_options::options_description desc;
  desc.add_options()
    ("help", "Show help message")
    ("host", boost::program_options::value<std::string>(), "Host for the MongoDB.")
    ("port", boost::program_options::value<std::size_t>(), "Port for the MongoDB.");

  boost::program_options::variables_map vm;
  boost::program_options::store(boost::program_options::parse_command_line(argc, argv, desc), vm);
  boost::program_options::notify(vm);

  if (vm.count("help"))
  {
    std::cout << desc << std::endl;
    return 1;
  }

  ros::AsyncSpinner spinner(1);
  spinner.start();

  moveit_warehouse::RobotStateStorage rs;

  std::string host = vm.count("host") ? vm["host"].as<std::string>() : "";
  std::size_t port = vm.count("port") ? vm["port"].as<std::size_t>() : 0;

  try
  {
    rs = moveit_warehouse::RobotStateStorage(host, port);
  }
  catch (...)
  {
    ROS_FATAL_STREAM("Couldn't connect to MongoDB on " << host << ":" <<  port);
    return -1;
  }

  std::vector<std::string> names;
  rs.getKnownRobotStates(names);
  if (names.empty())
    ROS_INFO("There are no previously stored robot states");
  else
  {
    ROS_INFO("Previously stored robot states:");
    for (std::size_t i = 0 ; i < names.size() ; ++i)
      ROS_INFO(" * %s", names[i].c_str());
  }

  boost::function<bool(moveit_msgs::SaveRobotStateToWarehouse::Request&  request,
                       moveit_msgs::SaveRobotStateToWarehouse::Response& response)>
    save_cb = boost::bind(&store_state, _1, _2, &rs);

  boost::function<bool(moveit_msgs::ListRobotStatesInWarehouse::Request&  request,
                       moveit_msgs::ListRobotStatesInWarehouse::Response& response)>
    list_cb = boost::bind(&list_states, _1, _2, &rs);

  boost::function<bool(moveit_msgs::GetRobotStateFromWarehouse::Request&  request,
                       moveit_msgs::GetRobotStateFromWarehouse::Response& response)>
    get_cb = boost::bind(&get_state, _1, _2, &rs);

  boost::function<bool(moveit_msgs::CheckIfRobotStateExistsInWarehouse::Request&  request,
                       moveit_msgs::CheckIfRobotStateExistsInWarehouse::Response& response)>
    has_cb = boost::bind(&has_state, _1, _2, &rs);

  ros::NodeHandle node("~");
  ros::ServiceServer save_state_server  = node.advertiseService("save_robot_state",  save_cb);
  ros::ServiceServer list_states_server = node.advertiseService("list_robot_states", list_cb);
  ros::ServiceServer get_state_server   = node.advertiseService("get_robot_state",   get_cb);
  ros::ServiceServer has_state_server   = node.advertiseService("has_robot_state",   has_cb);

  ros::waitForShutdown();
  return 0;
}
<commit_msg>now takes port + host from param server<commit_after>/*********************************************************************
 * Software License Agreement (BSD License)
 *
 *  Copyright (c) 2012, Willow Garage, Inc.
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above
 *     copyright notice, this list of conditions and the following
 *     disclaimer in the documentation and/or other materials provided
 *     with the distribution.
 *   * Neither the name of Willow Garage nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *  POSSIBILITY OF SUCH DAMAGE.
 *********************************************************************/

/* Author: Dan Greenwald */

#include <moveit/warehouse/state_storage.h>
#include <boost/program_options/cmdline.hpp>
#include <boost/program_options/options_description.hpp>
#include <boost/program_options/parsers.hpp>
#include <boost/program_options/variables_map.hpp>

#include <ros/ros.h>
#include <moveit_msgs/SaveRobotStateToWarehouse.h>
#include <moveit_msgs/ListRobotStatesInWarehouse.h>
#include <moveit_msgs/GetRobotStateFromWarehouse.h>
#include <moveit_msgs/CheckIfRobotStateExistsInWarehouse.h>

static const std::string ROBOT_DESCRIPTION="robot_description";

bool store_state(moveit_msgs::SaveRobotStateToWarehouse::Request&  request,
                 moveit_msgs::SaveRobotStateToWarehouse::Response& response,
                 moveit_warehouse::RobotStateStorage* rs)
{
  const moveit_msgs::RobotState& state = request.state;
  if ("" == request.name)
  {
    ROS_ERROR("You must specify a name to store a state");
    return response.success = false;
  }
  rs->addRobotState(request.state, request.name, request.robot);
  return response.success = true;
}

bool list_states(moveit_msgs::ListRobotStatesInWarehouse::Request&  request,
                  moveit_msgs::ListRobotStatesInWarehouse::Response& response,
                  moveit_warehouse::RobotStateStorage* rs)
{
  if ("" == request.regex)
  {
    rs->getKnownRobotStates(response.states, request.robot);
  }
  else
  {
    rs->getKnownRobotStates(request.regex, response.states, request.robot);
  }
  return true;
}

bool has_state(moveit_msgs::CheckIfRobotStateExistsInWarehouse::Request&  request,
               moveit_msgs::CheckIfRobotStateExistsInWarehouse::Response& response,
               moveit_warehouse::RobotStateStorage* rs)
{
  response.exists = rs->hasRobotState(request.name, request.robot);
  return true;
}

bool get_state(moveit_msgs::GetRobotStateFromWarehouse::Request&  request,
               moveit_msgs::GetRobotStateFromWarehouse::Response& response,
               moveit_warehouse::RobotStateStorage* rs)
{
  moveit_warehouse::RobotStateWithMetadata state_buffer;
  rs->getRobotState(state_buffer, request.name, request.robot);
  response.state = static_cast<const moveit_msgs::RobotState&>(*state_buffer);
  return true;
}

int main(int argc, char **argv)
{
  ros::init(argc, argv, "moveit_warehouse_services");

  ros::AsyncSpinner spinner(1);
  spinner.start();

  ros::NodeHandle node("~");
  std::string host; int port;
  node.param<std::string>("/warehouse_host", host, "");
  node.param<int>("/warehouse_port", port, 0);

  ROS_INFO("Connecting to warehouse on %s:%d", host.c_str(), port);
  moveit_warehouse::RobotStateStorage rs(host, port);

  std::vector<std::string> names;
  rs.getKnownRobotStates(names);
  if (names.empty())
    ROS_INFO("There are no previously stored robot states");
  else
  {
    ROS_INFO("Previously stored robot states:");
    for (std::size_t i = 0 ; i < names.size() ; ++i)
      ROS_INFO(" * %s", names[i].c_str());
  }

  boost::function<bool(moveit_msgs::SaveRobotStateToWarehouse::Request&  request,
                       moveit_msgs::SaveRobotStateToWarehouse::Response& response)>
    save_cb = boost::bind(&store_state, _1, _2, &rs);

  boost::function<bool(moveit_msgs::ListRobotStatesInWarehouse::Request&  request,
                       moveit_msgs::ListRobotStatesInWarehouse::Response& response)>
    list_cb = boost::bind(&list_states, _1, _2, &rs);

  boost::function<bool(moveit_msgs::GetRobotStateFromWarehouse::Request&  request,
                       moveit_msgs::GetRobotStateFromWarehouse::Response& response)>
    get_cb = boost::bind(&get_state, _1, _2, &rs);

  boost::function<bool(moveit_msgs::CheckIfRobotStateExistsInWarehouse::Request&  request,
                       moveit_msgs::CheckIfRobotStateExistsInWarehouse::Response& response)>
    has_cb = boost::bind(&has_state, _1, _2, &rs);

  ros::ServiceServer save_state_server  = node.advertiseService("save_robot_state",  save_cb);
  ros::ServiceServer list_states_server = node.advertiseService("list_robot_states", list_cb);
  ros::ServiceServer get_state_server   = node.advertiseService("get_robot_state",   get_cb);
  ros::ServiceServer has_state_server   = node.advertiseService("has_robot_state",   has_cb);

  ros::waitForShutdown();
  return 0;
}
<|endoftext|>


<commit_before>// $Id: PointGrid_test.C,v 1.2 1999/12/29 08:52:52 oliver Exp $
#include <BALL/CONCEPT/classTest.h>

#include <BALL/DATATYPE/pointGrid.h>

START_TEST(PointGrid, "$Id: PointGrid_test.C,v 1.2 1999/12/29 08:52:52 oliver Exp $")

/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////

using BALL::PointGrid;
PointGrid<float>*	grid;
CHECK(constructor/1)
grid = new PointGrid<float>(0.0, 0.0, 0.0,
														10.0, 10.0, 10.0,
														11, 11, 11);
TEST_NOT_EQUAL(grid, 0)
RESULT

CHECK(destructor)
delete grid;
RESULT

using BALL::Vector3;
Vector3	lower(0.0, 0.0, 0.0);
Vector3	upper(10.0, 10.0, 10.0);
CHECK(constructor/2)
grid = new PointGrid<float>(lower, upper, 1.0);
TEST_NOT_EQUAL(grid, 0)
RESULT

CHECK(constructor/3)
delete grid;
grid = new PointGrid<float>(lower, upper, 11, 11, 11);
TEST_NOT_EQUAL(grid, 0)
RESULT

CHECK(getSize)
TEST_EQUAL(grid->getSize(), 1331)
RESULT

CHECK(getDimension)
TEST_REAL_EQUAL(grid->getDimension().x, 10.0)
TEST_REAL_EQUAL(grid->getDimension().y, 10.0)
TEST_REAL_EQUAL(grid->getDimension().z, 10.0)
RESULT

CHECK(getOrigin)
lower = grid->getOrigin();
TEST_REAL_EQUAL(lower.x, 0.0)
TEST_REAL_EQUAL(lower.y, 0.0)
TEST_REAL_EQUAL(lower.z, 0.0)
RESULT

CHECK(setOrigin/1)
grid->setOrigin(1.0, 1.0, 1.0);
lower = grid->getOrigin();
TEST_REAL_EQUAL(lower.x, 1.0)
TEST_REAL_EQUAL(lower.y, 1.0)
TEST_REAL_EQUAL(lower.z, 1.0)
RESULT

CHECK(setOrigin/2)
lower.set(2.0, 2.0, 2.0);
grid->setOrigin(lower);
lower = grid->getOrigin();
TEST_REAL_EQUAL(lower.x, 2.0)
TEST_REAL_EQUAL(lower.y, 2.0)
TEST_REAL_EQUAL(lower.z, 2.0)
RESULT

CHECK(getMaxX)
TEST_REAL_EQUAL(grid->getMaxX(), 12.0)
RESULT

CHECK(getMaxY)
TEST_REAL_EQUAL(grid->getMaxY(), 12.0)
RESULT

CHECK(getMaxZ)
TEST_REAL_EQUAL(grid->getMaxZ(), 12.0)
RESULT

CHECK(getMinX)
TEST_REAL_EQUAL(grid->getMinX(), 2.0)
RESULT

CHECK(getMinY)
TEST_REAL_EQUAL(grid->getMinY(), 2.0)
RESULT

CHECK(getMinZ)
TEST_REAL_EQUAL(grid->getMinZ(), 2.0)
RESULT

CHECK(getXSpacing)
TEST_REAL_EQUAL(grid->getXSpacing(), 1.0)
RESULT

CHECK(getYSpacing)
TEST_REAL_EQUAL(grid->getYSpacing(), 1.0)
RESULT

CHECK(getZSpacing)
TEST_REAL_EQUAL(grid->getZSpacing(), 1.0)
RESULT

CHECK(getMaxXIndex)
TEST_EQUAL(grid->getMaxXIndex(), 10)
RESULT

CHECK(getMaxYIndex)
TEST_EQUAL(grid->getMaxYIndex(), 10)
RESULT

CHECK(getMaxZIndex)
TEST_EQUAL(grid->getMaxZIndex(), 10)
RESULT

CHECK(operator[])
(*grid)[3 + 11 * 3 + 11 * 11 * 3] = 1.2345;
lower.set(5.0, 5.0, 5.0);
TEST_EQUAL((*grid)[3 + 11 * 3 + 11 * 11 * 3], (*grid)[lower]);
RESULT

BALL::PointGrid<float>::GridIndex	index;
CHECK(getIndex/1)
lower.set(3.49, 3.51, 3.0);
index = grid->getIndex(lower);
TEST_EQUAL(index.x, 1)
TEST_EQUAL(index.y, 2)
TEST_EQUAL(index.z, 1)
RESULT

CHECK(getIndex/2)
index = grid->getIndex(3.49, 3.51, 3.0);
TEST_EQUAL(index.x, 1)
TEST_EQUAL(index.y, 2)
TEST_EQUAL(index.z, 1)
RESULT

CHECK(getData)
*(grid->getData(0, 0, 0)) = 5.4321;
lower = grid->getOrigin();
TEST_REAL_EQUAL(*(grid->getData(0)), 5.4321);
TEST_REAL_EQUAL(*(grid->getData(0)), *(grid->getData(lower)));
RESULT

CHECK(getGridCoordinates/1)
lower = grid->getGridCoordinates(0, 0, 0);
TEST_REAL_EQUAL(lower.x, 2.0)
TEST_REAL_EQUAL(lower.y, 2.0)
TEST_REAL_EQUAL(lower.z, 2.0)
RESULT

CHECK(getGridCoordinates/2)
lower = grid->getGridCoordinates(2 + 2 * 11 + 2 * 11 * 11);
TEST_REAL_EQUAL(lower.x, 4.0)
TEST_REAL_EQUAL(lower.y, 4.0)
TEST_REAL_EQUAL(lower.z, 4.0)
RESULT

CHECK(getGridCoordinates/3)
upper.set(3.999999, 4.0, 3.0001);
lower = grid->getGridCoordinates(upper);
TEST_REAL_EQUAL(lower.x, 3.0)
TEST_REAL_EQUAL(lower.y, 4.0)
TEST_REAL_EQUAL(lower.z, 3.0)
RESULT

/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
<commit_msg>cosmetic changes<commit_after>// $Id: PointGrid_test.C,v 1.3 2000/07/01 18:11:03 amoll Exp $
#include <BALL/CONCEPT/classTest.h>

#include <BALL/DATATYPE/pointGrid.h>

START_TEST(PointGrid, "$Id: PointGrid_test.C,v 1.3 2000/07/01 18:11:03 amoll Exp $")

/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
using namespace BALL;

String filename;
using BALL::PointGrid;
PointGrid<float>*	grid;

CHECK(constructor/0)
	grid = new PointGrid<float>();
	TEST_NOT_EQUAL(grid, 0)
RESULT

CHECK(destructor)
	delete grid;
RESULT

CHECK(constructor/1)
	grid = new PointGrid<float>(0.0, 0.0, 0.0,
															10.0, 10.0, 10.0,
															11, 11, 11);
	TEST_NOT_EQUAL(grid, 0)
RESULT

using BALL::Vector3;
Vector3	lower(0.0, 0.0, 0.0);
Vector3	upper(10.0, 10.0, 10.0);

CHECK(constructor/2)
	grid = new PointGrid<float>(lower, upper, 1.0);
	TEST_NOT_EQUAL(grid, 0)
RESULT

CHECK(constructor/3)
	delete grid;
	grid = new PointGrid<float>(lower, upper, 11, 11, 11);
	TEST_NOT_EQUAL(grid, 0)
RESULT

CHECK(getSize)
	TEST_EQUAL(grid->getSize(), 1331)
RESULT

PointGrid<float> g(0.0, 0.0, 0.0, 10.0, 10.0, 10.0,	11, 11, 11);

CHECK(set)
	PointGrid<float> g1;
	g1.set(g);
	TEST_EQUAL(g1.getSize(), 1331)
RESULT

CHECK(operator =)
	PointGrid<float> g1;
	g1 = g;
	TEST_EQUAL(g1.getSize(), 1331)
RESULT

CHECK(dump)
  String filename;
	NEW_TMP_FILE(filename)
	std::ofstream outfile(filename.c_str(), ios::out);
	g.dump(outfile);
	outfile.close();
	TEST_FILE(filename.c_str(), "data/PointGrid_test.txt", true)
RESULT

CHECK(isValid)
	TEST_EQUAL(g.isValid(), true)
RESULT

CHECK(getMaxX)
	TEST_REAL_EQUAL(grid->getMaxX(), 10.0)
RESULT

CHECK(getMaxY)
	TEST_REAL_EQUAL(grid->getMaxY(), 10.0)
RESULT

CHECK(getMaxZ)
	TEST_REAL_EQUAL(grid->getMaxZ(), 10.0)
RESULT

CHECK(getMinX)
	TEST_REAL_EQUAL(grid->getMinX(), 0.0)
RESULT

CHECK(getMinY)
	TEST_REAL_EQUAL(grid->getMinY(), 0.0)
RESULT

CHECK(getMinZ)
	TEST_REAL_EQUAL(grid->getMinZ(), 0.0)
RESULT

CHECK(getMaxXIndex)
	TEST_EQUAL(grid->getMaxXIndex(), 10)
RESULT

CHECK(getMaxYIndex)
	TEST_EQUAL(grid->getMaxYIndex(), 10)
RESULT

CHECK(getMaxZIndex)
	TEST_EQUAL(grid->getMaxZIndex(), 10)
RESULT

CHECK(getXSpacing)
	TEST_REAL_EQUAL(grid->getXSpacing(), 1.0)
RESULT

CHECK(getYSpacing)
	TEST_REAL_EQUAL(grid->getYSpacing(), 1.0)
RESULT

CHECK(getZSpacing)
	TEST_REAL_EQUAL(grid->getZSpacing(), 1.0)
RESULT

BALL::PointGrid<float>::GridIndex	index;

CHECK(getIndex/1)
	lower.set(3.49, 3.51, 3.0);
	index = grid->getIndex(lower);
	TEST_EQUAL(index.x, 3)
	TEST_EQUAL(index.y, 4)
	TEST_EQUAL(index.z, 3)
RESULT

CHECK(getIndex/2)
	index = grid->getIndex(3.49, 3.51, 3.0);
	TEST_EQUAL(index.x, 3)
	TEST_EQUAL(index.y, 4)
	TEST_EQUAL(index.z, 3)
RESULT

CHECK(getData/1/2)
	*(grid->getData(0, 0, 0)) = 5.4321;
	lower = grid->getOrigin();
	TEST_REAL_EQUAL(*(grid->getData(0)), 5.4321);
	TEST_REAL_EQUAL(*(grid->getData(0)), *(grid->getData(lower)));
RESULT

CHECK(operator[]/1/2)
	(*grid)[3 + 11 * 3 + 11 * 11 * 3] = 1.2345;
	lower.set(3.0, 3.0, 3.0);
	TEST_EQUAL((*grid)[3 + 11 * 3 + 11 * 11 * 3], (*grid)[lower]);
RESULT

CHECK(getGridCoordinates/1)
	lower = grid->getGridCoordinates(0, 0, 0);
	TEST_REAL_EQUAL(lower.x, 0.0)
	TEST_REAL_EQUAL(lower.y, 0.0)
	TEST_REAL_EQUAL(lower.z, 0.0)
RESULT

CHECK(getGridCoordinates/2)
	lower = grid->getGridCoordinates(2 + 2 * 11 + 2 * 11 * 11);
	TEST_REAL_EQUAL(lower.x, 2.0)
	TEST_REAL_EQUAL(lower.y, 2.0)
	TEST_REAL_EQUAL(lower.z, 2.0)
RESULT

CHECK(getGridCoordinates/3)
	upper.set(3.999999, 4.0, 3.0001);
	lower = grid->getGridCoordinates(upper);
	TEST_REAL_EQUAL(lower.x, 3.0)
	TEST_REAL_EQUAL(lower.y, 4.0)
	TEST_REAL_EQUAL(lower.z, 3.0)
RESULT

CHECK(getBoxIndices)
///
RESULT

CHECK(getBoxData)
///
RESULT

CHECK(getOrigin)
	lower = grid->getOrigin();
	TEST_REAL_EQUAL(lower.x, 0.0)
	TEST_REAL_EQUAL(lower.y, 0.0)
	TEST_REAL_EQUAL(lower.z, 0.0)
RESULT

CHECK(setOrigin/1)
	grid->setOrigin(1.0, 1.0, 1.0);
	lower = grid->getOrigin();
	TEST_REAL_EQUAL(lower.x, 1.0)
	TEST_REAL_EQUAL(lower.y, 1.0)
	TEST_REAL_EQUAL(lower.z, 1.0)
	index = grid->getIndex(3.49, 3.51, 3.0);
	TEST_EQUAL(index.x, 2)
	TEST_EQUAL(index.y, 3)
	TEST_EQUAL(index.z, 2)
RESULT

CHECK(setOrigin/2)
	lower.set(2.0, 2.0, 2.0);
	grid->setOrigin(lower);
	lower = grid->getOrigin();
	TEST_REAL_EQUAL(lower.x, 2.0)
	TEST_REAL_EQUAL(lower.y, 2.0)
	TEST_REAL_EQUAL(lower.z, 2.0)
	index = grid->getIndex(3.49, 3.51, 3.0);
	TEST_EQUAL(index.x, 1)
	TEST_EQUAL(index.y, 2)
	TEST_EQUAL(index.z, 1)
RESULT

CHECK(getDimension)
	TEST_REAL_EQUAL(grid->getDimension().x, 10.0)
	TEST_REAL_EQUAL(grid->getDimension().y, 10.0)
	TEST_REAL_EQUAL(grid->getDimension().z, 10.0)
RESULT

CHECK(getInterpolatedValue)
///
RESULT

/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
<|endoftext|>