<commit_before>
#include "Log.h"
#include "Platform.h"

#include <emscripten.h>
#include <emscripten/html5.h>
#include <GLES2/gl2.h>

using namespace std;

void report_result(int result)
{
  if (result == 0) {
    printf("Test successful!\n");
  } else {
    printf("Test failed!\n");
  }
#ifdef REPORT_RESULT
  REPORT_RESULT();
#endif
}

#define PIX_C(x, y) ((x)/256.0f + (y)/256.0f)
#define CLAMP(c) ((c) < 0.f ? 0.f : ((c) > 1.f ? 1.f : (c)))
#define PIX(x, y) CLAMP(PIX_C(x, y))

// ---

GLuint shader_program;

static const char *vss = R"(
attribute vec4 vPosition;
uniform mat4 mat;
varying vec2 texCoord;

void main()
{
  gl_Position = vPosition;
  texCoord = (vPosition.xy + vec2(1.0)) * vec2(0.5);
}
)";

static const char *pss = R"(
#ifdef GL_ES
precision lowp float;
#endif

varying vec2 texCoord;
uniform vec3 colors[3];
uniform sampler2D tex;

void main()
{
  gl_FragColor = texture2D(tex, texCoord);
}
)";

// ---

static GLuint make_shader(GLenum type, const char* text)
{
    GLuint shader = 0u;
    GLint shader_ok;

    shader = glCreateShader(type);
    if (shader != 0u)
    {
        glShaderSource(shader, 1, reinterpret_cast<const GLchar**>(&text), NULL);
        glCompileShader(shader);
        glGetShaderiv(shader, GL_COMPILE_STATUS, &shader_ok);
        if (shader_ok != GL_TRUE)
        {
            GLint maxLength = 0;
            glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &maxLength);
            string buf(maxLength, 0);
            glGetShaderInfoLog(shader, maxLength, &maxLength, &buf[0]);

            LOGE << "ERROR: Failed to compile " << ((type == GL_FRAGMENT_SHADER) ? "fragment" : "vertex") << " shader" << endl;
            LOGE << buf << endl;

            glDeleteShader(shader);
            shader = 0u;
        }
    }

    return shader;
}

static GLuint make_shader_program(const char* vs_text, const char* fs_text)
{
    GLuint program = 0u;
    GLint program_ok;
    GLuint vertex_shader = 0u;
    GLuint fragment_shader = 0u;

    vertex_shader = make_shader(GL_VERTEX_SHADER, vs_text);
    if (vertex_shader != 0u)
    {
        fragment_shader = make_shader(GL_FRAGMENT_SHADER, fs_text);
        if (fragment_shader != 0u)
        {
            /* make the program that connect the two shader and link it */
            program = glCreateProgram();
            if (program != 0u)
            {
                /* attach both shader and link */
                glAttachShader(program, vertex_shader);
                glAttachShader(program, fragment_shader);
                glLinkProgram(program);
                glGetProgramiv(program, GL_LINK_STATUS, &program_ok);

                if (program_ok != GL_TRUE)
                {
                    GLint maxLength = 0;
                    glGetShaderiv(program, GL_INFO_LOG_LENGTH, &maxLength);
                    string buf(maxLength, 0);
                    glGetShaderInfoLog(program, maxLength, &maxLength, &buf[0]);

                    LOGE << "ERROR: Failed to link shader program" << endl;
                    LOGE << buf << endl;

                    glDeleteProgram(program);
                    glDeleteShader(fragment_shader);
                    glDeleteShader(vertex_shader);
                    program = 0u;
                }
            }
        }
        else
        {
            LOGE << "ERROR: Unable to load fragment shader" << endl;
            glDeleteShader(vertex_shader);
        }
    }
    else
    {
        LOGE << "ERROR: Unable to load vertex shader" << endl;
    }

    return program;
}

// ---

void draw()
{
  int w, h, fs;
  emscripten_get_canvas_size(&w, &h, &fs);
  float xs = (float)h / w;
  float ys = 1.0f;
  float mat[] = { xs, 0, 0, 0, 0, ys, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 };
  glUniformMatrix4fv(glGetUniformLocation(shader_program, "mat"), 1, 0, mat);
  glClearColor(0,0,1,1);
  glClear(GL_COLOR_BUFFER_BIT);
  glDrawArrays(GL_TRIANGLES, 0, 6);

  unsigned char imageData[256*256*4];
  glReadPixels(0, 0, 256, 256, GL_RGBA, GL_UNSIGNED_BYTE, imageData);
  for(int y = 0; y < 256; ++y)
    for(int x = 0; x < 256; ++x)
    {
      unsigned char red = imageData[(y*256+x)*4];
      float expectedRed = PIX(x, y);
      unsigned char eRed = (unsigned char)(expectedRed * 255.0f);
      assert(fabs((int)eRed - red) <= 2);
    }
  emscripten_cancel_main_loop();
  report_result(0);
}

int main()
{
  emscripten_set_canvas_size(256, 256);
  EmscriptenWebGLContextAttributes attr;
  emscripten_webgl_init_context_attributes(&attr);
  attr.alpha = attr.depth = attr.stencil = attr.antialias = attr.preserveDrawingBuffer = attr.preferLowPowerToHighPerformance = attr.failIfMajorPerformanceCaveat = 0;
  attr.enableExtensionsByDefault = 1;
  attr.premultipliedAlpha = 0;
  attr.majorVersion = 1;
  attr.minorVersion = 0;
  EMSCRIPTEN_WEBGL_CONTEXT_HANDLE ctx = emscripten_webgl_create_context(0, &attr);
  emscripten_webgl_make_context_current(ctx);

  //

  shader_program = make_shader_program(vss, pss);
  if (shader_program == 0u)
  {
    return 0;
  }

  glUseProgram(shader_program);
  glBindAttribLocation(shader_program, 0, "vPosition");

  //

  GLuint vbo;
  glGenBuffers(1, &vbo);
  glBindBuffer(GL_ARRAY_BUFFER, vbo);

  float verts[] = { -1, -1, 1, -1, -1, 1, -1, 1, 1, -1, 1, 1 };
  glBufferData(GL_ARRAY_BUFFER, sizeof(verts), verts, GL_STATIC_DRAW);
  glVertexAttribPointer(0, 2, GL_FLOAT, 0, sizeof(float)*2, 0);
  glEnableVertexAttribArray(0);
  GLuint tex;
  glGenTextures(1, &tex);
  glBindTexture(GL_TEXTURE_2D, tex);
  glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
  glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
  float texData[256*256];
  for(int y = 0; y < 256; ++y)
    for(int x = 0; x < 256; ++x)
    {
      texData[y*256+x] = PIX(x, y);
    }
  glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE, 256, 256, 0, GL_LUMINANCE, GL_FLOAT, texData);
  emscripten_set_main_loop(draw, 0, 0);
  return 0;
}
<commit_msg>TestingWebGL: SWITCHING TO ANIMATION, BASED ON EMSCRIPTEN'S test_html5_fullscreen.c<commit_after>
#include "Log.h"
#include "Platform.h"

#include <emscripten.h>
#include <emscripten/html5.h>
#include <GLES2/gl2.h>
#include <math.h>

using namespace std;

void report_result(int result)
{
  if (result == 0) {
    printf("Test successful!\n");
  } else {
    printf("Test failed!\n");
  }
#ifdef REPORT_RESULT
  REPORT_RESULT();
#endif
}

// ---

GLuint shader_program;

static const char *vss = R"(
attribute vec4 vPosition;
uniform mat4 mat;

void main()
{
  gl_Position = mat * vPosition;
}
)";

static const char *pss = R"(
#ifdef GL_ES
precision lowp float;
#endif

uniform vec3 colors[3];

void main()
{
  gl_FragColor = vec4(1,0,0,1);
}
)";

// ---

static GLuint make_shader(GLenum type, const char* text)
{
    GLuint shader = 0u;
    GLint shader_ok;

    shader = glCreateShader(type);
    if (shader != 0u)
    {
        glShaderSource(shader, 1, reinterpret_cast<const GLchar**>(&text), NULL);
        glCompileShader(shader);
        glGetShaderiv(shader, GL_COMPILE_STATUS, &shader_ok);
        if (shader_ok != GL_TRUE)
        {
            GLint maxLength = 0;
            glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &maxLength);
            string buf(maxLength, 0);
            glGetShaderInfoLog(shader, maxLength, &maxLength, &buf[0]);

            LOGE << "ERROR: Failed to compile " << ((type == GL_FRAGMENT_SHADER) ? "fragment" : "vertex") << " shader" << endl;
            LOGE << buf << endl;

            glDeleteShader(shader);
            shader = 0u;
        }
    }

    return shader;
}

static GLuint make_shader_program(const char* vs_text, const char* fs_text)
{
    GLuint program = 0u;
    GLint program_ok;
    GLuint vertex_shader = 0u;
    GLuint fragment_shader = 0u;

    vertex_shader = make_shader(GL_VERTEX_SHADER, vs_text);
    if (vertex_shader != 0u)
    {
        fragment_shader = make_shader(GL_FRAGMENT_SHADER, fs_text);
        if (fragment_shader != 0u)
        {
            /* make the program that connect the two shader and link it */
            program = glCreateProgram();
            if (program != 0u)
            {
                /* attach both shader and link */
                glAttachShader(program, vertex_shader);
                glAttachShader(program, fragment_shader);
                glLinkProgram(program);
                glGetProgramiv(program, GL_LINK_STATUS, &program_ok);

                if (program_ok != GL_TRUE)
                {
                    GLint maxLength = 0;
                    glGetShaderiv(program, GL_INFO_LOG_LENGTH, &maxLength);
                    string buf(maxLength, 0);
                    glGetShaderInfoLog(program, maxLength, &maxLength, &buf[0]);

                    LOGE << "ERROR: Failed to link shader program" << endl;
                    LOGE << buf << endl;

                    glDeleteProgram(program);
                    glDeleteShader(fragment_shader);
                    glDeleteShader(vertex_shader);
                    program = 0u;
                }
            }
        }
        else
        {
            LOGE << "ERROR: Unable to load fragment shader" << endl;
            glDeleteShader(vertex_shader);
        }
    }
    else
    {
        LOGE << "ERROR: Unable to load vertex shader" << endl;
    }

    return program;
}

// ---

void draw()
{
  int w, h, fs;
  emscripten_get_canvas_size(&w, &h, &fs);
  float t = emscripten_get_now() / 1000.0f;
  float xs = (float)h / w;
  float ys = 1.0f;
  float mat[] = { cosf(t) * xs, sinf(t) * ys, 0, 0, -sinf(t) * xs, cosf(t) * ys, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 };
  glUniformMatrix4fv(glGetUniformLocation(shader_program, "mat"), 1, 0, mat);
  glClearColor(0,0,1,1);
  glClear(GL_COLOR_BUFFER_BIT);
  glDrawArrays(GL_TRIANGLES, 0, 3);
}

int main()
{
  emscripten_set_canvas_size(256, 256);
  EmscriptenWebGLContextAttributes attr;
  emscripten_webgl_init_context_attributes(&attr);
  attr.alpha = attr.depth = attr.stencil = attr.antialias = attr.preserveDrawingBuffer = attr.preferLowPowerToHighPerformance = attr.failIfMajorPerformanceCaveat = 0;
  attr.enableExtensionsByDefault = 1;
  attr.premultipliedAlpha = 0;
  attr.majorVersion = 1;
  attr.minorVersion = 0;
  EMSCRIPTEN_WEBGL_CONTEXT_HANDLE ctx = emscripten_webgl_create_context(0, &attr);
  emscripten_webgl_make_context_current(ctx);

  //

  shader_program = make_shader_program(vss, pss);
  if (shader_program == 0u)
  {
    return 0;
  }

  glUseProgram(shader_program);
  glBindAttribLocation(shader_program, 0, "vPosition");

  //

  GLuint vbo;
  glGenBuffers(1, &vbo);
  glBindBuffer(GL_ARRAY_BUFFER, vbo);

  float verts[] = { 0.0, 0.5, 0.0, -0.5, -0.5, 0.0, 0.5, -0.5, 0.0 };
  glBufferData(GL_ARRAY_BUFFER, sizeof(verts), verts, GL_STATIC_DRAW);
  glVertexAttribPointer(0, 3, GL_FLOAT, 0, 0, 0);
  glEnableVertexAttribArray(0);

  emscripten_set_main_loop(draw, 0, 0);

  return 0;
}
<|endoftext|>


<commit_before>/*******************************************************************************
 * tests/api/groupby_node_test.cpp
 *
 * Part of Project Thrill.
 *
 * Copyright (C) 2015 Huyen Chau Nguyen <hello@chau-nguyen.de>
 *
 * This file has no license. Only Chuck Norris can compile it.
 ******************************************************************************/

