<commit_before>// Virvo - Virtual Reality Volume Rendering
// Copyright (C) 1999-2003 University of Stuttgart, 2004-2005 Brown University
// Contact: Jurgen P. Schulze, jschulze@ucsd.edu
//
// This file is part of Virvo.
//
// Virvo 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 (see license.txt); if not, write to the
// Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

#include "util.h"

#include <GL/glew.h>

#ifdef _WIN32
#include <Windows.h>
#endif

#include <stdio.h>
#include <stdarg.h>

namespace gl = virvo::gl;

#ifndef APIENTRY
#define APIENTRY
#endif

#ifndef NDEBUG

//--------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------
#if defined(GL_KHR_debug)
static char const* GetDebugTypeString(GLenum type)
{
    switch (type)
    {
    case GL_DEBUG_TYPE_ERROR:
        return "error";
    case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR:
        return "deprecated behavior detected";
    case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR:
        return "undefined behavior detected";
    case GL_DEBUG_TYPE_PORTABILITY:
        return "portablility warning";
    case GL_DEBUG_TYPE_PERFORMANCE:
        return "performance warning";
    case GL_DEBUG_TYPE_OTHER:
        return "other";
    case GL_DEBUG_TYPE_MARKER:
        return "marker";
    }

    return "{unknown type}";
}
#endif

//--------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------
#ifdef _WIN32
static void OutputDebugStringAF(char const* format, ...)
{
    char text[1024] = {0};

    va_list args;
    va_start(args, format);

    vsnprintf_s(text, _TRUNCATE, format, args);

    va_end(args);

    OutputDebugStringA(text);
}
#endif

//--------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------
#if defined(GL_KHR_debug)
static void APIENTRY DebugCallback( GLenum /*source*/,
                                    GLenum type,
                                    GLuint /*id*/,
                                    GLenum /*severity*/,
                                    GLsizei /*length*/,
                                    const GLchar* message,
                                    GLvoid* /*userParam*/
                                    )
{
    if (type != GL_DEBUG_TYPE_ERROR)
        return;

#ifdef _WIN32
    if (IsDebuggerPresent())
    {
        OutputDebugStringAF("GL %s: %s\n", GetDebugTypeString(type), message);
        DebugBreak();
    }
#endif

    fprintf(stderr, "GL %s: %s\n", GetDebugTypeString(type), message);
}
#endif

#endif // !NDEBUG

//--------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------
void gl::enableDebugCallback()
{
#if !defined(NDEBUG) && defined(GL_KHR_debug)
    if (GLEW_KHR_debug)
    {
        glEnable(GL_DEBUG_OUTPUT);
        glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);

        glDebugMessageCallback(DebugCallback, 0);
    }
#endif // !NDEBUG
}

//--------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------
GLenum gl::getError(char const* file, int line)
{
    GLenum err = glGetError();

    if (err != GL_NO_ERROR)
        fprintf(stderr, "%s(%d) : GL error: %s\n", file, line, gluErrorString(err));

    return err;
}

//--------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------
static char const* GetFramebufferStatusString(GLenum status)
{
    switch (status)
    {
    case GL_FRAMEBUFFER_COMPLETE:
        return "framebuffer complete";
    case GL_FRAMEBUFFER_UNDEFINED:
        return "framebuffer undefined";
    case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT:
        return "framebuffer incomplete attachment";
    case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:
        return "framebuffer incomplete missing attachment";
    case GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER:
        return "framebuffer incomplete draw buffer";
    case GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER:
        return "framebuffer incomplete read buffer";
    case GL_FRAMEBUFFER_UNSUPPORTED:
        return "framebuffer unsupported";
    case GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE:
        return "framebuffer incomplete multisample";
    case GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS:
        return "framebuffer incomplete layer targets";
    default:
        return "{unknown status}";
    }
}

//--------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------
GLenum gl::getFramebufferStatus(GLenum target, char const* file, int line)
{
    GLenum status = glCheckFramebufferStatus(target);

    if (status != GL_FRAMEBUFFER_COMPLETE)
        fprintf(stderr, "%s(%d) : GL framebuffer error: %s\n", file, line, GetFramebufferStatusString(status));

    return status;
}

//--------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------
static void DrawFullScreenQuad()
{
    glMatrixMode(GL_PROJECTION);
    glPushMatrix();
    glLoadIdentity();
    glMatrixMode(GL_MODELVIEW);
    glPushMatrix();
    glLoadIdentity();

    glBegin(GL_QUADS);
    glTexCoord2f(0.0f, 0.0f); glVertex2f(-1.0f, -1.0f);
    glTexCoord2f(1.0f, 0.0f); glVertex2f( 1.0f, -1.0f);
    glTexCoord2f(1.0f, 1.0f); glVertex2f( 1.0f,  1.0f);
    glTexCoord2f(0.0f, 1.0f); glVertex2f(-1.0f,  1.0f);
    glEnd();

    glMatrixMode(GL_PROJECTION);
    glPopMatrix();
    glMatrixMode(GL_MODELVIEW);
    glPopMatrix();
}

//--------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------
void gl::blendTexture(GLuint texture, GLenum sfactor, GLenum dfactor)
{
    glPushAttrib(GL_ALL_ATTRIB_BITS);

    glActiveTexture(GL_TEXTURE0);

    glEnable(GL_BLEND);
    glBlendFunc(sfactor, dfactor);

    glEnable(GL_TEXTURE_2D);
    glBindTexture(GL_TEXTURE_2D, texture);

    glDepthMask(GL_FALSE);

    DrawFullScreenQuad();

    glPopAttrib();
}

