<commit_before>// Copyright (c) 2014 Greenheart Games Pty. Ltd. All rights reserved.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.

#include "greenworks_async_workers.h"

#include "nan.h"
#include "steam/steam_api.h"
#include "v8.h"

#include "greenworks_unzip.h"
#include "greenworks_zip.h"

namespace {

struct FilesContentContainer {
  std::vector<char*> files_content;
  ~FilesContentContainer() {
    for (size_t i = 0; i < files_content.size(); ++i) {
      delete files_content[i];
    }
  }
};

};

namespace greenworks {

FileContentSaveWorker::FileContentSaveWorker(NanCallback* success_callback,
    NanCallback* error_callback, std::string file_name, std::string content):
        SteamAsyncWorker(success_callback, error_callback),
        file_name_(file_name),
        content_(content) {
}

void FileContentSaveWorker::Execute() {
  if (!SteamRemoteStorage()->FileWrite(
      file_name_.c_str(), content_.c_str(), content_.size()))
    SetErrorMessage("Error on writing to file.");
}

FilesSaveWorker::FilesSaveWorker(NanCallback* success_callback,
    NanCallback* error_callback, const std::vector<std::string>& files_path):
        SteamAsyncWorker(success_callback, error_callback),
        files_path_(files_path) {
}

void FilesSaveWorker::Execute() {
  FilesContentContainer container;
  std::vector<int> files_content_length;
  for (size_t i = 0; i < files_path_.size(); ++i) {
    char* content = NULL;
    int length = 0;
    if (!utils::ReadFile(files_path_[i].c_str(), content, length))
      break;
    container.files_content.push_back(content);
    files_content_length.push_back(length);
  }
  if (container.files_content.size() != files_path_.size()) {
    SetErrorMessage("Error on reading files.");
    return;
  }
  for (size_t i = 0; i < files_path_.size(); ++i) {
    std::string file_name = utils::GetFileNameFromPath(files_path_[i]);
    if (!SteamRemoteStorage()->FileWrite(file_name.c_str(),
        container.files_content[i], files_content_length[i])) {
      SetErrorMessage("Error on writing file on Steam Cloud.");
      return;
    }
  }
}

FileReadWorker::FileReadWorker(NanCallback* success_callback,
    NanCallback* error_callback, std::string file_name):
        SteamAsyncWorker(success_callback, error_callback),
        file_name_(file_name) {
}

void FileReadWorker::Execute() {
  ISteamRemoteStorage* steam_remote_storage = SteamRemoteStorage();

  if (!steam_remote_storage->FileExists(file_name_.c_str())) {
    SetErrorMessage("File doesn't exist.");
    return;
  }

  int32 file_size = steam_remote_storage->GetFileSize(file_name_.c_str());

  char* content = new char[file_size+1];
  int32 end_pos = steam_remote_storage->FileRead(
      file_name_.c_str(), content, file_size);
  content[end_pos] = '\0';

  if (end_pos == 0 && file_size > 0) {
    SetErrorMessage("Error on reading file.");
  } else {
    content_ = std::string(content);
  }

  delete content;
}

void FileReadWorker::HandleOKCallback() {
  NanScope();

  v8::Local<v8::Value> argv[] = { NanNew<v8::String>(content_) };
  callback->Call(1, argv);
}

CloudQuotaGetWorker::CloudQuotaGetWorker(NanCallback* success_callback,
      NanCallback* error_callback):SteamAsyncWorker(success_callback,
          error_callback), total_bytes_(-1), available_bytes_(-1) {
}

void CloudQuotaGetWorker::Execute() {
  ISteamRemoteStorage* steam_remote_storage = SteamRemoteStorage();

  if (!steam_remote_storage->GetQuota(&total_bytes_, &available_bytes_)) {
    SetErrorMessage("Error on getting cloud quota.");
    return;
  }
}

void CloudQuotaGetWorker::HandleOKCallback() {
  NanScope();
  v8::Local<v8::Value> argv[] = { NanNew<v8::Integer>(total_bytes_),
                                  NanNew<v8::Integer>(available_bytes_) };
  callback->Call(2, argv);
}

ActivateAchievementWorker::ActivateAchievementWorker(
    NanCallback* success_callback, NanCallback* error_callback,
    const std::string& achievement):
        SteamAsyncWorker(success_callback,
        error_callback), achievement_(achievement) {
}

void ActivateAchievementWorker::Execute() {
  ISteamUserStats* steam_user_stats = SteamUserStats();

  steam_user_stats->SetAchievement(achievement_.c_str());
  if (!steam_user_stats->StoreStats())
    SetErrorMessage("Error on storing user achievement");
}

GetAchievementWorker::GetAchievementWorker(
    NanCallback* success_callback,
    NanCallback* error_callback,
    const std::string& achievement):
        SteamAsyncWorker(success_callback, error_callback),
        achievement_(achievement),
        is_achieved_(false) {
}

void GetAchievementWorker::Execute() {
  ISteamUserStats* steam_user_stats = SteamUserStats();
  bool success = steam_user_stats->GetAchievement(achievement_.c_str(),
                                                  &is_achieved_);
  if (!success) {
    SetErrorMessage("Achivement name is not valid.");
  }
}

void GetAchievementWorker::HandleOKCallback() {
  NanScope();
  v8::Local<v8::Value> argv[] = { NanNew(is_achieved_) };
  callback->Call(1, argv);
}

ClearAchievementWorker::ClearAchievementWorker(
    NanCallback* success_callback,
    NanCallback* error_callback,
    const std::string& achievement):
        SteamAsyncWorker(success_callback, error_callback),
        achievement_(achievement),
        success_(false) {
}

void ClearAchievementWorker::Execute() {
  ISteamUserStats* steam_user_stats = SteamUserStats();
  success_ = steam_user_stats->ClearAchievement(achievement_.c_str());
  if (!success_) {
    SetErrorMessage("Achievement name is not valid.");
  } else if (!steam_user_stats->StoreStats()) {
    SetErrorMessage("Fails on uploading user stats to server.");
  }
}

void ClearAchievementWorker::HandleOKCallback() {
  NanScope();
  v8::Local<v8::Value> argv;
  callback->Call(0, &argv);
}

GetNumberOfPlayersWorker::GetNumberOfPlayersWorker(
    NanCallback* success_callback, NanCallback* error_callback)
       :SteamCallbackAsyncWorker(success_callback, error_callback),
        num_of_players_(-1) {
}

void GetNumberOfPlayersWorker::Execute() {
  SteamAPICall_t steam_api_call = SteamUserStats()->GetNumberOfCurrentPlayers();
  call_result_.Set(steam_api_call, this,
      &GetNumberOfPlayersWorker::OnGetNumberOfPlayersCompleted);

  WaitForCompleted();
}

void GetNumberOfPlayersWorker::OnGetNumberOfPlayersCompleted(
    NumberOfCurrentPlayers_t* result, bool io_failure) {
  if (io_failure) {
    SetErrorMessage("Error on getting number of players: Steam API IO Failure");
  } else if (result->m_bSuccess) {
    num_of_players_ = result->m_cPlayers;
  } else {
    SetErrorMessage("Error on getting number of players.");
  }
  is_completed_ = true;
}

void GetNumberOfPlayersWorker::HandleOKCallback() {
  NanScope();

  v8::Local<v8::Value> argv[] = { NanNew(num_of_players_) };
  callback->Call(1, argv);
}

CreateArchiveWorker::CreateArchiveWorker(NanCallback* success_callback,
    NanCallback* error_callback, const std::string& zip_file_path,
    const std::string& source_dir, const std::string& password,
    int compress_level)
        :SteamAsyncWorker(success_callback, error_callback),
         zip_file_path_(zip_file_path),
         source_dir_(source_dir),
         password_(password),
         compress_level_(compress_level) {
}

void CreateArchiveWorker::Execute() {
  int result = zip(zip_file_path_.c_str(),
                   source_dir_.c_str(),
                   compress_level_,
                   password_.empty()?NULL:password_.c_str());
  if (result)
    SetErrorMessage("Error on creating zip file.");
}

ExtractArchiveWorker::ExtractArchiveWorker(NanCallback* success_callback,
    NanCallback* error_callback, const std::string& zip_file_path,
    const std::string& extract_path, const std::string& password)
        : SteamAsyncWorker(success_callback, error_callback),
          zip_file_path_(zip_file_path),
          extract_path_(extract_path),
          password_(password) {
}

void ExtractArchiveWorker::Execute() {
  int result = unzip(zip_file_path_.c_str(), extract_path_.c_str(),
      password_.empty()?NULL:password_.c_str());
  if (result)
    SetErrorMessage("Error on extracting zip file.");
}

}  // namespace greenworks
<commit_msg>Revert "fixed empty array initialization error in MSVC"<commit_after>// Copyright (c) 2014 Greenheart Games Pty. Ltd. All rights reserved.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.

#include "greenworks_async_workers.h"

#include "nan.h"
#include "steam/steam_api.h"
#include "v8.h"

#include "greenworks_unzip.h"
#include "greenworks_zip.h"

namespace {

struct FilesContentContainer {
  std::vector<char*> files_content;
  ~FilesContentContainer() {
    for (size_t i = 0; i < files_content.size(); ++i) {
      delete files_content[i];
    }
  }
};

};

