<commit_before>
#include "../../core/logs.h"
#include "../../private/graphics/opengl/glew/glew.h"
#include <iostream>
#include "glwindow.h"
#include "texture.h"

namespace Yuni
{
namespace UI
{

	bool GLWindow::initialize()
	{
		// Black background
		::glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
		// Depth Buffer setup
		::glClearDepth(1.0f);
		// Enables Depth Testing
		::glEnable(GL_DEPTH_TEST);
		// The type of Depth Testing to do
		::glDepthFunc(GL_LEQUAL);
		// Enable back-face culling
		::glEnable(GL_CULL_FACE);

		// Display OpenGL version
#ifndef NDEBUG
		Yuni::Logs::Logger<> logs;
		const uint8* version = ::glGetString(GL_VERSION);
		logs.notice() << "OpenGL " << (const char*)version;
#endif

		// Init GLEW
		GLenum error = ::glewInit();
		if (GLEW_OK != error)
			logs.error() << ::glewGetErrorString(error);

		// Wait for the context to be ready before initializing some GL objects in the main window
		RenderWindow::initialize();

		return true;
	}

	void GLWindow::resize(uint width, uint height)
	{
		// Prevent A Divide By Zero
		if (0 == height)
			height = 1;

		// Reset The Current Viewport
		::glViewport(0, 0, width, height);

		// Select the Projection Matrix
		::glMatrixMode(GL_PROJECTION);
		// Reset the Projection Matrix
		::glLoadIdentity();

		// Calculate the Aspect Ratio of the window
		::gluPerspective(60.0f, (GLfloat)width / (GLfloat)height, 0.01f, 1000.0f);

		// Select the Modelview Matrix
		::glMatrixMode(GL_MODELVIEW);
		// Reset the Modelview Matrix
		::glLoadIdentity();

		RenderWindow::resize(width, height);
	}

	void GLWindow::drawFullWindowQuad(const Gfx3D::Texture::Ptr& texture) const
	{
		auto textureType = multiSampling() ? GL_TEXTURE_2D_MULTISAMPLE : GL_TEXTURE_2D;
		::glBindTexture(textureType, texture->id());

		::glPushAttrib(GL_DEPTH_BUFFER_BIT | GL_ENABLE_BIT);
		::glDisable(GL_DEPTH_TEST);
		//::glCullFace(GL_FRONT);

		::glMatrixMode(GL_PROJECTION);
		::glPushMatrix();
		::glLoadIdentity();
		::gluOrtho2D(-1.0f, 1.0f, 1.0f, -1.0f);

		::glMatrixMode(GL_MODELVIEW);
		::glPushMatrix();
		::glLoadIdentity();

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

		/*
		// Texture coordinates are useless when 2D shaders are activated
		// but they are used when no post-processing effect is present
		const float texCoord[] =
			{
				0.0f, 0.0f,
				0.0f, 1.0f,
				1.0f, 1.0f,
				0.0f, 0.0f,
				1.0f, 1.0f,
				1.0f, 0.0f
			};
		::glEnableVertexAttribArray(Gfx3D::Vertex<>::vaTextureCoord);
		::glVertexAttribPointer(Gfx3D::Vertex<>::vaTextureCoord, 2, GL_FLOAT, 0, 0, texCoord);
		// Set vertex positions
		const float vertices[] =
			{
				-1.0f, 1.0f,
				-1.0f, -1.0f,
				1.0f, -1.0f,
				-1.0f, 1.0f,
				1.0f, -1.0f,
				1.0f, 1.0f
			};
		::glEnableVertexAttribArray(Gfx3D::Vertex<>::vaPosition);
		::glVertexAttribPointer(Gfx3D::Vertex<>::vaPosition, 2, GL_FLOAT, 0, 0, vertices);
		// Draw
		::glDrawArrays(GL_TRIANGLES, 0, 6);
		*/

		::glMatrixMode(GL_PROJECTION);
		::glPopMatrix();
		::glMatrixMode(GL_MODELVIEW);
		::glPopMatrix();

		::glPopAttrib();
		//::glCullFace(GL_BACK);

		::glBindTexture(textureType, 0);
	}

	void GLWindow::clear() const
	{
		::glClear(GL_COLOR_BUFFER_BIT);
	}

	void GLWindow::clear(const Color::RGB<>& color) const
	{
		::glClearColor(color.red, color.green, color.blue, 1.0f);
		::glClear(GL_COLOR_BUFFER_BIT);
	}

	void GLWindow::clearRect(int x, int y, uint width, uint height) const
	{
		// We offer coordinates top-left to bottom-right
		// but GL coordinates are bottom-left to top-right, so convert Y
		::glEnable(GL_SCISSOR_TEST);
		::glScissor(x, pHeight - height - y, width, height);
		::glClear(GL_COLOR_BUFFER_BIT);
		::glDisable(GL_SCISSOR_TEST);
	}

} // namespace UI
} // namespace Yuni
<commit_msg>UI : Fixed Release compilation.<commit_after>
#include "../../core/logs.h"
#include "../../private/graphics/opengl/glew/glew.h"
#include <iostream>
#include "glwindow.h"
#include "texture.h"

namespace Yuni
{
namespace UI
{

	bool GLWindow::initialize()
	{
		// Black background
		::glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
		// Depth Buffer setup
		::glClearDepth(1.0f);
		// Enables Depth Testing
		::glEnable(GL_DEPTH_TEST);
		// The type of Depth Testing to do
		::glDepthFunc(GL_LEQUAL);
		// Enable back-face culling
		::glEnable(GL_CULL_FACE);

		// Display OpenGL version
#ifndef NDEBUG
		Yuni::Logs::Logger<> logs;
		const uint8* version = ::glGetString(GL_VERSION);
		logs.notice() << "OpenGL " << (const char*)version;
#endif

		// Init GLEW
		GLenum error = ::glewInit();
		if (GLEW_OK != error)
		{
#ifndef NDEBUG
			logs.error() << ::glewGetErrorString(error);
#endif
			return false;
		}

		// Wait for the context to be ready before initializing some GL objects in the main window
		RenderWindow::initialize();

		return true;
	}

	void GLWindow::resize(uint width, uint height)
	{
		// Prevent A Divide By Zero
		if (0 == height)
			height = 1;

		// Reset The Current Viewport
		::glViewport(0, 0, width, height);

		// Select the Projection Matrix
		::glMatrixMode(GL_PROJECTION);
		// Reset the Projection Matrix
		::glLoadIdentity();

		// Calculate the Aspect Ratio of the window
		::gluPerspective(60.0f, (GLfloat)width / (GLfloat)height, 0.01f, 1000.0f);

		// Select the Modelview Matrix
		::glMatrixMode(GL_MODELVIEW);
		// Reset the Modelview Matrix
		::glLoadIdentity();

		RenderWindow::resize(width, height);
	}

	void GLWindow::drawFullWindowQuad(const Gfx3D::Texture::Ptr& texture) const
	{
		auto textureType = multiSampling() ? GL_TEXTURE_2D_MULTISAMPLE : GL_TEXTURE_2D;
		::glBindTexture(textureType, texture->id());

		::glPushAttrib(GL_DEPTH_BUFFER_BIT | GL_ENABLE_BIT);
		::glDisable(GL_DEPTH_TEST);
		//::glCullFace(GL_FRONT);

		::glMatrixMode(GL_PROJECTION);
		::glPushMatrix();
		::glLoadIdentity();
		::gluOrtho2D(-1.0f, 1.0f, 1.0f, -1.0f);

		::glMatrixMode(GL_MODELVIEW);
		::glPushMatrix();
		::glLoadIdentity();

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

		/*
		// Texture coordinates are useless when 2D shaders are activated
		// but they are used when no post-processing effect is present
		const float texCoord[] =
			{
				0.0f, 0.0f,
				0.0f, 1.0f,
				1.0f, 1.0f,
				0.0f, 0.0f,
				1.0f, 1.0f,
				1.0f, 0.0f
			};
		::glEnableVertexAttribArray(Gfx3D::Vertex<>::vaTextureCoord);
		::glVertexAttribPointer(Gfx3D::Vertex<>::vaTextureCoord, 2, GL_FLOAT, 0, 0, texCoord);
		// Set vertex positions
		const float vertices[] =
			{
				-1.0f, 1.0f,
				-1.0f, -1.0f,
				1.0f, -1.0f,
				-1.0f, 1.0f,
				1.0f, -1.0f,
				1.0f, 1.0f
			};
		::glEnableVertexAttribArray(Gfx3D::Vertex<>::vaPosition);
		::glVertexAttribPointer(Gfx3D::Vertex<>::vaPosition, 2, GL_FLOAT, 0, 0, vertices);
		// Draw
		::glDrawArrays(GL_TRIANGLES, 0, 6);
		*/

		::glMatrixMode(GL_PROJECTION);
		::glPopMatrix();
		::glMatrixMode(GL_MODELVIEW);
		::glPopMatrix();

		::glPopAttrib();
		//::glCullFace(GL_BACK);

		::glBindTexture(textureType, 0);
	}

	void GLWindow::clear() const
	{
		::glClear(GL_COLOR_BUFFER_BIT);
	}

	void GLWindow::clear(const Color::RGB<>& color) const
	{
		::glClearColor(color.red, color.green, color.blue, 1.0f);
		::glClear(GL_COLOR_BUFFER_BIT);
	}

	void GLWindow::clearRect(int x, int y, uint width, uint height) const
	{
		// We offer coordinates top-left to bottom-right
		// but GL coordinates are bottom-left to top-right, so convert Y
		::glEnable(GL_SCISSOR_TEST);
		::glScissor(x, pHeight - height - y, width, height);
		::glClear(GL_COLOR_BUFFER_BIT);
		::glDisable(GL_SCISSOR_TEST);
	}

} // namespace UI
} // namespace Yuni
<|endoftext|>


<commit_before>#include "tinyfiledialogs/tinyfiledialogs.c"

bool Confirm(String title, String text, bool serious) {
  return tinyfd_messageBox(title.ToCString<char>(), text.ToCString<char>(), "yesno", serious ? "error" : "question", 1) == 1;
}

void Notify(String title, String text, bool serious) {
  tinyfd_messageBox(title.ToCString<char>(), text.ToCString<char>(), "ok", serious ? "error" : "info", 0);
}

int Proceed(String title, String text, bool serious) {
  return tinyfd_messageBox(title.ToCString<char>(), text.ToCString<char>(), "yesnocancel", serious ? "error" : "question", 0);
}

int RequestColor(String title, int color) {
  unsigned char c[3];
  c[0] = (color >> 16) & 0xFF;
  c[1] = (color >> 8) & 0xFF;
  c[2] = color & 0xFF;

  if ( tinyfd_colorChooser(title.ToCString<char>(), NULL, c, c) ) {
    color = (c[0] << 16) | (c[1] << 8) | c[2];
  }

  return color;
}

String RequestDir(String title, String dir) {
  const char* selDir = tinyfd_selectFolderDialog(title.ToCString<char>(), dir.ToCString<char>());
  if ( selDir != NULL ) {
    return selDir;
  } else {
    return "";
  }
}

String RequestFile(String title, String filters, bool save, String file) {
  const char* fname = NULL;
  if ( !save ) {
    fname = tinyfd_openFileDialog(title.ToCString<char>(), file.ToCString<char>(), 0, NULL, NULL, 0);
  } else {
    fname = tinyfd_saveFileDialog(title.ToCString<char>(), file.ToCString<char>(), 0, NULL, NULL);
  }

  if ( fname != NULL) {
    return fname;
  } else {
    return "";
  }
}

String RequestInput(String title, String text, String def, bool password) {
  const char* input = tinyfd_inputBox(title.ToCString<char>(), text.ToCString<char>(), password ? (const char*)NULL : def.ToCString<char>());
  if ( input != NULL ) {
    return input;
  } else {
    return "";
  }
}
<commit_msg>Fixes for Linux<commit_after>#ifdef _WIN32
#include "tinyfiledialogs/tinyfiledialogs.c"
#else
#include "tinyfiledialogs/tinyfiledialogs.h"
#endif

bool Confirm(String title, String text, bool serious) {
  return tinyfd_messageBox(title.ToCString<char>(), text.ToCString<char>(), "yesno", serious ? "error" : "question", 1) == 1;
}

void Notify(String title, String text, bool serious) {
  tinyfd_messageBox(title.ToCString<char>(), text.ToCString<char>(), "ok", serious ? "error" : "info", 0);
}

int Proceed(String title, String text, bool serious) {
  return tinyfd_messageBox(title.ToCString<char>(), text.ToCString<char>(), "yesnocancel", serious ? "error" : "question", 0);
}