#include <thrill/api/allgather.hpp>
#include <thrill/api/generate.hpp>
#include <thrill/api/groupby.hpp>
#include <thrill/api/groupby_index.hpp>
#include <thrill/api/sum.hpp>
#include <thrill/common/logger.hpp>
#include <thrill/data/file.hpp>
#include <gtest/gtest.h>
#include <thrill/core/multiway_merge.hpp>

#include <algorithm>
#include <cstdlib>
#include <limits>
#include <string>
#include <vector>

using namespace thrill; // NOLINT

static const bool debug = false;

TEST(GroupByNode, CompileAndSum) {

    std::function<void(Context&)> start_func =
        [](Context& ctx) {
            unsigned n = 999999;
            static const unsigned m = 4;

            auto sizets = Generate(
                ctx,
                [](const size_t& index) {
                    return static_cast<std::size_t>(index + 1);
                },
                n);

            auto modulo_keyfn = [](size_t in) { return (in % m); };

            auto sum_fn =
                [](api::GroupByIterator<std::size_t, decltype(modulo_keyfn)>& r) {
                    auto res = 0;
                    int k = 0;
                    while (r.HasNext()) {
                        auto n = r.Next();
                        k = n % m;
                        res += n;
                    }
                    return static_cast<int>(res);
                };

            // group by to compute sum and gather results
            auto reduced = sizets.GroupBy(modulo_keyfn, sum_fn);
            std::vector<int> out_vec = reduced.AllGather();

            // compute vector with expected results
            std::vector<unsigned> res_vec(m, 0);
            for (unsigned t = 0; t <= n; ++t) {
                res_vec[t % m] += t;
            }

            std::sort(out_vec.begin(), out_vec.end());
            std::sort(res_vec.begin(), res_vec.end());

            LOG << "res_vec " << "/" << " out_vec";
            for (std::size_t i = 0; i < res_vec.size(); ++i) {
                LOG << res_vec[i] << " / " << out_vec[i];
                ASSERT_EQ(res_vec[i], out_vec[i]);
            }
        };

    api::RunLocalTests(start_func);
}

TEST(GroupByNode, Median) {

    std::function<void(Context&)> start_func =
        [](Context& ctx) {
            unsigned n = 999999;
            static const unsigned m = 4;

            auto sizets = Generate(
                ctx,
                [](const size_t& index) {
                    return index + 1;
                },
                n);

            auto modulo_keyfn = [](size_t in) { return (in % m); };

            auto median_fn =
                [](api::GroupByIterator<std::size_t, decltype(modulo_keyfn)>& r) {
                    std::vector<std::size_t> all;
                    while (r.HasNext()) {
                        all.push_back(r.Next());
                    }
                    std::sort(std::begin(all), std::end(all));
                    for (auto c : all) {
                        LOG << c;
                    }
                    return static_cast<int>(all[all.size() / 2 - 1]);
                };

            // group by to compute sum and gather results
            auto reduced = sizets.GroupBy(modulo_keyfn, median_fn);
            std::vector<int> out_vec = reduced.AllGather();

            // compute vector with expected results
            std::vector<std::vector<unsigned> > res_vecvec(m);
            std::vector<unsigned> res_vec(m, 0);
            for (unsigned t = 1; t <= n; ++t) {
                res_vecvec[t % m].push_back(t);
            }
            for (std::size_t i = 0; i < res_vecvec.size(); ++i) {
                std::sort(std::begin(res_vecvec[i]), std::end(res_vecvec[i]));
                res_vec[i] = res_vecvec[i][res_vecvec[i].size() / 2 - 1];
            }

            std::sort(out_vec.begin(), out_vec.end());
            std::sort(res_vec.begin(), res_vec.end());

            LOG << "res_vec " << "/" << " out_vec";
            for (std::size_t i = 0; i < res_vec.size(); ++i) {
                LOG << res_vec[i] << " / " << out_vec[i];
                ASSERT_EQ(res_vec[i], out_vec[i]);
            }
        };

    api::RunLocalTests(start_func);
}

TEST(GroupByNode, GroupByIndexCorrectResults) {

    std::function<void(Context&)> start_func =
        [](Context& ctx) {

            auto integers = Generate(
                ctx,
                [](const size_t& index) {
                    return index;
                },
                5);

            static size_t result_size = 6;

            auto key = [](size_t in) {
                           return in % 6;
                       };

            auto add_function = [](api::GroupByIterator<std::size_t, decltype(key)>& r) {
                                    std::size_t res = 4;
                                    while(r.HasNext()) {
                                        res += r.Next();
                                    }
                                    return res;
                                };

            auto reduced = integers.GroupByIndex(key, add_function, result_size);

            std::vector<size_t> out_vec = reduced.AllGather();
            // ASSERT_EQ(9u, out_vec.size());

            int i = 4;
            for (size_t element : out_vec) {
                LOG << element;
                ASSERT_EQ(i, element);
                ++i;
            }
        };

    // api::RunLocalTests(start_func);
    RunLocalMock(2, 1, start_func);
}

/******************************************************************************/
<commit_msg>activate all local tests for groupby index<commit_after>/*******************************************************************************
 * tests/api/groupby_node_test.cpp
 *
 * Part of Project Thrill.
 *
 * Copyright (C) 2015 Huyen Chau Nguyen <hello@chau-nguyen.de>
 *
 * This file has no license. Only Chuck Norris can compile it.
 ******************************************************************************/

#include <thrill/api/allgather.hpp>
#include <thrill/api/generate.hpp>
#include <thrill/api/groupby.hpp>
#include <thrill/api/groupby_index.hpp>
#include <thrill/api/sum.hpp>
#include <thrill/common/logger.hpp>
#include <thrill/data/file.hpp>
#include <gtest/gtest.h>
#include <thrill/core/multiway_merge.hpp>

#include <algorithm>
#include <cstdlib>
#include <limits>
#include <string>
#include <vector>

using namespace thrill; // NOLINT

static const bool debug = false;

TEST(GroupByNode, CompileAndSum) {

    std::function<void(Context&)> start_func =
        [](Context& ctx) {
            unsigned n = 999999;
            static const unsigned m = 4;

            auto sizets = Generate(
                ctx,
                [](const size_t& index) {
                    return static_cast<std::size_t>(index + 1);
                },
                n);

            auto modulo_keyfn = [](size_t in) { return (in % m); };

            auto sum_fn =
                [](api::GroupByIterator<std::size_t, decltype(modulo_keyfn)>& r) {
                    auto res = 0;
                    int k = 0;
                    while (r.HasNext()) {
                        auto n = r.Next();
                        k = n % m;
                        res += n;
                    }
                    return static_cast<int>(res);
                };

            // group by to compute sum and gather results
            auto reduced = sizets.GroupBy(modulo_keyfn, sum_fn);
            std::vector<int> out_vec = reduced.AllGather();

            // compute vector with expected results
            std::vector<unsigned> res_vec(m, 0);
            for (unsigned t = 0; t <= n; ++t) {
                res_vec[t % m] += t;
            }

            std::sort(out_vec.begin(), out_vec.end());
            std::sort(res_vec.begin(), res_vec.end());

            LOG << "res_vec " << "/" << " out_vec";
            for (std::size_t i = 0; i < res_vec.size(); ++i) {
                LOG << res_vec[i] << " / " << out_vec[i];
                ASSERT_EQ(res_vec[i], out_vec[i]);
            }
        };

    api::RunLocalTests(start_func);
}

TEST(GroupByNode, Median) {

    std::function<void(Context&)> start_func =
        [](Context& ctx) {
            unsigned n = 999999;
            static const unsigned m = 4;

            auto sizets = Generate(
                ctx,
                [](const size_t& index) {
                    return index + 1;
                },
                n);

            auto modulo_keyfn = [](size_t in) { return (in % m); };

            auto median_fn =
                [](api::GroupByIterator<std::size_t, decltype(modulo_keyfn)>& r) {
                    std::vector<std::size_t> all;
                    while (r.HasNext()) {
                        all.push_back(r.Next());
                    }
                    std::sort(std::begin(all), std::end(all));
                    for (auto c : all) {
                        LOG << c;
                    }
                    return static_cast<int>(all[all.size() / 2 - 1]);
                };

            // group by to compute sum and gather results
            auto reduced = sizets.GroupBy(modulo_keyfn, median_fn);
            std::vector<int> out_vec = reduced.AllGather();

            // compute vector with expected results
            std::vector<std::vector<unsigned> > res_vecvec(m);
            std::vector<unsigned> res_vec(m, 0);
            for (unsigned t = 1; t <= n; ++t) {
                res_vecvec[t % m].push_back(t);
            }
            for (std::size_t i = 0; i < res_vecvec.size(); ++i) {
                std::sort(std::begin(res_vecvec[i]), std::end(res_vecvec[i]));
                res_vec[i] = res_vecvec[i][res_vecvec[i].size() / 2 - 1];
            }

            std::sort(out_vec.begin(), out_vec.end());
            std::sort(res_vec.begin(), res_vec.end());

            LOG << "res_vec " << "/" << " out_vec";
            for (std::size_t i = 0; i < res_vec.size(); ++i) {
                LOG << res_vec[i] << " / " << out_vec[i];
                ASSERT_EQ(res_vec[i], out_vec[i]);
            }
        };

    api::RunLocalTests(start_func);
}

TEST(GroupByNode, GroupByIndexCorrectResults) {

    std::function<void(Context&)> start_func =
        [](Context& ctx) {

            auto integers = Generate(
                ctx,
                [](const size_t& index) {
                    return index;
                },
                5);

            static size_t result_size = 6;

            auto key = [](size_t in) {
                           return in % 6;
                       };

            auto add_function = [](api::GroupByIterator<std::size_t, decltype(key)>& r) {
                                    std::size_t res = 4;
                                    while(r.HasNext()) {
                                        res += r.Next();
                                    }
                                    return res;
                                };

            auto reduced = integers.GroupByIndex(key, add_function, result_size);

            std::vector<size_t> out_vec = reduced.AllGather();
            // ASSERT_EQ(9u, out_vec.size());

            int i = 4;
            for (size_t element : out_vec) {
                LOG << element;
                ASSERT_EQ(i, element);
                ++i;
            }
        };

    api::RunLocalTests(start_func);
    // RunLocalMock(2, 1, start_func);
}

/******************************************************************************/
<|endoftext|>


<commit_before>
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include "atNotifier.h++"

// Define the "notify level" (we make this a class variable so that
// altering the level will affect all those calling notify())
int atNotifier::notify_level = AT_INFO;

atNotifier::atNotifier()
{
   // Initialize the instance variables (an empty header and output to stdout)
   memset(header_name, 0, sizeof(header_name));
   output_file_ptr = stdout;
}

atNotifier::~atNotifier()
{
}

void atNotifier::setName(char * name)
{
   // Copy the name into the header (use strncpy to avoid writing over
   // the end of the array)
   strncpy(header_name, name, sizeof(header_name) - 1);

   // Guarantee a NULL character (covers the case when strncpy does copy
   // all "n" characters)
   header_name[sizeof(header_name) - 1] = '\0';
}

void atNotifier::setNotifyLevel(int desiredLevel)
{
   // Make sure the user chose a valid desired level
   if ( (desiredLevel == AT_INFO) || (desiredLevel == AT_WARN) ||
        (desiredLevel == AT_ERROR) || (desiredLevel == AT_FATAL_ERROR) ||
        (desiredLevel == AT_SILENT) )
   {
      // Set the level to the requested level
      notify_level = desiredLevel;
   }
   else
   {
      // Otherwise, output a warning about the illegal level
      notify(AT_WARN, "Attempt to set illegal notify level [%04x].\n",
             desiredLevel);
   }
}

void atNotifier::setNotifyDestination(FILE *output)
{
   // Set the output to the FILE given by the user (note that this class
   // does not open nor close the file)
   output_file_ptr = output;
}

void atNotifier::notify(int level, char *str, ...)
{
   va_list   args;

   // When in SILENT level, *never* notify
   if (notify_level & AT_SILENT)
      return;

   // Output if debug or no_header flag is set or if level is greater than
   // or equal to the current notify level
   if ( (level & AT_DEBUG) || (level & AT_FORCE) ||
        ((level & AT_LEVEL_MASK) >= notify_level) )
   {
      // If the "no header" bit is not set, output the header
      if (!(level & AT_NO_HEADER))
      {
         // Clear all modification flags
         level = level & AT_LEVEL_MASK;

         // Print the initial level as appropriate
         switch (level)
         {
            case AT_INFO:
               fprintf(output_file_ptr, "INFO: ");
               break;
            case AT_WARN:
               fprintf(output_file_ptr, "WARN: ");
               break;
            case AT_ERROR:
               fprintf(output_file_ptr, "ERROR: ");
               break;
            case AT_FATAL_ERROR:
               fprintf(output_file_ptr, "\n\nFATAL_ERROR: ");
               break;
            default:
               fprintf(output_file_ptr,"**** UNKNOWN ERROR LEVEL [%d] ****",
                       level);
               break;
         }

         // Then print the header name
         fprintf(output_file_ptr, header_name);
      }

      // Finally print the message itself with parameters (like printf)
      va_start(args, str);
      vfprintf(output_file_ptr, str, args);
      va_end(args);

      // If the user called this a fatal error, bail out harshly
      if ((level & AT_FATAL_ERROR) > 0)
      {
         // AT_FATAL_ERROR exits
         exit(AT_FATAL_ERROR);
      }
   }
}