//--------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------
void gl::blendTexture(GLuint texture)
{
    blendTexture(texture, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
}

//--------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------
void gl::blendPixels(GLsizei srcW, GLsizei srcH, GLenum format, GLenum type, const GLvoid* pixels, GLenum sfactor, GLenum dfactor)
{
    glPushAttrib(GL_COLOR_BUFFER_BIT);

    GLint viewport[4];

    glGetIntegerv(GL_VIEWPORT, &viewport[0]);

    glWindowPos2i(viewport[0], viewport[1]);

    GLfloat scaleX = static_cast<GLfloat>(viewport[2]) / srcW;
    GLfloat scaleY = static_cast<GLfloat>(viewport[3]) / srcH;

    glPixelZoom(scaleX, scaleY);

    glEnable(GL_BLEND);
    glBlendFunc(sfactor, dfactor);

    glDrawPixels(srcW, srcH, format, type, pixels);

    glPopAttrib();
}

//--------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------
void gl::blendPixels(GLsizei srcW, GLsizei srcH, GLenum format, GLenum type, const GLvoid* pixels)
{
    blendPixels(srcW, srcH, format, type, pixels, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
}

//--------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------
void gl::renderInterlacedStereoStencilBuffer(bool lines)
{
    static const GLubyte kPatternLines[32*(32/8)] = {
        0xFF, 0xFF, 0xFF, 0xFF,
        0x00, 0x00, 0x00, 0x00,
        0xFF, 0xFF, 0xFF, 0xFF,
        0x00, 0x00, 0x00, 0x00,
        0xFF, 0xFF, 0xFF, 0xFF,
        0x00, 0x00, 0x00, 0x00,
        0xFF, 0xFF, 0xFF, 0xFF,
        0x00, 0x00, 0x00, 0x00,
        0xFF, 0xFF, 0xFF, 0xFF,
        0x00, 0x00, 0x00, 0x00,
        0xFF, 0xFF, 0xFF, 0xFF,
        0x00, 0x00, 0x00, 0x00,
        0xFF, 0xFF, 0xFF, 0xFF,
        0x00, 0x00, 0x00, 0x00,
        0xFF, 0xFF, 0xFF, 0xFF,
        0x00, 0x00, 0x00, 0x00,
        0xFF, 0xFF, 0xFF, 0xFF,
        0x00, 0x00, 0x00, 0x00,
        0xFF, 0xFF, 0xFF, 0xFF,
        0x00, 0x00, 0x00, 0x00,
        0xFF, 0xFF, 0xFF, 0xFF,
        0x00, 0x00, 0x00, 0x00,
        0xFF, 0xFF, 0xFF, 0xFF,
        0x00, 0x00, 0x00, 0x00,
        0xFF, 0xFF, 0xFF, 0xFF,
        0x00, 0x00, 0x00, 0x00,
        0xFF, 0xFF, 0xFF, 0xFF,
        0x00, 0x00, 0x00, 0x00,
        0xFF, 0xFF, 0xFF, 0xFF,
        0x00, 0x00, 0x00, 0x00,
        0xFF, 0xFF, 0xFF, 0xFF,
        0x00, 0x00, 0x00, 0x00,
    };

    static const GLubyte kPatternCheckerBoard[32*(32/8)] = {
        0xAA, 0xAA, 0xAA, 0xAA,
        0x55, 0x55, 0x55, 0x55,
        0xAA, 0xAA, 0xAA, 0xAA,
        0x55, 0x55, 0x55, 0x55,
        0xAA, 0xAA, 0xAA, 0xAA,
        0x55, 0x55, 0x55, 0x55,
        0xAA, 0xAA, 0xAA, 0xAA,
        0x55, 0x55, 0x55, 0x55,
        0xAA, 0xAA, 0xAA, 0xAA,
        0x55, 0x55, 0x55, 0x55,
        0xAA, 0xAA, 0xAA, 0xAA,
        0x55, 0x55, 0x55, 0x55,
        0xAA, 0xAA, 0xAA, 0xAA,
        0x55, 0x55, 0x55, 0x55,
        0xAA, 0xAA, 0xAA, 0xAA,
        0x55, 0x55, 0x55, 0x55,
        0xAA, 0xAA, 0xAA, 0xAA,
        0x55, 0x55, 0x55, 0x55,
        0xAA, 0xAA, 0xAA, 0xAA,
        0x55, 0x55, 0x55, 0x55,
        0xAA, 0xAA, 0xAA, 0xAA,
        0x55, 0x55, 0x55, 0x55,
        0xAA, 0xAA, 0xAA, 0xAA,
        0x55, 0x55, 0x55, 0x55,
        0xAA, 0xAA, 0xAA, 0xAA,
        0x55, 0x55, 0x55, 0x55,
        0xAA, 0xAA, 0xAA, 0xAA,
        0x55, 0x55, 0x55, 0x55,
        0xAA, 0xAA, 0xAA, 0xAA,
        0x55, 0x55, 0x55, 0x55,
        0xAA, 0xAA, 0xAA, 0xAA,
        0x55, 0x55, 0x55, 0x55,
    };

    glPushAttrib(GL_ALL_ATTRIB_BITS);
    glPushClientAttrib(GL_CLIENT_ALL_ATTRIB_BITS);

    glDisable(GL_DEPTH_TEST);
    glDisable(GL_SCISSOR_TEST);
    glDisable(GL_LIGHTING);

    glColorMask(0, 0, 0, 0);
    glDepthMask(0);

    glClearStencil(0);
    glClear(GL_STENCIL_BUFFER_BIT);

    glPixelStorei(GL_UNPACK_ALIGNMENT, 1);

    glEnable(GL_POLYGON_STIPPLE);
    if (lines)
        glPolygonStipple(kPatternLines);
    else
        glPolygonStipple(kPatternCheckerBoard);

    glEnable(GL_STENCIL_TEST);
    glStencilMask(0xFFFFFFFF);
    glStencilOp(GL_REPLACE, GL_REPLACE, GL_REPLACE);
    glStencilFunc(GL_ALWAYS, 1, 0xFFFFFFFF);

    DrawFullScreenQuad();

    glPopAttrib();
    glPopClientAttrib();
}
<commit_msg>check for GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS before use<commit_after>// Virvo - Virtual Reality Volume Rendering
// Copyright (C) 1999-2003 University of Stuttgart, 2004-2005 Brown University
// Contact: Jurgen P. Schulze, jschulze@ucsd.edu
//
// This file is part of Virvo.
//
// Virvo 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 (see license.txt); if not, write to the
// Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

#include "util.h"

#include <GL/glew.h>

#ifdef _WIN32
#include <Windows.h>
#endif

#include <stdio.h>
#include <stdarg.h>

namespace gl = virvo::gl;

#ifndef APIENTRY
#define APIENTRY
#endif

#ifndef NDEBUG

//--------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------
#if defined(GL_KHR_debug)
static char const* GetDebugTypeString(GLenum type)
{
    switch (type)
    {
    case GL_DEBUG_TYPE_ERROR:
        return "error";
    case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR:
        return "deprecated behavior detected";
    case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR:
        return "undefined behavior detected";
    case GL_DEBUG_TYPE_PORTABILITY:
        return "portablility warning";
    case GL_DEBUG_TYPE_PERFORMANCE:
        return "performance warning";
    case GL_DEBUG_TYPE_OTHER:
        return "other";
    case GL_DEBUG_TYPE_MARKER:
        return "marker";
    }

    return "{unknown type}";
}
#endif

//--------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------
#ifdef _WIN32
static void OutputDebugStringAF(char const* format, ...)
{
    char text[1024] = {0};

    va_list args;
    va_start(args, format);

    vsnprintf_s(text, _TRUNCATE, format, args);

    va_end(args);

    OutputDebugStringA(text);
}
#endif

//--------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------
#if defined(GL_KHR_debug)
static void APIENTRY DebugCallback( GLenum /*source*/,
                                    GLenum type,
                                    GLuint /*id*/,
                                    GLenum /*severity*/,
                                    GLsizei /*length*/,
                                    const GLchar* message,
                                    GLvoid* /*userParam*/
                                    )
{
    if (type != GL_DEBUG_TYPE_ERROR)
        return;

#ifdef _WIN32
    if (IsDebuggerPresent())
    {
        OutputDebugStringAF("GL %s: %s\n", GetDebugTypeString(type), message);
        DebugBreak();
    }
#endif

    fprintf(stderr, "GL %s: %s\n", GetDebugTypeString(type), message);
}
#endif

#endif // !NDEBUG

//--------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------
void gl::enableDebugCallback()
{
#if !defined(NDEBUG) && defined(GL_KHR_debug)
    if (GLEW_KHR_debug)
    {
        glEnable(GL_DEBUG_OUTPUT);
        glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);

        glDebugMessageCallback(DebugCallback, 0);
    }
#endif // !NDEBUG
}

//--------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------
GLenum gl::getError(char const* file, int line)
{
    GLenum err = glGetError();

    if (err != GL_NO_ERROR)
        fprintf(stderr, "%s(%d) : GL error: %s\n", file, line, gluErrorString(err));

    return err;
}

//--------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------
static char const* GetFramebufferStatusString(GLenum status)
{
    switch (status)
    {
    case GL_FRAMEBUFFER_COMPLETE:
        return "framebuffer complete";
    case GL_FRAMEBUFFER_UNDEFINED:
        return "framebuffer undefined";
    case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT:
        return "framebuffer incomplete attachment";
    case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:
        return "framebuffer incomplete missing attachment";
    case GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER:
        return "framebuffer incomplete draw buffer";
    case GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER:
        return "framebuffer incomplete read buffer";
    case GL_FRAMEBUFFER_UNSUPPORTED:
        return "framebuffer unsupported";
    case GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE:
        return "framebuffer incomplete multisample";
#ifdef GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS
    case GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS:
        return "framebuffer incomplete layer targets";
#endif
    default:
        return "{unknown status}";
    }
}

//--------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------
GLenum gl::getFramebufferStatus(GLenum target, char const* file, int line)
{
    GLenum status = glCheckFramebufferStatus(target);

    if (status != GL_FRAMEBUFFER_COMPLETE)
        fprintf(stderr, "%s(%d) : GL framebuffer error: %s\n", file, line, GetFramebufferStatusString(status));

    return status;
}

//--------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------
static void DrawFullScreenQuad()
{
    glMatrixMode(GL_PROJECTION);
    glPushMatrix();
    glLoadIdentity();
    glMatrixMode(GL_MODELVIEW);
    glPushMatrix();
    glLoadIdentity();

    glBegin(GL_QUADS);
    glTexCoord2f(0.0f, 0.0f); glVertex2f(-1.0f, -1.0f);
    glTexCoord2f(1.0f, 0.0f); glVertex2f( 1.0f, -1.0f);
    glTexCoord2f(1.0f, 1.0f); glVertex2f( 1.0f,  1.0f);
    glTexCoord2f(0.0f, 1.0f); glVertex2f(-1.0f,  1.0f);
    glEnd();

    glMatrixMode(GL_PROJECTION);
    glPopMatrix();
    glMatrixMode(GL_MODELVIEW);
    glPopMatrix();
}

//--------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------
void gl::blendTexture(GLuint texture, GLenum sfactor, GLenum dfactor)
{
    glPushAttrib(GL_ALL_ATTRIB_BITS);

    glActiveTexture(GL_TEXTURE0);

    glEnable(GL_BLEND);
    glBlendFunc(sfactor, dfactor);

    glEnable(GL_TEXTURE_2D);
    glBindTexture(GL_TEXTURE_2D, texture);

    glDepthMask(GL_FALSE);

    DrawFullScreenQuad();

    glPopAttrib();
}

//--------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------
void gl::blendTexture(GLuint texture)
{
    blendTexture(texture, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
}

//--------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------
void gl::blendPixels(GLsizei srcW, GLsizei srcH, GLenum format, GLenum type, const GLvoid* pixels, GLenum sfactor, GLenum dfactor)
{
    glPushAttrib(GL_COLOR_BUFFER_BIT);

    GLint viewport[4];

    glGetIntegerv(GL_VIEWPORT, &viewport[0]);

    glWindowPos2i(viewport[0], viewport[1]);

    GLfloat scaleX = static_cast<GLfloat>(viewport[2]) / srcW;
    GLfloat scaleY = static_cast<GLfloat>(viewport[3]) / srcH;

    glPixelZoom(scaleX, scaleY);

    glEnable(GL_BLEND);
    glBlendFunc(sfactor, dfactor);

    glDrawPixels(srcW, srcH, format, type, pixels);

    glPopAttrib();
}

//--------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------
void gl::blendPixels(GLsizei srcW, GLsizei srcH, GLenum format, GLenum type, const GLvoid* pixels)
{
    blendPixels(srcW, srcH, format, type, pixels, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
}

//--------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------
void gl::renderInterlacedStereoStencilBuffer(bool lines)
{
    static const GLubyte kPatternLines[32*(32/8)] = {
        0xFF, 0xFF, 0xFF, 0xFF,
        0x00, 0x00, 0x00, 0x00,
        0xFF, 0xFF, 0xFF, 0xFF,
        0x00, 0x00, 0x00, 0x00,
        0xFF, 0xFF, 0xFF, 0xFF,
        0x00, 0x00, 0x00, 0x00,
        0xFF, 0xFF, 0xFF, 0xFF,
        0x00, 0x00, 0x00, 0x00,
        0xFF, 0xFF, 0xFF, 0xFF,
        0x00, 0x00, 0x00, 0x00,
        0xFF, 0xFF, 0xFF, 0xFF,
        0x00, 0x00, 0x00, 0x00,
        0xFF, 0xFF, 0xFF, 0xFF,
        0x00, 0x00, 0x00, 0x00,
        0xFF, 0xFF, 0xFF, 0xFF,
        0x00, 0x00, 0x00, 0x00,
        0xFF, 0xFF, 0xFF, 0xFF,
        0x00, 0x00, 0x00, 0x00,
        0xFF, 0xFF, 0xFF, 0xFF,
        0x00, 0x00, 0x00, 0x00,
        0xFF, 0xFF, 0xFF, 0xFF,
        0x00, 0x00, 0x00, 0x00,
        0xFF, 0xFF, 0xFF, 0xFF,
        0x00, 0x00, 0x00, 0x00,
        0xFF, 0xFF, 0xFF, 0xFF,
        0x00, 0x00, 0x00, 0x00,
        0xFF, 0xFF, 0xFF, 0xFF,
        0x00, 0x00, 0x00, 0x00,
        0xFF, 0xFF, 0xFF, 0xFF,
        0x00, 0x00, 0x00, 0x00,
        0xFF, 0xFF, 0xFF, 0xFF,
        0x00, 0x00, 0x00, 0x00,
    };

    static const GLubyte kPatternCheckerBoard[32*(32/8)] = {
        0xAA, 0xAA, 0xAA, 0xAA,
        0x55, 0x55, 0x55, 0x55,
        0xAA, 0xAA, 0xAA, 0xAA,
        0x55, 0x55, 0x55, 0x55,
        0xAA, 0xAA, 0xAA, 0xAA,
        0x55, 0x55, 0x55, 0x55,
        0xAA, 0xAA, 0xAA, 0xAA,
        0x55, 0x55, 0x55, 0x55,
        0xAA, 0xAA, 0xAA, 0xAA,
        0x55, 0x55, 0x55, 0x55,
        0xAA, 0xAA, 0xAA, 0xAA,
        0x55, 0x55, 0x55, 0x55,
        0xAA, 0xAA, 0xAA, 0xAA,
        0x55, 0x55, 0x55, 0x55,
        0xAA, 0xAA, 0xAA, 0xAA,
        0x55, 0x55, 0x55, 0x55,
        0xAA, 0xAA, 0xAA, 0xAA,
        0x55, 0x55, 0x55, 0x55,
        0xAA, 0xAA, 0xAA, 0xAA,
        0x55, 0x55, 0x55, 0x55,
        0xAA, 0xAA, 0xAA, 0xAA,
        0x55, 0x55, 0x55, 0x55,
        0xAA, 0xAA, 0xAA, 0xAA,
        0x55, 0x55, 0x55, 0x55,
        0xAA, 0xAA, 0xAA, 0xAA,
        0x55, 0x55, 0x55, 0x55,
        0xAA, 0xAA, 0xAA, 0xAA,
        0x55, 0x55, 0x55, 0x55,
        0xAA, 0xAA, 0xAA, 0xAA,
        0x55, 0x55, 0x55, 0x55,
        0xAA, 0xAA, 0xAA, 0xAA,
        0x55, 0x55, 0x55, 0x55,
    };

    glPushAttrib(GL_ALL_ATTRIB_BITS);
    glPushClientAttrib(GL_CLIENT_ALL_ATTRIB_BITS);

    glDisable(GL_DEPTH_TEST);
    glDisable(GL_SCISSOR_TEST);
    glDisable(GL_LIGHTING);

    glColorMask(0, 0, 0, 0);
    glDepthMask(0);

    glClearStencil(0);
    glClear(GL_STENCIL_BUFFER_BIT);

    glPixelStorei(GL_UNPACK_ALIGNMENT, 1);

    glEnable(GL_POLYGON_STIPPLE);
    if (lines)
        glPolygonStipple(kPatternLines);
    else
        glPolygonStipple(kPatternCheckerBoard);

    glEnable(GL_STENCIL_TEST);
    glStencilMask(0xFFFFFFFF);
    glStencilOp(GL_REPLACE, GL_REPLACE, GL_REPLACE);
    glStencilFunc(GL_ALWAYS, 1, 0xFFFFFFFF);

    DrawFullScreenQuad();

    glPopAttrib();
    glPopClientAttrib();
}
<|endoftext|>


<commit_before>// Virvo - Virtual Reality Volume Rendering
// Copyright (C) 1999-2003 University of Stuttgart, 2004-2005 Brown University
// Contact: Jurgen P. Schulze, jschulze@ucsd.edu
//
// This file is part of Virvo.
//
// Virvo 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 (see license.txt); if not, write to the
// Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

#include "vvvirvo.h"

#include <algorithm>
#include <locale>
#include <string>

#ifdef HAVE_CONFIG_H
#include "vvconfig.h"
#endif

#define VV_STRINGIFY(X) VV_STRINGIFY2(X)
#define VV_STRINGIFY2(X) #X

const char* virvo::version()
{
  return VV_STRINGIFY(VV_VERSION_MAJOR) "." VV_STRINGIFY(VV_VERSION_MINOR);
}

bool virvo::hasFeature(const char* name)
{
#ifndef HAVE_CONFIG_H
  return false;
#endif

  std::string str = name;
  std::transform(str.begin(), str.end(), str.begin(), ::tolower);

  if (str == "bonjour")
  {
#ifdef HAVE_BONJOUR
    return true;
#else
    return false;
#endif
  }
  else if (str == "cg")
  {
#ifdef HAVE_CG
    return true;
#else
    return false;
#endif
  }
  else if (str == "cuda")
  {
#ifdef HAVE_CUDA
    return true;
#else
    return false;
#endif
  }
  else if (str == "ffmpeg")
  {
#ifdef HAVE_FFMEPG
    return true;
#else
    return false;
#endif
  }
  else if (str == "gl" || str == "opengl")
  {
#ifdef HAVE_GL
    return true;
#else
    return false;
#endif
  }
  else if (str == "glu")
  {
#ifdef HAVE_GLU
    return true;
#else
    return false;
#endif
  }
  else if (str == "nifty")
  {
#if VV_HAVE_NIFTI
    return true;
#else
    return false;
#endif
  }
  else if (str == "snappy")
  {
#ifdef HAVE_SNAPPY
    return true;
#else
    return false;
#endif
  }
  else if (str == "volpack")
  {
#ifdef HAVE_VOLPACK
    return true;
#else
    return false;
#endif
  }
  else if (str == "x11")
  {
#ifdef HAVE_X11
    return true;
#else
    return false;
#endif
  }
  else
  {
    return false;
  }
}

// vim: sw=2:expandtab:softtabstop=2:ts=2:cino=\:0g0t0
<commit_msg>Fix a typo<commit_after>// Virvo - Virtual Reality Volume Rendering
// Copyright (C) 1999-2003 University of Stuttgart, 2004-2005 Brown University
// Contact: Jurgen P. Schulze, jschulze@ucsd.edu
//
// This file is part of Virvo.
//
// Virvo 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 (see license.txt); if not, write to the
// Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

#include "vvvirvo.h"

#include <algorithm>
#include <locale>
#include <string>

#ifdef HAVE_CONFIG_H
#include "vvconfig.h"
#endif

#define VV_STRINGIFY(X) VV_STRINGIFY2(X)
#define VV_STRINGIFY2(X) #X

const char* virvo::version()
{
  return VV_STRINGIFY(VV_VERSION_MAJOR) "." VV_STRINGIFY(VV_VERSION_MINOR);
}

bool virvo::hasFeature(const char* name)
{
#ifndef HAVE_CONFIG_H
  return false;
#endif

  std::string str = name;
  std::transform(str.begin(), str.end(), str.begin(), ::tolower);

  if (str == "bonjour")
  {
#ifdef HAVE_BONJOUR
    return true;
#else
    return false;
#endif
  }
  else if (str == "cg")
  {
#ifdef HAVE_CG
    return true;
#else
    return false;
#endif
  }
  else if (str == "cuda")
  {
#ifdef HAVE_CUDA
    return true;
#else
    return false;
#endif
  }
  else if (str == "ffmpeg")
  {
#ifdef HAVE_FFMEPG
    return true;
#else
    return false;
#endif
  }
  else if (str == "gl" || str == "opengl")
  {
#ifdef HAVE_GL
    return true;
#else
    return false;
#endif
  }
  else if (str == "glu")
  {
#ifdef HAVE_GLU
    return true;
#else
    return false;
#endif
  }
  else if (str == "nifti")
  {
#if VV_HAVE_NIFTI
    return true;
#else
    return false;
#endif
  }
  else if (str == "snappy")
  {
#ifdef HAVE_SNAPPY
    return true;
#else
    return false;
#endif
  }
  else if (str == "volpack")
  {
#ifdef HAVE_VOLPACK
    return true;
#else
    return false;
#endif
  }
  else if (str == "x11")
  {
#ifdef HAVE_X11
    return true;
#else
    return false;
#endif
  }
  else
  {
    return false;
  }
}

// vim: sw=2:expandtab:softtabstop=2:ts=2:cino=\:0g0t0
<|endoftext|>


<commit_before>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>

#include "btree_str_kv.h"
#include "test.h"
#include "common.h"
#include "list.h"
#include "memleak.h"

typedef uint16_t key_len_t;

void kv_set_key_test()
{

    TEST_INIT();
    memleak_start();

    char str[] = "teststring";
    uint8_t *key = alca(uint8_t, sizeof(void *));
    size_t str_len = sizeof(str);

    // set key ptr
    btree_str_kv_set_key(key, str, str_len);
    void *kv_addr;
    memcpy(&kv_addr, key, sizeof(void *));

    // check key len
    key_len_t kv_len;
    memcpy(&kv_len, (key_len_t *)kv_addr, sizeof(key_len_t));
    key_len_t kv_len_dec = _endian_decode(kv_len);
    TEST_CHK(kv_len_dec == str_len);

    // check key size
    char kv_str[str_len];
    memcpy(kv_str, ((char *)kv_addr) + sizeof(key_len_t), str_len);
    int cmp = strcmp(kv_str, str);
    TEST_CHK(cmp == 0);
    free(kv_addr);

    memleak_end();
    TEST_RESULT("kv set key test");
}

void construct_key_ptr(const char *str, const key_len_t len, void *key_ptr){
    void *key;
    key_len_t _str_len;
    key = (void *)malloc(sizeof(key_len_t) + len);
    _str_len = _endian_encode(len);
    memcpy(key, &_str_len, sizeof(key_len_t));
    memcpy((uint8_t*)key + sizeof(key_len_t), str, len);
    memcpy(key_ptr, &key, sizeof(void *));
}

void kv_get_key_test()
{

    TEST_INIT();
    memleak_start();

    // create kv ptr
    void *key;
    char str[] = "teststring";
    key_len_t str_len = sizeof(str);
    construct_key_ptr(str, str_len, &key);

    // get_key unpacks kv formated key
    char *strbuf = alca(char, str_len);
    size_t len;
    btree_str_kv_get_key(&key, strbuf, &len);

    // check results
    int cmp = strcmp(strbuf, str);
    TEST_CHK(cmp == 0);
    TEST_CHK(len ==str_len);
    free(key);

    memleak_end();
    TEST_RESULT("kv get key test");
}

void kv_free_test()
{

    TEST_INIT();
    memleak_start();

    void *key;
    char str[] = "teststring";
    key_len_t str_len = sizeof(str);
    construct_key_ptr(str, str_len, &key);

    TEST_CHK(key != NULL);
    btree_str_kv_free_key(&key);
    TEST_CHK(key == NULL);

    memleak_end();
    TEST_RESULT("kv free test");
}

int main()
{

    #ifdef _MEMPOOL
        mempool_init();
    #endif

    kv_set_key_test();
    kv_get_key_test();
    kv_free_test();
    return 0;
}
<commit_msg>additional str_kv_tests with kv ops<commit_after>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>

#include "btree.h"
#include "btree_kv.h"
#include "btree_str_kv.h"
#include "btreeblock.h"
#include "filemgr_ops.h"
#include "test.h"
#include "common.h"
#include "list.h"
#include "memleak.h"

typedef uint16_t key_len_t;

void freevars(void **vv, size_t n)
{
    for(int i = 0; i < n; i++){
        free(vv[i]);
    }
}

void kv_set_key_test()
{

    TEST_INIT();
    memleak_start();

    char str[] = "teststring";
    uint8_t *key = alca(uint8_t, sizeof(void *));
    size_t str_len = sizeof(str);

    // set key ptr
    btree_str_kv_set_key(key, str, str_len);
    void *kv_addr;
    memcpy(&kv_addr, key, sizeof(void *));

    // check key len
    key_len_t kv_len;
    memcpy(&kv_len, (key_len_t *)kv_addr, sizeof(key_len_t));
    key_len_t kv_len_dec = _endian_decode(kv_len);
    TEST_CHK(kv_len_dec == str_len);

    // check key size
    char kv_str[str_len];
    memcpy(kv_str, ((char *)kv_addr) + sizeof(key_len_t), str_len);
    int cmp = strcmp(kv_str, str);
    TEST_CHK(cmp == 0);
    free(kv_addr);

    memleak_end();
    TEST_RESULT("kv set key test");
}

void construct_key_ptr(const char *str, const key_len_t len, void *key_ptr){
    void *key;
    key_len_t _str_len;
    key = (void *)malloc(sizeof(key_len_t) + len);
    _str_len = _endian_encode(len);
    memcpy(key, &_str_len, sizeof(key_len_t));
    memcpy((uint8_t*)key + sizeof(key_len_t), str, len);
    memcpy(key_ptr, &key, sizeof(void *));
}

void kv_get_key_test()
{

    TEST_INIT();
    memleak_start();

    // create kv ptr
    void *key;
    char str[] = "teststring";
    key_len_t str_len = sizeof(str);
    construct_key_ptr(str, str_len, &key);

    // get_key unpacks kv formated key
    char *strbuf = alca(char, str_len);
    size_t len;
    btree_str_kv_get_key(&key, strbuf, &len);

    // check results
    int cmp = strcmp(strbuf, str);
    TEST_CHK(cmp == 0);
    TEST_CHK(len ==str_len);
    free(key);

    memleak_end();
    TEST_RESULT("kv get key test");
}

void kv_get_key_isnull_test()
{

    TEST_INIT();
    memleak_start();

    void *key = NULL;
    char *strbuf;
    size_t len;
    btree_str_kv_get_key(&key, strbuf, &len);

    // check results
    TEST_CHK(len == 0);
    free(key);

    memleak_end();
    TEST_RESULT("kv get key is null test");
}

void kv_free_test()
{

    TEST_INIT();
    memleak_start();

    void *key;
    char str[] = "teststring";
    key_len_t str_len = sizeof(str);
    construct_key_ptr(str, str_len, &key);

    TEST_CHK(key != NULL);
    btree_str_kv_free_key(&key);
    TEST_CHK(key == NULL);

    memleak_end();
    TEST_RESULT("kv free test");
}

struct bnode* dummy_node(uint8_t ksize, uint8_t vsize, uint16_t level)
{
    struct bnode *node;
    node = (struct bnode*)malloc(sizeof(bnode));
    memset(node, 0, sizeof(bnode));

    node->kvsize = ksize<<4 | vsize;
    node->level = level;
    node->data = (void *)malloc(node->kvsize);
    return node;
}

void kv_init_ops_test()
{
    TEST_INIT();
    memleak_start();

    // init with null
    btree_kv_ops *kv_ops = btree_str_kv_get_kb64_vb64(NULL);
    TEST_CHK(kv_ops != NULL);

    // re-init with existing ops
    btree_kv_ops *kv_ops_copy =  btree_str_kv_get_kb64_vb64(kv_ops);
    TEST_CHK(memcmp(kv_ops, kv_ops_copy, sizeof(btree_kv_ops)) == 0);

    free(kv_ops);
    memleak_end();
    TEST_RESULT("kv init ops test");
}

void kv_init_var_test()
{
    TEST_INIT();
    memleak_start();

    void *key, *value;
    btree_kv_ops *kv_ops = btree_str_kv_get_kb64_vb64(NULL);
    btree *tree = alca(struct btree, 1);
    uint8_t ksize = sizeof(void *);
    uint8_t vsize = 8;

    // unintialized key/value
    key = NULL;
    value = NULL;
    kv_ops->init_kv_var(tree, key, value);
    TEST_CHK(key == NULL);
    TEST_CHK(value == NULL);

    // initialized
    key = (void *)alca(uint8_t, ksize);
    value = (void *)alca(uint8_t, vsize);
    tree->vsize = vsize;
    kv_ops->init_kv_var(tree, key, value);
    TEST_CHK( *(uint8_t *)key == 0 );
    TEST_CHK( *(uint8_t *)value == 0 );

    free(kv_ops);
    memleak_end();
    TEST_RESULT("kv init var test");
}

void kv_set_var_test()
{
    TEST_INIT();
    memleak_start();

    bnoderef node;
    btree_kv_ops *kv_ops;
    void *key, *value;
    uint8_t ksize, vsize;
    int level;
    uint64_t v;
    int cmp;
    idx_t idx;
    char str[] = "teststring";
    char str2[] = "test";
    key_len_t str_len = sizeof(str);

    vsize = sizeof(v);
    v = 10;

    construct_key_ptr(str, str_len, &key);
    value = alca(uint8_t, vsize);
    memset(value, 0, vsize);
    memcpy(value, &v, vsize);

    // init ops
    kv_ops = alca(btree_kv_ops, 1);
    btree_str_kv_get_kb64_vb64(kv_ops);

    // set key/value in node
    idx = 0;
    level = 1;
    ksize = str_len + sizeof(key_len_t);
    node = dummy_node(ksize, vsize, level);
    kv_ops->set_kv(node, idx, &key, value);

    // verify node->data
    cmp = strcmp((char *)((uint8_t *)node->data + sizeof(key_len_t)), str);
    TEST_CHK(cmp == 0);
    cmp = memcmp((uint8_t *)node->data + ksize, value, vsize);
    TEST_CHK(cmp == 0);

    void *vars[] = {node->data, node, key};
    freevars(vars, sizeof(vars)/sizeof(void *));

    memleak_end();
    TEST_RESULT("kv set var test");
}

int main()
{

    #ifdef _MEMPOOL
        mempool_init();
    #endif

    kv_set_key_test();
    kv_get_key_test();
    kv_get_key_isnull_test();
    kv_free_test();
    kv_init_ops_test();
    kv_init_var_test();
    kv_set_var_test();

    return 0;
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2017 Politecnico di Torino
 *
 * 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 "BPF.h"
#include "catch.hpp"

TEST_CASE("test bpf table", "[bpf_table]") {
  const std::string BPF_PROGRAM = R"(
    BPF_TABLE("hash", int, int, myhash, 128);
  )";

  ebpf::BPF *bpf(new ebpf::BPF);
  ebpf::StatusTuple res(0);
  res = bpf->init(BPF_PROGRAM);
  REQUIRE(res.code() == 0);

  ebpf::BPFTable t = bpf->get_table("myhash");

  // update element
  std::string value;
  res = t.update_value("0x07", "0x42");
  REQUIRE(res.code() == 0);
  res = t.get_value("0x07", value);
  REQUIRE(res.code() == 0);
  REQUIRE(value == "0x42");

  // update another element
  res = t.update_value("0x11", "0x777");
  REQUIRE(res.code() == 0);
  res = t.get_value("0x11", value);
  REQUIRE(res.code() == 0);
  REQUIRE(value == "0x777");

  // remove value
  res = t.remove_value("0x11");
  REQUIRE(res.code() == 0);
  res = t.get_value("0x11", value);
  REQUIRE(res.code() != 0);

  // delete bpf_module, call to key/leaf printf/scanf must fail
  delete bpf;

  res = t.update_value("0x07", "0x42");
  REQUIRE(res.code() != 0);

  res = t.get_value("0x07", value);
  REQUIRE(res.code() != 0);

  res = t.remove_value("0x07");
  REQUIRE(res.code() != 0);
}
<commit_msg>Add tests for C++ API Hash table and Stack table<commit_after>/*
 * Copyright (c) 2017 Politecnico di Torino
 *
 * 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 <linux/version.h>
#include <unistd.h>
#include <string>

#include "BPF.h"
#include "catch.hpp"

TEST_CASE("test bpf table", "[bpf_table]") {
  const std::string BPF_PROGRAM = R"(
    BPF_TABLE("hash", int, int, myhash, 128);
  )";

  ebpf::BPF *bpf(new ebpf::BPF);
  ebpf::StatusTuple res(0);
  res = bpf->init(BPF_PROGRAM);
  REQUIRE(res.code() == 0);

  ebpf::BPFTable t = bpf->get_table("myhash");

  // update element
  std::string value;
  res = t.update_value("0x07", "0x42");
  REQUIRE(res.code() == 0);
  res = t.get_value("0x07", value);
  REQUIRE(res.code() == 0);
  REQUIRE(value == "0x42");

  // update another element
  res = t.update_value("0x11", "0x777");
  REQUIRE(res.code() == 0);
  res = t.get_value("0x11", value);
  REQUIRE(res.code() == 0);
  REQUIRE(value == "0x777");

  // remove value
  res = t.remove_value("0x11");
  REQUIRE(res.code() == 0);
  res = t.get_value("0x11", value);
  REQUIRE(res.code() != 0);

  // delete bpf_module, call to key/leaf printf/scanf must fail
  delete bpf;

  res = t.update_value("0x07", "0x42");
  REQUIRE(res.code() != 0);

  res = t.get_value("0x07", value);
  REQUIRE(res.code() != 0);

  res = t.remove_value("0x07");
  REQUIRE(res.code() != 0);
}

TEST_CASE("test bpf hash table", "[bpf_hash_table]") {
  const std::string BPF_PROGRAM = R"(
    BPF_HASH(myhash, int, int, 128);
  )";

  ebpf::BPF bpf;
  ebpf::StatusTuple res(0);
  res = bpf.init(BPF_PROGRAM);
  REQUIRE(res.code() == 0);

  auto t = bpf.get_hash_table<int, int>("myhash");

  int key, value;

  // updaate element
  key = 0x08;
  value = 0x43;
  res = t.update_value(key, value);
  REQUIRE(res.code() == 0);
  REQUIRE(t[key] == value);

  // update another element
  key = 0x12;
  value = 0x778;
  res = t.update_value(key, value);
  REQUIRE(res.code() == 0);
  key = 0x31;
  value = 0x123;
  res = t.update_value(key, value);
  REQUIRE(res.code() == 0);
  key = 0x12;
  value = 0;
  res = t.get_value(key, value);
  REQUIRE(res.code() == 0);
  REQUIRE(value == 0x778);

  // remove value and dump table
  key = 0x12;
  res = t.remove_value(key);
  REQUIRE(res.code() == 0);
  auto values = t.get_table_offline();
  REQUIRE(values.size() == 2);

  // clear table
  res = t.clear_table_non_atomic();
  REQUIRE(res.code() == 0);
  values = t.get_table_offline();
  REQUIRE(values.size() == 0);
}

TEST_CASE("test bpf stack table", "[bpf_stack_table]") {
#if LINUX_VERSION_CODE >= KERNEL_VERSION(4, 6, 0)
  const std::string BPF_PROGRAM = R"(
    BPF_HASH(id, int, int, 1);
    BPF_STACK_TRACE(stack_traces, 8);

    int on_sys_getuid(void *ctx) {
      int stack_id = stack_traces.get_stackid(ctx, BPF_F_REUSE_STACKID);
      int zero = 0, *val;
      val = id.lookup_or_init(&zero, &stack_id);
      (*val) = stack_id;
    }
  )";

  ebpf::BPF bpf;
  ebpf::StatusTuple res(0);
  res = bpf.init(BPF_PROGRAM);
  REQUIRE(res.code() == 0);
  res = bpf.attach_kprobe("sys_getuid", "on_sys_getuid");
  REQUIRE(res.code() == 0);
  REQUIRE(getuid() >= 0);
  res = bpf.detach_kprobe("sys_getuid");
  REQUIRE(res.code() == 0);

  auto id = bpf.get_hash_table<int, int>("id");
  auto stack_traces = bpf.get_stack_table("stack_traces");

  int stack_id = id[0];
  REQUIRE(stack_id >= 0);

  auto addrs = stack_traces.get_stack_addr(stack_id);
  auto symbols = stack_traces.get_stack_symbol(stack_id, -1);
  REQUIRE(addrs.size() > 0);
  REQUIRE(addrs.size() == symbols.size());
  bool found = false;
  for (const auto &symbol : symbols)
    if (symbol.find("sys_getuid") != std::string::npos) {
      found = true;
      break;
    }
  REQUIRE(found);

  stack_traces.clear_table_non_atomic();
  addrs = stack_traces.get_stack_addr(stack_id);
  REQUIRE(addrs.size() == 0);
#endif
}
<|endoftext|>


<commit_before>// Copyright 2017 - 2018 Code 4 Game, Org. All Rights Reserved.

#include "glTFForUE4PrivatePCH.h"
#include "glTFForUE4Module.h"

#include "ModuleManager.h"

#define LOCTEXT_NAMESPACE "FglTFForUE4Module"

class FglTFForUE4Module : public IglTFForUE4Module
{
public:
    /** IModuleInterface implementation */
    virtual void StartupModule()
    {
        //
    }

    virtual void ShutdownModule()
    {
        //
    }
};

#undef LOCTEXT_NAMESPACE

IMPLEMENT_MODULE(FglTFForUE4Module, glTFForUE4)
<commit_msg>fix some errors for ue4.20 again<commit_after>// Copyright 2017 - 2018 Code 4 Game, Org. All Rights Reserved.

#include "glTFForUE4PrivatePCH.h"
#include "glTFForUE4Module.h"

#include "Modules/ModuleManager.h"

#define LOCTEXT_NAMESPACE "FglTFForUE4Module"

class FglTFForUE4Module : public IglTFForUE4Module
{
public:
    /** IModuleInterface implementation */
    virtual void StartupModule()
    {
        //
    }

    virtual void ShutdownModule()
    {
        //
    }
};

#undef LOCTEXT_NAMESPACE

IMPLEMENT_MODULE(FglTFForUE4Module, glTFForUE4)
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2003, 2006, 2008, 2009, 2010, 2011 Apple Inc. All rights reserved.
 * Copyright (C) 2008 Holger Hans Peter Freyther
 * Copyright (C) 2014 Google Inc. All rights reserved.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 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
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public License
 * along with this library; see the file COPYING.LIB.  If not, write to
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301, USA.
 *
 */

#include "config.h"
#include "platform/fonts/shaping/SimpleShaper.h"

#include "platform/fonts/Character.h"
#include "platform/fonts/Font.h"
#include "platform/fonts/GlyphBuffer.h"
#include "platform/fonts/Latin1TextIterator.h"
#include "platform/fonts/SimpleFontData.h"
#include "platform/text/SurrogatePairAwareTextIterator.h"
#include "wtf/MathExtras.h"

using namespace WTF;
using namespace Unicode;

namespace blink {

SimpleShaper::SimpleShaper(const Font* font, const TextRun& run,
    HashSet<const SimpleFontData*>* fallbackFonts, GlyphBounds* bounds,
    bool forTextEmphasis)
    : m_font(font)
    , m_run(run)
    , m_currentCharacter(0)
    , m_runWidthSoFar(0)
    , m_isAfterExpansion(!run.allowsLeadingExpansion())
    , m_fallbackFonts(fallbackFonts)
    , m_bounds(bounds)
    , m_forTextEmphasis(forTextEmphasis)
{
    // If the padding is non-zero, count the number of spaces in the run
    // and divide that by the padding for per space addition.
    m_expansion = m_run.expansion();
    if (!m_expansion) {
        m_expansionPerOpportunity = 0;
    } else {
        bool isAfterExpansion = m_isAfterExpansion;
        unsigned expansionOpportunityCount = m_run.is8Bit() ? Character::expansionOpportunityCount(m_run.characters8(), m_run.length(), m_run.direction(), isAfterExpansion, m_run.textJustify()) : Character::expansionOpportunityCount(m_run.characters16(), m_run.length(), m_run.direction(), isAfterExpansion, m_run.textJustify());
        if (isAfterExpansion && !m_run.allowsTrailingExpansion())
            expansionOpportunityCount--;

        if (!expansionOpportunityCount)
            m_expansionPerOpportunity = 0;
        else
            m_expansionPerOpportunity = m_expansion / expansionOpportunityCount;
    }
}

GlyphData SimpleShaper::glyphDataForCharacter(CharacterData& charData, bool normalizeSpace)
{
    ASSERT(m_font);
    return m_font->glyphDataForCharacter(charData.character, m_run.rtl(), normalizeSpace);
}

float SimpleShaper::characterWidth(UChar32 character, const GlyphData& glyphData) const
{
    const SimpleFontData* fontData = glyphData.fontData;
    ASSERT(fontData);

    if (UNLIKELY(character == '\t' && m_run.allowTabs()))
        return m_font->tabWidth(*fontData, m_run.tabSize(), m_run.xPos() + m_runWidthSoFar);

    float width = fontData->widthForGlyph(glyphData.glyph);

    // SVG uses horizontalGlyphStretch(), when textLength is used to stretch/squeeze text.
    if (UNLIKELY(m_run.horizontalGlyphStretch() != 1))
        width *= m_run.horizontalGlyphStretch();

    return width;
}

void SimpleShaper::cacheFallbackFont(const SimpleFontData* fontData,
    const SimpleFontData* primaryFont)
{
    if (fontData == primaryFont)
        return;

    m_fallbackFonts->add(fontData);
}

float SimpleShaper::adjustSpacing(float width, const CharacterData& charData)
{
    // Account for letter-spacing.
    if (width)
        width += m_font->fontDescription().letterSpacing();

    bool isExpansionOpportunity = Character::treatAsSpace(charData.character) || (m_run.textJustify() == TextJustifyDistribute);
    if (isExpansionOpportunity || (m_run.textJustify() == TextJustifyAuto && Character::isCJKIdeographOrSymbol(charData.character))) {
        // Distribute the run's total expansion evenly over all expansion opportunities in the run.
        if (m_expansion) {
            if (!isExpansionOpportunity && !m_isAfterExpansion) {
                // Take the expansion opportunity before this ideograph.
                m_expansion -= m_expansionPerOpportunity;
                m_runWidthSoFar += m_expansionPerOpportunity;
            }
            if (m_run.allowsTrailingExpansion()
                || (m_run.ltr() && charData.characterOffset + charData.clusterLength < static_cast<size_t>(m_run.length()))
                || (m_run.rtl() && charData.characterOffset)) {
                m_expansion -= m_expansionPerOpportunity;
                width += m_expansionPerOpportunity;
                m_isAfterExpansion = true;
            }
        } else {
            m_isAfterExpansion = false;
        }

        // Account for word spacing.
        // We apply additional space between "words" by adding width to the space character.
        if (isExpansionOpportunity && (charData.character != '\t' || !m_run.allowTabs())
            && (charData.characterOffset || charData.character == noBreakSpace)
            && m_font->fontDescription().wordSpacing()) {
            width += m_font->fontDescription().wordSpacing();
        }
    } else {
        m_isAfterExpansion = false;
    }

    return width;
}

void SimpleShaper::updateGlyphBounds(const GlyphData& glyphData, float width, bool firstCharacter)
{
    ASSERT(glyphData.fontData);
    FloatRect bounds = glyphData.fontData->boundsForGlyph(glyphData.glyph);

    ASSERT(m_bounds);
    if (firstCharacter)
        m_bounds->firstGlyphOverflow = std::max<float>(0, -bounds.x());
    m_bounds->lastGlyphOverflow = std::max<float>(0, bounds.maxX() - width);
    m_bounds->maxGlyphBoundingBoxY = std::max(m_bounds->maxGlyphBoundingBoxY, bounds.maxY());
    m_bounds->minGlyphBoundingBoxY = std::min(m_bounds->minGlyphBoundingBoxY, bounds.y());
}

template <typename TextIterator>
unsigned SimpleShaper::advanceInternal(TextIterator& textIterator, GlyphBuffer* glyphBuffer)
{
    bool hasExtraSpacing = (m_font->fontDescription().letterSpacing() || m_font->fontDescription().wordSpacing() || m_expansion)
        && !m_run.spacingDisabled();

    const SimpleFontData* primaryFont = m_font->primaryFont();
    const SimpleFontData* lastFontData = primaryFont;
    bool normalizeSpace = m_run.normalizeSpace();

    CharacterData charData;
    while (textIterator.consume(charData.character, charData.clusterLength)) {
        charData.characterOffset = textIterator.currentCharacter();

        GlyphData glyphData = glyphDataForCharacter(charData, normalizeSpace);

        // Some fonts do not have a glyph for zero-width-space,
        // in that case use the space character and override the width.
        float width;
        bool spaceUsedAsZeroWidthSpace = false;
        if (!glyphData.glyph && Character::treatAsZeroWidthSpaceInComplexScript(charData.character)) {
            charData.character = space;
            glyphData = glyphDataForCharacter(charData);
            width = 0;
            spaceUsedAsZeroWidthSpace = true;
        } else {
            width = characterWidth(charData.character, glyphData);
        }

        Glyph glyph = glyphData.glyph;
        const SimpleFontData* fontData = glyphData.fontData;
        ASSERT(fontData);

        if (m_fallbackFonts && lastFontData != fontData && width) {
            lastFontData = fontData;
            cacheFallbackFont(fontData, primaryFont);
        }

        if (hasExtraSpacing && !spaceUsedAsZeroWidthSpace)
            width = adjustSpacing(width, charData);

        if (m_bounds)
            updateGlyphBounds(glyphData, width, !charData.characterOffset);

        if (m_forTextEmphasis) {
            if (!Character::canReceiveTextEmphasis(charData.character))
                glyph = 0;

            // The emphasis code expects mid-glyph offsets.
            width /= 2;
            m_runWidthSoFar += width;
        }

        if (glyphBuffer)
            glyphBuffer->add(glyph, fontData, m_runWidthSoFar);

        // Advance past the character we just dealt with.
        textIterator.advance(charData.clusterLength);
        m_runWidthSoFar += width;
    }

    unsigned consumedCharacters = textIterator.currentCharacter() - m_currentCharacter;
    m_currentCharacter = textIterator.currentCharacter();

    return consumedCharacters;
}

unsigned SimpleShaper::advance(unsigned offset, GlyphBuffer* glyphBuffer)
{
    unsigned length = m_run.length();

    if (offset > length)
        offset = length;

    if (m_currentCharacter >= offset)
        return 0;

    if (m_run.is8Bit()) {
        Latin1TextIterator textIterator(m_run.data8(m_currentCharacter), m_currentCharacter, offset, length);
        return advanceInternal(textIterator, glyphBuffer);
    }

    SurrogatePairAwareTextIterator textIterator(m_run.data16(m_currentCharacter), m_currentCharacter, offset, length);
    return advanceInternal(textIterator, glyphBuffer);
}

bool SimpleShaper::advanceOneCharacter(float& width)
{
    float initialWidth = m_runWidthSoFar;

    if (!advance(m_currentCharacter + 1))
        return false;

    width = m_runWidthSoFar - initialWidth;
    return true;
}

} // namespace blink
<commit_msg>At some places Blink is using old style character string notation for Unicode. Replacing those with defined Character Names/Unicodes. Also using local variable for multiple similar calls.<commit_after>/*
 * Copyright (C) 2003, 2006, 2008, 2009, 2010, 2011 Apple Inc. All rights reserved.
 * Copyright (C) 2008 Holger Hans Peter Freyther
 * Copyright (C) 2014 Google Inc. All rights reserved.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 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
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public License
 * along with this library; see the file COPYING.LIB.  If not, write to
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301, USA.
 *
 */

#include "config.h"
#include "platform/fonts/shaping/SimpleShaper.h"

#include "platform/fonts/Character.h"
#include "platform/fonts/Font.h"
#include "platform/fonts/GlyphBuffer.h"
#include "platform/fonts/Latin1TextIterator.h"
#include "platform/fonts/SimpleFontData.h"
#include "platform/text/SurrogatePairAwareTextIterator.h"
#include "wtf/MathExtras.h"
#include "wtf/unicode/CharacterNames.h"

using namespace WTF;
using namespace Unicode;

namespace blink {

SimpleShaper::SimpleShaper(const Font* font, const TextRun& run,
    HashSet<const SimpleFontData*>* fallbackFonts, GlyphBounds* bounds,
    bool forTextEmphasis)
    : m_font(font)
    , m_run(run)
    , m_currentCharacter(0)
    , m_runWidthSoFar(0)
    , m_isAfterExpansion(!run.allowsLeadingExpansion())
    , m_fallbackFonts(fallbackFonts)
    , m_bounds(bounds)
    , m_forTextEmphasis(forTextEmphasis)
{
    // If the padding is non-zero, count the number of spaces in the run
    // and divide that by the padding for per space addition.
    m_expansion = m_run.expansion();
    if (!m_expansion) {
        m_expansionPerOpportunity = 0;
    } else {
        bool isAfterExpansion = m_isAfterExpansion;
        unsigned expansionOpportunityCount = m_run.is8Bit() ? Character::expansionOpportunityCount(m_run.characters8(), m_run.length(), m_run.direction(), isAfterExpansion, m_run.textJustify()) : Character::expansionOpportunityCount(m_run.characters16(), m_run.length(), m_run.direction(), isAfterExpansion, m_run.textJustify());
        if (isAfterExpansion && !m_run.allowsTrailingExpansion())
            expansionOpportunityCount--;

        if (!expansionOpportunityCount)
            m_expansionPerOpportunity = 0;
        else
            m_expansionPerOpportunity = m_expansion / expansionOpportunityCount;
    }
}

GlyphData SimpleShaper::glyphDataForCharacter(CharacterData& charData, bool normalizeSpace)
{
    ASSERT(m_font);
    return m_font->glyphDataForCharacter(charData.character, m_run.rtl(), normalizeSpace);
}

float SimpleShaper::characterWidth(UChar32 character, const GlyphData& glyphData) const
{
    const SimpleFontData* fontData = glyphData.fontData;
    ASSERT(fontData);

    if (UNLIKELY(character == characterTabulation && m_run.allowTabs()))
        return m_font->tabWidth(*fontData, m_run.tabSize(), m_run.xPos() + m_runWidthSoFar);

    float width = fontData->widthForGlyph(glyphData.glyph);

    // SVG uses horizontalGlyphStretch(), when textLength is used to stretch/squeeze text.
    if (UNLIKELY(m_run.horizontalGlyphStretch() != 1))
        width *= m_run.horizontalGlyphStretch();

    return width;
}

void SimpleShaper::cacheFallbackFont(const SimpleFontData* fontData,
    const SimpleFontData* primaryFont)
{
    if (fontData == primaryFont)
        return;

    m_fallbackFonts->add(fontData);
}

float SimpleShaper::adjustSpacing(float width, const CharacterData& charData)
{
    // Account for letter-spacing.
    if (width)
        width += m_font->fontDescription().letterSpacing();

    bool isExpansionOpportunity = Character::treatAsSpace(charData.character) || (m_run.textJustify() == TextJustifyDistribute);
    if (isExpansionOpportunity || (m_run.textJustify() == TextJustifyAuto && Character::isCJKIdeographOrSymbol(charData.character))) {
        // Distribute the run's total expansion evenly over all expansion opportunities in the run.
        if (m_expansion) {
            if (!isExpansionOpportunity && !m_isAfterExpansion) {
                // Take the expansion opportunity before this ideograph.
                m_expansion -= m_expansionPerOpportunity;
                m_runWidthSoFar += m_expansionPerOpportunity;
            }
            if (m_run.allowsTrailingExpansion()
                || (m_run.ltr() && charData.characterOffset + charData.clusterLength < static_cast<size_t>(m_run.length()))
                || (m_run.rtl() && charData.characterOffset)) {
                m_expansion -= m_expansionPerOpportunity;
                width += m_expansionPerOpportunity;
                m_isAfterExpansion = true;
            }
        } else {
            m_isAfterExpansion = false;
        }

        // Account for word spacing.
        // We apply additional space between "words" by adding width to the space character.
        if (isExpansionOpportunity && (charData.character != characterTabulation || !m_run.allowTabs())
            && (charData.characterOffset || charData.character == noBreakSpace)
            && m_font->fontDescription().wordSpacing()) {
            width += m_font->fontDescription().wordSpacing();
        }
    } else {
        m_isAfterExpansion = false;
    }

    return width;
}

void SimpleShaper::updateGlyphBounds(const GlyphData& glyphData, float width, bool firstCharacter)
{
    ASSERT(glyphData.fontData);
    FloatRect bounds = glyphData.fontData->boundsForGlyph(glyphData.glyph);

    ASSERT(m_bounds);
    if (firstCharacter)
        m_bounds->firstGlyphOverflow = std::max<float>(0, -bounds.x());
    m_bounds->lastGlyphOverflow = std::max<float>(0, bounds.maxX() - width);
    m_bounds->maxGlyphBoundingBoxY = std::max(m_bounds->maxGlyphBoundingBoxY, bounds.maxY());
    m_bounds->minGlyphBoundingBoxY = std::min(m_bounds->minGlyphBoundingBoxY, bounds.y());
}

template <typename TextIterator>
unsigned SimpleShaper::advanceInternal(TextIterator& textIterator, GlyphBuffer* glyphBuffer)
{
    bool hasExtraSpacing = (m_font->fontDescription().letterSpacing() || m_font->fontDescription().wordSpacing() || m_expansion)
        && !m_run.spacingDisabled();

    const SimpleFontData* primaryFont = m_font->primaryFont();
    const SimpleFontData* lastFontData = primaryFont;
    bool normalizeSpace = m_run.normalizeSpace();

    CharacterData charData;
    while (textIterator.consume(charData.character, charData.clusterLength)) {
        charData.characterOffset = textIterator.currentCharacter();

        GlyphData glyphData = glyphDataForCharacter(charData, normalizeSpace);

        // Some fonts do not have a glyph for zero-width-space,
        // in that case use the space character and override the width.
        float width;
        bool spaceUsedAsZeroWidthSpace = false;
        if (!glyphData.glyph && Character::treatAsZeroWidthSpaceInComplexScript(charData.character)) {
            charData.character = space;
            glyphData = glyphDataForCharacter(charData);
            width = 0;
            spaceUsedAsZeroWidthSpace = true;
        } else {
            width = characterWidth(charData.character, glyphData);
        }

        Glyph glyph = glyphData.glyph;
        const SimpleFontData* fontData = glyphData.fontData;
        ASSERT(fontData);

        if (m_fallbackFonts && lastFontData != fontData && width) {
            lastFontData = fontData;
            cacheFallbackFont(fontData, primaryFont);
        }

        if (hasExtraSpacing && !spaceUsedAsZeroWidthSpace)
            width = adjustSpacing(width, charData);

        if (m_bounds)
            updateGlyphBounds(glyphData, width, !charData.characterOffset);

        if (m_forTextEmphasis) {
            if (!Character::canReceiveTextEmphasis(charData.character))
                glyph = 0;

            // The emphasis code expects mid-glyph offsets.
            width /= 2;
            m_runWidthSoFar += width;
        }

        if (glyphBuffer)
            glyphBuffer->add(glyph, fontData, m_runWidthSoFar);

        // Advance past the character we just dealt with.
        textIterator.advance(charData.clusterLength);
        m_runWidthSoFar += width;
    }

    unsigned consumedCharacters = textIterator.currentCharacter() - m_currentCharacter;
    m_currentCharacter = textIterator.currentCharacter();

    return consumedCharacters;
}

unsigned SimpleShaper::advance(unsigned offset, GlyphBuffer* glyphBuffer)
{
    unsigned length = m_run.length();

    if (offset > length)
        offset = length;

    if (m_currentCharacter >= offset)
        return 0;

    if (m_run.is8Bit()) {
        Latin1TextIterator textIterator(m_run.data8(m_currentCharacter), m_currentCharacter, offset, length);
        return advanceInternal(textIterator, glyphBuffer);
    }

    SurrogatePairAwareTextIterator textIterator(m_run.data16(m_currentCharacter), m_currentCharacter, offset, length);
    return advanceInternal(textIterator, glyphBuffer);
}

bool SimpleShaper::advanceOneCharacter(float& width)
{
    float initialWidth = m_runWidthSoFar;

    if (!advance(m_currentCharacter + 1))
        return false;

    width = m_runWidthSoFar - initialWidth;
    return true;
}

} // namespace blink
<|endoftext|>


<commit_before>/*
 * server_test.cpp
 *
 *  Created on: Jan 16, 2013
 *      Author: mfleder
 */

#include <stdio.h>
#include <lcm/lcm-cpp.hpp>
#include <boost/shared_ptr.hpp>
#include "affordance/AffordanceServer.h"
#include "affordance/AffordanceUpWrapper.h"
#include "affordance/AffordanceState.h"
#include <path_util/path_util.h>
#include <iostream>

using namespace boost;
using namespace std;
using namespace affordance;

/**populates the server w/ a bunch of affordances*/
void runPopulate(const shared_ptr<lcm::LCM> lcm)
{
    AffordanceUpWrapper wrapper(lcm);

    const int mapId = 0;
    int uniqueObjId = 0;

    //sphere
    AffordanceState sphere(uniqueObjId++, mapId,
                           KDL::Frame(KDL::Vector(-0.5, -0.5, 0.0)),
                           Eigen::Vector3f(1.0, 0.0, 1.0));   //color
    sphere._params[AffordanceState::RADIUS_NAME] = 0.125;
    sphere.setType(AffordanceState::SPHERE);
    wrapper.addNewlyFittedAffordance(sphere);

    //box
    float box_height = 0.01;
    AffordanceState box(uniqueObjId++, mapId,
                        KDL::Frame(KDL::Vector(0.0, 0.0, -box_height / 2.0)),
                        Eigen::Vector3f(0.75, 0.75, 0.0)); //color
    box._params[AffordanceState::LENGTH_NAME] = 100;
    box._params[AffordanceState::WIDTH_NAME]  = 100;
    box._params[AffordanceState::HEIGHT_NAME] = box_height;
    box.setType(AffordanceState::BOX);
    wrapper.addNewlyFittedAffordance(box);

    //cylinder
    AffordanceState cylinder(uniqueObjId++, mapId,
                             KDL::Frame(KDL::Vector(0.0, 1.0, 0.0)),
                             Eigen::Vector3f(0.0, 1.0, 1.0)); //color
    cylinder._params[AffordanceState::RADIUS_NAME] = 0.25;
    cylinder._params[AffordanceState::LENGTH_NAME] = 0.25;
    cylinder.setType(AffordanceState::CYLINDER);
    wrapper.addNewlyFittedAffordance(cylinder);

    //==car
    string carUrdfFName = getModelsPath() + string("/mit_gazebo_objects/mit_simple_vehicle/model.urdf");
    cout << "using card urdf = " << carUrdfFName << endl;

    vector<AffPtr> carAffs;
    AffordanceState::getBoxesCylindersSpheres(carUrdfFName, carAffs);
    for(uint i = 0; i < carAffs.size(); i++)
      wrapper.addNewlyFittedAffordance(*carAffs[i]);

    cout << "\n added " << carAffs.size() << " car affordances" << endl;

    //wait a few second so we get an update from the server
    boost::this_thread::sleep(boost::posix_time::seconds(3));

    //===now loop and printout periodically
    boost::posix_time::seconds sleepTime(60); //update (printout) every 60 seconds

    while (true)
    {
        //cout << "\n\n===" << j << endl;
        cout << wrapper << endl;
        boost::this_thread::sleep(sleepTime); //======sleep

        //======modify server
        // user code
        //===finished  modifications
    }
}

int main(int argc, char **argv)
{
    shared_ptr<lcm::LCM> theLcm(new lcm::LCM());

    if (!theLcm->good())
    {
        cerr << "Cannot create lcm object" << endl;
        return -1;
    }

    //create the server
    AffordanceServer s(theLcm);

    //thread will add to the affordance server
    //and possibly make changes over time
    boost::thread populateThread = boost::thread(runPopulate, theLcm);

    //lcm loop
    cout << "\nstarting lcm loop" << endl;

    while (0 == theLcm->handle())
    {
        ;
    }

    return 0;
}
<commit_msg>Switches demo_populate_affordance_server to use mit_vehicle rather than mit_simple_vehicle.<commit_after>/*
 * server_test.cpp
 *
 *  Created on: Jan 16, 2013
 *      Author: mfleder
 */

#include <stdio.h>
#include <lcm/lcm-cpp.hpp>
#include <boost/shared_ptr.hpp>
#include "affordance/AffordanceServer.h"
#include "affordance/AffordanceUpWrapper.h"
#include "affordance/AffordanceState.h"
#include <path_util/path_util.h>
#include <iostream>

using namespace boost;
using namespace std;
using namespace affordance;

/**populates the server w/ a bunch of affordances*/
void runPopulate(const shared_ptr<lcm::LCM> lcm)
{
    AffordanceUpWrapper wrapper(lcm);

    const int mapId = 0;
    int uniqueObjId = 0;

    //sphere
    AffordanceState sphere(uniqueObjId++, mapId,
                           KDL::Frame(KDL::Vector(-0.5, -0.5, 0.0)),
                           Eigen::Vector3f(1.0, 0.0, 1.0));   //color
    sphere._params[AffordanceState::RADIUS_NAME] = 0.125;
    sphere.setType(AffordanceState::SPHERE);
    wrapper.addNewlyFittedAffordance(sphere);

    //box
    float box_height = 0.01;
    AffordanceState box(uniqueObjId++, mapId,
                        KDL::Frame(KDL::Vector(0.0, 0.0, -box_height / 2.0)),
                        Eigen::Vector3f(0.75, 0.75, 0.0)); //color
    box._params[AffordanceState::LENGTH_NAME] = 100;
    box._params[AffordanceState::WIDTH_NAME]  = 100;
    box._params[AffordanceState::HEIGHT_NAME] = box_height;
    box.setType(AffordanceState::BOX);
    wrapper.addNewlyFittedAffordance(box);

    //cylinder
    AffordanceState cylinder(uniqueObjId++, mapId,
                             KDL::Frame(KDL::Vector(0.0, 1.0, 0.0)),
                             Eigen::Vector3f(0.0, 1.0, 1.0)); //color
    cylinder._params[AffordanceState::RADIUS_NAME] = 0.25;
    cylinder._params[AffordanceState::LENGTH_NAME] = 0.25;
    cylinder.setType(AffordanceState::CYLINDER);
    wrapper.addNewlyFittedAffordance(cylinder);

    //==car
    string carUrdfFName = getModelsPath() + string("/mit_gazebo_objects/mit_vehicle/model_drake.urdf");
    cout << "using card urdf = " << carUrdfFName << endl;

    vector<AffPtr> carAffs;
    AffordanceState::getBoxesCylindersSpheres(carUrdfFName, carAffs);
    for(uint i = 0; i < carAffs.size(); i++)
      wrapper.addNewlyFittedAffordance(*carAffs[i]);

    cout << "\n added " << carAffs.size() << " car affordances" << endl;

    //wait a few second so we get an update from the server
    boost::this_thread::sleep(boost::posix_time::seconds(3));

    //===now loop and printout periodically
    boost::posix_time::seconds sleepTime(60); //update (printout) every 60 seconds

    while (true)
    {
        //cout << "\n\n===" << j << endl;
        cout << wrapper << endl;
        boost::this_thread::sleep(sleepTime); //======sleep

        //======modify server
        // user code
        //===finished  modifications
    }
}

int main(int argc, char **argv)
{
    shared_ptr<lcm::LCM> theLcm(new lcm::LCM());

    if (!theLcm->good())
    {
        cerr << "Cannot create lcm object" << endl;
        return -1;
    }

    //create the server
    AffordanceServer s(theLcm);

    //thread will add to the affordance server
    //and possibly make changes over time
    boost::thread populateThread = boost::thread(runPopulate, theLcm);

    //lcm loop
    cout << "\nstarting lcm loop" << endl;

    while (0 == theLcm->handle())
    {
        ;
    }

    return 0;
}
<|endoftext|>


<commit_before>
#include "statusbar.h"

#include <QPainter>
#include <QX11Info>
#include <QTouchEvent>
#include <QDBusInterface>
#include <QDBusConnection>
#include <QGraphicsScene>
#include <QGraphicsView>
#include <QTimer>

#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/Xatom.h>
#include <X11/extensions/Xcomposite.h>
#include <X11/extensions/Xdamage.h>

// Fetches the shared status bar pixmap
static QPixmap fetchSharedPixmap()
{
    static Atom propertyWindowAtom = 0;
    static Atom pixmapHandleAtom = 0;

    // This contains the statusbar window
    if (propertyWindowAtom == 0)
        propertyWindowAtom = XInternAtom(QX11Info::display(), "_MEEGOTOUCH_STATUSBAR_PROPERTY_WINDOW", False);

    // This contains the shared pixmap
    if (pixmapHandleAtom == 0)
        pixmapHandleAtom = XInternAtom(QX11Info::display(), "_MEEGOTOUCH_STATUSBAR_PIXMAP", False);

    // Some common variables
    Atom actualType = 0;
    int actualFormat = 0;
    unsigned long nitems = 0;
    unsigned long bytesAfter = 0;
    unsigned char *data = 0;
    int status = 0;

    // Getting the status bar window
    status = XGetWindowProperty(QX11Info::display(),
                                QX11Info::appRootWindow(),
                                propertyWindowAtom,
                                0,
                                1,
                                False,
                                XA_WINDOW,
                                &actualType,
                                &actualFormat,
                                &nitems,
                                &bytesAfter,
                                &data);

    Window window(0);
    if (status == Success && data != None)
    {
        window = *(Window *)data;
        XFree(data);
    }

    // Getting the shared pixmap from the status bar window
    status = XGetWindowProperty(QX11Info::display(),
                                window,
                                pixmapHandleAtom,
                                0,
                                1,
                                False,
                                XA_PIXMAP,
                                &actualType,
                                &actualFormat,
                                &nitems,
                                &bytesAfter,
                                &data);

    QPixmap result;

    if (status == Success)
    {
        quint32 handle = *((unsigned long*)data);

        if (actualType == XA_PIXMAP && actualFormat == 32 && handle != 0)
        {
            result = QPixmap::fromX11Pixmap(handle, QPixmap::ExplicitlyShared);
            // TODO: we should register for damage events for this pixmap and repaint when they arrive
            //       (perhaps create an XEventListener fromt his class too?)
        }

        XFree(data);
    }

    return result;
}

StatusBar::StatusBar(QDeclarativeItem *parent) :
    QDeclarativeItem(parent)
{
    setFlag(QGraphicsItem::ItemHasNoContents, false);
    setAcceptTouchEvents(true);
    setImplicitHeight(36);
    QTimer::singleShot(3000, this, SLOT(initializeStatusBar()));
}

void StatusBar::initializeStatusBar()
{
    _sharedPixmap = fetchSharedPixmap();
    setImplicitHeight(_sharedPixmap.height() / 2);
    updateXThings();
}

void StatusBar::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
    Q_UNUSED(option)
    Q_UNUSED(widget)

    if (_sharedPixmap.isNull())
    {
        qDebug() << "StatusBar: the shared pixmap is null, can't draw it!";
        return;
    }

    // Info: The shared pixmap contains both the portrait and the landscape mode status bars below each other.
    //       Landscape is on top, portrait on bottom. They have the same height.
    //       All we need is check the orientation here and set the source rect accordingly.

    painter->drawPixmap(QRectF(0, 0, width(), height()), _sharedPixmap, QRectF(0, _isPortrait ? height() : 0, width(), height()));
}

bool StatusBar::isPortrait() const
{
    return _isPortrait;
}

void StatusBar::updateXThings()
{
    // If the pixmap is null, don't bother
    if (_sharedPixmap.isNull())
        return;

    // Statusbar rect
    QPointF p = mapToScene(0, 0);
    unsigned long data[4] = { (int)p.x(), (int)p.y(), width(), height() };
    qDebug() << "statusbar geo:" << (int)p.x() << (int)p.y() << width() << height();

    // Orientation angle
    int angle = isPortrait() ? 270 : 0;
    qDebug() << "orientation angle:" << angle;

    // Stuff for X
    QWidget *activeWindow = this->scene()->views().at(0);
    Display *dpy = QX11Info::display();

    // Setting the status bar geometry atom (probably not necessary here)
    Atom statusBarGeometryAtom = XInternAtom(dpy, "_MEEGOTOUCH_MSTATUSBAR_GEOMETRY", False);
    XChangeProperty(dpy, activeWindow->effectiveWinId(), statusBarGeometryAtom, XA_CARDINAL, 32, PropModeReplace, (unsigned char*)data, 4);

    // Setting the orientation angle atom (sysuid uses this to determine what orientation it should draw itself)
    Atom orientationAngleAtom = XInternAtom(dpy, "_MEEGOTOUCH_ORIENTATION_ANGLE", False);
    XChangeProperty(dpy, activeWindow->effectiveWinId(), orientationAngleAtom, XA_CARDINAL, 32, PropModeReplace, (unsigned char*)&angle, 1);
}

void StatusBar::setIsPortrait(bool value)
{
    // If there is no change, don't bother
    if (_isPortrait == value)
        return;

    _isPortrait = value;
    updateXThings();

    emit isPortraitChanged();
}

bool StatusBar::sceneEvent(QEvent *event)
{
    if (event->type() == QEvent::TouchBegin)
    {
        return true;
    }
    if (event->type() == QEvent::TouchEnd)
    {
        qDebug() << "opening status menu";

        QDBusInterface interface("com.meego.core.MStatusIndicatorMenu",
                                 "/statusindicatormenu",
                                 "com.meego.core.MStatusIndicatorMenu",
                                 QDBusConnection::sessionBus());

        interface.call(QDBus::NoBlock, "open");

        return true;
    }

    return false;
}
<commit_msg>Status bar: calling update() after getting the shared pixmap<commit_after>
#include "statusbar.h"

#include <QPainter>
#include <QX11Info>
#include <QTouchEvent>
#include <QDBusInterface>
#include <QDBusConnection>
#include <QGraphicsScene>
#include <QGraphicsView>
#include <QTimer>

#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/Xatom.h>
#include <X11/extensions/Xcomposite.h>
#include <X11/extensions/Xdamage.h>

// Fetches the shared status bar pixmap
static QPixmap fetchSharedPixmap()
{
    static Atom propertyWindowAtom = 0;
    static Atom pixmapHandleAtom = 0;

    // This contains the statusbar window
    if (propertyWindowAtom == 0)
        propertyWindowAtom = XInternAtom(QX11Info::display(), "_MEEGOTOUCH_STATUSBAR_PROPERTY_WINDOW", False);

    // This contains the shared pixmap
    if (pixmapHandleAtom == 0)
        pixmapHandleAtom = XInternAtom(QX11Info::display(), "_MEEGOTOUCH_STATUSBAR_PIXMAP", False);

    // Some common variables
    Atom actualType = 0;
    int actualFormat = 0;
    unsigned long nitems = 0;
    unsigned long bytesAfter = 0;
    unsigned char *data = 0;
    int status = 0;

    // Getting the status bar window
    status = XGetWindowProperty(QX11Info::display(),
                                QX11Info::appRootWindow(),
                                propertyWindowAtom,
                                0,
                                1,
                                False,
                                XA_WINDOW,
                                &actualType,
                                &actualFormat,
                                &nitems,
                                &bytesAfter,
                                &data);

    Window window(0);
    if (status == Success && data != None)
    {
        window = *(Window *)data;
        XFree(data);
    }

    // Getting the shared pixmap from the status bar window
    status = XGetWindowProperty(QX11Info::display(),
                                window,
                                pixmapHandleAtom,
                                0,
                                1,
                                False,
                                XA_PIXMAP,
                                &actualType,
                                &actualFormat,
                                &nitems,
                                &bytesAfter,
                                &data);

    QPixmap result;

    if (status == Success)
    {
        quint32 handle = *((unsigned long*)data);

        if (actualType == XA_PIXMAP && actualFormat == 32 && handle != 0)
        {
            result = QPixmap::fromX11Pixmap(handle, QPixmap::ExplicitlyShared);
            // TODO: we should register for damage events for this pixmap and repaint when they arrive
            //       (perhaps create an XEventListener fromt his class too?)
        }

        XFree(data);
    }

    return result;
}

StatusBar::StatusBar(QDeclarativeItem *parent) :
    QDeclarativeItem(parent)
{
    setFlag(QGraphicsItem::ItemHasNoContents, false);
    setAcceptTouchEvents(true);
    setImplicitHeight(36);
    QTimer::singleShot(3000, this, SLOT(initializeStatusBar()));
}

void StatusBar::initializeStatusBar()
{
    _sharedPixmap = fetchSharedPixmap();
    setImplicitHeight(_sharedPixmap.height() / 2);
    updateXThings();
}

void StatusBar::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
    Q_UNUSED(option)
    Q_UNUSED(widget)

    if (_sharedPixmap.isNull())
    {
        qDebug() << "StatusBar: the shared pixmap is null, can't draw it!";
        painter->setPen(QColor(Qt::black));
        painter->drawRect(0, 0, width(), height());
        return;
    }

    // Info: The shared pixmap contains both the portrait and the landscape mode status bars below each other.
    //       Landscape is on top, portrait on bottom. They have the same height.
    //       All we need is check the orientation here and set the source rect accordingly.

    painter->drawPixmap(QRectF(0, 0, width(), height()), _sharedPixmap, QRectF(0, _isPortrait ? height() : 0, width(), height()));
}