int RequestColor(String title, int color) {
  unsigned char c[3];
  c[0] = (color >> 16) & 0xFF;
  c[1] = (color >> 8) & 0xFF;
  c[2] = color & 0xFF;

  if ( tinyfd_colorChooser(title.ToCString<char>(), NULL, c, c) ) {
    color = (c[0] << 16) | (c[1] << 8) | c[2];
  }

  return color;
}

String RequestDir(String title, String dir) {
  const char* selDir = tinyfd_selectFolderDialog(title.ToCString<char>(), dir.ToCString<char>());
  if ( selDir != NULL ) {
    return selDir;
  } else {
    return "";
  }
}

String RequestFile(String title, String filters, bool save, String file) {
  const char* fname = NULL;
  if ( !save ) {
    fname = tinyfd_openFileDialog(title.ToCString<char>(), file.ToCString<char>(), 0, NULL, NULL, 0);
  } else {
    fname = tinyfd_saveFileDialog(title.ToCString<char>(), file.ToCString<char>(), 0, NULL, NULL);
  }

  if ( fname != NULL) {
    return fname;
  } else {
    return "";
  }
}

String RequestInput(String title, String text, String def, bool password) {
  const char* input = tinyfd_inputBox(title.ToCString<char>(), text.ToCString<char>(), password ? (const char*)NULL : def.ToCString<char>());
  if ( input != NULL ) {
    return input;
  } else {
    return "";
  }
}
<|endoftext|>


<commit_before>#include "GBAApp.h"

#include "GameController.h"

#include <QFileOpenEvent>

using namespace QGBA;

GBAApp::GBAApp(int& argc, char* argv[])
	: QApplication(argc, argv)
{
    QApplication::setApplicationName(PROJECT_NAME);
    QApplication::setApplicationVersion(PROJECT_VERSION);

	if (parseArguments(&m_args, &m_opts, argc, argv, 0)) {
		m_window.setOptions(&m_opts);
		m_window.argumentsPassed(&m_args);
	} else {
		m_window.setOptions(&m_opts);
	}

    m_window.show();
}

GBAApp::~GBAApp() {
	freeArguments(&m_args);
	GBAConfigFreeOpts(&m_opts);
}

bool GBAApp::event(QEvent* event) {
	if (event->type() == QEvent::FileOpen) {
		m_window.controller()->loadGame(static_cast<QFileOpenEvent*>(event)->file());
		return true;
	}
	return QApplication::event(event);
}
<commit_msg>Qt: Initialize arguments and options<commit_after>#include "GBAApp.h"

#include "GameController.h"

#include <QFileOpenEvent>

using namespace QGBA;

GBAApp::GBAApp(int& argc, char* argv[])
	: QApplication(argc, argv)
	, m_args()
	, m_opts()
{
    QApplication::setApplicationName(PROJECT_NAME);
    QApplication::setApplicationVersion(PROJECT_VERSION);

	if (parseArguments(&m_args, &m_opts, argc, argv, 0)) {
		m_window.setOptions(&m_opts);
		m_window.argumentsPassed(&m_args);
	} else {
		m_window.setOptions(&m_opts);
	}

    m_window.show();
}

GBAApp::~GBAApp() {
	freeArguments(&m_args);
	GBAConfigFreeOpts(&m_opts);
}

bool GBAApp::event(QEvent* event) {
	if (event->type() == QEvent::FileOpen) {
		m_window.controller()->loadGame(static_cast<QFileOpenEvent*>(event)->file());
		return true;
	}
	return QApplication::event(event);
}
<|endoftext|>


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

#include "Agent.h"
#include "Basics/ConditionLocker.h"

#include <velocypack/Iterator.h>
#include <velocypack/velocypack-aliases.h>

#include <chrono>
#include <iostream>

using namespace arangodb::velocypack;

namespace arangodb {
namespace consensus {

Agent::Agent () : Thread ("Agent"), _last_commit_index(0) {}

Agent::Agent (config_t const& config) :
  Thread ("Agent"), _config(config), _last_commit_index(0) {
  _state.setEndPoint(_config.end_points[this->id()]);
  _constituent.configure(this);
  _confirmed.resize(size(),0);
}

id_t Agent::id() const { return _config.id;}

Agent::~Agent () {
  shutdown();
}

State const& Agent::state () const {
  return _state;
}

/// @brief Start all agency threads
bool Agent::start() {

  LOG_TOPIC(INFO, Logger::AGENCY) << "Starting agency comm worker.";
  Thread::start();

  return true;
}

term_t Agent::term () const {
  return _constituent.term();
}

inline size_t Agent::size() const {
  return _config.size();
}

priv_rpc_ret_t Agent::requestVote(term_t t, id_t id, index_t lastLogIndex,
                                  index_t lastLogTerm, query_t const& query) {

  if (query != nullptr) { // record new endpoints
    if (query->slice().hasKey("endpoints") &&
        query->slice().get("endpoints").isArray()) {
      size_t j = 0;
      for (auto const& i : VPackArrayIterator(query->slice().get("endpoints"))) {
        _config.end_points[j++] = i.copyString();
      }
    }
  }

  return priv_rpc_ret_t(  // vote
    _constituent.vote(t, id, lastLogIndex, lastLogTerm), this->term());
}

config_t const& Agent::config () const {
  return _config;
}

id_t Agent::leaderID () const {
  return _constituent.leaderID();
}

bool Agent::leading() const {
  return _constituent.leading();
}

void Agent::persist(term_t t, id_t i) {
//  _state.persist(t, i);
}

bool Agent::waitFor (index_t index, duration_t timeout) {

  if (size() == 1) // single host agency
    return true;

  CONDITION_LOCKER(guard, _rest_cv);
  auto start = std::chrono::system_clock::now();

  while (true) {

    _rest_cv.wait();

    // shutting down
    if (this->isStopping()) {
      return false;
    }
    // timeout?
    if (std::chrono::system_clock::now() - start > timeout) {
      return false;
    }
    if (_last_commit_index >= index) {
      return true;
    }
  }
  // We should never get here
  TRI_ASSERT(false);
}

void Agent::reportIn (id_t id, index_t index) {
  MUTEX_LOCKER(mutexLocker, _ioLock);

  if (index > _confirmed[id])      // progress this follower?
    _confirmed[id] = index;

  if(index > _last_commit_index) { // progress last commit?
    size_t n = 0;
    for (size_t i = 0; i < size(); ++i) {
      n += (_confirmed[i]>=index);
    }
    if (n>size()/2) { // catch up read database and commit index
      LOG_TOPIC(INFO, Logger::AGENCY) << "Critical mass for commiting " <<
        _last_commit_index+1 << " through " << index << " to read db";

      _read_db.apply(_state.slices(_last_commit_index+1, index));
      _last_commit_index = index;
    }
  }

  _rest_cv.broadcast();            // wake up REST handlers
}

bool Agent::recvAppendEntriesRPC (term_t term, id_t leaderId, index_t prevIndex,
  term_t prevTerm, index_t leaderCommitIndex, query_t const& queries) {
  //Update commit index

  if (queries->slice().type() != VPackValueType::Array) {
    LOG_TOPIC(WARN, Logger::AGENCY)
      << "Received malformed entries for appending. Discarting!";
    return false;
  }
  if (queries->slice().length()) {
    LOG_TOPIC(INFO, Logger::AGENCY) << "Appending "<< queries->slice().length()
              << " entries to state machine.";
  } else {
    // heart-beat
  }

  if (_last_commit_index < leaderCommitIndex) {
    LOG_TOPIC(INFO, Logger::AGENCY) <<  "Updating last commited index to " << leaderCommitIndex;
  }
  _last_commit_index = leaderCommitIndex;

  // Sanity
  if (this->term() > term) {                 // (§5.1)
    LOG_TOPIC(WARN, Logger::AGENCY) << "I have a higher term than RPC caller.";
    throw LOWER_TERM_APPEND_ENTRIES_RPC;
  }

  // Delete conflits and append (§5.3)
  _state.log (queries, term, leaderId, prevIndex, prevTerm);
  return true;

}

#include <iostream>
append_entries_t Agent::sendAppendEntriesRPC (id_t slave_id) {

  index_t last_confirmed = _confirmed[slave_id];
  std::vector<log_t> unconfirmed = _state.get(last_confirmed);

  // RPC path
  std::stringstream path;
  path << "/_api/agency_priv/appendEntries?term=" << term() << "&leaderId="
       << id() << "&prevLogIndex=" << unconfirmed[0].index << "&prevLogTerm="
       << unconfirmed[0].term << "&leaderCommit=" << _last_commit_index;

  // Headers
	std::unique_ptr<std::map<std::string, std::string>> headerFields =
	  std::make_unique<std::map<std::string, std::string> >();

  // Body
  Builder builder;
  index_t last = unconfirmed[0].index;
  builder.add(VPackValue(VPackValueType::Array));
  for (size_t i = 1; i < unconfirmed.size(); ++i) {
    builder.add (VPackValue(VPackValueType::Object));
    builder.add ("index", VPackValue(unconfirmed[i].index));
    builder.add ("query", VPackSlice(unconfirmed[i].entry->data()));
    builder.close();
    last = unconfirmed[i].index;
  }
  builder.close();

  // Send request
  if (unconfirmed.size() > 1) {
    LOG_TOPIC(INFO, Logger::AGENCY)
      << "Appending " << unconfirmed.size()-1 << " entries up to index " << last
      << " to follower " << slave_id;
  }

  arangodb::ClusterComm::instance()->asyncRequest
    ("1", 1, _config.end_points[slave_id],
     arangodb::GeneralRequest::RequestType::POST,
     path.str(), std::make_shared<std::string>(builder.toJson()), headerFields,
     std::make_shared<AgentCallback>(this, slave_id, last),
     0, true);

  return append_entries_t(this->term(), true);

}

bool Agent::load () {
  LOG_TOPIC(INFO, Logger::AGENCY) << "Loading persistent state.";
  if (!_state.loadCollections()) {
    LOG(FATAL) << "Failed to load persistent state on statup.";
  }

  LOG_TOPIC(INFO, Logger::AGENCY) << "Reassembling spearhead and read stores.";
  _read_db.apply(_state.slices());
  _spearhead.apply(_state.slices(_last_commit_index+1));

  LOG_TOPIC(INFO, Logger::AGENCY) << "Starting spearhead worker.";
  _spearhead.start(this);
  _read_db.start(this);

  LOG_TOPIC(INFO, Logger::AGENCY) << "Starting constituent personality.";
  _constituent.update(0,0);
  _constituent.start();

  return true;
}

write_ret_t Agent::write (query_t const& query)  {

  if (_constituent.leading()) {                    // Leading
    MUTEX_LOCKER(mutexLocker, _ioLock);
    std::vector<bool> applied = _spearhead.apply(query); // Apply to spearhead
    std::vector<index_t> indices =
      _state.log (query, applied, term(), id()); // Append to log w/ indicies
    for (size_t i = 0; i < applied.size(); ++i) {
      if (applied[i]) {
        _confirmed[id()] = indices[i];           // Confirm myself
      }
    }
    _cv.signal();                                // Wake up run
    return write_ret_t(true,id(),applied,indices); // Indices to wait for to rest
  } else {                                       // Leading else redirect
    return write_ret_t(false,_constituent.leaderID());
  }
}

read_ret_t Agent::read (query_t const& query) const {
  if (_constituent.leading()) {     // We are leading
    query_t result = std::make_shared<arangodb::velocypack::Builder>();
    std::vector<bool> success= (_config.size() == 1) ?
      _spearhead.read(query, result) : _read_db.read (query, result);
    return read_ret_t(true, _constituent.leaderID(), success, result);
  } else {                          // We redirect
    return read_ret_t(false, _constituent.leaderID());
  }
}

void Agent::run() {

  CONDITION_LOCKER(guard, _cv);

  while (!this->isStopping()) {
    if (leading())
      _cv.wait(250000);
    else
      _cv.wait();

    // Collect all unacknowledged
    for (id_t i = 0; i < size(); ++i) {
      if (i != id()) {
        sendAppendEntriesRPC(i);
      }
    }
  }

}

void Agent::beginShutdown() {
  Thread::beginShutdown();
  _constituent.beginShutdown();
  _spearhead.beginShutdown();
  _read_db.beginShutdown();
  CONDITION_LOCKER(guard, _cv);
  guard.broadcast();
}

bool Agent::lead () {
  rebuildDBs();
  _cv.signal();
  return true;
}

bool Agent::rebuildDBs() {
  MUTEX_LOCKER(mutexLocker, _ioLock);
  _spearhead.apply(_state.slices());
  _read_db.apply(_state.slices());
  return true;
}

log_t const& Agent::lastLog() const {
  return _state.lastLog();
}

Store const& Agent::spearhead () const {
  return _spearhead;
}

Store const& Agent::readDB () const {
  return _read_db;
}

}}
<commit_msg>Overwriting ttls<commit_after>////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2014-2016 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
///     http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Kaveh Vahedipour
////////////////////////////////////////////////////////////////////////////////