<commit_msg>Flush output of notify().<commit_after>
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include "atNotifier.h++"

// Define the "notify level" (we make this a class variable so that
// altering the level will affect all those calling notify())
int atNotifier::notify_level = AT_INFO;

atNotifier::atNotifier()
{
   // Initialize the instance variables (an empty header and output to stdout)
   memset(header_name, 0, sizeof(header_name));
   output_file_ptr = stdout;
}

atNotifier::~atNotifier()
{
}

void atNotifier::setName(char * name)
{
   // Copy the name into the header (use strncpy to avoid writing over
   // the end of the array)
   strncpy(header_name, name, sizeof(header_name) - 1);

   // Guarantee a NULL character (covers the case when strncpy does copy
   // all "n" characters)
   header_name[sizeof(header_name) - 1] = '\0';
}

void atNotifier::setNotifyLevel(int desiredLevel)
{
   // Make sure the user chose a valid desired level
   if ( (desiredLevel == AT_INFO) || (desiredLevel == AT_WARN) ||
        (desiredLevel == AT_ERROR) || (desiredLevel == AT_FATAL_ERROR) ||
        (desiredLevel == AT_SILENT) )
   {
      // Set the level to the requested level
      notify_level = desiredLevel;
   }
   else
   {
      // Otherwise, output a warning about the illegal level
      notify(AT_WARN, "Attempt to set illegal notify level [%04x].\n",
             desiredLevel);
   }
}

void atNotifier::setNotifyDestination(FILE *output)
{
   // Set the output to the FILE given by the user (note that this class
   // does not open nor close the file)
   output_file_ptr = output;
}

void atNotifier::notify(int level, char *str, ...)
{
   va_list   args;

   // When in SILENT level, *never* notify
   if (notify_level & AT_SILENT)
      return;

   // Output if debug or no_header flag is set or if level is greater than
   // or equal to the current notify level
   if ( (level & AT_DEBUG) || (level & AT_FORCE) ||
        ((level & AT_LEVEL_MASK) >= notify_level) )
   {
      // If the "no header" bit is not set, output the header
      if (!(level & AT_NO_HEADER))
      {
         // Clear all modification flags
         level = level & AT_LEVEL_MASK;

         // Print the initial level as appropriate
         switch (level)
         {
            case AT_INFO:
               fprintf(output_file_ptr, "INFO: ");
               break;
            case AT_WARN:
               fprintf(output_file_ptr, "WARN: ");
               break;
            case AT_ERROR:
               fprintf(output_file_ptr, "ERROR: ");
               break;
            case AT_FATAL_ERROR:
               fprintf(output_file_ptr, "\n\nFATAL_ERROR: ");
               break;
            default:
               fprintf(output_file_ptr,"**** UNKNOWN ERROR LEVEL [%d] ****",
                       level);
               break;
         }

         // Then print the header name
         fprintf(output_file_ptr, header_name);
      }

      // Finally print the message itself with parameters (like printf)
      va_start(args, str);
      vfprintf(output_file_ptr, str, args);
      va_end(args);
      fflush(output_file_ptr);

      // If the user called this a fatal error, bail out harshly
      if ((level & AT_FATAL_ERROR) > 0)
      {
         // AT_FATAL_ERROR exits
         exit(AT_FATAL_ERROR);
      }
   }
}

<|endoftext|>


<commit_before>#include "ogg.h"
#include <string.h>
#include <stdlib.h>
#include <sstream>
#include <arpa/inet.h>

#define lsb32(offset) data[offset] | data[offset+1] << 8 | data[offset+2] << 16 | data[offset+3] << 24

namespace OGG{
  Page::Page(){
    data = NULL;
    datasize = 0;
    dataSum = 0;
  }

  bool Page::read(std::string & newData){
    //datasize = 0;
    if (newData.size()<27){
      return false;
    }
    dataSum = 0;
    if (!checkDataSize(27)){
      return false;
    }
    memcpy(data, newData.c_str(), 27);//copying the header, always 27 bytes
    if(!checkDataSize(27 + getPageSegments())){
      return false;
    }
    memcpy(data + 27, newData.c_str() + 27, getPageSegments());
    //copying the first part of the page into data, which tells the size of the page

    for(unsigned int i = 0; i < getPageSegments(); i++){
      dataSum += getSegmentTable()[i];
    }
    if(!checkDataSize(27 + getPageSegments()+dataSum)){
      return false;
    }
    memcpy(data + 27 + getPageSegments(), newData.c_str() + 27 + getPageSegments(), dataSum);
    newData.erase(0, getPageSize());
    return true;
  }

  long unsigned int Page::getMagicNumber(){
    return ntohl(((long unsigned int*)(data))[0]);
  }

  void Page::setMagicNumber(){
    if(checkDataSize(4)){
      memcpy(data, "OggS", 4);
    }
  }

  char Page::getVersion(){
    return data[4];
  }

  void Page::setVersion(char newVal){
    if(checkDataSize(5)){
      data[4] = newVal;
    }
  }

  char Page::getHeaderType(){
    return data[5];
  }

  void Page::setHeaderType(char newVal){
    if(checkDataSize(6)){
      data[5] = newVal;
    }
  }

  long long unsigned int Page::getGranulePosition(){
    if(checkDataSize(14)){
      //switching bit order upon return
      return ntohl(((long unsigned*)(data+6))[1]) & ((long long unsigned)(ntohl(((long unsigned*)(data+6))[0]) << 32));
    }
    return 0;
  }

  void Page::setGranulePosition(long long unsigned int newVal){
    if(checkDataSize(14)){
      ((long unsigned*)(data+6))[1] = htonl(newVal & 0xFFFFFFFF);
      ((long unsigned*)(data+6))[0] = htonl((newVal >> 32) & 0xFFFFFFFF);
    }
  }

  long unsigned int Page::getBitstreamSerialNumber(){
    //return ntohl(((long unsigned int*)(data+14))[0]);
    return lsb32(14);
  }

  void Page::setBitstreamSerialNumber(long unsigned int newVal){
    if(checkDataSize(18)){
      ((long unsigned *)(data+14))[0] = htonl(newVal);
    }
  }

  long unsigned int Page::getPageSequenceNumber(){
    return lsb32(18);
  }

  void Page::setPageSequenceNumber(long unsigned int newVal){
    if(checkDataSize(22)){
      ((long unsigned *)(data+18))[0] = htonl(newVal);
    }
  }

  long unsigned int Page::getCRCChecksum(){
    return ntohl(((long unsigned int*)(data+22))[0]);
    //return lsb32(22);
  }

  void Page::setCRCChecksum(long unsigned int newVal){
    if(checkDataSize(26)){
      ((long unsigned *)(data+22))[0] = htonl(newVal);
    }
  }

  char Page::getPageSegments(){
    return data[26];
  }

  inline void Page::setPageSegments(char newVal){
    data[26] = newVal;
  }

  char* Page::getSegmentTable(){
    return data+27;
  }

  std::deque<unsigned int> Page::getSegmentTableDeque(){
    std::deque<unsigned int> retVal;
    unsigned int temp = 0;
    char* segmentTable = getSegmentTable();
    for (unsigned int i = 0; i < getPageSegments(); i++){
      temp += segmentTable[i];
      if (segmentTable[i] < 255){
        retVal.push_back(temp);
        temp = 0;
      }
    }
    return retVal;
  }

  bool Page::setSegmentTable(std::vector<unsigned int> layout){
    unsigned int place = 0;
    char table[255];
    for (unsigned int i = 0; i < layout.size(); i++){
      while (layout[i]>=255){
        if (place >= 255) return false;
        table[place] = 255;
        layout[i] -= 255;
        place++;
      }
      if (place >= 255) return false;
      table[place] = layout[i];
      place++;
    }
    setSegmentTable(table,place);
    return true;
  }

  void Page::setSegmentTable(char* newVal, unsigned int length){
    if(checkDataSize(27 + length)){
      memcpy(data + 27, newVal, length);
    }
  }

  unsigned long int Page::getPageSize(){
    return 27 + getPageSegments()+dataSum;
  }

  char* Page::getFullPayload(){
    return data + 27 + getPageSegments();
  }

  bool Page::typeBOS(){
    if (getHeaderType() & 0x02){
      return true;
    }
    return false;
  }

  bool Page::typeEOS(){
    if (getHeaderType() & 0x04){
      return true;
    }
    return false;
  }

  bool Page::typeContinue(){
    if (getHeaderType() & 0x01){
      return true;
    }
    return false;
  }

  bool Page::typeNone(){
    if (getHeaderType() & 0x07 == 0x00){
      return true;
    }
    return false;
  }

  std::string Page::toPrettyString(){
    std::stringstream r;
    r << "Size(" << getPageSize() << ")(" << dataSum << ")" << std::endl;
    r << "Magic_Number: " << std::string(data, 4) << std::endl;
    r << "Version: " << (int)getVersion() << std::endl;
    r << "Header_type: " << std::hex << (int)getHeaderType() << std::dec;
    if (typeContinue()){
      r << " continued";
    }
    if (typeBOS()){
      r << " bos";
    }
    if (typeEOS()){
      r << " eos";
    }
    r << std::endl;
    r << "Granule_position: " << getGranulePosition() << std::endl;
    r << "Bitstream_SN: " << getBitstreamSerialNumber() << std::endl;
    r << "Page_sequence_number: " << getPageSequenceNumber() << std::endl;
    r << "CRC_checksum: " << std::hex << getCRCChecksum()<< std::dec << std::endl;
    r << "  Calced Checksum: " << std::hex << calcChecksum() << std::dec << std::endl;
    r << "CRC_checksum write: " << std::hex << getCRCChecksum()<< std::dec << std::endl;
    r << "Page_segments: " << (int)getPageSegments() << std::endl;
    r << "SegmentTable: ";
    std::deque<unsigned int> temp = getSegmentTableDeque();
    for (std::deque<unsigned int>::iterator i = temp.begin(); i != temp.end(); i++){
      r << (*i) << " ";
    }
    r << std::endl;
    return r.str();
  }

  long unsigned int Compute(char* buffer, unsigned int count){
    long unsigned int m_crc = ~0u;
    //const unsigned char* ptr = (const unsigned char *) buffer;
    for (unsigned int i = 0; i < count; i++) {
      buffer++;
      m_crc ^= ((unsigned long int)buffer << 24);
      for (int i = 0; i < 8; i++) {
        if (m_crc & 0x80000000) {
          m_crc = (m_crc << 1) ^ 0x04C11DB7;
        }else {
          m_crc <<= 1;
        }
      }
    }
    return m_crc;
  }

  long unsigned int Page::calcChecksum(){
    long unsigned int retVal = 0;
    long unsigned int oldChecksum = getCRCChecksum();
    setCRCChecksum (0);
    retVal = Compute(data, getPageSize());
    setCRCChecksum (oldChecksum);
    return retVal;
  }

  bool Page::checkDataSize(unsigned int size){
    if (size > datasize){
      void* tmp = realloc(data,size);
      if (tmp){
        data = (char*)tmp;
        datasize = size;
        return true;
      }else{
        return false;
      }
    }else{
      return true;
    }
  }
}
<commit_msg>Ogg fix<commit_after>#include "ogg.h"
#include <string.h>
#include <stdlib.h>
#include <sstream>
#include <arpa/inet.h>

namespace OGG{
  inline long long unsigned int get_64(char* data){
    long long unsigned int temp = 0;
    for (int i = 7; i>= 0; --i){
      temp <<= 8;
      temp += data[i];
    }
    return temp;
  }

  inline long unsigned int get_32(char* data){
    long unsigned int temp = 0;
    for (int i = 3; i>= 0; --i){
      temp <<= 8;
      temp += data[i];
    }
    return temp;
  }

  inline void set_64(char* data, long unsigned int val){
    for (int i = 0; i< 8; ++i){
      data[i] = val & 0xFF;
      val >>= 8;
    }
  }

  inline void set_32(char* data, long unsigned int val){
    for (int i = 0; i< 4; ++i){
      data[i] = val & 0xFF;
      val >>= 8;
    }
  }

  Page::Page(){
    data = NULL;
    datasize = 0;
    dataSum = 0;
  }

