<commit_before>//
//  libavg - Media Playback Engine.
//  Copyright (C) 2003-2008 Ulrich von Zadow
//
//  This library is free software; you can redistribute it and/or
//  modify it under the terms of the GNU Lesser General Public
//  License as published by the Free Software Foundation; either
//  version 2 of the License, or (at your option) any later version.
//
//  This library is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
//  Lesser General Public License for more details.
//
//  You should have received a copy of the GNU Lesser General Public
//  License along with this library; if not, write to the Free Software
//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
//
//  Current versions can be found at www.libavg.de
//

#include "PBOTexture.h"
#include "SDLDisplayEngine.h"
#include "../graphics/VertexArray.h"
#include "../base/Logger.h"
#include "../base/Exception.h"
#include "../base/ScopeTimer.h"
#include "../base/ObjectCounter.h"
#include "../base/MathHelper.h"
#include "../base/StringHelper.h"

#include <iostream>
#include <string>

namespace avg {

using namespace std;

PBOTexture::PBOTexture(IntPoint size, PixelFormat pf, const MaterialInfo& material,
        SDLDisplayEngine * pEngine, OGLMemoryMode memoryMode)
    : m_pf(pf),
      m_Material(material),
      m_pEngine(pEngine),
      m_MemoryMode(memoryMode)
{
    ObjectCounter::get()->incRef(&typeid(*this));
    m_ActiveSize = size;
    if (pEngine->usePOTTextures()) {
        m_Size.x = nextpow2(m_ActiveSize.x);
        m_Size.y = nextpow2(m_ActiveSize.y);
    } else {
        m_Size = m_ActiveSize;
    }
    if (m_Size.x > pEngine->getMaxTexSize() || m_Size.y > pEngine->getMaxTexSize()) {
        throw Exception(AVG_ERR_VIDEO_GENERAL, "Texture too large (" +toString(m_Size)
                + "). Maximum supported by graphics card is "
                + toString(pEngine->getMaxTexSize()));
    }
    createBitmap();
    createTexture();
}

PBOTexture::~PBOTexture()
{
    if (m_MemoryMode == MM_PBO) {
        glproc::DeleteBuffers(1, &m_hWritePixelBuffer);
        glproc::DeleteBuffers(1, &m_hReadPixelBuffer);
        OGLErrorCheck(AVG_ERR_VIDEO_GENERAL,
                "PBOTexture::~PBOTexture: glDeleteBuffers()");
    }
    ObjectCounter::get()->decRef(&typeid(*this));
}

BitmapPtr PBOTexture::lockBmp()
{
    if (m_MemoryMode == MM_PBO) {
        glproc::BindBuffer(GL_PIXEL_UNPACK_BUFFER_EXT, m_hWritePixelBuffer);
        OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "PBOTexture::lockBmp: glBindBuffer()");
        glproc::BufferData(GL_PIXEL_UNPACK_BUFFER_EXT,
                (m_ActiveSize.x+1)*(m_ActiveSize.y+1)*Bitmap::getBytesPerPixel(m_pf),
                0, GL_DYNAMIC_DRAW);
        OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "PBOTexture::lockBmp: glBufferData()");
        unsigned char * pBuffer = (unsigned char *)
            glproc::MapBuffer(GL_PIXEL_UNPACK_BUFFER_EXT, GL_WRITE_ONLY);
        OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "PBOTexture::lockBmp: glMapBuffer()");
        glproc::BindBuffer(GL_PIXEL_UNPACK_BUFFER_EXT, 0);
        OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "PBOTexture::lockBmp: glBindBuffer(0)");

        m_pBmp = BitmapPtr(new Bitmap(m_ActiveSize, m_pf, pBuffer,
                    m_ActiveSize.x*Bitmap::getBytesPerPixel(m_pf), false));
    }
    return m_pBmp;
}

void PBOTexture::unlockBmp()
{
    if (m_MemoryMode == MM_PBO) {
        glproc::BindBuffer(GL_PIXEL_UNPACK_BUFFER_EXT, m_hWritePixelBuffer);
        OGLErrorCheck(AVG_ERR_VIDEO_GENERAL,
                "PBOTexture::unlockBmp: glBindBuffer()");
        glproc::UnmapBuffer(GL_PIXEL_UNPACK_BUFFER_EXT);
        OGLErrorCheck(AVG_ERR_VIDEO_GENERAL,
                "PBOTexture::unlockBmp: glUnmapBuffer()");
        glproc::BindBuffer(GL_PIXEL_UNPACK_BUFFER_EXT, 0);
        OGLErrorCheck(AVG_ERR_VIDEO_GENERAL,
                "PBOTexture::unlockBmp: glBindBuffer(0)");
        m_pBmp = BitmapPtr();
    }
}

BitmapPtr PBOTexture::readbackBmp()
{
    if (m_MemoryMode == MM_PBO) {
        glproc::BindBuffer(GL_PIXEL_PACK_BUFFER_EXT, m_hReadPixelBuffer);
        OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "PBOTexture::readbackBmp: glBindBuffer()");
        glPixelStorei(GL_PACK_ALIGNMENT, 1);
        OGLErrorCheck(AVG_ERR_VIDEO_GENERAL,
                "PBOTexture::readbackBmp: GL_PACK_ALIGNMENT");
        glPixelStorei(GL_PACK_ROW_LENGTH, 0);
        glproc::BufferData(GL_PIXEL_PACK_BUFFER_EXT,
                m_ActiveSize.x*m_ActiveSize.y*Bitmap::getBytesPerPixel(m_pf),
                0, GL_STREAM_READ);
        OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "PBOTexture::readbackBmp: glBufferData()");
        m_pTex->activate();
        glGetTexImage(GL_TEXTURE_2D, 0, m_pEngine->getOGLSrcMode(m_pf),
                m_pEngine->getOGLPixelType(m_pf), 0);
        OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "PBOTexture::readbackBmp: glGetTexImage()");
        unsigned char * pBuffer = (unsigned char *)
                glproc::MapBuffer(GL_PIXEL_PACK_BUFFER_EXT, GL_READ_ONLY);
        OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "PBOTexture::readbackBmp: glMapBuffer()");
        BitmapPtr pBmp = BitmapPtr(new Bitmap(m_ActiveSize, m_pf, pBuffer,
                    m_ActiveSize.x*Bitmap::getBytesPerPixel(m_pf), true));
        glproc::UnmapBuffer(GL_PIXEL_PACK_BUFFER_EXT);
        OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "PBOTexture::readbackBmp: glUnmapBuffer()");
        glproc::BindBuffer(GL_PIXEL_PACK_BUFFER_EXT, 0);
        OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "PBOTexture::readbackBmp: glBindBuffer(0)");
        return pBmp;
    } else {
        return BitmapPtr(new Bitmap(*m_pBmp));
    }
}

static ProfilingZone TexSubImageProfilingZone("PBOTexture::texture download");
static ProfilingZone MipmapProfilingZone("PBOTexture::mipmap generation");

void PBOTexture::download() const
{
    if (m_MemoryMode == MM_PBO) {
        glproc::BindBuffer(GL_PIXEL_UNPACK_BUFFER_EXT, m_hWritePixelBuffer);
        OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "PBOTexture::download: glBindBuffer()");
    }

    m_pTex->activate();
    glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
    glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
    OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "PBOTexture::download: GL_UNPACK_ALIGNMENT");
    unsigned char * pStartPos = 0;
    if (m_MemoryMode == MM_OGL) {
        pStartPos += (ptrdiff_t)(m_pBmp->getPixels());
    }
    {
        ScopeTimer Timer(TexSubImageProfilingZone);
        glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, m_ActiveSize.x, m_ActiveSize.y,
                m_pTex->getGLFormat(m_pf), m_pTex->getGLType(m_pf),
                pStartPos);
    }
    OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "PBOTexture::download: glTexSubImage2D()");
    if (m_MemoryMode == MM_PBO) {
        glproc::BindBuffer(GL_PIXEL_UNPACK_BUFFER_EXT, 0);
        OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "PBOTexture::download: glBindBuffer(0)");
    }
}

void PBOTexture::setTex(GLTexturePtr pTex)
{
    AVG_ASSERT(m_MemoryMode == MM_PBO);
    AVG_ASSERT(!m_pBmp);

    m_pTex = pTex;
}

void PBOTexture::setMaterial(const MaterialInfo& material)
{
    if (m_Material.getUseMipmaps() != material.getUseMipmaps()) {
        m_Material = material;
        createTexture();
    } else {
        m_Material = material;
    }
}

const IntPoint& PBOTexture::getTextureSize() const
{
    return m_Size;
}

unsigned PBOTexture::getTexID() const
{
    return m_pTex->getID();
}

void PBOTexture::createBitmap()
{
    switch (m_MemoryMode) {
        case MM_PBO:
            glproc::GenBuffers(1, &m_hReadPixelBuffer);
            glproc::GenBuffers(1, &m_hWritePixelBuffer);
            OGLErrorCheck(AVG_ERR_VIDEO_GENERAL,
                    "OGLSurface::createBitmap: glGenBuffers()");
            glproc::BindBuffer(GL_PIXEL_UNPACK_BUFFER_EXT, m_hWritePixelBuffer);
            OGLErrorCheck(AVG_ERR_VIDEO_GENERAL,
                    "OGLSurface::createBitmap: glBindBuffer()");
            glproc::BufferData(GL_PIXEL_UNPACK_BUFFER_EXT,
                    (m_ActiveSize.x+1)*(m_ActiveSize.y+1)*Bitmap::getBytesPerPixel(m_pf),
                    0, GL_DYNAMIC_DRAW);
            OGLErrorCheck(AVG_ERR_VIDEO_GENERAL,
                    "OGLSurface::createBitmap: glBufferData()");
            glproc::BindBuffer(GL_PIXEL_UNPACK_BUFFER_EXT, 0);
            OGLErrorCheck(AVG_ERR_VIDEO_GENERAL,
                    "OGLSurface::createBitmap: glBindBuffer(0)");
            m_pBmp = BitmapPtr();
            break;
        case MM_OGL:
            m_pBmp = BitmapPtr(new Bitmap(m_ActiveSize, m_pf));
            break;
        default:
            AVG_ASSERT(0);
    }
}