#include "Agent.h"
#include "Basics/ConditionLocker.h"

#include <velocypack/Iterator.h>
#include <velocypack/velocypack-aliases.h>

#include <chrono>
#include <iostream>

using namespace arangodb::velocypack;

namespace arangodb {
namespace consensus {

Agent::Agent () : Thread ("Agent"), _last_commit_index(0) {}

Agent::Agent (config_t const& config) :
  Thread ("Agent"), _config(config), _last_commit_index(0) {
  _state.setEndPoint(_config.end_points[this->id()]);
  _constituent.configure(this);
  _confirmed.resize(size(),0);
}

id_t Agent::id() const { return _config.id;}

Agent::~Agent () {
  shutdown();
}

State const& Agent::state () const {
  return _state;
}

/// @brief Start all agency threads
bool Agent::start() {

  LOG_TOPIC(INFO, Logger::AGENCY) << "Starting agency comm worker.";
  Thread::start();

  return true;
}

term_t Agent::term () const {
  return _constituent.term();
}

inline size_t Agent::size() const {
  return _config.size();
}

priv_rpc_ret_t Agent::requestVote(term_t t, id_t id, index_t lastLogIndex,
                                  index_t lastLogTerm, query_t const& query) {

  if (query != nullptr) { // record new endpoints
    if (query->slice().hasKey("endpoints") &&
        query->slice().get("endpoints").isArray()) {
      size_t j = 0;
      for (auto const& i : VPackArrayIterator(query->slice().get("endpoints"))) {
        _config.end_points[j++] = i.copyString();
      }
    }
  }

  return priv_rpc_ret_t(  // vote
    _constituent.vote(t, id, lastLogIndex, lastLogTerm), this->term());
}

config_t const& Agent::config () const {
  return _config;
}

id_t Agent::leaderID () const {
  return _constituent.leaderID();
}

bool Agent::leading() const {
  return _constituent.leading();
}

void Agent::persist(term_t t, id_t i) {
//  _state.persist(t, i);
}

bool Agent::waitFor (index_t index, duration_t timeout) {

  if (size() == 1) // single host agency
    return true;

  CONDITION_LOCKER(guard, _rest_cv);
  auto start = std::chrono::system_clock::now();

  while (true) {

    _rest_cv.wait();

    // shutting down
    if (this->isStopping()) {
      return false;
    }
    // timeout?
    if (std::chrono::system_clock::now() - start > timeout) {
      return false;
    }
    if (_last_commit_index >= index) {
      return true;
    }
  }
  // We should never get here
  TRI_ASSERT(false);
}

void Agent::reportIn (id_t id, index_t index) {
  MUTEX_LOCKER(mutexLocker, _ioLock);

  if (index > _confirmed[id])      // progress this follower?
    _confirmed[id] = index;

  if(index > _last_commit_index) { // progress last commit?
    size_t n = 0;
    for (size_t i = 0; i < size(); ++i) {
      n += (_confirmed[i]>=index);
    }
    if (n>size()/2) { // catch up read database and commit index
      LOG_TOPIC(INFO, Logger::AGENCY) << "Critical mass for commiting " <<
        _last_commit_index+1 << " through " << index << " to read db";

      _read_db.apply(_state.slices(_last_commit_index+1, index));
      _last_commit_index = index;
    }
  }

  _rest_cv.broadcast();            // wake up REST handlers
}

bool Agent::recvAppendEntriesRPC (term_t term, id_t leaderId, index_t prevIndex,
  term_t prevTerm, index_t leaderCommitIndex, query_t const& queries) {
  //Update commit index

  if (queries->slice().type() != VPackValueType::Array) {
    LOG_TOPIC(WARN, Logger::AGENCY)
      << "Received malformed entries for appending. Discarting!";
    return false;
  }
  if (queries->slice().length()) {
    LOG_TOPIC(INFO, Logger::AGENCY) << "Appending "<< queries->slice().length()
              << " entries to state machine.";
  } else {
    // heart-beat
  }

  if (_last_commit_index < leaderCommitIndex) {
    LOG_TOPIC(INFO, Logger::AGENCY) <<  "Updating last commited index to " << leaderCommitIndex;
  }
  _last_commit_index = leaderCommitIndex;

  // Sanity
  if (this->term() > term) {                 // (§5.1)
    LOG_TOPIC(WARN, Logger::AGENCY) << "I have a higher term than RPC caller.";
    throw LOWER_TERM_APPEND_ENTRIES_RPC;
  }

  // Delete conflits and append (§5.3)
  _state.log (queries, term, leaderId, prevIndex, prevTerm);
  return true;

}

#include <iostream>
append_entries_t Agent::sendAppendEntriesRPC (id_t slave_id) {

  index_t last_confirmed = _confirmed[slave_id];
  std::vector<log_t> unconfirmed = _state.get(last_confirmed);

  // RPC path
  std::stringstream path;
  path << "/_api/agency_priv/appendEntries?term=" << term() << "&leaderId="
       << id() << "&prevLogIndex=" << unconfirmed[0].index << "&prevLogTerm="
       << unconfirmed[0].term << "&leaderCommit=" << _last_commit_index;

  // Headers
	std::unique_ptr<std::map<std::string, std::string>> headerFields =
	  std::make_unique<std::map<std::string, std::string> >();

  // Body
  Builder builder;
  index_t last = unconfirmed[0].index;
  builder.add(VPackValue(VPackValueType::Array));
  for (size_t i = 1; i < unconfirmed.size(); ++i) {
    builder.add (VPackValue(VPackValueType::Object));
    builder.add ("index", VPackValue(unconfirmed[i].index));
    builder.add ("query", VPackSlice(unconfirmed[i].entry->data()));
    builder.close();
    last = unconfirmed[i].index;
  }
  builder.close();

  // Send request
  if (unconfirmed.size() > 1) {
    LOG_TOPIC(INFO, Logger::AGENCY)
      << "Appending " << unconfirmed.size()-1 << " entries up to index " << last
      << " to follower " << slave_id;
  }

  arangodb::ClusterComm::instance()->asyncRequest
    ("1", 1, _config.end_points[slave_id],
     arangodb::GeneralRequest::RequestType::POST,
     path.str(), std::make_shared<std::string>(builder.toJson()), headerFields,
     std::make_shared<AgentCallback>(this, slave_id, last),
     0, true);

  return append_entries_t(this->term(), true);

}

bool Agent::load () {
  LOG_TOPIC(INFO, Logger::AGENCY) << "Loading persistent state.";
  if (!_state.loadCollections()) {
    LOG_TOPIC(WARN, Logger::AGENCY) << "Failed to load persistent state on statup.";
  }

  LOG_TOPIC(INFO, Logger::AGENCY) << "Reassembling spearhead and read stores.";
  _read_db.apply(_state.slices());
  _spearhead.apply(_state.slices(_last_commit_index+1));

  LOG_TOPIC(INFO, Logger::AGENCY) << "Starting spearhead worker.";
  _spearhead.start(this);
  _read_db.start(this);

  LOG_TOPIC(INFO, Logger::AGENCY) << "Starting constituent personality.";
  _constituent.update(0,0);
  _constituent.start();

  return true;
}

write_ret_t Agent::write (query_t const& query)  {

  if (_constituent.leading()) {                    // Leading
    MUTEX_LOCKER(mutexLocker, _ioLock);
    std::vector<bool> applied = _spearhead.apply(query); // Apply to spearhead
    std::vector<index_t> indices =
      _state.log (query, applied, term(), id()); // Append to log w/ indicies
    for (size_t i = 0; i < applied.size(); ++i) {
      if (applied[i]) {
        _confirmed[id()] = indices[i];           // Confirm myself
      }
    }
    _cv.signal();                                // Wake up run
    return write_ret_t(true,id(),applied,indices); // Indices to wait for to rest
  } else {                                       // Leading else redirect
    return write_ret_t(false,_constituent.leaderID());
  }
}

read_ret_t Agent::read (query_t const& query) const {
  if (_constituent.leading()) {     // We are leading
    query_t result = std::make_shared<arangodb::velocypack::Builder>();
    std::vector<bool> success= (_config.size() == 1) ?
      _spearhead.read(query, result) : _read_db.read (query, result);
    return read_ret_t(true, _constituent.leaderID(), success, result);
  } else {                          // We redirect
    return read_ret_t(false, _constituent.leaderID());
  }
}

void Agent::run() {

  CONDITION_LOCKER(guard, _cv);

  while (!this->isStopping()) {
    if (leading())
      _cv.wait(250000);
    else
      _cv.wait();

    // Collect all unacknowledged
    for (id_t i = 0; i < size(); ++i) {
      if (i != id()) {
        sendAppendEntriesRPC(i);
      }
    }
  }

}

void Agent::beginShutdown() {
  Thread::beginShutdown();
  _constituent.beginShutdown();
  _spearhead.beginShutdown();
  _read_db.beginShutdown();
  CONDITION_LOCKER(guard, _cv);
  guard.broadcast();
}

bool Agent::lead () {
  rebuildDBs();
  _cv.signal();
  return true;
}

bool Agent::rebuildDBs() {
  MUTEX_LOCKER(mutexLocker, _ioLock);
  _spearhead.apply(_state.slices());
  _read_db.apply(_state.slices());
  return true;
}

log_t const& Agent::lastLog() const {
  return _state.lastLog();
}

Store const& Agent::spearhead () const {
  return _spearhead;
}

Store const& Agent::readDB () const {
  return _read_db;
}

}}
<|endoftext|>


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

Program:   Medical Imaging & Interaction Toolkit
Language:  C++
Date:      $Date: 2010-03-15 11:12:36 +0100 (Mo, 15 Mrz 2010) $
Version:   $Revision: 21745 $

Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.

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

=========================================================================*/

#include "mitkTestingMacros.h"
#include "mitkPlanarSubdivisionPolygon.h"
#include "mitkPlaneGeometry.h"