bool StatusBar::isPortrait() const
{
    return _isPortrait;
}

void StatusBar::updateXThings()
{
    // If the pixmap is null, don't bother
    if (_sharedPixmap.isNull())
        return;

    // Statusbar rect
    QPointF p = mapToScene(0, 0);
    unsigned long data[4] = { (int)p.x(), (int)p.y(), width(), height() };
    qDebug() << "statusbar geo:" << (int)p.x() << (int)p.y() << width() << height();

    // Orientation angle
    int angle = isPortrait() ? 270 : 0;
    qDebug() << "orientation angle:" << angle;

    // Stuff for X
    QWidget *activeWindow = this->scene()->views().at(0);
    Display *dpy = QX11Info::display();

    // Setting the status bar geometry atom (probably not necessary here)
    Atom statusBarGeometryAtom = XInternAtom(dpy, "_MEEGOTOUCH_MSTATUSBAR_GEOMETRY", False);
    XChangeProperty(dpy, activeWindow->effectiveWinId(), statusBarGeometryAtom, XA_CARDINAL, 32, PropModeReplace, (unsigned char*)data, 4);

    // Setting the orientation angle atom (sysuid uses this to determine what orientation it should draw itself)
    Atom orientationAngleAtom = XInternAtom(dpy, "_MEEGOTOUCH_ORIENTATION_ANGLE", False);
    XChangeProperty(dpy, activeWindow->effectiveWinId(), orientationAngleAtom, XA_CARDINAL, 32, PropModeReplace, (unsigned char*)&angle, 1);

    update();
}

