<commit_before>#include "r_texture.h"
#include "u_sha512.h"
#include "u_file.h"
#include "engine.h"

#ifdef GL_UNSIGNED_INT_8_8_8_8_REV
#   define R_TEX_DATA_RGBA GL_UNSIGNED_INT_8_8_8_8_REV
#else
#   define R_TEX_DATA_RGBA GL_UNSINGED_BYTE
#endif
#ifdef GL_UNSIGNED_INT_8_8_8_8
#   define R_TEX_DATA_BGRA GL_UNSIGNED_INT_8_8_8_8
#else
#   define R_TEX_DATA_BGRA GL_UNSIGNED_BYTE
#endif

struct textureDXTCacheHeader {
    size_t width;
    size_t height;
    // Original format (RGB or RGBA) == (DXT1 or DXT5)
    textureFormat format;
};

static bool readDXTCache(texture &tex) {
    // Do we even have it in cache?
    const u::string path = neoPath() + "cache/";
    u::sha512 hash(tex.data(), tex.size());
    const u::string file = path + hash.hex();
    if (!u::exists(file))
        return false;

    // Found it in cache, unload the current texture and load the cache from disk.
    auto load = u::read(file, "rb");
    if (!load)
        return false;

    // Parse header
    auto vec = *load;
    textureDXTCacheHeader head;
    memcpy(&head, &vec[0], sizeof(head));

    const unsigned char *data = &vec[0] + sizeof(head);
    const size_t length = vec.size() - sizeof(head);

    // Now swap!
    tex.unload();
    tex.from(data, length, head.width, head.height, head.format);

    printf("R DXT: %s\n", file.c_str());
    return true;
}

static bool writeDXTCache(const texture &tex, GLuint handle) {
    // Don't bother caching if we already have it
    const u::string path = neoPath() + "cache/";
    u::sha512 hash(tex.data(), tex.size());
    const u::string file = path + hash.hex();
    if (u::exists(file))
        return false;

    // Build the header
    textureDXTCacheHeader head;
    head.width = tex.width();
    head.height = tex.height();
    head.format = tex.format();

    // Query the compressed texture size
    gl::BindTexture(GL_TEXTURE_2D, handle);
    GLint compressedSize;
    gl::GetTexLevelParameteriv(GL_TEXTURE_2D, 0,
        GL_TEXTURE_COMPRESSED_IMAGE_SIZE, &compressedSize);

    // Prepare the data
    u::vector<unsigned char> data;
    data.resize(sizeof(head) + compressedSize);
    memcpy(&data[0], &head, sizeof(head));

    // Read the compressed image
    gl::GetCompressedTexImage(GL_TEXTURE_2D, 0, &data[0] + sizeof(head));

    // Write it to disk!
    printf("W DXT: %s\n", file.c_str());
    return u::write(data, file);
}

struct queryFormat {
    GLenum format;
    GLenum data;
    GLenum internal;
};

// Given a source texture the following function finds the best way to present
// that texture to the hardware. This function will also favor texture compression
// if the hardware supports it by converting the texture if it needs to.
static queryFormat getBestFormat(texture &tex) {
    queryFormat fmt;
    memset(&fmt, 0, sizeof(fmt));
    textureFormat format = tex.format();

    // Convert the textures to a format S3TC texture compression supports if
    // the hardware supports S3TC compression
    if (gl::has("GL_EXT_texture_compression_s3tc")) {
        if (format == TEX_BGRA)
            tex.convert<TEX_RGBA>();
        else if (format == TEX_BGR)
            tex.convert<TEX_RGB>();
    }

    switch (format) {
        case TEX_RGBA:
            fmt.format = GL_RGBA;
            fmt.data = R_TEX_DATA_RGBA;
            if (gl::has("GL_EXT_texture_compression_s3tc"))
                fmt.internal = GL_COMPRESSED_RGBA_S3TC_DXT5_EXT;
            else
                fmt.internal = GL_RGBA;
            break;
        case TEX_RGB:
            fmt.format = GL_RGB;
            fmt.data = GL_UNSIGNED_BYTE;
            if (gl::has("GL_EXT_texture_compression_s3tc"))
                fmt.internal = GL_COMPRESSED_RGB_S3TC_DXT1_EXT;
            else
                fmt.internal = GL_RGBA;
            break;

        case TEX_BGRA:
            fmt.format = GL_BGRA;
            fmt.data = R_TEX_DATA_BGRA;
            fmt.internal = GL_RGBA;
            break;
        case TEX_BGR:
            fmt.format = GL_BGR;
            fmt.data = GL_UNSIGNED_BYTE;
            fmt.internal = GL_RGBA;
            break;
        case TEX_LUMINANCE:
            fmt.format = GL_RED;
            fmt.data = GL_UNSIGNED_BYTE;
            fmt.internal = GL_RED;
            break;
    }
    return fmt;
}

texture2D::texture2D(void) :
    m_uploaded(false),
    m_textureHandle(0)
{
    //
}

texture2D::~texture2D(void) {
    if (m_uploaded)
        gl::DeleteTextures(1, &m_textureHandle);
}

bool texture2D::useDXTCache(void) {
    if (!gl::has("GL_EXT_texture_compression_s3tc"))
        return false;
    if (!readDXTCache(m_texture))
        return false;
    switch (m_texture.format()) {
        case TEX_RGB:
            gl::CompressedTexImage2D(GL_TEXTURE_2D, 0, GL_COMPRESSED_RGB_S3TC_DXT1_EXT,
                m_texture.width(), m_texture.height(), 0, m_texture.size(), m_texture.data());
            break;
        case TEX_RGBA:
            gl::CompressedTexImage2D(GL_TEXTURE_2D, 0, GL_COMPRESSED_RGBA_S3TC_DXT5_EXT,
                m_texture.width(), m_texture.height(), 0, m_texture.size(), m_texture.data());
            break;
        default:
            neoFatal("malformatted DXT cache");
    }
    return true;
}

bool texture2D::cacheDXT(void) {
    if (gl::has("GL_EXT_texture_compression_s3tc"))
        return writeDXTCache(m_texture, m_textureHandle);
    return false;
}

bool texture2D::load(const u::string &file) {
    return m_texture.load(file);
}

bool texture2D::upload(void) {
    if (m_uploaded)
        return true;

    gl::GenTextures(1, &m_textureHandle);
    gl::BindTexture(GL_TEXTURE_2D, m_textureHandle);

    bool useCache = useDXTCache();
    if (!useCache) {
        queryFormat format = getBestFormat(m_texture);
        gl::TexImage2D(GL_TEXTURE_2D, 0, format.internal, m_texture.width(),
            m_texture.height(), 0, format.format, format.data, m_texture.data());
    }

    gl::GenerateMipmap(GL_TEXTURE_2D);
    gl::TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    gl::TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
    gl::TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    gl::TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);

    if (!useCache)
        cacheDXT();

    return m_uploaded = true;
}

void texture2D::bind(GLenum unit) {
    gl::ActiveTexture(unit);
    gl::BindTexture(GL_TEXTURE_2D, m_textureHandle);
}

void texture2D::resize(size_t width, size_t height) {
    m_texture.resize(width, height);
}

///! texture3D
texture3D::texture3D() :
    m_uploaded(false),
    m_textureHandle(0)
{
}

texture3D::~texture3D(void) {
    if (m_uploaded)
        gl::DeleteTextures(1, &m_textureHandle);
}

bool texture3D::load(const u::string &ft, const u::string &bk, const u::string &up,
                     const u::string &dn, const u::string &rt, const u::string &lf)
{
    if (!m_textures[0].load(ft)) return false;
    if (!m_textures[1].load(bk)) return false;
    if (!m_textures[2].load(up)) return false;
    if (!m_textures[3].load(dn)) return false;
    if (!m_textures[4].load(rt)) return false;
    if (!m_textures[5].load(lf)) return false;
    return true;
}

bool texture3D::upload(void) {
    if (m_uploaded)
        return true;

    gl::GenTextures(1, &m_textureHandle);
    gl::BindTexture(GL_TEXTURE_CUBE_MAP, m_textureHandle);

    gl::TexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    gl::TexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    gl::TexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    gl::TexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    gl::TexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);

    // find the largest texture in the cubemap and scale all others to it
    size_t mw = 0;
    size_t mh = 0;
    size_t mi = 0;
    for (size_t i = 0; i < 6; i++) {
        if (m_textures[i].width() > mw && m_textures[i].height() > mh)
            mi = i;
    }

    const size_t fw = m_textures[mi].width();
    const size_t fh = m_textures[mi].height();
    for (size_t i = 0; i < 6; i++) {
        if (m_textures[i].width() != fw || m_textures[i].height() != fh)
            m_textures[i].resize(fw, fh);
        queryFormat format = getBestFormat(m_textures[i]);
        gl::TexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0,
            format.internal, fw, fh, 0, format.format, format.data, m_textures[i].data());
    }

    return m_uploaded = true;
}

void texture3D::bind(GLenum unit) {
    gl::ActiveTexture(unit);
    gl::BindTexture(GL_TEXTURE_CUBE_MAP, m_textureHandle);
}

void texture3D::resize(size_t width, size_t height) {
    for (size_t i = 0; i < 6; i++)
        m_textures[i].resize(width, height);
}
<commit_msg>Remove prints<commit_after>#include "r_texture.h"
#include "u_sha512.h"
#include "u_file.h"
#include "engine.h"

#ifdef GL_UNSIGNED_INT_8_8_8_8_REV
#   define R_TEX_DATA_RGBA GL_UNSIGNED_INT_8_8_8_8_REV
#else
#   define R_TEX_DATA_RGBA GL_UNSINGED_BYTE
#endif
#ifdef GL_UNSIGNED_INT_8_8_8_8
#   define R_TEX_DATA_BGRA GL_UNSIGNED_INT_8_8_8_8
#else
#   define R_TEX_DATA_BGRA GL_UNSIGNED_BYTE
#endif