class mitkPlanarSubdivisionPolygonTestClass
{

public:

static void TestPlanarSubdivisionPolygonPlacement( mitk::PlanarSubdivisionPolygon::Pointer planarSubdivisionPolygon )
{
  // Test for correct minimum number of control points in cross-mode
  MITK_TEST_CONDITION( planarSubdivisionPolygon->GetMinimumNumberOfControlPoints() == 3, "Minimum number of control points" );

  // Test for correct maximum number of control points in cross-mode
  MITK_TEST_CONDITION( planarSubdivisionPolygon->GetMaximumNumberOfControlPoints() == 1000, "Maximum number of control points" );

  // Test for correct rounds of subdivisionPoints
  MITK_TEST_CONDITION( planarSubdivisionPolygon->GetSubdivisionRounds() == 5, "Subdivision point generation depth" );

  // Test for correct tension parameter
  MITK_TEST_CONDITION( planarSubdivisionPolygon->GetTensionParameter() == 0.0625, "Tension parameter" );

  // Initial placement of planarSubdivisionPolygon
  mitk::Point2D p0;
  p0[0] = 25.0; p0[1] = 25.0;
  planarSubdivisionPolygon->PlaceFigure( p0 );

  // Add second control point
  mitk::Point2D p1;
  p1[0] = 75.0; p1[1] = 25.0;
  planarSubdivisionPolygon->SetControlPoint(1, p1 );

  // Add third control point
  mitk::Point2D p2;
  p2[0] = 75.0; p2[1] = 75.0;
  planarSubdivisionPolygon->AddControlPoint( p2 );

  // Add fourth control point
  mitk::Point2D p3;
  p3[0] = 25.0; p3[1] = 75.0;
  planarSubdivisionPolygon->AddControlPoint( p3 );

  // Test for number of control points
  MITK_TEST_CONDITION( planarSubdivisionPolygon->GetNumberOfControlPoints() == 4, "Number of control points after placement" );

  // Test if PlanarFigure is closed
  MITK_TEST_CONDITION( planarSubdivisionPolygon->IsClosed(), "Test if property 'closed' is set by default" );

  // Test for number of polylines
  const mitk::PlanarFigure::PolyLineType polyLine0 = planarSubdivisionPolygon->GetPolyLine( 0 );
  mitk::PlanarFigure::PolyLineType::const_iterator iter = polyLine0.begin();
  MITK_TEST_CONDITION( planarSubdivisionPolygon->GetPolyLinesSize() == 1, "Number of polylines after placement" );

  // Test if subdivision point count is correct
  MITK_TEST_CONDITION( polyLine0.size() == 128, "correct number of subdivision points for this depth level" );

  // Test if control points are in correct order between subdivision points
  bool correctPoint = true;
  iter = polyLine0.begin();
  advance(iter, 31);
  if( iter->Point != p0 ){ correctPoint = false; }
  advance(iter, 32);
  if( iter->Point != p1 ){ correctPoint = false; }
  advance(iter, 32);
  if( iter->Point != p2 ){ correctPoint = false; }
  advance(iter, 32);
  if( iter->Point != p3 ){ correctPoint = false; }
  MITK_TEST_CONDITION( correctPoint, "Test if control points are in correct order in polyline" );

  // Test if a picked point has the correct coordinates
  correctPoint = true;

  mitk::Point2D testPoint;
  testPoint[0] = 50.000;
  testPoint[1] = 18.750;
  iter = polyLine0.begin();
  advance(iter, 47);
  if( (iter->Point[0] - testPoint[0]) + (iter->Point[1] - testPoint[1]) > mitk::eps ){ correctPoint = false; }

  testPoint[0] = 20.96007347106933593750;
  testPoint[1] = 58.74700927734375000000;
  iter = polyLine0.begin();
  advance(iter, 10);
  if( (iter->Point[0] - testPoint[0]) + (iter->Point[1] - testPoint[1]) > mitk::eps ){ correctPoint = false; }

  testPoint[0] = 76.96900177001953125000;
  testPoint[1] = 30.05101013183593750000;
  iter = polyLine0.begin();
  advance(iter, 67);
  if( (iter->Point[0] - testPoint[0]) + (iter->Point[1] - testPoint[1]) > mitk::eps ){ correctPoint = false; }

  MITK_TEST_CONDITION( correctPoint, "Test if subdivision points are calculated correctly" )

  // Test for number of measurement features
  /*
  Does not work yet

  planarSubdivisionPolygon->EvaluateFeatures();
  MITK_TEST_CONDITION( planarSubdivisionPolygon->GetNumberOfFeatures() == 2, "Number of measurement features" );

  // Test for correct feature evaluation
  double length0 = 4 * 50.0; // circumference
  MITK_TEST_CONDITION( fabs( planarSubdivisionPolygon->GetQuantity( 0 ) - length0) < mitk::eps, "Size of longest diameter" );

  double length1 = 50.0 * 50.0 ; // area
  MITK_TEST_CONDITION( fabs( planarSubdivisionPolygon->GetQuantity( 1 ) - length1) < mitk::eps, "Size of short axis diameter" );
  */
}

static void TestPlanarSubdivisionPolygonEditing( mitk::PlanarSubdivisionPolygon::Pointer planarSubdivisionPolygon )
{
  int initialNumberOfControlPoints = planarSubdivisionPolygon->GetNumberOfControlPoints();

  mitk::Point2D pnt;
  pnt[0] = 75.0; pnt[1] = 25.0;
  planarSubdivisionPolygon->AddControlPoint( pnt);

  MITK_TEST_CONDITION( planarSubdivisionPolygon->GetNumberOfControlPoints() == initialNumberOfControlPoints+1, "A new control-point shall be added" );
  MITK_TEST_CONDITION( planarSubdivisionPolygon->GetControlPoint( planarSubdivisionPolygon->GetNumberOfControlPoints()-1 ) == pnt, "Control-point shall be added at the end." );

  planarSubdivisionPolygon->RemoveControlPoint( 3 );
  MITK_TEST_CONDITION( planarSubdivisionPolygon->GetNumberOfControlPoints() == initialNumberOfControlPoints, "A control-point has been removed" );
  MITK_TEST_CONDITION( planarSubdivisionPolygon->GetControlPoint( 3 ) == pnt, "It shall be possible to remove any control-point." );

  planarSubdivisionPolygon->RemoveControlPoint( 0 );
  planarSubdivisionPolygon->RemoveControlPoint( 0 );
  planarSubdivisionPolygon->RemoveControlPoint( 0 );
  MITK_TEST_CONDITION( planarSubdivisionPolygon->GetNumberOfControlPoints() == 3, "Control-points cannot be removed if only three points remain." );

  mitk::Point2D pnt1;
  pnt1[0] = 33.0; pnt1[1] = 33.0;
  planarSubdivisionPolygon->AddControlPoint( pnt1, 0 );
  MITK_TEST_CONDITION( planarSubdivisionPolygon->GetNumberOfControlPoints() == 4, "A control-point has been added" );
  MITK_TEST_CONDITION( planarSubdivisionPolygon->GetControlPoint( 0 ) == pnt1, "It shall be possible to insert a control-point at any position." );

}

};
/**
 * mitkplanarSubdivisionPolygonTest tests the methods and behavior of mitk::planarSubdivisionPolygon with sub-tests:
 *
 * 1. Instantiation and basic tests, including feature evaluation
 *
 */
int mitkPlanarSubdivisionPolygonTest(int /* argc */, char* /*argv*/[])
{
  // always start with this!
  MITK_TEST_BEGIN("planarSubdivisionPolygon")

  // create PlaneGeometry on which to place the planarSubdivisionPolygon
  mitk::PlaneGeometry::Pointer planeGeometry = mitk::PlaneGeometry::New();
  planeGeometry->InitializeStandardPlane( 100.0, 100.0 );

  // **************************************************************************
  // 1. Instantiation and basic tests, including feature evaluation
  mitk::PlanarSubdivisionPolygon::Pointer planarSubdivisionPolygon = mitk::PlanarSubdivisionPolygon::New();
  planarSubdivisionPolygon->SetGeometry2D( planeGeometry );

  // first test: did this work?
  MITK_TEST_CONDITION_REQUIRED( planarSubdivisionPolygon.IsNotNull(), "Testing instantiation" );

  // Test placement of planarSubdivisionPolygon by control points
  mitkPlanarSubdivisionPolygonTestClass::TestPlanarSubdivisionPolygonPlacement( planarSubdivisionPolygon );

  mitkPlanarSubdivisionPolygonTestClass::TestPlanarSubdivisionPolygonEditing( planarSubdivisionPolygon );

  // always end with this!
  MITK_TEST_END();
}
<commit_msg>added property initiallyplaced and set maximum numbers to 1000<commit_after>/*=========================================================================

Program:   Medical Imaging & Interaction Toolkit
Language:  C++
Date:      $Date: 2010-03-15 11:12:36 +0100 (Mo, 15 Mrz 2010) $
Version:   $Revision: 21745 $

Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.

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

=========================================================================*/

#include "mitkTestingMacros.h"
#include "mitkPlanarSubdivisionPolygon.h"
#include "mitkPlaneGeometry.h"
#include "mitkProperties.h"

class mitkPlanarSubdivisionPolygonTestClass
{

public:

static void TestPlanarSubdivisionPolygonPlacement( mitk::PlanarSubdivisionPolygon::Pointer planarSubdivisionPolygon )
{
  // Test for correct minimum number of control points in cross-mode
  MITK_TEST_CONDITION( planarSubdivisionPolygon->GetMinimumNumberOfControlPoints() == 3, "Minimum number of control points" );

  // Test for correct maximum number of control points in cross-mode
  MITK_TEST_CONDITION( planarSubdivisionPolygon->GetMaximumNumberOfControlPoints() == 1000, "Maximum number of control points" );

  // Test for correct rounds of subdivisionPoints
  MITK_TEST_CONDITION( planarSubdivisionPolygon->GetSubdivisionRounds() == 5, "Subdivision point generation depth" );

  // Test for correct tension parameter
  MITK_TEST_CONDITION( planarSubdivisionPolygon->GetTensionParameter() == 0.0625, "Tension parameter" );

  planarSubdivisionPolygon->SetProperty( "initiallyplaced", mitk::BoolProperty::New( true ) );

  // Initial placement of planarSubdivisionPolygon
  mitk::Point2D p0;
  p0[0] = 25.0; p0[1] = 25.0;
  planarSubdivisionPolygon->PlaceFigure( p0 );

  // Add second control point
  mitk::Point2D p1;
  p1[0] = 75.0; p1[1] = 25.0;
  planarSubdivisionPolygon->SetControlPoint(1, p1 );

  // Add third control point
  mitk::Point2D p2;
  p2[0] = 75.0; p2[1] = 75.0;
  planarSubdivisionPolygon->AddControlPoint( p2 );

  // Add fourth control point
  mitk::Point2D p3;
  p3[0] = 25.0; p3[1] = 75.0;
  planarSubdivisionPolygon->AddControlPoint( p3 );

  // Test for number of control points
  MITK_TEST_CONDITION( planarSubdivisionPolygon->GetNumberOfControlPoints() == 4, "Number of control points after placement" );

  // Test if PlanarFigure is closed
  MITK_TEST_CONDITION( planarSubdivisionPolygon->IsClosed(), "Test if property 'closed' is set by default" );

  // Test for number of polylines
  const mitk::PlanarFigure::PolyLineType polyLine0 = planarSubdivisionPolygon->GetPolyLine( 0 );
  mitk::PlanarFigure::PolyLineType::const_iterator iter = polyLine0.begin();
  MITK_TEST_CONDITION( planarSubdivisionPolygon->GetPolyLinesSize() == 1, "Number of polylines after placement" );

  // Test if subdivision point count is correct
  MITK_TEST_CONDITION( polyLine0.size() == 128, "correct number of subdivision points for this depth level" );

  // Test if control points are in correct order between subdivision points
  bool correctPoint = true;
  iter = polyLine0.begin();
  advance(iter, 31);
  if( iter->Point != p0 ){ correctPoint = false; }
  advance(iter, 32);
  if( iter->Point != p1 ){ correctPoint = false; }
  advance(iter, 32);
  if( iter->Point != p2 ){ correctPoint = false; }
  advance(iter, 32);
  if( iter->Point != p3 ){ correctPoint = false; }
  MITK_TEST_CONDITION( correctPoint, "Test if control points are in correct order in polyline" );

  // Test if a picked point has the correct coordinates
  correctPoint = true;

  mitk::Point2D testPoint;
  testPoint[0] = 50.000;
  testPoint[1] = 18.750;
  iter = polyLine0.begin();
  advance(iter, 47);
  if( (iter->Point[0] - testPoint[0]) + (iter->Point[1] - testPoint[1]) > mitk::eps ){ correctPoint = false; }

  testPoint[0] = 20.96007347106933593750;
  testPoint[1] = 58.74700927734375000000;
  iter = polyLine0.begin();
  advance(iter, 10);
  if( (iter->Point[0] - testPoint[0]) + (iter->Point[1] - testPoint[1]) > mitk::eps ){ correctPoint = false; }

  testPoint[0] = 76.96900177001953125000;
  testPoint[1] = 30.05101013183593750000;
  iter = polyLine0.begin();
  advance(iter, 67);
  if( (iter->Point[0] - testPoint[0]) + (iter->Point[1] - testPoint[1]) > mitk::eps ){ correctPoint = false; }

  MITK_TEST_CONDITION( correctPoint, "Test if subdivision points are calculated correctly" )

  // Test for number of measurement features
  /*
  Does not work yet

  planarSubdivisionPolygon->EvaluateFeatures();
  MITK_TEST_CONDITION( planarSubdivisionPolygon->GetNumberOfFeatures() == 2, "Number of measurement features" );

  // Test for correct feature evaluation
  double length0 = 4 * 50.0; // circumference
  MITK_TEST_CONDITION( fabs( planarSubdivisionPolygon->GetQuantity( 0 ) - length0) < mitk::eps, "Size of longest diameter" );

  double length1 = 50.0 * 50.0 ; // area
  MITK_TEST_CONDITION( fabs( planarSubdivisionPolygon->GetQuantity( 1 ) - length1) < mitk::eps, "Size of short axis diameter" );
  */
}

static void TestPlanarSubdivisionPolygonEditing( mitk::PlanarSubdivisionPolygon::Pointer planarSubdivisionPolygon )
{
  int initialNumberOfControlPoints = planarSubdivisionPolygon->GetNumberOfControlPoints();

  mitk::Point2D pnt;
  pnt[0] = 75.0; pnt[1] = 25.0;
  planarSubdivisionPolygon->AddControlPoint( pnt);

  MITK_TEST_CONDITION( planarSubdivisionPolygon->GetNumberOfControlPoints() == initialNumberOfControlPoints+1, "A new control-point shall be added" );
  MITK_TEST_CONDITION( planarSubdivisionPolygon->GetControlPoint( planarSubdivisionPolygon->GetNumberOfControlPoints()-1 ) == pnt, "Control-point shall be added at the end." );

  planarSubdivisionPolygon->RemoveControlPoint( 3 );
  MITK_TEST_CONDITION( planarSubdivisionPolygon->GetNumberOfControlPoints() == initialNumberOfControlPoints, "A control-point has been removed" );
  MITK_TEST_CONDITION( planarSubdivisionPolygon->GetControlPoint( 3 ) == pnt, "It shall be possible to remove any control-point." );

  planarSubdivisionPolygon->RemoveControlPoint( 0 );
  planarSubdivisionPolygon->RemoveControlPoint( 0 );
  planarSubdivisionPolygon->RemoveControlPoint( 0 );
  MITK_TEST_CONDITION( planarSubdivisionPolygon->GetNumberOfControlPoints() == 3, "Control-points cannot be removed if only three points remain." );

  mitk::Point2D pnt1;
  pnt1[0] = 33.0; pnt1[1] = 33.0;
  planarSubdivisionPolygon->AddControlPoint( pnt1, 0 );
  MITK_TEST_CONDITION( planarSubdivisionPolygon->GetNumberOfControlPoints() == 4, "A control-point has been added" );
  MITK_TEST_CONDITION( planarSubdivisionPolygon->GetControlPoint( 0 ) == pnt1, "It shall be possible to insert a control-point at any position." );

}

};
/**
 * mitkplanarSubdivisionPolygonTest tests the methods and behavior of mitk::planarSubdivisionPolygon with sub-tests:
 *
 * 1. Instantiation and basic tests, including feature evaluation
 *
 */
