text stringlengths 54 60.6k |
|---|
<commit_before>// JSON private
#include "json/input.h"
// public
#include <disir/disir.h>
// standard
#include <iostream>
#include <stdarg.h>
using namespace dio;
//! Contructor
MoldReader::MoldReader (struct disir_instance *disir) : JsonIO (disir) {}
//! PUBLIC
enum dplugin_status
MoldReader::unmarshal (const char *filepath, struct disir_mold **mold)
{
enum dplugin_status pstatus;
pstatus = read_config (filepath, m_moldRoot);
if (pstatus != DPLUGIN_STATUS_OK)
{
return pstatus;
}
return construct_mold (mold);
}
//! PUBLIC
enum dplugin_status
MoldReader::unmarshal (std::istream& stream, struct disir_mold **mold)
{
Json::Reader reader;
bool success = reader.parse (stream, m_moldRoot);
if (!success)
{
disir_error_set (m_disir, "Parse error: %s",
reader.getFormattedErrorMessages().c_str());
return DPLUGIN_PARSE_ERROR;
}
return construct_mold (mold);
}
enum dplugin_status
MoldReader::construct_mold (struct disir_mold **mold)
{
struct disir_context *context_mold = NULL;
struct semantic_version semver;
enum disir_status status;
enum dplugin_status pstatus;
std::string version;
pstatus = MEMBERS_CHECK (m_moldRoot, MOLD, VERSION);
if (pstatus != DPLUGIN_STATUS_OK)
{
return pstatus;
}
status = dc_mold_begin (&context_mold);
if (status != DISIR_STATUS_OK)
goto error;
version = m_moldRoot[VERSION].asString ();
pstatus = get_version (version, &semver);
if (pstatus != DPLUGIN_STATUS_OK)
{
append_disir_error ("mold does not contain a valid version");
goto error;
}
if (mold_has_documentation (m_moldRoot))
{
auto doc = m_moldRoot[DOCUMENTATION].asString ();
status = dc_add_documentation (context_mold, doc.c_str (), doc.size ());
if (status != DISIR_STATUS_OK)
{
append_disir_error ("Could not add mold documentation");
}
}
pstatus = _unmarshal_mold (context_mold, m_moldRoot[MOLD]);
if (pstatus != DPLUGIN_STATUS_OK)
goto error;
status = dc_mold_finalize (&context_mold, mold);
if (status != DISIR_STATUS_OK)
goto error;
// If everything seemingly succeeded,
// however if there were errors we
if (m_errors.empty () == false)
{
populate_disir_with_errors ();
return DPLUGIN_FATAL_ERROR;
}
return DPLUGIN_STATUS_OK;
error:
if (context_mold)
{
// delete
dc_destroy (&context_mold);
}
populate_disir_with_errors ();
return DPLUGIN_FATAL_ERROR;
}
bool
MoldReader::mold_has_documentation (Json::Value& mold_root)
{
return mold_root[DOCUMENTATION].isString ();
}
bool
MoldReader::value_is_section (Json::Value& val)
{
return val.isObject () && val[ELEMENTS].isObject ();
}
bool
MoldReader::value_is_keyval (Json::Value& val)
{
return val.isObject () && val[DEFAULTS].isArray ();
}
//! PRIVATE
enum dplugin_status
MoldReader::_unmarshal_mold (struct disir_context *parent_context, Json::Value& parent)
{
Json::Value child_node;
struct disir_context *child_context = NULL;
enum disir_status status;
enum dplugin_status pstatus;
Json::OrderedValueIterator iter = parent.beginOrdered ();
for (; iter != parent.endOrdered(); ++iter)
{
child_node = *iter;
// if node is of tpe object and contains the keyval "elements", we interpret it
// as a mold section
if (value_is_section (child_node))
{
status = dc_begin (parent_context, DISIR_CONTEXT_SECTION, &child_context);
if (status != DISIR_STATUS_OK)
return DPLUGIN_FATAL_ERROR;
pstatus = set_context_metadata (child_context, iter);
if (pstatus != DPLUGIN_STATUS_OK)
goto skip_context;
pstatus = _unmarshal_mold (child_context, (*iter)[ELEMENTS]);
if (pstatus != DPLUGIN_STATUS_OK)
goto skip_context;
}
// if node is of type object and contains the keyval "default" we interpret it as
// a mold keyval
else if (value_is_keyval (child_node))
{
status = dc_begin (parent_context, DISIR_CONTEXT_KEYVAL, &child_context);
if (status != DISIR_STATUS_OK)
return DPLUGIN_FATAL_ERROR;
pstatus = set_context_metadata (child_context, iter);
if (pstatus != DPLUGIN_STATUS_OK)
goto skip_context;
pstatus = unmarshal_defaults (child_context, iter);
if (pstatus != DPLUGIN_STATUS_OK)
goto skip_context;
}
else
{
// We got a malformed entry, log it to disir error
// and continue
append_disir_error (iter,
"Interpreted keyval does not contain a list of defaults");
continue;
}
status = dc_finalize (&child_context);
if (status != DISIR_STATUS_OK)
{
return DPLUGIN_FATAL_ERROR;
}
// Skipping an erroneous json element
skip_context:
dc_destroy (&child_context);
}
return DPLUGIN_STATUS_OK;
}
//! json_context is of type Valueiterator because we need its name
enum dplugin_status
MoldReader::set_context_metadata (struct disir_context *context,
Json::OrderedValueIterator& Jcontext)
{
enum disir_status status;
enum dplugin_status pstatus;
struct semantic_version semver;
std::string doc;
Json::Value obj;
obj = *Jcontext;
pstatus = MEMBERS_CHECK (obj, INTRODUCED);
if (pstatus != DPLUGIN_STATUS_OK)
{
return pstatus;
}
auto name = Jcontext.name();
status = dc_set_name (context, name.c_str(), name.size ());
if (status != DISIR_STATUS_OK)
{
append_disir_error (Jcontext, "could not set name");
return DPLUGIN_FATAL_ERROR;
}
// Only set type if it's not a section
if (MEMBERS_CHECK (obj, TYPE) == DPLUGIN_STATUS_OK)
{
status = dc_set_value_type (context, string_to_type (obj[TYPE].asString ()));
if (status != DISIR_STATUS_OK)
{
append_disir_error (Jcontext, "could not set value type %s",
obj[TYPE].asString ().c_str ());
return DPLUGIN_FATAL_ERROR;
}
}
pstatus = get_version (obj[INTRODUCED].asString (), &semver);
if (pstatus != DPLUGIN_STATUS_OK)
{
append_disir_error (Jcontext, "could not convert version");
return DPLUGIN_FATAL_ERROR;
}
status = dc_add_introduced (context, semver);
if (status != DISIR_STATUS_OK)
{
append_disir_error (Jcontext, "could not add introduced: %s",
disir_status_string (status));
return DPLUGIN_FATAL_ERROR;
}
doc = obj[DOCUMENTATION].asString ();
if (doc.empty ())
{
// No documentation on this context exists
return DPLUGIN_STATUS_OK;
}
status = dc_add_documentation (context, doc.c_str (), doc.size ());
if (status != DISIR_STATUS_OK)
{
append_disir_error (Jcontext, "could not add documentation: %s",
disir_status_string (status));
return DPLUGIN_FATAL_ERROR;
}
return DPLUGIN_STATUS_OK;
}
enum dplugin_status
MoldReader::get_version (std::string version, struct semantic_version *semver)
{
const char *ver;
enum disir_status status;
ver = version.c_str ();
status = dc_semantic_version_convert (ver, semver);
if (status != DISIR_STATUS_OK)
{
return DPLUGIN_FATAL_ERROR;
}
return DPLUGIN_STATUS_OK;
}
enum dplugin_status
MoldReader::unmarshal_defaults (struct disir_context *context_keyval,
Json::OrderedValueIterator& it)
{
struct disir_context *context_default = NULL;
enum disir_status status;
enum dplugin_status pstatus;
Json::Value defaults;
pstatus = MEMBERS_CHECK (*it, DEFAULTS);
if (pstatus != DPLUGIN_STATUS_OK)
{
return pstatus;
}
defaults = (*it)[DEFAULTS];
Json::ValueIterator iter = defaults.begin ();
for (; iter != defaults.end (); ++iter)
{
status = dc_begin (context_keyval, DISIR_CONTEXT_DEFAULT, &context_default);
if (status != DISIR_STATUS_OK)
{
append_disir_error (it, "dc_begin resulted in error: %s",
disir_status_string (status));
return DPLUGIN_FATAL_ERROR;
}
pstatus = fetch_default_data (context_default, iter);
if (pstatus != DPLUGIN_STATUS_OK)
goto error;
status = dc_finalize (&context_default);
if (status != DISIR_STATUS_OK)
{
append_disir_error (it, "could not finalize defaul: %s",
disir_status_string (status));
goto error;
}
}
return DPLUGIN_STATUS_OK;
error:
if (context_default)
{
dc_destroy (&context_default);
}
return DPLUGIN_FATAL_ERROR;
}
enum dplugin_status
MoldReader::fetch_default_data (struct disir_context *context_default, Json::ValueIterator& it)
{
enum dplugin_status pstatus;
enum disir_status status;
struct semantic_version intro;
Json::Value def;
def = *it;
pstatus = MEMBERS_CHECK (def, INTRODUCED, VALUE);
if (pstatus != DPLUGIN_STATUS_OK)
{
return pstatus;
}
pstatus = get_version (def[INTRODUCED].asString (), &intro);
if (pstatus != DPLUGIN_STATUS_OK)
{
append_disir_error (it, "could not fetch version: %s",
it.name ().c_str ());
return DPLUGIN_FATAL_ERROR;
}
status = dc_add_introduced (context_default, intro);
if (status != DISIR_STATUS_OK)
{
append_disir_error (it, "could not fetch introduced: %s",
disir_status_string (status));
}
status = set_value (def[VALUE], context_default);
if (status != DISIR_STATUS_OK)
{
append_disir_error (it, "could not set value on default: %s",
disir_status_string (status));
}
return DPLUGIN_STATUS_OK;
}
<commit_msg>fix json: fix libdisir api usage (changed since initial commit)<commit_after>// JSON private
#include "json/input.h"
// public
#include <disir/disir.h>
// standard
#include <iostream>
#include <stdarg.h>
using namespace dio;
//! Contructor
MoldReader::MoldReader (struct disir_instance *disir) : JsonIO (disir) {}
//! PUBLIC
enum dplugin_status
MoldReader::unmarshal (const char *filepath, struct disir_mold **mold)
{
enum dplugin_status pstatus;
pstatus = read_config (filepath, m_moldRoot);
if (pstatus != DPLUGIN_STATUS_OK)
{
return pstatus;
}
return construct_mold (mold);
}
//! PUBLIC
enum dplugin_status
MoldReader::unmarshal (std::istream& stream, struct disir_mold **mold)
{
Json::Reader reader;
bool success = reader.parse (stream, m_moldRoot);
if (!success)
{
disir_error_set (m_disir, "Parse error: %s",
reader.getFormattedErrorMessages().c_str());
return DPLUGIN_PARSE_ERROR;
}
return construct_mold (mold);
}
enum dplugin_status
MoldReader::construct_mold (struct disir_mold **mold)
{
struct disir_context *context_mold = NULL;
struct semantic_version semver;
enum disir_status status;
enum dplugin_status pstatus;
std::string version;
pstatus = MEMBERS_CHECK (m_moldRoot, MOLD, VERSION);
if (pstatus != DPLUGIN_STATUS_OK)
{
return pstatus;
}
status = dc_mold_begin (&context_mold);
if (status != DISIR_STATUS_OK)
goto error;
version = m_moldRoot[VERSION].asString ();
pstatus = get_version (version, &semver);
if (pstatus != DPLUGIN_STATUS_OK)
{
append_disir_error ("mold does not contain a valid version");
goto error;
}
if (mold_has_documentation (m_moldRoot))
{
auto doc = m_moldRoot[DOCUMENTATION].asString ();
status = dc_add_documentation (context_mold, doc.c_str (), doc.size ());
if (status != DISIR_STATUS_OK)
{
append_disir_error ("Could not add mold documentation");
}
}
pstatus = _unmarshal_mold (context_mold, m_moldRoot[MOLD]);
if (pstatus != DPLUGIN_STATUS_OK)
goto error;
status = dc_mold_finalize (&context_mold, mold);
if (status != DISIR_STATUS_OK)
goto error;
// If everything seemingly succeeded,
// however if there were errors we
if (m_errors.empty () == false)
{
populate_disir_with_errors ();
return DPLUGIN_FATAL_ERROR;
}
return DPLUGIN_STATUS_OK;
error:
if (context_mold)
{
// delete
dc_destroy (&context_mold);
}
populate_disir_with_errors ();
return DPLUGIN_FATAL_ERROR;
}
bool
MoldReader::mold_has_documentation (Json::Value& mold_root)
{
return mold_root[DOCUMENTATION].isString ();
}
bool
MoldReader::value_is_section (Json::Value& val)
{
return val.isObject () && val[ELEMENTS].isObject ();
}
bool
MoldReader::value_is_keyval (Json::Value& val)
{
return val.isObject () && val[DEFAULTS].isArray ();
}
//! PRIVATE
enum dplugin_status
MoldReader::_unmarshal_mold (struct disir_context *parent_context, Json::Value& parent)
{
Json::Value child_node;
struct disir_context *child_context = NULL;
enum disir_status status;
enum dplugin_status pstatus;
Json::OrderedValueIterator iter = parent.beginOrdered ();
for (; iter != parent.endOrdered(); ++iter)
{
child_node = *iter;
// if node is of tpe object and contains the keyval "elements", we interpret it
// as a mold section
if (value_is_section (child_node))
{
status = dc_begin (parent_context, DISIR_CONTEXT_SECTION, &child_context);
if (status != DISIR_STATUS_OK)
return DPLUGIN_FATAL_ERROR;
pstatus = set_context_metadata (child_context, iter);
if (pstatus != DPLUGIN_STATUS_OK)
goto skip_context;
pstatus = _unmarshal_mold (child_context, (*iter)[ELEMENTS]);
if (pstatus != DPLUGIN_STATUS_OK)
goto skip_context;
}
// if node is of type object and contains the keyval "default" we interpret it as
// a mold keyval
else if (value_is_keyval (child_node))
{
status = dc_begin (parent_context, DISIR_CONTEXT_KEYVAL, &child_context);
if (status != DISIR_STATUS_OK)
return DPLUGIN_FATAL_ERROR;
pstatus = set_context_metadata (child_context, iter);
if (pstatus != DPLUGIN_STATUS_OK)
goto skip_context;
pstatus = unmarshal_defaults (child_context, iter);
if (pstatus != DPLUGIN_STATUS_OK)
goto skip_context;
}
else
{
// We got a malformed entry, log it to disir error
// and continue
append_disir_error (iter,
"Interpreted keyval does not contain a list of defaults");
continue;
}
status = dc_finalize (&child_context);
if (status != DISIR_STATUS_OK)
{
return DPLUGIN_FATAL_ERROR;
}
// Skipping an erroneous json element
skip_context:
dc_destroy (&child_context);
}
return DPLUGIN_STATUS_OK;
}
//! json_context is of type Valueiterator because we need its name
enum dplugin_status
MoldReader::set_context_metadata (struct disir_context *context,
Json::OrderedValueIterator& Jcontext)
{
enum disir_status status;
enum dplugin_status pstatus;
struct semantic_version semver;
std::string doc;
Json::Value obj;
obj = *Jcontext;
pstatus = MEMBERS_CHECK (obj, INTRODUCED);
if (pstatus != DPLUGIN_STATUS_OK)
{
return pstatus;
}
auto name = Jcontext.name();
status = dc_set_name (context, name.c_str(), name.size ());
if (status != DISIR_STATUS_OK)
{
append_disir_error (Jcontext, "could not set name");
return DPLUGIN_FATAL_ERROR;
}
// Only set type if it's not a section
if (MEMBERS_CHECK (obj, TYPE) == DPLUGIN_STATUS_OK)
{
status = dc_set_value_type (context, string_to_type (obj[TYPE].asString ()));
if (status != DISIR_STATUS_OK)
{
append_disir_error (Jcontext, "could not set value type %s",
obj[TYPE].asString ().c_str ());
return DPLUGIN_FATAL_ERROR;
}
}
pstatus = get_version (obj[INTRODUCED].asString (), &semver);
if (pstatus != DPLUGIN_STATUS_OK)
{
append_disir_error (Jcontext, "could not convert version");
return DPLUGIN_FATAL_ERROR;
}
status = dc_add_introduced (context, &semver);
if (status != DISIR_STATUS_OK)
{
append_disir_error (Jcontext, "could not add introduced: %s",
disir_status_string (status));
return DPLUGIN_FATAL_ERROR;
}
doc = obj[DOCUMENTATION].asString ();
if (doc.empty ())
{
// No documentation on this context exists
return DPLUGIN_STATUS_OK;
}
status = dc_add_documentation (context, doc.c_str (), doc.size ());
if (status != DISIR_STATUS_OK)
{
append_disir_error (Jcontext, "could not add documentation: %s",
disir_status_string (status));
return DPLUGIN_FATAL_ERROR;
}
return DPLUGIN_STATUS_OK;
}
enum dplugin_status
MoldReader::get_version (std::string version, struct semantic_version *semver)
{
const char *ver;
enum disir_status status;
ver = version.c_str ();
status = dc_semantic_version_convert (ver, semver);
if (status != DISIR_STATUS_OK)
{
return DPLUGIN_FATAL_ERROR;
}
return DPLUGIN_STATUS_OK;
}
enum dplugin_status
MoldReader::unmarshal_defaults (struct disir_context *context_keyval,
Json::OrderedValueIterator& it)
{
struct disir_context *context_default = NULL;
enum disir_status status;
enum dplugin_status pstatus;
Json::Value defaults;
pstatus = MEMBERS_CHECK (*it, DEFAULTS);
if (pstatus != DPLUGIN_STATUS_OK)
{
return pstatus;
}
defaults = (*it)[DEFAULTS];
Json::ValueIterator iter = defaults.begin ();
for (; iter != defaults.end (); ++iter)
{
status = dc_begin (context_keyval, DISIR_CONTEXT_DEFAULT, &context_default);
if (status != DISIR_STATUS_OK)
{
append_disir_error (it, "dc_begin resulted in error: %s",
disir_status_string (status));
return DPLUGIN_FATAL_ERROR;
}
pstatus = fetch_default_data (context_default, iter);
if (pstatus != DPLUGIN_STATUS_OK)
goto error;
status = dc_finalize (&context_default);
if (status != DISIR_STATUS_OK)
{
append_disir_error (it, "could not finalize defaul: %s",
disir_status_string (status));
goto error;
}
}
return DPLUGIN_STATUS_OK;
error:
if (context_default)
{
dc_destroy (&context_default);
}
return DPLUGIN_FATAL_ERROR;
}
enum dplugin_status
MoldReader::fetch_default_data (struct disir_context *context_default, Json::ValueIterator& it)
{
enum dplugin_status pstatus;
enum disir_status status;
struct semantic_version intro;
Json::Value def;
def = *it;
pstatus = MEMBERS_CHECK (def, INTRODUCED, VALUE);
if (pstatus != DPLUGIN_STATUS_OK)
{
return pstatus;
}
pstatus = get_version (def[INTRODUCED].asString (), &intro);
if (pstatus != DPLUGIN_STATUS_OK)
{
append_disir_error (it, "could not fetch version: %s",
it.name ().c_str ());
return DPLUGIN_FATAL_ERROR;
}
status = dc_add_introduced (context_default, &intro);
if (status != DISIR_STATUS_OK)
{
append_disir_error (it, "could not fetch introduced: %s",
disir_status_string (status));
}
status = set_value (def[VALUE], context_default);
if (status != DISIR_STATUS_OK)
{
append_disir_error (it, "could not set value on default: %s",
disir_status_string (status));
}
return DPLUGIN_STATUS_OK;
}
<|endoftext|> |
<commit_before>#pragma once
/**
* \file sal/concurrent_queue.hpp
* Intrusive concurrent queue (FIFO)
*/
#include <sal/config.hpp>
#include <sal/spinlock.hpp>
#include <atomic>
#include <mutex>
namespace sal {
__sal_begin
/// Opaque intrusive data to hook class into concurrent_queue
using concurrent_queue_hook = volatile void *;
/**
* Intrusive concurrent queue (FIFO).
*
* Queue elements of type \a T must provide \a Hook that stores opaque data
* managed by owning queue. Any given time specific hook can be used only to
* store element in single queue. Same hook can be used to store element in
* different queues at different times. If application needs to store element
* in multiple queues same time, it needs to provide multiple hooks, one per
* holding queue.
*
* Being intrusive, queue itself does not deal with node allocation. It is
* application's responsibility to handle node management and make sure that
* while in queue, element is kept alive and it's hook is not interfered with.
* Also, pushing and popping elements into/from queue does not copy them, just
* hooks/unhooks using specified member \a Hook in \a T.
*
* Usage:
* \code
* class foo
* {
* sal::concurrent_queue_hook hook;
* int a;
* char b;
* };
*
* sal::concurrent_queue<foo, &foo::hook> queue;
*
* foo f;
* queue.push(&f);
*
* auto fp = queue.try_pop(); // fp == &f
* \endcode
*/
template <typename T, concurrent_queue_hook T::*Hook>
class concurrent_queue
{
public:
concurrent_queue (const concurrent_queue &) = delete;
concurrent_queue &operator= (const concurrent_queue &) = delete;
/// Construct new empty queue
concurrent_queue () noexcept
{
next_(sentry_) = nullptr;
}
/**
* Construct new queue filled with elements moved from \a that. Using
* \a that after move is undefined behaviour (until another queue moves it's
* elements into \a that).
*
* \note Moving elements out of \a that is not thread-safe.
*/
concurrent_queue (concurrent_queue &&that) noexcept
{
next_(sentry_) = nullptr;
operator=(std::move(that));
}
/**
* Move elements from \a that to \a this. Using \a that after move is
* undefined behaviour (until another queue moves it's elements into
* \a that).
*
* Elements in \a this are "forgotten" during move. If these are dynamically
* allocated, it is applications responsibility to release them beforehand.
*
* \note Moving elements out of \a that is not thread-safe.
*/
concurrent_queue &operator= (concurrent_queue &&that) noexcept
{
if (that.tail_ == that.sentry_)
{
tail_ = head_ = sentry_;
}
else if (that.head_ == that.sentry_)
{
tail_ = that.tail_.load(std::memory_order_relaxed);
head_ = sentry_;
next_(head_) = next_(that.head_);
}
else
{
tail_ = that.tail_.load(std::memory_order_relaxed);
head_ = that.head_;
}
that.head_ = that.tail_ = nullptr;
return *this;
}
/// Push new \a node into \a this
void push (T *node) noexcept
{
next_(node) = nullptr;
auto back = tail_.exchange(node);
next_(back) = node;
}
/// Pop next element from queue. If empty, return nullptr
T *try_pop () noexcept
{
std::lock_guard<sal::spinlock> lock(mutex_);
auto front = head_, next = next_(front);
if (front == sentry_)
{
if (!next)
{
return nullptr;
}
front = head_ = next;
next = next_(next);
}
if (next)
{
head_ = next;
return front;
}
if (front != tail_.load())
{
return nullptr;
}
push(sentry_);
next = next_(front);
if (next)
{
head_ = next;
return front;
}
return nullptr;
}
private:
// TODO: std::hardware_destructive_interference_size
static constexpr size_t cache_line = 64;
// using pad0_ also as sentry_
T * const sentry_ = reinterpret_cast<T *>(&pad0_);
char pad0_[sizeof(T) < cache_line - sizeof(decltype(sentry_))
? cache_line - sizeof(decltype(sentry_))
: sizeof(T)
];
alignas(cache_line) std::atomic<T *> tail_{sentry_};
char pad1_[cache_line - sizeof(decltype(tail_))];
sal::spinlock mutex_{};
T *head_ = sentry_;
static T *&next_ (T *node) noexcept
{
return reinterpret_cast<T *&>(const_cast<void *&>(node->*Hook));
}
};
__sal_end
} // namespace sal
<commit_msg>concurrent_queue: add memory ordering constraints<commit_after>#pragma once
/**
* \file sal/concurrent_queue.hpp
* Intrusive concurrent queue (FIFO)
*/
#include <sal/config.hpp>
#include <sal/spinlock.hpp>
#include <atomic>
#include <mutex>
namespace sal {
__sal_begin
/// Opaque intrusive data to hook class into concurrent_queue
using concurrent_queue_hook = volatile void *;
/**
* Intrusive concurrent queue (FIFO).
*
* Queue elements of type \a T must provide \a Hook that stores opaque data
* managed by owning queue. Any given time specific hook can be used only to
* store element in single queue. Same hook can be used to store element in
* different queues at different times. If application needs to store element
* in multiple queues same time, it needs to provide multiple hooks, one per
* holding queue.
*
* Being intrusive, queue itself does not deal with node allocation. It is
* application's responsibility to handle node management and make sure that
* while in queue, element is kept alive and it's hook is not interfered with.
* Also, pushing and popping elements into/from queue does not copy them, just
* hooks/unhooks using specified member \a Hook in \a T.
*
* Usage:
* \code
* class foo
* {
* sal::concurrent_queue_hook hook;
* int a;
* char b;
* };
*
* sal::concurrent_queue<foo, &foo::hook> queue;
*
* foo f;
* queue.push(&f);
*
* auto fp = queue.try_pop(); // fp == &f
* \endcode
*/
template <typename T, concurrent_queue_hook T::*Hook>
class concurrent_queue
{
public:
concurrent_queue (const concurrent_queue &) = delete;
concurrent_queue &operator= (const concurrent_queue &) = delete;
/// Construct new empty queue
concurrent_queue () noexcept
{
next_(sentry_) = nullptr;
}
/**
* Construct new queue filled with elements moved from \a that. Using
* \a that after move is undefined behaviour (until another queue moves it's
* elements into \a that).
*
* \note Moving elements out of \a that is not thread-safe.
*/
concurrent_queue (concurrent_queue &&that) noexcept
{
next_(sentry_) = nullptr;
operator=(std::move(that));
}
/**
* Move elements from \a that to \a this. Using \a that after move is
* undefined behaviour (until another queue moves it's elements into
* \a that).
*
* Elements in \a this are "forgotten" during move. If these are dynamically
* allocated, it is applications responsibility to release them beforehand.
*
* \note Moving elements out of \a that is not thread-safe.
*/
concurrent_queue &operator= (concurrent_queue &&that) noexcept
{
if (that.tail_ == that.sentry_)
{
tail_ = head_ = sentry_;
}
else if (that.head_ == that.sentry_)
{
tail_ = that.tail_.load(std::memory_order_relaxed);
head_ = sentry_;
next_(head_) = next_(that.head_);
}
else
{
tail_ = that.tail_.load(std::memory_order_relaxed);
head_ = that.head_;
}
that.head_ = that.tail_ = nullptr;
return *this;
}
/// Push new \a node into \a this
void push (T *node) noexcept
{
next_(node) = nullptr;
auto back = tail_.exchange(node, std::memory_order_release);
next_(back) = node;
}
/// Pop next element from queue. If empty, return nullptr
T *try_pop () noexcept
{
std::lock_guard<sal::spinlock> lock(mutex_);
auto front = head_, next = next_(front);
if (front == sentry_)
{
if (!next)
{
return nullptr;
}
front = head_ = next;
next = next_(next);
}
if (next)
{
head_ = next;
return front;
}
if (front != tail_.load(std::memory_order_acquire))
{
return nullptr;
}
push(sentry_);
next = next_(front);
if (next)
{
head_ = next;
return front;
}
return nullptr;
}
private:
// TODO: std::hardware_destructive_interference_size
static constexpr size_t cache_line = 64;
// using pad0_ also as sentry_
T * const sentry_ = reinterpret_cast<T *>(&pad0_);
char pad0_[sizeof(T) < cache_line - sizeof(decltype(sentry_))
? cache_line - sizeof(decltype(sentry_))
: sizeof(T)
];
alignas(cache_line) std::atomic<T *> tail_{sentry_};
char pad1_[cache_line - sizeof(decltype(tail_))];
sal::spinlock mutex_{};
T *head_ = sentry_;
static T *&next_ (T *node) noexcept
{
return reinterpret_cast<T *&>(const_cast<void *&>(node->*Hook));
}
};
__sal_end
} // namespace sal
<|endoftext|> |
<commit_before>/*
Copyright (c) 2008, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author 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.
*/
#include <iostream>
#include <boost/config.hpp>
#include <fcntl.h>
#include <stdio.h>
int test_main();
extern bool tests_failure;
#include "libtorrent/assert.hpp"
#include <signal.h>
void sig_handler(int sig)
{
char stack_text[10000];
print_backtrace(stack_text, sizeof(stack_text), 30);
char const* sig_name = 0;
switch (sig)
{
#define SIG(x) case x: sig_name = #x; break
SIG(SIGSEGV);
SIG(SIGBUS);
SIG(SIGILL);
SIG(SIGABRT);
SIG(SIGFPE);
SIG(SIGSYS);
#undef SIG
};
fprintf(stderr, "signal: %s caught:\n%s\n", sig_name, stack_text);
exit(138);
}
int main()
{
#ifdef O_NONBLOCK
// on darwin, stdout is set to non-blocking mode by default
// which sometimes causes tests to fail with EAGAIN just
// by printing logs
int flags = fcntl(fileno(stdout), F_GETFL, 0);
fcntl(fileno(stdout), F_SETFL, flags & ~O_NONBLOCK);
flags = fcntl(fileno(stderr), F_GETFL, 0);
fcntl(fileno(stderr), F_SETFL, flags & ~O_NONBLOCK);
#endif
signal(SIGSEGV, &sig_handler);
signal(SIGBUS, &sig_handler);
signal(SIGILL, &sig_handler);
signal(SIGABRT, &sig_handler);
signal(SIGFPE, &sig_handler);
signal(SIGSYS, &sig_handler);
#ifndef BOOST_NO_EXCEPTIONS
try
{
#endif
test_main();
#ifndef BOOST_NO_EXCEPTIONS
}
catch (std::exception const& e)
{
std::cerr << "Terminated with exception: \"" << e.what() << "\"\n";
tests_failure = true;
}
catch (...)
{
std::cerr << "Terminated with unknown exception\n";
tests_failure = true;
}
#endif
fflush(stdout);
fflush(stderr);
return tests_failure ? 1 : 0;
}
<commit_msg>fix windows unit test build<commit_after>/*
Copyright (c) 2008, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author 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.
*/
#include <iostream>
#include <boost/config.hpp>
#include <fcntl.h>
#include <stdio.h>
int test_main();
extern bool tests_failure;
#include "libtorrent/assert.hpp"
#include <signal.h>
void sig_handler(int sig)
{
char stack_text[10000];
print_backtrace(stack_text, sizeof(stack_text), 30);
char const* sig_name = 0;
switch (sig)
{
#define SIG(x) case x: sig_name = #x; break
SIG(SIGSEGV);
#ifdef SIGBUS
SIG(SIGBUS);
#endif
SIG(SIGILL);
SIG(SIGABRT);
SIG(SIGFPE);
#ifdef SIGSYS
SIG(SIGSYS);
#endif
#undef SIG
};
fprintf(stderr, "signal: %s caught:\n%s\n", sig_name, stack_text);
exit(138);
}
int main()
{
#ifdef O_NONBLOCK
// on darwin, stdout is set to non-blocking mode by default
// which sometimes causes tests to fail with EAGAIN just
// by printing logs
int flags = fcntl(fileno(stdout), F_GETFL, 0);
fcntl(fileno(stdout), F_SETFL, flags & ~O_NONBLOCK);
flags = fcntl(fileno(stderr), F_GETFL, 0);
fcntl(fileno(stderr), F_SETFL, flags & ~O_NONBLOCK);
#endif
signal(SIGSEGV, &sig_handler);
#ifdef SIGBUS
signal(SIGBUS, &sig_handler);
#endif
signal(SIGILL, &sig_handler);
signal(SIGABRT, &sig_handler);
signal(SIGFPE, &sig_handler);
#ifdef SIGSYS
signal(SIGSYS, &sig_handler);
#endif
#ifndef BOOST_NO_EXCEPTIONS
try
{
#endif
test_main();
#ifndef BOOST_NO_EXCEPTIONS
}
catch (std::exception const& e)
{
std::cerr << "Terminated with exception: \"" << e.what() << "\"\n";
tests_failure = true;
}
catch (...)
{
std::cerr << "Terminated with unknown exception\n";
tests_failure = true;
}
#endif
fflush(stdout);
fflush(stderr);
return tests_failure ? 1 : 0;
}
<|endoftext|> |
<commit_before>#include "fly/logger/styler.hpp"
#include "fly/types/string/string.hpp"
//clang-format off
// Due to a missing #include in catch_reporter_registrars.hpp, this must be included first.
#include "catch2/interfaces/catch_interfaces_reporter.hpp"
//clang-format on
#include "catch2/catch_reporter_registrars.hpp"
#include "catch2/catch_session.hpp"
#include "catch2/catch_test_case_info.hpp"
#include "catch2/reporters/catch_reporter_console.hpp"
/**
* A Catch2 test reporter for reporting colorful test and section names to console.
*/
class FlyReporter : public Catch::ConsoleReporter
{
public:
FlyReporter(const Catch::ReporterConfig &config) : Catch::ConsoleReporter(config)
{
}
~FlyReporter() override = default;
static std::string getDescription()
{
return "Catch2 test reporter for libfly";
}
void testRunStarting(const Catch::TestRunInfo &info) override
{
Catch::ConsoleReporter::testRunStarting(info);
m_test_start = std::chrono::steady_clock::now();
}
void testRunEnded(const Catch::TestRunStats &stats) override
{
Catch::ConsoleReporter::testRunEnded(stats);
const auto end = std::chrono::steady_clock::now();
const auto duration = std::chrono::duration<double>(end - m_test_start);
// ConsoleReporter prints a second newline above, so go up one line before logging the time.
stream << fly::logger::Styler(
fly::logger::Cursor::Up,
fly::logger::Style::Bold,
fly::logger::Color::Cyan)
<< "Total time ";
stream << fly::String::format("{:.3f} seconds\n\n", duration.count());
}
void testCaseStarting(const Catch::TestCaseInfo &info) override
{
const auto style = fly::logger::Styler(fly::logger::Style::Bold, fly::logger::Color::Green);
stream << style << fly::String::format("[{:=>4}{} Test{:=<4}]\n", ' ', info.name, ' ');
Catch::ConsoleReporter::testCaseStarting(info);
m_current_test_case_start = std::chrono::steady_clock::now();
m_current_test_case = info.name;
}
void sectionStarting(const Catch::SectionInfo &info) override
{
if (info.name != m_current_test_case)
{
const auto style =
fly::logger::Styler(fly::logger::Style::Italic, fly::logger::Color::Cyan);
stream << style << fly::String::format("[ {} ]\n", info.name);
}
Catch::ConsoleReporter::sectionStarting(info);
}
void testCaseEnded(const Catch::TestCaseStats &stats) override
{
const auto end = std::chrono::steady_clock::now();
const auto duration = std::chrono::duration<double>(end - m_current_test_case_start);
const std::string &name = stats.testInfo->name;
if (stats.totals.assertions.allOk())
{
const auto style =
fly::logger::Styler(fly::logger::Style::Bold, fly::logger::Color::Green);
stream << style;
stream << fly::String::format(
"[==== PASSED {} ({:.3f} seconds) ====]\n\n",
name,
duration.count());
}
else
{
const auto style =
fly::logger::Styler(fly::logger::Style::Bold, fly::logger::Color::Red);
stream << style;
stream << fly::String::format(
"[==== FAILED {} ({:.3f} seconds) ====]\n\n",
name,
duration.count());
}
Catch::ConsoleReporter::testCaseEnded(stats);
m_current_test_case.clear();
}
private:
std::chrono::steady_clock::time_point m_test_start;
std::chrono::steady_clock::time_point m_current_test_case_start;
std::string m_current_test_case;
};
CATCH_REGISTER_REPORTER("libfly", FlyReporter)
int main(int argc, char **argv)
{
return Catch::Session().run(argc, argv);
}
<commit_msg>De-duplicate logging of repeated Catch2 section names<commit_after>#include "fly/logger/styler.hpp"
#include "fly/types/string/string.hpp"
// clang-format off
// Due to a missing #include in catch_reporter_registrars.hpp, this must be included first.
#include "catch2/interfaces/catch_interfaces_reporter.hpp"
// clang-format on
#include "catch2/catch_reporter_registrars.hpp"
#include "catch2/catch_session.hpp"
#include "catch2/catch_test_case_info.hpp"
#include "catch2/reporters/catch_reporter_console.hpp"
#include <chrono>
#include <cstdint>
#include <string>
#include <vector>
/**
* A Catch2 test reporter for reporting colorful test and section names to console.
*/
class FlyReporter : public Catch::ConsoleReporter
{
public:
explicit FlyReporter(const Catch::ReporterConfig &config) : Catch::ConsoleReporter(config)
{
}
~FlyReporter() override = default;
static std::string getDescription()
{
return "Catch2 test reporter for libfly";
}
void testRunStarting(const Catch::TestRunInfo &info) override
{
Catch::ConsoleReporter::testRunStarting(info);
m_test_start = std::chrono::steady_clock::now();
}
void testRunEnded(const Catch::TestRunStats &stats) override
{
Catch::ConsoleReporter::testRunEnded(stats);
const auto end = std::chrono::steady_clock::now();
const auto duration = std::chrono::duration<double>(end - m_test_start);
// ConsoleReporter prints a second newline above, so go up one line before logging the time.
stream << fly::logger::Styler(
fly::logger::Cursor::Up,
fly::logger::Style::Bold,
fly::logger::Color::Cyan)
<< "Total time ";
stream << fly::String::format("{:.3f} seconds\n\n", duration.count());
}
void testCaseStarting(const Catch::TestCaseInfo &info) override
{
Catch::ConsoleReporter::testCaseStarting(info);
stream_header(fly::logger::Color::Green, fly::String::format("{} Test", info.name));
m_current_test_case_start = std::chrono::steady_clock::now();
}
void sectionStarting(const Catch::SectionInfo &info) override
{
Catch::ConsoleReporter::sectionStarting(info);
std::size_t level = m_section_level++;
if (level == 0)
{
m_sections.push_back(info.name);
return;
}
auto path = fly::String::join('/', m_sections.back(), info.name);
if (auto it = std::find(m_sections.begin(), m_sections.end(), path); it != m_sections.end())
{
std::swap(*it, *(m_sections.end() - 1));
return;
}
const fly::logger::Styler style(fly::logger::Color::Cyan, fly::logger::Style::Italic);
stream << style << "[ ";
if (level != 1)
{
stream << fly::String::format("{: >{}}└─➤ ", "", (level - 2) * 4);
}
stream << fly::String::format("{} ]\n", info.name);
m_sections.push_back(std::move(path));
}
void sectionEnded(const Catch::SectionStats &stats) override
{
Catch::ConsoleReporter::sectionEnded(stats);
--m_section_level;
}
void testCaseEnded(const Catch::TestCaseStats &stats) override
{
Catch::ConsoleReporter::testCaseEnded(stats);
const auto end = std::chrono::steady_clock::now();
const auto duration = std::chrono::duration<double>(end - m_current_test_case_start);
const std::string &name = stats.testInfo->name;
if (stats.totals.assertions.allOk())
{
stream_header(
fly::logger::Color::Green,
fly::String::format("PASSED {} ({:.3f} seconds)", name, duration.count()));
}
else
{
stream_header(
fly::logger::Color::Red,
fly::String::format("FAILED {} ({:.3f} seconds)", name, duration.count()));
}
stream << '\n';
m_sections.clear();
}
private:
void stream_header(fly::logger::Color::StandardColor color, std::string message)
{
stream << fly::logger::Styler(fly::logger::Style::Bold, color)
<< fly::String::format("[==== {} ====]\n", message);
}
std::chrono::steady_clock::time_point m_test_start;
std::chrono::steady_clock::time_point m_current_test_case_start;
std::vector<std::string> m_sections;
std::size_t m_section_level {0};
};
CATCH_REGISTER_REPORTER("libfly", FlyReporter)
int main(int argc, char **argv)
{
return Catch::Session().run(argc, argv);
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2008, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author 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.
*/
#include <iostream>
#include <boost/config.hpp>
#include <fcntl.h>
#include <stdio.h>
int test_main();
extern bool tests_failure;
#include "libtorrent/assert.hpp"
#include <signal.h>
void sig_handler(int sig)
{
char stack_text[10000];
print_backtrace(stack_text, sizeof(stack_text), 30);
char const* sig_name = 0;
switch (sig)
{
#define SIG(x) case x: sig_name = #x; break
SIG(SIGSEGV);
SIG(SIGBUS);
SIG(SIGILL);
SIG(SIGABRT);
SIG(SIGFPE);
SIG(SIGSYS);
#undef SIG
};
fprintf(stderr, "signal: %s caught:\n%s\n", sig_name, stack_text);
exit(138);
}
int main()
{
#ifdef O_NONBLOCK
// on darwin, stdout is set to non-blocking mode by default
// which sometimes causes tests to fail with EAGAIN just
// by printing logs
int flags = fcntl(fileno(stdout), F_GETFL, 0);
fcntl(fileno(stdout), F_SETFL, flags & ~O_NONBLOCK);
flags = fcntl(fileno(stderr), F_GETFL, 0);
fcntl(fileno(stderr), F_SETFL, flags & ~O_NONBLOCK);
#endif
signal(SIGSEGV, &sig_handler);
signal(SIGBUS, &sig_handler);
signal(SIGILL, &sig_handler);
signal(SIGABRT, &sig_handler);
signal(SIGFPE, &sig_handler);
signal(SIGSYS, &sig_handler);
#ifndef BOOST_NO_EXCEPTIONS
try
{
#endif
test_main();
#ifndef BOOST_NO_EXCEPTIONS
}
catch (std::exception const& e)
{
std::cerr << "Terminated with exception: \"" << e.what() << "\"\n";
tests_failure = true;
}
catch (...)
{
std::cerr << "Terminated with unknown exception\n";
tests_failure = true;
}
#endif
fflush(stdout);
fflush(stderr);
return tests_failure ? 1 : 0;
}
<commit_msg>fix windows unit test build<commit_after>/*
Copyright (c) 2008, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author 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.
*/
#include <iostream>
#include <boost/config.hpp>
#include <fcntl.h>
#include <stdio.h>
int test_main();
extern bool tests_failure;
#include "libtorrent/assert.hpp"
#include <signal.h>
void sig_handler(int sig)
{
char stack_text[10000];
print_backtrace(stack_text, sizeof(stack_text), 30);
char const* sig_name = 0;
switch (sig)
{
#define SIG(x) case x: sig_name = #x; break
SIG(SIGSEGV);
#ifdef SIGBUS
SIG(SIGBUS);
#endif
SIG(SIGILL);
SIG(SIGABRT);
SIG(SIGFPE);
#ifdef SIGSYS
SIG(SIGSYS);
#endif
#undef SIG
};
fprintf(stderr, "signal: %s caught:\n%s\n", sig_name, stack_text);
exit(138);
}
int main()
{
#ifdef O_NONBLOCK
// on darwin, stdout is set to non-blocking mode by default
// which sometimes causes tests to fail with EAGAIN just
// by printing logs
int flags = fcntl(fileno(stdout), F_GETFL, 0);
fcntl(fileno(stdout), F_SETFL, flags & ~O_NONBLOCK);
flags = fcntl(fileno(stderr), F_GETFL, 0);
fcntl(fileno(stderr), F_SETFL, flags & ~O_NONBLOCK);
#endif
signal(SIGSEGV, &sig_handler);
#ifdef SIGBUS
signal(SIGBUS, &sig_handler);
#endif
signal(SIGILL, &sig_handler);
signal(SIGABRT, &sig_handler);
signal(SIGFPE, &sig_handler);
#ifdef SIGSYS
signal(SIGSYS, &sig_handler);
#endif
#ifndef BOOST_NO_EXCEPTIONS
try
{
#endif
test_main();
#ifndef BOOST_NO_EXCEPTIONS
}
catch (std::exception const& e)
{
std::cerr << "Terminated with exception: \"" << e.what() << "\"\n";
tests_failure = true;
}
catch (...)
{
std::cerr << "Terminated with unknown exception\n";
tests_failure = true;
}
#endif
fflush(stdout);
fflush(stderr);
return tests_failure ? 1 : 0;
}
<|endoftext|> |
<commit_before>#include <cstdlib>
#include <iostream>
#include "sslpkix/sslpkix.h"
#define CATCH_CONFIG_RUNNER
#include "catch.hpp"
static int prime_generation_callback(int p, int n, BN_GENCB *arg) {
(void)n;
(void)arg;
char c;
switch (p) {
default: c = 'B'; break;
case 0: c = '.'; break;
case 1: c = '+'; break;
case 2: c = '*'; break;
case 3: c = '\n'; break;
}
fputc(c, stderr);
return 1;
}
TEST_CASE("certificate/creation/1", "Certificate creation")
{
//
// Create issuer
//
sslpkix::CertificateName issuer;
REQUIRE(issuer.create());
REQUIRE(issuer.set_common_name("janeroe.example.com"));
REQUIRE(issuer.set_email("jane.roe@example.com"));
REQUIRE(issuer.set_country("US"));
REQUIRE(issuer.set_state("CA"));
REQUIRE(issuer.set_locality("Palo Alto"));
REQUIRE(issuer.set_organization("Jane Roe's CA Pty."));
//
// Create subject
//
sslpkix::CertificateName subject;
REQUIRE(subject.create());
REQUIRE(subject.set_common_name("johndoe.example.com"));
REQUIRE(subject.set_email("john.doe@example.com"));
REQUIRE(subject.set_country("BR"));
REQUIRE(subject.set_state("RS"));
REQUIRE(subject.set_locality("Porto Alegre"));
REQUIRE(subject.set_organization("John Doe's Company Pty."));
//
// Add a custom extensions - This is not required.
//
int nid;
const char *oid = "1.2.3.4.5.31";
const char *short_name = "CTE";
const char *long_name = "customTextEntry";
const char *value = "Some value here";
REQUIRE(sslpkix::add_custom_object(oid, short_name, long_name, &nid));
REQUIRE(subject.add_entry(short_name, value));
REQUIRE(subject.entry_value(nid) == value);
//
// Generate the key pair
//
sslpkix::PrivateKey key;
REQUIRE(key.create());
RSA *rsa_keypair = RSA_new();
REQUIRE(rsa_keypair != NULL);
BIGNUM *f4 = BN_new();
REQUIRE(f4 != NULL);
REQUIRE(BN_set_word(f4, RSA_F4) != 0); // Use the fourth Fermat Number
BN_GENCB cb;
BN_GENCB_set(&cb, prime_generation_callback, NULL);
REQUIRE(RSA_generate_key_ex(rsa_keypair, 1024, f4, &cb) != 0);
REQUIRE(key.copy(rsa_keypair));
BN_free(f4);
f4 = NULL;
RSA_free(rsa_keypair);
rsa_keypair = NULL;
sslpkix::FileSink key_file;
REQUIRE(key_file.open("JohnDoe.key", "wb"));
REQUIRE(key.save(key_file));
key_file.close();
//
// Create the certificate
//
sslpkix::Certificate cert;
REQUIRE(cert.create());
// Adjust version
REQUIRE(cert.set_version(sslpkix::Certificate::Version::v3));
// Adjust keys
REQUIRE(cert.set_pubkey(key));
// Use a hardcoded serial - Never do this in production code!
REQUIRE(cert.set_serial(31337L));
// Adjust issuer and subject
REQUIRE(cert.set_issuer(issuer));
REQUIRE(cert.set_subject(subject));
// Valid for 5 days from now
REQUIRE(cert.set_valid_since(0));
REQUIRE(cert.set_valid_until(5));
// Self-sign this certificate
REQUIRE(cert.sign(key));
// Save it
sslpkix::FileSink cert_file;
REQUIRE(cert_file.open("JohnDoe.crt", "wb"));
REQUIRE(cert.save(cert_file));
cert_file.close();
// TODO(jweyrich): Move the following to a different test case, "certificate/copy_ctor"
sslpkix::Certificate certCopy1(cert);
REQUIRE(certCopy1 == cert);
// TODO(jweyrich): Move the following to a different test case, "certificate/assignament_op"
sslpkix::Certificate certCopy2;
certCopy2 = cert;
REQUIRE(certCopy2 == cert);
}
TEST_CASE("iosink/operators", "IoSink operators")
{
sslpkix::FileSink cert_file;
REQUIRE(cert_file.open("JohnDoe.crt", "rb"));
std::string cert_string;
cert_file >> cert_string; // IoSink to std::string
//std::cout << cert_string << std::endl;
cert_file.close();
// TODO(jweyrich): Test whether operator>> was successful. How?
std::stringstream sstream;
sslpkix::MemorySink cert_mem;
REQUIRE(cert_mem.open_rw());
cert_mem << cert_string; // std::string to IoSink
sstream << cert_mem; // IoSink to std::stringstream
cert_mem.close();
REQUIRE(sstream.str() == cert_string);
// Reset the stringstream
sstream.str(std::string());
sslpkix::MemorySink key_mem;
REQUIRE(key_mem.open_rw());
std::filebuf fbuf;
fbuf.open("JohnDoe.key", std::ios::in);
std::istream istream(&fbuf);
istream >> key_mem; // std::istream to IoSink
std::string key_string;
key_mem >> key_string; // IoSink to std::string
//std::cout << key_string << std::endl;
istream.clear(); // Clear EOF flag (required before C++11)
istream.seekg(0); // Rewind the std::iostream
sstream << istream.rdbuf(); // std::istream to std::stringstream
//std::cout << sstream.str() << std::endl;
REQUIRE(sstream.str() == key_string);
fbuf.close();
key_mem.close();
}
TEST_CASE("certificate_name/entries", "CertificateName entries")
{
sslpkix::CertificateName name;
REQUIRE(name.create());
REQUIRE(name.set_common_name("John Doe"));
REQUIRE(name.common_name() == "John Doe");
REQUIRE(name.set_country("BR"));
REQUIRE(name.country() == "BR");
REQUIRE(name.set_email("john.doe@example.com"));
REQUIRE(name.email() == "john.doe@example.com");
REQUIRE(name.set_locality("Sao Paulo"));
REQUIRE(name.locality() == "Sao Paulo");
REQUIRE(name.set_organization("Independent"));
REQUIRE(name.organization() == "Independent");
REQUIRE(name.set_state("SP"));
REQUIRE(name.state() == "SP");
}
TEST_CASE("key/generation/rsa", "RSA key generation")
{
sslpkix::PrivateKey key;
REQUIRE(key.create());
RSA *rsa_keypair = RSA_new();
REQUIRE(rsa_keypair != NULL);
BIGNUM *f4 = BN_new();
REQUIRE(f4 != NULL);
REQUIRE(BN_set_word(f4, RSA_F4) != 0); // Use the fourth Fermat Number
BN_GENCB cb;
BN_GENCB_set(&cb, prime_generation_callback, NULL);
REQUIRE(RSA_generate_key_ex(rsa_keypair, 512, f4, &cb) != 0);
REQUIRE(key.copy(rsa_keypair));
BN_free(f4);
f4 = NULL;
RSA_free(rsa_keypair);
rsa_keypair = NULL;
// TODO(jweyrich): Move the following to a different test case, "key/copy_ctor"
sslpkix::PrivateKey keyCopy1(key);
REQUIRE(keyCopy1 == key);
}
TEST_CASE("certificate_name/extensions", "CertificateName extension")
{
int nid;
const char *oid = "1.2.3.4.5.31";
const char *short_name = "CTE";
const char *long_name = "customTextEntry";
const char *value = "Some value here";
REQUIRE(sslpkix::add_custom_object(oid, short_name, long_name, &nid));
sslpkix::CertificateName name;
REQUIRE(name.create());
REQUIRE(name.add_entry(short_name, value));
int index;
REQUIRE((index = name.find_entry(nid)) != -1);
REQUIRE(name.entry(index) != NULL);
REQUIRE(name.entry_count() == 1);
REQUIRE(name.entry_value(nid) == value);
// TODO(jweyrich): Move the following to a different test case, "certificate_name/copy_ctor"
sslpkix::CertificateName nameCopy1(name);
REQUIRE(nameCopy1 == name);
// TODO(jweyrich): Move the following to a different test case, "certificate_name/assignament_op"
sslpkix::CertificateName nameCopy2;
nameCopy2 = name;
REQUIRE(nameCopy2 == name);
}
int main(int argc, char *const argv[])
{
bool success = sslpkix::startup();
if (!success) {
std::cerr << "ERROR: Failed to initialize SSLPKIX." << std::endl;
exit(EXIT_FAILURE);
}
int result = Catch::Session().run(argc, argv);
sslpkix::shutdown();
return result;
}
<commit_msg>Test case was not seeding the PRNG.<commit_after>#include <cstdlib>
#include <iostream>
#include "sslpkix/sslpkix.h"
#define CATCH_CONFIG_RUNNER
#include "catch.hpp"
static int prime_generation_callback(int p, int n, BN_GENCB *arg) {
(void)n;
(void)arg;
char c;
switch (p) {
default: c = 'B'; break;
case 0: c = '.'; break;
case 1: c = '+'; break;
case 2: c = '*'; break;
case 3: c = '\n'; break;
}
fputc(c, stderr);
return 1;
}
TEST_CASE("certificate/creation/1", "Certificate creation")
{
//
// Create issuer
//
sslpkix::CertificateName issuer;
REQUIRE(issuer.create());
REQUIRE(issuer.set_common_name("janeroe.example.com"));
REQUIRE(issuer.set_email("jane.roe@example.com"));
REQUIRE(issuer.set_country("US"));
REQUIRE(issuer.set_state("CA"));
REQUIRE(issuer.set_locality("Palo Alto"));
REQUIRE(issuer.set_organization("Jane Roe's CA Pty."));
//
// Create subject
//
sslpkix::CertificateName subject;
REQUIRE(subject.create());
REQUIRE(subject.set_common_name("johndoe.example.com"));
REQUIRE(subject.set_email("john.doe@example.com"));
REQUIRE(subject.set_country("BR"));
REQUIRE(subject.set_state("RS"));
REQUIRE(subject.set_locality("Porto Alegre"));
REQUIRE(subject.set_organization("John Doe's Company Pty."));
//
// Add a custom extensions - This is not required.
//
int nid;
const char *oid = "1.2.3.4.5.31";
const char *short_name = "CTE";
const char *long_name = "customTextEntry";
const char *value = "Some value here";
REQUIRE(sslpkix::add_custom_object(oid, short_name, long_name, &nid));
REQUIRE(subject.add_entry(short_name, value));
REQUIRE(subject.entry_value(nid) == value);
//
// Generate the key pair
//
sslpkix::PrivateKey key;
REQUIRE(key.create());
RSA *rsa_keypair = RSA_new();
REQUIRE(rsa_keypair != NULL);
BIGNUM *f4 = BN_new();
REQUIRE(f4 != NULL);
REQUIRE(BN_set_word(f4, RSA_F4) != 0); // Use the fourth Fermat Number
BN_GENCB cb;
BN_GENCB_set(&cb, prime_generation_callback, NULL);
REQUIRE(RSA_generate_key_ex(rsa_keypair, 1024, f4, &cb) != 0);
REQUIRE(key.copy(rsa_keypair));
BN_free(f4);
f4 = NULL;
RSA_free(rsa_keypair);
rsa_keypair = NULL;
sslpkix::FileSink key_file;
REQUIRE(key_file.open("JohnDoe.key", "wb"));
REQUIRE(key.save(key_file));
key_file.close();
//
// Create the certificate
//
sslpkix::Certificate cert;
REQUIRE(cert.create());
// Adjust version
REQUIRE(cert.set_version(sslpkix::Certificate::Version::v3));
// Adjust keys
REQUIRE(cert.set_pubkey(key));
// Use a hardcoded serial - Never do this in production code!
REQUIRE(cert.set_serial(31337L));
// Adjust issuer and subject
REQUIRE(cert.set_issuer(issuer));
REQUIRE(cert.set_subject(subject));
// Valid for 5 days from now
REQUIRE(cert.set_valid_since(0));
REQUIRE(cert.set_valid_until(5));
// Self-sign this certificate
REQUIRE(cert.sign(key));
// Save it
sslpkix::FileSink cert_file;
REQUIRE(cert_file.open("JohnDoe.crt", "wb"));
REQUIRE(cert.save(cert_file));
cert_file.close();
// TODO(jweyrich): Move the following to a different test case, "certificate/copy_ctor"
sslpkix::Certificate certCopy1(cert);
REQUIRE(certCopy1 == cert);
// TODO(jweyrich): Move the following to a different test case, "certificate/assignament_op"
sslpkix::Certificate certCopy2;
certCopy2 = cert;
REQUIRE(certCopy2 == cert);
}
TEST_CASE("iosink/operators", "IoSink operators")
{
sslpkix::FileSink cert_file;
REQUIRE(cert_file.open("JohnDoe.crt", "rb"));
std::string cert_string;
cert_file >> cert_string; // IoSink to std::string
//std::cout << cert_string << std::endl;
cert_file.close();
// TODO(jweyrich): Test whether operator>> was successful. How?
std::stringstream sstream;
sslpkix::MemorySink cert_mem;
REQUIRE(cert_mem.open_rw());
cert_mem << cert_string; // std::string to IoSink
sstream << cert_mem; // IoSink to std::stringstream
cert_mem.close();
REQUIRE(sstream.str() == cert_string);
// Reset the stringstream
sstream.str(std::string());
sslpkix::MemorySink key_mem;
REQUIRE(key_mem.open_rw());
std::filebuf fbuf;
fbuf.open("JohnDoe.key", std::ios::in);
std::istream istream(&fbuf);
istream >> key_mem; // std::istream to IoSink
std::string key_string;
key_mem >> key_string; // IoSink to std::string
//std::cout << key_string << std::endl;
istream.clear(); // Clear EOF flag (required before C++11)
istream.seekg(0); // Rewind the std::iostream
sstream << istream.rdbuf(); // std::istream to std::stringstream
//std::cout << sstream.str() << std::endl;
REQUIRE(sstream.str() == key_string);
fbuf.close();
key_mem.close();
}
TEST_CASE("certificate_name/entries", "CertificateName entries")
{
sslpkix::CertificateName name;
REQUIRE(name.create());
REQUIRE(name.set_common_name("John Doe"));
REQUIRE(name.common_name() == "John Doe");
REQUIRE(name.set_country("BR"));
REQUIRE(name.country() == "BR");
REQUIRE(name.set_email("john.doe@example.com"));
REQUIRE(name.email() == "john.doe@example.com");
REQUIRE(name.set_locality("Sao Paulo"));
REQUIRE(name.locality() == "Sao Paulo");
REQUIRE(name.set_organization("Independent"));
REQUIRE(name.organization() == "Independent");
REQUIRE(name.set_state("SP"));
REQUIRE(name.state() == "SP");
}
TEST_CASE("key/generation/rsa", "RSA key generation")
{
sslpkix::PrivateKey key;
REQUIRE(key.create());
RSA *rsa_keypair = RSA_new();
REQUIRE(rsa_keypair != NULL);
BIGNUM *f4 = BN_new();
REQUIRE(f4 != NULL);
REQUIRE(BN_set_word(f4, RSA_F4) != 0); // Use the fourth Fermat Number
BN_GENCB cb;
BN_GENCB_set(&cb, prime_generation_callback, NULL);
REQUIRE(RSA_generate_key_ex(rsa_keypair, 512, f4, &cb) != 0);
REQUIRE(key.copy(rsa_keypair));
BN_free(f4);
f4 = NULL;
RSA_free(rsa_keypair);
rsa_keypair = NULL;
// TODO(jweyrich): Move the following to a different test case, "key/copy_ctor"
sslpkix::PrivateKey keyCopy1(key);
REQUIRE(keyCopy1 == key);
}
TEST_CASE("certificate_name/extensions", "CertificateName extension")
{
int nid;
const char *oid = "1.2.3.4.5.31";
const char *short_name = "CTE";
const char *long_name = "customTextEntry";
const char *value = "Some value here";
REQUIRE(sslpkix::add_custom_object(oid, short_name, long_name, &nid));
sslpkix::CertificateName name;
REQUIRE(name.create());
REQUIRE(name.add_entry(short_name, value));
int index;
REQUIRE((index = name.find_entry(nid)) != -1);
REQUIRE(name.entry(index) != NULL);
REQUIRE(name.entry_count() == 1);
REQUIRE(name.entry_value(nid) == value);
// TODO(jweyrich): Move the following to a different test case, "certificate_name/copy_ctor"
sslpkix::CertificateName nameCopy1(name);
REQUIRE(nameCopy1 == name);
// TODO(jweyrich): Move the following to a different test case, "certificate_name/assignament_op"
sslpkix::CertificateName nameCopy2;
nameCopy2 = name;
REQUIRE(nameCopy2 == name);
}
int main(int argc, char *const argv[])
{
bool success = sslpkix::startup();
if (!success) {
std::cerr << "ERROR: Failed to initialize SSLPKIX." << std::endl;
exit(EXIT_FAILURE);
}
success = sslpkix::seed_prng();
if (!success) {
std::cerr << "ERROR: Failed to seed the PRNG." << std::endl;
exit(EXIT_FAILURE);
}
int result = Catch::Session().run(argc, argv);
sslpkix::shutdown();
return result;
}
<|endoftext|> |
<commit_before>/*
* Author: doe300
*
* See the file "LICENSE" for the full license governing this code.
*/
#include <cstdlib>
#include <fstream>
#include "cpptest.h"
#include "cpptest-main.h"
#include "TestArithmetic.h"
#include "TestEmulator.h"
#include "TestGraph.h"
#include "TestInstructions.h"
#include "TestOperators.h"
#include "TestSPIRVFrontend.h"
#include "TestMathFunctions.h"
#include "TestIntegerFunctions.h"
#include "TestCommonFunctions.h"
#include "TestGeometricFunctions.h"
#include "TestRelationalFunctions.h"
#include "TestVectorFunctions.h"
#include "TestMemoryAccess.h"
#include "TestConversionFunctions.h"
#include "TestOptimizations.h"
#include "tools.h"
#include "../lib/cpplog/include/logger.h"
#include "RegressionTest.h"
using namespace std;
static vc4c::Configuration config;
template<bool R>
static Test::Suite* newLLVMCompilationTest()
{
return new RegressionTest(config, vc4c::Frontend::LLVM_IR, R);
}
template<bool R>
static Test::Suite* newSPIRVCompiltionTest()
{
return new RegressionTest(config, vc4c::Frontend::SPIR_V, R);
}
template<bool R>
static Test::Suite* newCompilationTest()
{
return new RegressionTest(config, vc4c::Frontend::DEFAULT, R);
}
static Test::Suite* newFastRegressionTest()
{
return new RegressionTest(config, vc4c::Frontend::DEFAULT, true, true);
}
static Test::Suite* newEmulatorTest()
{
return new TestEmulator(config);
}
static Test::Suite* newMathFunctionsTest()
{
return new TestMathFunctions(config);
}
static Test::Suite* newArithmeticTest()
{
return new TestArithmetic(config);
}
static Test::Suite* newIntegerFunctionsTest()
{
return new TestIntegerFunctions(config);
}
static Test::Suite* newCommonFunctionsTest()
{
return new TestCommonFunctions(config);
}
static Test::Suite* newGometricFunctionsTest()
{
return new TestGeometricFunctions(config);
}
static Test::Suite* newRelationalFunctionsTest()
{
return new TestRelationalFunctions(config);
}
static Test::Suite* newVectorFunctionsTest()
{
return new TestVectorFunctions(config);
}
static Test::Suite* newMemoryAccessTest()
{
return new TestMemoryAccess(config);
}
static Test::Suite* newConversionFunctionsTest()
{
return new TestConversionFuntions(config);
}
/*
*
*/
int main(int argc, char** argv)
{
//only output errors
logging::LOGGER.reset(new logging::ConsoleLogger(logging::Level::WARNING));
Test::registerSuite(Test::newInstance<TestOptimizations>, "test-optimizations", "Runs smoke tests on the single optimization steps");
Test::registerSuite(Test::newInstance<TestOperators>, "test-operators", "Tests the implementation of some operators");
Test::registerSuite(Test::newInstance<TestInstructions>, "test-instructions", "Tests some common instruction handling");
Test::registerSuite(Test::newInstance<TestSPIRVFrontend>, "test-spirv", "Tests the SPIR-V front-end");
Test::registerSuite(newLLVMCompilationTest<true>, "regressions-llvm", "Runs the regression-test using the LLVM-IR front-end", false);
Test::registerSuite(newSPIRVCompiltionTest<true>, "regressions-spirv", "Runs the regression-test using the SPIR-V front-end", false);
Test::registerSuite(newCompilationTest<true>, "regressions", "Runs the regression-test using the default front-end", false);
Test::registerSuite(newCompilationTest<false>, "test-compilation", "Runs all the compilation tests using the default front-end", true);
Test::registerSuite(newLLVMCompilationTest<false>, "test-compilation-llvm", "Runs all the compilation tests using the LLVM-IR front-end", false);
Test::registerSuite(newSPIRVCompiltionTest<false>, "test-compilation-spirv", "Runs all the compilation tests using the SPIR-V front-end", false);
Test::registerSuite(newFastRegressionTest, "fast-regressions", "Runs regression test-cases marked as fast", false);
Test::registerSuite(newEmulatorTest, "test-emulator", "Runs selected code-samples through the emulator");
Test::registerSuite(newMathFunctionsTest, "emulate-math", "Runs emulation tests for the OpenCL standard-library math functions");
Test::registerSuite(Test::newInstance<TestGraph>, "test-graph", "Runs basic test for the graph data structure");
Test::registerSuite(newArithmeticTest, "emulate-arithmetic", "Runs emulation tests for various kind of operations");
Test::registerSuite(newIntegerFunctionsTest, "emulate-integer", "Runs emulation tests for the OpenCL standard-library integer functions");
Test::registerSuite(newCommonFunctionsTest, "emulate-common", "Runs emulation tests for the OpenCL standard-library common functions");
Test::registerSuite(newGometricFunctionsTest, "emulate-geometric", "Runs emulation tests for the OpenCL standard-library geometric functions");
Test::registerSuite(newRelationalFunctionsTest, "emulate-relational", "Runs emulation tests for the OpenCL standard-library relational functions");
Test::registerSuite(newVectorFunctionsTest, "emulate-vector", "Runs emulation tests for the OpenCL standard-library vector functions");
Test::registerSuite(newMemoryAccessTest, "emulate-memory", "Runs emulation tests for various functions testing different kinds of memory access");
Test::registerSuite(newConversionFunctionsTest, "emulate-conversions", "Runs emulation tests for the OpenCL standard-library type conversion functions");
for(auto i = 1; i < argc; ++i)
{
vc4c::tools::parseConfigurationParameter(config, argv[i]);
//TODO rewrite, actually print same help (parts of it) as VC4C
if(std::string("--help") == argv[i] || std::string("-h") == argv[i])
std::cout << "NOTE: This only lists the options for the 'cpptest-lite' test-suite. For more options see 'VC4C --help'!" << std::endl;
}
return Test::runSuites(argc, argv);
}
<commit_msg>fix: fix not to print mis-leading errors<commit_after>/*
* Author: doe300
*
* See the file "LICENSE" for the full license governing this code.
*/
#include <cstdlib>
#include <fstream>
#include <vector>
#include "cpptest.h"
#include "cpptest-main.h"
#include "TestArithmetic.h"
#include "TestEmulator.h"
#include "TestGraph.h"
#include "TestInstructions.h"
#include "TestOperators.h"
#include "TestSPIRVFrontend.h"
#include "TestMathFunctions.h"
#include "TestIntegerFunctions.h"
#include "TestCommonFunctions.h"
#include "TestGeometricFunctions.h"
#include "TestRelationalFunctions.h"
#include "TestVectorFunctions.h"
#include "TestMemoryAccess.h"
#include "TestConversionFunctions.h"
#include "TestOptimizations.h"
#include "tools.h"
#include "../lib/cpplog/include/logger.h"
#include "RegressionTest.h"
using namespace std;
static vc4c::Configuration config;
template<bool R>
static Test::Suite* newLLVMCompilationTest()
{
return new RegressionTest(config, vc4c::Frontend::LLVM_IR, R);
}
template<bool R>
static Test::Suite* newSPIRVCompiltionTest()
{
return new RegressionTest(config, vc4c::Frontend::SPIR_V, R);
}
template<bool R>
static Test::Suite* newCompilationTest()
{
return new RegressionTest(config, vc4c::Frontend::DEFAULT, R);
}
static Test::Suite* newFastRegressionTest()
{
return new RegressionTest(config, vc4c::Frontend::DEFAULT, true, true);
}
static Test::Suite* newEmulatorTest()
{
return new TestEmulator(config);
}
static Test::Suite* newMathFunctionsTest()
{
return new TestMathFunctions(config);
}
static Test::Suite* newArithmeticTest()
{
return new TestArithmetic(config);
}
static Test::Suite* newIntegerFunctionsTest()
{
return new TestIntegerFunctions(config);
}
static Test::Suite* newCommonFunctionsTest()
{
return new TestCommonFunctions(config);
}
static Test::Suite* newGometricFunctionsTest()
{
return new TestGeometricFunctions(config);
}
static Test::Suite* newRelationalFunctionsTest()
{
return new TestRelationalFunctions(config);
}
static Test::Suite* newVectorFunctionsTest()
{
return new TestVectorFunctions(config);
}
static Test::Suite* newMemoryAccessTest()
{
return new TestMemoryAccess(config);
}
static Test::Suite* newConversionFunctionsTest()
{
return new TestConversionFuntions(config);
}
/*
*
*/
int main(int argc, char** argv)
{
//only output errors
logging::LOGGER.reset(new logging::ConsoleLogger(logging::Level::WARNING));
Test::registerSuite(Test::newInstance<TestOptimizations>, "test-optimizations", "Runs smoke tests on the single optimization steps");
Test::registerSuite(Test::newInstance<TestOperators>, "test-operators", "Tests the implementation of some operators");
Test::registerSuite(Test::newInstance<TestInstructions>, "test-instructions", "Tests some common instruction handling");
Test::registerSuite(Test::newInstance<TestSPIRVFrontend>, "test-spirv", "Tests the SPIR-V front-end");
Test::registerSuite(newLLVMCompilationTest<true>, "regressions-llvm", "Runs the regression-test using the LLVM-IR front-end", false);
Test::registerSuite(newSPIRVCompiltionTest<true>, "regressions-spirv", "Runs the regression-test using the SPIR-V front-end", false);
Test::registerSuite(newCompilationTest<true>, "regressions", "Runs the regression-test using the default front-end", false);
Test::registerSuite(newCompilationTest<false>, "test-compilation", "Runs all the compilation tests using the default front-end", true);
Test::registerSuite(newLLVMCompilationTest<false>, "test-compilation-llvm", "Runs all the compilation tests using the LLVM-IR front-end", false);
Test::registerSuite(newSPIRVCompiltionTest<false>, "test-compilation-spirv", "Runs all the compilation tests using the SPIR-V front-end", false);
Test::registerSuite(newFastRegressionTest, "fast-regressions", "Runs regression test-cases marked as fast", false);
Test::registerSuite(newEmulatorTest, "test-emulator", "Runs selected code-samples through the emulator");
Test::registerSuite(newMathFunctionsTest, "emulate-math", "Runs emulation tests for the OpenCL standard-library math functions");
Test::registerSuite(Test::newInstance<TestGraph>, "test-graph", "Runs basic test for the graph data structure");
Test::registerSuite(newArithmeticTest, "emulate-arithmetic", "Runs emulation tests for various kind of operations");
Test::registerSuite(newIntegerFunctionsTest, "emulate-integer", "Runs emulation tests for the OpenCL standard-library integer functions");
Test::registerSuite(newCommonFunctionsTest, "emulate-common", "Runs emulation tests for the OpenCL standard-library common functions");
Test::registerSuite(newGometricFunctionsTest, "emulate-geometric", "Runs emulation tests for the OpenCL standard-library geometric functions");
Test::registerSuite(newRelationalFunctionsTest, "emulate-relational", "Runs emulation tests for the OpenCL standard-library relational functions");
Test::registerSuite(newVectorFunctionsTest, "emulate-vector", "Runs emulation tests for the OpenCL standard-library vector functions");
Test::registerSuite(newMemoryAccessTest, "emulate-memory", "Runs emulation tests for various functions testing different kinds of memory access");
Test::registerSuite(newConversionFunctionsTest, "emulate-conversions", "Runs emulation tests for the OpenCL standard-library type conversion functions");
auto args = std::vector<char*>();
for(auto i = 1; i < argc; ++i)
{
if (!vc4c::tools::parseConfigurationParameter(config, argv[i]))
args.push_back(argv[i]);
//TODO rewrite, actually print same help (parts of it) as VC4C
if(std::string("--help") == argv[i] || std::string("-h") == argv[i])
std::cout << "NOTE: This only lists the options for the 'cpptest-lite' test-suite. For more options see 'VC4C --help'!" << std::endl;
}
return Test::runSuites(int(args.size()), args.data());
}
<|endoftext|> |
<commit_before>// Copyright (c) 2005 Daniel Wallin, Arvid Norberg
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
// ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
// SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
// ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
// OR OTHER DEALINGS IN THE SOFTWARE.
#ifndef TEST_050415_HPP
#define TEST_050415_HPP
#include <luabind/error.hpp>
#include <boost/preprocessor/cat.hpp>
#include <luabind/lua_include.hpp>
#include <string>
// See boost/exception/detail/attribute_noreturn.hpp
#if defined(BOOST_CLANG)
// Clang's noreturn changes the type so that it is not recognizable by
// Boost.FunctionTypes.
# define LUABIND_ATTRIBUTE_NORETURN
#elif defined(_MSC_VER)
# define LUABIND_ATTRIBUTE_NORETURN __declspec(noreturn)
#elif defined(__GNUC__)
# define LUABIND_ATTRIBUTE_NORETURN __attribute__((__noreturn__))
#else
# define LUABIND_ATTRIBUTE_NORETURN
#endif
// Individual tests must provide a definition for this function:
void test_main(lua_State* L);
void report_failure(char const* str, char const* file, int line);
#if defined(_MSC_VER)
#define COUNTER_GUARD(x)
#else
#define COUNTER_GUARD(type) \
struct BOOST_PP_CAT(type, _counter_guard) \
{ \
~BOOST_PP_CAT(type, _counter_guard()) \
{ \
TEST_CHECK(counted_type<type>::count == 0); \
} \
} BOOST_PP_CAT(type, _guard)
#endif
#define TEST_REPORT_AUX(x, line, file) \
report_failure(x, line, file)
#define TEST_CHECK(x) \
if (!(x)) \
TEST_REPORT_AUX("TEST_CHECK failed: \"" #x "\"", __FILE__, __LINE__)
#define TEST_ERROR(x) \
TEST_REPORT_AUX((std::string("ERROR: \"") + x + "\"").c_str(), __FILE__, __LINE__)
#define TEST_NOTHROW(x) \
try \
{ \
x; \
} \
catch (...) \
{ \
TEST_ERROR("Exception thrown: " #x); \
}
void dostring(lua_State* L, char const* str);
template<class T>
struct counted_type
{
static int count;
counted_type()
{
++count;
}
counted_type(counted_type const&)
{
++count;
}
~counted_type()
{
TEST_CHECK(--count >= 0);
}
};
template<class T>
int counted_type<T>::count = 0;
#define DOSTRING_EXPECTED(state_, str, expected) \
{ \
try \
{ \
dostring(state_, str); \
} \
catch (luabind::error const& e) \
{ \
using namespace std; \
if (std::strcmp( \
lua_tostring(e.state(), -1) \
, expected)) \
{ \
TEST_ERROR(lua_tostring(e.state(), -1)); \
lua_pop(L, 1); \
} \
} \
catch (std::string const& s) \
{ \
if (s != expected) \
TEST_ERROR(s.c_str()); \
} \
}
#define DOSTRING(state_, str) \
{ \
try \
{ \
dostring(state_, str); \
} \
catch (luabind::error const& e) \
{ \
TEST_ERROR(lua_tostring(e.state(), -1)); \
lua_pop(L, 1); \
} \
catch (std::string const& s) \
{ \
TEST_ERROR(s.c_str()); \
} \
}
#endif // TEST_050415_HPP
<commit_msg>test: DOSTRING_EXPECTED: Only check contains and improve message.<commit_after>// Copyright (c) 2005 Daniel Wallin, Arvid Norberg
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
// ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
// SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
// ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
// OR OTHER DEALINGS IN THE SOFTWARE.
#ifndef TEST_050415_HPP
#define TEST_050415_HPP
#include <luabind/error.hpp>
#include <boost/preprocessor/cat.hpp>
#include <luabind/lua_include.hpp>
#include <string>
// See boost/exception/detail/attribute_noreturn.hpp
#if defined(BOOST_CLANG)
// Clang's noreturn changes the type so that it is not recognizable by
// Boost.FunctionTypes.
# define LUABIND_ATTRIBUTE_NORETURN
#elif defined(_MSC_VER)
# define LUABIND_ATTRIBUTE_NORETURN __declspec(noreturn)
#elif defined(__GNUC__)
# define LUABIND_ATTRIBUTE_NORETURN __attribute__((__noreturn__))
#else
# define LUABIND_ATTRIBUTE_NORETURN
#endif
// Individual tests must provide a definition for this function:
void test_main(lua_State* L);
void report_failure(char const* str, char const* file, int line);
#if defined(_MSC_VER)
#define COUNTER_GUARD(x)
#else
#define COUNTER_GUARD(type) \
struct BOOST_PP_CAT(type, _counter_guard) \
{ \
~BOOST_PP_CAT(type, _counter_guard()) \
{ \
TEST_CHECK(counted_type<type>::count == 0); \
} \
} BOOST_PP_CAT(type, _guard)
#endif
#define TEST_REPORT_AUX(x, line, file) \
report_failure(x, line, file)
#define TEST_CHECK(x) \
if (!(x)) \
TEST_REPORT_AUX("TEST_CHECK failed: \"" #x "\"", __FILE__, __LINE__)
#define TEST_ERROR(x) \
TEST_REPORT_AUX((std::string("ERROR: \"") + x + "\"").c_str(), __FILE__, __LINE__)
#define TEST_NOTHROW(x) \
try \
{ \
x; \
} \
catch (...) \
{ \
TEST_ERROR("Exception thrown: " #x); \
}
void dostring(lua_State* L, char const* str);
template<class T>
struct counted_type
{
static int count;
counted_type()
{
++count;
}
counted_type(counted_type const&)
{
++count;
}
~counted_type()
{
TEST_CHECK(--count >= 0);
}
};
template<class T>
int counted_type<T>::count = 0;
#define DOSTRING_EXPECTED(state_, str, expected) \
{ \
try \
{ \
dostring(state_, str); \
} \
catch (std::string const& s) \
{ \
if (s.find(expected) == std::string::npos) \
TEST_ERROR("Expected error '" \
+ expected + "' but got '" + s + "'"); \
} \
}
#define DOSTRING(state_, str) \
{ \
try \
{ \
dostring(state_, str); \
} \
catch (std::string const& s) \
{ \
TEST_ERROR(s.c_str()); \
} \
}
#endif // TEST_050415_HPP
<|endoftext|> |
<commit_before>#include "renderer.hpp"
#include "renderer_types.hpp"
#include "../src/estd.hpp"
FrameSeriesResource makeFrameSeries()
{
return estd::make_unique<FrameSeries>();
}
void drawOne(FrameSeries& output,
Program programDef,
ProgramInputs inputs,
GeometryDef geometryDef)
{
output.beginFrame();
// define and draw the content of the frame
if (programDef.vertexShader.source.empty()
|| programDef.fragmentShader.source.empty()) {
return;
}
auto const& program = output.program(programDef);
withShaderProgram(program,
[&output,&inputs,&program,&geometryDef]() {
auto textureTargets = std::vector<GLenum> {};
{
auto i = 0;
for (auto& textureInput : inputs.textures) {
auto unit = i;
auto& texture = output.texture(textureInput.content);
auto target = GL_TEXTURE0 + unit;
textureTargets.emplace_back(target);
OGL_TRACE;
glActiveTexture(target);
glBindTexture(GL_TEXTURE_2D, texture.id);
// program binding
auto textureUniform = glGetUniformLocation(program.id,
textureInput.name.c_str());
glUniform1i(textureUniform, unit);
i++;
OGL_TRACE;
}
}
auto const& mesh = output.mesh(geometryDef);
// draw here
withVertexArray(mesh.vertexArray, [&program,&inputs,&mesh]() {
auto vertexAttribVars = std::vector<GLint> {};
std::transform(std::begin(inputs.attribs),
std::end(inputs.attribs),
std::back_inserter(vertexAttribVars),
[&program](ProgramInputs::AttribArrayInput const& element) {
return glGetAttribLocation(program.id, element.name.c_str());
});
int i = 0;
for (auto attrib : vertexAttribVars) {
glBindBuffer(GL_ARRAY_BUFFER, mesh.vertexBuffers[i].id);
glVertexAttribPointer(attrib, 2, GL_FLOAT, GL_FALSE, 0, 0);
glEnableVertexAttribArray(attrib);
i++;
}
validate(program);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mesh.indices.id);
glDrawElements(GL_TRIANGLES,
mesh.indicesCount,
GL_UNSIGNED_INT,
0);
for (auto attrib : vertexAttribVars) {
glDisableVertexAttribArray(attrib);
}
});
// unbind
for (auto target : textureTargets) {
glActiveTexture(target);
glBindTexture(GL_TEXTURE_2D, 0);
}
glActiveTexture(GL_TEXTURE0);
OGL_TRACE;
});
};
<commit_msg>capture bindings separately from drawing<commit_after>#include "renderer.hpp"
#include "renderer_types.hpp"
#include "../src/estd.hpp"
FrameSeriesResource makeFrameSeries()
{
return estd::make_unique<FrameSeries>();
}
namespace
{
struct ProgramBindings {
std::vector<GLint> textureUniforms;
std::vector<GLint> arrayAttribs;
};
}
ProgramBindings programBindings(ShaderProgramResource const& program,
ProgramInputs const& inputs)
{
auto bindings = ProgramBindings {};
std::transform(std::begin(inputs.textures),
std::end(inputs.textures),
std::back_inserter(bindings.textureUniforms),
[&program](ProgramInputs::TextureInput const& element) {
return glGetUniformLocation(program.id, element.name.c_str());
});
std::transform(std::begin(inputs.attribs),
std::end(inputs.attribs),
std::back_inserter(bindings.arrayAttribs),
[&program](ProgramInputs::AttribArrayInput const& element) {
return glGetAttribLocation(program.id, element.name.c_str());
});
return bindings;
};
void drawOne(FrameSeries& output,
Program programDef,
ProgramInputs inputs,
GeometryDef geometryDef)
{
output.beginFrame();
// define and draw the content of the frame
if (programDef.vertexShader.source.empty()
|| programDef.fragmentShader.source.empty()) {
return;
}
auto const& program = output.program(programDef);
withShaderProgram(program,
[&output,&inputs,&program,&geometryDef]() {
auto vars = programBindings(program, inputs);
auto textureTargets = std::vector<GLenum> {};
{
auto i = 0;
for (auto& textureInput : inputs.textures) {
auto unit = i;
auto& texture = output.texture(textureInput.content);
auto target = GL_TEXTURE0 + unit;
textureTargets.emplace_back(target);
OGL_TRACE;
glActiveTexture(target);
glBindTexture(GL_TEXTURE_2D, texture.id);
glUniform1i(vars.textureUniforms[i], unit);
i++;
OGL_TRACE;
}
}
auto const& mesh = output.mesh(geometryDef);
// draw here
withVertexArray(mesh.vertexArray, [&program,&vars,&mesh]() {
auto& vertexAttribVars = vars.arrayAttribs;
int i = 0;
for (auto attrib : vertexAttribVars) {
glBindBuffer(GL_ARRAY_BUFFER, mesh.vertexBuffers[i].id);
glVertexAttribPointer(attrib, 2, GL_FLOAT, GL_FALSE, 0, 0);
glEnableVertexAttribArray(attrib);
i++;
}
validate(program);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mesh.indices.id);
glDrawElements(GL_TRIANGLES,
mesh.indicesCount,
GL_UNSIGNED_INT,
0);
for (auto attrib : vertexAttribVars) {
glDisableVertexAttribArray(attrib);
}
});
// unbind
for (auto target : textureTargets) {
glActiveTexture(target);
glBindTexture(GL_TEXTURE_2D, 0);
}
glActiveTexture(GL_TEXTURE0);
OGL_TRACE;
});
};
<|endoftext|> |
<commit_before>/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*
* Modified by ScyllaDB
* Copyright (C) 2015 ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include "unimplemented.hh"
#include "core/sstring.hh"
#include "core/shared_ptr.hh"
#include "core/distributed.hh"
#include "utils/bounded_stats_deque.hh"
#include "gms/i_failure_detector.hh"
#include <iostream>
#include <cmath>
#include <list>
#include <map>
#include <experimental/optional>
namespace gms {
class inet_address;
class i_failure_detection_event_listener;
class endpoint_state;
class arrival_window {
public:
using clk = std::chrono::system_clock;
private:
clk::time_point _tlast{clk::time_point::min()};
utils::bounded_stats_deque _arrival_intervals;
// this is useless except to provide backwards compatibility in phi_convict_threshold,
// because everyone seems pretty accustomed to the default of 8, and users who have
// already tuned their phi_convict_threshold for their own environments won't need to
// change.
static constexpr double PHI_FACTOR{M_LOG10El};
public:
arrival_window(int size)
: _arrival_intervals(size) {
}
// in the event of a long partition, never record an interval longer than the rpc timeout,
// since if a host is regularly experiencing connectivity problems lasting this long we'd
// rather mark it down quickly instead of adapting
// this value defaults to the same initial value the FD is seeded with
static clk::duration get_max_interval();
void add(clk::time_point value, const gms::inet_address& ep);
double mean();
// see CASSANDRA-2597 for an explanation of the math at work here.
double phi(clk::time_point tnow);
friend std::ostream& operator<<(std::ostream& os, const arrival_window& w);
};
/**
* This FailureDetector is an implementation of the paper titled
* "The Phi Accrual Failure Detector" by Hayashibara.
* Check the paper and the <i>IFailureDetector</i> interface for details.
*/
class failure_detector : public i_failure_detector, public seastar::async_sharded_service<failure_detector> {
private:
static constexpr int SAMPLE_SIZE = 1000;
// this is useless except to provide backwards compatibility in phi_convict_threshold,
// because everyone seems pretty accustomed to the default of 8, and users who have
// already tuned their phi_convict_threshold for their own environments won't need to
// change.
static constexpr double PHI_FACTOR{M_LOG10El};
std::map<inet_address, arrival_window> _arrival_samples;
std::list<i_failure_detection_event_listener*> _fd_evnt_listeners;
double _phi = 8;
static constexpr std::chrono::milliseconds DEFAULT_MAX_PAUSE{5000};
std::chrono::milliseconds get_max_local_pause() {
// FIXME: cassandra.max_local_pause_in_ms
#if 0
if (System.getProperty("cassandra.max_local_pause_in_ms") != null) {
long pause = Long.parseLong(System.getProperty("cassandra.max_local_pause_in_ms"));
logger.warn("Overriding max local pause time to {}ms", pause);
return pause * 1000000L;
} else {
return DEFAULT_MAX_PAUSE;
}
#endif
return DEFAULT_MAX_PAUSE;
}
std::experimental::optional<arrival_window::clk::time_point> _last_interpret;
arrival_window::clk::time_point _last_paused;
public:
failure_detector() = default;
failure_detector(double phi) : _phi(phi) {
}
future<> stop() {
return make_ready_future<>();
}
sstring get_all_endpoint_states();
std::map<sstring, sstring> get_simple_states();
int get_down_endpoint_count();
int get_up_endpoint_count();
sstring get_endpoint_state(sstring address);
private:
void append_endpoint_state(std::stringstream& ss, endpoint_state& state);
public:
/**
* Dump the inter arrival times for examination if necessary.
*/
#if 0
void dumpInterArrivalTimes() {
File file = FileUtils.createTempFile("failuredetector-", ".dat");
OutputStream os = null;
try
{
os = new BufferedOutputStream(new FileOutputStream(file, true));
os.write(toString().getBytes());
}
catch (IOException e)
{
throw new FSWriteError(e, file);
}
finally
{
FileUtils.closeQuietly(os);
}
}
#endif
void set_phi_convict_threshold(double phi);
double get_phi_convict_threshold();
bool is_alive(inet_address ep);
void report(inet_address ep);
void interpret(inet_address ep);
void force_conviction(inet_address ep);
void remove(inet_address ep);
void register_failure_detection_event_listener(i_failure_detection_event_listener* listener);
void unregister_failure_detection_event_listener(i_failure_detection_event_listener* listener);
friend std::ostream& operator<<(std::ostream& os, const failure_detector& x);
};
extern distributed<failure_detector> _the_failure_detector;
inline failure_detector& get_local_failure_detector() {
return _the_failure_detector.local();
}
inline distributed<failure_detector>& get_failure_detector() {
return _the_failure_detector;
}
inline future<> set_phi_convict_threshold(double phi) {
return smp::submit_to(0, [phi] {
get_local_failure_detector().set_phi_convict_threshold(phi);
});
}
inline future<double> get_phi_convict_threshold() {
return smp::submit_to(0, [] {
return get_local_failure_detector().get_phi_convict_threshold();
});
}
inline future<sstring> get_all_endpoint_states() {
return smp::submit_to(0, [] {
return get_local_failure_detector().get_all_endpoint_states();
});
}
inline future<sstring> get_endpoint_state(sstring address) {
return smp::submit_to(0, [address] {
return get_local_failure_detector().get_endpoint_state(address);
});
}
inline future<std::map<sstring, sstring>> get_simple_states() {
return smp::submit_to(0, [] {
return get_local_failure_detector().get_simple_states();
});
}
inline future<int> get_down_endpoint_count() {
return smp::submit_to(0, [] {
return get_local_failure_detector().get_down_endpoint_count();
});
}
inline future<int> get_up_endpoint_count() {
return smp::submit_to(0, [] {
return get_local_failure_detector().get_up_endpoint_count();
});
}
} // namespace gms
<commit_msg>failure_detector: add accessor and api shortcut for arrival samples<commit_after>/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*
* Modified by ScyllaDB
* Copyright (C) 2015 ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include "unimplemented.hh"
#include "core/sstring.hh"
#include "core/shared_ptr.hh"
#include "core/distributed.hh"
#include "utils/bounded_stats_deque.hh"
#include "gms/i_failure_detector.hh"
#include <iostream>
#include <cmath>
#include <list>
#include <map>
#include <experimental/optional>
namespace gms {
class inet_address;
class i_failure_detection_event_listener;
class endpoint_state;
class arrival_window {
public:
using clk = std::chrono::system_clock;
private:
clk::time_point _tlast{clk::time_point::min()};
utils::bounded_stats_deque _arrival_intervals;
// this is useless except to provide backwards compatibility in phi_convict_threshold,
// because everyone seems pretty accustomed to the default of 8, and users who have
// already tuned their phi_convict_threshold for their own environments won't need to
// change.
static constexpr double PHI_FACTOR{M_LOG10El};
public:
arrival_window(int size)
: _arrival_intervals(size) {
}
// in the event of a long partition, never record an interval longer than the rpc timeout,
// since if a host is regularly experiencing connectivity problems lasting this long we'd
// rather mark it down quickly instead of adapting
// this value defaults to the same initial value the FD is seeded with
static clk::duration get_max_interval();
void add(clk::time_point value, const gms::inet_address& ep);
double mean();
// see CASSANDRA-2597 for an explanation of the math at work here.
double phi(clk::time_point tnow);
friend std::ostream& operator<<(std::ostream& os, const arrival_window& w);
};
/**
* This FailureDetector is an implementation of the paper titled
* "The Phi Accrual Failure Detector" by Hayashibara.
* Check the paper and the <i>IFailureDetector</i> interface for details.
*/
class failure_detector : public i_failure_detector, public seastar::async_sharded_service<failure_detector> {
private:
static constexpr int SAMPLE_SIZE = 1000;
// this is useless except to provide backwards compatibility in phi_convict_threshold,
// because everyone seems pretty accustomed to the default of 8, and users who have
// already tuned their phi_convict_threshold for their own environments won't need to
// change.
static constexpr double PHI_FACTOR{M_LOG10El};
std::map<inet_address, arrival_window> _arrival_samples;
std::list<i_failure_detection_event_listener*> _fd_evnt_listeners;
double _phi = 8;
static constexpr std::chrono::milliseconds DEFAULT_MAX_PAUSE{5000};
std::chrono::milliseconds get_max_local_pause() {
// FIXME: cassandra.max_local_pause_in_ms
#if 0
if (System.getProperty("cassandra.max_local_pause_in_ms") != null) {
long pause = Long.parseLong(System.getProperty("cassandra.max_local_pause_in_ms"));
logger.warn("Overriding max local pause time to {}ms", pause);
return pause * 1000000L;
} else {
return DEFAULT_MAX_PAUSE;
}
#endif
return DEFAULT_MAX_PAUSE;
}
std::experimental::optional<arrival_window::clk::time_point> _last_interpret;
arrival_window::clk::time_point _last_paused;
public:
failure_detector() = default;
failure_detector(double phi) : _phi(phi) {
}
future<> stop() {
return make_ready_future<>();
}
sstring get_all_endpoint_states();
std::map<sstring, sstring> get_simple_states();
int get_down_endpoint_count();
int get_up_endpoint_count();
sstring get_endpoint_state(sstring address);
std::map<inet_address, arrival_window> arrival_samples() const {
return _arrival_samples;
}
private:
void append_endpoint_state(std::stringstream& ss, endpoint_state& state);
public:
/**
* Dump the inter arrival times for examination if necessary.
*/
#if 0
void dumpInterArrivalTimes() {
File file = FileUtils.createTempFile("failuredetector-", ".dat");
OutputStream os = null;
try
{
os = new BufferedOutputStream(new FileOutputStream(file, true));
os.write(toString().getBytes());
}
catch (IOException e)
{
throw new FSWriteError(e, file);
}
finally
{
FileUtils.closeQuietly(os);
}
}
#endif
void set_phi_convict_threshold(double phi);
double get_phi_convict_threshold();
bool is_alive(inet_address ep);
void report(inet_address ep);
void interpret(inet_address ep);
void force_conviction(inet_address ep);
void remove(inet_address ep);
void register_failure_detection_event_listener(i_failure_detection_event_listener* listener);
void unregister_failure_detection_event_listener(i_failure_detection_event_listener* listener);
friend std::ostream& operator<<(std::ostream& os, const failure_detector& x);
};
extern distributed<failure_detector> _the_failure_detector;
inline failure_detector& get_local_failure_detector() {
return _the_failure_detector.local();
}
inline distributed<failure_detector>& get_failure_detector() {
return _the_failure_detector;
}
inline future<> set_phi_convict_threshold(double phi) {
return smp::submit_to(0, [phi] {
get_local_failure_detector().set_phi_convict_threshold(phi);
});
}
inline future<double> get_phi_convict_threshold() {
return smp::submit_to(0, [] {
return get_local_failure_detector().get_phi_convict_threshold();
});
}
inline future<sstring> get_all_endpoint_states() {
return smp::submit_to(0, [] {
return get_local_failure_detector().get_all_endpoint_states();
});
}
inline future<sstring> get_endpoint_state(sstring address) {
return smp::submit_to(0, [address] {
return get_local_failure_detector().get_endpoint_state(address);
});
}
inline future<std::map<sstring, sstring>> get_simple_states() {
return smp::submit_to(0, [] {
return get_local_failure_detector().get_simple_states();
});
}
inline future<int> get_down_endpoint_count() {
return smp::submit_to(0, [] {
return get_local_failure_detector().get_down_endpoint_count();
});
}
inline future<int> get_up_endpoint_count() {
return smp::submit_to(0, [] {
return get_local_failure_detector().get_up_endpoint_count();
});
}
inline future<std::map<inet_address, arrival_window>> get_arrival_samples() {
return smp::submit_to(0, [] {
return get_local_failure_detector().arrival_samples();
});
}
} // namespace gms
<|endoftext|> |
<commit_before>#ifndef _X_CLIENT_HPP
#define _X_CLIENT_HPP
#include <list>
#include <xcb/xcb.h>
#include <xcb/damage.h>
#include "data_types.hpp"
#include "x_connection.hpp"
class x_client {
public:
friend std::ostream & operator<<(std::ostream &, const x_client &);
friend bool operator==(const x_client &, const xcb_window_t &);
friend bool operator==(const xcb_window_t &, const x_client &);
x_client(const x_connection & c, const xcb_window_t & window);
~x_client(void);
bool operator==(const x_client & other)
{
return _window == other._window;
}
rectangle_t & rectangle(void);
const rectangle_t & rectangle(void) const;
xcb_window_t & window(void);
const xcb_window_t & window(void) const;
unsigned int net_wm_desktop(void) const;
void handle(xcb_generic_event_t * ge);
void update_geometry(void);
private:
const x_connection & _c;
rectangle_t _rectangle;
unsigned int _net_wm_desktop;
xcb_window_t _window;
void get_net_wm_desktop(void);
};
std::list<x_client>
make_x_clients(x_connection & c, const std::vector<xcb_window_t> & windows);
bool
operator==(const x_client &, const xcb_window_t &);
bool
operator==(const xcb_window_t &, const x_client &);
#endif
<commit_msg>Make x_connection non-const to make it usable as event_source<commit_after>#ifndef _X_CLIENT_HPP
#define _X_CLIENT_HPP
#include <list>
#include <xcb/xcb.h>
#include <xcb/damage.h>
#include "data_types.hpp"
#include "x_connection.hpp"
class x_client {
public:
friend std::ostream & operator<<(std::ostream &, const x_client &);
friend bool operator==(const x_client &, const xcb_window_t &);
friend bool operator==(const xcb_window_t &, const x_client &);
x_client(x_connection & c, const xcb_window_t & window);
~x_client(void);
bool operator==(const x_client & other)
{
return _window == other._window;
}
rectangle_t & rectangle(void);
const rectangle_t & rectangle(void) const;
xcb_window_t & window(void);
const xcb_window_t & window(void) const;
unsigned int net_wm_desktop(void) const;
void handle(xcb_generic_event_t * ge);
void update_geometry(void);
private:
x_connection & _c;
rectangle_t _rectangle;
unsigned int _net_wm_desktop;
xcb_window_t _window;
void get_net_wm_desktop(void);
};
std::list<x_client>
make_x_clients(x_connection & c, const std::vector<xcb_window_t> & windows);
bool
operator==(const x_client &, const xcb_window_t &);
bool
operator==(const xcb_window_t &, const x_client &);
#endif
<|endoftext|> |
<commit_before>#include "cache.h"
#include "disk_read_thread.h"
#include "parameters.h"
#include "aio_private.h"
const int AIO_HIGH_PRIO_SLOTS = 7;
const int NUM_DIRTY_PAGES_TO_FETCH = 16 * 18;
disk_read_thread::disk_read_thread(const logical_file_partition &_partition,
int node_id, page_cache *cache, int _disk_id): thread(
std::string("io-thread-") + itoa(node_id), node_id), disk_id(
_disk_id), queue(node_id, std::string("io-queue-") + itoa(node_id),
IO_QUEUE_SIZE, INT_MAX, false), low_prio_queue(node_id,
// TODO let's allow the low-priority queue to
// be infinitely large for now.
std::string("io-queue-low_prio-") + itoa(node_id),
IO_QUEUE_SIZE, INT_MAX, false), partition(_partition), filter(
open_files, _disk_id)
{
this->cache = cache;
aio = new async_io(_partition, AIO_DEPTH_PER_FILE, this);
#ifdef STATISTICS
num_empty = 0;
num_reads = 0;
num_writes = 0;
num_read_bytes = 0;
num_write_bytes = 0;
num_low_prio_accesses = 0;
num_requested_flushes = 0;
num_ignored_flushes_evicted = 0;
num_ignored_flushes_cleaned = 0;
num_ignored_flushes_old = 0;
tot_flush_delay = 0;
max_flush_delay = 0;
min_flush_delay = LONG_MAX;
#endif
thread::start();
}
/**
* Notify the IO issuer of the ignored flushes.
* All flush requests must come from the same IO instance.
*/
void notify_ignored_flushes(io_request ignored_flushes[], int num_ignored)
{
for (int i = 0; i < num_ignored; i++) {
ignored_flushes[i].set_discarded(true);
io_request *flush = &ignored_flushes[i];
io_interface *io = flush->get_io();
io->notify_completion(&flush, 1);
}
}
int disk_read_thread::process_low_prio_msg(message<io_request> &low_prio_msg)
{
int num_accesses = 0;
#ifdef STATISTICS
struct timeval curr_time;
gettimeofday(&curr_time, NULL);
#endif
io_request req;
#ifdef MEMCHECK
io_request *ignored_flushes = new io_request[low_prio_msg.get_num_objs()];
#else
io_request ignored_flushes[low_prio_msg.get_num_objs()];
#endif
int num_ignored = 0;
while (low_prio_msg.has_next()
&& aio->num_available_IO_slots() > AIO_HIGH_PRIO_SLOTS
// We only submit requests to the disk when there aren't
// high-prio requests.
&& queue.is_empty()) {
// We copy the request to the local stack.
low_prio_msg.get_next(req);
#ifdef STATISTICS
num_low_prio_accesses++;
#endif
assert(req.get_num_bufs() == 1);
// The request doesn't own the page, so the reference count
// isn't increased while in the queue. Now we try to write
// it back, we need to increase its reference. The only
// safe way to do it is to use the search method of
// the page cache.
page_cache *cache = (page_cache *) req.get_priv();
thread_safe_page *p = (thread_safe_page *) cache->search(
req.get_offset());
// The page has been evicted.
if (p == NULL) {
// The original page has been evicted, we should clear
// the prepare-writeback flag on it.
req.get_page(0)->set_prepare_writeback(false);
#ifdef STATISTICS
num_ignored_flushes_evicted++;
#endif
ignored_flushes[num_ignored++] = req;
continue;
}
// If the original page has been evicted and the new page for
// the offset has been added to the cache.
if (p != req.get_page(0)) {
p->dec_ref();
// The original page has been evicted, we should clear
// the prepare-writeback flag on it.
req.get_page(0)->set_prepare_writeback(false);
#ifdef STATISTICS
num_ignored_flushes_evicted++;
#endif
ignored_flushes[num_ignored++] = req;
continue;
}
// If we are here, it means the page is the one we are looking for.
// We can be certain that the page won't be evicted because we have
// a reference on it.
// The object of page always exists, so we can always
// lock a page.
p->lock();
// The page may have been written back by the applications.
// But in either way, we need to reset the PREPARE_WRITEBACK
// flag.
p->set_prepare_writeback(false);
// If the page is being written back or has been written back,
// we can skip the request.
if (p->is_io_pending() || !p->is_dirty()
|| p->get_flush_score() > DISCARD_FLUSH_THRESHOLD) {
p->unlock();
p->dec_ref();
#ifdef STATISTICS
if (p->get_flush_score() > DISCARD_FLUSH_THRESHOLD)
num_ignored_flushes_old++;
else
num_ignored_flushes_cleaned++;
#endif
ignored_flushes[num_ignored++] = req;
continue;
}
#ifdef STATISTICS
long delay = time_diff_us(req.get_timestamp(), curr_time);
tot_flush_delay += delay;
if (delay < min_flush_delay)
min_flush_delay = delay;
if (delay > max_flush_delay)
max_flush_delay = delay;
if (req.get_access_method() == READ) {
num_reads++;
num_read_bytes += req.get_size();
}
else {
num_writes++;
num_write_bytes += req.get_size();
}
#endif
assert(p == req.get_page(0));
p->set_io_pending(true);
p->unlock();
num_accesses++;
// The current private data points to the page cache.
// Now the request owns the page, it's safe to point to
// the page directly.
req.set_priv(p);
// This should block the thread.
aio->access(&req, 1);
}
if (low_prio_msg.is_empty())
low_prio_msg.clear();
if (num_ignored > 0)
notify_ignored_flushes(ignored_flushes, num_ignored);
#ifdef MEMCHECK
delete [] ignored_flushes;
#endif
return num_accesses;
}
void disk_read_thread::run() {
// First, check if we need to flush requests.
int num_flushes = flush_counter.get();
if (num_flushes > 0) {
// This thread is the only one that decreases the counter.
flush_counter.dec(1);
assert(flush_counter.get() >= 0);
aio->flush_requests();
}
message<io_request> msg_buffer[LOCAL_BUF_SIZE];
message<io_request> low_prio_msg;
const int LOCAL_REQ_BUF_SIZE = IO_MSG_SIZE;
do {
int num = queue.fetch(msg_buffer, LOCAL_BUF_SIZE);
if (enable_debug)
printf("I/O thread %d: queue size: %d, low-prio queue size: %d\n",
get_node_id(), queue.get_num_entries(),
low_prio_queue.get_num_entries());
// The high-prio queue is empty.
while (num == 0) {
// we can process as many low-prio requests as possible,
// but they shouldn't block the thread.
if (!low_prio_queue.is_empty()
&& aio->num_available_IO_slots() > AIO_HIGH_PRIO_SLOTS) {
if (low_prio_msg.is_empty()) {
int num = low_prio_queue.fetch(&low_prio_msg, 1);
assert(num == 1);
}
process_low_prio_msg(low_prio_msg);
}
/*
* this is the only thread that fetch requests from the queue.
* If there are no incoming requests and there are pending IOs,
* let's complete the pending IOs first.
*/
else if (aio->num_pending_ios() > 0) {
aio->wait4complete(1);
}
else if (cache) {
int ret = cache->flush_dirty_pages(&filter, NUM_DIRTY_PAGES_TO_FETCH);
if (ret == 0)
break;
#ifdef STATISTICS
num_requested_flushes += ret;
#endif
}
else
break;
// Let's try to fetch requests again.
num = queue.fetch(msg_buffer, LOCAL_BUF_SIZE);
}
io_request local_reqs[LOCAL_REQ_BUF_SIZE];
for (int i = 0; i < num; i++) {
int num_reqs = msg_buffer[i].get_num_objs();
assert(num_reqs <= LOCAL_REQ_BUF_SIZE);
msg_buffer[i].get_next_objs(local_reqs, num_reqs);
#ifdef STATISTICS
for (int j = 0; j < num_reqs; j++) {
if (local_reqs[j].get_access_method() == READ) {
num_reads++;
num_read_bytes += local_reqs[j].get_size();
}
else {
num_writes++;
num_write_bytes += local_reqs[j].get_size();
}
}
#endif
aio->access(local_reqs, num_reqs);
msg_buffer[i].clear();
}
// We can't exit the loop if there are still pending AIO requests.
// This thread is responsible for processing completed AIO requests.
} while (aio->num_pending_ios() > 0);
}
int disk_read_thread::dirty_page_filter::filter(const thread_safe_page *pages[],
int num, const thread_safe_page *returned_pages[])
{
assert(mappers.size() == 1);
int num_returned = 0;
for (int i = 0; i < num; i++) {
int id = mappers[0]->map2file(pages[i]->get_offset());
if (this->disk_id == id)
returned_pages[num_returned++] = pages[i];
}
return num_returned;
}
<commit_msg>Fix a compilation error when clang++ is used.<commit_after>#include "cache.h"
#include "disk_read_thread.h"
#include "parameters.h"
#include "aio_private.h"
const int AIO_HIGH_PRIO_SLOTS = 7;
const int NUM_DIRTY_PAGES_TO_FETCH = 16 * 18;
disk_read_thread::disk_read_thread(const logical_file_partition &_partition,
int node_id, page_cache *cache, int _disk_id): thread(
std::string("io-thread-") + itoa(node_id), node_id), disk_id(
_disk_id), queue(node_id, std::string("io-queue-") + itoa(node_id),
IO_QUEUE_SIZE, INT_MAX, false), low_prio_queue(node_id,
// TODO let's allow the low-priority queue to
// be infinitely large for now.
std::string("io-queue-low_prio-") + itoa(node_id),
IO_QUEUE_SIZE, INT_MAX, false), partition(_partition), filter(
open_files, _disk_id)
{
this->cache = cache;
aio = new async_io(_partition, AIO_DEPTH_PER_FILE, this);
#ifdef STATISTICS
num_empty = 0;
num_reads = 0;
num_writes = 0;
num_read_bytes = 0;
num_write_bytes = 0;
num_low_prio_accesses = 0;
num_requested_flushes = 0;
num_ignored_flushes_evicted = 0;
num_ignored_flushes_cleaned = 0;
num_ignored_flushes_old = 0;
tot_flush_delay = 0;
max_flush_delay = 0;
min_flush_delay = LONG_MAX;
#endif
thread::start();
}
/**
* Notify the IO issuer of the ignored flushes.
* All flush requests must come from the same IO instance.
*/
void notify_ignored_flushes(io_request ignored_flushes[], int num_ignored)
{
for (int i = 0; i < num_ignored; i++) {
ignored_flushes[i].set_discarded(true);
io_request *flush = &ignored_flushes[i];
io_interface *io = flush->get_io();
io->notify_completion(&flush, 1);
}
}
int disk_read_thread::process_low_prio_msg(message<io_request> &low_prio_msg)
{
int num_accesses = 0;
#ifdef STATISTICS
struct timeval curr_time;
gettimeofday(&curr_time, NULL);
#endif
io_request req;
#ifdef MEMCHECK
io_request *ignored_flushes = new io_request[low_prio_msg.get_num_objs()];
#else
io_request ignored_flushes[low_prio_msg.get_num_objs()];
#endif
int num_ignored = 0;
while (low_prio_msg.has_next()
&& aio->num_available_IO_slots() > AIO_HIGH_PRIO_SLOTS
// We only submit requests to the disk when there aren't
// high-prio requests.
&& queue.is_empty()) {
// We copy the request to the local stack.
low_prio_msg.get_next(req);
#ifdef STATISTICS
num_low_prio_accesses++;
#endif
assert(req.get_num_bufs() == 1);
// The request doesn't own the page, so the reference count
// isn't increased while in the queue. Now we try to write
// it back, we need to increase its reference. The only
// safe way to do it is to use the search method of
// the page cache.
page_cache *cache = (page_cache *) req.get_priv();
thread_safe_page *p = (thread_safe_page *) cache->search(
req.get_offset());
// The page has been evicted.
if (p == NULL) {
// The original page has been evicted, we should clear
// the prepare-writeback flag on it.
req.get_page(0)->set_prepare_writeback(false);
#ifdef STATISTICS
num_ignored_flushes_evicted++;
#endif
ignored_flushes[num_ignored++] = req;
continue;
}
// If the original page has been evicted and the new page for
// the offset has been added to the cache.
if (p != req.get_page(0)) {
p->dec_ref();
// The original page has been evicted, we should clear
// the prepare-writeback flag on it.
req.get_page(0)->set_prepare_writeback(false);
#ifdef STATISTICS
num_ignored_flushes_evicted++;
#endif
ignored_flushes[num_ignored++] = req;
continue;
}
// If we are here, it means the page is the one we are looking for.
// We can be certain that the page won't be evicted because we have
// a reference on it.
// The object of page always exists, so we can always
// lock a page.
p->lock();
// The page may have been written back by the applications.
// But in either way, we need to reset the PREPARE_WRITEBACK
// flag.
p->set_prepare_writeback(false);
// If the page is being written back or has been written back,
// we can skip the request.
if (p->is_io_pending() || !p->is_dirty()
|| p->get_flush_score() > DISCARD_FLUSH_THRESHOLD) {
p->unlock();
p->dec_ref();
#ifdef STATISTICS
if (p->get_flush_score() > DISCARD_FLUSH_THRESHOLD)
num_ignored_flushes_old++;
else
num_ignored_flushes_cleaned++;
#endif
ignored_flushes[num_ignored++] = req;
continue;
}
#ifdef STATISTICS
long delay = time_diff_us(req.get_timestamp(), curr_time);
tot_flush_delay += delay;
if (delay < min_flush_delay)
min_flush_delay = delay;
if (delay > max_flush_delay)
max_flush_delay = delay;
if (req.get_access_method() == READ) {
num_reads++;
num_read_bytes += req.get_size();
}
else {
num_writes++;
num_write_bytes += req.get_size();
}
#endif
assert(p == req.get_page(0));
p->set_io_pending(true);
p->unlock();
num_accesses++;
// The current private data points to the page cache.
// Now the request owns the page, it's safe to point to
// the page directly.
req.set_priv(p);
// This should block the thread.
aio->access(&req, 1);
}
if (low_prio_msg.is_empty())
low_prio_msg.clear();
if (num_ignored > 0)
notify_ignored_flushes(ignored_flushes, num_ignored);
#ifdef MEMCHECK
delete [] ignored_flushes;
#endif
return num_accesses;
}
void disk_read_thread::run() {
// First, check if we need to flush requests.
int num_flushes = flush_counter.get();
if (num_flushes > 0) {
// This thread is the only one that decreases the counter.
flush_counter.dec(1);
assert(flush_counter.get() >= 0);
aio->flush_requests();
}
message<io_request> msg_buffer[LOCAL_BUF_SIZE];
message<io_request> low_prio_msg;
const int LOCAL_REQ_BUF_SIZE = IO_MSG_SIZE;
do {
int num = queue.fetch(msg_buffer, LOCAL_BUF_SIZE);
if (enable_debug)
printf("I/O thread %d: queue size: %d, low-prio queue size: %d\n",
get_node_id(), queue.get_num_entries(),
low_prio_queue.get_num_entries());
// The high-prio queue is empty.
while (num == 0) {
// we can process as many low-prio requests as possible,
// but they shouldn't block the thread.
if (!low_prio_queue.is_empty()
&& aio->num_available_IO_slots() > AIO_HIGH_PRIO_SLOTS) {
if (low_prio_msg.is_empty()) {
int num = low_prio_queue.fetch(&low_prio_msg, 1);
assert(num == 1);
}
process_low_prio_msg(low_prio_msg);
}
/*
* this is the only thread that fetch requests from the queue.
* If there are no incoming requests and there are pending IOs,
* let's complete the pending IOs first.
*/
else if (aio->num_pending_ios() > 0) {
aio->wait4complete(1);
}
else if (cache) {
int ret = cache->flush_dirty_pages(&filter, NUM_DIRTY_PAGES_TO_FETCH);
if (ret == 0)
break;
#ifdef STATISTICS
num_requested_flushes += ret;
#endif
}
else
break;
// Let's try to fetch requests again.
num = queue.fetch(msg_buffer, LOCAL_BUF_SIZE);
}
#ifdef MEMCHECK
io_request *local_reqs = new io_request[LOCAL_REQ_BUF_SIZE];
#else
io_request local_reqs[LOCAL_REQ_BUF_SIZE];
#endif
for (int i = 0; i < num; i++) {
int num_reqs = msg_buffer[i].get_num_objs();
assert(num_reqs <= LOCAL_REQ_BUF_SIZE);
msg_buffer[i].get_next_objs(local_reqs, num_reqs);
#ifdef STATISTICS
for (int j = 0; j < num_reqs; j++) {
if (local_reqs[j].get_access_method() == READ) {
num_reads++;
num_read_bytes += local_reqs[j].get_size();
}
else {
num_writes++;
num_write_bytes += local_reqs[j].get_size();
}
}
#endif
aio->access(local_reqs, num_reqs);
msg_buffer[i].clear();
}
#ifdef MEMCHECK
delete [] local_reqs;
#endif
// We can't exit the loop if there are still pending AIO requests.
// This thread is responsible for processing completed AIO requests.
} while (aio->num_pending_ios() > 0);
}
int disk_read_thread::dirty_page_filter::filter(const thread_safe_page *pages[],
int num, const thread_safe_page *returned_pages[])
{
assert(mappers.size() == 1);
int num_returned = 0;
for (int i = 0; i < num; i++) {
int id = mappers[0]->map2file(pages[i]->get_offset());
if (this->disk_id == id)
returned_pages[num_returned++] = pages[i];
}
return num_returned;
}
<|endoftext|> |
<commit_before>/* -*- c-basic-offset: 2 -*- */
/*
Copyright(C) 2010 Tetsuro IKEDA
Copyright(C) 2011-2013 Kentoku SHIBA
Copyright(C) 2011-2015 Kouhei Sutou <kou@clear-code.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <mrn_mysql.h>
#include "mrn_path_mapper.hpp"
#include <string.h>
namespace mrn {
char *PathMapper::default_path_prefix = NULL;
char *PathMapper::default_mysql_data_home_path = NULL;
PathMapper::PathMapper(const char *original_mysql_path,
const char *path_prefix,
const char *mysql_data_home_path)
: original_mysql_path_(original_mysql_path),
path_prefix_(path_prefix),
mysql_data_home_path_(mysql_data_home_path) {
db_path_[0] = '\0';
db_name_[0] = '\0';
table_name_[0] = '\0';
mysql_table_name_[0] = '\0';
mysql_path_[0] = '\0';
}
/**
* "./${db}/${table}" ==> "${db}.mrn"
* "./${db}/" ==> "${db}.mrn"
* "/tmp/mysql-test/var/tmp/mysqld.1/#sql27c5_1_0" ==>
* "/tmp/mysql-test/var/tmp/mysqld.1/#sql27c5_1_0.mrn"
*/
const char *PathMapper::db_path() {
if (db_path_[0] != '\0') {
return db_path_;
}
if (original_mysql_path_[0] == FN_CURLIB &&
original_mysql_path_[1] == FN_LIBCHAR) {
if (path_prefix_) {
strcpy(db_path_, path_prefix_);
}
int i = 2, j = strlen(db_path_), len;
len = strlen(original_mysql_path_);
while (original_mysql_path_[i] != FN_LIBCHAR && i < len) {
db_path_[j++] = original_mysql_path_[i++];
}
db_path_[j] = '\0';
} else if (mysql_data_home_path_) {
int len = strlen(original_mysql_path_);
int mysql_data_home_len = strlen(mysql_data_home_path_);
if (len > mysql_data_home_len &&
!strncmp(original_mysql_path_,
mysql_data_home_path_,
mysql_data_home_len)) {
int i = mysql_data_home_len, j;
if (path_prefix_ && path_prefix_[0] == FN_LIBCHAR) {
strcpy(db_path_, path_prefix_);
j = strlen(db_path_);
} else {
grn_memcpy(db_path_, mysql_data_home_path_, mysql_data_home_len);
if (path_prefix_) {
if (path_prefix_[0] == FN_CURLIB &&
path_prefix_[1] == FN_LIBCHAR) {
strcpy(&db_path_[mysql_data_home_len], &path_prefix_[2]);
} else {
strcpy(&db_path_[mysql_data_home_len], path_prefix_);
}
j = strlen(db_path_);
} else {
j = mysql_data_home_len;
}
}
while (original_mysql_path_[i] != FN_LIBCHAR && i < len) {
db_path_[j++] = original_mysql_path_[i++];
}
if (i == len) {
grn_memcpy(db_path_, original_mysql_path_, len);
} else {
db_path_[j] = '\0';
}
} else {
strcpy(db_path_, original_mysql_path_);
}
} else {
strcpy(db_path_, original_mysql_path_);
}
strcat(db_path_, MRN_DB_FILE_SUFFIX);
return db_path_;
}
/**
* "./${db}/${table}" ==> "${db}"
* "./${db}/" ==> "${db}"
* "/tmp/mysql-test/var/tmp/mysqld.1/#sql27c5_1_0" ==>
* "/tmp/mysql-test/var/tmp/mysqld.1/#sql27c5_1_0"
*/
const char *PathMapper::db_name() {
if (db_name_[0] != '\0') {
return db_name_;
}
if (original_mysql_path_[0] == FN_CURLIB &&
original_mysql_path_[1] == FN_LIBCHAR) {
int i = 2, j = 0, len;
len = strlen(original_mysql_path_);
while (original_mysql_path_[i] != FN_LIBCHAR && i < len) {
db_name_[j++] = original_mysql_path_[i++];
}
db_name_[j] = '\0';
} else if (mysql_data_home_path_) {
int len = strlen(original_mysql_path_);
int mysql_data_home_len = strlen(mysql_data_home_path_);
if (len > mysql_data_home_len &&
!strncmp(original_mysql_path_,
mysql_data_home_path_,
mysql_data_home_len)) {
int i = mysql_data_home_len, j = 0;
while (original_mysql_path_[i] != FN_LIBCHAR && i < len) {
db_name_[j++] = original_mysql_path_[i++];
}
if (i == len) {
grn_memcpy(db_name_, original_mysql_path_, len);
} else {
db_name_[j] = '\0';
}
} else {
strcpy(db_name_, original_mysql_path_);
}
} else {
strcpy(db_name_, original_mysql_path_);
}
return db_name_;
}
/**
* "./${db}/${table}" ==> "${table}" (with encoding first '_')
*/
const char *PathMapper::table_name() {
if (table_name_[0] != '\0') {
return table_name_;
}
int len = strlen(original_mysql_path_);
int i = len, j = 0;
for (; original_mysql_path_[--i] != FN_LIBCHAR ;) {}
if (original_mysql_path_[i + 1] == '_') {
table_name_[j++] = '@';
table_name_[j++] = '0';
table_name_[j++] = '0';
table_name_[j++] = '5';
table_name_[j++] = 'f';
i++;
}
for (; i < len ;) {
table_name_[j++] = original_mysql_path_[++i];
}
table_name_[j] = '\0';
return table_name_;
}
/**
* "./${db}/${table}" ==> "${table}" (without encoding first '_')
*/
const char *PathMapper::mysql_table_name() {
if (mysql_table_name_[0] != '\0') {
return mysql_table_name_;
}
int len = strlen(original_mysql_path_);
int i = len, j = 0;
for (; original_mysql_path_[--i] != FN_LIBCHAR ;) {}
for (; i < len ;) {
if (len - i - 1 >= 3 &&
strncmp(original_mysql_path_ + i + 1, "#P#", 3) == 0) {
break;
}
mysql_table_name_[j++] = original_mysql_path_[++i];
}
mysql_table_name_[j] = '\0';
return mysql_table_name_;
}
/**
* "./${db}/${table}" ==> "./${db}/${table}"
* "./${db}/${table}#P#xxx" ==> "./${db}/${table}"
*/
const char *PathMapper::mysql_path() {
if (mysql_path_[0] != '\0') {
return mysql_path_;
}
int i;
int len = strlen(original_mysql_path_);
for (i = 0; i < len; i++) {
if (len - i >= 3 &&
strncmp(original_mysql_path_ + i, "#P#", 3) == 0) {
break;
}
mysql_path_[i] = original_mysql_path_[i];
}
mysql_path_[i] = '\0';
return mysql_path_;
}
bool PathMapper::is_internal_table_name() {
return mysql_table_name()[0] == '#';
}
}
<commit_msg>Add a missing include for std::memcpy<commit_after>/* -*- c-basic-offset: 2 -*- */
/*
Copyright(C) 2010 Tetsuro IKEDA
Copyright(C) 2011-2013 Kentoku SHIBA
Copyright(C) 2011-2015 Kouhei Sutou <kou@clear-code.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <mrn_mysql.h>
#include "mrn_path_mapper.hpp"
#include <string.h>
#include <cstring>
namespace mrn {
char *PathMapper::default_path_prefix = NULL;
char *PathMapper::default_mysql_data_home_path = NULL;
PathMapper::PathMapper(const char *original_mysql_path,
const char *path_prefix,
const char *mysql_data_home_path)
: original_mysql_path_(original_mysql_path),
path_prefix_(path_prefix),
mysql_data_home_path_(mysql_data_home_path) {
db_path_[0] = '\0';
db_name_[0] = '\0';
table_name_[0] = '\0';
mysql_table_name_[0] = '\0';
mysql_path_[0] = '\0';
}
/**
* "./${db}/${table}" ==> "${db}.mrn"
* "./${db}/" ==> "${db}.mrn"
* "/tmp/mysql-test/var/tmp/mysqld.1/#sql27c5_1_0" ==>
* "/tmp/mysql-test/var/tmp/mysqld.1/#sql27c5_1_0.mrn"
*/
const char *PathMapper::db_path() {
if (db_path_[0] != '\0') {
return db_path_;
}
if (original_mysql_path_[0] == FN_CURLIB &&
original_mysql_path_[1] == FN_LIBCHAR) {
if (path_prefix_) {
strcpy(db_path_, path_prefix_);
}
int i = 2, j = strlen(db_path_), len;
len = strlen(original_mysql_path_);
while (original_mysql_path_[i] != FN_LIBCHAR && i < len) {
db_path_[j++] = original_mysql_path_[i++];
}
db_path_[j] = '\0';
} else if (mysql_data_home_path_) {
int len = strlen(original_mysql_path_);
int mysql_data_home_len = strlen(mysql_data_home_path_);
if (len > mysql_data_home_len &&
!strncmp(original_mysql_path_,
mysql_data_home_path_,
mysql_data_home_len)) {
int i = mysql_data_home_len, j;
if (path_prefix_ && path_prefix_[0] == FN_LIBCHAR) {
strcpy(db_path_, path_prefix_);
j = strlen(db_path_);
} else {
grn_memcpy(db_path_, mysql_data_home_path_, mysql_data_home_len);
if (path_prefix_) {
if (path_prefix_[0] == FN_CURLIB &&
path_prefix_[1] == FN_LIBCHAR) {
strcpy(&db_path_[mysql_data_home_len], &path_prefix_[2]);
} else {
strcpy(&db_path_[mysql_data_home_len], path_prefix_);
}
j = strlen(db_path_);
} else {
j = mysql_data_home_len;
}
}
while (original_mysql_path_[i] != FN_LIBCHAR && i < len) {
db_path_[j++] = original_mysql_path_[i++];
}
if (i == len) {
grn_memcpy(db_path_, original_mysql_path_, len);
} else {
db_path_[j] = '\0';
}
} else {
strcpy(db_path_, original_mysql_path_);
}
} else {
strcpy(db_path_, original_mysql_path_);
}
strcat(db_path_, MRN_DB_FILE_SUFFIX);
return db_path_;
}
/**
* "./${db}/${table}" ==> "${db}"
* "./${db}/" ==> "${db}"
* "/tmp/mysql-test/var/tmp/mysqld.1/#sql27c5_1_0" ==>
* "/tmp/mysql-test/var/tmp/mysqld.1/#sql27c5_1_0"
*/
const char *PathMapper::db_name() {
if (db_name_[0] != '\0') {
return db_name_;
}
if (original_mysql_path_[0] == FN_CURLIB &&
original_mysql_path_[1] == FN_LIBCHAR) {
int i = 2, j = 0, len;
len = strlen(original_mysql_path_);
while (original_mysql_path_[i] != FN_LIBCHAR && i < len) {
db_name_[j++] = original_mysql_path_[i++];
}
db_name_[j] = '\0';
} else if (mysql_data_home_path_) {
int len = strlen(original_mysql_path_);
int mysql_data_home_len = strlen(mysql_data_home_path_);
if (len > mysql_data_home_len &&
!strncmp(original_mysql_path_,
mysql_data_home_path_,
mysql_data_home_len)) {
int i = mysql_data_home_len, j = 0;
while (original_mysql_path_[i] != FN_LIBCHAR && i < len) {
db_name_[j++] = original_mysql_path_[i++];
}
if (i == len) {
grn_memcpy(db_name_, original_mysql_path_, len);
} else {
db_name_[j] = '\0';
}
} else {
strcpy(db_name_, original_mysql_path_);
}
} else {
strcpy(db_name_, original_mysql_path_);
}
return db_name_;
}
/**
* "./${db}/${table}" ==> "${table}" (with encoding first '_')
*/
const char *PathMapper::table_name() {
if (table_name_[0] != '\0') {
return table_name_;
}
int len = strlen(original_mysql_path_);
int i = len, j = 0;
for (; original_mysql_path_[--i] != FN_LIBCHAR ;) {}
if (original_mysql_path_[i + 1] == '_') {
table_name_[j++] = '@';
table_name_[j++] = '0';
table_name_[j++] = '0';
table_name_[j++] = '5';
table_name_[j++] = 'f';
i++;
}
for (; i < len ;) {
table_name_[j++] = original_mysql_path_[++i];
}
table_name_[j] = '\0';
return table_name_;
}
/**
* "./${db}/${table}" ==> "${table}" (without encoding first '_')
*/
const char *PathMapper::mysql_table_name() {
if (mysql_table_name_[0] != '\0') {
return mysql_table_name_;
}
int len = strlen(original_mysql_path_);
int i = len, j = 0;
for (; original_mysql_path_[--i] != FN_LIBCHAR ;) {}
for (; i < len ;) {
if (len - i - 1 >= 3 &&
strncmp(original_mysql_path_ + i + 1, "#P#", 3) == 0) {
break;
}
mysql_table_name_[j++] = original_mysql_path_[++i];
}
mysql_table_name_[j] = '\0';
return mysql_table_name_;
}
/**
* "./${db}/${table}" ==> "./${db}/${table}"
* "./${db}/${table}#P#xxx" ==> "./${db}/${table}"
*/
const char *PathMapper::mysql_path() {
if (mysql_path_[0] != '\0') {
return mysql_path_;
}
int i;
int len = strlen(original_mysql_path_);
for (i = 0; i < len; i++) {
if (len - i >= 3 &&
strncmp(original_mysql_path_ + i, "#P#", 3) == 0) {
break;
}
mysql_path_[i] = original_mysql_path_[i];
}
mysql_path_[i] = '\0';
return mysql_path_;
}
bool PathMapper::is_internal_table_name() {
return mysql_table_name()[0] == '#';
}
}
<|endoftext|> |
<commit_before>#include <qpdf/QPDFCrypto_openssl.hh>
#include <cstring>
#include <stdexcept>
#include <qpdf/QIntC.hh>
static void
bad_bits(int bits)
{
throw std::logic_error(
std::string("unsupported key length: ") + std::to_string(bits));
}
static void
check_openssl(int status)
{
if (status != 1)
{
throw std::runtime_error("openssl error");
}
}
QPDFCrypto_openssl::QPDFCrypto_openssl() :
md_ctx(EVP_MD_CTX_new()), cipher_ctx(EVP_CIPHER_CTX_new())
{
memset(md_out, 0, sizeof(md_out));
EVP_MD_CTX_init(md_ctx);
EVP_CIPHER_CTX_init(cipher_ctx);
}
QPDFCrypto_openssl::~QPDFCrypto_openssl()
{
EVP_MD_CTX_reset(md_ctx);
EVP_CIPHER_CTX_reset(cipher_ctx);
EVP_CIPHER_CTX_free(cipher_ctx);
EVP_MD_CTX_free(md_ctx);
}
void
QPDFCrypto_openssl::provideRandomData(unsigned char* data, size_t len)
{
check_openssl(RAND_bytes(data, QIntC::to_int(len)));
}
void
QPDFCrypto_openssl::MD5_init()
{
check_openssl(EVP_MD_CTX_reset(md_ctx));
check_openssl(EVP_DigestInit_ex(md_ctx, EVP_md5(), nullptr));
}
void
QPDFCrypto_openssl::SHA2_init(int bits)
{
const EVP_MD* md = EVP_sha512();
switch (bits)
{
case 256:
md = EVP_sha256();
break;
case 384:
md = EVP_sha384();
break;
case 512:
md = EVP_sha512();
break;
default:
bad_bits(bits);
return;
}
sha2_bits = static_cast<size_t>(bits);
check_openssl(EVP_MD_CTX_reset(md_ctx));
check_openssl(EVP_DigestInit_ex(md_ctx, md, nullptr));
}
void
QPDFCrypto_openssl::MD5_update(unsigned char const* data, size_t len)
{
check_openssl(EVP_DigestUpdate(md_ctx, data, len));
}
void
QPDFCrypto_openssl::SHA2_update(unsigned char const* data, size_t len)
{
check_openssl(EVP_DigestUpdate(md_ctx, data, len));
}
void
QPDFCrypto_openssl::MD5_finalize()
{
if (EVP_MD_CTX_md(md_ctx))
{
check_openssl(EVP_DigestFinal(md_ctx, md_out + 0, nullptr));
}
}
void
QPDFCrypto_openssl::SHA2_finalize()
{
if (EVP_MD_CTX_md(md_ctx))
{
check_openssl(EVP_DigestFinal(md_ctx, md_out + 0, nullptr));
}
}
void
QPDFCrypto_openssl::MD5_digest(MD5_Digest d)
{
memcpy(d, md_out, sizeof(QPDFCryptoImpl::MD5_Digest));
}
std::string
QPDFCrypto_openssl::SHA2_digest()
{
return std::string(reinterpret_cast<char*>(md_out), sha2_bits / 8);
}
void
QPDFCrypto_openssl::RC4_init(unsigned char const* key_data, int key_len)
{
check_openssl(EVP_CIPHER_CTX_reset(cipher_ctx));
if (key_len == -1)
{
key_len = QIntC::to_int(
strlen(reinterpret_cast<const char*>(key_data)));
}
check_openssl(
EVP_EncryptInit_ex(cipher_ctx, EVP_rc4(), nullptr, nullptr, nullptr));
check_openssl(EVP_CIPHER_CTX_set_key_length(cipher_ctx, key_len));
check_openssl(
EVP_EncryptInit_ex(cipher_ctx, nullptr, nullptr, key_data, nullptr));
}
void
QPDFCrypto_openssl::rijndael_init(
bool encrypt, unsigned char const* key_data, size_t key_len,
bool cbc_mode, unsigned char* cbc_block)
{
const EVP_CIPHER* cipher = nullptr;
switch (key_len)
{
case 32:
cipher = cbc_mode ? EVP_aes_256_cbc() : EVP_aes_256_ecb();
break;
case 24:
cipher = cbc_mode ? EVP_aes_192_cbc() : EVP_aes_192_ecb();
break;
default:
cipher = cbc_mode ? EVP_aes_128_cbc() : EVP_aes_128_ecb();
break;
}
check_openssl(EVP_CIPHER_CTX_reset(cipher_ctx));
check_openssl(
EVP_CipherInit_ex(cipher_ctx, cipher, nullptr,
key_data, cbc_block, encrypt));
check_openssl(EVP_CIPHER_CTX_set_padding(cipher_ctx, 0));
}
void
QPDFCrypto_openssl::RC4_process(
unsigned char* in_data, size_t len, unsigned char* out_data)
{
if (nullptr == out_data)
{
out_data = in_data;
}
int out_len = static_cast<int>(len);
check_openssl(
EVP_EncryptUpdate(cipher_ctx, out_data, &out_len, in_data, out_len));
}
void
QPDFCrypto_openssl::rijndael_process(
unsigned char* in_data, unsigned char* out_data)
{
int len = QPDFCryptoImpl::rijndael_buf_size;
check_openssl(EVP_CipherUpdate(cipher_ctx, out_data, &len, in_data, len));
}
void
QPDFCrypto_openssl::RC4_finalize()
{
if (EVP_CIPHER_CTX_cipher(cipher_ctx))
{
check_openssl(EVP_CIPHER_CTX_reset(cipher_ctx));
}
}
void
QPDFCrypto_openssl::rijndael_finalize()
{
if (EVP_CIPHER_CTX_cipher(cipher_ctx))
{
check_openssl(EVP_CIPHER_CTX_reset(cipher_ctx));
}
}
<commit_msg>Include detailed OpenSSL error messages<commit_after>#include <qpdf/QPDFCrypto_openssl.hh>
#include <cstring>
#include <stdexcept>
#include <string>
#include <openssl/err.h>
#include <qpdf/QIntC.hh>
static void
bad_bits(int bits)
{
throw std::logic_error(
std::string("unsupported key length: ") + std::to_string(bits));
}
static void
check_openssl(int status)
{
if (status != 1)
{
// OpenSSL creates a "queue" of errors; copy the first (innermost)
// error to the exception message.
char buf[256] = "";
ERR_error_string_n(ERR_get_error(), buf, sizeof(buf));
std::string what = "OpenSSL error: ";
what += buf;
throw std::runtime_error(what);
}
ERR_clear_error();
}
QPDFCrypto_openssl::QPDFCrypto_openssl() :
md_ctx(EVP_MD_CTX_new()), cipher_ctx(EVP_CIPHER_CTX_new())
{
memset(md_out, 0, sizeof(md_out));
EVP_MD_CTX_init(md_ctx);
EVP_CIPHER_CTX_init(cipher_ctx);
}
QPDFCrypto_openssl::~QPDFCrypto_openssl()
{
EVP_MD_CTX_reset(md_ctx);
EVP_CIPHER_CTX_reset(cipher_ctx);
EVP_CIPHER_CTX_free(cipher_ctx);
EVP_MD_CTX_free(md_ctx);
}
void
QPDFCrypto_openssl::provideRandomData(unsigned char* data, size_t len)
{
check_openssl(RAND_bytes(data, QIntC::to_int(len)));
}
void
QPDFCrypto_openssl::MD5_init()
{
check_openssl(EVP_MD_CTX_reset(md_ctx));
check_openssl(EVP_DigestInit_ex(md_ctx, EVP_md5(), nullptr));
}
void
QPDFCrypto_openssl::SHA2_init(int bits)
{
const EVP_MD* md = EVP_sha512();
switch (bits)
{
case 256:
md = EVP_sha256();
break;
case 384:
md = EVP_sha384();
break;
case 512:
md = EVP_sha512();
break;
default:
bad_bits(bits);
return;
}
sha2_bits = static_cast<size_t>(bits);
check_openssl(EVP_MD_CTX_reset(md_ctx));
check_openssl(EVP_DigestInit_ex(md_ctx, md, nullptr));
}
void
QPDFCrypto_openssl::MD5_update(unsigned char const* data, size_t len)
{
check_openssl(EVP_DigestUpdate(md_ctx, data, len));
}
void
QPDFCrypto_openssl::SHA2_update(unsigned char const* data, size_t len)
{
check_openssl(EVP_DigestUpdate(md_ctx, data, len));
}
void
QPDFCrypto_openssl::MD5_finalize()
{
if (EVP_MD_CTX_md(md_ctx))
{
check_openssl(EVP_DigestFinal(md_ctx, md_out + 0, nullptr));
}
}
void
QPDFCrypto_openssl::SHA2_finalize()
{
if (EVP_MD_CTX_md(md_ctx))
{
check_openssl(EVP_DigestFinal(md_ctx, md_out + 0, nullptr));
}
}
void
QPDFCrypto_openssl::MD5_digest(MD5_Digest d)
{
memcpy(d, md_out, sizeof(QPDFCryptoImpl::MD5_Digest));
}
std::string
QPDFCrypto_openssl::SHA2_digest()
{
return std::string(reinterpret_cast<char*>(md_out), sha2_bits / 8);
}
void
QPDFCrypto_openssl::RC4_init(unsigned char const* key_data, int key_len)
{
check_openssl(EVP_CIPHER_CTX_reset(cipher_ctx));
if (key_len == -1)
{
key_len = QIntC::to_int(
strlen(reinterpret_cast<const char*>(key_data)));
}
check_openssl(
EVP_EncryptInit_ex(cipher_ctx, EVP_rc4(), nullptr, nullptr, nullptr));
check_openssl(EVP_CIPHER_CTX_set_key_length(cipher_ctx, key_len));
check_openssl(
EVP_EncryptInit_ex(cipher_ctx, nullptr, nullptr, key_data, nullptr));
}
void
QPDFCrypto_openssl::rijndael_init(
bool encrypt, unsigned char const* key_data, size_t key_len,
bool cbc_mode, unsigned char* cbc_block)
{
const EVP_CIPHER* cipher = nullptr;
switch (key_len)
{
case 32:
cipher = cbc_mode ? EVP_aes_256_cbc() : EVP_aes_256_ecb();
break;
case 24:
cipher = cbc_mode ? EVP_aes_192_cbc() : EVP_aes_192_ecb();
break;
default:
cipher = cbc_mode ? EVP_aes_128_cbc() : EVP_aes_128_ecb();
break;
}
check_openssl(EVP_CIPHER_CTX_reset(cipher_ctx));
check_openssl(
EVP_CipherInit_ex(cipher_ctx, cipher, nullptr,
key_data, cbc_block, encrypt));
check_openssl(EVP_CIPHER_CTX_set_padding(cipher_ctx, 0));
}
void
QPDFCrypto_openssl::RC4_process(
unsigned char* in_data, size_t len, unsigned char* out_data)
{
if (nullptr == out_data)
{
out_data = in_data;
}
int out_len = static_cast<int>(len);
check_openssl(
EVP_EncryptUpdate(cipher_ctx, out_data, &out_len, in_data, out_len));
}
void
QPDFCrypto_openssl::rijndael_process(
unsigned char* in_data, unsigned char* out_data)
{
int len = QPDFCryptoImpl::rijndael_buf_size;
check_openssl(EVP_CipherUpdate(cipher_ctx, out_data, &len, in_data, len));
}
void
QPDFCrypto_openssl::RC4_finalize()
{
if (EVP_CIPHER_CTX_cipher(cipher_ctx))
{
check_openssl(EVP_CIPHER_CTX_reset(cipher_ctx));
}
}
void
QPDFCrypto_openssl::rijndael_finalize()
{
if (EVP_CIPHER_CTX_cipher(cipher_ctx))
{
check_openssl(EVP_CIPHER_CTX_reset(cipher_ctx));
}
}
<|endoftext|> |
<commit_before>/*ckwg +5
* Copyright 2012 by Kitware, Inc. All Rights Reserved. Please refer to
* KITWARE_LICENSE.TXT for licensing information, or contact General Counsel,
* Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065.
*/
#include "gaussian_smooth.h"
#include <boost/make_shared.hpp>
#include "cl_manager.h"
extern const char* gaussian_smooth_source;
//*****************************************************************************
void gaussian_smooth::init()
{
cl_task::build_source(gaussian_smooth_source);
conv_x = make_kernel("convolveHoriz1D");
conv_y = make_kernel("convolveVert1D");
}
//*****************************************************************************
void gaussian_smooth::init(const cl_program_t &prog)
{
program = prog;
conv_x = make_kernel("convolveHoriz1D");
conv_y = make_kernel("convolveVert1D");
}
//*****************************************************************************
cl_task_t gaussian_smooth::clone()
{
gaussian_smooth_t clone_ = boost::make_shared<gaussian_smooth>(*this);
clone_->queue = cl_manager::inst()->create_queue();
return clone_;
}
//*****************************************************************************
template <class T>
void gaussian_smooth::smooth(const vil_image_view<T> &img, vil_image_view<T> &output, float sigma, int kernel_radius) const
{
cl_image img_cl = cl_manager::inst()->create_image<T>(img);
cl_image result = smooth( img_cl, sigma, kernel_radius);
cl::size_t<3> origin;
origin.push_back(0);
origin.push_back(0);
origin.push_back(0);
cl::size_t<3> region;
region.push_back(img.ni());
region.push_back(img.nj());
region.push_back(1);
output.set_size(img.ni(), img.nj());
queue->enqueueReadImage(*result().get(), CL_TRUE, origin, region, 0, 0, (float *)output.top_left_ptr());
}
//*****************************************************************************
cl_image gaussian_smooth::smooth(const cl_image &img, float sigma, int kernel_radius) const
{
int kernel_size = 2*kernel_radius+1;
float *filter = new float[kernel_size];
float coeff = 1.0f / sqrt(6.2831853072f * sigma * sigma);
int i = 0;
for (float x = -kernel_radius; x <= kernel_radius; x++, i++)
{
filter[i] = coeff * exp( (- x * x) / (2.0f * sigma * sigma));
}
cl_buffer smoothing_kernel = cl_manager::inst()->create_buffer<float>(CL_MEM_READ_ONLY, 5);
queue->enqueueWriteBuffer(*smoothing_kernel().get(), CL_TRUE, 0, smoothing_kernel.mem_size(), filter);
size_t ni = img.width(), nj = img.height();
cl_image working = cl_manager::inst()->create_image(img.format(), CL_MEM_READ_WRITE, ni, nj);
cl_image result = cl_manager::inst()->create_image(img.format(), CL_MEM_READ_WRITE, ni, nj);
// Set arguments to kernel
conv_x->setArg(0, *img().get());
conv_x->setArg(1, *smoothing_kernel().get());
conv_x->setArg(2, kernel_size);
conv_x->setArg(3, *working().get());
// Set arguments to kernel
conv_y->setArg(0, *working().get());
conv_y->setArg(1, *smoothing_kernel().get());
conv_y->setArg(2, kernel_size);
conv_y->setArg(3, *result().get());
//Run the kernel on specific ND range
cl::NDRange global(ni, nj);
//cl::NDRange local(1,1);
queue->enqueueNDRangeKernel(*conv_x.get(), cl::NullRange, global, cl::NullRange);
queue->enqueueBarrier();
queue->enqueueNDRangeKernel(*conv_y.get(), cl::NullRange, global, cl::NullRange);
queue->finish();
delete [] filter;
return result;
}
//*****************************************************************************
template void gaussian_smooth::smooth(const vil_image_view<vxl_byte> &, vil_image_view<vxl_byte> &, float, int) const;
template void gaussian_smooth::smooth(const vil_image_view<float> &, vil_image_view<float> &, float, int) const;
<commit_msg>fixed gaussian filter kernel to sume to 1<commit_after>/*ckwg +5
* Copyright 2012 by Kitware, Inc. All Rights Reserved. Please refer to
* KITWARE_LICENSE.TXT for licensing information, or contact General Counsel,
* Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065.
*/
#include "gaussian_smooth.h"
#include <boost/make_shared.hpp>
#include "cl_manager.h"
extern const char* gaussian_smooth_source;
//*****************************************************************************
void gaussian_smooth::init()
{
cl_task::build_source(gaussian_smooth_source);
conv_x = make_kernel("convolveHoriz1D");
conv_y = make_kernel("convolveVert1D");
}
//*****************************************************************************
void gaussian_smooth::init(const cl_program_t &prog)
{
program = prog;
conv_x = make_kernel("convolveHoriz1D");
conv_y = make_kernel("convolveVert1D");
}
//*****************************************************************************
cl_task_t gaussian_smooth::clone()
{
gaussian_smooth_t clone_ = boost::make_shared<gaussian_smooth>(*this);
clone_->queue = cl_manager::inst()->create_queue();
return clone_;
}
//*****************************************************************************
template <class T>
void gaussian_smooth::smooth(const vil_image_view<T> &img, vil_image_view<T> &output, float sigma, int kernel_radius) const
{
cl_image img_cl = cl_manager::inst()->create_image<T>(img);
cl_image result = smooth( img_cl, sigma, kernel_radius);
cl::size_t<3> origin;
origin.push_back(0);
origin.push_back(0);
origin.push_back(0);
cl::size_t<3> region;
region.push_back(img.ni());
region.push_back(img.nj());
region.push_back(1);
output.set_size(img.ni(), img.nj());
queue->enqueueReadImage(*result().get(), CL_TRUE, origin, region, 0, 0, (float *)output.top_left_ptr());
}
//*****************************************************************************
cl_image gaussian_smooth::smooth(const cl_image &img, float sigma, int kernel_radius) const
{
int kernel_size = 2*kernel_radius+1;
float *filter = new float[kernel_size];
int i = 0;
float sum=0.0f;
for (float x = -kernel_radius; x <= kernel_radius; x++, i++)
{
filter[i] = exp( (- x * x) / (2.0f * sigma * sigma));
sum += filter[i];
}
for (i = 0; i < kernel_size; ++i)
{
filter[i] /= sum;
}
cl_buffer smoothing_kernel = cl_manager::inst()->create_buffer<float>(CL_MEM_READ_ONLY, 5);
queue->enqueueWriteBuffer(*smoothing_kernel().get(), CL_TRUE, 0, smoothing_kernel.mem_size(), filter);
size_t ni = img.width(), nj = img.height();
cl_image working = cl_manager::inst()->create_image(img.format(), CL_MEM_READ_WRITE, ni, nj);
cl_image result = cl_manager::inst()->create_image(img.format(), CL_MEM_READ_WRITE, ni, nj);
// Set arguments to kernel
conv_x->setArg(0, *img().get());
conv_x->setArg(1, *smoothing_kernel().get());
conv_x->setArg(2, kernel_size);
conv_x->setArg(3, *working().get());
// Set arguments to kernel
conv_y->setArg(0, *working().get());
conv_y->setArg(1, *smoothing_kernel().get());
conv_y->setArg(2, kernel_size);
conv_y->setArg(3, *result().get());
//Run the kernel on specific ND range
cl::NDRange global(ni, nj);
//cl::NDRange local(1,1);
queue->enqueueNDRangeKernel(*conv_x.get(), cl::NullRange, global, cl::NullRange);
queue->enqueueBarrier();
queue->enqueueNDRangeKernel(*conv_y.get(), cl::NullRange, global, cl::NullRange);
queue->finish();
delete [] filter;
return result;
}
//*****************************************************************************
template void gaussian_smooth::smooth(const vil_image_view<vxl_byte> &, vil_image_view<vxl_byte> &, float, int) const;
template void gaussian_smooth::smooth(const vil_image_view<float> &, vil_image_view<float> &, float, int) const;
<|endoftext|> |
<commit_before>/*
This file is part of cpp-ethereum.
cpp-ethereum is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
cpp-ethereum 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @author Christian <c@ethdev.com>
* @date 2014
* Full-stack compiler that converts a source code string to bytecode.
*/
#include <libsolidity/AST.h>
#include <libsolidity/Scanner.h>
#include <libsolidity/Parser.h>
#include <libsolidity/GlobalContext.h>
#include <libsolidity/NameAndTypeResolver.h>
#include <libsolidity/Compiler.h>
#include <libsolidity/CompilerStack.h>
#include <jsonrpc/json/json.h>
using namespace std;
namespace dev
{
namespace solidity
{
void CompilerStack::setSource(string const& _sourceCode)
{
reset();
m_scanner = make_shared<Scanner>(CharStream(_sourceCode));
}
void CompilerStack::parse()
{
if (!m_scanner)
BOOST_THROW_EXCEPTION(CompilerError() << errinfo_comment("Source not available."));
m_contractASTNode = Parser().parse(m_scanner);
m_globalContext = make_shared<GlobalContext>();
m_globalContext->setCurrentContract(*m_contractASTNode);
NameAndTypeResolver(m_globalContext->getDeclarations()).resolveNamesAndTypes(*m_contractASTNode);
m_parseSuccessful = true;
}
void CompilerStack::parse(string const& _sourceCode)
{
setSource(_sourceCode);
parse();
}
bytes const& CompilerStack::compile(bool _optimize)
{
if (!m_parseSuccessful)
BOOST_THROW_EXCEPTION(CompilerError() << errinfo_comment("Parsing was not successful."));
m_bytecode.clear();
m_compiler = make_shared<Compiler>();
m_compiler->compileContract(*m_contractASTNode, m_globalContext->getMagicVariables());
return m_bytecode = m_compiler->getAssembledBytecode(_optimize);
}
bytes const& CompilerStack::compile(string const& _sourceCode, bool _optimize)
{
parse(_sourceCode);
return compile(_optimize);
}
void CompilerStack::streamAssembly(ostream& _outStream)
{
if (!m_compiler || m_bytecode.empty())
BOOST_THROW_EXCEPTION(CompilerError() << errinfo_comment("Compilation was not successful."));
m_compiler->streamAssembly(_outStream);
}
string const& CompilerStack::getInterface()
{
Json::StyledWriter writer;
if (!m_parseSuccessful)
BOOST_THROW_EXCEPTION(CompilerError() << errinfo_comment("Parsing was not successful."));
if (m_interface.empty())
{
Json::Value methods(Json::arrayValue);
vector<FunctionDefinition const*> exportedFunctions = m_contractASTNode->getInterfaceFunctions();
for (FunctionDefinition const* f: exportedFunctions)
{
Json::Value method;
Json::Value inputs(Json::arrayValue);
Json::Value outputs(Json::arrayValue);
auto streamVariables = [&](vector<ASTPointer<VariableDeclaration>> const& _vars,
Json::Value &json)
{
for (ASTPointer<VariableDeclaration> const& var: _vars)
{
Json::Value input;
input["name"] = var->getName();
input["type"] = var->getType()->toString();
json.append(input);
}
};
method["name"] = f->getName();
streamVariables(f->getParameters(), inputs);
method["inputs"] = inputs;
streamVariables(f->getReturnParameters(), outputs);
method["outputs"] = outputs;
methods.append(method);
}
m_interface = writer.write(methods);
}
return m_interface;
}
string const& CompilerStack::getDocumentation()
{
Json::StyledWriter writer;
if (!m_parseSuccessful)
BOOST_THROW_EXCEPTION(CompilerError() << errinfo_comment("Parsing was not successful."));
if (m_documentation.empty())
{
Json::Value doc;
Json::Value methods(Json::objectValue);
vector<FunctionDefinition const*> exportedFunctions = m_contractASTNode->getInterfaceFunctions();
for (FunctionDefinition const* f: exportedFunctions)
{
Json::Value user;
auto strPtr = f->getDocumentation();
if (strPtr)
{
user["user"] = Json::Value(*strPtr);
methods[f->getName()] = user;
}
}
doc["methods"] = methods;
m_documentation = writer.write(doc);
}
return m_documentation;
}
bytes CompilerStack::staticCompile(std::string const& _sourceCode, bool _optimize)
{
CompilerStack stack;
return stack.compile(_sourceCode, _optimize);
}
}
}
<commit_msg>Removing unneeded local variable in CompilerStack::getDocumentation()<commit_after>/*
This file is part of cpp-ethereum.
cpp-ethereum is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
cpp-ethereum 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @author Christian <c@ethdev.com>
* @date 2014
* Full-stack compiler that converts a source code string to bytecode.
*/
#include <libsolidity/AST.h>
#include <libsolidity/Scanner.h>
#include <libsolidity/Parser.h>
#include <libsolidity/GlobalContext.h>
#include <libsolidity/NameAndTypeResolver.h>
#include <libsolidity/Compiler.h>
#include <libsolidity/CompilerStack.h>
#include <jsonrpc/json/json.h>
using namespace std;
namespace dev
{
namespace solidity
{
void CompilerStack::setSource(string const& _sourceCode)
{
reset();
m_scanner = make_shared<Scanner>(CharStream(_sourceCode));
}
void CompilerStack::parse()
{
if (!m_scanner)
BOOST_THROW_EXCEPTION(CompilerError() << errinfo_comment("Source not available."));
m_contractASTNode = Parser().parse(m_scanner);
m_globalContext = make_shared<GlobalContext>();
m_globalContext->setCurrentContract(*m_contractASTNode);
NameAndTypeResolver(m_globalContext->getDeclarations()).resolveNamesAndTypes(*m_contractASTNode);
m_parseSuccessful = true;
}
void CompilerStack::parse(string const& _sourceCode)
{
setSource(_sourceCode);
parse();
}
bytes const& CompilerStack::compile(bool _optimize)
{
if (!m_parseSuccessful)
BOOST_THROW_EXCEPTION(CompilerError() << errinfo_comment("Parsing was not successful."));
m_bytecode.clear();
m_compiler = make_shared<Compiler>();
m_compiler->compileContract(*m_contractASTNode, m_globalContext->getMagicVariables());
return m_bytecode = m_compiler->getAssembledBytecode(_optimize);
}
bytes const& CompilerStack::compile(string const& _sourceCode, bool _optimize)
{
parse(_sourceCode);
return compile(_optimize);
}
void CompilerStack::streamAssembly(ostream& _outStream)
{
if (!m_compiler || m_bytecode.empty())
BOOST_THROW_EXCEPTION(CompilerError() << errinfo_comment("Compilation was not successful."));
m_compiler->streamAssembly(_outStream);
}
string const& CompilerStack::getInterface()
{
Json::StyledWriter writer;
if (!m_parseSuccessful)
BOOST_THROW_EXCEPTION(CompilerError() << errinfo_comment("Parsing was not successful."));
if (m_interface.empty())
{
Json::Value methods(Json::arrayValue);
vector<FunctionDefinition const*> exportedFunctions = m_contractASTNode->getInterfaceFunctions();
for (FunctionDefinition const* f: exportedFunctions)
{
Json::Value method;
Json::Value inputs(Json::arrayValue);
Json::Value outputs(Json::arrayValue);
auto streamVariables = [&](vector<ASTPointer<VariableDeclaration>> const& _vars,
Json::Value &json)
{
for (ASTPointer<VariableDeclaration> const& var: _vars)
{
Json::Value input;
input["name"] = var->getName();
input["type"] = var->getType()->toString();
json.append(input);
}
};
method["name"] = f->getName();
streamVariables(f->getParameters(), inputs);
method["inputs"] = inputs;
streamVariables(f->getReturnParameters(), outputs);
method["outputs"] = outputs;
methods.append(method);
}
m_interface = writer.write(methods);
}
return m_interface;
}
string const& CompilerStack::getDocumentation()
{
Json::StyledWriter writer;
if (!m_parseSuccessful)
BOOST_THROW_EXCEPTION(CompilerError() << errinfo_comment("Parsing was not successful."));
if (m_documentation.empty())
{
Json::Value doc;
Json::Value methods(Json::objectValue);
for (FunctionDefinition const* f: m_contractASTNode->getInterfaceFunctions())
{
Json::Value user;
auto strPtr = f->getDocumentation();
if (strPtr)
{
user["user"] = Json::Value(*strPtr);
methods[f->getName()] = user;
}
}
doc["methods"] = methods;
m_documentation = writer.write(doc);
}
return m_documentation;
}
bytes CompilerStack::staticCompile(std::string const& _sourceCode, bool _optimize)
{
CompilerStack stack;
return stack.compile(_sourceCode, _optimize);
}
}
}
<|endoftext|> |
<commit_before>#include <array>
#if (defined(__GNUC__) || _MSC_VER > 1600) // No <thread> in VS2010
#include <thread>
#endif
#include "GoTools/lrsplines2D/LRBSpline2D.h"
#include "GoTools/utils/checks.h"
#include "GoTools/utils/StreamUtils.h"
// The following is a workaround since 'thread_local' is not well supported by compilers yet
#if defined(__GNUC__)
#define thread_local __thread
#elif _MSC_VER > 1600 //defined(_WIN32)
#define thread_local __declspec( thread )
#else
#define thread_local // _MSC_VER == 1600, i.e. VS2010
#endif
using namespace std;
namespace Go
{
//------------------------------------------------------------------------------
namespace
//------------------------------------------------------------------------------
{
// Since some static buffers (provided for efficiency reasons) need to know the maximum degree
// used at compile time, the following constant, MAX_DEGREE, is here defined.
const int MAX_DEGREE = 20;
//------------------------------------------------------------------------------
double B(int deg, double t, const int* knot_ix, const double* kvals, bool at_end)
//------------------------------------------------------------------------------
{
// a POD rather than a stl vector used below due to the limitations of thread_local as currently
// defined (see #defines at the top of this file). A practical consequence is that
// MAX_DEGREE must be known at compile time.
static double thread_local tmp[MAX_DEGREE+2];
// only evaluate if within support
if ((t < kvals[knot_ix[0]]) || (t > kvals[knot_ix[deg+1]])) return 0;
assert(deg <= MAX_DEGREE);
fill (tmp, tmp+deg+1, 0);
// computing lowest-degree B-spline components (all zero except one)
int nonzero_ix = 0;
if (at_end) while (kvals[knot_ix[nonzero_ix+1]] < t) ++nonzero_ix;
else while (kvals[knot_ix[nonzero_ix+1]] <= t) ++nonzero_ix;
assert(nonzero_ix <= deg);
tmp[nonzero_ix] = 1;
// accumulating to attain correct degree
for (int d = 1; d != deg+1; ++d) {
const int lbound = max (0, nonzero_ix - d);
const int ubound = min (nonzero_ix, deg - d);
for (int i = lbound; i <= ubound; ++i) {
const double k_i = kvals[knot_ix[i]];
const double k_ip1 = kvals[knot_ix[i+1]];
const double k_ipd = kvals[knot_ix[i+d]];
const double k_ipdp1 = kvals[knot_ix[i+d+1]];
const double alpha = (k_ipd == k_i) ? 0 : (t - k_i) / (k_ipd - k_i);
const double beta = (k_ipdp1 == k_ip1) ? 0 : (k_ipdp1 - t) / (k_ipdp1 - k_ip1);
tmp[i] = alpha * tmp[i] + beta * tmp[i+1];
}
}
return tmp[0];
}
// //------------------------------------------------------------------------------
// // B-spline evaluation function
// double B_recursive(int deg, double t, const int* knot_ix, const double* kvals, bool at_end)
// //------------------------------------------------------------------------------
// {
// const double k0 = kvals[knot_ix[0]];
// const double k1 = kvals[knot_ix[1]];
// const double kd = kvals[knot_ix[deg]];
// const double kdp1 = kvals[knot_ix[deg+1]];
// assert(deg >= 0);
// if (deg == 0)
// return // at_end: half-open interval at end of domain should be considered differently
// (! at_end) ? ((k0 <= t && t < k1) ? 1 : 0) :
// ((k0 < t && t <= k1) ? 1 : 0);
// const double fac1 = (kd > k0) ? (t - k0) / (kd - k0) : 0;
// const double fac2 = (kdp1 > k1) ? (kdp1 - t) / (kdp1 - k1) : 0;
// return
// ( (fac1 > 0) ? fac1 * B(deg-1, t, knot_ix, kvals, at_end) : 0) +
// ( (fac2 > 0) ? fac2 * B(deg-1, t, knot_ix+1, kvals, at_end) : 0);
// }
//------------------------------------------------------------------------------
// B-spline derivative evaluation
double dB(int deg, double t, const int* knot_ix, const double* kvals, bool at_end, int der=1)
//------------------------------------------------------------------------------
{
const double k0 = kvals[knot_ix[0]];
const double k1 = kvals[knot_ix[1]];
const double kdeg = kvals[knot_ix[deg]];
const double kdp1 = kvals[knot_ix[deg+1]];
assert(der > 0); //@@ we should perhaps check that derivative <=
// degree - multiplicity
if (deg == 0)
return 0;
double fac1 = (kdeg > k0) ? ( deg) / (kdeg - k0) : 0;
double fac2 = (kdp1 > k1) ? (-deg) / (kdp1 - k1) : 0;
return
( (fac1 != 0) ?
( fac1 * ( (der>1) ?
dB(deg-1, t, knot_ix, kvals, at_end, der-1)
: B(deg-1, t, knot_ix, kvals, at_end) ) )
: 0 ) +
( (fac2 != 0) ?
( fac2 * ( (der>1) ?
dB(deg-1, t, knot_ix+1, kvals, at_end, der-1)
: B(deg-1, t, knot_ix+1, kvals, at_end) ) )
: 0 ) ;
}
//------------------------------------------------------------------------------
double compute_univariate_spline(int deg,
double u,
const vector<int>& k_ixes,
const double* kvals,
int deriv,
bool on_end)
//------------------------------------------------------------------------------
{
return (deriv>0) ?
dB(deg, u, &k_ixes[0], kvals, on_end, deriv) :
B( deg, u, &k_ixes[0], kvals, on_end);
}
}; // anonymous namespace
//==============================================================================
bool LRBSpline2D::operator<(const LRBSpline2D& rhs) const
//==============================================================================
{
const int tmp1 = compare_seq(kvec_u_.begin(), kvec_u_.end(), rhs.kvec_u_.begin(), rhs.kvec_u_.end());
if (tmp1 != 0) return (tmp1 < 0);
const int tmp2 = compare_seq(kvec_v_.begin(), kvec_v_.end(), rhs.kvec_v_.begin(), rhs.kvec_v_.end());
if (tmp2 != 0) return (tmp2 < 0);
const int tmp3 = compare_seq(coef_times_gamma_.begin(), coef_times_gamma_.end(),
rhs.coef_times_gamma_.begin(), rhs.coef_times_gamma_.end());
if (tmp3 != 0) return (tmp3 < 0);
return gamma_ < rhs.gamma_;
}
//==============================================================================
bool LRBSpline2D::operator==(const LRBSpline2D& rhs) const
//==============================================================================
{
const int tmp1 = compare_seq(kvec_u_.begin(), kvec_u_.end(),
rhs.kvec_u_.begin(), rhs.kvec_u_.end());
if (tmp1 != 0)
return false;
const int tmp2 = compare_seq(kvec_v_.begin(), kvec_v_.end(),
rhs.kvec_v_.begin(), rhs.kvec_v_.end());
if (tmp2 != 0)
return false;
return true;
}
//==============================================================================
void LRBSpline2D::write(ostream& os) const
//==============================================================================
{
object_to_stream(os, coef_times_gamma_);
object_to_stream(os, gamma_);
object_to_stream(os, '\n');
object_to_stream(os, kvec_u_);
object_to_stream(os, kvec_v_);
}
//==============================================================================
void LRBSpline2D::read(istream& is)
//==============================================================================
{
object_from_stream(is, coef_times_gamma_);
object_from_stream(is, gamma_);
object_from_stream(is, kvec_u_);
object_from_stream(is, kvec_v_);
}
//==============================================================================
double LRBSpline2D::evalBasisFunction(double u,
double v,
const double* const kvals_u,
const double* const kvals_v,
int u_deriv,
int v_deriv,
bool u_at_end,
bool v_at_end) const
//==============================================================================
{
return
compute_univariate_spline(degree(XFIXED), u, kvec(XFIXED), kvals_u, u_deriv, u_at_end) *
compute_univariate_spline(degree(YFIXED), v, kvec(YFIXED), kvals_v, v_deriv, v_at_end);
}
//==============================================================================
bool LRBSpline2D::overlaps(Element2D *el) const
//==============================================================================
{
// To be implemented
return false;
}
//==============================================================================
bool LRBSpline2D::addSupport(const Element2D *el)
//==============================================================================
{
for (size_t i=0; i<support_.size(); i++) {
if(el == support_[i]) {
return false;
}
}
support_.push_back(el);
return true;
}
//==============================================================================
void LRBSpline2D::removeSupport(const Element2D *el)
//==============================================================================
{
for (size_t i=0; i<support_.size(); i++) {
if(el == support_[i]) {
support_[i] = support_.back();
support_[support_.size()-1] = NULL;
support_.pop_back();
return;
}
}
}
}; // end namespace Go
<commit_msg>Function not implemented<commit_after>#include <array>
#if (defined(__GNUC__) || _MSC_VER > 1600) // No <thread> in VS2010
#include <thread>
#endif
#include "GoTools/lrsplines2D/LRBSpline2D.h"
#include "GoTools/utils/checks.h"
#include "GoTools/utils/StreamUtils.h"
// The following is a workaround since 'thread_local' is not well supported by compilers yet
#if defined(__GNUC__)
#define thread_local __thread
#elif _MSC_VER > 1600 //defined(_WIN32)
#define thread_local __declspec( thread )
#else
#define thread_local // _MSC_VER == 1600, i.e. VS2010
#endif
using namespace std;
namespace Go
{
//------------------------------------------------------------------------------
namespace
//------------------------------------------------------------------------------
{
// Since some static buffers (provided for efficiency reasons) need to know the maximum degree
// used at compile time, the following constant, MAX_DEGREE, is here defined.
const int MAX_DEGREE = 20;
//------------------------------------------------------------------------------
double B(int deg, double t, const int* knot_ix, const double* kvals, bool at_end)
//------------------------------------------------------------------------------
{
// a POD rather than a stl vector used below due to the limitations of thread_local as currently
// defined (see #defines at the top of this file). A practical consequence is that
// MAX_DEGREE must be known at compile time.
static double thread_local tmp[MAX_DEGREE+2];
// only evaluate if within support
if ((t < kvals[knot_ix[0]]) || (t > kvals[knot_ix[deg+1]])) return 0;
assert(deg <= MAX_DEGREE);
fill (tmp, tmp+deg+1, 0);
// computing lowest-degree B-spline components (all zero except one)
int nonzero_ix = 0;
if (at_end) while (kvals[knot_ix[nonzero_ix+1]] < t) ++nonzero_ix;
else while (kvals[knot_ix[nonzero_ix+1]] <= t) ++nonzero_ix;
assert(nonzero_ix <= deg);
tmp[nonzero_ix] = 1;
// accumulating to attain correct degree
for (int d = 1; d != deg+1; ++d) {
const int lbound = max (0, nonzero_ix - d);
const int ubound = min (nonzero_ix, deg - d);
for (int i = lbound; i <= ubound; ++i) {
const double k_i = kvals[knot_ix[i]];
const double k_ip1 = kvals[knot_ix[i+1]];
const double k_ipd = kvals[knot_ix[i+d]];
const double k_ipdp1 = kvals[knot_ix[i+d+1]];
const double alpha = (k_ipd == k_i) ? 0 : (t - k_i) / (k_ipd - k_i);
const double beta = (k_ipdp1 == k_ip1) ? 0 : (k_ipdp1 - t) / (k_ipdp1 - k_ip1);
tmp[i] = alpha * tmp[i] + beta * tmp[i+1];
}
}
return tmp[0];
}
// //------------------------------------------------------------------------------
// // B-spline evaluation function
// double B_recursive(int deg, double t, const int* knot_ix, const double* kvals, bool at_end)
// //------------------------------------------------------------------------------
// {
// const double k0 = kvals[knot_ix[0]];
// const double k1 = kvals[knot_ix[1]];
// const double kd = kvals[knot_ix[deg]];
// const double kdp1 = kvals[knot_ix[deg+1]];
// assert(deg >= 0);
// if (deg == 0)
// return // at_end: half-open interval at end of domain should be considered differently
// (! at_end) ? ((k0 <= t && t < k1) ? 1 : 0) :
// ((k0 < t && t <= k1) ? 1 : 0);
// const double fac1 = (kd > k0) ? (t - k0) / (kd - k0) : 0;
// const double fac2 = (kdp1 > k1) ? (kdp1 - t) / (kdp1 - k1) : 0;
// return
// ( (fac1 > 0) ? fac1 * B(deg-1, t, knot_ix, kvals, at_end) : 0) +
// ( (fac2 > 0) ? fac2 * B(deg-1, t, knot_ix+1, kvals, at_end) : 0);
// }
//------------------------------------------------------------------------------
// B-spline derivative evaluation
double dB(int deg, double t, const int* knot_ix, const double* kvals, bool at_end, int der=1)
//------------------------------------------------------------------------------
{
const double k0 = kvals[knot_ix[0]];
const double k1 = kvals[knot_ix[1]];
const double kdeg = kvals[knot_ix[deg]];
const double kdp1 = kvals[knot_ix[deg+1]];
assert(der > 0); //@@ we should perhaps check that derivative <=
// degree - multiplicity
if (deg == 0)
return 0;
double fac1 = (kdeg > k0) ? ( deg) / (kdeg - k0) : 0;
double fac2 = (kdp1 > k1) ? (-deg) / (kdp1 - k1) : 0;
return
( (fac1 != 0) ?
( fac1 * ( (der>1) ?
dB(deg-1, t, knot_ix, kvals, at_end, der-1)
: B(deg-1, t, knot_ix, kvals, at_end) ) )
: 0 ) +
( (fac2 != 0) ?
( fac2 * ( (der>1) ?
dB(deg-1, t, knot_ix+1, kvals, at_end, der-1)
: B(deg-1, t, knot_ix+1, kvals, at_end) ) )
: 0 ) ;
}
//------------------------------------------------------------------------------
double compute_univariate_spline(int deg,
double u,
const vector<int>& k_ixes,
const double* kvals,
int deriv,
bool on_end)
//------------------------------------------------------------------------------
{
return (deriv>0) ?
dB(deg, u, &k_ixes[0], kvals, on_end, deriv) :
B( deg, u, &k_ixes[0], kvals, on_end);
}
}; // anonymous namespace
//==============================================================================
bool LRBSpline2D::operator<(const LRBSpline2D& rhs) const
//==============================================================================
{
const int tmp1 = compare_seq(kvec_u_.begin(), kvec_u_.end(), rhs.kvec_u_.begin(), rhs.kvec_u_.end());
if (tmp1 != 0) return (tmp1 < 0);
const int tmp2 = compare_seq(kvec_v_.begin(), kvec_v_.end(), rhs.kvec_v_.begin(), rhs.kvec_v_.end());
if (tmp2 != 0) return (tmp2 < 0);
const int tmp3 = compare_seq(coef_times_gamma_.begin(), coef_times_gamma_.end(),
rhs.coef_times_gamma_.begin(), rhs.coef_times_gamma_.end());
if (tmp3 != 0) return (tmp3 < 0);
return gamma_ < rhs.gamma_;
}
//==============================================================================
bool LRBSpline2D::operator==(const LRBSpline2D& rhs) const
//==============================================================================
{
const int tmp1 = compare_seq(kvec_u_.begin(), kvec_u_.end(),
rhs.kvec_u_.begin(), rhs.kvec_u_.end());
if (tmp1 != 0)
return false;
const int tmp2 = compare_seq(kvec_v_.begin(), kvec_v_.end(),
rhs.kvec_v_.begin(), rhs.kvec_v_.end());
if (tmp2 != 0)
return false;
return true;
}
//==============================================================================
void LRBSpline2D::write(ostream& os) const
//==============================================================================
{
object_to_stream(os, coef_times_gamma_);
object_to_stream(os, gamma_);
object_to_stream(os, '\n');
object_to_stream(os, kvec_u_);
object_to_stream(os, kvec_v_);
}
//==============================================================================
void LRBSpline2D::read(istream& is)
//==============================================================================
{
object_from_stream(is, coef_times_gamma_);
object_from_stream(is, gamma_);
object_from_stream(is, kvec_u_);
object_from_stream(is, kvec_v_);
}
//==============================================================================
double LRBSpline2D::evalBasisFunction(double u,
double v,
const double* const kvals_u,
const double* const kvals_v,
int u_deriv,
int v_deriv,
bool u_at_end,
bool v_at_end) const
//==============================================================================
{
return
compute_univariate_spline(degree(XFIXED), u, kvec(XFIXED), kvals_u, u_deriv, u_at_end) *
compute_univariate_spline(degree(YFIXED), v, kvec(YFIXED), kvals_v, v_deriv, v_at_end);
}
//==============================================================================
bool LRBSpline2D::overlaps(Element2D *el) const
//==============================================================================
{
// Does it make sense to include equality?
if (el->umin() >= umax())
return false;
if (el->umax() <= umin())
return false;
if (el->vmin() >= vmax())
return false;
if (el->vmax() <= vmin())
return false;
return true;
}
//==============================================================================
bool LRBSpline2D::addSupport(const Element2D *el)
//==============================================================================
{
for (size_t i=0; i<support_.size(); i++) {
if(el == support_[i]) {
return false;
}
}
support_.push_back(el);
return true;
}
//==============================================================================
void LRBSpline2D::removeSupport(const Element2D *el)
//==============================================================================
{
for (size_t i=0; i<support_.size(); i++) {
if(el == support_[i]) {
support_[i] = support_.back();
support_[support_.size()-1] = NULL;
support_.pop_back();
return;
}
}
}
}; // end namespace Go
<|endoftext|> |
<commit_before>// Copyright (c) 2003 Daniel Wallin and Arvid Norberg
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
// ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
// SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
// ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
// OR OTHER DEALINGS IN THE SOFTWARE.
#ifndef LUABIND_OBJECT_REP_HPP_INCLUDED
#define LUABIND_OBJECT_REP_HPP_INCLUDED
#include <boost/aligned_storage.hpp>
#include <luabind/config.hpp>
#include <luabind/detail/instance_holder.hpp>
#include <luabind/detail/ref.hpp>
namespace luabind { namespace detail
{
class class_rep;
void finalize(lua_State* L, class_rep* crep);
// this class is allocated inside lua for each pointer.
// it contains the actual c++ object-pointer.
// it also tells if it is const or not.
class LUABIND_API object_rep
{
public:
object_rep(instance_holder* instance, class_rep* crep);
~object_rep();
const class_rep* crep() const { return m_classrep; }
class_rep* crep() { return m_classrep; }
void set_instance(instance_holder* instance) { m_instance = instance; }
void add_dependency(lua_State* L, int index);
void release_dependency_refs(lua_State* L);
std::pair<void*, int> get_instance(class_id target) const
{
if (m_instance == 0)
return std::pair<void*, int>(0, -1);
return m_instance->get(target);
}
bool is_const() const
{
return m_instance && m_instance->pointee_const();
}
void release()
{
if (m_instance)
m_instance->release();
}
void* allocate(std::size_t size)
{
if (size <= 32)
return &m_instance_buffer;
return std::malloc(size);
}
void deallocate(void* storage)
{
if (storage == &m_instance_buffer)
return;
std::free(storage);
}
private:
instance_holder* m_instance;
boost::aligned_storage<32> m_instance_buffer;
class_rep* m_classrep; // the class information about this object's type
std::size_t m_dependency_cnt; // counts dependencies
};
template<class T>
struct delete_s
{
static void apply(void* ptr)
{
delete static_cast<T*>(ptr);
}
};
template<class T>
struct destruct_only_s
{
static void apply(void* ptr)
{
// Removes unreferenced formal parameter warning on VC7.
(void)ptr;
#ifndef NDEBUG
int completeness_check[sizeof(T)];
(void)completeness_check;
#endif
static_cast<T*>(ptr)->~T();
}
};
inline object_rep* is_class_object(lua_State* L, int index)
{
object_rep* obj = static_cast<detail::object_rep*>(lua_touserdata(L, index));
if (!obj) return 0;
if (lua_getmetatable(L, index) == 0) return 0;
lua_pushstring(L, "__luabind_class");
lua_gettable(L, -2);
bool confirmation = lua_toboolean(L, -1) != 0;
lua_pop(L, 2);
if (!confirmation) return 0;
return obj;
}
LUABIND_API object_rep* get_instance(lua_State* L, int index);
LUABIND_API void push_instance_metatable(lua_State* L);
LUABIND_API object_rep* push_new_instance(lua_State* L, class_rep* cls);
}}
#endif // LUABIND_OBJECT_REP_HPP_INCLUDED
<commit_msg>Make object_rep noncopyable.<commit_after>// Copyright (c) 2003 Daniel Wallin and Arvid Norberg
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
// ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
// SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
// ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
// OR OTHER DEALINGS IN THE SOFTWARE.
#ifndef LUABIND_OBJECT_REP_HPP_INCLUDED
#define LUABIND_OBJECT_REP_HPP_INCLUDED
#include <boost/aligned_storage.hpp>
#include <luabind/config.hpp>
#include <luabind/detail/instance_holder.hpp>
#include <luabind/detail/ref.hpp>
namespace luabind { namespace detail
{
class class_rep;
void finalize(lua_State* L, class_rep* crep);
// this class is allocated inside lua for each pointer.
// it contains the actual c++ object-pointer.
// it also tells if it is const or not.
class LUABIND_API object_rep
{
public:
object_rep(instance_holder* instance, class_rep* crep);
~object_rep();
const class_rep* crep() const { return m_classrep; }
class_rep* crep() { return m_classrep; }
void set_instance(instance_holder* instance) { m_instance = instance; }
void add_dependency(lua_State* L, int index);
void release_dependency_refs(lua_State* L);
std::pair<void*, int> get_instance(class_id target) const
{
if (m_instance == 0)
return std::pair<void*, int>(0, -1);
return m_instance->get(target);
}
bool is_const() const
{
return m_instance && m_instance->pointee_const();
}
void release()
{
if (m_instance)
m_instance->release();
}
void* allocate(std::size_t size)
{
if (size <= 32)
return &m_instance_buffer;
return std::malloc(size);
}
void deallocate(void* storage)
{
if (storage == &m_instance_buffer)
return;
std::free(storage);
}
private:
object_rep(object_rep const&)
{}
void operator=(object_rep const&)
{}
instance_holder* m_instance;
boost::aligned_storage<32> m_instance_buffer;
class_rep* m_classrep; // the class information about this object's type
std::size_t m_dependency_cnt; // counts dependencies
};
template<class T>
struct delete_s
{
static void apply(void* ptr)
{
delete static_cast<T*>(ptr);
}
};
template<class T>
struct destruct_only_s
{
static void apply(void* ptr)
{
// Removes unreferenced formal parameter warning on VC7.
(void)ptr;
#ifndef NDEBUG
int completeness_check[sizeof(T)];
(void)completeness_check;
#endif
static_cast<T*>(ptr)->~T();
}
};
inline object_rep* is_class_object(lua_State* L, int index)
{
object_rep* obj = static_cast<detail::object_rep*>(lua_touserdata(L, index));
if (!obj) return 0;
if (lua_getmetatable(L, index) == 0) return 0;
lua_pushstring(L, "__luabind_class");
lua_gettable(L, -2);
bool confirmation = lua_toboolean(L, -1) != 0;
lua_pop(L, 2);
if (!confirmation) return 0;
return obj;
}
LUABIND_API object_rep* get_instance(lua_State* L, int index);
LUABIND_API void push_instance_metatable(lua_State* L);
LUABIND_API object_rep* push_new_instance(lua_State* L, class_rep* cls);
}}
#endif // LUABIND_OBJECT_REP_HPP_INCLUDED
<|endoftext|> |
<commit_before><commit_msg>adding 2sat with path retrieval<commit_after><|endoftext|> |
<commit_before>/**
* HandleIterator.cc
*
*
* Copyright(c) 2001 Thiago Maia, Andre Senna
* All rights reserved.
*/
#include <platform.h>
#include "HandleIterator.h"
#include "AtomTable.h"
#include "classes.h"
#include "ClassServer.h"
#include "TLB.h"
#include "AtomSpaceDefinitions.h"
HandleIterator::HandleIterator( AtomTable *t, Type type, bool subclass, VersionHandle vh) {
init(t, type, subclass, vh);
}
void HandleIterator::init( AtomTable *t, Type type, bool subclass, VersionHandle vh) {
table = t;
desiredType = type;
desiredTypeSubclass = subclass;
desiredVersionHandle = vh;
if (subclass) {
// current handle and type are set to be the first element in the
// first index that matches subclass criteria
currentType = 0;
while (currentType < ClassServer::getNumberOfClasses()) {
if ((ClassServer::isAssignableFrom(desiredType, currentType)) &&
table->getTypeIndexHead(currentType) != NULL) {
break;
} else {
currentType++;
}
}
currentHandle = currentType >= ClassServer::getNumberOfClasses() ? NULL : table->getTypeIndexHead(currentType);
} else {
// if no subclasses are allowed, the current handle is simply
// the first element of the desired type index.
currentHandle = table->getTypeIndexHead(type);
currentType = type;
}
// the AtomTable will notify this iterator when some atom is removed to
// prevent this iterator from iterating through a removed atom
table->registerIterator(this);
}
HandleIterator::~HandleIterator() {
table->unregisterIterator(this);
}
bool HandleIterator::hasNext() {
return currentHandle != NULL;
}
Handle HandleIterator::next() {
// keep current handle to return it
Handle answer = currentHandle;
// the iterator goes to the next position of the current list.
currentHandle = TLB::getAtom(currentHandle)->next(TYPE_INDEX);
// if the list finishes, it's necessary to move to the next index
// that matches subclass criteria
if (currentHandle == NULL) {
if (desiredTypeSubclass) {
currentType++;
while (currentType < ClassServer::getNumberOfClasses()) {
if ((ClassServer::isAssignableFrom(desiredType, currentType)) &&
table->getTypeIndexHead(currentType) != NULL) {
break;
} else {
currentType++;
}
}
// currentHandle is the first element of the next index.
currentHandle = currentType >= ClassServer::getNumberOfClasses() ? NULL : table->getTypeIndexHead(currentType);
}
}
return answer;
}
<commit_msg>Handle is an opaque type, don't assume its a pointer.<commit_after>/**
* HandleIterator.cc
*
*
* Copyright(c) 2001 Thiago Maia, Andre Senna
* All rights reserved.
*/
#include <platform.h>
#include "HandleIterator.h"
#include "AtomTable.h"
#include "classes.h"
#include "ClassServer.h"
#include "TLB.h"
#include "AtomSpaceDefinitions.h"
HandleIterator::HandleIterator( AtomTable *t, Type type, bool subclass, VersionHandle vh) {
init(t, type, subclass, vh);
}
void HandleIterator::init( AtomTable *t, Type type, bool subclass, VersionHandle vh) {
table = t;
desiredType = type;
desiredTypeSubclass = subclass;
desiredVersionHandle = vh;
if (subclass) {
// current handle and type are set to be the first element in the
// first index that matches subclass criteria
currentType = 0;
while (currentType < ClassServer::getNumberOfClasses()) {
if ((ClassServer::isAssignableFrom(desiredType, currentType)) &&
!TLB::isInvalidHandle(table->getTypeIndexHead(currentType)))
{
break;
} else {
currentType++;
}
}
currentHandle = currentType >= ClassServer::getNumberOfClasses() ? NULL : table->getTypeIndexHead(currentType);
} else {
// if no subclasses are allowed, the current handle is simply
// the first element of the desired type index.
currentHandle = table->getTypeIndexHead(type);
currentType = type;
}
// the AtomTable will notify this iterator when some atom is removed to
// prevent this iterator from iterating through a removed atom
table->registerIterator(this);
}
HandleIterator::~HandleIterator() {
table->unregisterIterator(this);
}
bool HandleIterator::hasNext() {
return !TLB::isInvalidHandle(currentHandle);
}
Handle HandleIterator::next() {
// keep current handle to return it
Handle answer = currentHandle;
// the iterator goes to the next position of the current list.
currentHandle = TLB::getAtom(currentHandle)->next(TYPE_INDEX);
// if the list finishes, it's necessary to move to the next index
// that matches subclass criteria
if (TLB::isInvalidHandle(currentHandle))
{
if (desiredTypeSubclass) {
currentType++;
while (currentType < ClassServer::getNumberOfClasses()) {
if ((ClassServer::isAssignableFrom(desiredType, currentType)) &&
!TLB::isInvalidHandle(table->getTypeIndexHead(currentType)))
{
break;
} else {
currentType++;
}
}
// currentHandle is the first element of the next index.
currentHandle = currentType >= ClassServer::getNumberOfClasses() ? NULL : table->getTypeIndexHead(currentType);
}
}
return answer;
}
<|endoftext|> |
<commit_before>//===-- ExpressionSourceCode.cpp --------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "lldb/Expression/ExpressionSourceCode.h"
#include "lldb/Core/StreamString.h"
using namespace lldb_private;
const char *
ExpressionSourceCode::g_expression_prefix = R"(
#undef NULL
#undef Nil
#undef nil
#undef YES
#undef NO
#define NULL (__null)
#define Nil (__null)
#define nil (__null)
#define YES ((BOOL)1)
#define NO ((BOOL)0)
typedef signed char BOOL;
typedef signed __INT8_TYPE__ int8_t;
typedef unsigned __INT8_TYPE__ uint8_t;
typedef signed __INT16_TYPE__ int16_t;
typedef unsigned __INT16_TYPE__ uint16_t;
typedef signed __INT32_TYPE__ int32_t;
typedef unsigned __INT32_TYPE__ uint32_t;
typedef signed __INT64_TYPE__ int64_t;
typedef unsigned __INT64_TYPE__ uint64_t;
typedef signed __INTPTR_TYPE__ intptr_t;
typedef unsigned __INTPTR_TYPE__ uintptr_t;
typedef __SIZE_TYPE__ size_t;
typedef __PTRDIFF_TYPE__ ptrdiff_t;
typedef unsigned short unichar;
)";
bool ExpressionSourceCode::GetText (std::string &text, lldb::LanguageType wrapping_language, bool const_object, bool static_method) const
{
if (m_wrap)
{
switch (wrapping_language)
{
default:
return false;
case lldb::eLanguageTypeC:
case lldb::eLanguageTypeC_plus_plus:
case lldb::eLanguageTypeObjC:
break;
}
StreamString wrap_stream;
switch (wrapping_language)
{
default:
break;
case lldb::eLanguageTypeC:
wrap_stream.Printf("%s \n"
"%s \n"
"void \n"
"%s(void *$__lldb_arg) \n"
"{ \n"
" %s; \n"
"} \n",
m_prefix.c_str(),
g_expression_prefix,
m_name.c_str(),
m_body.c_str());
break;
case lldb::eLanguageTypeC_plus_plus:
wrap_stream.Printf("%s \n"
"%s \n"
"void \n"
"$__lldb_class::%s(void *$__lldb_arg) %s\n"
"{ \n"
" %s; \n"
"} \n",
m_prefix.c_str(),
g_expression_prefix,
m_name.c_str(),
(const_object ? "const" : ""),
m_body.c_str());
break;
case lldb::eLanguageTypeObjC:
if (static_method)
{
wrap_stream.Printf("%s \n"
"%s \n"
"@interface $__lldb_objc_class ($__lldb_category) \n"
"+(void)%s:(void *)$__lldb_arg; \n"
"@end \n"
"@implementation $__lldb_objc_class ($__lldb_category) \n"
"+(void)%s:(void *)$__lldb_arg \n"
"{ \n"
" %s; \n"
"} \n"
"@end \n",
m_prefix.c_str(),
g_expression_prefix,
m_name.c_str(),
m_name.c_str(),
m_body.c_str());
}
else
{
wrap_stream.Printf("%s \n"
"%s \n"
"@interface $__lldb_objc_class ($__lldb_category) \n"
"-(void)%s:(void *)$__lldb_arg; \n"
"@end \n"
"@implementation $__lldb_objc_class ($__lldb_category) \n"
"-(void)%s:(void *)$__lldb_arg \n"
"{ \n"
" %s; \n"
"} \n"
"@end \n",
m_prefix.c_str(),
g_expression_prefix,
m_name.c_str(),
m_name.c_str(),
m_body.c_str());
}
break;
}
text = wrap_stream.GetString();
}
else
{
text.append(m_body);
}
return true;
}
<commit_msg>Import the builtin type prefix before we import the user expression prefix so that the user expression prefix can use the uint, int, size_t, and other types without having to define them.<commit_after>//===-- ExpressionSourceCode.cpp --------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "lldb/Expression/ExpressionSourceCode.h"
#include "lldb/Core/StreamString.h"
using namespace lldb_private;
const char *
ExpressionSourceCode::g_expression_prefix = R"(
#undef NULL
#undef Nil
#undef nil
#undef YES
#undef NO
#define NULL (__null)
#define Nil (__null)
#define nil (__null)
#define YES ((BOOL)1)
#define NO ((BOOL)0)
typedef signed char BOOL;
typedef signed __INT8_TYPE__ int8_t;
typedef unsigned __INT8_TYPE__ uint8_t;
typedef signed __INT16_TYPE__ int16_t;
typedef unsigned __INT16_TYPE__ uint16_t;
typedef signed __INT32_TYPE__ int32_t;
typedef unsigned __INT32_TYPE__ uint32_t;
typedef signed __INT64_TYPE__ int64_t;
typedef unsigned __INT64_TYPE__ uint64_t;
typedef signed __INTPTR_TYPE__ intptr_t;
typedef unsigned __INTPTR_TYPE__ uintptr_t;
typedef __SIZE_TYPE__ size_t;
typedef __PTRDIFF_TYPE__ ptrdiff_t;
typedef unsigned short unichar;
)";
bool ExpressionSourceCode::GetText (std::string &text, lldb::LanguageType wrapping_language, bool const_object, bool static_method) const
{
if (m_wrap)
{
switch (wrapping_language)
{
default:
return false;
case lldb::eLanguageTypeC:
case lldb::eLanguageTypeC_plus_plus:
case lldb::eLanguageTypeObjC:
break;
}
StreamString wrap_stream;
switch (wrapping_language)
{
default:
break;
case lldb::eLanguageTypeC:
wrap_stream.Printf("%s \n"
"%s \n"
"void \n"
"%s(void *$__lldb_arg) \n"
"{ \n"
" %s; \n"
"} \n",
g_expression_prefix,
m_prefix.c_str(),
m_name.c_str(),
m_body.c_str());
break;
case lldb::eLanguageTypeC_plus_plus:
wrap_stream.Printf("%s \n"
"%s \n"
"void \n"
"$__lldb_class::%s(void *$__lldb_arg) %s\n"
"{ \n"
" %s; \n"
"} \n",
g_expression_prefix,
m_prefix.c_str(),
m_name.c_str(),
(const_object ? "const" : ""),
m_body.c_str());
break;
case lldb::eLanguageTypeObjC:
if (static_method)
{
wrap_stream.Printf("%s \n"
"%s \n"
"@interface $__lldb_objc_class ($__lldb_category) \n"
"+(void)%s:(void *)$__lldb_arg; \n"
"@end \n"
"@implementation $__lldb_objc_class ($__lldb_category) \n"
"+(void)%s:(void *)$__lldb_arg \n"
"{ \n"
" %s; \n"
"} \n"
"@end \n",
g_expression_prefix,
m_prefix.c_str(),
m_name.c_str(),
m_name.c_str(),
m_body.c_str());
}
else
{
wrap_stream.Printf("%s \n"
"%s \n"
"@interface $__lldb_objc_class ($__lldb_category) \n"
"-(void)%s:(void *)$__lldb_arg; \n"
"@end \n"
"@implementation $__lldb_objc_class ($__lldb_category) \n"
"-(void)%s:(void *)$__lldb_arg \n"
"{ \n"
" %s; \n"
"} \n"
"@end \n",
g_expression_prefix,
m_prefix.c_str(),
m_name.c_str(),
m_name.c_str(),
m_body.c_str());
}
break;
}
text = wrap_stream.GetString();
}
else
{
text.append(m_body);
}
return true;
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <sstream>
#include <list>
#include <vector>
#include <assert.h>
using namespace std;
// Serialize/deserialize binary tree
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class binary_tree
{
public:
binary_tree(string serialized_str)
{
vector<string> tree_nodes;
tree_str_preprocessor(serialized_str, tree_nodes);
m_root = construct_tree(tree_nodes);
}
string deserialize_to_str()
{
list<TreeNode *> que;
string res;
stringstream ss;
que.push_back(m_root);
while (que.empty() != true)
{
auto node = que.front();
que.pop_front();
if (node != nullptr)
{
ss << node->val << "|";
}
else
{
ss << "#|";
}
if (node)
{
que.push_back(node->left);
que.push_back(node->right);
}
}
return ss.str();
}
private:
TreeNode *m_root = nullptr;
void tree_str_preprocessor(string serialized_str, vector<string> &out)
{
int idx = 0;
while (idx < serialized_str.length())
{
int stop_idx = serialized_str.find('|', idx);
if (stop_idx == string::npos) break;
out.push_back(serialized_str.substr(idx, stop_idx - idx));
idx = stop_idx + 1;
if (idx == serialized_str.length()) break;
}
}
TreeNode *construct_tree(vector<string> nodes)
{
stringstream ss(nodes[0]);
int root_val;
ss >> root_val;
auto root = new TreeNode(root_val);
list<TreeNode *> que;;
int iter = 0;
auto prev_node = root;
for (int i = 1; i < nodes.size(); i++)
{
iter++;
TreeNode *new_node = nullptr;
if (nodes[i] != "#")
{
stringstream ss(nodes[i]);
int new_val; ss >> new_val;
new_node = new TreeNode(new_val);
que.push_back(new_node);
}
if (iter == 1)
{
prev_node->left = new_node;
}
else if (iter == 2)
{
prev_node->right = new_node;
if (que.empty() == true)
{
assert(i == (nodes.size() - 1));
break;
}
prev_node = que.front();
que.pop_front();
iter = 0;
}
}
return root;
}
};
int test_basic()
{
string input("1|#|5|1|10|#|4|#|5|");
binary_tree bt(input);
string output = bt.deserialize_to_str();
binary_tree bt2(output);
string output2 = bt2.deserialize_to_str();
if (output != output2)
{
cout << "in: " << output << endl;;
cout << "out: " << output2 << endl;;
}
}
int main() {
// your code goes here
test_basic();
return 0;
}
<commit_msg>using space<commit_after>#include <iostream>
#include <sstream>
#include <list>
#include <vector>
#include <assert.h>
using namespace std;
// Serialize/deserialize binary tree
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class binary_tree
{
public:
binary_tree(string serialized_str)
{
vector<string> tree_nodes;
tree_str_preprocessor(serialized_str, tree_nodes);
m_root = construct_tree(tree_nodes);
}
string deserialize_to_str()
{
list<TreeNode *> que;
string res;
stringstream ss;
que.push_back(m_root);
while (que.empty() != true)
{
auto node = que.front();
que.pop_front();
if (node != nullptr)
{
ss << node->val << "|";
}
else
{
ss << "#|";
}
if (node)
{
que.push_back(node->left);
que.push_back(node->right);
}
}
return ss.str();
}
private:
TreeNode *m_root = nullptr;
void tree_str_preprocessor(string serialized_str, vector<string> &out)
{
int idx = 0;
while (idx < serialized_str.length())
{
int stop_idx = serialized_str.find('|', idx);
if (stop_idx == string::npos) break;
out.push_back(serialized_str.substr(idx, stop_idx - idx));
idx = stop_idx + 1;
if (idx == serialized_str.length()) break;
}
}
TreeNode *construct_tree(vector<string> nodes)
{
stringstream ss(nodes[0]);
int root_val;
ss >> root_val;
auto root = new TreeNode(root_val);
list<TreeNode *> que;;
int iter = 0;
auto prev_node = root;
for (int i = 1; i < nodes.size(); i++)
{
iter++;
TreeNode *new_node = nullptr;
if (nodes[i] != "#")
{
stringstream ss(nodes[i]);
int new_val; ss >> new_val;
new_node = new TreeNode(new_val);
que.push_back(new_node);
}
if (iter == 1)
{
prev_node->left = new_node;
}
else if (iter == 2)
{
prev_node->right = new_node;
if (que.empty() == true)
{
assert(i == (nodes.size() - 1));
break;
}
prev_node = que.front();
que.pop_front();
iter = 0;
}
}
return root;
}
};
int test_basic()
{
string input("1|#|5|1|10|#|4|#|5|");
binary_tree bt(input);
string output = bt.deserialize_to_str();
binary_tree bt2(output);
string output2 = bt2.deserialize_to_str();
if (output != output2)
{
cout << "in: " << output << endl;;
cout << "out: " << output2 << endl;;
}
}
int main() {
// your code goes here
test_basic();
return 0;
}
<|endoftext|> |
<commit_before>// PluginHelpers.cpp : Defines the exported functions for the DLL application.
//
#include "stdafx.h"
#include "pluginhelpers.h"
#include "UIExtension.h"
#include "..\..\ToDoList_Dev\Interfaces\UITheme.h"
#include "..\..\ToDoList_Dev\Interfaces\IUIExtension.h"
#include "..\..\ToDoList_Dev\Interfaces\ITasklist.h"
////////////////////////////////////////////////////////////////////////////////////////////////
using namespace Abstractspoon::Tdl::PluginHelpers;
////////////////////////////////////////////////////////////////////////////////////////////////
UIExtension::TaskAttribute UIExtension::Map(IUI_ATTRIBUTE attrib)
{
switch (attrib)
{
case IUI_TASKNAME: return UIExtension::TaskAttribute::Title;
case IUI_DONEDATE: return UIExtension::TaskAttribute::DoneDate;
case IUI_DUEDATE: return UIExtension::TaskAttribute::DueDate;
case IUI_STARTDATE: return UIExtension::TaskAttribute::StartDate;
case IUI_PRIORITY: return UIExtension::TaskAttribute::Priority;
case IUI_COLOR: return UIExtension::TaskAttribute::Color;
case IUI_ALLOCTO: return UIExtension::TaskAttribute::AllocBy;
case IUI_ALLOCBY: return UIExtension::TaskAttribute::AllocTo;
case IUI_STATUS: return UIExtension::TaskAttribute::Status;
case IUI_CATEGORY: return UIExtension::TaskAttribute::Category;
case IUI_PERCENT: return UIExtension::TaskAttribute::Percent;
case IUI_TIMEEST: return UIExtension::TaskAttribute::TimeEstimate;
case IUI_TIMESPENT: return UIExtension::TaskAttribute::TimeSpent;
case IUI_FILEREF: return UIExtension::TaskAttribute::FileReference;
case IUI_COMMENTS: return UIExtension::TaskAttribute::Comments;
case IUI_FLAG: return UIExtension::TaskAttribute::Flag;
case IUI_CREATIONDATE: return UIExtension::TaskAttribute::CreationDate;
case IUI_CREATEDBY: return UIExtension::TaskAttribute::CreatedBy;
case IUI_RISK: return UIExtension::TaskAttribute::Risk;
case IUI_EXTERNALID: return UIExtension::TaskAttribute::ExternalId;
case IUI_COST: return UIExtension::TaskAttribute::Cost;
case IUI_DEPENDENCY: return UIExtension::TaskAttribute::Dependency;
case IUI_RECURRENCE: return UIExtension::TaskAttribute::Recurrence;
case IUI_VERSION: return UIExtension::TaskAttribute::Version;
case IUI_POSITION: return UIExtension::TaskAttribute::Position;
case IUI_ID: return UIExtension::TaskAttribute::Id;
case IUI_LASTMOD: return UIExtension::TaskAttribute::LastModified;
case IUI_ICON: return UIExtension::TaskAttribute::Icon;
case IUI_TAGS: return UIExtension::TaskAttribute::Tag;
case IUI_CUSTOMATTRIB: return UIExtension::TaskAttribute::CustomAttribute;
case IUI_OFFSETTASK: return UIExtension::TaskAttribute::OffsetTask;
// case IUI_
}
return UIExtension::TaskAttribute::Unknown;
}
IUI_ATTRIBUTE UIExtension::Map(UIExtension::TaskAttribute attrib)
{
switch (attrib)
{
case UIExtension::TaskAttribute::Title: return IUI_TASKNAME;
case UIExtension::TaskAttribute::DoneDate: return IUI_DONEDATE;
case UIExtension::TaskAttribute::DueDate: return IUI_DUEDATE;
case UIExtension::TaskAttribute::StartDate: return IUI_STARTDATE;
case UIExtension::TaskAttribute::Priority: return IUI_PRIORITY;
case UIExtension::TaskAttribute::Color: return IUI_COLOR;
case UIExtension::TaskAttribute::AllocBy: return IUI_ALLOCTO;
case UIExtension::TaskAttribute::AllocTo: return IUI_ALLOCBY;
case UIExtension::TaskAttribute::Status: return IUI_STATUS;
case UIExtension::TaskAttribute::Category: return IUI_CATEGORY;
case UIExtension::TaskAttribute::Percent: return IUI_PERCENT;
case UIExtension::TaskAttribute::TimeEstimate: return IUI_TIMEEST;
case UIExtension::TaskAttribute::TimeSpent: return IUI_TIMESPENT;
case UIExtension::TaskAttribute::FileReference: return IUI_FILEREF;
case UIExtension::TaskAttribute::Comments: return IUI_COMMENTS;
case UIExtension::TaskAttribute::Flag: return IUI_FLAG;
case UIExtension::TaskAttribute::CreationDate: return IUI_CREATIONDATE;
case UIExtension::TaskAttribute::CreatedBy: return IUI_CREATEDBY;
case UIExtension::TaskAttribute::Risk: return IUI_RISK;
case UIExtension::TaskAttribute::ExternalId: return IUI_EXTERNALID;
case UIExtension::TaskAttribute::Cost: return IUI_COST;
case UIExtension::TaskAttribute::Dependency: return IUI_DEPENDENCY;
case UIExtension::TaskAttribute::Recurrence: return IUI_RECURRENCE;
case UIExtension::TaskAttribute::Version: return IUI_VERSION;
case UIExtension::TaskAttribute::Position: return IUI_POSITION;
case UIExtension::TaskAttribute::Id: return IUI_ID;
case UIExtension::TaskAttribute::LastModified: return IUI_LASTMOD;
case UIExtension::TaskAttribute::Icon: return IUI_ICON;
case UIExtension::TaskAttribute::Tag: return IUI_TAGS;
case UIExtension::TaskAttribute::CustomAttribute: return IUI_CUSTOMATTRIB;
case UIExtension::TaskAttribute::OffsetTask: return IUI_OFFSETTASK;
// case IUI_
}
return IUI_NONE;
}
Collections::Generic::HashSet<UIExtension::TaskAttribute>^ UIExtension::Map(const IUI_ATTRIBUTE* pAttrib, int numAttrib)
{
Collections::Generic::HashSet<TaskAttribute>^ attribs = gcnew(Collections::Generic::HashSet<TaskAttribute>);
for (int attrib = 0; attrib < numAttrib; attrib++)
attribs->Add(Map(pAttrib[attrib]));
return attribs;
}
UIExtension::UpdateType UIExtension::Map(IUI_UPDATETYPE type)
{
switch (type)
{
case IUI_EDIT: return UIExtension::UpdateType::Edit;
case IUI_NEW: return UIExtension::UpdateType::New;
case IUI_DELETE: return UIExtension::UpdateType::Delete;
case IUI_MOVE: return UIExtension::UpdateType::Move;
case IUI_ALL: return UIExtension::UpdateType::All;
// case IUI_
}
return UIExtension::UpdateType::Unknown;
}
UIExtension::AppCommand UIExtension::Map(IUI_APPCOMMAND cmd)
{
switch (cmd)
{
case IUI_EXPANDALL: return UIExtension::AppCommand::ExpandAll;
case IUI_COLLAPSEALL: return UIExtension::AppCommand::CollapseAll;
case IUI_EXPANDSELECTED: return UIExtension::AppCommand::ExpandSelected;
case IUI_COLLAPSESELECTED: return UIExtension::AppCommand::CollapseSelected;
case IUI_SORT: return UIExtension::AppCommand::Sort;
case IUI_TOGGLABLESORT: return UIExtension::AppCommand::ToggleSort;
case IUI_SETFOCUS: return UIExtension::AppCommand::SetFocus;
case IUI_RESIZEATTRIBCOLUMNS: return UIExtension::AppCommand::ResizeAttributeColumns;
case IUI_SELECTTASK: return UIExtension::AppCommand::SelectTask;
// case IUI_
}
return UIExtension::AppCommand::Unknown;
}
IUI_HITTEST UIExtension::Map(UIExtension::HitResult test)
{
switch (test)
{
case UIExtension::HitResult::Nowhere: return IUI_NOWHERE;
case UIExtension::HitResult::Tasklist: return IUI_TASKLIST;
case UIExtension::HitResult::ColumnHeader: return IUI_COLUMNHEADER;
case UIExtension::HitResult::Task: return IUI_TASK;
}
return IUI_NOWHERE;
}
////////////////////////////////////////////////////////////////////////////////////////////////
UIExtension::ParentNotify::ParentNotify(IntPtr hwndParent) : m_hwndParent(NULL), m_hwndFrom(NULL)
{
m_hwndParent = static_cast<HWND>(hwndParent.ToPointer());
}
UIExtension::ParentNotify::ParentNotify(IntPtr hwndParent, IntPtr hwndFrom) : m_hwndParent(NULL), m_hwndFrom(NULL)
{
m_hwndParent = static_cast<HWND>(hwndParent.ToPointer());
m_hwndFrom = static_cast<HWND>(hwndFrom.ToPointer());
}
bool UIExtension::ParentNotify::NotifyMod(UIExtension::TaskAttribute nAttribute, DateTime date)
{
IUITASKMOD mod = { UIExtension::Map(nAttribute), 0 };
mod.tValue = static_cast<__int64>(Task::Map(date));
return DoNotify(&mod, 1);
}
bool UIExtension::ParentNotify::NotifyMod(UIExtension::TaskAttribute nAttribute, double value)
{
IUITASKMOD mod = { UIExtension::Map(nAttribute), 0 };
mod.dValue = value;
return DoNotify(&mod, 1);
}
bool UIExtension::ParentNotify::NotifyMod(UIExtension::TaskAttribute nAttribute, double time, Task::TimeUnits units)
{
IUITASKMOD mod = { UIExtension::Map(nAttribute), 0 };
mod.dValue = time;
mod.nTimeUnits = Task::Map(units);
return DoNotify(&mod, 1);
}
bool UIExtension::ParentNotify::NotifyMod(UIExtension::TaskAttribute nAttribute, int value)
{
IUITASKMOD mod = { UIExtension::Map(nAttribute), 0 };
mod.nValue = value;
return DoNotify(&mod, 1);
}
bool UIExtension::ParentNotify::NotifyMod(UIExtension::TaskAttribute nAttribute, bool value)
{
IUITASKMOD mod = { UIExtension::Map(nAttribute), 0 };
mod.bValue = (value ? TRUE : FALSE);
return DoNotify(&mod, 1);
}
bool UIExtension::ParentNotify::NotifyMod(String^ sCustAttribID, String^ value)
{
IUITASKMOD mod = { IUI_CUSTOMATTRIB, 0 };
mod.szValue = MS(value);
mod.szCustomAttribID = MS(sCustAttribID);
return DoNotify(&mod, 1);
}
bool UIExtension::ParentNotify::NotifyMod(UIExtension::TaskAttribute nAttribute, String^ value)
{
IUITASKMOD mod = { UIExtension::Map(nAttribute), 0 };
mod.szValue = MS(value);
return DoNotify(&mod, 1);
}
bool UIExtension::ParentNotify::NotifyMod(UIExtension::TaskAttribute nAttribute, cli::array<String^>^ aValues)
{
IUITASKMOD mod = { UIExtension::Map(nAttribute), 0 };
//mod.szValue = MS(value);
return DoNotify(&mod, 1);
}
bool UIExtension::ParentNotify::DoNotify(const IUITASKMOD* pMod, int numMod)
{
if (!IsWindow(m_hwndParent))
return false;
::SendMessage(m_hwndParent, WM_IUI_MODIFYSELECTEDTASK, numMod, (LPARAM)pMod);
return true;
}
bool UIExtension::ParentNotify::NotifySelChange(UInt32 taskID)
{
if (!IsWindow(m_hwndParent))
return false;
::SendMessage(m_hwndParent, WM_IUI_SELECTTASK, 0, taskID);
return true;
}
bool UIExtension::ParentNotify::NotifySelChange(cli::array<UInt32>^ pdwTaskIDs)
{
if (!IsWindow(m_hwndParent) || !pdwTaskIDs->Length)
return false;
pin_ptr<UInt32> p = &pdwTaskIDs[0];
::SendMessage(m_hwndParent, WM_IUI_SELECTTASK, pdwTaskIDs->Length, (LPARAM)p);
return true;
}
////////////////////////////////////////////////////////////////////////////////////////////////
<commit_msg>Return the result of extension notifications<commit_after>// PluginHelpers.cpp : Defines the exported functions for the DLL application.
//
#include "stdafx.h"
#include "pluginhelpers.h"
#include "UIExtension.h"
#include "..\..\ToDoList_Dev\Interfaces\UITheme.h"
#include "..\..\ToDoList_Dev\Interfaces\IUIExtension.h"
#include "..\..\ToDoList_Dev\Interfaces\ITasklist.h"
////////////////////////////////////////////////////////////////////////////////////////////////
using namespace Abstractspoon::Tdl::PluginHelpers;
////////////////////////////////////////////////////////////////////////////////////////////////
UIExtension::TaskAttribute UIExtension::Map(IUI_ATTRIBUTE attrib)
{
switch (attrib)
{
case IUI_TASKNAME: return UIExtension::TaskAttribute::Title;
case IUI_DONEDATE: return UIExtension::TaskAttribute::DoneDate;
case IUI_DUEDATE: return UIExtension::TaskAttribute::DueDate;
case IUI_STARTDATE: return UIExtension::TaskAttribute::StartDate;
case IUI_PRIORITY: return UIExtension::TaskAttribute::Priority;
case IUI_COLOR: return UIExtension::TaskAttribute::Color;
case IUI_ALLOCTO: return UIExtension::TaskAttribute::AllocBy;
case IUI_ALLOCBY: return UIExtension::TaskAttribute::AllocTo;
case IUI_STATUS: return UIExtension::TaskAttribute::Status;
case IUI_CATEGORY: return UIExtension::TaskAttribute::Category;
case IUI_PERCENT: return UIExtension::TaskAttribute::Percent;
case IUI_TIMEEST: return UIExtension::TaskAttribute::TimeEstimate;
case IUI_TIMESPENT: return UIExtension::TaskAttribute::TimeSpent;
case IUI_FILEREF: return UIExtension::TaskAttribute::FileReference;
case IUI_COMMENTS: return UIExtension::TaskAttribute::Comments;
case IUI_FLAG: return UIExtension::TaskAttribute::Flag;
case IUI_CREATIONDATE: return UIExtension::TaskAttribute::CreationDate;
case IUI_CREATEDBY: return UIExtension::TaskAttribute::CreatedBy;
case IUI_RISK: return UIExtension::TaskAttribute::Risk;
case IUI_EXTERNALID: return UIExtension::TaskAttribute::ExternalId;
case IUI_COST: return UIExtension::TaskAttribute::Cost;
case IUI_DEPENDENCY: return UIExtension::TaskAttribute::Dependency;
case IUI_RECURRENCE: return UIExtension::TaskAttribute::Recurrence;
case IUI_VERSION: return UIExtension::TaskAttribute::Version;
case IUI_POSITION: return UIExtension::TaskAttribute::Position;
case IUI_ID: return UIExtension::TaskAttribute::Id;
case IUI_LASTMOD: return UIExtension::TaskAttribute::LastModified;
case IUI_ICON: return UIExtension::TaskAttribute::Icon;
case IUI_TAGS: return UIExtension::TaskAttribute::Tag;
case IUI_CUSTOMATTRIB: return UIExtension::TaskAttribute::CustomAttribute;
case IUI_OFFSETTASK: return UIExtension::TaskAttribute::OffsetTask;
// case IUI_
}
return UIExtension::TaskAttribute::Unknown;
}
IUI_ATTRIBUTE UIExtension::Map(UIExtension::TaskAttribute attrib)
{
switch (attrib)
{
case UIExtension::TaskAttribute::Title: return IUI_TASKNAME;
case UIExtension::TaskAttribute::DoneDate: return IUI_DONEDATE;
case UIExtension::TaskAttribute::DueDate: return IUI_DUEDATE;
case UIExtension::TaskAttribute::StartDate: return IUI_STARTDATE;
case UIExtension::TaskAttribute::Priority: return IUI_PRIORITY;
case UIExtension::TaskAttribute::Color: return IUI_COLOR;
case UIExtension::TaskAttribute::AllocBy: return IUI_ALLOCTO;
case UIExtension::TaskAttribute::AllocTo: return IUI_ALLOCBY;
case UIExtension::TaskAttribute::Status: return IUI_STATUS;
case UIExtension::TaskAttribute::Category: return IUI_CATEGORY;
case UIExtension::TaskAttribute::Percent: return IUI_PERCENT;
case UIExtension::TaskAttribute::TimeEstimate: return IUI_TIMEEST;
case UIExtension::TaskAttribute::TimeSpent: return IUI_TIMESPENT;
case UIExtension::TaskAttribute::FileReference: return IUI_FILEREF;
case UIExtension::TaskAttribute::Comments: return IUI_COMMENTS;
case UIExtension::TaskAttribute::Flag: return IUI_FLAG;
case UIExtension::TaskAttribute::CreationDate: return IUI_CREATIONDATE;
case UIExtension::TaskAttribute::CreatedBy: return IUI_CREATEDBY;
case UIExtension::TaskAttribute::Risk: return IUI_RISK;
case UIExtension::TaskAttribute::ExternalId: return IUI_EXTERNALID;
case UIExtension::TaskAttribute::Cost: return IUI_COST;
case UIExtension::TaskAttribute::Dependency: return IUI_DEPENDENCY;
case UIExtension::TaskAttribute::Recurrence: return IUI_RECURRENCE;
case UIExtension::TaskAttribute::Version: return IUI_VERSION;
case UIExtension::TaskAttribute::Position: return IUI_POSITION;
case UIExtension::TaskAttribute::Id: return IUI_ID;
case UIExtension::TaskAttribute::LastModified: return IUI_LASTMOD;
case UIExtension::TaskAttribute::Icon: return IUI_ICON;
case UIExtension::TaskAttribute::Tag: return IUI_TAGS;
case UIExtension::TaskAttribute::CustomAttribute: return IUI_CUSTOMATTRIB;
case UIExtension::TaskAttribute::OffsetTask: return IUI_OFFSETTASK;
// case IUI_
}
return IUI_NONE;
}
Collections::Generic::HashSet<UIExtension::TaskAttribute>^ UIExtension::Map(const IUI_ATTRIBUTE* pAttrib, int numAttrib)
{
Collections::Generic::HashSet<TaskAttribute>^ attribs = gcnew(Collections::Generic::HashSet<TaskAttribute>);
for (int attrib = 0; attrib < numAttrib; attrib++)
attribs->Add(Map(pAttrib[attrib]));
return attribs;
}
UIExtension::UpdateType UIExtension::Map(IUI_UPDATETYPE type)
{
switch (type)
{
case IUI_EDIT: return UIExtension::UpdateType::Edit;
case IUI_NEW: return UIExtension::UpdateType::New;
case IUI_DELETE: return UIExtension::UpdateType::Delete;
case IUI_MOVE: return UIExtension::UpdateType::Move;
case IUI_ALL: return UIExtension::UpdateType::All;
// case IUI_
}
return UIExtension::UpdateType::Unknown;
}
UIExtension::AppCommand UIExtension::Map(IUI_APPCOMMAND cmd)
{
switch (cmd)
{
case IUI_EXPANDALL: return UIExtension::AppCommand::ExpandAll;
case IUI_COLLAPSEALL: return UIExtension::AppCommand::CollapseAll;
case IUI_EXPANDSELECTED: return UIExtension::AppCommand::ExpandSelected;
case IUI_COLLAPSESELECTED: return UIExtension::AppCommand::CollapseSelected;
case IUI_SORT: return UIExtension::AppCommand::Sort;
case IUI_TOGGLABLESORT: return UIExtension::AppCommand::ToggleSort;
case IUI_SETFOCUS: return UIExtension::AppCommand::SetFocus;
case IUI_RESIZEATTRIBCOLUMNS: return UIExtension::AppCommand::ResizeAttributeColumns;
case IUI_SELECTTASK: return UIExtension::AppCommand::SelectTask;
// case IUI_
}
return UIExtension::AppCommand::Unknown;
}
IUI_HITTEST UIExtension::Map(UIExtension::HitResult test)
{
switch (test)
{
case UIExtension::HitResult::Nowhere: return IUI_NOWHERE;
case UIExtension::HitResult::Tasklist: return IUI_TASKLIST;
case UIExtension::HitResult::ColumnHeader: return IUI_COLUMNHEADER;
case UIExtension::HitResult::Task: return IUI_TASK;
}
return IUI_NOWHERE;
}
////////////////////////////////////////////////////////////////////////////////////////////////
UIExtension::ParentNotify::ParentNotify(IntPtr hwndParent) : m_hwndParent(NULL), m_hwndFrom(NULL)
{
m_hwndParent = static_cast<HWND>(hwndParent.ToPointer());
}
UIExtension::ParentNotify::ParentNotify(IntPtr hwndParent, IntPtr hwndFrom) : m_hwndParent(NULL), m_hwndFrom(NULL)
{
m_hwndParent = static_cast<HWND>(hwndParent.ToPointer());
m_hwndFrom = static_cast<HWND>(hwndFrom.ToPointer());
}
bool UIExtension::ParentNotify::NotifyMod(UIExtension::TaskAttribute nAttribute, DateTime date)
{
IUITASKMOD mod = { UIExtension::Map(nAttribute), 0 };
mod.tValue = static_cast<__int64>(Task::Map(date));
return DoNotify(&mod, 1);
}
bool UIExtension::ParentNotify::NotifyMod(UIExtension::TaskAttribute nAttribute, double value)
{
IUITASKMOD mod = { UIExtension::Map(nAttribute), 0 };
mod.dValue = value;
return DoNotify(&mod, 1);
}
bool UIExtension::ParentNotify::NotifyMod(UIExtension::TaskAttribute nAttribute, double time, Task::TimeUnits units)
{
IUITASKMOD mod = { UIExtension::Map(nAttribute), 0 };
mod.dValue = time;
mod.nTimeUnits = Task::Map(units);
return DoNotify(&mod, 1);
}
bool UIExtension::ParentNotify::NotifyMod(UIExtension::TaskAttribute nAttribute, int value)
{
IUITASKMOD mod = { UIExtension::Map(nAttribute), 0 };
mod.nValue = value;
return DoNotify(&mod, 1);
}
bool UIExtension::ParentNotify::NotifyMod(UIExtension::TaskAttribute nAttribute, bool value)
{
IUITASKMOD mod = { UIExtension::Map(nAttribute), 0 };
mod.bValue = (value ? TRUE : FALSE);
return DoNotify(&mod, 1);
}
bool UIExtension::ParentNotify::NotifyMod(String^ sCustAttribID, String^ value)
{
IUITASKMOD mod = { IUI_CUSTOMATTRIB, 0 };
mod.szValue = MS(value);
mod.szCustomAttribID = MS(sCustAttribID);
return DoNotify(&mod, 1);
}
bool UIExtension::ParentNotify::NotifyMod(UIExtension::TaskAttribute nAttribute, String^ value)
{
IUITASKMOD mod = { UIExtension::Map(nAttribute), 0 };
mod.szValue = MS(value);
return DoNotify(&mod, 1);
}
bool UIExtension::ParentNotify::NotifyMod(UIExtension::TaskAttribute nAttribute, cli::array<String^>^ aValues)
{
IUITASKMOD mod = { UIExtension::Map(nAttribute), 0 };
//mod.szValue = MS(value);
return DoNotify(&mod, 1);
}
bool UIExtension::ParentNotify::DoNotify(const IUITASKMOD* pMod, int numMod)
{
if (!IsWindow(m_hwndParent))
return false;
BOOL bRet = ::SendMessage(m_hwndParent, WM_IUI_MODIFYSELECTEDTASK, numMod, (LPARAM)pMod);
return (bRet != FALSE);
}
bool UIExtension::ParentNotify::NotifySelChange(UInt32 taskID)
{
if (!IsWindow(m_hwndParent))
return false;
BOOL bRet = ::SendMessage(m_hwndParent, WM_IUI_SELECTTASK, 0, taskID);
return (bRet != FALSE);
}
bool UIExtension::ParentNotify::NotifySelChange(cli::array<UInt32>^ pdwTaskIDs)
{
if (!IsWindow(m_hwndParent) || !pdwTaskIDs->Length)
return false;
pin_ptr<UInt32> p = &pdwTaskIDs[0];
BOOL bRet = ::SendMessage(m_hwndParent, WM_IUI_SELECTTASK, pdwTaskIDs->Length, (LPARAM)p);
return (bRet != FALSE);
}
////////////////////////////////////////////////////////////////////////////////////////////////
<|endoftext|> |
<commit_before>#include "llvm/IR/Function.h"
#include "llvm/IR/Constants.h"
#include "llvm/Pass.h"
#include "llvm/IR/LegacyPassManager.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/raw_ostream.h"
//#include "llvm/Transforms/Scalar.h"
#include "llvm/Transforms/IPO.h"
#include "llvm/LinkAllPasses.h" //createAlwaysInlinerLegacyPass
#include "Specializer.h" // materializeStringLiteral
#include <string> // stoi, strtok, ...
#include <fstream> // ifstream
//#include <stdexcept> // std::invalid_argument
namespace previrt
{
class ArgumentsConstraint : public llvm::ModulePass
{
public:
static char ID;
ArgumentsConstraint();
virtual ~ArgumentsConstraint();
virtual void getAnalysisUsage (llvm::AnalysisUsage &AU) const {}
virtual llvm::StringRef getPassName() const
{ return "Partial specialization of program arguments"; }
virtual bool runOnModule(llvm::Module &M);
};
}
using namespace llvm;
using namespace previrt;
static cl::opt<std::string> InputFilename
("Pconstraints-input",
cl::init(""),
cl::Hidden,
cl::desc("Specify the filename with input arguments"));
ArgumentsConstraint::ArgumentsConstraint()
: ModulePass (ID) {}
ArgumentsConstraint::~ArgumentsConstraint() {}
// line is "N S" where N is any non-negative number and S is a string
// between double quotes
bool parse_input_line(std::string line, unsigned &index, std::string &s) {
std::vector<std::string> tokens;
std::size_t pos = 0;
std::size_t found = line.find_first_of(' ', pos);
if (found != std::string::npos) {
tokens.push_back(line.substr(pos, found - pos));
pos = found+1;
tokens.push_back(line.substr(pos));
} else {
errs () << "Could not parse " << line << "\n";
return false;
}
if (tokens.size() != 2) {
return false;
} else {
// XXX: llvm disables exceptions
//try {
index = (unsigned) std::stoi(tokens[0]);
// }
// catch (const std::invalid_argument &ia) {
// return false;
// }
s = tokens[1];
return true;
}
}
// out contains all argv's parameters defined by the user
void populate_program_arguments(std::string filename,
std::map<unsigned, std::string> &out,
int &argc) {
std::string line;
std::ifstream fd (filename);
if (fd.is_open()) {
std::string argc_line;
getline(fd,argc_line);
argc = std::stoi(argc_line);
while (getline(fd,line)) {
unsigned i; std::string val;
if (parse_input_line(line, i, val)) {
out.insert(std::make_pair(i, val));
}
}
fd.close();
} else {
errs () << filename << " not found\n";
}
}
bool ArgumentsConstraint::runOnModule(Module &M) {
/*
Given argv[0], argv[1], ... argv[argc-1] and k extra arguments
from the manifest x1, ..., xk it builds a new argv array,
new_argv, such that
new_argv[0] = x1,
new_argv[1] = x2,
...
new_argv[k] = xk,
new_argv[k+1] = argv[1],
new_argv[k+2] = argv[2],
...
new_argv[k+argc-1]= argv[argc-1]
XXX: note that we ignore argv[0] because we assume that it is
always given by the manifest (x1).
*/
Function *main = M.getFunction("main");
if (!main) {
errs() << "Running on module without 'main' function.\n"
<< "Ignoring...\n";
return false;
}
if (main->arg_size() != 2) {
errs() << "main function has incorrect signature\n"
<< *(main->getFunctionType()) << "Ignoring...\n";
return false;
}
// Create partial map from indexes to strings
std::map<unsigned, std::string> argv_map;
int extra_argc = -1;
populate_program_arguments(InputFilename, argv_map, extra_argc);
if (argv_map.empty()) {
errs () << "User did not provide program parameters. Ignoring ...\n";
return false;
}
if (argv_map.find(0) == argv_map.end()) {
errs () << "argv[0] does not exist in the manifest. Ignoring ...\n";
return false;
}
IRBuilder<> builder(M.getContext());
IntegerType* intptrty =
cast<IntegerType>(M.getDataLayout().getIntPtrType(M.getContext(), 0));
Type* const strty =
PointerType::getUnqual(IntegerType::get(M.getContext(),8));
// new_main
Function *new_main = Function::Create(main->getFunctionType(),
main->getLinkage(), "", &M);
new_main->takeName(main);
Function::arg_iterator ai = new_main->arg_begin();
Value* argc = (Value*) &(*ai);
Value* argv = (Value*) &(*(++ai));
BasicBlock *entry = BasicBlock::Create(M.getContext(),"entry", new_main);
builder.SetInsertPoint(entry);
// new argc
Value* new_argc =
builder.CreateAdd(argc,
ConstantInt::get(argc->getType(),
argv_map.size() -1 /*ignore argv[0]*/),
"new_argc");
if (extra_argc != -1) {
builder.CreateAssumption(builder.CreateICmpEQ(argc,
ConstantInt::get(argc->getType(),
(extra_argc + 1 /* add argv[0] from command line*/))));
} else {
errs () << "No argc given in the manifest so specialization might not take place\n";
}
// new argv
Value* new_argv = builder.CreateAlloca(strty, new_argc, "new_argv");
// copy the manifest into new_argv
unsigned i=0;
for (auto &kv: argv_map) {
// create a global variable with the argument from the manifest
GlobalVariable *gv_i = materializeStringLiteral(M, kv.second.c_str());
// take the address of the global variable
Value *gv_i_ref =
builder.CreateConstGEP2_32(
cast<PointerType>(gv_i->getType())->getElementType(),gv_i, 0, 0);
// store the global variable into new_argv[i]
Value *new_argv_i = builder.CreateConstGEP1_32(new_argv,i);
builder.CreateStore(gv_i_ref, new_argv_i);
i++;
}
/* Loop that copies argv into new_argv starting at index k
Before
Entry
After
Entry:
...
goto PreHeader
PreHeader:
%j = alloca i32
store 0 %j
goto Header
Header:
%t1 = load %j
%f = icmp slt %t1, %argc
br %f, Body, Tail
Body:
%o1 = add %t1, %k
%a1 = gep %new_argv, %o1
%a2 = gep %argv, %t1
store (load %a2), %a1
%t2 = add %t1, 1
store %t2, %j
goto Header
Tail:
%r = call main(%newargc, %new_argv);
ret %r
*/
BasicBlock *pre_header = BasicBlock::Create(M.getContext(),"pre_header", new_main);
builder.CreateBr(pre_header);
builder.SetInsertPoint(pre_header);
Type *intTy = argc->getType();
AllocaInst *j = builder.CreateAlloca(intTy);
builder.CreateStore(ConstantInt::get(intTy, 1), j); /*ignore argv[0]*/
// header
BasicBlock *header = BasicBlock::Create(M.getContext(),"header", new_main);
builder.CreateBr(header);
builder.SetInsertPoint(header);
LoadInst *t1 = builder.CreateLoad(j);
Value *cond = builder.CreateICmpSLT(t1, argc);
BasicBlock *body = BasicBlock::Create(M.getContext(),"body", new_main);
BasicBlock *tail = BasicBlock::Create(M.getContext(),"tail", new_main);
builder.CreateCondBr(cond, body, tail);
// body
builder.SetInsertPoint(body);
Value *o1 = builder.CreateZExtOrTrunc(
builder.CreateAdd(ConstantInt::get(intTy, argv_map.size() -1 /*skip argv[0]*/),
t1),
intptrty);
Value *a1 = builder.CreateInBoundsGEP(new_argv, o1);
Value *o2 = builder.CreateZExtOrTrunc(t1, intptrty);
Value *a2 = builder.CreateInBoundsGEP(argv, o2);
builder.CreateStore(builder.CreateLoad(a2),a1);
Value *t2 = builder.CreateAdd(t1, ConstantInt::get(intTy,1));
builder.CreateStore(t2, j);
builder.CreateBr(header);
//tail
builder.SetInsertPoint(tail);
// call the code of the original main with new argc and new argv
Value* res = builder.CreateCall(main, {new_argc, new_argv});
builder.CreateRet(res);
// Modify main attributes so that it can be inlined
main->setLinkage(GlobalValue::PrivateLinkage);
main->removeFnAttr(Attribute::NoInline);
main->removeFnAttr(Attribute::OptimizeNone);
main->addFnAttr(Attribute::AlwaysInline);
legacy::PassManager mgr;
// remove alloca's
mgr.add(createPromoteMemoryToRegisterPass());
// break alloca's of aggregates into multiple allocas if possible
// it also performs mem2reg to remove alloca's at the same time
mgr.add(createSROAPass());
// inline original main function
mgr.add(createAlwaysInlinerLegacyPass());
mgr.run(M);
/* Old code that overrides argv with the arguments from the
manifest */
// Function::arg_iterator ai = main->arg_begin();
// Value* argv = (Value*) &(*(++ai));
// for (auto &kv: argv_map) {
// // create a global variable with the content of argv[i]
// GlobalVariable* gv_i = materializeStringLiteral(M, kv.second.c_str());
// // take the address of the global variable
// Value *gv_i_ref =
// builder.CreateConstGEP2_32(cast<PointerType>(gv_i->getType())->getElementType(),
// gv_i, 0, 0);
// // compute a gep instruction that access to argv[i]
// Value* argv_i = builder.CreateConstGEP1_32(argv, kv.first);
// // store the global variable into argv[i]
// builder.CreateStore(gv_i_ref, argv_i);
// }
// legacy::PassManager mgr;
// mgr.add(createGlobalOptimizerPass());
// mgr.add(createGlobalDCEPass());
// mgr.run(M);
return true;
}
char ArgumentsConstraint::ID = 0;
static RegisterPass<previrt::ArgumentsConstraint>
X("Pconstraints",
"Partial specialization of main arguments",
false, false);
<commit_msg>Add names to new global variables [ci skip]<commit_after>#include "llvm/IR/Function.h"
#include "llvm/IR/Constants.h"
#include "llvm/Pass.h"
#include "llvm/IR/LegacyPassManager.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/raw_ostream.h"
//#include "llvm/Transforms/Scalar.h"
#include "llvm/Transforms/IPO.h"
#include "llvm/LinkAllPasses.h" //createAlwaysInlinerLegacyPass
#include "Specializer.h" // materializeStringLiteral
#include <string> // stoi, strtok, ...
#include <fstream> // ifstream
//#include <stdexcept> // std::invalid_argument
namespace previrt
{
class ArgumentsConstraint : public llvm::ModulePass
{
public:
static char ID;
ArgumentsConstraint();
virtual ~ArgumentsConstraint();
virtual void getAnalysisUsage (llvm::AnalysisUsage &AU) const {}
virtual llvm::StringRef getPassName() const
{ return "Partial specialization of program arguments"; }
virtual bool runOnModule(llvm::Module &M);
};
}
using namespace llvm;
using namespace previrt;
static cl::opt<std::string> InputFilename
("Pconstraints-input",
cl::init(""),
cl::Hidden,
cl::desc("Specify the filename with input arguments"));
ArgumentsConstraint::ArgumentsConstraint()
: ModulePass (ID) {}
ArgumentsConstraint::~ArgumentsConstraint() {}
// line is "N S" where N is any non-negative number and S is a string
// between double quotes
bool parse_input_line(std::string line, unsigned &index, std::string &s) {
std::vector<std::string> tokens;
std::size_t pos = 0;
std::size_t found = line.find_first_of(' ', pos);
if (found != std::string::npos) {
tokens.push_back(line.substr(pos, found - pos));
pos = found+1;
tokens.push_back(line.substr(pos));
} else {
errs () << "Could not parse " << line << "\n";
return false;
}
if (tokens.size() != 2) {
return false;
} else {
// XXX: llvm disables exceptions
//try {
index = (unsigned) std::stoi(tokens[0]);
// }
// catch (const std::invalid_argument &ia) {
// return false;
// }
s = tokens[1];
return true;
}
}
// out contains all argv's parameters defined by the user
void populate_program_arguments(std::string filename,
std::map<unsigned, std::string> &out,
int &argc) {
std::string line;
std::ifstream fd (filename);
if (fd.is_open()) {
std::string argc_line;
getline(fd,argc_line);
argc = std::stoi(argc_line);
while (getline(fd,line)) {
unsigned i; std::string val;
if (parse_input_line(line, i, val)) {
out.insert(std::make_pair(i, val));
}
}
fd.close();
} else {
errs () << filename << " not found\n";
}
}
bool ArgumentsConstraint::runOnModule(Module &M) {
/*
Given argv[0], argv[1], ... argv[argc-1] and k extra arguments
from the manifest x1, ..., xk it builds a new argv array,
new_argv, such that
new_argv[0] = x1,
new_argv[1] = x2,
...
new_argv[k] = xk,
new_argv[k+1] = argv[1],
new_argv[k+2] = argv[2],
...
new_argv[k+argc-1]= argv[argc-1]
XXX: note that we ignore argv[0] because we assume that it is
always given by the manifest (x1).
*/
Function *main = M.getFunction("main");
if (!main) {
errs() << "Running on module without 'main' function.\n"
<< "Ignoring...\n";
return false;
}
if (main->arg_size() != 2) {
errs() << "main function has incorrect signature\n"
<< *(main->getFunctionType()) << "Ignoring...\n";
return false;
}
// Create partial map from indexes to strings
std::map<unsigned, std::string> argv_map;
int extra_argc = -1;
populate_program_arguments(InputFilename, argv_map, extra_argc);
if (argv_map.empty()) {
errs () << "User did not provide program parameters. Ignoring ...\n";
return false;
}
if (argv_map.find(0) == argv_map.end()) {
errs () << "argv[0] does not exist in the manifest. Ignoring ...\n";
return false;
}
IRBuilder<> builder(M.getContext());
IntegerType* intptrty =
cast<IntegerType>(M.getDataLayout().getIntPtrType(M.getContext(), 0));
Type* const strty =
PointerType::getUnqual(IntegerType::get(M.getContext(),8));
// new_main
Function *new_main = Function::Create(main->getFunctionType(),
main->getLinkage(), "", &M);
new_main->takeName(main);
Function::arg_iterator ai = new_main->arg_begin();
Value* argc = (Value*) &(*ai);
Value* argv = (Value*) &(*(++ai));
BasicBlock *entry = BasicBlock::Create(M.getContext(),"entry", new_main);
builder.SetInsertPoint(entry);
// new argc
Value* new_argc =
builder.CreateAdd(argc,
ConstantInt::get(argc->getType(),
argv_map.size() -1 /*ignore argv[0]*/),
"new_argc");
if (extra_argc != -1) {
builder.CreateAssumption(builder.CreateICmpEQ(argc,
ConstantInt::get(argc->getType(),
(extra_argc + 1 /* add argv[0] from command line*/))));
} else {
errs () << "No argc given in the manifest so specialization might not take place\n";
}
// new argv
Value* new_argv = builder.CreateAlloca(strty, new_argc, "new_argv");
// copy the manifest into new_argv
unsigned i=0;
for (auto &kv: argv_map) {
// create a global variable with the argument from the manifest
GlobalVariable *gv_i = materializeStringLiteral(M, kv.second.c_str());
gv_i->setName("new_argv");
// take the address of the global variable
Value *gv_i_ref =
builder.CreateConstGEP2_32(
cast<PointerType>(gv_i->getType())->getElementType(),gv_i, 0, 0);
// store the global variable into new_argv[i]
Value *new_argv_i = builder.CreateConstGEP1_32(new_argv,i);
builder.CreateStore(gv_i_ref, new_argv_i);
i++;
}
/* Loop that copies argv into new_argv starting at index k
Before
Entry
After
Entry:
...
goto PreHeader
PreHeader:
%j = alloca i32
store 0 %j
goto Header
Header:
%t1 = load %j
%f = icmp slt %t1, %argc
br %f, Body, Tail
Body:
%o1 = add %t1, %k
%a1 = gep %new_argv, %o1
%a2 = gep %argv, %t1
store (load %a2), %a1
%t2 = add %t1, 1
store %t2, %j
goto Header
Tail:
%r = call main(%newargc, %new_argv);
ret %r
*/
BasicBlock *pre_header = BasicBlock::Create(M.getContext(),"pre_header", new_main);
builder.CreateBr(pre_header);
builder.SetInsertPoint(pre_header);
Type *intTy = argc->getType();
AllocaInst *j = builder.CreateAlloca(intTy);
builder.CreateStore(ConstantInt::get(intTy, 1), j); /*ignore argv[0]*/
// header
BasicBlock *header = BasicBlock::Create(M.getContext(),"header", new_main);
builder.CreateBr(header);
builder.SetInsertPoint(header);
LoadInst *t1 = builder.CreateLoad(j);
Value *cond = builder.CreateICmpSLT(t1, argc);
BasicBlock *body = BasicBlock::Create(M.getContext(),"body", new_main);
BasicBlock *tail = BasicBlock::Create(M.getContext(),"tail", new_main);
builder.CreateCondBr(cond, body, tail);
// body
builder.SetInsertPoint(body);
Value *o1 = builder.CreateZExtOrTrunc(
builder.CreateAdd(ConstantInt::get(intTy, argv_map.size() -1 /*skip argv[0]*/),
t1),
intptrty);
Value *a1 = builder.CreateInBoundsGEP(new_argv, o1);
Value *o2 = builder.CreateZExtOrTrunc(t1, intptrty);
Value *a2 = builder.CreateInBoundsGEP(argv, o2);
builder.CreateStore(builder.CreateLoad(a2),a1);
Value *t2 = builder.CreateAdd(t1, ConstantInt::get(intTy,1));
builder.CreateStore(t2, j);
builder.CreateBr(header);
//tail
builder.SetInsertPoint(tail);
// call the code of the original main with new argc and new argv
Value* res = builder.CreateCall(main, {new_argc, new_argv});
builder.CreateRet(res);
// Modify main attributes so that it can be inlined
main->setLinkage(GlobalValue::PrivateLinkage);
main->removeFnAttr(Attribute::NoInline);
main->removeFnAttr(Attribute::OptimizeNone);
main->addFnAttr(Attribute::AlwaysInline);
legacy::PassManager mgr;
// remove alloca's
mgr.add(createPromoteMemoryToRegisterPass());
// break alloca's of aggregates into multiple allocas if possible
// it also performs mem2reg to remove alloca's at the same time
mgr.add(createSROAPass());
// inline original main function
mgr.add(createAlwaysInlinerLegacyPass());
mgr.run(M);
/* Old code that overrides argv with the arguments from the
manifest */
// Function::arg_iterator ai = main->arg_begin();
// Value* argv = (Value*) &(*(++ai));
// for (auto &kv: argv_map) {
// // create a global variable with the content of argv[i]
// GlobalVariable* gv_i = materializeStringLiteral(M, kv.second.c_str());
// // take the address of the global variable
// Value *gv_i_ref =
// builder.CreateConstGEP2_32(cast<PointerType>(gv_i->getType())->getElementType(),
// gv_i, 0, 0);
// // compute a gep instruction that access to argv[i]
// Value* argv_i = builder.CreateConstGEP1_32(argv, kv.first);
// // store the global variable into argv[i]
// builder.CreateStore(gv_i_ref, argv_i);
// }
// legacy::PassManager mgr;
// mgr.add(createGlobalOptimizerPass());
// mgr.add(createGlobalDCEPass());
// mgr.run(M);
return true;
}
char ArgumentsConstraint::ID = 0;
static RegisterPass<previrt::ArgumentsConstraint>
X("Pconstraints",
"Partial specialization of main arguments",
false, false);
<|endoftext|> |
<commit_before>#include "stdafx.h"
#include "PolymorphicTypeForestTest.h"
#include SHARED_PTR_HEADER
class ObjA:
public Object
{
};
class ObjB:
public Object
{
};
class ObjB1:
public ObjB
{
};
class ObjB2:
public ObjB
{
};
TEST_F(PolymorphicTypeForestTest, SimpleInsertion) {
std::shared_ptr<ObjA> pA(new ObjA);
std::shared_ptr<ObjB> pB(new ObjB);
// Prime the forest:
ASSERT_TRUE(forest.AddTree(pA)) << "Failed to add a witness to an empty tree";
ASSERT_TRUE(forest.AddTree(pB)) << "Failed to add an unrelated witness to a tree";
// Ensure we can find the items we just added
std::shared_ptr<ObjA> foundA;
std::shared_ptr<ObjB> foundB;
EXPECT_TRUE(forest.Resolve(foundA)) << "Failed to resolve the first-inserted type";
EXPECT_TRUE(forest.Resolve(foundB)) << "Failed to resolve the second-inserted type";
// Ensure object identities line up:
EXPECT_EQ(pA, foundA) << "Failed to resolve object A back to its original pointer";
EXPECT_EQ(pB, foundB) << "Failed to resolve object B back to its original pointer";
}
TEST_F(PolymorphicTypeForestTest, AncestralCollision) {
// Prime the forest:
forest.AddTree(std::make_shared<ObjA>());
forest.AddTree(std::make_shared<ObjB1>());
forest.AddTree(std::make_shared<ObjB2>());
// Attempt the illegal insertion:
EXPECT_FALSE(forest.AddTree(std::make_shared<ObjB>())) << "An insertion of an ambiguity-creating type was incorrectly allowed";
}
TEST_F(PolymorphicTypeForestTest, DescendantCollision) {
// Prime the forest:
forest.AddTree(std::make_shared<ObjA>());
forest.AddTree(std::make_shared<ObjB>());
// Attempt the illegal insertion:
EXPECT_FALSE(forest.AddTree(std::make_shared<ObjB1>())) << "An insertion of an ambiguity-creating type was incorrectly allowed";
}
TEST_F(PolymorphicTypeForestTest, APrioriAmbiguation) {
// Prime the forest:
forest.AddTree(std::make_shared<ObjA>());
// Attempt to find type B, which should not resolve yet because we haven't added B:
std::shared_ptr<ObjB> ptr;
EXPECT_TRUE(forest.Resolve(ptr)) << "A resolution attempt was considered ambiguous, even though it should have been unresolvable";
ASSERT_TRUE(ptr == nullptr) << "Was able to resolve a type name that should have been unavailable";
// Now add an object which will allow the prior resolution to succeed:
EXPECT_TRUE(forest.AddTree(std::make_shared<ObjB1>())) << "An insertion was not allowed which should have succeeded cleanly";
// And then, add an object which will make the prior resolution _ambiguous_
EXPECT_FALSE(forest.AddTree(std::make_shared<ObjB2>())) << "An ambiguating insertion was incorrectly allowed";
// Attempt the resolution again
EXPECT_TRUE(forest.Resolve(ptr)) << "Failed to resolve a type which should have been available";
}
TEST_F(PolymorphicTypeForestTest, AmbiguousAncestorRequest) {
// Prime the forest:
forest.AddTree(std::make_shared<ObjA>());
forest.AddTree(std::make_shared<ObjB1>());
// At this point, resolving B should be possible:
std::shared_ptr<ObjB> ptr;
EXPECT_TRUE(forest.Resolve(ptr)) << "Failed to resolve an ancestor of an existing type in the forest";
// Adding this type should not be possible, now that ObjB resolution has taken place
// The introduction of this tree would make the prior resolution ambiguous.
EXPECT_FALSE(forest.AddTree(std::make_shared<ObjB2>())) << "Resolved a type which should not have been resolvable due to existing memos";
// Attempt to find type B, which should still be resolvable
EXPECT_TRUE(forest.Resolve(ptr)) << "Was able to resolve a type name that should have been ambiguous";
}
TEST_F(PolymorphicTypeForestTest, GroundResolutionCheck) {
static_assert(
std::is_same<
ground_type_of<Object>::type,
Object
>::value,
"Incorrect identity property on ground_type_of"
);
static_assert(
std::is_same<
ground_type_of<ObjA>::type,
Object
>::value,
"Failed to match the ground type of an Object-grounded type"
);
// Now try to establish the ground of an ungrounded type:
static_assert(
std::is_same<
ground_type_of<std::string>::type,
std::string
>::value,
"Failed to reflect the ground type of a type which has no explicit ground"
);
}<commit_msg>Adding a unit test to validate cross-resolvable interfaces<commit_after>#include "stdafx.h"
#include "PolymorphicTypeForestTest.h"
#include SHARED_PTR_HEADER
class UnrelatedInterface:
{
public:
virtual ~UnrelatedInterface(void);
};
class ObjA:
public Object
{
};
class ObjB:
public Object
{
};
class ObjB1:
public ObjB
{
};
class ObjB2:
public ObjB,
public UnrelatedInterface
{
};
TEST_F(PolymorphicTypeForestTest, SimpleInsertion) {
std::shared_ptr<ObjA> pA(new ObjA);
std::shared_ptr<ObjB> pB(new ObjB);
// Prime the forest:
ASSERT_TRUE(forest.AddTree(pA)) << "Failed to add a witness to an empty tree";
ASSERT_TRUE(forest.AddTree(pB)) << "Failed to add an unrelated witness to a tree";
// Ensure we can find the items we just added
std::shared_ptr<ObjA> foundA;
std::shared_ptr<ObjB> foundB;
EXPECT_TRUE(forest.Resolve(foundA)) << "Failed to resolve the first-inserted type";
EXPECT_TRUE(forest.Resolve(foundB)) << "Failed to resolve the second-inserted type";
// Ensure object identities line up:
EXPECT_EQ(pA, foundA) << "Failed to resolve object A back to its original pointer";
EXPECT_EQ(pB, foundB) << "Failed to resolve object B back to its original pointer";
}
TEST_F(PolymorphicTypeForestTest, AncestralCollision) {
// Prime the forest:
forest.AddTree(std::make_shared<ObjA>());
forest.AddTree(std::make_shared<ObjB1>());
forest.AddTree(std::make_shared<ObjB2>());
// Attempt the illegal insertion:
EXPECT_FALSE(forest.AddTree(std::make_shared<ObjB>())) << "An insertion of an ambiguity-creating type was incorrectly allowed";
}
TEST_F(PolymorphicTypeForestTest, DescendantCollision) {
// Prime the forest:
forest.AddTree(std::make_shared<ObjA>());
forest.AddTree(std::make_shared<ObjB>());
// Attempt the illegal insertion:
EXPECT_FALSE(forest.AddTree(std::make_shared<ObjB1>())) << "An insertion of an ambiguity-creating type was incorrectly allowed";
}
TEST_F(PolymorphicTypeForestTest, APrioriAmbiguation) {
// Prime the forest:
forest.AddTree(std::make_shared<ObjA>());
// Attempt to find type B, which should not resolve yet because we haven't added B:
std::shared_ptr<ObjB> ptr;
EXPECT_TRUE(forest.Resolve(ptr)) << "A resolution attempt was considered ambiguous, even though it should have been unresolvable";
ASSERT_TRUE(ptr == nullptr) << "Was able to resolve a type name that should have been unavailable";
// Now add an object which will allow the prior resolution to succeed:
EXPECT_TRUE(forest.AddTree(std::make_shared<ObjB1>())) << "An insertion was not allowed which should have succeeded cleanly";
// And then, add an object which will make the prior resolution _ambiguous_
EXPECT_FALSE(forest.AddTree(std::make_shared<ObjB2>())) << "An ambiguating insertion was incorrectly allowed";
// Attempt the resolution again
EXPECT_TRUE(forest.Resolve(ptr)) << "Failed to resolve a type which should have been available";
}
TEST_F(PolymorphicTypeForestTest, AmbiguousAncestorRequest) {
// Prime the forest:
forest.AddTree(std::make_shared<ObjA>());
forest.AddTree(std::make_shared<ObjB1>());
// At this point, resolving B should be possible:
std::shared_ptr<ObjB> ptr;
EXPECT_TRUE(forest.Resolve(ptr)) << "Failed to resolve an ancestor of an existing type in the forest";
// Adding this type should not be possible, now that ObjB resolution has taken place
// The introduction of this tree would make the prior resolution ambiguous.
EXPECT_FALSE(forest.AddTree(std::make_shared<ObjB2>())) << "Resolved a type which should not have been resolvable due to existing memos";
// Attempt to find type B, which should still be resolvable
EXPECT_TRUE(forest.Resolve(ptr)) << "Was able to resolve a type name that should have been ambiguous";
}
TEST_F(PolymorphicTypeForestTest, GroundResolutionCheck) {
static_assert(
std::is_same<
ground_type_of<Object>::type,
Object
>::value,
"Incorrect identity property on ground_type_of"
);
static_assert(
std::is_same<
ground_type_of<ObjA>::type,
Object
>::value,
"Failed to match the ground type of an Object-grounded type"
);
// Now try to establish the ground of an ungrounded type:
static_assert(
std::is_same<
ground_type_of<std::string>::type,
std::string
>::value,
"Failed to reflect the ground type of a type which has no explicit ground"
);
}
TEST_F(PolymorphicTypeForestTest, UnrelatedInterfaceTest) {
// Add the object which has our interface:
forest.AddTree(std::make_shared<ObjB2>());
// Attempt to resolve based on this interface:
std::shared_ptr<UnrelatedInterface> urif;
EXPECT_TRUE(forest.Resolve(urif)) << "An ungrounded interface resolution attempt was incorrectly interpreted as ambiguous";
EXPECT_TRUE(urif != nullptr) << "Failed to resolve an ungrounded interface on ObjB2";
}<|endoftext|> |
<commit_before>/*
Copyright 2017-2020 Intel Corporation
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include "TraceConsumer.hpp"
#include "ETW/Microsoft_Windows_EventMetadata.h"
namespace {
uint32_t GetPropertyDataOffset(TRACE_EVENT_INFO const& tei, EVENT_RECORD const& eventRecord, uint32_t index);
// If ((epi.Flags & PropertyParamLength) != 0), the epi.lengthPropertyIndex
// field contains the index of the property that contains the number of
// CHAR/WCHARs in the string.
//
// Else if ((epi.Flags & PropertyLength) != 0 || epi.length != 0), the
// epi.length field contains number of CHAR/WCHARs in the string.
//
// Else the string is terminated by (CHAR/WCHAR)0.
//
// Note that some event providers do not correctly null-terminate the last
// string field in the event. While this is technically invalid, event decoders
// may silently tolerate such behavior instead of rejecting the event as
// invalid.
template<typename T>
uint32_t GetStringPropertySize(TRACE_EVENT_INFO const& tei, EVENT_RECORD const& eventRecord, uint32_t index, uint32_t offset,
uint32_t* propStatus)
{
auto const& epi = tei.EventPropertyInfoArray[index];
if ((epi.Flags & PropertyParamLength) != 0) {
assert(false); // TODO: just not implemented yet
return 0;
}
if (epi.length != 0) {
return epi.length * sizeof(T);
}
if (offset == UINT32_MAX) {
offset = GetPropertyDataOffset(tei, eventRecord, index);
assert(offset <= eventRecord.UserDataLength);
}
for (uint32_t size = 0;; size += sizeof(T)) {
if (offset + size > eventRecord.UserDataLength) {
// string ends at end of block, possibly ok (see note above)
return size - sizeof(T);
}
if (*(T const*) ((uintptr_t) eventRecord.UserData + offset + size) == (T) 0) {
*propStatus |= PROP_STATUS_NULL_TERMINATED;
return size + sizeof(T);
}
}
}
void GetPropertySize(TRACE_EVENT_INFO const& tei, EVENT_RECORD const& eventRecord, uint32_t index, uint32_t offset,
uint32_t* outSize, uint32_t* outCount, uint32_t* propStatus)
{
// We don't handle all flags yet, these are the ones we do:
auto const& epi = tei.EventPropertyInfoArray[index];
assert((epi.Flags & ~(PropertyStruct | PropertyParamCount | PropertyParamFixedCount)) == 0);
// Use the epi length and count by default. There are cases where the count
// is valid but (epi.Flags & PropertyParamFixedCount) == 0.
uint32_t size = epi.length;
uint32_t count = epi.count;
if (epi.Flags & PropertyStruct) {
size = 0;
for (USHORT i = 0; i < epi.structType.NumOfStructMembers; ++i) {
uint32_t memberSize = 0;
uint32_t memberCount = 0;
uint32_t memberStatus = 0;
GetPropertySize(tei, eventRecord, epi.structType.StructStartIndex + i, UINT32_MAX, &memberSize, &memberCount, &memberStatus);
size += memberSize * memberCount;
}
} else {
switch (epi.nonStructType.InType) {
case TDH_INTYPE_UNICODESTRING:
*propStatus |= PROP_STATUS_WCHAR_STRING;
size = GetStringPropertySize<wchar_t>(tei, eventRecord, index, offset, propStatus);
break;
case TDH_INTYPE_ANSISTRING:
*propStatus |= PROP_STATUS_CHAR_STRING;
size = GetStringPropertySize<char>(tei, eventRecord, index, offset, propStatus);
break;
case TDH_INTYPE_POINTER: // TODO: Not sure this is needed, epi.length seems to be correct?
case TDH_INTYPE_SIZET:
*propStatus |= PROP_STATUS_POINTER_SIZE;
size = (eventRecord.EventHeader.Flags & EVENT_HEADER_FLAG_64_BIT_HEADER) ? 8 : 4;
break;
case TDH_INTYPE_WBEMSID:
// TODO: can't figure out how to decode this... so reverting to TDH for now
{
PROPERTY_DATA_DESCRIPTOR descriptor;
descriptor.PropertyName = (ULONGLONG) &tei + epi.NameOffset;
descriptor.ArrayIndex = UINT32_MAX;
auto status = TdhGetPropertySize((EVENT_RECORD*) &eventRecord, 0, nullptr, 1, &descriptor, (ULONG*) &size);
(void) status;
}
break;
}
}
if (epi.Flags & PropertyParamCount) {
auto countIdx = epi.countPropertyIndex;
auto addr = (uintptr_t) eventRecord.UserData + GetPropertyDataOffset(tei, eventRecord, countIdx);
assert(tei.EventPropertyInfoArray[countIdx].Flags == 0);
switch (tei.EventPropertyInfoArray[countIdx].nonStructType.InType) {
case TDH_INTYPE_INT8: count = *(int8_t const*) addr; break;
case TDH_INTYPE_UINT8: count = *(uint8_t const*) addr; break;
case TDH_INTYPE_INT16: count = *(int16_t const*) addr; break;
case TDH_INTYPE_UINT16: count = *(uint16_t const*) addr; break;
case TDH_INTYPE_INT32: count = *(int32_t const*) addr; break;
case TDH_INTYPE_UINT32: count = *(uint32_t const*) addr; break;
default: assert(!"INTYPE not yet implemented for count.");
}
}
assert(size > 0);
assert(count > 0);
*outSize = size;
*outCount = count;
}
uint32_t GetPropertyDataOffset(TRACE_EVENT_INFO const& tei, EVENT_RECORD const& eventRecord, uint32_t index)
{
assert(index < tei.TopLevelPropertyCount);
uint32_t size = 0;
uint32_t count = 0;
uint32_t offset = 0;
uint32_t status = 0;
for (uint32_t i = 0; i < index; ++i) {
GetPropertySize(tei, eventRecord, i, offset, &size, &count, &status);
offset += size * count;
}
return offset;
}
TRACE_EVENT_INFO* GetTraceEventInfo(EventMetadata* metadata, EVENT_RECORD* eventRecord)
{
// Look up stored metadata
EventMetadataKey key;
key.guid_ = eventRecord->EventHeader.ProviderId;
key.desc_ = eventRecord->EventHeader.EventDescriptor;
auto ii = metadata->metadata_.find(key);
// If not found, look up metadata using TDH
if (ii == metadata->metadata_.end()) {
ULONG bufferSize = 0;
auto status = TdhGetEventInformation(eventRecord, 0, nullptr, nullptr, &bufferSize);
assert(status == ERROR_INSUFFICIENT_BUFFER);
ii = metadata->metadata_.emplace(key, std::vector<uint8_t>(bufferSize, 0)).first;
status = TdhGetEventInformation(eventRecord, 0, nullptr, (TRACE_EVENT_INFO*) ii->second.data(), &bufferSize);
assert(status == ERROR_SUCCESS);
}
return (TRACE_EVENT_INFO*) ii->second.data();
}
}
size_t EventMetadataKeyHash::operator()(EventMetadataKey const& key) const
{
static_assert((sizeof(key) % sizeof(size_t)) == 0, "sizeof(EventMetadataKey) must be multiple of sizeof(size_t)");
auto p = (size_t const*) &key;
auto h = (size_t) 0;
for (size_t i = 0; i < sizeof(key) / sizeof(size_t); ++i) {
h ^= p[i];
}
return h;
}
bool EventMetadataKeyEqual::operator()(EventMetadataKey const& lhs, EventMetadataKey const& rhs) const
{
return memcmp(&lhs, &rhs, sizeof(EventMetadataKey)) == 0;
}
void EventMetadata::AddMetadata(EVENT_RECORD* eventRecord)
{
if (eventRecord->EventHeader.EventDescriptor.Opcode == Microsoft_Windows_EventMetadata::EventInfo::Opcode) {
auto userData = (uint8_t const*) eventRecord->UserData;
auto tei = (TRACE_EVENT_INFO const*) userData;
if (tei->DecodingSource == DecodingSourceTlg || tei->EventDescriptor.Channel == 0xB) {
return; // Don't store tracelogging metadata
}
// Store metadata (overwriting any previous)
EventMetadataKey key;
key.guid_ = tei->ProviderGuid;
key.desc_ = tei->EventDescriptor;
metadata_[key].assign(userData, userData + eventRecord->UserDataLength);
}
}
// Look up metadata for this provider/event and use it to look up the property.
// If the metadata isn't found look it up using TDH. Then, look up each
// property in the metadata to obtain it's data pointer and size.
void EventMetadata::GetEventData(EVENT_RECORD* eventRecord, EventDataDesc* desc, uint32_t descCount, uint32_t optionalCount /*=0*/)
{
// Look up metadata
auto tei = GetTraceEventInfo(this, eventRecord);
// Lookup properties in metadata
uint32_t foundCount = 0;
#if 0 /* Helper to see all property names while debugging */
std::vector<wchar_t const*> props(tei->TopLevelPropertyCount, nullptr);
for (uint32_t i = 0; i < tei->TopLevelPropertyCount; ++i) {
props[i] = TEI_PROPERTY_NAME(tei, &tei->EventPropertyInfoArray[i]);
}
#endif
for (uint32_t i = 0, offset = 0; i < tei->TopLevelPropertyCount; ++i) {
uint32_t size = 0;
uint32_t count = 0;
uint32_t status = PROP_STATUS_FOUND;
GetPropertySize(*tei, *eventRecord, i, offset, &size, &count, &status);
auto propName = TEI_PROPERTY_NAME(tei, &tei->EventPropertyInfoArray[i]);
for (uint32_t j = 0; j < descCount; ++j) {
if (desc[j].status_ == PROP_STATUS_NOT_FOUND && wcscmp(propName, desc[j].name_) == 0) {
assert(desc[j].arrayIndex_ < count);
desc[j].data_ = (void*) ((uintptr_t) eventRecord->UserData + (offset + desc[j].arrayIndex_ * size));
desc[j].size_ = size;
desc[j].status_ = status;
foundCount += 1;
if (foundCount == descCount) {
return;
}
}
}
offset += size * count;
}
assert(foundCount >= descCount - optionalCount);
(void) optionalCount;
}
namespace {
template <typename T>
T GetEventString(EventDataDesc const& desc)
{
assert(desc.status_ & PROP_STATUS_FOUND);
assert(desc.status_ & (std::is_same<char, typename T::value_type>::value ? PROP_STATUS_CHAR_STRING : PROP_STATUS_WCHAR_STRING));
assert(desc.status_ & PROP_STATUS_NULL_TERMINATED);
assert((desc.size_ % sizeof(typename T::value_type)) == 0);
auto start = (typename T::value_type*) desc.data_;
auto end = (typename T::value_type*) ((uintptr_t) desc.data_ + desc.size_);
// Don't include null termination character
if (desc.status_ & PROP_STATUS_NULL_TERMINATED) {
assert(end > start);
end -= 1;
}
return T(start, end);
}
}
template <>
std::string EventDataDesc::GetData<std::string>() const
{
return GetEventString<std::string>(*this);
}
template <>
std::wstring EventDataDesc::GetData<std::wstring>() const
{
return GetEventString<std::wstring>(*this);
}
<commit_msg>More-gracefull handling of missing event information<commit_after>/*
Copyright 2017-2020 Intel Corporation
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include "TraceConsumer.hpp"
#include "ETW/Microsoft_Windows_EventMetadata.h"
namespace {
uint32_t GetPropertyDataOffset(TRACE_EVENT_INFO const& tei, EVENT_RECORD const& eventRecord, uint32_t index);
// If ((epi.Flags & PropertyParamLength) != 0), the epi.lengthPropertyIndex
// field contains the index of the property that contains the number of
// CHAR/WCHARs in the string.
//
// Else if ((epi.Flags & PropertyLength) != 0 || epi.length != 0), the
// epi.length field contains number of CHAR/WCHARs in the string.
//
// Else the string is terminated by (CHAR/WCHAR)0.
//
// Note that some event providers do not correctly null-terminate the last
// string field in the event. While this is technically invalid, event decoders
// may silently tolerate such behavior instead of rejecting the event as
// invalid.
template<typename T>
uint32_t GetStringPropertySize(TRACE_EVENT_INFO const& tei, EVENT_RECORD const& eventRecord, uint32_t index, uint32_t offset,
uint32_t* propStatus)
{
auto const& epi = tei.EventPropertyInfoArray[index];
if ((epi.Flags & PropertyParamLength) != 0) {
assert(false); // TODO: just not implemented yet
return 0;
}
if (epi.length != 0) {
return epi.length * sizeof(T);
}
if (offset == UINT32_MAX) {
offset = GetPropertyDataOffset(tei, eventRecord, index);
assert(offset <= eventRecord.UserDataLength);
}
for (uint32_t size = 0;; size += sizeof(T)) {
if (offset + size > eventRecord.UserDataLength) {
// string ends at end of block, possibly ok (see note above)
return size - sizeof(T);
}
if (*(T const*) ((uintptr_t) eventRecord.UserData + offset + size) == (T) 0) {
*propStatus |= PROP_STATUS_NULL_TERMINATED;
return size + sizeof(T);
}
}
}
void GetPropertySize(TRACE_EVENT_INFO const& tei, EVENT_RECORD const& eventRecord, uint32_t index, uint32_t offset,
uint32_t* outSize, uint32_t* outCount, uint32_t* propStatus)
{
// We don't handle all flags yet, these are the ones we do:
auto const& epi = tei.EventPropertyInfoArray[index];
assert((epi.Flags & ~(PropertyStruct | PropertyParamCount | PropertyParamFixedCount)) == 0);
// Use the epi length and count by default. There are cases where the count
// is valid but (epi.Flags & PropertyParamFixedCount) == 0.
uint32_t size = epi.length;
uint32_t count = epi.count;
if (epi.Flags & PropertyStruct) {
size = 0;
for (USHORT i = 0; i < epi.structType.NumOfStructMembers; ++i) {
uint32_t memberSize = 0;
uint32_t memberCount = 0;
uint32_t memberStatus = 0;
GetPropertySize(tei, eventRecord, epi.structType.StructStartIndex + i, UINT32_MAX, &memberSize, &memberCount, &memberStatus);
size += memberSize * memberCount;
}
} else {
switch (epi.nonStructType.InType) {
case TDH_INTYPE_UNICODESTRING:
*propStatus |= PROP_STATUS_WCHAR_STRING;
size = GetStringPropertySize<wchar_t>(tei, eventRecord, index, offset, propStatus);
break;
case TDH_INTYPE_ANSISTRING:
*propStatus |= PROP_STATUS_CHAR_STRING;
size = GetStringPropertySize<char>(tei, eventRecord, index, offset, propStatus);
break;
case TDH_INTYPE_POINTER: // TODO: Not sure this is needed, epi.length seems to be correct?
case TDH_INTYPE_SIZET:
*propStatus |= PROP_STATUS_POINTER_SIZE;
size = (eventRecord.EventHeader.Flags & EVENT_HEADER_FLAG_64_BIT_HEADER) ? 8 : 4;
break;
case TDH_INTYPE_WBEMSID:
// TODO: can't figure out how to decode this... so reverting to TDH for now
{
PROPERTY_DATA_DESCRIPTOR descriptor;
descriptor.PropertyName = (ULONGLONG) &tei + epi.NameOffset;
descriptor.ArrayIndex = UINT32_MAX;
auto status = TdhGetPropertySize((EVENT_RECORD*) &eventRecord, 0, nullptr, 1, &descriptor, (ULONG*) &size);
(void) status;
}
break;
}
}
if (epi.Flags & PropertyParamCount) {
auto countIdx = epi.countPropertyIndex;
auto addr = (uintptr_t) eventRecord.UserData + GetPropertyDataOffset(tei, eventRecord, countIdx);
assert(tei.EventPropertyInfoArray[countIdx].Flags == 0);
switch (tei.EventPropertyInfoArray[countIdx].nonStructType.InType) {
case TDH_INTYPE_INT8: count = *(int8_t const*) addr; break;
case TDH_INTYPE_UINT8: count = *(uint8_t const*) addr; break;
case TDH_INTYPE_INT16: count = *(int16_t const*) addr; break;
case TDH_INTYPE_UINT16: count = *(uint16_t const*) addr; break;
case TDH_INTYPE_INT32: count = *(int32_t const*) addr; break;
case TDH_INTYPE_UINT32: count = *(uint32_t const*) addr; break;
default: assert(!"INTYPE not yet implemented for count.");
}
}
assert(size > 0);
assert(count > 0);
*outSize = size;
*outCount = count;
}
uint32_t GetPropertyDataOffset(TRACE_EVENT_INFO const& tei, EVENT_RECORD const& eventRecord, uint32_t index)
{
assert(index < tei.TopLevelPropertyCount);
uint32_t size = 0;
uint32_t count = 0;
uint32_t offset = 0;
uint32_t status = 0;
for (uint32_t i = 0; i < index; ++i) {
GetPropertySize(tei, eventRecord, i, offset, &size, &count, &status);
offset += size * count;
}
return offset;
}
}
size_t EventMetadataKeyHash::operator()(EventMetadataKey const& key) const
{
static_assert((sizeof(key) % sizeof(size_t)) == 0, "sizeof(EventMetadataKey) must be multiple of sizeof(size_t)");
auto p = (size_t const*) &key;
auto h = (size_t) 0;
for (size_t i = 0; i < sizeof(key) / sizeof(size_t); ++i) {
h ^= p[i];
}
return h;
}
bool EventMetadataKeyEqual::operator()(EventMetadataKey const& lhs, EventMetadataKey const& rhs) const
{
return memcmp(&lhs, &rhs, sizeof(EventMetadataKey)) == 0;
}
void EventMetadata::AddMetadata(EVENT_RECORD* eventRecord)
{
if (eventRecord->EventHeader.EventDescriptor.Opcode == Microsoft_Windows_EventMetadata::EventInfo::Opcode) {
auto userData = (uint8_t const*) eventRecord->UserData;
auto tei = (TRACE_EVENT_INFO const*) userData;
if (tei->DecodingSource == DecodingSourceTlg || tei->EventDescriptor.Channel == 0xB) {
return; // Don't store tracelogging metadata
}
// Store metadata (overwriting any previous)
EventMetadataKey key;
key.guid_ = tei->ProviderGuid;
key.desc_ = tei->EventDescriptor;
metadata_[key].assign(userData, userData + eventRecord->UserDataLength);
}
}
// Look up metadata for this provider/event and use it to look up the property.
// If the metadata isn't found look it up using TDH. Then, look up each
// property in the metadata to obtain it's data pointer and size.
void EventMetadata::GetEventData(EVENT_RECORD* eventRecord, EventDataDesc* desc, uint32_t descCount, uint32_t optionalCount /*=0*/)
{
// Look up stored metadata. If not found, look up metadata using TDH and
// cache it for future events.
EventMetadataKey key;
key.guid_ = eventRecord->EventHeader.ProviderId;
key.desc_ = eventRecord->EventHeader.EventDescriptor;
auto ii = metadata_.find(key);
if (ii == metadata_.end()) {
ULONG bufferSize = 0;
auto status = TdhGetEventInformation(eventRecord, 0, nullptr, nullptr, &bufferSize);
if (status == ERROR_INSUFFICIENT_BUFFER) {
ii = metadata_.emplace(key, std::vector<uint8_t>(bufferSize, 0)).first;
status = TdhGetEventInformation(eventRecord, 0, nullptr, (TRACE_EVENT_INFO*) ii->second.data(), &bufferSize);
assert(status == ERROR_SUCCESS);
} else {
// No schema registered with system, nor ETL-embedded metadata.
ii = metadata_.emplace(key, std::vector<uint8_t>(sizeof(TRACE_EVENT_INFO), 0)).first;
assert(false);
}
}
auto tei = (TRACE_EVENT_INFO*) ii->second.data();
// Lookup properties in metadata
uint32_t foundCount = 0;
#if 0 /* Helper to see all property names while debugging */
std::vector<wchar_t const*> props(tei->TopLevelPropertyCount, nullptr);
for (uint32_t i = 0; i < tei->TopLevelPropertyCount; ++i) {
props[i] = TEI_PROPERTY_NAME(tei, &tei->EventPropertyInfoArray[i]);
}
#endif
for (uint32_t i = 0, offset = 0; i < tei->TopLevelPropertyCount; ++i) {
uint32_t size = 0;
uint32_t count = 0;
uint32_t status = PROP_STATUS_FOUND;
GetPropertySize(*tei, *eventRecord, i, offset, &size, &count, &status);
auto propName = TEI_PROPERTY_NAME(tei, &tei->EventPropertyInfoArray[i]);
for (uint32_t j = 0; j < descCount; ++j) {
if (desc[j].status_ == PROP_STATUS_NOT_FOUND && wcscmp(propName, desc[j].name_) == 0) {
assert(desc[j].arrayIndex_ < count);
desc[j].data_ = (void*) ((uintptr_t) eventRecord->UserData + (offset + desc[j].arrayIndex_ * size));
desc[j].size_ = size;
desc[j].status_ = status;
foundCount += 1;
if (foundCount == descCount) {
return;
}
}
}
offset += size * count;
}
assert(foundCount >= descCount - optionalCount);
(void) optionalCount;
}
namespace {
template <typename T>
T GetEventString(EventDataDesc const& desc)
{
assert(desc.status_ & PROP_STATUS_FOUND);
assert(desc.status_ & (std::is_same<char, typename T::value_type>::value ? PROP_STATUS_CHAR_STRING : PROP_STATUS_WCHAR_STRING));
assert(desc.status_ & PROP_STATUS_NULL_TERMINATED);
assert((desc.size_ % sizeof(typename T::value_type)) == 0);
auto start = (typename T::value_type*) desc.data_;
auto end = (typename T::value_type*) ((uintptr_t) desc.data_ + desc.size_);
// Don't include null termination character
if (desc.status_ & PROP_STATUS_NULL_TERMINATED) {
assert(end > start);
end -= 1;
}
return T(start, end);
}
}
template <>
std::string EventDataDesc::GetData<std::string>() const
{
return GetEventString<std::string>(*this);
}
template <>
std::wstring EventDataDesc::GetData<std::wstring>() const
{
return GetEventString<std::wstring>(*this);
}
<|endoftext|> |
<commit_before>#include "SocketsReader.h"
#include "InodeIpHelper.h"
#include "ProcNet.h"
#include "ProcFd.h"
#include "HexToIp.h"
NetDataAll SocketsReader::Read() {
unordered_map<string, NetData> tcpInodeIp;
unordered_map<string, NetData> udpInodeIp;
unordered_map<string, NetData> tcp6InodeIp;
unordered_map<string, NetData> udp6InodeIp;
vector<string> socketsInode = ProcFd(to_string(processId)).getSocketInodeList();
#pragma omp parallel sections
{
#pragma omp section
tcpInodeIp = ProcNet("tcp").getInodesIpMap();
#pragma omp section
udpInodeIp = ProcNet("udp").getInodesIpMap();
#pragma omp section
tcp6InodeIp = ProcNet("tcp6").getInodesIpMap();
#pragma omp section
udp6InodeIp = ProcNet("udp6").getInodesIpMap();
}
vector<NetData> tcpNetData;
vector<NetData> udpNetData;
vector<NetData> tcp6NetData;
vector<NetData> udp6NetData;
#pragma omp parallel sections
{
#pragma omp section
tcpNetData = InodeIpHelper::filterProccessIp(socketsInode, tcpInodeIp);
#pragma omp section
udpNetData = InodeIpHelper::filterProccessIp(socketsInode, udpInodeIp);
#pragma omp section
tcp6NetData = InodeIpHelper::filterProccessIp(socketsInode, tcp6InodeIp);
#pragma omp section
udp6NetData = InodeIpHelper::filterProccessIp(socketsInode, udp6InodeIp);
}
NetDataAll netDataAll;
#pragma omp parallel
{
#pragma omp for
for (int i = 0; i < tcpNetData.size(); ++i) {
NetData convertedNetData;
convertedNetData.localIp = HexToIp::convertHexToIpv4(tcpNetData[i].localIp);
convertedNetData.remoteIp = HexToIp::convertHexToIpv4(tcpNetData[i].remoteIp);
convertedNetData.localPort = HexToIp::convertHexToPort(tcpNetData[i].localPort);
convertedNetData.remotePort = HexToIp::convertHexToPort(tcpNetData[i].remotePort);
netDataAll.tcpNetData.push_back(convertedNetData);
}
#pragma omp for
for (int i = 0; i < udpNetData.size(); ++i) {
NetData convertedNetData;
convertedNetData.localIp = HexToIp::convertHexToIpv4(udpNetData[i].localIp);
convertedNetData.remoteIp = HexToIp::convertHexToIpv4(udpNetData[i].remoteIp);
convertedNetData.localPort = HexToIp::convertHexToPort(udpNetData[i].localPort);
convertedNetData.remotePort = HexToIp::convertHexToPort(udpNetData[i].remotePort);
netDataAll.udpNetData.push_back(convertedNetData);
}
#pragma omp for
for (int i = 0; i < tcp6NetData.size(); ++i) {
NetData convertedNetData;
convertedNetData.localIp = HexToIp::convertHexToIpv4(tcp6NetData[i].localIp);
convertedNetData.remoteIp = HexToIp::convertHexToIpv4(tcp6NetData[i].remoteIp);
convertedNetData.localPort = HexToIp::convertHexToPort(tcp6NetData[i].localPort);
convertedNetData.remotePort = HexToIp::convertHexToPort(tcp6NetData[i].remotePort);
netDataAll.tcp6NetData.push_back(convertedNetData);
}
#pragma omp for
for (int i = 0; i < udp6NetData.size(); ++i) {
NetData convertedNetData;
convertedNetData.localIp = HexToIp::convertHexToIpv4(udp6NetData[i].localIp);
convertedNetData.remoteIp = HexToIp::convertHexToIpv4(udp6NetData[i].remoteIp);
convertedNetData.localPort = HexToIp::convertHexToPort(udp6NetData[i].localPort);
convertedNetData.remotePort = HexToIp::convertHexToPort(udp6NetData[i].remotePort);
netDataAll.udp6NetData.push_back(convertedNetData);
}
}
return netDataAll;
}
<commit_msg>Convert to ipv6 instead of ipv4<commit_after>#include "SocketsReader.h"
#include "InodeIpHelper.h"
#include "ProcNet.h"
#include "ProcFd.h"
#include "HexToIp.h"
NetDataAll SocketsReader::Read() {
unordered_map<string, NetData> tcpInodeIp;
unordered_map<string, NetData> udpInodeIp;
unordered_map<string, NetData> tcp6InodeIp;
unordered_map<string, NetData> udp6InodeIp;
vector<string> socketsInode = ProcFd(to_string(processId)).getSocketInodeList();
#pragma omp parallel sections
{
#pragma omp section
tcpInodeIp = ProcNet("tcp").getInodesIpMap();
#pragma omp section
udpInodeIp = ProcNet("udp").getInodesIpMap();
#pragma omp section
tcp6InodeIp = ProcNet("tcp6").getInodesIpMap();
#pragma omp section
udp6InodeIp = ProcNet("udp6").getInodesIpMap();
}
vector<NetData> tcpNetData;
vector<NetData> udpNetData;
vector<NetData> tcp6NetData;
vector<NetData> udp6NetData;
#pragma omp parallel sections
{
#pragma omp section
tcpNetData = InodeIpHelper::filterProccessIp(socketsInode, tcpInodeIp);
#pragma omp section
udpNetData = InodeIpHelper::filterProccessIp(socketsInode, udpInodeIp);
#pragma omp section
tcp6NetData = InodeIpHelper::filterProccessIp(socketsInode, tcp6InodeIp);
#pragma omp section
udp6NetData = InodeIpHelper::filterProccessIp(socketsInode, udp6InodeIp);
}
NetDataAll netDataAll;
#pragma omp parallel
{
#pragma omp for
for (int i = 0; i < tcpNetData.size(); ++i) {
NetData convertedNetData;
convertedNetData.localIp = HexToIp::convertHexToIpv4(tcpNetData[i].localIp);
convertedNetData.remoteIp = HexToIp::convertHexToIpv4(tcpNetData[i].remoteIp);
convertedNetData.localPort = HexToIp::convertHexToPort(tcpNetData[i].localPort);
convertedNetData.remotePort = HexToIp::convertHexToPort(tcpNetData[i].remotePort);
netDataAll.tcpNetData.push_back(convertedNetData);
}
#pragma omp for
for (int i = 0; i < udpNetData.size(); ++i) {
NetData convertedNetData;
convertedNetData.localIp = HexToIp::convertHexToIpv4(udpNetData[i].localIp);
convertedNetData.remoteIp = HexToIp::convertHexToIpv4(udpNetData[i].remoteIp);
convertedNetData.localPort = HexToIp::convertHexToPort(udpNetData[i].localPort);
convertedNetData.remotePort = HexToIp::convertHexToPort(udpNetData[i].remotePort);
netDataAll.udpNetData.push_back(convertedNetData);
}
#pragma omp for
for (int i = 0; i < tcp6NetData.size(); ++i) {
NetData convertedNetData;
convertedNetData.localIp = HexToIp::convertHexToIpv6(tcp6NetData[i].localIp);
convertedNetData.remoteIp = HexToIp::convertHexToIpv6(tcp6NetData[i].remoteIp);
convertedNetData.localPort = HexToIp::convertHexToPort(tcp6NetData[i].localPort);
convertedNetData.remotePort = HexToIp::convertHexToPort(tcp6NetData[i].remotePort);
netDataAll.tcp6NetData.push_back(convertedNetData);
}
#pragma omp for
for (int i = 0; i < udp6NetData.size(); ++i) {
NetData convertedNetData;
convertedNetData.localIp = HexToIp::convertHexToIpv6(udp6NetData[i].localIp);
convertedNetData.remoteIp = HexToIp::convertHexToIpv6(udp6NetData[i].remoteIp);
convertedNetData.localPort = HexToIp::convertHexToPort(udp6NetData[i].localPort);
convertedNetData.remotePort = HexToIp::convertHexToPort(udp6NetData[i].remotePort);
netDataAll.udp6NetData.push_back(convertedNetData);
}
}
return netDataAll;
}
<|endoftext|> |
<commit_before>#include <vtkSmartPointer.h>
#include <vtkVRMLImporter.h>
#include <vtkActor.h>
#include <vtkActorCollection.h>
#include <vtkCamera.h>
#include <vtkMapper.h>
#include <vtkPointData.h>
#include <vtkPolyData.h>
#include <vtkPolyDataMapper.h>
#include <vtkPolyDataNormals.h>
#include <vtkProperty.h>
#include <vtkRenderWindow.h>
#include <vtkRenderWindowInteractor.h>
#include <vtkRenderer.h>
#include <vtkNamedColors.h>
int main ( int argc, char *argv[])
{
if(argc < 2)
{
std::cout << "Required arguments: Filename" << std::endl;
return EXIT_FAILURE;
}
std::string filename = argv[1];
std::cout << "Reading " << filename << std::endl;
vtkSmartPointer<vtkNamedColors> colors =
vtkSmartPointer<vtkNamedColors>::New();
vtkSmartPointer<vtkRenderer> renderer =
vtkSmartPointer<vtkRenderer>::New();
vtkSmartPointer<vtkRenderWindow> renderWindow =
vtkSmartPointer<vtkRenderWindow>::New();
renderWindow->AddRenderer(renderer);
vtkSmartPointer<vtkRenderWindowInteractor> renderWindowInteractor =
vtkSmartPointer<vtkRenderWindowInteractor>::New();
renderWindowInteractor->SetRenderWindow(renderWindow);
// VRML Import
vtkSmartPointer<vtkVRMLImporter> importer =
vtkSmartPointer<vtkVRMLImporter>::New();
importer->SetFileName ( filename.c_str() );
importer->SetRenderWindow(renderWindow);
importer->Update();
vtkSmartPointer<vtkActorCollection> actors =
vtkSmartPointer<vtkActorCollection>::New();
actors = renderer->GetActors();
std::cout << "There are " << actors->GetNumberOfItems() << " actors" << std::endl;
int m = 0;
actors->InitTraversal();
for (vtkIdType a = 0; a < actors->GetNumberOfItems(); ++a)
{
vtkActor * actor = actors->GetNextActor();
// The importer shininess parameter is between 0 and 1. VTK specular power is usually 10-100.
// Also, the default for the specular factor for VRML is 1, while VTK's is 0
double specularPower = actor->GetProperty()->GetSpecularPower();
actor->GetProperty()->SetSpecularPower(specularPower * 100.0);
actor->GetProperty()->SetSpecular(1.0);
// The VRML default ambient intensity is .2
double ambientIntensity = actor->GetProperty()->GetAmbient();
if (ambientIntensity == 0.0)
{
actor->GetProperty()->SetAmbient(.2);
}
vtkPolyDataMapper *mapper = vtkPolyDataMapper::SafeDownCast(actor->GetMapper());
vtkPolyData *dataSet = vtkPolyData::SafeDownCast(mapper->GetInput());
if (!dataSet->GetPointData()->GetNormals())
{
vtkSmartPointer<vtkPolyDataNormals> normals =
vtkSmartPointer<vtkPolyDataNormals>::New();
normals->SetInputData(dataSet);
normals->Update();
mapper->SetInputData(normals->GetOutput());
}
}
renderer->ResetCamera();
renderer->GetActiveCamera()->Azimuth(30);
renderer->GetActiveCamera()->Elevation(30);
renderer->GetActiveCamera()->Dolly(1.4);
renderer->ResetCameraClippingRange();
renderer->SetBackground(colors->GetColor3d("PaleGreen").GetData());
renderWindow->SetSize(640, 480);
renderWindow->Render();
renderWindowInteractor->Start();
return EXIT_SUCCESS;
}
<commit_msg>ENH: Better handling of specular power.<commit_after>#include <vtkSmartPointer.h>
#include <vtkVRMLImporter.h>
#include <vtkActor.h>
#include <vtkActorCollection.h>
#include <vtkCamera.h>
#include <vtkMapper.h>
#include <vtkPointData.h>
#include <vtkPolyData.h>
#include <vtkPolyDataMapper.h>
#include <vtkPolyDataNormals.h>
#include <vtkProperty.h>
#include <vtkRenderWindow.h>
#include <vtkRenderWindowInteractor.h>
#include <vtkRenderer.h>
#include <vtkNamedColors.h>
int main ( int argc, char *argv[])
{
if(argc < 2)
{
std::cout << "Required arguments: Filename" << std::endl;
return EXIT_FAILURE;
}
std::string filename = argv[1];
std::cout << "Reading " << filename << std::endl;
vtkSmartPointer<vtkNamedColors> colors =
vtkSmartPointer<vtkNamedColors>::New();
vtkSmartPointer<vtkRenderer> renderer =
vtkSmartPointer<vtkRenderer>::New();
vtkSmartPointer<vtkRenderWindow> renderWindow =
vtkSmartPointer<vtkRenderWindow>::New();
renderWindow->AddRenderer(renderer);
vtkSmartPointer<vtkRenderWindowInteractor> renderWindowInteractor =
vtkSmartPointer<vtkRenderWindowInteractor>::New();
renderWindowInteractor->SetRenderWindow(renderWindow);
// VRML Import
vtkSmartPointer<vtkVRMLImporter> importer =
vtkSmartPointer<vtkVRMLImporter>::New();
importer->SetFileName ( filename.c_str() );
importer->SetRenderWindow(renderWindow);
importer->Update();
vtkSmartPointer<vtkActorCollection> actors =
vtkSmartPointer<vtkActorCollection>::New();
actors = renderer->GetActors();
std::cout << "There are " << actors->GetNumberOfItems() << " actors" << std::endl;
int m = 0;
actors->InitTraversal();
for (vtkIdType a = 0; a < actors->GetNumberOfItems(); ++a)
{
vtkActor * actor = actors->GetNextActor();
// The importer shininess parameter is between 0 and 1. VTK specular power is usually 10-100.
// Also, the default for the specular factor for VRML is 1, while VTK's is 0
double specularPower = actor->GetProperty()->GetSpecularPower();
if (specularPower <= 1.0)
{
actor->GetProperty()->SetSpecularPower(specularPower * 128.0);
}
double specular = actor->GetProperty()->GetSpecular();
if (specular == 0.0)
{
actor->GetProperty()->SetSpecular(1.0);
}
// The VRML default ambient intensity is .2
double ambientIntensity = actor->GetProperty()->GetAmbient();
if (ambientIntensity == 0.0)
{
actor->GetProperty()->SetAmbient(.2);
}
vtkPolyDataMapper *mapper = vtkPolyDataMapper::SafeDownCast(actor->GetMapper());
vtkPolyData *dataSet = vtkPolyData::SafeDownCast(mapper->GetInput());
if (!dataSet->GetPointData()->GetNormals())
{
vtkSmartPointer<vtkPolyDataNormals> normals =
vtkSmartPointer<vtkPolyDataNormals>::New();
normals->SetInputData(dataSet);
normals->Update();
mapper->SetInputData(normals->GetOutput());
}
}
renderer->ResetCamera();
renderer->GetActiveCamera()->Azimuth(30);
renderer->GetActiveCamera()->Elevation(30);
renderer->GetActiveCamera()->Dolly(1.4);
renderer->ResetCameraClippingRange();
renderer->SetBackground(colors->GetColor3d("PaleGreen").GetData());
renderWindow->SetSize(640, 480);
renderWindow->Render();
renderWindowInteractor->Start();
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>// Copyright (C) 2003 CEA/DEN, EDF R&D
//
//
//
// File : VISU_DatConvertor.hxx
// Author : Alexey PETROV
// Module : VISU
#ifndef MED_Utilities_HeaderFile
#define MED_Utilities_HeaderFile
#include <iostream>
#include <sstream>
#include <string>
#include <stdexcept>
namespace UNV{
using namespace std;
class PrefixPrinter{
static int myCounter;
public:
PrefixPrinter();
~PrefixPrinter();
static string GetPrefix();
};
/**
* @returns \p false when error occured, \p true otherwise.
* Adjusts the \p in_stream to the beginning of the
* dataset \p ds_name.
*/
inline bool beginning_of_dataset(std::istream& in_file, const std::string& ds_name)
{
assert (in_file.good());
assert (!ds_name.empty());
std::string olds, news;
while(true){
in_file >> olds >> news;
/*
* a "-1" followed by a number means the beginning of a dataset
* stop combing at the end of the file
*/
while( ((olds != "-1") || (news == "-1") ) && !in_file.eof() ){
olds = news;
in_file >> news;
}
if(in_file.eof())
return false;
if (news == ds_name)
return true;
}
// should never end up here
return false;
}
/**
* Method for converting exponential notation
* from "D" to "e", for example
* \p 3.141592654D+00 \p --> \p 3.141592654e+00
* in order to make it readable for C++.
*/
inline double D_to_e(std::string& number)
{
/* find "D" in string, start looking at
* 6th element, to improve speed.
* We dont expect a "D" earlier
*/
const int position = number.find("D",6);
if(position != std::string::npos){
number.replace(position, 1, "e");
}
return atof (number.c_str());
}
};
#ifndef MESSAGE
#define MESSAGE(msg) std::cout<<__FILE__<<"["<<__LINE__<<"]::"<<msg<<endl;
#define BEGMSG(msg) std::cout<<UNV::PrefixPrinter::GetPrefix()<<msg
#define ADDMSG(msg) std::cout<<msg
#endif
#ifndef EXCEPTION
#define EXCEPTION(TYPE, MSG) {\
std::ostringstream aStream;\
aStream<<__FILE__<<"["<<__LINE__<<"]::"<<MSG;\
throw TYPE(aStream.str());\
}
#endif
#endif
<commit_msg>SMH: Fix from Paul<commit_after>// Copyright (C) 2003 CEA/DEN, EDF R&D
//
//
//
// File : VISU_DatConvertor.hxx
// Author : Alexey PETROV
// Module : VISU
#ifndef MED_Utilities_HeaderFile
#define MED_Utilities_HeaderFile
#include <iostream>
#include <sstream>
#include <string>
#include <stdexcept>
#include <cassert>
namespace UNV{
using namespace std;
class PrefixPrinter{
static int myCounter;
public:
PrefixPrinter();
~PrefixPrinter();
static string GetPrefix();
};
/**
* @returns \p false when error occured, \p true otherwise.
* Adjusts the \p in_stream to the beginning of the
* dataset \p ds_name.
*/
inline bool beginning_of_dataset(std::istream& in_file, const std::string& ds_name)
{
assert (in_file.good());
assert (!ds_name.empty());
std::string olds, news;
while(true){
in_file >> olds >> news;
/*
* a "-1" followed by a number means the beginning of a dataset
* stop combing at the end of the file
*/
while( ((olds != "-1") || (news == "-1") ) && !in_file.eof() ){
olds = news;
in_file >> news;
}
if(in_file.eof())
return false;
if (news == ds_name)
return true;
}
// should never end up here
return false;
}
/**
* Method for converting exponential notation
* from "D" to "e", for example
* \p 3.141592654D+00 \p --> \p 3.141592654e+00
* in order to make it readable for C++.
*/
inline double D_to_e(std::string& number)
{
/* find "D" in string, start looking at
* 6th element, to improve speed.
* We dont expect a "D" earlier
*/
const int position = number.find("D",6);
if(position != std::string::npos){
number.replace(position, 1, "e");
}
return atof (number.c_str());
}
};
#ifndef MESSAGE
#define MESSAGE(msg) std::cout<<__FILE__<<"["<<__LINE__<<"]::"<<msg<<endl;
#define BEGMSG(msg) std::cout<<UNV::PrefixPrinter::GetPrefix()<<msg
#define ADDMSG(msg) std::cout<<msg
#endif
#ifndef EXCEPTION
#define EXCEPTION(TYPE, MSG) {\
std::ostringstream aStream;\
aStream<<__FILE__<<"["<<__LINE__<<"]::"<<MSG;\
throw TYPE(aStream.str());\
}
#endif
#endif
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: vtkCellDataToPointData.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkCellDataToPointData.h"
#include "vtkCellData.h"
#include "vtkCell.h"
#include "vtkDataSet.h"
#include "vtkIdList.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkUnstructuredGrid.h"
#include "vtkSmartPointer.h"
#include "vtkUnsignedIntArray.h"
#include "vtkObjectFactory.h"
#include "vtkPointData.h"
#include <algorithm>
#include <functional>
vtkStandardNewMacro(vtkCellDataToPointData);
//----------------------------------------------------------------------------
// Instantiate object so that cell data is not passed to output.
vtkCellDataToPointData::vtkCellDataToPointData()
{
this->PassCellData = 0;
}
#define VTK_MAX_CELLS_PER_POINT 4096
//----------------------------------------------------------------------------
int vtkCellDataToPointData::RequestData(
vtkInformation*,
vtkInformationVector** inputVector,
vtkInformationVector* outputVector)
{
vtkInformation* info = outputVector->GetInformationObject(0);
vtkDataSet *output = vtkDataSet::SafeDownCast(
info->Get(vtkDataObject::DATA_OBJECT()));
vtkInformation* inInfo = inputVector[0]->GetInformationObject(0);
vtkDataSet *input = vtkDataSet::SafeDownCast(
inInfo->Get(vtkDataObject::DATA_OBJECT()));
vtkDebugMacro(<<"Mapping cell data to point data");
// Special traversal algorithm for unstructured grid
if (input->IsA("vtkUnstructuredGrid"))
{
return this->RequestDataForUnstructuredGrid(0, inputVector, outputVector);
}
vtkIdType cellId, ptId;
vtkIdType numCells, numPts;
vtkCellData *inPD=input->GetCellData();
vtkPointData *outPD=output->GetPointData();
vtkIdList *cellIds;
double weight;
double *weights;
vtkDebugMacro(<<"Mapping cell data to point data");
// First, copy the input to the output as a starting point
output->CopyStructure( input );
cellIds = vtkIdList::New();
cellIds->Allocate(VTK_MAX_CELLS_PER_POINT);
if ( (numPts=input->GetNumberOfPoints()) < 1 )
{
vtkDebugMacro(<<"No input point data!");
cellIds->Delete();
return 1;
}
weights = new double[VTK_MAX_CELLS_PER_POINT];
// Pass the point data first. The fields and attributes
// which also exist in the cell data of the input will
// be over-written during CopyAllocate
output->GetPointData()->CopyGlobalIdsOff();
output->GetPointData()->PassData(input->GetPointData());
output->GetPointData()->CopyFieldOff("vtkGhostLevels");
// notice that inPD and outPD are vtkCellData and vtkPointData; respectively.
// It's weird, but it works.
outPD->InterpolateAllocate(inPD,numPts);
int abort=0;
vtkIdType progressInterval=numPts/20 + 1;
for (ptId=0; ptId < numPts && !abort; ptId++)
{
if ( !(ptId % progressInterval) )
{
this->UpdateProgress(static_cast<double>(ptId)/numPts);
abort = GetAbortExecute();
}
input->GetPointCells(ptId, cellIds);
numCells = cellIds->GetNumberOfIds();
if ( numCells > 0 && numCells < VTK_MAX_CELLS_PER_POINT )
{
weight = 1.0 / numCells;
for (cellId=0; cellId < numCells; cellId++)
{
weights[cellId] = weight;
}
outPD->InterpolatePoint(inPD, ptId, cellIds, weights);
}
else
{
outPD->NullPoint(ptId);
}
}
if ( !this->PassCellData )
{
output->GetCellData()->CopyAllOff();
output->GetCellData()->CopyFieldOn("vtkGhostLevels");
}
output->GetCellData()->PassData(input->GetCellData());
cellIds->Delete();
delete [] weights;
return 1;
}
//----------------------------------------------------------------------------
void vtkCellDataToPointData::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
os << indent << "Pass Cell Data: " << (this->PassCellData ? "On\n" : "Off\n");
}
//----------------------------------------------------------------------------
// Helper template function that implement the major part of the algorighm
// which will be expanded by the vtkTemplateMacro. The template function is
// provided so that coverage test can cover this function.
namespace
{
template <typename T>
void __spread (vtkUnstructuredGrid* const src, vtkUnsignedIntArray* const num,
vtkDataArray* const srcarray, vtkDataArray* const dstarray,
vtkIdType ncells, vtkIdType npoints, vtkIdType ncomps)
{
T const* const srcptr = static_cast<T const*>(srcarray->GetVoidPointer(0));
T * const dstptr = static_cast<T *>(dstarray->GetVoidPointer(0));
// zero initialization
vtkstd::fill_n(dstptr, npoints*ncomps, T(0));
// accumulate
T const* srcbeg = srcptr;
for (vtkIdType cid = 0; cid < ncells; ++cid, srcbeg += ncomps)
{
vtkIdList* const pids = src->GetCell(cid)->GetPointIds();
for (vtkIdType i = 0, I = pids->GetNumberOfIds(); i < I; ++i)
{
T* const dstbeg = dstptr + pids->GetId(i)*ncomps;
// accumulate cell data to point data <==> point_data += cell_data
vtkstd::transform(srcbeg,srcbeg+ncomps,dstbeg,dstbeg,vtkstd::plus<T>());
}
}
// average
T* dstbeg = dstptr;
for (vtkIdType pid = 0; pid < npoints; ++pid, dstbeg += ncomps)
{
// guard against divide by zero
if (unsigned int const denum = num->GetValue(pid))
{
// divide point data by the number of cells using it <==>
// point_data /= denum
vtkstd::transform(dstbeg, dstbeg+ncomps, dstbeg,
vtkstd::bind2nd(vtkstd::divides<T>(), denum));
}
}
}
}
//----------------------------------------------------------------------------
int vtkCellDataToPointData::RequestDataForUnstructuredGrid
(vtkInformation*,
vtkInformationVector** inputVector,
vtkInformationVector* outputVector)
{
vtkUnstructuredGrid* const src = vtkUnstructuredGrid::SafeDownCast(
inputVector[0]->GetInformationObject(0)->Get(vtkDataObject::DATA_OBJECT()));
vtkUnstructuredGrid* const dst = vtkUnstructuredGrid::SafeDownCast(
outputVector->GetInformationObject(0)->Get(vtkDataObject::DATA_OBJECT()));
vtkIdType const ncells = src->GetNumberOfCells ();
vtkIdType const npoints = src->GetNumberOfPoints();
if (ncells < 1 || npoints < 1)
{
vtkDebugMacro(<<"No input data!");
return 1;
}
// count the number of cells associated with each point
vtkSmartPointer<vtkUnsignedIntArray> num
= vtkSmartPointer<vtkUnsignedIntArray>::New();
num->SetNumberOfComponents(1);
num->SetNumberOfTuples(npoints);
vtkstd::fill_n(num->GetPointer(0), npoints, 0u);
for (vtkIdType cid = 0; cid < ncells; ++cid)
{
vtkIdList* const pids = src->GetCell(cid)->GetPointIds();
for (vtkIdType i = 0, I = pids->GetNumberOfIds(); i < I; ++i)
{
vtkIdType const pid = pids->GetId(i);
num->SetValue(pid, num->GetValue(pid)+1);
}
}
// First, copy the input to the output as a starting point
dst->CopyStructure(src);
vtkPointData* const opd = dst->GetPointData();
// Pass the point data first. The fields and attributes
// which also exist in the cell data of the input will
// be over-written during CopyAllocate
opd->CopyGlobalIdsOff();
opd->PassData(src->GetPointData());
opd->CopyFieldOff("vtkGhostLevels");
// Copy all existing cell fields into a temporary cell data array
vtkSmartPointer<vtkCellData> clean = vtkSmartPointer<vtkCellData>::New();
clean->PassData(src->GetCellData());
// Remove all fields that are not a data array.
for (vtkIdType fid = clean->GetNumberOfArrays(); fid--;)
{
if (!clean->GetAbstractArray(fid)->IsA("vtkDataArray"))
{
clean->RemoveArray(fid);
}
}
// Cell field list constructed from the filtered cell data array
vtkDataSetAttributes::FieldList cfl(1);
cfl.InitializeFieldList(clean);
opd->InterpolateAllocate(cfl, npoints, npoints);
for (int fid = 0, nfields = cfl.GetNumberOfFields(); fid < nfields; ++fid)
{
// update progress and check for an abort request.
this->UpdateProgress((fid+1.)/nfields);
if (this->GetAbortExecute())
{
break;
}
// indices into the field arrays associated with the cell and the point
// respectively
int const srcid = cfl.GetFieldIndex(fid);
int const dstid = cfl.GetDSAIndex(0,fid);
if (srcid < 0 || dstid < 0)
{
continue;
}
vtkCellData * const srccelldata = src->GetCellData ();
vtkPointData* const dstpointdata = dst->GetPointData();
if (!srccelldata || !dstpointdata)
{
continue;
}
vtkDataArray* const srcarray = srccelldata ->GetArray(srcid);
vtkDataArray* const dstarray = dstpointdata->GetArray(dstid);
dstarray->SetNumberOfTuples(npoints);
vtkIdType const ncomps = srcarray->GetNumberOfComponents();
switch (srcarray->GetDataType())
{
vtkTemplateMacro
(__spread<VTK_TT>(src,num,srcarray,dstarray,ncells,npoints,ncomps));
}
}
if (!this->PassCellData)
{
dst->GetCellData()->CopyAllOff();
dst->GetCellData()->CopyFieldOn("vtkGhostLevels");
}
dst->GetCellData()->PassData(src->GetCellData());
return 1;
}
<commit_msg>Fixed BUG #11520. Fixes segfault for unstructured grids.<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: vtkCellDataToPointData.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkCellDataToPointData.h"
#include "vtkCellData.h"
#include "vtkCell.h"
#include "vtkDataSet.h"
#include "vtkIdList.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkUnstructuredGrid.h"
#include "vtkSmartPointer.h"
#include "vtkUnsignedIntArray.h"
#include "vtkObjectFactory.h"
#include "vtkPointData.h"
#include <algorithm>
#include <functional>
vtkStandardNewMacro(vtkCellDataToPointData);
//----------------------------------------------------------------------------
// Instantiate object so that cell data is not passed to output.
vtkCellDataToPointData::vtkCellDataToPointData()
{
this->PassCellData = 0;
}
#define VTK_MAX_CELLS_PER_POINT 4096
//----------------------------------------------------------------------------
int vtkCellDataToPointData::RequestData(
vtkInformation*,
vtkInformationVector** inputVector,
vtkInformationVector* outputVector)
{
vtkInformation* info = outputVector->GetInformationObject(0);
vtkDataSet *output = vtkDataSet::SafeDownCast(
info->Get(vtkDataObject::DATA_OBJECT()));
vtkInformation* inInfo = inputVector[0]->GetInformationObject(0);
vtkDataSet *input = vtkDataSet::SafeDownCast(
inInfo->Get(vtkDataObject::DATA_OBJECT()));
vtkDebugMacro(<<"Mapping cell data to point data");
// Special traversal algorithm for unstructured grid
if (input->IsA("vtkUnstructuredGrid"))
{
return this->RequestDataForUnstructuredGrid(0, inputVector, outputVector);
}
vtkIdType cellId, ptId;
vtkIdType numCells, numPts;
vtkCellData *inPD=input->GetCellData();
vtkPointData *outPD=output->GetPointData();
vtkIdList *cellIds;
double weight;
double *weights;
vtkDebugMacro(<<"Mapping cell data to point data");
// First, copy the input to the output as a starting point
output->CopyStructure( input );
cellIds = vtkIdList::New();
cellIds->Allocate(VTK_MAX_CELLS_PER_POINT);
if ( (numPts=input->GetNumberOfPoints()) < 1 )
{
vtkDebugMacro(<<"No input point data!");
cellIds->Delete();
return 1;
}
weights = new double[VTK_MAX_CELLS_PER_POINT];
// Pass the point data first. The fields and attributes
// which also exist in the cell data of the input will
// be over-written during CopyAllocate
output->GetPointData()->CopyGlobalIdsOff();
output->GetPointData()->PassData(input->GetPointData());
output->GetPointData()->CopyFieldOff("vtkGhostLevels");
// notice that inPD and outPD are vtkCellData and vtkPointData; respectively.
// It's weird, but it works.
outPD->InterpolateAllocate(inPD,numPts);
int abort=0;
vtkIdType progressInterval=numPts/20 + 1;
for (ptId=0; ptId < numPts && !abort; ptId++)
{
if ( !(ptId % progressInterval) )
{
this->UpdateProgress(static_cast<double>(ptId)/numPts);
abort = GetAbortExecute();
}
input->GetPointCells(ptId, cellIds);
numCells = cellIds->GetNumberOfIds();
if ( numCells > 0 && numCells < VTK_MAX_CELLS_PER_POINT )
{
weight = 1.0 / numCells;
for (cellId=0; cellId < numCells; cellId++)
{
weights[cellId] = weight;
}
outPD->InterpolatePoint(inPD, ptId, cellIds, weights);
}
else
{
outPD->NullPoint(ptId);
}
}
if ( !this->PassCellData )
{
output->GetCellData()->CopyAllOff();
output->GetCellData()->CopyFieldOn("vtkGhostLevels");
}
output->GetCellData()->PassData(input->GetCellData());
cellIds->Delete();
delete [] weights;
return 1;
}
//----------------------------------------------------------------------------
void vtkCellDataToPointData::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
os << indent << "Pass Cell Data: " << (this->PassCellData ? "On\n" : "Off\n");
}
//----------------------------------------------------------------------------
// Helper template function that implement the major part of the algorighm
// which will be expanded by the vtkTemplateMacro. The template function is
// provided so that coverage test can cover this function.
namespace
{
template <typename T>
void __spread (vtkUnstructuredGrid* const src, vtkUnsignedIntArray* const num,
vtkDataArray* const srcarray, vtkDataArray* const dstarray,
vtkIdType ncells, vtkIdType npoints, vtkIdType ncomps)
{
T const* const srcptr = static_cast<T const*>(srcarray->GetVoidPointer(0));
T * const dstptr = static_cast<T *>(dstarray->GetVoidPointer(0));
// zero initialization
vtkstd::fill_n(dstptr, npoints*ncomps, T(0));
// accumulate
T const* srcbeg = srcptr;
for (vtkIdType cid = 0; cid < ncells; ++cid, srcbeg += ncomps)
{
vtkIdList* const pids = src->GetCell(cid)->GetPointIds();
for (vtkIdType i = 0, I = pids->GetNumberOfIds(); i < I; ++i)
{
T* const dstbeg = dstptr + pids->GetId(i)*ncomps;
// accumulate cell data to point data <==> point_data += cell_data
vtkstd::transform(srcbeg,srcbeg+ncomps,dstbeg,dstbeg,vtkstd::plus<T>());
}
}
// average
T* dstbeg = dstptr;
for (vtkIdType pid = 0; pid < npoints; ++pid, dstbeg += ncomps)
{
// guard against divide by zero
if (unsigned int const denum = num->GetValue(pid))
{
// divide point data by the number of cells using it <==>
// point_data /= denum
vtkstd::transform(dstbeg, dstbeg+ncomps, dstbeg,
vtkstd::bind2nd(vtkstd::divides<T>(), denum));
}
}
}
}
//----------------------------------------------------------------------------
int vtkCellDataToPointData::RequestDataForUnstructuredGrid
(vtkInformation*,
vtkInformationVector** inputVector,
vtkInformationVector* outputVector)
{
vtkUnstructuredGrid* const src = vtkUnstructuredGrid::SafeDownCast(
inputVector[0]->GetInformationObject(0)->Get(vtkDataObject::DATA_OBJECT()));
vtkUnstructuredGrid* const dst = vtkUnstructuredGrid::SafeDownCast(
outputVector->GetInformationObject(0)->Get(vtkDataObject::DATA_OBJECT()));
vtkIdType const ncells = src->GetNumberOfCells ();
vtkIdType const npoints = src->GetNumberOfPoints();
if (ncells < 1 || npoints < 1)
{
vtkDebugMacro(<<"No input data!");
return 1;
}
// count the number of cells associated with each point
vtkSmartPointer<vtkUnsignedIntArray> num
= vtkSmartPointer<vtkUnsignedIntArray>::New();
num->SetNumberOfComponents(1);
num->SetNumberOfTuples(npoints);
vtkstd::fill_n(num->GetPointer(0), npoints, 0u);
for (vtkIdType cid = 0; cid < ncells; ++cid)
{
vtkIdList* const pids = src->GetCell(cid)->GetPointIds();
for (vtkIdType i = 0, I = pids->GetNumberOfIds(); i < I; ++i)
{
vtkIdType const pid = pids->GetId(i);
num->SetValue(pid, num->GetValue(pid)+1);
}
}
// First, copy the input to the output as a starting point
dst->CopyStructure(src);
vtkPointData* const opd = dst->GetPointData();
// Pass the point data first. The fields and attributes
// which also exist in the cell data of the input will
// be over-written during CopyAllocate
opd->CopyGlobalIdsOff();
opd->PassData(src->GetPointData());
opd->CopyFieldOff("vtkGhostLevels");
// Copy all existing cell fields into a temporary cell data array
vtkSmartPointer<vtkCellData> clean = vtkSmartPointer<vtkCellData>::New();
clean->PassData(src->GetCellData());
// Remove all fields that are not a data array.
for (vtkIdType fid = clean->GetNumberOfArrays(); fid--;)
{
if (!clean->GetAbstractArray(fid)->IsA("vtkDataArray"))
{
clean->RemoveArray(fid);
}
}
// Cell field list constructed from the filtered cell data array
vtkDataSetAttributes::FieldList cfl(1);
cfl.InitializeFieldList(clean);
opd->InterpolateAllocate(cfl, npoints, npoints);
for (int fid = 0, nfields = cfl.GetNumberOfFields(); fid < nfields; ++fid)
{
// update progress and check for an abort request.
this->UpdateProgress((fid+1.)/nfields);
if (this->GetAbortExecute())
{
break;
}
// indices into the field arrays associated with the cell and the point
// respectively
int const dstid = cfl.GetFieldIndex(fid);
int const srcid = cfl.GetDSAIndex(0,fid);
if (srcid < 0 || dstid < 0)
{
continue;
}
vtkCellData * const srccelldata = clean;
vtkPointData* const dstpointdata = dst->GetPointData();
if (!srccelldata || !dstpointdata)
{
continue;
}
vtkDataArray* const srcarray = srccelldata ->GetArray(srcid);
vtkDataArray* const dstarray = dstpointdata->GetArray(dstid);
dstarray->SetNumberOfTuples(npoints);
vtkIdType const ncomps = srcarray->GetNumberOfComponents();
switch (srcarray->GetDataType())
{
vtkTemplateMacro
(__spread<VTK_TT>(src,num,srcarray,dstarray,ncells,npoints,ncomps));
}
}
if (!this->PassCellData)
{
dst->GetCellData()->CopyAllOff();
dst->GetCellData()->CopyFieldOn("vtkGhostLevels");
}
dst->GetCellData()->PassData(src->GetCellData());
return 1;
}
<|endoftext|> |
<commit_before>/***************************************************************************
* Copyright (c) 2009 Werner Mayer <wmayer[at]users.sourceforge.net> *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* 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; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
int createSWIGPointerObj_T(const char* TypeName, void* obj, PyObject** ptr, int own)
{
swig_module_info *module = SWIG_GetModule(NULL);
if (!module)
return 1;
swig_type_info * swig_type = 0;
swig_type = SWIG_TypeQuery(TypeName);
if (!swig_type)
throw Base::RuntimeError("Cannot find type information for requested type");
*ptr = SWIG_NewPointerObj(obj,swig_type,own);
if (*ptr == 0)
throw Base::RuntimeError("Cannot convert into requested type");
// success
return 0;
}
int convertSWIGPointerObj_T(const char* TypeName, PyObject* obj, void** ptr, int flags)
{
swig_module_info *module = SWIG_GetModule(NULL);
if (!module)
return 1;
swig_type_info * swig_type = 0;
swig_type = SWIG_TypeQuery(TypeName);
if (!swig_type)
throw Base::RuntimeError("Cannot find type information for requested type");
// return value of 0 is on success
if (SWIG_ConvertPtr(obj, ptr, swig_type, flags))
throw Base::RuntimeError("Cannot convert into requested type");
// success
return 0;
}
void cleanupSWIG_T(const char* TypeName)
{
swig_module_info *swig_module = SWIG_GetModule(NULL);
if (!swig_module)
return;
swig_type_info * swig_type = 0;
swig_type = SWIG_TypeQuery(TypeName);
if (!swig_type)
return;
PyObject *module, *dict;
PyInterpreterState *interp = PyThreadState_GET()->interp;
PyObject *modules = interp->modules;
module = PyDict_GetItemString(modules, "__builtin__");
if (module != NULL && PyModule_Check(module)) {
dict = PyModule_GetDict(module);
PyDict_SetItemString(dict, "_", Py_None);
}
module = PyDict_GetItemString(modules, "__main__");
if (module != NULL && PyModule_Check(module)) {
PyObject* dict = PyModule_GetDict(module);
if (!dict) return;
Py_ssize_t pos;
PyObject *key, *value;
pos = 0;
while (PyDict_Next(dict, &pos, &key, &value)) {
#if PY_MAJOR_VERSION >= 3
if (value != Py_None && PyUnicode_Check(key)) {
#else
if (value != Py_None && PyString_Check(key)) {
#endif
void* ptr = 0;
if (SWIG_ConvertPtr(value, &ptr, 0, 0) == 0)
PyDict_SetItem(dict, key, Py_None);
}
}
}
// Run garbage collector
PyGC_Collect();
}
<commit_msg>Update swigpyrun.in for Python 3.8<commit_after>/***************************************************************************
* Copyright (c) 2009 Werner Mayer <wmayer[at]users.sourceforge.net> *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* 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; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
int createSWIGPointerObj_T(const char* TypeName, void* obj, PyObject** ptr, int own)
{
swig_module_info *module = SWIG_GetModule(NULL);
if (!module)
return 1;
swig_type_info * swig_type = 0;
swig_type = SWIG_TypeQuery(TypeName);
if (!swig_type)
throw Base::RuntimeError("Cannot find type information for requested type");
*ptr = SWIG_NewPointerObj(obj,swig_type,own);
if (*ptr == 0)
throw Base::RuntimeError("Cannot convert into requested type");
// success
return 0;
}
int convertSWIGPointerObj_T(const char* TypeName, PyObject* obj, void** ptr, int flags)
{
swig_module_info *module = SWIG_GetModule(NULL);
if (!module)
return 1;
swig_type_info * swig_type = 0;
swig_type = SWIG_TypeQuery(TypeName);
if (!swig_type)
throw Base::RuntimeError("Cannot find type information for requested type");
// return value of 0 is on success
if (SWIG_ConvertPtr(obj, ptr, swig_type, flags))
throw Base::RuntimeError("Cannot convert into requested type");
// success
return 0;
}
void cleanupSWIG_T(const char* TypeName)
{
swig_module_info *swig_module = SWIG_GetModule(NULL);
if (!swig_module)
return;
swig_type_info * swig_type = 0;
swig_type = SWIG_TypeQuery(TypeName);
if (!swig_type)
return;
PyObject *module, *dict;
PyInterpreterState *interp = PyThreadState_GET()->interp;
PyObject *modules = PyImport_GetModuleDict();
module = PyDict_GetItemString(modules, "__builtin__");
if (module != NULL && PyModule_Check(module)) {
dict = PyModule_GetDict(module);
PyDict_SetItemString(dict, "_", Py_None);
}
module = PyDict_GetItemString(modules, "__main__");
if (module != NULL && PyModule_Check(module)) {
PyObject* dict = PyModule_GetDict(module);
if (!dict) return;
Py_ssize_t pos;
PyObject *key, *value;
pos = 0;
while (PyDict_Next(dict, &pos, &key, &value)) {
#if PY_MAJOR_VERSION >= 3
if (value != Py_None && PyUnicode_Check(key)) {
#else
if (value != Py_None && PyString_Check(key)) {
#endif
void* ptr = 0;
if (SWIG_ConvertPtr(value, &ptr, 0, 0) == 0)
PyDict_SetItem(dict, key, Py_None);
}
}
}
// Run garbage collector
PyGC_Collect();
}
<|endoftext|> |
<commit_before>#include "CAM_Module.h"
#include "CAM_DataModel.h"
#include "CAM_Application.h"
#include "CAM_Study.h"
#include <QtxAction.h>
#include <QtxActionMenuMgr.h>
#include <QtxActionToolMgr.h>
static const char* ModuleIcon[] = {
"20 20 2 1",
" c None",
". c #000000",
" ",
" ",
" ",
" .................. ",
" . . ",
" . . ",
" . . ",
" . . ",
" . . ",
" . . ",
" . . ",
" . . ",
" .................. ",
" . . . ",
" . . . ",
" ... ... ... ",
" .. .. .. .. .. .. ",
" . . . . . . ",
" .. .. .. .. .. .. ",
" ... ... ... "};
QPixmap MYPixmap( ModuleIcon );
/*!Constructor.*/
CAM_Module::CAM_Module()
: QObject(),
myApp( 0 ),
myIcon( MYPixmap ),
myDataModel( 0 )
{
}
/*!Constructor. initialize \a name.*/
CAM_Module::CAM_Module( const QString& name )
: QObject(),
myApp( 0 ),
myName( name ),
myIcon( MYPixmap ),
myDataModel( 0 )
{
}
/*!Destructor. Remove data model.*/
CAM_Module::~CAM_Module()
{
delete myDataModel;
myDataModel = 0;
}
/*!Initialize application.*/
void CAM_Module::initialize( CAM_Application* app )
{
myApp = app;
}
/*!\retval Module icon.*/
QPixmap CAM_Module::moduleIcon() const
{
return myIcon;
}
/*!\retval Module name.*/
QString CAM_Module::moduleName() const
{
return myName;
}
/*! \brief Return data model.
* Create data model, if it was't created before.
*/
CAM_DataModel* CAM_Module::dataModel() const
{
if ( !myDataModel )
{
CAM_Module* that = (CAM_Module*)this;
that->myDataModel = that->createDataModel();
that->myDataModel->initialize();
}
return myDataModel;
}
/*!\retval CAM_Application pointer - application.*/
CAM_Application* CAM_Module::application() const
{
return myApp;
}
/*!Public slot
* \retval true.
*/
bool CAM_Module::activateModule( SUIT_Study* study )
{
return true;
}
/*!Public slot
* \retval true.
*/
bool CAM_Module::deactivateModule( SUIT_Study* )
{
return true;
}
/*!Public slot, remove data model from \a study.*/
void CAM_Module::studyClosed( SUIT_Study* study )
{
CAM_Study* camDoc = dynamic_cast<CAM_Study*>( study );
if ( !camDoc )
return;
if ( camDoc->containsDataModel( dataModel() ) )
camDoc->removeDataModel( dataModel() );
}
/*!Public slot, do nothing.*/
void CAM_Module::studyChanged( SUIT_Study* , SUIT_Study* )
{
}
/*!Create and return new instance of CAM_DataModel.*/
CAM_DataModel* CAM_Module::createDataModel()
{
return new CAM_DataModel( this );
}
/*!Sets module name to \a name.
* \param name - new name for module.
*/
void CAM_Module::setModuleName( const QString& name )
{
myName = name;
}
/*!Sets module icon to \a icon.
* \param icon - new icon for module.
*/
void CAM_Module::setModuleIcon( const QPixmap& icon )
{
myIcon = icon;
}
/*! Return menu manager pointer.
* \retval QtxActionMenuMgr pointer - menu manager.
*/
QtxActionMenuMgr* CAM_Module::menuMgr() const
{
QtxActionMenuMgr* mgr = 0;
if ( application() && application()->desktop() )
mgr = application()->desktop()->menuMgr();
return mgr;
}
/*! Return tool manager pointer.
* \retval QtxActionToolMgr pointer - tool manager.
*/
QtxActionToolMgr* CAM_Module::toolMgr() const
{
QtxActionToolMgr* mgr = 0;
if ( application() && application()->desktop() )
mgr = application()->desktop()->toolMgr();
return mgr;
}
/*! Create tool bar with name \a name, if it was't created before.
* \retval -1 - if tool manager was't be created.
*/
int CAM_Module::createTool( const QString& name )
{
if ( !toolMgr() )
return -1;
return toolMgr()->createToolBar( name );
}
int CAM_Module::createTool( QAction* a, const int tBar, const int id, const int idx )
{
if ( !toolMgr() )
return -1;
int regId = registerAction( id, a );
int intId = toolMgr()->insert( a, tBar, idx );
return intId != -1 ? regId : -1;
}
int CAM_Module::createTool( QAction* a, const QString& tBar, const int id, const int idx )
{
if ( !toolMgr() )
return -1;
int regId = registerAction( id, a );
int intId = toolMgr()->insert( a, tBar, idx );
return intId != -1 ? regId : -1;
}
int CAM_Module::createTool( const int id, const int tBar, const int idx )
{
if ( !toolMgr() )
return -1;
int intId = toolMgr()->insert( action( id ), tBar, idx );
return intId != -1 ? id : -1;
}
int CAM_Module::createTool( const int id, const QString& tBar, const int idx )
{
if ( !toolMgr() )
return -1;
int intId = toolMgr()->insert( action( id ), tBar, idx );
return intId != -1 ? id : -1;
}
int CAM_Module::createMenu( const QString& subMenu, const int menu,
const int id, const int group, const int index )
{
if ( !menuMgr() )
return -1;
return menuMgr()->insert( subMenu, menu, group, index );
}
int CAM_Module::createMenu( const QString& subMenu, const QString& menu,
const int id, const int group, const int index )
{
if ( !menuMgr() )
return -1;
return menuMgr()->insert( subMenu, menu, group, index );
}
int CAM_Module::createMenu( QAction* a, const int menu, const int id, const int group, const int index )
{
if ( !a || !menuMgr() )
return -1;
int regId = registerAction( id, a );
int intId = menuMgr()->insert( a, menu, group, index );
return intId != -1 ? regId : -1;
}
int CAM_Module::createMenu( QAction* a, const QString& menu, const int id, const int group, const int index )
{
if ( !a || !menuMgr() )
return -1;
int regId = registerAction( id, a );
int intId = menuMgr()->insert( a, menu, group, index );
return intId != -1 ? regId : -1;
}
int CAM_Module::createMenu( const int id, const int menu, const int group, const int index )
{
if ( !menuMgr() )
return -1;
int intId = menuMgr()->insert( action( id ), menu, group, index );
return intId != -1 ? id : -1;
}
int CAM_Module::createMenu( const int id, const QString& menu, const int group, const int index )
{
if ( !menuMgr() )
return -1;
int intId = menuMgr()->insert( action( id ), menu, group, index );
return intId != -1 ? id : -1;
}
/*!Sets menus shown to \a on floag.
*\param on - flag.
*/
void CAM_Module::setMenuShown( const bool on )
{
QtxActionMenuMgr* mMgr = menuMgr();
if ( !mMgr )
return;
bool upd = mMgr->isUpdatesEnabled();
mMgr->setUpdatesEnabled( false );
QAction* sep = separator();
for ( QMap<int, QAction*>::Iterator it = myActionMap.begin(); it != myActionMap.end(); ++it )
{
if ( it.data() != sep )
mMgr->setShown( mMgr->actionId( it.data() ), on );
}
mMgr->setUpdatesEnabled( upd );
if ( upd )
mMgr->update();
}
/*!Sets menu shown for QAction \a a to \a on flag.
* \param a - QAction
* \param on - flag
*/
void CAM_Module::setMenuShown( QAction* a, const bool on )
{
if ( menuMgr() )
menuMgr()->setShown( menuMgr()->actionId( a ), on );
}
/*!Sets menu shown for action with id=\a id to \a on flag.
* \param id - id of action
* \param on - flag
*/
void CAM_Module::setMenuShown( const int id, const bool on )
{
setMenuShown( action( id ), on );
}
/*!Set tools shown to \a on flag.
*\param on - boolean flag.
*/
void CAM_Module::setToolShown( const bool on )
{
QtxActionToolMgr* tMgr = toolMgr();
if ( !tMgr )
return;
bool upd = tMgr->isUpdatesEnabled();
tMgr->setUpdatesEnabled( false );
QAction* sep = separator();
for ( QMap<int, QAction*>::Iterator it = myActionMap.begin(); it != myActionMap.end(); ++it )
{
if ( it.data() != sep )
tMgr->setShown( tMgr->actionId( it.data() ), on );
}
tMgr->setUpdatesEnabled( upd );
if ( upd )
tMgr->update();
}
/*!Set tools shown for QAction \a a to \a on flag.
* \param a - QAction
* \param on - boolean flag
*/
void CAM_Module::setToolShown( QAction* a, const bool on )
{
if ( toolMgr() )
toolMgr()->setShown( toolMgr()->actionId( a ), on );
}
/*!Set tools shown for action with id=\a id to \a on flag.
* \param id - integer action id
* \param on - boolean flag
*/
void CAM_Module::setToolShown( const int id, const bool on )
{
setToolShown( action( id ), on );
}
/*! Return action by id.
* \param id - id of action.
* \retval QAction.
*/
QAction* CAM_Module::action( const int id ) const
{
QAction* a = 0;
if ( myActionMap.contains( id ) )
a = myActionMap[id];
return a;
}
/*! Return id by action.
* \param a - QAction.
* \retval id of action.
*/
int CAM_Module::actionId( const QAction* a ) const
{
int id = -1;
for ( QMap<int, QAction*>::ConstIterator it = myActionMap.begin(); it != myActionMap.end() && id == -1; ++it )
{
if ( it.data() == a )
id = it.key();
}
return id;
}
/*! Create new instance of QtxAction and register action with \a id.
* \param id - id for new action.
* \param text - parameter for creation QtxAction
* \param icon - parameter for creation QtxAction
* \param menu - parameter for creation QtxAction
* \param tip - tip status for QtxAction action.
* \param key - parameter for creation QtxAction
* \param parent - parent for action
* \param toggle - parameter for creation QtxAction
* \param reciever -
* \param member -
*/
QAction* CAM_Module::createAction( const int id, const QString& text, const QIconSet& icon,
const QString& menu, const QString& tip, const int key,
QObject* parent, const bool toggle, QObject* reciever, const char* member )
{
QtxAction* a = new QtxAction( text, icon, menu, key, parent, 0, toggle );
a->setStatusTip( tip );
if ( reciever && member )
connect( a, SIGNAL( activated() ), reciever, member );
registerAction( id, a );
return a;
}
/*! Register action in action map.
* \param id - id for action.
* \param a - action
* \retval new id for action.
*/
int CAM_Module::registerAction( const int id, QAction* a )
{
int ident = -1;
for ( QMap<int, QAction*>::ConstIterator it = myActionMap.begin(); it != myActionMap.end() && ident == -1; ++it )
if ( it.data() == a )
ident = it.key();
if ( ident != -1 )
return ident;
static int generatedId = -1;
ident = id < 0 ? --generatedId : id;
myActionMap.insert( id, a );
if ( menuMgr() )
menuMgr()->registerAction( a );
if ( toolMgr() )
toolMgr()->registerAction( a );
return ident;
}
/*! Return qt action manager separator.*/
QAction* CAM_Module::separator()
{
return QtxActionMgr::separator();
}
<commit_msg>Fix a bug of menu management (action is registered incorrectly if -1 (default) id is used)<commit_after>#include "CAM_Module.h"
#include "CAM_DataModel.h"
#include "CAM_Application.h"
#include "CAM_Study.h"
#include <QtxAction.h>
#include <QtxActionMenuMgr.h>
#include <QtxActionToolMgr.h>
static const char* ModuleIcon[] = {
"20 20 2 1",
" c None",
". c #000000",
" ",
" ",
" ",
" .................. ",
" . . ",
" . . ",
" . . ",
" . . ",
" . . ",
" . . ",
" . . ",
" . . ",
" .................. ",
" . . . ",
" . . . ",
" ... ... ... ",
" .. .. .. .. .. .. ",
" . . . . . . ",
" .. .. .. .. .. .. ",
" ... ... ... "};
QPixmap MYPixmap( ModuleIcon );
/*!Constructor.*/
CAM_Module::CAM_Module()
: QObject(),
myApp( 0 ),
myIcon( MYPixmap ),
myDataModel( 0 )
{
}
/*!Constructor. initialize \a name.*/
CAM_Module::CAM_Module( const QString& name )
: QObject(),
myApp( 0 ),
myName( name ),
myIcon( MYPixmap ),
myDataModel( 0 )
{
}
/*!Destructor. Remove data model.*/
CAM_Module::~CAM_Module()
{
delete myDataModel;
myDataModel = 0;
}
/*!Initialize application.*/
void CAM_Module::initialize( CAM_Application* app )
{
myApp = app;
}
/*!\retval Module icon.*/
QPixmap CAM_Module::moduleIcon() const
{
return myIcon;
}
/*!\retval Module name.*/
QString CAM_Module::moduleName() const
{
return myName;
}
/*! \brief Return data model.
* Create data model, if it was't created before.
*/
CAM_DataModel* CAM_Module::dataModel() const
{
if ( !myDataModel )
{
CAM_Module* that = (CAM_Module*)this;
that->myDataModel = that->createDataModel();
that->myDataModel->initialize();
}
return myDataModel;
}
/*!\retval CAM_Application pointer - application.*/
CAM_Application* CAM_Module::application() const
{
return myApp;
}
/*!Public slot
* \retval true.
*/
bool CAM_Module::activateModule( SUIT_Study* study )
{
return true;
}
/*!Public slot
* \retval true.
*/
bool CAM_Module::deactivateModule( SUIT_Study* )
{
return true;
}
/*!Public slot, remove data model from \a study.*/
void CAM_Module::studyClosed( SUIT_Study* study )
{
CAM_Study* camDoc = dynamic_cast<CAM_Study*>( study );
if ( !camDoc )
return;
if ( camDoc->containsDataModel( dataModel() ) )
camDoc->removeDataModel( dataModel() );
}
/*!Public slot, do nothing.*/
void CAM_Module::studyChanged( SUIT_Study* , SUIT_Study* )
{
}
/*!Create and return new instance of CAM_DataModel.*/
CAM_DataModel* CAM_Module::createDataModel()
{
return new CAM_DataModel( this );
}
/*!Sets module name to \a name.
* \param name - new name for module.
*/
void CAM_Module::setModuleName( const QString& name )
{
myName = name;
}
/*!Sets module icon to \a icon.
* \param icon - new icon for module.
*/
void CAM_Module::setModuleIcon( const QPixmap& icon )
{
myIcon = icon;
}
/*! Return menu manager pointer.
* \retval QtxActionMenuMgr pointer - menu manager.
*/
QtxActionMenuMgr* CAM_Module::menuMgr() const
{
QtxActionMenuMgr* mgr = 0;
if ( application() && application()->desktop() )
mgr = application()->desktop()->menuMgr();
return mgr;
}
/*! Return tool manager pointer.
* \retval QtxActionToolMgr pointer - tool manager.
*/
QtxActionToolMgr* CAM_Module::toolMgr() const
{
QtxActionToolMgr* mgr = 0;
if ( application() && application()->desktop() )
mgr = application()->desktop()->toolMgr();
return mgr;
}
/*! Create tool bar with name \a name, if it was't created before.
* \retval -1 - if tool manager was't be created.
*/
int CAM_Module::createTool( const QString& name )
{
if ( !toolMgr() )
return -1;
return toolMgr()->createToolBar( name );
}
int CAM_Module::createTool( QAction* a, const int tBar, const int id, const int idx )
{
if ( !toolMgr() )
return -1;
int regId = registerAction( id, a );
int intId = toolMgr()->insert( a, tBar, idx );
return intId != -1 ? regId : -1;
}
int CAM_Module::createTool( QAction* a, const QString& tBar, const int id, const int idx )
{
if ( !toolMgr() )
return -1;
int regId = registerAction( id, a );
int intId = toolMgr()->insert( a, tBar, idx );
return intId != -1 ? regId : -1;
}
int CAM_Module::createTool( const int id, const int tBar, const int idx )
{
if ( !toolMgr() )
return -1;
int intId = toolMgr()->insert( action( id ), tBar, idx );
return intId != -1 ? id : -1;
}
int CAM_Module::createTool( const int id, const QString& tBar, const int idx )
{
if ( !toolMgr() )
return -1;
int intId = toolMgr()->insert( action( id ), tBar, idx );
return intId != -1 ? id : -1;
}
int CAM_Module::createMenu( const QString& subMenu, const int menu,
const int id, const int group, const int index )
{
if ( !menuMgr() )
return -1;
return menuMgr()->insert( subMenu, menu, group, index );
}
int CAM_Module::createMenu( const QString& subMenu, const QString& menu,
const int id, const int group, const int index )
{
if ( !menuMgr() )
return -1;
return menuMgr()->insert( subMenu, menu, group, index );
}
int CAM_Module::createMenu( QAction* a, const int menu, const int id, const int group, const int index )
{
if ( !a || !menuMgr() )
return -1;
int regId = registerAction( id, a );
int intId = menuMgr()->insert( a, menu, group, index );
return intId != -1 ? regId : -1;
}
int CAM_Module::createMenu( QAction* a, const QString& menu, const int id, const int group, const int index )
{
if ( !a || !menuMgr() )
return -1;
int regId = registerAction( id, a );
int intId = menuMgr()->insert( a, menu, group, index );
return intId != -1 ? regId : -1;
}
int CAM_Module::createMenu( const int id, const int menu, const int group, const int index )
{
if ( !menuMgr() )
return -1;
int intId = menuMgr()->insert( action( id ), menu, group, index );
return intId != -1 ? id : -1;
}
int CAM_Module::createMenu( const int id, const QString& menu, const int group, const int index )
{
if ( !menuMgr() )
return -1;
int intId = menuMgr()->insert( action( id ), menu, group, index );
return intId != -1 ? id : -1;
}
/*!Sets menus shown to \a on floag.
*\param on - flag.
*/
void CAM_Module::setMenuShown( const bool on )
{
QtxActionMenuMgr* mMgr = menuMgr();
if ( !mMgr )
return;
bool upd = mMgr->isUpdatesEnabled();
mMgr->setUpdatesEnabled( false );
QAction* sep = separator();
for ( QMap<int, QAction*>::Iterator it = myActionMap.begin(); it != myActionMap.end(); ++it )
{
if ( it.data() != sep )
mMgr->setShown( mMgr->actionId( it.data() ), on );
}
mMgr->setUpdatesEnabled( upd );
if ( upd )
mMgr->update();
}
/*!Sets menu shown for QAction \a a to \a on flag.
* \param a - QAction
* \param on - flag
*/
void CAM_Module::setMenuShown( QAction* a, const bool on )
{
if ( menuMgr() )
menuMgr()->setShown( menuMgr()->actionId( a ), on );
}
/*!Sets menu shown for action with id=\a id to \a on flag.
* \param id - id of action
* \param on - flag
*/
void CAM_Module::setMenuShown( const int id, const bool on )
{
setMenuShown( action( id ), on );
}
/*!Set tools shown to \a on flag.
*\param on - boolean flag.
*/
void CAM_Module::setToolShown( const bool on )
{
QtxActionToolMgr* tMgr = toolMgr();
if ( !tMgr )
return;
bool upd = tMgr->isUpdatesEnabled();
tMgr->setUpdatesEnabled( false );
QAction* sep = separator();
for ( QMap<int, QAction*>::Iterator it = myActionMap.begin(); it != myActionMap.end(); ++it )
{
if ( it.data() != sep )
tMgr->setShown( tMgr->actionId( it.data() ), on );
}
tMgr->setUpdatesEnabled( upd );
if ( upd )
tMgr->update();
}
/*!Set tools shown for QAction \a a to \a on flag.
* \param a - QAction
* \param on - boolean flag
*/
void CAM_Module::setToolShown( QAction* a, const bool on )
{
if ( toolMgr() )
toolMgr()->setShown( toolMgr()->actionId( a ), on );
}
/*!Set tools shown for action with id=\a id to \a on flag.
* \param id - integer action id
* \param on - boolean flag
*/
void CAM_Module::setToolShown( const int id, const bool on )
{
setToolShown( action( id ), on );
}
/*! Return action by id.
* \param id - id of action.
* \retval QAction.
*/
QAction* CAM_Module::action( const int id ) const
{
QAction* a = 0;
if ( myActionMap.contains( id ) )
a = myActionMap[id];
return a;
}
/*! Return id by action.
* \param a - QAction.
* \retval id of action.
*/
int CAM_Module::actionId( const QAction* a ) const
{
int id = -1;
for ( QMap<int, QAction*>::ConstIterator it = myActionMap.begin(); it != myActionMap.end() && id == -1; ++it )
{
if ( it.data() == a )
id = it.key();
}
return id;
}
/*! Create new instance of QtxAction and register action with \a id.
* \param id - id for new action.
* \param text - parameter for creation QtxAction
* \param icon - parameter for creation QtxAction
* \param menu - parameter for creation QtxAction
* \param tip - tip status for QtxAction action.
* \param key - parameter for creation QtxAction
* \param parent - parent for action
* \param toggle - parameter for creation QtxAction
* \param reciever -
* \param member -
*/
QAction* CAM_Module::createAction( const int id, const QString& text, const QIconSet& icon,
const QString& menu, const QString& tip, const int key,
QObject* parent, const bool toggle, QObject* reciever, const char* member )
{
QtxAction* a = new QtxAction( text, icon, menu, key, parent, 0, toggle );
a->setStatusTip( tip );
if ( reciever && member )
connect( a, SIGNAL( activated() ), reciever, member );
registerAction( id, a );
return a;
}
/*! Register action in action map.
* \param id - id for action.
* \param a - action
* \retval new id for action.
*/
int CAM_Module::registerAction( const int id, QAction* a )
{
int ident = -1;
for ( QMap<int, QAction*>::ConstIterator it = myActionMap.begin(); it != myActionMap.end() && ident == -1; ++it )
if ( it.data() == a )
ident = it.key();
if ( ident != -1 )
return ident;
static int generatedId = -1;
ident = id < 0 ? --generatedId : id;
myActionMap.insert( ident, a );
if ( menuMgr() )
menuMgr()->registerAction( a );
if ( toolMgr() )
toolMgr()->registerAction( a );
return ident;
}
/*! Return qt action manager separator.*/
QAction* CAM_Module::separator()
{
return QtxActionMgr::separator();
}
<|endoftext|> |
<commit_before>//
// Instruction.hpp
// Clock Signal
//
// Created by Thomas Harte on 1/15/21.
// Copyright © 2021 Thomas Harte. All rights reserved.
//
#ifndef InstructionSets_x86_Instruction_h
#define InstructionSets_x86_Instruction_h
#include <cstdint>
namespace CPU {
namespace Decoder {
namespace x86 {
/*
Operations are documented below to establish expectations as to which
instruction fields will be meaningful for each; this is a work-in-progress
and may currently contain errors in the opcode descriptions — especially
where implicit register dependencies are afoot.
*/
enum class Operation: uint8_t {
Invalid,
/// ASCII adjust after addition; source will be AL and destination will be AX.
AAA,
/// ASCII adjust before division; destination will be AX and source will be a multiplier.
AAD,
/// ASCII adjust after multiplication; destination will be AX and source will be a divider.
AAM,
/// ASCII adjust after subtraction; source will be AL and destination will be AX.
AAS,
/// Convert byte into word; source will be AL, destination will be AH.
CBW,
/// Complement carry flag; no source or destination provided.
CMC,
/// Compare; source, destination, operand and displacement will be populated appropriately.
CMP,
/// Compare [bytes or words, per operation size]; source and destination implied to be DS:[SI] and ES:[DI].
CMPS,
/// Convert word to double word; source will be AX and destination will be DX.
CWD,
/// Decimal adjust after addition; source and destination will be AL.
DAA,
/// Decimal adjust after subtraction; source and destination will be AL.
DAS,
/// Decrement; source, destination, operand and displacement will be populated appropriately.
DEC,
/// Increment; source, destination, operand and displacement will be populated appropriately.
INC,
/// Escape, for a coprocessor; perform the bus cycles necessary to read the source and destination and perform a NOP.
ESC,
/// Stops the processor until the next interrupt is fired.
HLT,
/// Waits until the WAIT input is asserted; if an interrupt occurs then it is serviced but returns to the WAIT.
WAIT,
/// Add with carry; source, destination, operand and displacement will be populated appropriately.
ADC,
/// Add; source, destination, operand and displacement will be populated appropriately.
ADD,
/// Subtract with borrow; source, destination, operand and displacement will be populated appropriately.
SBB,
/// Subtract; source, destination, operand and displacement will be populated appropriately.
SUB,
/// Unsigned multiply; multiplies the source value by AX or AL, storing the result in DX:AX or AX.
MUL,
/// Signed multiply; multiplies the source value by AX or AL, storing the result in DX:AX or AX.
IMUL,
/// Unsigned divide; divide the source value by AX or AL, storing the quotient in AL and the remainder in AH.
DIV,
/// Signed divide; divide the source value by AX or AL, storing the quotient in AL and the remainder in AH.
IDIV,
/// Reads from the port specified by source to the destination.
IN,
/// Writes from the port specified by destination from the source.
OUT,
// Various jumps; see the displacement to calculate targets.
JO, JNO, JB, JNB, JE, JNE, JBE, JNBE,
JS, JNS, JP, JNP, JL, JNL, JLE, JNLE,
/// Far call; see the segment() and offset() fields.
CALLF,
/// Displacement call; followed by a 16-bit operand providing a call offset.
CALLD,
/// Near call.
CALLN,
/// Return from interrupt.
IRET,
/// Near return; if source is not ::None then it will be an ::Immediate indicating how many additional bytes to remove from the stack.
RETF,
/// Far return; if source is not ::None then it will be an ::Immediate indicating how many additional bytes to remove from the stack.
RETN,
/// Near jump; if an operand is not ::None then it gives an absolute destination; otherwise see the displacement.
JMPN,
/// Far jump to the indicated segment and offset.
JMPF,
/// Relative jump performed only if CX = 0; see the displacement.
JPCX,
/// Generates a software interrupt of the level stated in the operand.
INT,
/// Generates a software interrupt of level 3.
INT3,
/// Generates a software interrupt of level 4 if overflow is set.
INTO,
/// Load status flags to AH.
LAHF,
/// Load status flags from AH.
SAHF,
/// Load a segment and offset from the source into DS and the destination.
LDS,
/// Load a segment and offset from the source into ES and the destination.
LES,
/// Computes the effective address of the source and loads it into the destination.
LEA,
/// Load string; reads from DS:SI into AL or AX, subject to segment override.
LODS,
/// Move string; moves a byte or word from DS:SI to ES:DI. If a segment override is provided, it overrides the the source.
MOVS,
/// Scan string; reads a byte or word from DS:SI and compares it to AL or AX.
SCAS,
/// Store string; store AL or AX to ES:DI.
STOS,
// Perform a possibly-conditional loop, decrementing CX. See the displacement.
LOOP, LOOPE, LOOPNE,
/// Loads the destination with the source.
MOV,
/// Negatives; source and destination point to the same thing, to negative.
NEG,
/// Logical NOT; source and destination point to the same thing, to negative.
NOT,
/// Logical AND; source, destination, operand and displacement will be populated appropriately.
AND,
/// Logical OR of source onto destination.
OR,
/// Logical XOR of source onto destination.
XOR,
/// NOP; no further fields.
NOP,
/// POP from the stack to destination.
POP,
/// POP from the stack to the flags register.
POPF,
/// PUSH the source to the stack.
PUSH,
/// PUSH the flags register to the stack.
PUSHF,
/// Rotate the destination left through carry the number of bits indicated by source.
RCL,
/// Rotate the destination right through carry the number of bits indicated by source.
RCR,
/// Rotate the destination left the number of bits indicated by source.
ROL,
/// Rotate the destination right the number of bits indicated by source.
ROR,
/// Arithmetic shift left the destination by the number of bits indicated by source.
SAL,
/// Arithmetic shift right the destination by the number of bits indicated by source.
SAR,
/// Logical shift right the destination by the number of bits indicated by source.
SHR,
/// Clear carry flag; no source or destination provided.
CLC,
/// Clear direction flag; no source or destination provided.
CLD,
/// Clear interrupt flag; no source or destination provided.
CLI,
/// Set carry flag.
STC,
/// Set decimal flag.
STD,
/// Set interrupt flag.
STI,
/// Compares source and destination.
TEST,
/// Exchanges the contents of the source and destination.
XCHG,
/// Load AL with DS:[AL+BX].
XLAT,
};
enum class Size: uint8_t {
Implied = 0,
Byte = 1,
Word = 2,
DWord = 4,
};
enum class Source: uint8_t {
None,
CS, DS, ES, SS,
AL, AH, AX,
BL, BH, BX,
CL, CH, CX,
DL, DH, DX,
SI, DI,
BP, SP,
IndBXPlusSI,
IndBXPlusDI,
IndBPPlusSI,
IndBPPlusDI,
IndSI,
IndDI,
DirectAddress,
IndBP,
IndBX,
Immediate
};
enum class Repetition: uint8_t {
None, RepE, RepNE
};
class Instruction {
public:
Operation operation = Operation::Invalid;
bool operator ==(const Instruction &rhs) const {
return
repetition_size_ == rhs.repetition_size_ &&
sources_ == rhs.sources_ &&
displacement_ == rhs.displacement_ &&
operand_ == rhs.operand_;
}
private:
// b0, b1: a Repetition;
// b2+: operation size.
uint8_t repetition_size_ = 0;
// b0–b5: source;
// b6–b11: destination;
// b12–b14: segment override;
// b15: lock.
uint16_t sources_ = 0;
// Unpackable fields.
int16_t displacement_ = 0;
uint16_t operand_ = 0; // ... or used to store a segment for far operations.
public:
Source source() const { return Source(sources_ & 0x3f); }
Source destination() const { return Source((sources_ >> 6) & 0x3f); }
bool lock() const { return sources_ & 0x8000; }
Source segment_override() const { return Source((sources_ >> 12) & 7); }
Repetition repetition() const { return Repetition(repetition_size_ & 3); }
Size operation_size() const { return Size(repetition_size_ >> 2); }
uint16_t segment() const { return uint16_t(operand_); }
uint16_t offset() const { return uint16_t(displacement_); }
int16_t displacement() const { return displacement_; }
uint16_t operand() const { return operand_; }
Instruction() noexcept {}
Instruction(
Operation operation,
Source source,
Source destination,
bool lock,
Source segment_override,
Repetition repetition,
Size operation_size,
int16_t displacement,
uint16_t operand) noexcept :
operation(operation),
repetition_size_(uint8_t((int(operation_size) << 2) | int(repetition))),
sources_(uint16_t(
int(source) |
(int(destination) << 6) |
(int(segment_override) << 12) |
(int(lock) << 15)
)),
displacement_(displacement),
operand_(operand) {}
};
static_assert(sizeof(Instruction) <= 8);
}
}
}
#endif /* InstructionSets_x86_Instruction_h */
<commit_msg>Better sorts by function, corrects TEST description.<commit_after>//
// Instruction.hpp
// Clock Signal
//
// Created by Thomas Harte on 1/15/21.
// Copyright © 2021 Thomas Harte. All rights reserved.
//
#ifndef InstructionSets_x86_Instruction_h
#define InstructionSets_x86_Instruction_h
#include <cstdint>
namespace CPU {
namespace Decoder {
namespace x86 {
/*
Operations are documented below to establish expectations as to which
instruction fields will be meaningful for each; this is a work-in-progress
and may currently contain errors in the opcode descriptions — especially
where implicit register dependencies are afoot.
*/
enum class Operation: uint8_t {
Invalid,
/// ASCII adjust after addition; source will be AL and destination will be AX.
AAA,
/// ASCII adjust before division; destination will be AX and source will be a multiplier.
AAD,
/// ASCII adjust after multiplication; destination will be AX and source will be a divider.
AAM,
/// ASCII adjust after subtraction; source will be AL and destination will be AX.
AAS,
/// Decimal adjust after addition; source and destination will be AL.
DAA,
/// Decimal adjust after subtraction; source and destination will be AL.
DAS,
/// Convert byte into word; source will be AL, destination will be AH.
CBW,
/// Convert word to double word; source will be AX and destination will be DX.
CWD,
/// Escape, for a coprocessor; perform the bus cycles necessary to read the source and destination and perform a NOP.
ESC,
/// Stops the processor until the next interrupt is fired.
HLT,
/// Waits until the WAIT input is asserted; if an interrupt occurs then it is serviced but returns to the WAIT.
WAIT,
/// Add with carry; source, destination, operand and displacement will be populated appropriately.
ADC,
/// Add; source, destination, operand and displacement will be populated appropriately.
ADD,
/// Subtract with borrow; source, destination, operand and displacement will be populated appropriately.
SBB,
/// Subtract; source, destination, operand and displacement will be populated appropriately.
SUB,
/// Unsigned multiply; multiplies the source value by AX or AL, storing the result in DX:AX or AX.
MUL,
/// Signed multiply; multiplies the source value by AX or AL, storing the result in DX:AX or AX.
IMUL,
/// Unsigned divide; divide the source value by AX or AL, storing the quotient in AL and the remainder in AH.
DIV,
/// Signed divide; divide the source value by AX or AL, storing the quotient in AL and the remainder in AH.
IDIV,
/// Increment; source, destination, operand and displacement will be populated appropriately.
INC,
/// Decrement; source, destination, operand and displacement will be populated appropriately.
DEC,
/// Reads from the port specified by source to the destination.
IN,
/// Writes from the port specified by destination from the source.
OUT,
// Various jumps; see the displacement to calculate targets.
JO, JNO, JB, JNB, JE, JNE, JBE, JNBE,
JS, JNS, JP, JNP, JL, JNL, JLE, JNLE,
/// Far call; see the segment() and offset() fields.
CALLF,
/// Displacement call; followed by a 16-bit operand providing a call offset.
CALLD,
/// Near call.
CALLN,
/// Return from interrupt.
IRET,
/// Near return; if source is not ::None then it will be an ::Immediate indicating how many additional bytes to remove from the stack.
RETF,
/// Far return; if source is not ::None then it will be an ::Immediate indicating how many additional bytes to remove from the stack.
RETN,
/// Near jump; if an operand is not ::None then it gives an absolute destination; otherwise see the displacement.
JMPN,
/// Far jump to the indicated segment and offset.
JMPF,
/// Relative jump performed only if CX = 0; see the displacement.
JPCX,
/// Generates a software interrupt of the level stated in the operand.
INT,
/// Generates a software interrupt of level 3.
INT3,
/// Generates a software interrupt of level 4 if overflow is set.
INTO,
/// Load status flags to AH.
LAHF,
/// Load status flags from AH.
SAHF,
/// Load a segment and offset from the source into DS and the destination.
LDS,
/// Load a segment and offset from the source into ES and the destination.
LES,
/// Computes the effective address of the source and loads it into the destination.
LEA,
/// Compare [bytes or words, per operation size]; source and destination implied to be DS:[SI] and ES:[DI].
CMPS,
/// Load string; reads from DS:SI into AL or AX, subject to segment override.
LODS,
/// Move string; moves a byte or word from DS:SI to ES:DI. If a segment override is provided, it overrides the the source.
MOVS,
/// Scan string; reads a byte or word from DS:SI and compares it to AL or AX.
SCAS,
/// Store string; store AL or AX to ES:DI.
STOS,
// Perform a possibly-conditional loop, decrementing CX. See the displacement.
LOOP, LOOPE, LOOPNE,
/// Loads the destination with the source.
MOV,
/// Negatives; source and destination point to the same thing, to negative.
NEG,
/// Logical NOT; source and destination point to the same thing, to negative.
NOT,
/// Logical AND; source, destination, operand and displacement will be populated appropriately.
AND,
/// Logical OR of source onto destination.
OR,
/// Logical XOR of source onto destination.
XOR,
/// NOP; no further fields.
NOP,
/// POP from the stack to destination.
POP,
/// POP from the stack to the flags register.
POPF,
/// PUSH the source to the stack.
PUSH,
/// PUSH the flags register to the stack.
PUSHF,
/// Rotate the destination left through carry the number of bits indicated by source.
RCL,
/// Rotate the destination right through carry the number of bits indicated by source.
RCR,
/// Rotate the destination left the number of bits indicated by source.
ROL,
/// Rotate the destination right the number of bits indicated by source.
ROR,
/// Arithmetic shift left the destination by the number of bits indicated by source.
SAL,
/// Arithmetic shift right the destination by the number of bits indicated by source.
SAR,
/// Logical shift right the destination by the number of bits indicated by source.
SHR,
/// Clear carry flag; no source or destination provided.
CLC,
/// Clear direction flag; no source or destination provided.
CLD,
/// Clear interrupt flag; no source or destination provided.
CLI,
/// Set carry flag.
STC,
/// Set decimal flag.
STD,
/// Set interrupt flag.
STI,
/// Complement carry flag; no source or destination provided.
CMC,
/// Compare; source, destination, operand and displacement will be populated appropriately.
CMP,
/// Sets flags based on the result of a logical AND of source and destination.
TEST,
/// Exchanges the contents of the source and destination.
XCHG,
/// Load AL with DS:[AL+BX].
XLAT,
};
enum class Size: uint8_t {
Implied = 0,
Byte = 1,
Word = 2,
DWord = 4,
};
enum class Source: uint8_t {
None,
CS, DS, ES, SS,
AL, AH, AX,
BL, BH, BX,
CL, CH, CX,
DL, DH, DX,
SI, DI,
BP, SP,
IndBXPlusSI,
IndBXPlusDI,
IndBPPlusSI,
IndBPPlusDI,
IndSI,
IndDI,
DirectAddress,
IndBP,
IndBX,
Immediate
};
enum class Repetition: uint8_t {
None, RepE, RepNE
};
class Instruction {
public:
Operation operation = Operation::Invalid;
bool operator ==(const Instruction &rhs) const {
return
repetition_size_ == rhs.repetition_size_ &&
sources_ == rhs.sources_ &&
displacement_ == rhs.displacement_ &&
operand_ == rhs.operand_;
}
private:
// b0, b1: a Repetition;
// b2+: operation size.
uint8_t repetition_size_ = 0;
// b0–b5: source;
// b6–b11: destination;
// b12–b14: segment override;
// b15: lock.
uint16_t sources_ = 0;
// Unpackable fields.
int16_t displacement_ = 0;
uint16_t operand_ = 0; // ... or used to store a segment for far operations.
public:
Source source() const { return Source(sources_ & 0x3f); }
Source destination() const { return Source((sources_ >> 6) & 0x3f); }
bool lock() const { return sources_ & 0x8000; }
Source segment_override() const { return Source((sources_ >> 12) & 7); }
Repetition repetition() const { return Repetition(repetition_size_ & 3); }
Size operation_size() const { return Size(repetition_size_ >> 2); }
uint16_t segment() const { return uint16_t(operand_); }
uint16_t offset() const { return uint16_t(displacement_); }
int16_t displacement() const { return displacement_; }
uint16_t operand() const { return operand_; }
Instruction() noexcept {}
Instruction(
Operation operation,
Source source,
Source destination,
bool lock,
Source segment_override,
Repetition repetition,
Size operation_size,
int16_t displacement,
uint16_t operand) noexcept :
operation(operation),
repetition_size_(uint8_t((int(operation_size) << 2) | int(repetition))),
sources_(uint16_t(
int(source) |
(int(destination) << 6) |
(int(segment_override) << 12) |
(int(lock) << 15)
)),
displacement_(displacement),
operand_(operand) {}
};
static_assert(sizeof(Instruction) <= 8);
}
}
}
#endif /* InstructionSets_x86_Instruction_h */
<|endoftext|> |
<commit_before>// Copyright 2016 The SwiftShader Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "FrameBufferAndroid.hpp"
#include <cutils/log.h>
namespace sw
{
inline int dequeueBuffer(ANativeWindow* window, ANativeWindowBuffer** buffer)
{
#if ANDROID_PLATFORM_SDK_VERSION > 16
return native_window_dequeue_buffer_and_wait(window, buffer);
#else
return window->dequeueBuffer(window, buffer);
#endif
}
inline int queueBuffer(ANativeWindow* window, ANativeWindowBuffer* buffer, int fenceFd)
{
#if ANDROID_PLATFORM_SDK_VERSION > 16
return window->queueBuffer(window, buffer, fenceFd);
#else
return window->queueBuffer(window, buffer);
#endif
}
inline int cancelBuffer(ANativeWindow* window, ANativeWindowBuffer* buffer, int fenceFd)
{
#if ANDROID_PLATFORM_SDK_VERSION > 16
return window->cancelBuffer(window, buffer, fenceFd);
#else
return window->cancelBuffer(window, buffer);
#endif
}
FrameBufferAndroid::FrameBufferAndroid(ANativeWindow* window, int width, int height)
: FrameBuffer(width, height, false, false),
nativeWindow(window), buffer(nullptr), gralloc(nullptr)
{
hw_module_t const* pModule;
hw_get_module(GRALLOC_HARDWARE_MODULE_ID, &pModule);
gralloc = reinterpret_cast<gralloc_module_t const*>(pModule);
nativeWindow->common.incRef(&nativeWindow->common);
native_window_set_usage(nativeWindow, GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN);
}
FrameBufferAndroid::~FrameBufferAndroid()
{
nativeWindow->common.decRef(&nativeWindow->common);
}
void FrameBufferAndroid::blit(void *source, const Rect *sourceRect, const Rect *destRect, Format sourceFormat, size_t sourceStride)
{
copy(source, sourceFormat, sourceStride);
if(buffer)
{
if(locked)
{
locked = nullptr;
unlock();
}
queueBuffer(nativeWindow, buffer, -1);
buffer->common.decRef(&buffer->common);
}
}
void *FrameBufferAndroid::lock()
{
if(dequeueBuffer(nativeWindow, &buffer) != 0)
{
return nullptr;
}
buffer->common.incRef(&buffer->common);
if(gralloc->lock(gralloc, buffer->handle,
GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN,
0, 0, buffer->width, buffer->height, &locked) != 0)
{
ALOGE("%s failed to lock buffer %p", __FUNCTION__, buffer);
return nullptr;
}
if((buffer->width < width) || (buffer->height < height))
{
ALOGI("lock failed: buffer of %dx%d too small for window of %dx%d",
buffer->width, buffer->height, width, height);
return nullptr;
}
switch(buffer->format)
{
default: ALOGE("Unsupported buffer format %d", buffer->format); ASSERT(false);
case HAL_PIXEL_FORMAT_RGB_565: destFormat = FORMAT_R5G6B5; break;
case HAL_PIXEL_FORMAT_RGB_888: destFormat = FORMAT_R8G8B8; break;
case HAL_PIXEL_FORMAT_RGBA_8888: destFormat = FORMAT_A8B8G8R8; break;
#if ANDROID_PLATFORM_SDK_VERSION > 16
case HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED: destFormat = FORMAT_X8B8G8R8; break;
#endif
case HAL_PIXEL_FORMAT_RGBX_8888: destFormat = FORMAT_X8B8G8R8; break;
case HAL_PIXEL_FORMAT_BGRA_8888: destFormat = FORMAT_A8R8G8B8; break;
}
stride = buffer->stride * Surface::bytes(destFormat);
return locked;
}
void FrameBufferAndroid::unlock()
{
if(!buffer)
{
ALOGE("%s: badness unlock with no active buffer", __FUNCTION__);
return;
}
locked = nullptr;
if(gralloc->unlock(gralloc, buffer->handle) != 0)
{
ALOGE("%s: badness unlock failed", __FUNCTION__);
}
}
}
sw::FrameBuffer *createFrameBuffer(void *display, ANativeWindow* window, int width, int height)
{
return new sw::FrameBufferAndroid(window, width, height);
}
<commit_msg>Remove superfluous incRef/decRef on graphics buffer.<commit_after>// Copyright 2016 The SwiftShader Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "FrameBufferAndroid.hpp"
#include <cutils/log.h>
namespace sw
{
inline int dequeueBuffer(ANativeWindow* window, ANativeWindowBuffer** buffer)
{
#if ANDROID_PLATFORM_SDK_VERSION > 16
return native_window_dequeue_buffer_and_wait(window, buffer);
#else
return window->dequeueBuffer(window, buffer);
#endif
}
inline int queueBuffer(ANativeWindow* window, ANativeWindowBuffer* buffer, int fenceFd)
{
#if ANDROID_PLATFORM_SDK_VERSION > 16
return window->queueBuffer(window, buffer, fenceFd);
#else
return window->queueBuffer(window, buffer);
#endif
}
inline int cancelBuffer(ANativeWindow* window, ANativeWindowBuffer* buffer, int fenceFd)
{
#if ANDROID_PLATFORM_SDK_VERSION > 16
return window->cancelBuffer(window, buffer, fenceFd);
#else
return window->cancelBuffer(window, buffer);
#endif
}
FrameBufferAndroid::FrameBufferAndroid(ANativeWindow* window, int width, int height)
: FrameBuffer(width, height, false, false),
nativeWindow(window), buffer(nullptr), gralloc(nullptr)
{
hw_module_t const* pModule;
hw_get_module(GRALLOC_HARDWARE_MODULE_ID, &pModule);
gralloc = reinterpret_cast<gralloc_module_t const*>(pModule);
nativeWindow->common.incRef(&nativeWindow->common);
native_window_set_usage(nativeWindow, GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN);
}
FrameBufferAndroid::~FrameBufferAndroid()
{
nativeWindow->common.decRef(&nativeWindow->common);
}
void FrameBufferAndroid::blit(void *source, const Rect *sourceRect, const Rect *destRect, Format sourceFormat, size_t sourceStride)
{
copy(source, sourceFormat, sourceStride);
if(buffer)
{
if(locked)
{
locked = nullptr;
unlock();
}
queueBuffer(nativeWindow, buffer, -1);
}
}
void *FrameBufferAndroid::lock()
{
if(dequeueBuffer(nativeWindow, &buffer) != 0)
{
return nullptr;
}
if(gralloc->lock(gralloc, buffer->handle,
GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN,
0, 0, buffer->width, buffer->height, &locked) != 0)
{
ALOGE("%s failed to lock buffer %p", __FUNCTION__, buffer);
return nullptr;
}
if((buffer->width < width) || (buffer->height < height))
{
ALOGI("lock failed: buffer of %dx%d too small for window of %dx%d",
buffer->width, buffer->height, width, height);
return nullptr;
}
switch(buffer->format)
{
default: ALOGE("Unsupported buffer format %d", buffer->format); ASSERT(false);
case HAL_PIXEL_FORMAT_RGB_565: destFormat = FORMAT_R5G6B5; break;
case HAL_PIXEL_FORMAT_RGB_888: destFormat = FORMAT_R8G8B8; break;
case HAL_PIXEL_FORMAT_RGBA_8888: destFormat = FORMAT_A8B8G8R8; break;
#if ANDROID_PLATFORM_SDK_VERSION > 16
case HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED: destFormat = FORMAT_X8B8G8R8; break;
#endif
case HAL_PIXEL_FORMAT_RGBX_8888: destFormat = FORMAT_X8B8G8R8; break;
case HAL_PIXEL_FORMAT_BGRA_8888: destFormat = FORMAT_A8R8G8B8; break;
}
stride = buffer->stride * Surface::bytes(destFormat);
return locked;
}
void FrameBufferAndroid::unlock()
{
if(!buffer)
{
ALOGE("%s: badness unlock with no active buffer", __FUNCTION__);
return;
}
locked = nullptr;
if(gralloc->unlock(gralloc, buffer->handle) != 0)
{
ALOGE("%s: badness unlock failed", __FUNCTION__);
}
}
}
sw::FrameBuffer *createFrameBuffer(void *display, ANativeWindow* window, int width, int height)
{
return new sw::FrameBufferAndroid(window, width, height);
}
<|endoftext|> |
<commit_before>#include <seqan/basic.h>
using namespace seqan;
//An arbitrary class
struct MyClass
{
};
int main()
{
///The following code creates 100 instances of $MyClass$ on the heap.
///The allocator object used is a temporary $Default$.
MyClass * my_class_arr;
allocate(Default(), my_class_arr, 100);
arrayConstruct(my_class_arr, my_class_arr + 100);
///Before the storage is deallocated, the $MyClass$ objects must be destroyed.
arrayDestruct(my_class_arr, my_class_arr + 100);
deallocate(Default(), my_class_arr, 100);
///We can use any kind of object as allocator, but dedicated allocators offer more advanced functionality, e.g. @Function.clear@.
Allocator<SimpleAlloc< > > alloc1;
allocate(alloc1, my_class_arr, 200);
char * char_array;
allocate(alloc1, char_array, 300);
clear(alloc1); //deallocated all storage at once.
return 0;
}
<commit_msg><commit_after>///A tutorial about the use of allocators.
#include <seqan/basic.h>
using namespace seqan;
///We define an arbitrary class.
struct MyClass
{
};
int main()
{
///We create 100 instances of $MyClass$ on the heap
///using a default temporary allocator object $Default$.
MyClass* my_class_arr;
allocate(Default(), my_class_arr, 100);
arrayConstruct(my_class_arr, my_class_arr + 100);
///Before the storage is deallocated, the $MyClass$ objects have to be destroyed.
arrayDestruct(my_class_arr, my_class_arr + 100);
deallocate(Default(), my_class_arr, 100);
///We can use any kind of object as an allocator.
///However, dedicated allocators offer more advanced functionality, e.g. @Function.clear@.
Allocator<SimpleAlloc< > > alloc1;
char * char_array;
allocate(alloc1, char_array, 300);
///@Function.clear@ can be used to deallocate all storage at once.
clear(alloc1);
return 0;
}
<|endoftext|> |
<commit_before>/* Copyright (C) 2003 MySQL AB
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
/************************************************************************************************
Name: NdbRecAttr.C
Include:
Link:
Author: UABRONM Mikael Ronstrm UAB/B/SD
Date: 971206
Version: 0.1
Description: Interface between TIS and NDB
Documentation:
Adjust: 971206 UABRONM First version
************************************************************************************************/
#include <ndb_global.h>
#include <NdbOut.hpp>
#include <NdbRecAttr.hpp>
#include "NdbDictionaryImpl.hpp"
#include <NdbTCP.h>
NdbRecAttr::NdbRecAttr()
{
init();
}
NdbRecAttr::~NdbRecAttr()
{
release();
}
int
NdbRecAttr::setup(const class NdbDictionary::Column* col, char* aValue)
{
return setup(&(col->m_impl), aValue);
}
int
NdbRecAttr::setup(const NdbColumnImpl* anAttrInfo, char* aValue)
{
Uint32 tAttrSize = anAttrInfo->m_attrSize;
Uint32 tArraySize = anAttrInfo->m_arraySize;
Uint32 tAttrByteSize = tAttrSize * tArraySize;
m_column = anAttrInfo;
theAttrId = anAttrInfo->m_attrId;
theAttrSize = tAttrSize;
theArraySize = tArraySize;
theValue = aValue;
theNULLind = 0;
m_nullable = anAttrInfo->m_nullable;
// check alignment to signal data
// a future version could check alignment per data type as well
if (aValue != NULL && (UintPtr(aValue)&3) == 0 && (tAttrByteSize&3) == 0) {
theStorageX = NULL;
theRef = aValue;
return 0;
}
if (tAttrByteSize <= 32) {
theStorageX = NULL;
theStorage[0] = 0;
theStorage[1] = 0;
theStorage[2] = 0;
theStorage[3] = 0;
theRef = theStorage;
return 0;
}
Uint32 tSize = (tAttrByteSize + 7) >> 3;
Uint64* tRef = new Uint64[tSize];
if (tRef != NULL) {
for (Uint32 i = 0; i < tSize; i++) {
tRef[i] = 0;
}
theStorageX = tRef;
theRef = tRef;
return 0;
}
return -1;
}
void
NdbRecAttr::copyout()
{
char* tRef = (char*)theRef;
char* tValue = theValue;
if (tRef != tValue && tRef != NULL && tValue != NULL) {
Uint32 n = theAttrSize * theArraySize;
while (n-- > 0) {
*tValue++ = *tRef++;
}
}
}
NdbRecAttr *
NdbRecAttr::clone() const {
NdbRecAttr * ret = new NdbRecAttr();
ret->theAttrId = theAttrId;
ret->theNULLind = theNULLind;
ret->theAttrSize = theAttrSize;
ret->theArraySize = theArraySize;
ret->m_column = m_column;
Uint32 n = theAttrSize * theArraySize;
if(n <= 32){
ret->theRef = (char*)&ret->theStorage[0];
ret->theStorageX = 0;
ret->theValue = 0;
} else {
ret->theStorageX = new Uint64[((n + 7) >> 3)];
ret->theRef = (char*)ret->theStorageX;
ret->theValue = 0;
}
memcpy(ret->theRef, theRef, n);
return ret;
}
bool
NdbRecAttr::receive_data(const Uint32 * data, Uint32 sz){
const Uint32 n = (theAttrSize * theArraySize + 3) >> 2;
if(n == sz){
if(!copyoutRequired())
memcpy(theRef, data, 4 * sz);
else
memcpy(theValue, data, theAttrSize * theArraySize);
return true;
} else if(sz == 0){
setNULL();
return true;
}
return false;
}
NdbOut& operator<<(NdbOut& ndbout, const NdbRecAttr &r)
{
if (r.isNULL())
{
ndbout << "[NULL]";
return ndbout;
}
if (r.arraySize() > 1)
ndbout << "[";
for (Uint32 j = 0; j < r.arraySize(); j++)
{
if (j > 0)
ndbout << " ";
switch(r.getType())
{
case NdbDictionary::Column::Bigunsigned:
ndbout << r.u_64_value();
break;
case NdbDictionary::Column::Unsigned:
ndbout << r.u_32_value();
break;
case NdbDictionary::Column::Smallunsigned:
ndbout << r.u_short_value();
break;
case NdbDictionary::Column::Tinyunsigned:
ndbout << (unsigned) r.u_char_value();
break;
case NdbDictionary::Column::Bigint:
ndbout << r.int64_value();
break;
case NdbDictionary::Column::Int:
ndbout << r.int32_value();
break;
case NdbDictionary::Column::Smallint:
ndbout << r.short_value();
break;
case NdbDictionary::Column::Tinyint:
ndbout << (int) r.char_value();
break;
case NdbDictionary::Column::Char:
ndbout.print("%.*s", r.arraySize(), r.aRef());
j = r.arraySize();
break;
case NdbDictionary::Column::Varchar:
{
short len = ntohs(r.u_short_value());
ndbout.print("%.*s", len, r.aRef()+2);
}
j = r.arraySize();
break;
case NdbDictionary::Column::Float:
ndbout << r.float_value();
break;
case NdbDictionary::Column::Double:
ndbout << r.double_value();
break;
default: /* no print functions for the rest, just print type */
ndbout << r.getType();
j = r.arraySize();
if (j > 1)
ndbout << " %u times" << j;
break;
}
}
if (r.arraySize() > 1)
{
ndbout << "]";
}
return ndbout;
}
<commit_msg>Reset null indicator<commit_after>/* Copyright (C) 2003 MySQL AB
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
/************************************************************************************************
Name: NdbRecAttr.C
Include:
Link:
Author: UABRONM Mikael Ronstrm UAB/B/SD
Date: 971206
Version: 0.1
Description: Interface between TIS and NDB
Documentation:
Adjust: 971206 UABRONM First version
************************************************************************************************/
#include <ndb_global.h>
#include <NdbOut.hpp>
#include <NdbRecAttr.hpp>
#include "NdbDictionaryImpl.hpp"
#include <NdbTCP.h>
NdbRecAttr::NdbRecAttr()
{
init();
}
NdbRecAttr::~NdbRecAttr()
{
release();
}
int
NdbRecAttr::setup(const class NdbDictionary::Column* col, char* aValue)
{
return setup(&(col->m_impl), aValue);
}
int
NdbRecAttr::setup(const NdbColumnImpl* anAttrInfo, char* aValue)
{
Uint32 tAttrSize = anAttrInfo->m_attrSize;
Uint32 tArraySize = anAttrInfo->m_arraySize;
Uint32 tAttrByteSize = tAttrSize * tArraySize;
m_column = anAttrInfo;
theAttrId = anAttrInfo->m_attrId;
theAttrSize = tAttrSize;
theArraySize = tArraySize;
theValue = aValue;
theNULLind = 0;
m_nullable = anAttrInfo->m_nullable;
// check alignment to signal data
// a future version could check alignment per data type as well
if (aValue != NULL && (UintPtr(aValue)&3) == 0 && (tAttrByteSize&3) == 0) {
theStorageX = NULL;
theRef = aValue;
return 0;
}
if (tAttrByteSize <= 32) {
theStorageX = NULL;
theStorage[0] = 0;
theStorage[1] = 0;
theStorage[2] = 0;
theStorage[3] = 0;
theRef = theStorage;
return 0;
}
Uint32 tSize = (tAttrByteSize + 7) >> 3;
Uint64* tRef = new Uint64[tSize];
if (tRef != NULL) {
for (Uint32 i = 0; i < tSize; i++) {
tRef[i] = 0;
}
theStorageX = tRef;
theRef = tRef;
return 0;
}
return -1;
}
void
NdbRecAttr::copyout()
{
char* tRef = (char*)theRef;
char* tValue = theValue;
if (tRef != tValue && tRef != NULL && tValue != NULL) {
Uint32 n = theAttrSize * theArraySize;
while (n-- > 0) {
*tValue++ = *tRef++;
}
}
}
NdbRecAttr *
NdbRecAttr::clone() const {
NdbRecAttr * ret = new NdbRecAttr();
ret->theAttrId = theAttrId;
ret->theNULLind = theNULLind;
ret->theAttrSize = theAttrSize;
ret->theArraySize = theArraySize;
ret->m_column = m_column;
Uint32 n = theAttrSize * theArraySize;
if(n <= 32){
ret->theRef = (char*)&ret->theStorage[0];
ret->theStorageX = 0;
ret->theValue = 0;
} else {
ret->theStorageX = new Uint64[((n + 7) >> 3)];
ret->theRef = (char*)ret->theStorageX;
ret->theValue = 0;
}
memcpy(ret->theRef, theRef, n);
return ret;
}
bool
NdbRecAttr::receive_data(const Uint32 * data, Uint32 sz){
const Uint32 n = (theAttrSize * theArraySize + 3) >> 2;
if(n == sz){
theNULLind = 0;
if(!copyoutRequired())
memcpy(theRef, data, 4 * sz);
else
memcpy(theValue, data, theAttrSize * theArraySize);
return true;
} else if(sz == 0){
setNULL();
return true;
}
return false;
}
NdbOut& operator<<(NdbOut& ndbout, const NdbRecAttr &r)
{
if (r.isNULL())
{
ndbout << "[NULL]";
return ndbout;
}
if (r.arraySize() > 1)
ndbout << "[";
for (Uint32 j = 0; j < r.arraySize(); j++)
{
if (j > 0)
ndbout << " ";
switch(r.getType())
{
case NdbDictionary::Column::Bigunsigned:
ndbout << r.u_64_value();
break;
case NdbDictionary::Column::Unsigned:
ndbout << r.u_32_value();
break;
case NdbDictionary::Column::Smallunsigned:
ndbout << r.u_short_value();
break;
case NdbDictionary::Column::Tinyunsigned:
ndbout << (unsigned) r.u_char_value();
break;
case NdbDictionary::Column::Bigint:
ndbout << r.int64_value();
break;
case NdbDictionary::Column::Int:
ndbout << r.int32_value();
break;
case NdbDictionary::Column::Smallint:
ndbout << r.short_value();
break;
case NdbDictionary::Column::Tinyint:
ndbout << (int) r.char_value();
break;
case NdbDictionary::Column::Char:
ndbout.print("%.*s", r.arraySize(), r.aRef());
j = r.arraySize();
break;
case NdbDictionary::Column::Varchar:
{
short len = ntohs(r.u_short_value());
ndbout.print("%.*s", len, r.aRef()+2);
}
j = r.arraySize();
break;
case NdbDictionary::Column::Float:
ndbout << r.float_value();
break;
case NdbDictionary::Column::Double:
ndbout << r.double_value();
break;
default: /* no print functions for the rest, just print type */
ndbout << r.getType();
j = r.arraySize();
if (j > 1)
ndbout << " %u times" << j;
break;
}
}
if (r.arraySize() > 1)
{
ndbout << "]";
}
return ndbout;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/flip/flip_session_pool.h"
#include "base/logging.h"
#include "net/flip/flip_session.h"
namespace net {
// The maximum number of sessions to open to a single domain.
const int kMaxSessionsPerDomain = 1;
scoped_ptr<FlipSessionPool::FlipSessionsMap> FlipSessionPool::sessions_;
FlipSession* FlipSessionPool::Get(const HostResolver::RequestInfo& info,
HttpNetworkSession* session) {
if (!sessions_.get())
sessions_.reset(new FlipSessionsMap());
const std::string domain = info.hostname();
FlipSession* flip_session = NULL;
FlipSessionList* list = GetSessionList(domain);
if (list) {
if (list->size() >= kMaxSessionsPerDomain) {
flip_session = list->front();
list->pop_front();
}
} else {
list = AddSessionList(domain);
}
DCHECK(list);
if (!flip_session) {
flip_session = new FlipSession(domain, session);
flip_session->AddRef(); // Keep it in the cache.
}
DCHECK(flip_session);
list->push_back(flip_session);
DCHECK(list->size() <= kMaxSessionsPerDomain);
return flip_session;
}
void FlipSessionPool::Remove(FlipSession* session) {
std::string domain = session->domain();
FlipSessionList* list = GetSessionList(domain);
if (list == NULL)
return;
list->remove(session);
if (!list->size())
RemoveSessionList(domain);
}
FlipSessionPool::FlipSessionList*
FlipSessionPool::AddSessionList(std::string domain) {
DCHECK(sessions_->find(domain) == sessions_->end());
return (*sessions_)[domain] = new FlipSessionList();
}
// static
FlipSessionPool::FlipSessionList*
FlipSessionPool::GetSessionList(std::string domain) {
FlipSessionsMap::iterator it = sessions_->find(domain);
if (it == sessions_->end())
return NULL;
return it->second;
}
// static
void FlipSessionPool::RemoveSessionList(std::string domain) {
FlipSessionList* list = GetSessionList(domain);
if (list) {
delete list;
sessions_->erase(domain);
} else {
DCHECK(false) << "removing orphaned session list";
}
}
// static
void FlipSessionPool::CloseAllSessions() {
while (sessions_.get() && sessions_->size()) {
FlipSessionList* list = sessions_->begin()->second;
DCHECK(list);
sessions_->erase(sessions_->begin()->first);
while (list->size()) {
FlipSession* session = list->front();
list->pop_front();
session->CloseAllStreams(net::OK);
session->Release();
}
delete list;
}
}
} // namespace net
<commit_msg>Fix signed/unsigned mismatch for linux<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/flip/flip_session_pool.h"
#include "base/logging.h"
#include "net/flip/flip_session.h"
namespace net {
// The maximum number of sessions to open to a single domain.
const size_t kMaxSessionsPerDomain = 1;
scoped_ptr<FlipSessionPool::FlipSessionsMap> FlipSessionPool::sessions_;
FlipSession* FlipSessionPool::Get(const HostResolver::RequestInfo& info,
HttpNetworkSession* session) {
if (!sessions_.get())
sessions_.reset(new FlipSessionsMap());
const std::string domain = info.hostname();
FlipSession* flip_session = NULL;
FlipSessionList* list = GetSessionList(domain);
if (list) {
if (list->size() >= kMaxSessionsPerDomain) {
flip_session = list->front();
list->pop_front();
}
} else {
list = AddSessionList(domain);
}
DCHECK(list);
if (!flip_session) {
flip_session = new FlipSession(domain, session);
flip_session->AddRef(); // Keep it in the cache.
}
DCHECK(flip_session);
list->push_back(flip_session);
DCHECK(list->size() <= kMaxSessionsPerDomain);
return flip_session;
}
void FlipSessionPool::Remove(FlipSession* session) {
std::string domain = session->domain();
FlipSessionList* list = GetSessionList(domain);
if (list == NULL)
return;
list->remove(session);
if (!list->size())
RemoveSessionList(domain);
}
FlipSessionPool::FlipSessionList*
FlipSessionPool::AddSessionList(std::string domain) {
DCHECK(sessions_->find(domain) == sessions_->end());
return (*sessions_)[domain] = new FlipSessionList();
}
// static
FlipSessionPool::FlipSessionList*
FlipSessionPool::GetSessionList(std::string domain) {
FlipSessionsMap::iterator it = sessions_->find(domain);
if (it == sessions_->end())
return NULL;
return it->second;
}
// static
void FlipSessionPool::RemoveSessionList(std::string domain) {
FlipSessionList* list = GetSessionList(domain);
if (list) {
delete list;
sessions_->erase(domain);
} else {
DCHECK(false) << "removing orphaned session list";
}
}
// static
void FlipSessionPool::CloseAllSessions() {
while (sessions_.get() && sessions_->size()) {
FlipSessionList* list = sessions_->begin()->second;
DCHECK(list);
sessions_->erase(sessions_->begin()->first);
while (list->size()) {
FlipSession* session = list->front();
list->pop_front();
session->CloseAllStreams(net::OK);
session->Release();
}
delete list;
}
}
} // namespace net
<|endoftext|> |
<commit_before>/**
* Class definition for a MicroBit Device Firmware Update loader.
*
* This is actually just a frontend to a memory resident nordic DFU loader.
*
* We rely on the BLE standard pairing processes to provide encryption and authentication.
* We assume any device that is paied with the micro:bit is authorized to reprogram the device.
*
*/
#include "MicroBit.h"
#include "ble/UUID.h"
#if !defined(__arm)
#pragma GCC diagnostic ignored "-Wunused-function"
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-parameter"
#endif
/*
* The underlying Nordic libraries that support BLE do not compile cleanly with the stringent GCC settings we employ
* If we're compiling under GCC, then we suppress any warnings generated from this code (but not the rest of the DAL)
* The ARM cc compiler is more tolerant. We don't test __GNUC__ here to detect GCC as ARMCC also typically sets this
* as a compatability option, but does not support the options used...
*/
extern "C" {
#include "dfu_app_handler.h"
}
/*
* Return to our predefined compiler settings.
*/
#if !defined(__arm)
#pragma GCC diagnostic pop
#endif
/**
* Constructor.
* Create a representation of a MicroBit device.
* @param messageBus callback function to receive MicroBitMessageBus events.
*/
MicroBitDFUService::MicroBitDFUService(BLEDevice &_ble) :
ble(_ble)
{
// Opcodes can be issued here to control the MicroBitDFU Service, as defined above.
GattCharacteristic microBitDFUServiceControlCharacteristic(MicroBitDFUServiceControlCharacteristicUUID, &controlByte, 0, sizeof(uint8_t),
GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_READ | GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_WRITE);
controlByte = 0x00;
// Set default security requirements
microBitDFUServiceControlCharacteristic.requireSecurity(SecurityManager::MICROBIT_BLE_SECURITY_LEVEL);
GattCharacteristic *characteristics[] = {µBitDFUServiceControlCharacteristic};
GattService service(MicroBitDFUServiceUUID, characteristics, sizeof(characteristics) / sizeof(GattCharacteristic *));
ble.addService(service);
microBitDFUServiceControlCharacteristicHandle = microBitDFUServiceControlCharacteristic.getValueHandle();
ble.gattServer().write(microBitDFUServiceControlCharacteristicHandle, &controlByte, sizeof(uint8_t));
ble.gattServer().onDataWritten(this, &MicroBitDFUService::onDataWritten);
}
/**
* Callback. Invoked when any of our attributes are written via BLE.
*/
void MicroBitDFUService::onDataWritten(const GattWriteCallbackParams *params)
{
if (params->handle == microBitDFUServiceControlCharacteristicHandle)
{
if(params->len > 0 && params->data[0] == MICROBIT_DFU_OPCODE_START_DFU)
{
uBit.display.stopAnimation();
uBit.display.clear();
#if CONFIG_ENABLED(MICROBIT_DBG)
uBit.serial.printf(" ACTIVATING BOOTLOADER.\n");
#endif
// Perform an explicit disconnection to assist our peer to reconnect to the DFU service
ble.disconnect(Gap::LOCAL_HOST_TERMINATED_CONNECTION);
// Call bootloader_start implicitly trough a event handler call
// it is a work around for bootloader_start not being public in sdk 8.1
ble_dfu_t p_dfu;
ble_dfu_evt_t p_evt;
p_dfu.conn_handle = params->connHandle;
p_evt.ble_dfu_evt_type = BLE_DFU_START;
dfu_app_on_dfu_evt(&p_dfu, &p_evt);
}
}
}
/**
* UUID definitions for BLE Services and Characteristics.
*/
const uint8_t MicroBitDFUServiceUUID[] = {
0xe9,0x5d,0x93,0xb0,0x25,0x1d,0x47,0x0a,0xa0,0x62,0xfa,0x19,0x22,0xdf,0xa9,0xa8
};
const uint8_t MicroBitDFUServiceControlCharacteristicUUID[] = {
0xe9,0x5d,0x93,0xb1,0x25,0x1d,0x47,0x0a,0xa0,0x62,0xfa,0x19,0x22,0xdf,0xa9,0xa8
};
<commit_msg>microbit-dal: fixed android waiting after DFU mode initiated<commit_after>/**
* Class definition for a MicroBit Device Firmware Update loader.
*
* This is actually just a frontend to a memory resident nordic DFU loader.
*
* We rely on the BLE standard pairing processes to provide encryption and authentication.
* We assume any device that is paied with the micro:bit is authorized to reprogram the device.
*
*/
#include "MicroBit.h"
#include "ble/UUID.h"
#if !defined(__arm)
#pragma GCC diagnostic ignored "-Wunused-function"
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-parameter"
#endif
/*
* The underlying Nordic libraries that support BLE do not compile cleanly with the stringent GCC settings we employ
* If we're compiling under GCC, then we suppress any warnings generated from this code (but not the rest of the DAL)
* The ARM cc compiler is more tolerant. We don't test __GNUC__ here to detect GCC as ARMCC also typically sets this
* as a compatability option, but does not support the options used...
*/
extern "C" {
#include "dfu_app_handler.h"
}
/*
* Return to our predefined compiler settings.
*/
#if !defined(__arm)
#pragma GCC diagnostic pop
#endif
/**
* Constructor.
* Create a representation of a MicroBit device.
* @param messageBus callback function to receive MicroBitMessageBus events.
*/
MicroBitDFUService::MicroBitDFUService(BLEDevice &_ble) :
ble(_ble)
{
// Opcodes can be issued here to control the MicroBitDFU Service, as defined above.
GattCharacteristic microBitDFUServiceControlCharacteristic(MicroBitDFUServiceControlCharacteristicUUID, &controlByte, 0, sizeof(uint8_t),
GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_READ | GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_WRITE);
controlByte = 0x00;
// Set default security requirements
microBitDFUServiceControlCharacteristic.requireSecurity(SecurityManager::MICROBIT_BLE_SECURITY_LEVEL);
GattCharacteristic *characteristics[] = {µBitDFUServiceControlCharacteristic};
GattService service(MicroBitDFUServiceUUID, characteristics, sizeof(characteristics) / sizeof(GattCharacteristic *));
ble.addService(service);
microBitDFUServiceControlCharacteristicHandle = microBitDFUServiceControlCharacteristic.getValueHandle();
ble.gattServer().write(microBitDFUServiceControlCharacteristicHandle, &controlByte, sizeof(uint8_t));
ble.gattServer().onDataWritten(this, &MicroBitDFUService::onDataWritten);
}
/**
* Callback. Invoked when any of our attributes are written via BLE.
*/
void MicroBitDFUService::onDataWritten(const GattWriteCallbackParams *params)
{
if (params->handle == microBitDFUServiceControlCharacteristicHandle)
{
if(params->len > 0 && params->data[0] == MICROBIT_DFU_OPCODE_START_DFU)
{
uBit.display.stopAnimation();
uBit.display.clear();
#if CONFIG_ENABLED(MICROBIT_DBG)
uBit.serial.printf(" ACTIVATING BOOTLOADER.\n");
#endif
// Perform an explicit disconnection to assist our peer to reconnect to the DFU service
ble.disconnect(Gap::REMOTE_DEV_TERMINATION_DUE_TO_POWER_OFF);
wait_ms(1000);
// Call bootloader_start implicitly trough a event handler call
// it is a work around for bootloader_start not being public in sdk 8.1
ble_dfu_t p_dfu;
ble_dfu_evt_t p_evt;
p_dfu.conn_handle = params->connHandle;
p_evt.ble_dfu_evt_type = BLE_DFU_START;
dfu_app_on_dfu_evt(&p_dfu, &p_evt);
}
}
}
/**
* UUID definitions for BLE Services and Characteristics.
*/
const uint8_t MicroBitDFUServiceUUID[] = {
0xe9,0x5d,0x93,0xb0,0x25,0x1d,0x47,0x0a,0xa0,0x62,0xfa,0x19,0x22,0xdf,0xa9,0xa8
};
const uint8_t MicroBitDFUServiceControlCharacteristicUUID[] = {
0xe9,0x5d,0x93,0xb1,0x25,0x1d,0x47,0x0a,0xa0,0x62,0xfa,0x19,0x22,0xdf,0xa9,0xa8
};
<|endoftext|> |
<commit_before>#include <common/SFLogger.h>
#include "QMCommonFunc.h"
#include "QueryParser.h"
#include <glog/logging.h>
#include <fstream>
namespace sf1r
{
boost::shared_ptr<izenelib::am::rde_hash<izenelib::util::UString,bool> >
QueryUtility::restrictTermDicPtr_;
boost::shared_ptr<izenelib::am::rde_hash<termid_t,bool> >
QueryUtility::restrictTermIdDicPtr_;
std::string QueryUtility::dicPath_;
boost::shared_ptr<izenelib::ir::idmanager::IDManager> QueryUtility::idManager_;
boost::shared_mutex QueryUtility::sharedMutex_;
bool QueryUtility::reloadRestrictTermDictionary(void)
{
if (dicPath_.empty() || idManager_ == NULL )
{
LOG(ERROR)<<"Restict dictionary load failed";
return false;
}
return buildRestrictTermDictionary(dicPath_, idManager_);
}
bool QueryUtility::buildRestrictTermDictionary(const std::string& dicPath,
const boost::shared_ptr<izenelib::ir::idmanager::IDManager>& idManager)
{
// Write Lock
boost::upgrade_lock<boost::shared_mutex> lock(sharedMutex_);
boost::upgrade_to_unique_lock<boost::shared_mutex> uniqueLock(lock);
{
restrictTermDicPtr_.reset(new izenelib::am::rde_hash<izenelib::util::UString,bool>());
restrictTermIdDicPtr_.reset(new izenelib::am::rde_hash<termid_t,bool>());
// ---------------------------- [ Build restrictTermIdList ]
// TODO : Currently Encoding type is following the encoding type of KMA.
izenelib::util::UString::EncodingType encodingType = izenelib::util::UString::CP949;
std::ifstream fpin( dicPath.c_str() );
if ( !fpin.is_open() )
{
LOG(ERROR) << "[QueryUtility] Warning : (Line " << __LINE__
<< ") : Restrict word ditionary File(" << dicPath << ") is not opened."
<< std::endl;
return false;
}
while( fpin.good() )
{
termid_t termId;
std::string restrictTerm;
getline( fpin, restrictTerm);
if (restrictTerm.empty() || restrictTerm[0] == ';')
continue;
izenelib::util::UString restrictUTerm(restrictTerm, encodingType);
idManager->getTermIdByTermString( restrictUTerm, termId );
LOG(INFO) << "[[[[[[[ Restrict keyword : ";
restrictUTerm.displayStringValue(izenelib::util::UString::UTF_8, std::cerr);
std::cerr << std::endl;
QueryUtility::restrictTermDicPtr_->insert(restrictUTerm, true);
QueryUtility::restrictTermIdDicPtr_->insert(termId, true);
}
fpin.close();
}
// Set dicPath and idmanager if dictionary loading is successful.
dicPath_ = dicPath;
idManager_ = idManager;
return true;
} // end - buildRestrictTermDictionary()
bool QueryUtility::isRestrictWord(const izenelib::util::UString& inputTerm)
{
boost::shared_lock<boost::shared_mutex> lock(sharedMutex_);
if( !QueryUtility::restrictTermDicPtr_ ) return false;
if ( QueryUtility::restrictTermDicPtr_->find( inputTerm ) != NULL )
{
std::string restrictKeyword;
inputTerm.convertString(restrictKeyword, izenelib::util::UString::UTF_8); // XXX
LOG(WARNING) << "[QueryUtility] Warning : Restricted Keyword (" << restrictKeyword
<< ") occurs" << endl;
return true;
}
return false;
} // end - isRestrictWord()
bool QueryUtility::isRestrictId(termid_t termId)
{
boost::shared_lock<boost::shared_mutex> lock(sharedMutex_);
if ( QueryUtility::restrictTermIdDicPtr_->find( termId ) != NULL )
{
LOG(WARNING) << "[QueryUtility] Warning : Restricted termid (" << termId
<< ") occurs" << endl;
return true;
}
return false;
} // end - isRestrictId()
void QueryUtility::getMergedUniqueTokens(
const std::vector<izenelib::util::UString>& inputTokens,
const izenelib::util::UString& rawString,
boost::shared_ptr<LAManager> laManager,
std::vector<izenelib::util::UString>& resultTokens,
bool useOriginalQuery
)
{
std::vector<izenelib::util::UString> tmpResultTokens;
std::set<izenelib::util::UString> queryTermSet;
useOriginalQuery = true;
//insert original query string in its form
if ( useOriginalQuery )
queryTermSet.insert(rawString);
{
// get tokenized query terms form LAManager
la::TermList termList;
AnalysisInfo analysisInfo;
laManager->getTermList(rawString, analysisInfo, termList );
for (la::TermList::iterator p = termList.begin(); p != termList.end(); ++p)
{
QueryParser::removeEscapeChar(p->text_);
queryTermSet.insert(p->text_);
}
}
//insert input Tokens
std::vector<izenelib::util::UString>::const_iterator termIter = inputTokens.begin();
for (; termIter != inputTokens.end(); ++termIter)
queryTermSet.insert(*termIter);
//pack all in one vector with word-restriction processing
std::set<izenelib::util::UString>::iterator iter = queryTermSet.begin();
for (; iter != queryTermSet.end(); ++iter)
{
if ( QueryUtility::isRestrictWord( *iter ) )
continue;
tmpResultTokens.push_back(*iter);
}
resultTokens.swap(tmpResultTokens);
} // end - getMergedUniqueTokens()
void QueryUtility::getMergedUniqueTokens(
const izenelib::util::UString& rawString,
boost::shared_ptr<LAManager> laManager,
std::vector<izenelib::util::UString>& resultTokens,
bool useOriginalQuery
)
{
QueryUtility::getMergedUniqueTokens(
std::vector<izenelib::util::UString>(),
rawString,
laManager,
resultTokens,
useOriginalQuery
);
} // end - getMergedUniqueTokens()
} // end - namespace sf1r
<commit_msg>in QueryUtility::getMergedUniqueTokens(), to allow argument "laManager" be passed as NULL pointer, add NULL pointer check before calling its method.<commit_after>#include <common/SFLogger.h>
#include "QMCommonFunc.h"
#include "QueryParser.h"
#include <glog/logging.h>
#include <fstream>
namespace sf1r
{
boost::shared_ptr<izenelib::am::rde_hash<izenelib::util::UString,bool> >
QueryUtility::restrictTermDicPtr_;
boost::shared_ptr<izenelib::am::rde_hash<termid_t,bool> >
QueryUtility::restrictTermIdDicPtr_;
std::string QueryUtility::dicPath_;
boost::shared_ptr<izenelib::ir::idmanager::IDManager> QueryUtility::idManager_;
boost::shared_mutex QueryUtility::sharedMutex_;
bool QueryUtility::reloadRestrictTermDictionary(void)
{
if (dicPath_.empty() || idManager_ == NULL )
{
LOG(ERROR)<<"Restict dictionary load failed";
return false;
}
return buildRestrictTermDictionary(dicPath_, idManager_);
}
bool QueryUtility::buildRestrictTermDictionary(const std::string& dicPath,
const boost::shared_ptr<izenelib::ir::idmanager::IDManager>& idManager)
{
// Write Lock
boost::upgrade_lock<boost::shared_mutex> lock(sharedMutex_);
boost::upgrade_to_unique_lock<boost::shared_mutex> uniqueLock(lock);
{
restrictTermDicPtr_.reset(new izenelib::am::rde_hash<izenelib::util::UString,bool>());
restrictTermIdDicPtr_.reset(new izenelib::am::rde_hash<termid_t,bool>());
// ---------------------------- [ Build restrictTermIdList ]
// TODO : Currently Encoding type is following the encoding type of KMA.
izenelib::util::UString::EncodingType encodingType = izenelib::util::UString::CP949;
std::ifstream fpin( dicPath.c_str() );
if ( !fpin.is_open() )
{
LOG(ERROR) << "[QueryUtility] Warning : (Line " << __LINE__
<< ") : Restrict word ditionary File(" << dicPath << ") is not opened."
<< std::endl;
return false;
}
while( fpin.good() )
{
termid_t termId;
std::string restrictTerm;
getline( fpin, restrictTerm);
if (restrictTerm.empty() || restrictTerm[0] == ';')
continue;
izenelib::util::UString restrictUTerm(restrictTerm, encodingType);
idManager->getTermIdByTermString( restrictUTerm, termId );
LOG(INFO) << "[[[[[[[ Restrict keyword : ";
restrictUTerm.displayStringValue(izenelib::util::UString::UTF_8, std::cerr);
std::cerr << std::endl;
QueryUtility::restrictTermDicPtr_->insert(restrictUTerm, true);
QueryUtility::restrictTermIdDicPtr_->insert(termId, true);
}
fpin.close();
}
// Set dicPath and idmanager if dictionary loading is successful.
dicPath_ = dicPath;
idManager_ = idManager;
return true;
} // end - buildRestrictTermDictionary()
bool QueryUtility::isRestrictWord(const izenelib::util::UString& inputTerm)
{
boost::shared_lock<boost::shared_mutex> lock(sharedMutex_);
if( !QueryUtility::restrictTermDicPtr_ ) return false;
if ( QueryUtility::restrictTermDicPtr_->find( inputTerm ) != NULL )
{
std::string restrictKeyword;
inputTerm.convertString(restrictKeyword, izenelib::util::UString::UTF_8); // XXX
LOG(WARNING) << "[QueryUtility] Warning : Restricted Keyword (" << restrictKeyword
<< ") occurs" << endl;
return true;
}
return false;
} // end - isRestrictWord()
bool QueryUtility::isRestrictId(termid_t termId)
{
boost::shared_lock<boost::shared_mutex> lock(sharedMutex_);
if ( QueryUtility::restrictTermIdDicPtr_->find( termId ) != NULL )
{
LOG(WARNING) << "[QueryUtility] Warning : Restricted termid (" << termId
<< ") occurs" << endl;
return true;
}
return false;
} // end - isRestrictId()
void QueryUtility::getMergedUniqueTokens(
const std::vector<izenelib::util::UString>& inputTokens,
const izenelib::util::UString& rawString,
boost::shared_ptr<LAManager> laManager,
std::vector<izenelib::util::UString>& resultTokens,
bool useOriginalQuery
)
{
std::vector<izenelib::util::UString> tmpResultTokens;
std::set<izenelib::util::UString> queryTermSet;
useOriginalQuery = true;
//insert original query string in its form
if ( useOriginalQuery )
queryTermSet.insert(rawString);
if (laManager)
{
// get tokenized query terms form LAManager
la::TermList termList;
AnalysisInfo analysisInfo;
laManager->getTermList(rawString, analysisInfo, termList );
for (la::TermList::iterator p = termList.begin(); p != termList.end(); ++p)
{
QueryParser::removeEscapeChar(p->text_);
queryTermSet.insert(p->text_);
}
}
//insert input Tokens
std::vector<izenelib::util::UString>::const_iterator termIter = inputTokens.begin();
for (; termIter != inputTokens.end(); ++termIter)
queryTermSet.insert(*termIter);
//pack all in one vector with word-restriction processing
std::set<izenelib::util::UString>::iterator iter = queryTermSet.begin();
for (; iter != queryTermSet.end(); ++iter)
{
if ( QueryUtility::isRestrictWord( *iter ) )
continue;
tmpResultTokens.push_back(*iter);
}
resultTokens.swap(tmpResultTokens);
} // end - getMergedUniqueTokens()
void QueryUtility::getMergedUniqueTokens(
const izenelib::util::UString& rawString,
boost::shared_ptr<LAManager> laManager,
std::vector<izenelib::util::UString>& resultTokens,
bool useOriginalQuery
)
{
QueryUtility::getMergedUniqueTokens(
std::vector<izenelib::util::UString>(),
rawString,
laManager,
resultTokens,
useOriginalQuery
);
} // end - getMergedUniqueTokens()
} // end - namespace sf1r
<|endoftext|> |
<commit_before>/**********************************************************************
* $Id$
*
* GEOS - Geometry Engine Open Source
* http://geos.refractions.net
*
* Copyright (C) 2001-2002 Vivid Solutions Inc.
* Copyright (C) 2005 Refractions Research Inc.
*
* This is free software; you can redistribute and/or modify it under
* the terms of the GNU Lesser General Public Licence as published
* by the Free Software Foundation.
* See the COPYING file for more information.
*
**********************************************************************
*
* Last port: operation/buffer/BufferSubgraph.java rev. 1.17
*
**********************************************************************/
#include <cassert>
#include <vector>
#include <list>
#include <geos/opOverlay.h> // FIXME: reduce this include
#include <geos/operation/buffer/BufferSubgraph.h>
#include <geos/geom/Envelope.h>
#include <geos/geomgraph/Node.h>
#include <geos/geomgraph/DirectedEdge.h>
#ifndef GEOS_DEBUG
#define GEOS_DEBUG 0
#endif
using namespace std;
using namespace geos::geomgraph;
using namespace geos::noding;
using namespace geos::algorithm;
using namespace geos::operation::overlay;
using namespace geos::geom;
namespace geos {
namespace operation { // geos.operation
namespace buffer { // geos.operation.buffer
// Argument is unused
BufferSubgraph::BufferSubgraph(CGAlgorithms *cga):
rightMostCoord(NULL),
env(NULL)
{
}
BufferSubgraph::~BufferSubgraph()
{
delete env;
}
/*public*/
void
BufferSubgraph::create(Node *node)
{
addReachable(node);
finder.findEdge(&dirEdgeList);
rightMostCoord=&(finder.getCoordinate());
}
/*private*/
void
BufferSubgraph::addReachable(Node *startNode)
{
vector<Node*> nodeStack;
nodeStack.push_back(startNode);
while (!nodeStack.empty()) {
Node *node=nodeStack.back();
nodeStack.pop_back();
add(node, &nodeStack);
}
}
/*private*/
void
BufferSubgraph::add(Node *node, vector<Node*> *nodeStack)
{
node->setVisited(true);
nodes.push_back(node);
EdgeEndStar *ees=node->getEdges();
EdgeEndStar::iterator it=ees->begin();
EdgeEndStar::iterator endIt=ees->end();
for( ; it!=endIt; ++it)
{
DirectedEdge *de=(DirectedEdge*) (*it);
dirEdgeList.push_back(de);
DirectedEdge *sym=de->getSym();
Node *symNode=sym->getNode();
/**
* NOTE: this is a depth-first traversal of the graph.
* This will cause a large depth of recursion.
* It might be better to do a breadth-first traversal.
*/
if (! symNode->isVisited()) nodeStack->push_back(symNode);
}
}
/*private*/
void
BufferSubgraph::clearVisitedEdges()
{
for(unsigned int i=0; i<dirEdgeList.size(); ++i)
{
DirectedEdge *de=dirEdgeList[i];
de->setVisited(false);
}
}
/*public*/
void
BufferSubgraph::computeDepth(int outsideDepth)
{
clearVisitedEdges();
// find an outside edge to assign depth to
DirectedEdge *de=finder.getEdge();
#if GEOS_DEBUG
cerr<<"outside depth: "<<outsideDepth<<endl;
#endif
//Node *n=de->getNode();
//Label *label=de->getLabel();
// right side of line returned by finder is on the outside
de->setEdgeDepths(Position::RIGHT, outsideDepth);
copySymDepths(de);
//computeNodeDepth(n, de);
computeDepths(de);
}
void
BufferSubgraph::computeNodeDepth(Node *n)
// throw(TopologyException *)
{
// find a visited dirEdge to start at
DirectedEdge *startEdge=NULL;
DirectedEdgeStar *ees=(DirectedEdgeStar *)n->getEdges();
EdgeEndStar::iterator endIt=ees->end();
EdgeEndStar::iterator it=ees->begin();
for(; it!=endIt; ++it)
{
DirectedEdge *de=(DirectedEdge*)*it;
if (de->isVisited() || de->getSym()->isVisited()) {
startEdge=de;
break;
}
}
// MD - testing Result: breaks algorithm
//if (startEdge==null) return;
assert(startEdge!=NULL); // unable to find edge to compute depths at n->getCoordinate()
ees->computeDepths(startEdge);
// copy depths to sym edges
for(it=ees->begin(); it!=endIt; ++it)
{
DirectedEdge *de=(DirectedEdge*) (*it);
de->setVisited(true);
copySymDepths(de);
}
}
/*private*/
void
BufferSubgraph::copySymDepths(DirectedEdge *de)
{
#if GEOS_DEBUG
cerr << "copySymDepths: " << de->getDepth(Position::LEFT)
<< ", " << de->getDepth(Position::RIGHT)
<< endl;
#endif
DirectedEdge *sym=de->getSym();
sym->setDepth(Position::LEFT, de->getDepth(Position::RIGHT));
sym->setDepth(Position::RIGHT, de->getDepth(Position::LEFT));
}
/*public*/
void
BufferSubgraph::findResultEdges()
{
#if GEOS_DEBUG
cerr<<"BufferSubgraph::findResultEdges got "<<dirEdgeList.size()<<" edges"<<endl;
#endif
for(unsigned int i=0; i<dirEdgeList.size(); ++i)
{
DirectedEdge *de=dirEdgeList[i];
/**
* Select edges which have an interior depth on the RHS
* and an exterior depth on the LHS.
* Note that because of weird rounding effects there may be
* edges which have negative depths! Negative depths
* count as "outside".
*/
// <FIX> - handle negative depths
#if GEOS_DEBUG
cerr << " dirEdge "<<i<<": " << de->printEdge() << endl
<< " depth right: " << de->getDepth(Position::RIGHT) << endl
<< " depth left: " << de->getDepth(Position::LEFT) << endl
<< " interiorAreaEdge: " << de->isInteriorAreaEdge()<<endl;
#endif
if ( de->getDepth(Position::RIGHT)>=1
&& de->getDepth(Position::LEFT)<=0
&& !de->isInteriorAreaEdge()) {
de->setInResult(true);
#if GEOS_DEBUG
cerr<<" IN RESULT"<<endl;
#endif
}
}
}
/*public*/
int
BufferSubgraph::compareTo(BufferSubgraph *graph)
{
if (rightMostCoord->x<graph->rightMostCoord->x) {
return -1;
}
if (rightMostCoord->x>graph->rightMostCoord->x) {
return 1;
}
return 0;
}
/*private*/
void
BufferSubgraph::computeDepths(DirectedEdge *startEdge)
{
set<Node *> nodesVisited;
list<Node*> nodeQueue; // Used to be a vector
Node *startNode=startEdge->getNode();
nodeQueue.push_back(startNode);
//nodesVisited.push_back(startNode);
nodesVisited.insert(startNode);
startEdge->setVisited(true);
while (! nodeQueue.empty())
{
//System.out.println(nodes.size() + " queue: " + nodeQueue.size());
Node *n=nodeQueue.front(); // [0];
//nodeQueue.erase(nodeQueue.begin());
nodeQueue.pop_front();
nodesVisited.insert(n);
// compute depths around node, starting at this edge since it has depths assigned
computeNodeDepth(n);
// add all adjacent nodes to process queue,
// unless the node has been visited already
EdgeEndStar *ees=n->getEdges();
EdgeEndStar::iterator endIt=ees->end();
EdgeEndStar::iterator it=ees->begin();
for(; it!=endIt; ++it)
{
DirectedEdge *de=(DirectedEdge*) (*it);
DirectedEdge *sym=de->getSym();
if (sym->isVisited()) continue;
Node *adjNode=sym->getNode();
//if (! contains(nodesVisited,adjNode))
if(nodesVisited.insert(adjNode).second)
{
nodeQueue.push_back(adjNode);
//nodesVisited.insert(adjNode);
}
}
}
}
/*private*/
bool
BufferSubgraph::contains(set<Node*>&nodeSet, Node *node)
{
//bool result=false;
if ( nodeSet.find(node) != nodeSet.end() ) return true;
return false;
}
/*public*/
Envelope *
BufferSubgraph::getEnvelope()
{
if (env == NULL) {
env = new Envelope();
unsigned int size = dirEdgeList.size();
for(unsigned int i=0; i<size; ++i)
{
DirectedEdge *dirEdge=dirEdgeList[i];
const CoordinateSequence *pts = dirEdge->getEdge()->getCoordinates();
int n = pts->getSize()-1;
for (int j=0; j<n; ++j) {
env->expandToInclude(pts->getAt(j));
}
}
}
return env;
}
std::ostream& operator<< (std::ostream& os, const BufferSubgraph& bs)
{
os << "BufferSubgraph[" << &bs << "] "
<< bs.nodes.size() << " nodes, "
<< bs.dirEdgeList.size() << " directed edges" << std::endl;
for (unsigned int i=0, n=bs.nodes.size(); i<n; i++)
os << " Node " << i << ": " << bs.nodes[i]->print() << std::endl;
for (unsigned int i=0, n=bs.dirEdgeList.size(); i<n; i++)
{
os << " DirEdge " << i << ": " << std::endl
<< bs.dirEdgeList[i]->printEdge() << std::endl;
}
return os;
}
} // namespace geos.operation.buffer
} // namespace geos.operation
} // namespace geos
/**********************************************************************
* $Log$
* Revision 1.28 2006/03/15 11:39:45 strk
* comments cleanup, changed computeDepths to use a list<> rather then a vector (performance related)
*
* Revision 1.27 2006/03/14 17:10:14 strk
* cleanups
*
* Revision 1.26 2006/03/14 14:16:52 strk
* operator<< for BufferSubgraph, more debugging calls
*
* Revision 1.25 2006/03/14 00:19:40 strk
* opBuffer.h split, streamlined headers in some (not all) files in operation/buffer/
*
* Revision 1.24 2006/03/06 19:40:47 strk
* geos::util namespace. New GeometryCollection::iterator interface, many cleanups.
*
* Revision 1.23 2006/03/03 10:46:21 strk
* Removed 'using namespace' from headers, added missing headers in .cpp files, removed useless includes in headers (bug#46)
*
* Revision 1.22 2006/03/02 12:12:01 strk
* Renamed DEBUG macros to GEOS_DEBUG, all wrapped in #ifndef block to allow global override (bug#43)
*
* Revision 1.21 2006/02/19 19:46:49 strk
* Packages <-> namespaces mapping for most GEOS internal code (uncomplete, but working). Dir-level libs for index/ subdirs.
*
* Revision 1.20 2005/11/29 00:48:35 strk
* Removed edgeList cache from EdgeEndRing. edgeMap is enough.
* Restructured iterated access by use of standard ::iterator abstraction
* with scoped typedefs.
*
* Revision 1.19 2005/11/08 20:12:44 strk
* Memory overhead reductions in buffer operations.
*
**********************************************************************/
<commit_msg>Changed operator<< to use operator<< for Nodes<commit_after>/**********************************************************************
* $Id$
*
* GEOS - Geometry Engine Open Source
* http://geos.refractions.net
*
* Copyright (C) 2001-2002 Vivid Solutions Inc.
* Copyright (C) 2005 Refractions Research Inc.
*
* This is free software; you can redistribute and/or modify it under
* the terms of the GNU Lesser General Public Licence as published
* by the Free Software Foundation.
* See the COPYING file for more information.
*
**********************************************************************
*
* Last port: operation/buffer/BufferSubgraph.java rev. 1.17
*
**********************************************************************/
#include <cassert>
#include <vector>
#include <list>
#include <geos/opOverlay.h> // FIXME: reduce this include
#include <geos/operation/buffer/BufferSubgraph.h>
#include <geos/geom/Envelope.h>
#include <geos/geomgraph/Node.h>
#include <geos/geomgraph/DirectedEdge.h>
#ifndef GEOS_DEBUG
#define GEOS_DEBUG 0
#endif
using namespace std;
using namespace geos::geomgraph;
using namespace geos::noding;
using namespace geos::algorithm;
using namespace geos::operation::overlay;
using namespace geos::geom;
namespace geos {
namespace operation { // geos.operation
namespace buffer { // geos.operation.buffer
// Argument is unused
BufferSubgraph::BufferSubgraph(CGAlgorithms *cga):
rightMostCoord(NULL),
env(NULL)
{
}
BufferSubgraph::~BufferSubgraph()
{
delete env;
}
/*public*/
void
BufferSubgraph::create(Node *node)
{
addReachable(node);
finder.findEdge(&dirEdgeList);
rightMostCoord=&(finder.getCoordinate());
}
/*private*/
void
BufferSubgraph::addReachable(Node *startNode)
{
vector<Node*> nodeStack;
nodeStack.push_back(startNode);
while (!nodeStack.empty()) {
Node *node=nodeStack.back();
nodeStack.pop_back();
add(node, &nodeStack);
}
}
/*private*/
void
BufferSubgraph::add(Node *node, vector<Node*> *nodeStack)
{
node->setVisited(true);
nodes.push_back(node);
EdgeEndStar *ees=node->getEdges();
EdgeEndStar::iterator it=ees->begin();
EdgeEndStar::iterator endIt=ees->end();
for( ; it!=endIt; ++it)
{
DirectedEdge *de=(DirectedEdge*) (*it);
dirEdgeList.push_back(de);
DirectedEdge *sym=de->getSym();
Node *symNode=sym->getNode();
/**
* NOTE: this is a depth-first traversal of the graph.
* This will cause a large depth of recursion.
* It might be better to do a breadth-first traversal.
*/
if (! symNode->isVisited()) nodeStack->push_back(symNode);
}
}
/*private*/
void
BufferSubgraph::clearVisitedEdges()
{
for(unsigned int i=0; i<dirEdgeList.size(); ++i)
{
DirectedEdge *de=dirEdgeList[i];
de->setVisited(false);
}
}
/*public*/
void
BufferSubgraph::computeDepth(int outsideDepth)
{
clearVisitedEdges();
// find an outside edge to assign depth to
DirectedEdge *de=finder.getEdge();
#if GEOS_DEBUG
cerr<<"outside depth: "<<outsideDepth<<endl;
#endif
//Node *n=de->getNode();
//Label *label=de->getLabel();
// right side of line returned by finder is on the outside
de->setEdgeDepths(Position::RIGHT, outsideDepth);
copySymDepths(de);
//computeNodeDepth(n, de);
computeDepths(de);
}
void
BufferSubgraph::computeNodeDepth(Node *n)
// throw(TopologyException *)
{
// find a visited dirEdge to start at
DirectedEdge *startEdge=NULL;
DirectedEdgeStar *ees=(DirectedEdgeStar *)n->getEdges();
EdgeEndStar::iterator endIt=ees->end();
EdgeEndStar::iterator it=ees->begin();
for(; it!=endIt; ++it)
{
DirectedEdge *de=(DirectedEdge*)*it;
if (de->isVisited() || de->getSym()->isVisited()) {
startEdge=de;
break;
}
}
// MD - testing Result: breaks algorithm
//if (startEdge==null) return;
assert(startEdge!=NULL); // unable to find edge to compute depths at n->getCoordinate()
ees->computeDepths(startEdge);
// copy depths to sym edges
for(it=ees->begin(); it!=endIt; ++it)
{
DirectedEdge *de=(DirectedEdge*) (*it);
de->setVisited(true);
copySymDepths(de);
}
}
/*private*/
void
BufferSubgraph::copySymDepths(DirectedEdge *de)
{
#if GEOS_DEBUG
cerr << "copySymDepths: " << de->getDepth(Position::LEFT)
<< ", " << de->getDepth(Position::RIGHT)
<< endl;
#endif
DirectedEdge *sym=de->getSym();
sym->setDepth(Position::LEFT, de->getDepth(Position::RIGHT));
sym->setDepth(Position::RIGHT, de->getDepth(Position::LEFT));
}
/*public*/
void
BufferSubgraph::findResultEdges()
{
#if GEOS_DEBUG
cerr<<"BufferSubgraph::findResultEdges got "<<dirEdgeList.size()<<" edges"<<endl;
#endif
for(unsigned int i=0; i<dirEdgeList.size(); ++i)
{
DirectedEdge *de=dirEdgeList[i];
/**
* Select edges which have an interior depth on the RHS
* and an exterior depth on the LHS.
* Note that because of weird rounding effects there may be
* edges which have negative depths! Negative depths
* count as "outside".
*/
// <FIX> - handle negative depths
#if GEOS_DEBUG
cerr << " dirEdge "<<i<<": " << de->printEdge() << endl
<< " depth right: " << de->getDepth(Position::RIGHT) << endl
<< " depth left: " << de->getDepth(Position::LEFT) << endl
<< " interiorAreaEdge: " << de->isInteriorAreaEdge()<<endl;
#endif
if ( de->getDepth(Position::RIGHT)>=1
&& de->getDepth(Position::LEFT)<=0
&& !de->isInteriorAreaEdge()) {
de->setInResult(true);
#if GEOS_DEBUG
cerr<<" IN RESULT"<<endl;
#endif
}
}
}
/*public*/
int
BufferSubgraph::compareTo(BufferSubgraph *graph)
{
if (rightMostCoord->x<graph->rightMostCoord->x) {
return -1;
}
if (rightMostCoord->x>graph->rightMostCoord->x) {
return 1;
}
return 0;
}
/*private*/
void
BufferSubgraph::computeDepths(DirectedEdge *startEdge)
{
set<Node *> nodesVisited;
list<Node*> nodeQueue; // Used to be a vector
Node *startNode=startEdge->getNode();
nodeQueue.push_back(startNode);
//nodesVisited.push_back(startNode);
nodesVisited.insert(startNode);
startEdge->setVisited(true);
while (! nodeQueue.empty())
{
//System.out.println(nodes.size() + " queue: " + nodeQueue.size());
Node *n=nodeQueue.front(); // [0];
//nodeQueue.erase(nodeQueue.begin());
nodeQueue.pop_front();
nodesVisited.insert(n);
// compute depths around node, starting at this edge since it has depths assigned
computeNodeDepth(n);
// add all adjacent nodes to process queue,
// unless the node has been visited already
EdgeEndStar *ees=n->getEdges();
EdgeEndStar::iterator endIt=ees->end();
EdgeEndStar::iterator it=ees->begin();
for(; it!=endIt; ++it)
{
DirectedEdge *de=(DirectedEdge*) (*it);
DirectedEdge *sym=de->getSym();
if (sym->isVisited()) continue;
Node *adjNode=sym->getNode();
//if (! contains(nodesVisited,adjNode))
if(nodesVisited.insert(adjNode).second)
{
nodeQueue.push_back(adjNode);
//nodesVisited.insert(adjNode);
}
}
}
}
/*private*/
bool
BufferSubgraph::contains(set<Node*>&nodeSet, Node *node)
{
//bool result=false;
if ( nodeSet.find(node) != nodeSet.end() ) return true;
return false;
}
/*public*/
Envelope *
BufferSubgraph::getEnvelope()
{
if (env == NULL) {
env = new Envelope();
unsigned int size = dirEdgeList.size();
for(unsigned int i=0; i<size; ++i)
{
DirectedEdge *dirEdge=dirEdgeList[i];
const CoordinateSequence *pts = dirEdge->getEdge()->getCoordinates();
int n = pts->getSize()-1;
for (int j=0; j<n; ++j) {
env->expandToInclude(pts->getAt(j));
}
}
}
return env;
}
std::ostream& operator<< (std::ostream& os, const BufferSubgraph& bs)
{
os << "BufferSubgraph[" << &bs << "] "
<< bs.nodes.size() << " nodes, "
<< bs.dirEdgeList.size() << " directed edges" << std::endl;
for (unsigned int i=0, n=bs.nodes.size(); i<n; i++)
os << " Node " << i << ": " << *(bs.nodes[i]) << std::endl;
for (unsigned int i=0, n=bs.dirEdgeList.size(); i<n; i++)
{
os << " DirEdge " << i << ": " << std::endl
<< bs.dirEdgeList[i]->printEdge() << std::endl;
}
return os;
}
} // namespace geos.operation.buffer
} // namespace geos.operation
} // namespace geos
/**********************************************************************
* $Log$
* Revision 1.29 2006/03/15 17:33:39 strk
* Changed operator<< to use operator<< for Nodes
*
* Revision 1.28 2006/03/15 11:39:45 strk
* comments cleanup, changed computeDepths to use a list<> rather then a vector (performance related)
*
* Revision 1.27 2006/03/14 17:10:14 strk
* cleanups
*
* Revision 1.26 2006/03/14 14:16:52 strk
* operator<< for BufferSubgraph, more debugging calls
*
* Revision 1.25 2006/03/14 00:19:40 strk
* opBuffer.h split, streamlined headers in some (not all) files in operation/buffer/
*
* Revision 1.24 2006/03/06 19:40:47 strk
* geos::util namespace. New GeometryCollection::iterator interface, many cleanups.
*
* Revision 1.23 2006/03/03 10:46:21 strk
* Removed 'using namespace' from headers, added missing headers in .cpp files, removed useless includes in headers (bug#46)
*
* Revision 1.22 2006/03/02 12:12:01 strk
* Renamed DEBUG macros to GEOS_DEBUG, all wrapped in #ifndef block to allow global override (bug#43)
*
* Revision 1.21 2006/02/19 19:46:49 strk
* Packages <-> namespaces mapping for most GEOS internal code (uncomplete, but working). Dir-level libs for index/ subdirs.
*
* Revision 1.20 2005/11/29 00:48:35 strk
* Removed edgeList cache from EdgeEndRing. edgeMap is enough.
* Restructured iterated access by use of standard ::iterator abstraction
* with scoped typedefs.
*
* Revision 1.19 2005/11/08 20:12:44 strk
* Memory overhead reductions in buffer operations.
*
**********************************************************************/
<|endoftext|> |
<commit_before>// $Id$
AliAnalysisTaskSE* AddTaskJetPreparation(
const char* dataType = "ESD",
const char* periodstr = "LHC11h",
const char* usedTracks = "PicoTracks",
const char* usedMCParticles = "MCParticlesSelected",
const char* usedClusters = "CaloClusters",
const char* outClusName = "CaloClustersCorr",
const Double_t hadcorr = 2.0,
const Double_t Eexcl = 0.00,
const Double_t phiMatch = 0.03,
const Double_t etaMatch = 0.015,
const Double_t minPtEt = 0.15,
const UInt_t pSel = AliVEvent::kAny,
const Bool_t trackclus = kTRUE,
const Bool_t doHistos = kFALSE,
const Bool_t makePicoTracks = kTRUE,
const Bool_t makeTrigger = kTRUE,
const Bool_t isEmcalTrain = kFALSE,
const Double_t trackeff = 1.0
)
{
// Add task macros for all jet related helper tasks.
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr)
{
Error("AddTaskJetPreparation","No analysis manager found.");
return 0;
}
// Set trackcuts according to period. Every period used should be definied here
TString period(periodstr);
TString clusterColName(usedClusters);
TString particleColName(usedMCParticles);
TString dType(dataType);
if ((dType == "AOD") && (clusterColName == "CaloClusters"))
clusterColName = "caloClusters";
if ((dType == "ESD") && (clusterColName == "caloClusters"))
clusterColName = "CaloClusters";
if (makePicoTracks && (dType == "ESD" || dType == "AOD") )
{
TString inputTracks = "tracks";
if (dType == "ESD")
{
inputTracks = "HybridTracks";
TString trackCuts(Form("Hybrid_%s", period.Data()));
// Hybrid tracks maker for ESD
gROOT->LoadMacro("$ALICE_ROOT/PWG/EMCAL/macros/AddTaskEmcalEsdTpcTrack.C");
AliEmcalEsdTpcTrackTask *hybTask = AddTaskEmcalEsdTpcTrack(inputTracks.Data(),trackCuts.Data());
hybTask->SelectCollisionCandidates(pSel);
// Track propagator to extend track to the TPC boundaries
gROOT->LoadMacro("$ALICE_ROOT/PWG/EMCAL/macros/AddTaskEmcalTrackPropagator.C");
AliEmcalTrackPropagatorTask *propTask = AddTaskEmcalTrackPropagator(inputTracks.Data());
propTask->SelectCollisionCandidates(pSel);
}
// Produce PicoTracks
gROOT->LoadMacro("$ALICE_ROOT/PWG/EMCAL/macros/AddTaskEmcalPicoTrackMaker.C");
AliEmcalPicoTrackMaker *pTrackTask = AddTaskEmcalPicoTrackMaker("PicoTracks", inputTracks.Data(), period.Data());
pTrackTask->SelectCollisionCandidates(pSel);
pTrackTask->SetTrackEfficiency(trackeff);
}
// Produce particles used for hadronic correction
gROOT->LoadMacro("$ALICE_ROOT/PWG/EMCAL/macros/AddTaskEmcalParticleMaker.C");
AliEmcalParticleMaker *emcalParts = AddTaskEmcalParticleMaker(usedTracks,clusterColName.Data(),"EmcalTracks","EmcalClusters");
emcalParts->SelectCollisionCandidates(pSel);
// Trigger maker
if (makeTrigger) {
gROOT->LoadMacro("$ALICE_ROOT/PWG/EMCAL/macros/AddTaskEmcalTriggerMaker.C");
AliEmcalTriggerMaker *emcalTriggers = AddTaskEmcalTriggerMaker("EmcalTriggers");
emcalTriggers->SelectCollisionCandidates(pSel);
}
// Relate tracks and clusters
gROOT->LoadMacro("$ALICE_ROOT/PWG/EMCAL/macros/AddTaskEmcalClusTrackMatcher.C");
AliEmcalClusTrackMatcherTask *emcalClus = AddTaskEmcalClusTrackMatcher("EmcalTracks","EmcalClusters",0.1);
emcalClus->SelectCollisionCandidates(pSel);
if (isEmcalTrain)
RequestMemory(emcalClus,100*1024);
gROOT->LoadMacro("$ALICE_ROOT/PWGJE/EMCALJetTasks/macros/AddTaskHadCorr.C");
AliHadCorrTask *hCorr = AddTaskHadCorr("EmcalTracks","EmcalClusters",outClusName,hadcorr,minPtEt,phiMatch,etaMatch,Eexcl,trackclus,doHistos);
hCorr->SelectCollisionCandidates(pSel);
if (isEmcalTrain) {
if (doHistos)
RequestMemory(hCorr,500*1024);
}
// Produce MC particles
if(particleColName != "")
{
gROOT->LoadMacro("$ALICE_ROOT/PWG/EMCAL/macros/AddTaskMCTrackSelector.C");
AliEmcalMCTrackSelector *mcPartTask = AddTaskMCTrackSelector(particleColName.Data(), kFALSE, kFALSE);
mcPartTask->SelectCollisionCandidates(pSel);
}
// Return one task that represents the jet preparation on LEGO trains
return emcalParts;
}
<commit_msg>Propagate to 440 in case of ESD<commit_after>// $Id$
AliAnalysisTaskSE* AddTaskJetPreparation(
const char* dataType = "ESD",
const char* periodstr = "LHC11h",
const char* usedTracks = "PicoTracks",
const char* usedMCParticles = "MCParticlesSelected",
const char* usedClusters = "CaloClusters",
const char* outClusName = "CaloClustersCorr",
const Double_t hadcorr = 2.0,
const Double_t Eexcl = 0.00,
const Double_t phiMatch = 0.03,
const Double_t etaMatch = 0.015,
const Double_t minPtEt = 0.15,
const UInt_t pSel = AliVEvent::kAny,
const Bool_t trackclus = kTRUE,
const Bool_t doHistos = kFALSE,
const Bool_t makePicoTracks = kTRUE,
const Bool_t makeTrigger = kTRUE,
const Bool_t isEmcalTrain = kFALSE,
const Double_t trackeff = 1.0
)
{
// Add task macros for all jet related helper tasks.
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr)
{
Error("AddTaskJetPreparation","No analysis manager found.");
return 0;
}
// Set trackcuts according to period. Every period used should be definied here
TString period(periodstr);
TString clusterColName(usedClusters);
TString particleColName(usedMCParticles);
TString dType(dataType);
if ((dType == "AOD") && (clusterColName == "CaloClusters"))
clusterColName = "caloClusters";
if ((dType == "ESD") && (clusterColName == "caloClusters"))
clusterColName = "CaloClusters";
if (makePicoTracks && (dType == "ESD" || dType == "AOD") )
{
TString inputTracks = "tracks";
if (dType == "ESD")
{
inputTracks = "HybridTracks";
TString trackCuts(Form("Hybrid_%s", period.Data()));
// Hybrid tracks maker for ESD
gROOT->LoadMacro("$ALICE_ROOT/PWG/EMCAL/macros/AddTaskEmcalEsdTpcTrack.C");
AliEmcalEsdTpcTrackTask *hybTask = AddTaskEmcalEsdTpcTrack(inputTracks.Data(),trackCuts.Data());
hybTask->SelectCollisionCandidates(pSel);
// Track propagator to extend track to the TPC boundaries
gROOT->LoadMacro("$ALICE_ROOT/PWG/EMCAL/macros/AddTaskEmcalTrackPropagator.C");
AliEmcalTrackPropagatorTask *propTask = AddTaskEmcalTrackPropagator(inputTracks.Data(),440.);
propTask->SelectCollisionCandidates(pSel);
}
// Produce PicoTracks
gROOT->LoadMacro("$ALICE_ROOT/PWG/EMCAL/macros/AddTaskEmcalPicoTrackMaker.C");
AliEmcalPicoTrackMaker *pTrackTask = AddTaskEmcalPicoTrackMaker("PicoTracks", inputTracks.Data(), period.Data());
pTrackTask->SelectCollisionCandidates(pSel);
pTrackTask->SetTrackEfficiency(trackeff);
}
// Produce particles used for hadronic correction
gROOT->LoadMacro("$ALICE_ROOT/PWG/EMCAL/macros/AddTaskEmcalParticleMaker.C");
AliEmcalParticleMaker *emcalParts = AddTaskEmcalParticleMaker(usedTracks,clusterColName.Data(),"EmcalTracks","EmcalClusters");
emcalParts->SelectCollisionCandidates(pSel);
// Trigger maker
if (makeTrigger) {
gROOT->LoadMacro("$ALICE_ROOT/PWG/EMCAL/macros/AddTaskEmcalTriggerMaker.C");
AliEmcalTriggerMaker *emcalTriggers = AddTaskEmcalTriggerMaker("EmcalTriggers");
emcalTriggers->SelectCollisionCandidates(pSel);
}
// Relate tracks and clusters
gROOT->LoadMacro("$ALICE_ROOT/PWG/EMCAL/macros/AddTaskEmcalClusTrackMatcher.C");
AliEmcalClusTrackMatcherTask *emcalClus = AddTaskEmcalClusTrackMatcher("EmcalTracks","EmcalClusters",0.1);
emcalClus->SelectCollisionCandidates(pSel);
if (isEmcalTrain)
RequestMemory(emcalClus,100*1024);
gROOT->LoadMacro("$ALICE_ROOT/PWGJE/EMCALJetTasks/macros/AddTaskHadCorr.C");
AliHadCorrTask *hCorr = AddTaskHadCorr("EmcalTracks","EmcalClusters",outClusName,hadcorr,minPtEt,phiMatch,etaMatch,Eexcl,trackclus,doHistos);
hCorr->SelectCollisionCandidates(pSel);
if (isEmcalTrain) {
if (doHistos)
RequestMemory(hCorr,500*1024);
}
// Produce MC particles
if(particleColName != "")
{
gROOT->LoadMacro("$ALICE_ROOT/PWG/EMCAL/macros/AddTaskMCTrackSelector.C");
AliEmcalMCTrackSelector *mcPartTask = AddTaskMCTrackSelector(particleColName.Data(), kFALSE, kFALSE);
mcPartTask->SelectCollisionCandidates(pSel);
}
// Return one task that represents the jet preparation on LEGO trains
return emcalParts;
}
<|endoftext|> |
<commit_before>//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2013, Image Engine Design Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// * Neither the name of Image Engine Design nor the names of any
// other contributors to this software 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.
//
//////////////////////////////////////////////////////////////////////////
#include "boost/filesystem/path.hpp"
#include "GEO/GEO_AttributeHandle.h"
#include "GU/GU_Detail.h"
#include "OBJ/OBJ_Node.h"
#include "OP/OP_Director.h"
#include "PRM/PRM_Include.h"
#include "PRM/PRM_SpareData.h"
#include "ROP/ROP_Error.h"
#include "IECore/LinkedScene.h"
#include "IECoreHoudini/Convert.h"
#include "IECoreHoudini/HoudiniScene.h"
#include "IECoreHoudini/ROP_SceneCacheWriter.h"
using namespace IECore;
using namespace IECoreHoudini;
const char *ROP_SceneCacheWriter::typeName = "ieSceneCacheWriter";
ROP_SceneCacheWriter::ROP_SceneCacheWriter( OP_Network *net, const char *name, OP_Operator *op )
: ROP_Node( net, name, op ), m_liveScene( 0 ), m_outScene( 0 )
{
}
ROP_SceneCacheWriter::~ROP_SceneCacheWriter()
{
}
OP_Node *ROP_SceneCacheWriter::create( OP_Network *net, const char *name, OP_Operator *op )
{
return new ROP_SceneCacheWriter( net, name, op );
}
PRM_Name ROP_SceneCacheWriter::pFile( "file", "File" );
PRM_Name ROP_SceneCacheWriter::pRootObject( "rootObject", "Root Object" );
PRM_Default ROP_SceneCacheWriter::fileDefault( 0, "$HIP/output.scc" );
PRM_Default ROP_SceneCacheWriter::rootObjectDefault( 0, "/obj" );
OP_TemplatePair *ROP_SceneCacheWriter::buildParameters()
{
static PRM_Template *thisTemplate = 0;
if ( !thisTemplate )
{
thisTemplate = new PRM_Template[3];
thisTemplate[0] = PRM_Template(
PRM_FILE, 1, &pFile, &fileDefault, 0, 0, 0, 0, 0,
"An SCC file to write, based on the Houdini hierarchy defined by the Root Object provided."
);
thisTemplate[1] = PRM_Template(
PRM_STRING, PRM_TYPE_DYNAMIC_PATH, 1, &pRootObject, &rootObjectDefault, 0, 0, 0,
&PRM_SpareData::objPath, 0, "The node to use as the root of the SceneCache"
);
}
static OP_TemplatePair *templatePair = 0;
if ( !templatePair )
{
OP_TemplatePair *extraTemplatePair = new OP_TemplatePair( thisTemplate );
templatePair = new OP_TemplatePair( ROP_Node::getROPbaseTemplate(), extraTemplatePair );
}
return templatePair;
}
int ROP_SceneCacheWriter::startRender( int nframes, fpreal s, fpreal e )
{
UT_String nodePath;
evalString( nodePath, pRootObject.getToken(), 0, 0 );
UT_String value;
evalString( value, pFile.getToken(), 0, 0 );
std::string file = value.toStdString();
try
{
SceneInterface::Path emptyPath;
m_liveScene = new IECoreHoudini::HoudiniScene( nodePath, emptyPath, emptyPath );
// wrapping with a LinkedScene to ensure full expansion when writing the non-linked file
if ( boost::filesystem::path( file ).extension().string() != ".lscc" )
{
m_liveScene = new LinkedScene( m_liveScene );
}
}
catch ( IECore::Exception &e )
{
addError( ROP_MESSAGE, e.what() );
return false;
}
try
{
m_outScene = SceneInterface::create( file, IndexedIO::Write );
}
catch ( IECore::Exception &e )
{
addError( ROP_MESSAGE, ( "Could not create a writable IECore::SceneInterface at \"" + file + "\"" ).c_str() );
return false;
}
return true;
}
ROP_RENDER_CODE ROP_SceneCacheWriter::renderFrame( fpreal time, UT_Interrupt *boss )
{
SceneInterfacePtr outScene = m_outScene;
// we need to re-root the scene if its trying to cache a top level object
UT_String nodePath;
evalString( nodePath, pRootObject.getToken(), 0, 0 );
OBJ_Node *node = OPgetDirector()->findNode( nodePath )->castToOBJNode();
if ( node && node->getObjectType() == OBJ_GEOMETRY )
{
OP_Context context( CHgetEvalTime() );
const GU_Detail *geo = node->getRenderGeometry( context );
const GEO_AttributeHandle attrHandle = geo->getPrimAttribute( "name" );
bool reRoot = !attrHandle.isAttributeValid();
if ( attrHandle.isAttributeValid() )
{
const GA_ROAttributeRef attrRef( attrHandle.getAttribute() );
int numShapes = geo->getUniqueValueCount( attrRef );
bool reRoot = ( numShapes == 0 );
if ( numShapes == 1 )
{
const char *name = geo->getUniqueStringValue( attrRef, 0 );
if ( !strcmp( name, "" ) || !strcmp( name, "/" ) )
{
reRoot = true;
}
}
}
if ( reRoot )
{
outScene = m_outScene->createChild( node->getName().toStdString() );
}
}
return doWrite( m_liveScene, outScene, time );
}
ROP_RENDER_CODE ROP_SceneCacheWriter::endRender()
{
m_liveScene = 0;
m_outScene = 0;
return ROP_CONTINUE_RENDER;
}
ROP_RENDER_CODE ROP_SceneCacheWriter::doWrite( const SceneInterface *liveScene, SceneInterface *outScene, double time )
{
if ( liveScene != m_liveScene )
{
outScene->writeTransform( liveScene->readTransform( time ), time );
}
bool link = false;
SceneInterface::NameList attrs;
liveScene->attributeNames( attrs );
for ( SceneInterface::NameList::iterator it = attrs.begin(); it != attrs.end(); ++it )
{
outScene->writeAttribute( *it, liveScene->readAttribute( *it, time ), time );
if ( *it == LinkedScene::linkAttribute )
{
link = true;
}
}
// If this is a link, we exit now, since all other write calls will throw exceptions
if ( link )
{
return ROP_CONTINUE_RENDER;
}
SceneInterface::NameList tags;
liveScene->readTags( tags, false );
outScene->writeTags( tags );
if ( liveScene->hasObject() )
{
try
{
outScene->writeObject( liveScene->readObject( time ), time );
}
catch ( IECore::Exception &e )
{
addError( ROP_MESSAGE, e.what() );
return ROP_ABORT_RENDER;
}
}
SceneInterface::NameList children;
liveScene->childNames( children );
for ( SceneInterface::NameList::iterator it = children.begin(); it != children.end(); ++it )
{
ConstSceneInterfacePtr liveChild = liveScene->child( *it );
SceneInterfacePtr outChild = outScene->child( *it, SceneInterface::CreateIfMissing );
ROP_RENDER_CODE status = doWrite( liveChild, outChild, time );
if ( status != ROP_CONTINUE_RENDER )
{
return status;
}
}
return ROP_CONTINUE_RENDER;
}
<commit_msg>fixing bug with local variable<commit_after>//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2013, Image Engine Design Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// * Neither the name of Image Engine Design nor the names of any
// other contributors to this software 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.
//
//////////////////////////////////////////////////////////////////////////
#include "boost/filesystem/path.hpp"
#include "GEO/GEO_AttributeHandle.h"
#include "GU/GU_Detail.h"
#include "OBJ/OBJ_Node.h"
#include "OP/OP_Director.h"
#include "PRM/PRM_Include.h"
#include "PRM/PRM_SpareData.h"
#include "ROP/ROP_Error.h"
#include "IECore/LinkedScene.h"
#include "IECoreHoudini/Convert.h"
#include "IECoreHoudini/HoudiniScene.h"
#include "IECoreHoudini/ROP_SceneCacheWriter.h"
using namespace IECore;
using namespace IECoreHoudini;
const char *ROP_SceneCacheWriter::typeName = "ieSceneCacheWriter";
ROP_SceneCacheWriter::ROP_SceneCacheWriter( OP_Network *net, const char *name, OP_Operator *op )
: ROP_Node( net, name, op ), m_liveScene( 0 ), m_outScene( 0 )
{
}
ROP_SceneCacheWriter::~ROP_SceneCacheWriter()
{
}
OP_Node *ROP_SceneCacheWriter::create( OP_Network *net, const char *name, OP_Operator *op )
{
return new ROP_SceneCacheWriter( net, name, op );
}
PRM_Name ROP_SceneCacheWriter::pFile( "file", "File" );
PRM_Name ROP_SceneCacheWriter::pRootObject( "rootObject", "Root Object" );
PRM_Default ROP_SceneCacheWriter::fileDefault( 0, "$HIP/output.scc" );
PRM_Default ROP_SceneCacheWriter::rootObjectDefault( 0, "/obj" );
OP_TemplatePair *ROP_SceneCacheWriter::buildParameters()
{
static PRM_Template *thisTemplate = 0;
if ( !thisTemplate )
{
thisTemplate = new PRM_Template[3];
thisTemplate[0] = PRM_Template(
PRM_FILE, 1, &pFile, &fileDefault, 0, 0, 0, 0, 0,
"An SCC file to write, based on the Houdini hierarchy defined by the Root Object provided."
);
thisTemplate[1] = PRM_Template(
PRM_STRING, PRM_TYPE_DYNAMIC_PATH, 1, &pRootObject, &rootObjectDefault, 0, 0, 0,
&PRM_SpareData::objPath, 0, "The node to use as the root of the SceneCache"
);
}
static OP_TemplatePair *templatePair = 0;
if ( !templatePair )
{
OP_TemplatePair *extraTemplatePair = new OP_TemplatePair( thisTemplate );
templatePair = new OP_TemplatePair( ROP_Node::getROPbaseTemplate(), extraTemplatePair );
}
return templatePair;
}
int ROP_SceneCacheWriter::startRender( int nframes, fpreal s, fpreal e )
{
UT_String nodePath;
evalString( nodePath, pRootObject.getToken(), 0, 0 );
UT_String value;
evalString( value, pFile.getToken(), 0, 0 );
std::string file = value.toStdString();
try
{
SceneInterface::Path emptyPath;
m_liveScene = new IECoreHoudini::HoudiniScene( nodePath, emptyPath, emptyPath );
// wrapping with a LinkedScene to ensure full expansion when writing the non-linked file
if ( boost::filesystem::path( file ).extension().string() != ".lscc" )
{
m_liveScene = new LinkedScene( m_liveScene );
}
}
catch ( IECore::Exception &e )
{
addError( ROP_MESSAGE, e.what() );
return false;
}
try
{
m_outScene = SceneInterface::create( file, IndexedIO::Write );
}
catch ( IECore::Exception &e )
{
addError( ROP_MESSAGE, ( "Could not create a writable IECore::SceneInterface at \"" + file + "\"" ).c_str() );
return false;
}
return true;
}
ROP_RENDER_CODE ROP_SceneCacheWriter::renderFrame( fpreal time, UT_Interrupt *boss )
{
SceneInterfacePtr outScene = m_outScene;
// we need to re-root the scene if its trying to cache a top level object
UT_String nodePath;
evalString( nodePath, pRootObject.getToken(), 0, 0 );
OBJ_Node *node = OPgetDirector()->findNode( nodePath )->castToOBJNode();
if ( node && node->getObjectType() == OBJ_GEOMETRY )
{
OP_Context context( CHgetEvalTime() );
const GU_Detail *geo = node->getRenderGeometry( context );
const GEO_AttributeHandle attrHandle = geo->getPrimAttribute( "name" );
bool reRoot = !attrHandle.isAttributeValid();
if ( attrHandle.isAttributeValid() )
{
const GA_ROAttributeRef attrRef( attrHandle.getAttribute() );
int numShapes = geo->getUniqueValueCount( attrRef );
reRoot = ( numShapes == 0 );
if ( numShapes == 1 )
{
const char *name = geo->getUniqueStringValue( attrRef, 0 );
if ( !strcmp( name, "" ) || !strcmp( name, "/" ) )
{
reRoot = true;
}
}
}
if ( reRoot )
{
outScene = m_outScene->createChild( node->getName().toStdString() );
}
}
return doWrite( m_liveScene, outScene, time );
}
ROP_RENDER_CODE ROP_SceneCacheWriter::endRender()
{
m_liveScene = 0;
m_outScene = 0;
return ROP_CONTINUE_RENDER;
}
ROP_RENDER_CODE ROP_SceneCacheWriter::doWrite( const SceneInterface *liveScene, SceneInterface *outScene, double time )
{
if ( liveScene != m_liveScene )
{
outScene->writeTransform( liveScene->readTransform( time ), time );
}
bool link = false;
SceneInterface::NameList attrs;
liveScene->attributeNames( attrs );
for ( SceneInterface::NameList::iterator it = attrs.begin(); it != attrs.end(); ++it )
{
outScene->writeAttribute( *it, liveScene->readAttribute( *it, time ), time );
if ( *it == LinkedScene::linkAttribute )
{
link = true;
}
}
// If this is a link, we exit now, since all other write calls will throw exceptions
if ( link )
{
return ROP_CONTINUE_RENDER;
}
SceneInterface::NameList tags;
liveScene->readTags( tags, false );
outScene->writeTags( tags );
if ( liveScene->hasObject() )
{
try
{
outScene->writeObject( liveScene->readObject( time ), time );
}
catch ( IECore::Exception &e )
{
addError( ROP_MESSAGE, e.what() );
return ROP_ABORT_RENDER;
}
}
SceneInterface::NameList children;
liveScene->childNames( children );
for ( SceneInterface::NameList::iterator it = children.begin(); it != children.end(); ++it )
{
ConstSceneInterfacePtr liveChild = liveScene->child( *it );
SceneInterfacePtr outChild = outScene->child( *it, SceneInterface::CreateIfMissing );
ROP_RENDER_CODE status = doWrite( liveChild, outChild, time );
if ( status != ROP_CONTINUE_RENDER )
{
return status;
}
}
return ROP_CONTINUE_RENDER;
}
<|endoftext|> |
<commit_before>#include <IO/TinyPlyLoader/TinyPlyFileLoader.hpp>
#include <Core/Asset/FileData.hpp>
#include <tinyply.h>
#include <fstream>
#include <iostream>
#include <string>
const std::string plyExt( "ply" );
namespace Ra {
namespace IO {
using namespace Core::Utils; // log
using namespace Core::Asset; // Filedata
TinyPlyFileLoader::TinyPlyFileLoader() {}
TinyPlyFileLoader::~TinyPlyFileLoader() {}
std::vector<std::string> TinyPlyFileLoader::getFileExtensions() const {
return std::vector<std::string>( {"*." + plyExt} );
}
bool TinyPlyFileLoader::handleFileExtension( const std::string& extension ) const {
return extension.compare( plyExt ) == 0;
}
FileData* TinyPlyFileLoader::loadFile( const std::string& filename ) {
// Read the file and create a std::istringstream suitable
// for the lib -- tinyply does not perform any file i/o.
std::ifstream ss( filename, std::ios::binary );
// Parse the ASCII header fields
tinyply::PlyFile file;
file.parse_header( ss );
auto elements = file.get_elements();
if ( std::any_of( elements.begin(), elements.end(), []( const auto& e ) -> bool {
return e.name == "face" && e.size != 0;
} ) )
{
// Mesh found. Let the other loaders handle it
LOG( logINFO ) << "[TinyPLY] Faces found. Aborting" << std::endl;
return nullptr;
}
// we are now sure to have a point-cloud
FileData* fileData = new FileData( filename );
if ( !fileData->isInitialized() )
{
delete fileData;
LOG( logINFO ) << "[TinyPLY] Filedata cannot be initialized...";
return nullptr;
}
if ( fileData->isVerbose() )
{
LOG( logINFO ) << "[TinyPLY] File Loading begin...";
LOG( logINFO )
<< "........................................................................\n";
for ( auto c : file.get_comments() )
std::cout << "Comment: " << c;
for ( auto e : file.get_elements() )
{
LOG( logINFO ) << "element - " << e.name << " (" << e.size << ")";
for ( auto p : e.properties )
std::cout << "\tproperty - " << p.name << " ("
<< tinyply::PropertyTable[p.propertyType].str << ")";
}
LOG( logINFO )
<< "........................................................................\n";
}
// The count returns the number of instances of the property group. The vectors
// above will be resized into a multiple of the property group size as
// they are "flattened"... i.e. verts = {x, y, z, x, y, z, ...}
std::shared_ptr<tinyply::PlyData> vertBuffer;
try
{ vertBuffer = file.request_properties_from_element( "vertex", {"x", "y", "z"} ); }
catch ( const std::exception& e )
{
vertBuffer = nullptr;
LOG( logERROR ) << "[TinyPLY] " << e.what();
}
// if there is no vertex prop, or their count is 0, then quit.
if ( !vertBuffer || vertBuffer->count == 0 )
{
delete fileData;
LOG( logINFO ) << "[TinyPLY] No vertice found";
return nullptr;
}
auto startTime {std::clock()};
// a unique name is required by the component messaging system
static int nameId {0};
auto geometry = std::make_unique<GeometryData>( "PC_" + std::to_string( ++nameId ),
GeometryData::POINT_CLOUD );
geometry->setFrame( Core::Transform::Identity() );
std::shared_ptr<tinyply::PlyData> normalBuffer( nullptr );
std::shared_ptr<tinyply::PlyData> alphaBuffer( nullptr );
std::shared_ptr<tinyply::PlyData> colorBuffer( nullptr );
// check which buffers are available from file header
try
{ normalBuffer = file.request_properties_from_element( "vertex", {"nx", "ny", "nz"} ); }
catch ( const std::exception& e )
{
normalBuffer = nullptr;
LOG( logERROR ) << "[TinyPLY] " << e.what();
}
try
{ alphaBuffer = file.request_properties_from_element( "vertex", {"alpha"} ); }
catch ( const std::exception& e )
{
alphaBuffer = nullptr;
LOG( logERROR ) << "[TinyPLY] " << e.what();
}
try
{ colorBuffer = file.request_properties_from_element( "vertex", {"red", "green", "blue"} ); }
catch ( const std::exception& e )
{
colorBuffer = nullptr;
LOG( logERROR ) << "[TinyPLY] " << e.what();
}
// read buffer data from file content
file.read( ss );
std::vector<Eigen::Matrix<float, 3, 1, Eigen::DontAlign>> verts( vertBuffer->count );
std::memcpy( verts.data(), vertBuffer->buffer.get(), vertBuffer->buffer.size_bytes() );
geometry->setVertices( verts );
if ( normalBuffer && normalBuffer->count != 0 )
{
std::vector<Eigen::Matrix<float, 3, 1, Eigen::DontAlign>> normals( normalBuffer->count );
std::memcpy(
normals.data(), normalBuffer->buffer.get(), normalBuffer->buffer.size_bytes() );
geometry->setNormals( normals );
}
size_t colorCount = colorBuffer ? colorBuffer->count : 0;
if ( colorCount != 0 )
{
std::vector<Eigen::Matrix<uint8_t, 3, 1, Eigen::DontAlign>> colors( colorBuffer->count );
std::memcpy( colors.data(), colorBuffer->buffer.get(), colorBuffer->buffer.size_bytes() );
auto* cols = colors.data();
auto& container = geometry->getColors();
container.resize( colorCount );
if ( alphaBuffer && alphaBuffer->count == colorCount )
{
uint8_t* al = alphaBuffer->buffer.get();
for ( auto& c : container )
{
c = Core::Utils::Color::fromRGB( ( *cols ).cast<Scalar>() / 255_ra,
Scalar( *al ) / 255_ra );
cols++;
al++;
}
}
else
{
for ( auto& c : container )
{
c = Core::Utils::Color::fromRGB( ( *cols ).cast<Scalar>() / 255_ra );
cols++;
}
}
}
fileData->m_geometryData.clear();
fileData->m_geometryData.reserve( 1 );
fileData->m_geometryData.push_back( std::move( geometry ) );
fileData->m_loadingTime = ( std::clock() - startTime ) / Scalar( CLOCKS_PER_SEC );
if ( fileData->isVerbose() )
{
LOG( logINFO ) << "[TinyPLY] File Loading end.";
fileData->displayInfo();
}
fileData->m_processed = true;
return fileData;
}
std::string TinyPlyFileLoader::name() const {
return "TinyPly";
}
} // namespace IO
} // namespace Ra
<commit_msg>[IO] Refactor tinyply loader, use lambda to factorize code.<commit_after>#include <IO/TinyPlyLoader/TinyPlyFileLoader.hpp>
#include <Core/Asset/FileData.hpp>
#include <tinyply.h>
#include <fstream>
#include <iostream>
#include <string>
const std::string plyExt( "ply" );
namespace Ra {
namespace IO {
using namespace Core::Utils; // log
using namespace Core::Asset; // Filedata
TinyPlyFileLoader::TinyPlyFileLoader() {}
TinyPlyFileLoader::~TinyPlyFileLoader() {}
std::vector<std::string> TinyPlyFileLoader::getFileExtensions() const {
return std::vector<std::string>( {"*." + plyExt} );
}
bool TinyPlyFileLoader::handleFileExtension( const std::string& extension ) const {
return extension.compare( plyExt ) == 0;
}
FileData* TinyPlyFileLoader::loadFile( const std::string& filename ) {
// Read the file and create a std::istringstream suitable
// for the lib -- tinyply does not perform any file i/o.
std::ifstream ss( filename, std::ios::binary );
// Parse the ASCII header fields
tinyply::PlyFile file;
file.parse_header( ss );
auto elements = file.get_elements();
if ( std::any_of( elements.begin(), elements.end(), []( const auto& e ) -> bool {
return e.name == "face" && e.size != 0;
} ) )
{
// Mesh found. Let the other loaders handle it
LOG( logINFO ) << "[TinyPLY] Faces found. Aborting" << std::endl;
return nullptr;
}
// we are now sure to have a point-cloud
FileData* fileData = new FileData( filename );
if ( !fileData->isInitialized() )
{
delete fileData;
LOG( logINFO ) << "[TinyPLY] Filedata cannot be initialized...";
return nullptr;
}
if ( fileData->isVerbose() )
{
LOG( logINFO ) << "[TinyPLY] File Loading begin...";
LOG( logINFO ) << "....................................................................\n";
for ( auto c : file.get_comments() )
std::cout << "Comment: " << c;
for ( auto e : file.get_elements() )
{
LOG( logINFO ) << "element - " << e.name << " (" << e.size << ")";
for ( auto p : e.properties )
std::cout << "\tproperty - " << p.name << " ("
<< tinyply::PropertyTable[p.propertyType].str << ")";
}
LOG( logINFO ) << "....................................................................\n";
}
// The count returns the number of instances of the property group. The vectors
// above will be resized into a multiple of the property group size as
// they are "flattened"... i.e. verts = {x, y, z, x, y, z, ...}
auto initBuffer = [&file]( const std::string& elementKey,
const std::vector<std::string> propertyKeys ) {
std::shared_ptr<tinyply::PlyData> ret;
try
{ ret = file.request_properties_from_element( elementKey, propertyKeys ); }
catch ( const std::exception& e )
{
ret = nullptr;
LOG( logERROR ) << "[TinyPLY] " << e.what();
}
return ret;
};
auto vertBuffer {initBuffer( "vertex", {"x", "y", "z"} )};
// if there is no vertex prop, or their count is 0, then quit.
if ( !vertBuffer || vertBuffer->count == 0 )
{
delete fileData;
LOG( logINFO ) << "[TinyPLY] No vertice found";
return nullptr;
}
auto startTime {std::clock()};
// a unique name is required by the component messaging system
static int nameId {0};
auto geometry = std::make_unique<GeometryData>( "PC_" + std::to_string( ++nameId ),
GeometryData::POINT_CLOUD );
geometry->setFrame( Core::Transform::Identity() );
auto normalBuffer {initBuffer( "vertex", {"nx", "ny", "nz"} )};
auto alphaBuffer {initBuffer( "vertex", {"alpha"} )};
auto colorBuffer {initBuffer( "vertex", {"red", "green", "blue"} )};
// read buffer data from file content
file.read( ss );
std::vector<Eigen::Matrix<float, 3, 1, Eigen::DontAlign>> verts( vertBuffer->count );
std::memcpy( verts.data(), vertBuffer->buffer.get(), vertBuffer->buffer.size_bytes() );
geometry->setVertices( verts );
if ( normalBuffer && normalBuffer->count != 0 )
{
std::vector<Eigen::Matrix<float, 3, 1, Eigen::DontAlign>> normals( normalBuffer->count );
std::memcpy(
normals.data(), normalBuffer->buffer.get(), normalBuffer->buffer.size_bytes() );
geometry->setNormals( normals );
}
size_t colorCount = colorBuffer ? colorBuffer->count : 0;
if ( colorCount != 0 )
{
std::vector<Eigen::Matrix<uint8_t, 3, 1, Eigen::DontAlign>> colors( colorBuffer->count );
std::memcpy( colors.data(), colorBuffer->buffer.get(), colorBuffer->buffer.size_bytes() );
auto* cols = colors.data();
auto& container = geometry->getColors();
container.resize( colorCount );
if ( alphaBuffer && alphaBuffer->count == colorCount )
{
uint8_t* al = alphaBuffer->buffer.get();
for ( auto& c : container )
{
c = Core::Utils::Color::fromRGB( ( *cols ).cast<Scalar>() / 255_ra,
Scalar( *al ) / 255_ra );
++cols;
++al;
}
}
else
{
for ( auto& c : container )
{
c = Core::Utils::Color::fromRGB( ( *cols ).cast<Scalar>() / 255_ra );
++cols;
}
}
}
fileData->m_geometryData.clear();
fileData->m_geometryData.reserve( 1 );
fileData->m_geometryData.push_back( std::move( geometry ) );
fileData->m_loadingTime = ( std::clock() - startTime ) / Scalar( CLOCKS_PER_SEC );
if ( fileData->isVerbose() )
{
LOG( logINFO ) << "[TinyPLY] File Loading end.";
fileData->displayInfo();
}
fileData->m_processed = true;
return fileData;
}
std::string TinyPlyFileLoader::name() const {
return "TinyPly";
}
} // namespace IO
} // namespace Ra
<|endoftext|> |
<commit_before>#include <IO/TinyPlyLoader/TinyPlyFileLoader.hpp>
#include <assimp/scene.h>
#include <assimp/postprocess.h>
#include <tinyply/tinyply.h>
#include <string>
#include <iostream>
#include <fstream>
const std::string plyExt ("ply");
namespace Ra {
namespace IO {
TinyPlyFileLoader::TinyPlyFileLoader()
{
}
TinyPlyFileLoader::~TinyPlyFileLoader()
{
}
std::vector<std::string> TinyPlyFileLoader::getFileExtensions() const
{
return std::vector<std::string> ({"*."+plyExt});
}
bool TinyPlyFileLoader::handleFileExtension( const std::string& extension ) const
{
return extension.compare(plyExt) == 0;
}
Asset::FileData * TinyPlyFileLoader::loadFile( const std::string& filename )
{
// Read the file and create a std::istringstream suitable
// for the lib -- tinyply does not perform any file i/o.
std::ifstream ss(filename, std::ios::binary);
// Parse the ASCII header fields
tinyply::PlyFile file(ss);
for (auto e : file.get_elements())
{
if(e.name.compare("face") == 0 && e.size != 0)
{
// Mesh found. Let the other loaders handle it
LOG( logINFO ) << "[TinyPLY] Faces found. Aborting" << std::endl;
return nullptr;
}
}
// we are now sure to have a point-cloud
Asset::FileData * fileData = new Asset::FileData( filename );
if ( !fileData->isInitialized() )
{
delete fileData;
LOG( logINFO ) << "[TinyPLY] Filedata cannot be initialized...";
return nullptr;
}
if ( fileData->isVerbose() )
{
LOG( logINFO ) << "[TinyPLY] File Loading begin...";
}
// Define containers to hold the extracted data. The type must match
// the property type given in the header. Tinyply will interally allocate the
// the appropriate amount of memory.
std::vector<float> verts;
// The count returns the number of instances of the property group. The vectors
// above will be resized into a multiple of the property group size as
// they are "flattened"... i.e. verts = {x, y, z, x, y, z, ...}
uint32_t vertexCount= file.request_properties_from_element("vertex", { "x", "y", "z" }, verts);
if(vertexCount == 0) {
delete fileData;
LOG( logINFO ) << "[TinyPLY] No vertice found";
return nullptr;
}
fileData->m_geometryData.clear();
fileData->m_geometryData.reserve(1);
Asset::GeometryData* geometry = new Asset::GeometryData();
geometry->setType( Asset::GeometryData::POINT_CLOUD );
std::vector<float> normals;
std::vector<uint8_t> colors;
uint32_t normalCount = file.request_properties_from_element("vertex", { "nx", "ny", "nz" }, normals);
uint32_t colorCount = file.request_properties_from_element("vertex", { "red", "green", "blue", "alpha" }, colors);
std::clock_t startTime;
startTime = std::clock();
file.read(ss);
geometry->setVertices(*(reinterpret_cast<std::vector<Eigen::Matrix <float, 3, 1, Eigen::DontAlign>> *> (&verts)));
geometry->setFrame(Core::Transform::Identity());
if (normalCount != 0) {
geometry->setNormals(*(reinterpret_cast<std::vector<Eigen::Matrix <float, 3, 1, Eigen::DontAlign>> *> (&normals)));
}
if (colorCount != 0) {
geometry->setColors(*(reinterpret_cast<std::vector<Eigen::Matrix <uint8_t, 4, 1, Eigen::DontAlign>> *> (&colors)));
for (auto& c : geometry->getColors()) c /= Scalar(255);
}
fileData->m_loadingTime = ( std::clock() - startTime ) / Scalar( CLOCKS_PER_SEC );
fileData->m_geometryData.push_back( std::unique_ptr< Asset::GeometryData >( geometry ) );
if ( fileData->isVerbose() )
{
LOG( logINFO ) << "[TinyPLY] File Loading end.";
fileData->displayInfo();
}
fileData->m_processed = true;
return fileData;
}
}
}
<commit_msg>Remove unused include directives<commit_after>#include <IO/TinyPlyLoader/TinyPlyFileLoader.hpp>
#include <tinyply/tinyply.h>
#include <string>
#include <iostream>
#include <fstream>
const std::string plyExt ("ply");
namespace Ra {
namespace IO {
TinyPlyFileLoader::TinyPlyFileLoader()
{
}
TinyPlyFileLoader::~TinyPlyFileLoader()
{
}
std::vector<std::string> TinyPlyFileLoader::getFileExtensions() const
{
return std::vector<std::string> ({"*."+plyExt});
}
bool TinyPlyFileLoader::handleFileExtension( const std::string& extension ) const
{
return extension.compare(plyExt) == 0;
}
Asset::FileData * TinyPlyFileLoader::loadFile( const std::string& filename )
{
// Read the file and create a std::istringstream suitable
// for the lib -- tinyply does not perform any file i/o.
std::ifstream ss(filename, std::ios::binary);
// Parse the ASCII header fields
tinyply::PlyFile file(ss);
for (auto e : file.get_elements())
{
if(e.name.compare("face") == 0 && e.size != 0)
{
// Mesh found. Let the other loaders handle it
LOG( logINFO ) << "[TinyPLY] Faces found. Aborting" << std::endl;
return nullptr;
}
}
// we are now sure to have a point-cloud
Asset::FileData * fileData = new Asset::FileData( filename );
if ( !fileData->isInitialized() )
{
delete fileData;
LOG( logINFO ) << "[TinyPLY] Filedata cannot be initialized...";
return nullptr;
}
if ( fileData->isVerbose() )
{
LOG( logINFO ) << "[TinyPLY] File Loading begin...";
}
// Define containers to hold the extracted data. The type must match
// the property type given in the header. Tinyply will interally allocate the
// the appropriate amount of memory.
std::vector<float> verts;
// The count returns the number of instances of the property group. The vectors
// above will be resized into a multiple of the property group size as
// they are "flattened"... i.e. verts = {x, y, z, x, y, z, ...}
uint32_t vertexCount= file.request_properties_from_element("vertex", { "x", "y", "z" }, verts);
if(vertexCount == 0) {
delete fileData;
LOG( logINFO ) << "[TinyPLY] No vertice found";
return nullptr;
}
fileData->m_geometryData.clear();
fileData->m_geometryData.reserve(1);
Asset::GeometryData* geometry = new Asset::GeometryData();
geometry->setType( Asset::GeometryData::POINT_CLOUD );
std::vector<float> normals;
std::vector<uint8_t> colors;
uint32_t normalCount = file.request_properties_from_element("vertex", { "nx", "ny", "nz" }, normals);
uint32_t colorCount = file.request_properties_from_element("vertex", { "red", "green", "blue", "alpha" }, colors);
std::clock_t startTime;
startTime = std::clock();
file.read(ss);
geometry->setVertices(*(reinterpret_cast<std::vector<Eigen::Matrix <float, 3, 1, Eigen::DontAlign>> *> (&verts)));
geometry->setFrame(Core::Transform::Identity());
if (normalCount != 0) {
geometry->setNormals(*(reinterpret_cast<std::vector<Eigen::Matrix <float, 3, 1, Eigen::DontAlign>> *> (&normals)));
}
if (colorCount != 0) {
geometry->setColors(*(reinterpret_cast<std::vector<Eigen::Matrix <uint8_t, 4, 1, Eigen::DontAlign>> *> (&colors)));
for (auto& c : geometry->getColors()) c /= Scalar(255);
}
fileData->m_loadingTime = ( std::clock() - startTime ) / Scalar( CLOCKS_PER_SEC );
fileData->m_geometryData.push_back( std::unique_ptr< Asset::GeometryData >( geometry ) );
if ( fileData->isVerbose() )
{
LOG( logINFO ) << "[TinyPLY] File Loading end.";
fileData->displayInfo();
}
fileData->m_processed = true;
return fileData;
}
}
}
<|endoftext|> |
<commit_before>// IFC SDK : IFC2X3 C++ Early Classes
// Copyright (C) 2009 CSTB
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// The full license is in Licence.txt file included with this
// distribution or is available at :
// http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
#include "Step/BaseExpressDataSet.h"
#include "Step/BaseEntity.h"
#include "Step/BaseSPFObject.h"
#include "Step/SPFHeader.h"
#include "Step/SPFData.h"
#include "Step/RefLinkedList.h"
#include "Step/logger.h"
#include <iostream>
using namespace Step;
BaseExpressDataSet::BaseExpressDataSet() :
m_maxId(0)
{
}
BaseExpressDataSet::~BaseExpressDataSet()
{
MapOfEntities::iterator objIt = m_Id2BaseEntity.begin();
for (; objIt != m_Id2BaseEntity.end(); objIt++)
{
objIt->second->release();
}
}
BaseEntity* BaseExpressDataSet::find(Id id)
{
MapOfEntities::iterator it = m_Id2BaseEntity.find(id);
if (it != m_Id2BaseEntity.end())
return it->second.get();
else
return NULL;
}
SPFHeader& BaseExpressDataSet::getHeader()
{
return m_header;
}
void BaseExpressDataSet::setHeader(SPFHeader& header)
{
m_header = header;
}
Id BaseExpressDataSet::getNewId()
{
return ++m_maxId;
}
Id BaseExpressDataSet::maxId()
{
return m_maxId;
}
void BaseExpressDataSet::updateMaxId(Id id)
{
if (id > m_maxId)
{
m_maxId = id;
}
}
bool BaseExpressDataSet::registerObject(Id id, BaseEntity* obj)
{
if (exists(id))
{
if (!m_Id2BaseEntity[id]->isOfType(BaseSPFObject::getClassType()))
{
LOG_ERROR("Can't register the object with id " << id << ", in use");
return false;
}
else
{
//implicit destruction of BaseSPFObject thanks to RefPtr...
m_Id2BaseEntity[id]->m_args = 0;
m_Id2BaseEntity[id] = obj;
obj->setExpressDataSet(this);
return true;
}
}
m_Id2BaseEntity[id] = obj;
obj->setExpressDataSet(this);
return true;
}
bool BaseExpressDataSet::exists(Id id) const
{
return (!(m_Id2BaseEntity.find(id) == m_Id2BaseEntity.end()));
}
BaseEntity *BaseExpressDataSet::get(Id id)
{
MapOfEntities::iterator it = m_Id2BaseEntity.find(id);
if (it == m_Id2BaseEntity.end())
{
LOG_WARNING("Entity #" << id << " was never declared");
return 0;
}
else if (it->second->isOfType(BaseSPFObject::getClassType()))
{
// Get the appropriate allocate function
AllocateFuncType allocFunc =
static_cast<BaseSPFObject*> (it->second.get())->getAllocateFunction();
if (allocFunc)
{
// Call it and get the result
BaseEntity* ret = (*allocFunc)(this, id);
return ret;
}
else
{
LOG_WARNING("Entity #" << id << " cannot be allocated");
return 0;
}
}
else
return it->second.get();
}
MapOfEntities& BaseExpressDataSet::getAll()
{
return m_Id2BaseEntity;
}
BaseSPFObject* BaseExpressDataSet::getSPFObject(Id id)
{
#if 0
if (!exists(id))
{
updateMaxId(id);
BaseSPFObject* bo = new BaseSPFObject(id, new SPFData());
bo->setExpressDataSet(this);
m_Id2BaseObject[id] = bo;
return bo;
}
else
return static_cast<BaseSPFObject*> (m_Id2BaseObject[id].get());
#else // Flo: faster impl
MapOfEntities::const_iterator it = m_Id2BaseEntity.find(id);
if (it == m_Id2BaseEntity.end())
{
if (id > m_maxId)
{
m_maxId = id;
};
BaseSPFObject* bo = new BaseSPFObject(id, new SPFData());
bo->setExpressDataSet(this);
m_Id2BaseEntity.insert(std::make_pair(id,bo));
return bo;
}
else
return static_cast<BaseSPFObject*> (it->second.get());
#endif
}
SPFData* BaseExpressDataSet::getArgs(Id id)
{
if (!exists(id))
{
updateMaxId(id);
BaseSPFObject* bo = new BaseSPFObject(id, new SPFData());
bo->setExpressDataSet(this);
m_Id2BaseEntity[id] = bo;
return bo->getArgs();
}
else
return m_Id2BaseEntity[id]->getArgs();
}
void BaseExpressDataSet::instantiateAll(CallBack *callback)
{
MapOfEntities::iterator it = m_Id2BaseEntity.begin();
if(callback)
{
callback->setMaximum(m_Id2BaseEntity.size());
}
size_t progress=0;
for (; it != m_Id2BaseEntity.end(); it++)
{
if (it->second->isOfType(BaseSPFObject::getClassType()))
{
LOG_DEBUG("Instantiating #" << it->first)
// Get the appropriate allocate function
AllocateFuncType
allocFunc =
static_cast<BaseSPFObject*> (it->second.get())->getAllocateFunction();
if (allocFunc)
{
// Call it and get the result
BaseEntity* ret = (*allocFunc)(this, it->first);
ret->inited();
}
else
{
LOG_WARNING("Entity #" << it->first << " was never declared");
}
}
else
it->second->inited();
if(callback)
{
callback->setProgress(++progress);
if (callback->stop())
return;
}
}
}
AllocateFuncType BaseExpressDataSet::getAllocateFunction(BaseSPFObject* spfObj)
{
return spfObj->getAllocateFunction();
}
<commit_msg>For statement optimizations<commit_after>// IFC SDK : IFC2X3 C++ Early Classes
// Copyright (C) 2009 CSTB
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// The full license is in Licence.txt file included with this
// distribution or is available at :
// http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
#include "Step/BaseExpressDataSet.h"
#include "Step/BaseEntity.h"
#include "Step/BaseSPFObject.h"
#include "Step/SPFHeader.h"
#include "Step/SPFData.h"
#include "Step/RefLinkedList.h"
#include "Step/logger.h"
#include <iostream>
using namespace Step;
BaseExpressDataSet::BaseExpressDataSet() :
m_maxId(0)
{
}
BaseExpressDataSet::~BaseExpressDataSet()
{
MapOfEntities::iterator objIt = m_Id2BaseEntity.begin();
for (MapOfEntities::iterator total = m_Id2BaseEntity.end(); objIt != total; ++objIt)
{
objIt->second->release();
}
}
BaseEntity* BaseExpressDataSet::find(Id id)
{
MapOfEntities::iterator it = m_Id2BaseEntity.find(id);
if (it != m_Id2BaseEntity.end())
return it->second.get();
else
return NULL;
}
SPFHeader& BaseExpressDataSet::getHeader()
{
return m_header;
}
void BaseExpressDataSet::setHeader(SPFHeader& header)
{
m_header = header;
}
Id BaseExpressDataSet::getNewId()
{
return ++m_maxId;
}
Id BaseExpressDataSet::maxId()
{
return m_maxId;
}
void BaseExpressDataSet::updateMaxId(Id id)
{
if (id > m_maxId)
{
m_maxId = id;
}
}
bool BaseExpressDataSet::registerObject(Id id, BaseEntity* obj)
{
if (exists(id))
{
if (!m_Id2BaseEntity[id]->isOfType(BaseSPFObject::getClassType()))
{
LOG_ERROR("Can't register the object with id " << id << ", in use");
return false;
}
else
{
//implicit destruction of BaseSPFObject thanks to RefPtr...
m_Id2BaseEntity[id]->m_args = 0;
m_Id2BaseEntity[id] = obj;
obj->setExpressDataSet(this);
return true;
}
}
m_Id2BaseEntity[id] = obj;
obj->setExpressDataSet(this);
return true;
}
bool BaseExpressDataSet::exists(Id id) const
{
return (!(m_Id2BaseEntity.find(id) == m_Id2BaseEntity.end()));
}
BaseEntity *BaseExpressDataSet::get(Id id)
{
MapOfEntities::iterator it = m_Id2BaseEntity.find(id);
if (it == m_Id2BaseEntity.end())
{
LOG_WARNING("Entity #" << id << " was never declared");
return 0;
}
else if (it->second->isOfType(BaseSPFObject::getClassType()))
{
// Get the appropriate allocate function
AllocateFuncType allocFunc =
static_cast<BaseSPFObject*> (it->second.get())->getAllocateFunction();
if (allocFunc)
{
// Call it and get the result
BaseEntity* ret = (*allocFunc)(this, id);
return ret;
}
else
{
LOG_WARNING("Entity #" << id << " cannot be allocated");
return 0;
}
}
else
return it->second.get();
}
MapOfEntities& BaseExpressDataSet::getAll()
{
return m_Id2BaseEntity;
}
BaseSPFObject* BaseExpressDataSet::getSPFObject(Id id)
{
#if 0
if (!exists(id))
{
updateMaxId(id);
BaseSPFObject* bo = new BaseSPFObject(id, new SPFData());
bo->setExpressDataSet(this);
m_Id2BaseObject[id] = bo;
return bo;
}
else
return static_cast<BaseSPFObject*> (m_Id2BaseObject[id].get());
#else // Flo: faster impl
MapOfEntities::const_iterator it = m_Id2BaseEntity.find(id);
if (it == m_Id2BaseEntity.end())
{
if (id > m_maxId)
{
m_maxId = id;
};
BaseSPFObject* bo = new BaseSPFObject(id, new SPFData());
bo->setExpressDataSet(this);
m_Id2BaseEntity.insert(std::make_pair(id,bo));
return bo;
}
else
return static_cast<BaseSPFObject*> (it->second.get());
#endif
}
SPFData* BaseExpressDataSet::getArgs(Id id)
{
if (!exists(id))
{
updateMaxId(id);
BaseSPFObject* bo = new BaseSPFObject(id, new SPFData());
bo->setExpressDataSet(this);
m_Id2BaseEntity[id] = bo;
return bo->getArgs();
}
else
return m_Id2BaseEntity[id]->getArgs();
}
void BaseExpressDataSet::instantiateAll(CallBack *callback)
{
MapOfEntities::iterator it = m_Id2BaseEntity.begin();
if(callback)
{
callback->setMaximum(m_Id2BaseEntity.size());
}
size_t progress=0;
for (MapOfEntities::iterator total = m_Id2BaseEntity.end(); it != total; ++it)
{
if (it->second->isOfType(BaseSPFObject::getClassType()))
{
LOG_DEBUG("Instantiating #" << it->first)
// Get the appropriate allocate function
AllocateFuncType
allocFunc =
static_cast<BaseSPFObject*> (it->second.get())->getAllocateFunction();
if (allocFunc)
{
// Call it and get the result
BaseEntity* ret = (*allocFunc)(this, it->first);
ret->inited();
}
else
{
LOG_WARNING("Entity #" << it->first << " was never declared");
}
}
else
it->second->inited();
if(callback)
{
callback->setProgress(++progress);
if (callback->stop())
return;
}
}
}
AllocateFuncType BaseExpressDataSet::getAllocateFunction(BaseSPFObject* spfObj)
{
return spfObj->getAllocateFunction();
}
<|endoftext|> |
<commit_before>// Copyright 2016 Alessio Sclocco <a.sclocco@vu.nl>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <iostream>
#include <vector>
#include <ctime>
#include <algorithm>
#include <configuration.hpp>
#include <Dedispersion.hpp>
#include <ArgumentList.hpp>
#include <Observation.hpp>
#include <utils.hpp>
#include <Shifts.hpp>
#include <ReadData.hpp>
#include <utils.hpp>
int main(int argc, char * argv[]) {
unsigned int padding = 0;
uint8_t inputBits = 0;
bool printResults = false;
uint64_t wrongSamples = 0;
std::string channelsFile;
AstroData::Observation observation_c;
AstroData::Observation observation;
try {
isa::utils::ArgumentList args(argc, argv);
printResults = args.getSwitch("-print_results");
inputBits = args.getSwitchArgument< unsigned int >("-input_bits");
padding = args.getSwitchArgument< unsigned int >("-padding");
channelsFile = args.getSwitchArgument< std::string >("-zapped_channels");
observation.setNrBeams(args.getSwitchArgument< unsigned int >("-beams"));
observation.setNrSyntheticBeams(args.getSwitchArgument< unsigned int >("-synthetic_beams"));
observation.setFrequencyRange(args.getSwitchArgument< unsigned int >("-subbands"), args.getSwitchArgument< unsigned int >("-channels"), args.getSwitchArgument< float >("-min_freq"), args.getSwitchArgument< float >("-channel_bandwidth"));
observation.setNrSamplesPerBatch(args.getSwitchArgument< unsigned int >("-samples"));
observation.setDMSubbandingRange(args.getSwitchArgument< unsigned int >("-subbanding_dms"), args.getSwitchArgument< float >("-subbanding_dm_first"), args.getSwitchArgument< float >("-subbanding_dm_step"));
observation.setDMRange(args.getSwitchArgument< unsigned int >("-dms"), args.getSwitchArgument< float >("-dm_first"), args.getSwitchArgument< float >("-dm_step"));
} catch ( isa::utils::SwitchNotFound & err ) {
std::cerr << err.what() << std::endl;
return 1;
} catch ( std::exception & err ) {
std::cerr << "Usage: " << argv[0] << " [-print_results] -input_bits ... -padding ... -zapped_channels ... -beams ... -synthetic_beams ... -min_freq ... -channel_bandwidth ... -samples ... -subbands ... -channels ... -subbanding_dms ... -dms ... -subbanding_dm_first ... -dm_first ... -subbanding_dm_step ... -dm_step ..." << std::endl;
return 1;
}
observation_c = observation;
observation_c.setDMRange(observation.getNrDMsSubbanding() * observation.getNrDMs(), observation.getFirstDMSubbanding() + observation.getFirstDM(), observation.getDMStep());
// Allocate memory
std::vector< inputDataType > dispersedData;
std::vector< outputDataType > subbandedData;
std::vector< outputDataType > dedispersedData;
std::vector< outputDataType > dedispersedData_c;
std::vector< uint8_t > zappedChannels(observation_c.getNrPaddedChannels(padding / sizeof(uint8_t)));
std::vector< uint8_t > beamDriver(observation_c.getNrSyntheticBeams() * observation_c.getNrPaddedChannels(padding / sizeof(uint8_t)));
std::vector< float > * shifts = PulsarSearch::getShifts(observation_c, padding);
AstroData::readZappedChannels(observation_c, channelsFile, zappedChannels);
observation_c.setNrSamplesPerDispersedChannel(observation.getNrSamplesPerBatch() + static_cast< unsigned int >(shifts->at(0) * (observation_c.getFirstDM() + ((observation_c.getNrDMs() - 1) * observation_c.getDMStep()))));
observation.setNrSamplesPerBatchSubbanding(observation.getNrSamplesPerBatch() + static_cast< unsigned int >(shifts->at(0) * (observation.getFirstDM() + ((observation.getNrDMs() - 1) * observation.getDMStep()))));
observation.setNrSamplesPerSubbandingDispersedChannel(observation.getNrSamplesPerBatchSubbanding() + static_cast< unsigned int >(shifts->at(0) * (observation.getFirstDMSubbanding() + ((observation.getNrDMsSubbanding() - 1) * observation.getDMSubbandingStep()))));
if ( inputBits >= 8 ) {
dispersedData.resize(observation_c.getNrBeams() * observation_c.getNrChannels() * observation_c.getNrSamplesPerPaddedDispersedChannel(padding / sizeof(inputDataType)));
subbandedData.resize(observation.getNrBeams() * observation.getNrSubbands() * observation.getNrDMsSubbanding() * observation.getNrSamplesPerPaddedSubbandingDispersedChannel(padding / sizeof(inputDataType)));
dedispersedData.resize(observation.getNrSyntheticBeams() * (observation.getNrDMsSubbanding() * observation.getNrDMs()) * observation.getNrSamplesPerPaddedBatch(padding / sizeof(inputDataType)));
dedispersedData_c.resize(observation_c.getNrSyntheticBeams() * observation_c.getNrDMs() * observation_c.getNrSamplesPerPaddedBatch(padding / sizeof(inputDataType)));
} else {
dispersedData.resize(observation_c.getNrBeams() * observation_c.getNrChannels() * isa::utils::pad(observation_c.getNrSamplesPerDispersedChannel() / (8 / inputBits), padding / sizeof(inputDataType)));
subbandedData.resize(observation.getNrBeams() * observation.getNrSubbands() * isa::utils::pad(observation.getNrSamplesPerSubbandingDispersedChannel() / (8 / inputBits), padding / sizeof(inputDataType)));
dedispersedData.resize(observation.getNrSyntheticBeams() * (observation.getNrDMsSubbanding() * observation.getNrDMs()) * isa::utils::pad(observation.getNrSamplesPerBatch() / (8 / inputBits), padding / sizeof(inputDataType)));
dedispersedData_c.resize(observation_c.getNrSyntheticBeams() * observation_c.getNrDMs() * isa::utils::pad(observation_c.getNrSamplesPerBatch() / (8 / inputBits), padding / sizeof(inputDataType)));
}
// Generate data
srand(time(0));
for ( unsigned int beam = 0; beam < observation_c.getNrBeams(); beam++ ) {
for ( unsigned int channel = 0; channel < observation_c.getNrChannels(); channel++ ) {
for ( unsigned int sample = 0; sample < observation_c.getNrSamplesPerDispersedChannel(); sample++ ) {
if ( inputBits >= 8 ) {
dispersedData[(beam * observation_c.getNrChannels() * observation_c.getNrSamplesPerPaddedDispersedChannel(padding / sizeof(inputDataType))) + (channel * observation_c.getNrSamplesPerPaddedDispersedChannel(padding / sizeof(inputDataType))) + sample] = rand() % observation_c.getNrChannels();
} else {
unsigned int byte = 0;
uint8_t firstBit = 0;
uint8_t value = rand() % inputBits;
uint8_t buffer = 0;
byte = sample / (8 / inputBits);
firstBit = (sample % (8 / inputBits)) * inputBits;
buffer = dispersedData[(beam * observation_c.getNrChannels() * isa::utils::pad(observation_c.getNrSamplesPerDispersedChannel() / (8 / inputBits), padding / sizeof(inputDataType))) + (channel * isa::utils::pad(observation_c.getNrSamplesPerDispersedChannel() / (8 / inputBits), padding / sizeof(inputDataType))) + byte];
for ( unsigned int bit = 0; bit < inputBits; bit++ ) {
isa::utils::setBit(buffer, isa::utils::getBit(value, bit), firstBit + bit);
}
dispersedData[(beam * observation_c.getNrChannels() * isa::utils::pad(observation_c.getNrSamplesPerDispersedChannel() / (8 / inputBits), padding / sizeof(inputDataType))) + (channel * isa::utils::pad(observation_c.getNrSamplesPerDispersedChannel() / (8 / inputBits), padding / sizeof(inputDataType))) + byte] = buffer;
}
}
}
}
for ( unsigned int beam = 0; beam < observation_c.getNrSyntheticBeams(); beam++ ) {
for ( unsigned int channel = 0; channel < observation_c.getNrChannels(); channel++ ) {
beamDriver[(beam * observation_c.getNrPaddedChannels(padding / sizeof(uint8_t))) + channel] = rand() % observation_c.getNrBeams();
}
}
std::fill(subbandedData.begin(), subbandedData.end(), 0);
std::fill(dedispersedData.begin(), dedispersedData.end(), 0);
std::fill(dedispersedData_c.begin(), dedispersedData_c.end(), 0);
// Execute dedispersion
PulsarSearch::dedispersion< inputDataType, intermediateDataType, outputDataType >(observation_c, zappedChannels, beamDriver, dispersedData, dedispersedData_c, *shifts, padding, inputBits);
PulsarSearch::subbandDedispersionStepOne< inputDataType, intermediateDataType, outputDataType >(observation, zappedChannels, dispersedData, subbandedData, *shifts, padding, inputBits);
PulsarSearch::subbandDedispersionStepTwo< outputDataType, intermediateDataType, outputDataType >(observation, beamDriver, subbandedData, dedispersedData, *shifts, padding);
for ( unsigned int sBeam = 0; sBeam < observation.getNrSyntheticBeams(); sBeam++ ) {
for ( unsigned int firstStepDM = 0; firstStepDM < observation.getNrDMsSubbanding(); firstStepDM++ ) {
for ( unsigned int dm = 0; dm < observation.getNrDMs(); dm++ ) {
if ( printResults ) {
std::cout << "sBeam: " << sBeam << " DM: " << (firstStepDM * observation.getNrDMs()) + dm << std::endl;
}
for ( unsigned int sample = 0; sample < observation.getNrSamplesPerBatch(); sample++ ) {
if ( !isa::utils::same(dedispersedData[(sBeam * observation.getNrDMsSubbanding() * observation.getNrDMs() * observation.getNrSamplesPerPaddedBatch(padding / sizeof(outputDataType))) + (firstStepDM * observation.getNrDMs() * observation.getNrSamplesPerPaddedBatch(padding / sizeof(outputDataType))) + (dm * observation.getNrSamplesPerPaddedBatch(padding / sizeof(outputDataType))) + sample], dedispersedData_c[(sBeam * observation_c.getNrDMs() * observation.getNrSamplesPerPaddedBatch(padding / sizeof(outputDataType))) + (((firstStepDM * observation.getNrDMs()) + dm) * observation.getNrSamplesPerPaddedBatch(padding / sizeof(outputDataType))) + sample]) ) {
wrongSamples++;
}
if ( printResults ) {
std::cout << dedispersedData[(sBeam * observation.getNrDMsSubbanding() * observation.getNrDMs() * observation.getNrSamplesPerPaddedBatch(padding / sizeof(outputDataType))) + (firstStepDM * observation.getNrDMs() * observation.getNrSamplesPerPaddedBatch(padding / sizeof(outputDataType))) + (dm * observation.getNrSamplesPerPaddedBatch(padding / sizeof(outputDataType))) + sample] << "," << dedispersedData_c[(sBeam * observation_c.getNrDMs() * observation.getNrSamplesPerPaddedBatch(padding / sizeof(outputDataType))) + (((firstStepDM * observation.getNrDMs()) + dm) * observation.getNrSamplesPerPaddedBatch(padding / sizeof(outputDataType))) + sample] << " ";
}
}
if ( printResults ) {
std::cout << std::endl;
}
}
}
}
if ( wrongSamples > 0 ) {
std::cout << "Wrong samples: " << wrongSamples << " (" << (wrongSamples * 100.0) / (static_cast< uint64_t >(observation_c.getNrSyntheticBeams()) * observation_c.getNrDMs() * observation_c.getNrSamplesPerBatch()) << "%)." << std::endl;
} else {
std::cout << "TEST PASSED." << std::endl;
}
return 0;
}
<commit_msg>Wrong first DM.<commit_after>// Copyright 2016 Alessio Sclocco <a.sclocco@vu.nl>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <iostream>
#include <vector>
#include <ctime>
#include <algorithm>
#include <configuration.hpp>
#include <Dedispersion.hpp>
#include <ArgumentList.hpp>
#include <Observation.hpp>
#include <utils.hpp>
#include <Shifts.hpp>
#include <ReadData.hpp>
#include <utils.hpp>
int main(int argc, char * argv[]) {
unsigned int padding = 0;
uint8_t inputBits = 0;
bool printResults = false;
uint64_t wrongSamples = 0;
std::string channelsFile;
AstroData::Observation observation_c;
AstroData::Observation observation;
try {
isa::utils::ArgumentList args(argc, argv);
printResults = args.getSwitch("-print_results");
inputBits = args.getSwitchArgument< unsigned int >("-input_bits");
padding = args.getSwitchArgument< unsigned int >("-padding");
channelsFile = args.getSwitchArgument< std::string >("-zapped_channels");
observation.setNrBeams(args.getSwitchArgument< unsigned int >("-beams"));
observation.setNrSyntheticBeams(args.getSwitchArgument< unsigned int >("-synthetic_beams"));
observation.setFrequencyRange(args.getSwitchArgument< unsigned int >("-subbands"), args.getSwitchArgument< unsigned int >("-channels"), args.getSwitchArgument< float >("-min_freq"), args.getSwitchArgument< float >("-channel_bandwidth"));
observation.setNrSamplesPerBatch(args.getSwitchArgument< unsigned int >("-samples"));
observation.setDMSubbandingRange(args.getSwitchArgument< unsigned int >("-subbanding_dms"), args.getSwitchArgument< float >("-subbanding_dm_first"), args.getSwitchArgument< float >("-subbanding_dm_step"));
observation.setDMRange(args.getSwitchArgument< unsigned int >("-dms"), 0.0, args.getSwitchArgument< float >("-dm_step"));
observation_c = observation;
observation_c.setDMRange(observation.getNrDMsSubbanding() * observation.getNrDMs(), args.getSwitchArgument< float >("-dm_first"), observation.getDMStep());
} catch ( isa::utils::SwitchNotFound & err ) {
std::cerr << err.what() << std::endl;
return 1;
} catch ( std::exception & err ) {
std::cerr << "Usage: " << argv[0] << " [-print_results] -input_bits ... -padding ... -zapped_channels ... -beams ... -synthetic_beams ... -min_freq ... -channel_bandwidth ... -samples ... -subbands ... -channels ... -subbanding_dms ... -dms ... -subbanding_dm_first ... -dm_first ... -subbanding_dm_step ... -dm_step ..." << std::endl;
return 1;
}
// Allocate memory
std::vector< inputDataType > dispersedData;
std::vector< outputDataType > subbandedData;
std::vector< outputDataType > dedispersedData;
std::vector< outputDataType > dedispersedData_c;
std::vector< uint8_t > zappedChannels(observation_c.getNrPaddedChannels(padding / sizeof(uint8_t)));
std::vector< uint8_t > beamDriver(observation_c.getNrSyntheticBeams() * observation_c.getNrPaddedChannels(padding / sizeof(uint8_t)));
std::vector< float > * shifts = PulsarSearch::getShifts(observation_c, padding);
AstroData::readZappedChannels(observation_c, channelsFile, zappedChannels);
observation_c.setNrSamplesPerDispersedChannel(observation.getNrSamplesPerBatch() + static_cast< unsigned int >(shifts->at(0) * (observation_c.getFirstDM() + ((observation_c.getNrDMs() - 1) * observation_c.getDMStep()))));
observation.setNrSamplesPerBatchSubbanding(observation.getNrSamplesPerBatch() + static_cast< unsigned int >(shifts->at(0) * (observation.getFirstDM() + ((observation.getNrDMs() - 1) * observation.getDMStep()))));
observation.setNrSamplesPerSubbandingDispersedChannel(observation.getNrSamplesPerBatchSubbanding() + static_cast< unsigned int >(shifts->at(0) * (observation.getFirstDMSubbanding() + ((observation.getNrDMsSubbanding() - 1) * observation.getDMSubbandingStep()))));
if ( inputBits >= 8 ) {
dispersedData.resize(observation_c.getNrBeams() * observation_c.getNrChannels() * observation_c.getNrSamplesPerPaddedDispersedChannel(padding / sizeof(inputDataType)));
subbandedData.resize(observation.getNrBeams() * observation.getNrSubbands() * observation.getNrDMsSubbanding() * observation.getNrSamplesPerPaddedSubbandingDispersedChannel(padding / sizeof(inputDataType)));
dedispersedData.resize(observation.getNrSyntheticBeams() * (observation.getNrDMsSubbanding() * observation.getNrDMs()) * observation.getNrSamplesPerPaddedBatch(padding / sizeof(inputDataType)));
dedispersedData_c.resize(observation_c.getNrSyntheticBeams() * observation_c.getNrDMs() * observation_c.getNrSamplesPerPaddedBatch(padding / sizeof(inputDataType)));
} else {
dispersedData.resize(observation_c.getNrBeams() * observation_c.getNrChannels() * isa::utils::pad(observation_c.getNrSamplesPerDispersedChannel() / (8 / inputBits), padding / sizeof(inputDataType)));
subbandedData.resize(observation.getNrBeams() * observation.getNrSubbands() * isa::utils::pad(observation.getNrSamplesPerSubbandingDispersedChannel() / (8 / inputBits), padding / sizeof(inputDataType)));
dedispersedData.resize(observation.getNrSyntheticBeams() * (observation.getNrDMsSubbanding() * observation.getNrDMs()) * isa::utils::pad(observation.getNrSamplesPerBatch() / (8 / inputBits), padding / sizeof(inputDataType)));
dedispersedData_c.resize(observation_c.getNrSyntheticBeams() * observation_c.getNrDMs() * isa::utils::pad(observation_c.getNrSamplesPerBatch() / (8 / inputBits), padding / sizeof(inputDataType)));
}
// Generate data
srand(time(0));
for ( unsigned int beam = 0; beam < observation_c.getNrBeams(); beam++ ) {
for ( unsigned int channel = 0; channel < observation_c.getNrChannels(); channel++ ) {
for ( unsigned int sample = 0; sample < observation_c.getNrSamplesPerDispersedChannel(); sample++ ) {
if ( inputBits >= 8 ) {
dispersedData[(beam * observation_c.getNrChannels() * observation_c.getNrSamplesPerPaddedDispersedChannel(padding / sizeof(inputDataType))) + (channel * observation_c.getNrSamplesPerPaddedDispersedChannel(padding / sizeof(inputDataType))) + sample] = rand() % observation_c.getNrChannels();
} else {
unsigned int byte = 0;
uint8_t firstBit = 0;
uint8_t value = rand() % inputBits;
uint8_t buffer = 0;
byte = sample / (8 / inputBits);
firstBit = (sample % (8 / inputBits)) * inputBits;
buffer = dispersedData[(beam * observation_c.getNrChannels() * isa::utils::pad(observation_c.getNrSamplesPerDispersedChannel() / (8 / inputBits), padding / sizeof(inputDataType))) + (channel * isa::utils::pad(observation_c.getNrSamplesPerDispersedChannel() / (8 / inputBits), padding / sizeof(inputDataType))) + byte];
for ( unsigned int bit = 0; bit < inputBits; bit++ ) {
isa::utils::setBit(buffer, isa::utils::getBit(value, bit), firstBit + bit);
}
dispersedData[(beam * observation_c.getNrChannels() * isa::utils::pad(observation_c.getNrSamplesPerDispersedChannel() / (8 / inputBits), padding / sizeof(inputDataType))) + (channel * isa::utils::pad(observation_c.getNrSamplesPerDispersedChannel() / (8 / inputBits), padding / sizeof(inputDataType))) + byte] = buffer;
}
}
}
}
for ( unsigned int beam = 0; beam < observation_c.getNrSyntheticBeams(); beam++ ) {
for ( unsigned int channel = 0; channel < observation_c.getNrChannels(); channel++ ) {
beamDriver[(beam * observation_c.getNrPaddedChannels(padding / sizeof(uint8_t))) + channel] = rand() % observation_c.getNrBeams();
}
}
std::fill(subbandedData.begin(), subbandedData.end(), 0);
std::fill(dedispersedData.begin(), dedispersedData.end(), 0);
std::fill(dedispersedData_c.begin(), dedispersedData_c.end(), 0);
// Execute dedispersion
PulsarSearch::dedispersion< inputDataType, intermediateDataType, outputDataType >(observation_c, zappedChannels, beamDriver, dispersedData, dedispersedData_c, *shifts, padding, inputBits);
PulsarSearch::subbandDedispersionStepOne< inputDataType, intermediateDataType, outputDataType >(observation, zappedChannels, dispersedData, subbandedData, *shifts, padding, inputBits);
PulsarSearch::subbandDedispersionStepTwo< outputDataType, intermediateDataType, outputDataType >(observation, beamDriver, subbandedData, dedispersedData, *shifts, padding);
for ( unsigned int sBeam = 0; sBeam < observation.getNrSyntheticBeams(); sBeam++ ) {
for ( unsigned int firstStepDM = 0; firstStepDM < observation.getNrDMsSubbanding(); firstStepDM++ ) {
for ( unsigned int dm = 0; dm < observation.getNrDMs(); dm++ ) {
if ( printResults ) {
std::cout << "sBeam: " << sBeam << " DM: " << (firstStepDM * observation.getNrDMs()) + dm << std::endl;
}
for ( unsigned int sample = 0; sample < observation.getNrSamplesPerBatch(); sample++ ) {
if ( !isa::utils::same(dedispersedData[(sBeam * observation.getNrDMsSubbanding() * observation.getNrDMs() * observation.getNrSamplesPerPaddedBatch(padding / sizeof(outputDataType))) + (firstStepDM * observation.getNrDMs() * observation.getNrSamplesPerPaddedBatch(padding / sizeof(outputDataType))) + (dm * observation.getNrSamplesPerPaddedBatch(padding / sizeof(outputDataType))) + sample], dedispersedData_c[(sBeam * observation_c.getNrDMs() * observation.getNrSamplesPerPaddedBatch(padding / sizeof(outputDataType))) + (((firstStepDM * observation.getNrDMs()) + dm) * observation.getNrSamplesPerPaddedBatch(padding / sizeof(outputDataType))) + sample]) ) {
wrongSamples++;
}
if ( printResults ) {
std::cout << dedispersedData[(sBeam * observation.getNrDMsSubbanding() * observation.getNrDMs() * observation.getNrSamplesPerPaddedBatch(padding / sizeof(outputDataType))) + (firstStepDM * observation.getNrDMs() * observation.getNrSamplesPerPaddedBatch(padding / sizeof(outputDataType))) + (dm * observation.getNrSamplesPerPaddedBatch(padding / sizeof(outputDataType))) + sample] << "," << dedispersedData_c[(sBeam * observation_c.getNrDMs() * observation.getNrSamplesPerPaddedBatch(padding / sizeof(outputDataType))) + (((firstStepDM * observation.getNrDMs()) + dm) * observation.getNrSamplesPerPaddedBatch(padding / sizeof(outputDataType))) + sample] << " ";
}
}
if ( printResults ) {
std::cout << std::endl;
}
}
}
}
if ( wrongSamples > 0 ) {
std::cout << "Wrong samples: " << wrongSamples << " (" << (wrongSamples * 100.0) / (static_cast< uint64_t >(observation_c.getNrSyntheticBeams()) * observation_c.getNrDMs() * observation_c.getNrSamplesPerBatch()) << "%)." << std::endl;
} else {
std::cout << "TEST PASSED." << std::endl;
}
return 0;
}
<|endoftext|> |
<commit_before>// @(#)root/mathcore:$Id$
// Author: L. Moneta Fri Dec 22 14:43:33 2006
/**********************************************************************
* *
* Copyright (c) 2006 LCG ROOT Math Team, CERN/PH-SFT *
* *
* *
**********************************************************************/
// Implementation file for class MinimizerFactory
#include "Math/Factory.h"
#include "Math/Error.h"
#include "RConfigure.h"
#include "Math/Minimizer.h"
#include "Math/MinimizerOptions.h"
#include "Math/DistSampler.h"
#include "Math/DistSamplerOptions.h"
// uncomment these if you dont want to use the plugin manager
// but you need to link also the needed minimization libraries (e.g Minuit and/or Minuit2)
// #define MATH_NO_PLUGIN_MANAGER
// #define HAS_MINUIT
// #define HAS_MINUIT2
#ifndef MATH_NO_PLUGIN_MANAGER
// use ROOT Plug-in manager
#include "TPluginManager.h"
#include "TROOT.h"
#include "TVirtualMutex.h"
#else
// all the minimizer implementation classes
//#define HAS_MINUIT2
#ifdef HAS_MINUIT2
#include "Minuit2/Minuit2Minimizer.h"
#endif
#ifdef HAS_MINUIT
#include "TMinuitMinimizer.h"
#endif
#ifdef R__HAS_MATHMORE
#include "Math/GSLMinimizer.h"
#include "Math/GSLNLSMinimizer.h"
#include "Math/GSLSimAnMinimizer.h"
#endif
#endif
#include <algorithm>
#include <cassert>
//#define DEBUG
#ifdef DEBUG
#include <iostream>
#endif
#ifndef MATH_NO_PLUGIN_MANAGER
// use ROOT Plugin Manager to create Minimizer concrete classes
ROOT::Math::Minimizer * ROOT::Math::Factory::CreateMinimizer(const std::string & minimizerType,const std::string & algoType)
{
// create Minimizer using the plug-in manager given the type of Minimizer (MINUIT, MINUIT2, FUMILI, etc..) and
// algorithm (MIGRAD, SIMPLEX, etc..)
const char * minim = minimizerType.c_str();
const char * algo = algoType.c_str();
//case of fumili2
std::string s1,s2;
if (minimizerType == "Fumili2" ) {
s1 = "Minuit2";
s2 = "fumili";
minim = s1.c_str();
algo = s2.c_str();
}
if (minimizerType == "TMinuit") {
s1 = "Minuit";
minim = s1.c_str();
}
if (minimizerType.empty() ) minim = ROOT::Math::MinimizerOptions::DefaultMinimizerType().c_str();
R__LOCKGUARD2(gROOTMutex);
// create Minimizer using the PM
TPluginHandler *h;
//gDebug = 3;
if ((h = gROOT->GetPluginManager()->FindHandler("ROOT::Math::Minimizer",minim ))) {
if (h->LoadPlugin() == -1) {
#ifdef DEBUG
std::cout << "Error Loading ROOT::Math::Minimizer " << minim << std::endl;
#endif
return 0;
}
// create plug-in with required algorithm
ROOT::Math::Minimizer * min = reinterpret_cast<ROOT::Math::Minimizer *>( h->ExecPlugin(1,algo ) );
#ifdef DEBUG
if (min != 0)
std::cout << "Loaded Minimizer " << minimizerType << " " << algoType << std::endl;
else
std::cout << "Error creating Minimizer " << minimizerType << " " << algoType << std::endl;
#endif
return min;
}
return 0;
}
#else
// use directly classes instances
ROOT::Math::Minimizer * ROOT::Math::Factory::CreateMinimizer(const std::string & minimizerType, const std::string & algoType)
{
// static method to create a minimizer .
// not using PM so direct dependency on all libraries (Minuit, Minuit2, MathMore, etc...)
// The default is the Minuit2 minimizer or GSL Minimizer
// should use enumerations instead of string ?
Minimizer * min = 0;
std::string algo = algoType;
#ifdef HAS_MINUIT2
if (minimizerType == "Minuit2")
min = new ROOT::Minuit2::Minuit2Minimizer(algoType.c_str());
if (minimizerType == "Fumili2")
min = new ROOT::Minuit2::Minuit2Minimizer("fumili");
#endif
#ifdef HAS_MINUIT
// use TMinuit
if (minimizerType == "Minuit" || minimizerType == "TMinuit")
min = new TMinuitMinimizer(algoType.c_str());
#endif
#ifdef R__HAS_MATHMORE
// use GSL minimizer
if (minimizerType == "GSL")
min = new ROOT::Math::GSLMinimizer(algoType.c_str());
else if (minimizerType == "GSL_NLS")
min = new ROOT::Math::GSLNLSMinimizer();
else if (minimizerType == "GSL_SIMAN")
min = new ROOT::Math::GSLSimAnMinimizer();
#endif
#ifdef HAS_MINUIT2
// DEFAULT IS MINUIT2 based on MIGRAD id minuit2 exists
else
min = new ROOT::Minuit2::Minuit2Minimizer();
#endif
return min;
}
#endif
ROOT::Math::DistSampler * ROOT::Math::Factory::CreateDistSampler(const std::string & type) {
#ifdef MATH_NO_PLUGIN_MANAGER
MATH_ERROR_MSG("Factory::CreateDistSampler","ROOT plug-in manager not available");
return 0;
#else
// create a DistSampler class using the ROOT plug-in manager
const char * typeName = type.c_str();
if (type.empty() ) typeName = ROOT::Math::DistSamplerOptions::DefaultSampler().c_str();
TPluginManager *pm = gROOT->GetPluginManager();
assert(pm != 0);
TPluginHandler *h = pm->FindHandler("ROOT::Math::DistSampler", typeName );
if (h != 0) {
if (h->LoadPlugin() == -1) {
MATH_ERROR_MSG("Factory::CreateDistSampler","Error loading DistSampler plug-in");
return 0;
}
ROOT::Math::DistSampler * smp = reinterpret_cast<ROOT::Math::DistSampler *>( h->ExecPlugin(0) );
assert(smp != 0);
return smp;
}
MATH_ERROR_MSGVAL("Factory::CreateDistSampler","Error finding DistSampler plug-in",typeName);
return 0;
#endif
}
<commit_msg>Fix also the DistSampler<commit_after>// @(#)root/mathcore:$Id$
// Author: L. Moneta Fri Dec 22 14:43:33 2006
/**********************************************************************
* *
* Copyright (c) 2006 LCG ROOT Math Team, CERN/PH-SFT *
* *
* *
**********************************************************************/
// Implementation file for class MinimizerFactory
#include "Math/Factory.h"
#include "Math/Error.h"
#include "RConfigure.h"
#include "Math/Minimizer.h"
#include "Math/MinimizerOptions.h"
#include "Math/DistSampler.h"
#include "Math/DistSamplerOptions.h"
// uncomment these if you dont want to use the plugin manager
// but you need to link also the needed minimization libraries (e.g Minuit and/or Minuit2)
// #define MATH_NO_PLUGIN_MANAGER
// #define HAS_MINUIT
// #define HAS_MINUIT2
#ifndef MATH_NO_PLUGIN_MANAGER
// use ROOT Plug-in manager
#include "TPluginManager.h"
#include "TROOT.h"
#include "TVirtualMutex.h"
#else
// all the minimizer implementation classes
//#define HAS_MINUIT2
#ifdef HAS_MINUIT2
#include "Minuit2/Minuit2Minimizer.h"
#endif
#ifdef HAS_MINUIT
#include "TMinuitMinimizer.h"
#endif
#ifdef R__HAS_MATHMORE
#include "Math/GSLMinimizer.h"
#include "Math/GSLNLSMinimizer.h"
#include "Math/GSLSimAnMinimizer.h"
#endif
#endif
#include <algorithm>
#include <cassert>
//#define DEBUG
#ifdef DEBUG
#include <iostream>
#endif
#ifndef MATH_NO_PLUGIN_MANAGER
// use ROOT Plugin Manager to create Minimizer concrete classes
ROOT::Math::Minimizer * ROOT::Math::Factory::CreateMinimizer(const std::string & minimizerType,const std::string & algoType)
{
// create Minimizer using the plug-in manager given the type of Minimizer (MINUIT, MINUIT2, FUMILI, etc..) and
// algorithm (MIGRAD, SIMPLEX, etc..)
const char * minim = minimizerType.c_str();
const char * algo = algoType.c_str();
//case of fumili2
std::string s1,s2;
if (minimizerType == "Fumili2" ) {
s1 = "Minuit2";
s2 = "fumili";
minim = s1.c_str();
algo = s2.c_str();
}
if (minimizerType == "TMinuit") {
s1 = "Minuit";
minim = s1.c_str();
}
if (minimizerType.empty() ) minim = ROOT::Math::MinimizerOptions::DefaultMinimizerType().c_str();
R__LOCKGUARD2(gROOTMutex);
// create Minimizer using the PM
TPluginHandler *h;
//gDebug = 3;
if ((h = gROOT->GetPluginManager()->FindHandler("ROOT::Math::Minimizer",minim ))) {
if (h->LoadPlugin() == -1) {
#ifdef DEBUG
std::cout << "Error Loading ROOT::Math::Minimizer " << minim << std::endl;
#endif
return 0;
}
// create plug-in with required algorithm
ROOT::Math::Minimizer * min = reinterpret_cast<ROOT::Math::Minimizer *>( h->ExecPlugin(1,algo ) );
#ifdef DEBUG
if (min != 0)
std::cout << "Loaded Minimizer " << minimizerType << " " << algoType << std::endl;
else
std::cout << "Error creating Minimizer " << minimizerType << " " << algoType << std::endl;
#endif
return min;
}
return 0;
}
#else
// use directly classes instances
ROOT::Math::Minimizer * ROOT::Math::Factory::CreateMinimizer(const std::string & minimizerType, const std::string & algoType)
{
// static method to create a minimizer .
// not using PM so direct dependency on all libraries (Minuit, Minuit2, MathMore, etc...)
// The default is the Minuit2 minimizer or GSL Minimizer
// should use enumerations instead of string ?
Minimizer * min = 0;
std::string algo = algoType;
#ifdef HAS_MINUIT2
if (minimizerType == "Minuit2")
min = new ROOT::Minuit2::Minuit2Minimizer(algoType.c_str());
if (minimizerType == "Fumili2")
min = new ROOT::Minuit2::Minuit2Minimizer("fumili");
#endif
#ifdef HAS_MINUIT
// use TMinuit
if (minimizerType == "Minuit" || minimizerType == "TMinuit")
min = new TMinuitMinimizer(algoType.c_str());
#endif
#ifdef R__HAS_MATHMORE
// use GSL minimizer
if (minimizerType == "GSL")
min = new ROOT::Math::GSLMinimizer(algoType.c_str());
else if (minimizerType == "GSL_NLS")
min = new ROOT::Math::GSLNLSMinimizer();
else if (minimizerType == "GSL_SIMAN")
min = new ROOT::Math::GSLSimAnMinimizer();
#endif
#ifdef HAS_MINUIT2
// DEFAULT IS MINUIT2 based on MIGRAD id minuit2 exists
else
min = new ROOT::Minuit2::Minuit2Minimizer();
#endif
return min;
}
#endif
ROOT::Math::DistSampler * ROOT::Math::Factory::CreateDistSampler(const std::string & type) {
#ifdef MATH_NO_PLUGIN_MANAGER
MATH_ERROR_MSG("Factory::CreateDistSampler","ROOT plug-in manager not available");
return 0;
#else
// create a DistSampler class using the ROOT plug-in manager
const char * typeName = type.c_str();
if (type.empty() ) typeName = ROOT::Math::DistSamplerOptions::DefaultSampler().c_str();
R__LOCKGUARD2(gROOTMutex);
TPluginManager *pm = gROOT->GetPluginManager();
assert(pm != 0);
TPluginHandler *h = pm->FindHandler("ROOT::Math::DistSampler", typeName );
if (h != 0) {
if (h->LoadPlugin() == -1) {
MATH_ERROR_MSG("Factory::CreateDistSampler","Error loading DistSampler plug-in");
return 0;
}
ROOT::Math::DistSampler * smp = reinterpret_cast<ROOT::Math::DistSampler *>( h->ExecPlugin(0) );
assert(smp != 0);
return smp;
}
MATH_ERROR_MSGVAL("Factory::CreateDistSampler","Error finding DistSampler plug-in",typeName);
return 0;
#endif
}
<|endoftext|> |
<commit_before>// following example from:
// http://www.boost.org/doc/libs/1_58_0/libs/spirit/example/qi/employee.cpp
// std includes
#include <iostream>
#include <string>
// boost includes
#include <boost/spirit/include/qi.hpp>
namespace frontend {
namespace spirit = boost::spirit;
namespace qi = spirit::qi;
namespace ascii = spirit::ascii;
struct cursor {
std::string file;
unsigned long long offset;
unsigned long long line;
unsigned long long col;
// verify inputs using enum
// decl/ref/defn/call
std::string reference_type;
// variable/function/scope/label/type
std::string specifier;
// if variable/function, then type
std::string type;
std::string language;
std::string name;
std::string scope;
};
}
// adapt struct to boost fusion
BOOST_FUSION_ADAPT_STRUCT(frontend::cursor, (std::string, file),
(unsigned long long, offset),
(unsigned long long, line), (unsigned long long, col),
(std::string, reference_type),
(std::string, specifier), (std::string, type),
(std::string, language), (std::string, name),
(std::string, scope));
namespace frontend {
template <typename Iterator>
struct cursor_parser : qi::grammar<Iterator, cursor(), ascii::space_type> {
qi::rule<Iterator, std::string(), ascii::space_type> quoted_string;
qi::rule<Iterator, cursor(), ascii::space_type> start;
cursor_parser() : cursor_parser::base_type(start) {
using qi::uint_;
using qi::lexeme;
using ascii::char_;
quoted_string %= lexeme['"' >> +(char_ - '"') >> '"'];
start %=
// file
quoted_string >> ',' >>
// offset
uint_ >> ',' >>
// line
uint_ >> ',' >>
// col
uint_ >> ',' >>
// reference_type
quoted_string >> ',' >>
// specifier
quoted_string >> ',' >>
// type
quoted_string >> ',' >>
// language
quoted_string >> ',' >>
// name
quoted_string >> ',' >>
// scope
quoted_string;
}
};
}
int main() {
std::string s;
frontend::cursor c;
while (getline(std::cin, s)) {
c = {}; // zero it out
if (phrase_parse(s.cbegin(), s.cend(),
frontend::cursor_parser<std::string::const_iterator>(),
boost::spirit::ascii::space, c)) {
std::cout << boost::fusion::as_vector(c) << std::endl;
std::cerr << c.file << std::endl;
} else {
std::cerr << "failed!" << std::endl;
return 1;
}
}
std::cerr << "completed!" << std::endl;
return 0;
}
<commit_msg>got newline working<commit_after>// following example from:
// http://www.boost.org/doc/libs/1_58_0/libs/spirit/example/qi/employee.cpp
// std includes
#include <iostream>
#include <string>
// boost includes
#include <boost/spirit/include/qi.hpp>
namespace frontend {
namespace spirit = boost::spirit;
namespace qi = spirit::qi;
namespace ascii = spirit::ascii;
struct cursor {
std::string file;
unsigned long long offset;
unsigned long long line;
unsigned long long col;
// verify inputs using enum
// decl/ref/defn/call
std::string reference_type;
// variable/function/scope/label/type
std::string specifier;
// if variable/function, then type
std::string type;
std::string language;
std::string name;
std::string scope;
};
}
// adapt struct to boost fusion
BOOST_FUSION_ADAPT_STRUCT(frontend::cursor, (std::string, file),
(unsigned long long, offset),
(unsigned long long, line), (unsigned long long, col),
(std::string, reference_type),
(std::string, specifier), (std::string, type),
(std::string, language), (std::string, name),
(std::string, scope));
namespace frontend {
template <typename Iterator>
struct cursor_parser : qi::grammar<Iterator, cursor(), qi::blank_type> {
qi::rule<Iterator, std::string(), qi::blank_type> quoted_string;
qi::rule<Iterator, cursor(), qi::blank_type> start;
cursor_parser() : cursor_parser::base_type(start) {
using qi::uint_;
using qi::lexeme;
using ascii::char_;
quoted_string %= lexeme['"' >> +(char_ - '"') >> '"'];
start %=
// file
quoted_string >> ',' >>
// offset
uint_ >> ',' >>
// line
uint_ >> ',' >>
// col
uint_ >> ',' >>
// reference_type
quoted_string >> ',' >>
// specifier
quoted_string >> ',' >>
// type
quoted_string >> ',' >>
// language
quoted_string >> ',' >>
// name
quoted_string >> ',' >>
// scope
quoted_string;
}
};
// template <typename Iterator>
// bool parse_cursors_as_vector(Iterator first, Iterator last,
// std::vector<cursor> &v) {
// bool res = qi::phrase_parse(first, last, (cursor_parser % qi::eol), )
// }
}
int main() {
std::string s;
frontend::cursor c;
while (getline(std::cin, s)) {
s += '\n';
c = {}; // zero it out
if (phrase_parse(s.cbegin(), s.cend(),
frontend::cursor_parser<std::string::const_iterator>(),
boost::spirit::qi::blank, c)) {
std::cout << boost::fusion::as_vector(c) << std::endl;
std::cerr << c.file << std::endl;
} else {
std::cerr << "failed!" << std::endl;
return 1;
}
}
std::cerr << "completed!" << std::endl;
return 0;
}
<|endoftext|> |
<commit_before>#include "Evaluator.h"
#include "Globals.h"
#include "SquareHelpers.h"
Evaluator::Evaluator()
{
_params = EvalParams();
}
Evaluator::Evaluator(const EvalParams& params)
{
_params = params;
}
int Evaluator::operator()(const Board& board) const
{
int terminalScore = 0;
return TerminalScore(board, &terminalScore)
? terminalScore
: MaterialScore(board) + LaserableScore(board);
}
int Evaluator::Distance(int loc1, int loc2) const
{
int xDiff = std::abs((loc1 - loc2) % BoardWidth);
int yDiff = std::abs((loc1 - loc2) / BoardWidth);
return xDiff + yDiff;
}
bool Evaluator::TerminalScore(const Board& board, int* score) const
{
bool terminal = board.IsCheckmate() || board.IsDraw();
if (terminal)
{
*score = board.IsDraw()
? 0
: _params.CheckmateVal() * (GetOwner(board.LastCapture()) == Player::Silver ? -1 : 1);
}
return terminal;
}
int Evaluator::MaterialScore(const Board& board) const
{
int eval = 0, pieceVal, pharaohVal, pharaohLoc;
Piece piece;
Player player;
Square sq;
for (size_t i = 0; i < BoardArea; i++)
{
sq = board.Get(i);
if (sq != OffBoard && sq != Empty)
{
player = GetOwner(sq);
piece = GetPiece(sq);
pieceVal = _params.PieceVal(piece);
pharaohLoc = board.PharaohPosition(player);
pharaohVal = piece == Piece::Scarab ? _params.PiecePharaohVal(Distance(i, pharaohLoc)) : 0;
eval += (pieceVal + pharaohVal) * (player == Player::Silver ? 1 : -1);
}
}
return eval;
}
int Evaluator::LaserableScore(const Board& board) const
{
return LaserableScore(Player::Silver, board) - LaserableScore(Player::Red, board);
}
int Evaluator::LaserableScore(Player player, const Board& board) const
{
int squares = 0;
int bonus = 0;
int enemyPharaoh = board.PharaohPosition(
player == Player::Silver ? Player::Red : Player::Silver);
// Find the starting location and direction for the laser beam.
int loc = Sphinx[(int)player];
int dirIndex = GetOrientation(board.Get(loc));
int dir, p;
Square dest = Empty;
while (dest != OffBoard && dirIndex >= 0)
{
dir = Directions[dirIndex];
// Take a step with the laser beam.
loc += dir;
// Is this location occupied?
dest = board.Get(loc);
if (IsPiece(dest))
{
p = (int)GetPiece(dest);
dirIndex = Reflections[dirIndex][p - 2][GetOrientation(dest)];
}
else
{
++squares;
}
bonus += _params.LaserPharaohVal(Distance(enemyPharaoh, loc));
}
return _params.LaserVal() * squares + bonus;
}
<commit_msg>Improved distance metric.<commit_after>#include "Evaluator.h"
#include "Globals.h"
#include "SquareHelpers.h"
Evaluator::Evaluator()
{
_params = EvalParams();
}
Evaluator::Evaluator(const EvalParams& params)
{
_params = params;
}
int Evaluator::operator()(const Board& board) const
{
int terminalScore = 0;
return TerminalScore(board, &terminalScore)
? terminalScore
: MaterialScore(board) + LaserableScore(board);
}
int Evaluator::Distance(int loc1, int loc2) const
{
int xDiff = std::abs((loc1 - loc2) % BoardWidth);
int yDiff = std::abs((loc1 - loc2) / BoardWidth);
return std::max(xDiff, yDiff);
}
bool Evaluator::TerminalScore(const Board& board, int* score) const
{
bool terminal = board.IsCheckmate() || board.IsDraw();
if (terminal)
{
*score = board.IsDraw()
? 0
: _params.CheckmateVal() * (GetOwner(board.LastCapture()) == Player::Silver ? -1 : 1);
}
return terminal;
}
int Evaluator::MaterialScore(const Board& board) const
{
int eval = 0, pieceVal, pharaohVal, pharaohLoc;
Piece piece;
Player player;
Square sq;
for (size_t i = 0; i < BoardArea; i++)
{
sq = board.Get(i);
if (sq != OffBoard && sq != Empty)
{
player = GetOwner(sq);
piece = GetPiece(sq);
pieceVal = _params.PieceVal(piece);
pharaohLoc = board.PharaohPosition(player);
pharaohVal = piece == Piece::Scarab ? _params.PiecePharaohVal(Distance(i, pharaohLoc)) : 0;
eval += (pieceVal + pharaohVal) * (player == Player::Silver ? 1 : -1);
}
}
return eval;
}
int Evaluator::LaserableScore(const Board& board) const
{
return LaserableScore(Player::Silver, board) - LaserableScore(Player::Red, board);
}
int Evaluator::LaserableScore(Player player, const Board& board) const
{
int squares = 0;
int bonus = 0;
int enemyPharaoh = board.PharaohPosition(
player == Player::Silver ? Player::Red : Player::Silver);
// Find the starting location and direction for the laser beam.
int loc = Sphinx[(int)player];
int dirIndex = GetOrientation(board.Get(loc));
int dir, p;
Square dest = Empty;
while (dest != OffBoard && dirIndex >= 0)
{
dir = Directions[dirIndex];
// Take a step with the laser beam.
loc += dir;
// Is this location occupied?
dest = board.Get(loc);
if (IsPiece(dest))
{
p = (int)GetPiece(dest);
dirIndex = Reflections[dirIndex][p - 2][GetOrientation(dest)];
}
else
{
++squares;
}
bonus += _params.LaserPharaohVal(Distance(enemyPharaoh, loc));
}
return _params.LaserVal() * squares + bonus;
}
<|endoftext|> |
<commit_before>#include "../include/parlex/detail/abstract_syntax_tree.hpp"
#include "graphviz_dot.hpp"
#include "parlex/builder.hpp"
#include "parlex/detail/grammar.hpp"
parlex::detail::ast_node::ast_node(match const & m, std::vector<ast_node> const & children, leaf const * l) : match(m), children(children), l(l) {}
std::string parlex::detail::ast_node::to_dot(grammar const & g) const
{
auto const nameFunc = [&](ast_node const * n)
{
std::stringstream result;
result << g.get_recognizer(uint16_t(n->l->recognizer_index)).name << " (" << n << ")";
return result.str();
};
auto const edgeFunc = [&](ast_node const * n) {
std::vector<std::pair<std::string, ast_node const *>> results;
for (auto i = n->children.begin(); i != n->children.end(); ++i) {
results.emplace_back("label=" + enquote(std::to_string(i - n->children.begin() + 1)), &*i);
}
return results;
};
auto const propFunc = [&](ast_node const * n) { return std::string(); };
return directed_graph<ast_node const *>(this, nameFunc, edgeFunc, propFunc);
}
<commit_msg>Make the output of ast_node::to_dot give friendlier node names.<commit_after>#include "../include/parlex/detail/abstract_syntax_tree.hpp"
#include "graphviz_dot.hpp"
#include "parlex/builder.hpp"
#include "parlex/detail/grammar.hpp"
parlex::detail::ast_node::ast_node(match const & m, std::vector<ast_node> const & children, leaf const * l) : match(m), children(children), l(l) {}
std::string parlex::detail::ast_node::to_dot(grammar const & g) const
{
auto const nameFunc = [&](ast_node const * n)
{
std::stringstream result;
result << g.get_recognizer(n->recognizer_index).name << " (" + std::to_string(n->document_position + 1) + " - " + std::to_string(n->consumed_character_count + n->document_position) + ")";
return result.str();
};
auto const edgeFunc = [&](ast_node const * n) {
std::vector<std::pair<std::string, ast_node const *>> results;
for (auto i = n->children.begin(); i != n->children.end(); ++i) {
results.emplace_back("label=" + enquote(std::to_string(i - n->children.begin() + 1)), &*i);
}
return results;
};
auto const propFunc = [&](ast_node const * n) { return std::string(); };
return directed_graph<ast_node const *>(this, nameFunc, edgeFunc, propFunc);
}
<|endoftext|> |
<commit_before>////////////////////////////////////////////////////////////////////////////
///
/// WraithOne tech Engine
///
/// https://github.com/WraithOne/WOtech
/// by https://twitter.com/WraithOne
///
/// File: Gametimer.cpp
///
/// Description:
///
/// Created: 12.05.2014
/// Edited: 06.11.2016
///
////////////////////////////////////////////////////////////////////////////
//////////////
// INCLUDES //
//////////////
#include "pch.h"
#include "GameTimer.h"
namespace WOtech
{
GameTimer::GameTimer() : m_active(false)
{
LARGE_INTEGER frequency;
if (!QueryPerformanceFrequency(&frequency))
{
//g_pLogfile->Textout(RED, false, "QueryPreformanceFrequency FAILED <frequency>");
}
m_secondsPerCount = 1.0f / static_cast<float32>(frequency.QuadPart);
Reset();
}
float32 GameTimer::PlayingTime()
{
if (m_active)
{
// The distance m_currentTime - m_baseTime includes paused time,
// which we do not want to count. To correct this, we can subtract
// the paused time from m_currentTime:
return static_cast<float32>(((m_currentTime.QuadPart - m_pausedTime.QuadPart) - m_baseTime.QuadPart)*m_secondsPerCount);
}
else
{
// The clock is currently not running so don't count the time since
// the clock was stopped
return static_cast<float32>(((m_stopTime.QuadPart - m_pausedTime.QuadPart) - m_baseTime.QuadPart)*m_secondsPerCount);
}
}
void GameTimer::PlayingTime(_In_ float32 time)
{
// Reset the internal state to reflect a PlayingTime of 'time'
// Offset the baseTime by this 'time'.
m_baseTime.QuadPart = m_stopTime.QuadPart - static_cast<__int64>(time / m_secondsPerCount);
}
float32 GameTimer::DeltaTime()
{
return m_deltaTime;
}
void GameTimer::Reset()
{
LARGE_INTEGER currentTime;
if (!QueryPerformanceCounter(¤tTime))
{
//g_pLogfile->Textout(RED, false, "QueryPreformanceFrequency FAILED <currentTime>");
}
m_baseTime = currentTime;
m_previousTime = currentTime;
m_stopTime = currentTime;
m_currentTime = currentTime;
m_pausedTime.QuadPart = 0;
m_active = false;
}
void GameTimer::Start()
{
LARGE_INTEGER startTime;
if (!QueryPerformanceCounter(&startTime))
{
//g_pLogfile->Textout(RED, false, "QueryPreformanceFrequency FAILED <startTime>");
}
if (!m_active)
{
// Accumulate the time elapsed between stop and start pairs.
m_pausedTime.QuadPart += (startTime.QuadPart - m_stopTime.QuadPart);
m_previousTime = startTime;
m_stopTime.QuadPart = 0;
m_active = true;
}
}
void GameTimer::Stop()
{
if (m_active)
{
// Set the stop time to the time of the last update.
m_stopTime = m_currentTime;
m_active = false;
}
}
void GameTimer::Update()
{
if (!m_active)
{
m_deltaTime = 0.0;
return;
}
LARGE_INTEGER currentTime;
if (!QueryPerformanceCounter(¤tTime))
{
//g_pLogfile->Textout(RED, false, "QueryPreformanceFrequency FAILED <currentTime>");
}
m_currentTime = currentTime;
m_deltaTime = (m_currentTime.QuadPart - m_previousTime.QuadPart)*m_secondsPerCount;
m_previousTime = m_currentTime;
if (m_deltaTime < 0.0)
{
m_deltaTime = 0.0;
}
}
}//namespace WOtech<commit_msg>fixed variable initialisation<commit_after>////////////////////////////////////////////////////////////////////////////
///
/// WraithOne tech Engine
///
/// https://github.com/WraithOne/WOtech
/// by https://twitter.com/WraithOne
///
/// File: Gametimer.cpp
///
/// Description:
///
/// Created: 12.05.2014
/// Edited: 06.11.2016
///
////////////////////////////////////////////////////////////////////////////
//////////////
// INCLUDES //
//////////////
#include "pch.h"
#include "GameTimer.h"
namespace WOtech
{
GameTimer::GameTimer() : m_active(false), m_secondsPerCount(0.0f), m_deltaTime(0.0f)
{
LARGE_INTEGER frequency;
if (!QueryPerformanceFrequency(&frequency))
{
//g_pLogfile->Textout(RED, false, "QueryPreformanceFrequency FAILED <frequency>");
}
m_secondsPerCount = 1.0f / static_cast<float32>(frequency.QuadPart);
Reset();
}
float32 GameTimer::PlayingTime()
{
if (m_active)
{
// The distance m_currentTime - m_baseTime includes paused time,
// which we do not want to count. To correct this, we can subtract
// the paused time from m_currentTime:
return static_cast<float32>(((m_currentTime.QuadPart - m_pausedTime.QuadPart) - m_baseTime.QuadPart)*m_secondsPerCount);
}
else
{
// The clock is currently not running so don't count the time since
// the clock was stopped
return static_cast<float32>(((m_stopTime.QuadPart - m_pausedTime.QuadPart) - m_baseTime.QuadPart)*m_secondsPerCount);
}
}
void GameTimer::PlayingTime(_In_ float32 time)
{
// Reset the internal state to reflect a PlayingTime of 'time'
// Offset the baseTime by this 'time'.
m_baseTime.QuadPart = m_stopTime.QuadPart - static_cast<__int64>(time / m_secondsPerCount);
}
float32 GameTimer::DeltaTime()
{
return m_deltaTime;
}
void GameTimer::Reset()
{
LARGE_INTEGER currentTime;
if (!QueryPerformanceCounter(¤tTime))
{
//g_pLogfile->Textout(RED, false, "QueryPreformanceFrequency FAILED <currentTime>");
}
m_baseTime = currentTime;
m_previousTime = currentTime;
m_stopTime = currentTime;
m_currentTime = currentTime;
m_pausedTime.QuadPart = 0;
m_active = false;
}
void GameTimer::Start()
{
LARGE_INTEGER startTime;
if (!QueryPerformanceCounter(&startTime))
{
//g_pLogfile->Textout(RED, false, "QueryPreformanceFrequency FAILED <startTime>");
}
if (!m_active)
{
// Accumulate the time elapsed between stop and start pairs.
m_pausedTime.QuadPart += (startTime.QuadPart - m_stopTime.QuadPart);
m_previousTime = startTime;
m_stopTime.QuadPart = 0;
m_active = true;
}
}
void GameTimer::Stop()
{
if (m_active)
{
// Set the stop time to the time of the last update.
m_stopTime = m_currentTime;
m_active = false;
}
}
void GameTimer::Update()
{
if (!m_active)
{
m_deltaTime = 0.0;
return;
}
LARGE_INTEGER currentTime;
if (!QueryPerformanceCounter(¤tTime))
{
//g_pLogfile->Textout(RED, false, "QueryPreformanceFrequency FAILED <currentTime>");
}
m_currentTime = currentTime;
m_deltaTime = (m_currentTime.QuadPart - m_previousTime.QuadPart)*m_secondsPerCount;
m_previousTime = m_currentTime;
if (m_deltaTime < 0.0)
{
m_deltaTime = 0.0;
}
}
}//namespace WOtech<|endoftext|> |
<commit_before>/*
* Detect_Breapoints.cpp
*
* Created on: Jun 19, 2015
* Author: fsedlaze
*/
#include "Detect_Breakpoints.h"
#include "../tree/IntervallTree.h"
#include "../tree/TNode.h"
long get_ref_lengths(int id, RefVector ref) {
long length = 0;
for (size_t i = 0; i < (size_t) id && i < ref.size(); i++) {
length += ref[i].RefLength + Parameter::Instance()->max_dist;
}
return length;
}
void flush_tree(IntervallTree & local_tree, TNode *& local_root, IntervallTree & final, TNode *& root_final, long pos) {
IntervallTree tmp_tree;
TNode *tmp_root = NULL;
std::vector<Breakpoint *> points;
local_tree.get_breakpoints(local_root, points);
clarify(points);
for (int i = 0; i < points.size(); i++) {
if (abs(pos - points[i]->get_coordinates().start.min_pos) < 100000 || abs(pos - points[i]->get_coordinates().stop.max_pos) < 100000) { //TODO arbitrary threshold!
tmp_tree.insert(points[i], tmp_root);
} else if (points[i]->get_support() > Parameter::Instance()->min_support && points[i]->get_length() > Parameter::Instance()->min_length) {
final.insert(points[i], root_final);
}
}
local_tree.makeempty(local_root);
local_tree = tmp_tree;
local_root = tmp_root;
}
std::vector<Breakpoint *> detect_breakpoints(std::string read_filename) {
estimate_parameters(read_filename);
BamParser * mapped_file = 0;
RefVector ref;
if (read_filename.find("bam") != string::npos) {
mapped_file = new BamParser(read_filename);
ref = mapped_file->get_refInfo();
} else {
cerr << "File Format not recognized. File must be a sorted .bam file!" << endl;
exit(0);
}
//Using PlaneSweep to comp coverage and iterate through reads:
//PlaneSweep * sweep = new PlaneSweep();
std::cout << "start parsing..." << std::endl;
//Using Interval tree to store and manage breakpoints:
IntervallTree final;
TNode * root_final = NULL;
int current_RefID = 0;
//IntervallTree local_tree;
//TNode *local_root = NULL;
IntervallTree bst;
TNode *root = NULL;
Alignment * tmp_aln = mapped_file->parseRead(Parameter::Instance()->min_mq);
while (!tmp_aln->getSequence().first.empty()) {
/* if((tmp_aln->getAlignment()->IsPrimaryAlignment())){
std::cout<<tmp_aln->getName()<<" is primary"<<std::endl;
}
if(!(tmp_aln->getAlignment()->AlignmentFlag & 0x800)){
std::cout<<tmp_aln->getName()<<" is not 0x800"<<std::endl;
}
if(tmp_aln->get_is_save()){
std::cout<<tmp_aln->getName()<<" is save"<<std::endl;
}*/
if ((tmp_aln->getAlignment()->IsPrimaryAlignment()) && (!(tmp_aln->getAlignment()->AlignmentFlag & 0x800) && tmp_aln->get_is_save())) {
//TODO call after every x reads to long time store things! Requires split of TRA and others!!
//flush_tree(local_tree, local_root, final, root_final);
if (current_RefID != tmp_aln->getRefID()) { // Regular scan through the SV and move those where the end point lies far behind the current pos or reads. Eg. 1MB?
current_RefID = tmp_aln->getRefID();
std::cout << "Switch Chr " << ref[tmp_aln->getRefID()].RefName << " " << ref[tmp_aln->getRefID()].RefLength << std::endl;
std::vector<Breakpoint *> points;
clarify(points);
bst.get_breakpoints(root, points);
for (int i = 0; i < points.size(); i++) {
// if (((double) points[i]->support() / (double) points[i]->get_cov()) > 0.5) {
//std::cout<<points[i]->get_support() <<" "<<abs(points[i]->get_coordinates().stop - points[i]->get_coordinates().start)<<std::endl;
points[i]->calc_support();
if (points[i]->get_support() > Parameter::Instance()->min_support && points[i]->get_length() > Parameter::Instance()->min_length) {
final.insert(points[i], root_final);
}
}
bst.makeempty(root);
}
std::vector<str_event> cigar_event;
std::vector<str_event> md_event;
std::vector<aln_str> split_events;
if (tmp_aln->getMappingQual() > Parameter::Instance()->min_mq) {
#pragma omp parallel // starts a new team
{
#pragma omp sections
{
{
//if (Parameter::Instance()->useMD_CIGAR) {
//cigar_event = tmp_aln->get_events_CIGAR();
//}
}
#pragma omp section
{
//if (Parameter::Instance()->useMD_CIGAR) {
//md_event = tmp_aln->get_events_MD(20);
//}
}
#pragma omp section
{
split_events = tmp_aln->getSA(ref);
}
}
}
tmp_aln->set_supports_SV((cigar_event.empty() && md_event.empty()) && split_events.empty());
//sweep->add_read(tmp_aln);
//maybe flush the tree after each chr.....?
long ref_space = get_ref_lengths(tmp_aln->getRefID(), ref);
int cov = 0; //sweep->get_num_reads();
//maybe just store the extreme intervals for coverage -> If the cov doubled within Xbp or were the coverage is 0.
add_events(tmp_aln, cigar_event, 0, ref_space, bst, root, cov, tmp_aln->getQueryBases());
add_events(tmp_aln, md_event, 1, ref_space, bst, root, cov, tmp_aln->getQueryBases());
add_splits(tmp_aln, split_events, 2, ref, bst, root, cov, tmp_aln->getQueryBases());
}
}
mapped_file->parseReadFast(Parameter::Instance()->min_mq, tmp_aln);
}
//filter and copy results:
std::cout << "Finalizing .." << std::endl;
std::vector<Breakpoint *> points;
clarify(points);
bst.get_breakpoints(root, points);
for (int i = 0; i < points.size(); i++) {
// if (((double) points[i]->support() / (double) points[i]->get_cov()) > 0.5) {
//std::cout<<points[i]->get_support() <<" "<<abs(points[i]->get_coordinates().stop - points[i]->get_coordinates().start)<<std::endl;
points[i]->calc_support();
if (points[i]->get_support() > Parameter::Instance()->min_support && points[i]->get_length() > Parameter::Instance()->min_length) {
final.insert(points[i], root_final);
}
}
bst.makeempty(root);
// sweep->finalyze();
points.clear();
final.get_breakpoints(root_final, points);
//std::cout<<"Points: "<<points.size()<<endl;
clarify(points);
for (int i = 0; i < points.size(); i++) {
if (points[i]->get_support() > Parameter::Instance()->min_support && points[i]->get_length() > Parameter::Instance()->min_length) {
points[i]->predict_SV();
points[i]->set_id(i + 1);
// std::cout << "calls: " << points[i]->to_string(ref) << std::endl;
}
}
return points;
}
void add_events(Alignment * tmp, std::vector<str_event> events, short type, long ref_space, IntervallTree & bst, TNode *&root, int cov, std::string read_seq) {
bool flag = (strcmp(tmp->getName().c_str(), Parameter::Instance()->read_name.c_str()) == 0);
for (size_t i = 0; i < events.size(); i++) {
position_str svs;
//position_str stop;
read_str read;
//read.name = tmp->getName();
read.type = type;
read.SV = 0;
//start.support.push_back(read); //not very nice!
//stop.support.push_back(read);
if (flag) {
std::cout << tmp->getName() << " " << tmp->getRefID() << " " << events[i].pos << " " << abs(events[i].length) << std::endl;
}
svs.start.min_pos = (long) events[i].pos;
svs.start.min_pos += ref_space;
svs.stop.max_pos = svs.start.min_pos;
if (events[i].length > 0) {
svs.stop.max_pos += events[i].length;
}
if (tmp->getStrand()) {
read.strand.first = (tmp->getStrand());
read.strand.second = !(tmp->getStrand());
} else {
read.strand.first = !(tmp->getStrand());
read.strand.second = (tmp->getStrand());
}
// start.support[0].read_start.min = events[i].read_pos;
if (type == 0 && events[i].length < 0) {
read.SV |= INS; //insertion
} else if (type == 0) {
read.SV |= DEL; //deletion
} else {
read.SV |= DEL;
read.SV |= INV;
}
if (flag) {
std::cout << tmp->getName() << " " << tmp->getRefID() << " " << svs.start.min_pos - ref_space << " " << svs.stop.max_pos - ref_space << std::endl;
}
if (svs.start.min_pos > svs.stop.max_pos) {
//can this actually happen?
read.coordinates.first = svs.stop.max_pos;
read.coordinates.second = svs.start.min_pos;
} else {
read.coordinates.first = svs.start.min_pos;
read.coordinates.second = svs.stop.max_pos;
}
svs.start.max_pos = svs.start.min_pos;
svs.stop.min_pos = svs.stop.max_pos;
if (svs.start.min_pos > svs.stop.max_pos) {
//maybe we have to invert the directions???
svs_breakpoint_str pos = svs.start;
svs.start = svs.stop;
svs.stop = pos;
pair<bool, bool> tmp = read.strand;
read.strand.first = tmp.second;
read.strand.second = tmp.first;
//read.strand.first = !tmp.first;
//read.strand.second = !tmp.second;
}
//TODO: we might not need this:
if (svs.start.min_pos > svs.stop.max_pos) {
read.coordinates.first = svs.stop.max_pos;
read.coordinates.second = svs.start.min_pos;
} else {
read.coordinates.first = svs.start.min_pos;
read.coordinates.second = svs.stop.max_pos;
}
svs.support[tmp->getName()] = read;
Breakpoint * point = new Breakpoint(svs, cov);
bst.insert(point, root);
}
}
void add_splits(Alignment * tmp, std::vector<aln_str> events, short type, RefVector ref, IntervallTree & bst, TNode *&root, int cov, std::string read_seq) {
/* bool flag = false;
if (Parameter::Instance()->overlaps(ref[tmp->getRefID()].RefName,
tmp->getPosition(), tmp->getPosition() + tmp->getRefLength())) {
Parameter::Instance()->read_name = tmp->getName();
flag = true;
}
*/
bool flag = (strcmp(tmp->getName().c_str(), Parameter::Instance()->read_name.c_str()) == 0);
for (size_t i = 1; i < events.size() && events.size() < Parameter::Instance()->max_splits; i++) {
if (flag) {
std::cout << "Genome pos: " << tmp->getName() << " ";
if (events[i - 1].strand) {
std::cout << "+";
} else {
std::cout << "-";
}
std::cout << events[i - 1].pos << " " << events[i - 1].pos + events[i - 1].length << " p2: ";
if (events[i - 1].strand) {
std::cout << "+";
} else {
std::cout << "-";
}
std::cout << events[i].pos << " " << events[i].pos + events[i].length << " Ref: " << events[i - 1].RefID << " " << events[i].RefID << std::endl;
}
position_str svs;
//position_str stop;
read_str read;
//read.name = tmp->getName();
read.type = 2;
read.SV = 0;
//stop.support.push_back(read);
//they mimic paired end sequencing:
if (events[i].RefID == events[i - 1].RefID) {
//TODO: changed because of test:
if (events[i - 1].strand == events[i].strand) {
if (events[i - 1].strand) { // this might be a problem for INV??
read.strand.first = events[i - 1].strand;
read.strand.second = !events[i].strand;
} else {
read.strand.first = !events[i - 1].strand;
read.strand.second = events[i].strand;
}
svs.read_start = events[i - 1].read_pos_start + events[i - 1].length;
svs.read_stop = events[i].read_pos_start;
if (events[i - 1].strand) {
svs.start.min_pos = events[i - 1].pos + events[i - 1].length + get_ref_lengths(events[i - 1].RefID, ref);
svs.stop.max_pos = events[i].pos + get_ref_lengths(events[i].RefID, ref);
} else {
svs.start.min_pos = events[i].pos + events[i].length + get_ref_lengths(events[i].RefID, ref);
svs.stop.max_pos = events[i - 1].pos + get_ref_lengths(events[i - 1].RefID, ref);
}
if ((svs.start.min_pos - svs.stop.max_pos) > 100) {
read.SV |= DUP;
} else if (abs(svs.stop.max_pos - svs.start.min_pos) + (Parameter::Instance()->min_cigar_event * 2) < (svs.read_stop - svs.read_start)) {
read.SV |= INS;
} else if (abs(svs.stop.max_pos - svs.start.min_pos) > (svs.read_stop - svs.read_start) + (Parameter::Instance()->min_cigar_event * 2)) {
read.SV |= DEL;
} else {
read.SV = 'n';
}
} else { // if first part of read is in a different direction as the second part
read.strand.first = events[i - 1].strand;
read.strand.second = !events[i].strand;
read.SV |= INV;
if (events[i - 1].strand) {
svs.start.min_pos = events[i - 1].pos + events[i - 1].length + get_ref_lengths(events[i - 1].RefID, ref);
svs.stop.max_pos = events[i].pos + events[i].length + get_ref_lengths(events[i].RefID, ref);
} else {
svs.start.min_pos = events[i - 1].pos + get_ref_lengths(events[i - 1].RefID, ref);
svs.stop.max_pos = events[i].pos + get_ref_lengths(events[i].RefID, ref);
}
}
} else { //if not on the same chr-> TRA
read.strand.first = events[i - 1].strand;
read.strand.second = !events[i].strand;
if (events[i - 1].strand == events[i].strand) {
if (events[i - 1].strand) {
svs.start.min_pos = events[i - 1].pos + events[i - 1].length + get_ref_lengths(events[i - 1].RefID, ref);
svs.stop.max_pos = events[i].pos + get_ref_lengths(events[i].RefID, ref);
} else {
svs.start.min_pos = events[i - 1].pos + get_ref_lengths(events[i - 1].RefID, ref);
svs.stop.max_pos = events[i].pos + events[i].length + get_ref_lengths(events[i].RefID, ref);
}
} else {
if (events[i - 1].strand) {
svs.start.min_pos = events[i - 1].pos + events[i - 1].length + get_ref_lengths(events[i - 1].RefID, ref);
svs.stop.max_pos = events[i].pos + events[i].length + get_ref_lengths(events[i].RefID, ref);
} else {
svs.start.min_pos = events[i - 1].pos + get_ref_lengths(events[i - 1].RefID, ref);
svs.stop.max_pos = events[i].pos + get_ref_lengths(events[i].RefID, ref);
}
}
read.SV |= TRA;
}
if (flag) {
std::cout << tmp->getName() << " start: " << svs.start.min_pos << " stop: " << svs.stop.max_pos;
if (events[i - 1].strand) {
std::cout << " +";
} else {
std::cout << " -";
}
if (events[i].strand) {
std::cout << " +";
} else {
std::cout << " -";
}
std::cout << std::endl;
}
if (read.SV != 'n') {
//std::cout<<"split"<<std::endl;
svs.start.max_pos = svs.start.min_pos;
svs.stop.min_pos = svs.stop.max_pos;
if (svs.start.min_pos > svs.stop.max_pos) {
//maybe we have to invert the directions???
svs_breakpoint_str pos = svs.start;
svs.start = svs.stop;
svs.stop = pos;
pair<bool, bool> tmp = read.strand;
read.strand.first = tmp.second;
read.strand.second = tmp.first;
//read.strand.first = !tmp.first;
//read.strand.second = !tmp.second;
}
//TODO: we might not need this:
if (svs.start.min_pos > svs.stop.max_pos) {
read.coordinates.first = svs.stop.max_pos;
read.coordinates.second = svs.start.min_pos;
} else {
read.coordinates.first = svs.start.min_pos;
read.coordinates.second = svs.stop.max_pos;
}
svs.support[tmp->getName()] = read;
Breakpoint * point = new Breakpoint(svs, cov);
bst.insert(point, root);
}
}
}
void clarify(std::vector<Breakpoint *> & points) {
//if WTF regions next to duplications-> delete!
/*for(size_t i=0;i<points.size();i++){
}*/
}
void estimate_parameters(std::string read_filename) {
BamParser * mapped_file = 0;
RefVector ref;
if (read_filename.find("bam") != string::npos) {
mapped_file = new BamParser(read_filename);
ref = mapped_file->get_refInfo();
} else {
cerr << "File Format not recognized. File must be a sorted .bam file!" << endl;
exit(0);
}
Alignment * tmp_aln = mapped_file->parseRead(Parameter::Instance()->min_mq);
double num = 0;
double avg_score = 0;
double avg_mis = 0;
double avg_indel = 0;
while (!tmp_aln->getSequence().first.empty() && num < 1000) {
if ((tmp_aln->getAlignment()->IsPrimaryAlignment()) && (!(tmp_aln->getAlignment()->AlignmentFlag & 0x800) && tmp_aln->get_is_save())) {
//get score ratio
double score = tmp_aln->get_scrore_ratio();
if (score != -1) {
avg_score += score;
} else {
avg_score += avg_score / num;
}
//cout<<"Para:\t"<<score;
//get avg mismatches
std::string md = tmp_aln->get_md();
if (!md.empty()) {
avg_mis += tmp_aln->get_num_mismatches(md);
//cout<<"\t"<<tmp_aln->get_num_mismatches(md);
}
//cigar threshold: (without 1!)
avg_indel += tmp_aln->get_avg_indel_length_Cigar();
//cout<<"\t"<<tmp_aln->get_avg_indel_length_Cigar()<<endl;
num++;
}
mapped_file->parseReadFast(Parameter::Instance()->min_mq, tmp_aln);
}
std::cout << avg_indel / num << std::endl;
Parameter::Instance()->min_num_mismatches = (avg_mis / num) * 0.3; //previously: 0.3
Parameter::Instance()->min_cigar_event = (avg_indel / num) * 20; //previously: 20
Parameter::Instance()->score_treshold =(avg_score / num) / 2; //previously: 2 //2
std::cout << "score: " << Parameter::Instance()->score_treshold << std::endl;
std::cout << "md: " << Parameter::Instance()->min_num_mismatches << std::endl;
std::cout << "indel: " << Parameter::Instance()->min_cigar_event << std::endl;
}
<commit_msg>Delete DetectBreakpoints.cpp<commit_after><|endoftext|> |
<commit_before>// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use these files 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 2012 - Gonzalo Iglesias, Adrià de Gispert, William Byrne
#ifndef FSTUTILS_APPLYLMONTHEFLY_HPP
#define FSTUTILS_APPLYLMONTHEFLY_HPP
/**
* \file
* \brief Contains implementation of ApplyLanguageModelOnTheFly
* \date 8-8-2012
* \author Gonzalo Iglesias
*/
#include <idbridge.hpp>
#include <lm/wrappers/nplm.hh>
namespace fst {
template <class StateT>
struct StateHandler {
inline void setLength(unsigned length) {}
inline unsigned getLength(StateT const &state) { return state.length;}
};
template<>
struct StateHandler<lm::np::State> {
unsigned length_;
inline void setLength(unsigned length) { length_ = length;}
inline unsigned getLength(lm::np::State const &state) const { return length_; }
};
template<class ArcT>
struct ApplyLanguageModelOnTheFlyInterface {
virtual VectorFst<ArcT> *run(VectorFst<ArcT> const& fst) = 0;
virtual VectorFst<ArcT> *run(VectorFst<ArcT> const& fst, unordered_set<typename ArcT::Label> const &epsilons) = 0;
virtual ~ApplyLanguageModelOnTheFlyInterface(){}
};
/**
* \brief Class that applies language model on the fly using kenlm.
* \remarks This implementation could be optimized a little further, i.e.
* all visited states must be tracked down so that non-topsorted or cyclic fsts work correctly.
* But we could keep track of these states in a memory efficient way (i.e. only highest state n for consecutive 0-to-n seen).
*/
template <class Arc
, class MakeWeightT = MakeWeight<Arc>
, class KenLMModelT = lm::ngram::Model
, class IdBridgeT = ucam::fsttools::IdBridge >
class ApplyLanguageModelOnTheFly : public ApplyLanguageModelOnTheFlyInterface<Arc> {
private:
typedef typename Arc::StateId StateId;
typedef typename Arc::Label Label;
typedef typename Arc::Weight Weight;
typedef unsigned long long ull;
unordered_map< ull, StateId > stateexistence_;
static const ull sid = 1000000000;
/// m12state=<m1state,m2state>
unordered_map<uint64_t, pair<StateId, typename KenLMModelT::State > > statemap_;
/// history, lmstate
unordered_map<basic_string<unsigned>
, StateId
, ucam::util::hashfvecuint
, ucam::util::hasheqvecuint> seenlmstates_;
/// Queue of states of the new machine to process.
queue<StateId> qc_;
///Arc labels to be treated as epsilons, i.e. transparent to the language model.
unordered_set<Label> epsilons_;
KenLMModelT& lmmodel_;
const typename KenLMModelT::Vocabulary& vocab_;
float natlog10_;
///Templated functor that creates weights.
MakeWeightT mw_;
basic_string<unsigned> history;
unsigned *buffer;
unsigned buffersize;
//Word Penalty.
float wp_;
const ucam::fsttools::IdBridge& idbridge_;
StateHandler<typename KenLMModelT::State> sh_;
///Public methods
public:
///Set MakeWeight functor
inline void setMakeWeight ( const MakeWeightT& mw ) {
mw_ = mw;
};
/**
* Constructor. Initializes on-the-fly composition with a language model.
* \param fst Machine you want to apply the language to. Pass a delayed machine if you can, as it will expand it in constructor.
* \param model A KenLM language model
* \param epsilons List of words to work as epsilons
* \param natlog Use or not natural logs
* \param lmscale Language model scale
*/
ApplyLanguageModelOnTheFly ( KenLMModelT& model
, unordered_set<Label>& epsilons
, bool natlog
, float lmscale
, float lmwp
, const IdBridgeT& idbridge
, MakeWeightT &mw
)
: natlog10_ ( natlog ? -lmscale* ::log ( 10.0 ) : -lmscale )
, lmmodel_ ( model )
, vocab_ ( model.GetVocabulary() )
, wp_ ( lmwp )
, epsilons_ ( epsilons )
, history ( model.Order(), 0)
, idbridge_ (idbridge)
, mw_(mw)
{
init();
};
ApplyLanguageModelOnTheFly ( KenLMModelT& model
, bool natlog
, float lmscale
, float lmwp
, const IdBridgeT& idbridge
, MakeWeightT &mw
)
: natlog10_ ( natlog ? -lmscale* ::log ( 10.0 ) : -lmscale )
, lmmodel_ ( model )
, vocab_ ( model.GetVocabulary() )
, wp_ ( lmwp )
, history ( model.Order(), 0)
, idbridge_ (idbridge)
, mw_(mw)
{
init();
};
void init() {
sh_.setLength(lmmodel_.Order());
buffersize = (lmmodel_.Order() - 1 ) * sizeof (unsigned);
buffer = const_cast<unsigned *> ( history.c_str() );
}
///Destructor
~ApplyLanguageModelOnTheFly() {};
virtual VectorFst<Arc> *run(const VectorFst<Arc>& fst) {
return this->operator()(fst);
}
virtual VectorFst<Arc> *run(const VectorFst<Arc>& fst, unordered_set<Label> const &epsilons) {
epsilons_ = epsilons; // this may be necessary e.g. for pdts
return this->operator()(fst);
}
///functor: Run composition itself
VectorFst<Arc> * operator() (const VectorFst<Arc>& fst) {
const VectorFst<Arc> &fst_ = fst;
if (!fst_.NumStates() ) {
LWARN ("Empty lattice. ... Skipping LM application!");
return NULL;
}
VectorFst<Arc> *composed;
composed = new VectorFst<Arc>;
///Initialize and push with first state
typename KenLMModelT::State bs = lmmodel_.NullContextState();
pair<StateId, bool> nextp = add ( composed, bs, fst_.Start(), fst_.Final ( fst_.Start() ) );
qc_.push ( nextp.first );
composed->SetStart ( nextp.first );
while ( qc_.size() ) {
StateId s = qc_.front();
qc_.pop();
pair<StateId, const typename KenLMModelT::State> p = get ( s );
StateId& s1 = p.first;
const typename KenLMModelT::State s2 = p.second;
for ( ArcIterator< VectorFst<Arc> > arc1 ( fst_, s1 ); !arc1.Done();
arc1.Next() ) {
const Arc& a1 = arc1.Value();
float w = 0;
float wp = wp_;
typename KenLMModelT::State nextlmstate;
if ( epsilons_.find ( a1.olabel ) == epsilons_.end() ) {
w = lmmodel_.Score ( s2, idbridge_.map (a1.olabel), nextlmstate ) * natlog10_;
//silly hack
if ( a1.olabel <= 2 ) {
wp = 0;
if (a1.olabel == 1 ) w = 0; //get same result as srilm
}
} else {
nextlmstate = s2;
wp = 0; //We don't count epsilon labels
}
LINFO("Adding a1.nextstate=" << a1.nextstate);
pair<StateId, bool> nextp = add ( composed, nextlmstate
, a1.nextstate
, fst_.Final ( a1.nextstate ) );
StateId& newstate = nextp.first;
bool visited = nextp.second;
composed->AddArc ( s
, Arc ( a1.ilabel, a1.olabel
, Times ( a1.weight, Times (mw_ ( w ) , mw_ (wp) ) )
, newstate ) );
//Finally, only add newstate to the queue if it hasn't been visited previously
if ( !visited ) {
qc_.push ( newstate );
}
}
}
LINFO ( "Done! Number of states=" << composed->NumStates() );
stateexistence_.clear();
statemap_.clear();
seenlmstates_.clear();
history.resize( lmmodel_.Order(), 0);
return composed;
};
private:
/**
* \brief Adds a state.
* \return true if the state requested has already been visited, false otherwise.
*/
inline pair <StateId, bool> add ( fst::VectorFst<Arc> *composed, typename KenLMModelT::State& m2nextstate,
StateId m1nextstate, Weight m1stateweight ) {
static StateId lm = 0;
getIdx ( m2nextstate );
///New history:
if ( seenlmstates_.find ( history ) == seenlmstates_.end() ) {
seenlmstates_[history] = ++lm;
}
uint64_t compound = m1nextstate * sid + seenlmstates_[history];
LDEBUG ( "compound id=" << compound );
if ( stateexistence_.find ( compound ) == stateexistence_.end() ) {
LDEBUG ( "New State!" );
statemap_[composed->NumStates()] =
pair<StateId, const typename KenLMModelT::State > ( m1nextstate, m2nextstate );
composed->AddState();
if ( m1stateweight != mw_ ( ZPosInfinity() ) ) composed->SetFinal (
composed->NumStates() - 1, m1stateweight );
stateexistence_[compound] = composed->NumStates() - 1;
return pair<StateId, bool> ( composed->NumStates() - 1, false );
}
return pair<StateId, bool> ( stateexistence_[compound], true );
};
/**
* \brief Get an id string representing the history, given a kenlm state.
*
*/
inline void getIdx ( const typename KenLMModelT::State& state,
uint order = 4 ) {
memcpy ( buffer, state.words, buffersize );
// for ( uint k = state.length; k < history.size(); ++k ) history[k] = 0;
for ( uint k = sh_.getLength(state); k < history.size(); ++k ) history[k] = 0;
};
///Map from output state to input lattice + language model state
inline pair<StateId, typename KenLMModelT::State > get ( StateId state ) {
return statemap_[state];
};
};
} // end namespaces
#endif
<commit_msg>Delete one message<commit_after>// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use these files 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 2012 - Gonzalo Iglesias, Adrià de Gispert, William Byrne
#ifndef FSTUTILS_APPLYLMONTHEFLY_HPP
#define FSTUTILS_APPLYLMONTHEFLY_HPP
/**
* \file
* \brief Contains implementation of ApplyLanguageModelOnTheFly
* \date 8-8-2012
* \author Gonzalo Iglesias
*/
#include <idbridge.hpp>
#include <lm/wrappers/nplm.hh>
namespace fst {
template <class StateT>
struct StateHandler {
inline void setLength(unsigned length) {}
inline unsigned getLength(StateT const &state) { return state.length;}
};
template<>
struct StateHandler<lm::np::State> {
unsigned length_;
inline void setLength(unsigned length) { length_ = length;}
inline unsigned getLength(lm::np::State const &state) const { return length_; }
};
template<class ArcT>
struct ApplyLanguageModelOnTheFlyInterface {
virtual VectorFst<ArcT> *run(VectorFst<ArcT> const& fst) = 0;
virtual VectorFst<ArcT> *run(VectorFst<ArcT> const& fst, unordered_set<typename ArcT::Label> const &epsilons) = 0;
virtual ~ApplyLanguageModelOnTheFlyInterface(){}
};
/**
* \brief Class that applies language model on the fly using kenlm.
* \remarks This implementation could be optimized a little further, i.e.
* all visited states must be tracked down so that non-topsorted or cyclic fsts work correctly.
* But we could keep track of these states in a memory efficient way (i.e. only highest state n for consecutive 0-to-n seen).
*/
template <class Arc
, class MakeWeightT = MakeWeight<Arc>
, class KenLMModelT = lm::ngram::Model
, class IdBridgeT = ucam::fsttools::IdBridge >
class ApplyLanguageModelOnTheFly : public ApplyLanguageModelOnTheFlyInterface<Arc> {
private:
typedef typename Arc::StateId StateId;
typedef typename Arc::Label Label;
typedef typename Arc::Weight Weight;
typedef unsigned long long ull;
unordered_map< ull, StateId > stateexistence_;
static const ull sid = 1000000000;
/// m12state=<m1state,m2state>
unordered_map<uint64_t, pair<StateId, typename KenLMModelT::State > > statemap_;
/// history, lmstate
unordered_map<basic_string<unsigned>
, StateId
, ucam::util::hashfvecuint
, ucam::util::hasheqvecuint> seenlmstates_;
/// Queue of states of the new machine to process.
queue<StateId> qc_;
///Arc labels to be treated as epsilons, i.e. transparent to the language model.
unordered_set<Label> epsilons_;
KenLMModelT& lmmodel_;
const typename KenLMModelT::Vocabulary& vocab_;
float natlog10_;
///Templated functor that creates weights.
MakeWeightT mw_;
basic_string<unsigned> history;
unsigned *buffer;
unsigned buffersize;
//Word Penalty.
float wp_;
const ucam::fsttools::IdBridge& idbridge_;
StateHandler<typename KenLMModelT::State> sh_;
///Public methods
public:
///Set MakeWeight functor
inline void setMakeWeight ( const MakeWeightT& mw ) {
mw_ = mw;
};
/**
* Constructor. Initializes on-the-fly composition with a language model.
* \param fst Machine you want to apply the language to. Pass a delayed machine if you can, as it will expand it in constructor.
* \param model A KenLM language model
* \param epsilons List of words to work as epsilons
* \param natlog Use or not natural logs
* \param lmscale Language model scale
*/
ApplyLanguageModelOnTheFly ( KenLMModelT& model
, unordered_set<Label>& epsilons
, bool natlog
, float lmscale
, float lmwp
, const IdBridgeT& idbridge
, MakeWeightT &mw
)
: natlog10_ ( natlog ? -lmscale* ::log ( 10.0 ) : -lmscale )
, lmmodel_ ( model )
, vocab_ ( model.GetVocabulary() )
, wp_ ( lmwp )
, epsilons_ ( epsilons )
, history ( model.Order(), 0)
, idbridge_ (idbridge)
, mw_(mw)
{
init();
};
ApplyLanguageModelOnTheFly ( KenLMModelT& model
, bool natlog
, float lmscale
, float lmwp
, const IdBridgeT& idbridge
, MakeWeightT &mw
)
: natlog10_ ( natlog ? -lmscale* ::log ( 10.0 ) : -lmscale )
, lmmodel_ ( model )
, vocab_ ( model.GetVocabulary() )
, wp_ ( lmwp )
, history ( model.Order(), 0)
, idbridge_ (idbridge)
, mw_(mw)
{
init();
};
void init() {
sh_.setLength(lmmodel_.Order());
buffersize = (lmmodel_.Order() - 1 ) * sizeof (unsigned);
buffer = const_cast<unsigned *> ( history.c_str() );
}
///Destructor
~ApplyLanguageModelOnTheFly() {};
virtual VectorFst<Arc> *run(const VectorFst<Arc>& fst) {
return this->operator()(fst);
}
virtual VectorFst<Arc> *run(const VectorFst<Arc>& fst, unordered_set<Label> const &epsilons) {
epsilons_ = epsilons; // this may be necessary e.g. for pdts
return this->operator()(fst);
}
///functor: Run composition itself
VectorFst<Arc> * operator() (const VectorFst<Arc>& fst) {
const VectorFst<Arc> &fst_ = fst;
if (!fst_.NumStates() ) {
LWARN ("Empty lattice. ... Skipping LM application!");
return NULL;
}
VectorFst<Arc> *composed;
composed = new VectorFst<Arc>;
///Initialize and push with first state
typename KenLMModelT::State bs = lmmodel_.NullContextState();
pair<StateId, bool> nextp = add ( composed, bs, fst_.Start(), fst_.Final ( fst_.Start() ) );
qc_.push ( nextp.first );
composed->SetStart ( nextp.first );
while ( qc_.size() ) {
StateId s = qc_.front();
qc_.pop();
pair<StateId, const typename KenLMModelT::State> p = get ( s );
StateId& s1 = p.first;
const typename KenLMModelT::State s2 = p.second;
for ( ArcIterator< VectorFst<Arc> > arc1 ( fst_, s1 ); !arc1.Done();
arc1.Next() ) {
const Arc& a1 = arc1.Value();
float w = 0;
float wp = wp_;
typename KenLMModelT::State nextlmstate;
if ( epsilons_.find ( a1.olabel ) == epsilons_.end() ) {
w = lmmodel_.Score ( s2, idbridge_.map (a1.olabel), nextlmstate ) * natlog10_;
//silly hack
if ( a1.olabel <= 2 ) {
wp = 0;
if (a1.olabel == 1 ) w = 0; //get same result as srilm
}
} else {
nextlmstate = s2;
wp = 0; //We don't count epsilon labels
}
pair<StateId, bool> nextp = add ( composed, nextlmstate
, a1.nextstate
, fst_.Final ( a1.nextstate ) );
StateId& newstate = nextp.first;
bool visited = nextp.second;
composed->AddArc ( s
, Arc ( a1.ilabel, a1.olabel
, Times ( a1.weight, Times (mw_ ( w ) , mw_ (wp) ) )
, newstate ) );
//Finally, only add newstate to the queue if it hasn't been visited previously
if ( !visited ) {
qc_.push ( newstate );
}
}
}
LINFO ( "Done! Number of states=" << composed->NumStates() );
stateexistence_.clear();
statemap_.clear();
seenlmstates_.clear();
history.resize( lmmodel_.Order(), 0);
return composed;
};
private:
/**
* \brief Adds a state.
* \return true if the state requested has already been visited, false otherwise.
*/
inline pair <StateId, bool> add ( fst::VectorFst<Arc> *composed, typename KenLMModelT::State& m2nextstate,
StateId m1nextstate, Weight m1stateweight ) {
static StateId lm = 0;
getIdx ( m2nextstate );
///New history:
if ( seenlmstates_.find ( history ) == seenlmstates_.end() ) {
seenlmstates_[history] = ++lm;
}
uint64_t compound = m1nextstate * sid + seenlmstates_[history];
LDEBUG ( "compound id=" << compound );
if ( stateexistence_.find ( compound ) == stateexistence_.end() ) {
LDEBUG ( "New State!" );
statemap_[composed->NumStates()] =
pair<StateId, const typename KenLMModelT::State > ( m1nextstate, m2nextstate );
composed->AddState();
if ( m1stateweight != mw_ ( ZPosInfinity() ) ) composed->SetFinal (
composed->NumStates() - 1, m1stateweight );
stateexistence_[compound] = composed->NumStates() - 1;
return pair<StateId, bool> ( composed->NumStates() - 1, false );
}
return pair<StateId, bool> ( stateexistence_[compound], true );
};
/**
* \brief Get an id string representing the history, given a kenlm state.
*
*/
inline void getIdx ( const typename KenLMModelT::State& state,
uint order = 4 ) {
memcpy ( buffer, state.words, buffersize );
// for ( uint k = state.length; k < history.size(); ++k ) history[k] = 0;
for ( uint k = sh_.getLength(state); k < history.size(); ++k ) history[k] = 0;
};
///Map from output state to input lattice + language model state
inline pair<StateId, typename KenLMModelT::State > get ( StateId state ) {
return statemap_[state];
};
};
} // end namespaces
#endif
<|endoftext|> |
<commit_before>//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2013, Image Engine Design Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above
// copyright notice, this list of conditions and the following
// disclaimer.
//
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided with
// the distribution.
//
// * Neither the name of John Haddon nor the names of
// any other contributors to this software 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.
//
//////////////////////////////////////////////////////////////////////////
#include "boost/tokenizer.hpp"
#include "IECore/PreWorldRenderable.h"
#include "IECore/Camera.h"
#include "IECore/MatrixMotionTransform.h"
#include "IECore/WorldBlock.h"
#include "IECore/Light.h"
#include "IECore/AttributeBlock.h"
#include "Gaffer/Context.h"
#include "GafferScene/Render.h"
#include "GafferScene/ScenePlug.h"
#include "GafferScene/SceneProcedural.h"
using namespace Imath;
using namespace IECore;
using namespace Gaffer;
using namespace GafferScene;
IE_CORE_DEFINERUNTIMETYPED( Render );
size_t Render::g_firstPlugIndex = 0;
Render::Render( const std::string &name )
: Node( name )
{
storeIndexOfNextChild( g_firstPlugIndex );
addChild( new ScenePlug( "in" ) );
}
Render::~Render()
{
}
ScenePlug *Render::inPlug()
{
return getChild<ScenePlug>( g_firstPlugIndex );
}
const ScenePlug *Render::inPlug() const
{
return getChild<ScenePlug>( g_firstPlugIndex );
}
void Render::outputScene( const ScenePlug *scene, IECore::Renderer *renderer ) const
{
ConstCompoundObjectPtr globals = scene->globalsPlug()->getValue();
outputOptions( globals, renderer );
outputCamera( scene, globals, renderer );
{
WorldBlock world( renderer );
outputLights( scene, globals, renderer );
SceneProceduralPtr proc = new SceneProcedural( scene, Context::current() );
// we have to render the procedural directly rather than give it to the renderer
// as a procedural, because otherwise the 3delight rerendering loses all its shaders.
proc->render( renderer );
}
}
void Render::outputOptions( const IECore::CompoundObject *globals, IECore::Renderer *renderer ) const
{
CompoundObject::ObjectMap::const_iterator it, eIt;
for( it = globals->members().begin(), eIt = globals->members().end(); it != eIt; it++ )
{
if( const PreWorldRenderable *r = runTimeCast<PreWorldRenderable>( it->second.get() ) )
{
r->render( renderer );
}
else if( const Data *d = runTimeCast<Data>( it->second.get() ) )
{
renderer->setOption( it->first, d );
}
}
}
void Render::outputCamera( const ScenePlug *scene, const IECore::CompoundObject *globals, IECore::Renderer *renderer ) const
{
// get the camera from the scene
const StringData *cameraPathData = globals->member<StringData>( "render:camera" );
IECore::CameraPtr camera = 0;
if( cameraPathData )
{
ScenePlug::ScenePath cameraPath;
stringToPath( cameraPathData->readable(), cameraPath );
IECore::ConstCameraPtr constCamera = runTimeCast<const IECore::Camera>( scene->object( cameraPath ) );
if( constCamera )
{
camera = constCamera->copy();
const BoolData *cameraBlurData = globals->member<BoolData>( "render:cameraBlur" );
const bool cameraBlur = cameraBlurData ? cameraBlurData->readable() : false;
camera->setTransform( transform( scene, cameraPath, shutter( globals ), cameraBlur ) );
}
}
if( !camera )
{
camera = new IECore::Camera();
}
// apply the resolution
const V2iData *resolutionData = globals->member<V2iData>( "render:resolution" );
if( resolutionData )
{
camera->parameters()["resolution"] = resolutionData->copy();
}
camera->addStandardParameters();
// apply the shutter
camera->parameters()["shutter"] = new V2fData( shutter( globals ) );
// and output
camera->render( renderer );
}
void Render::outputLights( const ScenePlug *scene, const IECore::CompoundObject *globals, IECore::Renderer *renderer ) const
{
const CompoundData *forwardDeclarations = globals->member<CompoundData>( "gaffer:forwardDeclarations" );
if( !forwardDeclarations )
{
return;
}
CompoundDataMap::const_iterator it, eIt;
for( it = forwardDeclarations->readable().begin(), eIt = forwardDeclarations->readable().end(); it != eIt; it++ )
{
const CompoundData *declaration = runTimeCast<const CompoundData>( it->second.get() );
if( !declaration )
{
continue;
}
const IECore::TypeId type = (IECore::TypeId)declaration->member<IntData>( "type", true )->readable();
if( type != IECore::LightTypeId )
{
continue;
}
ScenePlug::ScenePath path;
stringToPath( it->first.string(), path );
IECore::ConstLightPtr constLight = runTimeCast<const IECore::Light>( scene->object( path ) );
if( !constLight )
{
continue;
}
ConstCompoundObjectPtr attributes = scene->fullAttributes( path );
const BoolData *visibilityData = attributes->member<BoolData>( "gaffer:visibility" );
if( visibilityData && !visibilityData->readable() )
{
continue;
}
M44f transform = scene->fullTransform( path );
LightPtr light = constLight->copy();
light->setHandle( it->first.string() );
{
AttributeBlock attributeBlock( renderer );
CompoundObject::ObjectMap::const_iterator aIt, aeIt;
for( aIt = attributes->members().begin(), aeIt = attributes->members().end(); aIt != aeIt; aIt++ )
{
if( const Data *attribute = runTimeCast<const Data>( aIt->second.get() ) )
{
renderer->setAttribute( aIt->first.string(), attribute );
}
}
renderer->concatTransform( transform );
light->render( renderer );
}
renderer->illuminate( light->getHandle(), true );
}
}
Imath::V2f Render::shutter( const IECore::CompoundObject *globals ) const
{
const BoolData *cameraBlurData = globals->member<BoolData>( "render:cameraBlur" );
const bool cameraBlur = cameraBlurData ? cameraBlurData->readable() : false;
const BoolData *transformBlurData = globals->member<BoolData>( "render:transformBlur" );
const bool transformBlur = transformBlurData ? transformBlurData->readable() : false;
const BoolData *deformationBlurData = globals->member<BoolData>( "render:deformationBlur" );
const bool deformationBlur = deformationBlurData ? deformationBlurData->readable() : false;
V2f shutter( Context::current()->getFrame() );
if( cameraBlur || transformBlur || deformationBlur )
{
const V2fData *shutterData = globals->member<V2fData>( "render:shutter" );
const V2f relativeShutter = shutterData ? shutterData->readable() : V2f( -0.25, 0.25 );
shutter += relativeShutter;
}
return shutter;
}
IECore::TransformPtr Render::transform( const ScenePlug *scene, const ScenePlug::ScenePath &path, const Imath::V2f &shutter, bool motionBlur ) const
{
int numSamples = 1;
if( motionBlur )
{
ConstCompoundObjectPtr attributes = scene->fullAttributes( path );
const IntData *transformBlurSegmentsData = attributes->member<IntData>( "gaffer:transformBlurSegments" );
numSamples = transformBlurSegmentsData ? transformBlurSegmentsData->readable() + 1 : 2;
const BoolData *transformBlurData = attributes->member<BoolData>( "gaffer:transformBlur" );
if( transformBlurData && !transformBlurData->readable() )
{
numSamples = 1;
}
}
MatrixMotionTransformPtr result = new MatrixMotionTransform();
ContextPtr transformContext = new Context( *Context::current() );
Context::Scope scopedContext( transformContext );
for( int i = 0; i < numSamples; i++ )
{
float frame = lerp( shutter[0], shutter[1], (float)i / std::max( 1, numSamples - 1 ) );
transformContext->setFrame( frame );
result->snapshots()[frame] = scene->fullTransform( path );
}
return result;
}
void Render::stringToPath( const std::string &s, ScenePlug::ScenePath &path ) const
{
typedef boost::tokenizer<boost::char_separator<char> > Tokenizer;
Tokenizer tokenizer( s, boost::char_separator<char>( "/" ) );
for( Tokenizer::const_iterator it = tokenizer.begin(), eIt = tokenizer.end(); it != eIt; it++ )
{
path.push_back( *it );
}
}
<commit_msg>Removing workaround for 3delight bug, which was fixed in 10.0.138.<commit_after>//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2013, Image Engine Design Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above
// copyright notice, this list of conditions and the following
// disclaimer.
//
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided with
// the distribution.
//
// * Neither the name of John Haddon nor the names of
// any other contributors to this software 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.
//
//////////////////////////////////////////////////////////////////////////
#include "boost/tokenizer.hpp"
#include "IECore/PreWorldRenderable.h"
#include "IECore/Camera.h"
#include "IECore/MatrixMotionTransform.h"
#include "IECore/WorldBlock.h"
#include "IECore/Light.h"
#include "IECore/AttributeBlock.h"
#include "Gaffer/Context.h"
#include "GafferScene/Render.h"
#include "GafferScene/ScenePlug.h"
#include "GafferScene/SceneProcedural.h"
using namespace Imath;
using namespace IECore;
using namespace Gaffer;
using namespace GafferScene;
IE_CORE_DEFINERUNTIMETYPED( Render );
size_t Render::g_firstPlugIndex = 0;
Render::Render( const std::string &name )
: Node( name )
{
storeIndexOfNextChild( g_firstPlugIndex );
addChild( new ScenePlug( "in" ) );
}
Render::~Render()
{
}
ScenePlug *Render::inPlug()
{
return getChild<ScenePlug>( g_firstPlugIndex );
}
const ScenePlug *Render::inPlug() const
{
return getChild<ScenePlug>( g_firstPlugIndex );
}
void Render::outputScene( const ScenePlug *scene, IECore::Renderer *renderer ) const
{
ConstCompoundObjectPtr globals = scene->globalsPlug()->getValue();
outputOptions( globals, renderer );
outputCamera( scene, globals, renderer );
{
WorldBlock world( renderer );
outputLights( scene, globals, renderer );
SceneProceduralPtr proc = new SceneProcedural( scene, Context::current() );
renderer->procedural( proc );
}
}
void Render::outputOptions( const IECore::CompoundObject *globals, IECore::Renderer *renderer ) const
{
CompoundObject::ObjectMap::const_iterator it, eIt;
for( it = globals->members().begin(), eIt = globals->members().end(); it != eIt; it++ )
{
if( const PreWorldRenderable *r = runTimeCast<PreWorldRenderable>( it->second.get() ) )
{
r->render( renderer );
}
else if( const Data *d = runTimeCast<Data>( it->second.get() ) )
{
renderer->setOption( it->first, d );
}
}
}
void Render::outputCamera( const ScenePlug *scene, const IECore::CompoundObject *globals, IECore::Renderer *renderer ) const
{
// get the camera from the scene
const StringData *cameraPathData = globals->member<StringData>( "render:camera" );
IECore::CameraPtr camera = 0;
if( cameraPathData )
{
ScenePlug::ScenePath cameraPath;
stringToPath( cameraPathData->readable(), cameraPath );
IECore::ConstCameraPtr constCamera = runTimeCast<const IECore::Camera>( scene->object( cameraPath ) );
if( constCamera )
{
camera = constCamera->copy();
const BoolData *cameraBlurData = globals->member<BoolData>( "render:cameraBlur" );
const bool cameraBlur = cameraBlurData ? cameraBlurData->readable() : false;
camera->setTransform( transform( scene, cameraPath, shutter( globals ), cameraBlur ) );
}
}
if( !camera )
{
camera = new IECore::Camera();
}
// apply the resolution
const V2iData *resolutionData = globals->member<V2iData>( "render:resolution" );
if( resolutionData )
{
camera->parameters()["resolution"] = resolutionData->copy();
}
camera->addStandardParameters();
// apply the shutter
camera->parameters()["shutter"] = new V2fData( shutter( globals ) );
// and output
camera->render( renderer );
}
void Render::outputLights( const ScenePlug *scene, const IECore::CompoundObject *globals, IECore::Renderer *renderer ) const
{
const CompoundData *forwardDeclarations = globals->member<CompoundData>( "gaffer:forwardDeclarations" );
if( !forwardDeclarations )
{
return;
}
CompoundDataMap::const_iterator it, eIt;
for( it = forwardDeclarations->readable().begin(), eIt = forwardDeclarations->readable().end(); it != eIt; it++ )
{
const CompoundData *declaration = runTimeCast<const CompoundData>( it->second.get() );
if( !declaration )
{
continue;
}
const IECore::TypeId type = (IECore::TypeId)declaration->member<IntData>( "type", true )->readable();
if( type != IECore::LightTypeId )
{
continue;
}
ScenePlug::ScenePath path;
stringToPath( it->first.string(), path );
IECore::ConstLightPtr constLight = runTimeCast<const IECore::Light>( scene->object( path ) );
if( !constLight )
{
continue;
}
ConstCompoundObjectPtr attributes = scene->fullAttributes( path );
const BoolData *visibilityData = attributes->member<BoolData>( "gaffer:visibility" );
if( visibilityData && !visibilityData->readable() )
{
continue;
}
M44f transform = scene->fullTransform( path );
LightPtr light = constLight->copy();
light->setHandle( it->first.string() );
{
AttributeBlock attributeBlock( renderer );
CompoundObject::ObjectMap::const_iterator aIt, aeIt;
for( aIt = attributes->members().begin(), aeIt = attributes->members().end(); aIt != aeIt; aIt++ )
{
if( const Data *attribute = runTimeCast<const Data>( aIt->second.get() ) )
{
renderer->setAttribute( aIt->first.string(), attribute );
}
}
renderer->concatTransform( transform );
light->render( renderer );
}
renderer->illuminate( light->getHandle(), true );
}
}
Imath::V2f Render::shutter( const IECore::CompoundObject *globals ) const
{
const BoolData *cameraBlurData = globals->member<BoolData>( "render:cameraBlur" );
const bool cameraBlur = cameraBlurData ? cameraBlurData->readable() : false;
const BoolData *transformBlurData = globals->member<BoolData>( "render:transformBlur" );
const bool transformBlur = transformBlurData ? transformBlurData->readable() : false;
const BoolData *deformationBlurData = globals->member<BoolData>( "render:deformationBlur" );
const bool deformationBlur = deformationBlurData ? deformationBlurData->readable() : false;
V2f shutter( Context::current()->getFrame() );
if( cameraBlur || transformBlur || deformationBlur )
{
const V2fData *shutterData = globals->member<V2fData>( "render:shutter" );
const V2f relativeShutter = shutterData ? shutterData->readable() : V2f( -0.25, 0.25 );
shutter += relativeShutter;
}
return shutter;
}
IECore::TransformPtr Render::transform( const ScenePlug *scene, const ScenePlug::ScenePath &path, const Imath::V2f &shutter, bool motionBlur ) const
{
int numSamples = 1;
if( motionBlur )
{
ConstCompoundObjectPtr attributes = scene->fullAttributes( path );
const IntData *transformBlurSegmentsData = attributes->member<IntData>( "gaffer:transformBlurSegments" );
numSamples = transformBlurSegmentsData ? transformBlurSegmentsData->readable() + 1 : 2;
const BoolData *transformBlurData = attributes->member<BoolData>( "gaffer:transformBlur" );
if( transformBlurData && !transformBlurData->readable() )
{
numSamples = 1;
}
}
MatrixMotionTransformPtr result = new MatrixMotionTransform();
ContextPtr transformContext = new Context( *Context::current() );
Context::Scope scopedContext( transformContext );
for( int i = 0; i < numSamples; i++ )
{
float frame = lerp( shutter[0], shutter[1], (float)i / std::max( 1, numSamples - 1 ) );
transformContext->setFrame( frame );
result->snapshots()[frame] = scene->fullTransform( path );
}
return result;
}
void Render::stringToPath( const std::string &s, ScenePlug::ScenePath &path ) const
{
typedef boost::tokenizer<boost::char_separator<char> > Tokenizer;
Tokenizer tokenizer( s, boost::char_separator<char>( "/" ) );
for( Tokenizer::const_iterator it = tokenizer.begin(), eIt = tokenizer.end(); it != eIt; it++ )
{
path.push_back( *it );
}
}
<|endoftext|> |
<commit_before>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2008 Gael Guennebaud <g.gael@free.fr>
//
// Eigen is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3 of the License, or (at your option) any later version.
//
// Alternatively, you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation; either version 2 of
// the License, or (at your option) any later version.
//
// Eigen 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 or the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License and a copy of the GNU General Public License along with
// Eigen. If not, see <http://www.gnu.org/licenses/>.
#include "main.h"
#include <Eigen/SVD>
#include <Eigen/LU>
template<typename MatrixType> void svd(const MatrixType& m)
{
/* this test covers the following files:
SVD.h
*/
int rows = m.rows();
int cols = m.cols();
typedef typename MatrixType::Scalar Scalar;
typedef typename NumTraits<Scalar>::Real RealScalar;
MatrixType a = MatrixType::Random(rows,cols);
Matrix<Scalar, MatrixType::RowsAtCompileTime, 1> b =
Matrix<Scalar, MatrixType::RowsAtCompileTime, 1>::Random(rows,1);
Matrix<Scalar, MatrixType::ColsAtCompileTime, 1> x(cols,1), x2(cols,1);
RealScalar largerEps = test_precision<RealScalar>();
if (ei_is_same_type<RealScalar,float>::ret)
largerEps = 1e-3f;
{
SVD<MatrixType> svd(a);
MatrixType sigma = MatrixType::Zero(rows,cols);
MatrixType matU = MatrixType::Zero(rows,rows);
sigma.block(0,0,cols,cols) = svd.singularValues().asDiagonal();
matU = svd.matrixU();
VERIFY_IS_APPROX(a, matU * sigma * svd.matrixV().transpose());
}
if (rows==cols)
{
if (ei_is_same_type<RealScalar,float>::ret)
{
MatrixType a1 = MatrixType::Random(rows,cols);
a += a * a.adjoint() + a1 * a1.adjoint();
}
SVD<MatrixType> svd(a);
svd.solve(b, &x);
VERIFY_IS_APPROX(a * x,b);
}
if(rows==cols)
{
SVD<MatrixType> svd(a);
MatrixType unitary, positive;
svd.computeUnitaryPositive(&unitary, &positive);
VERIFY_IS_APPROX(unitary * unitary.adjoint(), MatrixType::Identity(unitary.rows(),unitary.rows()));
VERIFY_IS_APPROX(positive, positive.adjoint());
for(int i = 0; i < rows; i++) VERIFY(positive.diagonal()[i] >= 0); // cheap necessary (not sufficient) condition for positivity
VERIFY_IS_APPROX(unitary*positive, a);
svd.computePositiveUnitary(&positive, &unitary);
VERIFY_IS_APPROX(unitary * unitary.adjoint(), MatrixType::Identity(unitary.rows(),unitary.rows()));
VERIFY_IS_APPROX(positive, positive.adjoint());
for(int i = 0; i < rows; i++) VERIFY(positive.diagonal()[i] >= 0); // cheap necessary (not sufficient) condition for positivity
VERIFY_IS_APPROX(positive*unitary, a);
}
}
template<typename MatrixType> void svd_verify_assert()
{
MatrixType tmp;
SVD<MatrixType> svd;
VERIFY_RAISES_ASSERT(svd.solve(tmp, &tmp))
VERIFY_RAISES_ASSERT(svd.matrixU())
VERIFY_RAISES_ASSERT(svd.singularValues())
VERIFY_RAISES_ASSERT(svd.matrixV())
VERIFY_RAISES_ASSERT(svd.computeUnitaryPositive(&tmp,&tmp))
VERIFY_RAISES_ASSERT(svd.computePositiveUnitary(&tmp,&tmp))
VERIFY_RAISES_ASSERT(svd.computeRotationScaling(&tmp,&tmp))
VERIFY_RAISES_ASSERT(svd.computeScalingRotation(&tmp,&tmp))
}
void test_svd()
{
for(int i = 0; i < g_repeat; i++) {
CALL_SUBTEST( svd(Matrix3f()) );
CALL_SUBTEST( svd(Matrix4d()) );
CALL_SUBTEST( svd(MatrixXf(7,7)) );
CALL_SUBTEST( svd(MatrixXd(14,7)) );
// complex are not implemented yet
// CALL_SUBTEST( svd(MatrixXcd(6,6)) );
// CALL_SUBTEST( svd(MatrixXcf(3,3)) );
}
CALL_SUBTEST( svd_verify_assert<Matrix3f>() );
CALL_SUBTEST( svd_verify_assert<Matrix3d>() );
CALL_SUBTEST( svd_verify_assert<MatrixXf>() );
CALL_SUBTEST( svd_verify_assert<MatrixXd>() );
}
<commit_msg>simplifications<commit_after>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2008 Gael Guennebaud <g.gael@free.fr>
//
// Eigen is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3 of the License, or (at your option) any later version.
//
// Alternatively, you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation; either version 2 of
// the License, or (at your option) any later version.
//
// Eigen 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 or the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License and a copy of the GNU General Public License along with
// Eigen. If not, see <http://www.gnu.org/licenses/>.
#include "main.h"
#include <Eigen/SVD>
#include <Eigen/LU>
template<typename MatrixType> void svd(const MatrixType& m)
{
/* this test covers the following files:
SVD.h
*/
int rows = m.rows();
int cols = m.cols();
typedef typename MatrixType::Scalar Scalar;
typedef typename NumTraits<Scalar>::Real RealScalar;
MatrixType a = MatrixType::Random(rows,cols);
Matrix<Scalar, MatrixType::RowsAtCompileTime, 1> b =
Matrix<Scalar, MatrixType::RowsAtCompileTime, 1>::Random(rows,1);
Matrix<Scalar, MatrixType::ColsAtCompileTime, 1> x(cols,1), x2(cols,1);
{
SVD<MatrixType> svd(a);
MatrixType sigma = MatrixType::Zero(rows,cols);
MatrixType matU = MatrixType::Zero(rows,rows);
sigma.diagonal() = svd.singularValues();
matU = svd.matrixU();
VERIFY_IS_APPROX(a, matU * sigma * svd.matrixV().transpose());
}
if (rows==cols)
{
if (ei_is_same_type<RealScalar,float>::ret)
{
MatrixType a1 = MatrixType::Random(rows,cols);
a += a * a.adjoint() + a1 * a1.adjoint();
}
SVD<MatrixType> svd(a);
svd.solve(b, &x);
VERIFY_IS_APPROX(a * x,b);
}
if(rows==cols)
{
SVD<MatrixType> svd(a);
MatrixType unitary, positive;
svd.computeUnitaryPositive(&unitary, &positive);
VERIFY_IS_APPROX(unitary * unitary.adjoint(), MatrixType::Identity(unitary.rows(),unitary.rows()));
VERIFY_IS_APPROX(positive, positive.adjoint());
for(int i = 0; i < rows; i++) VERIFY(positive.diagonal()[i] >= 0); // cheap necessary (not sufficient) condition for positivity
VERIFY_IS_APPROX(unitary*positive, a);
svd.computePositiveUnitary(&positive, &unitary);
VERIFY_IS_APPROX(unitary * unitary.adjoint(), MatrixType::Identity(unitary.rows(),unitary.rows()));
VERIFY_IS_APPROX(positive, positive.adjoint());
for(int i = 0; i < rows; i++) VERIFY(positive.diagonal()[i] >= 0); // cheap necessary (not sufficient) condition for positivity
VERIFY_IS_APPROX(positive*unitary, a);
}
}
template<typename MatrixType> void svd_verify_assert()
{
MatrixType tmp;
SVD<MatrixType> svd;
VERIFY_RAISES_ASSERT(svd.solve(tmp, &tmp))
VERIFY_RAISES_ASSERT(svd.matrixU())
VERIFY_RAISES_ASSERT(svd.singularValues())
VERIFY_RAISES_ASSERT(svd.matrixV())
VERIFY_RAISES_ASSERT(svd.computeUnitaryPositive(&tmp,&tmp))
VERIFY_RAISES_ASSERT(svd.computePositiveUnitary(&tmp,&tmp))
VERIFY_RAISES_ASSERT(svd.computeRotationScaling(&tmp,&tmp))
VERIFY_RAISES_ASSERT(svd.computeScalingRotation(&tmp,&tmp))
}
void test_svd()
{
for(int i = 0; i < g_repeat; i++) {
CALL_SUBTEST( svd(Matrix3f()) );
CALL_SUBTEST( svd(Matrix4d()) );
CALL_SUBTEST( svd(MatrixXf(7,7)) );
CALL_SUBTEST( svd(MatrixXd(14,7)) );
// complex are not implemented yet
// CALL_SUBTEST( svd(MatrixXcd(6,6)) );
// CALL_SUBTEST( svd(MatrixXcf(3,3)) );
}
CALL_SUBTEST( svd_verify_assert<Matrix3f>() );
CALL_SUBTEST( svd_verify_assert<Matrix3d>() );
CALL_SUBTEST( svd_verify_assert<MatrixXf>() );
CALL_SUBTEST( svd_verify_assert<MatrixXd>() );
}
<|endoftext|> |
<commit_before>/******************************************************************************
* ____ _ _____ *
* / ___| / \ | ___| C++ *
* | | / _ \ | |_ Actor *
* | |___ / ___ \| _| Framework *
* \____/_/ \_|_| *
* *
* Copyright (C) 2011 - 2016 *
* Dominik Charousset <dominik.charousset (at) haw-hamburg.de> *
* *
* Distributed under the terms and conditions of the BSD 3-Clause License or *
* (at your option) under the terms and conditions of the Boost Software *
* License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. *
* *
* If you did not receive a copy of the license files, see *
* http://opensource.org/licenses/BSD-3-Clause and *
* http://www.boost.org/LICENSE_1_0.txt. *
******************************************************************************/
#ifndef CAF_ACTOR_CONFIG_HPP
#define CAF_ACTOR_CONFIG_HPP
#include <string>
#include <functional>
#include "caf/fwd.hpp"
#include "caf/input_range.hpp"
#include "caf/abstract_channel.hpp"
namespace caf {
/// Stores spawn-time flags and groups.
class actor_config {
public:
execution_unit* host;
int flags;
input_range<const group>* groups;
std::function<behavior (local_actor*)> init_fun;
explicit actor_config(execution_unit* ptr = nullptr);
inline actor_config& add_flag(int x) {
flags |= x;
return *this;
}
};
/// @relates actor_config
std::string to_string(const actor_config& x);
} // namespace caf
#endif // CAF_ACTOR_CONFIG_HPP
<commit_msg>Fix FreeBSD 12 build with Clang 4.0<commit_after>/******************************************************************************
* ____ _ _____ *
* / ___| / \ | ___| C++ *
* | | / _ \ | |_ Actor *
* | |___ / ___ \| _| Framework *
* \____/_/ \_|_| *
* *
* Copyright (C) 2011 - 2016 *
* Dominik Charousset <dominik.charousset (at) haw-hamburg.de> *
* *
* Distributed under the terms and conditions of the BSD 3-Clause License or *
* (at your option) under the terms and conditions of the Boost Software *
* License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. *
* *
* If you did not receive a copy of the license files, see *
* http://opensource.org/licenses/BSD-3-Clause and *
* http://www.boost.org/LICENSE_1_0.txt. *
******************************************************************************/
#ifndef CAF_ACTOR_CONFIG_HPP
#define CAF_ACTOR_CONFIG_HPP
#include <string>
#include <functional>
#include "caf/fwd.hpp"
#include "caf/behavior.hpp"
#include "caf/input_range.hpp"
#include "caf/abstract_channel.hpp"
namespace caf {
/// Stores spawn-time flags and groups.
class actor_config {
public:
execution_unit* host;
int flags;
input_range<const group>* groups;
std::function<behavior (local_actor*)> init_fun;
explicit actor_config(execution_unit* ptr = nullptr);
inline actor_config& add_flag(int x) {
flags |= x;
return *this;
}
};
/// @relates actor_config
std::string to_string(const actor_config& x);
} // namespace caf
#endif // CAF_ACTOR_CONFIG_HPP
<|endoftext|> |
<commit_before>#include <sm/BoostPropertyTree.hpp>
#include <boost/property_tree/xml_parser.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <boost/property_tree/ini_parser.hpp>
#include <boost/property_tree/info_parser.hpp>
#include <sm/BoostPropertyTreeImplementation.hpp>
namespace sm {
BoostPropertyTree::BoostPropertyTree(const std::string & baseNamespace) :
PropertyTree(boost::shared_ptr<PropertyTreeImplementation>(new BoostPropertyTreeImplementation), baseNamespace)
{
}
BoostPropertyTree::~BoostPropertyTree()
{
}
void BoostPropertyTree::loadXml(const boost::filesystem::path & fileName)
{
dynamic_cast<BoostPropertyTreeImplementation*>(_imp.get())->loadXml(fileName);
}
void BoostPropertyTree::saveXml(const boost::filesystem::path & fileName) const
{
dynamic_cast<const BoostPropertyTreeImplementation*>(_imp.get())->saveXml(fileName);
}
void BoostPropertyTree::loadJson(const boost::filesystem::path & fileName)
{
dynamic_cast<BoostPropertyTreeImplementation*>(_imp.get())->loadJson(fileName);
}
void BoostPropertyTree::saveJson(const boost::filesystem::path & fileName) const
{
dynamic_cast<const BoostPropertyTreeImplementation*>(_imp.get())->saveJson(fileName);
}
void BoostPropertyTree::loadIni(const boost::filesystem::path & fileName)
{
dynamic_cast<BoostPropertyTreeImplementation*>(_imp.get())->loadIni(fileName);
}
void BoostPropertyTree::saveIni(const boost::filesystem::path & fileName) const
{
dynamic_cast<const BoostPropertyTreeImplementation*>(_imp.get())->saveIni(fileName);
}
void BoostPropertyTree::loadInfo(const boost::filesystem::path & fileName)
{
dynamic_cast<BoostPropertyTreeImplementation*>(_imp.get())->loadInfo(fileName);
}
void BoostPropertyTree::saveInfo(const boost::filesystem::path & fileName) const
{
dynamic_cast<const BoostPropertyTreeImplementation*>(_imp.get())->saveInfo(fileName);
}
BoostPropertyTree::iterator BoostPropertyTree::begin()
{
dynamic_cast<BoostPropertyTreeImplementation*>(_imp.get())->begin();
}
BoostPropertyTree::const_iterator BoostPropertyTree::begin() const
{
dynamic_cast<const BoostPropertyTreeImplementation*>(_imp.get())->begin();
}
BoostPropertyTree::iterator BoostPropertyTree::end()
{
dynamic_cast<BoostPropertyTreeImplementation*>(_imp.get())->end();
}
BoostPropertyTree::const_iterator BoostPropertyTree::end() const
{
dynamic_cast<const BoostPropertyTreeImplementation*>(_imp.get())->end();
}
} // namespace sm
<commit_msg>Added missing return statements from the Boost property tree<commit_after>#include <sm/BoostPropertyTree.hpp>
#include <boost/property_tree/xml_parser.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <boost/property_tree/ini_parser.hpp>
#include <boost/property_tree/info_parser.hpp>
#include <sm/BoostPropertyTreeImplementation.hpp>
namespace sm {
BoostPropertyTree::BoostPropertyTree(const std::string & baseNamespace) :
PropertyTree(boost::shared_ptr<PropertyTreeImplementation>(new BoostPropertyTreeImplementation), baseNamespace)
{
}
BoostPropertyTree::~BoostPropertyTree()
{
}
void BoostPropertyTree::loadXml(const boost::filesystem::path & fileName)
{
dynamic_cast<BoostPropertyTreeImplementation*>(_imp.get())->loadXml(fileName);
}
void BoostPropertyTree::saveXml(const boost::filesystem::path & fileName) const
{
dynamic_cast<const BoostPropertyTreeImplementation*>(_imp.get())->saveXml(fileName);
}
void BoostPropertyTree::loadJson(const boost::filesystem::path & fileName)
{
dynamic_cast<BoostPropertyTreeImplementation*>(_imp.get())->loadJson(fileName);
}
void BoostPropertyTree::saveJson(const boost::filesystem::path & fileName) const
{
dynamic_cast<const BoostPropertyTreeImplementation*>(_imp.get())->saveJson(fileName);
}
void BoostPropertyTree::loadIni(const boost::filesystem::path & fileName)
{
dynamic_cast<BoostPropertyTreeImplementation*>(_imp.get())->loadIni(fileName);
}
void BoostPropertyTree::saveIni(const boost::filesystem::path & fileName) const
{
dynamic_cast<const BoostPropertyTreeImplementation*>(_imp.get())->saveIni(fileName);
}
void BoostPropertyTree::loadInfo(const boost::filesystem::path & fileName)
{
dynamic_cast<BoostPropertyTreeImplementation*>(_imp.get())->loadInfo(fileName);
}
void BoostPropertyTree::saveInfo(const boost::filesystem::path & fileName) const
{
dynamic_cast<const BoostPropertyTreeImplementation*>(_imp.get())->saveInfo(fileName);
}
BoostPropertyTree::iterator BoostPropertyTree::begin()
{
return dynamic_cast<BoostPropertyTreeImplementation*>(_imp.get())->begin();
}
BoostPropertyTree::const_iterator BoostPropertyTree::begin() const
{
return dynamic_cast<const BoostPropertyTreeImplementation*>(_imp.get())->begin();
}
BoostPropertyTree::iterator BoostPropertyTree::end()
{
return dynamic_cast<BoostPropertyTreeImplementation*>(_imp.get())->end();
}
BoostPropertyTree::const_iterator BoostPropertyTree::end() const
{
return dynamic_cast<const BoostPropertyTreeImplementation*>(_imp.get())->end();
}
} // namespace sm
<|endoftext|> |
<commit_before>/*
kopetestdaction.cpp - Kopete Standard Actionds
Copyright (c) 2001-2002 by Ryan Cumming. <bodnar42@phalynx.dhs.org>
Kopete (c) 2002 by the Kopete developers <kopete-devel@kde.org>
*************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
*************************************************************************
*/
#include <kaction.h>
#include <klocale.h>
#include <kdebug.h>
#include "kopete.h"
#include "kopetestdaction.h"
#include "kopetecontactlist.h"
#include "kopetecontactlistview.h"
#include "kopeteprotocol.h"
#include "pluginloader.h"
/** KopeteGroupList **/
KopeteGroupList::KopeteGroupList(const QString& text, const QString& pix, const KShortcut& cut, const QObject* receiver, const char* slot, QObject* parent, const char* name)
: KListAction(text, pix, cut, parent, name)
{
connect( this, SIGNAL( activated() ), receiver, slot );
connect(KopeteContactList::contactList(), SIGNAL(groupAdded(const QString &)), this, SLOT(slotUpdateList()));
connect(KopeteContactList::contactList(), SIGNAL(groupRemoved(const QString &)), this, SLOT(slotUpdateList()));
slotUpdateList();
}
KopeteGroupList::~KopeteGroupList()
{
}
void KopeteGroupList::slotUpdateList()
{
m_groupList = QStringList();
m_groupList << "Top Level";
m_groupList += KopeteContactList::contactList()->groups();
setItems( m_groupList );
}
KAction* KopeteStdAction::chat( const QObject *recvr, const char *slot,
QObject* parent, const char *name )
{
return new KAction( i18n("Start &Chat..."), "mail_generic", 0, recvr, slot, parent,
name );
}
KAction* KopeteStdAction::sendMessage(const QObject *recvr, const char *slot, QObject* parent, const char *name)
{
return new KAction( i18n("&Send Message..."), "mail_generic", 0, recvr, slot,
parent, name );
}
KAction* KopeteStdAction::contactInfo(const QObject *recvr, const char *slot, QObject* parent, const char *name)
{
return new KAction( i18n("User &Info..."), "identity", 0, recvr, slot, parent,
name );
}
KAction* KopeteStdAction::viewHistory(const QObject *recvr, const char *slot, QObject* parent, const char *name)
{
return new KAction( i18n("View &History..."), "history", 0, recvr, slot, parent,
name );
}
KAction* KopeteStdAction::addGroup(const QObject *recvr, const char *slot, QObject* parent, const char *name)
{
return new KAction( i18n("&Add Group..."), "folder", 0, recvr, slot, parent,
name );
}
KAction* KopeteStdAction::changeMetaContact(const QObject *recvr, const char *slot, QObject* parent, const char *name)
{
return new KAction( i18n("Cha&nge MetaContact"), "move", 0, recvr, slot, parent,
name );
}
KListAction *KopeteStdAction::moveContact(const QObject *recvr, const char *slot, QObject* parent, const char *name)
{
return new KopeteGroupList( i18n("&Move Contact"), "editcut", 0, recvr, slot,
parent, name );
}
KListAction *KopeteStdAction::copyContact( const QObject *recvr,
const char *slot, QObject* parent, const char *name )
{
return new KopeteGroupList( i18n("Cop&y Contact"), "editcopy", 0, recvr, slot,
parent, name );
}
KAction* KopeteStdAction::deleteContact(const QObject *recvr, const char *slot, QObject* parent, const char *name)
{
return new KAction( i18n("&Delete Contact..."), "edittrash", 0, recvr, slot,
parent, name );
}
KListAction *KopeteStdAction::addContact(const QObject *recvr, const char *slot, QObject* parent, const char *name)
{
KListAction *a=new KListAction( i18n("&Add Contact"), "bookmark_add", 0, recvr, slot, parent, name );
QStringList protocolList;
QValueList<KopeteLibraryInfo> l = kopeteapp->libraryLoader()->loaded();
for (QValueList<KopeteLibraryInfo>::Iterator i = l.begin(); i != l.end(); ++i)
{
KopetePlugin *tmpprot = (kopeteapp->libraryLoader())->mLibHash[(*i).specfile]->plugin;
KopeteProtocol *prot = dynamic_cast<KopeteProtocol*>( tmpprot );
if (prot)
{
protocolList.append((*i).name);
}
}
a->setItems( protocolList );
return a;
}
KAction* KopeteStdAction::changeAlias(const QObject *recvr, const char *slot, QObject* parent, const char *name)
{
return new KAction( i18n("Change A&lias"), "signature", 0, recvr, slot, parent, name );
}
#include "kopetestdaction.moc"
/*
* Local variables:
* c-indentation-style: k&r
* c-basic-offset: 8
* indent-tabs-mode: t
* End:
*/
// vim: set noet ts=4 sts=4 sw=4:
<commit_msg>Style-guide fix<commit_after>/*
kopetestdaction.cpp - Kopete Standard Actionds
Copyright (c) 2001-2002 by Ryan Cumming. <bodnar42@phalynx.dhs.org>
Kopete (c) 2002 by the Kopete developers <kopete-devel@kde.org>
*************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
*************************************************************************
*/
#include <kaction.h>
#include <klocale.h>
#include <kdebug.h>
#include "kopete.h"
#include "kopetestdaction.h"
#include "kopetecontactlist.h"
#include "kopetecontactlistview.h"
#include "kopeteprotocol.h"
#include "pluginloader.h"
/** KopeteGroupList **/
KopeteGroupList::KopeteGroupList(const QString& text, const QString& pix, const KShortcut& cut, const QObject* receiver, const char* slot, QObject* parent, const char* name)
: KListAction(text, pix, cut, parent, name)
{
connect( this, SIGNAL( activated() ), receiver, slot );
connect(KopeteContactList::contactList(), SIGNAL(groupAdded(const QString &)), this, SLOT(slotUpdateList()));
connect(KopeteContactList::contactList(), SIGNAL(groupRemoved(const QString &)), this, SLOT(slotUpdateList()));
slotUpdateList();
}
KopeteGroupList::~KopeteGroupList()
{
}
void KopeteGroupList::slotUpdateList()
{
m_groupList = QStringList();
m_groupList << "Top Level";
m_groupList += KopeteContactList::contactList()->groups();
setItems( m_groupList );
}
KAction* KopeteStdAction::chat( const QObject *recvr, const char *slot,
QObject* parent, const char *name )
{
return new KAction( i18n("Start &Chat..."), "mail_generic", 0, recvr, slot, parent,
name );
}
KAction* KopeteStdAction::sendMessage(const QObject *recvr, const char *slot, QObject* parent, const char *name)
{
return new KAction( i18n("&Send Message..."), "mail_generic", 0, recvr, slot,
parent, name );
}
KAction* KopeteStdAction::contactInfo(const QObject *recvr, const char *slot, QObject* parent, const char *name)
{
return new KAction( i18n("User &Info..."), "identity", 0, recvr, slot, parent,
name );
}
KAction* KopeteStdAction::viewHistory(const QObject *recvr, const char *slot, QObject* parent, const char *name)
{
return new KAction( i18n("View &History..."), "history", 0, recvr, slot, parent,
name );
}
KAction* KopeteStdAction::addGroup(const QObject *recvr, const char *slot, QObject* parent, const char *name)
{
return new KAction( i18n("&Add Group..."), "folder", 0, recvr, slot, parent,
name );
}
KAction* KopeteStdAction::changeMetaContact(const QObject *recvr, const char *slot, QObject* parent, const char *name)
{
return new KAction( i18n("Cha&nge MetaContact..."), "move", 0, recvr, slot, parent,
name );
}
KListAction *KopeteStdAction::moveContact(const QObject *recvr, const char *slot, QObject* parent, const char *name)
{
return new KopeteGroupList( i18n("&Move Contact"), "editcut", 0, recvr, slot,
parent, name );
}
KListAction *KopeteStdAction::copyContact( const QObject *recvr,
const char *slot, QObject* parent, const char *name )
{
return new KopeteGroupList( i18n("Cop&y Contact"), "editcopy", 0, recvr, slot,
parent, name );
}
KAction* KopeteStdAction::deleteContact(const QObject *recvr, const char *slot, QObject* parent, const char *name)
{
return new KAction( i18n("&Delete Contact..."), "edittrash", 0, recvr, slot,
parent, name );
}
KListAction *KopeteStdAction::addContact(const QObject *recvr, const char *slot, QObject* parent, const char *name)
{
KListAction *a=new KListAction( i18n("&Add Contact"), "bookmark_add", 0, recvr, slot, parent, name );
QStringList protocolList;
QValueList<KopeteLibraryInfo> l = kopeteapp->libraryLoader()->loaded();
for (QValueList<KopeteLibraryInfo>::Iterator i = l.begin(); i != l.end(); ++i)
{
KopetePlugin *tmpprot = (kopeteapp->libraryLoader())->mLibHash[(*i).specfile]->plugin;
KopeteProtocol *prot = dynamic_cast<KopeteProtocol*>( tmpprot );
if (prot)
{
protocolList.append((*i).name);
}
}
a->setItems( protocolList );
return a;
}
KAction* KopeteStdAction::changeAlias(const QObject *recvr, const char *slot, QObject* parent, const char *name)
{
return new KAction( i18n("Change A&lias..."), "signature", 0, recvr, slot, parent, name );
}
#include "kopetestdaction.moc"
/*
* Local variables:
* c-indentation-style: k&r
* c-basic-offset: 8
* indent-tabs-mode: t
* End:
*/
// vim: set noet ts=4 sts=4 sw=4:
<|endoftext|> |
<commit_before>/*
kopetestdaction.cpp - Kopete Standard Actionds
Copyright (c) 2001-2002 by Ryan Cumming <ryan@kde.org>
Copyright (c) 2002-2003 by Martijn Klingens <klingens@kde.org>
Kopete (c) 2001-2003 by the Kopete developers <kopete-devel@kde.org>
*************************************************************************
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Lesser General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
*************************************************************************
*/
#include "kopetestdaction.h"
#include <qapplication.h>
#include <kdebug.h>
#include <kdeversion.h>
#include <kguiitem.h>
#include <klocale.h>
#include <ksettings/dialog.h>
#include <kstdaction.h>
#include <kstdguiitem.h>
#include <kwin.h>
#include <kcmultidialog.h>
#include "kopetecontactlist.h"
#include "kopetegroup.h"
KopeteGroupListAction::KopeteGroupListAction( const QString &text, const QString &pix, const KShortcut &cut, const QObject *receiver,
const char *slot, QObject *parent, const char *name )
: KListAction( text, pix, cut, parent, name )
{
connect( this, SIGNAL( activated() ), receiver, slot );
connect( KopeteContactList::contactList(), SIGNAL( groupAdded( KopeteGroup * ) ), this, SLOT( slotUpdateList() ) );
connect( KopeteContactList::contactList(), SIGNAL( groupRemoved( KopeteGroup * ) ), this, SLOT( slotUpdateList() ) );
slotUpdateList();
}
KopeteGroupListAction::~KopeteGroupListAction()
{
}
void KopeteGroupListAction::slotUpdateList()
{
QStringList groupList;
// Add groups to our list
KopeteGroupList groups = KopeteContactList::contactList()->groups();
for ( KopeteGroup *it = groups.first(); it; it = groups.next() )
{
// FIXME: I think handling the i18n for temporary and top level
// groups belongs in KopeteGroup instead.
// It's now duplicated in KopeteGroupListAction and
// KopeteGroupViewItem already - Martijn
QString displayName;
switch ( it->type() )
{
case KopeteGroup::Temporary:
// Moving to temporary makes no sense, skip the group
continue;
case KopeteGroup::TopLevel:
displayName = i18n( "(Top-Level)" );
break;
default:
displayName = it->displayName();
break;
}
groupList.append( displayName );
}
setItems( groupList );
}
KSettings::Dialog *KopetePreferencesAction::s_settingsDialog = 0L;
KopetePreferencesAction::KopetePreferencesAction( KActionCollection *parent, const char *name )
// FIXME: Pending kdelibs change, uncomment when it's in - Martijn
//#if KDE_IS_VERSION( 3, 1, 90 )
//: KAction( KStdGuiItem::preferences(), 0, 0, 0, parent, name )
//#else
: KAction( KGuiItem( i18n( "&Configure Kopete..." ),
QString::fromLatin1( "configure" ) ), 0, 0, 0, parent, name )
//#endif
{
connect( this, SIGNAL( activated() ), this, SLOT( slotShowPreferences() ) );
}
KopetePreferencesAction::~KopetePreferencesAction()
{
}
void KopetePreferencesAction::slotShowPreferences()
{
// FIXME: Use static deleter - Martijn
if ( !s_settingsDialog )
s_settingsDialog = new KSettings::Dialog( KSettings::Dialog::Static, qApp->mainWidget() );
s_settingsDialog->show();
s_settingsDialog->dialog()->raise();
#if KDE_IS_VERSION( 3, 1, 90 )
KWin::activateWindow( s_settingsDialog->dialog()->winId() );
#endif
}
KAction * KopeteStdAction::preferences( KActionCollection *parent, const char *name )
{
return new KopetePreferencesAction( parent, name );
}
KAction * KopeteStdAction::chat( const QObject *recvr, const char *slot, QObject *parent, const char *name )
{
return new KAction( i18n( "Start &Chat..." ), QString::fromLatin1( "mail_generic" ), 0, recvr, slot, parent, name );
}
KAction * KopeteStdAction::sendMessage( const QObject *recvr, const char *slot, QObject *parent, const char *name )
{
return new KAction( i18n( "&Send Message..." ), QString::fromLatin1( "mail_generic" ), 0, recvr, slot, parent, name );
}
KAction * KopeteStdAction::contactInfo( const QObject *recvr, const char *slot, QObject *parent, const char *name )
{
return new KAction( i18n( "User &Info" ), QString::fromLatin1( "messagebox_info" ), 0, recvr, slot, parent, name );
}
KAction * KopeteStdAction::sendFile( const QObject *recvr, const char *slot, QObject *parent, const char *name )
{
return new KAction( i18n( "Send &File..." ), QString::fromLatin1( "launch" ), 0, recvr, slot, parent, name );
}
KAction * KopeteStdAction::viewHistory( const QObject *recvr, const char *slot, QObject *parent, const char *name )
{
return new KAction( i18n( "View &History..." ), QString::fromLatin1( "history" ), 0, recvr, slot, parent, name );
}
KAction * KopeteStdAction::addGroup( const QObject *recvr, const char *slot, QObject *parent, const char *name )
{
return new KAction( i18n( "&Create Group..." ), QString::fromLatin1( "folder" ), 0, recvr, slot, parent, name );
}
KAction * KopeteStdAction::changeMetaContact( const QObject *recvr, const char *slot, QObject *parent, const char *name )
{
return new KAction( i18n( "Cha&nge Meta Contact..." ), QString::fromLatin1( "move" ), 0, recvr, slot, parent, name );
}
KListAction * KopeteStdAction::moveContact( const QObject *recvr, const char *slot, QObject *parent, const char *name )
{
return new KopeteGroupListAction( i18n( "&Move To" ), QString::fromLatin1( "editcut" ), 0, recvr, slot, parent, name );
}
KListAction * KopeteStdAction::copyContact( const QObject *recvr, const char *slot, QObject *parent, const char *name )
{
return new KopeteGroupListAction( i18n( "Cop&y To" ), QString::fromLatin1( "editcopy" ), 0, recvr, slot, parent, name );
}
KAction * KopeteStdAction::deleteContact( const QObject *recvr, const char *slot, QObject *parent, const char *name )
{
return new KAction( i18n( "&Delete Contact..." ), QString::fromLatin1( "edittrash" ), 0, recvr, slot, parent, name );
}
KAction * KopeteStdAction::changeAlias( const QObject *recvr, const char *slot, QObject *parent, const char *name )
{
return new KAction( i18n( "Change A&lias..." ), QString::fromLatin1( "signature" ), 0, recvr, slot, parent, name );
}
#include "kopetestdaction.moc"
// vim: set noet ts=4 sts=4 sw=4:
<commit_msg>Fix minor UI bug / annoyance.<commit_after>/*
kopetestdaction.cpp - Kopete Standard Actionds
Copyright (c) 2001-2002 by Ryan Cumming <ryan@kde.org>
Copyright (c) 2002-2003 by Martijn Klingens <klingens@kde.org>
Kopete (c) 2001-2003 by the Kopete developers <kopete-devel@kde.org>
*************************************************************************
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Lesser General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
*************************************************************************
*/
#include "kopetestdaction.h"
#include <qapplication.h>
#include <kdebug.h>
#include <kdeversion.h>
#include <kguiitem.h>
#include <klocale.h>
#include <ksettings/dialog.h>
#include <kstdaction.h>
#include <kstdguiitem.h>
#include <kwin.h>
#include <kcmultidialog.h>
#include "kopetecontactlist.h"
#include "kopetegroup.h"
KopeteGroupListAction::KopeteGroupListAction( const QString &text, const QString &pix, const KShortcut &cut, const QObject *receiver,
const char *slot, QObject *parent, const char *name )
: KListAction( text, pix, cut, parent, name )
{
connect( this, SIGNAL( activated() ), receiver, slot );
connect( KopeteContactList::contactList(), SIGNAL( groupAdded( KopeteGroup * ) ), this, SLOT( slotUpdateList() ) );
connect( KopeteContactList::contactList(), SIGNAL( groupRemoved( KopeteGroup * ) ), this, SLOT( slotUpdateList() ) );
slotUpdateList();
}
KopeteGroupListAction::~KopeteGroupListAction()
{
}
void KopeteGroupListAction::slotUpdateList()
{
QStringList groupList;
// Add groups to our list
KopeteGroupList groups = KopeteContactList::contactList()->groups();
for ( KopeteGroup *it = groups.first(); it; it = groups.next() )
{
// FIXME: I think handling the i18n for temporary and top level
// groups belongs in KopeteGroup instead.
// It's now duplicated in KopeteGroupListAction and
// KopeteGroupViewItem already - Martijn
QString displayName;
switch ( it->type() )
{
case KopeteGroup::Temporary:
// Moving to temporary makes no sense, skip the group
continue;
case KopeteGroup::TopLevel:
displayName = i18n( "(Top-Level)" );
break;
default:
displayName = it->displayName();
break;
}
groupList.append( displayName );
}
groupList.sort();
setItems( groupList );
}
KSettings::Dialog *KopetePreferencesAction::s_settingsDialog = 0L;
KopetePreferencesAction::KopetePreferencesAction( KActionCollection *parent, const char *name )
// FIXME: Pending kdelibs change, uncomment when it's in - Martijn
//#if KDE_IS_VERSION( 3, 1, 90 )
//: KAction( KStdGuiItem::preferences(), 0, 0, 0, parent, name )
//#else
: KAction( KGuiItem( i18n( "&Configure Kopete..." ),
QString::fromLatin1( "configure" ) ), 0, 0, 0, parent, name )
//#endif
{
connect( this, SIGNAL( activated() ), this, SLOT( slotShowPreferences() ) );
}
KopetePreferencesAction::~KopetePreferencesAction()
{
}
void KopetePreferencesAction::slotShowPreferences()
{
// FIXME: Use static deleter - Martijn
if ( !s_settingsDialog )
s_settingsDialog = new KSettings::Dialog( KSettings::Dialog::Static, qApp->mainWidget() );
s_settingsDialog->show();
s_settingsDialog->dialog()->raise();
#if KDE_IS_VERSION( 3, 1, 90 )
KWin::activateWindow( s_settingsDialog->dialog()->winId() );
#endif
}
KAction * KopeteStdAction::preferences( KActionCollection *parent, const char *name )
{
return new KopetePreferencesAction( parent, name );
}
KAction * KopeteStdAction::chat( const QObject *recvr, const char *slot, QObject *parent, const char *name )
{
return new KAction( i18n( "Start &Chat..." ), QString::fromLatin1( "mail_generic" ), 0, recvr, slot, parent, name );
}
KAction * KopeteStdAction::sendMessage( const QObject *recvr, const char *slot, QObject *parent, const char *name )
{
return new KAction( i18n( "&Send Message..." ), QString::fromLatin1( "mail_generic" ), 0, recvr, slot, parent, name );
}
KAction * KopeteStdAction::contactInfo( const QObject *recvr, const char *slot, QObject *parent, const char *name )
{
return new KAction( i18n( "User &Info" ), QString::fromLatin1( "messagebox_info" ), 0, recvr, slot, parent, name );
}
KAction * KopeteStdAction::sendFile( const QObject *recvr, const char *slot, QObject *parent, const char *name )
{
return new KAction( i18n( "Send &File..." ), QString::fromLatin1( "launch" ), 0, recvr, slot, parent, name );
}
KAction * KopeteStdAction::viewHistory( const QObject *recvr, const char *slot, QObject *parent, const char *name )
{
return new KAction( i18n( "View &History..." ), QString::fromLatin1( "history" ), 0, recvr, slot, parent, name );
}
KAction * KopeteStdAction::addGroup( const QObject *recvr, const char *slot, QObject *parent, const char *name )
{
return new KAction( i18n( "&Create Group..." ), QString::fromLatin1( "folder" ), 0, recvr, slot, parent, name );
}
KAction * KopeteStdAction::changeMetaContact( const QObject *recvr, const char *slot, QObject *parent, const char *name )
{
return new KAction( i18n( "Cha&nge Meta Contact..." ), QString::fromLatin1( "move" ), 0, recvr, slot, parent, name );
}
KListAction * KopeteStdAction::moveContact( const QObject *recvr, const char *slot, QObject *parent, const char *name )
{
return new KopeteGroupListAction( i18n( "&Move To" ), QString::fromLatin1( "editcut" ), 0, recvr, slot, parent, name );
}
KListAction * KopeteStdAction::copyContact( const QObject *recvr, const char *slot, QObject *parent, const char *name )
{
return new KopeteGroupListAction( i18n( "Cop&y To" ), QString::fromLatin1( "editcopy" ), 0, recvr, slot, parent, name );
}
KAction * KopeteStdAction::deleteContact( const QObject *recvr, const char *slot, QObject *parent, const char *name )
{
return new KAction( i18n( "&Delete Contact..." ), QString::fromLatin1( "edittrash" ), 0, recvr, slot, parent, name );
}
KAction * KopeteStdAction::changeAlias( const QObject *recvr, const char *slot, QObject *parent, const char *name )
{
return new KAction( i18n( "Change A&lias..." ), QString::fromLatin1( "signature" ), 0, recvr, slot, parent, name );
}
#include "kopetestdaction.moc"
// vim: set noet ts=4 sts=4 sw=4:
<|endoftext|> |
<commit_before>// This file is part of the dune-gdt project:
// https://github.com/dune-community/dune-gdt
// Copyright 2010-2018 dune-gdt developers and contributors. All rights reserved.
// License: Dual licensed as BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
// or GPL-2.0+ (http://opensource.org/licenses/gpl-license)
// with "runtime exception" (http://www.dune-project.org/license.html)
// Authors:
// Felix Schindler (2018)
// René Fritze (2018)
#ifndef DUNE_GDT_LOCAL_FINITE_ELEMENTS_DEFAULT_HH
#define DUNE_GDT_LOCAL_FINITE_ELEMENTS_DEFAULT_HH
#include <dune/xt/common/memory.hh>
#include "interfaces.hh"
namespace Dune {
namespace GDT {
/**
* \brief Implements LocalFiniteElementInterface, given a basis, coefficients and an interpolation.
*/
template <class D, size_t d, class R, size_t r, size_t rC = 1>
class LocalFiniteElementDefault : public LocalFiniteElementInterface<D, d, R, r, rC>
{
using ThisType = LocalFiniteElementDefault<D, d, R, r, rC>;
using BaseType = LocalFiniteElementInterface<D, d, R, r, rC>;
public:
using typename BaseType::BasisType;
using typename BaseType::CoefficientsType;
using typename BaseType::DomainType;
using typename BaseType::InterpolationType;
LocalFiniteElementDefault(const int ord,
const BasisType& bas,
const CoefficientsType& coeffs,
const InterpolationType& inter,
std::vector<DomainType> lps = {})
: geometry_type_(bas.geometry_type())
, order_(ord)
, basis_(bas)
, coefficients_(coeffs)
, interpolation_(inter)
, lagrange_points_(lps)
{
check_input();
}
/**
* \attention Do not delete any of the moved in raw pointers manually afterwads!
**/
LocalFiniteElementDefault(const int ord,
BasisType*&& bas_ptr,
CoefficientsType*&& coeffs_ptr,
InterpolationType*&& inter_ptr,
std::vector<DomainType> lps = {})
: geometry_type_(bas_ptr->geometry_type())
, order_(ord)
, basis_(std::move(bas_ptr))
, coefficients_(std::move(coeffs_ptr))
, interpolation_(std::move(inter_ptr))
, lagrange_points_(lps)
{
check_input();
}
const GeometryType& geometry_type() const override
{
return geometry_type_;
}
int order() const override
{
return order_;
}
size_t size() const override
{
return basis_.access().size();
}
const BasisType& basis() const override
{
return basis_.access();
}
const CoefficientsType& coefficients() const override
{
return coefficients_.access();
}
const InterpolationType& interpolation() const override
{
return interpolation_.access();
}
bool is_lagrangian() const override
{
return lagrange_points_.size() > 0;
}
const std::vector<DomainType>& lagrange_points() const override
{
if (!is_lagrangian())
DUNE_THROW(Exceptions::finite_element_error, "do not call lagrange_points() if is_lagrangian() is false!");
return lagrange_points_;
}
private:
void check_input()
{
DUNE_THROW_IF(coefficients_.access().geometry_type() != geometry_type_,
Exceptions::finite_element_error,
"\n coefficients_.access().geometry_type() = " << coefficients_.access().geometry_type()
<< "\n geometry_type_ = " << geometry_type_);
DUNE_THROW_IF(coefficients_.access().size() != basis_.access().size(),
Exceptions::finite_element_error,
"\n coefficients_.access().size() = "
<< coefficients_.access().size() << "\n basis_.access().size() = " << basis_.access().size());
DUNE_THROW_IF(interpolation_.access().geometry_type() != geometry_type_,
Exceptions::finite_element_error,
"\n interpolation_.access().geometry_type() = " << interpolation_.access().geometry_type()
<< "\n " << geometry_type_);
DUNE_THROW_IF(interpolation_.access().size() != basis_.access().size(),
Exceptions::finite_element_error,
"\n interpolation_.access().size() = "
<< interpolation_.access().size() << "\n basis_.access().size() = " << basis_.access().size());
DUNE_THROW_IF(!(lagrange_points_.size() == basis_.access().size() / (r * rC) || lagrange_points_.size() == 0),
Exceptions::finite_element_error,
"\n lagrange_points_.size() = " << lagrange_points_.size()
<< "\n basis_.access().size() / (r * rC) = "
<< basis_.access().size() / (r * rC));
} // ... check_input(...)
const GeometryType geometry_type_;
const int order_;
const XT::Common::ConstStorageProvider<BasisType> basis_;
const XT::Common::ConstStorageProvider<CoefficientsType> coefficients_;
const XT::Common::ConstStorageProvider<InterpolationType> interpolation_;
const std::vector<DomainType> lagrange_points_;
}; // class LocalFiniteElementDefault
template <class D, size_t d, class R = double, size_t r = 1, size_t rC = 1>
class ThreadSafeDefaultLocalFiniteElementFamily : public LocalFiniteElementFamilyInterface<D, d, R, r, rC>
{
using ThisType = ThreadSafeDefaultLocalFiniteElementFamily<D, d, R, r, rC>;
using BaseType = LocalFiniteElementFamilyInterface<D, d, R, r, rC>;
public:
using typename BaseType::LocalFiniteElementType;
ThreadSafeDefaultLocalFiniteElementFamily(
std::function<std::unique_ptr<LocalFiniteElementType>(const GeometryType&, const int&)> factory)
: factory_(factory)
{}
ThreadSafeDefaultLocalFiniteElementFamily(const ThisType& other)
: factory_(other.factory_)
{
// we do not even try to create the FEs in a thread safe way, they will just be recreated when required
}
ThreadSafeDefaultLocalFiniteElementFamily(ThisType&& source)
: factory_(std::move(source.factory_))
, fes_(std::move(source.fes_))
{}
const LocalFiniteElementType& get(const GeometryType& geometry_type, const int order) const override final
{
const auto key = std::make_pair(geometry_type, order);
// if the FE already exists, no need to lock since at() is thread safe and we are returning the object reference,
// not a map iterator which might get invalidated
// TODO: Double checked locking pattern is not thread-safe without memory barriers.
if (fes_.count(key) == 0) {
// the FE needs to be created, we need to lock
std::lock_guard<std::mutex> DXTC_UNUSED(guard)(mutex_);
// and to check again if someone else created the FE while we were waiting to acquire the lock
if (fes_.count(key) == 0) {
auto dings = factory_(geometry_type, order);
fes_.insert(std::make_pair(key, std::shared_ptr<LocalFiniteElementType>(dings.release())));
}
}
return *fes_.at(key);
} // ... get(...)
private:
const std::function<std::unique_ptr<LocalFiniteElementType>(const GeometryType&, const int&)> factory_;
mutable std::map<std::pair<GeometryType, int>, std::shared_ptr<LocalFiniteElementType>> fes_;
mutable std::mutex mutex_;
}; // class ThreadSafeDefaultLocalFiniteElementFamily
} // namespace GDT
} // namespace Dune
#endif // DUNE_GDT_LOCAL_FINITE_ELEMENTS_DEFAULT_HH
<commit_msg>[local.fem] add LocalL2FiniteElementInterpolation<commit_after>// This file is part of the dune-gdt project:
// https://github.com/dune-community/dune-gdt
// Copyright 2010-2018 dune-gdt developers and contributors. All rights reserved.
// License: Dual licensed as BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
// or GPL-2.0+ (http://opensource.org/licenses/gpl-license)
// with "runtime exception" (http://www.dune-project.org/license.html)
// Authors:
// Felix Schindler (2018)
// René Fritze (2018)
#ifndef DUNE_GDT_LOCAL_FINITE_ELEMENTS_DEFAULT_HH
#define DUNE_GDT_LOCAL_FINITE_ELEMENTS_DEFAULT_HH
#include <dune/geometry/quadraturerules.hh>
#include <dune/xt/common/memory.hh>
#include <dune/xt/grid/integrals.hh>
#include "interfaces.hh"
namespace Dune {
namespace GDT {
/**
* \brief Implements LocalFiniteElementInterface, given a basis, coefficients and an interpolation.
*/
template <class D, size_t d, class R, size_t r, size_t rC = 1>
class LocalFiniteElementDefault : public LocalFiniteElementInterface<D, d, R, r, rC>
{
using ThisType = LocalFiniteElementDefault<D, d, R, r, rC>;
using BaseType = LocalFiniteElementInterface<D, d, R, r, rC>;
public:
using typename BaseType::BasisType;
using typename BaseType::CoefficientsType;
using typename BaseType::DomainType;
using typename BaseType::InterpolationType;
LocalFiniteElementDefault(const int ord,
const BasisType& bas,
const CoefficientsType& coeffs,
const InterpolationType& inter,
std::vector<DomainType> lps = {})
: geometry_type_(bas.geometry_type())
, order_(ord)
, basis_(bas)
, coefficients_(coeffs)
, interpolation_(inter)
, lagrange_points_(lps)
{
check_input();
}
/**
* \attention Do not delete any of the moved in raw pointers manually afterwads!
**/
LocalFiniteElementDefault(const int ord,
BasisType*&& bas_ptr,
CoefficientsType*&& coeffs_ptr,
InterpolationType*&& inter_ptr,
std::vector<DomainType> lps = {})
: geometry_type_(bas_ptr->geometry_type())
, order_(ord)
, basis_(std::move(bas_ptr))
, coefficients_(std::move(coeffs_ptr))
, interpolation_(std::move(inter_ptr))
, lagrange_points_(lps)
{
check_input();
}
const GeometryType& geometry_type() const override
{
return geometry_type_;
}
int order() const override
{
return order_;
}
size_t size() const override
{
return basis_.access().size();
}
const BasisType& basis() const override
{
return basis_.access();
}
const CoefficientsType& coefficients() const override
{
return coefficients_.access();
}
const InterpolationType& interpolation() const override
{
return interpolation_.access();
}
bool is_lagrangian() const override
{
return lagrange_points_.size() > 0;
}
const std::vector<DomainType>& lagrange_points() const override
{
if (!is_lagrangian())
DUNE_THROW(Exceptions::finite_element_error, "do not call lagrange_points() if is_lagrangian() is false!");
return lagrange_points_;
}
private:
void check_input()
{
DUNE_THROW_IF(coefficients_.access().geometry_type() != geometry_type_,
Exceptions::finite_element_error,
"\n coefficients_.access().geometry_type() = " << coefficients_.access().geometry_type()
<< "\n geometry_type_ = " << geometry_type_);
DUNE_THROW_IF(coefficients_.access().size() != basis_.access().size(),
Exceptions::finite_element_error,
"\n coefficients_.access().size() = "
<< coefficients_.access().size() << "\n basis_.access().size() = " << basis_.access().size());
DUNE_THROW_IF(interpolation_.access().geometry_type() != geometry_type_,
Exceptions::finite_element_error,
"\n interpolation_.access().geometry_type() = " << interpolation_.access().geometry_type()
<< "\n " << geometry_type_);
DUNE_THROW_IF(interpolation_.access().size() != basis_.access().size(),
Exceptions::finite_element_error,
"\n interpolation_.access().size() = "
<< interpolation_.access().size() << "\n basis_.access().size() = " << basis_.access().size());
DUNE_THROW_IF(!(lagrange_points_.size() == basis_.access().size() / (r * rC) || lagrange_points_.size() == 0),
Exceptions::finite_element_error,
"\n lagrange_points_.size() = " << lagrange_points_.size()
<< "\n basis_.access().size() / (r * rC) = "
<< basis_.access().size() / (r * rC));
} // ... check_input(...)
const GeometryType geometry_type_;
const int order_;
const XT::Common::ConstStorageProvider<BasisType> basis_;
const XT::Common::ConstStorageProvider<CoefficientsType> coefficients_;
const XT::Common::ConstStorageProvider<InterpolationType> interpolation_;
const std::vector<DomainType> lagrange_points_;
}; // class LocalFiniteElementDefault
template <class D, size_t d, class R = double, size_t r = 1, size_t rC = 1>
class ThreadSafeDefaultLocalFiniteElementFamily : public LocalFiniteElementFamilyInterface<D, d, R, r, rC>
{
using ThisType = ThreadSafeDefaultLocalFiniteElementFamily<D, d, R, r, rC>;
using BaseType = LocalFiniteElementFamilyInterface<D, d, R, r, rC>;
public:
using typename BaseType::LocalFiniteElementType;
ThreadSafeDefaultLocalFiniteElementFamily(
std::function<std::unique_ptr<LocalFiniteElementType>(const GeometryType&, const int&)> factory)
: factory_(factory)
{}
ThreadSafeDefaultLocalFiniteElementFamily(const ThisType& other)
: factory_(other.factory_)
{
// we do not even try to create the FEs in a thread safe way, they will just be recreated when required
}
ThreadSafeDefaultLocalFiniteElementFamily(ThisType&& source)
: factory_(std::move(source.factory_))
, fes_(std::move(source.fes_))
{}
const LocalFiniteElementType& get(const GeometryType& geometry_type, const int order) const override final
{
const auto key = std::make_pair(geometry_type, order);
// if the FE already exists, no need to lock since at() is thread safe and we are returning the object reference,
// not a map iterator which might get invalidated
// TODO: Double checked locking pattern is not thread-safe without memory barriers.
if (fes_.count(key) == 0) {
// the FE needs to be created, we need to lock
std::lock_guard<std::mutex> DXTC_UNUSED(guard)(mutex_);
// and to check again if someone else created the FE while we were waiting to acquire the lock
if (fes_.count(key) == 0) {
auto dings = factory_(geometry_type, order);
fes_.insert(std::make_pair(key, std::shared_ptr<LocalFiniteElementType>(dings.release())));
}
}
return *fes_.at(key);
} // ... get(...)
private:
const std::function<std::unique_ptr<LocalFiniteElementType>(const GeometryType&, const int&)> factory_;
mutable std::map<std::pair<GeometryType, int>, std::shared_ptr<LocalFiniteElementType>> fes_;
mutable std::mutex mutex_;
}; // class ThreadSafeDefaultLocalFiniteElementFamily
template <class D, size_t d, class R, size_t r = 1>
class LocalL2FiniteElementInterpolation : public LocalFiniteElementInterpolationInterface<D, d, R, r, 1>
{
using ThisType = LocalL2FiniteElementInterpolation<D, d, R, r>;
using BaseType = LocalFiniteElementInterpolationInterface<D, d, R, r, 1>;
public:
using typename BaseType::DomainType;
using typename BaseType::RangeType;
using LocalBasisType = LocalFiniteElementBasisInterface<D, d, R, r, 1>;
LocalL2FiniteElementInterpolation(const LocalBasisType& local_basis)
: local_basis_(local_basis.copy())
{}
LocalL2FiniteElementInterpolation(const ThisType& other)
: local_basis_(other.local_basis_->copy())
{}
LocalL2FiniteElementInterpolation(ThisType& source) = default;
ThisType* copy() const override final
{
return new ThisType(*this);
}
const GeometryType& geometry_type() const override final
{
return local_basis_->geometry_type();
}
size_t size() const override final
{
return local_basis_->size();
}
using BaseType::interpolate;
void interpolate(const std::function<RangeType(DomainType)>& local_function,
const int order,
DynamicVector<R>& dofs) const override final
{
if (dofs.size() < this->size())
dofs.resize(this->size());
dofs *= 0.;
std::vector<RangeType> basis_values(local_basis_->size());
RangeType function_value;
for (auto&& quadrature_point : QuadratureRules<D, d>::rule(this->geometry_type(), order + local_basis_->order())) {
const auto point_in_reference_element = quadrature_point.position();
const auto quadrature_weight = quadrature_point.weight();
local_basis_->evaluate(point_in_reference_element, basis_values);
function_value = local_function(point_in_reference_element);
for (size_t ii = 0; ii < local_basis_->size(); ++ii)
dofs[ii] = (basis_values[ii] * function_value) * quadrature_weight;
}
} // ... interpolate(...)
private:
std::unique_ptr<LocalBasisType> local_basis_;
}; // class LocalL2FiniteElementInterpolation
} // namespace GDT
} // namespace Dune
#endif // DUNE_GDT_LOCAL_FINITE_ELEMENTS_DEFAULT_HH
<|endoftext|> |
<commit_before>// This file is part of the dune-hdd project:
// http://users.dune-project.org/projects/dune-hdd
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef DUNE_HDD_LINEARELLIPTIC_PROBLEMS_SPE10_HH
#define DUNE_HDD_LINEARELLIPTIC_PROBLEMS_SPE10_HH
#include <memory>
#include <vector>
#include <utility>
#include <sstream>
#include <dune/common/fmatrix.hh>
#include <dune/stuff/common/memory.hh>
#include <dune/stuff/common/fvector.hh>
#include <dune/stuff/common/float_cmp.hh>
#include <dune/stuff/common/type_utils.hh>
#include <dune/stuff/functions/constant.hh>
#include <dune/stuff/functions/combined.hh>
#include <dune/stuff/functions/flattop.hh>
#include <dune/stuff/functions/spe10.hh>
#include <dune/stuff/playground/functions/indicator.hh>
#include <dune/pymor/functions/default.hh>
#include "default.hh"
namespace Dune {
namespace HDD {
namespace LinearElliptic {
namespace Problems {
namespace Spe10 {
template< class E, class D, int d, class R, int r = 1 >
class Model1
: public ProblemInterface< E, D, d, R, r >
{
Model1() { static_assert(AlwaysFalse< E >::value, "Not available for these dimensions!"); }
};
template< class E, class D, class R >
class Model1< E, D, 2, R, 1 >
: public Problems::Default< E, D, 2, R, 1 >
{
typedef Problems::Default< E, D, 2, R, 1 > BaseType;
typedef Model1< E, D, 2, R, 1 > ThisType;
typedef Stuff::Functions::Constant< E, D, 2, R, 1 > ConstantFunctionType;
typedef Stuff::Functions::FlatTop< E, D, 2, R, 1 > FlatTopFunctionType;
typedef Stuff::Functions::Indicator< E, D, 2, R, 1 > IndicatorFunctionType;
typedef Stuff::Functions::Spe10::Model1< E, D, 2, R, 2, 2 > Spe10FunctionType;
public:
typedef typename BaseType::EntityType EntityType;
typedef typename BaseType::DomainFieldType DomainFieldType;
static const unsigned int dimDomain = BaseType::dimDomain;
typedef typename BaseType::DomainType DomainType;
typedef typename BaseType::RangeFieldType RangeFieldType;
static const unsigned int dimRange = BaseType::dimRange;
static const bool available = true;
static std::string static_id()
{
return BaseType::BaseType::static_id() + ".spe10.model1";
}
static Stuff::Common::Configuration default_config(const std::string sub_name = "")
{
std::istringstream ss("# a definition of a channel would be analogue to the one of forces\n"
"forces.0.domain = [0.95 1.10; 0.30 0.45]\n"
"forces.0.value = 2000\n"
"forces.1.domain = [3.00 3.15; 0.75 0.90]\n"
"forces.1.value = -1000\n"
"forces.2.domain = [4.25 4.40; 0.25 0.40]\n"
"forces.2.value = -1000");
Stuff::Common::Configuration config(ss);
config["filename"] = Stuff::Functions::Spe10::internal::model1_filename;
config["lower_left"] = "[0.0 0.0]";
config["upper_right"] = "[5.0 1.0]";
config["parametric_channel"] = "false";
config.set("channel_boundary_layer", FlatTopFunctionType::default_config().template get< std::string >("boundary_layer"));
if (sub_name.empty())
return config;
else {
Stuff::Common::Configuration tmp;
tmp.add(config, sub_name);
return tmp;
}
} // ... default_config(...)
static std::unique_ptr< ThisType > create(const Stuff::Common::Configuration config = default_config(),
const std::string sub_name = static_id())
{
const Stuff::Common::Configuration cfg = config.has_sub(sub_name) ? config.sub(sub_name) : config;
const Stuff::Common::Configuration def_cfg = default_config();
return Stuff::Common::make_unique< ThisType >(
cfg.get("filename", def_cfg.get< std::string >("filename")),
cfg.get("lower_left", def_cfg.get< DomainType >("lower_left")),
cfg.get("upper_right", def_cfg.get< DomainType >("upper_right")),
get_values(cfg, "channel"),
get_values(cfg, "forces"),
cfg.get("channel_boundary_layer", def_cfg.get< DomainType >("channel_boundary_layer")),
cfg.get("parametric_channel", def_cfg.get< bool >("parametric_channel")));
} // ... create(...)
Model1(const std::string filename,
const DomainType& lower_left,
const DomainType& upper_right,
const std::vector< std::tuple< DomainType, DomainType, RangeFieldType > >& channel_values,
const std::vector< std::tuple< DomainType, DomainType, RangeFieldType > >& force_values,
const DomainType& channel_boundary_layer = default_config().get< DomainType >("channel_boundary_layer"),
const bool parametric_channel = default_config().get< bool >("parametric_channel"))
: BaseType(create_base(filename,
lower_left,
upper_right,
channel_values,
force_values,
channel_boundary_layer,
parametric_channel))
{}
private:
typedef std::vector< std::tuple< DomainType, DomainType, RangeFieldType > > Values;
typedef typename BaseType::DiffusionFactorType::NonparametricType FlatTopIndicatorType;
static BaseType create_base(const std::string filename,
const DomainType& lower_left,
const DomainType& upper_right,
const Values& channel_values,
const Values& force_values,
const DomainType& channel_boundary_layer,
const bool parametric_channel)
{
// build the channel as a sum of flattop functions
std::shared_ptr< FlatTopIndicatorType > channel(nullptr);
if (channel_values.empty())
channel = std::make_shared< ConstantFunctionType >(0, "zero");
else
channel = create_indicator(channel_values[0], channel_boundary_layer);
for (size_t ii = 1; ii < channel_values.size(); ++ii)
channel = Stuff::Functions::make_sum(channel,
create_indicator(channel_values[ii], channel_boundary_layer),
"channel");
// build the rest
auto one = std::make_shared< ConstantFunctionType >(1, "one");
auto diffusion_tensor = std::make_shared< Spe10FunctionType >(filename,
lower_left,
upper_right,
Stuff::Functions::Spe10::internal::model1_min_value,
Stuff::Functions::Spe10::internal::model1_max_value,
"diffusion_tensor");
auto force = std::make_shared< IndicatorFunctionType >(force_values, "force");
auto dirichlet = std::make_shared< ConstantFunctionType >(0, "dirichlet");
auto neumann = std::make_shared< ConstantFunctionType >(0, "neumann");
if (parametric_channel) {
typedef Pymor::Functions::NonparametricDefault< E, D, 2, R, 1 > ScalarWrapper;
typedef Pymor::Functions::NonparametricDefault< E, D, 2, R, 2, 2 > MatrixWrapper;
typedef Pymor::Functions::AffinelyDecomposableDefault< E, D, 2, R, 1 > ParametricFunctionType;
auto diffusion_factor = std::make_shared< ParametricFunctionType >("diffusion_factor");
auto minus_one = std::make_shared< ConstantFunctionType >(-1, "minus_one");
diffusion_factor->register_affine_part(Stuff::Functions::make_sum(one, channel));
diffusion_factor->register_component(Stuff::Functions::make_prodcut(minus_one, channel),
new Pymor::ParameterFunctional("mu", 1, "mu[0]"));
return BaseType(diffusion_factor,
std::make_shared< MatrixWrapper >(diffusion_tensor),
std::make_shared< ScalarWrapper >(force),
std::make_shared< ScalarWrapper >(dirichlet),
std::make_shared< ScalarWrapper >(neumann));
} else {
auto zero_pt_nine = std::make_shared< ConstantFunctionType >(0.9, "0.9");
return BaseType(Stuff::Functions::make_sum(one,
Stuff::Functions::make_product(zero_pt_nine,
channel,
"scaled_channel"),
"diffusion_factor"),
diffusion_tensor,
force,
dirichlet,
neumann);
}
} // ... create_base(...)
static Values get_values(const Stuff::Common::Configuration& cfg, const std::string id)
{
Values values;
DomainType tmp_lower;
DomainType tmp_upper;
if (cfg.has_sub(id)) {
const Stuff::Common::Configuration sub_cfg = cfg.sub(id);
size_t cc = 0;
while (sub_cfg.has_sub(DSC::toString(cc))) {
const Stuff::Common::Configuration local_cfg = sub_cfg.sub(DSC::toString(cc));
if (local_cfg.has_key("domain") && local_cfg.has_key("value")) {
auto domains = local_cfg.get< FieldMatrix< DomainFieldType, 2, 2 > >("domain");
tmp_lower[0] = domains[0][0];
tmp_lower[1] = domains[1][0];
tmp_upper[0] = domains[0][1];
tmp_upper[1] = domains[1][1];
auto val = local_cfg.get< RangeFieldType >("value");
values.emplace_back(tmp_lower, tmp_upper, val);
} else
break;
++cc;
}
}
return values;
} // ... get_values(...)
static std::shared_ptr< FlatTopIndicatorType > create_indicator(const typename Values::value_type& value,
const DomainType& channel_boundary_layer)
{
if (Stuff::Common::FloatCmp::eq(channel_boundary_layer, DomainType(0))) {
return std::make_shared< IndicatorFunctionType >(Values(1, value), "channel");
} else
return std::make_shared< FlatTopFunctionType >(std::get< 0 >(value),
std::get< 1 >(value),
channel_boundary_layer,
std::get< 2 >(value),
"channel");
} // ... create_indicator(...)
}; // class Model1< ..., 2, ... 1 >
} // namespace Spe10
} // namespace Problems
} // namespace LinearElliptic
} // namespace HDD
} // namespace Dune
#endif // DUNE_HDD_LINEARELLIPTIC_PROBLEMS_SPE10_HH
<commit_msg>fixes typo in cff4add1e40765534dcd25ff8169a12cfde0125b<commit_after>// This file is part of the dune-hdd project:
// http://users.dune-project.org/projects/dune-hdd
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef DUNE_HDD_LINEARELLIPTIC_PROBLEMS_SPE10_HH
#define DUNE_HDD_LINEARELLIPTIC_PROBLEMS_SPE10_HH
#include <memory>
#include <vector>
#include <utility>
#include <sstream>
#include <dune/common/fmatrix.hh>
#include <dune/stuff/common/memory.hh>
#include <dune/stuff/common/fvector.hh>
#include <dune/stuff/common/float_cmp.hh>
#include <dune/stuff/common/type_utils.hh>
#include <dune/stuff/functions/constant.hh>
#include <dune/stuff/functions/combined.hh>
#include <dune/stuff/functions/flattop.hh>
#include <dune/stuff/functions/spe10.hh>
#include <dune/stuff/playground/functions/indicator.hh>
#include <dune/pymor/functions/default.hh>
#include "default.hh"
namespace Dune {
namespace HDD {
namespace LinearElliptic {
namespace Problems {
namespace Spe10 {
template< class E, class D, int d, class R, int r = 1 >
class Model1
: public ProblemInterface< E, D, d, R, r >
{
Model1() { static_assert(AlwaysFalse< E >::value, "Not available for these dimensions!"); }
};
template< class E, class D, class R >
class Model1< E, D, 2, R, 1 >
: public Problems::Default< E, D, 2, R, 1 >
{
typedef Problems::Default< E, D, 2, R, 1 > BaseType;
typedef Model1< E, D, 2, R, 1 > ThisType;
typedef Stuff::Functions::Constant< E, D, 2, R, 1 > ConstantFunctionType;
typedef Stuff::Functions::FlatTop< E, D, 2, R, 1 > FlatTopFunctionType;
typedef Stuff::Functions::Indicator< E, D, 2, R, 1 > IndicatorFunctionType;
typedef Stuff::Functions::Spe10::Model1< E, D, 2, R, 2, 2 > Spe10FunctionType;
public:
typedef typename BaseType::EntityType EntityType;
typedef typename BaseType::DomainFieldType DomainFieldType;
static const unsigned int dimDomain = BaseType::dimDomain;
typedef typename BaseType::DomainType DomainType;
typedef typename BaseType::RangeFieldType RangeFieldType;
static const unsigned int dimRange = BaseType::dimRange;
static const bool available = true;
static std::string static_id()
{
return BaseType::BaseType::static_id() + ".spe10.model1";
}
static Stuff::Common::Configuration default_config(const std::string sub_name = "")
{
std::istringstream ss("# a definition of a channel would be analogue to the one of forces\n"
"forces.0.domain = [0.95 1.10; 0.30 0.45]\n"
"forces.0.value = 2000\n"
"forces.1.domain = [3.00 3.15; 0.75 0.90]\n"
"forces.1.value = -1000\n"
"forces.2.domain = [4.25 4.40; 0.25 0.40]\n"
"forces.2.value = -1000");
Stuff::Common::Configuration config(ss);
config["filename"] = Stuff::Functions::Spe10::internal::model1_filename;
config["lower_left"] = "[0.0 0.0]";
config["upper_right"] = "[5.0 1.0]";
config["parametric_channel"] = "false";
config.set("channel_boundary_layer", FlatTopFunctionType::default_config().template get< std::string >("boundary_layer"));
if (sub_name.empty())
return config;
else {
Stuff::Common::Configuration tmp;
tmp.add(config, sub_name);
return tmp;
}
} // ... default_config(...)
static std::unique_ptr< ThisType > create(const Stuff::Common::Configuration config = default_config(),
const std::string sub_name = static_id())
{
const Stuff::Common::Configuration cfg = config.has_sub(sub_name) ? config.sub(sub_name) : config;
const Stuff::Common::Configuration def_cfg = default_config();
return Stuff::Common::make_unique< ThisType >(
cfg.get("filename", def_cfg.get< std::string >("filename")),
cfg.get("lower_left", def_cfg.get< DomainType >("lower_left")),
cfg.get("upper_right", def_cfg.get< DomainType >("upper_right")),
get_values(cfg, "channel"),
get_values(cfg, "forces"),
cfg.get("channel_boundary_layer", def_cfg.get< DomainType >("channel_boundary_layer")),
cfg.get("parametric_channel", def_cfg.get< bool >("parametric_channel")));
} // ... create(...)
Model1(const std::string filename,
const DomainType& lower_left,
const DomainType& upper_right,
const std::vector< std::tuple< DomainType, DomainType, RangeFieldType > >& channel_values,
const std::vector< std::tuple< DomainType, DomainType, RangeFieldType > >& force_values,
const DomainType& channel_boundary_layer = default_config().get< DomainType >("channel_boundary_layer"),
const bool parametric_channel = default_config().get< bool >("parametric_channel"))
: BaseType(create_base(filename,
lower_left,
upper_right,
channel_values,
force_values,
channel_boundary_layer,
parametric_channel))
{}
private:
typedef std::vector< std::tuple< DomainType, DomainType, RangeFieldType > > Values;
typedef typename BaseType::DiffusionFactorType::NonparametricType FlatTopIndicatorType;
static BaseType create_base(const std::string filename,
const DomainType& lower_left,
const DomainType& upper_right,
const Values& channel_values,
const Values& force_values,
const DomainType& channel_boundary_layer,
const bool parametric_channel)
{
// build the channel as a sum of flattop functions
std::shared_ptr< FlatTopIndicatorType > channel(nullptr);
if (channel_values.empty())
channel = std::make_shared< ConstantFunctionType >(0, "zero");
else
channel = create_indicator(channel_values[0], channel_boundary_layer);
for (size_t ii = 1; ii < channel_values.size(); ++ii)
channel = Stuff::Functions::make_sum(channel,
create_indicator(channel_values[ii], channel_boundary_layer),
"channel");
// build the rest
auto one = std::make_shared< ConstantFunctionType >(1, "one");
auto diffusion_tensor = std::make_shared< Spe10FunctionType >(filename,
lower_left,
upper_right,
Stuff::Functions::Spe10::internal::model1_min_value,
Stuff::Functions::Spe10::internal::model1_max_value,
"diffusion_tensor");
auto force = std::make_shared< IndicatorFunctionType >(force_values, "force");
auto dirichlet = std::make_shared< ConstantFunctionType >(0, "dirichlet");
auto neumann = std::make_shared< ConstantFunctionType >(0, "neumann");
if (parametric_channel) {
typedef Pymor::Functions::NonparametricDefault< E, D, 2, R, 1 > ScalarWrapper;
typedef Pymor::Functions::NonparametricDefault< E, D, 2, R, 2, 2 > MatrixWrapper;
typedef Pymor::Functions::AffinelyDecomposableDefault< E, D, 2, R, 1 > ParametricFunctionType;
auto diffusion_factor = std::make_shared< ParametricFunctionType >("diffusion_factor");
auto minus_one = std::make_shared< ConstantFunctionType >(-1, "minus_one");
diffusion_factor->register_affine_part(Stuff::Functions::make_sum(one, channel));
diffusion_factor->register_component(Stuff::Functions::make_product(minus_one, channel),
new Pymor::ParameterFunctional("mu", 1, "mu[0]"));
return BaseType(diffusion_factor,
std::make_shared< MatrixWrapper >(diffusion_tensor),
std::make_shared< ScalarWrapper >(force),
std::make_shared< ScalarWrapper >(dirichlet),
std::make_shared< ScalarWrapper >(neumann));
} else {
auto zero_pt_nine = std::make_shared< ConstantFunctionType >(0.9, "0.9");
return BaseType(Stuff::Functions::make_sum(one,
Stuff::Functions::make_product(zero_pt_nine,
channel,
"scaled_channel"),
"diffusion_factor"),
diffusion_tensor,
force,
dirichlet,
neumann);
}
} // ... create_base(...)
static Values get_values(const Stuff::Common::Configuration& cfg, const std::string id)
{
Values values;
DomainType tmp_lower;
DomainType tmp_upper;
if (cfg.has_sub(id)) {
const Stuff::Common::Configuration sub_cfg = cfg.sub(id);
size_t cc = 0;
while (sub_cfg.has_sub(DSC::toString(cc))) {
const Stuff::Common::Configuration local_cfg = sub_cfg.sub(DSC::toString(cc));
if (local_cfg.has_key("domain") && local_cfg.has_key("value")) {
auto domains = local_cfg.get< FieldMatrix< DomainFieldType, 2, 2 > >("domain");
tmp_lower[0] = domains[0][0];
tmp_lower[1] = domains[1][0];
tmp_upper[0] = domains[0][1];
tmp_upper[1] = domains[1][1];
auto val = local_cfg.get< RangeFieldType >("value");
values.emplace_back(tmp_lower, tmp_upper, val);
} else
break;
++cc;
}
}
return values;
} // ... get_values(...)
static std::shared_ptr< FlatTopIndicatorType > create_indicator(const typename Values::value_type& value,
const DomainType& channel_boundary_layer)
{
if (Stuff::Common::FloatCmp::eq(channel_boundary_layer, DomainType(0))) {
return std::make_shared< IndicatorFunctionType >(Values(1, value), "channel");
} else
return std::make_shared< FlatTopFunctionType >(std::get< 0 >(value),
std::get< 1 >(value),
channel_boundary_layer,
std::get< 2 >(value),
"channel");
} // ... create_indicator(...)
}; // class Model1< ..., 2, ... 1 >
} // namespace Spe10
} // namespace Problems
} // namespace LinearElliptic
} // namespace HDD
} // namespace Dune
#endif // DUNE_HDD_LINEARELLIPTIC_PROBLEMS_SPE10_HH
<|endoftext|> |
<commit_before>// Created on: 2012-07-18
// Created by: Kirill GAVRILOV
// Copyright (c) 2012 OPEN CASCADE SAS
//
// The content of this file is subject to the Open CASCADE Technology Public
// License Version 6.5 (the "License"). You may not use the content of this file
// except in compliance with the License. Please obtain a copy of the License
// at http://www.opencascade.org and read it completely before using this file.
//
// The Initial Developer of the Original Code is Open CASCADE S.A.S., having its
// main offices at: 1, place des Freres Montgolfier, 78280 Guyancourt, France.
//
// The Original Code and all software distributed under the License is
// distributed on an "AS IS" basis, without warranty of any kind, and the
// Initial Developer hereby disclaims all such warranties, including without
// limitation, any warranties of merchantability, fitness for a particular
// purpose or non-infringement. Please see the License for the specific terms
// and conditions governing the rights and limitations under the License.
#include <Image_PixMap.hxx>
#ifdef _MSC_VER
//
#elif (defined(__GNUC__) && __GNUC__ >= 4 && __GNUC_MINOR__ >= 1)
#include <mm_malloc.h>
#else
extern "C" int posix_memalign (void** thePtr, size_t theAlign, size_t theBytesCount);
#endif
template<typename TypePtr>
inline TypePtr MemAllocAligned (const Standard_Size& theBytesCount,
const Standard_Size& theAlign = 16)
{
#if defined(_MSC_VER)
return (TypePtr )_aligned_malloc (theBytesCount, theAlign);
#elif (defined(__GNUC__) && __GNUC__ >= 4 && __GNUC_MINOR__ >= 1)
return (TypePtr ) _mm_malloc (theBytesCount, theAlign);
#else
void* aPtr;
if (posix_memalign (&aPtr, theAlign, theBytesCount))
{
aPtr = NULL;
}
return (TypePtr )aPtr;
#endif
}
inline void MemFreeAligned (void* thePtrAligned)
{
#if defined(_MSC_VER)
_aligned_free (thePtrAligned);
#elif (defined(__GNUC__) && __GNUC__ >= 4 && __GNUC_MINOR__ >= 1)
_mm_free (thePtrAligned);
#else
free (thePtrAligned);
#endif
}
IMPLEMENT_STANDARD_HANDLE (Image_PixMap, Standard_Transient)
IMPLEMENT_STANDARD_RTTIEXT(Image_PixMap, Standard_Transient)
// =======================================================================
// function : Image_PixMap
// purpose :
// =======================================================================
Image_PixMap::Image_PixMap()
: myImgFormat (Image_PixMap::ImgGray),
myIsOwnPointer (true)
{
memset (&myData, 0, sizeof(myData));
myData.mySizeBPP = 1;
myData.myTopToDown = 1;
setFormat (Image_PixMap::ImgGray);
}
// =======================================================================
// function : ~Image_PixMap
// purpose :
// =======================================================================
Image_PixMap::~Image_PixMap()
{
Clear();
}
Standard_Size Image_PixMap::SizePixelBytes (const Image_PixMap::ImgFormat thePixelFormat)
{
switch (thePixelFormat)
{
case ImgGrayF:
return sizeof(float);
case ImgRGBAF:
case ImgBGRAF:
return sizeof(float) * 4;
case ImgRGBF:
case ImgBGRF:
return sizeof(float) * 3;
case ImgRGBA:
case ImgBGRA:
return 4;
case ImgRGB32:
case ImgBGR32:
return 4;
case ImgRGB:
case ImgBGR:
return 3;
case ImgGray:
default:
return 1;
}
}
// =======================================================================
// function : setFormat
// purpose :
// =======================================================================
void Image_PixMap::setFormat (Image_PixMap::ImgFormat thePixelFormat)
{
myImgFormat = thePixelFormat;
myData.mySizeBPP = SizePixelBytes (myImgFormat);
}
// =======================================================================
// function : setTopDown
// purpose :
// =======================================================================
void Image_PixMap::setTopDown()
{
myData.myTopRowPtr = ((myData.myTopToDown == 1 || myData.myDataPtr == NULL)
? myData.myDataPtr : (myData.myDataPtr + myData.mySizeRowBytes * (myData.mySizeY - 1)));
}
// =======================================================================
// function : InitWrapper
// purpose :
// =======================================================================
bool Image_PixMap::InitWrapper (Image_PixMap::ImgFormat thePixelFormat,
Standard_Byte* theDataPtr,
const Standard_Size theSizeX,
const Standard_Size theSizeY,
const Standard_Size theSizeRowBytes)
{
Clear (thePixelFormat);
if ((theSizeX == 0) || (theSizeY == 0) || (theDataPtr == NULL))
{
return false;
}
myData.mySizeX = theSizeX;
myData.mySizeY = theSizeY;
myData.mySizeRowBytes = (theSizeRowBytes != 0) ? theSizeRowBytes : (theSizeX * myData.mySizeBPP);
myData.myDataPtr = theDataPtr;
myIsOwnPointer = false;
setTopDown();
return true;
}
// =======================================================================
// function : InitTrash
// purpose :
// =======================================================================
bool Image_PixMap::InitTrash (Image_PixMap::ImgFormat thePixelFormat,
const Standard_Size theSizeX,
const Standard_Size theSizeY,
const Standard_Size theSizeRowBytes)
{
Clear (thePixelFormat);
if ((theSizeX == 0) || (theSizeY == 0))
{
return false;
}
myData.mySizeX = theSizeX;
myData.mySizeY = theSizeY;
myData.mySizeRowBytes = myData.mySizeX * myData.mySizeBPP;
if (theSizeRowBytes > myData.mySizeRowBytes)
{
// use argument only if it greater
myData.mySizeRowBytes = theSizeRowBytes;
}
myData.myDataPtr = MemAllocAligned<Standard_Byte*> (SizeBytes());
myIsOwnPointer = true;
setTopDown();
return myData.myDataPtr != NULL;
}
// =======================================================================
// function : InitZero
// purpose :
// =======================================================================
bool Image_PixMap::InitZero (Image_PixMap::ImgFormat thePixelFormat,
const Standard_Size theSizeX,
const Standard_Size theSizeY,
const Standard_Size theSizeRowBytes,
const Standard_Byte theValue)
{
if (!InitTrash (thePixelFormat, theSizeX, theSizeY, theSizeRowBytes))
{
return false;
}
memset (myData.myDataPtr, (int )theValue, SizeBytes());
return true;
}
// =======================================================================
// function : InitCopy
// purpose :
// =======================================================================
bool Image_PixMap::InitCopy (const Image_PixMap& theCopy)
{
if (&theCopy == this)
{
// self-copying disallowed
return false;
}
if (InitTrash (theCopy.myImgFormat, theCopy.myData.mySizeX, theCopy.myData.mySizeY, theCopy.myData.mySizeRowBytes))
{
memcpy (myData.myDataPtr, theCopy.myData.myDataPtr, theCopy.SizeBytes());
return true;
}
return false;
}
// =======================================================================
// function : Clear
// purpose :
// =======================================================================
void Image_PixMap::Clear (Image_PixMap::ImgFormat thePixelFormat)
{
if (myIsOwnPointer && (myData.myDataPtr != NULL))
{
MemFreeAligned (myData.myDataPtr);
}
myData.myDataPtr = myData.myTopRowPtr = NULL;
myIsOwnPointer = true;
myData.mySizeX = myData.mySizeY = myData.mySizeRowBytes = 0;
setFormat (thePixelFormat);
myData.myTopToDown = 1;
}
// =======================================================================
// function : PixelColor
// purpose :
// =======================================================================
Quantity_Color Image_PixMap::PixelColor (const Standard_Integer theX,
const Standard_Integer theY,
Quantity_Parameter& theAlpha) const
{
if (IsEmpty() ||
theX < 0 || (Standard_Size )theX >= myData.mySizeX ||
theY < 0 || (Standard_Size )theY >= myData.mySizeY)
{
theAlpha = 0.0; // transparent
return Quantity_Color (0.0, 0.0, 0.0, Quantity_TOC_RGB);
}
switch (myImgFormat)
{
case ImgGrayF:
{
const Standard_ShortReal& aPixel = Value<Standard_ShortReal> (theY, theX);
theAlpha = 1.0; // opaque
return Quantity_Color (Quantity_Parameter (Standard_Real (aPixel)),
Quantity_Parameter (Standard_Real (aPixel)),
Quantity_Parameter (Standard_Real (aPixel)),
Quantity_TOC_RGB);
break;
}
case ImgRGBAF:
{
const Image_ColorRGBAF& aPixel = Value<Image_ColorRGBAF> (theY, theX);
theAlpha = aPixel.a();
return Quantity_Color (Quantity_Parameter (aPixel.r()),
Quantity_Parameter (aPixel.g()),
Quantity_Parameter (aPixel.b()),
Quantity_TOC_RGB);
}
case ImgBGRAF:
{
const Image_ColorBGRAF& aPixel = Value<Image_ColorBGRAF> (theY, theX);
theAlpha = aPixel.a();
return Quantity_Color (Quantity_Parameter (aPixel.r()),
Quantity_Parameter (aPixel.g()),
Quantity_Parameter (aPixel.b()),
Quantity_TOC_RGB);
}
case ImgRGBF:
{
const Image_ColorRGBF& aPixel = Value<Image_ColorRGBF> (theY, theX);
theAlpha = 1.0; // opaque
return Quantity_Color (Quantity_Parameter (aPixel.r()),
Quantity_Parameter (aPixel.g()),
Quantity_Parameter (aPixel.b()),
Quantity_TOC_RGB);
}
case ImgBGRF:
{
const Image_ColorBGRF& aPixel = Value<Image_ColorBGRF> (theY, theX);
theAlpha = 1.0; // opaque
return Quantity_Color (Quantity_Parameter (aPixel.r()),
Quantity_Parameter (aPixel.g()),
Quantity_Parameter (aPixel.b()),
Quantity_TOC_RGB);
}
case ImgRGBA:
{
const Image_ColorRGBA& aPixel = Value<Image_ColorRGBA> (theY, theX);
theAlpha = Standard_Real (aPixel.a()) / 255.0;
return Quantity_Color (Quantity_Parameter (Standard_Real (aPixel.r()) / 255.0),
Quantity_Parameter (Standard_Real (aPixel.g()) / 255.0),
Quantity_Parameter (Standard_Real (aPixel.b()) / 255.0),
Quantity_TOC_RGB);
}
case ImgBGRA:
{
const Image_ColorBGRA& aPixel = Value<Image_ColorBGRA> (theY, theX);
theAlpha = Standard_Real (aPixel.a()) / 255.0;
return Quantity_Color (Quantity_Parameter (Standard_Real (aPixel.r()) / 255.0),
Quantity_Parameter (Standard_Real (aPixel.g()) / 255.0),
Quantity_Parameter (Standard_Real (aPixel.b()) / 255.0),
Quantity_TOC_RGB);
}
case ImgRGB32:
{
const Image_ColorRGB32& aPixel = Value<Image_ColorRGB32> (theY, theX);
theAlpha = 1.0; // opaque
return Quantity_Color (Quantity_Parameter (Standard_Real (aPixel.r()) / 255.0),
Quantity_Parameter (Standard_Real (aPixel.g()) / 255.0),
Quantity_Parameter (Standard_Real (aPixel.b()) / 255.0),
Quantity_TOC_RGB);
}
case ImgBGR32:
{
const Image_ColorBGR32& aPixel = Value<Image_ColorBGR32> (theY, theX);
theAlpha = 1.0; // opaque
return Quantity_Color (Quantity_Parameter (Standard_Real (aPixel.r()) / 255.0),
Quantity_Parameter (Standard_Real (aPixel.g()) / 255.0),
Quantity_Parameter (Standard_Real (aPixel.b()) / 255.0),
Quantity_TOC_RGB);
}
case ImgRGB:
{
const Image_ColorRGB& aPixel = Value<Image_ColorRGB> (theY, theX);
theAlpha = 1.0; // opaque
return Quantity_Color (Quantity_Parameter (Standard_Real (aPixel.r()) / 255.0),
Quantity_Parameter (Standard_Real (aPixel.g()) / 255.0),
Quantity_Parameter (Standard_Real (aPixel.b()) / 255.0),
Quantity_TOC_RGB);
}
case ImgBGR:
{
const Image_ColorBGR& aPixel = Value<Image_ColorBGR> (theY, theX);
theAlpha = 1.0; // opaque
return Quantity_Color (Quantity_Parameter (Standard_Real (aPixel.r()) / 255.0),
Quantity_Parameter (Standard_Real (aPixel.g()) / 255.0),
Quantity_Parameter (Standard_Real (aPixel.b()) / 255.0),
Quantity_TOC_RGB);
}
case ImgGray:
{
const Standard_Byte& aPixel = Value<Standard_Byte> (theY, theX);
theAlpha = 1.0; // opaque
return Quantity_Color (Quantity_Parameter (Standard_Real (aPixel) / 255.0),
Quantity_Parameter (Standard_Real (aPixel) / 255.0),
Quantity_Parameter (Standard_Real (aPixel) / 255.0),
Quantity_TOC_RGB);
}
default:
{
// not supported image type
theAlpha = 0.0; // transparent
return Quantity_Color (0.0, 0.0, 0.0, Quantity_TOC_RGB);
}
}
}
<commit_msg>No alligned memory alloc under bcc32<commit_after>// Created on: 2012-07-18
// Created by: Kirill GAVRILOV
// Copyright (c) 2012 OPEN CASCADE SAS
//
// The content of this file is subject to the Open CASCADE Technology Public
// License Version 6.5 (the "License"). You may not use the content of this file
// except in compliance with the License. Please obtain a copy of the License
// at http://www.opencascade.org and read it completely before using this file.
//
// The Initial Developer of the Original Code is Open CASCADE S.A.S., having its
// main offices at: 1, place des Freres Montgolfier, 78280 Guyancourt, France.
//
// The Original Code and all software distributed under the License is
// distributed on an "AS IS" basis, without warranty of any kind, and the
// Initial Developer hereby disclaims all such warranties, including without
// limitation, any warranties of merchantability, fitness for a particular
// purpose or non-infringement. Please see the License for the specific terms
// and conditions governing the rights and limitations under the License.
#include <Image_PixMap.hxx>
#ifdef _MSC_VER
//
#elif (defined(__GNUC__) && __GNUC__ >= 4 && __GNUC_MINOR__ >= 1)
#include <mm_malloc.h>
#else
extern "C" int posix_memalign (void** thePtr, size_t theAlign, size_t theBytesCount);
#endif
template<typename TypePtr>
inline TypePtr MemAllocAligned (const Standard_Size& theBytesCount,
const Standard_Size& theAlign = 16)
{
#if defined(_MSC_VER)
return (TypePtr )_aligned_malloc (theBytesCount, theAlign);
#elif (defined(__GNUC__) && __GNUC__ >= 4 && __GNUC_MINOR__ >= 1)
return (TypePtr ) _mm_malloc (theBytesCount, theAlign);
#elif defined(__BORLANDC__)
return (TypePtr ) malloc (theBytesCount);
#else
void* aPtr;
if (posix_memalign (&aPtr, theAlign, theBytesCount))
{
aPtr = NULL;
}
return (TypePtr )aPtr;
#endif
}
inline void MemFreeAligned (void* thePtrAligned)
{
#if defined(_MSC_VER)
_aligned_free (thePtrAligned);
#elif (defined(__GNUC__) && __GNUC__ >= 4 && __GNUC_MINOR__ >= 1)
_mm_free (thePtrAligned);
#else
free (thePtrAligned);
#endif
}
IMPLEMENT_STANDARD_HANDLE (Image_PixMap, Standard_Transient)
IMPLEMENT_STANDARD_RTTIEXT(Image_PixMap, Standard_Transient)
// =======================================================================
// function : Image_PixMap
// purpose :
// =======================================================================
Image_PixMap::Image_PixMap()
: myImgFormat (Image_PixMap::ImgGray),
myIsOwnPointer (true)
{
memset (&myData, 0, sizeof(myData));
myData.mySizeBPP = 1;
myData.myTopToDown = 1;
setFormat (Image_PixMap::ImgGray);
}
// =======================================================================
// function : ~Image_PixMap
// purpose :
// =======================================================================
Image_PixMap::~Image_PixMap()
{
Clear();
}
Standard_Size Image_PixMap::SizePixelBytes (const Image_PixMap::ImgFormat thePixelFormat)
{
switch (thePixelFormat)
{
case ImgGrayF:
return sizeof(float);
case ImgRGBAF:
case ImgBGRAF:
return sizeof(float) * 4;
case ImgRGBF:
case ImgBGRF:
return sizeof(float) * 3;
case ImgRGBA:
case ImgBGRA:
return 4;
case ImgRGB32:
case ImgBGR32:
return 4;
case ImgRGB:
case ImgBGR:
return 3;
case ImgGray:
default:
return 1;
}
}
// =======================================================================
// function : setFormat
// purpose :
// =======================================================================
void Image_PixMap::setFormat (Image_PixMap::ImgFormat thePixelFormat)
{
myImgFormat = thePixelFormat;
myData.mySizeBPP = SizePixelBytes (myImgFormat);
}
// =======================================================================
// function : setTopDown
// purpose :
// =======================================================================
void Image_PixMap::setTopDown()
{
myData.myTopRowPtr = ((myData.myTopToDown == 1 || myData.myDataPtr == NULL)
? myData.myDataPtr : (myData.myDataPtr + myData.mySizeRowBytes * (myData.mySizeY - 1)));
}
// =======================================================================
// function : InitWrapper
// purpose :
// =======================================================================
bool Image_PixMap::InitWrapper (Image_PixMap::ImgFormat thePixelFormat,
Standard_Byte* theDataPtr,
const Standard_Size theSizeX,
const Standard_Size theSizeY,
const Standard_Size theSizeRowBytes)
{
Clear (thePixelFormat);
if ((theSizeX == 0) || (theSizeY == 0) || (theDataPtr == NULL))
{
return false;
}
myData.mySizeX = theSizeX;
myData.mySizeY = theSizeY;
myData.mySizeRowBytes = (theSizeRowBytes != 0) ? theSizeRowBytes : (theSizeX * myData.mySizeBPP);
myData.myDataPtr = theDataPtr;
myIsOwnPointer = false;
setTopDown();
return true;
}
// =======================================================================
// function : InitTrash
// purpose :
// =======================================================================
bool Image_PixMap::InitTrash (Image_PixMap::ImgFormat thePixelFormat,
const Standard_Size theSizeX,
const Standard_Size theSizeY,
const Standard_Size theSizeRowBytes)
{
Clear (thePixelFormat);
if ((theSizeX == 0) || (theSizeY == 0))
{
return false;
}
myData.mySizeX = theSizeX;
myData.mySizeY = theSizeY;
myData.mySizeRowBytes = myData.mySizeX * myData.mySizeBPP;
if (theSizeRowBytes > myData.mySizeRowBytes)
{
// use argument only if it greater
myData.mySizeRowBytes = theSizeRowBytes;
}
myData.myDataPtr = MemAllocAligned<Standard_Byte*> (SizeBytes());
myIsOwnPointer = true;
setTopDown();
return myData.myDataPtr != NULL;
}
// =======================================================================
// function : InitZero
// purpose :
// =======================================================================
bool Image_PixMap::InitZero (Image_PixMap::ImgFormat thePixelFormat,
const Standard_Size theSizeX,
const Standard_Size theSizeY,
const Standard_Size theSizeRowBytes,
const Standard_Byte theValue)
{
if (!InitTrash (thePixelFormat, theSizeX, theSizeY, theSizeRowBytes))
{
return false;
}
memset (myData.myDataPtr, (int )theValue, SizeBytes());
return true;
}
// =======================================================================
// function : InitCopy
// purpose :
// =======================================================================
bool Image_PixMap::InitCopy (const Image_PixMap& theCopy)
{
if (&theCopy == this)
{
// self-copying disallowed
return false;
}
if (InitTrash (theCopy.myImgFormat, theCopy.myData.mySizeX, theCopy.myData.mySizeY, theCopy.myData.mySizeRowBytes))
{
memcpy (myData.myDataPtr, theCopy.myData.myDataPtr, theCopy.SizeBytes());
return true;
}
return false;
}
// =======================================================================
// function : Clear
// purpose :
// =======================================================================
void Image_PixMap::Clear (Image_PixMap::ImgFormat thePixelFormat)
{
if (myIsOwnPointer && (myData.myDataPtr != NULL))
{
MemFreeAligned (myData.myDataPtr);
}
myData.myDataPtr = myData.myTopRowPtr = NULL;
myIsOwnPointer = true;
myData.mySizeX = myData.mySizeY = myData.mySizeRowBytes = 0;
setFormat (thePixelFormat);
myData.myTopToDown = 1;
}
// =======================================================================
// function : PixelColor
// purpose :
// =======================================================================
Quantity_Color Image_PixMap::PixelColor (const Standard_Integer theX,
const Standard_Integer theY,
Quantity_Parameter& theAlpha) const
{
if (IsEmpty() ||
theX < 0 || (Standard_Size )theX >= myData.mySizeX ||
theY < 0 || (Standard_Size )theY >= myData.mySizeY)
{
theAlpha = 0.0; // transparent
return Quantity_Color (0.0, 0.0, 0.0, Quantity_TOC_RGB);
}
switch (myImgFormat)
{
case ImgGrayF:
{
const Standard_ShortReal& aPixel = Value<Standard_ShortReal> (theY, theX);
theAlpha = 1.0; // opaque
return Quantity_Color (Quantity_Parameter (Standard_Real (aPixel)),
Quantity_Parameter (Standard_Real (aPixel)),
Quantity_Parameter (Standard_Real (aPixel)),
Quantity_TOC_RGB);
break;
}
case ImgRGBAF:
{
const Image_ColorRGBAF& aPixel = Value<Image_ColorRGBAF> (theY, theX);
theAlpha = aPixel.a();
return Quantity_Color (Quantity_Parameter (aPixel.r()),
Quantity_Parameter (aPixel.g()),
Quantity_Parameter (aPixel.b()),
Quantity_TOC_RGB);
}
case ImgBGRAF:
{
const Image_ColorBGRAF& aPixel = Value<Image_ColorBGRAF> (theY, theX);
theAlpha = aPixel.a();
return Quantity_Color (Quantity_Parameter (aPixel.r()),
Quantity_Parameter (aPixel.g()),
Quantity_Parameter (aPixel.b()),
Quantity_TOC_RGB);
}
case ImgRGBF:
{
const Image_ColorRGBF& aPixel = Value<Image_ColorRGBF> (theY, theX);
theAlpha = 1.0; // opaque
return Quantity_Color (Quantity_Parameter (aPixel.r()),
Quantity_Parameter (aPixel.g()),
Quantity_Parameter (aPixel.b()),
Quantity_TOC_RGB);
}
case ImgBGRF:
{
const Image_ColorBGRF& aPixel = Value<Image_ColorBGRF> (theY, theX);
theAlpha = 1.0; // opaque
return Quantity_Color (Quantity_Parameter (aPixel.r()),
Quantity_Parameter (aPixel.g()),
Quantity_Parameter (aPixel.b()),
Quantity_TOC_RGB);
}
case ImgRGBA:
{
const Image_ColorRGBA& aPixel = Value<Image_ColorRGBA> (theY, theX);
theAlpha = Standard_Real (aPixel.a()) / 255.0;
return Quantity_Color (Quantity_Parameter (Standard_Real (aPixel.r()) / 255.0),
Quantity_Parameter (Standard_Real (aPixel.g()) / 255.0),
Quantity_Parameter (Standard_Real (aPixel.b()) / 255.0),
Quantity_TOC_RGB);
}
case ImgBGRA:
{
const Image_ColorBGRA& aPixel = Value<Image_ColorBGRA> (theY, theX);
theAlpha = Standard_Real (aPixel.a()) / 255.0;
return Quantity_Color (Quantity_Parameter (Standard_Real (aPixel.r()) / 255.0),
Quantity_Parameter (Standard_Real (aPixel.g()) / 255.0),
Quantity_Parameter (Standard_Real (aPixel.b()) / 255.0),
Quantity_TOC_RGB);
}
case ImgRGB32:
{
const Image_ColorRGB32& aPixel = Value<Image_ColorRGB32> (theY, theX);
theAlpha = 1.0; // opaque
return Quantity_Color (Quantity_Parameter (Standard_Real (aPixel.r()) / 255.0),
Quantity_Parameter (Standard_Real (aPixel.g()) / 255.0),
Quantity_Parameter (Standard_Real (aPixel.b()) / 255.0),
Quantity_TOC_RGB);
}
case ImgBGR32:
{
const Image_ColorBGR32& aPixel = Value<Image_ColorBGR32> (theY, theX);
theAlpha = 1.0; // opaque
return Quantity_Color (Quantity_Parameter (Standard_Real (aPixel.r()) / 255.0),
Quantity_Parameter (Standard_Real (aPixel.g()) / 255.0),
Quantity_Parameter (Standard_Real (aPixel.b()) / 255.0),
Quantity_TOC_RGB);
}
case ImgRGB:
{
const Image_ColorRGB& aPixel = Value<Image_ColorRGB> (theY, theX);
theAlpha = 1.0; // opaque
return Quantity_Color (Quantity_Parameter (Standard_Real (aPixel.r()) / 255.0),
Quantity_Parameter (Standard_Real (aPixel.g()) / 255.0),
Quantity_Parameter (Standard_Real (aPixel.b()) / 255.0),
Quantity_TOC_RGB);
}
case ImgBGR:
{
const Image_ColorBGR& aPixel = Value<Image_ColorBGR> (theY, theX);
theAlpha = 1.0; // opaque
return Quantity_Color (Quantity_Parameter (Standard_Real (aPixel.r()) / 255.0),
Quantity_Parameter (Standard_Real (aPixel.g()) / 255.0),
Quantity_Parameter (Standard_Real (aPixel.b()) / 255.0),
Quantity_TOC_RGB);
}
case ImgGray:
{
const Standard_Byte& aPixel = Value<Standard_Byte> (theY, theX);
theAlpha = 1.0; // opaque
return Quantity_Color (Quantity_Parameter (Standard_Real (aPixel) / 255.0),
Quantity_Parameter (Standard_Real (aPixel) / 255.0),
Quantity_Parameter (Standard_Real (aPixel) / 255.0),
Quantity_TOC_RGB);
}
default:
{
// not supported image type
theAlpha = 0.0; // transparent
return Quantity_Color (0.0, 0.0, 0.0, Quantity_TOC_RGB);
}
}
}
<|endoftext|> |
<commit_before>// MatDataTable class
#include <iostream>
#include <stdlib.h>
#include <sstream>
#include "MatDataTable.h"
#include "SqliteDb.h"
#include "Env.h"
#include "CycException.h"
using namespace std;
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
MatDataTable::MatDataTable() :
mat_(""),
elem_len_(0)
elem_len_(0),
initialized_(false)
{
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
MatDataTable::MatDataTable(string mat, vector<element_t> elem_vec, map<Elem,
int> elem_index, double ref_disp, double ref_kd, double
ref_sol) :
mat_(mat),
elem_vec_(elem_vec),
elem_index_(elem_index),
ref_disp_(ref_disp),
ref_kd_(ref_kd),
ref_sol_(ref_sol)
{
elem_len_= elem_vec_.size();
initialized_=true;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
MatDataTable::~MatDataTable() {
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
double MatDataTable::K_d(Elem ent){
check_validity(ent);
return data(ent, KD);
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
double MatDataTable::S(Elem ent){
check_validity(ent);
return data(ent, SOL);
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
double MatDataTable::D(Elem ent){
check_validity(ent);
return data(ent, DISP);
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void MatDataTable::check_validity(Elem ent) {
map<Elem, int>::iterator it;
it=elem_index_.find(ent);
if (it==elem_index_.end()){
stringstream err;
err << "Element " << ent << " not valid";
throw CycException(err.str());
}
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
double MatDataTable::data(Elem ent, ChemDataType data) {
double to_ret;
switch( data ){
case DISP :
to_ret = ref(DISP)*rel(ent, DISP);
break;
case KD :
to_ret = ref(KD)*rel(ent, KD);
break;
case SOL :
to_ret = ref(SOL)*rel(ent, SOL);
break;
default :
throw CycException("The ChemDataType provided is not yet supported.");
}
return to_ret;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
double MatDataTable::rel(Elem ent, ChemDataType data) {
double to_ret;
int h = elem_index_[1];
int ind = elem_index_[ent];
switch( data ){
case DISP :
to_ret = elem_vec_[ind].D/elem_vec_[h].D;
break;
case KD :
to_ret = elem_vec_[ind].K_d/elem_vec_[h].K_d;
break;
case SOL :
to_ret = elem_vec_[ind].S/elem_vec_[h].S;
break;
default :
throw CycException("The ChemDataType provided is not yet supported.");
}
return to_ret;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
double MatDataTable::ref(ChemDataType data){
double to_ret;
int h = elem_index_[1];
switch( data ){
case DISP :
(initialized_) ? (to_ret=ref_disp_) : (to_ret=elem_vec_[h].D) ;
break;
case KD :
(initialized_) ? (to_ret=ref_kd_) : (to_ret=elem_vec_[h].K_d) ;
break;
case SOL :
(initialized_) ? (to_ret=ref_sol_) : (to_ret=elem_vec_[h].S) ;
break;
default :
throw CycException("The ChemDataType provided is not yet supported.");
}
return to_ret;
}
<commit_msg>duplicate initializer ... not sure where that came from This is actually worse than it was at work.<commit_after>// MatDataTable class
#include <iostream>
#include <stdlib.h>
#include <sstream>
#include "MatDataTable.h"
#include "SqliteDb.h"
#include "Env.h"
#include "CycException.h"
using namespace std;
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
MatDataTable::MatDataTable() :
mat_(""),
elem_len_(0),
initialized_(false)
{
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
MatDataTable::MatDataTable(string mat, vector<element_t> elem_vec, map<Elem,
int> elem_index, double ref_disp, double ref_kd, double
ref_sol) :
mat_(mat),
elem_vec_(elem_vec),
elem_index_(elem_index),
ref_disp_(ref_disp),
ref_kd_(ref_kd),
ref_sol_(ref_sol)
{
elem_len_= elem_vec_.size();
initialized_=true;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
MatDataTable::~MatDataTable() {
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
double MatDataTable::K_d(Elem ent){
check_validity(ent);
return data(ent, KD);
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
double MatDataTable::S(Elem ent){
check_validity(ent);
return data(ent, SOL);
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
double MatDataTable::D(Elem ent){
check_validity(ent);
return data(ent, DISP);
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void MatDataTable::check_validity(Elem ent) {
map<Elem, int>::iterator it;
it=elem_index_.find(ent);
if (it==elem_index_.end()){
stringstream err;
err << "Element " << ent << " not valid";
throw CycException(err.str());
}
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
double MatDataTable::data(Elem ent, ChemDataType data) {
double to_ret;
switch( data ){
case DISP :
to_ret = ref(DISP)*rel(ent, DISP);
break;
case KD :
to_ret = ref(KD)*rel(ent, KD);
break;
case SOL :
to_ret = ref(SOL)*rel(ent, SOL);
break;
default :
throw CycException("The ChemDataType provided is not yet supported.");
}
return to_ret;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
double MatDataTable::rel(Elem ent, ChemDataType data) {
double to_ret;
int h = elem_index_[1];
int ind = elem_index_[ent];
switch( data ){
case DISP :
to_ret = elem_vec_[ind].D/elem_vec_[h].D;
break;
case KD :
to_ret = elem_vec_[ind].K_d/elem_vec_[h].K_d;
break;
case SOL :
to_ret = elem_vec_[ind].S/elem_vec_[h].S;
break;
default :
throw CycException("The ChemDataType provided is not yet supported.");
}
return to_ret;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
double MatDataTable::ref(ChemDataType data){
double to_ret;
int h = elem_index_[1];
switch( data ){
case DISP :
(initialized_) ? (to_ret=ref_disp_) : (to_ret=elem_vec_[h].D) ;
break;
case KD :
(initialized_) ? (to_ret=ref_kd_) : (to_ret=elem_vec_[h].K_d) ;
break;
case SOL :
(initialized_) ? (to_ret=ref_sol_) : (to_ret=elem_vec_[h].S) ;
break;
default :
throw CycException("The ChemDataType provided is not yet supported.");
}
return to_ret;
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <CL/cl.hpp>
#include <string>
#include <vector>
using namespace std;
int main (int argc, char* argv[])
{
//read input commandline arguments
for (int i = 1; i < argc; ++i)
{
if (std::string(argv[i]) == "-a")
{
//initialise desired accuracy variable according to commandline argument -a
//or if no argument is given, set default value
int accuracy = 90;
}
if (std::string(argv[i]) == "-p")
{
//initialise maximum polygons variable according to commandline argument -p
//or if no argument is given, set default value
int polygons = 50;
}
if (std::string(argv[i]) == "-v")
{
//initialise maximum verices per polygon variable according to commandline argument -v
//or if no argument is given, set default value
int vertices = 6;
}
}
//read specified input image file
//initialise variables
class DNA
{
public:
string genome;
int polygons;
int vertices;
polygon[polygons];
}
class polygon;
{
public:
int x[vertices];
int y[vertices];
int R;
int G;
int B;
int alpha;
}
//initialise opencl device
//get all platforms (drivers)
std::vector<cl::Platform> all_platforms;
cl::Platform::get(&all_platforms);
if(all_platforms.size()==0){
std::cout<<" No platforms found. Check OpenCL installation!\n";
exit(1);
}
cl::Platform default_platform=all_platforms[0];
std::cout << "Using platform: "<<default_platform.getInfo<CL_PLATFORM_NAME>()<<"\n";
//get default device of the default platform
std::vector<cl::Device> all_devices;
default_platform.getDevices(CL_DEVICE_TYPE_ALL, &all_devices);
if(all_devices.size()==0){
std::cout<<" No devices found. Check OpenCL installation!\n";
exit(1);
}
cl::Device default_device=all_devices[0];
std::cout<< "Using device: "<<default_device.getInfo<CL_DEVICE_NAME>()<<"\n";
cl::Context context({default_device});
cl::Program::Sources sources;
//run render loop until desired accuracy is reached
while (leaderaccuracy<accuracy)
{
}
//perform final render, output svg and raster image
saverender(leaderDNA);
}
int computefitnesspercent (DNA, originalimage)
{
//compute what % match DNA is to original image
}
int computefitness (DNA, originalimage)
{
//compute the fitness of input DNA, i.e. how close is it to original image?
//read leader dna
//compare input dna to leader dna to find changed polygons
compareDNA(leaderDNA,DNA);
//create bounding box containing changed polygons
//render leader dna within bounding box
leaderrender = renderDNA(leaderDNA,boundx,boundy);
//render input dna within bounding box
inputrender = renderDNA(DNA,boundx,boundy);
//compare leader and input dna rendered bounding boxes
compareimage(leaderrender,inputrender);
//returns 1 if input dna is fitter than leader dna, else returns 0
}
int compareDNA(DNA0,DNA1)
{
//compare DNA0 to DNA1 to find changed polygons
}
int compareimage(image0,image1)
{
//compare two raster images, return 1 if image1 fitter than image0, else return 0
char *img1data, *img2data, fname[15];
int s, n = 0, y = 0;
sprintf(fname, "photo%d.bmp", p - 1);
cout << "\n" << fname;
ifstream img1(fname, ios::in|ios::binary|ios::ate);
sprintf(fname, "photo%d.bmp", p);
cout << "\n" << fname;
ifstream img2(fname, ios::in|ios::binary|ios::ate);
if (img1.is_open() && img2.is_open())
{
s = (int)img1.tellg();
img1data = new char [s];
img1.seekg (0, ios::beg);
img1.read (img1data, s);
img1.close();
img2data = new char [s];
img2.seekg (0, ios::beg);
img2.read (img2data, s);
img2.close();
}
for(int i=0; i<s; i++)
if (img1data[i]==img2data[i]) y++;
return (y);
}
int renderDNA (shape_t * DNA, cairo_t * cr)
{
//render input DNA to a raster image and svg
//render to raster image
cairo_set_source_rgb(cr, 1, 1, 1);
cairo_rectangle(cr, 0, 0, WIDTH, HEIGHT);
cairo_fill(cr);
for(int i = 0; i < NUM_SHAPES; i++)
draw_shape(dna, cr, i);
//render to svg
}
void draw_shape(shape_t * dna, cairo_t * cr, int i)
{
//draw an individual shape within a DNA strand
cairo_set_line_width(cr, 0);
shape_t * shape = &dna[i];
cairo_set_source_rgba(cr, shape->r, shape->g, shape->b, shape->a);
cairo_move_to(cr, shape->points[0].x, shape->points[0].y);
for(int j = 1; j < NUM_POINTS; j++)
cairo_line_to(cr, shape->points[j].x, shape->points[j].y);
cairo_fill(cr);
}
}
int mutateDNA (DNA,mutationtype)
{
//mutate input DNA randomly according to mutation type
mutated_shape = RANDINT(NUM_SHAPES);
double roulette = RANDDOUBLE(2.8);
double drastic = RANDDOUBLE(2);
// mutate color
if(roulette<1)
{
if(dna_test[mutated_shape].a < 0.01 // completely transparent shapes are stupid
|| roulette<0.25)
{
if(drastic < 1)
{
dna_test[mutated_shape].a += RANDDOUBLE(0.1);
dna_test[mutated_shape].a = CLAMP(dna_test[mutated_shape].a, 0.0, 1.0);
}
else
dna_test[mutated_shape].a = RANDDOUBLE(1.0);
}
else if(roulette<0.50)
{
if(drastic < 1)
{
dna_test[mutated_shape].r += RANDDOUBLE(0.1);
dna_test[mutated_shape].r = CLAMP(dna_test[mutated_shape].r, 0.0, 1.0);
}
else
dna_test[mutated_shape].r = RANDDOUBLE(1.0);
}
else if(roulette<0.75)
{
if(drastic < 1)
{
dna_test[mutated_shape].g += RANDDOUBLE(0.1);
dna_test[mutated_shape].g = CLAMP(dna_test[mutated_shape].g, 0.0, 1.0);
}
else
dna_test[mutated_shape].g = RANDDOUBLE(1.0);
}
else
{
if(drastic < 1)
{
dna_test[mutated_shape].b += RANDDOUBLE(0.1);
dna_test[mutated_shape].b = CLAMP(dna_test[mutated_shape].b, 0.0, 1.0);
}
else
dna_test[mutated_shape].b = RANDDOUBLE(1.0);
}
}
// mutate shape
else if(roulette < 2.0)
{
int point_i = RANDINT(NUM_POINTS);
if(roulette<1.5)
{
if(drastic < 1)
{
dna_test[mutated_shape].points[point_i].x += (int)RANDDOUBLE(WIDTH/10.0);
dna_test[mutated_shape].points[point_i].x = CLAMP(dna_test[mutated_shape].points[point_i].x, 0, WIDTH-1);
}
else
dna_test[mutated_shape].points[point_i].x = RANDDOUBLE(WIDTH);
}
else
{
if(drastic < 1)
{
dna_test[mutated_shape].points[point_i].y += (int)RANDDOUBLE(HEIGHT/10.0);
dna_test[mutated_shape].points[point_i].y = CLAMP(dna_test[mutated_shape].points[point_i].y, 0, HEIGHT-1);
}
else
dna_test[mutated_shape].points[point_i].y = RANDDOUBLE(HEIGHT);
}
}
// mutate stacking
else
{
int destination = RANDINT(NUM_SHAPES);
shape_t s = dna_test[mutated_shape];
dna_test[mutated_shape] = dna_test[destination];
dna_test[destination] = s;
return destination;
}
return -1;
}
}
int saveDNA(DNA)
{
int result;
while(1)
{
// start by writing a temp file.
pFile = fopen ("volution.dna.temp","w");
fprintf (pFile, DNA);
fclose (pFile);
// Then rename the real backup to a secondary backup.
result = rename("volution.dna","volution_2.dna");
// Then rename the temp file to the primary backup
result = rename("volution.dna.temp","volution.dna");
// Then delete the temp file
result = remove("volution.dna.temp");
//sleep for 30 seconds.
sleep(30000);
}
}
int saverender(DNA)
{
//render DNA and save resulting image to disk as .svg file and raster image (.png)
//render image from DNA
renderDNA(DNA);
//save resultant image to disk as svg and png files
}
<commit_msg>work on main loop<commit_after>#include <iostream>
#include <CL/cl.hpp>
#include <string>
#include <vector>
using namespace std;
int main (int argc, char* argv[])
{
//read input commandline arguments
for (int i = 1; i < argc; ++i)
{
if (std::string(argv[i]) == "-a")
{
//initialise desired accuracy variable according to commandline argument -a
//or if no argument is given, set default value
int accuracy = 90;
}
if (std::string(argv[i]) == "-p")
{
//initialise maximum polygons variable according to commandline argument -p
//or if no argument is given, set default value
int polygons = 50;
}
if (std::string(argv[i]) == "-v")
{
//initialise maximum verices per polygon variable according to commandline argument -v
//or if no argument is given, set default value
int vertices = 6;
}
}
//read specified input image file
//initialise variables
class DNA
{
public:
string genome;
int polygons;
int vertices;
polygon[polygons];
}
class polygon;
{
public:
int x[vertices];
int y[vertices];
int R;
int G;
int B;
int alpha;
}
//initialise opencl device
//get all platforms (drivers)
std::vector<cl::Platform> all_platforms;
cl::Platform::get(&all_platforms);
if(all_platforms.size()==0){
std::cout<<" No platforms found. Check OpenCL installation!\n";
exit(1);
}
cl::Platform default_platform=all_platforms[0];
std::cout << "Using platform: "<<default_platform.getInfo<CL_PLATFORM_NAME>()<<"\n";
//get default device of the default platform
std::vector<cl::Device> all_devices;
default_platform.getDevices(CL_DEVICE_TYPE_ALL, &all_devices);
if(all_devices.size()==0){
std::cout<<" No devices found. Check OpenCL installation!\n";
exit(1);
}
cl::Device default_device=all_devices[0];
std::cout<< "Using device: "<<default_device.getInfo<CL_DEVICE_NAME>()<<"\n";
cl::Context context({default_device});
cl::Program::Sources sources;
//initialise DNA with a random seed
leaderDNA = seedDNA();
//run render loop until desired accuracy is reached
while (leaderaccuracy<accuracy)
{
//mutate from the leaderDNA
mutatedDNA = mutateDNA(leaderDNA)
//compute fitness of mutation vs leaderDNA
//check if it is fitter, if so overwrite leaderDNA
if (computefitness() == 1)
{
//overwrite leaderDNA
}
}
//perform final render, output svg and raster image
saverender(leaderDNA);
}
int computefitnesspercent (DNA, originalimage)
{
//compute what % match DNA is to original image
}
int computefitness (DNA, originalimage)
{
//compute the fitness of input DNA, i.e. how close is it to original image?
//read leader dna
//compare input dna to leader dna to find changed polygons
compareDNA(leaderDNA,DNA);
//create bounding box containing changed polygons
//render leader dna within bounding box
leaderrender = renderDNA(leaderDNA,boundx,boundy);
//render input dna within bounding box
inputrender = renderDNA(DNA,boundx,boundy);
//compare leader and input dna rendered bounding boxes
compareimage(leaderrender,inputrender);
//returns 1 if input dna is fitter than leader dna, else returns 0
}
int seedDNA()
{
//create a random seed dna
}
int compareDNA(DNA0,DNA1)
{
//compare DNA0 to DNA1 to find changed polygons
}
int compareimage(image0,image1)
{
//compare two raster images, return 1 if image1 fitter than image0, else return 0
char *img1data, *img2data, fname[15];
int s, n = 0, y = 0;
sprintf(fname, "photo%d.bmp", p - 1);
cout << "\n" << fname;
ifstream img1(fname, ios::in|ios::binary|ios::ate);
sprintf(fname, "photo%d.bmp", p);
cout << "\n" << fname;
ifstream img2(fname, ios::in|ios::binary|ios::ate);
if (img1.is_open() && img2.is_open())
{
s = (int)img1.tellg();
img1data = new char [s];
img1.seekg (0, ios::beg);
img1.read (img1data, s);
img1.close();
img2data = new char [s];
img2.seekg (0, ios::beg);
img2.read (img2data, s);
img2.close();
}
for(int i=0; i<s; i++)
if (img1data[i]==img2data[i]) y++;
return (y);
}
int renderDNA (shape_t * DNA, cairo_t * cr)
{
//render input DNA to a raster image and svg
//render to raster image
cairo_set_source_rgb(cr, 1, 1, 1);
cairo_rectangle(cr, 0, 0, WIDTH, HEIGHT);
cairo_fill(cr);
for(int i = 0; i < NUM_SHAPES; i++)
draw_shape(dna, cr, i);
//render to svg
}
void draw_shape(shape_t * dna, cairo_t * cr, int i)
{
//draw an individual shape within a DNA strand
cairo_set_line_width(cr, 0);
shape_t * shape = &dna[i];
cairo_set_source_rgba(cr, shape->r, shape->g, shape->b, shape->a);
cairo_move_to(cr, shape->points[0].x, shape->points[0].y);
for(int j = 1; j < NUM_POINTS; j++)
cairo_line_to(cr, shape->points[j].x, shape->points[j].y);
cairo_fill(cr);
}
}
int mutateDNA (DNA,mutationtype)
{
//mutate input DNA randomly according to mutation type
mutated_shape = RANDINT(NUM_SHAPES);
double roulette = RANDDOUBLE(2.8);
double drastic = RANDDOUBLE(2);
// mutate color
if(roulette<1)
{
if(dna_test[mutated_shape].a < 0.01 // completely transparent shapes are stupid
|| roulette<0.25)
{
if(drastic < 1)
{
dna_test[mutated_shape].a += RANDDOUBLE(0.1);
dna_test[mutated_shape].a = CLAMP(dna_test[mutated_shape].a, 0.0, 1.0);
}
else
dna_test[mutated_shape].a = RANDDOUBLE(1.0);
}
else if(roulette<0.50)
{
if(drastic < 1)
{
dna_test[mutated_shape].r += RANDDOUBLE(0.1);
dna_test[mutated_shape].r = CLAMP(dna_test[mutated_shape].r, 0.0, 1.0);
}
else
dna_test[mutated_shape].r = RANDDOUBLE(1.0);
}
else if(roulette<0.75)
{
if(drastic < 1)
{
dna_test[mutated_shape].g += RANDDOUBLE(0.1);
dna_test[mutated_shape].g = CLAMP(dna_test[mutated_shape].g, 0.0, 1.0);
}
else
dna_test[mutated_shape].g = RANDDOUBLE(1.0);
}
else
{
if(drastic < 1)
{
dna_test[mutated_shape].b += RANDDOUBLE(0.1);
dna_test[mutated_shape].b = CLAMP(dna_test[mutated_shape].b, 0.0, 1.0);
}
else
dna_test[mutated_shape].b = RANDDOUBLE(1.0);
}
}
// mutate shape
else if(roulette < 2.0)
{
int point_i = RANDINT(NUM_POINTS);
if(roulette<1.5)
{
if(drastic < 1)
{
dna_test[mutated_shape].points[point_i].x += (int)RANDDOUBLE(WIDTH/10.0);
dna_test[mutated_shape].points[point_i].x = CLAMP(dna_test[mutated_shape].points[point_i].x, 0, WIDTH-1);
}
else
dna_test[mutated_shape].points[point_i].x = RANDDOUBLE(WIDTH);
}
else
{
if(drastic < 1)
{
dna_test[mutated_shape].points[point_i].y += (int)RANDDOUBLE(HEIGHT/10.0);
dna_test[mutated_shape].points[point_i].y = CLAMP(dna_test[mutated_shape].points[point_i].y, 0, HEIGHT-1);
}
else
dna_test[mutated_shape].points[point_i].y = RANDDOUBLE(HEIGHT);
}
}
// mutate stacking
else
{
int destination = RANDINT(NUM_SHAPES);
shape_t s = dna_test[mutated_shape];
dna_test[mutated_shape] = dna_test[destination];
dna_test[destination] = s;
return destination;
}
return -1;
}
}
int saveDNA(DNA)
{
int result;
while(1)
{
// start by writing a temp file.
pFile = fopen ("volution.dna.temp","w");
fprintf (pFile, DNA);
fclose (pFile);
// Then rename the real backup to a secondary backup.
result = rename("volution.dna","volution_2.dna");
// Then rename the temp file to the primary backup
result = rename("volution.dna.temp","volution.dna");
// Then delete the temp file
result = remove("volution.dna.temp");
//sleep for 30 seconds.
sleep(30000);
}
}
int saverender(DNA)
{
//render DNA and save resulting image to disk as .svg file and raster image (.png)
//render image from DNA
renderDNA(DNA);
//save resultant image to disk as svg and png files
}
<|endoftext|> |
<commit_before>/*
* opencog/atoms/core/PutLink.cc
*
* Copyright (C) 2015 Linas Vepstas
* All Rights Reserved
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License v3 as
* published by the Free Software Foundation and including the exceptions
* at http://opencog.org/wiki/Licenses
*
* This program 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 General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program; if not, write to:
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include <opencog/atoms/base/atom_types.h>
#include <opencog/atoms/base/ClassServer.h>
#include "DefineLink.h"
#include "FreeLink.h"
#include "LambdaLink.h"
#include "PutLink.h"
using namespace opencog;
PutLink::PutLink(const HandleSeq& oset, Type t)
: RewriteLink(oset, t)
{
init();
}
PutLink::PutLink(const Link& l)
: RewriteLink(l)
{
init();
}
/* ================================================================= */
/// PutLink expects a very strict format: an arity-2 link, with
/// the first part being a pattern, and the second a list or set
/// of values. If the pattern has N variables, then the seccond
/// part must have N values. Furthermore, any type restrictions on
/// the variables must be satisfied by the values.
///
/// The following formats are understood:
///
/// PutLink
/// <pattern with 1 variable>
/// <any single atom>
///
/// PutLink
/// <pattern with N variables>
/// ListLink ;; must have arity N
/// <atom 1>
/// ...
/// <atom N>
///
/// The below is a handy-dandy easy-to-use form. When it is reduced,
/// it will result in the creation of a set of reduced forms, not
/// just one (the two sets haveing the same arity). Unfortunately,
/// this trick cannot work for N=1 unless the variable is cosntrained
/// to not be a set.
///
/// PutLink
/// <pattern with N variables>
/// SetLink ;; Must hold a set of ListLinks
/// ListLink ;; must have arity N
/// <atom 1>
/// ...
/// <atom N>
///
void PutLink::init(void)
{
if (not classserver().isA(get_type(), PUT_LINK))
throw InvalidParamException(TRACE_INFO, "Expecting a PutLink");
size_t sz = _outgoing.size();
if (2 != sz and 3 != sz)
throw InvalidParamException(TRACE_INFO,
"Expecting an outgoing set size of two or three, got %d; %s",
sz, to_string().c_str());
ScopeLink::extract_variables(_outgoing);
if (2 == sz)
{
// If the body is just a single variable, and there are no
// type declarations for it, then ScopeLink gets confused.
_vardecl = Handle::UNDEFINED;
_body = _outgoing[0];
_values = _outgoing[1];
}
else
_values = _outgoing[2];
static_typecheck_values();
}
/// Check that the values in the PutLink obey the type constraints.
/// This only performs "static" typechecking, at construction-time;
/// since the values may be dynamically obtained at run-time, we cannot
/// check these here.
void PutLink::static_typecheck_values(void)
{
// Cannot typecheck at this pont in time, because the schema
// might not be defined yet...
Type btype = _body->get_type();
if (DEFINED_SCHEMA_NODE == btype)
return;
if (DEFINED_PREDICATE_NODE == btype)
return;
// If its part of a signature, there is nothing to do.
if (classserver().isA(btype, TYPE_NODE) or TYPE_CHOICE == btype)
return;
size_t sz = _varlist.varseq.size();
Handle valley = _values;
Type vtype = valley->get_type();
// If its a LambdaLink, try to see if its eta-reducible. If
// so, then eta-reduce it immediately. A LambdaLink is
// eta-reducible when it's body is a ListLink.
if (LAMBDA_LINK == vtype)
{
LambdaLinkPtr lam(LambdaLinkCast(_values));
Handle body = lam->get_body();
Type bt = body->get_type();
if (LIST_LINK == bt)
{
valley = body;
vtype = bt;
}
}
if (1 == sz)
{
if (not _varlist.is_type(valley)
and SET_LINK != vtype
and PUT_LINK != vtype
and not (classserver().isA(vtype, SATISFYING_LINK)))
{
throw InvalidParamException(TRACE_INFO,
"PutLink mismatched type!");
}
return;
}
// Cannot typecheck naked FunctionLinks. For example:
// (cog-execute! (Put (Plus) (List (Number 2) (Number 2))))
if (0 == sz and classserver().isA(btype, FUNCTION_LINK))
return;
// The standard, default case is to get a ListLink as an argument.
if (LIST_LINK == vtype)
{
if (not _varlist.is_type(valley->getOutgoingSet()))
{
if (_vardecl)
throw SyntaxException(TRACE_INFO,
"PutLink has mismatched value list! vardecl=%s\nvals=%s",
_vardecl->to_string().c_str(),
_values->to_string().c_str());
else
throw SyntaxException(TRACE_INFO,
"PutLink has mismatched value list! body=%s\nvals=%s",
_body->to_string().c_str(),
_values->to_string().c_str());
}
return;
}
// GetLinks (and the like) are evaluated dynamically, later.
if (classserver().isA(vtype, SATISFYING_LINK))
return;
// If its part of a signature, there is nothing to do.
if (TYPE_NODE == vtype or TYPE_CHOICE == vtype)
return;
// The only remaining possibility is that there is set of ListLinks.
if (SET_LINK != vtype)
throw InvalidParamException(TRACE_INFO,
"PutLink was expecting a ListLink, SetLink or GetLink!");
if (1 < sz)
{
for (const Handle& h : valley->getOutgoingSet())
{
// If the arity is greater than one, then the values must be in a list.
if (h->get_type() != LIST_LINK)
throw InvalidParamException(TRACE_INFO,
"PutLink expected value list!");
if (not _varlist.is_type(h->getOutgoingSet()))
throw InvalidParamException(TRACE_INFO,
"PutLink bad value list!");
}
return;
}
// If the arity is one, the values must obey type constraint.
for (const Handle& h : valley->getOutgoingSet())
{
if (not _varlist.is_type(h))
throw InvalidParamException(TRACE_INFO,
"PutLink bad type!");
}
}
/* ================================================================= */
static inline Handle reddy(RewriteLinkPtr subs, const HandleSeq& oset)
{
subs->make_silent(true);
return subs->beta_reduce(oset);
}
/**
* Perform the actual beta reduction --
*
* Substitute values for the variables in the pattern tree.
* This is a lot like applying the function fun to the argument list
* args, except that no actual evaluation is performed; only
* substitution. The resulting tree is NOT placed into any atomspace,
* either. If you want that, you must do it youself. If you want
* evaluation or execution to happen during or after sustitution, use
* either the EvaluationLink, the ExecutionOutputLink, or the Instantiator.
*
* So, for example, if this PutLink looks like this:
*
* PutLink
* EvaluationLink
* PredicateNode "is a kind of"
* ListLink
* VariableNode $a
* ConceptNode "hot patootie"
* ConceptNode "cowpie"
*
* then the reduced value will be
*
* EvaluationLink
* PredicateNode "is a kind of"
* ListLink
* ConceptNode "cowpie"
* ConceptNode "hot patootie"
*
* Type checking is performed during substitution; if the values fail to
* have the desired types, no substitution is performed. In this case,
* an undefined handle is returned. For set substitutions, this acts as
* a filter, removing (filtering out) the mismatched types.
*
* Again, only a substitution is performed, there is no execution or
* evaluation. Note also that the resulting tree is NOT placed into
* any atomspace!
*/
Handle PutLink::do_reduce(void) const
{
Handle bods(_body);
Variables vars(_varlist);
RewriteLinkPtr subs(RewriteLinkCast(get_handle()));
// Resolve the body, if needed. That is, if the body is
// given in a defintion, get that defintion.
Type btype = _body->get_type();
if (DEFINED_SCHEMA_NODE == btype or
DEFINED_PREDICATE_NODE == btype)
{
bods = DefineLink::get_definition(bods);
btype = bods->get_type();
// XXX TODO we should perform a type-check on the function.
if (not classserver().isA(btype, LAMBDA_LINK))
throw InvalidParamException(TRACE_INFO,
"Expecting a LambdaLink, got %s",
bods->to_string().c_str());
}
// If the body is a lambda, work with that.
if (classserver().isA(btype, LAMBDA_LINK))
{
LambdaLinkPtr lam(LambdaLinkCast(bods));
bods = lam->get_body();
vars = lam->get_variables();
btype = bods->get_type();
subs = lam;
}
// Now get the values that we will plug into the body.
Handle valley = _values;
Type vtype = valley->get_type();
// If the value is a LambdaLink, try to see if its eta-reducible.
// If so, then eta-reduce it immediately. A LambdaLink is
// eta-reducible when it's body is a ListLink.
if (LAMBDA_LINK == vtype)
{
LambdaLinkPtr lam(LambdaLinkCast(_values));
Handle eta = lam->get_body();
Type bt = eta->get_type();
if (LIST_LINK == bt)
{
valley = eta;
vtype = bt;
}
}
size_t nvars = vars.varseq.size();
// FunctionLinks behave like combinators; that is, one can create
// valid beta-redexes with them. We handle that here.
//
// XXX At this time, we don't know the number of arguments any
// given FunctionLink might take. Atomese does have the mechanisms
// to declare these, including arbitrary-arity functions, its
// just that its currently not declared anywhere for any of the
// FunctionLinks. So we just punt. Example usage:
// (cog-execute! (Put (Plus) (List (Number 2) (Number 2))))
// (cog-execute! (Put (Plus (Number 9)) (List (Number 2) (Number 2))))
if (0 == nvars and classserver().isA(btype, FUNCTION_LINK))
{
if (LIST_LINK == vtype)
{
HandleSeq oset(bods->getOutgoingSet());
const HandleSeq& rest = valley->getOutgoingSet();
oset.insert(oset.end(), rest.begin(), rest.end());
return createLink(oset, btype);
}
if (SET_LINK != vtype)
{
HandleSeq oset(bods->getOutgoingSet());
oset.emplace_back(valley);
return createLink(oset, btype);
}
// If the values are given in a set, then iterate over the set...
HandleSeq bset;
for (const Handle& h : valley->getOutgoingSet())
{
if (LIST_LINK == h->get_type())
{
HandleSeq oset(bods->getOutgoingSet());
const HandleSeq& rest = h->getOutgoingSet();
oset.insert(oset.end(), rest.begin(), rest.end());
bset.emplace_back(createLink(oset, btype));
}
else
{
HandleSeq oset(bods->getOutgoingSet());
oset.emplace_back(h);
bset.emplace_back(createLink(oset, btype));
}
}
return createLink(bset, SET_LINK);
}
// If there is only one variable in the PutLink body...
if (1 == nvars)
{
if (SET_LINK != vtype)
{
HandleSeq oset;
oset.emplace_back(valley);
try
{
// return vars.substitute(bods, oset, /* silent */ true);
return reddy(subs, oset);
}
catch (const TypeCheckException& ex)
{
return Handle::UNDEFINED;
}
}
// If the values are given in a set, then iterate over the set...
HandleSeq bset;
for (const Handle& h : valley->getOutgoingSet())
{
HandleSeq oset;
oset.emplace_back(h);
try
{
// bset.emplace_back(vars.substitute(bods, oset, /* silent */ true));
bset.emplace_back(reddy(subs, oset));
}
catch (const TypeCheckException& ex) {}
}
return createLink(bset, SET_LINK);
}
// If we are here, then there are multiple variables in the body.
// See how many values there are. If the values are a ListLink,
// then assume that there is only a single set of values to plug in.
if (LIST_LINK == vtype)
{
const HandleSeq& oset = valley->getOutgoingSet();
try
{
// return vars.substitute(bods, oset, /* silent */ true);
return reddy(subs, oset);
}
catch (const TypeCheckException& ex)
{
return Handle::UNDEFINED;
}
}
// If we are here, then there are multiple values.
// These MUST be given to us as a SetLink.
OC_ASSERT(SET_LINK == vtype,
"Should have caught this earlier, in the ctor");
HandleSeq bset;
for (const Handle& h : valley->getOutgoingSet())
{
const HandleSeq& oset = h->getOutgoingSet();
try
{
// bset.emplace_back(vars.substitute(bods, oset, /* silent */ true));
bset.emplace_back(reddy(subs, oset));
}
catch (const TypeCheckException& ex) {}
}
return createLink(bset, SET_LINK);
}
Handle PutLink::reduce(void)
{
return do_reduce();
}
DEFINE_LINK_FACTORY(PutLink, PUT_LINK)
/* ===================== END OF FILE ===================== */
<commit_msg>Fix wording<commit_after>/*
* opencog/atoms/core/PutLink.cc
*
* Copyright (C) 2015 Linas Vepstas
* All Rights Reserved
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License v3 as
* published by the Free Software Foundation and including the exceptions
* at http://opencog.org/wiki/Licenses
*
* This program 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 General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program; if not, write to:
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include <opencog/atoms/base/atom_types.h>
#include <opencog/atoms/base/ClassServer.h>
#include "DefineLink.h"
#include "FreeLink.h"
#include "LambdaLink.h"
#include "PutLink.h"
using namespace opencog;
PutLink::PutLink(const HandleSeq& oset, Type t)
: RewriteLink(oset, t)
{
init();
}
PutLink::PutLink(const Link& l)
: RewriteLink(l)
{
init();
}
/* ================================================================= */
/// PutLink expects a very strict format: an arity-2 link, with
/// the first part being a pattern, and the second a list or set
/// of values. If the pattern has N variables, then the seccond
/// part must have N values. Furthermore, any type restrictions on
/// the variables must be satisfied by the values.
///
/// The following formats are understood:
///
/// PutLink
/// <pattern with 1 variable>
/// <any single atom>
///
/// PutLink
/// <pattern with N variables>
/// ListLink ;; must have arity N
/// <atom 1>
/// ...
/// <atom N>
///
/// The below is a handy-dandy easy-to-use form. When it is reduced,
/// it will result in the creation of a set of reduced forms, not
/// just one (the two sets haveing the same arity). Unfortunately,
/// this trick cannot work for N=1 unless the variable is cosntrained
/// to not be a set.
///
/// PutLink
/// <pattern with N variables>
/// SetLink ;; Must hold a set of ListLinks
/// ListLink ;; must have arity N
/// <atom 1>
/// ...
/// <atom N>
///
void PutLink::init(void)
{
if (not classserver().isA(get_type(), PUT_LINK))
throw InvalidParamException(TRACE_INFO, "Expecting a PutLink");
size_t sz = _outgoing.size();
if (2 != sz and 3 != sz)
throw InvalidParamException(TRACE_INFO,
"Expecting an outgoing set size of two or three, got %d; %s",
sz, to_string().c_str());
ScopeLink::extract_variables(_outgoing);
if (2 == sz)
{
// If the body is just a single variable, and there are no
// type declarations for it, then ScopeLink gets confused.
_vardecl = Handle::UNDEFINED;
_body = _outgoing[0];
_values = _outgoing[1];
}
else
_values = _outgoing[2];
static_typecheck_values();
}
/// Check that the values in the PutLink obey the type constraints.
/// This only performs "static" typechecking, at construction-time;
/// since the values may be dynamically obtained at run-time, we cannot
/// check these here.
void PutLink::static_typecheck_values(void)
{
// Cannot typecheck at this pont in time, because the schema
// might not be defined yet...
Type btype = _body->get_type();
if (DEFINED_SCHEMA_NODE == btype)
return;
if (DEFINED_PREDICATE_NODE == btype)
return;
// If its part of a signature, there is nothing to do.
if (classserver().isA(btype, TYPE_NODE) or TYPE_CHOICE == btype)
return;
size_t sz = _varlist.varseq.size();
Handle valley = _values;
Type vtype = valley->get_type();
// If its a LambdaLink, try to see if its eta-reducible. If
// so, then eta-reduce it immediately. A LambdaLink is
// eta-reducible when it's body is a ListLink.
if (LAMBDA_LINK == vtype)
{
LambdaLinkPtr lam(LambdaLinkCast(_values));
Handle body = lam->get_body();
Type bt = body->get_type();
if (LIST_LINK == bt)
{
valley = body;
vtype = bt;
}
}
if (1 == sz)
{
if (not _varlist.is_type(valley)
and SET_LINK != vtype
and PUT_LINK != vtype
and not (classserver().isA(vtype, SATISFYING_LINK)))
{
throw InvalidParamException(TRACE_INFO,
"PutLink mismatched type!");
}
return;
}
// Cannot typecheck naked FunctionLinks. For example:
// (cog-execute! (Put (Plus) (List (Number 2) (Number 2))))
if (0 == sz and classserver().isA(btype, FUNCTION_LINK))
return;
// The standard, default case is to get a ListLink as an argument.
if (LIST_LINK == vtype)
{
if (not _varlist.is_type(valley->getOutgoingSet()))
{
if (_vardecl)
throw SyntaxException(TRACE_INFO,
"PutLink has mismatched value list! vardecl=%s\nvals=%s",
_vardecl->to_string().c_str(),
_values->to_string().c_str());
else
throw SyntaxException(TRACE_INFO,
"PutLink has mismatched value list! body=%s\nvals=%s",
_body->to_string().c_str(),
_values->to_string().c_str());
}
return;
}
// GetLinks (and the like) are evaluated dynamically, later.
if (classserver().isA(vtype, SATISFYING_LINK))
return;
// If its part of a signature, there is nothing to do.
if (TYPE_NODE == vtype or TYPE_CHOICE == vtype)
return;
// The only remaining possibility is that there is set of ListLinks.
if (SET_LINK != vtype)
throw InvalidParamException(TRACE_INFO,
"PutLink was expecting a ListLink, SetLink or GetLink!");
if (1 < sz)
{
for (const Handle& h : valley->getOutgoingSet())
{
// If the arity is greater than one, then the values must be in a list.
if (h->get_type() != LIST_LINK)
throw InvalidParamException(TRACE_INFO,
"PutLink expected value list!");
if (not _varlist.is_type(h->getOutgoingSet()))
throw InvalidParamException(TRACE_INFO,
"PutLink bad value list!");
}
return;
}
// If the arity is one, the values must obey type constraint.
for (const Handle& h : valley->getOutgoingSet())
{
if (not _varlist.is_type(h))
throw InvalidParamException(TRACE_INFO,
"PutLink bad type!");
}
}
/* ================================================================= */
static inline Handle reddy(RewriteLinkPtr subs, const HandleSeq& oset)
{
subs->make_silent(true);
return subs->beta_reduce(oset);
}
/**
* Perform the actual beta reduction --
*
* Substitute values for the variables in the pattern tree.
* This is a lot like applying the function fun to the argument list
* args, except that no actual evaluation is performed; only
* substitution. The resulting tree is NOT placed into any atomspace,
* either. If you want that, you must do it youself. If you want
* evaluation or execution to happen during or after sustitution, use
* either the EvaluationLink, the ExecutionOutputLink, or the Instantiator.
*
* So, for example, if this PutLink looks like this:
*
* PutLink
* EvaluationLink
* PredicateNode "is a kind of"
* ListLink
* VariableNode $a
* ConceptNode "hot patootie"
* ConceptNode "cowpie"
*
* then the reduced value will be
*
* EvaluationLink
* PredicateNode "is a kind of"
* ListLink
* ConceptNode "cowpie"
* ConceptNode "hot patootie"
*
* Type checking is performed during substitution; if the values fail to
* have the desired types, no substitution is performed. In this case,
* an undefined handle is returned. For set substitutions, this acts as
* a filter, removing (filtering out) the mismatched types.
*
* Again, only a substitution is performed, there is no execution or
* evaluation. Note also that the resulting tree is NOT placed into
* any atomspace!
*/
Handle PutLink::do_reduce(void) const
{
Handle bods(_body);
Variables vars(_varlist);
RewriteLinkPtr subs(RewriteLinkCast(get_handle()));
// Resolve the body, if needed. That is, if the body is
// given in a defintion, get that defintion.
Type btype = _body->get_type();
if (DEFINED_SCHEMA_NODE == btype or
DEFINED_PREDICATE_NODE == btype)
{
bods = DefineLink::get_definition(bods);
btype = bods->get_type();
// XXX TODO we should perform a type-check on the function.
if (not classserver().isA(btype, LAMBDA_LINK))
throw InvalidParamException(TRACE_INFO,
"Expecting a LambdaLink, got %s",
bods->to_string().c_str());
}
// If the body is a lambda, work with that.
if (classserver().isA(btype, LAMBDA_LINK))
{
LambdaLinkPtr lam(LambdaLinkCast(bods));
bods = lam->get_body();
vars = lam->get_variables();
btype = bods->get_type();
subs = lam;
}
// Now get the values that we will plug into the body.
Handle valley = _values;
Type vtype = valley->get_type();
// If the value is a LambdaLink, try to see if its eta-reducible.
// If so, then eta-reduce it immediately. A LambdaLink is
// eta-reducible when it's body is a ListLink.
if (LAMBDA_LINK == vtype)
{
LambdaLinkPtr lam(LambdaLinkCast(_values));
Handle eta = lam->get_body();
Type bt = eta->get_type();
if (LIST_LINK == bt)
{
valley = eta;
vtype = bt;
}
}
size_t nvars = vars.varseq.size();
// FunctionLinks behave like pointless lambdas; that is, one can
// create valid beta-redexes with them. We handle that here.
//
// XXX At this time, we don't know the number of arguments any
// given FunctionLink might take. Atomese does have the mechanisms
// to declare these, including arbitrary-arity functions, its
// just that its currently not declared anywhere for any of the
// FunctionLinks. So we just punt. Example usage:
// (cog-execute! (Put (Plus) (List (Number 2) (Number 2))))
// (cog-execute! (Put (Plus (Number 9)) (List (Number 2) (Number 2))))
if (0 == nvars and classserver().isA(btype, FUNCTION_LINK))
{
if (LIST_LINK == vtype)
{
HandleSeq oset(bods->getOutgoingSet());
const HandleSeq& rest = valley->getOutgoingSet();
oset.insert(oset.end(), rest.begin(), rest.end());
return createLink(oset, btype);
}
if (SET_LINK != vtype)
{
HandleSeq oset(bods->getOutgoingSet());
oset.emplace_back(valley);
return createLink(oset, btype);
}
// If the values are given in a set, then iterate over the set...
HandleSeq bset;
for (const Handle& h : valley->getOutgoingSet())
{
if (LIST_LINK == h->get_type())
{
HandleSeq oset(bods->getOutgoingSet());
const HandleSeq& rest = h->getOutgoingSet();
oset.insert(oset.end(), rest.begin(), rest.end());
bset.emplace_back(createLink(oset, btype));
}
else
{
HandleSeq oset(bods->getOutgoingSet());
oset.emplace_back(h);
bset.emplace_back(createLink(oset, btype));
}
}
return createLink(bset, SET_LINK);
}
// If there is only one variable in the PutLink body...
if (1 == nvars)
{
if (SET_LINK != vtype)
{
HandleSeq oset;
oset.emplace_back(valley);
try
{
// return vars.substitute(bods, oset, /* silent */ true);
return reddy(subs, oset);
}
catch (const TypeCheckException& ex)
{
return Handle::UNDEFINED;
}
}
// If the values are given in a set, then iterate over the set...
HandleSeq bset;
for (const Handle& h : valley->getOutgoingSet())
{
HandleSeq oset;
oset.emplace_back(h);
try
{
// bset.emplace_back(vars.substitute(bods, oset, /* silent */ true));
bset.emplace_back(reddy(subs, oset));
}
catch (const TypeCheckException& ex) {}
}
return createLink(bset, SET_LINK);
}
// If we are here, then there are multiple variables in the body.
// See how many values there are. If the values are a ListLink,
// then assume that there is only a single set of values to plug in.
if (LIST_LINK == vtype)
{
const HandleSeq& oset = valley->getOutgoingSet();
try
{
// return vars.substitute(bods, oset, /* silent */ true);
return reddy(subs, oset);
}
catch (const TypeCheckException& ex)
{
return Handle::UNDEFINED;
}
}
// If we are here, then there are multiple values.
// These MUST be given to us as a SetLink.
OC_ASSERT(SET_LINK == vtype,
"Should have caught this earlier, in the ctor");
HandleSeq bset;
for (const Handle& h : valley->getOutgoingSet())
{
const HandleSeq& oset = h->getOutgoingSet();
try
{
// bset.emplace_back(vars.substitute(bods, oset, /* silent */ true));
bset.emplace_back(reddy(subs, oset));
}
catch (const TypeCheckException& ex) {}
}
return createLink(bset, SET_LINK);
}
Handle PutLink::reduce(void)
{
return do_reduce();
}
DEFINE_LINK_FACTORY(PutLink, PUT_LINK)
/* ===================== END OF FILE ===================== */
<|endoftext|> |
<commit_before>// AMX profiler for SA-MP server: http://sa-mp.com
//
// Copyright (C) 2011-2012 Sergey Zolotarev
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <functional>
#include <iostream>
#include <tuple>
#include "call_graph.h"
#include "function.h"
#include "function_info.h"
namespace amx_profiler {
CallGraphNode::CallGraphNode(const std::shared_ptr<FunctionInfo> &info,
const std::shared_ptr<CallGraphNode> &caller)
: info_(info)
, caller_(caller)
, std::enable_shared_from_this<CallGraphNode>()
{
}
void CallGraphNode::AddCallee(const std::shared_ptr<FunctionInfo> &fn) {
auto new_node = std::shared_ptr<CallGraphNode>(new CallGraphNode(fn, shared_from_this()));
AddCallee(new_node);
}
void CallGraphNode::AddCallee(const std::shared_ptr<CallGraphNode> &node) {
// Avoid duplicate functions
for (auto iterator = callees_.begin(); iterator != callees_.end(); ++iterator) {
if ((*iterator)->info()->function()->address() == node->info()->function()->address()) {
return;
}
}
callees_.push_back(node);
}
void CallGraphNode::Write(std::ostream &stream) const {
if (!callees_.empty()) {
std::string caller_name;
if (info_) {
caller_name = info_->function()->name();
} else {
caller_name = "Application";
}
for (auto iterator = callees_.begin(); iterator != callees_.end(); ++iterator) {
std::tuple<double, double, double> color;
if (!info_) {
color = std::make_tuple(0.002, 1.000, 1.000);
} else {
auto fn = (*iterator)->info()->function();
if (fn->type() == "native") {
color = std::make_tuple(0.002, 1.000, 1.000);
} else if (fn->type() == "public") {
color = std::make_tuple(0.666, 1.000, 1.000);
} else {
color = std::make_tuple(0.000, 0.000, 0.000);
}
}
stream << '\t' << caller_name << " -> " << (*iterator)->info()->function()->name()
<< " [color=\""
<< std::get<0>(color) << ","
<< std::get<1>(color) << ","
<< std::get<2>(color)
<< "\"];" << std::endl;
(*iterator)->Write(stream);
}
}
}
CallGraph::CallGraph(const std::shared_ptr<CallGraphNode> &root)
: root_(root)
, sentinel_(new CallGraphNode(0))
{
if (!root) {
root_ = sentinel_;
}
}
void CallGraph::Write(std::ostream &stream) const {
stream <<
"digraph prof {\n"
" size=\"6,4\"; ratio = fill;\n"
" node [style=filled];\n"
;
// Write all nodes recrusively
sentinel_->Write(stream);
stream <<
"}\n";
}
} // namespace amx_profiler<commit_msg>CallGraph: Fix public call arrow color<commit_after>// AMX profiler for SA-MP server: http://sa-mp.com
//
// Copyright (C) 2011-2012 Sergey Zolotarev
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <functional>
#include <iostream>
#include <tuple>
#include "call_graph.h"
#include "function.h"
#include "function_info.h"
namespace amx_profiler {
CallGraphNode::CallGraphNode(const std::shared_ptr<FunctionInfo> &info,
const std::shared_ptr<CallGraphNode> &caller)
: info_(info)
, caller_(caller)
, std::enable_shared_from_this<CallGraphNode>()
{
}
void CallGraphNode::AddCallee(const std::shared_ptr<FunctionInfo> &fn) {
auto new_node = std::shared_ptr<CallGraphNode>(new CallGraphNode(fn, shared_from_this()));
AddCallee(new_node);
}
void CallGraphNode::AddCallee(const std::shared_ptr<CallGraphNode> &node) {
// Avoid duplicate functions
for (auto iterator = callees_.begin(); iterator != callees_.end(); ++iterator) {
if ((*iterator)->info()->function()->address() == node->info()->function()->address()) {
return;
}
}
callees_.push_back(node);
}
void CallGraphNode::Write(std::ostream &stream) const {
if (!callees_.empty()) {
std::string caller_name;
if (info_) {
caller_name = info_->function()->name();
} else {
caller_name = "Application";
}
for (auto iterator = callees_.begin(); iterator != callees_.end(); ++iterator) {
std::tuple<double, double, double> color;
auto type = (*iterator)->info()->function()->type();
if (!info_ || type == "public") {
color = std::make_tuple(0.666, 1.000, 1.000);
} else if (type == "native") {
color = std::make_tuple(0.002, 1.000, 1.000);
} else {
color = std::make_tuple(0.000, 0.000, 0.000);
}
stream << '\t' << caller_name << " -> " << (*iterator)->info()->function()->name()
<< " [color=\""
<< std::get<0>(color) << ","
<< std::get<1>(color) << ","
<< std::get<2>(color)
<< "\"];" << std::endl;
(*iterator)->Write(stream);
}
}
}
CallGraph::CallGraph(const std::shared_ptr<CallGraphNode> &root)
: root_(root)
, sentinel_(new CallGraphNode(0))
{
if (!root) {
root_ = sentinel_;
}
}
void CallGraph::Write(std::ostream &stream) const {
stream <<
"digraph prof {\n"
" size=\"6,4\"; ratio = fill;\n"
" node [style=filled];\n"
;
// Write all nodes recrusively
sentinel_->Write(stream);
stream <<
"}\n";
}
} // namespace amx_profiler<|endoftext|> |
<commit_before>/*
* Copyright (C) Sometrik oy 2015
*
*/
#include <string.h>
#include <android/log.h>
#include "Menu.h"
#include <jni.h>
#include <android/asset_manager.h>
#include <android/asset_manager_jni.h>
#include <iostream>
#include <android/bitmap.h>
#include <ContextAndroid.h>
#include <AndroidClient.h>
#include <AndroidPlatform.h>
#include <FWApplication.h>
#include <TouchEvent.h>
#include <CommandEvent.h>
#include <DrawEvent.h>
#include <android_fopen.h>
using namespace std;
extern FWApplication * applicationMain();
bool AndroidPlatform::onTouchesEvent(jobject * _obj, int mode, int fingerIndex, double time, float x, float y) {
x /= getDisplayScale();
y /= getDisplayScale();
switch (mode) {
case 1:
{
TouchEvent ev(getActiveViewId(), TouchEvent::ACTION_DOWN, x, y, time, fingerIndex);
postEvent(ev);
}
break;
case 2:
{
TouchEvent ev(getActiveViewId(), TouchEvent::ACTION_MOVE, x, y, time, fingerIndex);
postEvent(ev);
}
break;
case 3:
{
TouchEvent ev(getActiveViewId(), TouchEvent::ACTION_UP, x, y, time, fingerIndex);
postEvent(ev);
}
break;
}
return true;
}
void AndroidPlatform::onResize(int width, int height) {
__android_log_print(ANDROID_LOG_ERROR, "Sometrik", "resize: %d %d ", width, height);
getApplication().onResize(width / getDisplayScale(), height / getDisplayScale(), width, height);
}
void
AndroidPlatform::menuPressed() {
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "Platform menupressed called");
CommandEvent ce(FW_ID_MENU);
postEvent(ce);
// jclass handlerClass = env->GetObjectClass(handler);
// jmethodID emptyMessageMethod = env->GetMethodID(handlerClass, "sendEmptyMessage", "(I)Z");
// env->CallVoidMethod(handler, emptyMessageMethod, 1);
}
bool AndroidPlatform::onUpdate(double timestamp) {
bool shouldUpdate = getApplication().onUpdate(timestamp);
return shouldUpdate;
}
void
AndroidPlatform::onDraw() {
DrawEvent ev(0);
postEvent(ev);
}
void AndroidPlatform::showCanvas(canvas::ContextAndroid & context) {
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "showCanvas called");
auto env = getJNIEnv();
jclass cls = env->GetObjectClass(framework);
jmethodID methodRef = env->GetMethodID(cls, "setNativeCanvas", "(Landroid/graphics/Bitmap;)V");
env->CallVoidMethod(framework, methodRef, dynamic_cast<canvas::AndroidSurface&>(context.getDefaultSurface()).getBitmap());
}
std::string AndroidPlatform::showTextEntryDialog(const std::string & message) {
return "";
}
void AndroidPlatform::showMessageBox(const std::string & title, const std::string & message) {
}
void
AndroidPlatform::onInit(JNIEnv * env, JavaVM * _gJavaVM) {
// gJavaVM = NULL;
// env->GetJavaVM(&gJavaVM);
gJavaVM = _gJavaVM;
gJavaVM->AttachCurrentThread(&env, NULL);
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "checking gjavavm");
if (gJavaVM == NULL){
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "1");
}
if (_gJavaVM == NULL){
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "2");
}
}
std::string AndroidPlatform::getBundleFilename(const char * filename) {
return filename;
}
std::string AndroidPlatform::getLocalFilename(const char * filename, FileType type) {
auto env = getJNIEnv();
jstring path;
jstring jfilename;
std::string result;
switch (type) {
case DATABASE:
case CACHE_DATABASE:
jfilename = env->NewStringUTF(filename);
path = (jstring) env->CallObjectMethod(framework, env->GetMethodID(env->GetObjectClass(framework), "getDBPath", "(Ljava/lang/String;)Ljava/lang/String;"), jfilename);
result = env->GetStringUTFChars(path, JNI_FALSE);
env->ReleaseStringUTFChars(jfilename, filename);
env->ReleaseStringUTFChars(path, result.c_str());
return result;
case NORMAL:
return "";
}
return "";
}
std::string AndroidPlatform::loadValue(const std::string & key) {
auto env = getJNIEnv();
jstring jkey = env->NewStringUTF(key.c_str());
jstring value = (jstring) env->CallObjectMethod(framework, env->GetMethodID(env->GetObjectClass(framework), "getFromPrefs", "(Ljava/lang/String;)Ljava/lang/String;"), jkey);
std::string result = env->GetStringUTFChars(value, JNI_FALSE);
env->ReleaseStringUTFChars(jkey, key.c_str());
env->ReleaseStringUTFChars(value, result.c_str());
return result;
}
void AndroidPlatform::storeValue(const std::string & key, const std::string & value) {
auto env = getJNIEnv();
jstring jkey = env->NewStringUTF(key.c_str());
jstring jvalue = env->NewStringUTF(value.c_str());
env->CallVoidMethod(framework, env->GetMethodID(env->GetObjectClass(framework), "addToPrefs", "(Ljava/lang/String;Ljava/lang/String;)V"), jkey, jvalue);
env->ReleaseStringUTFChars(jkey, key.c_str());
env->ReleaseStringUTFChars(jvalue, value.c_str());
}
void
AndroidPlatform::sendMessage(const Message & message) {
FWPlatform::sendMessage(message);
auto env = getJNIEnv();
jclass frameworkCls = env->FindClass("com/sometrik/framework/FrameWork");
jclass messageCls = env->FindClass("com/sometrik/framework/NativeMessage");
jmethodID sendMessageMethod = env->GetStaticMethodID(frameworkCls, "sendMessage", "(Lcom/sometrik/framework/FrameWork;Lcom/sometrik/framework/NativeMessage)V");
jmethodID messageConstructor = env->GetMethodID(messageCls, "<init>", "(IIILjava/lang/String;Ljava/lang/String;)V");
int messageTypeId = int(message.getType());
const char * textValue = message.getTextValue().c_str();
const char * textValue2 = message.getTextValue2().c_str();
jstring jtextValue = env->NewStringUTF(textValue);
jstring jtextValue2 = env->NewStringUTF(textValue2);
jobject jmessage = env->NewObject(messageCls, messageConstructor, messageTypeId, message.getElementId(), message.getParentElementId(), jtextValue, jtextValue2);
env->CallVoidMethod(frameworkCls, sendMessageMethod, framework, jmessage);
env->ReleaseStringUTFChars(jtextValue, textValue);
env->ReleaseStringUTFChars(jtextValue2, textValue2);
}
double AndroidPlatform::getTime() const {
auto env = getJNIEnv();
jclass systemClass = env->FindClass("Ljava/lang/System");
double currentTime = (double)env->CallStaticLongMethod(systemClass, env->GetStaticMethodID(systemClass, "currentTimeMillis", "()L"));
env->DeleteLocalRef(systemClass);
return currentTime;
}
int AndroidPlatform::showActionSheet(const FWRect & rect, const FWActionSheet & sheet) {
//Initialize java int and string arrays
auto env = getJNIEnv();
std::vector<FWOption> optionsVector = sheet.getOptions();
jobjectArray stringArray = (jobjectArray) env->NewObjectArray(optionsVector.size(), env->FindClass("java/lang/String"), 0);
jintArray intArray = env->NewIntArray(optionsVector.size());
jint fill[optionsVector.size()];
//Set values to java arrays
for (int i = 0; i < optionsVector.size(); i++) {
const char * text = optionsVector[i].getText().c_str();
jstring jtext = env->NewStringUTF(text);
env->SetObjectArrayElement(stringArray, i, jtext);
fill[i] = optionsVector[i].getId();
env->ReleaseStringUTFChars(jtext, text);
}
env->SetIntArrayRegion(intArray, 0, optionsVector.size(), fill);
//Send values to java to create the action sheet
jclass cls = env->FindClass("com/sometrik/framework/FrameWork");
jmethodID methodRef = env->GetStaticMethodID(cls, "createOptionsFromJNI", "(Lcom/sometrik/framework/FrameWork;I[I[Ljava/lang/String;)V");
env->CallStaticVoidMethod(cls, methodRef, framework, 22, intArray, stringArray);
//Not returning anything
return 0;
}
JNIEnv* AndroidPlatform::getJNIEnv() const {
if (gJavaVM == NULL) {
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "JavaVM is null");
return NULL;
}
JNIEnv *Myenv = NULL;
gJavaVM->GetEnv((void**)&Myenv, JNI_VERSION_1_6);
if (Myenv == NULL){
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "Env is null");
}
return Myenv;
}
std::shared_ptr<AndroidPlatform> platform;
extern "C" {
void Java_com_sometrik_framework_MyGLRenderer_onResize(JNIEnv* env, jobject thiz, float x, float y) {
platform->setDisplayWidth(x);
platform->setDisplayHeight(y);
platform->onResize(x, y);
}
void Java_com_sometrik_framework_FrameWork_menuPressed(JNIEnv* env, jobject thiz) {
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "menu pressed: env = %p", env);
platform->menuPressed();
}
void Java_com_sometrik_framework_FrameWork_touchEvent(JNIEnv* env, jobject thiz, int mode, int fingerIndex, long time, float x, float y) {
platform->onTouchesEvent(&thiz, mode, fingerIndex, time, x, y);
}
jboolean Java_com_sometrik_framework_MyGLRenderer_onUpdate(JNIEnv* env, jobject thiz, double timestamp) {
if (platform->onUpdate(timestamp)) {
return JNI_TRUE;
} else {
return JNI_FALSE;
}
}
static JavaVM * gJavaVM = 0;
void Java_com_sometrik_framework_MyGLRenderer_onInit(JNIEnv* env, jobject thiz, jobject assetManager, jobject surface, float screenWidth, float screenHeight, float displayScale, bool hasEs3) {
if (!platform.get()) {
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "Creating Platform");
const char* glslVersion = "#version 100"; // "#version es 300"
AAssetManager* manager = AAssetManager_fromJava(env, assetManager);
android_fopen_set_asset_manager(manager);
platform = std::make_shared<AndroidPlatform>(env, assetManager, surface, displayScale, glslVersion, hasEs3);
}
FWApplication * application = applicationMain();
platform->setApplication(application);
platform->onInit(env, gJavaVM);
application->initialize(platform.get());
platform->setDisplayWidth(screenWidth);
platform->setDisplayHeight(screenHeight);
platform->onResize(screenWidth, screenHeight);
application->initializeContent();
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "Init end");
}
void Java_com_sometrik_framework_NativeLooper_test(JNIEnv* env, jobject thiz) {
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "Test");
// platform->onInit();
}
void Java_com_sometrik_framework_MyGLRenderer_nativeOnDraw(JNIEnv* env, jobject thiz) {
platform->onDraw();
}
void Java_com_sometrik_framework_FrameWork_okPressed(JNIEnv* env, jobject thiz, jstring text) {
jclass cls = env->FindClass("com/sometrik/framework/FrameWork");
jmethodID methodRef = env->GetMethodID(cls, "printText", "(Ljava/lang/String;)V");
env->CallVoidMethod(thiz, methodRef, text);
}
jint JNI_OnLoad(JavaVM *vm, void *reserved) {
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "JNI_Onload on AndroidPlatform");
gJavaVM = vm;
return JNI_VERSION_1_6;
}
}
<commit_msg>send internal element id as a parameter to postEvent<commit_after>/*
* Copyright (C) Sometrik oy 2015
*
*/
#include <string.h>
#include <android/log.h>
#include "Menu.h"
#include <jni.h>
#include <android/asset_manager.h>
#include <android/asset_manager_jni.h>
#include <iostream>
#include <android/bitmap.h>
#include <ContextAndroid.h>
#include <AndroidClient.h>
#include <AndroidPlatform.h>
#include <FWApplication.h>
#include <TouchEvent.h>
#include <CommandEvent.h>
#include <DrawEvent.h>
#include <android_fopen.h>
using namespace std;
extern FWApplication * applicationMain();
bool
AndroidPlatform::onTouchesEvent(jobject * _obj, int mode, int fingerIndex, double time, float x, float y) {
x /= getDisplayScale();
y /= getDisplayScale();
switch (mode) {
case 1:
{
TouchEvent ev(TouchEvent::ACTION_DOWN, x, y, time, fingerIndex);
postEvent(getActiveViewId(), ev);
}
break;
case 2:
{
TouchEvent ev(TouchEvent::ACTION_MOVE, x, y, time, fingerIndex);
postEvent(getActiveViewId(), ev);
}
break;
case 3:
{
TouchEvent ev(TouchEvent::ACTION_UP, x, y, time, fingerIndex);
postEvent(getActiveViewId(), ev);
}
break;
}
return true;
}
void AndroidPlatform::onResize(int width, int height) {
__android_log_print(ANDROID_LOG_ERROR, "Sometrik", "resize: %d %d ", width, height);
getApplication().onResize(width / getDisplayScale(), height / getDisplayScale(), width, height);
}
void
AndroidPlatform::menuPressed() {
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "Platform menupressed called");
CommandEvent ce(FW_ID_MENU);
postEvent(getActiveViewId(), ce);
// jclass handlerClass = env->GetObjectClass(handler);
// jmethodID emptyMessageMethod = env->GetMethodID(handlerClass, "sendEmptyMessage", "(I)Z");
// env->CallVoidMethod(handler, emptyMessageMethod, 1);
}
bool AndroidPlatform::onUpdate(double timestamp) {
bool shouldUpdate = getApplication().onUpdate(timestamp);
return shouldUpdate;
}
void
AndroidPlatform::onDraw() {
DrawEvent ev;
postEvent(getActiveViewId(), ev);
}
void AndroidPlatform::showCanvas(canvas::ContextAndroid & context) {
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "showCanvas called");
auto env = getJNIEnv();
jclass cls = env->GetObjectClass(framework);
jmethodID methodRef = env->GetMethodID(cls, "setNativeCanvas", "(Landroid/graphics/Bitmap;)V");
env->CallVoidMethod(framework, methodRef, dynamic_cast<canvas::AndroidSurface&>(context.getDefaultSurface()).getBitmap());
}
std::string AndroidPlatform::showTextEntryDialog(const std::string & message) {
return "";
}
void AndroidPlatform::showMessageBox(const std::string & title, const std::string & message) {
}
void
AndroidPlatform::onInit(JNIEnv * env, JavaVM * _gJavaVM) {
// gJavaVM = NULL;
// env->GetJavaVM(&gJavaVM);
gJavaVM = _gJavaVM;
gJavaVM->AttachCurrentThread(&env, NULL);
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "checking gjavavm");
if (gJavaVM == NULL){
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "1");
}
if (_gJavaVM == NULL){
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "2");
}
}
std::string AndroidPlatform::getBundleFilename(const char * filename) {
return filename;
}
std::string AndroidPlatform::getLocalFilename(const char * filename, FileType type) {
auto env = getJNIEnv();
jstring path;
jstring jfilename;
std::string result;
switch (type) {
case DATABASE:
case CACHE_DATABASE:
jfilename = env->NewStringUTF(filename);
path = (jstring) env->CallObjectMethod(framework, env->GetMethodID(env->GetObjectClass(framework), "getDBPath", "(Ljava/lang/String;)Ljava/lang/String;"), jfilename);
result = env->GetStringUTFChars(path, JNI_FALSE);
env->ReleaseStringUTFChars(jfilename, filename);
env->ReleaseStringUTFChars(path, result.c_str());
return result;
case NORMAL:
return "";
}
return "";
}
std::string AndroidPlatform::loadValue(const std::string & key) {
auto env = getJNIEnv();
jstring jkey = env->NewStringUTF(key.c_str());
jstring value = (jstring) env->CallObjectMethod(framework, env->GetMethodID(env->GetObjectClass(framework), "getFromPrefs", "(Ljava/lang/String;)Ljava/lang/String;"), jkey);
std::string result = env->GetStringUTFChars(value, JNI_FALSE);
env->ReleaseStringUTFChars(jkey, key.c_str());
env->ReleaseStringUTFChars(value, result.c_str());
return result;
}
void AndroidPlatform::storeValue(const std::string & key, const std::string & value) {
auto env = getJNIEnv();
jstring jkey = env->NewStringUTF(key.c_str());
jstring jvalue = env->NewStringUTF(value.c_str());
env->CallVoidMethod(framework, env->GetMethodID(env->GetObjectClass(framework), "addToPrefs", "(Ljava/lang/String;Ljava/lang/String;)V"), jkey, jvalue);
env->ReleaseStringUTFChars(jkey, key.c_str());
env->ReleaseStringUTFChars(jvalue, value.c_str());
}
void
AndroidPlatform::sendMessage(const Message & message) {
FWPlatform::sendMessage(message);
auto env = getJNIEnv();
jclass frameworkCls = env->FindClass("com/sometrik/framework/FrameWork");
jclass messageCls = env->FindClass("com/sometrik/framework/NativeMessage");
jmethodID sendMessageMethod = env->GetStaticMethodID(frameworkCls, "sendMessage", "(Lcom/sometrik/framework/FrameWork;Lcom/sometrik/framework/NativeMessage)V");
jmethodID messageConstructor = env->GetMethodID(messageCls, "<init>", "(IIILjava/lang/String;Ljava/lang/String;)V");
int messageTypeId = int(message.getType());
const char * textValue = message.getTextValue().c_str();
const char * textValue2 = message.getTextValue2().c_str();
jstring jtextValue = env->NewStringUTF(textValue);
jstring jtextValue2 = env->NewStringUTF(textValue2);
jobject jmessage = env->NewObject(messageCls, messageConstructor, messageTypeId, message.getElementId(), message.getParentElementId(), jtextValue, jtextValue2);
env->CallVoidMethod(frameworkCls, sendMessageMethod, framework, jmessage);
env->ReleaseStringUTFChars(jtextValue, textValue);
env->ReleaseStringUTFChars(jtextValue2, textValue2);
}
double AndroidPlatform::getTime() const {
auto env = getJNIEnv();
jclass systemClass = env->FindClass("Ljava/lang/System");
double currentTime = (double)env->CallStaticLongMethod(systemClass, env->GetStaticMethodID(systemClass, "currentTimeMillis", "()L"));
env->DeleteLocalRef(systemClass);
return currentTime;
}
int AndroidPlatform::showActionSheet(const FWRect & rect, const FWActionSheet & sheet) {
//Initialize java int and string arrays
auto env = getJNIEnv();
std::vector<FWOption> optionsVector = sheet.getOptions();
jobjectArray stringArray = (jobjectArray) env->NewObjectArray(optionsVector.size(), env->FindClass("java/lang/String"), 0);
jintArray intArray = env->NewIntArray(optionsVector.size());
jint fill[optionsVector.size()];
//Set values to java arrays
for (int i = 0; i < optionsVector.size(); i++) {
const char * text = optionsVector[i].getText().c_str();
jstring jtext = env->NewStringUTF(text);
env->SetObjectArrayElement(stringArray, i, jtext);
fill[i] = optionsVector[i].getId();
env->ReleaseStringUTFChars(jtext, text);
}
env->SetIntArrayRegion(intArray, 0, optionsVector.size(), fill);
//Send values to java to create the action sheet
jclass cls = env->FindClass("com/sometrik/framework/FrameWork");
jmethodID methodRef = env->GetStaticMethodID(cls, "createOptionsFromJNI", "(Lcom/sometrik/framework/FrameWork;I[I[Ljava/lang/String;)V");
env->CallStaticVoidMethod(cls, methodRef, framework, 22, intArray, stringArray);
//Not returning anything
return 0;
}
JNIEnv* AndroidPlatform::getJNIEnv() const {
if (gJavaVM == NULL) {
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "JavaVM is null");
return NULL;
}
JNIEnv *Myenv = NULL;
gJavaVM->GetEnv((void**)&Myenv, JNI_VERSION_1_6);
if (Myenv == NULL){
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "Env is null");
}
return Myenv;
}
std::shared_ptr<AndroidPlatform> platform;
extern "C" {
void Java_com_sometrik_framework_MyGLRenderer_onResize(JNIEnv* env, jobject thiz, float x, float y) {
platform->setDisplayWidth(x);
platform->setDisplayHeight(y);
platform->onResize(x, y);
}
void Java_com_sometrik_framework_FrameWork_menuPressed(JNIEnv* env, jobject thiz) {
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "menu pressed: env = %p", env);
platform->menuPressed();
}
void Java_com_sometrik_framework_FrameWork_touchEvent(JNIEnv* env, jobject thiz, int mode, int fingerIndex, long time, float x, float y) {
platform->onTouchesEvent(&thiz, mode, fingerIndex, time, x, y);
}
jboolean Java_com_sometrik_framework_MyGLRenderer_onUpdate(JNIEnv* env, jobject thiz, double timestamp) {
if (platform->onUpdate(timestamp)) {
return JNI_TRUE;
} else {
return JNI_FALSE;
}
}
static JavaVM * gJavaVM = 0;
void Java_com_sometrik_framework_MyGLRenderer_onInit(JNIEnv* env, jobject thiz, jobject assetManager, jobject surface, float screenWidth, float screenHeight, float displayScale, bool hasEs3) {
if (!platform.get()) {
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "Creating Platform");
const char* glslVersion = "#version 100"; // "#version es 300"
AAssetManager* manager = AAssetManager_fromJava(env, assetManager);
android_fopen_set_asset_manager(manager);
platform = std::make_shared<AndroidPlatform>(env, assetManager, surface, displayScale, glslVersion, hasEs3);
}
FWApplication * application = applicationMain();
platform->setApplication(application);
platform->onInit(env, gJavaVM);
application->initialize(platform.get());
platform->setDisplayWidth(screenWidth);
platform->setDisplayHeight(screenHeight);
platform->onResize(screenWidth, screenHeight);
application->initializeContent();
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "Init end");
}
void Java_com_sometrik_framework_NativeLooper_test(JNIEnv* env, jobject thiz) {
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "Test");
// platform->onInit();
}
void Java_com_sometrik_framework_MyGLRenderer_nativeOnDraw(JNIEnv* env, jobject thiz) {
platform->onDraw();
}
void Java_com_sometrik_framework_FrameWork_okPressed(JNIEnv* env, jobject thiz, jstring text) {
jclass cls = env->FindClass("com/sometrik/framework/FrameWork");
jmethodID methodRef = env->GetMethodID(cls, "printText", "(Ljava/lang/String;)V");
env->CallVoidMethod(thiz, methodRef, text);
}
jint JNI_OnLoad(JavaVM *vm, void *reserved) {
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "JNI_Onload on AndroidPlatform");
gJavaVM = vm;
return JNI_VERSION_1_6;
}
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) Sometrik oy 2015
*
*/
#include <string.h>
#include <android/log.h>
#include "Menu.h"
#include <jni.h>
#include <android/asset_manager.h>
#include <android/asset_manager_jni.h>
#include <iostream>
#include <android/bitmap.h>
#include <ContextAndroid.h>
#include <AndroidClient.h>
#include <AndroidPlatform.h>
#include <FWApplication.h>
#include <TouchEvent.h>
#include <CommandEvent.h>
#include <DrawEvent.h>
#include <android_fopen.h>
using namespace std;
extern FWApplication * applicationMain();
bool AndroidPlatform::onTouchesEvent(jobject * _obj, int mode, int fingerIndex, double time, float x, float y) {
x /= getDisplayScale();
y /= getDisplayScale();
switch (mode) {
case 1:
{
TouchEvent ev(getActiveViewId(), TouchEvent::ACTION_DOWN, x, y, time, fingerIndex);
postEvent(ev);
}
break;
case 2:
{
TouchEvent ev(getActiveViewId(), TouchEvent::ACTION_MOVE, x, y, time, fingerIndex);
postEvent(ev);
}
break;
case 3:
{
TouchEvent ev(getActiveViewId(), TouchEvent::ACTION_UP, x, y, time, fingerIndex);
postEvent(ev);
}
break;
}
return true;
}
void AndroidPlatform::onResize(int width, int height) {
__android_log_print(ANDROID_LOG_ERROR, "Sometrik", "resize: %d %d ", width, height);
getApplication().onResize(width / getDisplayScale(), height / getDisplayScale(), width, height);
}
void
AndroidPlatform::menuPressed() {
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "Platform menupressed called");
postEvent(CommandEvent(FW_ID_MENU));
// jclass handlerClass = env->GetObjectClass(handler);
// jmethodID emptyMessageMethod = env->GetMethodID(handlerClass, "sendEmptyMessage", "(I)Z");
// env->CallVoidMethod(handler, emptyMessageMethod, 1);
}
int AndroidPlatform::showActionSheet(const FWRect & rect, const FWActionSheet & sheet) {
//Initialize java int and string arrays
auto env = getJNIEnv();
std::vector<FWOption> optionsVector = sheet.getOptions();
jobjectArray stringArray = (jobjectArray) env->NewObjectArray(optionsVector.size(), env->FindClass("java/lang/String"), 0);
jintArray intArray = env->NewIntArray(optionsVector.size());
jint fill[optionsVector.size()];
//Set values to java arrays
for (int i = 0; i < optionsVector.size(); i++) {
const char * text = optionsVector[i].getText().c_str();
jstring jtext = env->NewStringUTF(text);
env->SetObjectArrayElement(stringArray, i, jtext);
fill[i] = optionsVector[i].getId();
env->ReleaseStringUTFChars(jtext, text);
}
env->SetIntArrayRegion(intArray, 0, optionsVector.size(), fill);
//Send values to java to create the action sheet
jclass cls = env->FindClass("com/sometrik/framework/FrameWork");
jmethodID methodRef = env->GetStaticMethodID(cls, "createOptionsFromJNI", "(Lcom/sometrik/framework/FrameWork;I[I[Ljava/lang/String;)V");
env->CallStaticVoidMethod(cls, methodRef, framework, 22, intArray, stringArray);
//Not returning anything
return 0;
}
bool AndroidPlatform::onUpdate(double timestamp) {
bool shouldUpdate = getApplication().onUpdate(timestamp);
return shouldUpdate;
}
void
AndroidPlatform::onDraw() {
DrawEvent ev(0);
postEvent(ev);
}
std::string AndroidPlatform::showTextEntryDialog(const std::string & message) {
return "";
}
void AndroidPlatform::showMessageBox(const std::string & title, const std::string & message) {
messagePoster(5, title, message);
}
void AndroidPlatform::createInputDialog(const char * _title, const char * _message, int params) {
auto env = getJNIEnv();
jclass cls = env->FindClass("com/sometrik/framework/FrameWork");
jmethodID methodRef = env->GetMethodID(cls, "createInputDialog", "(Ljava/lang/String;Ljava/lang/String;)V");
jstring title = env->NewStringUTF(_title);
jstring message = env->NewStringUTF(_message);
//Call method with void return (env, object, method, parameters...)
//String has to be made with jstring name = (*env)->NewStringUTF(env, "What you want");
env->CallVoidMethod(framework, methodRef, title, message);
env->ReleaseStringUTFChars(title, _title);
env->ReleaseStringUTFChars(message, _message);
}
void AndroidPlatform::showCanvas(canvas::ContextAndroid & context) {
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "showCanvas called");
auto env = getJNIEnv();
jclass cls = env->GetObjectClass(framework);
jmethodID methodRef = env->GetMethodID(cls, "setNativeCanvas", "(Landroid/graphics/Bitmap;)V");
env->CallVoidMethod(framework, methodRef, dynamic_cast<canvas::AndroidSurface&>(context.getDefaultSurface()).getBitmap());
}
void
AndroidPlatform::onInit(JNIEnv * env, JavaVM * _gJavaVM) {
// gJavaVM = NULL;
// env->GetJavaVM(&gJavaVM);
gJavaVM = _gJavaVM;
gJavaVM->AttachCurrentThread(&env, NULL);
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "checking gjavavm");
if (gJavaVM == NULL){
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "1");
}
if (_gJavaVM == NULL){
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "2");
}
}
std::string AndroidPlatform::getBundleFilename(const char * filename) {
return filename;
}
std::string AndroidPlatform::getLocalFilename(const char * filename, FileType type) {
auto env = getJNIEnv();
jstring path;
jstring jfilename;
std::string result;
switch (type) {
case DATABASE:
case CACHE_DATABASE:
jfilename = env->NewStringUTF(filename);
path = (jstring) env->CallObjectMethod(framework, env->GetMethodID(env->GetObjectClass(framework), "getDBPath", "(Ljava/lang/String;)Ljava/lang/String;"), jfilename);
result = env->GetStringUTFChars(path, JNI_FALSE);
env->ReleaseStringUTFChars(jfilename, filename);
env->ReleaseStringUTFChars(path, result.c_str());
return result;
case NORMAL:
return "";
}
return "";
}
std::string AndroidPlatform::loadValue(const std::string & key) {
auto env = getJNIEnv();
jstring jkey = env->NewStringUTF(key.c_str());
jstring value = (jstring) env->CallObjectMethod(framework, env->GetMethodID(env->GetObjectClass(framework), "getFromPrefs", "(Ljava/lang/String;)Ljava/lang/String;"), jkey);
std::string result = env->GetStringUTFChars(value, JNI_FALSE);
env->ReleaseStringUTFChars(jkey, key.c_str());
env->ReleaseStringUTFChars(value, result.c_str());
return result;
}
void AndroidPlatform::storeValue(const std::string & key, const std::string & value) {
auto env = getJNIEnv();
jstring jkey = env->NewStringUTF(key.c_str());
jstring jvalue = env->NewStringUTF(value.c_str());
env->CallVoidMethod(framework, env->GetMethodID(env->GetObjectClass(framework), "addToPrefs", "(Ljava/lang/String;Ljava/lang/String;)V"), jkey, jvalue);
env->ReleaseStringUTFChars(jkey, key.c_str());
env->ReleaseStringUTFChars(jvalue, value.c_str());
}
void AndroidPlatform::messagePoster(int message, const std::string text) {
auto env = getJNIEnv();
jclass cls = env->FindClass("com/sometrik/framework/FrameWork");
jmethodID methodRef = env->GetStaticMethodID(cls, "LeaveMessageToSurface", "(Lcom/sometrik/framework/FrameWork;ILjava/lang/String;)V");
jstring jtext = env->NewStringUTF(text.c_str());
env->CallStaticVoidMethod(cls, methodRef, framework, message, jtext);
env->ReleaseStringUTFChars(jtext, text.c_str());
}
void AndroidPlatform::messagePoster(int message, int content) {
auto env = getJNIEnv();
jclass cls = env->FindClass("com/sometrik/framework/FrameWork");
jmethodID methodRef = env->GetStaticMethodID(cls, "LeaveMessageToSurface", "(Lcom/sometrik/framework/FrameWork;II)V");
env->CallStaticVoidMethod(cls, methodRef, framework, message, content);
}
void AndroidPlatform::messagePoster(int message, const std::string title, const std::string text) {
auto env = getJNIEnv();
jclass cls = env->FindClass("com/sometrik/framework/FrameWork");
jmethodID methodRef = env->GetStaticMethodID(cls, "LeaveMessageToSurface", "(Lcom/sometrik/framework/FrameWork;ILjava/lang/String;Ljava/lang/String;)V");
jstring jtitle = env->NewStringUTF(title.c_str());
jstring jtext = env->NewStringUTF(text.c_str());
env->CallStaticVoidMethod(cls, methodRef, framework, message, jtitle, jtext);
env->ReleaseStringUTFChars(jtitle, title.c_str());
env->ReleaseStringUTFChars(jtext, text.c_str());
}
double AndroidPlatform::getTime() const {
auto env = getJNIEnv();
jclass systemClass = env->FindClass("Ljava/lang/System");
double currentTime = (double)env->CallStaticLongMethod(systemClass, env->GetStaticMethodID(systemClass, "currentTimeMillis", "()L"));
env->DeleteLocalRef(systemClass);
return currentTime;
}
JNIEnv* AndroidPlatform::getJNIEnv() const {
if (gJavaVM == NULL) {
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "JavaVM is null");
return NULL;
}
JNIEnv *Myenv = NULL;
gJavaVM->GetEnv((void**)&Myenv, JNI_VERSION_1_6);
if (Myenv == NULL){
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "Env is null");
}
return Myenv;
}
std::shared_ptr<AndroidPlatform> platform;
extern "C" {
void Java_com_sometrik_framework_MyGLRenderer_onResize(JNIEnv* env, jobject thiz, float x, float y) {
platform->setDisplayWidth(x);
platform->setDisplayHeight(y);
platform->onResize(x, y);
}
void Java_com_sometrik_framework_FrameWork_menuPressed(JNIEnv* env, jobject thiz) {
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "menu pressed: env = %p", env);
platform->menuPressed();
}
void Java_com_sometrik_framework_FrameWork_touchEvent(JNIEnv* env, jobject thiz, int mode, int fingerIndex, long time, float x, float y) {
platform->onTouchesEvent(&thiz, mode, fingerIndex, time, x, y);
}
jboolean Java_com_sometrik_framework_MyGLRenderer_onUpdate(JNIEnv* env, jobject thiz, double timestamp) {
if (platform->onUpdate(timestamp)) {
return JNI_TRUE;
} else {
return JNI_FALSE;
}
}
static JavaVM * gJavaVM = 0;
void Java_com_sometrik_framework_MyGLRenderer_onInit(JNIEnv* env, jobject thiz, jobject assetManager, jobject surface, float screenWidth, float screenHeight, float displayScale, bool hasEs3) {
if (!platform.get()) {
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "Creating Platform");
const char* glslVersion = "#version 100"; // "#version es 300"
AAssetManager* manager = AAssetManager_fromJava(env, assetManager);
android_fopen_set_asset_manager(manager);
platform = std::make_shared<AndroidPlatform>(env, assetManager, surface, displayScale, glslVersion, hasEs3);
}
FWApplication * application = applicationMain();
platform->setApplication(application);
platform->onInit(env, gJavaVM);
application->initialize(this);
platform->setDisplayWidth(screenWidth);
platform->setDisplayHeight(screenHeight);
platform->onResize(screenWidth, screenHeight);
application->initializeContent();
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "Init end");
}
void Java_com_sometrik_framework_NativeLooper_test(JNIEnv* env, jobject thiz) {
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "Test");
// platform->onInit();
}
void Java_com_sometrik_framework_MyGLRenderer_nativeOnDraw(JNIEnv* env, jobject thiz) {
platform->onDraw();
}
void Java_com_sometrik_framework_FrameWork_okPressed(JNIEnv* env, jobject thiz, jstring text) {
jclass cls = env->FindClass("com/sometrik/framework/FrameWork");
jmethodID methodRef = env->GetMethodID(cls, "printText", "(Ljava/lang/String;)V");
env->CallVoidMethod(thiz, methodRef, text);
}
jint JNI_OnLoad(JavaVM *vm, void *reserved) {
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "JNI_Onload on AndroidPlatform");
gJavaVM = vm;
return JNI_VERSION_1_6;
}
}
<commit_msg>Fix build error with postEvent<commit_after>/*
* Copyright (C) Sometrik oy 2015
*
*/
#include <string.h>
#include <android/log.h>
#include "Menu.h"
#include <jni.h>
#include <android/asset_manager.h>
#include <android/asset_manager_jni.h>
#include <iostream>
#include <android/bitmap.h>
#include <ContextAndroid.h>
#include <AndroidClient.h>
#include <AndroidPlatform.h>
#include <FWApplication.h>
#include <TouchEvent.h>
#include <CommandEvent.h>
#include <DrawEvent.h>
#include <android_fopen.h>
using namespace std;
extern FWApplication * applicationMain();
bool AndroidPlatform::onTouchesEvent(jobject * _obj, int mode, int fingerIndex, double time, float x, float y) {
x /= getDisplayScale();
y /= getDisplayScale();
switch (mode) {
case 1:
{
TouchEvent ev(getActiveViewId(), TouchEvent::ACTION_DOWN, x, y, time, fingerIndex);
postEvent(ev);
}
break;
case 2:
{
TouchEvent ev(getActiveViewId(), TouchEvent::ACTION_MOVE, x, y, time, fingerIndex);
postEvent(ev);
}
break;
case 3:
{
TouchEvent ev(getActiveViewId(), TouchEvent::ACTION_UP, x, y, time, fingerIndex);
postEvent(ev);
}
break;
}
return true;
}
void AndroidPlatform::onResize(int width, int height) {
__android_log_print(ANDROID_LOG_ERROR, "Sometrik", "resize: %d %d ", width, height);
getApplication().onResize(width / getDisplayScale(), height / getDisplayScale(), width, height);
}
void
AndroidPlatform::menuPressed() {
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "Platform menupressed called");
CommandEvent ce(FW_ID_MENU);
postEvent(ce);
// jclass handlerClass = env->GetObjectClass(handler);
// jmethodID emptyMessageMethod = env->GetMethodID(handlerClass, "sendEmptyMessage", "(I)Z");
// env->CallVoidMethod(handler, emptyMessageMethod, 1);
}
int AndroidPlatform::showActionSheet(const FWRect & rect, const FWActionSheet & sheet) {
//Initialize java int and string arrays
auto env = getJNIEnv();
std::vector<FWOption> optionsVector = sheet.getOptions();
jobjectArray stringArray = (jobjectArray) env->NewObjectArray(optionsVector.size(), env->FindClass("java/lang/String"), 0);
jintArray intArray = env->NewIntArray(optionsVector.size());
jint fill[optionsVector.size()];
//Set values to java arrays
for (int i = 0; i < optionsVector.size(); i++) {
const char * text = optionsVector[i].getText().c_str();
jstring jtext = env->NewStringUTF(text);
env->SetObjectArrayElement(stringArray, i, jtext);
fill[i] = optionsVector[i].getId();
env->ReleaseStringUTFChars(jtext, text);
}
env->SetIntArrayRegion(intArray, 0, optionsVector.size(), fill);
//Send values to java to create the action sheet
jclass cls = env->FindClass("com/sometrik/framework/FrameWork");
jmethodID methodRef = env->GetStaticMethodID(cls, "createOptionsFromJNI", "(Lcom/sometrik/framework/FrameWork;I[I[Ljava/lang/String;)V");
env->CallStaticVoidMethod(cls, methodRef, framework, 22, intArray, stringArray);
//Not returning anything
return 0;
}
bool AndroidPlatform::onUpdate(double timestamp) {
bool shouldUpdate = getApplication().onUpdate(timestamp);
return shouldUpdate;
}
void
AndroidPlatform::onDraw() {
DrawEvent ev(0);
postEvent(ev);
}
std::string AndroidPlatform::showTextEntryDialog(const std::string & message) {
return "";
}
void AndroidPlatform::showMessageBox(const std::string & title, const std::string & message) {
messagePoster(5, title, message);
}
void AndroidPlatform::createInputDialog(const char * _title, const char * _message, int params) {
auto env = getJNIEnv();
jclass cls = env->FindClass("com/sometrik/framework/FrameWork");
jmethodID methodRef = env->GetMethodID(cls, "createInputDialog", "(Ljava/lang/String;Ljava/lang/String;)V");
jstring title = env->NewStringUTF(_title);
jstring message = env->NewStringUTF(_message);
//Call method with void return (env, object, method, parameters...)
//String has to be made with jstring name = (*env)->NewStringUTF(env, "What you want");
env->CallVoidMethod(framework, methodRef, title, message);
env->ReleaseStringUTFChars(title, _title);
env->ReleaseStringUTFChars(message, _message);
}
void AndroidPlatform::showCanvas(canvas::ContextAndroid & context) {
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "showCanvas called");
auto env = getJNIEnv();
jclass cls = env->GetObjectClass(framework);
jmethodID methodRef = env->GetMethodID(cls, "setNativeCanvas", "(Landroid/graphics/Bitmap;)V");
env->CallVoidMethod(framework, methodRef, dynamic_cast<canvas::AndroidSurface&>(context.getDefaultSurface()).getBitmap());
}
void
AndroidPlatform::onInit(JNIEnv * env, JavaVM * _gJavaVM) {
// gJavaVM = NULL;
// env->GetJavaVM(&gJavaVM);
gJavaVM = _gJavaVM;
gJavaVM->AttachCurrentThread(&env, NULL);
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "checking gjavavm");
if (gJavaVM == NULL){
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "1");
}
if (_gJavaVM == NULL){
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "2");
}
}
std::string AndroidPlatform::getBundleFilename(const char * filename) {
return filename;
}
std::string AndroidPlatform::getLocalFilename(const char * filename, FileType type) {
auto env = getJNIEnv();
jstring path;
jstring jfilename;
std::string result;
switch (type) {
case DATABASE:
case CACHE_DATABASE:
jfilename = env->NewStringUTF(filename);
path = (jstring) env->CallObjectMethod(framework, env->GetMethodID(env->GetObjectClass(framework), "getDBPath", "(Ljava/lang/String;)Ljava/lang/String;"), jfilename);
result = env->GetStringUTFChars(path, JNI_FALSE);
env->ReleaseStringUTFChars(jfilename, filename);
env->ReleaseStringUTFChars(path, result.c_str());
return result;
case NORMAL:
return "";
}
return "";
}
std::string AndroidPlatform::loadValue(const std::string & key) {
auto env = getJNIEnv();
jstring jkey = env->NewStringUTF(key.c_str());
jstring value = (jstring) env->CallObjectMethod(framework, env->GetMethodID(env->GetObjectClass(framework), "getFromPrefs", "(Ljava/lang/String;)Ljava/lang/String;"), jkey);
std::string result = env->GetStringUTFChars(value, JNI_FALSE);
env->ReleaseStringUTFChars(jkey, key.c_str());
env->ReleaseStringUTFChars(value, result.c_str());
return result;
}
void AndroidPlatform::storeValue(const std::string & key, const std::string & value) {
auto env = getJNIEnv();
jstring jkey = env->NewStringUTF(key.c_str());
jstring jvalue = env->NewStringUTF(value.c_str());
env->CallVoidMethod(framework, env->GetMethodID(env->GetObjectClass(framework), "addToPrefs", "(Ljava/lang/String;Ljava/lang/String;)V"), jkey, jvalue);
env->ReleaseStringUTFChars(jkey, key.c_str());
env->ReleaseStringUTFChars(jvalue, value.c_str());
}
void AndroidPlatform::messagePoster(int message, const std::string text) {
auto env = getJNIEnv();
jclass cls = env->FindClass("com/sometrik/framework/FrameWork");
jmethodID methodRef = env->GetStaticMethodID(cls, "LeaveMessageToSurface", "(Lcom/sometrik/framework/FrameWork;ILjava/lang/String;)V");
jstring jtext = env->NewStringUTF(text.c_str());
env->CallStaticVoidMethod(cls, methodRef, framework, message, jtext);
env->ReleaseStringUTFChars(jtext, text.c_str());
}
void AndroidPlatform::messagePoster(int message, int content) {
auto env = getJNIEnv();
jclass cls = env->FindClass("com/sometrik/framework/FrameWork");
jmethodID methodRef = env->GetStaticMethodID(cls, "LeaveMessageToSurface", "(Lcom/sometrik/framework/FrameWork;II)V");
env->CallStaticVoidMethod(cls, methodRef, framework, message, content);
}
void AndroidPlatform::messagePoster(int message, const std::string title, const std::string text) {
auto env = getJNIEnv();
jclass cls = env->FindClass("com/sometrik/framework/FrameWork");
jmethodID methodRef = env->GetStaticMethodID(cls, "LeaveMessageToSurface", "(Lcom/sometrik/framework/FrameWork;ILjava/lang/String;Ljava/lang/String;)V");
jstring jtitle = env->NewStringUTF(title.c_str());
jstring jtext = env->NewStringUTF(text.c_str());
env->CallStaticVoidMethod(cls, methodRef, framework, message, jtitle, jtext);
env->ReleaseStringUTFChars(jtitle, title.c_str());
env->ReleaseStringUTFChars(jtext, text.c_str());
}
double AndroidPlatform::getTime() const {
auto env = getJNIEnv();
jclass systemClass = env->FindClass("Ljava/lang/System");
double currentTime = (double)env->CallStaticLongMethod(systemClass, env->GetStaticMethodID(systemClass, "currentTimeMillis", "()L"));
env->DeleteLocalRef(systemClass);
return currentTime;
}
JNIEnv* AndroidPlatform::getJNIEnv() const {
if (gJavaVM == NULL) {
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "JavaVM is null");
return NULL;
}
JNIEnv *Myenv = NULL;
gJavaVM->GetEnv((void**)&Myenv, JNI_VERSION_1_6);
if (Myenv == NULL){
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "Env is null");
}
return Myenv;
}
std::shared_ptr<AndroidPlatform> platform;
extern "C" {
void Java_com_sometrik_framework_MyGLRenderer_onResize(JNIEnv* env, jobject thiz, float x, float y) {
platform->setDisplayWidth(x);
platform->setDisplayHeight(y);
platform->onResize(x, y);
}
void Java_com_sometrik_framework_FrameWork_menuPressed(JNIEnv* env, jobject thiz) {
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "menu pressed: env = %p", env);
platform->menuPressed();
}
void Java_com_sometrik_framework_FrameWork_touchEvent(JNIEnv* env, jobject thiz, int mode, int fingerIndex, long time, float x, float y) {
platform->onTouchesEvent(&thiz, mode, fingerIndex, time, x, y);
}
jboolean Java_com_sometrik_framework_MyGLRenderer_onUpdate(JNIEnv* env, jobject thiz, double timestamp) {
if (platform->onUpdate(timestamp)) {
return JNI_TRUE;
} else {
return JNI_FALSE;
}
}
static JavaVM * gJavaVM = 0;
void Java_com_sometrik_framework_MyGLRenderer_onInit(JNIEnv* env, jobject thiz, jobject assetManager, jobject surface, float screenWidth, float screenHeight, float displayScale, bool hasEs3) {
if (!platform.get()) {
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "Creating Platform");
const char* glslVersion = "#version 100"; // "#version es 300"
AAssetManager* manager = AAssetManager_fromJava(env, assetManager);
android_fopen_set_asset_manager(manager);
platform = std::make_shared<AndroidPlatform>(env, assetManager, surface, displayScale, glslVersion, hasEs3);
}
FWApplication * application = applicationMain();
platform->setApplication(application);
platform->onInit(env, gJavaVM);
application->initialize(this);
platform->setDisplayWidth(screenWidth);
platform->setDisplayHeight(screenHeight);
platform->onResize(screenWidth, screenHeight);
application->initializeContent();
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "Init end");
}
void Java_com_sometrik_framework_NativeLooper_test(JNIEnv* env, jobject thiz) {
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "Test");
// platform->onInit();
}
void Java_com_sometrik_framework_MyGLRenderer_nativeOnDraw(JNIEnv* env, jobject thiz) {
platform->onDraw();
}
void Java_com_sometrik_framework_FrameWork_okPressed(JNIEnv* env, jobject thiz, jstring text) {
jclass cls = env->FindClass("com/sometrik/framework/FrameWork");
jmethodID methodRef = env->GetMethodID(cls, "printText", "(Ljava/lang/String;)V");
env->CallVoidMethod(thiz, methodRef, text);
}
jint JNI_OnLoad(JavaVM *vm, void *reserved) {
__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "JNI_Onload on AndroidPlatform");
gJavaVM = vm;
return JNI_VERSION_1_6;
}
}
<|endoftext|> |
<commit_before>// Transaction.cpp
#include "Transaction.h"
#include "Model.h"
#include "MarketModel.h"
#include <string>
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Transaction::Transaction(Model* creator, TransType type) {
minfrac = 0;
price_ = 0;
supplier_ = NULL;
requester_ = NULL;
resource_ = NULL;
type_ = type;
if (type == OFFER) {
supplier_ = creator;
} else {
requester_ = creator;
}
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Transaction::~Transaction() { }
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Transaction* Transaction::clone() {
// clones resource_ and gives copy to the transaction clone
Transaction* trans = new Transaction(*this);
trans->setResource(resource_);
return trans;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
MarketModel* Transaction::market() const {
//try {
MarketModel* market = MarketModel::marketForCommod(commod_);
//} catch(CycMarketlessCommodException e) {
//throw e;
//}
return market;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Model* Transaction::supplier() const {
if (supplier_ == NULL) {
std::string err_msg = "Uninitilized message supplier.";
throw CycNullMsgParamException(err_msg);
}
return supplier_;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void Transaction::setSupplier(Model* supplier) {
supplier_ = supplier;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Model* Transaction::requester() const {
if (requester_ == NULL) {
std::string err_msg = "Uninitilized message requester.";
throw CycNullMsgParamException(err_msg);
}
return requester_;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void Transaction::setRequester(Model* requester) {
requester_ = requester;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
std::string Transaction::commod() const {
return commod_;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void Transaction::setCommod(std::string newCommod) {
commod_ = newCommod;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
bool Transaction::isOffer() const {
return type_ == OFFER;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
double Transaction::price() const {
return price_;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void Transaction::setPrice(double newPrice) {
price_ = newPrice;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
rsrc_ptr Transaction::resource() const {
return resource_;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void Transaction::setResource(rsrc_ptr newResource) {
if (newResource.get()) {
resource_ = newResource->clone();
}
}
<commit_msg>transaction market() method has code that makes it clear that it throws an exception.<commit_after>// Transaction.cpp
#include "Transaction.h"
#include "Model.h"
#include "MarketModel.h"
#include <string>
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Transaction::Transaction(Model* creator, TransType type) {
minfrac = 0;
price_ = 0;
supplier_ = NULL;
requester_ = NULL;
resource_ = NULL;
type_ = type;
if (type == OFFER) {
supplier_ = creator;
} else {
requester_ = creator;
}
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Transaction::~Transaction() { }
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Transaction* Transaction::clone() {
// clones resource_ and gives copy to the transaction clone
Transaction* trans = new Transaction(*this);
trans->setResource(resource_);
return trans;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
MarketModel* Transaction::market() const {
// put here to make explicit that this method throws
MarketModel* market;
try {
market = MarketModel::marketForCommod(commod_);
} catch(CycMarketlessCommodException e) {
throw e;
}
return market;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Model* Transaction::supplier() const {
if (supplier_ == NULL) {
std::string err_msg = "Uninitilized message supplier.";
throw CycNullMsgParamException(err_msg);
}
return supplier_;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void Transaction::setSupplier(Model* supplier) {
supplier_ = supplier;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Model* Transaction::requester() const {
if (requester_ == NULL) {
std::string err_msg = "Uninitilized message requester.";
throw CycNullMsgParamException(err_msg);
}
return requester_;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void Transaction::setRequester(Model* requester) {
requester_ = requester;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
std::string Transaction::commod() const {
return commod_;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void Transaction::setCommod(std::string newCommod) {
commod_ = newCommod;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
bool Transaction::isOffer() const {
return type_ == OFFER;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
double Transaction::price() const {
return price_;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void Transaction::setPrice(double newPrice) {
price_ = newPrice;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
rsrc_ptr Transaction::resource() const {
return resource_;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void Transaction::setResource(rsrc_ptr newResource) {
if (newResource.get()) {
resource_ = newResource->clone();
}
}
<|endoftext|> |
<commit_before>// Compilation using GCC compiler under Linux.
// g++ -std=c++0x program.cpp -pthread -o program.out
// ./program.out
#include <iostream>
#include <thread>
// Thread function.
void threadFun()
{
std::cout << "Hello from thread!\n";
}
int main (int argc, char **argv)
{
// This is worker thread that will execute function.
// Fork-join parallelism - this is the fork - execution splits to
// main and worker thread.
std::thread th(&threadFun); //< Create thread and pass the thread function.
std::cout << "Hello World!\n";
th.join(); // Join worker thread to main thread.
return 0;
}
<commit_msg>Updated compiler version in comments.<commit_after>// Compiled using GCC compiler (4.8.1) under Linux.
// g++ -std=c++0x thread01.cpp -pthread -o a.out
// Run: ./a.out
#include <iostream>
#include <thread>
// Thread function.
void threadFun()
{
std::cout << "Hello from thread!\n";
}
int main (int argc, char **argv)
{
// This is worker thread that will execute function.
// Fork-join parallelism - this is the fork - execution splits to
// main and worker thread.
std::thread th(&threadFun); //< Create thread and pass the thread function.
std::cout << "Hello World!\n";
th.join(); // Join worker thread to main thread.
return 0;
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "perfetto/ext/base/subprocess.h"
#if PERFETTO_HAS_SUBPROCESS()
#include <thread>
#include <signal.h>
#include <sys/stat.h>
#include <unistd.h>
#include "perfetto/ext/base/file_utils.h"
#include "perfetto/ext/base/temp_file.h"
#include "test/gtest_and_gmock.h"
namespace perfetto {
namespace base {
namespace {
std::string GenLargeString() {
std::string contents;
for (int i = 0; i < 4096; i++) {
contents += "very long text " + std::to_string(i) + "\n";
}
// Make sure that |contents| is > the default pipe buffer on Linux (4 pages).
PERFETTO_DCHECK(contents.size() > 4096 * 4);
return contents;
}
TEST(SubprocessTest, InvalidPath) {
Subprocess p({"/usr/bin/invalid_1337"});
EXPECT_FALSE(p.Call());
EXPECT_EQ(p.status(), Subprocess::kExited);
EXPECT_EQ(p.returncode(), 128);
EXPECT_EQ(p.output(), "execve() failed\n");
}
TEST(SubprocessTest, StdoutOnly) {
Subprocess p({"sh", "-c", "(echo skip_err >&2); echo out_only"});
p.args.stdout_mode = Subprocess::kBuffer;
p.args.stderr_mode = Subprocess::kDevNull;
EXPECT_TRUE(p.Call());
EXPECT_EQ(p.status(), Subprocess::kExited);
EXPECT_EQ(p.output(), "out_only\n");
}
TEST(SubprocessTest, StderrOnly) {
Subprocess p({"sh", "-c", "(echo err_only >&2); echo skip_out"});
p.args.stdout_mode = Subprocess::kDevNull;
p.args.stderr_mode = Subprocess::kBuffer;
EXPECT_TRUE(p.Call());
EXPECT_EQ(p.output(), "err_only\n");
}
TEST(SubprocessTest, BothStdoutAndStderr) {
Subprocess p({"sh", "-c", "echo out; (echo err >&2); echo out2"});
p.args.stdout_mode = Subprocess::kBuffer;
p.args.stderr_mode = Subprocess::kBuffer;
EXPECT_TRUE(p.Call());
EXPECT_EQ(p.output(), "out\nerr\nout2\n");
}
TEST(SubprocessTest, BinTrue) {
Subprocess p({"true"});
EXPECT_TRUE(p.Call());
EXPECT_EQ(p.status(), Subprocess::kExited);
EXPECT_EQ(p.returncode(), 0);
}
TEST(SubprocessTest, BinFalse) {
Subprocess p({"false"});
EXPECT_FALSE(p.Call());
EXPECT_EQ(p.status(), Subprocess::kExited);
EXPECT_EQ(p.returncode(), 1);
}
TEST(SubprocessTest, Echo) {
Subprocess p({"echo", "-n", "foobar"});
p.args.stdout_mode = Subprocess::kBuffer;
EXPECT_TRUE(p.Call());
EXPECT_EQ(p.status(), Subprocess::kExited);
EXPECT_EQ(p.returncode(), 0);
EXPECT_EQ(p.output(), "foobar");
}
TEST(SubprocessTest, FeedbackLongInput) {
std::string contents = GenLargeString();
Subprocess p({"cat", "-"});
p.args.stdout_mode = Subprocess::kBuffer;
p.args.input = contents;
EXPECT_TRUE(p.Call());
EXPECT_EQ(p.status(), Subprocess::kExited);
EXPECT_EQ(p.returncode(), 0);
EXPECT_EQ(p.output(), contents);
}
TEST(SubprocessTest, CatLargeFile) {
std::string contents = GenLargeString();
TempFile tf = TempFile::Create();
WriteAll(tf.fd(), contents.data(), contents.size());
FlushFile(tf.fd());
Subprocess p({"cat", tf.path().c_str()});
p.args.stdout_mode = Subprocess::kBuffer;
EXPECT_TRUE(p.Call());
EXPECT_EQ(p.output(), contents);
}
TEST(SubprocessTest, Timeout) {
Subprocess p({"sleep", "60"});
EXPECT_FALSE(p.Call(/*timeout_ms=*/1));
EXPECT_EQ(p.status(), Subprocess::kKilledBySignal);
}
TEST(SubprocessTest, TimeoutNotHit) {
Subprocess p({"sleep", "0.01"});
EXPECT_TRUE(p.Call(/*timeout_ms=*/100000));
}
TEST(SubprocessTest, TimeoutStopOutput) {
Subprocess p({"sh", "-c", "while true; do echo stuff; done"});
p.args.stdout_mode = Subprocess::kDevNull;
EXPECT_FALSE(p.Call(/*timeout_ms=*/10));
EXPECT_EQ(p.status(), Subprocess::kKilledBySignal);
}
TEST(SubprocessTest, ExitBeforeReadingStdin) {
// 'sh -c' is to avoid closing stdin (sleep closes it before sleeping).
Subprocess p({"sh", "-c", "sleep 0.01"});
p.args.stdout_mode = Subprocess::kDevNull;
p.args.stderr_mode = Subprocess::kDevNull;
p.args.input = GenLargeString();
EXPECT_TRUE(p.Call());
EXPECT_EQ(p.status(), Subprocess::kExited);
EXPECT_EQ(p.returncode(), 0);
}
TEST(SubprocessTest, StdinWriteStall) {
// 'sh -c' is to avoid closing stdin (sleep closes it before sleeping).
// This causes a situation where the write on the stdin will stall because
// nobody reads it and the pipe buffer fills up. In this situation we should
// still handle the timeout properly.
Subprocess p({"sh", "-c", "sleep 10"});
p.args.stdout_mode = Subprocess::kDevNull;
p.args.stderr_mode = Subprocess::kDevNull;
p.args.input = GenLargeString();
EXPECT_FALSE(p.Call(/*timeout_ms=*/10));
EXPECT_EQ(p.status(), Subprocess::kKilledBySignal);
}
TEST(SubprocessTest, StartAndWait) {
Subprocess p({"sleep", "1000"});
p.Start();
EXPECT_EQ(p.Poll(), Subprocess::kRunning);
p.KillAndWaitForTermination();
EXPECT_EQ(p.status(), Subprocess::kKilledBySignal);
EXPECT_EQ(p.Poll(), Subprocess::kKilledBySignal);
EXPECT_EQ(p.returncode(), 128 + SIGKILL);
}
TEST(SubprocessTest, PollBehavesProperly) {
Subprocess p({"sh", "-c", "echo foobar"});
p.args.stdout_mode = Subprocess::kBuffer;
p.args.input = "ignored";
p.Start();
// Here we use kill() as a way to tell if the process is still running.
// SIGWINCH is ignored by default.
while (kill(p.pid(), SIGWINCH) == 0) {
usleep(1000);
}
// At this point Poll() must detect the termination.
EXPECT_EQ(p.Poll(), Subprocess::kExited);
EXPECT_EQ(p.returncode(), 0);
}
// Test the case of passing a lambda in |entrypoint| but no cmd.c
TEST(SubprocessTest, Entrypoint) {
Subprocess p;
p.args.input = "ping\n";
p.args.stdout_mode = Subprocess::kBuffer;
p.args.entrypoint_for_testing = [] {
char buf[32]{};
PERFETTO_CHECK(fgets(buf, sizeof(buf), stdin));
PERFETTO_CHECK(strcmp(buf, "ping\n") == 0);
printf("pong\n");
fflush(stdout);
_exit(42);
};
EXPECT_FALSE(p.Call());
EXPECT_EQ(p.returncode(), 42);
EXPECT_EQ(p.output(), "pong\n");
}
// Test the case of passing both a lambda entrypoint and a process to exec.
TEST(SubprocessTest, EntrypointAndExec) {
base::Pipe pipe1 = base::Pipe::Create();
base::Pipe pipe2 = base::Pipe::Create();
int pipe1_wr = *pipe1.wr;
int pipe2_wr = *pipe2.wr;
Subprocess p({"echo", "123"});
p.args.stdout_mode = Subprocess::kBuffer;
p.args.preserve_fds.push_back(pipe2_wr);
p.args.entrypoint_for_testing = [pipe1_wr, pipe2_wr] {
base::ignore_result(write(pipe1_wr, "fail", 4));
base::ignore_result(write(pipe2_wr, "pass", 4));
};
p.Start();
pipe1.wr.reset();
pipe2.wr.reset();
char buf[8];
EXPECT_LE(read(*pipe1.rd, buf, sizeof(buf)), 0);
EXPECT_EQ(read(*pipe2.rd, buf, sizeof(buf)), 4);
buf[4] = '\0';
EXPECT_STREQ(buf, "pass");
EXPECT_TRUE(p.Wait());
EXPECT_EQ(p.status(), Subprocess::kExited);
EXPECT_EQ(p.output(), "123\n");
}
TEST(SubprocessTest, Wait) {
Subprocess p({"sleep", "10000"});
p.Start();
for (int i = 0; i < 3; i++) {
EXPECT_FALSE(p.Wait(1 /*ms*/));
EXPECT_EQ(p.status(), Subprocess::kRunning);
}
kill(p.pid(), SIGBUS);
EXPECT_TRUE(p.Wait(30000 /*ms*/));
EXPECT_TRUE(p.Wait()); // Should be a no-op.
EXPECT_EQ(p.status(), Subprocess::kKilledBySignal);
EXPECT_EQ(p.returncode(), 128 + SIGBUS);
}
TEST(SubprocessTest, KillOnDtor) {
// Here we use kill(SIGWINCH) as a way to tell if the process is still alive.
// SIGWINCH is one of the few signals that has default ignore disposition.
int pid;
{
Subprocess p({"sleep", "10000"});
p.Start();
pid = p.pid();
EXPECT_EQ(kill(pid, SIGWINCH), 0);
}
EXPECT_EQ(kill(pid, SIGWINCH), -1);
}
} // namespace
} // namespace base
} // namespace perfetto
#endif // PERFETTO_HAS_SUBPROCESS()
<commit_msg>Disable PollBehavesProperly. am: 1c5e512582<commit_after>/*
* Copyright (C) 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "perfetto/ext/base/subprocess.h"
#if PERFETTO_HAS_SUBPROCESS()
#include <thread>
#include <signal.h>
#include <sys/stat.h>
#include <unistd.h>
#include "perfetto/ext/base/file_utils.h"
#include "perfetto/ext/base/temp_file.h"
#include "test/gtest_and_gmock.h"
namespace perfetto {
namespace base {
namespace {
std::string GenLargeString() {
std::string contents;
for (int i = 0; i < 4096; i++) {
contents += "very long text " + std::to_string(i) + "\n";
}
// Make sure that |contents| is > the default pipe buffer on Linux (4 pages).
PERFETTO_DCHECK(contents.size() > 4096 * 4);
return contents;
}
TEST(SubprocessTest, InvalidPath) {
Subprocess p({"/usr/bin/invalid_1337"});
EXPECT_FALSE(p.Call());
EXPECT_EQ(p.status(), Subprocess::kExited);
EXPECT_EQ(p.returncode(), 128);
EXPECT_EQ(p.output(), "execve() failed\n");
}
TEST(SubprocessTest, StdoutOnly) {
Subprocess p({"sh", "-c", "(echo skip_err >&2); echo out_only"});
p.args.stdout_mode = Subprocess::kBuffer;
p.args.stderr_mode = Subprocess::kDevNull;
EXPECT_TRUE(p.Call());
EXPECT_EQ(p.status(), Subprocess::kExited);
EXPECT_EQ(p.output(), "out_only\n");
}
TEST(SubprocessTest, StderrOnly) {
Subprocess p({"sh", "-c", "(echo err_only >&2); echo skip_out"});
p.args.stdout_mode = Subprocess::kDevNull;
p.args.stderr_mode = Subprocess::kBuffer;
EXPECT_TRUE(p.Call());
EXPECT_EQ(p.output(), "err_only\n");
}
TEST(SubprocessTest, BothStdoutAndStderr) {
Subprocess p({"sh", "-c", "echo out; (echo err >&2); echo out2"});
p.args.stdout_mode = Subprocess::kBuffer;
p.args.stderr_mode = Subprocess::kBuffer;
EXPECT_TRUE(p.Call());
EXPECT_EQ(p.output(), "out\nerr\nout2\n");
}
TEST(SubprocessTest, BinTrue) {
Subprocess p({"true"});
EXPECT_TRUE(p.Call());
EXPECT_EQ(p.status(), Subprocess::kExited);
EXPECT_EQ(p.returncode(), 0);
}
TEST(SubprocessTest, BinFalse) {
Subprocess p({"false"});
EXPECT_FALSE(p.Call());
EXPECT_EQ(p.status(), Subprocess::kExited);
EXPECT_EQ(p.returncode(), 1);
}
TEST(SubprocessTest, Echo) {
Subprocess p({"echo", "-n", "foobar"});
p.args.stdout_mode = Subprocess::kBuffer;
EXPECT_TRUE(p.Call());
EXPECT_EQ(p.status(), Subprocess::kExited);
EXPECT_EQ(p.returncode(), 0);
EXPECT_EQ(p.output(), "foobar");
}
TEST(SubprocessTest, FeedbackLongInput) {
std::string contents = GenLargeString();
Subprocess p({"cat", "-"});
p.args.stdout_mode = Subprocess::kBuffer;
p.args.input = contents;
EXPECT_TRUE(p.Call());
EXPECT_EQ(p.status(), Subprocess::kExited);
EXPECT_EQ(p.returncode(), 0);
EXPECT_EQ(p.output(), contents);
}
TEST(SubprocessTest, CatLargeFile) {
std::string contents = GenLargeString();
TempFile tf = TempFile::Create();
WriteAll(tf.fd(), contents.data(), contents.size());
FlushFile(tf.fd());
Subprocess p({"cat", tf.path().c_str()});
p.args.stdout_mode = Subprocess::kBuffer;
EXPECT_TRUE(p.Call());
EXPECT_EQ(p.output(), contents);
}
TEST(SubprocessTest, Timeout) {
Subprocess p({"sleep", "60"});
EXPECT_FALSE(p.Call(/*timeout_ms=*/1));
EXPECT_EQ(p.status(), Subprocess::kKilledBySignal);
}
TEST(SubprocessTest, TimeoutNotHit) {
Subprocess p({"sleep", "0.01"});
EXPECT_TRUE(p.Call(/*timeout_ms=*/100000));
}
TEST(SubprocessTest, TimeoutStopOutput) {
Subprocess p({"sh", "-c", "while true; do echo stuff; done"});
p.args.stdout_mode = Subprocess::kDevNull;
EXPECT_FALSE(p.Call(/*timeout_ms=*/10));
EXPECT_EQ(p.status(), Subprocess::kKilledBySignal);
}
TEST(SubprocessTest, ExitBeforeReadingStdin) {
// 'sh -c' is to avoid closing stdin (sleep closes it before sleeping).
Subprocess p({"sh", "-c", "sleep 0.01"});
p.args.stdout_mode = Subprocess::kDevNull;
p.args.stderr_mode = Subprocess::kDevNull;
p.args.input = GenLargeString();
EXPECT_TRUE(p.Call());
EXPECT_EQ(p.status(), Subprocess::kExited);
EXPECT_EQ(p.returncode(), 0);
}
TEST(SubprocessTest, StdinWriteStall) {
// 'sh -c' is to avoid closing stdin (sleep closes it before sleeping).
// This causes a situation where the write on the stdin will stall because
// nobody reads it and the pipe buffer fills up. In this situation we should
// still handle the timeout properly.
Subprocess p({"sh", "-c", "sleep 10"});
p.args.stdout_mode = Subprocess::kDevNull;
p.args.stderr_mode = Subprocess::kDevNull;
p.args.input = GenLargeString();
EXPECT_FALSE(p.Call(/*timeout_ms=*/10));
EXPECT_EQ(p.status(), Subprocess::kKilledBySignal);
}
TEST(SubprocessTest, StartAndWait) {
Subprocess p({"sleep", "1000"});
p.Start();
EXPECT_EQ(p.Poll(), Subprocess::kRunning);
p.KillAndWaitForTermination();
EXPECT_EQ(p.status(), Subprocess::kKilledBySignal);
EXPECT_EQ(p.Poll(), Subprocess::kKilledBySignal);
EXPECT_EQ(p.returncode(), 128 + SIGKILL);
}
#if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID) && defined(ADDRESS_SANITIZER)
#define MAYBE_PollBehavesProperly DISABLED_PollBehavesProperly
#else
#define MAYBE_PollBehavesProperly PollBehavesProperly
#endif
// TODO(b/158484911): Re-enable once problem is fixed.
TEST(SubprocessTest, MAYBE_PollBehavesProperly) {
Subprocess p({"sh", "-c", "echo foobar"});
p.args.stdout_mode = Subprocess::kBuffer;
p.args.input = "ignored";
p.Start();
// Here we use kill() as a way to tell if the process is still running.
// SIGWINCH is ignored by default.
while (kill(p.pid(), SIGWINCH) == 0) {
usleep(1000);
}
// At this point Poll() must detect the termination.
EXPECT_EQ(p.Poll(), Subprocess::kExited);
EXPECT_EQ(p.returncode(), 0);
}
// Test the case of passing a lambda in |entrypoint| but no cmd.c
TEST(SubprocessTest, Entrypoint) {
Subprocess p;
p.args.input = "ping\n";
p.args.stdout_mode = Subprocess::kBuffer;
p.args.entrypoint_for_testing = [] {
char buf[32]{};
PERFETTO_CHECK(fgets(buf, sizeof(buf), stdin));
PERFETTO_CHECK(strcmp(buf, "ping\n") == 0);
printf("pong\n");
fflush(stdout);
_exit(42);
};
EXPECT_FALSE(p.Call());
EXPECT_EQ(p.returncode(), 42);
EXPECT_EQ(p.output(), "pong\n");
}
// Test the case of passing both a lambda entrypoint and a process to exec.
TEST(SubprocessTest, EntrypointAndExec) {
base::Pipe pipe1 = base::Pipe::Create();
base::Pipe pipe2 = base::Pipe::Create();
int pipe1_wr = *pipe1.wr;
int pipe2_wr = *pipe2.wr;
Subprocess p({"echo", "123"});
p.args.stdout_mode = Subprocess::kBuffer;
p.args.preserve_fds.push_back(pipe2_wr);
p.args.entrypoint_for_testing = [pipe1_wr, pipe2_wr] {
base::ignore_result(write(pipe1_wr, "fail", 4));
base::ignore_result(write(pipe2_wr, "pass", 4));
};
p.Start();
pipe1.wr.reset();
pipe2.wr.reset();
char buf[8];
EXPECT_LE(read(*pipe1.rd, buf, sizeof(buf)), 0);
EXPECT_EQ(read(*pipe2.rd, buf, sizeof(buf)), 4);
buf[4] = '\0';
EXPECT_STREQ(buf, "pass");
EXPECT_TRUE(p.Wait());
EXPECT_EQ(p.status(), Subprocess::kExited);
EXPECT_EQ(p.output(), "123\n");
}
TEST(SubprocessTest, Wait) {
Subprocess p({"sleep", "10000"});
p.Start();
for (int i = 0; i < 3; i++) {
EXPECT_FALSE(p.Wait(1 /*ms*/));
EXPECT_EQ(p.status(), Subprocess::kRunning);
}
kill(p.pid(), SIGBUS);
EXPECT_TRUE(p.Wait(30000 /*ms*/));
EXPECT_TRUE(p.Wait()); // Should be a no-op.
EXPECT_EQ(p.status(), Subprocess::kKilledBySignal);
EXPECT_EQ(p.returncode(), 128 + SIGBUS);
}
TEST(SubprocessTest, KillOnDtor) {
// Here we use kill(SIGWINCH) as a way to tell if the process is still alive.
// SIGWINCH is one of the few signals that has default ignore disposition.
int pid;
{
Subprocess p({"sleep", "10000"});
p.Start();
pid = p.pid();
EXPECT_EQ(kill(pid, SIGWINCH), 0);
}
EXPECT_EQ(kill(pid, SIGWINCH), -1);
}
} // namespace
} // namespace base
} // namespace perfetto
#endif // PERFETTO_HAS_SUBPROCESS()
<|endoftext|> |
<commit_before>/*
* mp3stream - encode /dev/dsp and send it to a shoutcast server
* 2005 - bl0rg.net - public domain
*
* mp3stream.cc - main file, contains command-line option decoding and
* mainloop.
*/
#include <assert.h>
#include <unistd.h>
#include <iostream>
#include <list>
#include <string>
#include <map>
using namespace std;
#include "Error.h"
#include "AudioCard.h"
#include "Streamer.h"
#include "Url.h"
#include "LameEncoder.h"
static const string usageString =
"Usage:\n\n"
"mp3stream [-h] [-b bitrate] [-n name] [-g genre] [-p publicstr]\n"
" [-d description] [-c contentid] [-u url] [-t streamurl] [-v]\n\n"
"-b bitrate: set the bitrate of the stream in kbps (default 128 kbps)\n"
"-v: show visual feedback while encoding\n\n"
"To send streams to multiple url, specify one or more streamurls.\n"
"The stream description will consist of the last parameters given.\n"
"For example: \n\n"
"mp3stream -b 128 -n \"128 kbps\" -t xaudio://localhost:8001/stream128 \n"
" -b 64 -n \"64 kbps\" -t xaudio://localhost:8001/stream64\n\n"
"will send a 128 kbps encoded stream to the icecast server under the\n"
"mountpoint /stream128 and a 64 kbps encoded stream to the icecast server\n"
"under the mountpoint /stream64.\n\n"
"mp3stream can also log the encoded data to a file by using a file:/// URL.\n"
"For example: \n\n"
"mp3stream -b 128 -n \"128 kbps\" -t xaudio://localhost/bla -t file:///var/mp3-log.mp3\n\n"
"will send the 128 kbps encoded data to localhost and log it into mp3-log.mp3.\n";
static void usage(const char *program) {
cerr << usageString;
}
int main(int argc, char *argv[]) {
if (argc < 2) {
usage(argv[0]);
return 1;
}
unsigned long bitrate = 128;
string name = "";
string genre = "";
string publicStr = "";
string description = "";
string url = "";
string contentid = "";
list<Streamer *> streamerList;
int retval = 0;
bool bDisplay = false;
int c;
while ((c = getopt(argc, argv, "hb:n:g:p:d:c:u:t:v")) >= 0) {
switch (c) {
case 'h':
usage(argv[0]);
return 0;
case 'v':
bDisplay = true;
break;
case 'b':
bitrate = atoi(optarg);
break;
case 'n':
name = string(optarg);
break;
case 'g':
genre = string(optarg);
break;
case 'p':
publicStr = string(optarg);
break;
case 'd':
description = string(optarg);
break;
case 'c':
contentid = string(optarg);
break;
case 'u':
url = string(optarg);
break;
case 't':
try {
Stream stream(bitrate, name, genre, url,
publicStr, description, contentid);
Url streamUrl(optarg);
Streamer *streamer = new Streamer(stream, streamUrl);
streamerList.push_front(streamer);
} catch (Error &e) {
cerr << "Could not parse URL \"" << optarg << "\": "
<< e.getMessage() << endl;
retval = 1;
goto exit;
}
break;
default:
cerr << "Unknown switch " << c << endl;
usage(argv[0]);
return 1;
}
}
try {
AudioCard *audioCard = NULL;
map<LameEncoder *,list<Streamer *> > encoderMap;
try {
audioCard = new AudioCard(false);
} catch (AudioError &e) {
cerr << "Could not initialize soundcard: " << e.getMessage() << endl;
retval = 1;
goto exit;
}
for (list<Streamer *>::iterator pStreamer = streamerList.begin();
pStreamer != streamerList.end(); pStreamer++) {
Streamer &streamer = *(*pStreamer);
unsigned long bitrate = streamer.getBitrate();
map<LameEncoder *,list<Streamer *> >::iterator p;
for (p = encoderMap.begin();
p != encoderMap.end(); p++) {
const LameEncoder &encoder = *(p->first);
list<Streamer *> &listStreamer = p->second;
if (encoder.getBitrate() == bitrate) {
listStreamer.push_back((*pStreamer));
break;
}
}
if (p == encoderMap.end()) {
try {
LameEncoder *encoder = new LameEncoder(*audioCard, bitrate);
list<Streamer *> &listStreamer = encoderMap[encoder];
listStreamer.push_back((*pStreamer));
} catch (LameError &e) {
cerr << "Could not create an encoder with " << bitrate << " kbps: "
<< endl
<< " " << e.getMessage() << endl;
retval = 1;
goto cleanup;
}
}
}
/* Print information about setup */
cerr << endl
<< "Streaming setup:" << endl
<< "----------------" << endl;
for (map<LameEncoder *,list<Streamer *> >::iterator p = encoderMap.begin();
p != encoderMap.end(); p++) {
LameEncoder *encoder = p->first;
list<Streamer *> &l = p->second;
cerr << "Streaming " << encoder->getBitrate()
<< " kbps stream to: " << endl;
for (list<Streamer *>::iterator pStreamer = l.begin();
pStreamer != l.end(); pStreamer++) {
cerr << " " << (*pStreamer)->getUrl()
<< " " << (*pStreamer)->getInfo() << endl;
}
cerr << endl;
}
for (list<Streamer *>::iterator pStreamer = streamerList.begin();
pStreamer != streamerList.end(); pStreamer++) {
Streamer &streamer = *(*pStreamer);
cerr << "Logging in to " << streamer.getUrl() << "... ";
try {
streamer.Login();
} catch (Error &e) {
cerr << endl;
cerr << " " << e.getMessage() << endl;
retval = 1;
goto cleanup;
}
cerr << "OK" << endl;
}
cerr << "Streaming..." << endl;
/* main loop */
static short buf[rawDataBlockSize / 2];
static unsigned char mp3Buf[rawDataBlockSize];
for (;;) {
audioCard->Read(buf);
static int count = 0;
if (bDisplay && ((count++ % 300) == 0)) {
unsigned short maxVol = 0;
for (unsigned int i = 0; i < rawDataBlockSize / 2; i++) {
if (abs(buf[i]) > maxVol)
maxVol = abs(buf[i]);
}
cout << "\r ";
if (maxVol > 32000) {
cout << "\r*clip*";
} else {
cout << "\r=";
for (unsigned short j = 0; j <= maxVol; j += 500)
cout << "=";
}
cout.flush();
}
for (map<LameEncoder *,list<Streamer *> >::iterator p = encoderMap.begin();
p != encoderMap.end(); p++) {
LameEncoder *encoder = p->first;
list<Streamer *> &l = p->second;
int ret = encoder->EncodeBuffer(buf, sizeof(buf),
mp3Buf, sizeof(mp3Buf));
if (ret > 0) {
for (list<Streamer *>::iterator pStreamer = l.begin();
pStreamer != l.end(); pStreamer++) {
Streamer &streamer = *(*pStreamer);
streamer.Write(mp3Buf, ret);
}
}
}
}
cleanup:
for (map<LameEncoder *,list<Streamer *> >::iterator p = encoderMap.begin();
p != encoderMap.end(); p++) {
LameEncoder *encoder = p->first;
delete encoder;
}
delete audioCard;
} catch (Error &e) {
cerr << e.getMessage() << endl;
retval = 1;
goto exit;
}
exit:
for (list<Streamer *>::iterator pStreamer = streamerList.begin();
pStreamer != streamerList.end(); pStreamer++) {
delete (*pStreamer);
}
return retval;
}
<commit_msg>faster display, and send correct size of buf to lame<commit_after>/*
* mp3stream - encode /dev/dsp and send it to a shoutcast server
* 2005 - bl0rg.net - public domain
*
* mp3stream.cc - main file, contains command-line option decoding and
* mainloop.
*/
#include <assert.h>
#include <unistd.h>
#include <iostream>
#include <list>
#include <string>
#include <map>
using namespace std;
#include "Error.h"
#include "AudioCard.h"
#include "Streamer.h"
#include "Url.h"
#include "LameEncoder.h"
static const string usageString =
"Usage:\n\n"
"mp3stream [-h] [-b bitrate] [-n name] [-g genre] [-p publicstr]\n"
" [-d description] [-c contentid] [-u url] [-t streamurl] [-v]\n\n"
"-b bitrate: set the bitrate of the stream in kbps (default 128 kbps)\n"
"-v: show visual feedback while encoding\n\n"
"To send streams to multiple url, specify one or more streamurls.\n"
"The stream description will consist of the last parameters given.\n"
"For example: \n\n"
"mp3stream -b 128 -n \"128 kbps\" -t xaudio://localhost:8001/stream128 \n"
" -b 64 -n \"64 kbps\" -t xaudio://localhost:8001/stream64\n\n"
"will send a 128 kbps encoded stream to the icecast server under the\n"
"mountpoint /stream128 and a 64 kbps encoded stream to the icecast server\n"
"under the mountpoint /stream64.\n\n"
"mp3stream can also log the encoded data to a file by using a file:/// URL.\n"
"For example: \n\n"
"mp3stream -b 128 -n \"128 kbps\" -t xaudio://localhost/bla -t file:///var/mp3-log.mp3\n\n"
"will send the 128 kbps encoded data to localhost and log it into mp3-log.mp3.\n";
static void usage(const char *program) {
cerr << usageString;
}
int main(int argc, char *argv[]) {
if (argc < 2) {
usage(argv[0]);
return 1;
}
unsigned long bitrate = 128;
string name = "";
string genre = "";
string publicStr = "";
string description = "";
string url = "";
string contentid = "";
list<Streamer *> streamerList;
int retval = 0;
bool bDisplay = false;
int c;
while ((c = getopt(argc, argv, "hb:n:g:p:d:c:u:t:v")) >= 0) {
switch (c) {
case 'h':
usage(argv[0]);
return 0;
case 'v':
bDisplay = true;
break;
case 'b':
bitrate = atoi(optarg);
break;
case 'n':
name = string(optarg);
break;
case 'g':
genre = string(optarg);
break;
case 'p':
publicStr = string(optarg);
break;
case 'd':
description = string(optarg);
break;
case 'c':
contentid = string(optarg);
break;
case 'u':
url = string(optarg);
break;
case 't':
try {
Stream stream(bitrate, name, genre, url,
publicStr, description, contentid);
Url streamUrl(optarg);
Streamer *streamer = new Streamer(stream, streamUrl);
streamerList.push_front(streamer);
} catch (Error &e) {
cerr << "Could not parse URL \"" << optarg << "\": "
<< e.getMessage() << endl;
retval = 1;
goto exit;
}
break;
default:
cerr << "Unknown switch " << c << endl;
usage(argv[0]);
return 1;
}
}
try {
AudioCard *audioCard = NULL;
map<LameEncoder *,list<Streamer *> > encoderMap;
try {
audioCard = new AudioCard(false);
} catch (AudioError &e) {
cerr << "Could not initialize soundcard: " << e.getMessage() << endl;
retval = 1;
goto exit;
}
for (list<Streamer *>::iterator pStreamer = streamerList.begin();
pStreamer != streamerList.end(); pStreamer++) {
Streamer &streamer = *(*pStreamer);
unsigned long bitrate = streamer.getBitrate();
map<LameEncoder *,list<Streamer *> >::iterator p;
for (p = encoderMap.begin();
p != encoderMap.end(); p++) {
const LameEncoder &encoder = *(p->first);
list<Streamer *> &listStreamer = p->second;
if (encoder.getBitrate() == bitrate) {
listStreamer.push_back((*pStreamer));
break;
}
}
if (p == encoderMap.end()) {
try {
LameEncoder *encoder = new LameEncoder(*audioCard, bitrate);
list<Streamer *> &listStreamer = encoderMap[encoder];
listStreamer.push_back((*pStreamer));
} catch (LameError &e) {
cerr << "Could not create an encoder with " << bitrate << " kbps: "
<< endl
<< " " << e.getMessage() << endl;
retval = 1;
goto cleanup;
}
}
}
/* Print information about setup */
cerr << endl
<< "Streaming setup:" << endl
<< "----------------" << endl;
for (map<LameEncoder *,list<Streamer *> >::iterator p = encoderMap.begin();
p != encoderMap.end(); p++) {
LameEncoder *encoder = p->first;
list<Streamer *> &l = p->second;
cerr << "Streaming " << encoder->getBitrate()
<< " kbps stream to: " << endl;
for (list<Streamer *>::iterator pStreamer = l.begin();
pStreamer != l.end(); pStreamer++) {
cerr << " " << (*pStreamer)->getUrl()
<< " " << (*pStreamer)->getInfo() << endl;
}
cerr << endl;
}
for (list<Streamer *>::iterator pStreamer = streamerList.begin();
pStreamer != streamerList.end(); pStreamer++) {
Streamer &streamer = *(*pStreamer);
cerr << "Logging in to " << streamer.getUrl() << "... ";
try {
streamer.Login();
} catch (Error &e) {
cerr << endl;
cerr << " " << e.getMessage() << endl;
retval = 1;
goto cleanup;
}
cerr << "OK" << endl;
}
cerr << "Streaming..." << endl;
/* main loop */
static short buf[rawDataBlockSize / 2];
static unsigned char mp3Buf[rawDataBlockSize];
for (;;) {
audioCard->Read(buf);
static int count = 0;
if (bDisplay && ((count++ % 5) == 0)) {
unsigned short maxVol = 0;
for (unsigned int i = 0; i < rawDataBlockSize / 2; i++) {
if (abs(buf[i]) > maxVol)
maxVol = abs(buf[i]);
}
cout << "\r ";
if (maxVol > 32000) {
cout << "\r*clip*";
} else {
cout << "\r=";
for (unsigned short j = 0; j <= maxVol; j += 500)
cout << "=";
}
cout.flush();
}
for (map<LameEncoder *,list<Streamer *> >::iterator p = encoderMap.begin();
p != encoderMap.end(); p++) {
LameEncoder *encoder = p->first;
list<Streamer *> &l = p->second;
int ret = encoder->EncodeBuffer(buf, rawDataBlockSize / 2,
mp3Buf, sizeof(mp3Buf));
if (ret > 0) {
for (list<Streamer *>::iterator pStreamer = l.begin();
pStreamer != l.end(); pStreamer++) {
Streamer &streamer = *(*pStreamer);
streamer.Write(mp3Buf, ret);
}
}
}
}
cleanup:
for (map<LameEncoder *,list<Streamer *> >::iterator p = encoderMap.begin();
p != encoderMap.end(); p++) {
LameEncoder *encoder = p->first;
delete encoder;
}
delete audioCard;
} catch (Error &e) {
cerr << e.getMessage() << endl;
retval = 1;
goto exit;
}
exit:
for (list<Streamer *>::iterator pStreamer = streamerList.begin();
pStreamer != streamerList.end(); pStreamer++) {
delete (*pStreamer);
}
return retval;
}
<|endoftext|> |
<commit_before>/* bzflag
* Copyright (c) 1993 - 2004 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
#include "common.h"
/* interface header */
#include "CustomDynamicColor.h"
/* system implementation headers */
#include <sstream>
/* common implementation headers */
#include "DynamicColor.h"
CustomDynamicColor::CustomDynamicColor()
{
color = new DynamicColor;
return;
}
CustomDynamicColor::~CustomDynamicColor()
{
delete color;
return;
}
bool CustomDynamicColor::read(const char *cmd, std::istream& input)
{
int channel = -1;
if (strcasecmp ("red", cmd) == 0) {
channel = 0;
}
else if (strcasecmp ("green", cmd) == 0) {
channel = 1;
}
else if (strcasecmp ("blue", cmd) == 0) {
channel = 2;
}
else if (strcasecmp ("alpha", cmd) == 0) {
channel = 3;
}
else {
// NOTE: we don't use a WorldFileObstacle
return WorldFileObject::read(cmd, input);
}
// in case WorldFileObject() at a later date
if (channel < 0) {
std::cout << "unknown color channel" << std::endl;
return false;
}
std::string args;
std::string command;
std::getline(input, args);
std::istringstream parms(args);
if (!(parms >> command)) {
std::cout << "missing parameter type for " << cmd << " channel" << std::endl;
return false;
}
if (command == "limits") {
float min, max;
if (!(parms >> min) || !(parms >> max)) {
std::cout << "missing limits for " << cmd << " channel" << std::endl;
return false;
}
color->setLimits(channel, min, max);
}
else if (command == "sinusoid") {
float period, offset;
if (!(parms >> period) || !(parms >> offset)) {
std::cout << "missing sinusoid parameters for " << cmd << " channel"
<< std::endl;
return false;
}
color->setSinusoid(channel, period, offset);
}
else if (command == "clampup") {
float period, offset, width;
if (!(parms >> period) || !(parms >> offset) || !(parms >> width)) {
std::cout << "missing clampup parameters for " << cmd << " channel"
<< std::endl;
return false;
}
color->setClampUp(channel, period, offset, width);
}
else if (command == "clampdown") {
float period, offset, width;
if (!(parms >> period) || !(parms >> offset) || !(parms >> width)) {
std::cout << "missing clampdown parameters for " << cmd << " channel"
<< std::endl;
return false;
}
color->setClampDown(channel, period, offset, width);
}
else {
return false;
}
input.putback('\n');
return true;
}
void CustomDynamicColor::write(WorldInfo * /*world*/) const
{
color->finalize();
DYNCOLORMGR.addColor (color);
color = NULL;
return;
}
// Local variables: ***
// mode: C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<commit_msg>follow along, make dynamic color keywords case insensitive<commit_after>/* bzflag
* Copyright (c) 1993 - 2004 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
#include "common.h"
/* interface header */
#include "CustomDynamicColor.h"
/* system implementation headers */
#include <sstream>
/* common implementation headers */
#include "DynamicColor.h"
CustomDynamicColor::CustomDynamicColor()
{
color = new DynamicColor;
return;
}
CustomDynamicColor::~CustomDynamicColor()
{
delete color;
return;
}
bool CustomDynamicColor::read(const char *cmd, std::istream& input)
{
int channel = -1;
if (strcasecmp ("red", cmd) == 0) {
channel = 0;
}
else if (strcasecmp ("green", cmd) == 0) {
channel = 1;
}
else if (strcasecmp ("blue", cmd) == 0) {
channel = 2;
}
else if (strcasecmp ("alpha", cmd) == 0) {
channel = 3;
}
else {
// NOTE: we don't use a WorldFileObstacle
return WorldFileObject::read(cmd, input);
}
// in case WorldFileObject() at a later date
if (channel < 0) {
std::cout << "unknown color channel" << std::endl;
return false;
}
std::string args;
std::string command;
std::getline(input, args);
std::istringstream parms(args);
if (!(parms >> command)) {
std::cout << "missing parameter type for "
<< cmd << " channel" << std::endl;
return false;
}
if (strcasecmp (command.c_str(), "limits") == 0) {
float min, max;
if (!(parms >> min) || !(parms >> max)) {
std::cout << "missing limits for " << cmd << " channel" << std::endl;
return false;
}
color->setLimits(channel, min, max);
}
else if (strcasecmp (command.c_str(), "sinusoid") == 0) {
float period, offset;
if (!(parms >> period) || !(parms >> offset)) {
std::cout << "missing sinusoid parameters for " << cmd << " channel"
<< std::endl;
return false;
}
color->setSinusoid(channel, period, offset);
}
else if (strcasecmp (command.c_str(), "clampup") == 0) {
float period, offset, width;
if (!(parms >> period) || !(parms >> offset) || !(parms >> width)) {
std::cout << "missing clampup parameters for " << cmd << " channel"
<< std::endl;
return false;
}
color->setClampUp(channel, period, offset, width);
}
else if (strcasecmp (command.c_str(), "clampdown") == 0) {
float period, offset, width;
if (!(parms >> period) || !(parms >> offset) || !(parms >> width)) {
std::cout << "missing clampdown parameters for " << cmd << " channel"
<< std::endl;
return false;
}
color->setClampDown(channel, period, offset, width);
}
else {
return false;
}
input.putback('\n');
return true;
}
void CustomDynamicColor::write(WorldInfo * /*world*/) const
{
color->finalize();
DYNCOLORMGR.addColor (color);
color = NULL;
return;
}
// Local variables: ***
// mode: C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<|endoftext|> |
<commit_before>/**
* Copyright (C) 2003-2006 Funambol
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*/
#include "base/util/utils.h"
#include "base/util/WString.h"
#include "base/Log.h"
#include "vocl/VObject.h"
#include "string.h"
VObject::VObject() {
productID = NULL;
version = NULL;
properties = new ArrayList();
}
VObject::~VObject() {
if (productID) {
delete [] productID; productID = NULL;
}
if (version) {
delete [] version; version = NULL;
}
if (properties) {
delete properties; properties = NULL;
}
}
void VObject::set(wchar_t** p, wchar_t* v) {
if (*p) {
delete [] *p;
}
*p = (v) ? wstrdup(v) : NULL;
}
void VObject::setVersion(wchar_t* ver) {
set(&version, ver);
}
void VObject::setProdID(wchar_t* prodID) {
set(&productID, prodID);
}
wchar_t* VObject::getVersion() {
return version;
}
wchar_t* VObject::getProdID() {
return productID;
}
void VObject::addProperty(VProperty* vProp) {
properties->add((ArrayElement&) *vProp);
}
int VObject::propertiesCount() {
return properties->size();
}
bool VObject::removeProperty(int index) {
if(index < 0 || index >= propertiesCount())
return false;
properties->remove(index);
return true;
}
void VObject::removeProperty(wchar_t* propName) {
for (int i=0; i<properties->size(); i++) {
VProperty *property;
property = (VProperty* )properties->get(i);
if(!wcscmp(property->getName(), propName)) {
properties->remove(i);
break;
}
}
}
bool VObject::containsProperty(wchar_t* propName) {
for (int i=0; i<properties->size(); i++) {
VProperty *property;
property = (VProperty* )properties->get(i);
if(!wcscmp(property->getName(), propName)) {
return true;
}
}
return false;
}
VProperty* VObject::getProperty(int index) {
return (VProperty*)properties->get(index);
}
VProperty* VObject::getProperty(wchar_t* propName) {
for (int i=0; i<properties->size(); i++) {
VProperty *property;
property = (VProperty* )properties->get(i);
if(!wcscmp(property->getName(), propName)) {
return property;
}
}
return NULL;
}
wchar_t* VObject::toString() {
WString strVObject;
const wchar_t* eof;
if(version && !wcscmp(version,TEXT("3.0")))
eof = TEXT("\n");
else
eof = TEXT("\r\n");
// let's reserve some space to avoid reallocation in most cases
strVObject.reserve(5000);
for (int i=0; i<properties->size(); i++) {
VProperty *property;
property = (VProperty*)properties->get(i);
if(property->containsParameter(TEXT("GROUP"))) {
strVObject.append(property->getParameterValue(TEXT("GROUP")));
strVObject.append(TEXT("."));
property->removeParameter(TEXT("GROUP"));
}
strVObject.append(property->getName());
for(int k=0; k<property->parameterCount(); k++) {
strVObject.append(TEXT(";"));
wchar_t* paramName = new wchar_t[wcslen(property->getParameter(k))+1];
wcscpy(paramName, property->getParameter(k));
strVObject.append(paramName);
const wchar_t *value = property->getParameterValue(k);
if(value) {
strVObject.append(TEXT("="));
strVObject.append(value);
}
delete [] paramName; paramName = NULL;
}
strVObject.append(TEXT(":"));
if(property->getValue()) {
if(property->equalsEncoding(TEXT("BASE64"))) {
wchar_t delim[] = TEXT("\r\n ");
int fold = 76;
int sizeOfValue = int(wcslen(property->getValue()));
int size = sizeOfValue + (int)(sizeOfValue/fold + 2)*int(wcslen(delim));
int index = 0;
wchar_t* output = new wchar_t[size + 1];
wcscpy(output, TEXT("\0"));
while (index<sizeOfValue)
{
wcscat(output,delim);
wcsncat(output,property->getValue()+index,fold);
index+=fold;
}
strVObject.append(output);
// the extra empty line is needed because the Bachus-Naur
// specification of vCard 2.1 says so
strVObject.append(eof);
delete [] output;
}
else
strVObject.append(property->getValue());
}
strVObject.append(eof);
}
// memory must be free by caller with delete []
wchar_t *str = wstrdup(strVObject);
return str;
}
void VObject::insertProperty(VProperty* property) {
if (propertiesCount() == 0 || wcscmp(getProperty(propertiesCount()-1)->getName(),TEXT("END")))
addProperty(property);
else {
VProperty* lastProperty = getProperty(TEXT("END"));
removeProperty(TEXT("END"));
addProperty(property);
addProperty(lastProperty);
}
}
void VObject::addFirstProperty(VProperty* property) {
properties->add(0,(ArrayElement&)*property);
}
void VObject::removeAllProperies(wchar_t* propName) {
for(int i = 0, m = propertiesCount(); i < m ; i++)
if(!wcscmp(getProperty(i)->getName(), propName)) {
removeProperty(i);
--i;
--m;
}
}
// Patrick Ohly: hack below, see header file
static int hex2int( wchar_t x )
{
return (x >= '0' && x <= '9') ? x - '0' :
(x >= 'A' && x <= 'F') ? x - 'A' + 10 :
(x >= 'a' && x <= 'f') ? x - 'a' + 10 :
0;
}
#define SEMICOLON_REPLACEMENT '\a'
void VObject::toNativeEncoding()
{
BOOL is_30 = !wcscmp(getVersion(), TEXT("3.0"));
// line break is encoded with either one or two
// characters on different platforms
const int linebreaklen = wcslen(SYNC4J_LINEBREAK);
for (int index = propertiesCount() - 1; index >= 0; index--) {
VProperty *vprop = getProperty(index);
wchar_t *foreign = vprop->getValue();
// the native encoding is always shorter than the foreign one
wchar_t *native = new wchar_t[wcslen(foreign) + 1];
if (vprop->equalsEncoding(TEXT("QUOTED-PRINTABLE"))) {
int in = 0, out = 0;
wchar_t curr;
// this is a very crude quoted-printable decoder,
// based on Wikipedia's explanation of quoted-printable
while ((curr = foreign[in]) != 0) {
in++;
if (curr == '=') {
wchar_t values[2];
values[0] = foreign[in];
in++;
if (!values[0]) {
// incomplete?!
break;
}
values[1] = foreign[in];
in++;
if (values[0] == '\r' && values[1] == '\n') {
// soft line break, ignore it
} else {
native[out] = (hex2int(values[0]) << 4) |
hex2int(values[1]);
out++;
// replace \r\n with \n?
if ( linebreaklen == 1 &&
out >= 2 &&
native[out - 2] == '\r' &&
native[out - 1] == '\n' ) {
native[out - 2] = SYNC4J_LINEBREAK[0];
out--;
}
// the conversion to wchar on Windows is
// probably missing here
}
} else {
native[out] = curr;
out++;
}
}
native[out] = 0;
out++;
} else {
wcscpy(native, foreign);
}
// decode escaped characters after backslash:
// \n is line break only in 3.0
wchar_t curr;
int in = 0, out = 0;
while ((curr = native[in]) != 0) {
in++;
switch (curr) {
case '\\':
curr = native[in];
in++;
switch (curr) {
case 'n':
if (is_30) {
// replace with line break
wcsncpy(native + out, SYNC4J_LINEBREAK, linebreaklen);
out += linebreaklen;
} else {
// normal escaped character
native[out] = curr;
out++;
}
break;
case 0:
// unexpected end of string
break;
default:
// just copy next character
native[out] = curr;
out++;
break;
}
break;
case ';':
// field separator - must replace with something special
// so that we can encode it again in fromNativeEncoding()
native[out] = SEMICOLON_REPLACEMENT;
out++;
break;
default:
native[out] = curr;
out++;
}
}
native[out] = 0;
out++;
// charset handling:
// - doesn't exist at the moment, vCards have to be in ASCII or UTF-8
// - an explicit CHARSET parameter is removed because its parameter
// value might differ between 2.1 and 3.0 (quotation marks allowed in
// 3.0 but not 2.1) and thus would require extra code to convert it;
// when charsets really get supported this needs to be addressed
wchar_t *charset = vprop->getParameterValue(TEXT("CHARSET"));
if (charset) {
// proper decoding of the value and the property value text
// would go here, for the time being we just remove the
// value
if (wcsicmp(charset, TEXT("UTF-8")) &&
wcsicmp(charset, TEXT("\"UTF-8\""))) {
LOG.error("ignoring unsupported charset");
}
vprop->removeParameter(TEXT("CHARSET"));
}
vprop->setValue(native);
delete [] native;
}
}
void VObject::fromNativeEncoding()
{
BOOL is_30 = !wcscmp(getVersion(), TEXT("3.0"));
for (int index = propertiesCount() - 1; index >= 0; index--) {
VProperty *vprop = getProperty(index);
if (vprop->equalsEncoding(TEXT("QUOTED-PRINTABLE"))) {
// remove this, we cannot recreate it
vprop->removeParameter(TEXT("ENCODING"));
}
wchar_t *native = vprop->getValue();
// in the worst case every comma/linebreak is replaced with
// two characters and each \n with =0D=0A
wchar_t *foreign = new wchar_t[6 * wcslen(native) + 1];
wchar_t curr;
int in = 0, out = 0;
// line break is encoded with either one or two
// characters on different platforms
const int linebreaklen = wcslen(SYNC4J_LINEBREAK);
// use backslash for special characters,
// if necessary do quoted-printable encoding
bool doquoted = !is_30 &&
wcsstr(native, SYNC4J_LINEBREAK) != NULL;
while ((curr = native[in]) != 0) {
in++;
switch (curr) {
case ',':
if (!is_30) {
// normal character
foreign[out] = curr;
out++;
break;
}
// no break!
case ';':
case '\\':
foreign[out] = '\\';
out++;
foreign[out] = curr;
out++;
break;
case SEMICOLON_REPLACEMENT:
foreign[out] = ';';
out++;
break;
default:
if (doquoted &&
(curr == '=' || (unsigned char)curr >= 128)) {
// escape = and non-ASCII characters
wsprintf(foreign + out, TEXT("=%02X"), (unsigned int)(unsigned char)curr);
out += 3;
} else if (!wcsncmp(native + in - 1,
SYNC4J_LINEBREAK,
linebreaklen)) {
// line break
if (is_30) {
foreign[out] = '\\';
out++;
foreign[out] = 'n';
out++;
} else {
wcscpy(foreign + out, TEXT("=0D=0A"));
out += 6;
}
in += linebreaklen - 1;
} else {
foreign[out] = curr;
out++;
}
break;
}
}
foreign[out] = 0;
vprop->setValue(foreign);
delete [] foreign;
if (doquoted) {
// we have used quoted-printable encoding
vprop->addParameter(TEXT("ENCODING"), TEXT("QUOTED-PRINTABLE"));
}
}
}
<commit_msg>compatibility with VisualStudio 2005 compiler<commit_after>/**
* Copyright (C) 2003-2006 Funambol
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*/
#include "base/util/utils.h"
#include "base/util/WString.h"
#include "base/Log.h"
#include "vocl/VObject.h"
#include "string.h"
VObject::VObject() {
productID = NULL;
version = NULL;
properties = new ArrayList();
}
VObject::~VObject() {
if (productID) {
delete [] productID; productID = NULL;
}
if (version) {
delete [] version; version = NULL;
}
if (properties) {
delete properties; properties = NULL;
}
}
void VObject::set(wchar_t** p, wchar_t* v) {
if (*p) {
delete [] *p;
}
*p = (v) ? wstrdup(v) : NULL;
}
void VObject::setVersion(wchar_t* ver) {
set(&version, ver);
}
void VObject::setProdID(wchar_t* prodID) {
set(&productID, prodID);
}
wchar_t* VObject::getVersion() {
return version;
}
wchar_t* VObject::getProdID() {
return productID;
}
void VObject::addProperty(VProperty* vProp) {
properties->add((ArrayElement&) *vProp);
}
int VObject::propertiesCount() {
return properties->size();
}
bool VObject::removeProperty(int index) {
if(index < 0 || index >= propertiesCount())
return false;
properties->remove(index);
return true;
}
void VObject::removeProperty(wchar_t* propName) {
for (int i=0; i<properties->size(); i++) {
VProperty *property;
property = (VProperty* )properties->get(i);
if(!wcscmp(property->getName(), propName)) {
properties->remove(i);
break;
}
}
}
bool VObject::containsProperty(wchar_t* propName) {
for (int i=0; i<properties->size(); i++) {
VProperty *property;
property = (VProperty* )properties->get(i);
if(!wcscmp(property->getName(), propName)) {
return true;
}
}
return false;
}
VProperty* VObject::getProperty(int index) {
return (VProperty*)properties->get(index);
}
VProperty* VObject::getProperty(wchar_t* propName) {
for (int i=0; i<properties->size(); i++) {
VProperty *property;
property = (VProperty* )properties->get(i);
if(!wcscmp(property->getName(), propName)) {
return property;
}
}
return NULL;
}
wchar_t* VObject::toString() {
WString strVObject;
const wchar_t* eof;
if(version && !wcscmp(version,TEXT("3.0")))
eof = TEXT("\n");
else
eof = TEXT("\r\n");
// let's reserve some space to avoid reallocation in most cases
strVObject.reserve(5000);
for (int i=0; i<properties->size(); i++) {
VProperty *property;
property = (VProperty*)properties->get(i);
if(property->containsParameter(TEXT("GROUP"))) {
strVObject.append(property->getParameterValue(TEXT("GROUP")));
strVObject.append(TEXT("."));
property->removeParameter(TEXT("GROUP"));
}
strVObject.append(property->getName());
for(int k=0; k<property->parameterCount(); k++) {
strVObject.append(TEXT(";"));
wchar_t* paramName = new wchar_t[wcslen(property->getParameter(k))+1];
wcscpy(paramName, property->getParameter(k));
strVObject.append(paramName);
const wchar_t *value = property->getParameterValue(k);
if(value) {
strVObject.append(TEXT("="));
strVObject.append(value);
}
delete [] paramName; paramName = NULL;
}
strVObject.append(TEXT(":"));
if(property->getValue()) {
if(property->equalsEncoding(TEXT("BASE64"))) {
wchar_t delim[] = TEXT("\r\n ");
int fold = 76;
int sizeOfValue = int(wcslen(property->getValue()));
int size = sizeOfValue + (int)(sizeOfValue/fold + 2)*int(wcslen(delim));
int index = 0;
wchar_t* output = new wchar_t[size + 1];
wcscpy(output, TEXT("\0"));
while (index<sizeOfValue)
{
wcscat(output,delim);
wcsncat(output,property->getValue()+index,fold);
index+=fold;
}
strVObject.append(output);
// the extra empty line is needed because the Bachus-Naur
// specification of vCard 2.1 says so
strVObject.append(eof);
delete [] output;
}
else
strVObject.append(property->getValue());
}
strVObject.append(eof);
}
// memory must be free by caller with delete []
wchar_t *str = wstrdup(strVObject);
return str;
}
void VObject::insertProperty(VProperty* property) {
if (propertiesCount() == 0 || wcscmp(getProperty(propertiesCount()-1)->getName(),TEXT("END")))
addProperty(property);
else {
VProperty* lastProperty = getProperty(TEXT("END"));
removeProperty(TEXT("END"));
addProperty(property);
addProperty(lastProperty);
}
}
void VObject::addFirstProperty(VProperty* property) {
properties->add(0,(ArrayElement&)*property);
}
void VObject::removeAllProperies(wchar_t* propName) {
for(int i = 0, m = propertiesCount(); i < m ; i++)
if(!wcscmp(getProperty(i)->getName(), propName)) {
removeProperty(i);
--i;
--m;
}
}
// Patrick Ohly: hack below, see header file
static int hex2int( wchar_t x )
{
return (x >= '0' && x <= '9') ? x - '0' :
(x >= 'A' && x <= 'F') ? x - 'A' + 10 :
(x >= 'a' && x <= 'f') ? x - 'a' + 10 :
0;
}
#define SEMICOLON_REPLACEMENT '\a'
void VObject::toNativeEncoding()
{
BOOL is_30 = !wcscmp(getVersion(), TEXT("3.0"));
// line break is encoded with either one or two
// characters on different platforms
const int linebreaklen = wcslen(SYNC4J_LINEBREAK);
for (int index = propertiesCount() - 1; index >= 0; index--) {
VProperty *vprop = getProperty(index);
wchar_t *foreign = vprop->getValue();
// the native encoding is always shorter than the foreign one
wchar_t *native = new wchar_t[wcslen(foreign) + 1];
if (vprop->equalsEncoding(TEXT("QUOTED-PRINTABLE"))) {
int in = 0, out = 0;
wchar_t curr;
// this is a very crude quoted-printable decoder,
// based on Wikipedia's explanation of quoted-printable
while ((curr = foreign[in]) != 0) {
in++;
if (curr == '=') {
wchar_t values[2];
values[0] = foreign[in];
in++;
if (!values[0]) {
// incomplete?!
break;
}
values[1] = foreign[in];
in++;
if (values[0] == '\r' && values[1] == '\n') {
// soft line break, ignore it
} else {
native[out] = (hex2int(values[0]) << 4) |
hex2int(values[1]);
out++;
// replace \r\n with \n?
if ( linebreaklen == 1 &&
out >= 2 &&
native[out - 2] == '\r' &&
native[out - 1] == '\n' ) {
native[out - 2] = SYNC4J_LINEBREAK[0];
out--;
}
// the conversion to wchar on Windows is
// probably missing here
}
} else {
native[out] = curr;
out++;
}
}
native[out] = 0;
out++;
} else {
wcscpy(native, foreign);
}
// decode escaped characters after backslash:
// \n is line break only in 3.0
wchar_t curr;
int in = 0, out = 0;
while ((curr = native[in]) != 0) {
in++;
switch (curr) {
case '\\':
curr = native[in];
in++;
switch (curr) {
case 'n':
if (is_30) {
// replace with line break
wcsncpy(native + out, SYNC4J_LINEBREAK, linebreaklen);
out += linebreaklen;
} else {
// normal escaped character
native[out] = curr;
out++;
}
break;
case 0:
// unexpected end of string
break;
default:
// just copy next character
native[out] = curr;
out++;
break;
}
break;
case ';':
// field separator - must replace with something special
// so that we can encode it again in fromNativeEncoding()
native[out] = SEMICOLON_REPLACEMENT;
out++;
break;
default:
native[out] = curr;
out++;
}
}
native[out] = 0;
out++;
// charset handling:
// - doesn't exist at the moment, vCards have to be in ASCII or UTF-8
// - an explicit CHARSET parameter is removed because its parameter
// value might differ between 2.1 and 3.0 (quotation marks allowed in
// 3.0 but not 2.1) and thus would require extra code to convert it;
// when charsets really get supported this needs to be addressed
wchar_t *charset = vprop->getParameterValue(TEXT("CHARSET"));
if (charset) {
// proper decoding of the value and the property value text
// would go here, for the time being we just remove the
// value
if (_wcsicmp(charset, TEXT("UTF-8")) &&
_wcsicmp(charset, TEXT("\"UTF-8\""))) {
LOG.error("ignoring unsupported charset");
}
vprop->removeParameter(TEXT("CHARSET"));
}
vprop->setValue(native);
delete [] native;
}
}
void VObject::fromNativeEncoding()
{
BOOL is_30 = !wcscmp(getVersion(), TEXT("3.0"));
for (int index = propertiesCount() - 1; index >= 0; index--) {
VProperty *vprop = getProperty(index);
if (vprop->equalsEncoding(TEXT("QUOTED-PRINTABLE"))) {
// remove this, we cannot recreate it
vprop->removeParameter(TEXT("ENCODING"));
}
wchar_t *native = vprop->getValue();
// in the worst case every comma/linebreak is replaced with
// two characters and each \n with =0D=0A
wchar_t *foreign = new wchar_t[6 * wcslen(native) + 1];
wchar_t curr;
int in = 0, out = 0;
// line break is encoded with either one or two
// characters on different platforms
const int linebreaklen = wcslen(SYNC4J_LINEBREAK);
// use backslash for special characters,
// if necessary do quoted-printable encoding
bool doquoted = !is_30 &&
wcsstr(native, SYNC4J_LINEBREAK) != NULL;
while ((curr = native[in]) != 0) {
in++;
switch (curr) {
case ',':
if (!is_30) {
// normal character
foreign[out] = curr;
out++;
break;
}
// no break!
case ';':
case '\\':
foreign[out] = '\\';
out++;
foreign[out] = curr;
out++;
break;
case SEMICOLON_REPLACEMENT:
foreign[out] = ';';
out++;
break;
default:
if (doquoted &&
(curr == '=' || (unsigned char)curr >= 128)) {
// escape = and non-ASCII characters
wsprintf(foreign + out, TEXT("=%02X"), (unsigned int)(unsigned char)curr);
out += 3;
} else if (!wcsncmp(native + in - 1,
SYNC4J_LINEBREAK,
linebreaklen)) {
// line break
if (is_30) {
foreign[out] = '\\';
out++;
foreign[out] = 'n';
out++;
} else {
wcscpy(foreign + out, TEXT("=0D=0A"));
out += 6;
}
in += linebreaklen - 1;
} else {
foreign[out] = curr;
out++;
}
break;
}
}
foreign[out] = 0;
vprop->setValue(foreign);
delete [] foreign;
if (doquoted) {
// we have used quoted-printable encoding
vprop->addParameter(TEXT("ENCODING"), TEXT("QUOTED-PRINTABLE"));
}
}
}
<|endoftext|> |
<commit_before>#include "commodconverter_facility.h"
namespace commodconverter {
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
CommodconverterFacility::CommodconverterFacility(cyclus::Context* ctx)
: cyclus::Facility(ctx) {};
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// pragmas
#pragma cyclus def schema commodconverter::CommodconverterFacility
#pragma cyclus def annotations commodconverter::CommodconverterFacility
#pragma cyclus def initinv commodconverter::CommodconverterFacility
#pragma cyclus def snapshotinv commodconverter::CommodconverterFacility
#pragma cyclus def initfromdb commodconverter::CommodconverterFacility
#pragma cyclus def initfromcopy commodconverter::CommodconverterFacility
#pragma cyclus def infiletodb commodconverter::CommodconverterFacility
#pragma cyclus def snapshot commodconverter::CommodconverterFacility
#pragma cyclus def clone commodconverter::CommodconverterFacility
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
std::string CommodconverterFacility::str() {
return Facility::str();
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void CommodconverterFacility::Tick() {}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void CommodconverterFacility::Tock() {}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
extern "C" cyclus::Agent* ConstructCommodconverterFacility(cyclus::Context* ctx) {
return new CommodconverterFacility(ctx);
}
} // namespace commodconverter
<commit_msg>copying new necessary functions from enrichment facility<commit_after>#include "commodconverter_facility.h"
namespace commodconverter {
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
CommodconverterFacility::CommodconverterFacility(cyclus::Context* ctx)
: cyclus::Facility(ctx) {};
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// pragmas
#pragma cyclus def schema commodconverter::CommodconverterFacility
#pragma cyclus def annotations commodconverter::CommodconverterFacility
#pragma cyclus def initinv commodconverter::CommodconverterFacility
#pragma cyclus def snapshotinv commodconverter::CommodconverterFacility
#pragma cyclus def initfromdb commodconverter::CommodconverterFacility
#pragma cyclus def initfromcopy commodconverter::CommodconverterFacility
#pragma cyclus def infiletodb commodconverter::CommodconverterFacility
#pragma cyclus def snapshot commodconverter::CommodconverterFacility
#pragma cyclus def clone commodconverter::CommodconverterFacility
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
std::string CommodconverterFacility::str() {
return Facility::str();
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void CommodconverterFacility::Tick() {}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void CommodconverterFacility::Tock() {}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
std::string CommodConverter::str() {
std::stringstream ss;
ss << cyclus::FacilityModel::str();
ss << " has facility parameters {" << "\n"
<< " Input Commodity = " << in_commod() << ",\n"
<< " Output Commodity = " << out_commod() << ",\n"
<< " Process Time = " << process_time() << ",\n"
<< " Capacity = " << capacity() << ",\n"
<< "'}";
return ss.str();
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void CommodconverterFacility::Build(cyclus::Agent* parent) {
using cyclus::Material;
Facility::Build(parent);
if (initial_reserves > 0) {
inventory.Push(
Material::Create(
this, initial_reserves, context()->GetRecipe(in_recipe)));
}
LOG(cyclus::LEV_DEBUG2, "ComCnv") << "CommodconverterFacility "
<< " entering the simuluation: ";
LOG(cyclus::LEV_DEBUG2, "ComCnv") << str();
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void CommodconverterFacility::Tick() {
LOG(cyclus::LEV_INFO3, "ComCnv") << prototype() << " is ticking {";
LOG(cyclus::LEV_INFO3, "ComCnv") << "}";
current_swu_capacity = SwuCapacity();
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void CommodconverterFacility::Tock() {
LOG(cyclus::LEV_INFO3, "ComCnv") << prototype() << " is tocking {";
LOG(cyclus::LEV_INFO3, "ComCnv") << "}";
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
std::set<cyclus::RequestPortfolio<cyclus::Material>::Ptr>
CommodconverterFacility::GetMatlRequests() {
using cyclus::CapacityConstraint;
using cyclus::Material;
using cyclus::RequestPortfolio;
using cyclus::Request;
std::set<RequestPortfolio<Material>::Ptr> ports;
RequestPortfolio<Material>::Ptr port(new RequestPortfolio<Material>());
Material::Ptr mat = Request_();
double amt = mat->quantity();
if (amt > cyclus::eps()) {
CapacityConstraint<Material> cc(amt);
port->AddConstraint(cc);
port->AddRequest(mat, this, in_commod);
ports.insert(port);
} // if amt > eps
return ports;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void CommodconverterFacility::AcceptMatlTrades(
const std::vector< std::pair<cyclus::Trade<cyclus::Material>,
cyclus::Material::Ptr> >& responses) {
// see
// http://stackoverflow.com/questions/5181183/boostshared-ptr-and-inheritance
std::vector< std::pair<cyclus::Trade<cyclus::Material>,
cyclus::Material::Ptr> >::const_iterator it;
for (it = responses.begin(); it != responses.end(); ++it) {
AddMat_(it->second);
}
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
std::set<cyclus::BidPortfolio<cyclus::Material>::Ptr>
CommodconverterFacility::GetMatlBids(
cyclus::CommodMap<cyclus::Material>::type& commod_requests) {
using cyclus::Bid;
using cyclus::BidPortfolio;
using cyclus::CapacityConstraint;
using cyclus::Converter;
using cyclus::Material;
using cyclus::Request;
std::set<BidPortfolio<Material>::Ptr> ports;
if (commod_requests.count(out_commod) > 0 && inventory.quantity() > 0) {
BidPortfolio<Material>::Ptr port(new BidPortfolio<Material>());
std::vector<Request<Material>*>& requests =
commod_requests[out_commod];
std::vector<Request<Material>*>::iterator it;
for (it = requests.begin(); it != requests.end(); ++it) {
Request<Material>* req = *it;
if (ValidReq(req->target())) {
Material::Ptr offer = Offer_(req->target());
port->AddBid(req, offer, this);
}
}
Converter<Material>::Ptr sc(new SWUConverter(feed_assay, tails_assay));
Converter<Material>::Ptr nc(new NatUConverter(feed_assay, tails_assay));
CapacityConstraint<Material> swu(swu_capacity, sc);
CapacityConstraint<Material> natu(inventory.quantity(), nc);
port->AddConstraint(swu);
port->AddConstraint(natu);
LOG(cyclus::LEV_INFO5, "ComCnv") << prototype()
<< " adding a swu constraint of "
<< swu.capacity();
LOG(cyclus::LEV_INFO5, "ComCnv") << prototype()
<< " adding a natu constraint of "
<< natu.capacity();
ports.insert(port);
}
return ports;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
bool CommodconverterFacility::ValidReq(const cyclus::Material::Ptr mat) {
cyclus::toolkit::MatQuery q(mat);
double u235 = q.atom_frac(922350000);
double u238 = q.atom_frac(922380000);
return (u238 > 0 && u235 / (u235 + u238) > TailsAssay());
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void CommodconverterFacility::GetMatlTrades(
const std::vector< cyclus::Trade<cyclus::Material> >& trades,
std::vector<std::pair<cyclus::Trade<cyclus::Material>,
cyclus::Material::Ptr> >& responses) {
using cyclus::Material;
using cyclus::Trade;
std::vector< Trade<Material> >::const_iterator it;
for (it = trades.begin(); it != trades.end(); ++it) {
Material::Ptr mat = it->bid->offer();
double qty = it->amt;
Material::Ptr response = Enrich_(mat, qty);
responses.push_back(std::make_pair(*it, response));
LOG(cyclus::LEV_INFO5, "ComCnv") << prototype()
<< " just received an order"
<< " for " << it->amt
<< " of " << out_commod;
}
if (cyclus::IsNegative(current_swu_capacity)) {
throw cyclus::ValueError(
"ComCnv " + prototype()
+ " is being asked to provide more than its SWU capacity.");
}
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void CommodconverterFacility::AddMat_(cyclus::Material::Ptr mat) {
if (mat->comp() != context()->GetRecipe(in_recipe)) {
throw cyclus::ValueError(
"CommodconverterFacility recipe and material composition not the same.");
}
LOG(cyclus::LEV_INFO5, "ComCnv") << prototype() << " is initially holding "
<< inventory.quantity() << " total.";
try {
inventory.Push(mat);
} catch (cyclus::Error& e) {
e.msg(Agent::InformErrorMsg(e.msg()));
throw e;
}
LOG(cyclus::LEV_INFO5, "ComCnv") << prototype() << " added " << mat->quantity()
<< " of " << in_commod
<< " to its inventory, which is holding "
<< inventory.quantity() << " total.";
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
extern "C" cyclus::Agent* ConstructCommodconverterFacility(cyclus::Context* ctx) {
return new CommodconverterFacility(ctx);
}
} // namespace commodconverter
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "utils_llvm.h"
#include <fcntl.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include "android/librsloader.h"
#include "class_loader.h"
#include "object.h"
#include "object_utils.h"
#include "runtime_support_llvm.h"
namespace art {
std::string MangleForLLVM(const std::string& s) {
std::string result;
size_t char_count = CountModifiedUtf8Chars(s.c_str());
const char* cp = &s[0];
for (size_t i = 0; i < char_count; ++i) {
uint16_t ch = GetUtf16FromUtf8(&cp);
if (ch == '$' || ch == '<' || ch == '>' || ch > 127) {
StringAppendF(&result, "_0%04x", ch);
} else {
switch (ch) {
case '_':
result += "_1";
break;
case ';':
result += "_2";
break;
case '[':
result += "_3";
break;
case '/':
result += "_";
break;
default:
result.push_back(ch);
break;
}
}
}
return result;
}
std::string LLVMShortName(const Method* m) {
MethodHelper mh(m);
std::string class_name(mh.GetDeclaringClassDescriptor());
// Remove the leading 'L' and trailing ';'...
CHECK_EQ(class_name[0], 'L') << class_name;
CHECK_EQ(class_name[class_name.size() - 1], ';') << class_name;
class_name.erase(0, 1);
class_name.erase(class_name.size() - 1, 1);
std::string method_name(mh.GetName());
std::string short_name;
short_name += "Art_";
short_name += MangleForLLVM(class_name);
short_name += "_";
short_name += MangleForLLVM(method_name);
return short_name;
}
std::string LLVMLongName(const Method* m) {
std::string long_name;
long_name += LLVMShortName(m);
long_name += "__";
std::string signature(MethodHelper(m).GetSignature());
signature.erase(0, 1);
signature.erase(signature.begin() + signature.find(')'), signature.end());
long_name += MangleForLLVM(signature);
return long_name;
}
std::string LLVMStubName(const Method* m) {
MethodHelper mh(m);
std::string stub_name;
if (m->IsStatic()) {
stub_name += "ArtSUpcall_";
} else {
stub_name += "ArtUpcall_";
}
stub_name += mh.GetShorty();
return stub_name;
}
void LLVMLinkLoadMethod(const std::string& file_name, Method* method) {
CHECK(method != NULL);
int fd = open(file_name.c_str(), O_RDONLY);
CHECK(fd >= 0) << "Error: ELF not found: " << file_name;
struct stat sb;
CHECK(fstat(fd, &sb) == 0) << "Error: Unable to stat ELF: " << file_name;
unsigned char const *image = (unsigned char const *)
mmap(NULL, sb.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
CHECK(image != MAP_FAILED) << "Error: Unable to mmap ELF: " << file_name;
RSExecRef relocatable =
rsloaderCreateExec(image, sb.st_size, art_find_runtime_support_func, 0);
CHECK(relocatable) << "Error: Unable to load ELF: " << file_name;
const void *addr = rsloaderGetSymbolAddress(relocatable, LLVMLongName(method).c_str());
CHECK(addr) << "Error: ELF (" << file_name << ") has no symbol " << LLVMLongName(method);
method->SetCode(reinterpret_cast<const uint32_t*>(addr));
method->SetFrameSizeInBytes(0);
method->SetCoreSpillMask(0);
method->SetFpSpillMask(0);
method->SetMappingTable(reinterpret_cast<const uint32_t*>(NULL));
method->SetVmapTable(reinterpret_cast<const uint16_t*>(NULL));
method->SetGcMap(reinterpret_cast<const uint8_t*>(NULL));
addr = rsloaderGetSymbolAddress(relocatable, LLVMStubName(method).c_str());
CHECK(addr) << "Error: ELF (" << file_name << ") has no symbol " << LLVMStubName(method);
method->SetInvokeStub(reinterpret_cast<void (*)(const art::Method*, art::Object*, art::Thread*,
art::byte*, art::JValue*)>(addr));
close(fd);
}
} // namespace art
<commit_msg>Use JValue* instead of byte* on the LLVM side too.<commit_after>/*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "utils_llvm.h"
#include <fcntl.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include "android/librsloader.h"
#include "class_loader.h"
#include "object.h"
#include "object_utils.h"
#include "runtime_support_llvm.h"
namespace art {
std::string MangleForLLVM(const std::string& s) {
std::string result;
size_t char_count = CountModifiedUtf8Chars(s.c_str());
const char* cp = &s[0];
for (size_t i = 0; i < char_count; ++i) {
uint16_t ch = GetUtf16FromUtf8(&cp);
if (ch == '$' || ch == '<' || ch == '>' || ch > 127) {
StringAppendF(&result, "_0%04x", ch);
} else {
switch (ch) {
case '_':
result += "_1";
break;
case ';':
result += "_2";
break;
case '[':
result += "_3";
break;
case '/':
result += "_";
break;
default:
result.push_back(ch);
break;
}
}
}
return result;
}
std::string LLVMShortName(const Method* m) {
MethodHelper mh(m);
std::string class_name(mh.GetDeclaringClassDescriptor());
// Remove the leading 'L' and trailing ';'...
CHECK_EQ(class_name[0], 'L') << class_name;
CHECK_EQ(class_name[class_name.size() - 1], ';') << class_name;
class_name.erase(0, 1);
class_name.erase(class_name.size() - 1, 1);
std::string method_name(mh.GetName());
std::string short_name;
short_name += "Art_";
short_name += MangleForLLVM(class_name);
short_name += "_";
short_name += MangleForLLVM(method_name);
return short_name;
}
std::string LLVMLongName(const Method* m) {
std::string long_name;
long_name += LLVMShortName(m);
long_name += "__";
std::string signature(MethodHelper(m).GetSignature());
signature.erase(0, 1);
signature.erase(signature.begin() + signature.find(')'), signature.end());
long_name += MangleForLLVM(signature);
return long_name;
}
std::string LLVMStubName(const Method* m) {
MethodHelper mh(m);
std::string stub_name;
if (m->IsStatic()) {
stub_name += "ArtSUpcall_";
} else {
stub_name += "ArtUpcall_";
}
stub_name += mh.GetShorty();
return stub_name;
}
void LLVMLinkLoadMethod(const std::string& file_name, Method* method) {
CHECK(method != NULL);
int fd = open(file_name.c_str(), O_RDONLY);
CHECK(fd >= 0) << "Error: ELF not found: " << file_name;
struct stat sb;
CHECK(fstat(fd, &sb) == 0) << "Error: Unable to stat ELF: " << file_name;
unsigned char const *image = (unsigned char const *)
mmap(NULL, sb.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
CHECK(image != MAP_FAILED) << "Error: Unable to mmap ELF: " << file_name;
RSExecRef relocatable =
rsloaderCreateExec(image, sb.st_size, art_find_runtime_support_func, 0);
CHECK(relocatable) << "Error: Unable to load ELF: " << file_name;
const void *addr = rsloaderGetSymbolAddress(relocatable, LLVMLongName(method).c_str());
CHECK(addr) << "Error: ELF (" << file_name << ") has no symbol " << LLVMLongName(method);
method->SetCode(reinterpret_cast<const uint32_t*>(addr));
method->SetFrameSizeInBytes(0);
method->SetCoreSpillMask(0);
method->SetFpSpillMask(0);
method->SetMappingTable(reinterpret_cast<const uint32_t*>(NULL));
method->SetVmapTable(reinterpret_cast<const uint16_t*>(NULL));
method->SetGcMap(reinterpret_cast<const uint8_t*>(NULL));
addr = rsloaderGetSymbolAddress(relocatable, LLVMStubName(method).c_str());
CHECK(addr) << "Error: ELF (" << file_name << ") has no symbol " << LLVMStubName(method);
method->SetInvokeStub(reinterpret_cast<void (*)(const art::Method*, art::Object*, art::Thread*,
art::JValue*, art::JValue*)>(addr));
close(fd);
}
} // namespace art
<|endoftext|> |
<commit_before><commit_msg>- More robust checking for ruby install paths on unix systems.<commit_after><|endoftext|> |
<commit_before>// Very simple pool. It can only allocate memory. And all of the memory it
// allocates must be freed at the same time.
#ifndef UTIL_POOL_H
#define UTIL_POOL_H
#include <vector>
#include <stdint.h>
namespace util {
class Pool {
public:
Pool();
~Pool();
void *Allocate(std::size_t size) {
void *ret = current_;
current_ += size;
if (current_ < current_end_) {
return ret;
} else {
return More(size);
}
}
/*
template<typename T>
void *Allocate() {
void *ret = Allocate(sizeof(T));
return ret;
}
*/
void FreeAll();
private:
void *More(std::size_t size);
std::vector<void *> free_list_;
uint8_t *current_, *current_end_;
// no copying
Pool(const Pool &);
Pool &operator=(const Pool &);
};
} // namespace util
#endif // UTIL_POOL_H
<commit_msg>allocate size of class temlate fn<commit_after>// Very simple pool. It can only allocate memory. And all of the memory it
// allocates must be freed at the same time.
#ifndef UTIL_POOL_H
#define UTIL_POOL_H
#include <vector>
#include <stdint.h>
namespace util {
class Pool {
public:
Pool();
~Pool();
void *Allocate(std::size_t size) {
void *ret = current_;
current_ += size;
if (current_ < current_end_) {
return ret;
} else {
return More(size);
}
}
template<typename T>
void *Allocate() {
void *ret = Allocate(sizeof(T));
return ret;
}
void FreeAll();
private:
void *More(std::size_t size);
std::vector<void *> free_list_;
uint8_t *current_, *current_end_;
// no copying
Pool(const Pool &);
Pool &operator=(const Pool &);
};
} // namespace util
#endif // UTIL_POOL_H
<|endoftext|> |
<commit_before>#include "DTIDEBuildAPI.h"
DTIDEBuildAPI::DTIDEBuildAPI()
{
}
DTIDEBuildAPI::~DTIDEBuildAPI()
{
std::list<std::string>::iterator it;
// Clean up.
for(it = m_OutputFiles.begin(); it != m_OutputFiles.end(); it++)
unlink((*it).c_str());
for(it = m_SymbolFiles.begin(); it != m_SymbolFiles.begin(); it++)
unlink((*it).c_str());
}
void DTIDEBuildAPI::AddError(std::string message, std::string file, int line)
{
ErrorEntry entry;
entry.IsWarning = false;
entry.Message = message;
entry.File = file;
entry.Line = line;
m_ErrorEntries.insert(m_ErrorEntries.begin(), entry);
}
void DTIDEBuildAPI::AddWarning(std::string message, std::string file, int line)
{
ErrorEntry entry;
entry.IsWarning = true;
entry.Message = message;
entry.File = file;
entry.Line = line;
m_ErrorEntries.insert(m_ErrorEntries.begin(), entry);
}
void DTIDEBuildAPI::AddIntermediateFile(std::string path, std::string langtarget)
{
IntermediateFile entry;
entry.Path = path;
entry.Language = langtarget;
m_IntermediateFiles.insert(m_IntermediateFiles.begin(), entry);
}
void DTIDEBuildAPI::AddOutputFile(std::string path)
{
m_OutputFiles.insert(m_OutputFiles.begin(), path);
}
void DTIDEBuildAPI::AddSymbolsFile(std::string path)
{
m_SymbolFiles.insert(m_SymbolFiles.begin(), path);
}
void DTIDEBuildAPI::End()
{
}
<commit_msg>Fix for build server (Linux build).<commit_after>#include "DTIDEBuildAPI.h"
#ifndef WIN32
#include <unistd.h>
#endif
DTIDEBuildAPI::DTIDEBuildAPI()
{
}
DTIDEBuildAPI::~DTIDEBuildAPI()
{
std::list<std::string>::iterator it;
// Clean up.
for(it = m_OutputFiles.begin(); it != m_OutputFiles.end(); it++)
unlink((*it).c_str());
for(it = m_SymbolFiles.begin(); it != m_SymbolFiles.begin(); it++)
unlink((*it).c_str());
}
void DTIDEBuildAPI::AddError(std::string message, std::string file, int line)
{
ErrorEntry entry;
entry.IsWarning = false;
entry.Message = message;
entry.File = file;
entry.Line = line;
m_ErrorEntries.insert(m_ErrorEntries.begin(), entry);
}
void DTIDEBuildAPI::AddWarning(std::string message, std::string file, int line)
{
ErrorEntry entry;
entry.IsWarning = true;
entry.Message = message;
entry.File = file;
entry.Line = line;
m_ErrorEntries.insert(m_ErrorEntries.begin(), entry);
}
void DTIDEBuildAPI::AddIntermediateFile(std::string path, std::string langtarget)
{
IntermediateFile entry;
entry.Path = path;
entry.Language = langtarget;
m_IntermediateFiles.insert(m_IntermediateFiles.begin(), entry);
}
void DTIDEBuildAPI::AddOutputFile(std::string path)
{
m_OutputFiles.insert(m_OutputFiles.begin(), path);
}
void DTIDEBuildAPI::AddSymbolsFile(std::string path)
{
m_SymbolFiles.insert(m_SymbolFiles.begin(), path);
}
void DTIDEBuildAPI::End()
{
}
<|endoftext|> |
<commit_before>/*******************************
Copyright (c) 2016-2019 Grégoire Angerand
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
**********************************/
#include "import.h"
#ifndef EDITOR_NO_ASSIMP
#include <yave/utils/FileSystemModel.h>
#include <assimp/Importer.hpp>
#include <assimp/scene.h>
#include <assimp/postprocess.h>
#include <unordered_map>
#include <unordered_set>
namespace editor {
namespace import {
struct SceneImportContext {
usize unamed_materials = 0;
};
static core::String clean_material_name(SceneImportContext& ctx, aiMaterial* mat) {
aiString name;
if(mat->Get(AI_MATKEY_NAME, name) != AI_SUCCESS) {
return fmt("unamed_material_%", ctx.unamed_materials++);
}
return clean_asset_name(name.C_Str());
}
static std::pair<core::Vector<Named<ImageData>>, core::Vector<Named<MaterialData>>> import_materias_and_textures(SceneImportContext& ctx,
core::Span<aiMaterial*> materials,
const core::String& filename) {
const FileSystemModel* fs = FileSystemModel::local_filesystem();
usize name_len = fs->filename(filename).size();
core::String path(filename.data(), filename.size() - name_len);
auto texture_name = [](aiMaterial* mat, aiTextureType type) {
if(mat->GetTextureCount(type)) {
aiString name;
mat->GetTexture(type, 0, &name);
return core::String(name.C_Str());
}
return core::String();
};
std::unordered_map<core::String, Named<ImageData>> images;
core::Vector<Named<MaterialData>> mats;
for(aiMaterial* mat : materials) {
auto process_tex = [&](aiTextureType type) -> std::string_view {
core::String name = texture_name(mat, type);
if(name.is_empty()) {
return "";
}
auto it = images.find(name);
if(it == images.end()) {
it = images.insert(std::pair(name, import_image(fs->join(path, name), ImageImportFlags::GenerateMipmaps))).first;
}
return it->second.name();
};
MaterialData material_data;
material_data.textures[SimpleMaterialData::Diffuse] = process_tex(aiTextureType_DIFFUSE);
material_data.textures[SimpleMaterialData::Normal] = process_tex(aiTextureType_NORMALS);
material_data.textures[SimpleMaterialData::RoughnessMetallic] = process_tex(aiTextureType_SHININESS);
mats.emplace_back(clean_material_name(ctx, mat), std::move(material_data));
{
aiTextureType loaded[] = {aiTextureType_DIFFUSE, aiTextureType_NORMALS, aiTextureType_SHININESS};
for(usize i = 0; i != AI_TEXTURE_TYPE_MAX + 1; ++i) {
aiTextureType type = aiTextureType(i);
if(mat->GetTextureCount(type)) {
if(std::find(std::begin(loaded), std::end(loaded), i) == std::end(loaded)) {
log_msg(fmt("Material \"%\" texture \"%\" has unknown type %.", clean_material_name(ctx, mat), texture_name(mat, type), i), Log::Warning);
// load texture anyway
process_tex(type);
}
}
}
}
}
core::Vector<Named<ImageData>> imgs;
std::transform(images.begin(), images.end(), std::back_inserter(imgs), [](auto& i) { return std::move(i.second); });
return {std::move(imgs), std::move(mats)};
}
SceneData import_scene(const core::String& filename, SceneImportFlags flags) {
y_profile();
int import_flags =
aiProcess_Triangulate |
aiProcess_FindInvalidData |
aiProcess_GenSmoothNormals |
//aiProcess_CalcTangentSpace |
aiProcess_GenUVCoords |
aiProcess_ImproveCacheLocality |
aiProcess_OptimizeGraph |
aiProcess_OptimizeMeshes |
aiProcess_JoinIdenticalVertices |
aiProcess_ValidateDataStructure |
0;
if((flags & SceneImportFlags::FlipUVs) == SceneImportFlags::FlipUVs) {
import_flags |= aiProcess_FlipUVs;
}
Assimp::Importer importer;
auto scene = importer.ReadFile(filename, import_flags);
if(!scene) {
y_throw("Unable to load scene.");
}
if(scene->mFlags & AI_SCENE_FLAGS_INCOMPLETE) {
log_msg("Scene is incomplete!", Log::Warning);
}
SceneImportContext ctx;
auto meshes = core::Span<aiMesh*>(scene->mMeshes, scene->mNumMeshes);
auto animations = core::Span<aiAnimation*>(scene->mAnimations, scene->mNumAnimations);
auto materials = core::Span<aiMaterial*>(scene->mMaterials, scene->mNumMaterials);
log_msg(fmt("% meshes, % animations, % materials found", meshes.size(), animations.size(), materials.size()));
SceneData data;
if((flags & SceneImportFlags::ImportMeshes) == SceneImportFlags::ImportMeshes) {
std::transform(meshes.begin(), meshes.end(), std::back_inserter(data.meshes), [=](aiMesh* mesh) {
return Named(clean_asset_name(mesh->mName.C_Str()), import_mesh(mesh, scene));
});
}
if((flags & SceneImportFlags::ImportAnims) == SceneImportFlags::ImportAnims) {
std::transform(animations.begin(), animations.end(), std::back_inserter(data.animations), [=](aiAnimation* anim) {
return Named(clean_asset_name(anim->mName.C_Str()), import_animation(anim));
});
}
if((flags & (SceneImportFlags::ImportImages | SceneImportFlags::ImportMaterials)) != SceneImportFlags::None) {
auto [imgs, mats] = import_materias_and_textures(ctx, materials, filename);
data.images = std::move(imgs);
if((flags & SceneImportFlags::ImportMaterials) == SceneImportFlags::ImportMaterials) {
data.materials = std::move(mats);
}
}
if((flags & SceneImportFlags::ImportObjects) == SceneImportFlags::ImportObjects) {
for(usize i = 0; i != meshes.size(); ++i) {
if(meshes[i]->mMaterialIndex < materials.size()) {
core::String mesh_name = clean_asset_name(meshes[i]->mName.C_Str());
data.objects.emplace_back(mesh_name, ObjectData{mesh_name, data.materials[meshes[i]->mMaterialIndex].name()});
}
}
}
return data;
}
core::String supported_scene_extensions() {
std::string extensions;
Assimp::Importer importer;
importer.GetExtensionList(extensions);
return extensions;
}
}
}
#else
namespace editor {
namespace import {
SceneData import_scene(const core::String& filename, SceneImportFlags flags) {
unused(filename, flags);
y_throw("Scene loading not supported.");
SceneData data;
return data;
}
core::String supported_scene_extensions() {
return "";
}
}
}
#endif
<commit_msg>Fixed material import<commit_after>/*******************************
Copyright (c) 2016-2019 Grégoire Angerand
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
**********************************/
#include "import.h"
#ifndef EDITOR_NO_ASSIMP
#include <yave/utils/FileSystemModel.h>
#include <assimp/Importer.hpp>
#include <assimp/scene.h>
#include <assimp/postprocess.h>
#include <unordered_map>
#include <unordered_set>
namespace editor {
namespace import {
struct SceneImportContext {
usize unamed_materials = 0;
};
static core::String clean_material_name(SceneImportContext& ctx, aiMaterial* mat) {
aiString name;
if(mat->Get(AI_MATKEY_NAME, name) != AI_SUCCESS) {
return fmt("unamed_material_%", ctx.unamed_materials++);
}
return clean_asset_name(name.C_Str());
}
static std::pair<core::Vector<Named<ImageData>>, core::Vector<Named<MaterialData>>> import_materias_and_textures(SceneImportContext& ctx,
core::Span<aiMaterial*> materials,
const core::String& filename) {
const FileSystemModel* fs = FileSystemModel::local_filesystem();
usize name_len = fs->filename(filename).size();
core::String path(filename.data(), filename.size() - name_len);
auto texture_name = [](aiMaterial* mat, aiTextureType type) {
if(mat->GetTextureCount(type)) {
aiString name;
mat->GetTexture(type, 0, &name);
return core::String(name.C_Str());
}
return core::String();
};
std::unordered_map<core::String, Named<ImageData>> images;
core::Vector<Named<MaterialData>> mats;
for(aiMaterial* mat : materials) {
auto process_tex = [&](aiTextureType type) -> std::string_view {
core::String name = texture_name(mat, type);
if(name.is_empty()) {
return "";
}
auto it = images.find(name);
if(it == images.end()) {
it = images.insert(std::pair(name, import_image(fs->join(path, name), ImageImportFlags::GenerateMipmaps))).first;
}
return it->second.name();
};
MaterialData material_data;
material_data.textures[SimpleMaterialData::Diffuse] = process_tex(aiTextureType_DIFFUSE);
material_data.textures[SimpleMaterialData::Normal] = process_tex(aiTextureType_NORMALS);
material_data.textures[SimpleMaterialData::Roughness] = process_tex(aiTextureType_SHININESS);
material_data.textures[SimpleMaterialData::Metallic] = process_tex(aiTextureType_UNKNOWN);
mats.emplace_back(clean_material_name(ctx, mat), std::move(material_data));
{
aiTextureType loaded[] = {aiTextureType_DIFFUSE, aiTextureType_NORMALS, aiTextureType_SHININESS};
for(usize i = 0; i != AI_TEXTURE_TYPE_MAX + 1; ++i) {
aiTextureType type = aiTextureType(i);
if(mat->GetTextureCount(type)) {
if(std::find(std::begin(loaded), std::end(loaded), i) == std::end(loaded)) {
log_msg(fmt("Material \"%\" texture \"%\" has unknown type %.", clean_material_name(ctx, mat), texture_name(mat, type), i), Log::Warning);
// load texture anyway
process_tex(type);
}
}
}
}
}
core::Vector<Named<ImageData>> imgs;
std::transform(images.begin(), images.end(), std::back_inserter(imgs), [](auto& i) { return std::move(i.second); });
return {std::move(imgs), std::move(mats)};
}
SceneData import_scene(const core::String& filename, SceneImportFlags flags) {
y_profile();
int import_flags =
aiProcess_Triangulate |
aiProcess_FindInvalidData |
aiProcess_GenSmoothNormals |
//aiProcess_CalcTangentSpace |
aiProcess_GenUVCoords |
aiProcess_ImproveCacheLocality |
aiProcess_OptimizeGraph |
aiProcess_OptimizeMeshes |
aiProcess_JoinIdenticalVertices |
aiProcess_ValidateDataStructure |
0;
if((flags & SceneImportFlags::FlipUVs) == SceneImportFlags::FlipUVs) {
import_flags |= aiProcess_FlipUVs;
}
Assimp::Importer importer;
auto scene = importer.ReadFile(filename, import_flags);
if(!scene) {
y_throw("Unable to load scene.");
}
if(scene->mFlags & AI_SCENE_FLAGS_INCOMPLETE) {
log_msg("Scene is incomplete!", Log::Warning);
}
SceneImportContext ctx;
auto meshes = core::Span<aiMesh*>(scene->mMeshes, scene->mNumMeshes);
auto animations = core::Span<aiAnimation*>(scene->mAnimations, scene->mNumAnimations);
auto materials = core::Span<aiMaterial*>(scene->mMaterials, scene->mNumMaterials);
log_msg(fmt("% meshes, % animations, % materials found", meshes.size(), animations.size(), materials.size()));
SceneData data;
if((flags & SceneImportFlags::ImportMeshes) == SceneImportFlags::ImportMeshes) {
std::transform(meshes.begin(), meshes.end(), std::back_inserter(data.meshes), [=](aiMesh* mesh) {
return Named(clean_asset_name(mesh->mName.C_Str()), import_mesh(mesh, scene));
});
}
if((flags & SceneImportFlags::ImportAnims) == SceneImportFlags::ImportAnims) {
std::transform(animations.begin(), animations.end(), std::back_inserter(data.animations), [=](aiAnimation* anim) {
return Named(clean_asset_name(anim->mName.C_Str()), import_animation(anim));
});
}
if((flags & (SceneImportFlags::ImportImages | SceneImportFlags::ImportMaterials)) != SceneImportFlags::None) {
auto [imgs, mats] = import_materias_and_textures(ctx, materials, filename);
data.images = std::move(imgs);
if((flags & SceneImportFlags::ImportMaterials) == SceneImportFlags::ImportMaterials) {
data.materials = std::move(mats);
}
}
if((flags & SceneImportFlags::ImportObjects) == SceneImportFlags::ImportObjects) {
for(usize i = 0; i != meshes.size(); ++i) {
if(meshes[i]->mMaterialIndex < materials.size()) {
core::String mesh_name = clean_asset_name(meshes[i]->mName.C_Str());
data.objects.emplace_back(mesh_name, ObjectData{mesh_name, data.materials[meshes[i]->mMaterialIndex].name()});
}
}
}
return data;
}
core::String supported_scene_extensions() {
std::string extensions;
Assimp::Importer importer;
importer.GetExtensionList(extensions);
return extensions;
}
}
}
#else
namespace editor {
namespace import {
SceneData import_scene(const core::String& filename, SceneImportFlags flags) {
unused(filename, flags);
y_throw("Scene loading not supported.");
SceneData data;
return data;
}
core::String supported_scene_extensions() {
return "";
}
}
}
#endif
<|endoftext|> |
<commit_before>/*
Copyright (C) 2001-present by Serge Lamikhov-Center
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#ifndef ELFIO_SECTION_HPP
#define ELFIO_SECTION_HPP
#include <string>
#include <iostream>
#include <new>
#include <limits>
namespace ELFIO {
class section
{
friend class elfio;
public:
virtual ~section() = default;
ELFIO_GET_ACCESS_DECL( Elf_Half, index );
ELFIO_GET_SET_ACCESS_DECL( std::string, name );
ELFIO_GET_SET_ACCESS_DECL( Elf_Word, type );
ELFIO_GET_SET_ACCESS_DECL( Elf_Xword, flags );
ELFIO_GET_SET_ACCESS_DECL( Elf_Word, info );
ELFIO_GET_SET_ACCESS_DECL( Elf_Word, link );
ELFIO_GET_SET_ACCESS_DECL( Elf_Xword, addr_align );
ELFIO_GET_SET_ACCESS_DECL( Elf_Xword, entry_size );
ELFIO_GET_SET_ACCESS_DECL( Elf64_Addr, address );
ELFIO_GET_SET_ACCESS_DECL( Elf_Xword, size );
ELFIO_GET_SET_ACCESS_DECL( Elf_Word, name_string_offset );
ELFIO_GET_ACCESS_DECL( Elf64_Off, offset );
virtual const char* get_data() const = 0;
virtual void set_data( const char* raw_data, Elf_Word size ) = 0;
virtual void set_data( const std::string& data ) = 0;
virtual void append_data( const char* raw_data, Elf_Word size ) = 0;
virtual void append_data( const std::string& data ) = 0;
virtual size_t get_stream_size() const = 0;
virtual void set_stream_size( size_t value ) = 0;
protected:
ELFIO_SET_ACCESS_DECL( Elf64_Off, offset );
ELFIO_SET_ACCESS_DECL( Elf_Half, index );
virtual bool load( std::istream& stream, std::streampos header_offset ) = 0;
virtual void save( std::ostream& stream,
std::streampos header_offset,
std::streampos data_offset ) = 0;
virtual bool is_address_initialized() const = 0;
};
template <class T> class section_impl : public section
{
public:
//------------------------------------------------------------------------------
section_impl( const endianess_convertor* convertor,
const address_translator* translator,
const std::shared_ptr<compression_interface>& compression )
: convertor( convertor ), translator( translator ),
compression( compression )
{
}
//------------------------------------------------------------------------------
// Section info functions
ELFIO_GET_SET_ACCESS( Elf_Word, type, header.sh_type );
ELFIO_GET_SET_ACCESS( Elf_Xword, flags, header.sh_flags );
ELFIO_GET_SET_ACCESS( Elf_Xword, size, header.sh_size );
ELFIO_GET_SET_ACCESS( Elf_Word, link, header.sh_link );
ELFIO_GET_SET_ACCESS( Elf_Word, info, header.sh_info );
ELFIO_GET_SET_ACCESS( Elf_Xword, addr_align, header.sh_addralign );
ELFIO_GET_SET_ACCESS( Elf_Xword, entry_size, header.sh_entsize );
ELFIO_GET_SET_ACCESS( Elf_Word, name_string_offset, header.sh_name );
ELFIO_GET_ACCESS( Elf64_Addr, address, header.sh_addr );
//------------------------------------------------------------------------------
Elf_Half get_index() const override { return index; }
//------------------------------------------------------------------------------
std::string get_name() const override { return name; }
//------------------------------------------------------------------------------
void set_name( const std::string& name_prm ) override
{
this->name = name_prm;
}
//------------------------------------------------------------------------------
void set_address( const Elf64_Addr& value ) override
{
header.sh_addr = decltype( header.sh_addr )( value );
header.sh_addr = ( *convertor )( header.sh_addr );
is_address_set = true;
}
//------------------------------------------------------------------------------
bool is_address_initialized() const override { return is_address_set; }
//------------------------------------------------------------------------------
const char* get_data() const override { return data.get(); }
//------------------------------------------------------------------------------
void set_data( const char* raw_data, Elf_Word size ) override
{
if ( get_type() != SHT_NOBITS ) {
data = std::unique_ptr<char[]>( new ( std::nothrow ) char[size] );
if ( nullptr != data.get() && nullptr != raw_data ) {
data_size = size;
std::copy( raw_data, raw_data + size, data.get() );
}
else {
data_size = 0;
}
}
set_size( data_size );
if ( translator->empty() ) {
set_stream_size( data_size );
}
}
//------------------------------------------------------------------------------
void set_data( const std::string& str_data ) override
{
return set_data( str_data.c_str(), (Elf_Word)str_data.size() );
}
//------------------------------------------------------------------------------
void append_data( const char* raw_data, Elf_Word size ) override
{
if ( get_type() != SHT_NOBITS ) {
if ( get_size() + size < data_size ) {
std::copy( raw_data, raw_data + size, data.get() + get_size() );
}
else {
data_size = 2 * ( data_size + size );
std::unique_ptr<char[]> new_data(
new ( std::nothrow ) char[data_size] );
if ( nullptr != new_data ) {
std::copy( data.get(), data.get() + get_size(),
new_data.get() );
std::copy( raw_data, raw_data + size,
new_data.get() + get_size() );
data = std::move( new_data );
}
else {
size = 0;
}
}
set_size( get_size() + size );
if ( translator->empty() ) {
set_stream_size( get_stream_size() + size );
}
}
}
//------------------------------------------------------------------------------
void append_data( const std::string& str_data ) override
{
return append_data( str_data.c_str(), (Elf_Word)str_data.size() );
}
//------------------------------------------------------------------------------
size_t get_stream_size() const override { return stream_size; }
//------------------------------------------------------------------------------
void set_stream_size( size_t value ) override { stream_size = value; }
//------------------------------------------------------------------------------
protected:
//------------------------------------------------------------------------------
ELFIO_GET_SET_ACCESS( Elf64_Off, offset, header.sh_offset );
//------------------------------------------------------------------------------
void set_index( const Elf_Half& value ) override { index = value; }
//------------------------------------------------------------------------------
bool load( std::istream& stream, std::streampos header_offset ) override
{
header = { 0 };
if ( translator->empty() ) {
stream.seekg( 0, std::istream::end );
set_stream_size( size_t( stream.tellg() ) );
}
else {
set_stream_size( std::numeric_limits<size_t>::max() );
}
stream.seekg( ( *translator )[header_offset] );
stream.read( reinterpret_cast<char*>( &header ), sizeof( header ) );
Elf_Xword size = get_size();
if ( nullptr == data && SHT_NULL != get_type() &&
SHT_NOBITS != get_type() && size < get_stream_size() ) {
data.reset( new ( std::nothrow ) char[size_t( size ) + 1] );
if ( ( 0 != size ) && ( nullptr != data ) ) {
stream.seekg(
( *translator )[( *convertor )( header.sh_offset )] );
stream.read( data.get(), size );
if ( static_cast<Elf_Xword>( stream.gcount() ) != size ) {
data = nullptr;
return false;
}
if ( ( get_flags() & SHF_RPX_DEFLATE ) ||
( get_flags() & SHF_COMPRESSED ) ) {
if ( compression == nullptr ) {
std::cerr
<< "WARN: compressed section found but no "
"compression implementation provided. Skipping."
<< std::endl;
data = nullptr;
return false;
}
// at this point, data holds the whole compressed stream
Elf_Xword uncompressed_size = 0;
auto decompressed_data = compression->inflate(
data.get(), convertor, size, uncompressed_size );
if ( decompressed_data == nullptr ) {
std::cerr << "Failed to decompress section data."
<< std::endl;
data = nullptr;
return false;
}
set_size( uncompressed_size );
data = std::move( decompressed_data );
}
// refresh size because it may have changed if we had to decompress data
size = get_size();
data.get()[size] =
0; // Ensure data is ended with 0 to avoid oob read
data_size = decltype( data_size )( size );
}
else {
data_size = 0;
}
}
return true;
}
//------------------------------------------------------------------------------
void save( std::ostream& stream,
std::streampos header_offset,
std::streampos data_offset ) override
{
if ( 0 != get_index() ) {
header.sh_offset = decltype( header.sh_offset )( data_offset );
header.sh_offset = ( *convertor )( header.sh_offset );
}
save_header( stream, header_offset );
if ( get_type() != SHT_NOBITS && get_type() != SHT_NULL &&
get_size() != 0 && data != nullptr ) {
save_data( stream, data_offset );
}
}
//------------------------------------------------------------------------------
private:
//------------------------------------------------------------------------------
void save_header( std::ostream& stream, std::streampos header_offset ) const
{
adjust_stream_size( stream, header_offset );
stream.write( reinterpret_cast<const char*>( &header ),
sizeof( header ) );
}
//------------------------------------------------------------------------------
void save_data( std::ostream& stream, std::streampos data_offset ) const
{
adjust_stream_size( stream, data_offset );
if ( ( ( get_flags() & SHF_COMPRESSED ) ||
( get_flags() & SHF_RPX_DEFLATE ) ) &&
compression != nullptr ) {
Elf_Xword decompressed_size = get_size();
Elf_Xword compressed_size = 0;
auto compressed_ptr = compression->deflate(
data.get(), convertor, decompressed_size, compressed_size );
stream.write( compressed_ptr.get(), compressed_size );
}
else {
stream.write( get_data(), get_size() );
}
}
//------------------------------------------------------------------------------
private:
T header = { 0 };
Elf_Half index = 0;
std::string name;
std::unique_ptr<char[]> data;
Elf_Word data_size = 0;
const endianess_convertor* convertor = nullptr;
const address_translator* translator = nullptr;
const std::shared_ptr<compression_interface> compression = nullptr;
bool is_address_set = false;
size_t stream_size = 0;
};
} // namespace ELFIO
#endif // ELFIO_SECTION_HPP
<commit_msg>Remove output to std::cerr<commit_after>/*
Copyright (C) 2001-present by Serge Lamikhov-Center
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#ifndef ELFIO_SECTION_HPP
#define ELFIO_SECTION_HPP
#include <string>
#include <iostream>
#include <new>
#include <limits>
namespace ELFIO {
class section
{
friend class elfio;
public:
virtual ~section() = default;
ELFIO_GET_ACCESS_DECL( Elf_Half, index );
ELFIO_GET_SET_ACCESS_DECL( std::string, name );
ELFIO_GET_SET_ACCESS_DECL( Elf_Word, type );
ELFIO_GET_SET_ACCESS_DECL( Elf_Xword, flags );
ELFIO_GET_SET_ACCESS_DECL( Elf_Word, info );
ELFIO_GET_SET_ACCESS_DECL( Elf_Word, link );
ELFIO_GET_SET_ACCESS_DECL( Elf_Xword, addr_align );
ELFIO_GET_SET_ACCESS_DECL( Elf_Xword, entry_size );
ELFIO_GET_SET_ACCESS_DECL( Elf64_Addr, address );
ELFIO_GET_SET_ACCESS_DECL( Elf_Xword, size );
ELFIO_GET_SET_ACCESS_DECL( Elf_Word, name_string_offset );
ELFIO_GET_ACCESS_DECL( Elf64_Off, offset );
virtual const char* get_data() const = 0;
virtual void set_data( const char* raw_data, Elf_Word size ) = 0;
virtual void set_data( const std::string& data ) = 0;
virtual void append_data( const char* raw_data, Elf_Word size ) = 0;
virtual void append_data( const std::string& data ) = 0;
virtual size_t get_stream_size() const = 0;
virtual void set_stream_size( size_t value ) = 0;
protected:
ELFIO_SET_ACCESS_DECL( Elf64_Off, offset );
ELFIO_SET_ACCESS_DECL( Elf_Half, index );
virtual bool load( std::istream& stream, std::streampos header_offset ) = 0;
virtual void save( std::ostream& stream,
std::streampos header_offset,
std::streampos data_offset ) = 0;
virtual bool is_address_initialized() const = 0;
};
template <class T> class section_impl : public section
{
public:
//------------------------------------------------------------------------------
section_impl( const endianess_convertor* convertor,
const address_translator* translator,
const std::shared_ptr<compression_interface>& compression )
: convertor( convertor ), translator( translator ),
compression( compression )
{
}
//------------------------------------------------------------------------------
// Section info functions
ELFIO_GET_SET_ACCESS( Elf_Word, type, header.sh_type );
ELFIO_GET_SET_ACCESS( Elf_Xword, flags, header.sh_flags );
ELFIO_GET_SET_ACCESS( Elf_Xword, size, header.sh_size );
ELFIO_GET_SET_ACCESS( Elf_Word, link, header.sh_link );
ELFIO_GET_SET_ACCESS( Elf_Word, info, header.sh_info );
ELFIO_GET_SET_ACCESS( Elf_Xword, addr_align, header.sh_addralign );
ELFIO_GET_SET_ACCESS( Elf_Xword, entry_size, header.sh_entsize );
ELFIO_GET_SET_ACCESS( Elf_Word, name_string_offset, header.sh_name );
ELFIO_GET_ACCESS( Elf64_Addr, address, header.sh_addr );
//------------------------------------------------------------------------------
Elf_Half get_index() const override { return index; }
//------------------------------------------------------------------------------
std::string get_name() const override { return name; }
//------------------------------------------------------------------------------
void set_name( const std::string& name_prm ) override
{
this->name = name_prm;
}
//------------------------------------------------------------------------------
void set_address( const Elf64_Addr& value ) override
{
header.sh_addr = decltype( header.sh_addr )( value );
header.sh_addr = ( *convertor )( header.sh_addr );
is_address_set = true;
}
//------------------------------------------------------------------------------
bool is_address_initialized() const override { return is_address_set; }
//------------------------------------------------------------------------------
const char* get_data() const override { return data.get(); }
//------------------------------------------------------------------------------
void set_data( const char* raw_data, Elf_Word size ) override
{
if ( get_type() != SHT_NOBITS ) {
data = std::unique_ptr<char[]>( new ( std::nothrow ) char[size] );
if ( nullptr != data.get() && nullptr != raw_data ) {
data_size = size;
std::copy( raw_data, raw_data + size, data.get() );
}
else {
data_size = 0;
}
}
set_size( data_size );
if ( translator->empty() ) {
set_stream_size( data_size );
}
}
//------------------------------------------------------------------------------
void set_data( const std::string& str_data ) override
{
return set_data( str_data.c_str(), (Elf_Word)str_data.size() );
}
//------------------------------------------------------------------------------
void append_data( const char* raw_data, Elf_Word size ) override
{
if ( get_type() != SHT_NOBITS ) {
if ( get_size() + size < data_size ) {
std::copy( raw_data, raw_data + size, data.get() + get_size() );
}
else {
data_size = 2 * ( data_size + size );
std::unique_ptr<char[]> new_data(
new ( std::nothrow ) char[data_size] );
if ( nullptr != new_data ) {
std::copy( data.get(), data.get() + get_size(),
new_data.get() );
std::copy( raw_data, raw_data + size,
new_data.get() + get_size() );
data = std::move( new_data );
}
else {
size = 0;
}
}
set_size( get_size() + size );
if ( translator->empty() ) {
set_stream_size( get_stream_size() + size );
}
}
}
//------------------------------------------------------------------------------
void append_data( const std::string& str_data ) override
{
return append_data( str_data.c_str(), (Elf_Word)str_data.size() );
}
//------------------------------------------------------------------------------
size_t get_stream_size() const override { return stream_size; }
//------------------------------------------------------------------------------
void set_stream_size( size_t value ) override { stream_size = value; }
//------------------------------------------------------------------------------
protected:
//------------------------------------------------------------------------------
ELFIO_GET_SET_ACCESS( Elf64_Off, offset, header.sh_offset );
//------------------------------------------------------------------------------
void set_index( const Elf_Half& value ) override { index = value; }
//------------------------------------------------------------------------------
bool load( std::istream& stream, std::streampos header_offset ) override
{
header = { 0 };
if ( translator->empty() ) {
stream.seekg( 0, std::istream::end );
set_stream_size( size_t( stream.tellg() ) );
}
else {
set_stream_size( std::numeric_limits<size_t>::max() );
}
stream.seekg( ( *translator )[header_offset] );
stream.read( reinterpret_cast<char*>( &header ), sizeof( header ) );
Elf_Xword size = get_size();
if ( nullptr == data && SHT_NULL != get_type() &&
SHT_NOBITS != get_type() && size < get_stream_size() ) {
data.reset( new ( std::nothrow ) char[size_t( size ) + 1] );
if ( ( 0 != size ) && ( nullptr != data ) ) {
stream.seekg(
( *translator )[( *convertor )( header.sh_offset )] );
stream.read( data.get(), size );
if ( static_cast<Elf_Xword>( stream.gcount() ) != size ) {
data = nullptr;
return false;
}
if ( ( ( get_flags() & SHF_RPX_DEFLATE ) ||
( get_flags() & SHF_COMPRESSED ) ) &&
compression != nullptr ) {
// at this point, data holds the whole compressed stream
Elf_Xword uncompressed_size = 0;
auto decompressed_data = compression->inflate(
data.get(), convertor, size, uncompressed_size );
if ( decompressed_data != nullptr ) {
set_size( uncompressed_size );
data = std::move( decompressed_data );
}
}
// refresh size because it may have changed if we had to decompress data
size = get_size();
data.get()[size] =
0; // Ensure data is ended with 0 to avoid oob read
data_size = decltype( data_size )( size );
}
else {
data_size = 0;
}
}
return true;
}
//------------------------------------------------------------------------------
void save( std::ostream& stream,
std::streampos header_offset,
std::streampos data_offset ) override
{
if ( 0 != get_index() ) {
header.sh_offset = decltype( header.sh_offset )( data_offset );
header.sh_offset = ( *convertor )( header.sh_offset );
}
save_header( stream, header_offset );
if ( get_type() != SHT_NOBITS && get_type() != SHT_NULL &&
get_size() != 0 && data != nullptr ) {
save_data( stream, data_offset );
}
}
//------------------------------------------------------------------------------
private:
//------------------------------------------------------------------------------
void save_header( std::ostream& stream, std::streampos header_offset ) const
{
adjust_stream_size( stream, header_offset );
stream.write( reinterpret_cast<const char*>( &header ),
sizeof( header ) );
}
//------------------------------------------------------------------------------
void save_data( std::ostream& stream, std::streampos data_offset ) const
{
adjust_stream_size( stream, data_offset );
if ( ( ( get_flags() & SHF_COMPRESSED ) ||
( get_flags() & SHF_RPX_DEFLATE ) ) &&
compression != nullptr ) {
Elf_Xword decompressed_size = get_size();
Elf_Xword compressed_size = 0;
auto compressed_ptr = compression->deflate(
data.get(), convertor, decompressed_size, compressed_size );
stream.write( compressed_ptr.get(), compressed_size );
}
else {
stream.write( get_data(), get_size() );
}
}
//------------------------------------------------------------------------------
private:
T header = { 0 };
Elf_Half index = 0;
std::string name;
std::unique_ptr<char[]> data;
Elf_Word data_size = 0;
const endianess_convertor* convertor = nullptr;
const address_translator* translator = nullptr;
const std::shared_ptr<compression_interface> compression = nullptr;
bool is_address_set = false;
size_t stream_size = 0;
};
} // namespace ELFIO
#endif // ELFIO_SECTION_HPP
<|endoftext|> |
<commit_before>/**
* @file matriz_operaciones.cpp
* @brief Implementación de operaciones con MatrizBit, independientes de la representación
*
*/
#include <iosfwd> // istream,ostream
#include <cstring> // strlen, strcat
#include <fstream>
#include "matriz_operaciones.h"
using namespace std;
void EliminarBlancos(istream& is)
{
while(isspace(is.peek()))
is.ignore();
}
//________________________________________________________________
bool Leer (istream& is, MatrizBit& m)
{
int filas;
int columnas;
bool exito;
EliminarBlancos(is);
/*
Primer formato: 'X' --> 1 ; '.' --> 0
*/
if (is.peek() == 'X' || is.peek() == '.')
{
const int MAX_POS = 1024;
char valores[MAX_POS];
char aux[MAX_POS];
is.getline(valores, MAX_POS);
columnas = strlen(valores);
filas = 1;
EliminarBlancos(is);
while (is.getline(aux, MAX_POS))
{
if (strlen(aux) != columnas)
return false;
strcat(valores, aux);
filas++;
EliminarBlancos(is);
}
exito = is.eof() && Inicializar(m, filas, columnas);
if (exito)
for (int i = 0; i < filas; i++)
for (int j = 0; j < columnas; j++)
{
char c = valores[columnas*i + j];
if (c == 'X' || c == '.')
SetElemento(m, i, j, c == 'X');
else
return false;
}
}
/*
Segundo formato: Lectura de '1' y '0'
*/
else
{
is >> filas >> columnas;
exito = is && Inicializar(m, filas, columnas);
if (exito)
{
for (int i = 0; i < filas && exito; i++)
for (int j = 0; j < columnas; j++)
{
char aux;
is >> aux;
if (aux == '1' || aux == '0')
SetElemento(m, i, j, aux);
else
return false;
}
exito = is;
}
}
return exito;
}
//________________________________________________________________
bool Escribir (ostream& os, const MatrizBit& m)
{
const int FILAS = GetFilas(m);
const int COLUMNAS = GetColumnas(m);
os << FILAS << " " << COLUMNAS << "\n";
for (int i = 0; i < FILAS; i++)
{
for (int j = 0; j < COLUMNAS; j++)
os << (GetElemento(m, i, j) ? '1' : '0') << ' ';
os << "\n";
}
os << "\n";
return os;
}
//________________________________________________________________
bool Leer (const char nombre[], MatrizBit& m)
{
ifstream f(nombre);
return Leer(f, m);
}
//________________________________________________________________
bool Escribir (const char nombre[], const MatrizBit& m)
{
ofstream f(nombre);
return Escribir(f, m);
}
//________________________________________________________________
void Traspuesta (MatrizBit& res, const MatrizBit& m)
{
const int FILAS = GetFilas(m);
const int COLUMNAS = GetColumnas(m);
for (int i = 0; i < FILAS; i++)
for (int j = 0; j < COLUMNAS; j++)
SetElemento(res, j, i, GetElemento(m, i, j));
}
//________________________________________________________________
void And (MatrizBit& res, const MatrizBit& m1, const MatrizBit& m2)
{
const int FILAS = GetFilas(m1);
const int COLUMNAS = GetColumnas(m1);
for (int i = 0; i < FILAS; i++)
for (int j = 0; j < COLUMNAS; j++)
SetElemento(res, i, j, GetElemento(m1, i, j) && GetElemento(m2, i, j));
}
//________________________________________________________________
void Or (MatrizBit& res, const MatrizBit& m1, const MatrizBit& m2)
{
const int FILAS = GetFilas(m1);
const int COLUMNAS = GetColumnas(m1);
for (int i = 0; i < FILAS; i++)
for (int j = 0; j < COLUMNAS; j++)
SetElemento(res, i, j, GetElemento(m1, i, j) || GetElemento(m2, i, j));
}
//________________________________________________________________
void Not (MatrizBit& res, const MatrizBit& m)
{
const int FILAS = GetFilas(m);
const int COLUMNAS = GetColumnas(m);
for (int i = 0; i < FILAS; i++)
for (int j = 0; j < COLUMNAS; j++)
SetElemento(res, i, j, !GetElemento(m, i, j));
}
/* Fin fichero: matriz_operaciones.cpp */
<commit_msg>== '1'<commit_after>/**
* @file matriz_operaciones.cpp
* @brief Implementación de operaciones con MatrizBit, independientes de la representación
*
*/
#include <iosfwd> // istream,ostream
#include <cstring> // strlen, strcat
#include <fstream>
#include "matriz_operaciones.h"
using namespace std;
void EliminarBlancos(istream& is)
{
while(isspace(is.peek()))
is.ignore();
}
//________________________________________________________________
bool Leer (istream& is, MatrizBit& m)
{
int filas;
int columnas;
bool exito;
EliminarBlancos(is);
/*
Primer formato: 'X' --> 1 ; '.' --> 0
*/
if (is.peek() == 'X' || is.peek() == '.')
{
const int MAX_POS = 1024;
char valores[MAX_POS];
char aux[MAX_POS];
is.getline(valores, MAX_POS);
columnas = strlen(valores);
filas = 1;
EliminarBlancos(is);
while (is.getline(aux, MAX_POS))
{
if (strlen(aux) != columnas)
return false;
strcat(valores, aux);
filas++;
EliminarBlancos(is);
}
exito = is.eof() && Inicializar(m, filas, columnas);
if (exito)
for (int i = 0; i < filas; i++)
for (int j = 0; j < columnas; j++)
{
char c = valores[columnas*i + j];
if (c == 'X' || c == '.')
SetElemento(m, i, j, c == 'X');
else
return false;
}
}
/*
Segundo formato: Lectura de '1' y '0'
*/
else
{
is >> filas >> columnas;
exito = is && Inicializar(m, filas, columnas);
if (exito)
{
for (int i = 0; i < filas && exito; i++)
for (int j = 0; j < columnas; j++)
{
char aux;
is >> aux;
if (aux == '1' || aux == '0')
SetElemento(m, i, j, aux == '1');
else
return false;
}
exito = is;
}
}
return exito;
}
//________________________________________________________________
bool Escribir (ostream& os, const MatrizBit& m)
{
const int FILAS = GetFilas(m);
const int COLUMNAS = GetColumnas(m);
os << FILAS << " " << COLUMNAS << "\n";
for (int i = 0; i < FILAS; i++)
{
for (int j = 0; j < COLUMNAS; j++)
os << (GetElemento(m, i, j) ? '1' : '0') << ' ';
os << "\n";
}
os << "\n";
return os;
}
//________________________________________________________________
bool Leer (const char nombre[], MatrizBit& m)
{
ifstream f(nombre);
return Leer(f, m);
}
//________________________________________________________________
bool Escribir (const char nombre[], const MatrizBit& m)
{
ofstream f(nombre);
return Escribir(f, m);
}
//________________________________________________________________
void Traspuesta (MatrizBit& res, const MatrizBit& m)
{
const int FILAS = GetFilas(m);
const int COLUMNAS = GetColumnas(m);
for (int i = 0; i < FILAS; i++)
for (int j = 0; j < COLUMNAS; j++)
SetElemento(res, j, i, GetElemento(m, i, j));
}
//________________________________________________________________
void And (MatrizBit& res, const MatrizBit& m1, const MatrizBit& m2)
{
const int FILAS = GetFilas(m1);
const int COLUMNAS = GetColumnas(m1);
for (int i = 0; i < FILAS; i++)
for (int j = 0; j < COLUMNAS; j++)
SetElemento(res, i, j, GetElemento(m1, i, j) && GetElemento(m2, i, j));
}
//________________________________________________________________
void Or (MatrizBit& res, const MatrizBit& m1, const MatrizBit& m2)
{
const int FILAS = GetFilas(m1);
const int COLUMNAS = GetColumnas(m1);
for (int i = 0; i < FILAS; i++)
for (int j = 0; j < COLUMNAS; j++)
SetElemento(res, i, j, GetElemento(m1, i, j) || GetElemento(m2, i, j));
}
//________________________________________________________________
void Not (MatrizBit& res, const MatrizBit& m)
{
const int FILAS = GetFilas(m);
const int COLUMNAS = GetColumnas(m);
for (int i = 0; i < FILAS; i++)
for (int j = 0; j < COLUMNAS; j++)
SetElemento(res, i, j, !GetElemento(m, i, j));
}
/* Fin fichero: matriz_operaciones.cpp */
<|endoftext|> |
<commit_before>#include "S_Campaign.h"
#include "j1Player.h"
#include "Gui.h"
#include "j1GameStartMenuBack.h"
#include "j1Render.h"
#include "ParticleManager.h"
#include "j1Window.h"
S_Campaign::S_Campaign()
{
scene_str = "Campaign";
}
S_Campaign::~S_Campaign()
{
}
bool S_Campaign::Awake(pugi::xml_node& conf)
{
int X_pos = App->win->GetWindowWHalf() - (int)(idle_button_rect.w * 0.5f);
newcampaign = App->gui->CreateButton(iPoint(X_pos, 200), &std::string("New Campaign"), ButtonType::idle_hover_pressed, &idle_button_rect, &hover_button_rect, &pressed_button_rect, false);
newcampaign->SetFont(App->font->Sherwood20);
((Gui*)newcampaign)->SetListener(this);
newcampaign->SetVisible(false);
newcampaign->Focusable(true);
loadcampaign = App->gui->CreateButton(iPoint(X_pos, 310), &std::string("Load Campaign"), ButtonType::idle_hover_pressed, &idle_button_rect, &hover_button_rect, &pressed_button_rect, false);
loadcampaign->SetFont(App->font->Sherwood20);
((Gui*)loadcampaign)->SetListener(this);
loadcampaign->SetVisible(false);
loadcampaign->Focusable(true);
back = App->gui->CreateButton(iPoint(920, 600), &std::string("Back"), ButtonType::idle_hover_pressed, &idle_button_rect, &hover_button_rect, &pressed_button_rect, false);
back->SetFont(App->font->Sherwood20);
((Gui*)back)->SetListener(this);
back->SetVisible(false);
back->Focusable(true);
buttons.push_back(newcampaign);
buttons.push_back(loadcampaign);
buttons.push_back(back);
return true;
}
bool S_Campaign::Start()
{
newcampaign->SetVisible(true);
loadcampaign->SetVisible(true);
back->SetVisible(true);
App->gui->SetFocus(buttons.front());
return true;
}
bool S_Campaign::Update()
{
MenuInput(&buttons);
return true;
}
bool S_Campaign::Clean()
{
newcampaign->SetVisible(false);
loadcampaign->SetVisible(false);
back->SetVisible(false);
return true;
}
void S_Campaign::OnGui(Gui* ui, GuiEvent event)
{
if ((ui == (Gui*)newcampaign) && (event == GuiEvent::mouse_lclk_down))
{
App->startmenuback->Freeze(true);
App->scene->ChangeScene(Scene_ID::startcutscenegame);
App->scene->Hide();
App->particlemanager->Enable();
for (int i = 0; i < App->cutscenemanager->bool_done_cutscenes.size(); i++) {
App->cutscenemanager->bool_done_cutscenes[i] = false;
}
}
if ((ui == (Gui*)loadcampaign) && (event == GuiEvent::mouse_lclk_down))
{
App->LoadGameModules("save_modules.xml");
}
if ((ui == (Gui*)back) && (event == GuiEvent::mouse_lclk_down))
{
App->scene->Show(Scene_ID::mainmenu);
}
}
bool S_Campaign::Save(pugi::xml_node& node) const
{
return true;
}
bool S_Campaign::Load(pugi::xml_node& node)
{
return true;
}<commit_msg>when you start game you allways start with 4 hearts<commit_after>#include "S_Campaign.h"
#include "j1Player.h"
#include "Gui.h"
#include "j1GameStartMenuBack.h"
#include "j1Render.h"
#include "ParticleManager.h"
#include "j1Window.h"
S_Campaign::S_Campaign()
{
scene_str = "Campaign";
}
S_Campaign::~S_Campaign()
{
}
bool S_Campaign::Awake(pugi::xml_node& conf)
{
int X_pos = App->win->GetWindowWHalf() - (int)(idle_button_rect.w * 0.5f);
newcampaign = App->gui->CreateButton(iPoint(X_pos, 200), &std::string("New Campaign"), ButtonType::idle_hover_pressed, &idle_button_rect, &hover_button_rect, &pressed_button_rect, false);
newcampaign->SetFont(App->font->Sherwood20);
((Gui*)newcampaign)->SetListener(this);
newcampaign->SetVisible(false);
newcampaign->Focusable(true);
loadcampaign = App->gui->CreateButton(iPoint(X_pos, 310), &std::string("Load Campaign"), ButtonType::idle_hover_pressed, &idle_button_rect, &hover_button_rect, &pressed_button_rect, false);
loadcampaign->SetFont(App->font->Sherwood20);
((Gui*)loadcampaign)->SetListener(this);
loadcampaign->SetVisible(false);
loadcampaign->Focusable(true);
back = App->gui->CreateButton(iPoint(920, 600), &std::string("Back"), ButtonType::idle_hover_pressed, &idle_button_rect, &hover_button_rect, &pressed_button_rect, false);
back->SetFont(App->font->Sherwood20);
((Gui*)back)->SetListener(this);
back->SetVisible(false);
back->Focusable(true);
buttons.push_back(newcampaign);
buttons.push_back(loadcampaign);
buttons.push_back(back);
return true;
}
bool S_Campaign::Start()
{
newcampaign->SetVisible(true);
loadcampaign->SetVisible(true);
back->SetVisible(true);
App->gui->SetFocus(buttons.front());
return true;
}
bool S_Campaign::Update()
{
MenuInput(&buttons);
return true;
}
bool S_Campaign::Clean()
{
newcampaign->SetVisible(false);
loadcampaign->SetVisible(false);
back->SetVisible(false);
return true;
}
void S_Campaign::OnGui(Gui* ui, GuiEvent event)
{
if ((ui == (Gui*)newcampaign) && (event == GuiEvent::mouse_lclk_down))
{
App->startmenuback->Freeze(true);
App->scene->ChangeScene(Scene_ID::startcutscenegame);
App->scene->Hide();
App->particlemanager->Enable();
for (int i = 0; i < App->cutscenemanager->bool_done_cutscenes.size(); i++) {
App->cutscenemanager->bool_done_cutscenes[i] = false;
}
App->player->hearts_containers_test_purpose = 4;
App->player->half_hearts_test_purpose = 8;
}
if ((ui == (Gui*)loadcampaign) && (event == GuiEvent::mouse_lclk_down))
{
App->LoadGameModules("save_modules.xml");
}
if ((ui == (Gui*)back) && (event == GuiEvent::mouse_lclk_down))
{
App->scene->Show(Scene_ID::mainmenu);
}
}
bool S_Campaign::Save(pugi::xml_node& node) const
{
return true;
}
bool S_Campaign::Load(pugi::xml_node& node)
{
return true;
}<|endoftext|> |
<commit_before>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2009 Torus Knot Software Ltd
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
#include "OgreNaClGLContext.h"
#include "OgreLog.h"
#include "OgreException.h"
#include "OgreRoot.h"
#include "OgreException.h"
#include "OgreLogManager.h"
#include "OgreStringConverter.h"
#include "OgreWindowEventUtilities.h"
#include "OgreGLES2Prerequisites.h"
#include "OgreGLES2RenderSystem.h"
#include "OgreNaClGLSupport.h"
#include "OgreNaClWindow.h"
#include "OgreNaClGLContext.h"
#include <stdint.h>
namespace Ogre {
NaClGLContext::NaClGLContext(const NaClWindow * window, const NaClGLSupport *glsupport, pp::Instance* instance, pp::CompletionCallback* swapCallback)
: pp::Graphics3DClient(instance)
, mWindow(window)
, mGLSupport(glsupport)
, mInstance(instance)
, mSwapCallback(swapCallback)
, mWidth(mWindow->getWidth())
, mHeight(mWindow->getHeight())
{
}
NaClGLContext::~NaClGLContext()
{
glSetCurrentContextPPAPI(0);
}
void NaClGLContext::setCurrent()
{
if (mInstance == NULL) {
glSetCurrentContextPPAPI(0);
return;
}
// Lazily create the Pepper context.
if (mContext.is_null())
{
LogManager::getSingleton().logMessage("\tcreate context started");
int32_t attribs[] = {
PP_GRAPHICS3DATTRIB_ALPHA_SIZE, 8,
PP_GRAPHICS3DATTRIB_DEPTH_SIZE, 24,
PP_GRAPHICS3DATTRIB_STENCIL_SIZE, 8,
PP_GRAPHICS3DATTRIB_SAMPLES, 0,
PP_GRAPHICS3DATTRIB_SAMPLE_BUFFERS, 0,
PP_GRAPHICS3DATTRIB_WIDTH, mWindow->getWidth(),
PP_GRAPHICS3DATTRIB_HEIGHT, mWindow->getHeight(),
PP_GRAPHICS3DATTRIB_NONE
};
mContext = pp::Graphics3D(*mInstance, pp::Graphics3D(), attribs);
if (mContext.is_null())
{
glSetCurrentContextPPAPI(0);
return;
}
mInstance->BindGraphics(mContext);
}
glSetCurrentContextPPAPI(mContext.pp_resource());
return;
}
void NaClGLContext::endCurrent()
{
glSetCurrentContextPPAPI(0);
}
GLES2Context* NaClGLContext::clone() const
{
NaClGLContext* res = new NaClGLContext(mWindow, mGLSupport, mInstance, mSwapCallback);
res->mInstance = this->mInstance;
return res;
}
void NaClGLContext::swapBuffers( bool waitForVSync )
{
mContext.SwapBuffers(*mSwapCallback);
}
// overrides pp::Graphics3DClient
void NaClGLContext::Graphics3DContextLost()
{
OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR,
"Unexpectedly lost graphics context.",
"NaClGLContext::Graphics3DContextLost" );
}
void NaClGLContext::resize()
{
if(mWidth != mWindow->getWidth() || mHeight != mWindow->getHeight() )
{
LogManager::getSingleton().logMessage("\tresizing");
mWidth = mWindow->getWidth();
mHeight = mWindow->getHeight();
glSetCurrentContextPPAPI(0);
mContext.ResizeBuffers( mWidth, mHeight );
glSetCurrentContextPPAPI(mContext.pp_resource());
LogManager::getSingleton().logMessage("\tdone resizing");
}
}
} // namespace
<commit_msg>NaCl Port: Fixed the code to support the current NaCl SDK.<commit_after>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2009 Torus Knot Software Ltd
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
#include "OgreNaClGLContext.h"
#include "OgreLog.h"
#include "OgreException.h"
#include "OgreRoot.h"
#include "OgreException.h"
#include "OgreLogManager.h"
#include "OgreStringConverter.h"
#include "OgreWindowEventUtilities.h"
#include "OgreGLES2Prerequisites.h"
#include "OgreGLES2RenderSystem.h"
#include "OgreNaClGLSupport.h"
#include "OgreNaClWindow.h"
#include "OgreNaClGLContext.h"
#include <stdint.h>
namespace Ogre {
NaClGLContext::NaClGLContext(const NaClWindow * window, const NaClGLSupport *glsupport, pp::Instance* instance, pp::CompletionCallback* swapCallback)
: pp::Graphics3DClient(instance)
, mWindow(window)
, mGLSupport(glsupport)
, mInstance(instance)
, mSwapCallback(swapCallback)
, mWidth(mWindow->getWidth())
, mHeight(mWindow->getHeight())
{
}
NaClGLContext::~NaClGLContext()
{
glSetCurrentContextPPAPI(0);
}
void NaClGLContext::setCurrent()
{
if (mInstance == NULL) {
glSetCurrentContextPPAPI(0);
return;
}
// Lazily create the Pepper context.
if (mContext.is_null())
{
LogManager::getSingleton().logMessage("\tcreate context started");
int32_t attribs[] = {
PP_GRAPHICS3DATTRIB_ALPHA_SIZE, 8,
PP_GRAPHICS3DATTRIB_DEPTH_SIZE, 24,
PP_GRAPHICS3DATTRIB_STENCIL_SIZE, 8,
PP_GRAPHICS3DATTRIB_SAMPLES, 0,
PP_GRAPHICS3DATTRIB_SAMPLE_BUFFERS, 0,
PP_GRAPHICS3DATTRIB_WIDTH, mWindow->getWidth(),
PP_GRAPHICS3DATTRIB_HEIGHT, mWindow->getHeight(),
PP_GRAPHICS3DATTRIB_NONE
};
mContext = pp::Graphics3D(mInstance, pp::Graphics3D(), attribs);
if (mContext.is_null())
{
glSetCurrentContextPPAPI(0);
return;
}
mInstance->BindGraphics(mContext);
}
glSetCurrentContextPPAPI(mContext.pp_resource());
return;
}
void NaClGLContext::endCurrent()
{
glSetCurrentContextPPAPI(0);
}
GLES2Context* NaClGLContext::clone() const
{
NaClGLContext* res = new NaClGLContext(mWindow, mGLSupport, mInstance, mSwapCallback);
res->mInstance = this->mInstance;
return res;
}
void NaClGLContext::swapBuffers( bool waitForVSync )
{
mContext.SwapBuffers(*mSwapCallback);
}
// overrides pp::Graphics3DClient
void NaClGLContext::Graphics3DContextLost()
{
OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR,
"Unexpectedly lost graphics context.",
"NaClGLContext::Graphics3DContextLost" );
}
void NaClGLContext::resize()
{
if(mWidth != mWindow->getWidth() || mHeight != mWindow->getHeight() )
{
LogManager::getSingleton().logMessage("\tresizing");
mWidth = mWindow->getWidth();
mHeight = mWindow->getHeight();
glSetCurrentContextPPAPI(0);
mContext.ResizeBuffers( mWidth, mHeight );
glSetCurrentContextPPAPI(mContext.pp_resource());
LogManager::getSingleton().logMessage("\tdone resizing");
}
}
} // namespace
<|endoftext|> |
<commit_before>#ifndef CUBE_CONTROL_SIGNAL
#define CUBE_CONTROL_SIGNAL
/* A private signal, currently shared by idle & cube
*
* It is used to rotate the cube from the idle plugin as a screensaver.
*/
/* Rotate cube to given angle and zoom level */
struct cube_control_signal : public wf::signal_data_t
{
double angle; // cube rotation in radians
double zoom; // 1.0 means 100%; increase value to zoom
double ease; // for cube deformation; range 0.0-1.0
bool last_frame; // ends cube animation if true
bool carried_out; // false if cube is disabled
};
#endif /* end of include guard: CUBE_CONTROL_SIGNAL */
<commit_msg>cube-control-signal: add missing include<commit_after>#ifndef CUBE_CONTROL_SIGNAL
#define CUBE_CONTROL_SIGNAL
#include <wayfire/signal-definitions.hpp>
/* A private signal, currently shared by idle & cube
*
* It is used to rotate the cube from the idle plugin as a screensaver.
*/
/* Rotate cube to given angle and zoom level */
struct cube_control_signal : public wf::signal_data_t
{
double angle; // cube rotation in radians
double zoom; // 1.0 means 100%; increase value to zoom
double ease; // for cube deformation; range 0.0-1.0
bool last_frame; // ends cube animation if true
bool carried_out; // false if cube is disabled
};
#endif /* end of include guard: CUBE_CONTROL_SIGNAL */
<|endoftext|> |
<commit_before>/*******************************************************************************
* c7a/communication/select.cpp
*
* Lightweight wrapper around select()
*
* Part of Project c7a.
*
* Copyright (C) 2015 Timo Bingmann <tb@panthema.net>
*
* This file has no license. Only Chuck Norris can compile it.
******************************************************************************/
#include <c7a/net/select.hpp>
#include <sys/time.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
namespace c7a {
Socket* Select::SelectOne(const int msec,
const bool readable, const bool writeable)
{
int maxfd = 0;
FD_ZERO(&readset_);
FD_ZERO(&writeset_);
FD_ZERO(&exceptset_);
for (Socket* s : socketlist_)
{
// maybe add to readable fd set
if (readable) FD_SET(s->GetFileDescriptor(), &readset_);
// maybe add to writable fd set
if (writeable) FD_SET(s->GetFileDescriptor(), &writeset_);
// but always add to exception fd set
FD_SET(s->GetFileDescriptor(), &exceptset_);
maxfd = std::max(maxfd, s->GetFileDescriptor() + 1);
}
struct timeval timeout;
timeout.tv_usec = (msec % 1000) * 1000;
timeout.tv_sec = msec / 1000;
#ifdef __linux__
// linux supports reading elapsed time from timeout
int r = ::select(maxfd, &readset_, &writeset_, &exceptset_, &timeout);
elapsed_ = msec - (timeout.tv_sec * 1000 + timeout.tv_usec / 1000);
#else
// else we have to do the gettimeofday() calls ourselves
struct timeval selstart, selfinish;
gettimeofday(&selstart, NULL);
int r = ::select(maxfd, &readset_, &writeset_, &exceptset_, &timeout);
gettimeofday(&selfinish, NULL);
elapsed_ = (selfinish.tv_sec - selstart.tv_sec) * 1000;
elapsed_ += (selfinish.tv_usec - selstart.tv_usec) / 1000;
// int selsays = msec - (timeout.tv_sec * 1000 + timeout.tv_usec / 1000);
Socket::trace("Spent %d msec in select. select says %d\n",
elapsed_, selsays);
#endif
if (r < 0) {
LOG << "Select::SelectOne() failed!"
<< " error=" << strerror(errno);
return NULL;
}
else if (r == 0) {
return NULL;
}
for (Socket* s : socketlist_)
{
if (readable && FD_ISSET(s->GetFileDescriptor(), &readset_)) return s;
if (writeable && FD_ISSET(s->GetFileDescriptor(), &writeset_)) return s;
if (FD_ISSET(s->GetFileDescriptor(), &exceptset_)) return s;
}
return NULL;
}
} // namespace c7a
/******************************************************************************/
<commit_msg>Yet again fixing Mac OSX's insufficientness.<commit_after>/*******************************************************************************
* c7a/communication/select.cpp
*
* Lightweight wrapper around select()
*
* Part of Project c7a.
*
* Copyright (C) 2015 Timo Bingmann <tb@panthema.net>
*
* This file has no license. Only Chuck Norris can compile it.
******************************************************************************/
#include <c7a/net/select.hpp>
#include <sys/time.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
namespace c7a {
Socket* Select::SelectOne(const int msec,
const bool readable, const bool writeable)
{
int maxfd = 0;
FD_ZERO(&readset_);
FD_ZERO(&writeset_);
FD_ZERO(&exceptset_);
for (Socket* s : socketlist_)
{
// maybe add to readable fd set
if (readable) FD_SET(s->GetFileDescriptor(), &readset_);
// maybe add to writable fd set
if (writeable) FD_SET(s->GetFileDescriptor(), &writeset_);
// but always add to exception fd set
FD_SET(s->GetFileDescriptor(), &exceptset_);
maxfd = std::max(maxfd, s->GetFileDescriptor() + 1);
}
struct timeval timeout;
timeout.tv_usec = (msec % 1000) * 1000;
timeout.tv_sec = msec / 1000;
#ifdef __linux__
// linux supports reading elapsed time from timeout
int r = ::select(maxfd, &readset_, &writeset_, &exceptset_, &timeout);
elapsed_ = msec - (timeout.tv_sec * 1000 + timeout.tv_usec / 1000);
#else
// else we have to do the gettimeofday() calls ourselves
struct timeval selstart, selfinish;
gettimeofday(&selstart, NULL);
int r = ::select(maxfd, &readset_, &writeset_, &exceptset_, &timeout);
gettimeofday(&selfinish, NULL);
elapsed_ = (selfinish.tv_sec - selstart.tv_sec) * 1000;
elapsed_ += (selfinish.tv_usec - selstart.tv_usec) / 1000;
// int selsays = msec - (timeout.tv_sec * 1000 + timeout.tv_usec / 1000);
LOG << "Select::SelectOne() spent " << elapsed_ << " msec in select."
<< "select() says " << r;
#endif
if (r < 0) {
LOG << "Select::SelectOne() failed!"
<< " error=" << strerror(errno);
return NULL;
}
else if (r == 0) {
return NULL;
}
for (Socket* s : socketlist_)
{
if (readable && FD_ISSET(s->GetFileDescriptor(), &readset_)) return s;
if (writeable && FD_ISSET(s->GetFileDescriptor(), &writeset_)) return s;
if (FD_ISSET(s->GetFileDescriptor(), &exceptset_)) return s;
}
return NULL;
}
} // namespace c7a
/******************************************************************************/
<|endoftext|> |
<commit_before>#include <QDebug>
#include <QSettings>
#include <QFileInfo>
#include <QDir>
#include <QThread>
#include <coreplugin/messagemanager.h>
#include <coreplugin/progressmanager/progressmanager.h>
#include <coreplugin/progressmanager/futureprogress.h>
#include "CppcheckRunner.h"
#include "Constants.h"
#include "Settings.h"
using namespace QtcCppcheck::Internal;
namespace
{
enum ErrorField
{
ErrorFieldFile = 0, ErrorFieldLine, ErrorFieldSeverity, ErrorFieldId,
ErrorFieldMessage
};
}
CppcheckRunner::CppcheckRunner(Settings *settings, QObject *parent) :
QObject(parent), settings_ (settings), showOutput_ (false), futureInterface_ (NULL)
{
Q_ASSERT (settings_ != NULL);
connect (&process_, SIGNAL (readyReadStandardOutput()),
SLOT (readOutput()));
connect (&process_, SIGNAL (readyReadStandardError()),
SLOT (readError()));
connect (&process_, SIGNAL (started()),
SLOT (started()));
connect (&process_, SIGNAL (error(QProcess::ProcessError)),
SLOT (error(QProcess::ProcessError)));
connect (&process_, SIGNAL (finished(int, QProcess::ExitStatus)),
SLOT (finished(int, QProcess::ExitStatus)));
// Restart checking if got queue.
connect (&process_, SIGNAL (finished(int, QProcess::ExitStatus)),
SLOT (checkQueuedFiles ()));
}
CppcheckRunner::~CppcheckRunner()
{
if (process_.isOpen())
{
process_.kill();
}
queueTimer_.stop ();
settings_ = NULL;
delete futureInterface_;
}
void CppcheckRunner::updateSettings()
{
Q_ASSERT (settings_ != NULL);
showOutput_ = settings_->showBinaryOutput ();
runArguments_.clear ();
runArguments_ << QLatin1String ("-q");
// Pass custom params BEFORE most of runner's to shadow if some repeat.
runArguments_ += settings_->customParameters ().split (
QLatin1Char (' '), QString::SkipEmptyParts);
QString enabled = QLatin1String ("--enable=warning,style,performance,"
"portability,information,missingInclude");
// Overwrite enable with user parameters if present
for(int i = runArguments_.size () - 1; i >= 0; --i)
{
if (runArguments_.at (i).startsWith (QLatin1String ("--enable")))
{
enabled = runArguments_.takeAt (i);
break;
}
}
if (settings_->checkUnused ())
{
enabled += QLatin1String (",unusedFunction");
}
else //TODO always check with threads but rescan for unused after finish?
{
runArguments_ << (QLatin1String ("-j ") +
QString::number (QThread::idealThreadCount ()));
}
runArguments_ << enabled;
if (settings_->checkInconclusive ())
{
runArguments_ << QLatin1String ("--inconclusive");
}
runArguments_ << QLatin1String ("--template={file},{line},{severity},{id},{message}");
}
void CppcheckRunner::checkFiles(const QStringList &fileNames)
{
Q_ASSERT (!fileNames.isEmpty ());
fileCheckQueue_ += fileNames;
fileCheckQueue_.removeDuplicates ();
fileCheckQueue_.sort ();
if (process_.isOpen ())
{
if (fileCheckQueue_ == currentlyCheckingFiles_)
{
process_.kill ();
// Rechecking will be restarted on finish signal.
}
return;
}
// Delay helps to avoid double checking same file on editor change.
const int checkDelayInMs = 200;
if (!queueTimer_.isActive ())
{
queueTimer_.singleShot (checkDelayInMs, this, SLOT (checkQueuedFiles ()));
}
}
void CppcheckRunner::stopChecking()
{
fileCheckQueue_.clear ();
if (process_.isOpen ())
{
process_.kill ();
}
}
void CppcheckRunner::checkQueuedFiles()
{
if (fileCheckQueue_.isEmpty ())
{
return;
}
QString binary = settings_->binaryFile ();
Q_ASSERT (!binary.isEmpty ());
QStringList arguments (runArguments_);
arguments += fileCheckQueue_;
currentlyCheckingFiles_ = fileCheckQueue_;
fileCheckQueue_.clear ();
emit startedChecking (currentlyCheckingFiles_);
process_.start (binary, arguments);
}
void CppcheckRunner::readOutput()
{
if (!showOutput_)
{
return;
}
process_.setReadChannel (QProcess::StandardOutput);
while (!process_.atEnd ())
{
QByteArray rawLine = process_.readLine ();
QString line = QString::fromUtf8 (rawLine).trimmed ();
if (line.isEmpty ())
{
continue;
}
Core::MessageManager::write (line, Core::MessageManager::Silent);
}
}
void CppcheckRunner::readError()
{
process_.setReadChannel (QProcess::StandardError);
while (!process_.atEnd ())
{
QByteArray rawLine = process_.readLine ();
QString line = QString::fromUtf8 (rawLine).trimmed ();
if (line.isEmpty ())
{
continue;
}
if (showOutput_)
{
Core::MessageManager::write (line, Core::MessageManager::Silent);
}
QStringList details = line.split (QLatin1Char (','));
if (details.size () <= ErrorFieldMessage)
{
continue;
}
QString file = QDir::fromNativeSeparators(details.at (ErrorFieldFile));
int lineNumber = details.at (ErrorFieldLine).toInt ();
char type = details.at (ErrorFieldSeverity).at (0).toLatin1 ();
QString description = line.mid (line.indexOf (details.at (ErrorFieldMessage)));
emit newTask (type, description, file, lineNumber);
}
}
void CppcheckRunner::started()
{
if (showOutput_)
{
Core::MessageManager::write (tr ("Cppcheck started"), Core::MessageManager::Silent);
}
using namespace Core;
delete futureInterface_;
futureInterface_ = new QFutureInterface<void>;
FutureProgress *progress = ProgressManager::addTask(futureInterface_->future(),
tr("Cppcheck"), Constants::TASK_CHECKING);
connect (progress, SIGNAL(canceled ()), SLOT(stopChecking ()));
futureInterface_->setProgressRange(0, 1); // To enable cancel action in progress
futureInterface_->reportStarted();
}
void CppcheckRunner::error(QProcess::ProcessError error)
{
Q_UNUSED (error);
if (showOutput_)
{
Core::MessageManager::write (tr ("Cppcheck error occured"), Core::MessageManager::Silent);
}
}
void CppcheckRunner::finished(int exitCode, QProcess::ExitStatus exitStatus)
{
Q_UNUSED (exitCode);
Q_UNUSED (exitStatus);
Q_ASSERT (futureInterface_ != NULL);
futureInterface_->reportFinished ();
process_.close ();
if (showOutput_)
{
Core::MessageManager::write (tr("Cppcheck finished"), Core::MessageManager::Silent);
}
}
<commit_msg>Use cppcheck's output to fill progress bar.<commit_after>#include <QDebug>
#include <QSettings>
#include <QFileInfo>
#include <QDir>
#include <QThread>
#include <coreplugin/messagemanager.h>
#include <coreplugin/progressmanager/progressmanager.h>
#include <coreplugin/progressmanager/futureprogress.h>
#include "CppcheckRunner.h"
#include "Constants.h"
#include "Settings.h"
using namespace QtcCppcheck::Internal;
namespace
{
enum ErrorField
{
ErrorFieldFile = 0, ErrorFieldLine, ErrorFieldSeverity, ErrorFieldId,
ErrorFieldMessage
};
}
CppcheckRunner::CppcheckRunner(Settings *settings, QObject *parent) :
QObject(parent), settings_ (settings), showOutput_ (false), futureInterface_ (NULL)
{
Q_ASSERT (settings_ != NULL);
connect (&process_, SIGNAL (readyReadStandardOutput()),
SLOT (readOutput()));
connect (&process_, SIGNAL (readyReadStandardError()),
SLOT (readError()));
connect (&process_, SIGNAL (started()),
SLOT (started()));
connect (&process_, SIGNAL (error(QProcess::ProcessError)),
SLOT (error(QProcess::ProcessError)));
connect (&process_, SIGNAL (finished(int, QProcess::ExitStatus)),
SLOT (finished(int, QProcess::ExitStatus)));
// Restart checking if got queue.
connect (&process_, SIGNAL (finished(int, QProcess::ExitStatus)),
SLOT (checkQueuedFiles ()));
}
CppcheckRunner::~CppcheckRunner()
{
if (process_.isOpen())
{
process_.kill();
}
queueTimer_.stop ();
settings_ = NULL;
delete futureInterface_;
}
void CppcheckRunner::updateSettings()
{
Q_ASSERT (settings_ != NULL);
showOutput_ = settings_->showBinaryOutput ();
runArguments_.clear ();
// Pass custom params BEFORE most of runner's to shadow if some repeat.
runArguments_ += settings_->customParameters ().split (
QLatin1Char (' '), QString::SkipEmptyParts);
QString enabled = QLatin1String ("--enable=warning,style,performance,"
"portability,information,missingInclude");
// Overwrite enable with user parameters if present
for(int i = runArguments_.size () - 1; i >= 0; --i)
{
if (runArguments_.at (i).startsWith (QLatin1String ("--enable")))
{
enabled = runArguments_.takeAt (i);
break;
}
}
if (settings_->checkUnused ())
{
enabled += QLatin1String (",unusedFunction");
}
else //TODO always check with threads but rescan for unused after finish?
{
runArguments_ << (QLatin1String ("-j ") +
QString::number (QThread::idealThreadCount ()));
}
runArguments_ << enabled;
if (settings_->checkInconclusive ())
{
runArguments_ << QLatin1String ("--inconclusive");
}
runArguments_ << QLatin1String ("--template={file},{line},{severity},{id},{message}");
}
void CppcheckRunner::checkFiles(const QStringList &fileNames)
{
Q_ASSERT (!fileNames.isEmpty ());
fileCheckQueue_ += fileNames;
fileCheckQueue_.removeDuplicates ();
fileCheckQueue_.sort ();
if (process_.isOpen ())
{
if (fileCheckQueue_ == currentlyCheckingFiles_)
{
process_.kill ();
// Rechecking will be restarted on finish signal.
}
return;
}
// Delay helps to avoid double checking same file on editor change.
const int checkDelayInMs = 200;
if (!queueTimer_.isActive ())
{
queueTimer_.singleShot (checkDelayInMs, this, SLOT (checkQueuedFiles ()));
}
}
void CppcheckRunner::stopChecking()
{
fileCheckQueue_.clear ();
if (process_.isOpen ())
{
process_.kill ();
}
}
void CppcheckRunner::checkQueuedFiles()
{
if (fileCheckQueue_.isEmpty ())
{
return;
}
QString binary = settings_->binaryFile ();
Q_ASSERT (!binary.isEmpty ());
QStringList arguments (runArguments_);
arguments += fileCheckQueue_;
currentlyCheckingFiles_ = fileCheckQueue_;
fileCheckQueue_.clear ();
emit startedChecking (currentlyCheckingFiles_);
process_.start (binary, arguments);
}
void CppcheckRunner::readOutput()
{
if (!showOutput_)
{
return;
}
process_.setReadChannel (QProcess::StandardOutput);
while (!process_.atEnd ())
{
QByteArray rawLine = process_.readLine ();
QString line = QString::fromUtf8 (rawLine).trimmed ();
if (line.isEmpty ())
{
continue;
}
const QString progressSample = QLatin1String ("% done");
if (line.endsWith (progressSample))
{
int percentEndIndex = line.length () - progressSample.length ();
int percentStartIndex = line.lastIndexOf(QLatin1String (" "), percentEndIndex);
int done = line.mid (percentStartIndex, percentEndIndex - percentStartIndex).toInt ();
futureInterface_->setProgressValue (done);
}
Core::MessageManager::write (line, Core::MessageManager::Silent);
}
}
void CppcheckRunner::readError()
{
process_.setReadChannel (QProcess::StandardError);
while (!process_.atEnd ())
{
QByteArray rawLine = process_.readLine ();
QString line = QString::fromUtf8 (rawLine).trimmed ();
if (line.isEmpty ())
{
continue;
}
if (showOutput_)
{
Core::MessageManager::write (line, Core::MessageManager::Silent);
}
QStringList details = line.split (QLatin1Char (','));
if (details.size () <= ErrorFieldMessage)
{
continue;
}
QString file = QDir::fromNativeSeparators(details.at (ErrorFieldFile));
int lineNumber = details.at (ErrorFieldLine).toInt ();
char type = details.at (ErrorFieldSeverity).at (0).toLatin1 ();
QString description = line.mid (line.indexOf (details.at (ErrorFieldMessage)));
emit newTask (type, description, file, lineNumber);
}
}
void CppcheckRunner::started()
{
if (showOutput_)
{
Core::MessageManager::write (tr ("Cppcheck started"), Core::MessageManager::Silent);
}
using namespace Core;
delete futureInterface_;
futureInterface_ = new QFutureInterface<void>;
FutureProgress *progress = ProgressManager::addTask(futureInterface_->future(),
tr("Cppcheck"), Constants::TASK_CHECKING);
connect (progress, SIGNAL(canceled ()), SLOT(stopChecking ()));
futureInterface_->setProgressRange(0, 100); // %
futureInterface_->reportStarted();
}
void CppcheckRunner::error(QProcess::ProcessError error)
{
Q_UNUSED (error);
if (showOutput_)
{
Core::MessageManager::write (tr ("Cppcheck error occured"), Core::MessageManager::Silent);
}
}
void CppcheckRunner::finished(int exitCode, QProcess::ExitStatus exitStatus)
{
Q_UNUSED (exitCode);
Q_UNUSED (exitStatus);
Q_ASSERT (futureInterface_ != NULL);
futureInterface_->reportFinished ();
process_.close ();
if (showOutput_)
{
Core::MessageManager::write (tr("Cppcheck finished"), Core::MessageManager::Silent);
}
}
<|endoftext|> |
<commit_before>#include "messagelayoutcontainer.hpp"
#include "messagelayoutelement.hpp"
#include "messages/selection.hpp"
#include "singletons/settingsmanager.hpp"
#include <QDebug>
#include <QPainter>
#define COMPACT_EMOTES_OFFSET 6
namespace chatterino {
namespace messages {
namespace layouts {
int MessageLayoutContainer::getHeight() const
{
return this->height;
}
int MessageLayoutContainer::getWidth() const
{
return this->width;
}
float MessageLayoutContainer::getScale() const
{
return this->scale;
}
// methods
void MessageLayoutContainer::begin(int _width, float _scale, Message::MessageFlags _flags)
{
this->clear();
this->width = _width;
this->scale = _scale;
this->flags = _flags;
}
void MessageLayoutContainer::clear()
{
this->elements.clear();
this->lines.clear();
this->height = 0;
this->line = 0;
this->currentX = 0;
this->currentY = 0;
this->lineStart = 0;
this->lineHeight = 0;
this->charIndex = 0;
}
void MessageLayoutContainer::addElement(MessageLayoutElement *element)
{
if (!this->fitsInLine(element->getRect().width())) {
this->breakLine();
}
this->_addElement(element);
}
void MessageLayoutContainer::addElementNoLineBreak(MessageLayoutElement *element)
{
this->_addElement(element);
}
void MessageLayoutContainer::_addElement(MessageLayoutElement *element)
{
// top margin
if (this->elements.size() == 0) {
this->currentY = this->margin.top * this->scale;
}
int newLineHeight = element->getRect().height();
// compact emote offset
bool isCompactEmote = !(this->flags & Message::DisableCompactEmotes) &&
element->getCreator().getFlags() & MessageElement::EmoteImages;
if (isCompactEmote) {
newLineHeight -= COMPACT_EMOTES_OFFSET * this->scale;
}
// update line height
this->lineHeight = std::max(this->lineHeight, newLineHeight);
// set move element
element->setPosition(QPoint(this->currentX, this->currentY - element->getRect().height()));
// add element
this->elements.push_back(std::unique_ptr<MessageLayoutElement>(element));
// set current x
this->currentX += element->getRect().width();
if (element->hasTrailingSpace()) {
this->currentX += this->spaceWidth;
}
}
void MessageLayoutContainer::breakLine()
{
int xOffset = 0;
if (this->flags & Message::Centered && this->elements.size() > 0) {
xOffset = (width - this->elements.at(this->elements.size() - 1)->getRect().right()) / 2;
}
for (size_t i = lineStart; i < this->elements.size(); i++) {
MessageLayoutElement *element = this->elements.at(i).get();
bool isCompactEmote = !(this->flags & Message::DisableCompactEmotes) &&
element->getCreator().getFlags() & MessageElement::EmoteImages;
int yExtra = 0;
if (isCompactEmote) {
yExtra = (COMPACT_EMOTES_OFFSET / 2) * this->scale;
}
element->setPosition(QPoint(element->getRect().x() + xOffset + this->margin.left,
element->getRect().y() + this->lineHeight + yExtra));
}
if (this->lines.size() != 0) {
this->lines.back().endIndex = this->lineStart;
this->lines.back().endCharIndex = this->charIndex;
}
this->lines.push_back({(int)lineStart, 0, this->charIndex, 0,
QRect(-100000, this->currentY, 200000, lineHeight)});
for (int i = this->lineStart; i < this->elements.size(); i++) {
this->charIndex += this->elements[i]->getSelectionIndexCount();
}
this->lineStart = this->elements.size();
// this->currentX = (int)(this->scale * 8);
this->currentX = 0;
this->currentY += this->lineHeight;
this->height = this->currentY + (this->margin.bottom * this->scale);
this->lineHeight = 0;
}
bool MessageLayoutContainer::atStartOfLine()
{
return this->lineStart == this->elements.size();
}
bool MessageLayoutContainer::fitsInLine(int _width)
{
return this->currentX + _width <= this->width - this->margin.left - this->margin.right;
}
void MessageLayoutContainer::end()
{
if (!this->atStartOfLine()) {
this->breakLine();
}
if (this->lines.size() != 0) {
this->lines[0].rect.setTop(-100000);
this->lines.back().rect.setBottom(100000);
this->lines.back().endIndex = this->elements.size();
this->lines.back().endCharIndex = this->charIndex;
}
}
MessageLayoutElement *MessageLayoutContainer::getElementAt(QPoint point)
{
for (std::unique_ptr<MessageLayoutElement> &element : this->elements) {
if (element->getRect().contains(point)) {
return element.get();
}
}
return nullptr;
}
// painting
void MessageLayoutContainer::paintElements(QPainter &painter)
{
for (const std::unique_ptr<MessageLayoutElement> &element : this->elements) {
#ifdef OHHEYITSFOURTF
painter.setPen(QColor(0, 255, 0));
painter.drawRect(element->getRect());
#endif
element->paint(painter);
}
}
void MessageLayoutContainer::paintAnimatedElements(QPainter &painter, int yOffset)
{
for (const std::unique_ptr<MessageLayoutElement> &element : this->elements) {
element->paintAnimated(painter, yOffset);
}
}
void MessageLayoutContainer::paintSelection(QPainter &painter, int messageIndex,
Selection &selection, int yOffset)
{
singletons::ThemeManager &themeManager = singletons::ThemeManager::getInstance();
QColor selectionColor = themeManager.messages.selection;
// don't draw anything
if (selection.min.messageIndex > messageIndex || selection.max.messageIndex < messageIndex) {
return;
}
// fully selected
if (selection.min.messageIndex < messageIndex && selection.max.messageIndex > messageIndex) {
for (Line &line : this->lines) {
QRect rect = line.rect;
rect.setTop(std::max(0, rect.top()) + yOffset);
rect.setBottom(std::min(this->height, rect.bottom()) + yOffset);
rect.setLeft(this->elements[line.startIndex]->getRect().left());
rect.setRight(this->elements[line.endIndex - 1]->getRect().right());
painter.fillRect(rect, selectionColor);
}
return;
}
int lineIndex = 0;
int index = 0;
// start in this message
if (selection.min.messageIndex == messageIndex) {
for (; lineIndex < this->lines.size(); lineIndex++) {
Line &line = this->lines[lineIndex];
index = line.startCharIndex;
bool returnAfter = false;
bool breakAfter = false;
int x = this->elements[line.startIndex]->getRect().left();
int r = this->elements[line.endIndex - 1]->getRect().right();
if (line.endCharIndex < selection.min.charIndex) {
continue;
}
for (int i = line.startIndex; i < line.endIndex; i++) {
int c = this->elements[i]->getSelectionIndexCount();
if (index + c > selection.min.charIndex) {
x = this->elements[i]->getXFromIndex(selection.min.charIndex - index);
// ends in same line
if (selection.max.messageIndex == messageIndex &&
line.endCharIndex > /*=*/selection.max.charIndex) //
{
returnAfter = true;
index = line.startCharIndex;
for (int i = line.startIndex; i < line.endIndex; i++) {
int c = this->elements[i]->getSelectionIndexCount();
if (index + c > selection.max.charIndex) {
r = this->elements[i]->getXFromIndex(selection.max.charIndex -
index);
break;
}
index += c;
}
}
// ends in same line end
if (selection.max.messageIndex != messageIndex) {
int lineIndex2 = lineIndex + 1;
for (; lineIndex2 < this->lines.size(); lineIndex2++) {
Line &line = this->lines[lineIndex2];
QRect rect = line.rect;
rect.setTop(std::max(0, rect.top()) + yOffset);
rect.setBottom(std::min(this->height, rect.bottom()) + yOffset);
rect.setLeft(this->elements[line.startIndex]->getRect().left());
rect.setRight(this->elements[line.endIndex - 1]->getRect().right());
painter.fillRect(rect, selectionColor);
}
returnAfter = true;
} else {
lineIndex++;
breakAfter = true;
}
break;
}
index += c;
}
QRect rect = line.rect;
rect.setTop(std::max(0, rect.top()) + yOffset);
rect.setBottom(std::min(this->height, rect.bottom()) + yOffset);
rect.setLeft(x);
rect.setRight(r);
painter.fillRect(rect, selectionColor);
if (returnAfter) {
return;
}
if (breakAfter) {
break;
}
}
}
// start in this message
for (; lineIndex < this->lines.size(); lineIndex++) {
Line &line = this->lines[lineIndex];
index = line.startCharIndex;
// just draw the garbage
if (line.endCharIndex < /*=*/selection.max.charIndex) {
QRect rect = line.rect;
rect.setTop(std::max(0, rect.top()) + yOffset);
rect.setBottom(std::min(this->height, rect.bottom()) + yOffset);
rect.setLeft(this->elements[line.startIndex]->getRect().left());
rect.setRight(this->elements[line.endIndex - 1]->getRect().right());
painter.fillRect(rect, selectionColor);
continue;
}
int r = this->elements[line.endIndex - 1]->getRect().right();
for (int i = line.startIndex; i < line.endIndex; i++) {
int c = this->elements[i]->getSelectionIndexCount();
if (index + c > selection.max.charIndex) {
r = this->elements[i]->getXFromIndex(selection.max.charIndex - index);
break;
}
index += c;
}
QRect rect = line.rect;
rect.setTop(std::max(0, rect.top()) + yOffset);
rect.setBottom(std::min(this->height, rect.bottom()) + yOffset);
rect.setLeft(this->elements[line.startIndex]->getRect().left());
rect.setRight(r);
painter.fillRect(rect, selectionColor);
break;
}
}
// selection
int MessageLayoutContainer::getSelectionIndex(QPoint point)
{
if (this->elements.size() == 0) {
return 0;
}
auto line = this->lines.begin();
for (; line != this->lines.end(); line++) {
if (line->rect.contains(point)) {
break;
}
}
int lineStart = line == this->lines.end() ? this->lines.back().startIndex : line->startIndex;
if (line != this->lines.end()) {
line++;
}
int lineEnd = line == this->lines.end() ? this->elements.size() : line->startIndex;
int index = 0;
for (int i = 0; i < lineEnd; i++) {
// end of line
if (i == lineEnd) {
break;
}
// before line
if (i < lineStart) {
index += this->elements[i]->getSelectionIndexCount();
continue;
}
// this is the word
if (point.x() < this->elements[i]->getRect().right()) {
index += this->elements[i]->getMouseOverIndex(point);
break;
}
index += this->elements[i]->getSelectionIndexCount();
}
return index;
}
// fourtf: no idea if this is acurate LOL
int MessageLayoutContainer::getLastCharacterIndex() const
{
if (this->lines.size() == 0) {
return 0;
}
return this->lines.back().endCharIndex;
}
void MessageLayoutContainer::addSelectionText(QString &str, int from, int to)
{
int index = 0;
bool first = true;
for (std::unique_ptr<MessageLayoutElement> &ele : this->elements) {
int c = ele->getSelectionIndexCount();
qDebug() << c;
if (first) {
if (index + c > from) {
ele->addCopyTextToString(str, from - index, to - from);
first = false;
}
} else {
if (index + c > to) {
ele->addCopyTextToString(str, 0, to - index);
break;
} else {
ele->addCopyTextToString(str);
}
}
index += c;
}
}
} // namespace layouts
} // namespace messages
} // namespace chatterino
<commit_msg>fixed text copying if a single word is selected<commit_after>#include "messagelayoutcontainer.hpp"
#include "messagelayoutelement.hpp"
#include "messages/selection.hpp"
#include "singletons/settingsmanager.hpp"
#include <QDebug>
#include <QPainter>
#define COMPACT_EMOTES_OFFSET 6
namespace chatterino {
namespace messages {
namespace layouts {
int MessageLayoutContainer::getHeight() const
{
return this->height;
}
int MessageLayoutContainer::getWidth() const
{
return this->width;
}
float MessageLayoutContainer::getScale() const
{
return this->scale;
}
// methods
void MessageLayoutContainer::begin(int _width, float _scale, Message::MessageFlags _flags)
{
this->clear();
this->width = _width;
this->scale = _scale;
this->flags = _flags;
}
void MessageLayoutContainer::clear()
{
this->elements.clear();
this->lines.clear();
this->height = 0;
this->line = 0;
this->currentX = 0;
this->currentY = 0;
this->lineStart = 0;
this->lineHeight = 0;
this->charIndex = 0;
}
void MessageLayoutContainer::addElement(MessageLayoutElement *element)
{
if (!this->fitsInLine(element->getRect().width())) {
this->breakLine();
}
this->_addElement(element);
}
void MessageLayoutContainer::addElementNoLineBreak(MessageLayoutElement *element)
{
this->_addElement(element);
}
void MessageLayoutContainer::_addElement(MessageLayoutElement *element)
{
// top margin
if (this->elements.size() == 0) {
this->currentY = this->margin.top * this->scale;
}
int newLineHeight = element->getRect().height();
// compact emote offset
bool isCompactEmote = !(this->flags & Message::DisableCompactEmotes) &&
element->getCreator().getFlags() & MessageElement::EmoteImages;
if (isCompactEmote) {
newLineHeight -= COMPACT_EMOTES_OFFSET * this->scale;
}
// update line height
this->lineHeight = std::max(this->lineHeight, newLineHeight);
// set move element
element->setPosition(QPoint(this->currentX, this->currentY - element->getRect().height()));
// add element
this->elements.push_back(std::unique_ptr<MessageLayoutElement>(element));
// set current x
this->currentX += element->getRect().width();
if (element->hasTrailingSpace()) {
this->currentX += this->spaceWidth;
}
}
void MessageLayoutContainer::breakLine()
{
int xOffset = 0;
if (this->flags & Message::Centered && this->elements.size() > 0) {
xOffset = (width - this->elements.at(this->elements.size() - 1)->getRect().right()) / 2;
}
for (size_t i = lineStart; i < this->elements.size(); i++) {
MessageLayoutElement *element = this->elements.at(i).get();
bool isCompactEmote = !(this->flags & Message::DisableCompactEmotes) &&
element->getCreator().getFlags() & MessageElement::EmoteImages;
int yExtra = 0;
if (isCompactEmote) {
yExtra = (COMPACT_EMOTES_OFFSET / 2) * this->scale;
}
element->setPosition(QPoint(element->getRect().x() + xOffset + this->margin.left,
element->getRect().y() + this->lineHeight + yExtra));
}
if (this->lines.size() != 0) {
this->lines.back().endIndex = this->lineStart;
this->lines.back().endCharIndex = this->charIndex;
}
this->lines.push_back({(int)lineStart, 0, this->charIndex, 0,
QRect(-100000, this->currentY, 200000, lineHeight)});
for (int i = this->lineStart; i < this->elements.size(); i++) {
this->charIndex += this->elements[i]->getSelectionIndexCount();
}
this->lineStart = this->elements.size();
// this->currentX = (int)(this->scale * 8);
this->currentX = 0;
this->currentY += this->lineHeight;
this->height = this->currentY + (this->margin.bottom * this->scale);
this->lineHeight = 0;
}
bool MessageLayoutContainer::atStartOfLine()
{
return this->lineStart == this->elements.size();
}
bool MessageLayoutContainer::fitsInLine(int _width)
{
return this->currentX + _width <= this->width - this->margin.left - this->margin.right;
}
void MessageLayoutContainer::end()
{
if (!this->atStartOfLine()) {
this->breakLine();
}
if (this->lines.size() != 0) {
this->lines[0].rect.setTop(-100000);
this->lines.back().rect.setBottom(100000);
this->lines.back().endIndex = this->elements.size();
this->lines.back().endCharIndex = this->charIndex;
}
}
MessageLayoutElement *MessageLayoutContainer::getElementAt(QPoint point)
{
for (std::unique_ptr<MessageLayoutElement> &element : this->elements) {
if (element->getRect().contains(point)) {
return element.get();
}
}
return nullptr;
}
// painting
void MessageLayoutContainer::paintElements(QPainter &painter)
{
for (const std::unique_ptr<MessageLayoutElement> &element : this->elements) {
#ifdef OHHEYITSFOURTF
painter.setPen(QColor(0, 255, 0));
painter.drawRect(element->getRect());
#endif
element->paint(painter);
}
}
void MessageLayoutContainer::paintAnimatedElements(QPainter &painter, int yOffset)
{
for (const std::unique_ptr<MessageLayoutElement> &element : this->elements) {
element->paintAnimated(painter, yOffset);
}
}
void MessageLayoutContainer::paintSelection(QPainter &painter, int messageIndex,
Selection &selection, int yOffset)
{
singletons::ThemeManager &themeManager = singletons::ThemeManager::getInstance();
QColor selectionColor = themeManager.messages.selection;
// don't draw anything
if (selection.min.messageIndex > messageIndex || selection.max.messageIndex < messageIndex) {
return;
}
// fully selected
if (selection.min.messageIndex < messageIndex && selection.max.messageIndex > messageIndex) {
for (Line &line : this->lines) {
QRect rect = line.rect;
rect.setTop(std::max(0, rect.top()) + yOffset);
rect.setBottom(std::min(this->height, rect.bottom()) + yOffset);
rect.setLeft(this->elements[line.startIndex]->getRect().left());
rect.setRight(this->elements[line.endIndex - 1]->getRect().right());
painter.fillRect(rect, selectionColor);
}
return;
}
int lineIndex = 0;
int index = 0;
// start in this message
if (selection.min.messageIndex == messageIndex) {
for (; lineIndex < this->lines.size(); lineIndex++) {
Line &line = this->lines[lineIndex];
index = line.startCharIndex;
bool returnAfter = false;
bool breakAfter = false;
int x = this->elements[line.startIndex]->getRect().left();
int r = this->elements[line.endIndex - 1]->getRect().right();
if (line.endCharIndex < selection.min.charIndex) {
continue;
}
for (int i = line.startIndex; i < line.endIndex; i++) {
int c = this->elements[i]->getSelectionIndexCount();
if (index + c > selection.min.charIndex) {
x = this->elements[i]->getXFromIndex(selection.min.charIndex - index);
// ends in same line
if (selection.max.messageIndex == messageIndex &&
line.endCharIndex > /*=*/selection.max.charIndex) //
{
returnAfter = true;
index = line.startCharIndex;
for (int i = line.startIndex; i < line.endIndex; i++) {
int c = this->elements[i]->getSelectionIndexCount();
if (index + c > selection.max.charIndex) {
r = this->elements[i]->getXFromIndex(selection.max.charIndex -
index);
break;
}
index += c;
}
}
// ends in same line end
if (selection.max.messageIndex != messageIndex) {
int lineIndex2 = lineIndex + 1;
for (; lineIndex2 < this->lines.size(); lineIndex2++) {
Line &line = this->lines[lineIndex2];
QRect rect = line.rect;
rect.setTop(std::max(0, rect.top()) + yOffset);
rect.setBottom(std::min(this->height, rect.bottom()) + yOffset);
rect.setLeft(this->elements[line.startIndex]->getRect().left());
rect.setRight(this->elements[line.endIndex - 1]->getRect().right());
painter.fillRect(rect, selectionColor);
}
returnAfter = true;
} else {
lineIndex++;
breakAfter = true;
}
break;
}
index += c;
}
QRect rect = line.rect;
rect.setTop(std::max(0, rect.top()) + yOffset);
rect.setBottom(std::min(this->height, rect.bottom()) + yOffset);
rect.setLeft(x);
rect.setRight(r);
painter.fillRect(rect, selectionColor);
if (returnAfter) {
return;
}
if (breakAfter) {
break;
}
}
}
// start in this message
for (; lineIndex < this->lines.size(); lineIndex++) {
Line &line = this->lines[lineIndex];
index = line.startCharIndex;
// just draw the garbage
if (line.endCharIndex < /*=*/selection.max.charIndex) {
QRect rect = line.rect;
rect.setTop(std::max(0, rect.top()) + yOffset);
rect.setBottom(std::min(this->height, rect.bottom()) + yOffset);
rect.setLeft(this->elements[line.startIndex]->getRect().left());
rect.setRight(this->elements[line.endIndex - 1]->getRect().right());
painter.fillRect(rect, selectionColor);
continue;
}
int r = this->elements[line.endIndex - 1]->getRect().right();
for (int i = line.startIndex; i < line.endIndex; i++) {
int c = this->elements[i]->getSelectionIndexCount();
if (index + c > selection.max.charIndex) {
r = this->elements[i]->getXFromIndex(selection.max.charIndex - index);
break;
}
index += c;
}
QRect rect = line.rect;
rect.setTop(std::max(0, rect.top()) + yOffset);
rect.setBottom(std::min(this->height, rect.bottom()) + yOffset);
rect.setLeft(this->elements[line.startIndex]->getRect().left());
rect.setRight(r);
painter.fillRect(rect, selectionColor);
break;
}
}
// selection
int MessageLayoutContainer::getSelectionIndex(QPoint point)
{
if (this->elements.size() == 0) {
return 0;
}
auto line = this->lines.begin();
for (; line != this->lines.end(); line++) {
if (line->rect.contains(point)) {
break;
}
}
int lineStart = line == this->lines.end() ? this->lines.back().startIndex : line->startIndex;
if (line != this->lines.end()) {
line++;
}
int lineEnd = line == this->lines.end() ? this->elements.size() : line->startIndex;
int index = 0;
for (int i = 0; i < lineEnd; i++) {
// end of line
if (i == lineEnd) {
break;
}
// before line
if (i < lineStart) {
index += this->elements[i]->getSelectionIndexCount();
continue;
}
// this is the word
if (point.x() < this->elements[i]->getRect().right()) {
index += this->elements[i]->getMouseOverIndex(point);
break;
}
index += this->elements[i]->getSelectionIndexCount();
}
return index;
}
// fourtf: no idea if this is acurate LOL
int MessageLayoutContainer::getLastCharacterIndex() const
{
if (this->lines.size() == 0) {
return 0;
}
return this->lines.back().endCharIndex;
}
void MessageLayoutContainer::addSelectionText(QString &str, int from, int to)
{
int index = 0;
bool first = true;
for (std::unique_ptr<MessageLayoutElement> &ele : this->elements) {
int c = ele->getSelectionIndexCount();
qDebug() << c;
if (first) {
if (index + c > from) {
ele->addCopyTextToString(str, from - index, to - index);
first = false;
if (index + c > to) {
break;
}
}
} else {
if (index + c > to) {
ele->addCopyTextToString(str, 0, to - index);
break;
} else {
ele->addCopyTextToString(str);
}
}
index += c;
}
}
} // namespace layouts
} // namespace messages
} // namespace chatterino
<|endoftext|> |
<commit_before>/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <list>
#include <sys/time.h>
#include <process/process.hpp>
#include "monitoring/linux/proc_utils.hpp"
#include "monitoring/linux/lxc_resource_collector.hpp"
#include "common/utils.hpp"
#include "common/resources.hpp"
#include "common/seconds.hpp"
#include "mesos/mesos.hpp"
using process::Clock;
namespace mesos {
namespace internal {
namespace monitoring {
LxcResourceCollector::LxcResourceCollector(const std::string& _containerName)
: containerName(_containerName), previousTimestamp(-1.0), previousCpuTicks(0.0)
{
}
LxcResourceCollector::~LxcResourceCollector() {}
Try<double> LxcResourceCollector::getMemoryUsage()
{
return getControlGroupDoubleValue("memory.memsw.usage_in_bytes");
}
Try<Rate> LxcResourceCollector::getCpuUsage()
{
if (previousTimestamp == -1.0) {
// TODO(sam): Make this handle the Try of the getStartTime.
previousTimestamp = getContainerStartTime().get().value;
}
double seconds = Clock::now();
Try<double> cpuTicks = getControlGroupDoubleValue("cpuacct.usage");
if (cpuTicks.isError()) {
return Try<Rate>::error("unable to read cpuacct.usage from lxc");
}
double ticks = nanoseconds(cpuTicks.get()).secs();
double elapsedTicks = ticks - previousCpuTicks;
previousCpuTicks = ticks;
double elapsedTime = seconds - previousTimestamp;
previousTimestamp = seconds;
return Rate(elapsedTime, elapsedTicks);
}
bool LxcResourceCollector::getControlGroupValue(
std::iostream* ios, const std::string& property) const
{
Try<int> status =
utils::os::shell(ios, "lxc-cgroup -n %s %s",
containerName.c_str(), property.c_str());
if (status.isError()) {
LOG(ERROR) << "Failed to get " << property
<< " for container " << containerName
<< ": " << status.error();
return false;
} else if (status.get() != 0) {
LOG(ERROR) << "Failed to get " << property
<< " for container " << containerName
<< ": lxc-cgroup returned " << status.get();
return false;
}
return true;
}
Try<double> LxcResourceCollector::getControlGroupDoubleValue(const std::string& property) const
{
std::stringstream ss;
if (getControlGroupValue(&ss, property)) {
double d;
ss >> d;
return d;
} else {
return Try<double>::error("unable to read control group double value");
}
}
Try<seconds> LxcResourceCollector::getContainerStartTime() const
{
using namespace std;
Try<list<pid_t> > allPidsTry = getAllPids();
if (allPidsTry.isError()) {
return Try<seconds>::error(allPidsTry.error());
}
// TODO does this need to be sorted?
return getStartTime(allPidsTry.get().front());
}
} // namespace monitoring {
} // namespace internal {
} // namespace mesos {
<commit_msg>lxc container failures logged as INFO instead of ERROR, because no container just means async triviality<commit_after>/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <list>
#include <sys/time.h>
#include <process/process.hpp>
#include "monitoring/linux/proc_utils.hpp"
#include "monitoring/linux/lxc_resource_collector.hpp"
#include "common/utils.hpp"
#include "common/resources.hpp"
#include "common/seconds.hpp"
#include "mesos/mesos.hpp"
using process::Clock;
namespace mesos {
namespace internal {
namespace monitoring {
LxcResourceCollector::LxcResourceCollector(const std::string& _containerName)
: containerName(_containerName), previousTimestamp(-1.0), previousCpuTicks(0.0)
{
}
LxcResourceCollector::~LxcResourceCollector() {}
Try<double> LxcResourceCollector::getMemoryUsage()
{
return getControlGroupDoubleValue("memory.memsw.usage_in_bytes");
}
Try<Rate> LxcResourceCollector::getCpuUsage()
{
if (previousTimestamp == -1.0) {
// TODO(sam): Make this handle the Try of the getStartTime.
previousTimestamp = getContainerStartTime().get().value;
}
double seconds = Clock::now();
Try<double> cpuTicks = getControlGroupDoubleValue("cpuacct.usage");
if (cpuTicks.isError()) {
return Try<Rate>::error("unable to read cpuacct.usage from lxc");
}
double ticks = nanoseconds(cpuTicks.get()).secs();
double elapsedTicks = ticks - previousCpuTicks;
previousCpuTicks = ticks;
double elapsedTime = seconds - previousTimestamp;
previousTimestamp = seconds;
return Rate(elapsedTime, elapsedTicks);
}
bool LxcResourceCollector::getControlGroupValue(
std::iostream* ios, const std::string& property) const
{
Try<int> status =
utils::os::shell(ios, "lxc-cgroup -n %s %s",
containerName.c_str(), property.c_str());
if (status.isError()) {
LOG(INFO) << "Failed to get " << property
<< " for container " << containerName
<< ": " << status.error();
return false;
} else if (status.get() != 0) {
LOG(INFO) << "Failed to get " << property
<< " for container " << containerName
<< ": lxc-cgroup returned " << status.get();
return false;
}
return true;
}
Try<double> LxcResourceCollector::getControlGroupDoubleValue(const std::string& property) const
{
std::stringstream ss;
if (getControlGroupValue(&ss, property)) {
double d;
ss >> d;
return d;
} else {
return Try<double>::error("unable to read control group double value");
}
}
Try<seconds> LxcResourceCollector::getContainerStartTime() const
{
using namespace std;
Try<list<pid_t> > allPidsTry = getAllPids();
if (allPidsTry.isError()) {
return Try<seconds>::error(allPidsTry.error());
}
// TODO does this need to be sorted?
return getStartTime(allPidsTry.get().front());
}
} // namespace monitoring {
} // namespace internal {
} // namespace mesos {
<|endoftext|> |
<commit_before><commit_msg>Injected quick-http needs into latest SWS codebase<commit_after><|endoftext|> |
<commit_before>#include "selfdrive/loggerd/loggerd.h"
ExitHandler do_exit;
// Handle initial encoder syncing by waiting for all encoders to reach the same frame id
bool sync_encoders(LoggerdState *s, CameraType cam_type, uint32_t frame_id) {
if (s->camera_synced[cam_type]) return true;
if (s->max_waiting > 1 && s->encoders_ready != s->max_waiting) {
// add a small margin to the start frame id in case one of the encoders already dropped the next frame
update_max_atomic(s->start_frame_id, frame_id + 2);
if (std::exchange(s->camera_ready[cam_type], true) == false) {
++s->encoders_ready;
LOGE("camera %d encoder ready", cam_type);
}
return false;
} else {
if (s->max_waiting == 1) update_max_atomic(s->start_frame_id, frame_id);
bool synced = frame_id >= s->start_frame_id;
s->camera_synced[cam_type] = synced;
if (!synced) LOGE("camera %d waiting for frame %d, cur %d", cam_type, (int)s->start_frame_id, frame_id);
return synced;
}
}
bool trigger_rotate_if_needed(LoggerdState *s, int cur_seg, uint32_t frame_id) {
const int frames_per_seg = SEGMENT_LENGTH * MAIN_FPS;
if (cur_seg >= 0 && frame_id >= ((cur_seg + 1) * frames_per_seg) + s->start_frame_id) {
// trigger rotate and wait until the main logger has rotated to the new segment
++s->ready_to_rotate;
std::unique_lock lk(s->rotate_lock);
s->rotate_cv.wait(lk, [&] {
return s->rotate_segment > cur_seg || do_exit;
});
return !do_exit;
}
return false;
}
void encoder_thread(LoggerdState *s, const LogCameraInfo &cam_info) {
set_thread_name(cam_info.filename);
int cur_seg = -1;
int encode_idx = 0;
LoggerHandle *lh = NULL;
std::vector<Encoder *> encoders;
VisionIpcClient vipc_client = VisionIpcClient("camerad", cam_info.stream_type, false);
while (!do_exit) {
if (!vipc_client.connect(false)) {
util::sleep_for(5);
continue;
}
// init encoders
if (encoders.empty()) {
VisionBuf buf_info = vipc_client.buffers[0];
LOGD("encoder init %dx%d", buf_info.width, buf_info.height);
// main encoder
encoders.push_back(new Encoder(cam_info.filename, buf_info.width, buf_info.height,
cam_info.fps, cam_info.bitrate, cam_info.is_h265,
cam_info.downscale, cam_info.record));
// qcamera encoder
if (cam_info.has_qcamera) {
encoders.push_back(new Encoder(qcam_info.filename, qcam_info.frame_width, qcam_info.frame_height,
qcam_info.fps, qcam_info.bitrate, qcam_info.is_h265, qcam_info.downscale));
}
}
while (!do_exit) {
VisionIpcBufExtra extra;
VisionBuf* buf = vipc_client.recv(&extra);
if (buf == nullptr) continue;
if (cam_info.trigger_rotate) {
s->last_camera_seen_tms = millis_since_boot();
if (!sync_encoders(s, cam_info.type, extra.frame_id)) {
continue;
}
// check if we're ready to rotate
trigger_rotate_if_needed(s, cur_seg, extra.frame_id);
if (do_exit) break;
}
// rotate the encoder if the logger is on a newer segment
if (s->rotate_segment > cur_seg) {
cur_seg = s->rotate_segment;
LOGW("camera %d rotate encoder to %s", cam_info.type, s->segment_path);
for (auto &e : encoders) {
e->encoder_close();
e->encoder_open(s->segment_path);
}
if (lh) {
lh_close(lh);
}
lh = logger_get_handle(&s->logger);
}
// encode a frame
for (int i = 0; i < encoders.size(); ++i) {
int out_id = encoders[i]->encode_frame(buf->y, buf->u, buf->v,
buf->width, buf->height, extra.timestamp_eof);
if (out_id == -1) {
LOGE("Failed to encode frame. frame_id: %d encode_id: %d", extra.frame_id, encode_idx);
}
// publish encode index
if (i == 0 && out_id != -1) {
MessageBuilder msg;
// this is really ugly
bool valid = (buf->get_frame_id() == extra.frame_id);
auto eidx = cam_info.type == DriverCam ? msg.initEvent(valid).initDriverEncodeIdx() :
(cam_info.type == WideRoadCam ? msg.initEvent(valid).initWideRoadEncodeIdx() : msg.initEvent(valid).initRoadEncodeIdx());
eidx.setFrameId(extra.frame_id);
eidx.setTimestampSof(extra.timestamp_sof);
eidx.setTimestampEof(extra.timestamp_eof);
if (Hardware::TICI()) {
eidx.setType(cereal::EncodeIndex::Type::FULL_H_E_V_C);
} else {
eidx.setType(cam_info.type == DriverCam ? cereal::EncodeIndex::Type::FRONT : cereal::EncodeIndex::Type::FULL_H_E_V_C);
}
eidx.setEncodeId(encode_idx);
eidx.setSegmentNum(cur_seg);
eidx.setSegmentId(out_id);
if (lh) {
auto bytes = msg.toBytes();
lh_log(lh, bytes.begin(), bytes.size(), true);
}
}
}
encode_idx++;
}
if (lh) {
lh_close(lh);
lh = NULL;
}
}
LOG("encoder destroy");
for(auto &e : encoders) {
e->encoder_close();
delete e;
}
}
void logger_rotate(LoggerdState *s) {
{
std::unique_lock lk(s->rotate_lock);
int segment = -1;
int err = logger_next(&s->logger, LOG_ROOT.c_str(), s->segment_path, sizeof(s->segment_path), &segment);
assert(err == 0);
s->rotate_segment = segment;
s->ready_to_rotate = 0;
s->last_rotate_tms = millis_since_boot();
}
s->rotate_cv.notify_all();
LOGW((s->logger.part == 0) ? "logging to %s" : "rotated to %s", s->segment_path);
}
void rotate_if_needed(LoggerdState *s) {
if (s->ready_to_rotate == s->max_waiting) {
logger_rotate(s);
}
double tms = millis_since_boot();
if ((tms - s->last_rotate_tms) > SEGMENT_LENGTH * 1000 &&
(tms - s->last_camera_seen_tms) > NO_CAMERA_PATIENCE &&
!LOGGERD_TEST) {
LOGW("no camera packet seen. auto rotating");
logger_rotate(s);
}
}
void loggerd_thread() {
// setup messaging
typedef struct QlogState {
int counter, freq;
} QlogState;
std::unordered_map<SubSocket*, QlogState> qlog_states;
LoggerdState s;
s.ctx = Context::create();
Poller * poller = Poller::create();
// subscribe to all socks
for (const auto& it : services) {
if (!it.should_log) continue;
SubSocket * sock = SubSocket::create(s.ctx, it.name);
assert(sock != NULL);
poller->registerSocket(sock);
qlog_states[sock] = {.counter = 0, .freq = it.decimation};
}
// init logger
logger_init(&s.logger, "rlog", true);
logger_rotate(&s);
Params().put("CurrentRoute", s.logger.route_name);
// init encoders
s.last_camera_seen_tms = millis_since_boot();
std::vector<std::thread> encoder_threads;
for (const auto &cam : cameras_logged) {
if (cam.enable) {
encoder_threads.push_back(std::thread(encoder_thread, &s, cam));
if (cam.trigger_rotate) s.max_waiting++;
}
}
uint64_t msg_count = 0, bytes_count = 0;
double start_ts = millis_since_boot();
while (!do_exit) {
// poll for new messages on all sockets
for (auto sock : poller->poll(1000)) {
// drain socket
QlogState &qs = qlog_states[sock];
Message *msg = nullptr;
while (!do_exit && (msg = sock->receive(true))) {
const bool in_qlog = qs.freq != -1 && (qs.counter++ % qs.freq == 0);
logger_log(&s.logger, (uint8_t *)msg->getData(), msg->getSize(), in_qlog);
bytes_count += msg->getSize();
delete msg;
rotate_if_needed(&s);
if ((++msg_count % 1000) == 0) {
double seconds = (millis_since_boot() - start_ts) / 1000.0;
LOGD("%lu messages, %.2f msg/sec, %.2f KB/sec", msg_count, msg_count / seconds, bytes_count * 0.001 / seconds);
}
}
}
}
LOGW("closing encoders");
s.rotate_cv.notify_all();
for (auto &t : encoder_threads) t.join();
LOGW("closing logger");
logger_close(&s.logger, &do_exit);
if (do_exit.power_failure) {
LOGE("power failure");
sync();
LOGE("sync done");
}
// messaging cleanup
for (auto &[sock, qs] : qlog_states) delete sock;
delete poller;
delete s.ctx;
}
<commit_msg>loggerd: don't let a single service clog up the main thread<commit_after>#include "selfdrive/loggerd/loggerd.h"
ExitHandler do_exit;
// Handle initial encoder syncing by waiting for all encoders to reach the same frame id
bool sync_encoders(LoggerdState *s, CameraType cam_type, uint32_t frame_id) {
if (s->camera_synced[cam_type]) return true;
if (s->max_waiting > 1 && s->encoders_ready != s->max_waiting) {
// add a small margin to the start frame id in case one of the encoders already dropped the next frame
update_max_atomic(s->start_frame_id, frame_id + 2);
if (std::exchange(s->camera_ready[cam_type], true) == false) {
++s->encoders_ready;
LOGE("camera %d encoder ready", cam_type);
}
return false;
} else {
if (s->max_waiting == 1) update_max_atomic(s->start_frame_id, frame_id);
bool synced = frame_id >= s->start_frame_id;
s->camera_synced[cam_type] = synced;
if (!synced) LOGE("camera %d waiting for frame %d, cur %d", cam_type, (int)s->start_frame_id, frame_id);
return synced;
}
}
bool trigger_rotate_if_needed(LoggerdState *s, int cur_seg, uint32_t frame_id) {
const int frames_per_seg = SEGMENT_LENGTH * MAIN_FPS;
if (cur_seg >= 0 && frame_id >= ((cur_seg + 1) * frames_per_seg) + s->start_frame_id) {
// trigger rotate and wait until the main logger has rotated to the new segment
++s->ready_to_rotate;
std::unique_lock lk(s->rotate_lock);
s->rotate_cv.wait(lk, [&] {
return s->rotate_segment > cur_seg || do_exit;
});
return !do_exit;
}
return false;
}
void encoder_thread(LoggerdState *s, const LogCameraInfo &cam_info) {
set_thread_name(cam_info.filename);
int cur_seg = -1;
int encode_idx = 0;
LoggerHandle *lh = NULL;
std::vector<Encoder *> encoders;
VisionIpcClient vipc_client = VisionIpcClient("camerad", cam_info.stream_type, false);
while (!do_exit) {
if (!vipc_client.connect(false)) {
util::sleep_for(5);
continue;
}
// init encoders
if (encoders.empty()) {
VisionBuf buf_info = vipc_client.buffers[0];
LOGD("encoder init %dx%d", buf_info.width, buf_info.height);
// main encoder
encoders.push_back(new Encoder(cam_info.filename, buf_info.width, buf_info.height,
cam_info.fps, cam_info.bitrate, cam_info.is_h265,
cam_info.downscale, cam_info.record));
// qcamera encoder
if (cam_info.has_qcamera) {
encoders.push_back(new Encoder(qcam_info.filename, qcam_info.frame_width, qcam_info.frame_height,
qcam_info.fps, qcam_info.bitrate, qcam_info.is_h265, qcam_info.downscale));
}
}
while (!do_exit) {
VisionIpcBufExtra extra;
VisionBuf* buf = vipc_client.recv(&extra);
if (buf == nullptr) continue;
if (cam_info.trigger_rotate) {
s->last_camera_seen_tms = millis_since_boot();
if (!sync_encoders(s, cam_info.type, extra.frame_id)) {
continue;
}
// check if we're ready to rotate
trigger_rotate_if_needed(s, cur_seg, extra.frame_id);
if (do_exit) break;
}
// rotate the encoder if the logger is on a newer segment
if (s->rotate_segment > cur_seg) {
cur_seg = s->rotate_segment;
LOGW("camera %d rotate encoder to %s", cam_info.type, s->segment_path);
for (auto &e : encoders) {
e->encoder_close();
e->encoder_open(s->segment_path);
}
if (lh) {
lh_close(lh);
}
lh = logger_get_handle(&s->logger);
}
// encode a frame
for (int i = 0; i < encoders.size(); ++i) {
int out_id = encoders[i]->encode_frame(buf->y, buf->u, buf->v,
buf->width, buf->height, extra.timestamp_eof);
if (out_id == -1) {
LOGE("Failed to encode frame. frame_id: %d encode_id: %d", extra.frame_id, encode_idx);
}
// publish encode index
if (i == 0 && out_id != -1) {
MessageBuilder msg;
// this is really ugly
bool valid = (buf->get_frame_id() == extra.frame_id);
auto eidx = cam_info.type == DriverCam ? msg.initEvent(valid).initDriverEncodeIdx() :
(cam_info.type == WideRoadCam ? msg.initEvent(valid).initWideRoadEncodeIdx() : msg.initEvent(valid).initRoadEncodeIdx());
eidx.setFrameId(extra.frame_id);
eidx.setTimestampSof(extra.timestamp_sof);
eidx.setTimestampEof(extra.timestamp_eof);
if (Hardware::TICI()) {
eidx.setType(cereal::EncodeIndex::Type::FULL_H_E_V_C);
} else {
eidx.setType(cam_info.type == DriverCam ? cereal::EncodeIndex::Type::FRONT : cereal::EncodeIndex::Type::FULL_H_E_V_C);
}
eidx.setEncodeId(encode_idx);
eidx.setSegmentNum(cur_seg);
eidx.setSegmentId(out_id);
if (lh) {
auto bytes = msg.toBytes();
lh_log(lh, bytes.begin(), bytes.size(), true);
}
}
}
encode_idx++;
}
if (lh) {
lh_close(lh);
lh = NULL;
}
}
LOG("encoder destroy");
for(auto &e : encoders) {
e->encoder_close();
delete e;
}
}
void logger_rotate(LoggerdState *s) {
{
std::unique_lock lk(s->rotate_lock);
int segment = -1;
int err = logger_next(&s->logger, LOG_ROOT.c_str(), s->segment_path, sizeof(s->segment_path), &segment);
assert(err == 0);
s->rotate_segment = segment;
s->ready_to_rotate = 0;
s->last_rotate_tms = millis_since_boot();
}
s->rotate_cv.notify_all();
LOGW((s->logger.part == 0) ? "logging to %s" : "rotated to %s", s->segment_path);
}
void rotate_if_needed(LoggerdState *s) {
if (s->ready_to_rotate == s->max_waiting) {
logger_rotate(s);
}
double tms = millis_since_boot();
if ((tms - s->last_rotate_tms) > SEGMENT_LENGTH * 1000 &&
(tms - s->last_camera_seen_tms) > NO_CAMERA_PATIENCE &&
!LOGGERD_TEST) {
LOGW("no camera packet seen. auto rotating");
logger_rotate(s);
}
}
void loggerd_thread() {
// setup messaging
typedef struct QlogState {
std::string name;
int counter, freq;
} QlogState;
std::unordered_map<SubSocket*, QlogState> qlog_states;
LoggerdState s;
s.ctx = Context::create();
Poller * poller = Poller::create();
// subscribe to all socks
for (const auto& it : services) {
if (!it.should_log) continue;
SubSocket * sock = SubSocket::create(s.ctx, it.name);
assert(sock != NULL);
poller->registerSocket(sock);
qlog_states[sock] = {
.name = it.name,
.counter = 0,
.freq = it.decimation,
};
}
// init logger
logger_init(&s.logger, "rlog", true);
logger_rotate(&s);
Params().put("CurrentRoute", s.logger.route_name);
// init encoders
s.last_camera_seen_tms = millis_since_boot();
std::vector<std::thread> encoder_threads;
for (const auto &cam : cameras_logged) {
if (cam.enable) {
encoder_threads.push_back(std::thread(encoder_thread, &s, cam));
if (cam.trigger_rotate) s.max_waiting++;
}
}
uint64_t msg_count = 0, bytes_count = 0;
double start_ts = millis_since_boot();
while (!do_exit) {
// poll for new messages on all sockets
for (auto sock : poller->poll(1000)) {
// drain socket
int count = 0;
QlogState &qs = qlog_states[sock];
Message *msg = nullptr;
while (!do_exit && (msg = sock->receive(true))) {
const bool in_qlog = qs.freq != -1 && (qs.counter++ % qs.freq == 0);
logger_log(&s.logger, (uint8_t *)msg->getData(), msg->getSize(), in_qlog);
bytes_count += msg->getSize();
delete msg;
rotate_if_needed(&s);
if ((++msg_count % 1000) == 0) {
double seconds = (millis_since_boot() - start_ts) / 1000.0;
LOGD("%lu messages, %.2f msg/sec, %.2f KB/sec", msg_count, msg_count / seconds, bytes_count * 0.001 / seconds);
}
count++;
if (count >= 50) {
LOGE("large volume of '%s' messages", qs.name.c_str());
break;
}
}
}
}
LOGW("closing encoders");
s.rotate_cv.notify_all();
for (auto &t : encoder_threads) t.join();
LOGW("closing logger");
logger_close(&s.logger, &do_exit);
if (do_exit.power_failure) {
LOGE("power failure");
sync();
LOGE("sync done");
}
// messaging cleanup
for (auto &[sock, qs] : qlog_states) delete sock;
delete poller;
delete s.ctx;
}
<|endoftext|> |
<commit_before>/*
* This file is part of telepathy-accounts-kcm
*
* Copyright (C) 2009 Collabora Ltd. <info@collabora.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "gabble-account-ui.h"
#include "main-options-widget.h"
#include "main-options-widget-googletalk.h"
#include "main-options-widget-facebook.h"
#include "main-options-widget-msn.h"
#include "main-options-widget-kde-talk.h"
#include "server-settings-widget.h"
#include "proxy-settings-widget.h"
#include <KCMTelepathyAccounts/AbstractAccountParametersWidget>
#include <KCMTelepathyAccounts/GenericAdvancedOptionsWidget>
#include <KCMTelepathyAccounts/ParameterEditModel>
#include <TelepathyQt/ProtocolParameter>
GabbleAccountUi::GabbleAccountUi(const QString &serviceName, QObject *parent)
: AbstractAccountUi(parent),
m_serviceName(serviceName)
{
// Register supported parameters
registerSupportedParameter(QLatin1String("account"), QVariant::String);
registerSupportedParameter(QLatin1String("password"), QVariant::String);
registerSupportedParameter(QLatin1String("port"), QVariant::UInt);
registerSupportedParameter(QLatin1String("server"), QVariant::String);
registerSupportedParameter(QLatin1String("require-encryption"), QVariant::Bool);
registerSupportedParameter(QLatin1String("old-ssl"), QVariant::Bool);
registerSupportedParameter(QLatin1String("low-bandwidth"), QVariant::Bool);
registerSupportedParameter(QLatin1String("ignore-ssl-errors"), QVariant::Bool);
registerSupportedParameter(QLatin1String("keepalive-interval"), QVariant::UInt);
registerSupportedParameter(QLatin1String("resource"), QVariant::String);
registerSupportedParameter(QLatin1String("priority"), QVariant::Int);
registerSupportedParameter(QLatin1String("stun-server"), QVariant::String);
registerSupportedParameter(QLatin1String("stun-port"), QVariant::UInt);
registerSupportedParameter(QLatin1String("fallback-stun-server"), QVariant::String);
registerSupportedParameter(QLatin1String("fallback-stun-port"), QVariant::UInt);
registerSupportedParameter(QLatin1String("https-proxy-server"), QVariant::String);
registerSupportedParameter(QLatin1String("https-proxy-port"), QVariant::UInt);
registerSupportedParameter(QLatin1String("fallback-socks5-proxies"), QVariant::StringList);
registerSupportedParameter(QLatin1String("fallback-conference-server"), QVariant::String);
}
GabbleAccountUi::~GabbleAccountUi()
{
}
AbstractAccountParametersWidget *GabbleAccountUi::mainOptionsWidget(
ParameterEditModel *model,
QWidget *parent) const
{
QModelIndex resourceIndex = model->indexForParameter(model->parameter(QLatin1String("resource")));
if (resourceIndex.isValid() && model->data(resourceIndex, ParameterEditModel::ValueRole).toString().isEmpty()) {
model->setData(resourceIndex, QString::fromLatin1("kde-telepathy"), ParameterEditModel::ValueRole);
}
if (m_serviceName == QLatin1String("google-talk")) {
return new MainOptionsWidgetGoogleTalk(model, parent);
} else if (m_serviceName == QLatin1String("facebook")) {
return new MainOptionsWidgetFacebook(model, parent);
} else if (m_serviceName == QLatin1String("msn-xmpp")) {
return new MainOptionsWidgetMSN(model, parent);
} else if (m_serviceName == QLatin1String("kde-talk")) {
return new MainOptionsWidgetKDETalk(model, parent);
} else {
return new MainOptionsWidget(model, parent);
}
}
bool GabbleAccountUi::hasAdvancedOptionsWidget() const
{
return true;
}
AbstractAccountParametersWidget *GabbleAccountUi::advancedOptionsWidget(
ParameterEditModel *model,
QWidget *parent) const
{
GenericAdvancedOptionsWidget *widget = new GenericAdvancedOptionsWidget(model, parent);
AbstractAccountParametersWidget* serverSettingsWidget = new ServerSettingsWidget(model, widget);
widget->addTab(serverSettingsWidget, i18n("Server"));
AbstractAccountParametersWidget* proxySettingsWidget = new ProxySettingsWidget(model, widget);
widget->addTab(proxySettingsWidget, i18n("Proxy"));
return widget;
}
#include "gabble-account-ui.moc"
<commit_msg>Set XMPP priority in the same way as resource parameter<commit_after>/*
* This file is part of telepathy-accounts-kcm
*
* Copyright (C) 2009 Collabora Ltd. <info@collabora.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "gabble-account-ui.h"
#include "main-options-widget.h"
#include "main-options-widget-googletalk.h"
#include "main-options-widget-facebook.h"
#include "main-options-widget-msn.h"
#include "main-options-widget-kde-talk.h"
#include "server-settings-widget.h"
#include "proxy-settings-widget.h"
#include <KCMTelepathyAccounts/AbstractAccountParametersWidget>
#include <KCMTelepathyAccounts/GenericAdvancedOptionsWidget>
#include <KCMTelepathyAccounts/ParameterEditModel>
#include <TelepathyQt/ProtocolParameter>
GabbleAccountUi::GabbleAccountUi(const QString &serviceName, QObject *parent)
: AbstractAccountUi(parent),
m_serviceName(serviceName)
{
// Register supported parameters
registerSupportedParameter(QLatin1String("account"), QVariant::String);
registerSupportedParameter(QLatin1String("password"), QVariant::String);
registerSupportedParameter(QLatin1String("port"), QVariant::UInt);
registerSupportedParameter(QLatin1String("server"), QVariant::String);
registerSupportedParameter(QLatin1String("require-encryption"), QVariant::Bool);
registerSupportedParameter(QLatin1String("old-ssl"), QVariant::Bool);
registerSupportedParameter(QLatin1String("low-bandwidth"), QVariant::Bool);
registerSupportedParameter(QLatin1String("ignore-ssl-errors"), QVariant::Bool);
registerSupportedParameter(QLatin1String("keepalive-interval"), QVariant::UInt);
registerSupportedParameter(QLatin1String("resource"), QVariant::String);
registerSupportedParameter(QLatin1String("priority"), QVariant::Int);
registerSupportedParameter(QLatin1String("stun-server"), QVariant::String);
registerSupportedParameter(QLatin1String("stun-port"), QVariant::UInt);
registerSupportedParameter(QLatin1String("fallback-stun-server"), QVariant::String);
registerSupportedParameter(QLatin1String("fallback-stun-port"), QVariant::UInt);
registerSupportedParameter(QLatin1String("https-proxy-server"), QVariant::String);
registerSupportedParameter(QLatin1String("https-proxy-port"), QVariant::UInt);
registerSupportedParameter(QLatin1String("fallback-socks5-proxies"), QVariant::StringList);
registerSupportedParameter(QLatin1String("fallback-conference-server"), QVariant::String);
}
GabbleAccountUi::~GabbleAccountUi()
{
}
AbstractAccountParametersWidget *GabbleAccountUi::mainOptionsWidget(
ParameterEditModel *model,
QWidget *parent) const
{
QModelIndex resourceIndex = model->indexForParameter(model->parameter(QLatin1String("resource")));
if (resourceIndex.isValid() && model->data(resourceIndex, ParameterEditModel::ValueRole).toString().isEmpty()) {
model->setData(resourceIndex, QString::fromLatin1("kde-telepathy"), ParameterEditModel::ValueRole);
}
QModelIndex priorityIndex = model->indexForParameter(model->parameter(QLatin1String("priority")));
if (priorityIndex.isValid() && model->data(priorityIndex, ParameterEditModel::ValueRole).toInt() == 0) {
model->setData(priorityIndex, 5, ParameterEditModel::ValueRole);
}
if (m_serviceName == QLatin1String("google-talk")) {
return new MainOptionsWidgetGoogleTalk(model, parent);
} else if (m_serviceName == QLatin1String("facebook")) {
return new MainOptionsWidgetFacebook(model, parent);
} else if (m_serviceName == QLatin1String("msn-xmpp")) {
return new MainOptionsWidgetMSN(model, parent);
} else if (m_serviceName == QLatin1String("kde-talk")) {
return new MainOptionsWidgetKDETalk(model, parent);
} else {
return new MainOptionsWidget(model, parent);
}
}
bool GabbleAccountUi::hasAdvancedOptionsWidget() const
{
return true;
}
AbstractAccountParametersWidget *GabbleAccountUi::advancedOptionsWidget(
ParameterEditModel *model,
QWidget *parent) const
{
GenericAdvancedOptionsWidget *widget = new GenericAdvancedOptionsWidget(model, parent);
AbstractAccountParametersWidget* serverSettingsWidget = new ServerSettingsWidget(model, widget);
widget->addTab(serverSettingsWidget, i18n("Server"));
AbstractAccountParametersWidget* proxySettingsWidget = new ProxySettingsWidget(model, widget);
widget->addTab(proxySettingsWidget, i18n("Proxy"));
return widget;
}
#include "gabble-account-ui.moc"
<|endoftext|> |
<commit_before>/*
**
** Author(s):
** - Laurent LEC <llec@aldebaran-robotics.com>
**
** Copyright (C) 2012 Aldebaran Robotics
*/
#include <string.h>
#include <qimessaging/c/qi_c.h>
#include <qimessaging/c/error_c.h>
#include <qimessaging/c/session_c.h>
#include <qimessaging/session.hpp>
#include <qimessaging/serviceinfo.hpp>
#include "error_p.h"
qi_session_t *qi_session_create()
{
qi::Session *session = new qi::Session();
return reinterpret_cast<qi_session_t*>(session);
}
bool qi_session_connect(qi_session_t *session, const char *address)
{
qi::Session *s = reinterpret_cast<qi::Session*>(session);
try
{
return s->connect(address);
}
catch (std::runtime_error &e)
{
qi_c_set_error(e.what());
return false;
}
}
void qi_session_destroy(qi_session_t *session)
{
qi::Session *s = reinterpret_cast<qi::Session*>(session);
delete s;
}
void qi_session_close(qi_session_t *session)
{
qi::Session *s = reinterpret_cast<qi::Session*>(session);
s->close();
}
int qi_session_get_service_id(qi_session_t *session, const char *service_name)
{
qi::Session *s = reinterpret_cast<qi::Session *>(session);
std::vector<qi::ServiceInfo> services;
std::vector<qi::ServiceInfo>::iterator it;
services = s->services();
for (it = services.begin(); it != services.end(); ++it)
if ((*it).name().compare(service_name) == 0)
return (*it).serviceId();
return 0;
}
qi_object_t *qi_session_get_service(qi_session_t *session, const char *name)
{
qi::Session *s = reinterpret_cast<qi::Session*>(session);
if (!s)
{
printf("session not valid.\n");
return 0;
}
qi_object_t *obj = qi_object_create();
qi::ObjectPtr &o = *(reinterpret_cast<qi::ObjectPtr *>(obj));
try
{
o = s->service(name);
if (!o) {
qi_object_destroy(obj);
return 0;
}
return obj;
}
catch (std::runtime_error &e)
{
qi_c_set_error(e.what());
return 0;
}
}
const char** qi_session_get_services(qi_session_t *session)
{
qi::Session *s = reinterpret_cast<qi::Session*>(session);
std::vector<qi::ServiceInfo> services;
size_t length = 0;
try {
services = s->services();
length = services.size();
} catch (std::runtime_error& e) {
return 0;
}
const char **result = static_cast<const char**>(malloc((length + 1) * sizeof(char *)));
unsigned int i = 0;
for (i = 0; i < length; i++)
{
result[i] = strdup(services[i].name().c_str());
}
result[i] = NULL;
return result;
}
void qi_session_free_services_list(const char **list)
{
while (*list != 0)
{
free((void*) (*list));
}
free((void*) (*list));
}
bool qi_session_listen(qi_session_t *session, const char *address)
{
qi::Session *s = reinterpret_cast<qi::Session*>(session);
return s->listen(address);
}
int qi_session_register_service(qi_session_t *session, const char *name, qi_object_t *object)
{
qi::Session *s = reinterpret_cast<qi::Session*>(session);
qi::ObjectPtr *obj = reinterpret_cast<qi::ObjectPtr *>(object);
try
{
return s->registerService(name, *obj);
}
catch (std::runtime_error &e)
{
qi_c_set_error(e.what());
}
return 0;
}
void qi_session_unregister_service(qi_session_t *session, unsigned int idx)
{
qi::Session *s = reinterpret_cast<qi::Session*>(session);
s->unregisterService(idx);
}
<commit_msg>C bindings: Catch exceptions from C++ and set error correctly.<commit_after>/*
**
** Author(s):
** - Laurent LEC <llec@aldebaran-robotics.com>
**
** Copyright (C) 2012 Aldebaran Robotics
*/
#include <string.h>
#include <qimessaging/c/qi_c.h>
#include <qimessaging/c/error_c.h>
#include <qimessaging/c/session_c.h>
#include <qimessaging/session.hpp>
#include <qimessaging/serviceinfo.hpp>
#include "error_p.h"
qi_session_t *qi_session_create()
{
qi::Session *session = new qi::Session();
return reinterpret_cast<qi_session_t*>(session);
}
bool qi_session_connect(qi_session_t *session, const char *address)
{
qi::Session *s = reinterpret_cast<qi::Session*>(session);
try
{
qi::Future<bool> fut = s->connect(address);
fut.wait();
if (fut.hasError() || fut.value() == false)
{
qi_c_set_error(fut.error().c_str());
return false;
}
return true;
}
catch (std::runtime_error &e)
{
qi_c_set_error(e.what());
return false;
}
catch (std::bad_alloc &e)
{
qi_c_set_error(e.what());
return false;
}
}
void qi_session_destroy(qi_session_t *session)
{
qi::Session *s = reinterpret_cast<qi::Session*>(session);
delete s;
}
void qi_session_close(qi_session_t *session)
{
qi::Session *s = reinterpret_cast<qi::Session*>(session);
s->close();
}
int qi_session_get_service_id(qi_session_t *session, const char *service_name)
{
qi::Session *s = reinterpret_cast<qi::Session *>(session);
std::vector<qi::ServiceInfo> services;
std::vector<qi::ServiceInfo>::iterator it;
services = s->services();
for (it = services.begin(); it != services.end(); ++it)
if ((*it).name().compare(service_name) == 0)
return (*it).serviceId();
return 0;
}
qi_object_t *qi_session_get_service(qi_session_t *session, const char *name)
{
qi::Session *s = reinterpret_cast<qi::Session*>(session);
if (!s)
{
qi_c_set_error("Session is not valid.");
return 0;
}
qi_object_t *obj = qi_object_create();
qi::ObjectPtr &o = *(reinterpret_cast<qi::ObjectPtr *>(obj));
try
{
o = s->service(name);
if (!o) {
qi_object_destroy(obj);
return 0;
}
return obj;
}
catch (std::runtime_error &e)
{
qi_c_set_error(e.what());
return 0;
}
}
const char** qi_session_get_services(qi_session_t *session)
{
qi::Session *s = reinterpret_cast<qi::Session*>(session);
std::vector<qi::ServiceInfo> services;
size_t length = 0;
try {
services = s->services();
length = services.size();
} catch (std::runtime_error& e) {
return 0;
}
const char **result = static_cast<const char**>(malloc((length + 1) * sizeof(char *)));
unsigned int i = 0;
for (i = 0; i < length; i++)
{
result[i] = strdup(services[i].name().c_str());
}
result[i] = NULL;
return result;
}
void qi_session_free_services_list(const char **list)
{
while (*list != 0)
{
free((void*) (*list));
}
free((void*) (*list));
}
bool qi_session_listen(qi_session_t *session, const char *address)
{
qi::Session *s = reinterpret_cast<qi::Session*>(session);
return s->listen(address);
}
int qi_session_register_service(qi_session_t *session, const char *name, qi_object_t *object)
{
qi::Session *s = reinterpret_cast<qi::Session*>(session);
qi::ObjectPtr *obj = reinterpret_cast<qi::ObjectPtr *>(object);
try
{
return s->registerService(name, *obj);
}
catch (std::runtime_error &e)
{
qi_c_set_error(e.what());
}
return 0;
}
void qi_session_unregister_service(qi_session_t *session, unsigned int idx)
{
qi::Session *s = reinterpret_cast<qi::Session*>(session);
s->unregisterService(idx);
}
<|endoftext|> |
<commit_before>/*************************************************************************
* Copyright (C) 2011-2016 by Paul-Louis Ageneau *
* paul-louis (at) ageneau (dot) org *
* *
* This file is part of Teapotnet. *
* *
* Teapotnet is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Affero General Public License as *
* published by the Free Software Foundation, either version 3 of *
* the License, or (at your option) any later version. *
* *
* Teapotnet 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 Affero General Public License for more details. *
* *
* You should have received a copy of the GNU Affero General Public *
* License along with Teapotnet. *
* If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
#include "tpn/board.hpp"
#include "tpn/resource.hpp"
#include "tpn/cache.hpp"
#include "tpn/html.hpp"
#include "tpn/user.hpp"
#include "tpn/store.hpp"
#include "tpn/config.hpp"
#include "pla/jsonserializer.hpp"
#include "pla/binaryserializer.hpp"
#include "pla/object.hpp"
namespace tpn
{
Board::Board(const String &name, const String &secret, const String &displayName) :
mName(name),
mDisplayName(displayName),
mSecret(secret),
mHasNew(false),
mUnread(0)
{
Assert(!mName.empty() && mName[0] == '/'); // TODO
Interface::Instance->add(urlPrefix(), this);
String prefix = "/mail" + mName;
Set<BinaryString> digests;
Store::Instance->retrieveValue(Store::Hash(prefix), digests);
for(auto it = digests.begin(); it != digests.end(); ++it)
{
//LogDebug("Board", "Retrieved digest: " + it->toString());
if(fetch(Network::Link::Null, prefix, "/", *it, false))
incoming(Network::Link::Null, prefix, "/", *it);
}
publish(prefix);
subscribe(prefix);
}
Board::~Board(void)
{
Interface::Instance->remove(urlPrefix(), this);
String prefix = "/mail" + mName;
unpublish(prefix);
unsubscribe(prefix);
}
String Board::urlPrefix(void) const
{
std::unique_lock<std::mutex> lock(mMutex);
return "/mail" + mName;
}
bool Board::hasNew(void) const
{
std::unique_lock<std::mutex> lock(mMutex);
bool value = false;
std::swap(mHasNew, value);
return value;
}
int Board::unread(void) const
{
// TODO
return 0;
}
BinaryString Board::digest(void) const
{
std::unique_lock<std::mutex> lock(mMutex);
return mDigest;
}
bool Board::add(const Mail &mail, bool noIssue)
{
{
std::unique_lock<std::mutex> lock(mMutex);
if(mail.empty() || mMails.contains(mail))
return false;
auto it = mMails.insert(mail);
const Mail &m = *it.first;
mUnorderedMails.append(&m);
}
if(!noIssue) issue("/mail" + mName, mail);
process();
publish("/mail" + mName);
mCondition.notify_all();
return true;
}
void Board::addMergeUrl(const String &url)
{
std::unique_lock<std::mutex> lock(mMutex);
mMergeUrls.insert(url);
}
void Board::removeMergeUrl(const String &url)
{
std::unique_lock<std::mutex> lock(mMutex);
mMergeUrls.erase(url);
}
void Board::process(void)
{
// Private, no sync
try {
// Write messages to temporary file
String tempFileName = File::TempName();
File tempFile(tempFileName, File::Truncate);
BinarySerializer serializer(&tempFile);
for(auto it = mMails.begin(); it != mMails.end(); ++it)
serializer << *it;
tempFile.close();
// Move to cache and process
Resource resource;
resource.cache(tempFileName, mName, "mail", mSecret);
// Retrieve digest and store it
mDigest = resource.digest();
Store::Instance->storeValue(Store::Hash("/mail" + mName), mDigest, Store::Permanent);
LogDebug("Board::process", "Board processed: " + mDigest.toString());
}
catch(const Exception &e)
{
LogWarn("Board::process", String("Board processing failed: ") + e.what());
}
}
bool Board::anounce(const Network::Link &link, const String &prefix, const String &path, List<BinaryString> &targets)
{
std::unique_lock<std::mutex> lock(mMutex);
targets.clear();
if(mDigest.empty())
return false;
targets.push_back(mDigest);
return true;
}
bool Board::incoming(const Network::Link &link, const String &prefix, const String &path, const BinaryString &target)
{
{
std::unique_lock<std::mutex> lock(mMutex);
if(target == mDigest)
return false;
}
if(fetch(link, prefix, path, target, true))
{
try {
std::unique_lock<std::mutex> lock(mMutex);
Resource resource(target, true); // local only (already fetched)
if(resource.type() != "mail")
return false;
Resource::Reader reader(&resource, mSecret);
BinarySerializer serializer(&reader);
Mail mail;
unsigned count = 0;
while(!!(serializer >> mail))
{
if(mail.empty())
continue;
if(!mMails.contains(mail))
{
auto it = mMails.insert(mail);
const Mail &m = *it.first;
mUnorderedMails.append(&m);
++mUnread;
mHasNew = true;
}
++count;
}
if(count == mMails.size())
{
mDigest = target;
}
else {
process();
if(mDigest != target)
publish("/mail" + mName);
}
}
catch(const Exception &e)
{
LogWarn("Board::incoming", e.what());
}
mCondition.notify_all();
}
return true;
}
bool Board::incoming(const Network::Link &link, const String &prefix, const String &path, const Mail &mail)
{
if(add(mail, true))
{
++mUnread;
mHasNew = true;
return true;
}
return false;
}
void Board::http(const String &prefix, Http::Request &request)
{
Assert(!request.url.empty());
try {
if(request.url == "/")
{
if(request.method == "POST")
{
if(request.post.contains("message") && !request.post["message"].empty())
{
Mail mail;
mail.setContent(request.post["message"]);
if(request.post.contains("parent"))
{
BinaryString parent;
request.post["parent"].extract(parent);
mail.setParent(parent);
}
if(request.post.contains("attachment"))
{
BinaryString attachment;
request.post["attachment"].extract(attachment);
if(!attachment.empty())
mail.addAttachment(attachment);
}
if(request.post.contains("author"))
{
mail.setAuthor(request.post["author"]);
}
else {
User *user = getAuthenticatedUser(request);
if(user) {
mail.setAuthor(user->name());
mail.sign(user->identifier(), user->privateKey());
}
}
add(mail);
Http::Response response(request, 200);
response.send();
}
throw 400;
}
if(request.get.contains("json"))
{
int next = 0;
if(request.get.contains("next"))
request.get["next"].extract(next);
duration timeout = milliseconds(Config::Get("request_timeout").toInt());
if(request.get.contains("timeout"))
timeout = seconds(request.get["timeout"].toDouble());
decltype(mUnorderedMails) temp;
{
std::unique_lock<std::mutex> lock(mMutex);
if(next >= int(mUnorderedMails.size()))
{
mCondition.wait_for(lock, std::chrono::duration<double>(timeout), [this, next]() {
return next < int(mUnorderedMails.size());
});
}
temp.reserve(int(mUnorderedMails.size() - next));
for(int i = next; i < int(mUnorderedMails.size()); ++i)
temp.push_back(mUnorderedMails[i]);
mUnread = 0;
mHasNew = false;
}
Http::Response response(request, 200);
response.headers["Content-Type"] = "application/json";
response.send();
JsonSerializer json(response.stream);
json.setOptionalOutputMode(true);
json << temp;
return;
}
bool isPopup = request.get.contains("popup");
bool isFrame = request.get.contains("frame");
Http::Response response(request, 200);
response.send();
Html page(response.stream);
String title;
{
std::unique_lock<std::mutex> lock(mMutex);
title = (!mDisplayName.empty() ? mDisplayName : "Board " + mName);
}
page.header(title, isPopup || isFrame);
if(!isFrame)
{
page.open("div","topmenu");
if(isPopup) page.span(title, ".button");
// TODO: should be hidden in CSS
#ifndef ANDROID
if(!isPopup)
{
String popupUrl = Http::AppendParam(request.fullUrl, "popup");
page.raw("<a class=\"button\" href=\""+popupUrl+"\" target=\"_blank\" onclick=\"return popup('"+popupUrl+"','/');\">Popup</a>");
}
#endif
page.close("div");
}
page.open("div", ".replypanel");
User *user = getAuthenticatedUser(request);
if(user)
{
page.javascript("var TokenMail = '"+user->generateToken("mail")+"';\n\
var TokenDirectory = '"+user->generateToken("directory")+"';\n\
var TokenContact = '"+user->generateToken("contact")+"';\n\
var UrlSelector = '"+user->urlPrefix()+"/myself/files/?json';\n\
var UrlUpload = '"+user->urlPrefix()+"/files/_upload/?json';");
page.raw("<a class=\"button\" href=\"#\" onclick=\"createFileSelector(UrlSelector, '#fileSelector', 'input.attachment', 'input.attachmentname', UrlUpload); return false;\"><img alt=\"File\" src=\"/paperclip.png\"></a>");
}
page.openForm("#", "post", "boardform");
page.textarea("input");
page.input("hidden", "attachment");
page.input("hidden", "attachmentname");
page.closeForm();
page.close("div");
page.div("","#attachedfile.attachedfile");
page.div("", "#fileSelector.fileselector");
if(isPopup) page.open("div", "board");
else page.open("div", "board.box");
page.open("div", "mail");
page.open("p"); page.text("No messages"); page.close("p");
page.close("div");
page.close("div");
page.javascript("function post() {\n\
var message = $(document.boardform.input).val();\n\
var attachment = $(document.boardform.attachment).val();\n\
if(!message) return false;\n\
var fields = {};\n\
fields['message'] = message;\n\
if(attachment) fields['attachment'] = attachment;\n\
$.post('"+prefix+request.url+"', fields)\n\
.fail(function(jqXHR, textStatus) {\n\
alert('The message could not be sent.');\n\
});\n\
$(document.boardform.input).val('');\n\
$(document.boardform.attachment).val('');\n\
$(document.boardform.attachmentname).val('');\n\
$('#attachedfile').hide();\n\
}\n\
$(document.boardform).submit(function() {\n\
post();\n\
return false;\n\
});\n\
$(document.boardform.attachment).change(function() {\n\
$('#attachedfile').html('');\n\
$('#attachedfile').hide();\n\
var filename = $(document.boardform.attachmentname).val();\n\
if(filename != '') {\n\
$('#attachedfile').append('<img class=\"icon\" src=\"/file.png\">');\n\
$('#attachedfile').append('<span class=\"filename\">'+filename+'</span>');\n\
$('#attachedfile').show();\n\
}\n\
$(document.boardform.input).focus();\n\
if($(document.boardform.input).val() == '') {\n\
$(document.boardform.input).val(filename);\n\
$(document.boardform.input).select();\n\
}\n\
});\n\
$('#attachedfile').hide();");
unsigned refreshPeriod = 2000;
page.javascript("setMailReceiver('"+Http::AppendParam(request.fullUrl, "json")+"','#mail', "+String::number(refreshPeriod)+");");
{
std::unique_lock<std::mutex> lock(mMutex);
for(auto &url : mMergeUrls)
page.javascript("setMailReceiver('"+Http::AppendParam(url, "json")+"','#mail', "+String::number(refreshPeriod)+");");
}
page.footer();
return;
}
}
catch(const Exception &e)
{
LogWarn("AddressBook::http", e.what());
throw 500;
}
throw 404;
}
}
<commit_msg>Fixed deadlock in Board<commit_after>/*************************************************************************
* Copyright (C) 2011-2016 by Paul-Louis Ageneau *
* paul-louis (at) ageneau (dot) org *
* *
* This file is part of Teapotnet. *
* *
* Teapotnet is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Affero General Public License as *
* published by the Free Software Foundation, either version 3 of *
* the License, or (at your option) any later version. *
* *
* Teapotnet 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 Affero General Public License for more details. *
* *
* You should have received a copy of the GNU Affero General Public *
* License along with Teapotnet. *
* If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
#include "tpn/board.hpp"
#include "tpn/resource.hpp"
#include "tpn/cache.hpp"
#include "tpn/html.hpp"
#include "tpn/user.hpp"
#include "tpn/store.hpp"
#include "tpn/config.hpp"
#include "pla/jsonserializer.hpp"
#include "pla/binaryserializer.hpp"
#include "pla/object.hpp"
namespace tpn
{
Board::Board(const String &name, const String &secret, const String &displayName) :
mName(name),
mDisplayName(displayName),
mSecret(secret),
mHasNew(false),
mUnread(0)
{
Assert(!mName.empty() && mName[0] == '/'); // TODO
Interface::Instance->add(urlPrefix(), this);
const String prefix = "/mail" + mName;
Set<BinaryString> digests;
Store::Instance->retrieveValue(Store::Hash(prefix), digests);
for(auto it = digests.begin(); it != digests.end(); ++it)
{
//LogDebug("Board", "Retrieved digest: " + it->toString());
if(fetch(Network::Link::Null, prefix, "/", *it, false))
incoming(Network::Link::Null, prefix, "/", *it);
}
publish(prefix);
subscribe(prefix);
}
Board::~Board(void)
{
Interface::Instance->remove(urlPrefix(), this);
const String prefix = "/mail" + mName;
unpublish(prefix);
unsubscribe(prefix);
}
String Board::urlPrefix(void) const
{
std::unique_lock<std::mutex> lock(mMutex);
return "/mail" + mName;
}
bool Board::hasNew(void) const
{
std::unique_lock<std::mutex> lock(mMutex);
bool value = false;
std::swap(mHasNew, value);
return value;
}
int Board::unread(void) const
{
// TODO
return 0;
}
BinaryString Board::digest(void) const
{
std::unique_lock<std::mutex> lock(mMutex);
return mDigest;
}
bool Board::add(const Mail &mail, bool noIssue)
{
{
std::unique_lock<std::mutex> lock(mMutex);
if(mail.empty() || mMails.contains(mail))
return false;
auto it = mMails.insert(mail);
const Mail &m = *it.first;
mUnorderedMails.append(&m);
}
const String prefix = "/mail" + mName;
if(!noIssue) issue(prefix, mail);
process();
publish(prefix);
mCondition.notify_all();
return true;
}
void Board::addMergeUrl(const String &url)
{
std::unique_lock<std::mutex> lock(mMutex);
mMergeUrls.insert(url);
}
void Board::removeMergeUrl(const String &url)
{
std::unique_lock<std::mutex> lock(mMutex);
mMergeUrls.erase(url);
}
void Board::process(void)
{
try {
std::unique_lock<std::mutex> lock(mMutex);
// Write messages to temporary file
String tempFileName = File::TempName();
File tempFile(tempFileName, File::Truncate);
BinarySerializer serializer(&tempFile);
for(auto it = mMails.begin(); it != mMails.end(); ++it)
serializer << *it;
tempFile.close();
// Move to cache and process
Resource resource;
resource.cache(tempFileName, mName, "mail", mSecret);
// Retrieve digest and store it
const String prefix = "/mail" + mName;
mDigest = resource.digest();
Store::Instance->storeValue(Store::Hash(prefix), mDigest, Store::Permanent);
LogDebug("Board::process", "Board processed: " + mDigest.toString());
}
catch(const Exception &e)
{
LogWarn("Board::process", String("Board processing failed: ") + e.what());
}
}
bool Board::anounce(const Network::Link &link, const String &prefix, const String &path, List<BinaryString> &targets)
{
std::unique_lock<std::mutex> lock(mMutex);
targets.clear();
if(mDigest.empty())
return false;
targets.push_back(mDigest);
return true;
}
bool Board::incoming(const Network::Link &link, const String &prefix, const String &path, const BinaryString &target)
{
{
std::unique_lock<std::mutex> lock(mMutex);
if(target == mDigest)
return false;
}
if(fetch(link, prefix, path, target, true))
{
try {
Resource resource(target, true); // local only (already fetched)
if(resource.type() != "mail")
return false;
bool complete = false;
{
std::unique_lock<std::mutex> lock(mMutex);
Resource::Reader reader(&resource, mSecret);
BinarySerializer serializer(&reader);
Mail mail;
unsigned count = 0;
while(!!(serializer >> mail))
{
if(mail.empty())
continue;
if(!mMails.contains(mail))
{
auto it = mMails.insert(mail);
const Mail &m = *it.first;
mUnorderedMails.append(&m);
++mUnread;
mHasNew = true;
}
++count;
}
if(count == mMails.size())
{
mDigest = target;
complete = true;
}
}
if(!complete)
{
const String prefix = "/mail" + mName;
process();
if(digest() != target)
publish(prefix);
}
}
catch(const Exception &e)
{
LogWarn("Board::incoming", e.what());
}
mCondition.notify_all();
}
return true;
}
bool Board::incoming(const Network::Link &link, const String &prefix, const String &path, const Mail &mail)
{
if(add(mail, true))
{
++mUnread;
mHasNew = true;
return true;
}
return false;
}
void Board::http(const String &prefix, Http::Request &request)
{
Assert(!request.url.empty());
try {
if(request.url == "/")
{
if(request.method == "POST")
{
if(request.post.contains("message") && !request.post["message"].empty())
{
Mail mail;
mail.setContent(request.post["message"]);
if(request.post.contains("parent"))
{
BinaryString parent;
request.post["parent"].extract(parent);
mail.setParent(parent);
}
if(request.post.contains("attachment"))
{
BinaryString attachment;
request.post["attachment"].extract(attachment);
if(!attachment.empty())
mail.addAttachment(attachment);
}
if(request.post.contains("author"))
{
mail.setAuthor(request.post["author"]);
}
else {
User *user = getAuthenticatedUser(request);
if(user) {
mail.setAuthor(user->name());
mail.sign(user->identifier(), user->privateKey());
}
}
add(mail);
Http::Response response(request, 200);
response.send();
}
throw 400;
}
if(request.get.contains("json"))
{
int next = 0;
if(request.get.contains("next"))
request.get["next"].extract(next);
duration timeout = milliseconds(Config::Get("request_timeout").toInt());
if(request.get.contains("timeout"))
timeout = seconds(request.get["timeout"].toDouble());
decltype(mUnorderedMails) temp;
{
std::unique_lock<std::mutex> lock(mMutex);
if(next >= int(mUnorderedMails.size()))
{
mCondition.wait_for(lock, std::chrono::duration<double>(timeout), [this, next]() {
return next < int(mUnorderedMails.size());
});
}
temp.reserve(int(mUnorderedMails.size() - next));
for(int i = next; i < int(mUnorderedMails.size()); ++i)
temp.push_back(mUnorderedMails[i]);
mUnread = 0;
mHasNew = false;
}
Http::Response response(request, 200);
response.headers["Content-Type"] = "application/json";
response.send();
JsonSerializer json(response.stream);
json.setOptionalOutputMode(true);
json << temp;
return;
}
bool isPopup = request.get.contains("popup");
bool isFrame = request.get.contains("frame");
Http::Response response(request, 200);
response.send();
Html page(response.stream);
String title;
{
std::unique_lock<std::mutex> lock(mMutex);
title = (!mDisplayName.empty() ? mDisplayName : "Board " + mName);
}
page.header(title, isPopup || isFrame);
if(!isFrame)
{
page.open("div","topmenu");
if(isPopup) page.span(title, ".button");
// TODO: should be hidden in CSS
#ifndef ANDROID
if(!isPopup)
{
String popupUrl = Http::AppendParam(request.fullUrl, "popup");
page.raw("<a class=\"button\" href=\""+popupUrl+"\" target=\"_blank\" onclick=\"return popup('"+popupUrl+"','/');\">Popup</a>");
}
#endif
page.close("div");
}
page.open("div", ".replypanel");
User *user = getAuthenticatedUser(request);
if(user)
{
page.javascript("var TokenMail = '"+user->generateToken("mail")+"';\n\
var TokenDirectory = '"+user->generateToken("directory")+"';\n\
var TokenContact = '"+user->generateToken("contact")+"';\n\
var UrlSelector = '"+user->urlPrefix()+"/myself/files/?json';\n\
var UrlUpload = '"+user->urlPrefix()+"/files/_upload/?json';");
page.raw("<a class=\"button\" href=\"#\" onclick=\"createFileSelector(UrlSelector, '#fileSelector', 'input.attachment', 'input.attachmentname', UrlUpload); return false;\"><img alt=\"File\" src=\"/paperclip.png\"></a>");
}
page.openForm("#", "post", "boardform");
page.textarea("input");
page.input("hidden", "attachment");
page.input("hidden", "attachmentname");
page.closeForm();
page.close("div");
page.div("","#attachedfile.attachedfile");
page.div("", "#fileSelector.fileselector");
if(isPopup) page.open("div", "board");
else page.open("div", "board.box");
page.open("div", "mail");
page.open("p"); page.text("No messages"); page.close("p");
page.close("div");
page.close("div");
page.javascript("function post() {\n\
var message = $(document.boardform.input).val();\n\
var attachment = $(document.boardform.attachment).val();\n\
if(!message) return false;\n\
var fields = {};\n\
fields['message'] = message;\n\
if(attachment) fields['attachment'] = attachment;\n\
$.post('"+prefix+request.url+"', fields)\n\
.fail(function(jqXHR, textStatus) {\n\
alert('The message could not be sent.');\n\
});\n\
$(document.boardform.input).val('');\n\
$(document.boardform.attachment).val('');\n\
$(document.boardform.attachmentname).val('');\n\
$('#attachedfile').hide();\n\
}\n\
$(document.boardform).submit(function() {\n\
post();\n\
return false;\n\
});\n\
$(document.boardform.attachment).change(function() {\n\
$('#attachedfile').html('');\n\
$('#attachedfile').hide();\n\
var filename = $(document.boardform.attachmentname).val();\n\
if(filename != '') {\n\
$('#attachedfile').append('<img class=\"icon\" src=\"/file.png\">');\n\
$('#attachedfile').append('<span class=\"filename\">'+filename+'</span>');\n\
$('#attachedfile').show();\n\
}\n\
$(document.boardform.input).focus();\n\
if($(document.boardform.input).val() == '') {\n\
$(document.boardform.input).val(filename);\n\
$(document.boardform.input).select();\n\
}\n\
});\n\
$('#attachedfile').hide();");
unsigned refreshPeriod = 2000;
page.javascript("setMailReceiver('"+Http::AppendParam(request.fullUrl, "json")+"','#mail', "+String::number(refreshPeriod)+");");
{
std::unique_lock<std::mutex> lock(mMutex);
for(auto &url : mMergeUrls)
page.javascript("setMailReceiver('"+Http::AppendParam(url, "json")+"','#mail', "+String::number(refreshPeriod)+");");
}
page.footer();
return;
}
}
catch(const Exception &e)
{
LogWarn("AddressBook::http", e.what());
throw 500;
}
throw 404;
}
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2012, The University of Oxford
* 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 of the University of Oxford 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 HOLDER 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.
*/
#include <mex.h>
#include <cuda_runtime_api.h>
#include <vector_functions.h> // This has to be before the OSKAR headers
#include "interferometry/oskar_Visibilities.h"
#include "utility/oskar_Log.h"
#include "utility/oskar_Mem.h"
#include "utility/oskar_vector_types.h"
#include "utility/oskar_get_error_string.h"
#include "math/oskar_cuda_dft_c2r_2d.h"
#include "math/oskar_linspace.h"
#include "math/oskar_meshgrid.h"
#include "imaging/oskar_Image.h"
#include "imaging/oskar_image_init.h"
#include "imaging/oskar_image_resize.h"
#include "imaging/oskar_make_image.h"
#include "imaging/oskar_make_image_dft.h"
#include "imaging/oskar_SettingsImage.h"
#include "imaging/oskar_evaluate_image_lm_grid.h"
#include "matlab/image/lib/oskar_mex_image_settings_from_matlab.h"
#include "matlab/image/lib/oskar_mex_image_to_matlab_struct.h"
#include "matlab/visibilities/lib/oskar_mex_vis_from_matlab_struct.h"
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <algorithm>
#include <limits>
using namespace std;
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
#ifndef M_PI_2
#define M_PI_2 1.57079632679489661923
#endif
#ifndef c_0
#define c_0 299792458.0
#endif
// Cleanup function called when the mex function is unloaded. (i.e. 'clear mex')
void cleanup(void)
{
cudaDeviceReset();
}
void mexFunction(int num_out, mxArray** out, int num_in, const mxArray** in)
{
bool cube_imager = false;
if (num_in == 2 && num_out < 2)
{
cube_imager = true;
}
else if (num_in == 6 && num_out < 2)
{
cube_imager = false;
}
else
{
mexErrMsgTxt("Usage: \n"
" image = oskar.image.make(vis, settings)\n"
" or\n"
" image = oskar.image.make(uu, vv, amp, frequency_hz, "
"num_pixels, field_of_view_deg)\n");
}
int err = OSKAR_SUCCESS;
oskar_Image image;
oskar_Log log;
log.keep_file = 0;
int location = OSKAR_LOCATION_CPU;
// Image with the oskar_make_image() function.
if (cube_imager)
{
// Load visibilities from MATLAB structure into a oskar_Visibilties structure.
oskar_Visibilities vis;
mexPrintf("= loading vis structure... ");
oskar_mex_vis_from_matlab_struct(&vis, in[0]);
mexPrintf("done.\n");
// Construct image settings structure.
oskar_SettingsImage settings;
mexPrintf("= Loading settings structure... ");
oskar_mex_image_settings_from_matlab(&settings, in[1]);
mexPrintf("done.\n");
// Setup image object.
int type = OSKAR_DOUBLE;
oskar_image_init(&image, type, location, &err);
// Make image.
mexPrintf("= Making image...\n");
mexEvalString("drawnow"); // Force flush of matlab print buffer
err = oskar_make_image(&image, &log, &vis, &settings);
if (err)
{
mexErrMsgIdAndTxt("OSKAR:ERROR",
"\noskar.image.make() [oskar_make_image] "
"failed with code %i: %s.\n",
err, oskar_get_error_string(err));
}
mexEvalString("drawnow");
mexPrintf("= Make image complete\n");
}
// Image with manual data selection.
else
{
// Make sure visibility data array is complex.
if (!mxIsComplex(in[2]))
{
mexErrMsgTxt("Input visibility amplitude array must be complex");
}
// Evaluate the and check consistency of data precision.
int type = 0;
if (mxGetClassID(in[0]) == mxDOUBLE_CLASS &&
mxGetClassID(in[1]) == mxDOUBLE_CLASS &&
mxGetClassID(in[2]) == mxDOUBLE_CLASS)
{
type = OSKAR_DOUBLE;
}
else if (mxGetClassID(in[0]) == mxSINGLE_CLASS &&
mxGetClassID(in[1]) == mxSINGLE_CLASS &&
mxGetClassID(in[2]) == mxSINGLE_CLASS)
{
type = OSKAR_SINGLE;
}
else
{
mexErrMsgTxt("uu, vv and amplitudes must be of the same type");
}
// Retrieve input arguments.
double freq = mxGetScalar(in[3]);
int size = (int)mxGetScalar(in[4]);
double fov_deg = mxGetScalar(in[5]);
double fov = fov_deg * M_PI/180.0;
// Evaluate the number of visibility samples are in the data.
int num_baselines = mxGetM(in[0]);
int num_times = mxGetN(in[0]);
if (num_baselines != (int)mxGetM(in[1]) ||
num_baselines != (int)mxGetM(in[2]) ||
num_times != (int)mxGetN(in[1]) ||
num_times != (int)mxGetN(in[2]))
{
mexErrMsgTxt("Dimension mismatch in input data.");
}
int num_samples = num_baselines * num_times;
// Setup the image cube.
oskar_image_init(&image, type, location);
oskar_image_resize(&image, size, size, 1, 1, 1);
image.centre_ra_deg = 0.0;
image.centre_dec_deg = 0.0;
image.fov_ra_deg = fov_deg;
image.fov_dec_deg = fov_deg;
image.time_start_mjd_utc = 0.0;
image.time_inc_sec = 0.0;
image.freq_start_hz = 0.0;
image.freq_inc_hz = 0.0;
image.image_type = 0;
oskar_Mem uu(type, location, num_samples);
oskar_Mem vv(type, location, num_samples);
oskar_Mem amp(type | OSKAR_COMPLEX, location, num_samples);
int num_pixels = size * size;
oskar_Mem l(type, location, num_pixels);
oskar_Mem m(type, location, num_pixels);
// Setup imaging data.
if (type == OSKAR_DOUBLE)
{
oskar_evaluate_image_lm_grid_d(size, size, fov, fov, l, m);
double* uu_ = (double*)mxGetData(in[0]);
double* vv_ = (double*)mxGetData(in[1]);
double* re_ = (double*)mxGetPr(in[2]);
double* im_ = (double*)mxGetPi(in[2]);
for (int i = 0; i < num_samples; ++i)
{
((double2*)amp.data)[i] = make_double2(re_[i], im_[i]);
((double*)uu.data)[i] = uu_[i];
((double*)vv.data)[i] = vv_[i];
}
}
else // (type == OSKAR_SINGLE)
{
oskar_evaluate_image_lm_grid_f(size, size, fov, fov, l, m);
float* uu_ = (float*)mxGetData(in[0]);
float* vv_ = (float*)mxGetData(in[1]);
float* re_ = (float*)mxGetPr(in[2]);
float* im_ = (float*)mxGetPi(in[2]);
for (int i = 0; i < num_samples; ++i)
{
((float2*)amp.data)[i] = make_float2(re_[i], im_[i]);
((float*)uu.data)[i] = uu_[i];
((float*)vv.data)[i] = vv_[i];
}
}
// Make the image.
mexPrintf("= Making image...\n");
mexEvalString("drawnow");
err = oskar_make_image_dft(&image.data, &uu, &vv, &, &l, &m, freq);
if (err)
{
mexErrMsgIdAndTxt("OSKAR:ERROR",
"\noskar.image.make() [oskar_make_image_dft] "
"failed with code %i: %s.\n",
err, oskar_get_error_string(err));
}
mexEvalString("drawnow");
mexPrintf("= Make image complete\n");
}
out[0] = oskar_mex_image_to_matlab_struct(&image, NULL);
// Register cleanup function.
mexAtExit(cleanup);
}
<commit_msg>Updated oskar_mex_make_image to allow it to compile.<commit_after>/*
* Copyright (c) 2012, The University of Oxford
* 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 of the University of Oxford 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 HOLDER 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.
*/
#include <mex.h>
#include <cuda_runtime_api.h>
#include <vector_functions.h> // This has to be before the OSKAR headers
#include "interferometry/oskar_Visibilities.h"
#include "utility/oskar_Log.h"
#include "utility/oskar_Mem.h"
#include "utility/oskar_vector_types.h"
#include "utility/oskar_get_error_string.h"
#include "math/oskar_cuda_dft_c2r_2d.h"
#include "math/oskar_linspace.h"
#include "math/oskar_meshgrid.h"
#include "imaging/oskar_Image.h"
#include "imaging/oskar_image_init.h"
#include "imaging/oskar_image_resize.h"
#include "imaging/oskar_make_image.h"
#include "imaging/oskar_make_image_dft.h"
#include "imaging/oskar_SettingsImage.h"
#include "imaging/oskar_evaluate_image_lm_grid.h"
#include "matlab/image/lib/oskar_mex_image_settings_from_matlab.h"
#include "matlab/image/lib/oskar_mex_image_to_matlab_struct.h"
#include "matlab/visibilities/lib/oskar_mex_vis_from_matlab_struct.h"
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <algorithm>
#include <limits>
using namespace std;
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
#ifndef M_PI_2
#define M_PI_2 1.57079632679489661923
#endif
#ifndef c_0
#define c_0 299792458.0
#endif
// Cleanup function called when the mex function is unloaded. (i.e. 'clear mex')
void cleanup(void)
{
cudaDeviceReset();
}
void mexFunction(int num_out, mxArray** out, int num_in, const mxArray** in)
{
bool cube_imager = false;
if (num_in == 2 && num_out < 2)
{
cube_imager = true;
}
else if (num_in == 6 && num_out < 2)
{
cube_imager = false;
}
else
{
mexErrMsgTxt("Usage: \n"
" image = oskar.image.make(vis, settings)\n"
" or\n"
" image = oskar.image.make(uu, vv, amp, frequency_hz, "
"num_pixels, field_of_view_deg)\n");
}
int err = OSKAR_SUCCESS;
oskar_Image image;
oskar_Log log;
log.keep_file = 0;
int location = OSKAR_LOCATION_CPU;
// Image with the oskar_make_image() function.
if (cube_imager)
{
// Load visibilities from MATLAB structure into a oskar_Visibilties structure.
oskar_Visibilities vis;
mexPrintf("= loading vis structure... ");
oskar_mex_vis_from_matlab_struct(&vis, in[0]);
mexPrintf("done.\n");
// Construct image settings structure.
oskar_SettingsImage settings;
mexPrintf("= Loading settings structure... ");
oskar_mex_image_settings_from_matlab(&settings, in[1]);
mexPrintf("done.\n");
// Setup image object.
int type = OSKAR_DOUBLE;
oskar_image_init(&image, type, location, &err);
// Make image.
mexPrintf("= Making image...\n");
mexEvalString("drawnow"); // Force flush of matlab print buffer
err = oskar_make_image(&image, &log, &vis, &settings);
if (err)
{
mexErrMsgIdAndTxt("OSKAR:ERROR",
"\noskar.image.make() [oskar_make_image] "
"failed with code %i: %s.\n",
err, oskar_get_error_string(err));
}
mexEvalString("drawnow");
mexPrintf("= Make image complete\n");
}
// Image with manual data selection.
else
{
// Make sure visibility data array is complex.
if (!mxIsComplex(in[2]))
{
mexErrMsgTxt("Input visibility amplitude array must be complex");
}
// Evaluate the and check consistency of data precision.
int type = 0;
if (mxGetClassID(in[0]) == mxDOUBLE_CLASS &&
mxGetClassID(in[1]) == mxDOUBLE_CLASS &&
mxGetClassID(in[2]) == mxDOUBLE_CLASS)
{
type = OSKAR_DOUBLE;
}
else if (mxGetClassID(in[0]) == mxSINGLE_CLASS &&
mxGetClassID(in[1]) == mxSINGLE_CLASS &&
mxGetClassID(in[2]) == mxSINGLE_CLASS)
{
type = OSKAR_SINGLE;
}
else
{
mexErrMsgTxt("uu, vv and amplitudes must be of the same type");
}
// Retrieve input arguments.
double freq = mxGetScalar(in[3]);
int size = (int)mxGetScalar(in[4]);
double fov_deg = mxGetScalar(in[5]);
double fov = fov_deg * M_PI/180.0;
// Evaluate the number of visibility samples are in the data.
int num_baselines = mxGetM(in[0]);
int num_times = mxGetN(in[0]);
if (num_baselines != (int)mxGetM(in[1]) ||
num_baselines != (int)mxGetM(in[2]) ||
num_times != (int)mxGetN(in[1]) ||
num_times != (int)mxGetN(in[2]))
{
mexErrMsgTxt("Dimension mismatch in input data.");
}
int num_samples = num_baselines * num_times;
// Setup the image cube.
oskar_image_init(&image, type, location, &err);
oskar_image_resize(&image, size, size, 1, 1, 1);
image.centre_ra_deg = 0.0;
image.centre_dec_deg = 0.0;
image.fov_ra_deg = fov_deg;
image.fov_dec_deg = fov_deg;
image.time_start_mjd_utc = 0.0;
image.time_inc_sec = 0.0;
image.freq_start_hz = 0.0;
image.freq_inc_hz = 0.0;
image.image_type = 0;
oskar_Mem uu(type, location, num_samples);
oskar_Mem vv(type, location, num_samples);
oskar_Mem amp(type | OSKAR_COMPLEX, location, num_samples);
int num_pixels = size * size;
oskar_Mem l(type, location, num_pixels);
oskar_Mem m(type, location, num_pixels);
// Setup imaging data.
if (type == OSKAR_DOUBLE)
{
oskar_evaluate_image_lm_grid_d(size, size, fov, fov, l, m);
double* uu_ = (double*)mxGetData(in[0]);
double* vv_ = (double*)mxGetData(in[1]);
double* re_ = (double*)mxGetPr(in[2]);
double* im_ = (double*)mxGetPi(in[2]);
for (int i = 0; i < num_samples; ++i)
{
((double2*)amp.data)[i] = make_double2(re_[i], im_[i]);
((double*)uu.data)[i] = uu_[i];
((double*)vv.data)[i] = vv_[i];
}
}
else // (type == OSKAR_SINGLE)
{
oskar_evaluate_image_lm_grid_f(size, size, fov, fov, l, m);
float* uu_ = (float*)mxGetData(in[0]);
float* vv_ = (float*)mxGetData(in[1]);
float* re_ = (float*)mxGetPr(in[2]);
float* im_ = (float*)mxGetPi(in[2]);
for (int i = 0; i < num_samples; ++i)
{
((float2*)amp.data)[i] = make_float2(re_[i], im_[i]);
((float*)uu.data)[i] = uu_[i];
((float*)vv.data)[i] = vv_[i];
}
}
// Make the image.
mexPrintf("= Making image...\n");
mexEvalString("drawnow");
err = oskar_make_image_dft(&image.data, &uu, &vv, &, &l, &m, freq);
if (err)
{
mexErrMsgIdAndTxt("OSKAR:ERROR",
"\noskar.image.make() [oskar_make_image_dft] "
"failed with code %i: %s.\n",
err, oskar_get_error_string(err));
}
mexEvalString("drawnow");
mexPrintf("= Make image complete\n");
}
out[0] = oskar_mex_image_to_matlab_struct(&image, NULL);
// Register cleanup function.
mexAtExit(cleanup);
}
<|endoftext|> |
<commit_before>#include <string>
#ifdef _LIBCPP_INLINE_VISIBILITY
#undef _LIBCPP_INLINE_VISIBILITY
#endif
#define _LIBCPP_INLINE_VISIBILITY
#include <vector>
int main()
{
std::vector<bool> vBool;
vBool.push_back(false);
vBool.push_back(true);
vBool.push_back(false);
vBool.push_back(true);
vBool.push_back(false);
vBool.push_back(true);
vBool.push_back(false);
vBool.push_back(true);
vBool.push_back(false);
vBool.push_back(true);
vBool.push_back(false);
vBool.push_back(true);
vBool.push_back(false);
vBool.push_back(true);
vBool.push_back(false);
vBool.push_back(true);
vBool.push_back(false);
vBool.push_back(true);
vBool.push_back(false);
vBool.push_back(true);
vBool.push_back(false);
vBool.push_back(true);
vBool.push_back(false);
vBool.push_back(true);
vBool.push_back(false);
vBool.push_back(true);
vBool.push_back(false);
vBool.push_back(true);
vBool.push_back(false);
vBool.push_back(true);
vBool.push_back(false);
vBool.push_back(true);
vBool.push_back(false);
vBool.push_back(true);
vBool.push_back(false);
vBool.push_back(true);
vBool.push_back(false);
vBool.push_back(true);
vBool.push_back(false);
vBool.push_back(true);
vBool.push_back(false);
vBool.push_back(true);
vBool.push_back(false);
vBool.push_back(true);
vBool.push_back(false);
vBool.push_back(true);
vBool.push_back(false);
vBool.push_back(true);
vBool.push_back(true);
return 0; // Set break point at this line.
}
<commit_msg>Move the stop point to somewhere before the final use of the variable we are inspecting.<commit_after>#include <string>
#ifdef _LIBCPP_INLINE_VISIBILITY
#undef _LIBCPP_INLINE_VISIBILITY
#endif
#define _LIBCPP_INLINE_VISIBILITY
#include <vector>
int main()
{
std::vector<bool> vBool;
vBool.push_back(false);
vBool.push_back(true);
vBool.push_back(false);
vBool.push_back(true);
vBool.push_back(false);
vBool.push_back(true);
vBool.push_back(false);
vBool.push_back(true);
vBool.push_back(false);
vBool.push_back(true);
vBool.push_back(false);
vBool.push_back(true);
vBool.push_back(false);
vBool.push_back(true);
vBool.push_back(false);
vBool.push_back(true);
vBool.push_back(false);
vBool.push_back(true);
vBool.push_back(false);
vBool.push_back(true);
vBool.push_back(false);
vBool.push_back(true);
vBool.push_back(false);
vBool.push_back(true);
vBool.push_back(false);
vBool.push_back(true);
vBool.push_back(false);
vBool.push_back(true);
vBool.push_back(false);
vBool.push_back(true);
vBool.push_back(false);
vBool.push_back(true);
vBool.push_back(false);
vBool.push_back(true);
vBool.push_back(false);
vBool.push_back(true);
vBool.push_back(false);
vBool.push_back(true);
vBool.push_back(false);
vBool.push_back(true);
vBool.push_back(false);
vBool.push_back(true);
vBool.push_back(false);
vBool.push_back(true);
vBool.push_back(false);
vBool.push_back(true);
vBool.push_back(false);
vBool.push_back(true);
vBool.push_back(true);
printf ("size: %d", (int) vBool.size()); // Set break point at this line.
return 0;
}
<|endoftext|> |
<commit_before>/*
* This code is based off Adam Nielsen's cfgpath C header found at
* https://github.com/Malvineous/cfgpath
*
* Following his code being public domain I have licensed this using the
* unlicense http://unlicense.org/. Full license text is available in
* the LICENSE file
*/
#include "cfgpath.hpp"
#include <sstream>
#include <stdexcept>
#include <cstdlib>
\
#ifdef _WIN32
#include <shlobj.h>
#include <direct.h>
const char _pathSep = '\\';
#endif
#ifdef __unix__
#include <sys/stat.h>
const char _pathSep = '/';
#endif
using std::stringstream;
bool createDirectoryIfNotExist(const string& path) {
#ifdef WIN32
return (_mkdir(path.c_str()) == 0 || errno == EEXIST);
#elif defined(__APPLE__)
#elif defined(__unix__)
return (mkdir(path.c_str(), 0700) == 0 || errno == EEXIST);
#else
throw std::logic_error("Incompatible OS");
#endif
}
string get_standard_config_path() {
stringstream cfgPath;
//Windows first, then Apple, then other *nixes
#ifdef WIN32
//using ansi windows for now
//assume appdata directory exists
char _confPath[MAX_PATH];
if (!SUCCEEDED(SHGetFolderPathA(NULL, CSIDL_APPDATA, NULL, 0, _confPath))) {
throw std::runtime_error("Unable to get standard config path from system");
}
cfgPath<< _confPath;
cfgPath<< _pathSep;
#elif defined(__APPLE__)
#elif defined(__unix__)
//Follow XDG Specification
//Assume $XDG_CONFIG_HOME exists if it's set
//Assume $HOME exists if it's set
const char * _confHome = getenv("XDG_CONFIG_HOME");
if (!_confHome) {
//XDG_CONFIG_HOME isn't set. USE $HOME/.config
_confHome = getenv("HOME");
if (!_confHome) throw std::runtime_error("Unable to find home directory");
cfgPath << _confHome;
cfgPath << _pathSep;
cfgPath << ".config";
if (!createDirectoryIfNotExist(cfgPath.str()))
throw std::runtime_error("Unable to create .config in user home");
} else {
cfgPath << _confHome;
}
cfgPath << _pathSep;
#else
throw std::logic_error("Incompatible OS");
#endif
return cfgPath.str();
}
bool createFileIfNotExist(const string& path) {
return true;
}
string cfgpath::get_user_config_folder(const string& appname) {
stringstream cfgPath;
cfgPath << get_standard_config_path();
cfgPath << appname;
if (!createDirectoryIfNotExist(cfgPath.str()))
throw std::runtime_error("Unable to create application config directory");
cfgPath << _pathSep;
return cfgPath.str();
}
string cfgpath::get_user_config_file(const string& appname, const std::__cxx11::string &extension) {
stringstream cfgPath;
cfgPath << get_standard_config_path() << appname << extension;
return cfgPath.str();
}
string cfgpath::get_user_data_folder(const string& appname) {
stringstream cfgPath;
//Windows first, then Apple, then other *nixes
#ifdef WIN32
//same path as config
cfgPath << get_user_config_folder(appname);
#elif defined(__APPLE__)
#elif defined(__unix__)
#else
throw std::logic_error("Incompatible OS");
#endif
return cfgPath.str();
}
<commit_msg>Implemented *nix get_user_data_folder<commit_after>/*
* This code is based off Adam Nielsen's cfgpath C header found at
* https://github.com/Malvineous/cfgpath
*
* Following his code being public domain I have licensed this using the
* unlicense http://unlicense.org/. Full license text is available in
* the LICENSE file
*/
#include "cfgpath.hpp"
#include <sstream>
#include <stdexcept>
#include <cstdlib>
\
#ifdef _WIN32
#include <shlobj.h>
#include <direct.h>
const char _pathSep = '\\';
#endif
#ifdef __unix__
#include <sys/stat.h>
const char _pathSep = '/';
#endif
using std::stringstream;
bool createDirectoryIfNotExist(const string& path) {
#ifdef WIN32
return (_mkdir(path.c_str()) == 0 || errno == EEXIST);
#elif defined(__APPLE__)
#elif defined(__unix__)
return (mkdir(path.c_str(), 0700) == 0 || errno == EEXIST);
#else
throw std::logic_error("Incompatible OS");
#endif
}
string get_standard_config_path() {
stringstream cfgPath;
//Windows first, then Apple, then other *nixes
#ifdef WIN32
//using ansi windows for now
//assume appdata directory exists
char _confPath[MAX_PATH];
if (!SUCCEEDED(SHGetFolderPathA(NULL, CSIDL_APPDATA, NULL, 0, _confPath))) {
throw std::runtime_error("Unable to get standard config path from system");
}
cfgPath<< _confPath;
cfgPath<< _pathSep;
#elif defined(__APPLE__)
#elif defined(__unix__)
//Follow XDG Specification
//Assume $XDG_CONFIG_HOME exists if it's set
//Assume $HOME exists if it's set
const char * _confHome = getenv("XDG_CONFIG_HOME");
if (!_confHome) {
//XDG_CONFIG_HOME isn't set. USE $HOME/.config
_confHome = getenv("HOME");
if (!_confHome) throw std::runtime_error("Unable to find home directory");
cfgPath << _confHome;
cfgPath << _pathSep;
cfgPath << ".config";
if (!createDirectoryIfNotExist(cfgPath.str()))
throw std::runtime_error("Unable to create .config in user home");
} else {
cfgPath << _confHome;
}
cfgPath << _pathSep;
#else
throw std::logic_error("Incompatible OS");
#endif
return cfgPath.str();
}
bool createFileIfNotExist(const string& path) {
return true;
}
string cfgpath::get_user_config_folder(const string& appname) {
stringstream cfgPath;
cfgPath << get_standard_config_path();
cfgPath << appname;
if (!createDirectoryIfNotExist(cfgPath.str()))
throw std::runtime_error("Unable to create application config directory");
cfgPath << _pathSep;
return cfgPath.str();
}
string cfgpath::get_user_config_file(const string& appname, const std::__cxx11::string &extension) {
stringstream cfgPath;
cfgPath << get_standard_config_path() << appname << extension;
return cfgPath.str();
}
string cfgpath::get_user_data_folder(const string& appname) {
stringstream cfgPath;
//Windows first, then Apple, then other *nixes
#ifdef WIN32
//same path as config
cfgPath << get_user_config_folder(appname);
#elif defined(__APPLE__)
#elif defined(__unix__)
//Follow XDG Specification
//Assume $XDG_DATA_HOME exists if it's set
//Assume $HOME exists if it's set
const char * _dataHome = getenv("XDG_DATA_HOME");
if (!_dataHome) {
//XDG_DATA_HOME isn't set. USE $HOME/.local/share
_dataHome = getenv("HOME");
if (!_dataHome) throw std::runtime_error("Unable to find home directory");
cfgPath << _dataHome << _pathSep << ".local";
if (!createDirectoryIfNotExist(cfgPath.str()))
throw std::runtime_error("Unable to create .local in user home");
cfgPath << _pathSep << "share";
if (!createDirectoryIfNotExist(cfgPath.str()))
throw std::runtime_error("Unable to create share in user home/.local");
} else {
cfgPath << _dataHome;
}
cfgPath << _pathSep << appname;
if (!createDirectoryIfNotExist(cfgPath.str()))
throw std::runtime_error("Unable to create application data directory");
cfgPath << _pathSep;
#else
throw std::logic_error("Incompatible OS");
#endif
return cfgPath.str();
}
<|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: core.cxx,v $
*
* $Revision: 1.3.34.1 $
*
* 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.
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_extensions.hxx"
#include <com/sun/star/oooimprovement/XCore.hpp>
#include "oooimprovecore_module.hxx"
#include <com/sun/star/frame/XTerminateListener.hpp>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/lang/XServiceInfo.hpp>
#include <com/sun/star/oooimprovement/XCoreController.hpp>
#include <com/sun/star/uno/XComponentContext.hpp>
#include <comphelper/componentmodule.hxx>
#include <comphelper/configurationhelper.hxx>
#include <comphelper/processfactory.hxx>
#include <comphelper/uieventslogger.hxx>
#include <cppuhelper/implbase3.hxx>
#include <svx/svxdlg.hxx>
#include <vcl/svapp.hxx>
#include <vos/mutex.hxx>
#include <svtools/itemset.hxx>
#include <svtools/stritem.hxx>
#include <sfx2/app.hxx>
#include <svx/dialogs.hrc>
#include <sfx2/sfxsids.hrc>
using namespace ::com::sun::star::oooimprovement;
using ::com::sun::star::frame::XTerminateListener;
using ::com::sun::star::lang::EventObject;
using ::com::sun::star::lang::XMultiServiceFactory;
using ::com::sun::star::lang::XServiceInfo;
using ::com::sun::star::uno::Reference;
using ::com::sun::star::uno::RuntimeException;
using ::com::sun::star::uno::Sequence;
using ::com::sun::star::uno::UNO_QUERY;
using ::com::sun::star::uno::XComponentContext;
using ::com::sun::star::uno::XInterface;
using ::comphelper::UiEventsLogger;
using ::rtl::OUString;
// declaration
namespace oooimprovecore
{
class Core : public ::cppu::WeakImplHelper3<XCore,XServiceInfo,XTerminateListener>
{
public:
// XServiceInfo - static version
static OUString SAL_CALL getImplementationName_static();
static Sequence<OUString> SAL_CALL getSupportedServiceNames_static();
static Reference<XInterface> Create(const Reference<XComponentContext>& context );
protected:
Core(const Reference<XComponentContext>&);
virtual ~Core();
// XCore
virtual sal_Int32 SAL_CALL getSessionLogEventCount() throw(RuntimeException);
virtual sal_Bool SAL_CALL getUiEventsLoggerEnabled() throw(RuntimeException);
virtual void SAL_CALL inviteUser() throw(RuntimeException);
// XServiceInfo
virtual OUString SAL_CALL getImplementationName() throw(RuntimeException);
virtual sal_Bool SAL_CALL supportsService(const OUString& service_name) throw(RuntimeException);
virtual Sequence<OUString> SAL_CALL getSupportedServiceNames() throw(RuntimeException);
// XTerminateListener
virtual void SAL_CALL queryTermination(const EventObject&) throw(RuntimeException);
virtual void SAL_CALL notifyTermination(const EventObject&) throw(RuntimeException);
// XEventListener
virtual void SAL_CALL disposing(const EventObject&) throw(RuntimeException);
};
}
// implementation
namespace oooimprovecore
{
Core::Core(const Reference<XComponentContext>&)
{ }
Core::~Core()
{ }
sal_Int32 SAL_CALL Core::getSessionLogEventCount() throw(RuntimeException)
{ return UiEventsLogger::getSessionLogEventCount(); }
sal_Bool SAL_CALL Core::getUiEventsLoggerEnabled() throw(RuntimeException)
{ return UiEventsLogger::isEnabled(); }
void SAL_CALL Core::inviteUser() throw(RuntimeException)
{
Reference<XMultiServiceFactory> xServiceFactory = ::comphelper::getProcessServiceFactory();
OUString help_url;
Reference<XCoreController> core_c(
xServiceFactory->createInstance(OUString::createFromAscii("com.sun.star.oooimprovement.CoreController")),
UNO_QUERY);
if(core_c.is())
::comphelper::ConfigurationHelper::readDirectKey(
xServiceFactory,
OUString::createFromAscii("/org.openoffice.Office.OOoImprovement.Settings"),
OUString::createFromAscii("Participation"),
OUString::createFromAscii("HelpUrl"),
::comphelper::ConfigurationHelper::E_READONLY) >>= help_url;
else
help_url = OUString::createFromAscii("http://www.openoffice.org");
{
::vos::OGuard aGuard( Application::GetSolarMutex() );
SfxAllItemSet aSet( SFX_APP()->GetPool() );
aSet.Put( SfxStringItem( SID_CURRENT_URL, help_url ) );
SvxAbstractDialogFactory* pFact = SvxAbstractDialogFactory::Create();
if ( pFact )
{
AbstractSfxSingleTabDialog *pDlg = pFact->CreateSfxSingleTabDialog( NULL, aSet, 0, RID_SVXPAGE_IMPROVEMENT );
pDlg->Execute();
delete pDlg;
}
}
}
sal_Bool SAL_CALL Core::supportsService(const OUString& service_name) throw(RuntimeException)
{
const Sequence<OUString> service_names(getSupportedServiceNames());
for (sal_Int32 idx = service_names.getLength()-1; idx>=0; --idx)
if(service_name == service_names[idx]) return sal_True;
return sal_False;
}
OUString SAL_CALL Core::getImplementationName() throw(RuntimeException)
{ return getImplementationName_static(); }
Sequence<OUString> SAL_CALL Core::getSupportedServiceNames() throw(RuntimeException)
{ return getSupportedServiceNames_static(); }
OUString SAL_CALL Core::getImplementationName_static()
{ return OUString::createFromAscii("com.sun.star.comp.extensions.oooimprovecore.Core"); }
Sequence<OUString> SAL_CALL Core::getSupportedServiceNames_static()
{
Sequence<OUString> aServiceNames(1);
aServiceNames[0] = OUString::createFromAscii("com.sun.star.oooimprovement.Core");
return aServiceNames;
}
void Core::queryTermination(const EventObject&) throw(RuntimeException)
{ }
void Core::notifyTermination(const EventObject&) throw(RuntimeException)
{
UiEventsLogger::disposing();
}
void Core::disposing(const EventObject&) throw(RuntimeException)
{ }
Reference<XInterface> Core::Create(const Reference<XComponentContext>& context)
{ return *(new Core(context)); }
void createRegistryInfo_Core()
{
static OAutoRegistration<Core> auto_reg;
}
}
<commit_msg>#i100000# fix for merge errors<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: core.cxx,v $
*
* $Revision: 1.3.34.1 $
*
* 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.
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_extensions.hxx"
#include <com/sun/star/oooimprovement/XCore.hpp>
#include "oooimprovecore_module.hxx"
#include <com/sun/star/frame/XTerminateListener.hpp>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/lang/XServiceInfo.hpp>
#include <com/sun/star/oooimprovement/XCoreController.hpp>
#include <com/sun/star/uno/XComponentContext.hpp>
#include <comphelper/componentmodule.hxx>
#include <comphelper/configurationhelper.hxx>
#include <comphelper/processfactory.hxx>
#include <comphelper/uieventslogger.hxx>
#include <cppuhelper/implbase3.hxx>
#include <svx/svxdlg.hxx>
#include <vcl/svapp.hxx>
#include <vos/mutex.hxx>
#include <svtools/itemset.hxx>
#include <svtools/stritem.hxx>
#include <sfx2/app.hxx>
#include <svx/dialogs.hrc>
#include <sfx2/sfxsids.hrc>
using namespace ::com::sun::star::oooimprovement;
using ::com::sun::star::frame::XTerminateListener;
using ::com::sun::star::lang::EventObject;
using ::com::sun::star::lang::XMultiServiceFactory;
using ::com::sun::star::lang::XServiceInfo;
using ::com::sun::star::uno::Reference;
using ::com::sun::star::uno::RuntimeException;
using ::com::sun::star::uno::Sequence;
using ::com::sun::star::uno::UNO_QUERY;
using ::com::sun::star::uno::XComponentContext;
using ::com::sun::star::uno::XInterface;
using ::comphelper::UiEventsLogger;
using ::rtl::OUString;
// declaration
namespace oooimprovecore
{
class Core : public ::cppu::WeakImplHelper3<XCore,XServiceInfo,XTerminateListener>
{
public:
// XServiceInfo - static version
static OUString SAL_CALL getImplementationName_static();
static Sequence<OUString> SAL_CALL getSupportedServiceNames_static();
static Reference<XInterface> Create(const Reference<XComponentContext>& context );
protected:
Core(const Reference<XComponentContext>&);
virtual ~Core();
// XCore
virtual sal_Int32 SAL_CALL getSessionLogEventCount() throw(RuntimeException);
virtual sal_Bool SAL_CALL getUiEventsLoggerEnabled() throw(RuntimeException);
virtual void SAL_CALL inviteUser() throw(RuntimeException);
// XServiceInfo
virtual OUString SAL_CALL getImplementationName() throw(RuntimeException);
virtual sal_Bool SAL_CALL supportsService(const OUString& service_name) throw(RuntimeException);
virtual Sequence<OUString> SAL_CALL getSupportedServiceNames() throw(RuntimeException);
// XTerminateListener
virtual void SAL_CALL queryTermination(const EventObject&) throw(RuntimeException);
virtual void SAL_CALL notifyTermination(const EventObject&) throw(RuntimeException);
// XEventListener
virtual void SAL_CALL disposing(const EventObject&) throw(RuntimeException);
};
}
// implementation
namespace oooimprovecore
{
Core::Core(const Reference<XComponentContext>&)
{ }
Core::~Core()
{ }
sal_Int32 SAL_CALL Core::getSessionLogEventCount() throw(RuntimeException)
{ return UiEventsLogger::getSessionLogEventCount(); }
sal_Bool SAL_CALL Core::getUiEventsLoggerEnabled() throw(RuntimeException)
{ return UiEventsLogger::isEnabled(); }
void SAL_CALL Core::inviteUser() throw(RuntimeException)
{
Reference<XMultiServiceFactory> xServiceFactory = ::comphelper::getProcessServiceFactory();
OUString help_url;
Reference<XCoreController> core_c(
xServiceFactory->createInstance(OUString::createFromAscii("com.sun.star.oooimprovement.CoreController")),
UNO_QUERY);
if(core_c.is())
::comphelper::ConfigurationHelper::readDirectKey(
xServiceFactory,
OUString::createFromAscii("/org.openoffice.Office.OOoImprovement.Settings"),
OUString::createFromAscii("Participation"),
OUString::createFromAscii("HelpUrl"),
::comphelper::ConfigurationHelper::E_READONLY) >>= help_url;
else
help_url = OUString::createFromAscii("http://www.openoffice.org");
{
::vos::OGuard aGuard( Application::GetSolarMutex() );
SfxAllItemSet aSet( SFX_APP()->GetPool() );
aSet.Put( SfxStringItem( SID_CURRENT_URL, help_url ) );
SvxAbstractDialogFactory* pFact = SvxAbstractDialogFactory::Create();
if ( pFact )
{
SfxAbstractDialog *pDlg = pFact->CreateSfxDialog( NULL, aSet, 0, RID_SVXPAGE_IMPROVEMENT );
pDlg->Execute();
delete pDlg;
}
}
}
sal_Bool SAL_CALL Core::supportsService(const OUString& service_name) throw(RuntimeException)
{
const Sequence<OUString> service_names(getSupportedServiceNames());
for (sal_Int32 idx = service_names.getLength()-1; idx>=0; --idx)
if(service_name == service_names[idx]) return sal_True;
return sal_False;
}
OUString SAL_CALL Core::getImplementationName() throw(RuntimeException)
{ return getImplementationName_static(); }
Sequence<OUString> SAL_CALL Core::getSupportedServiceNames() throw(RuntimeException)
{ return getSupportedServiceNames_static(); }
OUString SAL_CALL Core::getImplementationName_static()
{ return OUString::createFromAscii("com.sun.star.comp.extensions.oooimprovecore.Core"); }
Sequence<OUString> SAL_CALL Core::getSupportedServiceNames_static()
{
Sequence<OUString> aServiceNames(1);
aServiceNames[0] = OUString::createFromAscii("com.sun.star.oooimprovement.Core");
return aServiceNames;
}
void Core::queryTermination(const EventObject&) throw(RuntimeException)
{ }
void Core::notifyTermination(const EventObject&) throw(RuntimeException)
{
UiEventsLogger::disposing();
}
void Core::disposing(const EventObject&) throw(RuntimeException)
{ }
Reference<XInterface> Core::Create(const Reference<XComponentContext>& context)
{ return *(new Core(context)); }
void createRegistryInfo_Core()
{
static OAutoRegistration<Core> auto_reg;
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: astenum.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: jsc $ $Date: 2001-08-30 07:22:03 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _IDLC_ASTENUM_HXX_
#include <idlc/astenum.hxx>
#endif
using namespace ::rtl;
AstEnum::AstEnum(const ::rtl::OString& name, AstScope* pScope)
: AstType(NT_enum, name, pScope)
, AstScope(NT_enum)
, m_enumValueCount(0)
{
}
AstEnum::~AstEnum()
{
}
AstConstant* AstEnum::checkValue(AstExpression* pExpr)
{
DeclList::iterator iter = getIteratorBegin();
DeclList::iterator end = getIteratorEnd();
AstConstant* pConst = NULL;
AstDeclaration* pDecl = NULL;
while ( iter != end)
{
pDecl = *iter;
pConst = (AstConstant*)pDecl;
if (pConst->getConstValue()->compare(pExpr))
return pConst;
++iter;
}
if ( pExpr->getExprValue()->u.lval > m_enumValueCount )
m_enumValueCount = pExpr->getExprValue()->u.lval + 1;
return NULL;
}
sal_Bool AstEnum::dump(RegistryKey& rKey, RegistryTypeWriterLoader* pLoader)
{
RegistryKey localKey;
if (rKey.createKey( OStringToOUString(getFullName(), RTL_TEXTENCODING_UTF8 ), localKey))
{
fprintf(stderr, "%s: warning, could not create key '%s' in '%s'\n",
idlc()->getOptions()->getProgramName().getStr(),
getFullName().getStr(), OUStringToOString(rKey.getRegistryName(), RTL_TEXTENCODING_UTF8).getStr());
return sal_False;
}
sal_uInt16 nConst = getNodeCount(NT_enum_val);
if ( nConst > 0 )
{
RegistryTypeWriter aBlob(pLoader->getApi(),
RT_TYPE_ENUM,
OStringToOUString(getRelativName(), RTL_TEXTENCODING_UTF8),
OUString(), nConst, 0, 0);
aBlob.setDoku( getDocumentation() );
aBlob.setFileName( OStringToOUString(getFileName(), RTL_TEXTENCODING_UTF8));
DeclList::iterator iter = getIteratorBegin();
DeclList::iterator end = getIteratorEnd();
AstDeclaration* pDecl = NULL;
sal_uInt16 index = 0;
while ( iter != end )
{
pDecl = *iter;
if ( pDecl->getNodeType() == NT_enum_val )
((AstConstant*)pDecl)->dumpBlob(aBlob, index++);
++iter;
}
const sal_uInt8* pBlob = aBlob.getBlop();
sal_uInt32 aBlobSize = aBlob.getBlopSize();
if (localKey.setValue(OUString(), RG_VALUETYPE_BINARY,
(RegValue)pBlob, aBlobSize))
{
fprintf(stderr, "%s: warning, could not set value of key \"%s\" in %s\n",
idlc()->getOptions()->getProgramName().getStr(),
getFullName().getStr(), OUStringToOString(localKey.getRegistryName(), RTL_TEXTENCODING_UTF8).getStr());
return sal_False;
}
}
return sal_True;
}
AstDeclaration* AstEnum::addDeclaration(AstDeclaration* pDecl)
{
AstScope* pScope = getScope();
// add enum value to enclosing scope of the enum
// pDecl->setName(scopeAsDecl(pScope)->getScopedName() + "::" + pDecl->getLocalName());
// pScope->addDeclaration(pDecl);
return AstScope::addDeclaration(pDecl);
}
<commit_msg>INTEGRATION: CWS sb14 (1.3.84); FILE MERGED 2004/03/15 09:53:56 sb 1.3.84.2: #i21150# Adapted to new extensible type writer interface; added support for bound interface attributes. 2004/03/01 12:59:23 sb 1.3.84.1: #i21150# Added optional interface inheritance; added -stdin switch; do not warn about bad member names of com.sun.star.uno.Uik; some general clean up and added const qualifiers.<commit_after>/*************************************************************************
*
* $RCSfile: astenum.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2004-03-30 16:45:15 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _IDLC_ASTENUM_HXX_
#include <idlc/astenum.hxx>
#endif
#include "registry/version.h"
#include "registry/writer.hxx"
using namespace ::rtl;
AstEnum::AstEnum(const ::rtl::OString& name, AstScope* pScope)
: AstType(NT_enum, name, pScope)
, AstScope(NT_enum)
, m_enumValueCount(0)
{
}
AstEnum::~AstEnum()
{
}
AstConstant* AstEnum::checkValue(AstExpression* pExpr)
{
DeclList::const_iterator iter = getIteratorBegin();
DeclList::const_iterator end = getIteratorEnd();
AstConstant* pConst = NULL;
AstDeclaration* pDecl = NULL;
while ( iter != end)
{
pDecl = *iter;
pConst = (AstConstant*)pDecl;
if (pConst->getConstValue()->compare(pExpr))
return pConst;
++iter;
}
if ( pExpr->getExprValue()->u.lval > m_enumValueCount )
m_enumValueCount = pExpr->getExprValue()->u.lval + 1;
return NULL;
}
sal_Bool AstEnum::dump(RegistryKey& rKey)
{
RegistryKey localKey;
if (rKey.createKey( OStringToOUString(getFullName(), RTL_TEXTENCODING_UTF8 ), localKey))
{
fprintf(stderr, "%s: warning, could not create key '%s' in '%s'\n",
idlc()->getOptions()->getProgramName().getStr(),
getFullName().getStr(), OUStringToOString(rKey.getRegistryName(), RTL_TEXTENCODING_UTF8).getStr());
return sal_False;
}
sal_uInt16 nConst = getNodeCount(NT_enum_val);
if ( nConst > 0 )
{
typereg::Writer aBlob(
TYPEREG_VERSION_0, getDocumentation(),
OStringToOUString(getFileName(), RTL_TEXTENCODING_UTF8),
RT_TYPE_ENUM,
OStringToOUString(getRelativName(), RTL_TEXTENCODING_UTF8), 0,
nConst, 0, 0);
DeclList::const_iterator iter = getIteratorBegin();
DeclList::const_iterator end = getIteratorEnd();
AstDeclaration* pDecl = NULL;
sal_uInt16 index = 0;
while ( iter != end )
{
pDecl = *iter;
if ( pDecl->getNodeType() == NT_enum_val )
((AstConstant*)pDecl)->dumpBlob(aBlob, index++);
++iter;
}
sal_uInt32 aBlobSize;
void const * pBlob = aBlob.getBlob(&aBlobSize);
if (localKey.setValue(OUString(), RG_VALUETYPE_BINARY,
(RegValue)pBlob, aBlobSize))
{
fprintf(stderr, "%s: warning, could not set value of key \"%s\" in %s\n",
idlc()->getOptions()->getProgramName().getStr(),
getFullName().getStr(), OUStringToOString(localKey.getRegistryName(), RTL_TEXTENCODING_UTF8).getStr());
return sal_False;
}
}
return sal_True;
}
AstDeclaration* AstEnum::addDeclaration(AstDeclaration* pDecl)
{
AstScope* pScope = getScope();
// add enum value to enclosing scope of the enum
// pDecl->setName(scopeAsDecl(pScope)->getScopedName() + "::" + pDecl->getLocalName());
// pScope->addDeclaration(pDecl);
return AstScope::addDeclaration(pDecl);
}
<|endoftext|> |
<commit_before>#include "ScaledImageFactory.h"
#include <memory>
#define STB_IMAGE_RESIZE_IMPLEMENTATION
#include <stb/stb_image_resize.h>
using namespace std;
void GetScaledSubrect( wxImage& dst, const wxImage& src, const double scale, const wxPoint& pos )
{
#if 0
const size_t srcW = static_cast< size_t >( src.GetWidth() );
const size_t dstW = static_cast< size_t >( dst.GetWidth() );
const size_t dstH = static_cast< size_t >( dst.GetHeight() );
const float scaleInv = 1.0f / scale;
// color
{
const unsigned char* srcData = src.GetData();
unsigned char* dstData = dst.GetData();
for( size_t dstY = 0; dstY < dstH; ++dstY )
{
unsigned char* dstRow = &dstData[ dstY * dstW * 3 ];
const size_t srcY( ( dstY + pos.y ) * scaleInv );
const unsigned char* srcRow = &srcData[ srcY * srcW * 3 ];
for( size_t dstX = 0; dstX < dstW; ++dstX )
{
const size_t srcX( ( dstX + pos.x ) * scaleInv );
const unsigned char* srcPx = &srcRow[ srcX * 3 ];
dstRow[ dstX * 3 + 0 ] = srcPx[ 0 ];
dstRow[ dstX * 3 + 1 ] = srcPx[ 1 ];
dstRow[ dstX * 3 + 2 ] = srcPx[ 2 ];
}
}
}
if( !src.HasAlpha() )
return;
// alpha
{
const unsigned char* srcData = src.GetAlpha();
unsigned char* dstData = dst.GetAlpha();
for( size_t dstY = 0; dstY < dstH; ++dstY )
{
unsigned char* dstRow = &dstData[ dstY * dstW ];
const size_t srcY( ( dstY + pos.y ) * scaleInv );
const unsigned char* srcRow = &srcData[ srcY * srcW ];
for( size_t dstX = 0; dstX < dstW; ++dstX )
{
const size_t srcX( ( dstX + pos.x ) * scaleInv );
const unsigned char* srcPx = &srcRow[ srcX ];
dstRow[ dstX + 0 ] = srcPx[ 0 ];
}
}
}
return;
#endif
const stbir_filter filter = STBIR_FILTER_TRIANGLE;
const stbir_edge edge = STBIR_EDGE_CLAMP;
const stbir_colorspace colorspace = STBIR_COLORSPACE_SRGB;
stbir_resize_subpixel
(
src.GetData(), src.GetWidth(), src.GetHeight(), 0,
dst.GetData(), dst.GetWidth(), dst.GetHeight(), 0,
STBIR_TYPE_UINT8,
3,
0,
STBIR_ALPHA_CHANNEL_NONE,
edge, edge,
filter, filter,
colorspace,
NULL,
scale, scale,
static_cast< float >( pos.x ), static_cast< float >( pos.y )
);
if( !src.HasAlpha() )
return;
stbir_resize_subpixel
(
src.GetAlpha(), src.GetWidth(), src.GetHeight(), 0,
dst.GetAlpha(), dst.GetWidth(), dst.GetHeight(), 0,
STBIR_TYPE_UINT8,
1,
0,
STBIR_FLAG_ALPHA_PREMULTIPLIED,
edge, edge,
filter, filter,
colorspace,
NULL,
scale, scale,
static_cast< float >( pos.x ), static_cast< float >( pos.y )
);
}
class ScaledImageFactory::WorkerThread : public wxThread
{
public:
WorkerThread
(
wxEvtHandler* eventSink,
int id,
ScaledImageFactory::JobPoolType& mJobPool,
ScaledImageFactory::ResultQueueType& mResultQueue
)
: wxThread( wxTHREAD_JOINABLE )
, mEventSink( eventSink ), mEventId( id ), mJobPool( mJobPool ), mResultQueue( mResultQueue )
{ }
virtual ExitCode Entry()
{
ScaledImageFactory::JobItem job;
while( wxSORTABLEMSGQUEUE_NO_ERROR == mJobPool.Receive( job ) )
{
if( NULL == job.second.mImage || TestDestroy() )
break;
const wxRect& rect = job.first;
ScaledImageFactory::Context& ctx = job.second;
ScaledImageFactory::ResultItem result;
result.mGeneration = ctx.mGeneration;
result.mRect = rect;
result.mImage = new wxImage( rect.GetWidth(), rect.GetHeight(), false );
if( ctx.mImage->HasAlpha() )
{
result.mImage->SetAlpha( NULL );
}
GetScaledSubrect
(
*result.mImage,
*ctx.mImage,
ctx.mScale,
rect.GetPosition()
);
mResultQueue.Post( result );
wxQueueEvent( mEventSink, new wxThreadEvent( wxEVT_THREAD, mEventId ) );
}
return static_cast< wxThread::ExitCode >( 0 );
}
private:
wxEvtHandler* mEventSink;
int mEventId;
ScaledImageFactory::JobPoolType& mJobPool;
ScaledImageFactory::ResultQueueType& mResultQueue;
};
ScaledImageFactory::ScaledImageFactory( wxEvtHandler* eventSink, int id )
{
size_t numThreads = wxThread::GetCPUCount();
if( numThreads <= 0 ) numThreads = 1;
if( numThreads > 1 ) numThreads--;
for( size_t i = 0; i < numThreads; ++i )
{
mThreads.push_back( new WorkerThread( eventSink, id, mJobPool, mResultQueue ) );
}
for( wxThread*& thread : mThreads )
{
if( NULL == thread )
continue;
if( thread->Run() != wxTHREAD_NO_ERROR )
{
delete thread;
thread = NULL;
}
}
mCurrentCtx.mGeneration = 0;
}
ScaledImageFactory::~ScaledImageFactory()
{
// clear job queue and send down "kill" jobs
mJobPool.Clear();
for( size_t i = 0; i < mThreads.size(); ++i )
{
mJobPool.Post( JobItem( wxRect(), Context() ) );
}
for( wxThread* thread : mThreads )
{
if( NULL == thread )
continue;
thread->Wait();
delete thread;
}
}
void ScaledImageFactory::SetImage( wxImagePtr& newImage, double newScale )
{
if( NULL == mCurrentCtx.mImage )
throw std::runtime_error( "Image not set!" );
mCurrentCtx.mGeneration++;
mCurrentCtx.mImage = newImage;
mCurrentCtx.mScale = newScale;
mJobPool.Clear();
}
bool ScaledImageFactory::AddRect( const wxRect& rect )
{
if( NULL == mCurrentCtx.mImage )
throw std::runtime_error( "Image not set!" );
return( wxSORTABLEMSGQUEUE_NO_ERROR == mJobPool.Post( JobItem( rect, mCurrentCtx ) ) );
}
bool ScaledImageFactory::GetImage( wxRect& rect, wxImagePtr& image )
{
ResultItem item;
wxMessageQueueError err;
while( true )
{
err = mResultQueue.ReceiveTimeout( 0, item );
if( wxMSGQUEUE_TIMEOUT == err )
return false;
if( wxMSGQUEUE_MISC_ERROR == err )
throw std::runtime_error( "ResultQueue misc error!" );
if( item.mGeneration != mCurrentCtx.mGeneration )
continue;
break;
}
rect = item.mRect;
image = item.mImage;
return true;
}
void ScaledImageFactory::ClearQueue()
{
mJobPool.Clear();
}
<commit_msg>Fix copy/paste bug<commit_after>#include "ScaledImageFactory.h"
#include <memory>
#define STB_IMAGE_RESIZE_IMPLEMENTATION
#include <stb/stb_image_resize.h>
using namespace std;
void GetScaledSubrect( wxImage& dst, const wxImage& src, const double scale, const wxPoint& pos )
{
#if 0
const size_t srcW = static_cast< size_t >( src.GetWidth() );
const size_t dstW = static_cast< size_t >( dst.GetWidth() );
const size_t dstH = static_cast< size_t >( dst.GetHeight() );
const float scaleInv = 1.0f / scale;
// color
{
const unsigned char* srcData = src.GetData();
unsigned char* dstData = dst.GetData();
for( size_t dstY = 0; dstY < dstH; ++dstY )
{
unsigned char* dstRow = &dstData[ dstY * dstW * 3 ];
const size_t srcY( ( dstY + pos.y ) * scaleInv );
const unsigned char* srcRow = &srcData[ srcY * srcW * 3 ];
for( size_t dstX = 0; dstX < dstW; ++dstX )
{
const size_t srcX( ( dstX + pos.x ) * scaleInv );
const unsigned char* srcPx = &srcRow[ srcX * 3 ];
dstRow[ dstX * 3 + 0 ] = srcPx[ 0 ];
dstRow[ dstX * 3 + 1 ] = srcPx[ 1 ];
dstRow[ dstX * 3 + 2 ] = srcPx[ 2 ];
}
}
}
if( !src.HasAlpha() )
return;
// alpha
{
const unsigned char* srcData = src.GetAlpha();
unsigned char* dstData = dst.GetAlpha();
for( size_t dstY = 0; dstY < dstH; ++dstY )
{
unsigned char* dstRow = &dstData[ dstY * dstW ];
const size_t srcY( ( dstY + pos.y ) * scaleInv );
const unsigned char* srcRow = &srcData[ srcY * srcW ];
for( size_t dstX = 0; dstX < dstW; ++dstX )
{
const size_t srcX( ( dstX + pos.x ) * scaleInv );
const unsigned char* srcPx = &srcRow[ srcX ];
dstRow[ dstX + 0 ] = srcPx[ 0 ];
}
}
}
return;
#endif
const stbir_filter filter = STBIR_FILTER_TRIANGLE;
const stbir_edge edge = STBIR_EDGE_CLAMP;
const stbir_colorspace colorspace = STBIR_COLORSPACE_SRGB;
stbir_resize_subpixel
(
src.GetData(), src.GetWidth(), src.GetHeight(), 0,
dst.GetData(), dst.GetWidth(), dst.GetHeight(), 0,
STBIR_TYPE_UINT8,
3,
0,
STBIR_ALPHA_CHANNEL_NONE,
edge, edge,
filter, filter,
colorspace,
NULL,
scale, scale,
static_cast< float >( pos.x ), static_cast< float >( pos.y )
);
if( !src.HasAlpha() )
return;
stbir_resize_subpixel
(
src.GetAlpha(), src.GetWidth(), src.GetHeight(), 0,
dst.GetAlpha(), dst.GetWidth(), dst.GetHeight(), 0,
STBIR_TYPE_UINT8,
1,
0,
STBIR_FLAG_ALPHA_PREMULTIPLIED,
edge, edge,
filter, filter,
colorspace,
NULL,
scale, scale,
static_cast< float >( pos.x ), static_cast< float >( pos.y )
);
}
class ScaledImageFactory::WorkerThread : public wxThread
{
public:
WorkerThread
(
wxEvtHandler* eventSink,
int id,
ScaledImageFactory::JobPoolType& mJobPool,
ScaledImageFactory::ResultQueueType& mResultQueue
)
: wxThread( wxTHREAD_JOINABLE )
, mEventSink( eventSink ), mEventId( id ), mJobPool( mJobPool ), mResultQueue( mResultQueue )
{ }
virtual ExitCode Entry()
{
ScaledImageFactory::JobItem job;
while( wxSORTABLEMSGQUEUE_NO_ERROR == mJobPool.Receive( job ) )
{
if( NULL == job.second.mImage || TestDestroy() )
break;
const wxRect& rect = job.first;
ScaledImageFactory::Context& ctx = job.second;
ScaledImageFactory::ResultItem result;
result.mGeneration = ctx.mGeneration;
result.mRect = rect;
result.mImage = new wxImage( rect.GetWidth(), rect.GetHeight(), false );
if( ctx.mImage->HasAlpha() )
{
result.mImage->SetAlpha( NULL );
}
GetScaledSubrect
(
*result.mImage,
*ctx.mImage,
ctx.mScale,
rect.GetPosition()
);
mResultQueue.Post( result );
wxQueueEvent( mEventSink, new wxThreadEvent( wxEVT_THREAD, mEventId ) );
}
return static_cast< wxThread::ExitCode >( 0 );
}
private:
wxEvtHandler* mEventSink;
int mEventId;
ScaledImageFactory::JobPoolType& mJobPool;
ScaledImageFactory::ResultQueueType& mResultQueue;
};
ScaledImageFactory::ScaledImageFactory( wxEvtHandler* eventSink, int id )
{
size_t numThreads = wxThread::GetCPUCount();
if( numThreads <= 0 ) numThreads = 1;
if( numThreads > 1 ) numThreads--;
for( size_t i = 0; i < numThreads; ++i )
{
mThreads.push_back( new WorkerThread( eventSink, id, mJobPool, mResultQueue ) );
}
for( wxThread*& thread : mThreads )
{
if( NULL == thread )
continue;
if( thread->Run() != wxTHREAD_NO_ERROR )
{
delete thread;
thread = NULL;
}
}
mCurrentCtx.mGeneration = 0;
}
ScaledImageFactory::~ScaledImageFactory()
{
// clear job queue and send down "kill" jobs
mJobPool.Clear();
for( size_t i = 0; i < mThreads.size(); ++i )
{
mJobPool.Post( JobItem( wxRect(), Context() ) );
}
for( wxThread* thread : mThreads )
{
if( NULL == thread )
continue;
thread->Wait();
delete thread;
}
}
void ScaledImageFactory::SetImage( wxImagePtr& newImage, double newScale )
{
if( NULL == newImage )
throw std::runtime_error( "Image not set!" );
mCurrentCtx.mGeneration++;
mCurrentCtx.mImage = newImage;
mCurrentCtx.mScale = newScale;
mJobPool.Clear();
}
bool ScaledImageFactory::AddRect( const wxRect& rect )
{
if( NULL == mCurrentCtx.mImage )
throw std::runtime_error( "Image not set!" );
return( wxSORTABLEMSGQUEUE_NO_ERROR == mJobPool.Post( JobItem( rect, mCurrentCtx ) ) );
}
bool ScaledImageFactory::GetImage( wxRect& rect, wxImagePtr& image )
{
ResultItem item;
wxMessageQueueError err;
while( true )
{
err = mResultQueue.ReceiveTimeout( 0, item );
if( wxMSGQUEUE_TIMEOUT == err )
return false;
if( wxMSGQUEUE_MISC_ERROR == err )
throw std::runtime_error( "ResultQueue misc error!" );
if( item.mGeneration != mCurrentCtx.mGeneration )
continue;
break;
}
rect = item.mRect;
image = item.mImage;
return true;
}
void ScaledImageFactory::ClearQueue()
{
mJobPool.Clear();
}
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.