namespace greenworks {

FileContentSaveWorker::FileContentSaveWorker(NanCallback* success_callback,
    NanCallback* error_callback, std::string file_name, std::string content):
        SteamAsyncWorker(success_callback, error_callback),
        file_name_(file_name),
        content_(content) {
}

void FileContentSaveWorker::Execute() {
  if (!SteamRemoteStorage()->FileWrite(
      file_name_.c_str(), content_.c_str(), content_.size()))
    SetErrorMessage("Error on writing to file.");
}

FilesSaveWorker::FilesSaveWorker(NanCallback* success_callback,
    NanCallback* error_callback, const std::vector<std::string>& files_path):
        SteamAsyncWorker(success_callback, error_callback),
        files_path_(files_path) {
}

void FilesSaveWorker::Execute() {
  FilesContentContainer container;
  std::vector<int> files_content_length;
  for (size_t i = 0; i < files_path_.size(); ++i) {
    char* content = NULL;
    int length = 0;
    if (!utils::ReadFile(files_path_[i].c_str(), content, length))
      break;
    container.files_content.push_back(content);
    files_content_length.push_back(length);
  }
  if (container.files_content.size() != files_path_.size()) {
    SetErrorMessage("Error on reading files.");
    return;
  }
  for (size_t i = 0; i < files_path_.size(); ++i) {
    std::string file_name = utils::GetFileNameFromPath(files_path_[i]);
    if (!SteamRemoteStorage()->FileWrite(file_name.c_str(),
        container.files_content[i], files_content_length[i])) {
      SetErrorMessage("Error on writing file on Steam Cloud.");
      return;
    }
  }
}

FileReadWorker::FileReadWorker(NanCallback* success_callback,
    NanCallback* error_callback, std::string file_name):
        SteamAsyncWorker(success_callback, error_callback),
        file_name_(file_name) {
}

void FileReadWorker::Execute() {
  ISteamRemoteStorage* steam_remote_storage = SteamRemoteStorage();

  if (!steam_remote_storage->FileExists(file_name_.c_str())) {
    SetErrorMessage("File doesn't exist.");
    return;
  }

  int32 file_size = steam_remote_storage->GetFileSize(file_name_.c_str());

  char* content = new char[file_size+1];
  int32 end_pos = steam_remote_storage->FileRead(
      file_name_.c_str(), content, file_size);
  content[end_pos] = '\0';

  if (end_pos == 0 && file_size > 0) {
    SetErrorMessage("Error on reading file.");
  } else {
    content_ = std::string(content);
  }

  delete content;
}

void FileReadWorker::HandleOKCallback() {
  NanScope();

  v8::Local<v8::Value> argv[] = { NanNew<v8::String>(content_) };
  callback->Call(1, argv);
}

CloudQuotaGetWorker::CloudQuotaGetWorker(NanCallback* success_callback,
      NanCallback* error_callback):SteamAsyncWorker(success_callback,
          error_callback), total_bytes_(-1), available_bytes_(-1) {
}

void CloudQuotaGetWorker::Execute() {
  ISteamRemoteStorage* steam_remote_storage = SteamRemoteStorage();

  if (!steam_remote_storage->GetQuota(&total_bytes_, &available_bytes_)) {
    SetErrorMessage("Error on getting cloud quota.");
    return;
  }
}

void CloudQuotaGetWorker::HandleOKCallback() {
  NanScope();
  v8::Local<v8::Value> argv[] = { NanNew<v8::Integer>(total_bytes_),
                                  NanNew<v8::Integer>(available_bytes_) };
  callback->Call(2, argv);
}

ActivateAchievementWorker::ActivateAchievementWorker(
    NanCallback* success_callback, NanCallback* error_callback,
    const std::string& achievement):
        SteamAsyncWorker(success_callback,
        error_callback), achievement_(achievement) {
}

void ActivateAchievementWorker::Execute() {
  ISteamUserStats* steam_user_stats = SteamUserStats();

  steam_user_stats->SetAchievement(achievement_.c_str());
  if (!steam_user_stats->StoreStats())
    SetErrorMessage("Error on storing user achievement");
}

GetAchievementWorker::GetAchievementWorker(
    NanCallback* success_callback,
    NanCallback* error_callback,
    const std::string& achievement):
        SteamAsyncWorker(success_callback, error_callback),
        achievement_(achievement),
        is_achieved_(false) {
}

void GetAchievementWorker::Execute() {
  ISteamUserStats* steam_user_stats = SteamUserStats();
  bool success = steam_user_stats->GetAchievement(achievement_.c_str(),
                                                  &is_achieved_);
  if (!success) {
    SetErrorMessage("Achivement name is not valid.");
  }
}

void GetAchievementWorker::HandleOKCallback() {
  NanScope();
  v8::Local<v8::Value> argv[] = { NanNew(is_achieved_) };
  callback->Call(1, argv);
}

ClearAchievementWorker::ClearAchievementWorker(
    NanCallback* success_callback,
    NanCallback* error_callback,
    const std::string& achievement):
        SteamAsyncWorker(success_callback, error_callback),
        achievement_(achievement),
        success_(false) {
}

void ClearAchievementWorker::Execute() {
  ISteamUserStats* steam_user_stats = SteamUserStats();
  success_ = steam_user_stats->ClearAchievement(achievement_.c_str());
  if (!success_) {
    SetErrorMessage("Achievement name is not valid.");
  } else if (!steam_user_stats->StoreStats()) {
    SetErrorMessage("Fails on uploading user stats to server.");
  }
}

void ClearAchievementWorker::HandleOKCallback() {
  NanScope();
  callback->Call(0, {});
}

GetNumberOfPlayersWorker::GetNumberOfPlayersWorker(
    NanCallback* success_callback, NanCallback* error_callback)
       :SteamCallbackAsyncWorker(success_callback, error_callback),
        num_of_players_(-1) {
}

void GetNumberOfPlayersWorker::Execute() {
  SteamAPICall_t steam_api_call = SteamUserStats()->GetNumberOfCurrentPlayers();
  call_result_.Set(steam_api_call, this,
      &GetNumberOfPlayersWorker::OnGetNumberOfPlayersCompleted);

  WaitForCompleted();
}

void GetNumberOfPlayersWorker::OnGetNumberOfPlayersCompleted(
    NumberOfCurrentPlayers_t* result, bool io_failure) {
  if (io_failure) {
    SetErrorMessage("Error on getting number of players: Steam API IO Failure");
  } else if (result->m_bSuccess) {
    num_of_players_ = result->m_cPlayers;
  } else {
    SetErrorMessage("Error on getting number of players.");
  }
  is_completed_ = true;
}

void GetNumberOfPlayersWorker::HandleOKCallback() {
  NanScope();

  v8::Local<v8::Value> argv[] = { NanNew(num_of_players_) };
  callback->Call(1, argv);
}

CreateArchiveWorker::CreateArchiveWorker(NanCallback* success_callback,
    NanCallback* error_callback, const std::string& zip_file_path,
    const std::string& source_dir, const std::string& password,
    int compress_level)
        :SteamAsyncWorker(success_callback, error_callback),
         zip_file_path_(zip_file_path),
         source_dir_(source_dir),
         password_(password),
         compress_level_(compress_level) {
}

void CreateArchiveWorker::Execute() {
  int result = zip(zip_file_path_.c_str(),
                   source_dir_.c_str(),
                   compress_level_,
                   password_.empty()?NULL:password_.c_str());
  if (result)
    SetErrorMessage("Error on creating zip file.");
}

ExtractArchiveWorker::ExtractArchiveWorker(NanCallback* success_callback,
    NanCallback* error_callback, const std::string& zip_file_path,
    const std::string& extract_path, const std::string& password)
        : SteamAsyncWorker(success_callback, error_callback),
          zip_file_path_(zip_file_path),
          extract_path_(extract_path),
          password_(password) {
}

void ExtractArchiveWorker::Execute() {
  int result = unzip(zip_file_path_.c_str(), extract_path_.c_str(),
      password_.empty()?NULL:password_.c_str());
  if (result)
    SetErrorMessage("Error on extracting zip file.");
}

}  // namespace greenworks
<|endoftext|>


<commit_before>#include <Poco/Clock.h>
#include <Poco/Logger.h>
#include <Poco/Net/WebSocket.h>
#include <Poco/Net/NetException.h>

#include "di/Injectable.h"
#include "gws/GatewayCommunicator.h"

BEEEON_OBJECT_BEGIN(BeeeOn, GatewayCommunicator)
BEEEON_OBJECT_CASTABLE(StoppableLoop)
BEEEON_OBJECT_REF("messageHandler", &GatewayCommunicator::setGWMessageHandler)
BEEEON_OBJECT_NUMBER("maxMessageSize", &GatewayCommunicator::setMaxMessageSize)
BEEEON_OBJECT_TIME("receiveTimeout", &GatewayCommunicator::setReceiveTimeout)
BEEEON_OBJECT_TIME("sendTimeout", &GatewayCommunicator::setSendTimeout)
BEEEON_OBJECT_NUMBER("minThreads", &GatewayCommunicator::setMinThreads)
BEEEON_OBJECT_NUMBER("maxThreads", &GatewayCommunicator::setMaxThreads)
BEEEON_OBJECT_TIME("threadIdleTime", &GatewayCommunicator::setThreadIdleTime)
BEEEON_OBJECT_REF("asyncExecutor", &GatewayCommunicator::setAsyncExecutor)
BEEEON_OBJECT_REF("listeners", &GatewayCommunicator::registerListener)
BEEEON_OBJECT_END(BeeeOn, GatewayCommunicator)

using namespace std;
using namespace Poco;
using namespace Poco::Net;
using namespace BeeeOn;

GatewayCommunicator::GatewayCommunicator():
	m_maxMessageSize(4096),
	m_stop(false),
	m_workerRunnable(*this, &GatewayCommunicator::runWorker)
{
}

GatewayCommunicator::~GatewayCommunicator()
{
}

void GatewayCommunicator::registerListener(GatewayListener::Ptr listener)
{
	m_eventSource.addListener(listener);
}

void GatewayCommunicator::setAsyncExecutor(SharedPtr<AsyncExecutor> executor)
{
	m_eventSource.setAsyncExecutor(executor);
}

void GatewayCommunicator::addGateway(const GatewayID &gatewayID, WebSocket &webSocket)
{
	FastMutex::ScopedLock guard(m_connectionMapMutex);

	auto it = m_connectionMap.find(gatewayID);
	if (it != m_connectionMap.end()) {
		if (logger().debug()) {
			logger().debug("gateway " + gatewayID.toString()
					+ " found, using new connection", __FILE__, __LINE__);
		}

		it->second->removeFromReactor();
		m_connectionMap.erase(it);
	}

	webSocket.setReceiveTimeout(m_receiveTimeout);
	webSocket.setSendTimeout(m_sendTimeout);

	GatewayConnection::Ptr connection(
		new GatewayConnection(
			gatewayID,
			webSocket,
			m_reactor,
			[this](GatewayConnection::Ptr gatewayConnection)
			{
				enqueueReadable(gatewayConnection);
			},
			m_maxMessageSize
	));

	auto emplaced = m_connectionMap.emplace(gatewayID, connection);
	emplaced.first->second->addToReactor();

	GatewayEvent e(gatewayID);
	e.setSocketAddress(webSocket.peerAddress());

	if (it != m_connectionMap.end())
		m_eventSource.fireEvent(e, &GatewayListener::onReconnected);
	else
		m_eventSource.fireEvent(e, &GatewayListener::onConnected);
}

void GatewayCommunicator::removeGateway(const GatewayID &id)
{
	FastMutex::ScopedLock guard(m_connectionMapMutex);

	auto it = m_connectionMap.find(id);
	if (it == m_connectionMap.end()) {
		logger().warning("gateway " + id.toString() + " not found",
			__FILE__, __LINE__);
		return;
	}

	it->second->removeFromReactor();
	m_connectionMap.erase(it);

	const GatewayEvent e(id);
	m_eventSource.fireEvent(e, &GatewayListener::onDisconnected);
}

void GatewayCommunicator::removeIfInactive(const GatewayID &id,
	const Timestamp &timeFrom)
{
	FastMutex::ScopedLock guard(m_connectionMapMutex);

	auto it = m_connectionMap.find(id);
	if (it == m_connectionMap.end()) {
		logger().warning("gateway " + id.toString() + " not found",
			__FILE__, __LINE__);
		return;
	}

	if (timeFrom < it->second->lastReceiveTime())
		return;

	it->second->removeFromReactor();
	m_connectionMap.erase(it);

	const GatewayEvent e(id);
	m_eventSource.fireEvent(e, &GatewayListener::onDisconnected);
}

GatewayConnection::Ptr GatewayCommunicator::findConnection(const GatewayID &id)
{
	FastMutex::ScopedLock guard(m_connectionMapMutex);

	auto it = m_connectionMap.find(id);
	if (it == m_connectionMap.end())
		throw NotFoundException("gateway: " + id.toString());

	return it->second;
}

void GatewayCommunicator::sendMessage(const GatewayID &gatewayID,
	const GWMessage::Ptr message)
{
	findConnection(gatewayID)->sendMessage(message);
}

void GatewayCommunicator::start()
{
	initPool();

	m_stop = false;

	m_reactorThread.start(m_reactor);
}

void GatewayCommunicator::stop()
{
	m_stop = true;

	m_reactor.stop();
	logger().information("waiting to join reactor thread", __FILE__, __LINE__);
	m_reactorThread.join();

	m_connectionReadableQueue.clear();

	logger().information("waiting to join worker threads", __FILE__, __LINE__);
	pool().joinAll();

	FastMutex::ScopedLock guard(m_connectionMapMutex);
	logger().notice("destroying " + to_string(m_connectionMap.size())
			+ " active connections", __FILE__, __LINE__);

	for (auto &it : m_connectionMap) {
		it.second->removeFromReactor();

		const GatewayEvent e(it.second->gatewayID());
		m_eventSource.fireEvent(e, &GatewayListener::onDisconnected);
	}

	m_connectionMap.clear();
}

void GatewayCommunicator::enqueueReadable(GatewayConnection::Ptr connection)
{
	connection->removeFromReactor();

	m_connectionReadableQueue.enqueue(connection);

	try {
		pool().start(m_workerRunnable);
	}
	catch (const NoThreadAvailableException &e) {
		logger().warning(e.displayText(), __FILE__, __LINE__);
		// All configured threads are busy and thus there is no need to start
		// threads anymore. The connection is already queued and thus some
		// thread would serve it soon.
	}
}

void GatewayCommunicator::runWorker()
{
	while (!m_stop) {
		GatewayConnection::Ptr connection = m_connectionReadableQueue.dequeue();

		if (!connection.isNull())
			handleConnectionReadable(connection);

		// Exit when there is nothing to be done. The thread is returned
		// into the pool.
		if (m_connectionReadableQueue.empty())
			break;
	}
}

void GatewayCommunicator::handleConnectionReadable(GatewayConnection::Ptr connection)
{
	static Occasionally occasionally;

	occasionally.execute([this]() {
		ScopedLockWithUnlock<FastMutex> guard(m_connectionMapMutex);
		int connections = m_connectionMap.size();
		guard.unlock();

		logger().notice(
			"active connections: " + to_string(connections)
			+ ", readable queue: " + to_string(m_connectionReadableQueue.size())
			+ ", thread pool allocated: " + to_string(pool().allocated())
			+ ", available: " + to_string(pool().available())
			+ ", capacity: " + to_string(pool().capacity()),
			__FILE__, __LINE__);
	});

	Thread::current()->setName("worker-" + connection->gatewayID().toString());
	const Clock started;

	try {
		GWMessage::Ptr message = connection->receiveMessage();
		connection->addToReactor();

		if (message.isNull())
			return;

		m_messageHandler->handle(message, connection->gatewayID());
	}
	catch (const Exception &e) {
		logger().log(e, __FILE__, __LINE__);
		removeGateway(connection->gatewayID());
	}

	if (logger().information()) {
		logger().information("duration: "
			+ to_string(started.elapsed()) + "us",
			__FILE__, __LINE__);
	}
}