struct textureDXTCacheHeader {
    size_t width;
    size_t height;
    // Original format (RGB or RGBA) == (DXT1 or DXT5)
    textureFormat format;
};

static bool readDXTCache(texture &tex) {
    // Do we even have it in cache?
    const u::string path = neoPath() + "cache/";
    u::sha512 hash(tex.data(), tex.size());
    const u::string file = path + hash.hex();
    if (!u::exists(file))
        return false;

    // Found it in cache, unload the current texture and load the cache from disk.
    auto load = u::read(file, "rb");
    if (!load)
        return false;

    // Parse header
    auto vec = *load;
    textureDXTCacheHeader head;
    memcpy(&head, &vec[0], sizeof(head));

    const unsigned char *data = &vec[0] + sizeof(head);
    const size_t length = vec.size() - sizeof(head);

    // Now swap!
    tex.unload();
    tex.from(data, length, head.width, head.height, head.format);
    return true;
}

static bool writeDXTCache(const texture &tex, GLuint handle) {
    // Don't bother caching if we already have it
    const u::string path = neoPath() + "cache/";
    u::sha512 hash(tex.data(), tex.size());
    const u::string file = path + hash.hex();
    if (u::exists(file))
        return false;

    // Build the header
    textureDXTCacheHeader head;
    head.width = tex.width();
    head.height = tex.height();
    head.format = tex.format();

    // Query the compressed texture size
    gl::BindTexture(GL_TEXTURE_2D, handle);
    GLint compressedSize;
    gl::GetTexLevelParameteriv(GL_TEXTURE_2D, 0,
        GL_TEXTURE_COMPRESSED_IMAGE_SIZE, &compressedSize);

    // Prepare the data
    u::vector<unsigned char> data;
    data.resize(sizeof(head) + compressedSize);
    memcpy(&data[0], &head, sizeof(head));

    // Read the compressed image
    gl::GetCompressedTexImage(GL_TEXTURE_2D, 0, &data[0] + sizeof(head));

    // Write it to disk!
    return u::write(data, file);
}

struct queryFormat {
    GLenum format;
    GLenum data;
    GLenum internal;
};

// Given a source texture the following function finds the best way to present
// that texture to the hardware. This function will also favor texture compression
// if the hardware supports it by converting the texture if it needs to.
static queryFormat getBestFormat(texture &tex) {
    queryFormat fmt;
    memset(&fmt, 0, sizeof(fmt));
    textureFormat format = tex.format();

    // Convert the textures to a format S3TC texture compression supports if
    // the hardware supports S3TC compression
    if (gl::has("GL_EXT_texture_compression_s3tc")) {
        if (format == TEX_BGRA)
            tex.convert<TEX_RGBA>();
        else if (format == TEX_BGR)
            tex.convert<TEX_RGB>();
    }

    switch (format) {
        case TEX_RGBA:
            fmt.format = GL_RGBA;
            fmt.data = R_TEX_DATA_RGBA;
            if (gl::has("GL_EXT_texture_compression_s3tc"))
                fmt.internal = GL_COMPRESSED_RGBA_S3TC_DXT5_EXT;
            else
                fmt.internal = GL_RGBA;
            break;
        case TEX_RGB:
            fmt.format = GL_RGB;
            fmt.data = GL_UNSIGNED_BYTE;
            if (gl::has("GL_EXT_texture_compression_s3tc"))
                fmt.internal = GL_COMPRESSED_RGB_S3TC_DXT1_EXT;
            else
                fmt.internal = GL_RGBA;
            break;

        case TEX_BGRA:
            fmt.format = GL_BGRA;
            fmt.data = R_TEX_DATA_BGRA;
            fmt.internal = GL_RGBA;
            break;
        case TEX_BGR:
            fmt.format = GL_BGR;
            fmt.data = GL_UNSIGNED_BYTE;
            fmt.internal = GL_RGBA;
            break;
        case TEX_LUMINANCE:
            fmt.format = GL_RED;
            fmt.data = GL_UNSIGNED_BYTE;
            fmt.internal = GL_RED;
            break;
    }
    return fmt;
}

texture2D::texture2D(void) :
    m_uploaded(false),
    m_textureHandle(0)
{
    //
}

texture2D::~texture2D(void) {
    if (m_uploaded)
        gl::DeleteTextures(1, &m_textureHandle);
}

bool texture2D::useDXTCache(void) {
    if (!gl::has("GL_EXT_texture_compression_s3tc"))
        return false;
    if (!readDXTCache(m_texture))
        return false;
    switch (m_texture.format()) {
        case TEX_RGB:
            gl::CompressedTexImage2D(GL_TEXTURE_2D, 0, GL_COMPRESSED_RGB_S3TC_DXT1_EXT,
                m_texture.width(), m_texture.height(), 0, m_texture.size(), m_texture.data());
            break;
        case TEX_RGBA:
            gl::CompressedTexImage2D(GL_TEXTURE_2D, 0, GL_COMPRESSED_RGBA_S3TC_DXT5_EXT,
                m_texture.width(), m_texture.height(), 0, m_texture.size(), m_texture.data());
            break;
        default:
            neoFatal("malformatted DXT cache");
    }
    return true;
}

bool texture2D::cacheDXT(void) {
    if (gl::has("GL_EXT_texture_compression_s3tc"))
        return writeDXTCache(m_texture, m_textureHandle);
    return false;
}

bool texture2D::load(const u::string &file) {
    return m_texture.load(file);
}

bool texture2D::upload(void) {
    if (m_uploaded)
        return true;

    gl::GenTextures(1, &m_textureHandle);
    gl::BindTexture(GL_TEXTURE_2D, m_textureHandle);

    bool useCache = useDXTCache();
    if (!useCache) {
        queryFormat format = getBestFormat(m_texture);
        gl::TexImage2D(GL_TEXTURE_2D, 0, format.internal, m_texture.width(),
            m_texture.height(), 0, format.format, format.data, m_texture.data());
    }

    gl::GenerateMipmap(GL_TEXTURE_2D);
    gl::TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    gl::TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
    gl::TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    gl::TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);

    if (!useCache)
        cacheDXT();

    return m_uploaded = true;
}

void texture2D::bind(GLenum unit) {
    gl::ActiveTexture(unit);
    gl::BindTexture(GL_TEXTURE_2D, m_textureHandle);
}

void texture2D::resize(size_t width, size_t height) {
    m_texture.resize(width, height);
}

///! texture3D
texture3D::texture3D() :
    m_uploaded(false),
    m_textureHandle(0)
{
}

texture3D::~texture3D(void) {
    if (m_uploaded)
        gl::DeleteTextures(1, &m_textureHandle);
}

bool texture3D::load(const u::string &ft, const u::string &bk, const u::string &up,
                     const u::string &dn, const u::string &rt, const u::string &lf)
{
    if (!m_textures[0].load(ft)) return false;
    if (!m_textures[1].load(bk)) return false;
    if (!m_textures[2].load(up)) return false;
    if (!m_textures[3].load(dn)) return false;
    if (!m_textures[4].load(rt)) return false;
    if (!m_textures[5].load(lf)) return false;
    return true;
}

bool texture3D::upload(void) {
    if (m_uploaded)
        return true;

    gl::GenTextures(1, &m_textureHandle);
    gl::BindTexture(GL_TEXTURE_CUBE_MAP, m_textureHandle);

    gl::TexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    gl::TexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    gl::TexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    gl::TexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    gl::TexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);

    // find the largest texture in the cubemap and scale all others to it
    size_t mw = 0;
    size_t mh = 0;
    size_t mi = 0;
    for (size_t i = 0; i < 6; i++) {
        if (m_textures[i].width() > mw && m_textures[i].height() > mh)
            mi = i;
    }

    const size_t fw = m_textures[mi].width();
    const size_t fh = m_textures[mi].height();
    for (size_t i = 0; i < 6; i++) {
        if (m_textures[i].width() != fw || m_textures[i].height() != fh)
            m_textures[i].resize(fw, fh);
        queryFormat format = getBestFormat(m_textures[i]);
        gl::TexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0,
            format.internal, fw, fh, 0, format.format, format.data, m_textures[i].data());
    }

    return m_uploaded = true;
}

void texture3D::bind(GLenum unit) {
    gl::ActiveTexture(unit);
    gl::BindTexture(GL_TEXTURE_CUBE_MAP, m_textureHandle);
}

void texture3D::resize(size_t width, size_t height) {
    for (size_t i = 0; i < 6; i++)
        m_textures[i].resize(width, height);
}
<|endoftext|>


<commit_before>#ifndef __Rectangle__
#define __Rectangle__

#ifdef __APPLE__
#include <GLUT/glut.h>
#else
#include <GL/glut.h>
#endif
#include "color.hpp"

using namespace std;

class Rectangle {
public:
	double x1, y1, x2, y2;
	double width, height;
	Color color;

	void init(double x, double y, double w, double h, Color c);

	Rectangle();
	Rectangle(double x, double y, double w, double h);
	Rectangle(double x, double y, double w, double h, Color c);
	Rectangle(const Rectangle &c);
	Rectangle &operator= (const Rectangle &c);

	void setX(double x);
	void setY(double y);
	void setWidth(double w);
	void setHeight(double h);
	void setColor(Color c);

	double getX();
	double getY();
	double getWidth();
	double getHeight();

	bool hover(double x, double y);
	void draw();
};

#endif<commit_msg>Switch rectangle to use ui.hpp<commit_after>#ifndef __Rectangle__
#define __Rectangle__

#include "ui.hpp"

using namespace std;

class Rectangle {
public:
	double x1, y1, x2, y2;
	double width, height;
	Color color;

	void init(double x, double y, double w, double h, Color c);