int mitkPlanarSubdivisionPolygonTest(int /* argc */, char* /*argv*/[])
{
  // always start with this!
  MITK_TEST_BEGIN("planarSubdivisionPolygon")

  // create PlaneGeometry on which to place the planarSubdivisionPolygon
  mitk::PlaneGeometry::Pointer planeGeometry = mitk::PlaneGeometry::New();
  planeGeometry->InitializeStandardPlane( 100.0, 100.0 );

  // **************************************************************************
  // 1. Instantiation and basic tests, including feature evaluation
  mitk::PlanarSubdivisionPolygon::Pointer planarSubdivisionPolygon = mitk::PlanarSubdivisionPolygon::New();
  planarSubdivisionPolygon->SetGeometry2D( planeGeometry );

  // first test: did this work?
  MITK_TEST_CONDITION_REQUIRED( planarSubdivisionPolygon.IsNotNull(), "Testing instantiation" );

  // Test placement of planarSubdivisionPolygon by control points
  mitkPlanarSubdivisionPolygonTestClass::TestPlanarSubdivisionPolygonPlacement( planarSubdivisionPolygon );

  mitkPlanarSubdivisionPolygonTestClass::TestPlanarSubdivisionPolygonEditing( planarSubdivisionPolygon );

  // always end with this!
  MITK_TEST_END();
}
<|endoftext|>


<commit_before>/*!
  \copyright (c) RDO-Team, 2011
  \file      main.cpp
  \authors     (rdo@rk9.bmstu.ru)
  \authors     (impus@hotbox.ru)
  \date      2.10.2011
  \brief
  \indent    4T
*/

// ---------------------------------------------------------------------------- PCH
// ----------------------------------------------------------------------- INCLUDES
#define BOOST_TEST_MODULE RDOSequencesTest
#include <iostream>
#include <fstream>
#include <vector>
#include <math.h>
#include <boost/test/included/unit_test.hpp>
#include <boost/bind.hpp>
#include <boost/function.hpp>
// ----------------------------------------------------------------------- SYNOPSIS
#include "utils/rdofile.h"
#include "utils/platform.h"
#include "simulator/runtime/rdo_random_distribution.h"
// --------------------------------------------------------------------------------

#ifdef COMPILER_VISUAL_STUDIO
	#define  __SCANF  sscanf_s
#else  // not COMPILER_VISUAL_STUDIO
	#define  __SCANF  sscanf
#endif // COMPILER_VISUAL_STUDIO

typedef std::vector<double> Container;
typedef std::vector<ruint>  ContainerInt;
typedef const tstring contstr;

const long int g_seed                 = 123456789;                  //!<
contstr        g_filePath             = _T("../../test/sequences/");//!<
contstr        g_fileNormalName       = _T("data_normal.txt");      //!<
contstr        g_fileUniformName      = _T("data_uniform.txt");     //!<
contstr        g_fileExponentialName  = _T("data_exponential.txt"); //!<
contstr        g_fileTriangularName   = _T("data_trinagular.txt");  //!<

const ruint    g_count                = 100000;                     //!<
const double   g_main                 = 10.0;                       //!<
const double   g_var                  = 1.0;                        //!<
const double   g_from                 = 1.0;                        //!<
const double   g_to                   = 7.0;                        //!<
const double   g_top                  = 5.0;                        //!<
const ruint    g_precision            = 20;                         //!<

const ruint    g_countOfExamples      = 2000;                       //!<
const ruint    g_countOfR             = 39;                         //!<
const double   pi                     = 3.141592653;                //!<
const double   g_ksiEtalon            = 50.9985;                    //!<  . 95%  ,

// --------------------------------------------------------------------------------
// -------Templates
// --------------------------------------------------------------------------------
template <class T, class F, class contstr>
void onGenerateData(F binder, contstr g_fileName)
{
	if (rdo::File::exist(g_fileName.c_str()))
		return;

	T sequence(g_seed);
	Container test;
	test.reserve(g_count);

	for (ruint i = 0; i < g_count; ++i)
	{
		test.push_back(binder.operator()(&sequence));
	}

	std::ofstream stream(g_fileName.c_str());
	stream.precision(g_precision);
	STL_FOR_ALL(test, it)
	{
		stream << *it << std::endl;
	}
}

template <class T, class F, class contstr>
void onCheckData(F binder, contstr g_fileName)
{
	std::ifstream stream(g_fileName.c_str());
	BOOST_CHECK(stream.good());

	Container test;
	test.reserve(g_count);
	T sequence(g_seed);
	for (ruint i = 0; i < g_count; ++i)
	{
		test.push_back(binder.operator()(&sequence));
	}

	stream.precision(g_precision);
	STL_FOR_ALL(test, it)
	{
		BOOST_CHECK(stream.good());
		tstring str;
		stream >> str;

		double val;
		BOOST_CHECK(__SCANF(str.c_str(), _T("%lf"), &val) == 1);
		BOOST_CHECK(val == *it);
				if (val != *it)
		{
			std::cout.precision(g_precision);
			std::cout << *it << std::endl;
			std::cout << val << std::endl;
		}
	}
}

template <class T,class F>
double  area (F binder, double n, double m)
{
	double k = 1;
	double S1 = 1;
	double S2 = 0;
	ruint t = 10;
	while (fabs(S1-S2)/S1 > 0.01)
	{
		S2 = S1;
		S1 = 0;
		for (ruint g = 0; g < t + 1; ++g)
		{
			if ((g == 0) || (g == t - 1))
				k = 0.5;
			S1 += k*(binder.operator()(n + g*(m-n)/t));
			k = 1;
		}
		S1 *= (m-n)/t;
		t  *= 10;
	}
	return S1;
}

template <class T, class G, class F, class S>
void onCheckKsi(F binder, S binderSeq, double left, double right)
{
	Container x;
	x.reserve(g_countOfR + 1);
	double elem = (right-left)/(g_countOfR*1.0);	//

	for (ruint i = 0; i < g_countOfR + 1; ++i)
	{
		x.push_back(left + elem*i);
	}

	Container vb;									//
	vb.reserve(g_countOfExamples);

	G sequence(g_seed);								//
	for (ruint i = 0; i < g_countOfExamples; ++i)
	{
		vb.push_back(binderSeq.operator()(&sequence));
	}

	Container f_vb;									//
	f_vb.reserve(g_countOfR);

	for(ruint i = 0; i < g_countOfR; ++i)			//
	{
		ruint freq = 0;
		for(ruint k = 0; k < g_countOfExamples; ++k)
		{
			if((vb[k] > x[i]) & (vb[k] <= x[i+1]))
			{
				++freq;
			}
		}
		f_vb.push_back(freq);
	}

	Container F_etalon;
	F_etalon.reserve(g_countOfR);

	for (ruint i = 0; i < g_countOfR; ++i)
	{
		F_etalon.push_back(area<T>(binder, x[i], x[i+1]));
	}

	double ksi = 0;
	for(ruint i = 0; i < g_countOfR; ++i)
	{
		double ksiTemp = F_etalon[i]*g_countOfExamples;
		ksi += (f_vb[i] - ksiTemp)*(f_vb[i] - ksiTemp)/ksiTemp;
	}
	BOOST_CHECK(ksi <= g_ksiEtalon);
			if (ksi >  g_ksiEtalon)
	{
		std::cout << ksi << std::endl;
	}
}
// --------------------------------------------------------------------------------

class SequenceNormal
{
public:
	SequenceNormal(double main, double var)
		: m_main(main)
		, m_var (var )
	{}

	double get(double x) const
	{
		return 1/(sqrt(2*pi)*m_var*exp((x - m_main)*(x - m_main)/(2*m_var*m_var)));
	}

private:
	double m_main;
	double m_var;
};

class SequenceExponential
{
public:
	SequenceExponential(double main)
		: m_main(main)
	{}

	double get(double x) const
	{
		return 1/(m_main*exp(x/m_main));
	}

private:
	double m_main;
};

class SequenceUniform
{
public:
	SequenceUniform(double min, double max)
		: m_min(min)
		, m_max(max)
	{}

	double get(double x) const
	{
		UNUSED(x);
		return 1/(m_max-m_min);
	}

private:
	double m_min;
	double m_max;
};

class SequenceTriangular
{
public:
	SequenceTriangular(double min, double top, double max)
		: m_min(min-top)
		, m_top(top)
		, m_max(max-top)
	{}

	double get(double x) const
	{
		x -= m_top;
		double temp;
		if (x < 0)
		{
			temp = -2*x/((m_max - m_min)*m_min) + 2/(m_max - m_min);
		}
		else
		{
			temp = -2*x/((m_max - m_min)*m_max) + 2/(m_max - m_min);
		}
		return temp;
	}

private:
	double m_min;
	double m_top;
	double m_max;
};

BOOST_AUTO_TEST_SUITE(RDOSequencesTest)

// --------------------------------------------------------------------------------
// -------Normal sequence
// --------------------------------------------------------------------------------
BOOST_AUTO_TEST_CASE(RDONormalTestCreate)
{
	onGenerateData<rdo::runtime::RandGeneratorNormal>
		(boost::bind(&rdo::runtime::RandGeneratorNormal::next, _1, g_main, g_var), g_filePath + g_fileNormalName);
}

BOOST_AUTO_TEST_CASE(RDONormalTestCheck)
{
	onCheckData<rdo::runtime::RandGeneratorNormal>
		(boost::bind(&rdo::runtime::RandGeneratorNormal::next, _1, g_main, g_var), g_filePath + g_fileNormalName);

	SequenceNormal normal(g_main, g_var);
	onCheckKsi<SequenceNormal, rdo::runtime::RandGeneratorNormal>
		(boost::bind(&SequenceNormal::get, normal, _1),
		boost::bind(&rdo::runtime::RandGeneratorNormal::next, _1, g_main, g_var),
		g_main-4*g_var,
		g_main+4*g_var);
}
// --------------------------------------------------------------------------------

// --------------------------------------------------------------------------------
// -------Uniform sequence
// --------------------------------------------------------------------------------
BOOST_AUTO_TEST_CASE(RDOUniformTestCreate)
{
	onGenerateData<rdo::runtime::RandGeneratorUniform>
		(boost::bind(&rdo::runtime::RandGeneratorUniform::next, _1, g_from, g_to), g_filePath + g_fileUniformName);
}

BOOST_AUTO_TEST_CASE(RDOUniformTestCheck)
{
	onCheckData<rdo::runtime::RandGeneratorUniform>
		(boost::bind(&rdo::runtime::RandGeneratorUniform::next, _1, g_from, g_to), g_filePath + g_fileUniformName);

	SequenceUniform uniform(g_from, g_to);
	onCheckKsi<SequenceUniform, rdo::runtime::RandGeneratorUniform>
		(boost::bind(&SequenceUniform::get, uniform, _1),
		boost::bind(&rdo::runtime::RandGeneratorUniform::next, _1, g_from, g_to),
		g_from,
		g_to);
}
// --------------------------------------------------------------------------------

// --------------------------------------------------------------------------------
// -------Exponential sequence
// --------------------------------------------------------------------------------
BOOST_AUTO_TEST_CASE(RDOExponentialTestCreate)
{
	onGenerateData<rdo::runtime::RandGeneratorExponential>
		(boost::bind(&rdo::runtime::RandGeneratorExponential::next, _1, g_main), g_filePath + g_fileExponentialName);
}