  bool Page::read(std::string & newData){
    //datasize = 0;
    if (newData.size()<27){
      return false;
    }
    /*if (getMagicNumber() != 0x4f676753){
      return false;
    }*/
    dataSum = 0;
    if (!checkDataSize(27)){
      return false;
    }
    memcpy(data, newData.c_str(), 27);//copying the header, always 27 bytes

    if (newData.size() < 27 + getPageSegments()){//check input size
      return false;
    }
    if(!checkDataSize(27 + getPageSegments())){//check if size available in memory
      return false;
    }
    memcpy(data + 27, newData.c_str() + 27, getPageSegments());
    //copying the first part of the page into data, which tells the size of the page

    for(unsigned int i = 0; i < getPageSegments(); i++){
      dataSum += getSegmentTable()[i];
    }

    if (newData.size() < 27 + getPageSegments() + dataSum){//check input size
      return false;
    }
    if(!checkDataSize(27 + getPageSegments()+dataSum)){
      return false;
    }
    memcpy(data + 27 + getPageSegments(), newData.c_str() + 27 + getPageSegments(), dataSum);
    newData.erase(0, getPageSize());
    return true;
  }

  long unsigned int Page::getMagicNumber(){
    return ntohl(((long unsigned int*)(data))[0]);
  }

  void Page::setMagicNumber(){
    if(checkDataSize(4)){
      memcpy(data, "OggS", 4);
    }
  }

  char Page::getVersion(){
    return data[4];
  }

  void Page::setVersion(char newVal){
    if(checkDataSize(5)){
      data[4] = newVal;
    }
  }

  char Page::getHeaderType(){
    return data[5];
  }

  void Page::setHeaderType(char newVal){
    if(checkDataSize(6)){
      data[5] = newVal;
    }
  }

  long long unsigned int Page::getGranulePosition(){
    if(checkDataSize(14)){
      //switching bit order upon return
      //return ntohl(((long unsigned*)(data+6))[1]) & ((long long unsigned)((long long unsigned)ntohl(((long unsigned*)(data+6))[0]) << 32));
      //long long unsigned int temp;
      //temp = ((long unsigned int)(data+6)[0]);
      //temp = temp << 32 + ((long unsigned int)(data+6)[1]);
      return get_64(data+6);
    }
    return 0;
  }

  void Page::setGranulePosition(long long unsigned int newVal){
    if(checkDataSize(14)){
      ((long unsigned*)(data+6))[1] = htonl(newVal & 0xFFFFFFFF);
      ((long unsigned*)(data+6))[0] = htonl((newVal >> 32) & 0xFFFFFFFF);
    }
  }

  long unsigned int Page::getBitstreamSerialNumber(){
    //return ntohl(((long unsigned int*)(data+14))[0]);
    return get_32(data+14);
  }

  void Page::setBitstreamSerialNumber(long unsigned int newVal){
    if(checkDataSize(18)){
      //((long unsigned *)(data+14))[0] = htonl(newVal);
      set_32(data+14, newVal);
    }
  }

  long unsigned int Page::getPageSequenceNumber(){
    return get_32(data+18);
  }

  void Page::setPageSequenceNumber(long unsigned int newVal){
    if(checkDataSize(22)){
      //((long unsigned *)(data+18))[0] = htonl(newVal);
      set_32(data+18, newVal);
    }
  }

  long unsigned int Page::getCRCChecksum(){
    //return ntohl(((long unsigned int*)(data+22))[0]);
    return get_32(data+22);
  }

  void Page::setCRCChecksum(long unsigned int newVal){
    if(checkDataSize(26)){
      set_32(data+22,newVal);
    }
  }

  char Page::getPageSegments(){
    return data[26];
  }

  inline void Page::setPageSegments(char newVal){
    data[26] = newVal;
  }

  char* Page::getSegmentTable(){
    return data+27;
  }

  std::deque<unsigned int> Page::getSegmentTableDeque(){
    std::deque<unsigned int> retVal;
    unsigned int temp = 0;
    char* segmentTable = getSegmentTable();
    for (unsigned int i = 0; i < getPageSegments(); i++){
      temp += segmentTable[i];
      if (segmentTable[i] < 255){
        retVal.push_back(temp);
        temp = 0;
      }
    }
    return retVal;
  }

  bool Page::setSegmentTable(std::vector<unsigned int> layout){
    unsigned int place = 0;
    char table[255];
    for (unsigned int i = 0; i < layout.size(); i++){
      while (layout[i]>=255){
        if (place >= 255) return false;
        table[place] = 255;
        layout[i] -= 255;
        place++;
      }
      if (place >= 255) return false;
      table[place] = layout[i];
      place++;
    }
    setSegmentTable(table,place);
    return true;
  }

  void Page::setSegmentTable(char* newVal, unsigned int length){
    if(checkDataSize(27 + length)){
      memcpy(data + 27, newVal, length);
    }
  }

  unsigned long int Page::getPageSize(){
    return 27 + getPageSegments()+dataSum;
  }

  char* Page::getFullPayload(){
    return data + 27 + getPageSegments();
  }

  bool Page::typeBOS(){
    if (getHeaderType() & 0x02){
      return true;
    }
    return false;
  }

  bool Page::typeEOS(){
    if (getHeaderType() & 0x04){
      return true;
    }
    return false;
  }

  bool Page::typeContinue(){
    if (getHeaderType() & 0x01){
      return true;
    }
    return false;
  }

  bool Page::typeNone(){
    if (getHeaderType() & 0x07 == 0x00){
      return true;
    }
    return false;
  }

  std::string Page::toPrettyString(){
    std::stringstream r;
    r << "Size(" << getPageSize() << ")(" << dataSum << ")" << std::endl;
    r << "Magic_Number: " << std::string(data, 4) << std::endl;
    r << "Version: " << (int)getVersion() << std::endl;
    r << "Header_type: " << std::hex << (int)getHeaderType() << std::dec;
    if (typeContinue()){
      r << " continued";
    }
    if (typeBOS()){
      r << " bos";
    }
    if (typeEOS()){
      r << " eos";
    }
    r << std::endl;
    r << "Granule_position: " <<std::hex<< getGranulePosition() <<std::dec<< std::endl;
    r << "Bitstream_SN: " << getBitstreamSerialNumber() << std::endl;
    r << "Page_sequence_number: " << getPageSequenceNumber() << std::endl;
    r << "CRC_checksum: " << std::hex << getCRCChecksum()<< std::dec << std::endl;
    //r << "  Calced Checksum: " << std::hex << calcChecksum() << std::dec << std::endl;
    //r << "CRC_checksum write: " << std::hex << getCRCChecksum()<< std::dec << std::endl;
    r << "Page_segments: " << (int)getPageSegments() << std::endl;
    r << "SegmentTable: ";
    std::deque<unsigned int> temp = getSegmentTableDeque();
    for (std::deque<unsigned int>::iterator i = temp.begin(); i != temp.end(); i++){
      r << (*i) << " ";
    }
    r << std::endl;
    return r.str();
  }

  inline unsigned int crc32(unsigned int crc, const char *data, size_t len){
    static const unsigned int table[256] = {
    0x00000000U,0x04C11DB7U,0x09823B6EU,0x0D4326D9U,
    0x130476DCU,0x17C56B6BU,0x1A864DB2U,0x1E475005U,
    0x2608EDB8U,0x22C9F00FU,0x2F8AD6D6U,0x2B4BCB61U,
    0x350C9B64U,0x31CD86D3U,0x3C8EA00AU,0x384FBDBDU,
    0x4C11DB70U,0x48D0C6C7U,0x4593E01EU,0x4152FDA9U,
    0x5F15ADACU,0x5BD4B01BU,0x569796C2U,0x52568B75U,
    0x6A1936C8U,0x6ED82B7FU,0x639B0DA6U,0x675A1011U,
    0x791D4014U,0x7DDC5DA3U,0x709F7B7AU,0x745E66CDU,
    0x9823B6E0U,0x9CE2AB57U,0x91A18D8EU,0x95609039U,
    0x8B27C03CU,0x8FE6DD8BU,0x82A5FB52U,0x8664E6E5U,
    0xBE2B5B58U,0xBAEA46EFU,0xB7A96036U,0xB3687D81U,
    0xAD2F2D84U,0xA9EE3033U,0xA4AD16EAU,0xA06C0B5DU,
    0xD4326D90U,0xD0F37027U,0xDDB056FEU,0xD9714B49U,
    0xC7361B4CU,0xC3F706FBU,0xCEB42022U,0xCA753D95U,
    0xF23A8028U,0xF6FB9D9FU,0xFBB8BB46U,0xFF79A6F1U,
    0xE13EF6F4U,0xE5FFEB43U,0xE8BCCD9AU,0xEC7DD02DU,
    0x34867077U,0x30476DC0U,0x3D044B19U,0x39C556AEU,
    0x278206ABU,0x23431B1CU,0x2E003DC5U,0x2AC12072U,
    0x128E9DCFU,0x164F8078U,0x1B0CA6A1U,0x1FCDBB16U,
    0x018AEB13U,0x054BF6A4U,0x0808D07DU,0x0CC9CDCAU,
    0x7897AB07U,0x7C56B6B0U,0x71159069U,0x75D48DDEU,
    0x6B93DDDBU,0x6F52C06CU,0x6211E6B5U,0x66D0FB02U,
    0x5E9F46BFU,0x5A5E5B08U,0x571D7DD1U,0x53DC6066U,
    0x4D9B3063U,0x495A2DD4U,0x44190B0DU,0x40D816BAU,
    0xACA5C697U,0xA864DB20U,0xA527FDF9U,0xA1E6E04EU,
    0xBFA1B04BU,0xBB60ADFCU,0xB6238B25U,0xB2E29692U,
    0x8AAD2B2FU,0x8E6C3698U,0x832F1041U,0x87EE0DF6U,
    0x99A95DF3U,0x9D684044U,0x902B669DU,0x94EA7B2AU,
    0xE0B41DE7U,0xE4750050U,0xE9362689U,0xEDF73B3EU,
    0xF3B06B3BU,0xF771768CU,0xFA325055U,0xFEF34DE2U,
    0xC6BCF05FU,0xC27DEDE8U,0xCF3ECB31U,0xCBFFD686U,
    0xD5B88683U,0xD1799B34U,0xDC3ABDEDU,0xD8FBA05AU,
    0x690CE0EEU,0x6DCDFD59U,0x608EDB80U,0x644FC637U,
    0x7A089632U,0x7EC98B85U,0x738AAD5CU,0x774BB0EBU,
    0x4F040D56U,0x4BC510E1U,0x46863638U,0x42472B8FU,
    0x5C007B8AU,0x58C1663DU,0x558240E4U,0x51435D53U,
    0x251D3B9EU,0x21DC2629U,0x2C9F00F0U,0x285E1D47U,
    0x36194D42U,0x32D850F5U,0x3F9B762CU,0x3B5A6B9BU,
    0x0315D626U,0x07D4CB91U,0x0A97ED48U,0x0E56F0FFU,
    0x1011A0FAU,0x14D0BD4DU,0x19939B94U,0x1D528623U,
    0xF12F560EU,0xF5EE4BB9U,0xF8AD6D60U,0xFC6C70D7U,
    0xE22B20D2U,0xE6EA3D65U,0xEBA91BBCU,0xEF68060BU,
    0xD727BBB6U,0xD3E6A601U,0xDEA580D8U,0xDA649D6FU,
    0xC423CD6AU,0xC0E2D0DDU,0xCDA1F604U,0xC960EBB3U,
    0xBD3E8D7EU,0xB9FF90C9U,0xB4BCB610U,0xB07DABA7U,
    0xAE3AFBA2U,0xAAFBE615U,0xA7B8C0CCU,0xA379DD7BU,
    0x9B3660C6U,0x9FF77D71U,0x92B45BA8U,0x9675461FU,
    0x8832161AU,0x8CF30BADU,0x81B02D74U,0x857130C3U,
    0x5D8A9099U,0x594B8D2EU,0x5408ABF7U,0x50C9B640U,
    0x4E8EE645U,0x4A4FFBF2U,0x470CDD2BU,0x43CDC09CU,
    0x7B827D21U,0x7F436096U,0x7200464FU,0x76C15BF8U,
    0x68860BFDU,0x6C47164AU,0x61043093U,0x65C52D24U,
    0x119B4BE9U,0x155A565EU,0x18197087U,0x1CD86D30U,
    0x029F3D35U,0x065E2082U,0x0B1D065BU,0x0FDC1BECU,
    0x3793A651U,0x3352BBE6U,0x3E119D3FU,0x3AD08088U,
    0x2497D08DU,0x2056CD3AU,0x2D15EBE3U,0x29D4F654U,
    0xC5A92679U,0xC1683BCEU,0xCC2B1D17U,0xC8EA00A0U,
    0xD6AD50A5U,0xD26C4D12U,0xDF2F6BCBU,0xDBEE767CU,
    0xE3A1CBC1U,0xE760D676U,0xEA23F0AFU,0xEEE2ED18U,
    0xF0A5BD1DU,0xF464A0AAU,0xF9278673U,0xFDE69BC4U,
    0x89B8FD09U,0x8D79E0BEU,0x803AC667U,0x84FBDBD0U,
    0x9ABC8BD5U,0x9E7D9662U,0x933EB0BBU,0x97FFAD0CU,
    0xAFB010B1U,0xAB710D06U,0xA6322BDFU,0xA2F33668U,
    0xBCB4666DU,0xB8757BDAU,0xB5365D03U,0xB1F740B4U,
    };

    while (len > 0)
    {
      crc = table[*data ^ ((crc >> 24) & 0xff)] ^ (crc << 8);
      data++;
      len--;
    }
    return crc;
  }