void StatusBar::setIsPortrait(bool value)
{
    // If there is no change, don't bother
    if (_isPortrait == value)
        return;

    _isPortrait = value;
    updateXThings();

    emit isPortraitChanged();
}

bool StatusBar::sceneEvent(QEvent *event)
{
    if (event->type() == QEvent::TouchBegin)
    {
        return true;
    }
    if (event->type() == QEvent::TouchEnd)
    {
        qDebug() << "opening status menu";

        QDBusInterface interface("com.meego.core.MStatusIndicatorMenu",
                                 "/statusindicatormenu",
                                 "com.meego.core.MStatusIndicatorMenu",
                                 QDBusConnection::sessionBus());

        interface.call(QDBus::NoBlock, "open");

        return true;
    }

    return false;
}
<|endoftext|>


<commit_before>/** @file Action.hpp
*/

#ifndef __ACTION_HPP__
#define __ACTION_HPP__

#include "ESRoot/Types.hpp"
#include "PortUtils.hpp"

namespace ES
{
class ModelObject;
}
namespace Action
{

void send(ES::ModelObject* target, ES::EventRef signal);
/**<
Sends a message to a model object.
@param target The target object where the signal has to be sent.
@param signal The signal to be sent.
*/

template <typename T, typename S>
void send(T target, S signal);
/**<
Sends a message to a port.
@param port The port object where the signal has to be sent.
@param signal The signal to be sent.
*/

void start(ES::ModelObject* sm);
/**<
Starts the state machine of a model object.
@param sm The state machine to be started.
*/

void deleteObject(ES::ModelObject* modelObject);
/**<
Dispose a model object reference.
@param modelObject The object to be deleted.
*/

void log(ES::String message);
/**<
Logs a message.
@param message The message to be logged.
*/

template<typename LeftEnd, typename RightEnd>
void link(typename LeftEnd::EdgeType* e1, typename RightEnd::EdgeType* e2);
/**<
Links two model objects through the specified association.
It has no effect if the objects are already linked through the specified association.
@param LeftEnd The type representing the left end of the association.
@param RightEnd The type representing the rigth end of the association.
@param e1 The object at the left end of the association.
@param e2 The object at the right end of the association.
*/

template<typename LeftEnd, typename RightEnd>
void unlink(typename LeftEnd::EdgeType* e1, typename RightEnd::EdgeType* e2);
/**<
Unlinks two model objects through the specified association.
It has no effect if the objects are not linked through the specified association.
@param LeftEnd The type representing the left end of the association.
@param RightEnd The type representing the rigth end of the association.
@param e1 The object at the left end of the association.
@param e2 The object at the right end of the association.
*/

template<typename LeftEnd, typename RightEnd>
void link(typename LeftEnd::EdgeType* e1, typename RightEnd::EdgeType* e2)
{
	e1->template link<RightEnd>(e2);
	e2->template link<LeftEnd>(e1);
}

template<typename LeftEnd, typename RightEnd>
void unlink(typename LeftEnd::EdgeType* e1, typename RightEnd::EdgeType* e2)
{
	e1->template unlink<RightEnd>(e2);
	e2->template unlink<LeftEnd>(e1);
}

template <typename T, typename S>
void send(T target, S signal)
{
	target->send(signal);
}

}