BOOST_AUTO_TEST_CASE(RDOExponentialTestCheck)
{
	onCheckData<rdo::runtime::RandGeneratorExponential>
		(boost::bind(&rdo::runtime::RandGeneratorExponential::next, _1, g_main), g_filePath + g_fileExponentialName);

	SequenceExponential exponential(g_main);
	onCheckKsi<SequenceExponential, rdo::runtime::RandGeneratorExponential>
		(boost::bind(&SequenceExponential::get, exponential, _1),
		boost::bind(&rdo::runtime::RandGeneratorExponential::next, _1, g_main),
		0,
		7*g_main);
}
// --------------------------------------------------------------------------------

// --------------------------------------------------------------------------------
// -------Triangular sequence
// --------------------------------------------------------------------------------
BOOST_AUTO_TEST_CASE(RDOTriangularTestCreate)
{
	onGenerateData<rdo::runtime::RandGeneratorTriangular>
		(boost::bind(&rdo::runtime::RandGeneratorTriangular::next, _1, g_from, g_top, g_to), g_filePath + g_fileTriangularName);
}

BOOST_AUTO_TEST_CASE(RDOTriangularTestCheck)
{
	onCheckData<rdo::runtime::RandGeneratorTriangular>
		(boost::bind(&rdo::runtime::RandGeneratorTriangular::next, _1, g_from, g_top, g_to), g_filePath + g_fileTriangularName);

	SequenceTriangular triangular(g_from, g_top, g_to);
	onCheckKsi<SequenceTriangular, rdo::runtime::RandGeneratorTriangular>
		(boost::bind(&SequenceTriangular::get, triangular, _1),
		boost::bind(&rdo::runtime::RandGeneratorTriangular::next, _1, g_from, g_top, g_to),
		g_from,
		g_to);
}
// --------------------------------------------------------------------------------

BOOST_AUTO_TEST_SUITE_END()
<commit_msg> - исправлена точность сравнения под arm<commit_after>/*!
  \copyright (c) RDO-Team, 2011
  \file      main.cpp
  \authors     (rdo@rk9.bmstu.ru)
  \authors     (impus@hotbox.ru)
  \date      2.10.2011
  \brief
  \indent    4T
*/

// ---------------------------------------------------------------------------- PCH
// ----------------------------------------------------------------------- INCLUDES
#define BOOST_TEST_MODULE RDOSequencesTest
#include <iostream>
#include <fstream>
#include <vector>
#include <math.h>
#include <boost/test/included/unit_test.hpp>
#include <boost/bind.hpp>
#include <boost/function.hpp>
// ----------------------------------------------------------------------- SYNOPSIS
#include "utils/rdofile.h"
#include "utils/platform.h"
#include "simulator/runtime/rdo_random_distribution.h"
// --------------------------------------------------------------------------------

#ifdef COMPILER_VISUAL_STUDIO
	#define  __SCANF  sscanf_s
#else  // not COMPILER_VISUAL_STUDIO
	#define  __SCANF  sscanf
#endif // COMPILER_VISUAL_STUDIO

typedef std::vector<double> Container;
typedef std::vector<ruint>  ContainerInt;
typedef const tstring contstr;

const long int g_seed                 = 123456789;                  //!<
contstr        g_filePath             = _T("../../test/sequences/");//!<
contstr        g_fileNormalName       = _T("data_normal.txt");      //!<
contstr        g_fileUniformName      = _T("data_uniform.txt");     //!<
contstr        g_fileExponentialName  = _T("data_exponential.txt"); //!<
contstr        g_fileTriangularName   = _T("data_trinagular.txt");  //!<

const ruint    g_count                = 100000;                     //!<
const double   g_main                 = 10.0;                       //!<
const double   g_var                  = 1.0;                        //!<
const double   g_from                 = 1.0;                        //!<
const double   g_to                   = 7.0;                        //!<
const double   g_top                  = 5.0;                        //!<
#if defined(ARCHITECTURE_AMD64) || defined(ARCHITECTURE_X86)
const ruint    g_precision            = 20;                         //!<
#elif defined(ARCHITECTURE_ARM)
const ruint    g_precision            = 14;                         //!<
#endif

const ruint    g_countOfExamples      = 2000;                       //!<
const ruint    g_countOfR             = 39;                         //!<
const double   pi                     = 3.141592653;                //!<
const double   g_ksiEtalon            = 50.9985;                    //!<  . 95%  ,

// --------------------------------------------------------------------------------
// -------Templates
// --------------------------------------------------------------------------------
template <class T, class F, class contstr>
void onGenerateData(F binder, contstr g_fileName)
{
	if (rdo::File::exist(g_fileName.c_str()))
		return;

	T sequence(g_seed);
	Container test;
	test.reserve(g_count);

	for (ruint i = 0; i < g_count; ++i)
	{
		test.push_back(binder.operator()(&sequence));
	}

	std::ofstream stream(g_fileName.c_str());
	stream.precision(g_precision);
	STL_FOR_ALL(test, it)
	{
		stream << *it << std::endl;
	}
}

template <class T, class F, class contstr>
void onCheckData(F binder, contstr g_fileName)
{
	std::ifstream stream(g_fileName.c_str());
	BOOST_CHECK(stream.good());
	Container orig;
	while (stream.good())
	{
		double value;
		stream >> value;
		std::stringstream s;
		s.precision(g_precision);
		s << value;
		s >> value;
		orig.push_back(value);
	}

	Container test;
	test.reserve(g_count);
	T sequence(g_seed);
	for (ruint i = 0; i < g_count; ++i)
	{
		std::stringstream s;
		s.precision(g_precision);
		s << binder.operator()(&sequence);
		double value;
		s >> value;
		test.push_back(value);
	}

	Container::const_iterator origIt = orig.begin();
	stream.precision(g_precision);
	STL_FOR_ALL(test, it)
	{
		BOOST_CHECK(origIt != orig.end());
		rbool check = *it == *origIt;
		BOOST_CHECK(check);
		if (!check)
		{
			std::cout.precision(g_precision);
			std::cout << *it << std::endl;
			std::cout << *origIt << std::endl;
		}
		++origIt;
	}
}

template <class T,class F>
double  area (F binder, double n, double m)
{
	double k = 1;
	double S1 = 1;
	double S2 = 0;
	ruint t = 10;
	while (fabs(S1-S2)/S1 > 0.01)
	{
		S2 = S1;
		S1 = 0;
		for (ruint g = 0; g < t + 1; ++g)
		{
			if ((g == 0) || (g == t - 1))
				k = 0.5;
			S1 += k*(binder.operator()(n + g*(m-n)/t));
			k = 1;
		}
		S1 *= (m-n)/t;
		t  *= 10;
	}
	return S1;
}

template <class T, class G, class F, class S>
void onCheckKsi(F binder, S binderSeq, double left, double right)
{
	Container x;
	x.reserve(g_countOfR + 1);
	double elem = (right-left)/(g_countOfR*1.0);	//

	for (ruint i = 0; i < g_countOfR + 1; ++i)
	{
		x.push_back(left + elem*i);
	}

	Container vb;									//
	vb.reserve(g_countOfExamples);

	G sequence(g_seed);								//
	for (ruint i = 0; i < g_countOfExamples; ++i)
	{
		vb.push_back(binderSeq.operator()(&sequence));
	}

	Container f_vb;									//
	f_vb.reserve(g_countOfR);

	for(ruint i = 0; i < g_countOfR; ++i)			//
	{
		ruint freq = 0;
		for(ruint k = 0; k < g_countOfExamples; ++k)
		{
			if((vb[k] > x[i]) & (vb[k] <= x[i+1]))
			{
				++freq;
			}
		}
		f_vb.push_back(freq);
	}

	Container F_etalon;
	F_etalon.reserve(g_countOfR);

	for (ruint i = 0; i < g_countOfR; ++i)
	{
		F_etalon.push_back(area<T>(binder, x[i], x[i+1]));
	}

	double ksi = 0;
	for(ruint i = 0; i < g_countOfR; ++i)
	{
		double ksiTemp = F_etalon[i]*g_countOfExamples;
		ksi += (f_vb[i] - ksiTemp)*(f_vb[i] - ksiTemp)/ksiTemp;
	}
	BOOST_CHECK(ksi <= g_ksiEtalon);
			if (ksi >  g_ksiEtalon)
	{
		std::cout << ksi << std::endl;
	}
}
// --------------------------------------------------------------------------------

class SequenceNormal
{
public:
	SequenceNormal(double main, double var)
		: m_main(main)
		, m_var (var )
	{}

	double get(double x) const
	{
		return 1/(sqrt(2*pi)*m_var*exp((x - m_main)*(x - m_main)/(2*m_var*m_var)));
	}

private:
	double m_main;
	double m_var;
};

class SequenceExponential
{
public:
	SequenceExponential(double main)
		: m_main(main)
	{}

	double get(double x) const
	{
		return 1/(m_main*exp(x/m_main));
	}

private:
	double m_main;
};

class SequenceUniform
{
public:
	SequenceUniform(double min, double max)
		: m_min(min)
		, m_max(max)
	{}

	double get(double x) const
	{
		UNUSED(x);
		return 1/(m_max-m_min);
	}

private:
	double m_min;
	double m_max;
};

class SequenceTriangular
{
public:
	SequenceTriangular(double min, double top, double max)
		: m_min(min-top)
		, m_top(top)
		, m_max(max-top)
	{}

	double get(double x) const
	{
		x -= m_top;
		double temp;
		if (x < 0)
		{
			temp = -2*x/((m_max - m_min)*m_min) + 2/(m_max - m_min);
		}
		else
		{
			temp = -2*x/((m_max - m_min)*m_max) + 2/(m_max - m_min);
		}
		return temp;
	}

private:
	double m_min;
	double m_top;
	double m_max;
};

BOOST_AUTO_TEST_SUITE(RDOSequencesTest)

// --------------------------------------------------------------------------------
// -------Normal sequence
// --------------------------------------------------------------------------------
BOOST_AUTO_TEST_CASE(RDONormalTestCreate)
{
	onGenerateData<rdo::runtime::RandGeneratorNormal>
		(boost::bind(&rdo::runtime::RandGeneratorNormal::next, _1, g_main, g_var), g_filePath + g_fileNormalName);
}

BOOST_AUTO_TEST_CASE(RDONormalTestCheck)
{
	onCheckData<rdo::runtime::RandGeneratorNormal>
		(boost::bind(&rdo::runtime::RandGeneratorNormal::next, _1, g_main, g_var), g_filePath + g_fileNormalName);

	SequenceNormal normal(g_main, g_var);
	onCheckKsi<SequenceNormal, rdo::runtime::RandGeneratorNormal>
		(boost::bind(&SequenceNormal::get, normal, _1),
		boost::bind(&rdo::runtime::RandGeneratorNormal::next, _1, g_main, g_var),
		g_main-4*g_var,
		g_main+4*g_var);
}
// --------------------------------------------------------------------------------

// --------------------------------------------------------------------------------
// -------Uniform sequence
// --------------------------------------------------------------------------------
BOOST_AUTO_TEST_CASE(RDOUniformTestCreate)
{
	onGenerateData<rdo::runtime::RandGeneratorUniform>
		(boost::bind(&rdo::runtime::RandGeneratorUniform::next, _1, g_from, g_to), g_filePath + g_fileUniformName);
}

BOOST_AUTO_TEST_CASE(RDOUniformTestCheck)
{
	onCheckData<rdo::runtime::RandGeneratorUniform>
		(boost::bind(&rdo::runtime::RandGeneratorUniform::next, _1, g_from, g_to), g_filePath + g_fileUniformName);

	SequenceUniform uniform(g_from, g_to);
	onCheckKsi<SequenceUniform, rdo::runtime::RandGeneratorUniform>
		(boost::bind(&SequenceUniform::get, uniform, _1),
		boost::bind(&rdo::runtime::RandGeneratorUniform::next, _1, g_from, g_to),
		g_from,
		g_to);
}
// --------------------------------------------------------------------------------

// --------------------------------------------------------------------------------
// -------Exponential sequence
// --------------------------------------------------------------------------------
BOOST_AUTO_TEST_CASE(RDOExponentialTestCreate)
{
	onGenerateData<rdo::runtime::RandGeneratorExponential>
		(boost::bind(&rdo::runtime::RandGeneratorExponential::next, _1, g_main), g_filePath + g_fileExponentialName);
}

BOOST_AUTO_TEST_CASE(RDOExponentialTestCheck)
{
	onCheckData<rdo::runtime::RandGeneratorExponential>
		(boost::bind(&rdo::runtime::RandGeneratorExponential::next, _1, g_main), g_filePath + g_fileExponentialName);

	SequenceExponential exponential(g_main);
	onCheckKsi<SequenceExponential, rdo::runtime::RandGeneratorExponential>
		(boost::bind(&SequenceExponential::get, exponential, _1),
		boost::bind(&rdo::runtime::RandGeneratorExponential::next, _1, g_main),
		0,
		7*g_main);
}
// --------------------------------------------------------------------------------