  long unsigned int Page::calcChecksum(){
    long unsigned int retVal = 0;
    long unsigned int oldChecksum = getCRCChecksum();
    setCRCChecksum (0);
    retVal = crc32(0, data, getPageSize());
    setCRCChecksum (oldChecksum);
    return retVal;
  }

  bool Page::checkDataSize(unsigned int size){
    if (size > datasize){
      void* tmp = realloc(data,size);
      if (tmp){
        data = (char*)tmp;
        datasize = size;
        return true;
      }else{
        return false;
      }
    }else{
      return true;
    }
  }
}
<|endoftext|>


<commit_before>/**
	\file data_class.cpp
	\brief implimenataion of idata class methods
	\author Nikonov Maxim
*/
#include "bs_bos_core_data_storage_stdafx.h"

#include "data_class.h"
#include "arrays.h"
#include "arrays_tables.h"
#include "constants.h"

//! Default minimal pore volume allowed for active cells
//#define DEFAULT_MINIMAL_PORE_VOLUME     1.e-1
#define DEFAULT_MINIMAL_PORE_VOLUME     1.e-7
//! Default minimal pore volume allowed for active cells to splice with other cells
// miryanov: set MINSV equal to MINPV for SPE10 model
#define DEFAULT_MINIMAL_SPLICE_VOLUME     1.e-7
//! Default maximum thickness allowed between active cells to be coupled
#define DEFAULT_MAXIMUM_SPLICE_THICKNESS     1.e-2

namespace blue_sky
  {
  /*!
  	\class idata_traits
  	\brief for node insertion control
  */

  struct idata::idata_traits : public bs_node::sort_traits
    {
      struct idata_key : bs_node::sort_traits::key_type
        {
          virtual bool sort_order(const key_ptr&) const
            {
              return true;
            }
        };

      virtual const char *sort_name() const
        {
          return "idata trait";
        }

      virtual key_ptr key_generator(const sp_link&) const
        {
          return new idata_key();
        }

      virtual bool accepts(const sp_link &l) const
        {
          if (l->name().find("_in_pool",0,l->name().size()))
            return smart_ptr<this_t>(l->data(), bs_dynamic_cast());
          return false;
        }
    };

  idata::~idata ()
  {
    h5_pool->close_file();
  }

  idata::idata(bs_type_ctor_param /*param*/)
  : bs_node(bs_node::create_node (new this_t::idata_traits ())),
  h5_pool (BS_KERNEL.create_object ("h5_pool")),
  props (BS_KERNEL.create_object ("prop"))
  {
    init();
  }

  idata::idata(const this_t &src)
      : bs_refcounter (src), bs_node(src),
      h5_pool(give_kernel::Instance().create_object_copy(src.h5_pool)),
      props(give_kernel::Instance().create_object_copy(src.props))
      //scal3(give_kernel::Instance().create_object_copy(src.scal3)),
  {
    *this = src;
  }

  void idata::init()
  {
    //depth.resize((nx+1) * (ny+1) * (nz+1));
    h5_pool->open_file ("bs_data_storage.h5", "/pool");

    props->add_property_f (DEFAULT_MINIMAL_PORE_VOLUME, "minimal_pore_volume", "Minimal pore volume allowed for active cells");
    props->add_property_f (DEFAULT_MINIMAL_SPLICE_VOLUME, "minimal_splice_volume", "Minimal pore volume allowed for active cells to splice with other cells");
    props->add_property_f (DEFAULT_MAXIMUM_SPLICE_THICKNESS, "maximum_splice_thickness", "Default maximum thickness allowed between active cells to be coupled");

    //props->add_property_i (1, "nx", "3-ph oil relative permeability model: flag 0, 1 or 2 (stone model)");
    //props->add_property_i (1, "ny", "3-ph oil relative permeability model: flag 0, 1 or 2 (stone model)");
    //props->add_property_i (1, "nz", "3-ph oil relative permeability model: flag 0, 1 or 2 (stone model)");
    props->add_property_i (0, "rpo_model", "3-ph oil relative permeability model: flag 0, 1 or 2 (stone model)");
    props->add_property_i (1, "pvt_region", "Number of PVT regions in simulation");
    props->add_property_i (1, "sat_region", "Number of saturation regions in simulation");
    props->add_property_i (1, "eql_region", "Number of equilibrium regions in simulation");
    props->add_property_i (1, "fip_region", "Number of FIP regions in simulation");
    props->add_property_i (1, "rock_region", "Number of ROCK regions");
    props->add_property_i (0, "init_section", "flag indicating whether we have init section");

    props->add_property_s ("", "title", "Current model title");
    props->add_property_b (0, "oil_phase", "True if oil phase exists");
    props->add_property_b (0, "water_phase", "True if water phase exists");
    props->add_property_b (0, "gas_phase", "True if gas phase exists");
    props->add_property_b (0, "scalecrs", "True if SCALECRS is enabled");

  }

  void idata::flush_pool()
  {
    h5_pool->flush ();
  }

  idata &idata::operator=(const this_t &src)
  {
    h5_pool = src.h5_pool;
    return *this;
  }

  idata::vval_vs_depth &idata::get_prvd()
  {
    return prvd;
  }

  idata::vval_vs_depth &idata::get_rsvd()
  {
    return rsvd;
  }

  idata::vval_vs_depth &idata::get_pbvd()
  {
    return pbvd;
  }

  //idata::vsp_pvt &idata::get_pvt()
  //{
  //  return pvt;
  //}

  //const idata::sp_scal3p &idata::get_scal()
  //{
  //  return scal3;
  //}
  /*!
  	\brief updating dx, dy, dz
  				 add values in nonactive blocks for mesh generation algorithm
  	\return if success  0
  */

  void idata::set_region (int r_pvt,int r_sat, int r_eql, int r_fip)
  {
    props->set_i ("pvt_region", r_pvt);
    props->set_i ("fip_region", r_fip);
    props->set_i ("sat_region", r_sat);
    props->set_i ("eql_region", r_eql);

    // check
    if (r_pvt <= 0 || r_sat <= 0 || r_eql <= 0 || r_fip <= 0)
      {
        bs_throw_exception ("One of init parameters <= 0");
      }

    t_long def_val = -1;

    this->rock->resize(r_pvt);
    this->p_ref->resize(r_pvt);

    this->rock->assign (def_val);
    this->p_ref->assign (def_val);

    this->equil->resize(EQUIL_TOTAL * r_eql); //!TODO: EQUIL_TOTAL instead of 3

    this->pvto.resize(r_pvt);
    this->pvtdo.resize(r_pvt);
    this->pvtg.resize(r_pvt);
    this->pvtw.resize(r_pvt);
  }

  void idata::set_density (spv_float density)
  {
    if ((density->size() % 3 != 0) || (density->size()<3))
      {
        bs_throw_exception ("Not enough valid arguments yet");
      }

    set_density_internal(&(*density)[0]);
  }

  void idata::set_density_internal (const t_float *density)
  {
    std::ostringstream out_s;

    if (!pvto.size())
      throw bs_exception("idata.set_density()","PVT table for oil has not been initialized yet");

    if (!pvtw.size())
      throw bs_exception("idata.set_density()","PVT table for water has not been initialized yet");

    if (!pvtg.size())
      throw bs_exception("idata.set_density()","PVT table for gas has not been initialized yet");

    if (!rock->size())
      throw bs_exception("idata.set_density()","Rock properties table has not been initialized yet");

    if (!equil->size())
      throw bs_exception("idata.set_density()","EQUIL table has not been initialized yet");

    t_int n_pvt = props->get_i ("pvt_region");

    for (t_int i = 0; i < n_pvt; ++i)
      {
        idata::pvt_info &pvto__ = pvto[i];
        idata::pvt_info &pvtw__ = pvtw[i];
        idata::pvt_info &pvtg__ = pvtg[i];
        idata::pvt_info &pvdo__ = pvtdo[i];

        pvto__.has_density_		= true;
        pvto__.density_				= density[i*3];
        pvto__.molar_density_ = density[i*3];

        pvdo__.has_density_		= true;
        pvdo__.density_				= density[i*3];
        pvdo__.molar_density_ = density[i*3];

        pvtw__.has_density_		= true;
        pvtw__.density_				= density[i*3+1];
        pvtw__.molar_density_ = density[i*3+1];

        pvtg__.has_density_		= true;
        pvtg__.density_				= density[i*3+2];
        pvtg__.molar_density_ = density[i*3+2];
      }
  }

  spv_int idata::get_i_array (const std::string & array_name, bool safe = true)
  {
    return safe
        ? h5_pool->get_i_data (array_name)
        : h5_pool->get_i_data_unsafe (array_name)
        ;
  }

  spv_float idata::get_fp_array (const std::string &array_name, bool safe = true)
  {
    return safe
        ? h5_pool->get_fp_data (array_name)
        : h5_pool->get_fp_data_unsafe (array_name)
        ;
  }

  bool
  idata::contains_i_array (const std::string &array_name)
  {
    const spv_int &a = h5_pool->get_i_data_unsafe (array_name);
    return a && a->size ();
  }

  bool
  idata::contains_fp_array (const std::string &array_name)
  {
    const spv_float &a = h5_pool->get_fp_data_unsafe (array_name);
    return a && a->size ();
  }

  int idata::set_i_array (const std::string & array_name,  spv_int array)
  {
    return h5_pool->set_i_data (array_name, array);
  }

  int idata::set_fp_array (const std::string & array_name,  spv_float array)
  {
    return h5_pool->set_fp_data (array_name, array);
  }

  spv_int idata::create_i_array (const std::string & array_name,  t_int *array_dimens, t_int def_value)
  {
    spv_int new_array;
    t_long n;
    npy_intp dims[3];

    dims[0] = array_dimens[ARRAY_POOL_NX_A] * props->get_i ("nx") + array_dimens[ARRAY_POOL_NX_B];
    dims[1] = array_dimens[ARRAY_POOL_NY_A] * props->get_i ("ny") + array_dimens[ARRAY_POOL_NY_B];
    dims[2] = array_dimens[ARRAY_POOL_NZ_A] * props->get_i ("nz") + array_dimens[ARRAY_POOL_NZ_B];
    n = dims[0] * dims[1] * dims[2];

    new_array = BS_KERNEL.create_object (v_int::bs_type ());
    new_array->resize (n);
    std::fill (new_array->begin (), new_array->end(), def_value);
    new_array->reshape (3, dims);

    return new_array;
  }

  spv_float idata::create_fp_array (const std::string & array_name,  t_int *array_dimens, t_float def_value)
  {
    spv_float new_array;
    t_long n;
    npy_intp dims[3];
    dims[0] = array_dimens[ARRAY_POOL_NX_A] * props->get_i ("nx") + array_dimens[ARRAY_POOL_NX_B];
    dims[1] = array_dimens[ARRAY_POOL_NY_A] * props->get_i ("ny") + array_dimens[ARRAY_POOL_NY_B];
    dims[2] = array_dimens[ARRAY_POOL_NZ_A] * props->get_i ("nz") + array_dimens[ARRAY_POOL_NZ_B];
    n = dims[0] * dims[1] * dims[2];

    new_array = BS_KERNEL.create_object (v_float::bs_type ());
    new_array->resize (n);
    std::fill (new_array->begin (), new_array->end(), def_value);
    new_array->reshape (3, dims);

    return new_array;
  }

  // create object
  BLUE_SKY_TYPE_STD_CREATE(idata)
  BLUE_SKY_TYPE_STD_COPY(idata)

  BLUE_SKY_TYPE_IMPL(idata, bs_node, "idata", "BOS_Core Initial data storage", "BOS_Core Initial data storage")
}
<commit_msg>Remove default value from idata::get_*_array impl<commit_after>/**
	\file data_class.cpp
	\brief implimenataion of idata class methods
	\author Nikonov Maxim
*/
#include "bs_bos_core_data_storage_stdafx.h"

#include "data_class.h"
#include "arrays.h"
#include "arrays_tables.h"
#include "constants.h"

//! Default minimal pore volume allowed for active cells
//#define DEFAULT_MINIMAL_PORE_VOLUME     1.e-1
#define DEFAULT_MINIMAL_PORE_VOLUME     1.e-7
//! Default minimal pore volume allowed for active cells to splice with other cells
// miryanov: set MINSV equal to MINPV for SPE10 model
#define DEFAULT_MINIMAL_SPLICE_VOLUME     1.e-7
//! Default maximum thickness allowed between active cells to be coupled
#define DEFAULT_MAXIMUM_SPLICE_THICKNESS     1.e-2