void PBOTexture::createTexture()
{
    m_pTex = GLTexturePtr(new GLTexture(m_Size, m_pf, m_Material.getUseMipmaps(),
            m_Material.getTexWrapSMode(), m_Material.getTexWrapTMode()));

    if (m_pEngine->usePOTTextures()) {
        // Make sure the texture is transparent and black before loading stuff
        // into it to avoid garbage at the borders.
        int TexMemNeeded = m_Size.x*m_Size.y*Bitmap::getBytesPerPixel(m_pf);
        char * pPixels = new char[TexMemNeeded];
        memset(pPixels, 0, TexMemNeeded);
        glTexImage2D(GL_TEXTURE_2D, 0, m_pEngine->getOGLDestMode(m_pf), m_Size.x,
                m_Size.y, 0, m_pEngine->getOGLSrcMode(m_pf),
                m_pEngine->getOGLPixelType(m_pf), pPixels);
        OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "PBOTexture::createTexture: glTexImage2D()");
        free(pPixels);
    }
}

}
<commit_msg>Unneeded code removal.<commit_after>//
//  libavg - Media Playback Engine.
//  Copyright (C) 2003-2008 Ulrich von Zadow
//
//  This library is free software; you can redistribute it and/or
//  modify it under the terms of the GNU Lesser General Public
//  License as published by the Free Software Foundation; either
//  version 2 of the License, or (at your option) any later version.
//
//  This library is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
//  Lesser General Public License for more details.
//
//  You should have received a copy of the GNU Lesser General Public
//  License along with this library; if not, write to the Free Software
//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
//
//  Current versions can be found at www.libavg.de
//

#include "PBOTexture.h"
#include "SDLDisplayEngine.h"
#include "../graphics/VertexArray.h"
#include "../base/Logger.h"
#include "../base/Exception.h"
#include "../base/ScopeTimer.h"
#include "../base/ObjectCounter.h"
#include "../base/MathHelper.h"
#include "../base/StringHelper.h"

#include <iostream>
#include <string>

namespace avg {

using namespace std;

PBOTexture::PBOTexture(IntPoint size, PixelFormat pf, const MaterialInfo& material,
        SDLDisplayEngine * pEngine, OGLMemoryMode memoryMode)
    : m_pf(pf),
      m_Material(material),
      m_pEngine(pEngine),
      m_MemoryMode(memoryMode)
{
    ObjectCounter::get()->incRef(&typeid(*this));
    m_ActiveSize = size;
    if (pEngine->usePOTTextures()) {
        m_Size.x = nextpow2(m_ActiveSize.x);
        m_Size.y = nextpow2(m_ActiveSize.y);
    } else {
        m_Size = m_ActiveSize;
    }
    if (m_Size.x > pEngine->getMaxTexSize() || m_Size.y > pEngine->getMaxTexSize()) {
        throw Exception(AVG_ERR_VIDEO_GENERAL, "Texture too large (" +toString(m_Size)
                + "). Maximum supported by graphics card is "
                + toString(pEngine->getMaxTexSize()));
    }
    createBitmap();
    createTexture();
}

PBOTexture::~PBOTexture()
{
    if (m_MemoryMode == MM_PBO) {
        glproc::DeleteBuffers(1, &m_hWritePixelBuffer);
        glproc::DeleteBuffers(1, &m_hReadPixelBuffer);
        OGLErrorCheck(AVG_ERR_VIDEO_GENERAL,
                "PBOTexture::~PBOTexture: glDeleteBuffers()");
    }
    ObjectCounter::get()->decRef(&typeid(*this));
}

BitmapPtr PBOTexture::lockBmp()
{
    if (m_MemoryMode == MM_PBO) {
        glproc::BindBuffer(GL_PIXEL_UNPACK_BUFFER_EXT, m_hWritePixelBuffer);
        OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "PBOTexture::lockBmp: glBindBuffer()");
        glproc::BufferData(GL_PIXEL_UNPACK_BUFFER_EXT,
                (m_ActiveSize.x+1)*(m_ActiveSize.y+1)*Bitmap::getBytesPerPixel(m_pf),
                0, GL_DYNAMIC_DRAW);
        OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "PBOTexture::lockBmp: glBufferData()");
        unsigned char * pBuffer = (unsigned char *)
            glproc::MapBuffer(GL_PIXEL_UNPACK_BUFFER_EXT, GL_WRITE_ONLY);
        OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "PBOTexture::lockBmp: glMapBuffer()");
        glproc::BindBuffer(GL_PIXEL_UNPACK_BUFFER_EXT, 0);
        OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "PBOTexture::lockBmp: glBindBuffer(0)");

        m_pBmp = BitmapPtr(new Bitmap(m_ActiveSize, m_pf, pBuffer,
                    m_ActiveSize.x*Bitmap::getBytesPerPixel(m_pf), false));
    }
    return m_pBmp;
}

void PBOTexture::unlockBmp()
{
    if (m_MemoryMode == MM_PBO) {
        glproc::BindBuffer(GL_PIXEL_UNPACK_BUFFER_EXT, m_hWritePixelBuffer);
        OGLErrorCheck(AVG_ERR_VIDEO_GENERAL,
                "PBOTexture::unlockBmp: glBindBuffer()");
        glproc::UnmapBuffer(GL_PIXEL_UNPACK_BUFFER_EXT);
        OGLErrorCheck(AVG_ERR_VIDEO_GENERAL,
                "PBOTexture::unlockBmp: glUnmapBuffer()");
        glproc::BindBuffer(GL_PIXEL_UNPACK_BUFFER_EXT, 0);
        OGLErrorCheck(AVG_ERR_VIDEO_GENERAL,
                "PBOTexture::unlockBmp: glBindBuffer(0)");
        m_pBmp = BitmapPtr();
    }
}

BitmapPtr PBOTexture::readbackBmp()
{
    if (m_MemoryMode == MM_PBO) {
        glproc::BindBuffer(GL_PIXEL_PACK_BUFFER_EXT, m_hReadPixelBuffer);
        OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "PBOTexture::readbackBmp: glBindBuffer()");
        glPixelStorei(GL_PACK_ALIGNMENT, 1);
        OGLErrorCheck(AVG_ERR_VIDEO_GENERAL,
                "PBOTexture::readbackBmp: GL_PACK_ALIGNMENT");
        glPixelStorei(GL_PACK_ROW_LENGTH, 0);
        glproc::BufferData(GL_PIXEL_PACK_BUFFER_EXT,
                m_ActiveSize.x*m_ActiveSize.y*Bitmap::getBytesPerPixel(m_pf),
                0, GL_STREAM_READ);
        OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "PBOTexture::readbackBmp: glBufferData()");
        m_pTex->activate();
        glGetTexImage(GL_TEXTURE_2D, 0, m_pEngine->getOGLSrcMode(m_pf),
                m_pEngine->getOGLPixelType(m_pf), 0);
        OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "PBOTexture::readbackBmp: glGetTexImage()");
        unsigned char * pBuffer = (unsigned char *)
                glproc::MapBuffer(GL_PIXEL_PACK_BUFFER_EXT, GL_READ_ONLY);
        OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "PBOTexture::readbackBmp: glMapBuffer()");
        BitmapPtr pBmp = BitmapPtr(new Bitmap(m_ActiveSize, m_pf, pBuffer,
                    m_ActiveSize.x*Bitmap::getBytesPerPixel(m_pf), true));
        glproc::UnmapBuffer(GL_PIXEL_PACK_BUFFER_EXT);
        OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "PBOTexture::readbackBmp: glUnmapBuffer()");
        glproc::BindBuffer(GL_PIXEL_PACK_BUFFER_EXT, 0);
        OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "PBOTexture::readbackBmp: glBindBuffer(0)");
        return pBmp;
    } else {
        return BitmapPtr(new Bitmap(*m_pBmp));
    }
}

static ProfilingZone TexSubImageProfilingZone("PBOTexture::texture download");
static ProfilingZone MipmapProfilingZone("PBOTexture::mipmap generation");

void PBOTexture::download() const
{
    if (m_MemoryMode == MM_PBO) {
        glproc::BindBuffer(GL_PIXEL_UNPACK_BUFFER_EXT, m_hWritePixelBuffer);
        OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "PBOTexture::download: glBindBuffer()");
    }

    m_pTex->activate();
    glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
    glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
    OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "PBOTexture::download: GL_UNPACK_ALIGNMENT");
    unsigned char * pStartPos = 0;
    if (m_MemoryMode == MM_OGL) {
        pStartPos += (ptrdiff_t)(m_pBmp->getPixels());
    }
    {
        ScopeTimer Timer(TexSubImageProfilingZone);
        glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, m_ActiveSize.x, m_ActiveSize.y,
                m_pTex->getGLFormat(m_pf), m_pTex->getGLType(m_pf),
                pStartPos);
    }
    OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "PBOTexture::download: glTexSubImage2D()");
    if (m_MemoryMode == MM_PBO) {
        glproc::BindBuffer(GL_PIXEL_UNPACK_BUFFER_EXT, 0);
        OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "PBOTexture::download: glBindBuffer(0)");
    }
}

void PBOTexture::setTex(GLTexturePtr pTex)
{
    AVG_ASSERT(m_MemoryMode == MM_PBO);
    AVG_ASSERT(!m_pBmp);

    m_pTex = pTex;
}

void PBOTexture::setMaterial(const MaterialInfo& material)
{
    if (m_Material.getUseMipmaps() != material.getUseMipmaps()) {
        m_Material = material;
        createTexture();
    } else {
        m_Material = material;
    }
}

const IntPoint& PBOTexture::getTextureSize() const
{
    return m_Size;
}

unsigned PBOTexture::getTexID() const
{
    return m_pTex->getID();
}