void GatewayCommunicator::setGWMessageHandler(GWMessageHandler::Ptr handler)
{
	m_messageHandler = handler;
}

void GatewayCommunicator::setMaxMessageSize(int size)
{
	if (size < 0)
		throw InvalidArgumentException("size must be non negative");

	m_maxMessageSize = size;
}

void GatewayCommunicator::setReceiveTimeout(const Poco::Timespan &timeout)
{
	if (timeout < 0)
		throw InvalidArgumentException("receive timeout must be non negative");

	m_receiveTimeout = timeout;
}

void GatewayCommunicator::setSendTimeout(const Poco::Timespan &timeout)
{
	if (timeout < 0)
		throw InvalidArgumentException("send timeout must be non negative");

	m_sendTimeout = timeout;
}

GatewayCommunicator::ConnectionReadableQueue::~ConnectionReadableQueue()
{
	clear();
}

void GatewayCommunicator::ConnectionReadableQueue::enqueue(
	GatewayConnection::Ptr connection)
{
	FastMutex::ScopedLock guard(m_mutex);
	m_queue.push_back(connection);
}

GatewayConnection::Ptr GatewayCommunicator::ConnectionReadableQueue::dequeue()
{
	GatewayConnection::Ptr connection;

	FastMutex::ScopedLock guard(m_mutex);
	if (!m_queue.empty()) {
		connection = m_queue.front();
		m_queue.pop_front();
	}
	return connection;
}

bool GatewayCommunicator::ConnectionReadableQueue::empty() const
{
	FastMutex::ScopedLock guard(m_mutex);
	return m_queue.empty();
}

unsigned long GatewayCommunicator::ConnectionReadableQueue::size() const
{
	FastMutex::ScopedLock guard(m_mutex);
	return m_queue.size();
}

void GatewayCommunicator::ConnectionReadableQueue::clear()
{
	FastMutex::ScopedLock guard(m_mutex);
	m_queue.clear();
}
<commit_msg>GatewayCommunicator: fix missing catch blocks<commit_after>#include <Poco/Clock.h>
#include <Poco/Logger.h>
#include <Poco/Net/WebSocket.h>
#include <Poco/Net/NetException.h>

#include "di/Injectable.h"
#include "gws/GatewayCommunicator.h"

BEEEON_OBJECT_BEGIN(BeeeOn, GatewayCommunicator)
BEEEON_OBJECT_CASTABLE(StoppableLoop)
BEEEON_OBJECT_REF("messageHandler", &GatewayCommunicator::setGWMessageHandler)
BEEEON_OBJECT_NUMBER("maxMessageSize", &GatewayCommunicator::setMaxMessageSize)
BEEEON_OBJECT_TIME("receiveTimeout", &GatewayCommunicator::setReceiveTimeout)
BEEEON_OBJECT_TIME("sendTimeout", &GatewayCommunicator::setSendTimeout)
BEEEON_OBJECT_NUMBER("minThreads", &GatewayCommunicator::setMinThreads)
BEEEON_OBJECT_NUMBER("maxThreads", &GatewayCommunicator::setMaxThreads)
BEEEON_OBJECT_TIME("threadIdleTime", &GatewayCommunicator::setThreadIdleTime)
BEEEON_OBJECT_REF("asyncExecutor", &GatewayCommunicator::setAsyncExecutor)
BEEEON_OBJECT_REF("listeners", &GatewayCommunicator::registerListener)
BEEEON_OBJECT_END(BeeeOn, GatewayCommunicator)

using namespace std;
using namespace Poco;
using namespace Poco::Net;
using namespace BeeeOn;

GatewayCommunicator::GatewayCommunicator():
	m_maxMessageSize(4096),
	m_stop(false),
	m_workerRunnable(*this, &GatewayCommunicator::runWorker)
{
}

GatewayCommunicator::~GatewayCommunicator()
{
}

void GatewayCommunicator::registerListener(GatewayListener::Ptr listener)
{
	m_eventSource.addListener(listener);
}

void GatewayCommunicator::setAsyncExecutor(SharedPtr<AsyncExecutor> executor)
{
	m_eventSource.setAsyncExecutor(executor);
}

void GatewayCommunicator::addGateway(const GatewayID &gatewayID, WebSocket &webSocket)
{
	FastMutex::ScopedLock guard(m_connectionMapMutex);

	auto it = m_connectionMap.find(gatewayID);
	if (it != m_connectionMap.end()) {
		if (logger().debug()) {
			logger().debug("gateway " + gatewayID.toString()
					+ " found, using new connection", __FILE__, __LINE__);
		}

		it->second->removeFromReactor();
		m_connectionMap.erase(it);
	}

	webSocket.setReceiveTimeout(m_receiveTimeout);
	webSocket.setSendTimeout(m_sendTimeout);

	GatewayConnection::Ptr connection(
		new GatewayConnection(
			gatewayID,
			webSocket,
			m_reactor,
			[this](GatewayConnection::Ptr gatewayConnection)
			{
				enqueueReadable(gatewayConnection);
			},
			m_maxMessageSize
	));

	auto emplaced = m_connectionMap.emplace(gatewayID, connection);
	emplaced.first->second->addToReactor();

	GatewayEvent e(gatewayID);
	e.setSocketAddress(webSocket.peerAddress());

	if (it != m_connectionMap.end())
		m_eventSource.fireEvent(e, &GatewayListener::onReconnected);
	else
		m_eventSource.fireEvent(e, &GatewayListener::onConnected);
}

void GatewayCommunicator::removeGateway(const GatewayID &id)
{
	FastMutex::ScopedLock guard(m_connectionMapMutex);

	auto it = m_connectionMap.find(id);
	if (it == m_connectionMap.end()) {
		logger().warning("gateway " + id.toString() + " not found",
			__FILE__, __LINE__);
		return;
	}

	it->second->removeFromReactor();
	m_connectionMap.erase(it);

	const GatewayEvent e(id);
	m_eventSource.fireEvent(e, &GatewayListener::onDisconnected);
}

void GatewayCommunicator::removeIfInactive(const GatewayID &id,
	const Timestamp &timeFrom)
{
	FastMutex::ScopedLock guard(m_connectionMapMutex);

	auto it = m_connectionMap.find(id);
	if (it == m_connectionMap.end()) {
		logger().warning("gateway " + id.toString() + " not found",
			__FILE__, __LINE__);
		return;
	}

	if (timeFrom < it->second->lastReceiveTime())
		return;

	it->second->removeFromReactor();
	m_connectionMap.erase(it);

	const GatewayEvent e(id);
	m_eventSource.fireEvent(e, &GatewayListener::onDisconnected);
}

GatewayConnection::Ptr GatewayCommunicator::findConnection(const GatewayID &id)
{
	FastMutex::ScopedLock guard(m_connectionMapMutex);

	auto it = m_connectionMap.find(id);
	if (it == m_connectionMap.end())
		throw NotFoundException("gateway: " + id.toString());

	return it->second;
}

void GatewayCommunicator::sendMessage(const GatewayID &gatewayID,
	const GWMessage::Ptr message)
{
	findConnection(gatewayID)->sendMessage(message);
}

void GatewayCommunicator::start()
{
	initPool();

	m_stop = false;

	m_reactorThread.start(m_reactor);
}

void GatewayCommunicator::stop()
{
	m_stop = true;

	m_reactor.stop();
	logger().information("waiting to join reactor thread", __FILE__, __LINE__);
	m_reactorThread.join();

	m_connectionReadableQueue.clear();

	logger().information("waiting to join worker threads", __FILE__, __LINE__);
	pool().joinAll();

	FastMutex::ScopedLock guard(m_connectionMapMutex);
	logger().notice("destroying " + to_string(m_connectionMap.size())
			+ " active connections", __FILE__, __LINE__);

	for (auto &it : m_connectionMap) {
		it.second->removeFromReactor();

		const GatewayEvent e(it.second->gatewayID());
		m_eventSource.fireEvent(e, &GatewayListener::onDisconnected);
	}

	m_connectionMap.clear();
}

void GatewayCommunicator::enqueueReadable(GatewayConnection::Ptr connection)
{
	connection->removeFromReactor();

	m_connectionReadableQueue.enqueue(connection);

	try {
		pool().start(m_workerRunnable);
	}
	catch (const NoThreadAvailableException &e) {
		logger().warning(e.displayText(), __FILE__, __LINE__);
		// All configured threads are busy and thus there is no need to start
		// threads anymore. The connection is already queued and thus some
		// thread would serve it soon.
	}
}

void GatewayCommunicator::runWorker()
{
	while (!m_stop) {
		GatewayConnection::Ptr connection = m_connectionReadableQueue.dequeue();

		if (!connection.isNull())
			handleConnectionReadable(connection);

		// Exit when there is nothing to be done. The thread is returned
		// into the pool.
		if (m_connectionReadableQueue.empty())
			break;
	}
}

void GatewayCommunicator::handleConnectionReadable(GatewayConnection::Ptr connection)
{
	static Occasionally occasionally;

	occasionally.execute([this]() {
		ScopedLockWithUnlock<FastMutex> guard(m_connectionMapMutex);
		int connections = m_connectionMap.size();
		guard.unlock();

		logger().notice(
			"active connections: " + to_string(connections)
			+ ", readable queue: " + to_string(m_connectionReadableQueue.size())
			+ ", thread pool allocated: " + to_string(pool().allocated())
			+ ", available: " + to_string(pool().available())
			+ ", capacity: " + to_string(pool().capacity()),
			__FILE__, __LINE__);
	});

	Thread::current()->setName("worker-" + connection->gatewayID().toString());
	const Clock started;

	try {
		GWMessage::Ptr message = connection->receiveMessage();
		connection->addToReactor();

		if (message.isNull())
			return;

		m_messageHandler->handle(message, connection->gatewayID());
	}
	BEEEON_CATCH_CHAIN_ACTION(logger(), removeGateway(connection->gatewayID()));

	if (logger().information()) {
		logger().information("duration: "
			+ to_string(started.elapsed()) + "us",
			__FILE__, __LINE__);
	}
}

void GatewayCommunicator::setGWMessageHandler(GWMessageHandler::Ptr handler)
{
	m_messageHandler = handler;
}

void GatewayCommunicator::setMaxMessageSize(int size)
{
	if (size < 0)
		throw InvalidArgumentException("size must be non negative");

	m_maxMessageSize = size;
}

void GatewayCommunicator::setReceiveTimeout(const Poco::Timespan &timeout)
{
	if (timeout < 0)
		throw InvalidArgumentException("receive timeout must be non negative");

	m_receiveTimeout = timeout;
}

void GatewayCommunicator::setSendTimeout(const Poco::Timespan &timeout)
{
	if (timeout < 0)
		throw InvalidArgumentException("send timeout must be non negative");

	m_sendTimeout = timeout;
}

GatewayCommunicator::ConnectionReadableQueue::~ConnectionReadableQueue()
{
	clear();
}

void GatewayCommunicator::ConnectionReadableQueue::enqueue(
	GatewayConnection::Ptr connection)
{
	FastMutex::ScopedLock guard(m_mutex);
	m_queue.push_back(connection);
}

GatewayConnection::Ptr GatewayCommunicator::ConnectionReadableQueue::dequeue()
{
	GatewayConnection::Ptr connection;

	FastMutex::ScopedLock guard(m_mutex);
	if (!m_queue.empty()) {
		connection = m_queue.front();
		m_queue.pop_front();
	}
	return connection;
}

bool GatewayCommunicator::ConnectionReadableQueue::empty() const
{
	FastMutex::ScopedLock guard(m_mutex);
	return m_queue.empty();
}

unsigned long GatewayCommunicator::ConnectionReadableQueue::size() const
{
	FastMutex::ScopedLock guard(m_mutex);
	return m_queue.size();
}

void GatewayCommunicator::ConnectionReadableQueue::clear()
{
	FastMutex::ScopedLock guard(m_mutex);
	m_queue.clear();
}
<|endoftext|>


<commit_before>// This file was developed by Thomas Müller <thomas94@gmx.net>.
// It is published under the BSD 3-Clause License within the LICENSE file.