namespace blue_sky
  {
  /*!
  	\class idata_traits
  	\brief for node insertion control
  */

  struct idata::idata_traits : public bs_node::sort_traits
    {
      struct idata_key : bs_node::sort_traits::key_type
        {
          virtual bool sort_order(const key_ptr&) const
            {
              return true;
            }
        };

      virtual const char *sort_name() const
        {
          return "idata trait";
        }

      virtual key_ptr key_generator(const sp_link&) const
        {
          return new idata_key();
        }

      virtual bool accepts(const sp_link &l) const
        {
          if (l->name().find("_in_pool",0,l->name().size()))
            return smart_ptr<this_t>(l->data(), bs_dynamic_cast());
          return false;
        }
    };

  idata::~idata ()
  {
    h5_pool->close_file();
  }

  idata::idata(bs_type_ctor_param /*param*/)
  : bs_node(bs_node::create_node (new this_t::idata_traits ())),
  h5_pool (BS_KERNEL.create_object ("h5_pool")),
  props (BS_KERNEL.create_object ("prop"))
  {
    init();
  }

  idata::idata(const this_t &src)
      : bs_refcounter (src), bs_node(src),
      h5_pool(give_kernel::Instance().create_object_copy(src.h5_pool)),
      props(give_kernel::Instance().create_object_copy(src.props))
      //scal3(give_kernel::Instance().create_object_copy(src.scal3)),
  {
    *this = src;
  }

  void idata::init()
  {
    //depth.resize((nx+1) * (ny+1) * (nz+1));
    h5_pool->open_file ("bs_data_storage.h5", "/pool");

    props->add_property_f (DEFAULT_MINIMAL_PORE_VOLUME, "minimal_pore_volume", "Minimal pore volume allowed for active cells");
    props->add_property_f (DEFAULT_MINIMAL_SPLICE_VOLUME, "minimal_splice_volume", "Minimal pore volume allowed for active cells to splice with other cells");
    props->add_property_f (DEFAULT_MAXIMUM_SPLICE_THICKNESS, "maximum_splice_thickness", "Default maximum thickness allowed between active cells to be coupled");

    //props->add_property_i (1, "nx", "3-ph oil relative permeability model: flag 0, 1 or 2 (stone model)");
    //props->add_property_i (1, "ny", "3-ph oil relative permeability model: flag 0, 1 or 2 (stone model)");
    //props->add_property_i (1, "nz", "3-ph oil relative permeability model: flag 0, 1 or 2 (stone model)");
    props->add_property_i (0, "rpo_model", "3-ph oil relative permeability model: flag 0, 1 or 2 (stone model)");
    props->add_property_i (1, "pvt_region", "Number of PVT regions in simulation");
    props->add_property_i (1, "sat_region", "Number of saturation regions in simulation");
    props->add_property_i (1, "eql_region", "Number of equilibrium regions in simulation");
    props->add_property_i (1, "fip_region", "Number of FIP regions in simulation");
    props->add_property_i (1, "rock_region", "Number of ROCK regions");
    props->add_property_i (0, "init_section", "flag indicating whether we have init section");

    props->add_property_s ("", "title", "Current model title");
    props->add_property_b (0, "oil_phase", "True if oil phase exists");
    props->add_property_b (0, "water_phase", "True if water phase exists");
    props->add_property_b (0, "gas_phase", "True if gas phase exists");
    props->add_property_b (0, "scalecrs", "True if SCALECRS is enabled");

  }

  void idata::flush_pool()
  {
    h5_pool->flush ();
  }

  idata &idata::operator=(const this_t &src)
  {
    h5_pool = src.h5_pool;
    return *this;
  }

  idata::vval_vs_depth &idata::get_prvd()
  {
    return prvd;
  }

  idata::vval_vs_depth &idata::get_rsvd()
  {
    return rsvd;
  }

  idata::vval_vs_depth &idata::get_pbvd()
  {
    return pbvd;
  }

  //idata::vsp_pvt &idata::get_pvt()
  //{
  //  return pvt;
  //}

  //const idata::sp_scal3p &idata::get_scal()
  //{
  //  return scal3;
  //}
  /*!
  	\brief updating dx, dy, dz
  				 add values in nonactive blocks for mesh generation algorithm
  	\return if success  0
  */

  void idata::set_region (int r_pvt,int r_sat, int r_eql, int r_fip)
  {
    props->set_i ("pvt_region", r_pvt);
    props->set_i ("fip_region", r_fip);
    props->set_i ("sat_region", r_sat);
    props->set_i ("eql_region", r_eql);

    // check
    if (r_pvt <= 0 || r_sat <= 0 || r_eql <= 0 || r_fip <= 0)
      {
        bs_throw_exception ("One of init parameters <= 0");
      }

    t_long def_val = -1;

    this->rock->resize(r_pvt);
    this->p_ref->resize(r_pvt);

    this->rock->assign (def_val);
    this->p_ref->assign (def_val);

    this->equil->resize(EQUIL_TOTAL * r_eql); //!TODO: EQUIL_TOTAL instead of 3

    this->pvto.resize(r_pvt);
    this->pvtdo.resize(r_pvt);
    this->pvtg.resize(r_pvt);
    this->pvtw.resize(r_pvt);
  }

  void idata::set_density (spv_float density)
  {
    if ((density->size() % 3 != 0) || (density->size()<3))
      {
        bs_throw_exception ("Not enough valid arguments yet");
      }

    set_density_internal(&(*density)[0]);
  }

  void idata::set_density_internal (const t_float *density)
  {
    std::ostringstream out_s;

    if (!pvto.size())
      throw bs_exception("idata.set_density()","PVT table for oil has not been initialized yet");

    if (!pvtw.size())
      throw bs_exception("idata.set_density()","PVT table for water has not been initialized yet");

    if (!pvtg.size())
      throw bs_exception("idata.set_density()","PVT table for gas has not been initialized yet");

    if (!rock->size())
      throw bs_exception("idata.set_density()","Rock properties table has not been initialized yet");

    if (!equil->size())
      throw bs_exception("idata.set_density()","EQUIL table has not been initialized yet");

    t_int n_pvt = props->get_i ("pvt_region");

    for (t_int i = 0; i < n_pvt; ++i)
      {
        idata::pvt_info &pvto__ = pvto[i];
        idata::pvt_info &pvtw__ = pvtw[i];
        idata::pvt_info &pvtg__ = pvtg[i];
        idata::pvt_info &pvdo__ = pvtdo[i];

        pvto__.has_density_		= true;
        pvto__.density_				= density[i*3];
        pvto__.molar_density_ = density[i*3];

        pvdo__.has_density_		= true;
        pvdo__.density_				= density[i*3];
        pvdo__.molar_density_ = density[i*3];

        pvtw__.has_density_		= true;
        pvtw__.density_				= density[i*3+1];
        pvtw__.molar_density_ = density[i*3+1];

        pvtg__.has_density_		= true;
        pvtg__.density_				= density[i*3+2];
        pvtg__.molar_density_ = density[i*3+2];
      }
  }

  spv_int idata::get_i_array (const std::string & array_name, bool safe)
  {
    return safe
        ? h5_pool->get_i_data (array_name)
        : h5_pool->get_i_data_unsafe (array_name)
        ;
  }

  spv_float idata::get_fp_array (const std::string &array_name, bool safe)
  {
    return safe
        ? h5_pool->get_fp_data (array_name)
        : h5_pool->get_fp_data_unsafe (array_name)
        ;
  }

  bool
  idata::contains_i_array (const std::string &array_name)
  {
    const spv_int &a = h5_pool->get_i_data_unsafe (array_name);
    return a && a->size ();
  }

  bool
  idata::contains_fp_array (const std::string &array_name)
  {
    const spv_float &a = h5_pool->get_fp_data_unsafe (array_name);
    return a && a->size ();
  }

  int idata::set_i_array (const std::string & array_name,  spv_int array)
  {
    return h5_pool->set_i_data (array_name, array);
  }

  int idata::set_fp_array (const std::string & array_name,  spv_float array)
  {
    return h5_pool->set_fp_data (array_name, array);
  }

  spv_int idata::create_i_array (const std::string & array_name,  t_int *array_dimens, t_int def_value)
  {
    spv_int new_array;
    t_long n;
    npy_intp dims[3];

    dims[0] = array_dimens[ARRAY_POOL_NX_A] * props->get_i ("nx") + array_dimens[ARRAY_POOL_NX_B];
    dims[1] = array_dimens[ARRAY_POOL_NY_A] * props->get_i ("ny") + array_dimens[ARRAY_POOL_NY_B];
    dims[2] = array_dimens[ARRAY_POOL_NZ_A] * props->get_i ("nz") + array_dimens[ARRAY_POOL_NZ_B];
    n = dims[0] * dims[1] * dims[2];

    new_array = BS_KERNEL.create_object (v_int::bs_type ());
    new_array->resize (n);
    std::fill (new_array->begin (), new_array->end(), def_value);
    new_array->reshape (3, dims);

    return new_array;
  }

  spv_float idata::create_fp_array (const std::string & array_name,  t_int *array_dimens, t_float def_value)
  {
    spv_float new_array;
    t_long n;
    npy_intp dims[3];
    dims[0] = array_dimens[ARRAY_POOL_NX_A] * props->get_i ("nx") + array_dimens[ARRAY_POOL_NX_B];
    dims[1] = array_dimens[ARRAY_POOL_NY_A] * props->get_i ("ny") + array_dimens[ARRAY_POOL_NY_B];
    dims[2] = array_dimens[ARRAY_POOL_NZ_A] * props->get_i ("nz") + array_dimens[ARRAY_POOL_NZ_B];
    n = dims[0] * dims[1] * dims[2];

    new_array = BS_KERNEL.create_object (v_float::bs_type ());
    new_array->resize (n);
    std::fill (new_array->begin (), new_array->end(), def_value);
    new_array->reshape (3, dims);

    return new_array;
  }

  // create object
  BLUE_SKY_TYPE_STD_CREATE(idata)
  BLUE_SKY_TYPE_STD_COPY(idata)

  BLUE_SKY_TYPE_IMPL(idata, bs_node, "idata", "BOS_Core Initial data storage", "BOS_Core Initial data storage")
}
<|endoftext|>


<commit_before>/*
 * globalArrayXML.cpp
 *
 *  Created on: Oct 31, 2016
 *      Author: pnorbert
 */

#include <stdexcept>
#include <mpi.h>
#include <iostream>
#include <fstream>
#include <string>
#include <vector>

#include "ADIOS.h"

struct MYDATA {
    int NX;
    double *t;
    std::vector<double> p;
};

const int N = 10;
struct MYDATA solid, fluid;
MPI_Comm    comm=MPI_COMM_WORLD;
int         rank, size;

void write_data (adios::ADIOS adios, struct MYDATA &data, unsigned int outfile)
{
    adios.Write (outfile, "NX", &data.NX);
    adios.Write (outfile, "rank", &rank);
    adios.Write (outfile, "size", &size);
    adios.Write (outfile, "temperature", data.t);
    adios.Write (outfile, "pressure", data.p);
    //adios.Write (outfile, true); // true: advance step, this is default value
    adios.Write (outfile);
}

void write_checkpoint (adios::ADIOS adios, struct MYDATA &solid, struct MYDATA &fluid)
{
    try {
        // Open an output for a Group
        // a transport or an engine should be associated with the group
        int ckptfile = adios.Open("checkpoint.bp", "checkpoint", "w", comm);

        adios.Write (ckptfile, "solid/NX", &solid.NX);
        adios.Write (ckptfile, "solid/rank", &rank);
        adios.Write (ckptfile, "solid/size", &size);
        adios.Write (ckptfile, "solid/temperature", solid.t);
        adios.Write (ckptfile, "solid/pressure", solid.p);

        adios.Write (ckptfile, "fluid/NX", &fluid.NX);
        adios.Write (ckptfile, "fluid/rank", &rank);
        adios.Write (ckptfile, "fluid/size", &size);
        adios.Write (ckptfile, "fluid/temperature", fluid.t);
        adios.Write (ckptfile, "fluid/pressure", fluid.p);

        adios.Write(ckptfile);
        adios.Close(ckptfile); // Should this do Write() if user misses or should we complain?
    }
    catch ( std::exception& e ) //need to think carefully how to handle C++ exceptions with MPI to avoid deadlocking
    {
        if( rank == 0 )
        {
            std::cout << e.what() << "\n";
        }
    }
}