void PBOTexture::createBitmap()
{
    switch (m_MemoryMode) {
        case MM_PBO:
            glproc::GenBuffers(1, &m_hReadPixelBuffer);
            glproc::GenBuffers(1, &m_hWritePixelBuffer);
            OGLErrorCheck(AVG_ERR_VIDEO_GENERAL,
                    "OGLSurface::createBitmap: glGenBuffers()");
            m_pBmp = BitmapPtr();
            break;
        case MM_OGL:
            m_pBmp = BitmapPtr(new Bitmap(m_ActiveSize, m_pf));
            break;
        default:
            AVG_ASSERT(0);
    }
}

void PBOTexture::createTexture()
{
    m_pTex = GLTexturePtr(new GLTexture(m_Size, m_pf, m_Material.getUseMipmaps(),
            m_Material.getTexWrapSMode(), m_Material.getTexWrapTMode()));

    if (m_pEngine->usePOTTextures()) {
        // Make sure the texture is transparent and black before loading stuff
        // into it to avoid garbage at the borders.
        int TexMemNeeded = m_Size.x*m_Size.y*Bitmap::getBytesPerPixel(m_pf);
        char * pPixels = new char[TexMemNeeded];
        memset(pPixels, 0, TexMemNeeded);
        glTexImage2D(GL_TEXTURE_2D, 0, m_pEngine->getOGLDestMode(m_pf), m_Size.x,
                m_Size.y, 0, m_pEngine->getOGLSrcMode(m_pf),
                m_pEngine->getOGLPixelType(m_pf), pPixels);
        OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "PBOTexture::createTexture: glTexImage2D()");
        free(pPixels);
    }
}

}
<|endoftext|>


<commit_before><commit_msg>vml import: WaE (unused variable, unhandled enum value)<commit_after><|endoftext|>


<commit_before>// -*- mode: c++; c-basic-offset:4 -*-

// This file is part of libdap, A C++ implementation of the OPeNDAP Data
// Access Protocol.

// Copyright (c) 2005 OPeNDAP, Inc.
// Author: Nathan David Potter <ndp@opendap.org>
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
//
// You can contact OPeNDAP, Inc. at PO Box 112, Saunderstown, RI. 02874-0112.
#include <cppunit/TextTestRunner.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
#include <cppunit/extensions/HelperMacros.h>

#include <cstdio>

#define DODS_DEBUG

#include "debug.h"

#include "gridfields/grid.h"
#include "gridfields/gridfield.h"
#include "gridfields/bind.h"
#include "gridfields/array.h"
#include "gridfields/restrict.h"
#include "gridfields/refrestrict.h"
#include "gridfields/arrayreader.h"
#include "gridfields/accumulate.h"

using namespace GF;

namespace ugrid {

class BindTest : public CppUnit::TestFixture {

private:

    Grid *makeGrid(int scale, string name) {
      CellArray *twocells;
      CellArray *onecells;
      CellArray *zerocells;
      Grid *grid;
      Node triangle[3];
      Node segment[2];
      Node node;

      bool wf;
      int i;
      twocells = new CellArray();
      for (i=0; i<scale/2; i++) {
        triangle[0] = i;
        triangle[1] = i+1;
        triangle[2] = i+2;
        twocells->addCellNodes(triangle, 3);
      }
      //twocells->print();
      //getchar();
      onecells = new CellArray();
      for (i=0; i<scale-1; i++) {
        segment[0] = i;
        segment[1] = i+1;
        onecells->addCellNodes(segment, 2);
      }
      //onecells->print();

      //getchar();
      grid = new Grid(name, 2);
      grid->setImplicit0Cells(scale);
      grid->setKCells(onecells, 1);
      grid->setKCells(twocells, 2);
      //grid->print(0);
      //getchar();
      return grid;
    }

    Array *makeFloatArray(int size,const char *name) {
      Array *arr;
      arr = new Array(name, FLOAT, size);
      float *data;
      arr->getData(data);
      int i;

      for (i=0; i<size; i++) {
          data[i] = 2*i-10;
      }
      return arr;
    }
    GridField *makeGridField(int size, string gridname,const char *datname, int k) {

      Grid *G;
      GridField *GF;
      Array *data;

      G = makeGrid(12, "A");
      k = 0;
      data = makeFloatArray(12, "x");

      GF = new GridField(G, k, data);
      //printf("Valid? %i\n", !notValid(GF));
      //GF->print();

      return GF;
    }

public:

    // Called once before everything gets tested
    BindTest() {
    //    DBG(cerr << " BindTest - Constructor" << endl);

    }

    // Called at the end of the test
    ~BindTest() {
    //    DBG(cerr << " BindTest - Destructor" << endl);
    }

    // Called before each test
    void setup() {
    //    DBG(cerr << " BindTest - setup()" << endl);
    }

    // Called after each test
    void tearDown() {
    //    DBG(cerr << " tearDown()" << endl);
    }

    CPPUNIT_TEST_SUITE( BindTest );

    CPPUNIT_TEST(bind_test);

    CPPUNIT_TEST_SUITE_END();

    void  bind_test() {
      bool verbose = true;

      try {
        GridField *GF;
        GridField *Result;

        GF = makeGridField(12, "A", "x", 0);
        Array *arr = new Array("io", FLOAT, 12);
        GF->Bind(0, arr);

        GridField *aGF = AccumulateOp::Accumulate(GF, 0, "result", "result+1", "0", 0);

        if (verbose) aGF->print(9);
        printf("restricting...\n");
        Result = RefRestrictOp::Restrict("x<4",0,GF);
        if (verbose) Result->print(0);
        Result = RefRestrictOp::Restrict("x>-4",0,Result);
        if (verbose) Result->print(10);

        FileArrayReader *ar = new FileArrayReader("bindtest.dat", 0);
        ar->setPatternAttribute("result");
        GridField *G = BindOp::Bind("io", FLOAT, ar, 0, Result);

        if (verbose) G->print();

        CPPUNIT_ASSERT(true);
      }
      catch (std::string &e) {
        cerr << "Error: " << e << endl;
        CPPUNIT_ASSERT(false);
      }
      catch (...) {
        cerr << "Unknown Error." << endl;
        CPPUNIT_ASSERT(false);
      }
    }

}; // BindTest

CPPUNIT_TEST_SUITE_REGISTRATION(BindTest);

} // namespace ugrid

int
main( int, char** )
{
    CppUnit::TextTestRunner runner;
    runner.addTest( CppUnit::TestFactoryRegistry::getRegistry().makeTest() );

    bool wasSuccessful = runner.run( "", false ) ;

    return wasSuccessful ? 0 : 1;
}

<commit_msg>ugrid_functions: BindTest now uses DBG macros<commit_after>// -*- mode: c++; c-basic-offset:4 -*-

// This file is part of libdap, A C++ implementation of the OPeNDAP Data
// Access Protocol.

// Copyright (c) 2005 OPeNDAP, Inc.
// Author: Nathan David Potter <ndp@opendap.org>
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
//
// You can contact OPeNDAP, Inc. at PO Box 112, Saunderstown, RI. 02874-0112.
#include <cppunit/TextTestRunner.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
#include <cppunit/extensions/HelperMacros.h>

#include <cstdio>

#define DODS_DEBUG

#include "debug.h"

#include "gridfields/grid.h"
#include "gridfields/gridfield.h"
#include "gridfields/bind.h"
#include "gridfields/array.h"
#include "gridfields/restrict.h"
#include "gridfields/refrestrict.h"
#include "gridfields/arrayreader.h"
#include "gridfields/accumulate.h"

using namespace GF;

namespace ugrid {

class BindTest : public CppUnit::TestFixture {

private:

    Grid *makeGrid(int scale, string name) {
      CellArray *twocells;
      CellArray *onecells;
      CellArray *zerocells;
      Grid *grid;
      Node triangle[3];
      Node segment[2];
      Node node;

      bool wf;
      int i;
      twocells = new CellArray();
      for (i=0; i<scale/2; i++) {
        triangle[0] = i;
        triangle[1] = i+1;
        triangle[2] = i+2;
        twocells->addCellNodes(triangle, 3);
      }
      //twocells->print();
      //getchar();
      onecells = new CellArray();
      for (i=0; i<scale-1; i++) {
        segment[0] = i;
        segment[1] = i+1;
        onecells->addCellNodes(segment, 2);
      }
      //onecells->print();

      //getchar();
      grid = new Grid(name, 2);
      grid->setImplicit0Cells(scale);
      grid->setKCells(onecells, 1);
      grid->setKCells(twocells, 2);
      //grid->print(0);
      //getchar();
      return grid;
    }

    Array *makeFloatArray(int size,const char *name) {
      Array *arr;
      arr = new Array(name, FLOAT, size);
      float *data;
      arr->getData(data);
      int i;

      for (i=0; i<size; i++) {
          data[i] = 2*i-10;
      }
      return arr;
    }

    /**
     *
     */
    GridField *makeGridField(int size, string gridname,const char *datname, int k) {

      Grid *G;
      GridField *GF;
      Array *data;

      G = makeGrid(12, "A");
      k = 0;
      data = makeFloatArray(12, "x");

      GF = new GridField(G, k, data);
      //printf("Valid? %i\n", !notValid(GF));
      //GF->print();

      return GF;
    }

public:

    // Called once before everything gets tested
    BindTest() {
    //    DBG(cerr << " BindTest - Constructor" << endl);

    }

    // Called at the end of the test
    ~BindTest() {
    //    DBG(cerr << " BindTest - Destructor" << endl);
    }

    // Called before each test
    void setup() {
    //    DBG(cerr << " BindTest - setup()" << endl);
    }

    // Called after each test
    void tearDown() {
    //    DBG(cerr << " tearDown()" << endl);
    }

    CPPUNIT_TEST_SUITE( BindTest );

    CPPUNIT_TEST(bind_test);

    CPPUNIT_TEST_SUITE_END();