// --------------------------------------------------------------------------------
// -------Triangular sequence
// --------------------------------------------------------------------------------
BOOST_AUTO_TEST_CASE(RDOTriangularTestCreate)
{
	onGenerateData<rdo::runtime::RandGeneratorTriangular>
		(boost::bind(&rdo::runtime::RandGeneratorTriangular::next, _1, g_from, g_top, g_to), g_filePath + g_fileTriangularName);
}

BOOST_AUTO_TEST_CASE(RDOTriangularTestCheck)
{
	onCheckData<rdo::runtime::RandGeneratorTriangular>
		(boost::bind(&rdo::runtime::RandGeneratorTriangular::next, _1, g_from, g_top, g_to), g_filePath + g_fileTriangularName);

	SequenceTriangular triangular(g_from, g_top, g_to);
	onCheckKsi<SequenceTriangular, rdo::runtime::RandGeneratorTriangular>
		(boost::bind(&SequenceTriangular::get, triangular, _1),
		boost::bind(&rdo::runtime::RandGeneratorTriangular::next, _1, g_from, g_top, g_to),
		g_from,
		g_to);
}
// --------------------------------------------------------------------------------

BOOST_AUTO_TEST_SUITE_END()
<|endoftext|>


<commit_before>// Copyright (c) 2010 The WebM project authors. All Rights Reserved.
//
// Use of this source code is governed by a BSD-style license
// that can be found in the LICENSE file in the root of the source
// tree. An additional intellectual property rights grant can be found
// in the file PATENTS.  All contributing project authors may
// be found in the AUTHORS file in the root of the source tree.

#include <windows.h>
#include <windowsx.h>
#include <comdef.h>
#include <mfapi.h>
#include <mferror.h>
#include <mfidl.h>
#include <shlwapi.h>

#include "debugutil.hpp"
#include "eventutil.hpp"
#include "hrtext.hpp"
#include "mfmediastream.hpp"
#include "mfutil.hpp"

namespace WebmMfUtil
{

MfMediaStream::MfMediaStream():
  expected_event_(0),
  ref_count_(0),
  stream_event_error_(S_OK),
  stream_event_recvd_(0)
{
}

MfMediaStream::~MfMediaStream()
{
    if (ptr_sample_)
    {
        ptr_sample_ = 0;
    }
    if (ptr_event_queue_)
    {
        ptr_event_queue_ = 0;
    }
    if (ptr_stream_)
    {
        ptr_stream_ = 0;
    }
}

HRESULT MfMediaStream::QueryInterface(REFIID riid, void** ppv)
{
    static const QITAB qit[] =
    {
        QITABENT(MfMediaStream, IMFAsyncCallback),
        { 0 }
    };
    return QISearch(this, qit, riid, ppv);
}

ULONG MfMediaStream::AddRef()
{
    return InterlockedIncrement(&ref_count_);
}

ULONG MfMediaStream::Release()
{
    UINT ref_count = InterlockedDecrement(&ref_count_);
    if (ref_count == 0)
    {
        delete this;
    }
    return ref_count;
}

HRESULT MfMediaStream::Create_(IMFMediaStreamPtr& ptr_stream)
{
    ptr_stream_ = ptr_stream;
    HRESULT hr = ptr_stream_->QueryInterface(IID_IMFMediaEventGenerator,
        reinterpret_cast<void**>(&ptr_event_queue_));
    if (FAILED(hr))
    {
        DBGLOG("ERROR, failed to obtain stream event generator" << HRLOG(hr)
            << " returning E_FAIL.");
        return E_FAIL;
    }
    IMFStreamDescriptorPtr ptr_desc;
    hr = ptr_stream->GetStreamDescriptor(&ptr_desc);
    if (FAILED(hr))
    {
        DBGLOG("ERROR, GetStreamDescriptor failed" << HRLOG(hr));
        return hr;
    }
    hr = get_media_type(ptr_desc, &ptr_media_type_);
    if (FAILED(hr))
    {
        DBGLOG("ERROR, get_media_type failed" << HRLOG(hr));
        return hr;
    }
    hr = stream_event_.Create();
    if (FAILED(hr))
    {
        DBGLOG("ERROR, stream event creation failed" << HRLOG(hr));
        return hr;
    }
    return hr;
}

// IMFAsyncCallback method
STDMETHODIMP MfMediaStream::GetParameters(DWORD*, DWORD*)
{
    // Implementation of this method is optional.
    return E_NOTIMPL;
}

// IMFAsyncCallback method
STDMETHODIMP MfMediaStream::Invoke(IMFAsyncResult* pAsyncResult)
{
    stream_event_error_ = E_FAIL;
    MediaEventType event_type = MEError;
    IMFMediaEventPtr ptr_event;
    HRESULT hr = ptr_event_queue_->EndGetEvent(pAsyncResult, &ptr_event);
    if (FAILED(hr))
    {
        DBGLOG("ERROR, EndGetEvent failed" << HRLOG(hr));
    }
    else
    {
        hr = ptr_event->GetType(&event_type);
        if (FAILED(hr))
        {
            DBGLOG("ERROR, cannot get event type" << HRLOG(hr));
        }
        if (0 != expected_event_ && event_type != expected_event_)
        {
            DBGLOG("ERROR, unexpected event type, expected "
              << expected_event_ << " got " << event_type);
            stream_event_error_ = E_UNEXPECTED;
        }
        else
        {
            switch (event_type)
            {
            case MEMediaSample:
                DBGLOG("MEMediaSample");
                stream_event_error_ = OnMediaSample_(ptr_event);
                if (FAILED(stream_event_error_))
                {
                    DBGLOG("MEMediaSample handling failed");
                }
                break;
            case MEStreamPaused:
                DBGLOG("MEStreamPaused");
                stream_event_error_ = OnStreamPaused_(ptr_event);
                if (FAILED(stream_event_error_))
                {
                    DBGLOG("MEStreamSeeked handling failed");
                }
                break;
            case MEStreamSeeked:
                DBGLOG("MEStreamSeeked");
                stream_event_error_ = OnStreamSeeked_(ptr_event);
                if (FAILED(stream_event_error_))
                {
                    DBGLOG("MEStreamSeeked handling failed");
                }
                break;
            case MEStreamStarted:
                DBGLOG("MEStreamStarted");
                stream_event_error_ = OnStreamStarted_(ptr_event);
                if (FAILED(stream_event_error_))
                {
                    DBGLOG("MEStreamStarted handling failed");
                }
                break;
            case MEStreamStopped:
                DBGLOG("MEStreamStopped");
                stream_event_error_ = OnStreamStopped_(ptr_event);
                if (FAILED(stream_event_error_))
                {
                    DBGLOG("MEStreamStopped handling failed");
                }
                break;
            default:
                stream_event_error_ = E_UNEXPECTED;
                DBGLOG("unhandled event_type=" << event_type);
                break;
            }
        }
    }
    expected_event_ = 0;
    stream_event_recvd_ = event_type;
    return stream_event_.Set();
}

HRESULT MfMediaStream::OnMediaSample_(IMFMediaEventPtr& ptr_event)
{
    IUnknownPtr ptr_iunk;
    HRESULT hr = get_event_iunk_ptr(ptr_event, &ptr_iunk);
    if (FAILED(hr))
    {
        DBGLOG("ERROR, could not obtain IUnknown from event" << HRLOG(hr));
        return hr;
    }
    ptr_sample_ = ptr_iunk;
    if (!ptr_sample_)
    {
        DBGLOG("ERROR, sample pointer null");
        return E_POINTER;
    }
    return S_OK;
}

HRESULT MfMediaStream::OnStreamPaused_(IMFMediaEventPtr&)
{
    // no-op for now
    return S_OK;
}

HRESULT MfMediaStream::OnStreamSeeked_(IMFMediaEventPtr&)
{
    // no-op for now
    return S_OK;
}

HRESULT MfMediaStream::OnStreamStarted_(IMFMediaEventPtr&)
{
    // no-op for now
    return S_OK;
}

HRESULT MfMediaStream::OnStreamStopped_(IMFMediaEventPtr&)
{
    // no-op for now
    return S_OK;
}

HRESULT MfMediaStream::Create(IMFMediaStreamPtr& ptr_mfstream,
                              MfMediaStream** ptr_instance)
{
    if (!ptr_mfstream)
    {
        DBGLOG("null IMFMediaStream, returning E_INVALIDARG");
        return E_INVALIDARG;
    }
    MfMediaStream* ptr_stream = new (std::nothrow) MfMediaStream();
    if (!ptr_stream)
    {
        DBGLOG("null MfMediaStream, returning E_OUTOFMEMORY");
        return E_OUTOFMEMORY;
    }
    HRESULT hr = ptr_stream->Create_(ptr_mfstream);
    if (FAILED(hr))
    {
        DBGLOG("null MfMediaStream::Create_ failed" << HRLOG(hr));
        return hr;
    }
    ptr_stream->AddRef();
    *ptr_instance = ptr_stream;
    return hr;
}

HRESULT MfMediaStream::GetMediaType(IMFMediaType **ptr_type)
{
    if (!ptr_media_type_)
    {
        DBGLOG("ERROR, media type not set, E_UNEXPECTED");
        return E_UNEXPECTED;
    }
    return copy_media_type(ptr_media_type_, ptr_type);
}

HRESULT MfMediaStream::WaitForStreamEvent(MediaEventType event_type)
{
    expected_event_ = event_type;
    HRESULT hr = ptr_stream_->BeginGetEvent(this, NULL);
    if (FAILED(hr))
    {
        DBGLOG("ERROR, BeginGetEvent failed" << HRLOG(hr));
        return hr;
    }
    hr = stream_event_.Wait();
    if (FAILED(hr))
    {
        DBGLOG("ERROR, stream event wait failed" << HRLOG(hr));
        return hr;
    }
    if (FAILED(stream_event_error_))
    {
        // when event handling fails the last error is stored in
        // |media_event_type_recvd_|, just return it to the caller
        DBGLOG("ERROR, stream event handling failed"
            << HRLOG(stream_event_error_));
        return stream_event_error_;
    }
    return hr;
}

HRESULT MfMediaStream::GetSample(IMFSample **ptr_sample)
{
    if (!ptr_stream_)
    {
        DBGLOG("ERROR, stream not set, E_UNEXPECTED");
        return E_UNEXPECTED;
    }
    HRESULT hr = ptr_stream_->RequestSample(NULL);
    // MF_E_MEDIA_SOURCE_WRONGSTATE is not treated as an error by the pipeline
    if (FAILED(hr))
    {
        DBGLOG("ERROR, RequestSample failed" << HRLOG(hr));
        return hr;
    }
    hr = WaitForStreamEvent(MEMediaSample);
    if (FAILED(hr))
    {
        DBGLOG("WaitForStreamEvent MEMediaSample failed" << HRLOG(hr));
        return hr;
    }
    if (FAILED(stream_event_error_))
    {
        DBGLOG("MEMediaSample event handling failed"
            << HRLOG(stream_event_error_));
        return stream_event_error_;
    }
    if (!ptr_sample_)
    {
        // TODO(tomfinegan):
        DBGLOG("ERROR, null sample");
        return E_OUTOFMEMORY;
    }
    ptr_sample_->AddRef();
    *ptr_sample = ptr_sample_;
    return hr;
}

} // WebmMfUtil namespace
<commit_msg>mfmediastream: remove explicit smart ptr clean up<commit_after>// Copyright (c) 2010 The WebM project authors. All Rights Reserved.
//
// Use of this source code is governed by a BSD-style license
// that can be found in the LICENSE file in the root of the source
// tree. An additional intellectual property rights grant can be found
// in the file PATENTS.  All contributing project authors may
// be found in the AUTHORS file in the root of the source tree.

#include <windows.h>
#include <windowsx.h>
#include <comdef.h>
#include <mfapi.h>
#include <mferror.h>
#include <mfidl.h>
#include <shlwapi.h>

#include "debugutil.hpp"
#include "eventutil.hpp"
#include "hrtext.hpp"
#include "mfmediastream.hpp"
#include "mfutil.hpp"