void write_viz (adios::ADIOS adios, struct MYDATA &solid, struct MYDATA &fluid, unsigned int vizstream)
{
    // This stream is not associated with a group, so we must say for each write which group to use
    // The output variable is re-defined inside as <groupname>/<varname>, unless given as third string argument
    // An array variable's dimension definitions are also re-defined with dimensions <groupname>/<dimensionvar>
    adios.Write (vizstream, "solid", "NX", &solid.NX);
    adios.Write (vizstream, "solid", "rank", &rank);
    adios.Write (vizstream, "solid", "size", &size);
    // write solid group's temperature simply as temperature, risking overloading the 'temperature' variable when
    // reading from a file
    adios.Write (vizstream, "solid", "temperature", "my/tempvarinfile", solid.t);

    adios.Write (vizstream, "fluid", "NX", &fluid.NX);
    adios.Write (vizstream, "fluid", "rank", &rank);
    adios.Write (vizstream, "fluid", "size", &size);

    adios.Write (vizstream, "fluid", "temperature", "temperature", fluid.t);

    adios.Write(vizstream); // flushes all data to disk; required operation
    vizstream.AdvanceStep();
}

void compute (int it,  struct MYDATA &solid, struct MYDATA &fluid)
{
    for (int i = 0; i < solid.NX; i++)
    {
        solid.t[i] = it*100.0 + rank*solid.NX + i;
        solid.p[i] = it*1000.0 + rank*solid.NX + i;
    }
    for (int i = 0; i < fluid.NX; i++)
    {
        fluid.t[i] = it*200.0 + rank*fluid.NX + i;
        fluid.p[i] = it*2000.0 + rank*fluid.NX + i;
    }
}

int main( int argc, char* argv [] )
{
    MPI_Init (&argc, &argv);
    MPI_Comm_rank (comm, &rank);
    MPI_Comm_size (comm, &size);

    solid.NX = N;
    solid.t = new double(N);
    solid.p = std::vector<double>(N);

    fluid.NX = N;
    fluid.t = new double(N);
    fluid.p = std::vector<double>(N);

    try
    {
        // ADIOS manager object creation. MPI must be initialized
        adios::ADIOS adios( "globalArrayXML.xml", comm, true );

        // Open a file with a Method which has selected a group and a transport in the XML.
        // "a" will append to an already existing file, "w" would create a new file
        // Multiple writes to the same file work as append in this application run
        // FIXME: how do we support Update to same step?

        int solidfile = adios.Open("solid.bp", "solid", "a", comm); // "solid" is a method but incidentally also a group
        // Constructor only creates an object and what is needed there but does not open a stream/file
        // It can be used to initialize a staging connection if not declared before
        // FIXME: which argument can be post-poned into Open() instead of constructor?
        //solidfile.Open("solid.bp");

        // Open a file with a Method that has selected a group and an engine in the XML
        // The transport method(s) are (must be) associated with the engines
        // "a" will append to an already existing file, "w" would create a new file
        // Multiple writes to the same file work as append in this application run
        // FIXME: how do we support Update to same step?
        int fluidfile = adios.Open("fluid.bp", "fluid", "a", comm);

        //int ckptfile = adios.Open("checkpoint.bp", "checkpoint", "w", comm);
        // we do not open this here, but every time when needed in a function

        // Another output not associated with a single group, so that we can mix variables to it
        //adios:handle vizstream = adios.Open( "stream.bp", comm, "w", "STAGING", "options to staging method");
        int vizstream = adios.Open( "stream.bp", comm, "w", "groupless");

        // This creates an empty group inside, and we can write all kinds of variables to it

        //Get Monitor info
        std::ofstream logStream( "info_" + std::to_string(rank) + ".log" );
        adios.MonitorGroups( logStream );

        for (int it = 1; it <= 100; it++)
        {
            compute (it, solid, fluid);

            write_data(adios, solid, solidfile);
            write_data(adios, fluid, fluidfile);

            if (it%10 == 0) {
                write_checkpoint (adios, solid, fluid);
            }

            write_viz(adios, solid, fluid, vizstream);

            MPI_Barrier (comm);
            if (rank==0) printf("Timestep %d written\n", it);
        }

        adios.Close(solidfile);
        adios.Close(fluidfile);
        adios.Close(vizstream);

        // need barrier before we destroy the ADIOS object here automatically
        MPI_Barrier (comm);
        if (rank==0) printf("Finalize adios\n");
    }
    catch( std::exception& e ) //need to think carefully how to handle C++ exceptions with MPI to avoid deadlocking
    {
        if( rank == 0 )
        {
            std::cout << e.what() << "\n";
        }
    }

    delete[] solid.t;
    delete[] fluid.t;

    if (rank==0) printf("Finalize MPI\n");
    MPI_Finalize ();
    return 0;
}
<commit_msg>fix Write(vector) per API<commit_after>/*
 * globalArrayXML.cpp
 *
 *  Created on: Oct 31, 2016
 *      Author: pnorbert
 */

#include <stdexcept>
#include <mpi.h>
#include <iostream>
#include <fstream>
#include <string>
#include <vector>

#include "ADIOS.h"

struct MYDATA {
    int NX;
    double *t;
    std::vector<double> p;
};

const int N = 10;
struct MYDATA solid, fluid;
MPI_Comm    comm=MPI_COMM_WORLD;
int         rank, size;

void write_data (adios::ADIOS adios, struct MYDATA &data, unsigned int outfile)
{
    adios.Write (outfile, "NX", &data.NX);
    adios.Write (outfile, "rank", &rank);
    adios.Write (outfile, "size", &size);
    adios.Write (outfile, "temperature", data.t);
    adios.Write (outfile, "pressure", data.p.data());
    //adios.Write (outfile, true); // true: advance step, this is default value
    adios.Write (outfile);
}

void write_checkpoint (adios::ADIOS adios, struct MYDATA &solid, struct MYDATA &fluid)
{
    try {
        // Open an output for a Group
        // a transport or an engine should be associated with the group
        int ckptfile = adios.Open("checkpoint.bp", "checkpoint", "w", comm);

        adios.Write (ckptfile, "solid/NX", &solid.NX);
        adios.Write (ckptfile, "solid/rank", &rank);
        adios.Write (ckptfile, "solid/size", &size);
        adios.Write (ckptfile, "solid/temperature", solid.t);
        adios.Write (ckptfile, "solid/pressure", &solid.p[0]);

        adios.Write (ckptfile, "fluid/NX", &fluid.NX);
        adios.Write (ckptfile, "fluid/rank", &rank);
        adios.Write (ckptfile, "fluid/size", &size);
        adios.Write (ckptfile, "fluid/temperature", fluid.t);
        adios.Write (ckptfile, "fluid/pressure", fluid.p.data());

        adios.Write(ckptfile);
        adios.Close(ckptfile); // Should this do Write() if user misses or should we complain?
    }
    catch ( std::exception& e ) //need to think carefully how to handle C++ exceptions with MPI to avoid deadlocking
    {
        if( rank == 0 )
        {
            std::cout << e.what() << "\n";
        }
    }
}

void write_viz (adios::ADIOS adios, struct MYDATA &solid, struct MYDATA &fluid, unsigned int vizstream)
{
    // This stream is not associated with a group, so we must say for each write which group to use
    // The output variable is re-defined inside as <groupname>/<varname>, unless given as third string argument
    // An array variable's dimension definitions are also re-defined with dimensions <groupname>/<dimensionvar>
    adios.Write (vizstream, "solid", "NX", &solid.NX);
    adios.Write (vizstream, "solid", "rank", &rank);
    adios.Write (vizstream, "solid", "size", &size);
    // write solid group's temperature simply as temperature, risking overloading the 'temperature' variable when
    // reading from a file
    adios.Write (vizstream, "solid", "temperature", "my/tempvarinfile", solid.t);

    adios.Write (vizstream, "fluid", "NX", &fluid.NX);
    adios.Write (vizstream, "fluid", "rank", &rank);
    adios.Write (vizstream, "fluid", "size", &size);

    adios.Write (vizstream, "fluid", "temperature", "temperature", fluid.t);

    adios.Write(vizstream); // flushes all data to disk; required operation
    vizstream.AdvanceStep();
}

void compute (int it,  struct MYDATA &solid, struct MYDATA &fluid)
{
    for (int i = 0; i < solid.NX; i++)
    {
        solid.t[i] = it*100.0 + rank*solid.NX + i;
        solid.p[i] = it*1000.0 + rank*solid.NX + i;
    }
    for (int i = 0; i < fluid.NX; i++)
    {
        fluid.t[i] = it*200.0 + rank*fluid.NX + i;
        fluid.p[i] = it*2000.0 + rank*fluid.NX + i;
    }
}