    void  bind_test() {
      DBG(cerr << " bind_test - BEGIN" << endl);

      try {
        GridField *GF;
        GridField *Result;

        GF = makeGridField(12, "A", "x", 0);
        Array *arr = new Array("io", FLOAT, 12);
        GF->Bind(0, arr);

        GridField *aGF = AccumulateOp::Accumulate(GF, 0, "result", "result+1", "0", 0);
        DBG(aGF->PrintTo(cerr,9);)

        DBG( cerr << "restricting..." << endl;)
        Result = RefRestrictOp::Restrict("x<4",0,GF);
        DBG(Result->PrintTo(cerr,0);)

        Result = RefRestrictOp::Restrict("x>-4",0,Result);
        DBG(Result->PrintTo(cerr,10);)

        FileArrayReader *ar = new FileArrayReader("bindtest.dat", 0);
        ar->setPatternAttribute("result");
        GridField *G = BindOp::Bind("io", FLOAT, ar, 0, Result);
        DBG(G->PrintTo(cerr,0);)

        CPPUNIT_ASSERT(true);
      }
      catch (std::string &e) {
        cerr << "Error: " << e << endl;
        CPPUNIT_ASSERT(false);
      }
      catch (...) {
        cerr << "Unknown Error." << endl;
        CPPUNIT_ASSERT(false);
      }
    }

}; // BindTest

CPPUNIT_TEST_SUITE_REGISTRATION(BindTest);

} // namespace ugrid

int
main( int, char** )
{
    CppUnit::TextTestRunner runner;
    runner.addTest( CppUnit::TestFactoryRegistry::getRegistry().makeTest() );

    bool wasSuccessful = runner.run( "", false ) ;

    return wasSuccessful ? 0 : 1;
}

<|endoftext|>


<commit_before>// Copyright 2019 Open Source Robotics Foundation, Inc.
// Copyright 2016-2018 Proyectos y Sistemas de Mantenimiento SL (eProsima).
//
// 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 <limits.h>
#include <string>

#include "fastrtps/config.h"
#include "fastrtps/Domain.h"
#include "fastrtps/attributes/ParticipantAttributes.h"
#include "fastrtps/attributes/PublisherAttributes.h"
#include "fastrtps/attributes/SubscriberAttributes.h"
#include "fastrtps/participant/Participant.h"
#include "fastrtps/publisher/Publisher.h"
#include "fastrtps/publisher/PublisherListener.h"
#include "fastrtps/rtps/RTPSDomain.h"
#include "fastrtps/rtps/common/Locator.h"
#include "fastrtps/rtps/builtin/discovery/endpoint/EDPSimple.h"
#include "fastrtps/rtps/reader/ReaderListener.h"
#include "fastrtps/rtps/reader/RTPSReader.h"
#include "fastrtps/rtps/reader/StatefulReader.h"
#include "fastrtps/subscriber/Subscriber.h"
#include "fastrtps/subscriber/SubscriberListener.h"
#include "fastrtps/subscriber/SampleInfo.h"

#include "rcutils/filesystem.h"
#include "rcutils/get_env.h"

#include "rmw/allocators.h"

#include "rmw_fastrtps_shared_cpp/custom_participant_info.hpp"
#include "rmw_fastrtps_shared_cpp/participant.hpp"
#include "rmw_fastrtps_shared_cpp/rmw_common.hpp"
#include "rmw_fastrtps_shared_cpp/rmw_security_logging.hpp"

using Domain = eprosima::fastrtps::Domain;
using IPLocator = eprosima::fastrtps::rtps::IPLocator;
using Locator_t = eprosima::fastrtps::rtps::Locator_t;
using Participant = eprosima::fastrtps::Participant;
using ParticipantAttributes = eprosima::fastrtps::ParticipantAttributes;
using StatefulReader = eprosima::fastrtps::rtps::StatefulReader;

#if HAVE_SECURITY
static
bool
get_security_file_paths(
  std::array<std::string, 6> & security_files_paths, const char * secure_root)
{
  // here assume only 6 files for security
  const char * file_names[6] = {
    "identity_ca.cert.pem", "cert.pem", "key.pem",
    "permissions_ca.cert.pem", "governance.p7s", "permissions.p7s"
  };
  size_t num_files = sizeof(file_names) / sizeof(char *);

  std::string file_prefix("file://");

  for (size_t i = 0; i < num_files; i++) {
    rcutils_allocator_t allocator = rcutils_get_default_allocator();
    char * file_path = rcutils_join_path(secure_root, file_names[i], allocator);

    if (!file_path) {
      return false;
    }

    if (rcutils_is_readable(file_path)) {
      security_files_paths[i] = file_prefix + std::string(file_path);
    } else {
      allocator.deallocate(file_path, allocator.state);
      return false;
    }

    allocator.deallocate(file_path, allocator.state);
  }

  return true;
}
#endif

static
CustomParticipantInfo *
__create_participant(
  const char * identifier,
  ParticipantAttributes participantAttrs,
  bool leave_middleware_default_qos,
  rmw_dds_common::Context * common_context)
{
  // Declare everything before beginning to create things.
  ::ParticipantListener * listener = nullptr;
  Participant * participant = nullptr;
  CustomParticipantInfo * participant_info = nullptr;

  try {
    listener = new ::ParticipantListener(
      identifier, common_context);
  } catch (std::bad_alloc &) {
    RMW_SET_ERROR_MSG("failed to allocate participant listener");
    goto fail;
  }

  participant = Domain::createParticipant(participantAttrs, listener);
  if (!participant) {
    RMW_SET_ERROR_MSG("create_node() could not create participant");
    return nullptr;
  }

  try {
    participant_info = new CustomParticipantInfo();
  } catch (std::bad_alloc &) {
    RMW_SET_ERROR_MSG("failed to allocate node impl struct");
    goto fail;
  }
  participant_info->leave_middleware_default_qos = leave_middleware_default_qos;

  participant_info->participant = participant;
  participant_info->listener = listener;

  return participant_info;
fail:
  rmw_free(listener);
  if (participant) {
    Domain::removeParticipant(participant);
  }
  return nullptr;
}

CustomParticipantInfo *
rmw_fastrtps_shared_cpp::create_participant(
  const char * identifier,
  size_t domain_id,
  const rmw_security_options_t * security_options,
  bool localhost_only,
  const char * enclave,
  rmw_dds_common::Context * common_context)
{
  if (!security_options) {
    RMW_SET_ERROR_MSG("security_options is null");
    return nullptr;
  }
  ParticipantAttributes participantAttrs;

  // Load default XML profile.
  Domain::getDefaultParticipantAttributes(participantAttrs);

  if (localhost_only) {
    Locator_t local_network_interface_locator;
    static const std::string local_ip_name("127.0.0.1");
    local_network_interface_locator.kind = 1;
    local_network_interface_locator.port = 0;
    IPLocator::setIPv4(local_network_interface_locator, local_ip_name);
    participantAttrs.rtps.builtin.metatrafficUnicastLocatorList.push_back(
      local_network_interface_locator);
    participantAttrs.rtps.builtin.initialPeersList.push_back(local_network_interface_locator);
  }

#if FASTRTPS_VERSION_MAJOR < 2
  participantAttrs.rtps.builtin.domainId = static_cast<uint32_t>(domain_id);
#else
  participantAttrs.domainId = static_cast<uint32_t>(domain_id);
#endif

  size_t length = snprintf(nullptr, 0, "enclave=%s;", enclave) + 1;
  participantAttrs.rtps.userData.resize(length);
  int written = snprintf(
    reinterpret_cast<char *>(participantAttrs.rtps.userData.data()),
    length, "enclave=%s;", enclave);
  if (written < 0 || written > static_cast<int>(length) - 1) {
    RMW_SET_ERROR_MSG("failed to populate user_data buffer");
    return nullptr;
  }
  participantAttrs.rtps.setName(enclave);

  bool leave_middleware_default_qos = false;
  const char * env_value;
  const char * error_str;
  error_str = rcutils_get_env("RMW_FASTRTPS_USE_QOS_FROM_XML", &env_value);
  if (error_str != NULL) {
    RCUTILS_LOG_DEBUG_NAMED("rmw_fastrtps_shared_cpp", "Error getting env var: %s\n", error_str);
    return nullptr;
  }
  if (env_value != nullptr) {
    leave_middleware_default_qos = strcmp(env_value, "1") == 0;
  }
  // allow reallocation to support discovery messages bigger than 5000 bytes
  if (!leave_middleware_default_qos) {
    participantAttrs.rtps.builtin.readerHistoryMemoryPolicy =
      eprosima::fastrtps::rtps::PREALLOCATED_WITH_REALLOC_MEMORY_MODE;
    participantAttrs.rtps.builtin.writerHistoryMemoryPolicy =
      eprosima::fastrtps::rtps::PREALLOCATED_WITH_REALLOC_MEMORY_MODE;
  }
  if (security_options->security_root_path) {
    // if security_root_path provided, try to find the key and certificate files
#if HAVE_SECURITY
    std::array<std::string, 6> security_files_paths;
    if (get_security_file_paths(security_files_paths, security_options->security_root_path)) {
      eprosima::fastrtps::rtps::PropertyPolicy property_policy;
      using Property = eprosima::fastrtps::rtps::Property;
      property_policy.properties().emplace_back(
        Property("dds.sec.auth.plugin", "builtin.PKI-DH"));
      property_policy.properties().emplace_back(
        Property(
          "dds.sec.auth.builtin.PKI-DH.identity_ca", security_files_paths[0]));
      property_policy.properties().emplace_back(
        Property(
          "dds.sec.auth.builtin.PKI-DH.identity_certificate", security_files_paths[1]));
      property_policy.properties().emplace_back(
        Property(
          "dds.sec.auth.builtin.PKI-DH.private_key", security_files_paths[2]));
      property_policy.properties().emplace_back(
        Property("dds.sec.crypto.plugin", "builtin.AES-GCM-GMAC"));

      property_policy.properties().emplace_back(
        Property(
          "dds.sec.access.plugin", "builtin.Access-Permissions"));
      property_policy.properties().emplace_back(
        Property(
          "dds.sec.access.builtin.Access-Permissions.permissions_ca", security_files_paths[3]));
      property_policy.properties().emplace_back(
        Property(
          "dds.sec.access.builtin.Access-Permissions.governance", security_files_paths[4]));
      property_policy.properties().emplace_back(
        Property(
          "dds.sec.access.builtin.Access-Permissions.permissions", security_files_paths[5]));

      // Configure security logging
      if (!apply_security_logging_configuration(property_policy)) {
        return nullptr;
      }

      participantAttrs.rtps.properties = property_policy;
    } else if (security_options->enforce_security) {
      RMW_SET_ERROR_MSG("couldn't find all security files!");
      return nullptr;
    }
#else
    RMW_SET_ERROR_MSG(
      "This Fast-RTPS version doesn't have the security libraries\n"
      "Please compile Fast-RTPS using the -DSECURITY=ON CMake option");
    return nullptr;
#endif
  }
  return __create_participant(
    identifier,
    participantAttrs,
    leave_middleware_default_qos,
    common_context);
}