#endif
<commit_msg>Modifies link/unlink functions<commit_after>/** @file Action.hpp
*/

#ifndef __ACTION_HPP__
#define __ACTION_HPP__

#include "ESRoot/Types.hpp"
#include "PortUtils.hpp"

namespace ES
{
class ModelObject;
}
namespace Action
{

void send(ES::ModelObject* target, ES::EventRef signal);
/**<
Sends a message to a model object.
@param target The target object where the signal has to be sent.
@param signal The signal to be sent.
*/

template <typename T, typename S>
void send(T target, S signal);
/**<
Sends a message to a port.
@param port The port object where the signal has to be sent.
@param signal The signal to be sent.
*/

void start(ES::ModelObject* sm);
/**<
Starts the state machine of a model object.
@param sm The state machine to be started.
*/

void deleteObject(ES::ModelObject* modelObject);
/**<
Dispose a model object reference.
@param modelObject The object to be deleted.
*/

void log(ES::String message);
/**<
Logs a message.
@param message The message to be logged.
*/

template<typename L, typename LE, typename R, typename RE>
void link (L* leftObject, LE* leftEnd, R* rightObject, RE* rightEnd);
/**<
Links two model objects through the specified association.
It has no effect if the objects are already linked through the specified association.
@param leftEnd The type representing the left end of the association.
@param rightEnd The type representing the right end of the association.
@param leftObject The object at the left end of the association.
@param rightObject The object at the right end of the association.
*/

template<typename LeftEnd, typename RightEnd>
void unlink (L* leftObject, LE* leftEnd, R* rightObject, RE* rightEnd);
/**<
Unlinks two model objects through the specified association.
It has no effect if the objects are not linked through the specified association.
@param leftEnd The type representing the left end of the association.
@param rightEnd The type representing the right end of the association.
@param leftObject The object at the left end of the association.
@param rightObject The object at the right end of the association.
*/

template<typename L, typename LE, typename R, typename RE>
void link (L* leftObject, LE* leftEnd, R* rightObject, RE* rightEnd)
{
	leftEnd->association->link (leftObject, leftEnd, rightObject, rightEnd);
}

template<typename L, typename LE, typename R, typename RE>
void unlink (L* leftObject, LE* leftEnd, R* rightObject, RE* rightEnd);
{
	leftEnd->association->unlink (leftObject, leftEnd, rightObject, rightEnd);

}

template <typename T, typename S>
void send(T target, S signal)
{
	target->send(signal);
}

}

#endif
<|endoftext|>