int main( int argc, char* argv [] )
{
    MPI_Init (&argc, &argv);
    MPI_Comm_rank (comm, &rank);
    MPI_Comm_size (comm, &size);

    solid.NX = N;
    solid.t = new double(N);
    solid.p = std::vector<double>(N);

    fluid.NX = N;
    fluid.t = new double(N);
    fluid.p = std::vector<double>(N);

    try
    {
        // ADIOS manager object creation. MPI must be initialized
        adios::ADIOS adios( "globalArrayXML.xml", comm, true );

        // Open a file with a Method which has selected a group and a transport in the XML.
        // "a" will append to an already existing file, "w" would create a new file
        // Multiple writes to the same file work as append in this application run
        // FIXME: how do we support Update to same step?

        int solidfile = adios.Open("solid.bp", "solid", "a", comm); // "solid" is a method but incidentally also a group
        // Constructor only creates an object and what is needed there but does not open a stream/file
        // It can be used to initialize a staging connection if not declared before
        // FIXME: which argument can be post-poned into Open() instead of constructor?
        //solidfile.Open("solid.bp");

        // Open a file with a Method that has selected a group and an engine in the XML
        // The transport method(s) are (must be) associated with the engines
        // "a" will append to an already existing file, "w" would create a new file
        // Multiple writes to the same file work as append in this application run
        // FIXME: how do we support Update to same step?
        int fluidfile = adios.Open("fluid.bp", "fluid", "a", comm);

        //int ckptfile = adios.Open("checkpoint.bp", "checkpoint", "w", comm);
        // we do not open this here, but every time when needed in a function

        // Another output not associated with a single group, so that we can mix variables to it
        //adios:handle vizstream = adios.Open( "stream.bp", comm, "w", "STAGING", "options to staging method");
        int vizstream = adios.Open( "stream.bp", comm, "w", "groupless");

        // This creates an empty group inside, and we can write all kinds of variables to it

        //Get Monitor info
        std::ofstream logStream( "info_" + std::to_string(rank) + ".log" );
        adios.MonitorGroups( logStream );

        for (int it = 1; it <= 100; it++)
        {
            compute (it, solid, fluid);

            write_data(adios, solid, solidfile);
            write_data(adios, fluid, fluidfile);

            if (it%10 == 0) {
                write_checkpoint (adios, solid, fluid);
            }

            write_viz(adios, solid, fluid, vizstream);

            MPI_Barrier (comm);
            if (rank==0) printf("Timestep %d written\n", it);
        }

        adios.Close(solidfile);
        adios.Close(fluidfile);
        adios.Close(vizstream);

        // need barrier before we destroy the ADIOS object here automatically
        MPI_Barrier (comm);
        if (rank==0) printf("Finalize adios\n");
    }
    catch( std::exception& e ) //need to think carefully how to handle C++ exceptions with MPI to avoid deadlocking
    {
        if( rank == 0 )
        {
            std::cout << e.what() << "\n";
        }
    }

    delete[] solid.t;
    delete[] fluid.t;

    if (rank==0) printf("Finalize MPI\n");
    MPI_Finalize ();
    return 0;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: pptinanimations.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: kz $ $Date: 2006-12-12 16:46:37 $
 *
 *  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 _SD_PPT_INANIMATIONS_HXX
#define _SD_PPT_INANIMATIONS_HXX

#ifndef _COM_SUN_STAR_ANIMATIONS_XTIMECONTAINER_HPP_
#include <com/sun/star/animations/XTimeContainer.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_XDRAWPAGE_HPP_
#include <com/sun/star/drawing/XDrawPage.hpp>
#endif

#ifndef _SD_PPTANIMATIONS_HXX
#include "pptanimations.hxx"
#endif

#ifndef _SD_ANIMATIONS_HXX_
#include <animations.hxx>
#endif

#ifdef DBG_ANIM_LOG
#include <stdio.h>
#endif

#ifndef _SVDFPPT_HXX
#include <svx/svdfppt.hxx>
#endif

#include <list>

class DffRecordHeader;
class SdPage;
class SvStream;
class ImplSdPPTImport;

namespace ppt
{
class PropertySet;
class Atom;

class AnimationImporter
{
public:
    AnimationImporter( ImplSdPPTImport* pPPTImport, SvStream& rStCtrl );

    void import( const ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XDrawPage >& xPage, const DffRecordHeader& rProgTagContentHd );

private:
    void importAnimationContainer( const Atom* pAtom, const ::com::sun::star::uno::Reference< ::com::sun::star::animations::XAnimationNode >& xParent );
    void importTimeContainer( const Atom* pAtom, const ::com::sun::star::uno::Reference< ::com::sun::star::animations::XAnimationNode >& xNode );
    void importAnimationNodeContainer( const Atom* pAtom, const ::com::sun::star::uno::Reference< ::com::sun::star::animations::XAnimationNode >& xNode );
    void importAnimationSubContainer( const Atom* pAtom, const ::com::sun::star::uno::Reference< ::com::sun::star::animations::XAnimationNode >& xNode );

    void importAnimateSetContainer( const Atom* pAtom, const ::com::sun::star::uno::Reference< ::com::sun::star::animations::XAnimationNode >& xNode );
    void importAnimateFilterContainer( const Atom* pAtom, const ::com::sun::star::uno::Reference< ::com::sun::star::animations::XAnimationNode >& xNode );
    void importAnimateContainer( const Atom* pAtom, const ::com::sun::star::uno::Reference< ::com::sun::star::animations::XAnimationNode >& xNode );
    void importAnimateScaleContainer( const Atom* pAtom, const ::com::sun::star::uno::Reference< ::com::sun::star::animations::XAnimationNode >& xNode );
    void importAnimateColorContainer( const Atom* pAtom, const ::com::sun::star::uno::Reference< ::com::sun::star::animations::XAnimationNode >& xNode );
    void importAnimateRotationContainer( const Atom* pAtom, const ::com::sun::star::uno::Reference< ::com::sun::star::animations::XAnimationNode >& xNode );
    void importAnimateMotionContainer( const Atom* pAtom, const ::com::sun::star::uno::Reference< ::com::sun::star::animations::XAnimationNode >& xNode );
    void importCommandContainer( const Atom* pAtom, const ::com::sun::star::uno::Reference< ::com::sun::star::animations::XAnimationNode >& xNode );
    void importAudioContainer( const Atom* pAtom, const ::com::sun::star::uno::Reference< ::com::sun::star::animations::XAnimationNode >& xNode );

    void importAnimationEvents( const Atom* pAtom, const ::com::sun::star::uno::Reference< ::com::sun::star::animations::XAnimationNode >& xNode );
    void importAnimationValues( const Atom* pAtom, const ::com::sun::star::uno::Reference< ::com::sun::star::animations::XAnimationNode >& xNode );
    void importAnimationActions( const Atom* pAtom, const ::com::sun::star::uno::Reference< ::com::sun::star::animations::XAnimationNode >& xNode );
    void importAnimateAttributeTargetContainer( const Atom* pAtom, const ::com::sun::star::uno::Reference< ::com::sun::star::animations::XAnimationNode >& xNode );

    void importAnimateKeyPoints( const Atom* pAtom, const ::com::sun::star::uno::Reference< ::com::sun::star::animations::XAnimationNode >& xNode );
    void importPropertySetContainer( const Atom* pAtom,PropertySet& rSet );
    bool importAttributeValue( const Atom* pAtom, com::sun::star::uno::Any& rAny );
    bool importAttributeNamesContainer( const Atom* pAtom, rtl::OUString& rAttributeNames );
    sal_Int32 importTargetElementContainer( const Atom* pAtom, ::com::sun::star::uno::Any& rTarget, sal_Int16& nSubType );

    void fillNode( ::com::sun::star::uno::Reference< ::com::sun::star::animations::XAnimationNode >& xTiming, const AnimationNode& rNode, const PropertySet& rSet );
    ::com::sun::star::uno::Reference< ::com::sun::star::animations::XAnimationNode > createNode( const Atom* pAtom, const AnimationNode& rNode );

    bool convertAnimationNode( const ::com::sun::star::uno::Reference< ::com::sun::star::animations::XAnimationNode >& xNode, const ::com::sun::star::uno::Reference< ::com::sun::star::animations::XAnimationNode >& xParent );
    bool convertAnimationValue( MS_AttributeNames eAttribute, com::sun::star::uno::Any& rValue );

    void fixMainSequenceTiming( const ::com::sun::star::uno::Reference< ::com::sun::star::animations::XAnimationNode >& xNode );
    void fixInteractiveSequenceTiming( const ::com::sun::star::uno::Reference< ::com::sun::star::animations::XAnimationNode >& xNode );

    void processAfterEffectNodes();

    ::com::sun::star::uno::Any  implGetColorAny( sal_Int32 nMode, sal_Int32  nA, sal_Int32 nB, sal_Int32 nC );
    sal_Int16                   implGetColorSpace( sal_Int32 nMode, sal_Int32  nA, sal_Int32 nB, sal_Int32 nC );

private:
    ::com::sun::star::uno::Reference< ::com::sun::star::animations::XAnimationNode > mxRootNode;

    ImplSdPPTImport* mpPPTImport;
    SvStream&   mrStCtrl;

    sd::AfterEffectNodeList maAfterEffectNodes;

#ifdef DBG_ANIM_LOG
    FILE * mpFile;
#endif

    void dump_atom_header( const Atom* pAtom, bool bOpen, bool bAppend );
    void dump_atom( const Atom* pAtom, bool bNewLine = true );
    void dump( sal_uInt32 nLen, bool bNewLine = true );
    void dump_anim_group( const Atom* pAtom, const AnimationNode& rNode, const PropertySet& rSet, bool bOpen );
    void dump_target( ::com::sun::star::uno::Any& rAny );
    void dump( ::com::sun::star::uno::Any& rAny );
    void dump( const PropertySet& rSet );
    void dump( const AnimationNode& rNode );
    void dump( const char * pText );
    void dump( const rtl::OUString& rString );
    void dump( const char * pText, sal_Int32 nInt );
    void dump( const char * pText, double fDouble );
    void dump( const char * pText, const char * pText2 );
    void dump( const char * pText, const rtl::OUString& rString );
};

} // namespace ppt

#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.4.298); FILE MERGED 2008/04/01 15:34:04 thb 1.4.298.3: #i85898# Stripping all external header guards 2008/04/01 12:38:33 thb 1.4.298.2: #i85898# Stripping all external header guards 2008/03/31 13:56:53 rt 1.4.298.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: pptinanimations.hxx,v $
 * $Revision: 1.5 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef _SD_PPT_INANIMATIONS_HXX
#define _SD_PPT_INANIMATIONS_HXX

#include <com/sun/star/animations/XTimeContainer.hpp>
#include <com/sun/star/drawing/XDrawPage.hpp>

#ifndef _SD_PPTANIMATIONS_HXX
#include "pptanimations.hxx"
#endif
#include <animations.hxx>

#ifdef DBG_ANIM_LOG
#include <stdio.h>
#endif
#include <svx/svdfppt.hxx>

#include <list>

class DffRecordHeader;
class SdPage;
class SvStream;
class ImplSdPPTImport;

namespace ppt
{
class PropertySet;
class Atom;

class AnimationImporter
{
public:
    AnimationImporter( ImplSdPPTImport* pPPTImport, SvStream& rStCtrl );

    void import( const ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XDrawPage >& xPage, const DffRecordHeader& rProgTagContentHd );

private:
    void importAnimationContainer( const Atom* pAtom, const ::com::sun::star::uno::Reference< ::com::sun::star::animations::XAnimationNode >& xParent );
    void importTimeContainer( const Atom* pAtom, const ::com::sun::star::uno::Reference< ::com::sun::star::animations::XAnimationNode >& xNode );
    void importAnimationNodeContainer( const Atom* pAtom, const ::com::sun::star::uno::Reference< ::com::sun::star::animations::XAnimationNode >& xNode );
    void importAnimationSubContainer( const Atom* pAtom, const ::com::sun::star::uno::Reference< ::com::sun::star::animations::XAnimationNode >& xNode );

    void importAnimateSetContainer( const Atom* pAtom, const ::com::sun::star::uno::Reference< ::com::sun::star::animations::XAnimationNode >& xNode );
    void importAnimateFilterContainer( const Atom* pAtom, const ::com::sun::star::uno::Reference< ::com::sun::star::animations::XAnimationNode >& xNode );
    void importAnimateContainer( const Atom* pAtom, const ::com::sun::star::uno::Reference< ::com::sun::star::animations::XAnimationNode >& xNode );
    void importAnimateScaleContainer( const Atom* pAtom, const ::com::sun::star::uno::Reference< ::com::sun::star::animations::XAnimationNode >& xNode );
    void importAnimateColorContainer( const Atom* pAtom, const ::com::sun::star::uno::Reference< ::com::sun::star::animations::XAnimationNode >& xNode );
    void importAnimateRotationContainer( const Atom* pAtom, const ::com::sun::star::uno::Reference< ::com::sun::star::animations::XAnimationNode >& xNode );
    void importAnimateMotionContainer( const Atom* pAtom, const ::com::sun::star::uno::Reference< ::com::sun::star::animations::XAnimationNode >& xNode );
    void importCommandContainer( const Atom* pAtom, const ::com::sun::star::uno::Reference< ::com::sun::star::animations::XAnimationNode >& xNode );
    void importAudioContainer( const Atom* pAtom, const ::com::sun::star::uno::Reference< ::com::sun::star::animations::XAnimationNode >& xNode );

    void importAnimationEvents( const Atom* pAtom, const ::com::sun::star::uno::Reference< ::com::sun::star::animations::XAnimationNode >& xNode );
    void importAnimationValues( const Atom* pAtom, const ::com::sun::star::uno::Reference< ::com::sun::star::animations::XAnimationNode >& xNode );
    void importAnimationActions( const Atom* pAtom, const ::com::sun::star::uno::Reference< ::com::sun::star::animations::XAnimationNode >& xNode );
    void importAnimateAttributeTargetContainer( const Atom* pAtom, const ::com::sun::star::uno::Reference< ::com::sun::star::animations::XAnimationNode >& xNode );

    void importAnimateKeyPoints( const Atom* pAtom, const ::com::sun::star::uno::Reference< ::com::sun::star::animations::XAnimationNode >& xNode );
    void importPropertySetContainer( const Atom* pAtom,PropertySet& rSet );
    bool importAttributeValue( const Atom* pAtom, com::sun::star::uno::Any& rAny );
    bool importAttributeNamesContainer( const Atom* pAtom, rtl::OUString& rAttributeNames );
    sal_Int32 importTargetElementContainer( const Atom* pAtom, ::com::sun::star::uno::Any& rTarget, sal_Int16& nSubType );

    void fillNode( ::com::sun::star::uno::Reference< ::com::sun::star::animations::XAnimationNode >& xTiming, const AnimationNode& rNode, const PropertySet& rSet );
    ::com::sun::star::uno::Reference< ::com::sun::star::animations::XAnimationNode > createNode( const Atom* pAtom, const AnimationNode& rNode );

    bool convertAnimationNode( const ::com::sun::star::uno::Reference< ::com::sun::star::animations::XAnimationNode >& xNode, const ::com::sun::star::uno::Reference< ::com::sun::star::animations::XAnimationNode >& xParent );
    bool convertAnimationValue( MS_AttributeNames eAttribute, com::sun::star::uno::Any& rValue );

    void fixMainSequenceTiming( const ::com::sun::star::uno::Reference< ::com::sun::star::animations::XAnimationNode >& xNode );
    void fixInteractiveSequenceTiming( const ::com::sun::star::uno::Reference< ::com::sun::star::animations::XAnimationNode >& xNode );

    void processAfterEffectNodes();

    ::com::sun::star::uno::Any  implGetColorAny( sal_Int32 nMode, sal_Int32  nA, sal_Int32 nB, sal_Int32 nC );
    sal_Int16                   implGetColorSpace( sal_Int32 nMode, sal_Int32  nA, sal_Int32 nB, sal_Int32 nC );

private:
    ::com::sun::star::uno::Reference< ::com::sun::star::animations::XAnimationNode > mxRootNode;

    ImplSdPPTImport* mpPPTImport;
    SvStream&   mrStCtrl;

    sd::AfterEffectNodeList maAfterEffectNodes;

#ifdef DBG_ANIM_LOG
    FILE * mpFile;
#endif

    void dump_atom_header( const Atom* pAtom, bool bOpen, bool bAppend );
    void dump_atom( const Atom* pAtom, bool bNewLine = true );
    void dump( sal_uInt32 nLen, bool bNewLine = true );
    void dump_anim_group( const Atom* pAtom, const AnimationNode& rNode, const PropertySet& rSet, bool bOpen );
    void dump_target( ::com::sun::star::uno::Any& rAny );
    void dump( ::com::sun::star::uno::Any& rAny );
    void dump( const PropertySet& rSet );
    void dump( const AnimationNode& rNode );
    void dump( const char * pText );
    void dump( const rtl::OUString& rString );
    void dump( const char * pText, sal_Int32 nInt );
    void dump( const char * pText, double fDouble );
    void dump( const char * pText, const char * pText2 );
    void dump( const char * pText, const rtl::OUString& rString );
};

} // namespace ppt

#endif
<|endoftext|>