rmw_ret_t
rmw_fastrtps_shared_cpp::destroy_participant(CustomParticipantInfo * participant_info)
{
  rmw_ret_t result_ret = RMW_RET_OK;
  if (!participant_info) {
    RMW_SET_ERROR_MSG("participant_info is null");
    return RMW_RET_ERROR;
  }
  Domain::removeParticipant(participant_info->participant);
  delete participant_info->listener;
  participant_info->listener = nullptr;
  delete participant_info;
  return result_ret;
}
<commit_msg>Handle RMW_DEFAULT_DOMAIN_ID. (#394)<commit_after>// Copyright 2019 Open Source Robotics Foundation, Inc.
// Copyright 2016-2018 Proyectos y Sistemas de Mantenimiento SL (eProsima).
//
// 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 <limits.h>
#include <string>

#include "fastrtps/config.h"
#include "fastrtps/Domain.h"
#include "fastrtps/attributes/ParticipantAttributes.h"
#include "fastrtps/attributes/PublisherAttributes.h"
#include "fastrtps/attributes/SubscriberAttributes.h"
#include "fastrtps/participant/Participant.h"
#include "fastrtps/publisher/Publisher.h"
#include "fastrtps/publisher/PublisherListener.h"
#include "fastrtps/rtps/RTPSDomain.h"
#include "fastrtps/rtps/common/Locator.h"
#include "fastrtps/rtps/builtin/discovery/endpoint/EDPSimple.h"
#include "fastrtps/rtps/reader/ReaderListener.h"
#include "fastrtps/rtps/reader/RTPSReader.h"
#include "fastrtps/rtps/reader/StatefulReader.h"
#include "fastrtps/subscriber/Subscriber.h"
#include "fastrtps/subscriber/SubscriberListener.h"
#include "fastrtps/subscriber/SampleInfo.h"

#include "rcutils/filesystem.h"
#include "rcutils/get_env.h"

#include "rmw/allocators.h"

#include "rmw_fastrtps_shared_cpp/custom_participant_info.hpp"
#include "rmw_fastrtps_shared_cpp/participant.hpp"
#include "rmw_fastrtps_shared_cpp/rmw_common.hpp"
#include "rmw_fastrtps_shared_cpp/rmw_security_logging.hpp"

using Domain = eprosima::fastrtps::Domain;
using IPLocator = eprosima::fastrtps::rtps::IPLocator;
using Locator_t = eprosima::fastrtps::rtps::Locator_t;
using Participant = eprosima::fastrtps::Participant;
using ParticipantAttributes = eprosima::fastrtps::ParticipantAttributes;
using StatefulReader = eprosima::fastrtps::rtps::StatefulReader;

#if HAVE_SECURITY
static
bool
get_security_file_paths(
  std::array<std::string, 6> & security_files_paths, const char * secure_root)
{
  // here assume only 6 files for security
  const char * file_names[6] = {
    "identity_ca.cert.pem", "cert.pem", "key.pem",
    "permissions_ca.cert.pem", "governance.p7s", "permissions.p7s"
  };
  size_t num_files = sizeof(file_names) / sizeof(char *);

  std::string file_prefix("file://");

  for (size_t i = 0; i < num_files; i++) {
    rcutils_allocator_t allocator = rcutils_get_default_allocator();
    char * file_path = rcutils_join_path(secure_root, file_names[i], allocator);

    if (!file_path) {
      return false;
    }

    if (rcutils_is_readable(file_path)) {
      security_files_paths[i] = file_prefix + std::string(file_path);
    } else {
      allocator.deallocate(file_path, allocator.state);
      return false;
    }

    allocator.deallocate(file_path, allocator.state);
  }

  return true;
}
#endif

static
CustomParticipantInfo *
__create_participant(
  const char * identifier,
  ParticipantAttributes participantAttrs,
  bool leave_middleware_default_qos,
  rmw_dds_common::Context * common_context)
{
  // Declare everything before beginning to create things.
  ::ParticipantListener * listener = nullptr;
  Participant * participant = nullptr;
  CustomParticipantInfo * participant_info = nullptr;

  try {
    listener = new ::ParticipantListener(
      identifier, common_context);
  } catch (std::bad_alloc &) {
    RMW_SET_ERROR_MSG("failed to allocate participant listener");
    goto fail;
  }

  participant = Domain::createParticipant(participantAttrs, listener);
  if (!participant) {
    RMW_SET_ERROR_MSG("create_node() could not create participant");
    return nullptr;
  }

  try {
    participant_info = new CustomParticipantInfo();
  } catch (std::bad_alloc &) {
    RMW_SET_ERROR_MSG("failed to allocate node impl struct");
    goto fail;
  }
  participant_info->leave_middleware_default_qos = leave_middleware_default_qos;

  participant_info->participant = participant;
  participant_info->listener = listener;

  return participant_info;
fail:
  rmw_free(listener);
  if (participant) {
    Domain::removeParticipant(participant);
  }
  return nullptr;
}

CustomParticipantInfo *
rmw_fastrtps_shared_cpp::create_participant(
  const char * identifier,
  size_t domain_id,
  const rmw_security_options_t * security_options,
  bool localhost_only,
  const char * enclave,
  rmw_dds_common::Context * common_context)
{
  if (!security_options) {
    RMW_SET_ERROR_MSG("security_options is null");
    return nullptr;
  }
  ParticipantAttributes participantAttrs;

  // Load default XML profile.
  Domain::getDefaultParticipantAttributes(participantAttrs);

  if (localhost_only) {
    Locator_t local_network_interface_locator;
    static const std::string local_ip_name("127.0.0.1");
    local_network_interface_locator.kind = 1;
    local_network_interface_locator.port = 0;
    IPLocator::setIPv4(local_network_interface_locator, local_ip_name);
    participantAttrs.rtps.builtin.metatrafficUnicastLocatorList.push_back(
      local_network_interface_locator);
    participantAttrs.rtps.builtin.initialPeersList.push_back(local_network_interface_locator);
  }

  // No custom handling of RMW_DEFAULT_DOMAIN_ID. Simply use a reasonable domain id.
#if FASTRTPS_VERSION_MAJOR < 2
  participantAttrs.rtps.builtin.domainId =
    static_cast<uint32_t>(domain_id != RMW_DEFAULT_DOMAIN_ID ? domain_id : 0u);
#else
  participantAttrs.domainId =
    static_cast<uint32_t>(domain_id != RMW_DEFAULT_DOMAIN_ID ? domain_id : 0u);
#endif

  size_t length = snprintf(nullptr, 0, "enclave=%s;", enclave) + 1;
  participantAttrs.rtps.userData.resize(length);
  int written = snprintf(
    reinterpret_cast<char *>(participantAttrs.rtps.userData.data()),
    length, "enclave=%s;", enclave);
  if (written < 0 || written > static_cast<int>(length) - 1) {
    RMW_SET_ERROR_MSG("failed to populate user_data buffer");
    return nullptr;
  }
  participantAttrs.rtps.setName(enclave);

  bool leave_middleware_default_qos = false;
  const char * env_value;
  const char * error_str;
  error_str = rcutils_get_env("RMW_FASTRTPS_USE_QOS_FROM_XML", &env_value);
  if (error_str != NULL) {
    RCUTILS_LOG_DEBUG_NAMED("rmw_fastrtps_shared_cpp", "Error getting env var: %s\n", error_str);
    return nullptr;
  }
  if (env_value != nullptr) {
    leave_middleware_default_qos = strcmp(env_value, "1") == 0;
  }
  // allow reallocation to support discovery messages bigger than 5000 bytes
  if (!leave_middleware_default_qos) {
    participantAttrs.rtps.builtin.readerHistoryMemoryPolicy =
      eprosima::fastrtps::rtps::PREALLOCATED_WITH_REALLOC_MEMORY_MODE;
    participantAttrs.rtps.builtin.writerHistoryMemoryPolicy =
      eprosima::fastrtps::rtps::PREALLOCATED_WITH_REALLOC_MEMORY_MODE;
  }
  if (security_options->security_root_path) {
    // if security_root_path provided, try to find the key and certificate files
#if HAVE_SECURITY
    std::array<std::string, 6> security_files_paths;
    if (get_security_file_paths(security_files_paths, security_options->security_root_path)) {
      eprosima::fastrtps::rtps::PropertyPolicy property_policy;
      using Property = eprosima::fastrtps::rtps::Property;
      property_policy.properties().emplace_back(
        Property("dds.sec.auth.plugin", "builtin.PKI-DH"));
      property_policy.properties().emplace_back(
        Property(
          "dds.sec.auth.builtin.PKI-DH.identity_ca", security_files_paths[0]));
      property_policy.properties().emplace_back(
        Property(
          "dds.sec.auth.builtin.PKI-DH.identity_certificate", security_files_paths[1]));
      property_policy.properties().emplace_back(
        Property(
          "dds.sec.auth.builtin.PKI-DH.private_key", security_files_paths[2]));
      property_policy.properties().emplace_back(
        Property("dds.sec.crypto.plugin", "builtin.AES-GCM-GMAC"));

      property_policy.properties().emplace_back(
        Property(
          "dds.sec.access.plugin", "builtin.Access-Permissions"));
      property_policy.properties().emplace_back(
        Property(
          "dds.sec.access.builtin.Access-Permissions.permissions_ca", security_files_paths[3]));
      property_policy.properties().emplace_back(
        Property(
          "dds.sec.access.builtin.Access-Permissions.governance", security_files_paths[4]));
      property_policy.properties().emplace_back(
        Property(
          "dds.sec.access.builtin.Access-Permissions.permissions", security_files_paths[5]));

      // Configure security logging
      if (!apply_security_logging_configuration(property_policy)) {
        return nullptr;
      }

      participantAttrs.rtps.properties = property_policy;
    } else if (security_options->enforce_security) {
      RMW_SET_ERROR_MSG("couldn't find all security files!");
      return nullptr;
    }
#else
    RMW_SET_ERROR_MSG(
      "This Fast-RTPS version doesn't have the security libraries\n"
      "Please compile Fast-RTPS using the -DSECURITY=ON CMake option");
    return nullptr;
#endif
  }
  return __create_participant(
    identifier,
    participantAttrs,
    leave_middleware_default_qos,
    common_context);
}

rmw_ret_t
rmw_fastrtps_shared_cpp::destroy_participant(CustomParticipantInfo * participant_info)
{
  rmw_ret_t result_ret = RMW_RET_OK;
  if (!participant_info) {
    RMW_SET_ERROR_MSG("participant_info is null");
    return RMW_RET_ERROR;
  }
  Domain::removeParticipant(participant_info->participant);
  delete participant_info->listener;
  participant_info->listener = nullptr;
  delete participant_info;
  return result_ret;
}
<|endoftext|>


<commit_before>/*
 * Software License Agreement (BSD License)
 *
 *  Copyright (c) 2009, 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, Inc. 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.
 *
 * $Id: test_ii_normals.cpp 35790 2011-02-05 18:55:14Z holzers $
 *
 */
/** \author Stefan Holzer */

#include <gtest/gtest.h>

#include <boost/make_shared.hpp>
#include <pcl/point_types.h>
#include <pcl/io/pcd_io.h>
#include <pcl/features/integral_image_normal.h>

#include <iostream>

using namespace pcl;
using namespace pcl::io;
using namespace std;

PointCloud<PointXYZ> cloud;
IntegralImageNormalEstimation normalEstimator;

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
TEST (PCL, IINormalEstimation)
{
  Normal normal = normalEstimator.compute(cloud.width/2, cloud.height/2);

  EXPECT_NEAR (fabs (normal.normal_x), 0.0662114,  1e-4);
  EXPECT_NEAR (fabs (normal.normal_y), 0.597649,  1e-4);
  EXPECT_NEAR (fabs (normal.normal_z), 0.799019,  1e-4);
}

/* ---[ */
int
  main (int argc, char** argv)
{
  if (argc < 2)
  {
    std::cerr << "No test file given. Please download `table_scene_mug_stereo_textured.pcd` and pass its path to the test." << std::endl;
    return (-1);
  }

  sensor_msgs::PointCloud2 cloud_blob;
  if (loadPCDFile (argv[1], cloud_blob) < 0)
  {
    std::cerr << "Failed to read test file. Please download `table_scene_mug_stereo_textured.pcd` and pass its path to the test." << std::endl;
    return (-1);
  }

  fromROSMsg (cloud_blob, cloud);

  normalEstimator.setInputData(
    reinterpret_cast<float*>(&(cloud.points[0])),
    cloud.width, cloud.height,
    3, sizeof(cloud.points[0])/sizeof(float), (sizeof(cloud.points[0])/sizeof(float))*cloud.width, 10.0f);

  normalEstimator.setRectSize(2, 2);

  testing::InitGoogleTest (&argc, argv);
  return (RUN_ALL_TESTS ());

  return 1;
}
/* ]--- */

<commit_msg>no need for make_shared<commit_after>/*
 * Software License Agreement (BSD License)
 *
 *  Copyright (c) 2009, 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, Inc. 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.
 *
 * $Id: test_ii_normals.cpp 35790 2011-02-05 18:55:14Z holzers $
 *
 */
/** \author Stefan Holzer */

#include <gtest/gtest.h>

#include <pcl/point_types.h>
#include <pcl/io/pcd_io.h>
#include <pcl/features/integral_image_normal.h>

#include <iostream>

using namespace pcl;
using namespace pcl::io;
using namespace std;

PointCloud<PointXYZ> cloud;
IntegralImageNormalEstimation normalEstimator;

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
TEST (PCL, IINormalEstimation)
{
  Normal normal = normalEstimator.compute(cloud.width/2, cloud.height/2);

  EXPECT_NEAR (fabs (normal.normal_x), 0.0662114,  1e-4);
  EXPECT_NEAR (fabs (normal.normal_y), 0.597649,  1e-4);
  EXPECT_NEAR (fabs (normal.normal_z), 0.799019,  1e-4);
}

/* ---[ */
int
  main (int argc, char** argv)
{
  if (argc < 2)
  {
    std::cerr << "No test file given. Please download `table_scene_mug_stereo_textured.pcd` and pass its path to the test." << std::endl;
    return (-1);
  }

  sensor_msgs::PointCloud2 cloud_blob;
  if (loadPCDFile (argv[1], cloud_blob) < 0)
  {
    std::cerr << "Failed to read test file. Please download `table_scene_mug_stereo_textured.pcd` and pass its path to the test." << std::endl;
    return (-1);
  }

  fromROSMsg (cloud_blob, cloud);

  normalEstimator.setInputData(
    reinterpret_cast<float*>(&(cloud.points[0])),
    cloud.width, cloud.height,
    3, sizeof(cloud.points[0])/sizeof(float), (sizeof(cloud.points[0])/sizeof(float))*cloud.width, 10.0f);

  normalEstimator.setRectSize(2, 2);

  testing::InitGoogleTest (&argc, argv);
  return (RUN_ALL_TESTS ());

  return 1;
}
/* ]--- */

<|endoftext|>


<commit_before>#include "uitest.h"
#include "commandlinetest.h"
#include "configtest.h"

// scanning
#include "file.h"
#include "filelist.h"
#include "scanner.h"

// filtering
#include "duplicate.h"
#include "filter.h"

#include "apptest.h"

#include <cppunit/extensions/TestFactoryRegistry.h>
#include <cppunit/ui/text/TestRunner.h>

int main(void) {
	CppUnit::TextUi::TestRunner runner;

	CppUnit::TestFactoryRegistry &registry = CppUnit::TestFactoryRegistry::getRegistry();
	runner.addTest( registry.makeTest() );

	bool wasSuccessful = runner.run("", false);

	return wasSuccessful;
}<commit_msg>change testrunner for a better visualization<commit_after>// ui
#include "uitest.h"
#include "commandlinetest.h"
#include "configtest.h"

// scanning
#include "file.h"
#include "filelist.h"
#include "scanner.h"

// filtering
#include "duplicate.h"
#include "filter.h"

#include "apptest.h"

#include <cppunit/BriefTestProgressListener.h>
#include <cppunit/CompilerOutputter.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
#include <cppunit/TestResult.h>
#include <cppunit/TestResultCollector.h>
#include <cppunit/TestRunner.h>

int main () {
  CPPUNIT_NS::TestResult controller;

  CPPUNIT_NS::TestResultCollector result;
  controller.addListener( &result );

  CPPUNIT_NS::BriefTestProgressListener progress;
  controller.addListener( &progress );

  CPPUNIT_NS::TestRunner runner;
  runner.addTest( CPPUNIT_NS::TestFactoryRegistry::getRegistry().makeTest() );
  runner.run( controller );

  CPPUNIT_NS::CompilerOutputter outputter( &result, CPPUNIT_NS::stdCOut() );
  outputter.write();

  return result.wasSuccessful() ? 0 : 1;
}

<|endoftext|>


<commit_before>#include <polar/asset/audio.h>
#include <polar/component/audiosource.h>
#include <polar/component/color.h>
#include <polar/component/scale.h>
#include <polar/component/screenposition.h>
#include <polar/component/sprite/box.h>
#include <polar/component/sprite/slider.h>
#include <polar/component/text.h>
#include <polar/support/action/menu.h>
#include <polar/support/audio/sourcetype.h>
#include <polar/support/input/key.h>
#include <polar/support/ui/control.h>
#include <polar/system/action.h>
#include <polar/system/asset.h>
#include <polar/system/menu.h>
#include <polar/system/tweener.h>

namespace polar::system {
	void menu::activate() {
		auto &item = current_at(current);

		if(item.control) {
			if(item.control->activate()) {
				render(current, true);
				if(item.fn(item.control->get())) {
					auto assetM = engine->get<asset>().lock();
					IDType soundID;
					soundDtors[soundIndex++] = engine->add(soundID);
					soundIndex %= soundDtors.size();
					engine->add<component::audiosource>(
					    soundID, assetM->get<polar::asset::audio>("menu1"),
					    support::audio::sourcetype::effect);
				}
			}
		} else if(!item.children.empty()) {
			navigate(0, 1, true);
		}
	}

	void menu::navigate(int down, int right, bool force) {
		auto &item = current_at(current);
		auto size = current_size();

		bool playBeep = false;

		bool newForce = force;
		if(!force && right && item.control && item.control->navigate(right)) {
			item.fn(item.control->get());
			render(current, true);
			playBeep = true;
		} else {
			newForce = force;
		}

		if(newForce) {
			while(right > 0) {
				auto &i = current_at(current);
				if(!i.children.empty()) {
					stack.emplace_back(current);
					current = 0;
					--right;
					playBeep = true;
				} else {
					activate();
				}
			}
			while(right < 0) {
				if(stack.empty()) {
					if(force) {
						engine->transition = "back";
						return;
					}
				} else {
					current = stack.back();
					stack.pop_back();
					++right;
					playBeep = true;
				}
			}
			render_all();
		}
		if(down != 0) {
			auto sz = current_size();
			auto previous = current;
			current += down;
			if(current < 0) {
				current += sz;
			} else {
				current %= sz;
			}
			render(previous, true);
			playBeep = true;
		}

		if(playBeep) {
			auto assetM = engine->get<asset>().lock();
			IDType soundID;
			soundDtors[soundIndex++] = engine->add(soundID);
			soundIndex %= soundDtors.size();
			engine->add<component::audiosource>(
			    soundID, assetM->get<polar::asset::audio>("menu1"),
			    support::audio::sourcetype::effect);
		}
	}

	void menu::render(size_t i, bool replace) {
		auto &item = current_at(i);
		auto size = current_size();

		IDType id;
		if(replace) {
			itemDtors.at(i) = engine->add(id);
		} else {
			itemDtors.emplace_back(engine->add(id));
		}

		// max 6 items on screen at max scale of uiBase
		const Decimal uiHeight     = 8 * uiBase;
		const Decimal uiTextHeight = 160;
		const Decimal uiTextWidth  = 550;

		Decimal scale =
		    glm::min(Decimal(uiHeight) / Decimal(size), Decimal(uiScale));
		Decimal spacing = uiTextHeight * scale;
		Point2 origin   = Point2(60, 50 + spacing * (size - i - 1));

		engine->add<component::text>(id, font, item.value);
		engine->add<component::screenposition>(id, origin);
		engine->add<component::scale>(id, Point3(scale));

		if(int(i) == current) {
			engine->add<component::color>(id, Point4(1, 1, selectionAlpha, 1));
		}

		if(item.control) {
			IDType controlID;
			auto offset = Point2(uiTextWidth / uiBase * scale, 0);
			offset.y -= 12 * scale;
			controlDtors[i] = item.control->render(engine, controlID,
			                                       origin + offset, 8 * scale);
		}
	}

	void menu::init() {
		using lifetime = support::action::lifetime;
		namespace a = support::action::menu;

		auto assetM = engine->get<asset>().lock();
		auto act    = engine->get<action>().lock();
		auto tw     = engine->get<tweener<float>>().lock();

		assetM->request<polar::asset::audio>("menu1");

		font = assetM->get<polar::asset::font>("nasalization-rg");

		keep(act->bind<a::down   >(lifetime::on, [this] { navigate( 1);    }));
		keep(act->bind<a::up     >(lifetime::on, [this] { navigate(-1);    }));
		keep(act->bind<a::right  >(lifetime::on, [this] { navigate(0,  1); }));
		keep(act->bind<a::left   >(lifetime::on, [this] { navigate(0, -1); }));
		keep(act->bind<a::forward>(lifetime::on, [this] { activate();      }));
		keep(act->bind<a::back   >(lifetime::on, [this] {
			navigate(0, -1, true);
		}));

		keep(tw->tween(0.0f, 1.0f, 0.25, true, [this](auto, const float &x) {
			selectionAlpha = x;
		}));

		render_all();
	}
} // namespace polar::system
<commit_msg>Fix comment<commit_after>#include <polar/asset/audio.h>
#include <polar/component/audiosource.h>
#include <polar/component/color.h>
#include <polar/component/scale.h>
#include <polar/component/screenposition.h>
#include <polar/component/sprite/box.h>
#include <polar/component/sprite/slider.h>
#include <polar/component/text.h>
#include <polar/support/action/menu.h>
#include <polar/support/audio/sourcetype.h>
#include <polar/support/input/key.h>
#include <polar/support/ui/control.h>
#include <polar/system/action.h>
#include <polar/system/asset.h>
#include <polar/system/menu.h>
#include <polar/system/tweener.h>

namespace polar::system {
	void menu::activate() {
		auto &item = current_at(current);

		if(item.control) {
			if(item.control->activate()) {
				render(current, true);
				if(item.fn(item.control->get())) {
					auto assetM = engine->get<asset>().lock();
					IDType soundID;
					soundDtors[soundIndex++] = engine->add(soundID);
					soundIndex %= soundDtors.size();
					engine->add<component::audiosource>(
					    soundID, assetM->get<polar::asset::audio>("menu1"),
					    support::audio::sourcetype::effect);
				}
			}
		} else if(!item.children.empty()) {
			navigate(0, 1, true);
		}
	}

	void menu::navigate(int down, int right, bool force) {
		auto &item = current_at(current);
		auto size = current_size();

		bool playBeep = false;

		bool newForce = force;
		if(!force && right && item.control && item.control->navigate(right)) {
			item.fn(item.control->get());
			render(current, true);
			playBeep = true;
		} else {
			newForce = force;
		}

		if(newForce) {
			while(right > 0) {
				auto &i = current_at(current);
				if(!i.children.empty()) {
					stack.emplace_back(current);
					current = 0;
					--right;
					playBeep = true;
				} else {
					activate();
				}
			}
			while(right < 0) {
				if(stack.empty()) {
					if(force) {
						engine->transition = "back";
						return;
					}
				} else {
					current = stack.back();
					stack.pop_back();
					++right;
					playBeep = true;
				}
			}
			render_all();
		}
		if(down != 0) {
			auto sz = current_size();
			auto previous = current;
			current += down;
			if(current < 0) {
				current += sz;
			} else {
				current %= sz;
			}
			render(previous, true);
			playBeep = true;
		}

		if(playBeep) {
			auto assetM = engine->get<asset>().lock();
			IDType soundID;
			soundDtors[soundIndex++] = engine->add(soundID);
			soundIndex %= soundDtors.size();
			engine->add<component::audiosource>(
			    soundID, assetM->get<polar::asset::audio>("menu1"),
			    support::audio::sourcetype::effect);
		}
	}

	void menu::render(size_t i, bool replace) {
		auto &item = current_at(i);
		auto size = current_size();

		IDType id;
		if(replace) {
			itemDtors.at(i) = engine->add(id);
		} else {
			itemDtors.emplace_back(engine->add(id));
		}

		// max 8 items on screen at max scale of uiBase
		const Decimal uiHeight     = 8 * uiBase;
		const Decimal uiTextHeight = 160;
		const Decimal uiTextWidth  = 550;

		Decimal scale =
		    glm::min(Decimal(uiHeight) / Decimal(size), Decimal(uiScale));
		Decimal spacing = uiTextHeight * scale;
		Point2 origin   = Point2(60, 50 + spacing * (size - i - 1));

		engine->add<component::text>(id, font, item.value);
		engine->add<component::screenposition>(id, origin);
		engine->add<component::scale>(id, Point3(scale));

		if(int(i) == current) {
			engine->add<component::color>(id, Point4(1, 1, selectionAlpha, 1));
		}

		if(item.control) {
			IDType controlID;
			auto offset = Point2(uiTextWidth / uiBase * scale, 0);
			offset.y -= 12 * scale;
			controlDtors[i] = item.control->render(engine, controlID,
			                                       origin + offset, 8 * scale);
		}
	}

	void menu::init() {
		using lifetime = support::action::lifetime;
		namespace a = support::action::menu;

		auto assetM = engine->get<asset>().lock();
		auto act    = engine->get<action>().lock();
		auto tw     = engine->get<tweener<float>>().lock();

		assetM->request<polar::asset::audio>("menu1");

		font = assetM->get<polar::asset::font>("nasalization-rg");

		keep(act->bind<a::down   >(lifetime::on, [this] { navigate( 1);    }));
		keep(act->bind<a::up     >(lifetime::on, [this] { navigate(-1);    }));
		keep(act->bind<a::right  >(lifetime::on, [this] { navigate(0,  1); }));
		keep(act->bind<a::left   >(lifetime::on, [this] { navigate(0, -1); }));
		keep(act->bind<a::forward>(lifetime::on, [this] { activate();      }));
		keep(act->bind<a::back   >(lifetime::on, [this] {
			navigate(0, -1, true);
		}));

		keep(tw->tween(0.0f, 1.0f, 0.25, true, [this](auto, const float &x) {
			selectionAlpha = x;
		}));

		render_all();
	}
} // namespace polar::system
<|endoftext|>


<commit_before>#include <cstdint>
#include <cstddef>
#include <cstdlib>
#include <cstdio>

#include <iostream>
#include <string>
#include <locale>
#include <codecvt>

#include <ase/ase.hpp>

class ColorPrinter : public ase::IColorCallback
{
public:
	ColorPrinter()
	{
	}
	~ColorPrinter()
	{
	}

	virtual void GroupBegin(
		const std::u16string& Name
	) override
	{
	}

	virtual void GroupEnd() override
	{
	}

	virtual void ColorGray(
		const std::u16string& Name,
		ase::ColorType::Gray Color
	) override
	{
		std::printf(
			"Gray:\t[ %8.4f ]\n",
			Color.f32[0]
		);
	}

	virtual void ColorRGB(
		const std::u16string& Name,
		ase::ColorType::RGB Color
	) override
	{
		std::printf(
			"RGB:\t[ %8.4f %8.4f %8.4f ]\n",
			Color.f32[0],
			Color.f32[1],
			Color.f32[2]
		);
	}

	virtual void ColorLAB(
		const std::u16string& Name,
		ase::ColorType::LAB Color
	) override
	{
		std::printf(
			"LAB:\t[ %8.4f %8.4f %8.4f ]\n",
			Color.f32[0],
			Color.f32[1],
			Color.f32[2]
		);
	}

	virtual void ColorCMYK(
		const std::u16string& Name,
		ase::ColorType::CMYK Color
	) override
	{
		std::printf(
			"CMYK:\t[ %8.4f %8.4f %8.4f %8.4f ]\n",
			Color.f32[0],
			Color.f32[1],
			Color.f32[2],
			Color.f32[3]
		);
	}
private:
};

int main( int argc, char* argv[])
{
	if( argc < 2 )
	{
		return EXIT_FAILURE;
	}
	ColorPrinter Printer;
	ase::LoadFromFile( Printer, argv[1] );
	return EXIT_SUCCESS;
}
<commit_msg>Update ColorPrinter formatting<commit_after>#include <cstdint>
#include <cstddef>
#include <cstdlib>
#include <cstdio>

#include <iostream>
#include <string>
#include <locale>
#include <codecvt>

#include <ase/ase.hpp>

class ColorPrinter : public ase::IColorCallback
{
public:
	ColorPrinter()
		:
		Depth(0)
	{
	}
	~ColorPrinter()
	{
	}

	virtual void GroupBegin(
		const std::u16string& Name
	) override
	{
		++Depth;
	}

	virtual void GroupEnd() override
	{
		--Depth;
	}

	virtual void ColorGray(
		const std::u16string& Name,
		ase::ColorType::Gray Color
	) override
	{
		std::printf(
			"%*sGray:\t[ %8.4f ]\n",
			Depth * 4, "",
			Color.f32[0]
		);
	}

	virtual void ColorRGB(
		const std::u16string& Name,
		ase::ColorType::RGB Color
	) override
	{
		std::printf(
			"%*sRGB:\t[ %8.4f %8.4f %8.4f ]\n",
			Depth * 4, "",
			Color.f32[0],
			Color.f32[1],
			Color.f32[2]
		);
	}

	virtual void ColorLAB(
		const std::u16string& Name,
		ase::ColorType::LAB Color
	) override
	{
		std::printf(
			"%*sLAB:\t[ %8.4f %8.4f %8.4f ]\n",
			Depth * TabWidth, "",
			Color.f32[0],
			Color.f32[1],
			Color.f32[2]
		);
	}

	virtual void ColorCMYK(
		const std::u16string& Name,
		ase::ColorType::CMYK Color
	) override
	{
		std::printf(
			"%*sCMYK:\t[ %8.4f %8.4f %8.4f %8.4f ]\n",
			Depth * TabWidth, "",
			Color.f32[0],
			Color.f32[1],
			Color.f32[2],
			Color.f32[3]
		);
	}
private:
	std::int32_t Depth;
	static constexpr std::size_t TabWidth = 4;
};

int main( int argc, char* argv[])
{
	if( argc < 2 )
	{
		return EXIT_FAILURE;
	}
	ColorPrinter Printer;
	ase::LoadFromFile( Printer, argv[1] );
	return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>#ifndef IMP_IMAGE_BASE_HPP
#define IMP_IMAGE_BASE_HPP

//#include "globaldefs.h"
//#include "coredefs.h"

#include <imp/core/pixel_enums.hpp>
#include <imp/core/size.hpp>

namespace imp {

//! \todo We maybe do not want to have the Image class in the public dll interface??
class ImageBase
{
protected:
  ImageBase(PixelType pixel_type) :
    pixel_type_(pixel_type), size_(0,0), roi_(0,0,0,0)
  {
  }

  ImageBase(const ImageBase &from) :
    pixel_type_(from.pixelType()), size_(from.size_), roi_(from.roi_)
  {
  }

  ImageBase(PixelType pixel_type, unsigned int width, unsigned int height) :
      pixel_type_(pixel_type), size_(width, height), roi_(0, 0, width, height)
  {
  }

  ImageBase(PixelType pixel_type, const Size &size) :
      pixel_type_(pixel_type), size_(size), roi_(0, 0, size.width, size.height)
  {
  }

public:

  virtual ~ImageBase()
  {
  }

  ImageBase& operator= (const ImageBase &from)
  {
    // TODO == operator
    this->pixel_type_ = from.pixel_type_;
    this->size_ = from.size_;
    this->roi_ = from.roi_;
    return *this;
  }

  void setRoi(const Rect& roi)
  {
    roi_ = roi;
  }

  /** Returns the element types. */
  PixelType pixelType() const
  {
    return pixel_type_;
  }

  Size size() const
  {
    return size_;
  }

  Rect roi() const
  {
    return roi_;
  }

  unsigned int width() const
  {
    return size_.width;
  }

  unsigned int height() const
  {
    return size_.height;
  }

  /** Returns the number of pixels in the image. */
  size_t numel() const
  {
    return (size_.width * size_.height);
  }

  /** Returns the total amount of bytes saved in the data buffer. */
  virtual size_t bytes() const = 0;

  /** Returns the distance in bytes between starts of consecutive rows. */
  virtual std::uint32_t pitch() const = 0;

  /** Returns the distnace in pixels between starts of consecutive rows. */
  virtual std::uint32_t stride() const = 0;

  /** Returns the bit depth of the data pointer. */
  virtual std::uint8_t bitDepth() const = 0;

  /** Returns flag if the image data resides on the device/GPU (TRUE) or host/GPU (FALSE) */
  virtual bool isGpuMemory() const = 0;

private:
  PixelType pixel_type_;
  PixelOrder pixel_order_;
  Size size_;
  Rect roi_;
};

} // namespace iuprivate

#endif // IMP_IMAGE_H
<commit_msg>roi defined<commit_after>#ifndef IMP_IMAGE_BASE_HPP
#define IMP_IMAGE_BASE_HPP

//#include "globaldefs.h"
//#include "coredefs.h"

#include <imp/core/pixel_enums.hpp>
#include <imp/core/size.hpp>
#include <imp/core/roi.hpp>

namespace imp {

//! \todo We maybe do not want to have the Image class in the public dll interface??
class ImageBase
{
protected:
  ImageBase(PixelType pixel_type) :
    pixel_type_(pixel_type), size_(0,0), roi_(0,0,0,0)
  {
  }

  ImageBase(const ImageBase &from) :
    pixel_type_(from.pixelType()), size_(from.size_), roi_(from.roi_)
  {
  }

  ImageBase(PixelType pixel_type, unsigned int width, unsigned int height) :
      pixel_type_(pixel_type), size_(width, height), roi_(0, 0, width, height)
  {
  }

  ImageBase(PixelType pixel_type, const Size &size) :
      pixel_type_(pixel_type), size_(size), roi_(0, 0, size.width, size.height)
  {
  }

public:

  virtual ~ImageBase()
  {
  }

  ImageBase& operator= (const ImageBase &from)
  {
    // TODO == operator
    this->pixel_type_ = from.pixel_type_;
    this->size_ = from.size_;
    this->roi_ = from.roi_;
    return *this;
  }

  void setRoi(const Rect& roi)
  {
    roi_ = roi;
  }

  /** Returns the element types. */
  PixelType pixelType() const
  {
    return pixel_type_;
  }

  Size size() const
  {
    return size_;
  }

  Rect roi() const
  {
    return roi_;
  }

  unsigned int width() const
  {
    return size_.width;
  }

  unsigned int height() const
  {
    return size_.height;
  }

  /** Returns the number of pixels in the image. */
  size_t numel() const
  {
    return (size_.width * size_.height);
  }

  /** Returns the total amount of bytes saved in the data buffer. */
  virtual size_t bytes() const = 0;

  /** Returns the distance in bytes between starts of consecutive rows. */
  virtual std::uint32_t pitch() const = 0;

  /** Returns the distnace in pixels between starts of consecutive rows. */
  virtual std::uint32_t stride() const = 0;

  /** Returns the bit depth of the data pointer. */
  virtual std::uint8_t bitDepth() const = 0;

  /** Returns flag if the image data resides on the device/GPU (TRUE) or host/GPU (FALSE) */
  virtual bool isGpuMemory() const = 0;

private:
  PixelType pixel_type_;
  PixelOrder pixel_order_;
  Size2u size_;
  Roi2u roi_;
};

} // namespace iuprivate

#endif // IMP_IMAGE_H
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: XMLStarBasicContextFactory.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: dvo $ $Date: 2001-08-03 18:14:08 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _XMLOFF_XMLSTARBASICCONTEXTFACTORY_HXX
#define _XMLOFF_XMLSTARBASICCONTEXTFACTORY_HXX

#ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_
#include <com/sun/star/uno/Reference.hxx>
#endif

#ifndef _XMLOFF_XMLEVENT_HXX
#include "xmlevent.hxx"
#endif

namespace com { namespace sun { namespace star {
    namespace xml { namespace sax { class XAttributeList; } }
} } }
namespace rtl { class OUString; }
class SvXMLImport;
class XMLEventsImportContext;

class XMLStarBasicContextFactory : public XMLEventContextFactory
{
    const ::rtl::OUString sEventType;
    const ::rtl::OUString sLibrary;
    const ::rtl::OUString sMacroName;
    const ::rtl::OUString sStarBasic;

public:
    XMLStarBasicContextFactory();
    virtual ~XMLStarBasicContextFactory();

    virtual SvXMLImportContext* CreateContext(
        SvXMLImport& rImport,               /// import context
        sal_uInt16 nPrefix,                 /// element: namespace prefix
        const ::rtl::OUString& rLocalName,  /// element: local name
        const ::com::sun::star::uno::Reference<     /// attribute list
            ::com::sun::star::xml::sax::XAttributeList> & xAttrList,
        /// the context for the enclosing <script:events> element
        XMLEventsImportContext* rEvents,
        /// the event name (as understood by the API)
        const ::rtl::OUString& rApiEventName,
        /// the event type name (as registered)
        const ::rtl::OUString& rLanguage);
};

#endif
<commit_msg>INTEGRATION: CWS ooo19126 (1.2.634); FILE MERGED 2005/09/05 14:37:59 rt 1.2.634.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: XMLStarBasicContextFactory.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 12:55:56 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _XMLOFF_XMLSTARBASICCONTEXTFACTORY_HXX
#define _XMLOFF_XMLSTARBASICCONTEXTFACTORY_HXX

#ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_
#include <com/sun/star/uno/Reference.hxx>
#endif

#ifndef _XMLOFF_XMLEVENT_HXX
#include "xmlevent.hxx"
#endif

namespace com { namespace sun { namespace star {
    namespace xml { namespace sax { class XAttributeList; } }
} } }
namespace rtl { class OUString; }
class SvXMLImport;
class XMLEventsImportContext;

class XMLStarBasicContextFactory : public XMLEventContextFactory
{
    const ::rtl::OUString sEventType;
    const ::rtl::OUString sLibrary;
    const ::rtl::OUString sMacroName;
    const ::rtl::OUString sStarBasic;

public:
    XMLStarBasicContextFactory();
    virtual ~XMLStarBasicContextFactory();

    virtual SvXMLImportContext* CreateContext(
        SvXMLImport& rImport,               /// import context
        sal_uInt16 nPrefix,                 /// element: namespace prefix
        const ::rtl::OUString& rLocalName,  /// element: local name
        const ::com::sun::star::uno::Reference<     /// attribute list
            ::com::sun::star::xml::sax::XAttributeList> & xAttrList,
        /// the context for the enclosing <script:events> element
        XMLEventsImportContext* rEvents,
        /// the event name (as understood by the API)
        const ::rtl::OUString& rApiEventName,
        /// the event type name (as registered)
        const ::rtl::OUString& rLanguage);
};

#endif
<|endoftext|>