namespace WebmMfUtil
{

MfMediaStream::MfMediaStream():
  expected_event_(0),
  ref_count_(0),
  stream_event_error_(S_OK),
  stream_event_recvd_(0)
{
}

MfMediaStream::~MfMediaStream()
{
}

HRESULT MfMediaStream::QueryInterface(REFIID riid, void** ppv)
{
    static const QITAB qit[] =
    {
        QITABENT(MfMediaStream, IMFAsyncCallback),
        { 0 }
    };
    return QISearch(this, qit, riid, ppv);
}

ULONG MfMediaStream::AddRef()
{
    return InterlockedIncrement(&ref_count_);
}

ULONG MfMediaStream::Release()
{
    UINT ref_count = InterlockedDecrement(&ref_count_);
    if (ref_count == 0)
    {
        delete this;
    }
    return ref_count;
}

HRESULT MfMediaStream::Create_(IMFMediaStreamPtr& ptr_stream)
{
    ptr_stream_ = ptr_stream;
    HRESULT hr = ptr_stream_->QueryInterface(IID_IMFMediaEventGenerator,
        reinterpret_cast<void**>(&ptr_event_queue_));
    if (FAILED(hr))
    {
        DBGLOG("ERROR, failed to obtain stream event generator" << HRLOG(hr)
            << " returning E_FAIL.");
        return E_FAIL;
    }
    IMFStreamDescriptorPtr ptr_desc;
    hr = ptr_stream->GetStreamDescriptor(&ptr_desc);
    if (FAILED(hr))
    {
        DBGLOG("ERROR, GetStreamDescriptor failed" << HRLOG(hr));
        return hr;
    }
    hr = get_media_type(ptr_desc, &ptr_media_type_);
    if (FAILED(hr))
    {
        DBGLOG("ERROR, get_media_type failed" << HRLOG(hr));
        return hr;
    }
    hr = stream_event_.Create();
    if (FAILED(hr))
    {
        DBGLOG("ERROR, stream event creation failed" << HRLOG(hr));
        return hr;
    }
    return hr;
}

// IMFAsyncCallback method
STDMETHODIMP MfMediaStream::GetParameters(DWORD*, DWORD*)
{
    // Implementation of this method is optional.
    return E_NOTIMPL;
}

// IMFAsyncCallback method
STDMETHODIMP MfMediaStream::Invoke(IMFAsyncResult* pAsyncResult)
{
    stream_event_error_ = E_FAIL;
    MediaEventType event_type = MEError;
    IMFMediaEventPtr ptr_event;
    HRESULT hr = ptr_event_queue_->EndGetEvent(pAsyncResult, &ptr_event);
    if (FAILED(hr))
    {
        DBGLOG("ERROR, EndGetEvent failed" << HRLOG(hr));
    }
    else
    {
        hr = ptr_event->GetType(&event_type);
        if (FAILED(hr))
        {
            DBGLOG("ERROR, cannot get event type" << HRLOG(hr));
        }
        if (0 != expected_event_ && event_type != expected_event_)
        {
            DBGLOG("ERROR, unexpected event type, expected "
              << expected_event_ << " got " << event_type);
            stream_event_error_ = E_UNEXPECTED;
        }
        else
        {
            switch (event_type)
            {
            case MEMediaSample:
                DBGLOG("MEMediaSample");
                stream_event_error_ = OnMediaSample_(ptr_event);
                if (FAILED(stream_event_error_))
                {
                    DBGLOG("MEMediaSample handling failed");
                }
                break;
            case MEStreamPaused:
                DBGLOG("MEStreamPaused");
                stream_event_error_ = OnStreamPaused_(ptr_event);
                if (FAILED(stream_event_error_))
                {
                    DBGLOG("MEStreamSeeked handling failed");
                }
                break;
            case MEStreamSeeked:
                DBGLOG("MEStreamSeeked");
                stream_event_error_ = OnStreamSeeked_(ptr_event);
                if (FAILED(stream_event_error_))
                {
                    DBGLOG("MEStreamSeeked handling failed");
                }
                break;
            case MEStreamStarted:
                DBGLOG("MEStreamStarted");
                stream_event_error_ = OnStreamStarted_(ptr_event);
                if (FAILED(stream_event_error_))
                {
                    DBGLOG("MEStreamStarted handling failed");
                }
                break;
            case MEStreamStopped:
                DBGLOG("MEStreamStopped");
                stream_event_error_ = OnStreamStopped_(ptr_event);
                if (FAILED(stream_event_error_))
                {
                    DBGLOG("MEStreamStopped handling failed");
                }
                break;
            default:
                stream_event_error_ = E_UNEXPECTED;
                DBGLOG("unhandled event_type=" << event_type);
                break;
            }
        }
    }
    expected_event_ = 0;
    stream_event_recvd_ = event_type;
    return stream_event_.Set();
}

HRESULT MfMediaStream::OnMediaSample_(IMFMediaEventPtr& ptr_event)
{
    IUnknownPtr ptr_iunk;
    HRESULT hr = get_event_iunk_ptr(ptr_event, &ptr_iunk);
    if (FAILED(hr))
    {
        DBGLOG("ERROR, could not obtain IUnknown from event" << HRLOG(hr));
        return hr;
    }
    ptr_sample_ = ptr_iunk;
    if (!ptr_sample_)
    {
        DBGLOG("ERROR, sample pointer null");
        return E_POINTER;
    }
    return S_OK;
}

HRESULT MfMediaStream::OnStreamPaused_(IMFMediaEventPtr&)
{
    // no-op for now
    return S_OK;
}

HRESULT MfMediaStream::OnStreamSeeked_(IMFMediaEventPtr&)
{
    // no-op for now
    return S_OK;
}

HRESULT MfMediaStream::OnStreamStarted_(IMFMediaEventPtr&)
{
    // no-op for now
    return S_OK;
}

HRESULT MfMediaStream::OnStreamStopped_(IMFMediaEventPtr&)
{
    // no-op for now
    return S_OK;
}

HRESULT MfMediaStream::Create(IMFMediaStreamPtr& ptr_mfstream,
                              MfMediaStream** ptr_instance)
{
    if (!ptr_mfstream)
    {
        DBGLOG("null IMFMediaStream, returning E_INVALIDARG");
        return E_INVALIDARG;
    }
    MfMediaStream* ptr_stream = new (std::nothrow) MfMediaStream();
    if (!ptr_stream)
    {
        DBGLOG("null MfMediaStream, returning E_OUTOFMEMORY");
        return E_OUTOFMEMORY;
    }
    HRESULT hr = ptr_stream->Create_(ptr_mfstream);
    if (FAILED(hr))
    {
        DBGLOG("null MfMediaStream::Create_ failed" << HRLOG(hr));
        return hr;
    }
    ptr_stream->AddRef();
    *ptr_instance = ptr_stream;
    return hr;
}

HRESULT MfMediaStream::GetMediaType(IMFMediaType **ptr_type)
{
    if (!ptr_media_type_)
    {
        DBGLOG("ERROR, media type not set, E_UNEXPECTED");
        return E_UNEXPECTED;
    }
    return copy_media_type(ptr_media_type_, ptr_type);
}

HRESULT MfMediaStream::WaitForStreamEvent(MediaEventType event_type)
{
    expected_event_ = event_type;
    HRESULT hr = ptr_stream_->BeginGetEvent(this, NULL);
    if (FAILED(hr))
    {
        DBGLOG("ERROR, BeginGetEvent failed" << HRLOG(hr));
        return hr;
    }
    hr = stream_event_.Wait();
    if (FAILED(hr))
    {
        DBGLOG("ERROR, stream event wait failed" << HRLOG(hr));
        return hr;
    }
    if (FAILED(stream_event_error_))
    {
        // when event handling fails the last error is stored in
        // |media_event_type_recvd_|, just return it to the caller
        DBGLOG("ERROR, stream event handling failed"
            << HRLOG(stream_event_error_));
        return stream_event_error_;
    }
    return hr;
}

HRESULT MfMediaStream::GetSample(IMFSample **ptr_sample)
{
    if (!ptr_stream_)
    {
        DBGLOG("ERROR, stream not set, E_UNEXPECTED");
        return E_UNEXPECTED;
    }
    HRESULT hr = ptr_stream_->RequestSample(NULL);
    // MF_E_MEDIA_SOURCE_WRONGSTATE is not treated as an error by the pipeline
    if (FAILED(hr))
    {
        DBGLOG("ERROR, RequestSample failed" << HRLOG(hr));
        return hr;
    }
    hr = WaitForStreamEvent(MEMediaSample);
    if (FAILED(hr))
    {
        DBGLOG("WaitForStreamEvent MEMediaSample failed" << HRLOG(hr));
        return hr;
    }
    if (FAILED(stream_event_error_))
    {
        DBGLOG("MEMediaSample event handling failed"
            << HRLOG(stream_event_error_));
        return stream_event_error_;
    }
    if (!ptr_sample_)
    {
        // TODO(tomfinegan):
        DBGLOG("ERROR, null sample");
        return E_OUTOFMEMORY;
    }
    ptr_sample_->AddRef();
    *ptr_sample = ptr_sample_;
    return hr;
}

} // WebmMfUtil namespace
<|endoftext|>


<commit_before>/*************************************************************************
 *
 * 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: RptObjectListener.cxx,v $
 * $Revision: 1.4 $
 *
 * 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.
 *
 ************************************************************************/

#include "RptObjectListener.hxx"
#include "RptObject.hxx"
#include "RptDef.hxx"

namespace rptui
{
//============================================================================
// OObjectListener
//============================================================================

//----------------------------------------------------------------------------
DBG_NAME(rpt_OObjectListener)
OObjectListener::OObjectListener(OObjectBase* _pObject)
          :m_pObject(_pObject)
{
    DBG_CTOR(rpt_OObjectListener,NULL);
}

//----------------------------------------------------------------------------

OObjectListener::~OObjectListener()
{
    DBG_DTOR(rpt_OObjectListener,NULL);
}

// XEventListener
//----------------------------------------------------------------------------

void SAL_CALL OObjectListener::disposing( const  ::com::sun::star::lang::EventObject& ) throw( ::com::sun::star::uno::RuntimeException)
{
    /*
    // disconnect the listener
    if (m_pObject)
    {
        (m_pObject->m_xPropertyChangeListener).clear();
    }
    */
}

// XPropertyChangeListener
//----------------------------------------------------------------------------

void SAL_CALL OObjectListener::propertyChange( const  ::com::sun::star::beans::PropertyChangeEvent& evt ) throw( ::com::sun::star::uno::RuntimeException)
{
    m_pObject->_propertyChange( evt );
}

//----------------------------------------------------------------------------

//============================================================================
// DlgEdHint
//============================================================================

TYPEINIT1( DlgEdHint, SfxHint );

//----------------------------------------------------------------------------

DlgEdHint::DlgEdHint( DlgEdHintKind eHint )
    :eHintKind( eHint )
{
}

//----------------------------------------------------------------------------

DlgEdHint::DlgEdHint( DlgEdHintKind eHint, OUnoObject* pObj )
    :eHintKind( eHint )
    ,pDlgEdObj( pObj )
{
}

//----------------------------------------------------------------------------

DlgEdHint::~DlgEdHint()
{
}
//----------------------------------------------------------------------------
}
<commit_msg>INTEGRATION: CWS rptchart02 (1.3.92); FILE MERGED 2008/04/16 06:28:18 oj 1.3.92.2: RESYNC: (1.3-1.4); FILE MERGED 2008/04/03 06:35:18 oj 1.3.92.1: #i86343# remove unused code<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: RptObjectListener.cxx,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.
 *
 ************************************************************************/

#include "RptObjectListener.hxx"
#include "RptObject.hxx"
#include "RptDef.hxx"

namespace rptui
{
//============================================================================
// OObjectListener
//============================================================================

//----------------------------------------------------------------------------
DBG_NAME(rpt_OObjectListener)
OObjectListener::OObjectListener(OObjectBase* _pObject)
          :m_pObject(_pObject)
{
    DBG_CTOR(rpt_OObjectListener,NULL);
}

//----------------------------------------------------------------------------

OObjectListener::~OObjectListener()
{
    DBG_DTOR(rpt_OObjectListener,NULL);
}

// XEventListener
//----------------------------------------------------------------------------

void SAL_CALL OObjectListener::disposing( const  ::com::sun::star::lang::EventObject& ) throw( ::com::sun::star::uno::RuntimeException)
{
    /*
    // disconnect the listener
    if (m_pObject)
    {
        (m_pObject->m_xPropertyChangeListener).clear();
    }
    */
}

// XPropertyChangeListener
//----------------------------------------------------------------------------

void SAL_CALL OObjectListener::propertyChange( const  ::com::sun::star::beans::PropertyChangeEvent& evt ) throw( ::com::sun::star::uno::RuntimeException)
{
    m_pObject->_propertyChange( evt );
}

//----------------------------------------------------------------------------

//============================================================================
// DlgEdHint
//============================================================================

TYPEINIT1( DlgEdHint, SfxHint );

//----------------------------------------------------------------------------

DlgEdHint::DlgEdHint( DlgEdHintKind eHint )
    :eHintKind( eHint )
{
}

//----------------------------------------------------------------------------
DlgEdHint::~DlgEdHint()
{
}
//----------------------------------------------------------------------------
}
<|endoftext|>