	Rectangle();
	Rectangle(double x, double y, double w, double h);
	Rectangle(double x, double y, double w, double h, Color c);
	Rectangle(const Rectangle &c);
	Rectangle &operator= (const Rectangle &c);

	void setX(double x);
	void setY(double y);
	void setWidth(double w);
	void setHeight(double h);
	void setColor(Color c);

	double getX();
	double getY();
	double getWidth();
	double getHeight();

	bool hover(double x, double y);
	void draw();
};

#endif<|endoftext|>


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

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkImportContainerTest.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Insight Software Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

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

=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif

#include <iostream>
#include "itkImportImageContainer.h"
#include "itkNumericTraits.h"
#include "itkOutputWindow.h"
#include "itkTextOutput.h"

int itkImportContainerTest(int , char * [] )
{
  typedef float PixelType;
  typedef itk::ImportImageContainer<unsigned long, PixelType> ContainerType;

  itk::OutputWindow::SetInstance(itk::TextOutput::New());

// First test with ContainerManagesMemory false
  PixelType *ptr1;
  {
  // Test 1: Create an empty container and print it
  ContainerType::Pointer container1 = ContainerType::New();
  container1->Print(std::cout);
  std::cout << "After New(), size is "
            << container1->Size()
            << ", capacity is "
            <<  container1->Capacity()
            << " and import pointer is "
            << container1->GetImportPointer()
            << std::endl;

  // Test 2: Reserve memory
  container1->Reserve(1000);
  std::cout << "After container1->Reserve(1000), size is "
            << container1->Size()
            << ", capacity is "
            <<  container1->Capacity()
            << " and import pointer is "
            << container1->GetImportPointer()
            << std::endl;

  // Take control of the pointer
  container1->ContainerManageMemoryOff();
  ptr1 = container1->GetImportPointer();

  // Test 3: Reserve a smaller amount of memory
  container1->Reserve(100);
  std::cout << "After container1->Reserve(100), size is "
            << container1->Size()
            << ", capacity is "
            <<  container1->Capacity()
            << " and import pointer is "
            << container1->GetImportPointer()
            << std::endl;

  // Test 4: Squeeze the container
  container1->Squeeze();
  std::cout << "After container1->Squeeze() size is "
            << container1->Size()
            << ", capacity is "
            <<  container1->Capacity()
            << " and import pointer is "
            << container1->GetImportPointer()
            << std::endl;

  // Test 5: Initialize the container
  container1->Initialize();
  std::cout << "After container1->Initialize() size is "
            << container1->Size()
            << ", capacity is "
            <<  container1->Capacity()
            << " and import pointer is "
            << container1->GetImportPointer()
            << std::endl;
  }

// now repeat the tests with a user provided pointer
  PixelType *myPtr = new float[2000];
  {
  // Test 1: Create an empty container and print it
  ContainerType::Pointer container1 = ContainerType::New();
  container1->Print(std::cout);
  std::cout << "After New(), size is "
            << container1->Size()
            << ", capacity is "
            <<  container1->Capacity()
            << " and import pointer is "
            << container1->GetImportPointer()
            << std::endl;

  container1->SetImportPointer(myPtr, 2000);
  std::cout << "After New(), size is "
            << container1->Size()
            << ", capacity is "
            <<  container1->Capacity()
            << " and import pointer is "
            << container1->GetImportPointer()
            << std::endl;

  *(myPtr + 500) = 500.0;

  // Test 2: Reserve less memory than capacity
  container1->Reserve(1000);
  std::cout << "After container1->Reserve(1000), size is "
            << container1->Size()
            << ", capacity is "
            <<  container1->Capacity()
            << " and import pointer is "
            << container1->GetImportPointer()
            << std::endl;

  if (*(myPtr + 500) != 500.0)
    {
    std::cout << "Test failed: After container1->Reserve(1000), container1[500] does != 500." << std::endl;
    return EXIT_FAILURE;
    }

  // Test 3: Reserve more memory than capacity
  container1->Reserve(10000);
  std::cout << "After container1->Reserve(100), size is "
            << container1->Size()
            << ", capacity is "
            <<  container1->Capacity()
            << " and import pointer is "
            << container1->GetImportPointer()
            << std::endl;
  if (*(myPtr + 500) != 500.0)
    {
    std::cout << "Test failed: After container1->Reserve(10000), container1[500] does != 500." << std::endl;
    return EXIT_FAILURE;
    }

  // Test 4: Squeeze the container
  container1->Squeeze();
  std::cout << "After container1->Squeeze() size is "
            << container1->Size()
            << ", capacity is "
            <<  container1->Capacity()
            << " and import pointer is "
            << container1->GetImportPointer()
            << std::endl;

  if (*(myPtr + 500) != 500.0)
    {
    std::cout << "Test failed: After container1->Squeeze(), container1[500] does != 500." << std::endl;
    return EXIT_FAILURE;
    }

  // Test 5: Initialize the container
  container1->Initialize();
  std::cout << "After container1->Initialize() size is "
            << container1->Size()
            << ", capacity is "
            <<  container1->Capacity()
            << " and import pointer is "
            << container1->GetImportPointer()
            << std::endl;
  }

  // Now repeat tests with ContainerManagesMemory true
  {
  // Test 1: Create an empty container and print it
  ContainerType::Pointer container1 = ContainerType::New();
  container1->Print(std::cout);
  std::cout << "After New(), size is "
            << container1->Size()
            << ", capacity is "
            <<  container1->Capacity()
            << " and import pointer is "
            << container1->GetImportPointer()
            << std::endl;

  // Test 2: Reserve memory
  container1->Reserve(1000);
  std::cout << "After container1->Reserve(1000), size is "
            << container1->Size()
            << ", capacity is "
            <<  container1->Capacity()
            << " and import pointer is "
            << container1->GetImportPointer()
            << std::endl;

  // Test 3: Reserve a smaller amount of memory
  container1->Reserve(100);
  std::cout << "After container1->Reserve(100), size is "
            << container1->Size()
            << ", capacity is "
            <<  container1->Capacity()
            << " and import pointer is "
            << container1->GetImportPointer()
            << std::endl;

  // Test 4: Squeeze the container
  container1->Squeeze();
  std::cout << "After container1->Squeeze() size is "
            << container1->Size()
            << ", capacity is "
            <<  container1->Capacity()
            << " and import pointer is "
            << container1->GetImportPointer()
            << std::endl;

  // Test 5: Initialize the container
  container1->Initialize();
  std::cout << "After container1->Initialize() size is "
            << container1->Size()
            << ", capacity is "
            <<  container1->Capacity()
            << " and import pointer is "
            << container1->GetImportPointer()
            << std::endl;
  }

  // SGI's always say they can get you the memory you want.
#if !defined(__sgi)
  // Check the exception on the memory allocation
  bool caughtException = false;
  try
    {
    ContainerType::Pointer container1 = ContainerType::New();
    container1->Reserve( itk::NumericTraits<unsigned long>::max()/sizeof(PixelType));
    }
  catch (itk::ExceptionObject& err)
    {
    std::cout << "Caught expected exception: " << err << std::endl;
    caughtException = true;
    }
#else
  caughtException = true;
#endif

  // We must delete the memory we said we would manage
  delete [] ptr1;
  delete [] myPtr;

  if (!caughtException)
    {
    std::cout << "Failed to catch expected exception" << std::endl;
    return EXIT_FAILURE;
    }
  return EXIT_SUCCESS;
}
<commit_msg>COMP: SGIs always say they can get the memory you ask for. The expected exception will not be thrown. The oversized memory request is skipped for SGIs.<commit_after>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkImportContainerTest.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Insight Software Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

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

=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif

#include <iostream>
#include "itkImportImageContainer.h"
#include "itkNumericTraits.h"
#include "itkOutputWindow.h"
#include "itkTextOutput.h"