#include <tev/imageio/StbiImageLoader.h>
#include <tev/ThreadPool.h>

#include <stb_image.h>

using namespace Eigen;
using namespace std;

TEV_NAMESPACE_BEGIN

bool StbiImageLoader::canLoadFile(istream&) const {
    // Pretend you can load any file and throw exception on failure.
    // TODO: Add proper check.
    return true;
}

ImageData StbiImageLoader::load(istream& iStream, const filesystem::path&, const string& channelSelector) const {
    ImageData result;
    ThreadPool threadPool;

    static const stbi_io_callbacks callbacks = {
        // Read
        [](void* context, char* data, int size) {
            auto stream = reinterpret_cast<istream*>(context);
            stream->read(data, size);
            return (int)stream->gcount();
        },
        // Seek
        [](void* context, int size) {
            reinterpret_cast<istream*>(context)->seekg(size, ios_base::cur);
        },
        // EOF
        [](void* context) {
            return (int)!!(*reinterpret_cast<istream*>(context));
        },
    };

    void* data;
    int numChannels;
    Vector2i size;
    bool isHdr = stbi_is_hdr_from_callbacks(&callbacks, &iStream) != 0;
    iStream.clear();
    iStream.seekg(0);

    if (isHdr) {
        data = stbi_loadf_from_callbacks(&callbacks, &iStream, &size.x(), &size.y(), &numChannels, 0);
    } else {
        data = stbi_load_from_callbacks(&callbacks, &iStream, &size.x(), &size.y(), &numChannels, 0);
    }

    if (!data) {
        throw invalid_argument{tfm::format("%s", stbi_failure_reason())};
    }

    if (size.x() == 0 || size.y() == 0) {
        throw invalid_argument{"Image has zero pixels."};
    }

    ScopeGuard dataGuard{[data] { stbi_image_free(data); }};

    vector<Channel> channels = makeNChannels(numChannels, size);

    auto numPixels = (DenseIndex)size.x() * size.y();
    if (isHdr) {
        auto typedData = reinterpret_cast<float*>(data);
        threadPool.parallelFor<DenseIndex>(0, numPixels, [&](DenseIndex i) {
            int baseIdx = i * numChannels;
            for (int c = 0; c < numChannels; ++c) {
                channels[c].at(i) = typedData[baseIdx + c];
            }
        });
    } else {
        auto typedData = reinterpret_cast<unsigned char*>(data);
        threadPool.parallelFor<DenseIndex>(0, numPixels, [&](DenseIndex i) {
            int baseIdx = i * numChannels;
            for (int c = 0; c < numChannels; ++c) {
                channels[c].at(i) = toLinear((typedData[baseIdx + c]) / 255.0f);
            }
        });
    }

    vector<pair<size_t, size_t>> matches;
    for (size_t i = 0; i < channels.size(); ++i) {
        size_t matchId;
        if (matchesFuzzy(channels[i].name(), channelSelector, &matchId)) {
            matches.emplace_back(matchId, i);
        }
    }

    if (!channelSelector.empty()) {
        sort(begin(matches), end(matches));
    }

    for (const auto& match : matches) {
        result.channels.emplace_back(move(channels[match.second]));
    }

    // STBI can not load layers, so all channels simply reside
    // within a topmost root layer.
    result.layers.emplace_back("");

    return result;
}

TEV_NAMESPACE_END
<commit_msg>Fix incorrect STB inv-tonemap of alpha channel<commit_after>// This file was developed by Thomas Müller <thomas94@gmx.net>.
// It is published under the BSD 3-Clause License within the LICENSE file.

#include <tev/imageio/StbiImageLoader.h>
#include <tev/ThreadPool.h>

#include <stb_image.h>

using namespace Eigen;
using namespace std;

TEV_NAMESPACE_BEGIN

bool StbiImageLoader::canLoadFile(istream&) const {
    // Pretend you can load any file and throw exception on failure.
    // TODO: Add proper check.
    return true;
}

ImageData StbiImageLoader::load(istream& iStream, const filesystem::path&, const string& channelSelector) const {
    ImageData result;
    ThreadPool threadPool;

    static const stbi_io_callbacks callbacks = {
        // Read
        [](void* context, char* data, int size) {
            auto stream = reinterpret_cast<istream*>(context);
            stream->read(data, size);
            return (int)stream->gcount();
        },
        // Seek
        [](void* context, int size) {
            reinterpret_cast<istream*>(context)->seekg(size, ios_base::cur);
        },
        // EOF
        [](void* context) {
            return (int)!!(*reinterpret_cast<istream*>(context));
        },
    };

    void* data;
    int numChannels;
    Vector2i size;
    bool isHdr = stbi_is_hdr_from_callbacks(&callbacks, &iStream) != 0;
    iStream.clear();
    iStream.seekg(0);

    if (isHdr) {
        data = stbi_loadf_from_callbacks(&callbacks, &iStream, &size.x(), &size.y(), &numChannels, 0);
    } else {
        data = stbi_load_from_callbacks(&callbacks, &iStream, &size.x(), &size.y(), &numChannels, 0);
    }

    if (!data) {
        throw invalid_argument{tfm::format("%s", stbi_failure_reason())};
    }

    if (size.x() == 0 || size.y() == 0) {
        throw invalid_argument{"Image has zero pixels."};
    }

    ScopeGuard dataGuard{[data] { stbi_image_free(data); }};

    vector<Channel> channels = makeNChannels(numChannels, size);
    int alphaChannelIndex = 3;

    auto numPixels = (DenseIndex)size.x() * size.y();
    if (isHdr) {
        auto typedData = reinterpret_cast<float*>(data);
        threadPool.parallelFor<DenseIndex>(0, numPixels, [&](DenseIndex i) {
            int baseIdx = i * numChannels;
            for (int c = 0; c < numChannels; ++c) {
                channels[c].at(i) = typedData[baseIdx + c];
            }
        });
    } else {
        auto typedData = reinterpret_cast<unsigned char*>(data);
        threadPool.parallelFor<DenseIndex>(0, numPixels, [&](DenseIndex i) {
            int baseIdx = i * numChannels;
            for (int c = 0; c < numChannels; ++c) {
                if (c == alphaChannelIndex) {
                    channels[c].at(i) = (typedData[baseIdx + c]) / 255.0f;
                } else {
                    channels[c].at(i) = toLinear((typedData[baseIdx + c]) / 255.0f);
                }
            }
        });
    }

    vector<pair<size_t, size_t>> matches;
    for (size_t i = 0; i < channels.size(); ++i) {
        size_t matchId;
        if (matchesFuzzy(channels[i].name(), channelSelector, &matchId)) {
            matches.emplace_back(matchId, i);
        }
    }

    if (!channelSelector.empty()) {
        sort(begin(matches), end(matches));
    }

    for (const auto& match : matches) {
        result.channels.emplace_back(move(channels[match.second]));
    }

    // STBI can not load layers, so all channels simply reside
    // within a topmost root layer.
    result.layers.emplace_back("");

    return result;
}

TEV_NAMESPACE_END
<|endoftext|>


<commit_before>/* libwpd
 * Copyright (C) 2002 William Lachance (wrlach@gmail.com)
 * Copyright (C) 2002 Marc Maurer (uwog@uwog.net)
 * Copyright (C) 2007 Fridrich Strba (fridrich_strba@bluewin.ch)
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
 *
 * For further information visit http://libwpd.sourceforge.net
 */

/* "This product is not manufactured, approved, or supported by
 * Corel Corporation or Corel Corporation Limited."
 */

#include "WP6PrefixDataPacket.h"
#include "WP6PrefixIndice.h"
#include "WP6CommentAnnotationPacket.h"
#include "WP6GeneralTextPacket.h"
#include "WP6FontDescriptorPacket.h"
#include "WP6FillStylePacket.h"
#include "WP6DefaultInitialFontPacket.h"
#include "WP6ExtendedDocumentSummaryPacket.h"
#include "WP6OutlineStylePacket.h"
#include "WP6FileStructure.h"
#include "WP6GraphicsBoxStylePacket.h"
#include "WP6TableStylePacket.h"
#include "WP6GraphicsFilenamePacket.h"
#include "WP6GraphicsCachedFileDataPacket.h"
#include "libwpd_internal.h"

WP6PrefixDataPacket::WP6PrefixDataPacket(WPXInputStream * /* input */, WPXEncryption * /* encryption */) :
	m_dataSize(0)
{
}

WP6PrefixDataPacket * WP6PrefixDataPacket::constructPrefixDataPacket(WPXInputStream * input, WPXEncryption *encryption, WP6PrefixIndice *prefixIndice)
{
	switch (prefixIndice->getType())
	{
	case WP6_INDEX_HEADER_INITIAL_FONT:
		return new WP6DefaultInitialFontPacket(input, encryption, prefixIndice->getID(),
				prefixIndice->getDataOffset(), prefixIndice->getDataSize());
	case WP6_INDEX_HEADER_GENERAL_WORDPERFECT_TEXT:
		return new WP6GeneralTextPacket(input, encryption, prefixIndice->getID(),
				prefixIndice->getDataOffset(), prefixIndice->getDataSize());
	case WP6_INDEX_HEADER_DESIRED_FONT_DESCRIPTOR_POOL:
		return new WP6FontDescriptorPacket(input, encryption, prefixIndice->getID(),
				prefixIndice->getDataOffset(), prefixIndice->getDataSize());
	case WP6_INDEX_HEADER_FILL_STYLE:
		return new WP6FillStylePacket(input, encryption, prefixIndice->getID(),
				prefixIndice->getDataOffset(), prefixIndice->getDataSize());
	case WP6_INDEX_HEADER_EXTENDED_DOCUMENT_SUMMARY:
		return new WP6ExtendedDocumentSummaryPacket(input, encryption, prefixIndice->getID(),
				prefixIndice->getDataOffset(), prefixIndice->getDataSize());
	case WP6_INDEX_HEADER_OUTLINE_STYLE:
		return new WP6OutlineStylePacket(input, encryption, prefixIndice->getID(),
				prefixIndice->getDataOffset(), prefixIndice->getDataSize());
	case WP6_INDEX_HEADER_GRAPHICS_FILENAME:
		return new WP6GraphicsFilenamePacket(input, encryption, prefixIndice->getID(), prefixIndice->getFlags(),
				prefixIndice->getDataOffset(), prefixIndice->getDataSize());
	case WP6_INDEX_HEADER_GRAPHICS_CACHED_FILE_DATA:
		return new WP6GraphicsCachedFileDataPacket(input, encryption, prefixIndice->getID(),
				prefixIndice->getDataOffset(), prefixIndice->getDataSize());
	case WP6_INDEX_HEADER_GRAPHICS_BOX_STYLE:
		return new WP6GraphicsBoxStylePacket(input, encryption, prefixIndice->getID(),
				prefixIndice->getDataOffset(), prefixIndice->getDataSize());
	case WP6_INDEX_HEADER_TABLE_STYLE:
		return new WP6TableStylePacket(input, encryption, prefixIndice->getID(),
				prefixIndice->getDataOffset(), prefixIndice->getDataSize());
	case WP6_INDEX_HEADER_COMMENT_ANNOTATION:
		return new WP6CommentAnnotationPacket(input, encryption, prefixIndice->getID(),
				prefixIndice->getDataOffset(), prefixIndice->getDataSize());
	default:
		return 0;
	}
}

void WP6PrefixDataPacket::_read(WPXInputStream *input, WPXEncryption *encryption, uint32_t dataOffset, uint32_t dataSize)
{
	m_dataSize = dataSize;

	if (!m_dataSize)
		return;

	input->seek(dataOffset, WPX_SEEK_SET);

	_readContents(input, encryption);

	// assert that we haven't surpassed the size of the packet?
}
<commit_msg>Try to handle graciously corrupted prefix data packets<commit_after>/* libwpd
 * Copyright (C) 2002 William Lachance (wrlach@gmail.com)
 * Copyright (C) 2002 Marc Maurer (uwog@uwog.net)
 * Copyright (C) 2007 Fridrich Strba (fridrich_strba@bluewin.ch)
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
 *
 * For further information visit http://libwpd.sourceforge.net
 */

/* "This product is not manufactured, approved, or supported by
 * Corel Corporation or Corel Corporation Limited."
 */

#include "WP6PrefixDataPacket.h"
#include "WP6PrefixIndice.h"
#include "WP6CommentAnnotationPacket.h"
#include "WP6GeneralTextPacket.h"
#include "WP6FontDescriptorPacket.h"
#include "WP6FillStylePacket.h"
#include "WP6DefaultInitialFontPacket.h"
#include "WP6ExtendedDocumentSummaryPacket.h"
#include "WP6OutlineStylePacket.h"
#include "WP6FileStructure.h"
#include "WP6GraphicsBoxStylePacket.h"
#include "WP6TableStylePacket.h"
#include "WP6GraphicsFilenamePacket.h"
#include "WP6GraphicsCachedFileDataPacket.h"
#include "libwpd_internal.h"

WP6PrefixDataPacket::WP6PrefixDataPacket(WPXInputStream * /* input */, WPXEncryption * /* encryption */) :
	m_dataSize(0)
{
}

WP6PrefixDataPacket * WP6PrefixDataPacket::constructPrefixDataPacket(WPXInputStream * input, WPXEncryption *encryption, WP6PrefixIndice *prefixIndice)
{
	WP6PrefixDataPacket *tmpPacket = 0;
	try
	{
		switch (prefixIndice->getType())
		{
		case WP6_INDEX_HEADER_INITIAL_FONT:
			tmpPacket = new WP6DefaultInitialFontPacket(input, encryption, prefixIndice->getID(),
					prefixIndice->getDataOffset(), prefixIndice->getDataSize());
			break;
		case WP6_INDEX_HEADER_GENERAL_WORDPERFECT_TEXT:
			tmpPacket = new WP6GeneralTextPacket(input, encryption, prefixIndice->getID(),
					prefixIndice->getDataOffset(), prefixIndice->getDataSize());
			break;
		case WP6_INDEX_HEADER_DESIRED_FONT_DESCRIPTOR_POOL:
			tmpPacket = new WP6FontDescriptorPacket(input, encryption, prefixIndice->getID(),
					prefixIndice->getDataOffset(), prefixIndice->getDataSize());
			break;
		case WP6_INDEX_HEADER_FILL_STYLE:
			tmpPacket = new WP6FillStylePacket(input, encryption, prefixIndice->getID(),
					prefixIndice->getDataOffset(), prefixIndice->getDataSize());
			break;
		case WP6_INDEX_HEADER_EXTENDED_DOCUMENT_SUMMARY:
			tmpPacket = new WP6ExtendedDocumentSummaryPacket(input, encryption, prefixIndice->getID(),
					prefixIndice->getDataOffset(), prefixIndice->getDataSize());
			break;
		case WP6_INDEX_HEADER_OUTLINE_STYLE:
			tmpPacket = new WP6OutlineStylePacket(input, encryption, prefixIndice->getID(),
					prefixIndice->getDataOffset(), prefixIndice->getDataSize());
			break;
		case WP6_INDEX_HEADER_GRAPHICS_FILENAME:
			tmpPacket = new WP6GraphicsFilenamePacket(input, encryption, prefixIndice->getID(), prefixIndice->getFlags(),
					prefixIndice->getDataOffset(), prefixIndice->getDataSize());
			break;
		case WP6_INDEX_HEADER_GRAPHICS_CACHED_FILE_DATA:
			tmpPacket = new WP6GraphicsCachedFileDataPacket(input, encryption, prefixIndice->getID(),
					prefixIndice->getDataOffset(), prefixIndice->getDataSize());
			break;
		case WP6_INDEX_HEADER_GRAPHICS_BOX_STYLE:
			tmpPacket = new WP6GraphicsBoxStylePacket(input, encryption, prefixIndice->getID(),
					prefixIndice->getDataOffset(), prefixIndice->getDataSize());
			break;
		case WP6_INDEX_HEADER_TABLE_STYLE:
			tmpPacket = new WP6TableStylePacket(input, encryption, prefixIndice->getID(),
					prefixIndice->getDataOffset(), prefixIndice->getDataSize());
			break;
		case WP6_INDEX_HEADER_COMMENT_ANNOTATION:
			tmpPacket = new WP6CommentAnnotationPacket(input, encryption, prefixIndice->getID(),
					prefixIndice->getDataOffset(), prefixIndice->getDataSize());
			break;
		default:
			break;;
		}
	}
	catch (FileException)
	{
		if (tmpPacket)
			delete tmpPacket;
		tmpPacket = 0;
	}
	return tmpPacket;
}

void WP6PrefixDataPacket::_read(WPXInputStream *input, WPXEncryption *encryption, uint32_t dataOffset, uint32_t dataSize)
{
	m_dataSize = dataSize;

	if (!m_dataSize)
		return;

	input->seek(dataOffset, WPX_SEEK_SET);

	_readContents(input, encryption);

	// assert that we haven't surpassed the size of the packet?
}
<|endoftext|>


<commit_before>/****************************************************************************
 *
 *   Copyright (C) 2013 PX4 Development Team. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 * 3. Neither the name PX4 nor the names of its contributors may be
 *    used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 ****************************************************************************/

/**
 * @file rotation.cpp
 *
 * Vector rotation library
 */

#include <px4_platform_common/defines.h>
#include "math.h"
#include "rotation.h"

__EXPORT matrix::Dcmf
get_rot_matrix(enum Rotation rot)
{
	return matrix::Dcmf{matrix::Eulerf{
			math::radians((float)rot_lookup[rot].roll),
			math::radians((float)rot_lookup[rot].pitch),
			math::radians((float)rot_lookup[rot].yaw)}};
}

__EXPORT matrix::Quatf
get_rot_quaternion(enum Rotation rot)
{
	return matrix::Quatf{matrix::Eulerf{
			math::radians((float)rot_lookup[rot].roll),
			math::radians((float)rot_lookup[rot].pitch),
			math::radians((float)rot_lookup[rot].yaw)}};
}

__EXPORT void
rotate_3f(enum Rotation rot, float &x, float &y, float &z)
{
	float tmp;

	switch (rot) {
	case ROTATION_NONE:
	case ROTATION_MAX:
		return;

	case ROTATION_YAW_45: {
			tmp = M_SQRT1_2_F * (x - y);
			y   = M_SQRT1_2_F * (x + y);
			x = tmp;
			return;
		}

	case ROTATION_YAW_90: {
			tmp = x; x = -y; y = tmp;
			return;
		}

	case ROTATION_YAW_135: {
			tmp = -M_SQRT1_2_F * (x + y);
			y   =  M_SQRT1_2_F * (x - y);
			x = tmp;
			return;
		}

	case ROTATION_YAW_180:
		x = -x; y = -y;
		return;

	case ROTATION_YAW_225: {
			tmp = M_SQRT1_2_F * (y - x);
			y   = -M_SQRT1_2_F * (x + y);
			x = tmp;
			return;
		}

	case ROTATION_YAW_270: {
			tmp = x; x = y; y = -tmp;
			return;
		}

	case ROTATION_YAW_315: {
			tmp = M_SQRT1_2_F * (x + y);
			y   = M_SQRT1_2_F * (y - x);
			x = tmp;
			return;
		}

	case ROTATION_ROLL_180: {
			y = -y; z = -z;
			return;
		}

	case ROTATION_ROLL_180_YAW_45: {
			tmp = M_SQRT1_2_F * (x + y);
			y   = M_SQRT1_2_F * (x - y);
			x = tmp; z = -z;
			return;
		}

	case ROTATION_ROLL_180_YAW_90: {
			tmp = x; x = y; y = tmp; z = -z;
			return;
		}

	case ROTATION_ROLL_180_YAW_135: {
			tmp = M_SQRT1_2_F * (y - x);
			y   = M_SQRT1_2_F * (y + x);
			x = tmp; z = -z;
			return;
		}

	case ROTATION_PITCH_180: {
			x = -x; z = -z;
			return;
		}

	case ROTATION_ROLL_180_YAW_225: {
			tmp = -M_SQRT1_2_F * (x + y);
			y   =  M_SQRT1_2_F * (y - x);
			x = tmp; z = -z;
			return;
		}

	case ROTATION_ROLL_180_YAW_270: {
			tmp = x; x = -y; y = -tmp; z = -z;
			return;
		}

	case ROTATION_ROLL_180_YAW_315: {
			tmp =  M_SQRT1_2_F * (x - y);
			y   = -M_SQRT1_2_F * (x + y);
			x = tmp; z = -z;
			return;
		}

	case ROTATION_ROLL_90: {
			tmp = z; z = y; y = -tmp;
			return;
		}

	case ROTATION_ROLL_90_YAW_45: {
			tmp = z; z = y; y = -tmp;
			tmp = M_SQRT1_2_F * (x - y);
			y   = M_SQRT1_2_F * (x + y);
			x = tmp;
			return;
		}

	case ROTATION_ROLL_90_YAW_90: {
			tmp = x;
			x = z;
			z = y;
			y = tmp;
			return;
		}

	case ROTATION_ROLL_90_YAW_135: {
			tmp = z; z = y; y = -tmp;
			tmp = -M_SQRT1_2_F * (x + y);
			y   =  M_SQRT1_2_F * (x - y);
			x = tmp;
			return;
		}

	case ROTATION_ROLL_270: {
			tmp = z; z = -y; y = tmp;
			return;
		}

	case ROTATION_ROLL_270_YAW_45: {
			tmp = z; z = -y; y = tmp;
			tmp = M_SQRT1_2_F * (x - y);
			y   = M_SQRT1_2_F * (x + y);
			x = tmp;
			return;
		}

	case ROTATION_ROLL_270_YAW_90: {
			tmp = x;
			x = -z;
			z = -y;
			y = tmp;
			return;
		}

	case ROTATION_ROLL_270_YAW_135: {
			tmp = z; z = -y; y = tmp;
			tmp = -M_SQRT1_2_F * (x + y);
			y   =  M_SQRT1_2_F * (x - y);
			x = tmp;
			return;
		}

	case ROTATION_ROLL_270_YAW_270: {
			tmp = x;
			x = z;
			z = -y;
			y = -tmp;
			return;
		}

	case ROTATION_PITCH_90: {
			tmp = z; z = -x; x = tmp;
			return;
		}

	case ROTATION_PITCH_270: {
			tmp = z; z = x; x = -tmp;
			return;
		}

	case ROTATION_ROLL_180_PITCH_270: {
			tmp = z; z = x; x = tmp;
			y = -y;
			return;
		}

	case ROTATION_PITCH_90_YAW_180: {
			tmp = x;
			x = -z;
			y = -y;
			z = -tmp;
			return;
		}

	case ROTATION_PITCH_9_YAW_180: {
			const float tmpx = x;
			const float tmpy = y;
			const float tmpz = z;
			x = -0.987688f * tmpx +  0.000000f * tmpy + -0.156434f * tmpz;
			y =  0.000000f * tmpx + -1.000000f * tmpy +  0.000000f * tmpz;
			z = -0.156434f * tmpx +  0.000000f * tmpy +  0.987688f * tmpz;
			return;
		}

	case ROTATION_PITCH_45: {
			tmp = M_SQRT1_2_F * x + M_SQRT1_2_F * z;
			z = M_SQRT1_2_F * z - M_SQRT1_2_F * x;
			x = tmp;
			return;
		}

	case ROTATION_PITCH_315: {
			tmp = M_SQRT1_2_F * x - M_SQRT1_2_F * z;
			z = M_SQRT1_2_F * z + M_SQRT1_2_F * x;
			x = tmp;
			return;
		}

	case ROTATION_ROLL_90_YAW_270: {
			tmp = x;
			x = -z;
			z = y;
			y = -tmp;
			return;
		}

	case ROTATION_ROLL_270_YAW_180: {
			x = -x;
			tmp = y;
			y = -z;
			z = -tmp;
			return;
		}

	case ROTATION_PITCH_180_YAW_90: {
			tmp = x;
			x = -y;
			y = -tmp;
			z = -z;
			return;
		}

	case ROTATION_PITCH_180_YAW_270: {
			tmp = x;
			x = y;
			y = tmp;
			z = -z;
			return;
		}

	case ROTATION_ROLL_90_PITCH_90: {
			tmp = x;
			x = y;
			y = -z;
			z = -tmp;
			return;
		}

	case ROTATION_ROLL_180_PITCH_90: {
			tmp = x;
			x = -z;
			y = -y;
			z = -tmp;
			return;
		}

	case ROTATION_ROLL_270_PITCH_90: {
			tmp = x;
			x = -y;
			y = z;
			z = -tmp;
			return;
		}

	case ROTATION_ROLL_90_PITCH_180: {
			tmp = y;
			x = -x;
			y = -z;
			z = -tmp;
			return;
		}

	case ROTATION_ROLL_270_PITCH_180: {
			tmp = y;
			x = -x;
			y = z;
			z = tmp;
			return;
		}

	case ROTATION_ROLL_90_PITCH_270: {
			tmp = x;
			x = -y;
			y = -z;
			z = tmp;
			return;
		}

	case ROTATION_ROLL_270_PITCH_270: {
			tmp = x;
			x = y;
			y = z;
			z = tmp;
			return;
		}

	case ROTATION_ROLL_90_PITCH_180_YAW_90: {
			tmp = y;
			y = -x;
			x = z;
			z = -tmp;
			return;
		}

	case ROTATION_ROLL_90_PITCH_68_YAW_293: {
			const float tmpx = x;
			const float tmpy = y;
			const float tmpz = z;
			x = 0.146371f * tmpx + 0.362280f * tmpy - 0.920505f * tmpz;
			y = -0.344827f * tmpx - 0.853477f * tmpy - 0.390731f * tmpz;
			z = -0.927184f * tmpx + 0.374607f * tmpy;
			return;
		}

	case ROTATION_ROLL_90_PITCH_315: {
			const float tmpx = x;
			const float tmpy = y;
			const float tmpz = z;
			x = 0.707107f * tmpx - 0.707107f * tmpy;
			y = -tmpz;
			z = 0.707107f * tmpx + 0.707107f * tmpy;
			return;
		}

	}
}
<commit_msg>rotation: combine duplicates<commit_after>/****************************************************************************
 *
 *   Copyright (C) 2013 PX4 Development Team. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 * 3. Neither the name PX4 nor the names of its contributors may be
 *    used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 ****************************************************************************/