int itkImportContainerTest(int , char * [] )
{
  typedef float PixelType;
  typedef itk::ImportImageContainer<unsigned long, PixelType> ContainerType;

  itk::OutputWindow::SetInstance(itk::TextOutput::New());

// First test with ContainerManagesMemory false
  PixelType *ptr1;
  {
  // Test 1: Create an empty container and print it
  ContainerType::Pointer container1 = ContainerType::New();
  container1->Print(std::cout);
  std::cout << "After New(), size is "
            << container1->Size()
            << ", capacity is "
            <<  container1->Capacity()
            << " and import pointer is "
            << container1->GetImportPointer()
            << std::endl;

  // Test 2: Reserve memory
  container1->Reserve(1000);
  std::cout << "After container1->Reserve(1000), size is "
            << container1->Size()
            << ", capacity is "
            <<  container1->Capacity()
            << " and import pointer is "
            << container1->GetImportPointer()
            << std::endl;

  // Take control of the pointer
  container1->ContainerManageMemoryOff();
  ptr1 = container1->GetImportPointer();

  // Test 3: Reserve a smaller amount of memory
  container1->Reserve(100);
  std::cout << "After container1->Reserve(100), size is "
            << container1->Size()
            << ", capacity is "
            <<  container1->Capacity()
            << " and import pointer is "
            << container1->GetImportPointer()
            << std::endl;

  // Test 4: Squeeze the container
  container1->Squeeze();
  std::cout << "After container1->Squeeze() size is "
            << container1->Size()
            << ", capacity is "
            <<  container1->Capacity()
            << " and import pointer is "
            << container1->GetImportPointer()
            << std::endl;

  // Test 5: Initialize the container
  container1->Initialize();
  std::cout << "After container1->Initialize() size is "
            << container1->Size()
            << ", capacity is "
            <<  container1->Capacity()
            << " and import pointer is "
            << container1->GetImportPointer()
            << std::endl;
  }

// now repeat the tests with a user provided pointer
  PixelType *myPtr = new float[2000];
  {
  // Test 1: Create an empty container and print it
  ContainerType::Pointer container1 = ContainerType::New();
  container1->Print(std::cout);
  std::cout << "After New(), size is "
            << container1->Size()
            << ", capacity is "
            <<  container1->Capacity()
            << " and import pointer is "
            << container1->GetImportPointer()
            << std::endl;

  container1->SetImportPointer(myPtr, 2000);
  std::cout << "After New(), size is "
            << container1->Size()
            << ", capacity is "
            <<  container1->Capacity()
            << " and import pointer is "
            << container1->GetImportPointer()
            << std::endl;

  *(myPtr + 500) = 500.0;

  // Test 2: Reserve less memory than capacity
  container1->Reserve(1000);
  std::cout << "After container1->Reserve(1000), size is "
            << container1->Size()
            << ", capacity is "
            <<  container1->Capacity()
            << " and import pointer is "
            << container1->GetImportPointer()
            << std::endl;

  if (*(myPtr + 500) != 500.0)
    {
    std::cout << "Test failed: After container1->Reserve(1000), container1[500] does != 500." << std::endl;
    return EXIT_FAILURE;
    }

  // Test 3: Reserve more memory than capacity
  container1->Reserve(10000);
  std::cout << "After container1->Reserve(100), size is "
            << container1->Size()
            << ", capacity is "
            <<  container1->Capacity()
            << " and import pointer is "
            << container1->GetImportPointer()
            << std::endl;
  if (*(myPtr + 500) != 500.0)
    {
    std::cout << "Test failed: After container1->Reserve(10000), container1[500] does != 500." << std::endl;
    return EXIT_FAILURE;
    }

  // Test 4: Squeeze the container
  container1->Squeeze();
  std::cout << "After container1->Squeeze() size is "
            << container1->Size()
            << ", capacity is "
            <<  container1->Capacity()
            << " and import pointer is "
            << container1->GetImportPointer()
            << std::endl;

  if (*(myPtr + 500) != 500.0)
    {
    std::cout << "Test failed: After container1->Squeeze(), container1[500] does != 500." << std::endl;
    return EXIT_FAILURE;
    }

  // Test 5: Initialize the container
  container1->Initialize();
  std::cout << "After container1->Initialize() size is "
            << container1->Size()
            << ", capacity is "
            <<  container1->Capacity()
            << " and import pointer is "
            << container1->GetImportPointer()
            << std::endl;
  }

  // Now repeat tests with ContainerManagesMemory true
  {
  // Test 1: Create an empty container and print it
  ContainerType::Pointer container1 = ContainerType::New();
  container1->Print(std::cout);
  std::cout << "After New(), size is "
            << container1->Size()
            << ", capacity is "
            <<  container1->Capacity()
            << " and import pointer is "
            << container1->GetImportPointer()
            << std::endl;

  // Test 2: Reserve memory
  container1->Reserve(1000);
  std::cout << "After container1->Reserve(1000), size is "
            << container1->Size()
            << ", capacity is "
            <<  container1->Capacity()
            << " and import pointer is "
            << container1->GetImportPointer()
            << std::endl;

  // Test 3: Reserve a smaller amount of memory
  container1->Reserve(100);
  std::cout << "After container1->Reserve(100), size is "
            << container1->Size()
            << ", capacity is "
            <<  container1->Capacity()
            << " and import pointer is "
            << container1->GetImportPointer()
            << std::endl;

  // Test 4: Squeeze the container
  container1->Squeeze();
  std::cout << "After container1->Squeeze() size is "
            << container1->Size()
            << ", capacity is "
            <<  container1->Capacity()
            << " and import pointer is "
            << container1->GetImportPointer()
            << std::endl;

  // Test 5: Initialize the container
  container1->Initialize();
  std::cout << "After container1->Initialize() size is "
            << container1->Size()
            << ", capacity is "
            <<  container1->Capacity()
            << " and import pointer is "
            << container1->GetImportPointer()
            << std::endl;
  }

  // SGI's always say they can get you the memory you want.
#if !defined(__sgi)
  // Check the exception on the memory allocation
  bool caughtException = false;
  try
    {
    ContainerType::Pointer container1 = ContainerType::New();
    container1->Reserve( itk::NumericTraits<unsigned long>::max()/sizeof(PixelType));
    }
  catch (itk::ExceptionObject& err)
    {
    std::cout << "Caught expected exception: " << err << std::endl;
    caughtException = true;
    }
#endif

  // We must delete the memory we said we would manage
  delete [] ptr1;
  delete [] myPtr;

  // SGI's always say they can get you the memory you want.
#if !defined(__sgi)
  if (!caughtException)
    {
    std::cout << "Failed to catch expected exception" << std::endl;
    return EXIT_FAILURE;
    }
#endif
  return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>#include <stdio.h>
//#include "jsoncpp/json/json.h"
#include <map>
#include <errno.h>
#include <fcntl.h>
#include <string>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

#include "nvme.h"
#include "mp.h"

class StringSearchResponse : public StringSearchResponseWrapper {
public:
    virtual void strstrLoc ( const uint32_t pos ) {
	if (pos != -1)
	    fprintf(stderr, "string search at character pos=%d\n", pos);
    }
    StringSearchResponse(int id, PortalPoller *poller = 0) : StringSearchResponseWrapper(id, poller) {
    }
};

int main(int argc, char * const *argv)
{
    Nvme nvme;
    StringSearchRequestProxy search(IfcNames_StringSearchRequestS2H);
    StringSearchResponse     searchResponse(IfcNames_StringSearchResponseH2S);

    int flags, opt;
    const char *filename;
    const char *needle = "needle";
    int source_fd = -1;

    int doidentify;
    int dosearch = 0;
    int dotrace = 0;
    int dowrite = 0;
    while ((opt = getopt(argc, argv, "iw:s:t")) != -1) {
	switch (opt) {
	case 'i':
	    doidentify = 1;
	    break;
	case 's':
	    needle = optarg;
	    dosearch = 1;
	    break;
	case 't':
	    dotrace = 1;
	    break;
	case 'w':
	    filename = optarg;
	    dowrite = 1;
	    break;
	}
    }

    if (dowrite) {
	struct stat statbuf;
	int rc = stat(filename, &statbuf);
	if (rc < 0) {
	    fprintf(stderr, "%s:%d File %s does not exist %d:%s\n", __FILE__, __LINE__, filename, errno, strerror(errno));
	    char pwd[128];
	    getcwd(pwd, sizeof(pwd));
	    fprintf(stderr, "cwd = %s\n", pwd);
	    return rc;
	}
    }

    sleep(1);

    nvme.setup();

    if (dosearch) {
	int needle_len = strlen(needle);
	int border[needle_len+1];

	compute_borders(nvme.needleBuffer.buffer(), border, needle_len);
	compute_MP_next(nvme.needleBuffer.buffer(), (struct MP *)nvme.mpNextBuffer.buffer(), needle_len);
	nvme.needleBuffer.cacheInvalidate(0, 1); // flush the whole thing
	nvme.mpNextBuffer.cacheInvalidate(0, 1); // flush the whole thing

	//FIXME: read the text from NVME storage
	//MP(needle, haystack, mpNext, needle_len, haystack_len, &sw_match_cnt);

	// the MPEngine will read in the needle and mpNext
	search.setSearchString(nvme.needleRef, nvme.mpNextRef, needle_len);
    }

    if (doidentify)
	nvme.identify();
    nvme.getFeatures();
    nvme.allocIOQueues(0);

    fprintf(stderr, "CSTS %08x\n", nvme.read32( 0x1c));
    int startBlock = 100000; // base and extent of test file in SSD
    int blocksPerRequest = 8; //12*BlocksPerRequest;
    int numBlocks = 1*blocksPerRequest; // 55; //8177;
    if (dosearch) {
	search.startSearch(numBlocks*512);
    } else {
      // if search is not running, then data read below will be discarded
    }
    if (dowrite) {
	struct stat statbuf;
	int rc = stat(filename, &statbuf);
	if (rc < 0) {
	    fprintf(stderr, "%s:%d File %s does not exist %d:%s\n", __FILE__, __LINE__, filename, errno, strerror(errno));
	    char pwd[128];
	    getcwd(pwd, sizeof(pwd));
	    fprintf(stderr, "cwd = %s\n", pwd);
	    return rc;
	}
	numBlocks = statbuf.st_blocks;
	numBlocks -= (numBlocks % blocksPerRequest);
	fprintf(stderr, "Writing %d blocks from file %s to flash at block %d\n", numBlocks, filename, startBlock);
	source_fd = open(filename, O_RDONLY);
    }

    for (int block = 0; block < numBlocks; block += blocksPerRequest) {
	nvme_io_opcode opcode = (dowrite) ? nvme_write : nvme_read;
	fprintf(stderr, "starting transfer dowrite=%d opcode=%d\n", dowrite, opcode);
	if (opcode == nvme_write) {
	    if (filename) {
		read(source_fd, (char *)nvme.transferBuffer.buffer(), 512*blocksPerRequest);
	    } else {
		    int *buffer = (int *)nvme.transferBuffer.buffer();
		for (int i = 0; i < numBlocks*512/4; i ++)
		    buffer[i] = i;
	    }
	}
	int sc = nvme.doIO(opcode, startBlock, blocksPerRequest, (opcode == nvme_read ? 2 : 1), dotrace);
	nvme.status();
	if (sc != 0)
	    break;
	startBlock += blocksPerRequest;
    }

    nvme.dumpTrace();
    //nvme.transferStats();
    fprintf(stderr, "CSTS %08x\n", nvme.read32( 0x1c));

    return 0;
}
<commit_msg>include ConnectalProjectConfig.h<commit_after>#include <stdio.h>
//#include "jsoncpp/json/json.h"
#include <map>
#include <errno.h>
#include <fcntl.h>
#include <string>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

#include "ConnectalProjectConfig.h"

#include "nvme.h"
#include "mp.h"

class StringSearchResponse : public StringSearchResponseWrapper {
public:
    virtual void strstrLoc ( const uint32_t pos ) {
	if (pos != -1)
	    fprintf(stderr, "string search at character pos=%d\n", pos);
    }
    StringSearchResponse(int id, PortalPoller *poller = 0) : StringSearchResponseWrapper(id, poller) {
    }
};

int main(int argc, char * const *argv)
{
    Nvme nvme;
    StringSearchRequestProxy search(IfcNames_StringSearchRequestS2H);
    StringSearchResponse     searchResponse(IfcNames_StringSearchResponseH2S);

    int flags, opt;
    const char *filename;
    const char *needle = "needle";
    int source_fd = -1;

    int doidentify;
    int dosearch = 0;
    int dotrace = 0;
    int dowrite = 0;
    while ((opt = getopt(argc, argv, "iw:s:t")) != -1) {
	switch (opt) {
	case 'i':
	    doidentify = 1;
	    break;
	case 's':
	    needle = optarg;
	    dosearch = 1;
	    break;
	case 't':
	    dotrace = 1;
	    break;
	case 'w':
	    filename = optarg;
	    dowrite = 1;
	    break;
	}
    }

    if (dowrite) {
	struct stat statbuf;
	int rc = stat(filename, &statbuf);
	if (rc < 0) {
	    fprintf(stderr, "%s:%d File %s does not exist %d:%s\n", __FILE__, __LINE__, filename, errno, strerror(errno));
	    char pwd[128];
	    getcwd(pwd, sizeof(pwd));
	    fprintf(stderr, "cwd = %s\n", pwd);
	    return rc;
	}
    }

    sleep(1);

    nvme.setup();

    if (dosearch) {
	int needle_len = strlen(needle);
	int border[needle_len+1];

	compute_borders(nvme.needleBuffer.buffer(), border, needle_len);
	compute_MP_next(nvme.needleBuffer.buffer(), (struct MP *)nvme.mpNextBuffer.buffer(), needle_len);
	nvme.needleBuffer.cacheInvalidate(0, 1); // flush the whole thing
	nvme.mpNextBuffer.cacheInvalidate(0, 1); // flush the whole thing

	//FIXME: read the text from NVME storage
	//MP(needle, haystack, mpNext, needle_len, haystack_len, &sw_match_cnt);

	// the MPEngine will read in the needle and mpNext
	search.setSearchString(nvme.needleRef, nvme.mpNextRef, needle_len);
    }

    if (doidentify)
	nvme.identify();
    nvme.getFeatures();
    nvme.allocIOQueues(0);

    fprintf(stderr, "CSTS %08x\n", nvme.read32( 0x1c));
    int startBlock = 100000; // base and extent of test file in SSD
    int blocksPerRequest = 8; //12*BlocksPerRequest;
    int numBlocks = 1*blocksPerRequest; // 55; //8177;
    if (dosearch) {
	search.startSearch(numBlocks*512);
    } else {
      // if search is not running, then data read below will be discarded
    }
    if (dowrite) {
	struct stat statbuf;
	int rc = stat(filename, &statbuf);
	if (rc < 0) {
	    fprintf(stderr, "%s:%d File %s does not exist %d:%s\n", __FILE__, __LINE__, filename, errno, strerror(errno));
	    char pwd[128];
	    getcwd(pwd, sizeof(pwd));
	    fprintf(stderr, "cwd = %s\n", pwd);
	    return rc;
	}
	numBlocks = statbuf.st_blocks;
	numBlocks -= (numBlocks % blocksPerRequest);
	fprintf(stderr, "Writing %d blocks from file %s to flash at block %d\n", numBlocks, filename, startBlock);
	source_fd = open(filename, O_RDONLY);
    }

    for (int block = 0; block < numBlocks; block += blocksPerRequest) {
	nvme_io_opcode opcode = (dowrite) ? nvme_write : nvme_read;
	fprintf(stderr, "starting transfer dowrite=%d opcode=%d\n", dowrite, opcode);
	if (opcode == nvme_write) {
	    if (filename) {
		read(source_fd, (char *)nvme.transferBuffer.buffer(), 512*blocksPerRequest);
	    } else {
		    int *buffer = (int *)nvme.transferBuffer.buffer();
		for (int i = 0; i < numBlocks*512/4; i ++)
		    buffer[i] = i;
	    }
	}
	int sc = nvme.doIO(opcode, startBlock, blocksPerRequest, (opcode == nvme_read ? 2 : 1), dotrace);
	nvme.status();
	if (sc != 0)
	    break;
	startBlock += blocksPerRequest;
    }

    nvme.dumpTrace();
    //nvme.transferStats();
    fprintf(stderr, "CSTS %08x\n", nvme.read32( 0x1c));

    return 0;
}
<|endoftext|>


<commit_before>#include "ros_video_components/ros_signal_strength.hpp"
/*#include <QLabel>
#include <QMainWindow>
#include <QApplication>*/

#define RECT_X 5
#define RECT_Y 100
#define RECT_WIDTH RECT_X*40
#define RECT_HEIGHT 150
#define MAXDATA 100
#define MAXNUM 10
#define NUMCOLOR 3
#define GREEN 8
#define YELLOW 4
#define RED 1
#define HASH MAXDATA/MAXNUM
#define TOO_WEAK MAXDATA/20

ROS_Signal_Strength::ROS_Signal_Strength(QQuickItem * parent) :
    QQuickPaintedItem(parent),
    current_image(NULL),
    current_buffer(NULL),
    topic_value("/cam0"),
    ros_ready(false),
    img_trans(NULL) {
}

void ROS_Signal_Strength::setup(ros::NodeHandle * nh) {

    img_trans = new image_transport::ImageTransport(*nh);
    //TODO: make these parameters of the component
    image_sub = img_trans->subscribe(
          topic_value.toStdString(),
          1,
          &ROS_Signal_Strength::receive_image,
          this,
          image_transport::TransportHints("compressed")
    );

    ros_ready = true;
    ROS_INFO("Setup of video component complete");
}

void ROS_Signal_Strength::receive_image(const sensor_msgs::Image::ConstPtr &msg) {
    // check to see if we already have an image frame, if we do then we need to
    // delete it to avoid memory leaks
    if( current_image ) {
        delete current_image;
    }

    // allocate a buffer of sufficient size to contain our video frame
    uchar * temp_buffer = (uchar *) malloc(sizeof(uchar) * msg->data.size());

    // and copy the message into the buffer
    // we need to do this because QImage api requires the buffer we pass in to
    // continue to exist whilst the image is in use, but the msg and it's data will
    // be lost once we leave this context
    current_image = new QImage(
          temp_buffer,
          msg->width,
          msg->height,
          QImage::Format_RGB888 // TODO: detect the type from the message
    );

    ROS_INFO("Recieved Message");

    // We then swap out of bufer to avoid memory leaks
    if(current_buffer) {
        delete current_buffer;
        current_buffer = temp_buffer;
    }

    // finally we need to re-render the component to display the new image
    update();
}

void ROS_Signal_Strength::paint(QPainter * painter) {

	int data = 2; //int data = getSignalStrength
     //painter->drawImage(QPoint(5,0), *(this->current_image));
    //painter->drawArc(0, 0, 100, 10, 3, 10);
	int x = RECT_X;
	int y = RECT_Y;
	int width = RECT_WIDTH;
	int height = RECT_HEIGHT;

	//QPainter::drawRect(x, y, width, height);
	/*draw 4 more rectangles. the base of each would be
	x+y. **MORE EXPERIMENTATION NEEDED ON THIS ONE**
	num/25 rectangles*/
	QLinearGradient linearGradient(0, 0, 100, 100);
	int num = 0;
	float hash = HASH;
	if(data >= MAXDATA){
		num = MAXNUM;
	}else if(data <= TOO_WEAK){
		num = 0;
		linearGradient.setColorAt(0.0, Qt::white);
		painter->setBrush(linearGradient);
	}else{
		num = (data/hash) +1;
	}
	painter->drawRect(x, y, width, height); //draw the main rectangle
	//int i = 0;
	//y -= x;
	//int barWidth = width/numBars;
	int barWidth = width/MAXNUM;
	int barHeight = height/MAXNUM;
	y += ((MAXNUM-1) * height) /MAXNUM;
	const int increment = height/MAXNUM;
	//ROS_INFO("y is %d, barHeight is %d\n",y, barHeight);
	if(num == 0){
		//print flashing "NO SIGNAL" on the screen
		/*QLabel * label = new QLabel(&mainWindow);
		label->setText("NO SIGNAL\n");
		mainWindow.show();*/
		ROS_INFO("NO SIGNAL\n");
	}else{
		for(int i = 1; i <= num; i++){

		    if(num >= GREEN/*(MAXNUM - (MAXNUM/NUMCOLOR))*/){
			    linearGradient.setColorAt(0.2, Qt::green);
		    }else if(num >= YELLOW/*(MAXNUM/NUMCOLOR)*/){
			    linearGradient.setColorAt(0.2, Qt::yellow);
		    }else{
		    	linearGradient.setColorAt(0.2, Qt::red);
		    }
		    //linearGradient.setColorAt(1.0, Qt::black);
		    painter->setBrush(linearGradient);
			painter->drawRect(x, y, barWidth, barHeight);
			x += barWidth; //move x along
			barHeight += increment; //increase height
			y -= increment; //decrease height
		}
	}

    //if(current_image) {
    //    painter->drawImage(QPoint(0,0), *(this->current_image));
    //}
}

void ROS_Signal_Strength::set_topic(const QString & new_value) {
    if(topic_value != new_value) {
        topic_value = new_value;
        if(ros_ready) {
            image_sub.shutdown();
            image_sub = img_trans->subscribe(
                  topic_value.toStdString(),
                  1,
                  &ROS_Signal_Strength::receive_image,
                  this,
                  image_transport::TransportHints("compressed")
            );
        }
        emit topic_changed();
    }
}

QString ROS_Signal_Strength::get_topic() const {
    return topic_value;
}
<commit_msg>Tested with different MAXDATA<commit_after>#include "ros_video_components/ros_signal_strength.hpp"
/*#include <QLabel>
#include <QMainWindow>
#include <QApplication>*/

#define RECT_X 5
#define RECT_Y 100
#define RECT_WIDTH RECT_X*40
#define RECT_HEIGHT 150
#define MAXDATA 100
#define MAXNUM 5
#define NUMCOLOR 3
#define GREEN 4
#define YELLOW 2
#define RED 1
#define HASH MAXDATA/MAXNUM
#define TOO_WEAK MAXDATA/20

ROS_Signal_Strength::ROS_Signal_Strength(QQuickItem * parent) :
    QQuickPaintedItem(parent),
    current_image(NULL),
    current_buffer(NULL),
    topic_value("/cam0"),
    ros_ready(false),
    img_trans(NULL) {
}

void ROS_Signal_Strength::setup(ros::NodeHandle * nh) {

    img_trans = new image_transport::ImageTransport(*nh);
    //TODO: make these parameters of the component
    image_sub = img_trans->subscribe(
          topic_value.toStdString(),
          1,
          &ROS_Signal_Strength::receive_image,
          this,
          image_transport::TransportHints("compressed")
    );

    ros_ready = true;
    ROS_INFO("Setup of video component complete");
}

void ROS_Signal_Strength::receive_image(const sensor_msgs::Image::ConstPtr &msg) {
    // check to see if we already have an image frame, if we do then we need to
    // delete it to avoid memory leaks
    if( current_image ) {
        delete current_image;
    }

    // allocate a buffer of sufficient size to contain our video frame
    uchar * temp_buffer = (uchar *) malloc(sizeof(uchar) * msg->data.size());

    // and copy the message into the buffer
    // we need to do this because QImage api requires the buffer we pass in to
    // continue to exist whilst the image is in use, but the msg and it's data will
    // be lost once we leave this context
    current_image = new QImage(
          temp_buffer,
          msg->width,
          msg->height,
          QImage::Format_RGB888 // TODO: detect the type from the message
    );

    ROS_INFO("Recieved Message");

    // We then swap out of bufer to avoid memory leaks
    if(current_buffer) {
        delete current_buffer;
        current_buffer = temp_buffer;
    }

    // finally we need to re-render the component to display the new image
    update();
}

void ROS_Signal_Strength::paint(QPainter * painter) {

	int data = 3; //int data = getSignalStrength();
     //painter->drawImage(QPoint(5,0), *(this->current_image));
    //painter->drawArc(0, 0, 100, 10, 3, 10);
	int x = RECT_X;
	int y = RECT_Y;
	int width = RECT_WIDTH;
	int height = RECT_HEIGHT;

	//QPainter::drawRect(x, y, width, height);
	/*draw 4 more rectangles. the base of each would be
	x+y. **MORE EXPERIMENTATION NEEDED ON THIS ONE**
	num/25 rectangles*/
	QLinearGradient linearGradient(0, 0, 100, 100);
	int num = 0;
	float hash = HASH;
	if(data >= MAXDATA){
		num = MAXNUM;
	}else if(data <= TOO_WEAK){
		num = 0;
		linearGradient.setColorAt(0.0, Qt::white);
		painter->setBrush(linearGradient);
	}else{
		num = (data/hash) +1;
	}
	painter->drawRect(x, y, width, height); //draw the main rectangle
	//int i = 0;
	//y -= x;
	//int barWidth = width/numBars;
	int barWidth = width/MAXNUM;
	int barHeight = height/MAXNUM;
	y += ((MAXNUM-1) * height) /MAXNUM;
	const int increment = height/MAXNUM;
	//ROS_INFO("y is %d, barHeight is %d\n",y, barHeight);
	if(num == 0){
		//print flashing "NO SIGNAL" on the screen
		/*QLabel * label = new QLabel(&mainWindow);
		label->setText("NO SIGNAL\n");
		mainWindow.show();*/
		ROS_INFO("NO SIGNAL\n");
	}else{
		for(int i = 1; i <= num; i++){

		    if(num >= GREEN/*(MAXNUM - (MAXNUM/NUMCOLOR))*/){
			    linearGradient.setColorAt(0.2, Qt::green);
		    }else if(num >= YELLOW/*(MAXNUM/NUMCOLOR)*/){
			    linearGradient.setColorAt(0.2, Qt::yellow);
		    }else{
		    	linearGradient.setColorAt(0.2, Qt::red);
		    }
		    //linearGradient.setColorAt(1.0, Qt::black);
		    painter->setBrush(linearGradient);
			painter->drawRect(x, y, barWidth, barHeight);
			x += barWidth; //move x along
			barHeight += increment; //increase height
			y -= increment; //decrease height
		}
	}

    //if(current_image) {
    //    painter->drawImage(QPoint(0,0), *(this->current_image));
    //}
}

void ROS_Signal_Strength::set_topic(const QString & new_value) {
    if(topic_value != new_value) {
        topic_value = new_value;
        if(ros_ready) {
            image_sub.shutdown();
            image_sub = img_trans->subscribe(
                  topic_value.toStdString(),
                  1,
                  &ROS_Signal_Strength::receive_image,
                  this,
                  image_transport::TransportHints("compressed")
            );
        }
        emit topic_changed();
    }
}

QString ROS_Signal_Strength::get_topic() const {
    return topic_value;
}
<|endoftext|>


<commit_before>/*************************************************
* Wrappers for X.509 types                       *
* (C) 2005-2006 Jack Lloyd <lloyd@randombit.net> *
*************************************************/

#include <botan/oids.h>
#include <botan/pipe.h>
#include <botan/filters.h>
#include <botan/x509cert.h>
#include <botan/x509stor.h>
using namespace Botan;

#include <boost/python.hpp>
namespace python = boost::python;

template<typename T>
class vector_to_list
   {
   public:
      static PyObject* convert(const std::vector<T>& in)
         {
         python::list out;
         typename std::vector<T>::const_iterator i = in.begin();
         while(i != in.end())
            {
            out.append(*i);
            ++i;
            }
         return python::incref(out.ptr());
         }

      vector_to_list()
         {
         python::to_python_converter<std::vector<T>, vector_to_list<T> >();
         }
   };

template<typename T>
class memvec_to_hexstr
   {
   public:
      static PyObject* convert(const T& in)
         {
         Pipe pipe(new Hex_Encoder);
         pipe.process_msg(in);
         std::string result = pipe.read_all_as_string();
         return python::incref(python::str(result).ptr());
         }

      memvec_to_hexstr()
         {
         python::to_python_converter<T, memvec_to_hexstr<T> >();
         }
   };

class X509_Store_Search_Wrap : public X509_Store::Search_Func,
                               public python::wrapper<X509_Store::Search_Func>
   {
   public:
      bool match(const X509_Certificate& cert) const
         {
         return this->get_override("match")(cert);
         }
   };

BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(add_cert_ols, add_cert, 1, 2)
BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(validate_cert_ols, validate_cert, 1, 2)

void export_x509()
   {
   vector_to_list<std::string>();
   vector_to_list<X509_Certificate>();
   memvec_to_hexstr<MemoryVector<byte> >();

   python::class_<X509_Certificate>
      ("X509_Certificate", python::init<std::string>())
      .def(python::self == python::self)
      .def(python::self != python::self)
      .add_property("version", &X509_Certificate::x509_version)
      .add_property("is_CA", &X509_Certificate::is_CA_cert)
      .add_property("self_signed", &X509_Certificate::is_self_signed)
      .add_property("pathlimit", &X509_Certificate::path_limit)
      .add_property("as_pem", &X509_Object::PEM_encode)
      .def("start_time", &X509_Certificate::start_time)
      .def("end_time", &X509_Certificate::end_time)
      .def("subject_info", &X509_Certificate::subject_info)
      .def("issuer_info", &X509_Certificate::issuer_info)
      .def("ex_constraints", &X509_Certificate::ex_constraints)
      .def("policies", &X509_Certificate::policies)
      .def("subject_key_id", &X509_Certificate::subject_key_id)
      .def("authority_key_id", &X509_Certificate::authority_key_id);

   python::enum_<X509_Code>("verify_result")
      .value("verified", VERIFIED)
      .value("unknown_x509_error", UNKNOWN_X509_ERROR)
      .value("cannot_establish_trust", CANNOT_ESTABLISH_TRUST)
      .value("cert_chain_too_long", CERT_CHAIN_TOO_LONG)
      .value("signature_error", SIGNATURE_ERROR)
      .value("policy_error", POLICY_ERROR)
      .value("invalid_usage", INVALID_USAGE)
      .value("cert_format_error", CERT_FORMAT_ERROR)
      .value("cert_issuer_not_found", CERT_ISSUER_NOT_FOUND)
      .value("cert_not_yet_valid", CERT_NOT_YET_VALID)
      .value("cert_has_expired", CERT_HAS_EXPIRED)
      .value("cert_is_revoked", CERT_IS_REVOKED)
      .value("crl_format_error", CRL_FORMAT_ERROR)
      .value("crl_issuer_not_found", CRL_ISSUER_NOT_FOUND)
      .value("crl_not_yet_valid", CRL_NOT_YET_VALID)
      .value("crl_has_expired", CRL_HAS_EXPIRED)
      .value("ca_cert_cannot_sign", CA_CERT_CANNOT_SIGN)
      .value("ca_cert_not_for_cert_issuer", CA_CERT_NOT_FOR_CERT_ISSUER)
      .value("ca_cert_not_for_crl_issuer", CA_CERT_NOT_FOR_CRL_ISSUER);

   python::enum_<X509_Store::Cert_Usage>("cert_usage")
      .value("any", X509_Store::ANY)
      .value("tls_server", X509_Store::TLS_SERVER)
      .value("tls_client", X509_Store::TLS_CLIENT)
      .value("code_signing", X509_Store::CODE_SIGNING)
      .value("email_protection", X509_Store::EMAIL_PROTECTION)
      .value("time_stamping", X509_Store::TIME_STAMPING)
      .value("crl_signing", X509_Store::CRL_SIGNING);

      {
      python::scope in_class =
         python::class_<X509_Store>("X509_Store")
         .def("add_cert", &X509_Store::add_cert, add_cert_ols())
         .def("validate", &X509_Store::validate_cert, validate_cert_ols())
         .def("get_certs", &X509_Store::get_certs);

      python::class_<X509_Store_Search_Wrap, boost::noncopyable>
              ("Search_Func")
         .def("match", python::pure_virtual(&X509_Store::Search_Func::match));
      }
   }
<commit_msg>Add basic wrapping for X509_CRL, no member functions are exposed as they would require additional type conversions.<commit_after>/*************************************************
* Wrappers for X.509 types                       *
* (C) 2005-2006 Jack Lloyd <lloyd@randombit.net> *
*************************************************/

#include <botan/oids.h>
#include <botan/pipe.h>
#include <botan/filters.h>
#include <botan/x509cert.h>
#include <botan/x509_crl.h>
#include <botan/x509stor.h>
using namespace Botan;

#include <boost/python.hpp>
namespace python = boost::python;

template<typename T>
class vector_to_list
   {
   public:
      static PyObject* convert(const std::vector<T>& in)
         {
         python::list out;
         typename std::vector<T>::const_iterator i = in.begin();
         while(i != in.end())
            {
            out.append(*i);
            ++i;
            }
         return python::incref(out.ptr());
         }

      vector_to_list()
         {
         python::to_python_converter<std::vector<T>, vector_to_list<T> >();
         }
   };

template<typename T>
class memvec_to_hexstr
   {
   public:
      static PyObject* convert(const T& in)
         {
         Pipe pipe(new Hex_Encoder);
         pipe.process_msg(in);
         std::string result = pipe.read_all_as_string();
         return python::incref(python::str(result).ptr());
         }

      memvec_to_hexstr()
         {
         python::to_python_converter<T, memvec_to_hexstr<T> >();
         }
   };

class X509_Store_Search_Wrap : public X509_Store::Search_Func,
                               public python::wrapper<X509_Store::Search_Func>
   {
   public:
      bool match(const X509_Certificate& cert) const
         {
         return this->get_override("match")(cert);
         }
   };

BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(add_cert_ols, add_cert, 1, 2)
BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(validate_cert_ols, validate_cert, 1, 2)

void export_x509()
   {
   vector_to_list<std::string>();
   vector_to_list<X509_Certificate>();
   memvec_to_hexstr<MemoryVector<byte> >();

   python::class_<X509_Certificate>
      ("X509_Certificate", python::init<std::string>())
      .def(python::self == python::self)
      .def(python::self != python::self)
      .add_property("version", &X509_Certificate::x509_version)
      .add_property("is_CA", &X509_Certificate::is_CA_cert)
      .add_property("self_signed", &X509_Certificate::is_self_signed)
      .add_property("pathlimit", &X509_Certificate::path_limit)
      .add_property("as_pem", &X509_Object::PEM_encode)
      .def("start_time", &X509_Certificate::start_time)
      .def("end_time", &X509_Certificate::end_time)
      .def("subject_info", &X509_Certificate::subject_info)
      .def("issuer_info", &X509_Certificate::issuer_info)
      .def("ex_constraints", &X509_Certificate::ex_constraints)
      .def("policies", &X509_Certificate::policies)
      .def("subject_key_id", &X509_Certificate::subject_key_id)
      .def("authority_key_id", &X509_Certificate::authority_key_id);

   python::class_<X509_CRL>
      ("X509_CRL", python::init<std::string>())
      .add_property("as_pem", &X509_Object::PEM_encode);

   python::enum_<X509_Code>("verify_result")
      .value("verified", VERIFIED)
      .value("unknown_x509_error", UNKNOWN_X509_ERROR)
      .value("cannot_establish_trust", CANNOT_ESTABLISH_TRUST)
      .value("cert_chain_too_long", CERT_CHAIN_TOO_LONG)
      .value("signature_error", SIGNATURE_ERROR)
      .value("policy_error", POLICY_ERROR)
      .value("invalid_usage", INVALID_USAGE)
      .value("cert_format_error", CERT_FORMAT_ERROR)
      .value("cert_issuer_not_found", CERT_ISSUER_NOT_FOUND)
      .value("cert_not_yet_valid", CERT_NOT_YET_VALID)
      .value("cert_has_expired", CERT_HAS_EXPIRED)
      .value("cert_is_revoked", CERT_IS_REVOKED)
      .value("crl_format_error", CRL_FORMAT_ERROR)
      .value("crl_issuer_not_found", CRL_ISSUER_NOT_FOUND)
      .value("crl_not_yet_valid", CRL_NOT_YET_VALID)
      .value("crl_has_expired", CRL_HAS_EXPIRED)
      .value("ca_cert_cannot_sign", CA_CERT_CANNOT_SIGN)
      .value("ca_cert_not_for_cert_issuer", CA_CERT_NOT_FOR_CERT_ISSUER)
      .value("ca_cert_not_for_crl_issuer", CA_CERT_NOT_FOR_CRL_ISSUER);

   python::enum_<X509_Store::Cert_Usage>("cert_usage")
      .value("any", X509_Store::ANY)
      .value("tls_server", X509_Store::TLS_SERVER)
      .value("tls_client", X509_Store::TLS_CLIENT)
      .value("code_signing", X509_Store::CODE_SIGNING)
      .value("email_protection", X509_Store::EMAIL_PROTECTION)
      .value("time_stamping", X509_Store::TIME_STAMPING)
      .value("crl_signing", X509_Store::CRL_SIGNING);

      {
      python::scope in_class =
         python::class_<X509_Store>("X509_Store")
         .def("add_cert", &X509_Store::add_cert, add_cert_ols())
         .def("validate", &X509_Store::validate_cert, validate_cert_ols())
         .def("get_certs", &X509_Store::get_certs)
         .def("add_crl", &X509_Store::add_crl);

      python::class_<X509_Store_Search_Wrap, boost::noncopyable>
              ("Search_Func")
         .def("match", python::pure_virtual(&X509_Store::Search_Func::match));
      }
   }
<|endoftext|>


<commit_before>#ifndef _USE_MATH_DEFINES
#define _USE_MATH_DEFINES
#endif

#include <cmath>
#include <limits>
#include <fstream>
#include <iostream>
#include <algorithm>
#include <Tools/Noise/Noise.hpp>

#include "Frozenbits_generator_BEC.hpp"

using namespace aff3ct::tools;

Frozenbits_generator_BEC
::Frozenbits_generator_BEC(const int K, const int N)
: Frozenbits_generator(K, N), m((int)std::log2(N)), z((int)std::exp2(m), 0)
{
}

Frozenbits_generator_BEC
::~Frozenbits_generator_BEC()
{
}

void Frozenbits_generator_BEC
::evaluate()
{
	for (unsigned i = 0; i != this->best_channels.size(); i++)
		this->best_channels[i] = i;

	for (auto i = 0; i < std::exp2(m); i++)
		z[i] = 2.0 / std::pow((double)this->n->get_noise(), 2.0);

	for (auto l = 1; l <= m; l++)
	{
		auto o1 = (int)std::exp2(m - l +1);
		auto o2 = (int)std::exp2(m - l   );

//		for (auto t = 0; t < (int)std::exp2(l -1); t++)
//		{
//			double T = z[t * o1];
//
//			z[t * o1] = phi_inv(1.0 - std::pow(1.0 - phi(T), 2.0));
//			if (z[t * o1] == HUGE_VAL)
//				z[t * o1] = T + M_LN2 / (alpha * gamma);
//
//			z[t * o1 + o2] = 2.0 * T;
//		}
	}

	std::sort(this->best_channels.begin(), this->best_channels.end(), [this](int i1, int i2) { return z[i1] > z[i2]; });
}

void Frozenbits_generator_BEC
::check_noise()
{
	Frozenbits_generator::check_noise();

	this->n->is_of_type_throw(tools::Noise_type::EP);
}<commit_msg>Implement BEC frozen bits generator.<commit_after>#ifndef _USE_MATH_DEFINES
#define _USE_MATH_DEFINES
#endif

#include <cmath>
#include <limits>
#include <fstream>
#include <iostream>
#include <algorithm>
#include <Tools/Noise/Noise.hpp>

#include "Frozenbits_generator_BEC.hpp"

using namespace aff3ct::tools;

Frozenbits_generator_BEC
::Frozenbits_generator_BEC(const int K, const int N)
: Frozenbits_generator(K, N), m((int)std::log2(N)), z((int)std::exp2(m), 0)
{
}

Frozenbits_generator_BEC
::~Frozenbits_generator_BEC()
{
}

void Frozenbits_generator_BEC
::evaluate()
{
	for (unsigned i = 0; i != this->best_channels.size(); i++)
		this->best_channels[i] = i;

	for (auto i = 0; i < std::exp2(m); i++)
		z[i] = static_cast<double>(this->n->get_noise());

	for (auto l = 1; l <= m; l++)
	{
		auto o1 = (int)std::exp2(m - l +1);
		auto o2 = (int)std::exp2(m - l   );

		for (auto t = 0; t < (int)std::exp2(l -1); t++)
		{
			double T = z[t * o1];

			z[t * o1] = T * T;

			z[t * o1 + o2] = 2 * T - T * T ;
		}
	}

//	std::sort(this->best_channels.begin(), this->best_channels.end(), [this](int i1, int i2) { return z[i1] > z[i2]; });
//	for (auto chan : this->best_channels)
//		std::cout << chan << " ";
//	std::cout << std::endl;
}

void Frozenbits_generator_BEC
::check_noise()
{
	Frozenbits_generator::check_noise();

	this->n->is_of_type_throw(tools::Noise_type::EP);
}<|endoftext|>


<commit_before>#include "mob.hpp"

player::player(std::string name, std::string area, std::string skill, int level = 1, int EXP = 0)
{
  setName(name);
  setArea(area);
  setSkill(skill);
  setLevel(level);
  setEXP(EXP);
  setMaxHealth();
  setHealth(mobMaxHealth);
  setDamage();
}

//Member function definitions
void mob::setName(std::string name)
{
  mobName = name;
}
void mob::setArea(std::string area)
{
  mobName = name;
}
void mob::setSkill(std::string skill)
{
  mobSkill = skill;
}
void mob::setLevel(int level)
{
  mobLevel = level;
}
void mob::setEXP(int EXP)
{
  mobEXP = (35 * getLevel());
}
void mob::setHealth(int health)
{
  mobHealth = health;
}
void mob::setMaxHealth()
{
  mobMaxHealth = (63 * getLevel());
}
void mob::setDamage()
{
  mobDamage = (10 * getLevel());
}

//Member function constructors
void mob::getName()
{
  return mobName;
}
void mob::getArea()
{
  return mobArea;
}
void mob::getSkill()
{
  return mobSkill;
}
void mob::getLevel()
{
  return mobLevel;
}
void mob::getHealth()
{
  return mobHealth;
}
void mob::getMaxHealth()
{
  return mobMaxhealth;
}
void mob::getDamage()
{
  return mobDamage;
}
void mob::getEXP()
{
  return mobEXP;
}

<commit_msg>Update mob.cpp<commit_after>#include "mob.hpp"

player::player(std::string name, std::string area, std::string skill, int level = 1, int EXP = 0)
{
  setName(name);
  setArea(area);
  setSkill(skill);
  setLevel(level);
  setEXP(EXP);
  setMaxHealth();
  setHealth(mobMaxHealth);
  setDamage();
}

//Member function definitions
void mob::setName(std::string name)
{
  mobName = name;
}
void mob::setArea(std::string area)
{
  mobArea = area;
}
void mob::setSkill(std::string skill)
{
  mobSkill = skill;
}
void mob::setLevel(int level)
{
  mobLevel = level;
}
void mob::setEXP(int EXP)
{
  mobEXP = (35 * getLevel());
}
void mob::setHealth(int health)
{
  mobHealth = health;
}
void mob::setMaxHealth()
{
  mobMaxHealth = (63 * getLevel());
}
void mob::setDamage()
{
  mobDamage = (10 * getLevel());
}

//Member function constructors
void mob::getName()
{
  return mobName;
}
void mob::getArea()
{
  return mobArea;
}
void mob::getSkill()
{
  return mobSkill;
}
void mob::getLevel()
{
  return mobLevel;
}
void mob::getHealth()
{
  return mobHealth;
}
void mob::getMaxHealth()
{
  return mobMaxhealth;
}
void mob::getDamage()
{
  return mobDamage;
}
void mob::getEXP()
{
  return mobEXP;
}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: ActiveMSPList.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2004-05-19 08:27:33 $
 *
 *  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 _FRAMEWORK_SCRIPT_PROVIDER_OPENDOCUMENTLIST_HXX_
#define _FRAMEWORK_SCRIPT_PROVIDER_OPENDOCUMENTLIST_HXX_

#include <hash_map>
#include <map>

#include <osl/mutex.hxx>
#include <rtl/ustring>
#include <cppuhelper/implbase1.hxx>
#include <com/sun/star/uno/RuntimeException.hpp>
#include <com/sun/star/lang/XServiceInfo.hpp>

#include <com/sun/star/lang/XEventListener.hpp>
#include <com/sun/star/frame/XModel.hpp>

#include <drafts/com/sun/star/script/provider/XScriptProvider.hpp>
#include <drafts/com/sun/star/script/browse/XBrowseNode.hpp>

namespace func_provider
{
// for simplification
#define css ::com::sun::star
#define dcsss ::drafts::com::sun::star::script

//Typedefs
//=============================================================================

struct MspInst
{
    css::uno::Reference< dcsss::provider::XScriptProvider > provider;
    css::uno::Reference< dcsss::browse::XBrowseNode > node;
};

typedef ::std::map < css::uno::Reference< css::frame::XModel >,
                     MspInst > Model_map;

typedef ::std::hash_map< ::rtl::OUString,
    MspInst,
    ::rtl::OUStringHash,
            ::std::equal_to< ::rtl::OUString > > Msp_hash;

class ActiveMSPList : public ::cppu::WeakImplHelper1< css::lang::XEventListener  >
{

public:
    static ActiveMSPList& instance( const css::uno::Reference<
        css::uno::XComponentContext >& xContext );
    ~ActiveMSPList();
    void addActiveMSP( const css::uno::Reference< css::frame::XModel >& xModel,
                       const css::uno::Reference< dcsss::provider::XScriptProvider >& msp );

    //XEventListener
    //======================================================================

    virtual void SAL_CALL disposing( const css::lang::EventObject& Source )
        throw ( css::uno::RuntimeException );

    // Factory method for create MasterScriptProviders
    css::uno::Reference< dcsss::provider::XScriptProvider >
        createMSP( const css::uno::Any& context )
            throw ( css::uno::RuntimeException );
private:
    ActiveMSPList(  const css::uno::Reference<
        css::uno::XComponentContext > & xContext  );
    ::rtl::OUString
        getDocNameOrURLFromModel( const css::uno::Reference< css::frame::XModel >& xModel  );

    css::uno::Reference< dcsss::provider::XScriptProvider >
        createMSP( const ::rtl::OUString& context )
            throw ( css::uno::RuntimeException );

    css::uno::Reference< dcsss::provider::XScriptProvider >
        createMSP( const css::uno::Reference< css::frame::XModel >& xModel )
            throw ( css::uno::RuntimeException );

    css::uno::Reference< dcsss::provider::XScriptProvider >
        createNewMSP(  const css::uno::Any& )
            throw ( css::uno::RuntimeException );

    void createNonDocMSPs();
    Msp_hash m_hMsps;
    Model_map m_mModels;
    osl::Mutex m_mutex;
    ::rtl::OUString userDirString;
    ::rtl::OUString shareDirString;
    css::uno::Reference< css::uno::XComponentContext > m_xContext;
};
} // func_provider
#endif
<commit_msg>INTEGRATION: CWS scriptingf7 (1.4.4); FILE MERGED 2004/06/12 08:42:34 npower 1.4.4.1: #i25269# Add support for pkgchk.<commit_after>/*************************************************************************
 *
 *  $RCSfile: ActiveMSPList.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: hr $ $Date: 2004-07-23 14:09:20 $
 *
 *  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 _FRAMEWORK_SCRIPT_PROVIDER_OPENDOCUMENTLIST_HXX_
#define _FRAMEWORK_SCRIPT_PROVIDER_OPENDOCUMENTLIST_HXX_

#include <hash_map>
#include <map>

#include <osl/mutex.hxx>
#include <rtl/ustring>
#include <cppuhelper/implbase1.hxx>
#include <com/sun/star/uno/RuntimeException.hpp>
#include <com/sun/star/lang/XServiceInfo.hpp>

#include <com/sun/star/lang/XEventListener.hpp>
#include <com/sun/star/frame/XModel.hpp>

#include <drafts/com/sun/star/script/provider/XScriptProvider.hpp>
#include <drafts/com/sun/star/script/browse/XBrowseNode.hpp>

namespace func_provider
{
// for simplification
#define css ::com::sun::star
#define dcsss ::drafts::com::sun::star::script

//Typedefs
//=============================================================================

typedef ::std::map < css::uno::Reference< css::frame::XModel >,
                     css::uno::Reference< dcsss::provider::XScriptProvider > > Model_map;

typedef ::std::hash_map< ::rtl::OUString,
    css::uno::Reference< dcsss::provider::XScriptProvider >,
    ::rtl::OUStringHash,
            ::std::equal_to< ::rtl::OUString > > Msp_hash;

class ActiveMSPList : public ::cppu::WeakImplHelper1< css::lang::XEventListener  >
{

public:
    static ActiveMSPList& instance( const css::uno::Reference<
        css::uno::XComponentContext >& xContext );

    ActiveMSPList(  const css::uno::Reference<
        css::uno::XComponentContext > & xContext  );
    ~ActiveMSPList();
    css::uno::Reference< dcsss::provider::XScriptProvider >
        createMSP( const ::rtl::OUString& context )
            throw ( css::uno::RuntimeException );
    css::uno::Reference< dcsss::provider::XScriptProvider >
        createMSP( const css::uno::Any& context )
            throw ( css::uno::RuntimeException );
    css::uno::Sequence< css::uno::Reference< dcsss::provider::XScriptProvider > >
        getActiveProviders();
    //XEventListener
    //======================================================================

    virtual void SAL_CALL disposing( const css::lang::EventObject& Source )
        throw ( css::uno::RuntimeException );

private:
    void addActiveMSP( const css::uno::Reference< css::frame::XModel >& xModel,
                       const css::uno::Reference< dcsss::provider::XScriptProvider >& msp );
    css::uno::Reference< dcsss::provider::XScriptProvider >
        createNewMSP( const ::rtl::OUString& )
            throw ( css::uno::RuntimeException );
    void createNonDocMSPs();
    Msp_hash m_hMsps;
    Model_map m_mModels;
    osl::Mutex m_mutex;
    ::rtl::OUString userDirString;
    ::rtl::OUString shareDirString;
    css::uno::Reference< css::uno::XComponentContext > m_xContext;
};
} // func_provider
#endif
<|endoftext|>