/**
 * @file rotation.cpp
 *
 * Vector rotation library
 */

#include <px4_platform_common/defines.h>
#include "math.h"
#include "rotation.h"

__EXPORT matrix::Dcmf
get_rot_matrix(enum Rotation rot)
{
	return matrix::Dcmf{matrix::Eulerf{
			math::radians((float)rot_lookup[rot].roll),
			math::radians((float)rot_lookup[rot].pitch),
			math::radians((float)rot_lookup[rot].yaw)}};
}

__EXPORT matrix::Quatf
get_rot_quaternion(enum Rotation rot)
{
	return matrix::Quatf{matrix::Eulerf{
			math::radians((float)rot_lookup[rot].roll),
			math::radians((float)rot_lookup[rot].pitch),
			math::radians((float)rot_lookup[rot].yaw)}};
}

__EXPORT void
rotate_3f(enum Rotation rot, float &x, float &y, float &z)
{
	float tmp;

	switch (rot) {
	case ROTATION_NONE:
	case ROTATION_MAX:
		return;

	case ROTATION_YAW_45: {
			tmp = M_SQRT1_2_F * (x - y);
			y   = M_SQRT1_2_F * (x + y);
			x = tmp;
			return;
		}

	case ROTATION_YAW_90: {
			tmp = x; x = -y; y = tmp;
			return;
		}

	case ROTATION_YAW_135: {
			tmp = -M_SQRT1_2_F * (x + y);
			y   =  M_SQRT1_2_F * (x - y);
			x = tmp;
			return;
		}

	case ROTATION_YAW_180:
		x = -x; y = -y;
		return;

	case ROTATION_YAW_225: {
			tmp = M_SQRT1_2_F * (y - x);
			y   = -M_SQRT1_2_F * (x + y);
			x = tmp;
			return;
		}

	case ROTATION_YAW_270: {
			tmp = x; x = y; y = -tmp;
			return;
		}

	case ROTATION_YAW_315: {
			tmp = M_SQRT1_2_F * (x + y);
			y   = M_SQRT1_2_F * (y - x);
			x = tmp;
			return;
		}

	case ROTATION_ROLL_180: {
			y = -y; z = -z;
			return;
		}

	case ROTATION_ROLL_180_YAW_45: {
			tmp = M_SQRT1_2_F * (x + y);
			y   = M_SQRT1_2_F * (x - y);
			x = tmp; z = -z;
			return;
		}

	case ROTATION_ROLL_180_YAW_90:

	// FALLTHROUGH
	case ROTATION_PITCH_180_YAW_270: {
			tmp = x;
			x = y;
			y = tmp;
			z = -z;
			return;
		}

	case ROTATION_ROLL_180_YAW_135: {
			tmp = M_SQRT1_2_F * (y - x);
			y   = M_SQRT1_2_F * (y + x);
			x = tmp; z = -z;
			return;
		}

	case ROTATION_PITCH_180: {
			x = -x; z = -z;
			return;
		}

	case ROTATION_ROLL_180_YAW_225: {
			tmp = -M_SQRT1_2_F * (x + y);
			y   =  M_SQRT1_2_F * (y - x);
			x = tmp; z = -z;
			return;
		}

	case ROTATION_ROLL_180_YAW_270:

	// FALLTHROUGH
	case ROTATION_PITCH_180_YAW_90: {
			tmp = x;
			x = -y;
			y = -tmp;
			z = -z;
			return;
		}

	case ROTATION_ROLL_180_YAW_315: {
			tmp =  M_SQRT1_2_F * (x - y);
			y   = -M_SQRT1_2_F * (x + y);
			x = tmp; z = -z;
			return;
		}

	case ROTATION_ROLL_90: {
			tmp = z; z = y; y = -tmp;
			return;
		}

	case ROTATION_ROLL_90_YAW_45: {
			tmp = z; z = y; y = -tmp;
			tmp = M_SQRT1_2_F * (x - y);
			y   = M_SQRT1_2_F * (x + y);
			x = tmp;
			return;
		}

	case ROTATION_ROLL_90_YAW_90: {
			tmp = x;
			x = z;
			z = y;
			y = tmp;
			return;
		}

	case ROTATION_ROLL_90_YAW_135: {
			tmp = z; z = y; y = -tmp;
			tmp = -M_SQRT1_2_F * (x + y);
			y   =  M_SQRT1_2_F * (x - y);
			x = tmp;
			return;
		}

	case ROTATION_ROLL_270: {
			tmp = z; z = -y; y = tmp;
			return;
		}

	case ROTATION_ROLL_270_YAW_45: {
			tmp = z; z = -y; y = tmp;
			tmp = M_SQRT1_2_F * (x - y);
			y   = M_SQRT1_2_F * (x + y);
			x = tmp;
			return;
		}

	case ROTATION_ROLL_270_YAW_90: {
			tmp = x;
			x = -z;
			z = -y;
			y = tmp;
			return;
		}

	case ROTATION_ROLL_270_YAW_135: {
			tmp = z; z = -y; y = tmp;
			tmp = -M_SQRT1_2_F * (x + y);
			y   =  M_SQRT1_2_F * (x - y);
			x = tmp;
			return;
		}

	case ROTATION_PITCH_90: {
			tmp = z; z = -x; x = tmp;
			return;
		}

	case ROTATION_PITCH_270: {
			tmp = z; z = x; x = -tmp;
			return;
		}

	case ROTATION_ROLL_180_PITCH_270: {
			tmp = z; z = x; x = tmp;
			y = -y;
			return;
		}

	case ROTATION_PITCH_9_YAW_180: {
			const float tmpx = x;
			const float tmpy = y;
			const float tmpz = z;
			x = -0.987688f * tmpx +  0.000000f * tmpy + -0.156434f * tmpz;
			y =  0.000000f * tmpx + -1.000000f * tmpy +  0.000000f * tmpz;
			z = -0.156434f * tmpx +  0.000000f * tmpy +  0.987688f * tmpz;
			return;
		}

	case ROTATION_PITCH_45: {
			tmp = M_SQRT1_2_F * x + M_SQRT1_2_F * z;
			z = M_SQRT1_2_F * z - M_SQRT1_2_F * x;
			x = tmp;
			return;
		}

	case ROTATION_PITCH_315: {
			tmp = M_SQRT1_2_F * x - M_SQRT1_2_F * z;
			z = M_SQRT1_2_F * z + M_SQRT1_2_F * x;
			x = tmp;
			return;
		}

	case ROTATION_ROLL_90_YAW_270: {
			tmp = x;
			x = -z;
			z = y;
			y = -tmp;
			return;
		}

	case ROTATION_ROLL_90_PITCH_90: {
			tmp = x;
			x = y;
			y = -z;
			z = -tmp;
			return;
		}

	case ROTATION_ROLL_180_PITCH_90:

	// FALLTHROUGH
	case ROTATION_PITCH_90_YAW_180: {
			tmp = x;
			x = -z;
			y = -y;
			z = -tmp;
			return;
		}

	case ROTATION_ROLL_270_PITCH_90: {
			tmp = x;
			x = -y;
			y = z;
			z = -tmp;
			return;
		}

	case ROTATION_ROLL_90_PITCH_180:

	// FALLTHROUGH
	case ROTATION_ROLL_270_YAW_180: {
			tmp = y;
			x = -x;
			y = -z;
			z = -tmp;
			return;
		}

	case ROTATION_ROLL_270_PITCH_180: {
			tmp = y;
			x = -x;
			y = z;
			z = tmp;
			return;
		}

	case ROTATION_ROLL_90_PITCH_270: {
			tmp = x;
			x = -y;
			y = -z;
			z = tmp;
			return;
		}

	case ROTATION_ROLL_270_PITCH_270: {
			tmp = x;
			x = y;
			y = z;
			z = tmp;
			return;
		}

	case ROTATION_ROLL_90_PITCH_180_YAW_90:

	// FALLTHROUGH
	case ROTATION_ROLL_270_YAW_270: {
			tmp = x;
			x = z;
			z = -y;
			y = -tmp;
			return;
		}

	case ROTATION_ROLL_90_PITCH_68_YAW_293: {
			const float tmpx = x;
			const float tmpy = y;
			const float tmpz = z;
			x = 0.146371f * tmpx + 0.362280f * tmpy - 0.920505f * tmpz;
			y = -0.344827f * tmpx - 0.853477f * tmpy - 0.390731f * tmpz;
			z = -0.927184f * tmpx + 0.374607f * tmpy;
			return;
		}

	case ROTATION_ROLL_90_PITCH_315: {
			const float tmpx = x;
			const float tmpy = y;
			const float tmpz = z;
			x = 0.707107f * tmpx - 0.707107f * tmpy;
			y = -tmpz;
			z = 0.707107f * tmpx + 0.707107f * tmpy;
			return;
		}

	}
}
<|endoftext|>


<commit_before>/****************************************************************************
 *
 *   Copyright (c) 2012-2014 PX4 Development Team. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 * 3. Neither the name PX4 nor the names of its contributors may be
 *    used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 ****************************************************************************/

/**
 * @file CDev.cpp
 *
 * Character device base class.
 */

#include "CDev.hpp"

#include <cstring>

#include "px4_posix.h"
#include "drivers/drv_device.h"

namespace device
{

CDev::CDev(const char *name, const char *devname) :
	Device(name),
	_devname(devname)
{
	DEVICE_DEBUG("CDev::CDev");

	int ret = px4_sem_init(&_lock, 0, 1);

	if (ret != 0) {
		PX4_WARN("SEM INIT FAIL: ret %d", ret);
	}
}

CDev::~CDev()
{
	DEVICE_DEBUG("CDev::~CDev");

	if (_registered) {
		unregister_driver(_devname);
	}

	if (_pollset) {
		delete[](_pollset);
	}

	px4_sem_destroy(&_lock);
}

int
CDev::register_class_devname(const char *class_devname)
{
	DEVICE_DEBUG("CDev::register_class_devname %s", class_devname);

	if (class_devname == nullptr) {
		return -EINVAL;
	}

	int class_instance = 0;
	int ret = -ENOSPC;

	while (class_instance < 4) {
		char name[32];
		snprintf(name, sizeof(name), "%s%d", class_devname, class_instance);
		ret = register_driver(name, &fops, 0666, (void *)this);

		if (ret == OK) {
			break;
		}

		class_instance++;
	}

	if (class_instance == 4) {
		return ret;
	}

	return class_instance;
}

int
CDev::unregister_class_devname(const char *class_devname, unsigned class_instance)
{
	DEVICE_DEBUG("CDev::unregister_class_devname");
	char name[32];
	snprintf(name, sizeof(name), "%s%u", class_devname, class_instance);
	return unregister_driver(name);
}

int
CDev::init()
{
	DEVICE_DEBUG("CDev::init");

	// base class init first
	int ret = Device::init();

	if (ret != PX4_OK) {
		goto out;
	}

	// now register the driver
	if (_devname != nullptr) {
		ret = register_driver(_devname, &fops, 0666, (void *)this);

		if (ret != PX4_OK) {
			goto out;
		}

		_registered = true;
	}

out:
	return ret;
}

/*
 * Default implementations of the character device interface
 */
int
CDev::open(file_t *filep)
{
	DEVICE_DEBUG("CDev::open");
	int ret = PX4_OK;

	lock();
	/* increment the open count */
	_open_count++;

	if (_open_count == 1) {

		/* first-open callback may decline the open */
		ret = open_first(filep);

		if (ret != PX4_OK) {
			_open_count--;
		}
	}

	unlock();

	return ret;
}

int
CDev::open_first(file_t *filep)
{
	DEVICE_DEBUG("CDev::open_first");
	return PX4_OK;
}

int
CDev::close(file_t *filep)
{
	DEVICE_DEBUG("CDev::close");
	int ret = PX4_OK;

	lock();

	if (_open_count > 0) {
		/* decrement the open count */
		_open_count--;

		/* callback cannot decline the close */
		if (_open_count == 0) {
			ret = close_last(filep);
		}

	} else {
		ret = -EBADF;
	}

	unlock();

	return ret;
}

int
CDev::close_last(file_t *filep)
{
	DEVICE_DEBUG("CDev::close_last");
	return PX4_OK;
}

ssize_t
CDev::read(file_t *filep, char *buffer, size_t buflen)
{
	DEVICE_DEBUG("CDev::read");
	return -ENOSYS;
}

ssize_t
CDev::write(file_t *filep, const char *buffer, size_t buflen)
{
	DEVICE_DEBUG("CDev::write");
	return -ENOSYS;
}

off_t
CDev::seek(file_t *filep, off_t offset, int whence)
{
	DEVICE_DEBUG("CDev::seek");
	return -ENOSYS;
}

int
CDev::ioctl(file_t *filep, int cmd, unsigned long arg)
{
	DEVICE_DEBUG("CDev::ioctl");
	int ret = -ENOTTY;

	switch (cmd) {

	/* fetch a pointer to the driver's private data */
	case DIOC_GETPRIV:
		*(void **)(uintptr_t)arg = (void *)this;
		ret = PX4_OK;
		break;

	case DEVIOCSPUBBLOCK:
		_pub_blocked = (arg != 0);
		ret = PX4_OK;
		break;

	case DEVIOCGPUBBLOCK:
		ret = _pub_blocked;
		break;

	case DEVIOCGDEVICEID:
		ret = (int)_device_id.devid;
		break;

	default:
		break;
	}

	return ret;
}

int
CDev::poll(file_t *filep, px4_pollfd_struct_t *fds, bool setup)
{
	DEVICE_DEBUG("CDev::Poll %s", setup ? "setup" : "teardown");
	int ret = PX4_OK;

	if (setup) {
		/*
		 * Save the file pointer in the pollfd for the subclass'
		 * benefit.
		 */
		fds->priv = (void *)filep;
		DEVICE_DEBUG("CDev::poll: fds->priv = %p", filep);

		/*
		 * Lock against poll_notify() and possibly other callers.
		 */
		ATOMIC_ENTER;

		/*
		 * Try to store the fds for later use and handle array resizing.
		 */
		while ((ret = store_poll_waiter(fds)) == -ENFILE) {

			// No free slot found. Resize the pollset. This is expensive, but it's only needed initially.

			if (_max_pollwaiters >= 256 / 2) { //_max_pollwaiters is uint8_t
				ret = -ENOMEM;
				break;
			}

			const uint8_t new_count = _max_pollwaiters > 0 ? _max_pollwaiters * 2 : 1;
			px4_pollfd_struct_t **prev_pollset = _pollset;

#ifdef __PX4_NUTTX
			// malloc uses a semaphore, we need to call it enabled IRQ's
			px4_leave_critical_section(flags);
#endif
			px4_pollfd_struct_t **new_pollset = new px4_pollfd_struct_t *[new_count];

#ifdef __PX4_NUTTX
			flags = px4_enter_critical_section();
#endif

			if (prev_pollset == _pollset) {
				// no one else updated the _pollset meanwhile, so we're good to go
				if (!new_pollset) {
					ret = -ENOMEM;
					break;
				}

				if (_max_pollwaiters > 0) {
					memset(new_pollset + _max_pollwaiters, 0, sizeof(px4_pollfd_struct_t *) * (new_count - _max_pollwaiters));
					memcpy(new_pollset, _pollset, sizeof(px4_pollfd_struct_t *) * _max_pollwaiters);
					delete[](_pollset);
				}

				_pollset = new_pollset;
				_pollset[_max_pollwaiters] = fds;
				_max_pollwaiters = new_count;

				// Success
				ret = PX4_OK;
				break;
			}

#ifdef __PX4_NUTTX
			px4_leave_critical_section(flags);
#endif
			// We have to retry
			delete[] new_pollset;
#ifdef __PX4_NUTTX
			flags = px4_enter_critical_section();
#endif
		}

		if (ret == PX4_OK) {

			/*
			 * Check to see whether we should send a poll notification
			 * immediately.
			 */
			fds->revents |= fds->events & poll_state(filep);

			/* yes? post the notification */
			if (fds->revents != 0) {
				px4_sem_post(fds->sem);
			}

		} else {
			PX4_WARN("Store Poll Waiter error.");
		}

		ATOMIC_LEAVE;

	} else {
		ATOMIC_ENTER;
		/*
		 * Handle a teardown request.
		 */
		ret = remove_poll_waiter(fds);
		ATOMIC_LEAVE;
	}

	return ret;
}

void
CDev::poll_notify(pollevent_t events)
{
	DEVICE_DEBUG("CDev::poll_notify events = %0x", events);

	/* lock against poll() as well as other wakeups */
	ATOMIC_ENTER;

	for (unsigned i = 0; i < _max_pollwaiters; i++) {
		if (nullptr != _pollset[i]) {
			poll_notify_one(_pollset[i], events);
		}
	}

	ATOMIC_LEAVE;
}

void
CDev::poll_notify_one(px4_pollfd_struct_t *fds, pollevent_t events)
{
	DEVICE_DEBUG("CDev::poll_notify_one");

#ifdef __PX4_NUTTX
	int value = fds->sem->semcount;
#else
	int value = -1;
	px4_sem_getvalue(fds->sem, &value);
#endif

	/* update the reported event set */
	fds->revents |= fds->events & events;

	DEVICE_DEBUG(" Events fds=%p %0x %0x %0x %d", fds, fds->revents, fds->events, events, value);

	/* if the state is now interesting, wake the waiter if it's still asleep */
	/* XXX semcount check here is a vile hack; counting semphores should not be abused as cvars */
	if ((fds->revents != 0) && (value <= 0)) {
		px4_sem_post(fds->sem);
	}
}

pollevent_t
CDev::poll_state(file_t *filep)
{
	DEVICE_DEBUG("CDev::poll_notify");
	/* by default, no poll events to report */
	return 0;
}

int
CDev::store_poll_waiter(px4_pollfd_struct_t *fds)
{
	/*
	 * Look for a free slot.
	 */
	DEVICE_DEBUG("CDev::store_poll_waiter");

	for (unsigned i = 0; i < _max_pollwaiters; i++) {
		if (nullptr == _pollset[i]) {

			/* save the pollfd */
			_pollset[i] = fds;

			return PX4_OK;
		}
	}

	return -ENFILE;
}

int
CDev::remove_poll_waiter(px4_pollfd_struct_t *fds)
{
	DEVICE_DEBUG("CDev::remove_poll_waiter");

	for (unsigned i = 0; i < _max_pollwaiters; i++) {
		if (fds == _pollset[i]) {

			_pollset[i] = nullptr;
			return PX4_OK;

		}
	}

	PX4_WARN("poll: bad fd state");
	return -EINVAL;
}

} // namespace device
<commit_msg>CDev::poll_notify_one: remove checking the semaphore counter<commit_after>/****************************************************************************
 *
 *   Copyright (c) 2012-2014 PX4 Development Team. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 * 3. Neither the name PX4 nor the names of its contributors may be
 *    used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 ****************************************************************************/

/**
 * @file CDev.cpp
 *
 * Character device base class.
 */

#include "CDev.hpp"

#include <cstring>

#include "px4_posix.h"
#include "drivers/drv_device.h"

namespace device
{

CDev::CDev(const char *name, const char *devname) :
	Device(name),
	_devname(devname)
{
	DEVICE_DEBUG("CDev::CDev");

	int ret = px4_sem_init(&_lock, 0, 1);

	if (ret != 0) {
		PX4_WARN("SEM INIT FAIL: ret %d", ret);
	}
}

CDev::~CDev()
{
	DEVICE_DEBUG("CDev::~CDev");

	if (_registered) {
		unregister_driver(_devname);
	}

	if (_pollset) {
		delete[](_pollset);
	}

	px4_sem_destroy(&_lock);
}

int
CDev::register_class_devname(const char *class_devname)
{
	DEVICE_DEBUG("CDev::register_class_devname %s", class_devname);

	if (class_devname == nullptr) {
		return -EINVAL;
	}

	int class_instance = 0;
	int ret = -ENOSPC;

	while (class_instance < 4) {
		char name[32];
		snprintf(name, sizeof(name), "%s%d", class_devname, class_instance);
		ret = register_driver(name, &fops, 0666, (void *)this);

		if (ret == OK) {
			break;
		}

		class_instance++;
	}

	if (class_instance == 4) {
		return ret;
	}

	return class_instance;
}

int
CDev::unregister_class_devname(const char *class_devname, unsigned class_instance)
{
	DEVICE_DEBUG("CDev::unregister_class_devname");
	char name[32];
	snprintf(name, sizeof(name), "%s%u", class_devname, class_instance);
	return unregister_driver(name);
}

int
CDev::init()
{
	DEVICE_DEBUG("CDev::init");

	// base class init first
	int ret = Device::init();

	if (ret != PX4_OK) {
		goto out;
	}

	// now register the driver
	if (_devname != nullptr) {
		ret = register_driver(_devname, &fops, 0666, (void *)this);

		if (ret != PX4_OK) {
			goto out;
		}

		_registered = true;
	}

out:
	return ret;
}

/*
 * Default implementations of the character device interface
 */
int
CDev::open(file_t *filep)
{
	DEVICE_DEBUG("CDev::open");
	int ret = PX4_OK;

	lock();
	/* increment the open count */
	_open_count++;

	if (_open_count == 1) {

		/* first-open callback may decline the open */
		ret = open_first(filep);

		if (ret != PX4_OK) {
			_open_count--;
		}
	}

	unlock();

	return ret;
}

int
CDev::open_first(file_t *filep)
{
	DEVICE_DEBUG("CDev::open_first");
	return PX4_OK;
}

int
CDev::close(file_t *filep)
{
	DEVICE_DEBUG("CDev::close");
	int ret = PX4_OK;

	lock();

	if (_open_count > 0) {
		/* decrement the open count */
		_open_count--;

		/* callback cannot decline the close */
		if (_open_count == 0) {
			ret = close_last(filep);
		}

	} else {
		ret = -EBADF;
	}

	unlock();

	return ret;
}

int
CDev::close_last(file_t *filep)
{
	DEVICE_DEBUG("CDev::close_last");
	return PX4_OK;
}

ssize_t
CDev::read(file_t *filep, char *buffer, size_t buflen)
{
	DEVICE_DEBUG("CDev::read");
	return -ENOSYS;
}

ssize_t
CDev::write(file_t *filep, const char *buffer, size_t buflen)
{
	DEVICE_DEBUG("CDev::write");
	return -ENOSYS;
}

off_t
CDev::seek(file_t *filep, off_t offset, int whence)
{
	DEVICE_DEBUG("CDev::seek");
	return -ENOSYS;
}

int
CDev::ioctl(file_t *filep, int cmd, unsigned long arg)
{
	DEVICE_DEBUG("CDev::ioctl");
	int ret = -ENOTTY;

	switch (cmd) {

	/* fetch a pointer to the driver's private data */
	case DIOC_GETPRIV:
		*(void **)(uintptr_t)arg = (void *)this;
		ret = PX4_OK;
		break;

	case DEVIOCSPUBBLOCK:
		_pub_blocked = (arg != 0);
		ret = PX4_OK;
		break;

	case DEVIOCGPUBBLOCK:
		ret = _pub_blocked;
		break;

	case DEVIOCGDEVICEID:
		ret = (int)_device_id.devid;
		break;

	default:
		break;
	}

	return ret;
}

int
CDev::poll(file_t *filep, px4_pollfd_struct_t *fds, bool setup)
{
	DEVICE_DEBUG("CDev::Poll %s", setup ? "setup" : "teardown");
	int ret = PX4_OK;

	if (setup) {
		/*
		 * Save the file pointer in the pollfd for the subclass'
		 * benefit.
		 */
		fds->priv = (void *)filep;
		DEVICE_DEBUG("CDev::poll: fds->priv = %p", filep);

		/*
		 * Lock against poll_notify() and possibly other callers.
		 */
		ATOMIC_ENTER;

		/*
		 * Try to store the fds for later use and handle array resizing.
		 */
		while ((ret = store_poll_waiter(fds)) == -ENFILE) {

			// No free slot found. Resize the pollset. This is expensive, but it's only needed initially.

			if (_max_pollwaiters >= 256 / 2) { //_max_pollwaiters is uint8_t
				ret = -ENOMEM;
				break;
			}

			const uint8_t new_count = _max_pollwaiters > 0 ? _max_pollwaiters * 2 : 1;
			px4_pollfd_struct_t **prev_pollset = _pollset;

#ifdef __PX4_NUTTX
			// malloc uses a semaphore, we need to call it enabled IRQ's
			px4_leave_critical_section(flags);
#endif
			px4_pollfd_struct_t **new_pollset = new px4_pollfd_struct_t *[new_count];

#ifdef __PX4_NUTTX
			flags = px4_enter_critical_section();
#endif

			if (prev_pollset == _pollset) {
				// no one else updated the _pollset meanwhile, so we're good to go
				if (!new_pollset) {
					ret = -ENOMEM;
					break;
				}

				if (_max_pollwaiters > 0) {
					memset(new_pollset + _max_pollwaiters, 0, sizeof(px4_pollfd_struct_t *) * (new_count - _max_pollwaiters));
					memcpy(new_pollset, _pollset, sizeof(px4_pollfd_struct_t *) * _max_pollwaiters);
					delete[](_pollset);
				}

				_pollset = new_pollset;
				_pollset[_max_pollwaiters] = fds;
				_max_pollwaiters = new_count;

				// Success
				ret = PX4_OK;
				break;
			}

#ifdef __PX4_NUTTX
			px4_leave_critical_section(flags);
#endif
			// We have to retry
			delete[] new_pollset;
#ifdef __PX4_NUTTX
			flags = px4_enter_critical_section();
#endif
		}

		if (ret == PX4_OK) {

			/*
			 * Check to see whether we should send a poll notification
			 * immediately.
			 */
			fds->revents |= fds->events & poll_state(filep);

			/* yes? post the notification */
			if (fds->revents != 0) {
				px4_sem_post(fds->sem);
			}

		} else {
			PX4_WARN("Store Poll Waiter error.");
		}

		ATOMIC_LEAVE;

	} else {
		ATOMIC_ENTER;
		/*
		 * Handle a teardown request.
		 */
		ret = remove_poll_waiter(fds);
		ATOMIC_LEAVE;
	}

	return ret;
}

void
CDev::poll_notify(pollevent_t events)
{
	DEVICE_DEBUG("CDev::poll_notify events = %0x", events);

	/* lock against poll() as well as other wakeups */
	ATOMIC_ENTER;

	for (unsigned i = 0; i < _max_pollwaiters; i++) {
		if (nullptr != _pollset[i]) {
			poll_notify_one(_pollset[i], events);
		}
	}

	ATOMIC_LEAVE;
}

void
CDev::poll_notify_one(px4_pollfd_struct_t *fds, pollevent_t events)
{
	DEVICE_DEBUG("CDev::poll_notify_one");

	/* update the reported event set */
	fds->revents |= fds->events & events;

	DEVICE_DEBUG(" Events fds=%p %0x %0x %0x", fds, fds->revents, fds->events, events);

	if (fds->revents != 0) {
		px4_sem_post(fds->sem);
	}
}

pollevent_t
CDev::poll_state(file_t *filep)
{
	DEVICE_DEBUG("CDev::poll_notify");
	/* by default, no poll events to report */
	return 0;
}

int
CDev::store_poll_waiter(px4_pollfd_struct_t *fds)
{
	/*
	 * Look for a free slot.
	 */
	DEVICE_DEBUG("CDev::store_poll_waiter");

	for (unsigned i = 0; i < _max_pollwaiters; i++) {
		if (nullptr == _pollset[i]) {

			/* save the pollfd */
			_pollset[i] = fds;

			return PX4_OK;
		}
	}

	return -ENFILE;
}

int
CDev::remove_poll_waiter(px4_pollfd_struct_t *fds)
{
	DEVICE_DEBUG("CDev::remove_poll_waiter");

	for (unsigned i = 0; i < _max_pollwaiters; i++) {
		if (fds == _pollset[i]) {

			_pollset[i] = nullptr;
			return PX4_OK;

		}
	}

	PX4_WARN("poll: bad fd state");
	return -EINVAL;
}

} // namespace device
<|endoftext|>


<commit_before>namespace mant {
  template <typename T = double>
  class RandomSearch : public SamplingBasedOptimisationAlgorithm<T, T> {
    public:
      using SamplingBasedOptimisationAlgorithm<T, T>::SamplingBasedOptimisationAlgorithm;

      std::string toString() const noexcept override;

    protected:
      void optimiseImplementation() noexcept override;
  };

  //
  // Implementation
  //

  template <typename T>
  void RandomSearch<T>::optimiseImplementation() noexcept {
    while(!this->isFinished() && !this->isTerminated()) {
      ++this->numberOfIterations_;

      const arma::Col<T>& candidateParameter = this->getRandomParameter();
      updateBestParameter(candidateParameter, this->getSoftConstraintsValue(candidateParameter), this->getObjectiveValue(candidateParameter));
    };
  }

  template <typename T>
  std::string RandomSearch<T>::toString() const noexcept {
    return "random_search";
  }
}
<commit_msg>Added codomain support to RandomSearch<commit_after>namespace mant {
  template <typename T, typename U = double>
  class RandomSearch : public SamplingBasedOptimisationAlgorithm<T, U> {
    public:
      using SamplingBasedOptimisationAlgorithm<T, U>::SamplingBasedOptimisationAlgorithm;

      std::string toString() const noexcept override;

    protected:
      void optimiseImplementation() noexcept override;
  };

  //
  // Implementation
  //

  template <typename T, typename U>
  void RandomSearch<T, U>::optimiseImplementation() noexcept {
    while(!this->isFinished() && !this->isTerminated()) {
      ++this->numberOfIterations_;

      const arma::Col<T>& candidateParameter = this->getRandomParameter();
      updateBestParameter(candidateParameter, this->getSoftConstraintsValue(candidateParameter), this->getObjectiveValue(candidateParameter));
    };
  }

  template <typename T, typename U>
  std::string RandomSearch<T, U>::toString() const noexcept {
    return "random_search";
  }
}
<|endoftext|>


<commit_before>#ifndef ALEPH_REPRESENTATIONS_SET_HH__
#define ALEPH_REPRESENTATIONS_SET_HH__

#include <algorithm>
#include <set>
#include <vector>

namespace aleph
{

namespace topology
{

namespace representations
{

template <class IndexType> class Set
{
public:
  using Index = IndexType;

  void setNumColumns( Index numColumns )
  {
    _data.resize( numColumns );
    _dimensions.resize( numColumns );
  }

  Index getNumColumns() const
  {
    return static_cast<Index>( _data.size() );
  }

  std::pair<Index, bool> getMaximumIndex( Index column ) const
  {
    if( _data.at( column ).empty() )
      return std::make_pair( Index(0), false );
    else
      return std::make_pair( *_data.at( column ).rbegin(), true );
  }

  void addColumns( Index source, Index target )
  {
    auto&& sourceColumn = _data.at( source );
    auto&& targetColumn = _data.at( target );

    std::set<Index> result;

    std::set_symmetric_difference( sourceColumn.begin(), sourceColumn.end(),
                                   targetColumn.begin(), targetColumn.end(),
                                   std::inserter( result, result.begin() ) );

    targetColumn.swap( result );
  }

  template <class InputIterator> void setColumn( Index column,
                                                 InputIterator begin, InputIterator end )
  {
    _data.at( column ).clear();
    _data.at( column ).insert( begin, end );

    // Upon initialization, the column must by necessity have the dimension
    // that is indicated by the amount of indices in its boundary. The case
    // of 0-simplices needs special handling.
    _dimensions.at( column )
        = begin == end ? 0
                       : static_cast<Index>( std::distance( begin, end ) - 1 );
  }

  std::vector<Index> getColumn( Index column ) const
  {
    return { _data.at( column ).begin(), _data.at( column ).end() };
  }

  void clearColumn( Index column )
  {
    _data.at( static_cast<std::size_t>( column ) ).clear();
  }

  void setDimension( Index column, Index dimension )
  {
    _dimensions.at( column ) = dimension;
  }

  Index getDimension( Index column ) const
  {
    return _dimensions.at( column );
  }

  Index getDimension() const
  {
    if( _dimensions.empty() )
      return Index(0);
    else
      return *std::max_element( _dimensions.begin(), _dimensions.end() );
  }

  bool operator==( const Set& other ) const
  {
    return _data == other._data && _dimensions == other._dimensions;
  }

private:
  std::vector< std::set<Index> > _data;
  std::vector<Index> _dimensions;
};

} // namespace representations

} // namespace topology

} // namespace aleph

#endif
<commit_msg>Fixed implicit casts for set representation<commit_after>#ifndef ALEPH_REPRESENTATIONS_SET_HH__
#define ALEPH_REPRESENTATIONS_SET_HH__

#include <algorithm>
#include <set>
#include <vector>

namespace aleph
{

namespace topology
{

namespace representations
{

template <class IndexType> class Set
{
public:
  using Index = IndexType;

  void setNumColumns( Index numColumns )
  {
    _data.resize( static_cast<std::size_t>( numColumns ) );
    _dimensions.resize( static_cast<std::size_t>( numColumns ) );
  }

  Index getNumColumns() const
  {
    return static_cast<Index>( _data.size() );
  }

  std::pair<Index, bool> getMaximumIndex( Index column ) const
  {
    if( _data.at( column ).empty() )
      return std::make_pair( Index(0), false );
    else
      return std::make_pair( *_data.at( static_cast<std::size_t>( column ) ).rbegin(), true );
  }

  void addColumns( Index source, Index target )
  {
    auto&& sourceColumn = _data.at( static_cast<std::size_t>( source ) );
    auto&& targetColumn = _data.at( static_cast<std::size_t>( target ) );

    std::set<Index> result;

    std::set_symmetric_difference( sourceColumn.begin(), sourceColumn.end(),
                                   targetColumn.begin(), targetColumn.end(),
                                   std::inserter( result, result.begin() ) );

    targetColumn.swap( result );
  }

  template <class InputIterator> void setColumn( Index column,
                                                 InputIterator begin, InputIterator end )
  {
    _data.at( static_cast<std::size_t>( column ) ).clear();
    _data.at( static_cast<std::size_t>( column ) ).insert( begin, end );

    // Upon initialization, the column must by necessity have the dimension
    // that is indicated by the amount of indices in its boundary. The case
    // of 0-simplices needs special handling.
    _dimensions.at( static_cast<std::size_t>( column ) )
        = begin == end ? 0
                       : static_cast<Index>( std::distance( begin, end ) - 1 );
  }

  std::vector<Index> getColumn( Index column ) const
  {
    return { _data.at( static_cast<std::size_t>( column ) ).begin(), _data.at( static_cast<std::size_t>( column ) ).end() };
  }

  void clearColumn( Index column )
  {
    _data.at( static_cast<std::size_t>( column ) ).clear();
  }

  void setDimension( Index column, Index dimension )
  {
    _dimensions.at( static_cast<std::size_t>( column ) ) = dimension;
  }

  Index getDimension( Index column ) const
  {
    return _dimensions.at( static_cast<std::size_t>( column ) );
  }

  Index getDimension() const
  {
    if( _dimensions.empty() )
      return Index(0);
    else
      return *std::max_element( _dimensions.begin(), _dimensions.end() );
  }

  bool operator==( const Set& other ) const
  {
    return _data == other._data && _dimensions == other._dimensions;
  }

private:
  std::vector< std::set<Index> > _data;
  std::vector<Index> _dimensions;
};

} // namespace representations

} // namespace topology

} // namespace aleph

#endif
<|endoftext|>