text
stringlengths 54
60.6k
|
|---|
<commit_before>8366d394-2e4d-11e5-9284-b827eb9e62be<commit_msg>836c1d0e-2e4d-11e5-9284-b827eb9e62be<commit_after>836c1d0e-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>ea3f139c-2e4d-11e5-9284-b827eb9e62be<commit_msg>ea441522-2e4d-11e5-9284-b827eb9e62be<commit_after>ea441522-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>ce454d2e-2e4c-11e5-9284-b827eb9e62be<commit_msg>ce4a4c48-2e4c-11e5-9284-b827eb9e62be<commit_after>ce4a4c48-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>4c5589fe-2e4d-11e5-9284-b827eb9e62be<commit_msg>4c5a9b06-2e4d-11e5-9284-b827eb9e62be<commit_after>4c5a9b06-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>5633c6c4-2e4e-11e5-9284-b827eb9e62be<commit_msg>563987bc-2e4e-11e5-9284-b827eb9e62be<commit_after>563987bc-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>435cd19e-2e4e-11e5-9284-b827eb9e62be<commit_msg>4361d6c6-2e4e-11e5-9284-b827eb9e62be<commit_after>4361d6c6-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>d98b2842-2e4d-11e5-9284-b827eb9e62be<commit_msg>d9902504-2e4d-11e5-9284-b827eb9e62be<commit_after>d9902504-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>a9e9593c-2e4e-11e5-9284-b827eb9e62be<commit_msg>a9ee5c20-2e4e-11e5-9284-b827eb9e62be<commit_after>a9ee5c20-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>ebb6ff32-2e4d-11e5-9284-b827eb9e62be<commit_msg>ebbbf62c-2e4d-11e5-9284-b827eb9e62be<commit_after>ebbbf62c-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>774d5128-2e4d-11e5-9284-b827eb9e62be<commit_msg>7752453e-2e4d-11e5-9284-b827eb9e62be<commit_after>7752453e-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>#pragma once
/*
** Copyright (C) 2012 Aldebaran Robotics
** See COPYING for the license
*/
#ifndef _QI_EXECUTION_CONTEXT_HPP_
#define _QI_EXECUTION_CONTEXT_HPP_
#include <boost/function.hpp>
#include <qi/clock.hpp>
#include <qi/api.hpp>
namespace qi
{
template <typename T>
class Future;
class QI_API ExecutionContext
{
public:
virtual ~ExecutionContext() {}
// DEPRECATED STUFF
/// post a callback to be executed as soon as possible
QI_API_DEPRECATED virtual void post(const boost::function<void()>& callback) = 0;
/// call a callback asynchronously to be executed on tp
QI_API_DEPRECATED virtual qi::Future<void> async(const boost::function<void()>& callback,
qi::SteadyClockTimePoint tp) = 0;
/// call a callback asynchronously to be executed in delay
QI_API_DEPRECATED virtual qi::Future<void> async(const boost::function<void()>& callback,
qi::Duration delay = qi::Duration(0)) = 0;
/// call a callback asynchronously to be executed in delay
template <typename R>
QI_API_DEPRECATED typename boost::disable_if<boost::is_same<R, void>,
qi::Future<R> >::type
async(const boost::function<R()>& callback,
qi::Duration delay = qi::Duration(0));
/// call a callback asynchronously to be executed on tp
template <typename R>
QI_API_DEPRECATED typename boost::disable_if<boost::is_same<R, void>,
qi::Future<R> >::type
async(const boost::function<R()>& callback, qi::SteadyClockTimePoint tp);
// END OF DEPRECATED STUFF
/// post a callback to be executed as soon as possible
template <typename F>
void post2(F&& callback);
/// call a callback asynchronously to be executed on tp
template <typename F>
auto asyncAt(F&& callback, qi::SteadyClockTimePoint tp) -> qi::Future<decltype(callback())>;
/// call a callback asynchronously to be executed in delay
template <typename F>
auto asyncDelay(F&& callback, qi::Duration delay) -> qi::Future<decltype(callback())>;
template <typename F>
auto async2(F&& callback) -> qi::Future<decltype(callback())>
{
return asyncDelay(std::forward<F>(callback), qi::Duration(0));
}
/// return true if the current thread is in this context
virtual bool isInThisContext() = 0;
protected:
virtual void postImpl(boost::function<void()> callback) = 0;
virtual qi::Future<void> asyncAtImpl(boost::function<void()> cb, qi::SteadyClockTimePoint tp) = 0;
virtual qi::Future<void> asyncDelayImpl(boost::function<void()> cb, qi::Duration delay) = 0;
};
}
#include <qi/detail/future_fwd.hpp>
namespace qi
{
namespace detail
{
template <typename T>
class DelayedPromise: public Promise<T>
{
public:
void setup(boost::function<void (qi::Promise<T>)> cancelCallback, FutureCallbackType async = FutureCallbackType_Async)
{
Promise<T>::setup(cancelCallback, async);
}
};
template <typename R>
void setValue(qi::Promise<R>& p, const boost::function<R()>& f)
{
p.setValue(f());
}
template <>
inline void setValue<void>(qi::Promise<void>& p, const boost::function<void()>& f)
{
f();
p.setValue(0);
}
template <typename R>
void callAndSet(qi::Promise<R> p, boost::function<R()> f)
{
try
{
setValue<R>(p, f);
}
catch (const std::exception& e)
{
p.setError(e.what());
}
catch(...)
{
p.setError("unknown exception");
}
}
template <typename R>
void checkCanceled(qi::Future<void> f, qi::Promise<R> p)
{
if (f.wait() == FutureState_Canceled)
p.setCanceled();
// Nothing to do for other states.
}
}
template <typename R>
typename boost::disable_if<boost::is_same<R, void>,
qi::Future<R> >::type
ExecutionContext::async(const boost::function<R()>& callback,
qi::Duration delay)
{
detail::DelayedPromise<R> promise;
qi::Future<void> f = async(boost::function<void()>(boost::bind(
detail::callAndSet<R>, promise, callback)),
delay);
promise.setup(
boost::bind(&detail::futureCancelAdapter<void>,
boost::weak_ptr<detail::FutureBaseTyped<void> >(f.impl())),
FutureCallbackType_Sync);
f.connect(boost::bind(&detail::checkCanceled<R>, _1, promise));
return promise.future();
}
template <typename R>
typename boost::disable_if<boost::is_same<R, void>,
qi::Future<R> >::type
ExecutionContext::async(const boost::function<R()>& callback,
qi::SteadyClockTimePoint tp)
{
detail::DelayedPromise<R> promise;
qi::Future<void> f = async(boost::function<void()>(boost::bind(
detail::callAndSet<R>, promise, callback)),
tp);
promise.setup(
boost::bind(&detail::futureCancelAdapter<void>,
boost::weak_ptr<detail::FutureBaseTyped<void> >(f.impl())),
FutureCallbackType_Sync);
f.connect(boost::bind(&detail::checkCanceled<R>, _1, promise));
return promise.future();
}
template <typename F>
void ExecutionContext::post2(F&& callback)
{
postImpl(std::forward<F>(callback));
}
template <typename ReturnType, typename Callback>
struct ToPost
{
detail::DelayedPromise<ReturnType> promise;
Callback callback;
ToPost(Callback&& cb) :
callback(cb)
{}
ToPost(const Callback& cb) :
callback(cb)
{}
void operator()()
{
detail::callAndSet<ReturnType>(std::move(promise), std::move(callback));
}
};
template <typename F>
auto ExecutionContext::asyncAt(F&& callback, qi::SteadyClockTimePoint tp) -> qi::Future<decltype(callback())>
{
using ReturnType = decltype(callback());
ToPost<ReturnType, typename std::decay<F>::type> topost(std::move(callback));
auto promise = topost.promise;
qi::Future<void> f = asyncAtImpl(std::move(topost), tp);
promise.setup(boost::bind(&detail::futureCancelAdapter<void>,
boost::weak_ptr<detail::FutureBaseTyped<void> >(f.impl())),
FutureCallbackType_Sync);
f.connect(boost::bind(&detail::checkCanceled<ReturnType>, _1, promise));
return promise.future();
}
template <typename F>
auto ExecutionContext::asyncDelay(F&& callback, qi::Duration delay) -> qi::Future<decltype(callback())>
{
using ReturnType = decltype(callback());
ToPost<ReturnType, typename std::decay<F>::type> topost(std::move(callback));
auto promise = topost.promise;
qi::Future<void> f = asyncDelayImpl(std::move(topost), delay);
promise.setup(boost::bind(&detail::futureCancelAdapter<void>,
boost::weak_ptr<detail::FutureBaseTyped<void> >(f.impl())),
FutureCallbackType_Sync);
f.connect(boost::bind(&detail::checkCanceled<ReturnType>, _1, promise));
return promise.future();
}
}
#endif
<commit_msg>ExecutionContext: fix syncness of futures/promises<commit_after>#pragma once
/*
** Copyright (C) 2012 Aldebaran Robotics
** See COPYING for the license
*/
#ifndef _QI_EXECUTION_CONTEXT_HPP_
#define _QI_EXECUTION_CONTEXT_HPP_
#include <boost/function.hpp>
#include <qi/clock.hpp>
#include <qi/api.hpp>
namespace qi
{
template <typename T>
class Future;
class QI_API ExecutionContext
{
public:
virtual ~ExecutionContext() {}
// DEPRECATED STUFF
/// post a callback to be executed as soon as possible
QI_API_DEPRECATED virtual void post(const boost::function<void()>& callback) = 0;
/// call a callback asynchronously to be executed on tp
QI_API_DEPRECATED virtual qi::Future<void> async(const boost::function<void()>& callback,
qi::SteadyClockTimePoint tp) = 0;
/// call a callback asynchronously to be executed in delay
QI_API_DEPRECATED virtual qi::Future<void> async(const boost::function<void()>& callback,
qi::Duration delay = qi::Duration(0)) = 0;
/// call a callback asynchronously to be executed in delay
template <typename R>
QI_API_DEPRECATED typename boost::disable_if<boost::is_same<R, void>,
qi::Future<R> >::type
async(const boost::function<R()>& callback,
qi::Duration delay = qi::Duration(0));
/// call a callback asynchronously to be executed on tp
template <typename R>
QI_API_DEPRECATED typename boost::disable_if<boost::is_same<R, void>,
qi::Future<R> >::type
async(const boost::function<R()>& callback, qi::SteadyClockTimePoint tp);
// END OF DEPRECATED STUFF
/// post a callback to be executed as soon as possible
template <typename F>
void post2(F&& callback);
/// call a callback asynchronously to be executed on tp
template <typename F>
auto asyncAt(F&& callback, qi::SteadyClockTimePoint tp) -> qi::Future<decltype(callback())>;
/// call a callback asynchronously to be executed in delay
template <typename F>
auto asyncDelay(F&& callback, qi::Duration delay) -> qi::Future<decltype(callback())>;
template <typename F>
auto async2(F&& callback) -> qi::Future<decltype(callback())>
{
return asyncDelay(std::forward<F>(callback), qi::Duration(0));
}
/// return true if the current thread is in this context
virtual bool isInThisContext() = 0;
protected:
virtual void postImpl(boost::function<void()> callback) = 0;
virtual qi::Future<void> asyncAtImpl(boost::function<void()> cb, qi::SteadyClockTimePoint tp) = 0;
virtual qi::Future<void> asyncDelayImpl(boost::function<void()> cb, qi::Duration delay) = 0;
};
}
#include <qi/detail/future_fwd.hpp>
namespace qi
{
namespace detail
{
template <typename T>
class DelayedPromise: public Promise<T>
{
public:
void setup(boost::function<void (qi::Promise<T>)> cancelCallback, FutureCallbackType async = FutureCallbackType_Async)
{
Promise<T>::setup(cancelCallback, async);
}
};
template <typename R>
void setValue(qi::Promise<R>& p, const boost::function<R()>& f)
{
p.setValue(f());
}
template <>
inline void setValue<void>(qi::Promise<void>& p, const boost::function<void()>& f)
{
f();
p.setValue(0);
}
template <typename R>
void callAndSet(qi::Promise<R> p, boost::function<R()> f)
{
try
{
setValue<R>(p, f);
}
catch (const std::exception& e)
{
p.setError(e.what());
}
catch(...)
{
p.setError("unknown exception");
}
}
template <typename R>
void checkCanceled(qi::Future<void> f, qi::Promise<R> p)
{
if (f.wait() == FutureState_Canceled)
p.setCanceled();
// Nothing to do for other states.
}
}
template <typename R>
typename boost::disable_if<boost::is_same<R, void>,
qi::Future<R> >::type
ExecutionContext::async(const boost::function<R()>& callback,
qi::Duration delay)
{
detail::DelayedPromise<R> promise;
qi::Future<void> f = async(boost::function<void()>(boost::bind(
detail::callAndSet<R>, promise, callback)),
delay);
promise.setup(
boost::bind(&detail::futureCancelAdapter<void>,
boost::weak_ptr<detail::FutureBaseTyped<void> >(f.impl())));
f.connect(boost::bind(&detail::checkCanceled<R>, _1, promise), FutureCallbackType_Sync);
return promise.future();
}
template <typename R>
typename boost::disable_if<boost::is_same<R, void>,
qi::Future<R> >::type
ExecutionContext::async(const boost::function<R()>& callback,
qi::SteadyClockTimePoint tp)
{
detail::DelayedPromise<R> promise;
qi::Future<void> f = async(boost::function<void()>(boost::bind(
detail::callAndSet<R>, promise, callback)),
tp);
promise.setup(
boost::bind(&detail::futureCancelAdapter<void>,
boost::weak_ptr<detail::FutureBaseTyped<void> >(f.impl())));
f.connect(boost::bind(&detail::checkCanceled<R>, _1, promise), FutureCallbackType_Sync);
return promise.future();
}
template <typename F>
void ExecutionContext::post2(F&& callback)
{
postImpl(std::forward<F>(callback));
}
template <typename ReturnType, typename Callback>
struct ToPost
{
detail::DelayedPromise<ReturnType> promise;
Callback callback;
ToPost(Callback&& cb) :
callback(cb)
{}
ToPost(const Callback& cb) :
callback(cb)
{}
void operator()()
{
detail::callAndSet<ReturnType>(std::move(promise), std::move(callback));
}
};
template <typename F>
auto ExecutionContext::asyncAt(F&& callback, qi::SteadyClockTimePoint tp) -> qi::Future<decltype(callback())>
{
using ReturnType = decltype(callback());
ToPost<ReturnType, typename std::decay<F>::type> topost(std::move(callback));
auto promise = topost.promise;
qi::Future<void> f = asyncAtImpl(std::move(topost), tp);
promise.setup(boost::bind(&detail::futureCancelAdapter<void>,
boost::weak_ptr<detail::FutureBaseTyped<void> >(f.impl())));
f.connect(boost::bind(&detail::checkCanceled<ReturnType>, _1, promise), FutureCallbackType_Sync);
return promise.future();
}
template <typename F>
auto ExecutionContext::asyncDelay(F&& callback, qi::Duration delay) -> qi::Future<decltype(callback())>
{
using ReturnType = decltype(callback());
ToPost<ReturnType, typename std::decay<F>::type> topost(std::move(callback));
auto promise = topost.promise;
qi::Future<void> f = asyncDelayImpl(std::move(topost), delay);
promise.setup(boost::bind(&detail::futureCancelAdapter<void>,
boost::weak_ptr<detail::FutureBaseTyped<void> >(f.impl())));
f.connect(boost::bind(&detail::checkCanceled<ReturnType>, _1, promise), FutureCallbackType_Sync);
return promise.future();
}
}
#endif
<|endoftext|>
|
<commit_before>ba65d228-2e4d-11e5-9284-b827eb9e62be<commit_msg>ba6ac670-2e4d-11e5-9284-b827eb9e62be<commit_after>ba6ac670-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>ea2d681c-2e4e-11e5-9284-b827eb9e62be<commit_msg>ea32a728-2e4e-11e5-9284-b827eb9e62be<commit_after>ea32a728-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>da02ece8-2e4c-11e5-9284-b827eb9e62be<commit_msg>da08093a-2e4c-11e5-9284-b827eb9e62be<commit_after>da08093a-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>d6eb4e06-2e4c-11e5-9284-b827eb9e62be<commit_msg>d6f05d92-2e4c-11e5-9284-b827eb9e62be<commit_after>d6f05d92-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>af89bfd6-2e4d-11e5-9284-b827eb9e62be<commit_msg>af8eb5f4-2e4d-11e5-9284-b827eb9e62be<commit_after>af8eb5f4-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>fd1dd2cc-2e4e-11e5-9284-b827eb9e62be<commit_msg>fd22d07e-2e4e-11e5-9284-b827eb9e62be<commit_after>fd22d07e-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>d607d8ea-2e4e-11e5-9284-b827eb9e62be<commit_msg>d60cd5c0-2e4e-11e5-9284-b827eb9e62be<commit_after>d60cd5c0-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>5b075680-2e4d-11e5-9284-b827eb9e62be<commit_msg>5b0c64ae-2e4d-11e5-9284-b827eb9e62be<commit_after>5b0c64ae-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>da056b24-2e4e-11e5-9284-b827eb9e62be<commit_msg>da0a6bb0-2e4e-11e5-9284-b827eb9e62be<commit_after>da0a6bb0-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>939a56e6-2e4d-11e5-9284-b827eb9e62be<commit_msg>939f5ba0-2e4d-11e5-9284-b827eb9e62be<commit_after>939f5ba0-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>097361cc-2e4f-11e5-9284-b827eb9e62be<commit_msg>09789566-2e4f-11e5-9284-b827eb9e62be<commit_after>09789566-2e4f-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>cd64d9dc-2e4d-11e5-9284-b827eb9e62be<commit_msg>cd69cf32-2e4d-11e5-9284-b827eb9e62be<commit_after>cd69cf32-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>e47404ee-2e4e-11e5-9284-b827eb9e62be<commit_msg>e479168c-2e4e-11e5-9284-b827eb9e62be<commit_after>e479168c-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>7002cef6-2e4e-11e5-9284-b827eb9e62be<commit_msg>7008167c-2e4e-11e5-9284-b827eb9e62be<commit_after>7008167c-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>cf172fd2-2e4d-11e5-9284-b827eb9e62be<commit_msg>cf1c27bc-2e4d-11e5-9284-b827eb9e62be<commit_after>cf1c27bc-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>09c51472-2e4f-11e5-9284-b827eb9e62be<commit_msg>09ca2688-2e4f-11e5-9284-b827eb9e62be<commit_after>09ca2688-2e4f-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>21568dde-2e4d-11e5-9284-b827eb9e62be<commit_msg>215b92de-2e4d-11e5-9284-b827eb9e62be<commit_after>215b92de-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>a6bac3aa-2e4d-11e5-9284-b827eb9e62be<commit_msg>a6bfbee6-2e4d-11e5-9284-b827eb9e62be<commit_after>a6bfbee6-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>#include "deviceinfo.h"
DeviceInfo::DeviceInfo(Device *device)
: SysExMessage(SysExMessage::GET_DEVICE_INFO, SysExMessage::QUERY, device) {
}
BYTE_VECTOR *DeviceInfo::getMessageData() {
BYTE_VECTOR *messageData = new BYTE_VECTOR();
messageData->push_back(this->infoItem);
return messageData;
}
std::string DeviceInfo::getDataAsString() {
std::string result(data->begin() + 1, data->end());
return result;
}
DeviceInfo::DeviceInfoItem DeviceInfo::getDeviceInfoItem() {
return (DeviceInfoItem)(*data)[0];
}
<commit_msg>when returning data as string return an empty string if there are no data<commit_after>#include "deviceinfo.h"
DeviceInfo::DeviceInfo(Device *device)
: SysExMessage(SysExMessage::GET_DEVICE_INFO, SysExMessage::QUERY, device) {
}
BYTE_VECTOR *DeviceInfo::getMessageData() {
BYTE_VECTOR *messageData = new BYTE_VECTOR();
messageData->push_back(this->infoItem);
return messageData;
}
std::string DeviceInfo::getDataAsString() {
if (data->size() > 0) {
std::string result(data->begin() + 1, data->end());
return result;
} else {
return std::string();
}
}
DeviceInfo::DeviceInfoItem DeviceInfo::getDeviceInfoItem() {
return (DeviceInfoItem)(*data)[0];
}
<|endoftext|>
|
<commit_before>2824b7b0-2e4f-11e5-9284-b827eb9e62be<commit_msg>2829afa4-2e4f-11e5-9284-b827eb9e62be<commit_after>2829afa4-2e4f-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>2f62625e-2e4d-11e5-9284-b827eb9e62be<commit_msg>2f6759f8-2e4d-11e5-9284-b827eb9e62be<commit_after>2f6759f8-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>f37bfad4-2e4c-11e5-9284-b827eb9e62be<commit_msg>f38156be-2e4c-11e5-9284-b827eb9e62be<commit_after>f38156be-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>8939023c-2e4e-11e5-9284-b827eb9e62be<commit_msg>893e0b4c-2e4e-11e5-9284-b827eb9e62be<commit_after>893e0b4c-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>b6e1c43c-2e4c-11e5-9284-b827eb9e62be<commit_msg>b6e6d0c6-2e4c-11e5-9284-b827eb9e62be<commit_after>b6e6d0c6-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>5200784a-2e4e-11e5-9284-b827eb9e62be<commit_msg>5206dba4-2e4e-11e5-9284-b827eb9e62be<commit_after>5206dba4-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>c400cd0c-2e4c-11e5-9284-b827eb9e62be<commit_msg>c405beb6-2e4c-11e5-9284-b827eb9e62be<commit_after>c405beb6-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>5f0af7fe-2e4e-11e5-9284-b827eb9e62be<commit_msg>5f0ff59c-2e4e-11e5-9284-b827eb9e62be<commit_after>5f0ff59c-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>4c541dac-2e4e-11e5-9284-b827eb9e62be<commit_msg>4c593530-2e4e-11e5-9284-b827eb9e62be<commit_after>4c593530-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>68877aaa-2e4e-11e5-9284-b827eb9e62be<commit_msg>688c760e-2e4e-11e5-9284-b827eb9e62be<commit_after>688c760e-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>6cbd0e46-2e4e-11e5-9284-b827eb9e62be<commit_msg>6cc213e6-2e4e-11e5-9284-b827eb9e62be<commit_after>6cc213e6-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>98bedb60-2e4d-11e5-9284-b827eb9e62be<commit_msg>98c3cce2-2e4d-11e5-9284-b827eb9e62be<commit_after>98c3cce2-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>c1ef2bda-2e4c-11e5-9284-b827eb9e62be<commit_msg>c1f41f46-2e4c-11e5-9284-b827eb9e62be<commit_after>c1f41f46-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>3b3c1de4-2e4e-11e5-9284-b827eb9e62be<commit_msg>3b503446-2e4e-11e5-9284-b827eb9e62be<commit_after>3b503446-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>50acc11a-2e4e-11e5-9284-b827eb9e62be<commit_msg>50b1f3ba-2e4e-11e5-9284-b827eb9e62be<commit_after>50b1f3ba-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>9abdac6a-2e4e-11e5-9284-b827eb9e62be<commit_msg>9ac2d51e-2e4e-11e5-9284-b827eb9e62be<commit_after>9ac2d51e-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>7260d8e6-2e4e-11e5-9284-b827eb9e62be<commit_msg>7265fc40-2e4e-11e5-9284-b827eb9e62be<commit_after>7265fc40-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>aac03b46-2e4e-11e5-9284-b827eb9e62be<commit_msg>aac53268-2e4e-11e5-9284-b827eb9e62be<commit_after>aac53268-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>ca75ed1a-2e4d-11e5-9284-b827eb9e62be<commit_msg>ca7adad2-2e4d-11e5-9284-b827eb9e62be<commit_after>ca7adad2-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>28f7bfe0-2e4d-11e5-9284-b827eb9e62be<commit_msg>28fd1602-2e4d-11e5-9284-b827eb9e62be<commit_after>28fd1602-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>3b94757e-2e4f-11e5-9284-b827eb9e62be<commit_msg>3b99739e-2e4f-11e5-9284-b827eb9e62be<commit_after>3b99739e-2e4f-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>1abe8882-2e4d-11e5-9284-b827eb9e62be<commit_msg>1ac397be-2e4d-11e5-9284-b827eb9e62be<commit_after>1ac397be-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>65c024a2-2e4e-11e5-9284-b827eb9e62be<commit_msg>65c52ede-2e4e-11e5-9284-b827eb9e62be<commit_after>65c52ede-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>81d3c946-2e4e-11e5-9284-b827eb9e62be<commit_msg>81d8d7e2-2e4e-11e5-9284-b827eb9e62be<commit_after>81d8d7e2-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>82908e4c-2e4d-11e5-9284-b827eb9e62be<commit_msg>829593ba-2e4d-11e5-9284-b827eb9e62be<commit_after>829593ba-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>f1a29a6a-2e4c-11e5-9284-b827eb9e62be<commit_msg>f1a8539c-2e4c-11e5-9284-b827eb9e62be<commit_after>f1a8539c-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>3f1a1818-2e4d-11e5-9284-b827eb9e62be<commit_msg>3f1f1890-2e4d-11e5-9284-b827eb9e62be<commit_after>3f1f1890-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>c5ccc3a0-2e4e-11e5-9284-b827eb9e62be<commit_msg>c5d1d728-2e4e-11e5-9284-b827eb9e62be<commit_after>c5d1d728-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>f2962a02-2e4e-11e5-9284-b827eb9e62be<commit_msg>f2a9f67c-2e4e-11e5-9284-b827eb9e62be<commit_after>f2a9f67c-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>78facc62-2e4d-11e5-9284-b827eb9e62be<commit_msg>78ffc5aa-2e4d-11e5-9284-b827eb9e62be<commit_after>78ffc5aa-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>612a75fa-2e4e-11e5-9284-b827eb9e62be<commit_msg>612f809a-2e4e-11e5-9284-b827eb9e62be<commit_after>612f809a-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>2532cda0-2e4d-11e5-9284-b827eb9e62be<commit_msg>2537c738-2e4d-11e5-9284-b827eb9e62be<commit_after>2537c738-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>bae15b72-2e4e-11e5-9284-b827eb9e62be<commit_msg>bae66cac-2e4e-11e5-9284-b827eb9e62be<commit_after>bae66cac-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>82f3da96-2e4e-11e5-9284-b827eb9e62be<commit_msg>82f8f328-2e4e-11e5-9284-b827eb9e62be<commit_after>82f8f328-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>e9726404-2e4e-11e5-9284-b827eb9e62be<commit_msg>e97794d8-2e4e-11e5-9284-b827eb9e62be<commit_after>e97794d8-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>d577c23e-2e4c-11e5-9284-b827eb9e62be<commit_msg>d57d195a-2e4c-11e5-9284-b827eb9e62be<commit_after>d57d195a-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>39456658-2e4e-11e5-9284-b827eb9e62be<commit_msg>394a5a28-2e4e-11e5-9284-b827eb9e62be<commit_after>394a5a28-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>56a6a37a-2e4d-11e5-9284-b827eb9e62be<commit_msg>56aba4d8-2e4d-11e5-9284-b827eb9e62be<commit_after>56aba4d8-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>#include "../common/init.h"
#include "../common/timer.h"
#include <iostream>
#include <vector>
#include <stdexcept>
#include "util/graphics/bitmap.h"
#include "util/font.h"
#include "util/debug.h"
#include "util/exceptions/load_exception.h"
#include "util/token_exception.h"
#include "util/input/input.h"
#include "util/input/input-manager.h"
#include "util/sound/sound.h"
#include "util/exceptions/exception.h"
#include "util/network/network.h"
#include "util/network/irc.h"
#include "util/thread.h"
#include "util/pointer.h"
#include "util/system.h"
#include "util/timedifference.h"
#include "util/configuration.h"
#include <queue>
#include <map>
static std::vector<std::string> split(std::string str, char splitter){
std::vector<std::string> strings;
size_t next = str.find(splitter);
while (next != std::string::npos){
strings.push_back(str.substr(0, next));
str = str.substr(next+1);
next = str.find(splitter);
}
if (str != ""){
strings.push_back(str);
}
return strings;
}
static void setTrue(void * b){
bool * what = (bool*) b;
*what = true;
}
static void nextTab(void * i){
::Network::IRC::ChatInterface * interface = (::Network::IRC::ChatInterface *)i;
interface->nextChannel();
}
static void previousTab(void * i){
::Network::IRC::ChatInterface * interface = (::Network::IRC::ChatInterface *)i;
interface->previousChannel();
}
class Game{
public:
Game(const std::string & name, bool host = true):
name(name),
host(host){
}
~Game(){
}
void addClient(const std::string & name, const std::string & ip){
clients[name] = ip;
}
std::string clientsAsString(){
std::string clientlist;
for (std::map<std::string, std::string>::iterator i = clients.begin(); i != clients.end(); i++){
clientlist += (*i).first + ", ";
}
return clientlist.substr(0, clientlist.size() - 2);
}
void start(const std::string & hostip) {
Global::debug(0) << "Game " << name << " is starting." << std::endl;
Global::debug(0) << "Connecting to " << hostip << "...." << std::endl;
}
std::map<std::string, std::string> & getClients(){
return clients;
}
const std::string & getName() const {
return name;
}
bool isHost() const {
return host;
}
private:
std::string name;
bool host;
std::map<std::string, std::string> clients;
};
class InputLogicDraw: public Util::Logic, public Util::Draw, public ::Network::IRC::Message::EventInterface {
public:
InputLogicDraw(int port, const std::string & host, const std::string & username):
chatInterface(host, port, username),
escaped(false){
ircClient = Util::ReferenceCount< ::Network::IRC::Client >(new ::Network::IRC::Client(host, port));
chatInterface.getInputBox().addHook(Keyboard::Key_ESC, setTrue, &escaped);
chatInterface.getInputBox().addHook(Keyboard::Key_TAB, nextTab, &chatInterface);
chatInterface.subscribe(this);
// Get IP
chatInterface.getClient()->sendCommand(::Network::IRC::Command::Userhost, chatInterface.getClient()->getName());
}
::Network::IRC::ChatInterface chatInterface;
Util::ReferenceCount< ::Network::IRC::Client > ircClient;
bool escaped;
std::string ipAddress;
Util::ReferenceCount<Game> game;
std::map<std::string, std::string> hosts;
void remoteCommand(const ::Network::IRC::Command & command){
if (command.getType() == ::Network::IRC::Command::ReplyUserhost){
const std::vector<std::string> & params = command.getParameters();
const std::string & extract = params.at(1);
for (unsigned int i = 0; i < extract.size(); i++){
if (extract[i] == '@'){
ipAddress = extract.substr(++i, extract.size()-1);
Global::debug(0) << "Your IP Address is: " << ipAddress << std::endl;
}
}
}
if (command.hasCtcp()){
const std::vector<std::string> & ctcp = command.getCtcp();
if (command.getType() == ::Network::IRC::Command::PrivateMessage){
try {
if (ctcp.at(0) == "game"){
const std::string & gameCommand = ctcp.at(1);
if (gameCommand == "invite"){
const std::string & gameName = ctcp.at(2);
const std::string & hostName = ctcp.at(3);
chatInterface.addMessageToTab("* " + hostName + " has invited you to join the game [" + gameName + "]. Type \"/game join " + gameName + "\".");
hosts[gameName] = hostName;
} else if (gameCommand == "join"){
if (game != NULL && game->isHost()){
const std::string & gameName = ctcp.at(2);
const std::string & clientName = ctcp.at(3);
const std::string & ip = ctcp.at(4);
chatInterface.addMessageToTab("* " + clientName + " has joined " + gameName + ".");
game->addClient(clientName, ip);
} else {
chatInterface.addMessageToTab("* received a join request with no game pending.");
}
} else if (gameCommand == "start"){
if (game != NULL && !game->isHost()){
const std::string & gameName = ctcp.at(2);
const std::string & serverIp = ctcp.at(3);
chatInterface.addMessageToTab("* Host has started game " + gameName);
game->start(serverIp);
}
}
} else {
Global::debug(0) << "Got ctcp: " << ctcp.at(0) << std::endl;
}
} catch (const std::out_of_range & ex){
}
}
}
}
void localCommand(const std::vector<std::string> & command){
if (command.at(0) == "help"){
chatInterface.addMessageToTab("* commands: lol, game");
} else if (command.at(0) == "lol"){
chatInterface.addMessageToTab("* You LOLOLOLOLLOLOLOL yourself.");
} else if (command.at(0) == "game"){
// Game
if (command.size() > 1){
if (command.at(1) == "help"){
chatInterface.addMessageToTab("* game commands: help, new, start, list-users, list-hosts, invite, join.");
} else if (command.at(1) == "new"){
try{
game = Util::ReferenceCount<Game>(new Game(command.at(2)));
chatInterface.addMessageToTab("* game \"" + command.at(2) + "\" created.");
} catch (const std::out_of_range & ex){
chatInterface.addMessageToTab("* /game new [name]");
}
} else if (command.at(1) == "start"){
if (game != NULL && game->isHost()){
chatInterface.addMessageToTab("* Starting game " + game->getName());
for (std::map<std::string, std::string>::iterator i = game->getClients().begin(); i != game->getClients().end(); i++){
chatInterface.getClient()->sendCommand(::Network::IRC::Command::PrivateMessage,
(*i).first,
":\001game start " + game->getName() + " " + ipAddress + "\001");
}
} else {
chatInterface.addMessageToTab("* Create a game first...");
}
} else if (command.at(1) == "list-users"){
if (game != NULL){
chatInterface.addMessageToTab("* Users who accepted game request: " + game->clientsAsString());
} else {
chatInterface.addMessageToTab("* Create a game first...");
}
} else if (command.at(1) == "list-hosts"){
if (!hosts.empty()){
std::string hostlist;
for (std::map<std::string, std::string>::iterator i = hosts.begin(); i != hosts.end(); i++){
hostlist += (*i).first + +" [" + (*i).second + "], ";
}
chatInterface.addMessageToTab("* Hosts and games you've been invited to: " + hostlist.substr(0, hostlist.size() - 2));
} else {
chatInterface.addMessageToTab("* You have no invites.");
}
} else if (command.at(1) == "invite"){
if (game != NULL){
try {
chatInterface.addMessageToTab("* Sending request to " + command.at(2));
chatInterface.getClient()->sendCommand(::Network::IRC::Command::PrivateMessage,
command.at(2),
":\001game invite " + game->getName() + " " + chatInterface.getClient()->getName() + "\001");
} catch (const std::out_of_range & ex){
chatInterface.addMessageToTab("* /game invite [username]");
}
} else {
chatInterface.addMessageToTab("* Create a game first...");
}
} else if (command.at(1) == "join"){
if (!hosts.empty()){
try {
const std::string & gameName = command.at(2);
const std::string & hostName = hosts[gameName];
chatInterface.addMessageToTab("* Joining game at " + gameName);
chatInterface.getClient()->sendCommand(::Network::IRC::Command::PrivateMessage,
hostName,
":\001game join " + gameName + " " + chatInterface.getClient()->getName() + " " + ipAddress + "\001");
game = Util::ReferenceCount<Game>(new Game(gameName, false));
} catch (const std::out_of_range & ex){
chatInterface.addMessageToTab("* /game join [name]");
}
} else {
chatInterface.addMessageToTab("* You must be invited to a game first...");
}
}
}
} else {
//chatInterface.addMessageToTab("* Uknown command.");
}
}
double ticks(double system){
return system;
}
void run(){
try {
chatInterface.act();
} catch (const Exception::Return & ex){
escaped = true;
throw ex;
}
}
bool done(){
return escaped;
}
void draw(const Graphics::Bitmap & screen){
chatInterface.draw(screen);
}
};
static void doIrc(const std::string & host, int port, const std::string & username){
InputLogicDraw client(port, host, username);
Util::standardLoop(client, client);
}
static void arguments(const std::string & application, int status){
std::cout << "Usage: ./" << application << " port host [username]" << std::endl;
exit(status);
}
int main(int argc, char ** argv){
if (argc >= 2){
int port = atoi(argv[1]);
std::string hostname = argv[2];
std::string username = "paintown-test";
if (argc > 3){
username = argv[3];
}
Screen::realInit(Configuration::getScreenWidth(), Configuration::getScreenHeight());
atexit(Screen::realFinish);
Common::startTimers();
Sound::initialize();
Global::setDebug(2);
Util::Parameter<Graphics::Bitmap*> use(Graphics::screenParameter, Graphics::getScreenBuffer());
Keyboard::pushRepeatState(true);
InputManager manager;
Util::Parameter<Util::ReferenceCount<Path::RelativePath> >
defaultFont(Font::defaultFont, Util::ReferenceCount<Path::RelativePath>(new Path::RelativePath("fonts/arial.ttf")));
Network::init();
try {
doIrc(hostname, port, username);
} catch (const Exception::Return & ex){
} catch (const Network::NetworkException & ex){
Global::debug(0) << "Network Exception: " << ex.getMessage() << std::endl;
}
Network::shutdown();
} else {
arguments(argv[0],0);
}
return 0;
}
#ifdef USE_ALLEGRO
END_OF_MAIN()
#endif
<commit_msg>[util] Make irc game test clients connect to game server and send hello.<commit_after>#include "../common/init.h"
#include "../common/timer.h"
#include <iostream>
#include <vector>
#include <stdexcept>
#include "util/graphics/bitmap.h"
#include "util/font.h"
#include "util/debug.h"
#include "util/exceptions/load_exception.h"
#include "util/token_exception.h"
#include "util/input/input.h"
#include "util/input/input-manager.h"
#include "util/sound/sound.h"
#include "util/exceptions/exception.h"
#include "util/network/chat.h"
#include "util/network/network.h"
#include "util/network/irc.h"
#include "util/thread.h"
#include "util/pointer.h"
#include "util/system.h"
#include "util/timedifference.h"
#include "util/configuration.h"
#include <queue>
#include <map>
static std::vector<std::string> split(std::string str, char splitter){
std::vector<std::string> strings;
size_t next = str.find(splitter);
while (next != std::string::npos){
strings.push_back(str.substr(0, next));
str = str.substr(next+1);
next = str.find(splitter);
}
if (str != ""){
strings.push_back(str);
}
return strings;
}
static void setTrue(void * b){
bool * what = (bool*) b;
*what = true;
}
static void nextTab(void * i){
::Network::IRC::ChatInterface * interface = (::Network::IRC::ChatInterface *)i;
interface->nextChannel();
}
static void previousTab(void * i){
::Network::IRC::ChatInterface * interface = (::Network::IRC::ChatInterface *)i;
interface->previousChannel();
}
class Game{
public:
Game(const std::string & name, bool host = true):
name(name),
host(host){
}
~Game(){
}
void addClient(const std::string & name, const std::string & ip){
clients[name] = ip;
}
std::string clientsAsString(){
std::string clientlist;
for (std::map<std::string, std::string>::iterator i = clients.begin(); i != clients.end(); i++){
clientlist += (*i).first + ", ";
}
return clientlist.substr(0, clientlist.size() - 2);
}
void start(const std::string & ip, const std::string & hostip) {
// TODO move to a thread, otherwise the server is going to hang...
int port = 9991;
if (isHost()){
Global::debug(0) << "Game " << name << " is starting." << std::endl;
Global::debug(0) << "Starting server on port " << port << "...." << std::endl;
::Network::Chat::Server server(port);
server.start();
// Wait for all clients to send a message
unsigned int allReceived = 0;
while (allReceived < clients.size()){
server.poll();
while (server.hasMessages()){
::Network::Chat::Message message = server.nextMessage();
std::map<std::string, std::string>::iterator check = clients.find(message.getName());
if (check != clients.end()){
Global::debug(0) << "Message Received: " << message.getMessage() << std::endl;
allReceived++;
}
}
}
Global::debug(0) << "Received all messages. Shutting down." << std::endl;
server.shutdown();
} else {
Global::debug(0) << "Game " << name << " is starting." << std::endl;
Global::debug(0) << "Connecting to " << hostip << "...." << std::endl;
Network::Socket socket = Network::connectReliable(hostip, port);
Global::debug(0) << "Connected" << std::endl;
::Network::Chat::Client client(0, socket);
client.start();
::Network::Chat::Message ourMessage(::Network::Chat::Message::Chat, ip, "Hello from: " + ip);
client.sendMessage(ourMessage);
Global::debug(0) << "Message sent. Shutting down." << std::endl;
client.shutdown();
}
}
std::map<std::string, std::string> & getClients(){
return clients;
}
const std::string & getName() const {
return name;
}
bool isHost() const {
return host;
}
private:
std::string name;
bool host;
std::map<std::string, std::string> clients;
};
class InputLogicDraw: public Util::Logic, public Util::Draw, public ::Network::IRC::Message::EventInterface {
public:
InputLogicDraw(int port, const std::string & host, const std::string & username):
chatInterface(host, port, username),
escaped(false){
ircClient = Util::ReferenceCount< ::Network::IRC::Client >(new ::Network::IRC::Client(host, port));
chatInterface.getInputBox().addHook(Keyboard::Key_ESC, setTrue, &escaped);
chatInterface.getInputBox().addHook(Keyboard::Key_TAB, nextTab, &chatInterface);
chatInterface.subscribe(this);
// Get IP
chatInterface.getClient()->sendCommand(::Network::IRC::Command::Userhost, chatInterface.getClient()->getName());
}
::Network::IRC::ChatInterface chatInterface;
Util::ReferenceCount< ::Network::IRC::Client > ircClient;
bool escaped;
std::string ipAddress;
Util::ReferenceCount<Game> game;
std::map<std::string, std::string> hosts;
void remoteCommand(const ::Network::IRC::Command & command){
if (command.getType() == ::Network::IRC::Command::ReplyUserhost){
const std::vector<std::string> & params = command.getParameters();
const std::string & extract = params.at(1);
for (unsigned int i = 0; i < extract.size(); i++){
if (extract[i] == '@'){
ipAddress = extract.substr(++i, extract.size()-1);
Global::debug(0) << "Your IP Address is: " << ipAddress << std::endl;
}
}
}
if (command.hasCtcp()){
const std::vector<std::string> & ctcp = command.getCtcp();
if (command.getType() == ::Network::IRC::Command::PrivateMessage){
try {
if (ctcp.at(0) == "game"){
const std::string & gameCommand = ctcp.at(1);
if (gameCommand == "invite"){
const std::string & gameName = ctcp.at(2);
const std::string & hostName = ctcp.at(3);
chatInterface.addMessageToTab("* " + hostName + " has invited you to join the game [" + gameName + "]. Type \"/game join " + gameName + "\".");
hosts[gameName] = hostName;
} else if (gameCommand == "join"){
if (game != NULL && game->isHost()){
const std::string & gameName = ctcp.at(2);
const std::string & clientName = ctcp.at(3);
const std::string & ip = ctcp.at(4);
chatInterface.addMessageToTab("* " + clientName + " has joined " + gameName + ".");
game->addClient(clientName, ip);
} else {
chatInterface.addMessageToTab("* received a join request with no game pending.");
}
} else if (gameCommand == "start"){
if (game != NULL && !game->isHost()){
const std::string & gameName = ctcp.at(2);
const std::string & serverIp = ctcp.at(3);
chatInterface.addMessageToTab("* Host has started game " + gameName);
game->start(ipAddress, serverIp);
}
}
} else {
Global::debug(0) << "Got ctcp: " << ctcp.at(0) << std::endl;
}
} catch (const std::out_of_range & ex){
}
}
}
}
void localCommand(const std::vector<std::string> & command){
if (command.at(0) == "help"){
chatInterface.addMessageToTab("* commands: lol, game");
} else if (command.at(0) == "lol"){
chatInterface.addMessageToTab("* You LOLOLOLOLLOLOLOL yourself.");
} else if (command.at(0) == "game"){
// Game
if (command.size() > 1){
if (command.at(1) == "help"){
chatInterface.addMessageToTab("* game commands: help, new, start, list-users, list-hosts, invite, join.");
} else if (command.at(1) == "new"){
try{
game = Util::ReferenceCount<Game>(new Game(command.at(2)));
chatInterface.addMessageToTab("* game \"" + command.at(2) + "\" created.");
} catch (const std::out_of_range & ex){
chatInterface.addMessageToTab("* /game new [name]");
}
} else if (command.at(1) == "start"){
if (game != NULL && game->isHost()){
chatInterface.addMessageToTab("* Starting game " + game->getName());
game->start(ipAddress, ipAddress);
for (std::map<std::string, std::string>::iterator i = game->getClients().begin(); i != game->getClients().end(); i++){
chatInterface.getClient()->sendCommand(::Network::IRC::Command::PrivateMessage,
(*i).first,
":\001game start " + game->getName() + " " + ipAddress + "\001");
}
} else {
chatInterface.addMessageToTab("* Create a game first...");
}
} else if (command.at(1) == "list-users"){
if (game != NULL){
chatInterface.addMessageToTab("* Users who accepted game request: " + game->clientsAsString());
} else {
chatInterface.addMessageToTab("* Create a game first...");
}
} else if (command.at(1) == "list-hosts"){
if (!hosts.empty()){
std::string hostlist;
for (std::map<std::string, std::string>::iterator i = hosts.begin(); i != hosts.end(); i++){
hostlist += (*i).first + +" [" + (*i).second + "], ";
}
chatInterface.addMessageToTab("* Hosts and games you've been invited to: " + hostlist.substr(0, hostlist.size() - 2));
} else {
chatInterface.addMessageToTab("* You have no invites.");
}
} else if (command.at(1) == "invite"){
if (game != NULL){
try {
chatInterface.addMessageToTab("* Sending request to " + command.at(2));
chatInterface.getClient()->sendCommand(::Network::IRC::Command::PrivateMessage,
command.at(2),
":\001game invite " + game->getName() + " " + chatInterface.getClient()->getName() + "\001");
} catch (const std::out_of_range & ex){
chatInterface.addMessageToTab("* /game invite [username]");
}
} else {
chatInterface.addMessageToTab("* Create a game first...");
}
} else if (command.at(1) == "join"){
if (!hosts.empty()){
try {
const std::string & gameName = command.at(2);
const std::string & hostName = hosts[gameName];
chatInterface.addMessageToTab("* Joining game at " + gameName);
chatInterface.getClient()->sendCommand(::Network::IRC::Command::PrivateMessage,
hostName,
":\001game join " + gameName + " " + chatInterface.getClient()->getName() + " " + ipAddress + "\001");
game = Util::ReferenceCount<Game>(new Game(gameName, false));
} catch (const std::out_of_range & ex){
chatInterface.addMessageToTab("* /game join [name]");
}
} else {
chatInterface.addMessageToTab("* You must be invited to a game first...");
}
}
}
} else {
//chatInterface.addMessageToTab("* Uknown command.");
}
}
double ticks(double system){
return system;
}
void run(){
try {
chatInterface.act();
} catch (const Exception::Return & ex){
escaped = true;
throw ex;
}
}
bool done(){
return escaped;
}
void draw(const Graphics::Bitmap & screen){
chatInterface.draw(screen);
}
};
static void doIrc(const std::string & host, int port, const std::string & username){
InputLogicDraw client(port, host, username);
Util::standardLoop(client, client);
}
static void arguments(const std::string & application, int status){
std::cout << "Usage: ./" << application << " port host [username]" << std::endl;
exit(status);
}
int main(int argc, char ** argv){
if (argc >= 2){
int port = atoi(argv[1]);
std::string hostname = argv[2];
std::string username = "paintown-test";
if (argc > 3){
username = argv[3];
}
Screen::realInit(Configuration::getScreenWidth(), Configuration::getScreenHeight());
atexit(Screen::realFinish);
Common::startTimers();
Sound::initialize();
Global::setDebug(2);
Util::Parameter<Graphics::Bitmap*> use(Graphics::screenParameter, Graphics::getScreenBuffer());
Keyboard::pushRepeatState(true);
InputManager manager;
Util::Parameter<Util::ReferenceCount<Path::RelativePath> >
defaultFont(Font::defaultFont, Util::ReferenceCount<Path::RelativePath>(new Path::RelativePath("fonts/arial.ttf")));
Network::init();
try {
doIrc(hostname, port, username);
} catch (const Exception::Return & ex){
} catch (const Network::NetworkException & ex){
Global::debug(0) << "Network Exception: " << ex.getMessage() << std::endl;
}
Network::shutdown();
} else {
arguments(argv[0],0);
}
return 0;
}
#ifdef USE_ALLEGRO
END_OF_MAIN()
#endif
<|endoftext|>
|
<commit_before>/***********************************************************************
result.cpp - Implements the Result, ResNSel, and ResUse classes.
Copyright (c) 1998 by Kevin Atkinson, (c) 1999-2001 by MySQL AB, and
(c) 2004-2007 by Educational Technology Resources, Inc. Others may
also hold copyrights on code in this file. See the CREDITS file in the
top directory of the distribution for details.
This file is part of MySQL++.
MySQL++ 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.
MySQL++ 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 MySQL++; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
USA
***********************************************************************/
#include "result.h"
#include "dbdriver.h"
namespace mysqlpp {
ResUse::ResUse(MYSQL_RES* result, DBDriver* dbd, bool te) :
OptionalExceptions(te),
driver_(result ? dbd : 0),
fields_(this)
{
if (result) {
result_ = result;
names_ = new FieldNames(this);
types_ = new FieldTypes(this);
}
}
ResUse::~ResUse()
{
}
void
ResUse::copy(const ResUse& other)
{
set_exceptions(other.throw_exceptions());
if (other.result_) {
result_ = other.result_;
fields_ = Fields(this);
names_ = other.names_;
types_ = other.types_;
driver_ = other.driver_;
}
else {
result_ = 0;
names_ = 0;
types_ = 0;
driver_ = 0;
}
}
void
Result::data_seek(ulonglong offset) const
{
driver_->data_seek(result_.raw(), offset);
}
const Field&
ResUse::fetch_field() const
{
return *driver_->fetch_field(result_.raw());
}
const unsigned long*
ResUse::fetch_lengths() const
{
return driver_->fetch_lengths(result_.raw());
}
Row
ResUse::fetch_row() const
{
if (!result_) {
if (throw_exceptions()) {
throw UseQueryError("Results not fetched");
}
else {
return Row();
}
}
MYSQL_ROW row = driver_->fetch_row(result_.raw());
const unsigned long* lengths = fetch_lengths();
if (row && lengths) {
return Row(row, this, lengths, throw_exceptions());
}
else {
return Row();
}
}
MYSQL_ROW
ResUse::fetch_raw_row() const
{
return driver_->fetch_row(result_.raw());
}
int
ResUse::field_num(const std::string& i) const
{
size_t index = (*names_)[i];
if ((index >= names_->size()) && throw_exceptions()) {
throw BadFieldName(i.c_str());
}
return int(index);
}
void
ResUse::field_seek(size_t field) const
{
driver_->field_seek(result_.raw(), field);
}
int
ResUse::num_fields() const
{
return driver_->num_fields(result_.raw());
}
ulonglong
Result::num_rows() const
{
return driver_ ? driver_->num_rows(result_.raw()) : 0;
}
ResUse&
ResUse::operator =(const ResUse& other)
{
if (this != &other) {
copy(other);
}
return *this;
}
} // end namespace mysqlpp
<commit_msg>Result::field_num() returns -1 instead of throwing BadFieldName if exceptions are disabled. Now all sources of this exception are optional.<commit_after>/***********************************************************************
result.cpp - Implements the Result, ResNSel, and ResUse classes.
Copyright (c) 1998 by Kevin Atkinson, (c) 1999-2001 by MySQL AB, and
(c) 2004-2007 by Educational Technology Resources, Inc. Others may
also hold copyrights on code in this file. See the CREDITS file in the
top directory of the distribution for details.
This file is part of MySQL++.
MySQL++ 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.
MySQL++ 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 MySQL++; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
USA
***********************************************************************/
#include "result.h"
#include "dbdriver.h"
namespace mysqlpp {
ResUse::ResUse(MYSQL_RES* result, DBDriver* dbd, bool te) :
OptionalExceptions(te),
driver_(result ? dbd : 0),
fields_(this)
{
if (result) {
result_ = result;
names_ = new FieldNames(this);
types_ = new FieldTypes(this);
}
}
ResUse::~ResUse()
{
}
void
ResUse::copy(const ResUse& other)
{
set_exceptions(other.throw_exceptions());
if (other.result_) {
result_ = other.result_;
fields_ = Fields(this);
names_ = other.names_;
types_ = other.types_;
driver_ = other.driver_;
}
else {
result_ = 0;
names_ = 0;
types_ = 0;
driver_ = 0;
}
}
void
Result::data_seek(ulonglong offset) const
{
driver_->data_seek(result_.raw(), offset);
}
const Field&
ResUse::fetch_field() const
{
return *driver_->fetch_field(result_.raw());
}
const unsigned long*
ResUse::fetch_lengths() const
{
return driver_->fetch_lengths(result_.raw());
}
Row
ResUse::fetch_row() const
{
if (!result_) {
if (throw_exceptions()) {
throw UseQueryError("Results not fetched");
}
else {
return Row();
}
}
MYSQL_ROW row = driver_->fetch_row(result_.raw());
const unsigned long* lengths = fetch_lengths();
if (row && lengths) {
return Row(row, this, lengths, throw_exceptions());
}
else {
return Row();
}
}
MYSQL_ROW
ResUse::fetch_raw_row() const
{
return driver_->fetch_row(result_.raw());
}
int
ResUse::field_num(const std::string& i) const
{
size_t index = (*names_)[i];
if ((index >= names_->size()) && throw_exceptions()) {
if (throw_exceptions()) {
throw BadFieldName(i.c_str());
}
else {
return -1;
}
}
return int(index);
}
void
ResUse::field_seek(size_t field) const
{
driver_->field_seek(result_.raw(), field);
}
int
ResUse::num_fields() const
{
return driver_->num_fields(result_.raw());
}
ulonglong
Result::num_rows() const
{
return driver_ ? driver_->num_rows(result_.raw()) : 0;
}
ResUse&
ResUse::operator =(const ResUse& other)
{
if (this != &other) {
copy(other);
}
return *this;
}
} // end namespace mysqlpp
<|endoftext|>
|
<commit_before>/***********************************************************************
result.cpp - Implements the Result, ResNSel, and ResUse classes.
Copyright (c) 1998 by Kevin Atkinson, (c) 1999, 2000 and 2001 by
MySQL AB, and (c) 2004, 2005 by Educational Technology Resources, Inc.
Others may also hold copyrights on code in this file. See the CREDITS
file in the top directory of the distribution for details.
This file is part of MySQL++.
MySQL++ 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.
MySQL++ 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 MySQL++; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
USA
***********************************************************************/
#include "result.h"
namespace mysqlpp {
ResUse::ResUse(MYSQL_RES* result, bool te) :
OptionalExceptions(te),
initialized_(false),
types_(0),
fields_(this)
{
if ((result_ = result) != 0) {
names_ = new FieldNames(this);
if (names_) {
types_ = new FieldTypes(this);
}
table_ = field(0).table;
initialized_ = true;
}
}
ResUse::~ResUse()
{
purge();
}
void
ResUse::copy(const ResUse& other)
{
if (initialized_) {
purge();
}
set_exceptions(other.throw_exceptions());
if (other.result_) {
result_ = other.result_;
fields_ = Fields(this);
names_ = other.names_;
if (other.types_) {
types_ = new FieldTypes(*other.types_);
}
else {
types_ = 0;
}
table_ = other.table_;
initialized_ = true;
}
else {
result_ = 0;
types_ = 0;
names_ = 0;
initialized_ = other.initialized_;
}
}
int
ResUse::field_num(const std::string& i) const
{
if (!names_) {
names_ = new FieldNames(this);
}
size_t index = (*names_)[i];
if ((index >= names_->size()) && throw_exceptions()) {
throw BadFieldName(i.c_str());
}
return int(index);
}
const std::string&
ResUse::field_name(int i) const
{
if (!names_) {
names_ = new FieldNames(this);
}
return names_->at(i);
}
const RefCountedPointer<FieldNames>
ResUse::field_names() const
{
if (!names_) {
names_ = new FieldNames(this);
}
return names_;
}
const mysql_type_info&
ResUse::field_type(int i) const
{
if (!types_) {
types_ = new FieldTypes(this);
}
return (*types_)[i];
}
const FieldTypes&
ResUse::field_types() const
{
if (!types_) {
types_ = new FieldTypes(this);
}
return *types_;
}
void
ResUse::purge()
{
if (result_) {
mysql_free_result(result_);
result_ = 0;
}
names_ = 0;
delete types_;
types_ = 0;
table_.erase();
}
ResUse&
ResUse::operator =(const ResUse& other)
{
if (this == &other) {
return *this;
}
copy(other);
other.result_ = 0;
return *this;
}
} // end namespace mysqlpp
<commit_msg>Comment change<commit_after>/***********************************************************************
result.cpp - Implements the Result, ResNSel, and ResUse classes.
Copyright (c) 1998 by Kevin Atkinson, (c) 1999-2001 by MySQL AB, and
(c) 2004-2007 by Educational Technology Resources, Inc. Others may
also hold copyrights on code in this file. See the CREDITS file in the
top directory of the distribution for details.
This file is part of MySQL++.
MySQL++ 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.
MySQL++ 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 MySQL++; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
USA
***********************************************************************/
#include "result.h"
namespace mysqlpp {
ResUse::ResUse(MYSQL_RES* result, bool te) :
OptionalExceptions(te),
initialized_(false),
types_(0),
fields_(this)
{
if ((result_ = result) != 0) {
names_ = new FieldNames(this);
if (names_) {
types_ = new FieldTypes(this);
}
table_ = field(0).table;
initialized_ = true;
}
}
ResUse::~ResUse()
{
purge();
}
void
ResUse::copy(const ResUse& other)
{
if (initialized_) {
purge();
}
set_exceptions(other.throw_exceptions());
if (other.result_) {
result_ = other.result_;
fields_ = Fields(this);
names_ = other.names_;
if (other.types_) {
types_ = new FieldTypes(*other.types_);
}
else {
types_ = 0;
}
table_ = other.table_;
initialized_ = true;
}
else {
result_ = 0;
types_ = 0;
names_ = 0;
initialized_ = other.initialized_;
}
}
int
ResUse::field_num(const std::string& i) const
{
if (!names_) {
names_ = new FieldNames(this);
}
size_t index = (*names_)[i];
if ((index >= names_->size()) && throw_exceptions()) {
throw BadFieldName(i.c_str());
}
return int(index);
}
const std::string&
ResUse::field_name(int i) const
{
if (!names_) {
names_ = new FieldNames(this);
}
return names_->at(i);
}
const RefCountedPointer<FieldNames>
ResUse::field_names() const
{
if (!names_) {
names_ = new FieldNames(this);
}
return names_;
}
const mysql_type_info&
ResUse::field_type(int i) const
{
if (!types_) {
types_ = new FieldTypes(this);
}
return (*types_)[i];
}
const FieldTypes&
ResUse::field_types() const
{
if (!types_) {
types_ = new FieldTypes(this);
}
return *types_;
}
void
ResUse::purge()
{
if (result_) {
mysql_free_result(result_);
result_ = 0;
}
names_ = 0;
delete types_;
types_ = 0;
table_.erase();
}
ResUse&
ResUse::operator =(const ResUse& other)
{
if (this == &other) {
return *this;
}
copy(other);
other.result_ = 0;
return *this;
}
} // end namespace mysqlpp
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: svdocirc.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: vg $ $Date: 2007-04-11 16:23:32 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _SVDOCIRC_HXX
#define _SVDOCIRC_HXX
#ifndef _SVDORECT_HXX
#include <svx/svdorect.hxx>
#endif
#ifndef INCLUDED_SVXDLLAPI_H
#include "svx/svxdllapi.h"
#endif
//************************************************************
// Vorausdeklarationen
//************************************************************
namespace sdr
{
namespace properties
{
class CircleProperties;
} // end of namespace properties
} // end of namespace sdr
//************************************************************
// Hilfsklasse SdrCircObjGeoData
//************************************************************
// #109872#
class SdrCircObjGeoData : public SdrTextObjGeoData
{
public:
long nStartWink;
long nEndWink;
};
//************************************************************
// SdrCircObj
//************************************************************
class SVX_DLLPUBLIC SdrCircObj : public SdrRectObj
{
virtual sdr::properties::BaseProperties* CreateObjectSpecificProperties();
// to allow sdr::properties::CircleProperties access to ImpSetAttrToCircInfo()
friend class sdr::properties::CircleProperties;
// only for SdrCircleAttributes
SdrObjKind GetCircleKind() const { return eKind; }
protected:
SdrObjKind eKind;
long nStartWink;
long nEndWink;
Point aPnt1;
Point aPnt2;
// bitfield
unsigned mbPolygonIsLine : 1;
private:
SVX_DLLPRIVATE XPolygon ImpCalcXPolyCirc(const Rectangle& rRect1, long nStart, long nEnd, FASTBOOL bContour=FALSE) const; // ImpCalcXPoly -> ImpCalcXPolyCirc
SVX_DLLPRIVATE void ImpSetCreateParams(SdrDragStat& rStat) const;
SVX_DLLPRIVATE void ImpSetAttrToCircInfo(); // Werte vom Pool kopieren
SVX_DLLPRIVATE void ImpSetCircInfoToAttr(); // Werte in den Pool kopieren
// Liefert TRUE, wenn das Painten ein XPolygon erfordert.
SVX_DLLPRIVATE FASTBOOL PaintNeedsXPolyCirc() const; // PaintNeedsXPoly-> PaintNeedsXPolyCirc
SVX_DLLPRIVATE virtual void RecalcXPoly();
protected:
virtual void SFX_NOTIFY(SfxBroadcaster& rBC, const TypeId& rBCType, const SfxHint& rHint, const TypeId& rHintType);
public:
TYPEINFO();
SdrCircObj(SdrObjKind eNewKind); // Circ, CArc, Sect oder CCut
SdrCircObj(SdrObjKind eNewKind, const Rectangle& rRect);
// 0=0.00Deg=3h 9000=90.00Deg=12h 18000=180.00Deg=9h 27000=270.00Deg=6h
// Der Verlauf des Kreises von StartWink nach EndWink ist immer entgegen
// dem Uhrzeigersinn.
// Wenn nNewStartWink==nNewEndWink hat der Kreisbogen einen Verlaufswinkel
// von 0 Grad. Bei nNewStartWink+36000==nNewEndWink ist der Verlaufswinkel
// 360.00 Grad.
SdrCircObj(SdrObjKind eNewKind, const Rectangle& rRect, long nNewStartWink, long nNewEndWink);
virtual ~SdrCircObj();
virtual void TakeObjInfo(SdrObjTransformInfoRec& rInfo) const;
virtual UINT16 GetObjIdentifier() const;
virtual void RecalcBoundRect();
virtual void TakeUnrotatedSnapRect(Rectangle& rRect) const;
virtual sal_Bool DoPaintObject(XOutputDevice& rOut, const SdrPaintInfoRec& rInfoRec) const;
virtual SdrObject* CheckHit(const Point& rPnt, USHORT nTol, const SetOfByte* pVisiLayer) const;
virtual void TakeObjNameSingul(String& rName) const;
virtual void TakeObjNamePlural(String& rName) const;
virtual void operator=(const SdrObject& rObj);
virtual void RecalcSnapRect();
virtual void NbcSetSnapRect(const Rectangle& rRect);
virtual basegfx::B2DPolyPolygon TakeXorPoly(sal_Bool bDetail) const;
virtual sal_uInt32 GetSnapPointCount() const;
virtual Point GetSnapPoint(sal_uInt32 i) const;
virtual sal_uInt32 GetHdlCount() const;
virtual SdrHdl* GetHdl(sal_uInt32 nHdlNum) const;
virtual FASTBOOL HasSpecialDrag() const;
virtual FASTBOOL BegDrag(SdrDragStat& rDrag) const;
virtual FASTBOOL MovDrag(SdrDragStat& rDrag) const;
virtual FASTBOOL EndDrag(SdrDragStat& rDrag);
virtual void BrkDrag(SdrDragStat& rDrag) const;
virtual String GetDragComment(const SdrDragStat& rDrag, FASTBOOL bUndoDragComment, FASTBOOL bCreateComment) const;
virtual basegfx::B2DPolyPolygon TakeDragPoly(const SdrDragStat& rDrag) const;
virtual FASTBOOL BegCreate(SdrDragStat& rStat);
virtual FASTBOOL MovCreate(SdrDragStat& rStat);
virtual FASTBOOL EndCreate(SdrDragStat& rStat, SdrCreateCmd eCmd);
virtual FASTBOOL BckCreate(SdrDragStat& rStat);
virtual void BrkCreate(SdrDragStat& rStat);
virtual basegfx::B2DPolyPolygon TakeCreatePoly(const SdrDragStat& rDrag) const;
virtual Pointer GetCreatePointer() const;
virtual void NbcMove(const Size& aSiz);
virtual void NbcResize(const Point& rRef, const Fraction& xFact, const Fraction& yFact);
virtual void NbcMirror(const Point& rRef1, const Point& rRef2);
virtual void NbcShear (const Point& rRef, long nWink, double tn, FASTBOOL bVShear);
virtual SdrObject* DoConvertToPolyObj(BOOL bBezier) const;
protected:
virtual SdrObjGeoData* NewGeoData() const;
virtual void SaveGeoData(SdrObjGeoData& rGeo) const;
virtual void RestGeoData(const SdrObjGeoData& rGeo);
public:
long GetStartWink() const { return nStartWink; }
long GetEndWink() const { return nEndWink; }
};
#endif //_SVDOCIRC_HXX
<commit_msg>INTEGRATION: CWS aw048 (1.2.20); FILE MERGED 2007/04/18 10:54:43 aw 1.2.20.1: adaption to moved headers<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: svdocirc.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: kz $ $Date: 2007-05-09 13:29:42 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _SVDOCIRC_HXX
#define _SVDOCIRC_HXX
#ifndef _SVDORECT_HXX
#include <svx/svdorect.hxx>
#endif
#ifndef INCLUDED_SVXDLLAPI_H
#include "svx/svxdllapi.h"
#endif
//************************************************************
// Vorausdeklarationen
//************************************************************
namespace sdr
{
namespace properties
{
class CircleProperties;
} // end of namespace properties
} // end of namespace sdr
//************************************************************
// Hilfsklasse SdrCircObjGeoData
//************************************************************
// #109872#
class SdrCircObjGeoData : public SdrTextObjGeoData
{
public:
long nStartWink;
long nEndWink;
};
//************************************************************
// SdrCircObj
//************************************************************
class SVX_DLLPUBLIC SdrCircObj : public SdrRectObj
{
virtual sdr::properties::BaseProperties* CreateObjectSpecificProperties();
// to allow sdr::properties::CircleProperties access to ImpSetAttrToCircInfo()
friend class sdr::properties::CircleProperties;
// only for SdrCircleAttributes
SdrObjKind GetCircleKind() const { return meCircleKind; }
protected:
SdrObjKind meCircleKind;
long nStartWink;
long nEndWink;
Point aPnt1;
Point aPnt2;
// bitfield
unsigned mbPolygonIsLine : 1;
private:
SVX_DLLPRIVATE basegfx::B2DPolygon ImpCalcXPolyCirc(const SdrObjKind eKind, const Rectangle& rRect1, long nStart, long nEnd) const;
SVX_DLLPRIVATE void ImpSetCreateParams(SdrDragStat& rStat) const;
SVX_DLLPRIVATE void ImpSetAttrToCircInfo(); // Werte vom Pool kopieren
SVX_DLLPRIVATE void ImpSetCircInfoToAttr(); // Werte in den Pool kopieren
// Liefert TRUE, wenn das Painten ein XPolygon erfordert.
SVX_DLLPRIVATE FASTBOOL PaintNeedsXPolyCirc() const; // PaintNeedsXPoly-> PaintNeedsXPolyCirc
SVX_DLLPRIVATE virtual void RecalcXPoly();
protected:
virtual void SFX_NOTIFY(SfxBroadcaster& rBC, const TypeId& rBCType, const SfxHint& rHint, const TypeId& rHintType);
public:
TYPEINFO();
SdrCircObj(SdrObjKind eNewKind); // Circ, CArc, Sect oder CCut
SdrCircObj(SdrObjKind eNewKind, const Rectangle& rRect);
// 0=0.00Deg=3h 9000=90.00Deg=12h 18000=180.00Deg=9h 27000=270.00Deg=6h
// Der Verlauf des Kreises von StartWink nach EndWink ist immer entgegen
// dem Uhrzeigersinn.
// Wenn nNewStartWink==nNewEndWink hat der Kreisbogen einen Verlaufswinkel
// von 0 Grad. Bei nNewStartWink+36000==nNewEndWink ist der Verlaufswinkel
// 360.00 Grad.
SdrCircObj(SdrObjKind eNewKind, const Rectangle& rRect, long nNewStartWink, long nNewEndWink);
virtual ~SdrCircObj();
virtual void TakeObjInfo(SdrObjTransformInfoRec& rInfo) const;
virtual UINT16 GetObjIdentifier() const;
virtual void RecalcBoundRect();
virtual void TakeUnrotatedSnapRect(Rectangle& rRect) const;
virtual sal_Bool DoPaintObject(XOutputDevice& rOut, const SdrPaintInfoRec& rInfoRec) const;
virtual SdrObject* CheckHit(const Point& rPnt, USHORT nTol, const SetOfByte* pVisiLayer) const;
virtual void TakeObjNameSingul(String& rName) const;
virtual void TakeObjNamePlural(String& rName) const;
virtual void operator=(const SdrObject& rObj);
virtual void RecalcSnapRect();
virtual void NbcSetSnapRect(const Rectangle& rRect);
virtual basegfx::B2DPolyPolygon TakeXorPoly(sal_Bool bDetail) const;
virtual sal_uInt32 GetSnapPointCount() const;
virtual Point GetSnapPoint(sal_uInt32 i) const;
virtual sal_uInt32 GetHdlCount() const;
virtual SdrHdl* GetHdl(sal_uInt32 nHdlNum) const;
virtual FASTBOOL HasSpecialDrag() const;
virtual FASTBOOL BegDrag(SdrDragStat& rDrag) const;
virtual FASTBOOL MovDrag(SdrDragStat& rDrag) const;
virtual FASTBOOL EndDrag(SdrDragStat& rDrag);
virtual void BrkDrag(SdrDragStat& rDrag) const;
virtual String GetDragComment(const SdrDragStat& rDrag, FASTBOOL bUndoDragComment, FASTBOOL bCreateComment) const;
virtual basegfx::B2DPolyPolygon TakeDragPoly(const SdrDragStat& rDrag) const;
virtual FASTBOOL BegCreate(SdrDragStat& rStat);
virtual FASTBOOL MovCreate(SdrDragStat& rStat);
virtual FASTBOOL EndCreate(SdrDragStat& rStat, SdrCreateCmd eCmd);
virtual FASTBOOL BckCreate(SdrDragStat& rStat);
virtual void BrkCreate(SdrDragStat& rStat);
virtual basegfx::B2DPolyPolygon TakeCreatePoly(const SdrDragStat& rDrag) const;
virtual Pointer GetCreatePointer() const;
virtual void NbcMove(const Size& aSiz);
virtual void NbcResize(const Point& rRef, const Fraction& xFact, const Fraction& yFact);
virtual void NbcMirror(const Point& rRef1, const Point& rRef2);
virtual void NbcShear (const Point& rRef, long nWink, double tn, FASTBOOL bVShear);
virtual SdrObject* DoConvertToPolyObj(BOOL bBezier) const;
protected:
virtual SdrObjGeoData* NewGeoData() const;
virtual void SaveGeoData(SdrObjGeoData& rGeo) const;
virtual void RestGeoData(const SdrObjGeoData& rGeo);
public:
long GetStartWink() const { return nStartWink; }
long GetEndWink() const { return nEndWink; }
};
#endif //_SVDOCIRC_HXX
<|endoftext|>
|
<commit_before>//=================================================================================================
// Copyright (c) 2013, Johannes Meyer, TU Darmstadt
// 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 Flight Systems and Automatic Control group,
// TU Darmstadt, 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 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 <hector_quadrotor_model/quadrotor_propulsion.h>
#include <hector_quadrotor_model/helpers.h>
#include <ros/node_handle.h>
#include <ros/callback_queue.h>
#include <boost/array.hpp>
extern "C" {
#include "quadrotorPropulsion/quadrotorPropulsion.h"
#include "quadrotorPropulsion/quadrotorPropulsion_initialize.h"
}
namespace hector_quadrotor_model {
// extern void quadrotorPropulsion(const real_T xin[4], const real_T uin[10], const PropulsionParameters parameter, real_T dt, real_T y[6], real_T xpred[4]);
struct QuadrotorPropulsion::PropulsionModel {
PropulsionParameters parameters_;
boost::array<real_T,4> x;
boost::array<real_T,4> x_pred;
boost::array<real_T,10> u;
boost::array<real_T,14> y;
};
QuadrotorPropulsion::QuadrotorPropulsion()
{
// initialize propulsion model
quadrotorPropulsion_initialize();
propulsion_model_ = new PropulsionModel;
}
QuadrotorPropulsion::~QuadrotorPropulsion()
{
delete propulsion_model_;
}
inline void QuadrotorPropulsion::f(const real_T xin[4], const real_T uin[10], real_T dt, real_T y[14], real_T xpred[4]) const
{
::quadrotorPropulsion(xin, uin, propulsion_model_->parameters_, dt, y, xpred);
}
void QuadrotorPropulsion::configure(const std::string &ns)
{
ros::NodeHandle param(ns);
// get model parameters
param.getParam("k_m", propulsion_model_->parameters_.k_m);
param.getParam("k_t", propulsion_model_->parameters_.k_t);
param.getParam("CT0s", propulsion_model_->parameters_.CT0s);
param.getParam("CT1s", propulsion_model_->parameters_.CT1s);
param.getParam("CT2s", propulsion_model_->parameters_.CT2s);
param.getParam("J_M", propulsion_model_->parameters_.J_M);
param.getParam("l_m", propulsion_model_->parameters_.l_m);
param.getParam("Psi", propulsion_model_->parameters_.Psi);
param.getParam("R_A", propulsion_model_->parameters_.R_A);
param.getParam("alpha_m", propulsion_model_->parameters_.alpha_m);
param.getParam("beta_m", propulsion_model_->parameters_.beta_m);
#ifndef NDEBUG
std::cout << "Loaded the following quadrotor propulsion model parameters from namespace " << param.getNamespace() << ":" << std::endl;
std::cout << "k_m = " << propulsion_model_->parameters_.k_m << std::endl;
std::cout << "k_t = " << propulsion_model_->parameters_.k_t << std::endl;
std::cout << "CT2s = " << propulsion_model_->parameters_.CT2s << std::endl;
std::cout << "CT1s = " << propulsion_model_->parameters_.CT1s << std::endl;
std::cout << "CT0s = " << propulsion_model_->parameters_.CT0s << std::endl;
std::cout << "Psi = " << propulsion_model_->parameters_.Psi << std::endl;
std::cout << "J_M = " << propulsion_model_->parameters_.J_M << std::endl;
std::cout << "R_A = " << propulsion_model_->parameters_.R_A << std::endl;
std::cout << "l_m = " << propulsion_model_->parameters_.l_m << std::endl;
std::cout << "alpha_m = " << propulsion_model_->parameters_.alpha_m << std::endl;
std::cout << "beta_m = " << propulsion_model_->parameters_.beta_m << std::endl;
#endif
param.getParam("supply_voltage", initial_voltage_);
reset();
}
void QuadrotorPropulsion::reset()
{
boost::mutex::scoped_lock lock(mutex_);
propulsion_model_->x.assign(0.0);
propulsion_model_->x_pred.assign(0.0);
propulsion_model_->u.assign(0.0);
propulsion_model_->y.assign(0.0);
wrench_ = geometry_msgs::Wrench();
motor_status_ = hector_uav_msgs::MotorStatus();
motor_status_.voltage.resize(4);
motor_status_.frequency.resize(4);
motor_status_.current.resize(4);
supply_ = hector_uav_msgs::Supply();
supply_.voltage.resize(1);
supply_.voltage[0] = initial_voltage_;
last_command_time_ = ros::Time();
command_queue_ = std::queue<hector_uav_msgs::MotorPWMConstPtr>(); // .clear();
}
void QuadrotorPropulsion::setVoltage(const hector_uav_msgs::MotorPWM& voltage)
{
boost::mutex::scoped_lock lock(mutex_);
last_command_time_ = voltage.header.stamp;
if (motor_status_.on && voltage.pwm.size() >= 4) {
propulsion_model_->u[6] = voltage.pwm[0] * supply_.voltage[0] / 255.0;
propulsion_model_->u[7] = voltage.pwm[1] * supply_.voltage[0] / 255.0;
propulsion_model_->u[8] = voltage.pwm[2] * supply_.voltage[0] / 255.0;
propulsion_model_->u[9] = voltage.pwm[3] * supply_.voltage[0] / 255.0;
} else {
propulsion_model_->u[6] = 0.0;
propulsion_model_->u[7] = 0.0;
propulsion_model_->u[8] = 0.0;
propulsion_model_->u[9] = 0.0;
}
}
void QuadrotorPropulsion::setTwist(const geometry_msgs::Twist &twist)
{
boost::mutex::scoped_lock lock(mutex_);
propulsion_model_->u[0] = twist.linear.x;
propulsion_model_->u[1] = -twist.linear.y;
propulsion_model_->u[2] = -twist.linear.z;
propulsion_model_->u[3] = twist.angular.x;
propulsion_model_->u[4] = -twist.angular.y;
propulsion_model_->u[5] = -twist.angular.z;
}
void QuadrotorPropulsion::addVoltageToQueue(const hector_uav_msgs::MotorPWMConstPtr& command)
{
boost::mutex::scoped_lock lock(command_queue_mutex_);
if (!motor_status_.on) {
ROS_WARN_NAMED("quadrotor_propulsion", "Received new motor command. Enabled motors.");
engage();
}
ROS_DEBUG_STREAM_NAMED("quadrotor_propulsion", "Received motor command valid at " << command->header.stamp);
command_queue_.push(command);
command_condition_.notify_all();
}
bool QuadrotorPropulsion::processQueue(const ros::Time ×tamp, const ros::Duration &tolerance, const ros::Duration &delay, const ros::WallDuration &wait, ros::CallbackQueue *callback_queue) {
boost::mutex::scoped_lock lock(command_queue_mutex_);
bool new_command = false;
ros::Time min = timestamp - delay - tolerance /* - ros::Duration(dt) */;
ros::Time max = timestamp - delay + tolerance;
while(1) {
if (!command_queue_.empty()) {
hector_uav_msgs::MotorPWMConstPtr new_motor_voltage = command_queue_.front();
ros::Time new_time = new_motor_voltage->header.stamp;
if (new_time.isZero() || (new_time >= min && new_time <= max)) {
setVoltage(*new_motor_voltage);
command_queue_.pop();
new_command = true;
ROS_DEBUG_STREAM_NAMED("quadrotor_propulsion", "Using motor command valid at t = " << new_time.toSec() << "s for simulation step at t = " << timestamp.toSec() << "s (dt = " << (timestamp - new_time).toSec() << "s)");
// new motor command is too old:
} else if (new_time < min) {
ROS_DEBUG_NAMED("quadrotor_propulsion", "Command received was %fs too old. Discarding.", (new_time - timestamp).toSec());
command_queue_.pop();
continue;
// new motor command is too new:
} else {
// do nothing
}
} else {
if (!motor_status_.on || wait.isZero()) break;
ROS_DEBUG_NAMED("quadrotor_propulsion", "Waiting for command at simulation step t = %fs... last update was %fs ago", timestamp.toSec(), (timestamp - last_command_time_).toSec());
if (!callback_queue) {
if (command_condition_.timed_wait(lock, wait.toBoost())) continue;
} else {
lock.unlock();
callback_queue->callAvailable(wait);
lock.lock();
if (!command_queue_.empty()) continue;
}
ROS_ERROR_NAMED("quadrotor_propulsion", "Command timed out. Disabled motors.");
shutdown();
}
} while(false);
return new_command;
}
void QuadrotorPropulsion::update(double dt)
{
if (dt <= 0.0) return;
// std::cout << "u = [ ";
// for(std::size_t i = 0; i < propulsion_model_->u.size(); ++i)
// std::cout << propulsion_model_->u[i] << " ";
// std::cout << "]" << std::endl;
checknan(propulsion_model_->u, "propulsion model input");
checknan(propulsion_model_->x, "propulsion model state");
// update propulsion model
f(propulsion_model_->x.data(), propulsion_model_->u.data(), dt, propulsion_model_->y.data(), propulsion_model_->x_pred.data());
propulsion_model_->x = propulsion_model_->x_pred;
checknan(propulsion_model_->y, "propulsion model output");
// std::cout << "y = [ ";
// for(std::size_t i = 0; i < propulsion_model_->y.size(); ++i)
// std::cout << propulsion_model_->y[i] << " ";
// std::cout << "]" << std::endl;
wrench_.force.x = propulsion_model_->y[0];
wrench_.force.y = -propulsion_model_->y[1];
wrench_.force.z = propulsion_model_->y[2];
wrench_.torque.x = propulsion_model_->y[3];
wrench_.torque.y = -propulsion_model_->y[4];
wrench_.torque.z = -propulsion_model_->y[5];
motor_status_.voltage[0] = propulsion_model_->u[6];
motor_status_.voltage[1] = propulsion_model_->u[7];
motor_status_.voltage[2] = propulsion_model_->u[8];
motor_status_.voltage[3] = propulsion_model_->u[9];
motor_status_.frequency[0] = propulsion_model_->y[6];
motor_status_.frequency[1] = propulsion_model_->y[7];
motor_status_.frequency[2] = propulsion_model_->y[8];
motor_status_.frequency[3] = propulsion_model_->y[9];
motor_status_.running = motor_status_.frequency[0] > 1.0 && motor_status_.frequency[1] > 1.0 && motor_status_.frequency[2] > 1.0 && motor_status_.frequency[3] > 1.0;
motor_status_.current[0] = propulsion_model_->y[10];
motor_status_.current[1] = propulsion_model_->y[11];
motor_status_.current[2] = propulsion_model_->y[12];
motor_status_.current[3] = propulsion_model_->y[13];
}
void QuadrotorPropulsion::engage()
{
motor_status_.on = true;
}
void QuadrotorPropulsion::shutdown()
{
motor_status_.on = false;
}
} // namespace hector_quadrotor_model
<commit_msg>hector_quadrotor_model: added try..catch block to catch runtime error if the gazebo time is very small<commit_after>//=================================================================================================
// Copyright (c) 2013, Johannes Meyer, TU Darmstadt
// 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 Flight Systems and Automatic Control group,
// TU Darmstadt, 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 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 <hector_quadrotor_model/quadrotor_propulsion.h>
#include <hector_quadrotor_model/helpers.h>
#include <ros/node_handle.h>
#include <ros/callback_queue.h>
#include <boost/array.hpp>
extern "C" {
#include "quadrotorPropulsion/quadrotorPropulsion.h"
#include "quadrotorPropulsion/quadrotorPropulsion_initialize.h"
}
namespace hector_quadrotor_model {
// extern void quadrotorPropulsion(const real_T xin[4], const real_T uin[10], const PropulsionParameters parameter, real_T dt, real_T y[6], real_T xpred[4]);
struct QuadrotorPropulsion::PropulsionModel {
PropulsionParameters parameters_;
boost::array<real_T,4> x;
boost::array<real_T,4> x_pred;
boost::array<real_T,10> u;
boost::array<real_T,14> y;
};
QuadrotorPropulsion::QuadrotorPropulsion()
{
// initialize propulsion model
quadrotorPropulsion_initialize();
propulsion_model_ = new PropulsionModel;
}
QuadrotorPropulsion::~QuadrotorPropulsion()
{
delete propulsion_model_;
}
inline void QuadrotorPropulsion::f(const real_T xin[4], const real_T uin[10], real_T dt, real_T y[14], real_T xpred[4]) const
{
::quadrotorPropulsion(xin, uin, propulsion_model_->parameters_, dt, y, xpred);
}
void QuadrotorPropulsion::configure(const std::string &ns)
{
ros::NodeHandle param(ns);
// get model parameters
param.getParam("k_m", propulsion_model_->parameters_.k_m);
param.getParam("k_t", propulsion_model_->parameters_.k_t);
param.getParam("CT0s", propulsion_model_->parameters_.CT0s);
param.getParam("CT1s", propulsion_model_->parameters_.CT1s);
param.getParam("CT2s", propulsion_model_->parameters_.CT2s);
param.getParam("J_M", propulsion_model_->parameters_.J_M);
param.getParam("l_m", propulsion_model_->parameters_.l_m);
param.getParam("Psi", propulsion_model_->parameters_.Psi);
param.getParam("R_A", propulsion_model_->parameters_.R_A);
param.getParam("alpha_m", propulsion_model_->parameters_.alpha_m);
param.getParam("beta_m", propulsion_model_->parameters_.beta_m);
#ifndef NDEBUG
std::cout << "Loaded the following quadrotor propulsion model parameters from namespace " << param.getNamespace() << ":" << std::endl;
std::cout << "k_m = " << propulsion_model_->parameters_.k_m << std::endl;
std::cout << "k_t = " << propulsion_model_->parameters_.k_t << std::endl;
std::cout << "CT2s = " << propulsion_model_->parameters_.CT2s << std::endl;
std::cout << "CT1s = " << propulsion_model_->parameters_.CT1s << std::endl;
std::cout << "CT0s = " << propulsion_model_->parameters_.CT0s << std::endl;
std::cout << "Psi = " << propulsion_model_->parameters_.Psi << std::endl;
std::cout << "J_M = " << propulsion_model_->parameters_.J_M << std::endl;
std::cout << "R_A = " << propulsion_model_->parameters_.R_A << std::endl;
std::cout << "l_m = " << propulsion_model_->parameters_.l_m << std::endl;
std::cout << "alpha_m = " << propulsion_model_->parameters_.alpha_m << std::endl;
std::cout << "beta_m = " << propulsion_model_->parameters_.beta_m << std::endl;
#endif
param.getParam("supply_voltage", initial_voltage_);
reset();
}
void QuadrotorPropulsion::reset()
{
boost::mutex::scoped_lock lock(mutex_);
propulsion_model_->x.assign(0.0);
propulsion_model_->x_pred.assign(0.0);
propulsion_model_->u.assign(0.0);
propulsion_model_->y.assign(0.0);
wrench_ = geometry_msgs::Wrench();
motor_status_ = hector_uav_msgs::MotorStatus();
motor_status_.voltage.resize(4);
motor_status_.frequency.resize(4);
motor_status_.current.resize(4);
supply_ = hector_uav_msgs::Supply();
supply_.voltage.resize(1);
supply_.voltage[0] = initial_voltage_;
last_command_time_ = ros::Time();
command_queue_ = std::queue<hector_uav_msgs::MotorPWMConstPtr>(); // .clear();
}
void QuadrotorPropulsion::setVoltage(const hector_uav_msgs::MotorPWM& voltage)
{
boost::mutex::scoped_lock lock(mutex_);
last_command_time_ = voltage.header.stamp;
if (motor_status_.on && voltage.pwm.size() >= 4) {
propulsion_model_->u[6] = voltage.pwm[0] * supply_.voltage[0] / 255.0;
propulsion_model_->u[7] = voltage.pwm[1] * supply_.voltage[0] / 255.0;
propulsion_model_->u[8] = voltage.pwm[2] * supply_.voltage[0] / 255.0;
propulsion_model_->u[9] = voltage.pwm[3] * supply_.voltage[0] / 255.0;
} else {
propulsion_model_->u[6] = 0.0;
propulsion_model_->u[7] = 0.0;
propulsion_model_->u[8] = 0.0;
propulsion_model_->u[9] = 0.0;
}
}
void QuadrotorPropulsion::setTwist(const geometry_msgs::Twist &twist)
{
boost::mutex::scoped_lock lock(mutex_);
propulsion_model_->u[0] = twist.linear.x;
propulsion_model_->u[1] = -twist.linear.y;
propulsion_model_->u[2] = -twist.linear.z;
propulsion_model_->u[3] = twist.angular.x;
propulsion_model_->u[4] = -twist.angular.y;
propulsion_model_->u[5] = -twist.angular.z;
}
void QuadrotorPropulsion::addVoltageToQueue(const hector_uav_msgs::MotorPWMConstPtr& command)
{
boost::mutex::scoped_lock lock(command_queue_mutex_);
if (!motor_status_.on) {
ROS_WARN_NAMED("quadrotor_propulsion", "Received new motor command. Enabled motors.");
engage();
}
ROS_DEBUG_STREAM_NAMED("quadrotor_propulsion", "Received motor command valid at " << command->header.stamp);
command_queue_.push(command);
command_condition_.notify_all();
}
bool QuadrotorPropulsion::processQueue(const ros::Time ×tamp, const ros::Duration &tolerance, const ros::Duration &delay, const ros::WallDuration &wait, ros::CallbackQueue *callback_queue) {
boost::mutex::scoped_lock lock(command_queue_mutex_);
bool new_command = false;
ros::Time min(timestamp), max(timestamp);
try {
min = timestamp - delay - tolerance /* - ros::Duration(dt) */;
} catch (std::runtime_error &e) {}
try {
max = timestamp - delay + tolerance;
} catch (std::runtime_error &e) {}
while(1) {
if (!command_queue_.empty()) {
hector_uav_msgs::MotorPWMConstPtr new_motor_voltage = command_queue_.front();
ros::Time new_time = new_motor_voltage->header.stamp;
if (new_time.isZero() || (new_time >= min && new_time <= max)) {
setVoltage(*new_motor_voltage);
command_queue_.pop();
new_command = true;
ROS_DEBUG_STREAM_NAMED("quadrotor_propulsion", "Using motor command valid at t = " << new_time.toSec() << "s for simulation step at t = " << timestamp.toSec() << "s (dt = " << (timestamp - new_time).toSec() << "s)");
// new motor command is too old:
} else if (new_time < min) {
ROS_DEBUG_NAMED("quadrotor_propulsion", "Command received was %fs too old. Discarding.", (new_time - timestamp).toSec());
command_queue_.pop();
continue;
// new motor command is too new:
} else {
// do nothing
}
} else {
if (!motor_status_.on || wait.isZero()) break;
ROS_DEBUG_NAMED("quadrotor_propulsion", "Waiting for command at simulation step t = %fs... last update was %fs ago", timestamp.toSec(), (timestamp - last_command_time_).toSec());
if (!callback_queue) {
if (command_condition_.timed_wait(lock, wait.toBoost())) continue;
} else {
lock.unlock();
callback_queue->callAvailable(wait);
lock.lock();
if (!command_queue_.empty()) continue;
}
ROS_ERROR_NAMED("quadrotor_propulsion", "Command timed out. Disabled motors.");
shutdown();
}
} while(false);
return new_command;
}
void QuadrotorPropulsion::update(double dt)
{
if (dt <= 0.0) return;
// std::cout << "u = [ ";
// for(std::size_t i = 0; i < propulsion_model_->u.size(); ++i)
// std::cout << propulsion_model_->u[i] << " ";
// std::cout << "]" << std::endl;
checknan(propulsion_model_->u, "propulsion model input");
checknan(propulsion_model_->x, "propulsion model state");
// update propulsion model
f(propulsion_model_->x.data(), propulsion_model_->u.data(), dt, propulsion_model_->y.data(), propulsion_model_->x_pred.data());
propulsion_model_->x = propulsion_model_->x_pred;
checknan(propulsion_model_->y, "propulsion model output");
// std::cout << "y = [ ";
// for(std::size_t i = 0; i < propulsion_model_->y.size(); ++i)
// std::cout << propulsion_model_->y[i] << " ";
// std::cout << "]" << std::endl;
wrench_.force.x = propulsion_model_->y[0];
wrench_.force.y = -propulsion_model_->y[1];
wrench_.force.z = propulsion_model_->y[2];
wrench_.torque.x = propulsion_model_->y[3];
wrench_.torque.y = -propulsion_model_->y[4];
wrench_.torque.z = -propulsion_model_->y[5];
motor_status_.voltage[0] = propulsion_model_->u[6];
motor_status_.voltage[1] = propulsion_model_->u[7];
motor_status_.voltage[2] = propulsion_model_->u[8];
motor_status_.voltage[3] = propulsion_model_->u[9];
motor_status_.frequency[0] = propulsion_model_->y[6];
motor_status_.frequency[1] = propulsion_model_->y[7];
motor_status_.frequency[2] = propulsion_model_->y[8];
motor_status_.frequency[3] = propulsion_model_->y[9];
motor_status_.running = motor_status_.frequency[0] > 1.0 && motor_status_.frequency[1] > 1.0 && motor_status_.frequency[2] > 1.0 && motor_status_.frequency[3] > 1.0;
motor_status_.current[0] = propulsion_model_->y[10];
motor_status_.current[1] = propulsion_model_->y[11];
motor_status_.current[2] = propulsion_model_->y[12];
motor_status_.current[3] = propulsion_model_->y[13];
}
void QuadrotorPropulsion::engage()
{
motor_status_.on = true;
}
void QuadrotorPropulsion::shutdown()
{
motor_status_.on = false;
}
} // namespace hector_quadrotor_model
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: namedvaluecollection.hxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: ihi $ $Date: 2007-11-21 16:52:10 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef COMPHELPER_NAMEDVALUECOLLECTION_HXX
#define COMPHELPER_NAMEDVALUECOLLECTION_HXX
#ifndef INCLUDED_COMPHELPERDLLAPI_H
#include <comphelper/comphelperdllapi.h>
#endif
/** === begin UNO includes === **/
#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_
#include <com/sun/star/uno/Sequence.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_ANY_HXX_
#include <com/sun/star/uno/Any.hxx>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_NAMEDVALUE_HPP_
#include <com/sun/star/beans/NamedValue.hpp>
#endif
/** === end UNO includes === **/
#include <memory>
//........................................................................
namespace comphelper
{
//........................................................................
// ====================================================================
// = NamedValueCollection
// ====================================================================
struct NamedValueCollection_Impl;
/** a collection of named values, packed in various formats.
*/
class COMPHELPER_DLLPUBLIC NamedValueCollection
{
private:
::std::auto_ptr< NamedValueCollection_Impl > m_pImpl;
public:
NamedValueCollection();
/** constructs a collection
@param _rArguments
a sequence of Any's containing either PropertyValue's or NamedValue's.
*/
NamedValueCollection( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& _rArguments );
/** constructs a collection
@param _rArguments
a sequence of PropertyValues's
*/
NamedValueCollection( const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& _rArguments );
/** constructs a collection
@param _rArguments
a sequence of NamedValue's
*/
NamedValueCollection( const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::NamedValue >& _rArguments );
~NamedValueCollection();
inline void assign( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& _rArguments )
{
impl_assign( _rArguments );
}
inline void assign( const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& _rArguments )
{
impl_assign( _rArguments );
}
inline void assign( const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::NamedValue >& _rArguments )
{
impl_assign( _rArguments );
}
/// returns the number of elements in the collection
size_t size() const;
/// determines whether the collection is empty
bool empty() const;
/** retrieves a value with a given name from the collection, if it is present
@param _pAsciiValueName
the ASCII name of the value to retrieve
@param _out_rValue
is the output parameter taking the desired value upon successful return. If
a value with the given name is not present in the collection, or if a wrong-typed
value is present, then this parameter will not be touched.
@return
<TRUE/> if there is a value with the given name, which could successfully
be extraced. In this case, <arg>_out_rValue</arg> will contain the requested
value.<br/>
<FALSE/>, if there is no value with the given name.
@throws IllegalArgumentException
in case there is a value with the given name, but it cannot legally assigned to
_out_rValue.
*/
template < typename VALUE_TYPE >
bool get_ensureType( const sal_Char* _pAsciiValueName, VALUE_TYPE& _out_rValue ) const
{
return get_ensureType( ::rtl::OUString::createFromAscii( _pAsciiValueName ), &_out_rValue, ::cppu::UnoType< VALUE_TYPE >::get() );
}
template < typename VALUE_TYPE >
bool get_ensureType( const ::rtl::OUString& _rValueName, VALUE_TYPE& _out_rValue ) const
{
return get_ensureType( _rValueName, &_out_rValue, ::cppu::UnoType< VALUE_TYPE >::get() );
}
/** retrieves a value with a given name, or defaults it to a given value, if its not present
in the colllection
*/
template < typename VALUE_TYPE >
VALUE_TYPE getOrDefault( const sal_Char* _pAsciiValueName, const VALUE_TYPE& _rDefault ) const
{
return getOrDefault( ::rtl::OUString::createFromAscii( _pAsciiValueName ), _rDefault );
}
template < typename VALUE_TYPE >
VALUE_TYPE getOrDefault( const ::rtl::OUString& _rValueName, const VALUE_TYPE& _rDefault ) const
{
VALUE_TYPE retVal( _rDefault );
get_ensureType( _rValueName, retVal );
return retVal;
}
/** retrieves a (untyped) value with a given name
If the collection does not contain a value with the given name, an empty
Any is returned.
*/
const ::com::sun::star::uno::Any& get( const sal_Char* _pAsciiValueName ) const
{
return get( ::rtl::OUString::createFromAscii( _pAsciiValueName ) );
}
/** retrieves a (untyped) value with a given name
If the collection does not contain a value with the given name, an empty
Any is returned.
*/
const ::com::sun::star::uno::Any& get( const ::rtl::OUString& _rValueName ) const
{
return impl_get( _rValueName );
}
/// determines whether a value with a given name is present in the collection
inline bool has( const sal_Char* _pAsciiValueName ) const
{
return impl_has( ::rtl::OUString::createFromAscii( _pAsciiValueName ) );
}
/// determines whether a value with a given name is present in the collection
inline bool has( const ::rtl::OUString& _rValueName ) const
{
return impl_has( _rValueName );
}
/** puts a value into the collection
@return <TRUE/> if and only if a value was already present previously, in
which case it has been overwritten.
*/
template < typename VALUE_TYPE >
inline bool put( const sal_Char* _pAsciiValueName, const VALUE_TYPE& _rValue )
{
return impl_put( ::rtl::OUString::createFromAscii( _pAsciiValueName ), ::com::sun::star::uno::makeAny( _rValue ) );
}
/** puts a value into the collection
@return <TRUE/> if and only if a value was already present previously, in
which case it has been overwritten.
*/
template < typename VALUE_TYPE >
inline bool put( const ::rtl::OUString& _rValueName, const VALUE_TYPE& _rValue )
{
return impl_put( _rValueName, ::com::sun::star::uno::makeAny( _rValue ) );
}
inline bool put( const sal_Char* _pAsciiValueName, const ::com::sun::star::uno::Any& _rValue )
{
return impl_put( ::rtl::OUString::createFromAscii( _pAsciiValueName ), _rValue );
}
inline bool put( const ::rtl::OUString& _rValueName, const ::com::sun::star::uno::Any& _rValue )
{
return impl_put( _rValueName, _rValue );
}
/** removes the value with the given name from the collection
@return <TRUE/> if and only if a value with the given name existed in the collection.
*/
inline bool remove( const sal_Char* _pAsciiValueName )
{
return impl_remove( ::rtl::OUString::createFromAscii( _pAsciiValueName ) );
}
/** removes the value with the given name from the collection
@return <TRUE/> if and only if a value with the given name existed in the collection.
*/
inline bool remove( const ::rtl::OUString& _rValueName )
{
return impl_remove( _rValueName );
}
/** transforms the collection to a sequence of PropertyValues
@return
the number of elements in the sequence
*/
sal_Int32 operator >>= ( ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& _out_rValues );
/** transforms the collection to a sequence of NamedValues
@return
the number of elements in the sequence
*/
sal_Int32 operator >>= ( ::com::sun::star::uno::Sequence< ::com::sun::star::beans::NamedValue >& _out_rValues );
private:
void impl_assign( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& _rArguments );
void impl_assign( const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& _rArguments );
void impl_assign( const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::NamedValue >& _rArguments );
bool get_ensureType(
const ::rtl::OUString& _rValueName,
void* _pValueLocation,
const ::com::sun::star::uno::Type& _rExpectedValueType
) const;
const ::com::sun::star::uno::Any&
impl_get( const ::rtl::OUString& _rValueName ) const;
bool impl_has( const ::rtl::OUString& _rValueName ) const;
bool impl_put( const ::rtl::OUString& _rValueName, const ::com::sun::star::uno::Any& _rValue );
bool impl_remove( const ::rtl::OUString& _rValueName );
};
//........................................................................
} // namespace comphelper
//........................................................................
#endif // COMPHELPER_NAMEDVALUECOLLECTION_HXX
<commit_msg>INTEGRATION: CWS odbmacros2 (1.7.10); FILE MERGED 2008/01/30 13:17:22 fs 1.7.10.3: #i49133# new ctor taking an Any 2007/12/12 11:29:30 fs 1.7.10.2: +getProperty/NamedValues 2007/12/06 13:30:51 fs 1.7.10.1: #i49133# operator >>= is const<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: namedvaluecollection.hxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: kz $ $Date: 2008-03-06 19:58:55 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef COMPHELPER_NAMEDVALUECOLLECTION_HXX
#define COMPHELPER_NAMEDVALUECOLLECTION_HXX
#ifndef INCLUDED_COMPHELPERDLLAPI_H
#include <comphelper/comphelperdllapi.h>
#endif
/** === begin UNO includes === **/
#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_
#include <com/sun/star/uno/Sequence.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_ANY_HXX_
#include <com/sun/star/uno/Any.hxx>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_NAMEDVALUE_HPP_
#include <com/sun/star/beans/NamedValue.hpp>
#endif
/** === end UNO includes === **/
#include <memory>
//........................................................................
namespace comphelper
{
//........................................................................
// ====================================================================
// = NamedValueCollection
// ====================================================================
struct NamedValueCollection_Impl;
/** a collection of named values, packed in various formats.
*/
class COMPHELPER_DLLPUBLIC NamedValueCollection
{
private:
::std::auto_ptr< NamedValueCollection_Impl > m_pImpl;
public:
NamedValueCollection();
/** constructs a collection
@param _rElements
the wrapped elements of the collection. The <code>Any</code> might contain a sequence of
property values, a sequence of named values, or directly a property value or named value.
All other cases are worth an assertion in non-product builds.
*/
NamedValueCollection( const ::com::sun::star::uno::Any& _rElements );
/** constructs a collection
@param _rArguments
a sequence of Any's containing either PropertyValue's or NamedValue's.
*/
NamedValueCollection( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& _rArguments );
/** constructs a collection
@param _rArguments
a sequence of PropertyValues's
*/
NamedValueCollection( const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& _rArguments );
/** constructs a collection
@param _rArguments
a sequence of NamedValue's
*/
NamedValueCollection( const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::NamedValue >& _rArguments );
~NamedValueCollection();
inline void assign( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& _rArguments )
{
impl_assign( _rArguments );
}
inline void assign( const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& _rArguments )
{
impl_assign( _rArguments );
}
inline void assign( const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::NamedValue >& _rArguments )
{
impl_assign( _rArguments );
}
/// returns the number of elements in the collection
size_t size() const;
/// determines whether the collection is empty
bool empty() const;
/** retrieves a value with a given name from the collection, if it is present
@param _pAsciiValueName
the ASCII name of the value to retrieve
@param _out_rValue
is the output parameter taking the desired value upon successful return. If
a value with the given name is not present in the collection, or if a wrong-typed
value is present, then this parameter will not be touched.
@return
<TRUE/> if there is a value with the given name, which could successfully
be extraced. In this case, <arg>_out_rValue</arg> will contain the requested
value.<br/>
<FALSE/>, if there is no value with the given name.
@throws IllegalArgumentException
in case there is a value with the given name, but it cannot legally assigned to
_out_rValue.
*/
template < typename VALUE_TYPE >
bool get_ensureType( const sal_Char* _pAsciiValueName, VALUE_TYPE& _out_rValue ) const
{
return get_ensureType( ::rtl::OUString::createFromAscii( _pAsciiValueName ), &_out_rValue, ::cppu::UnoType< VALUE_TYPE >::get() );
}
template < typename VALUE_TYPE >
bool get_ensureType( const ::rtl::OUString& _rValueName, VALUE_TYPE& _out_rValue ) const
{
return get_ensureType( _rValueName, &_out_rValue, ::cppu::UnoType< VALUE_TYPE >::get() );
}
/** retrieves a value with a given name, or defaults it to a given value, if its not present
in the colllection
*/
template < typename VALUE_TYPE >
VALUE_TYPE getOrDefault( const sal_Char* _pAsciiValueName, const VALUE_TYPE& _rDefault ) const
{
return getOrDefault( ::rtl::OUString::createFromAscii( _pAsciiValueName ), _rDefault );
}
template < typename VALUE_TYPE >
VALUE_TYPE getOrDefault( const ::rtl::OUString& _rValueName, const VALUE_TYPE& _rDefault ) const
{
VALUE_TYPE retVal( _rDefault );
get_ensureType( _rValueName, retVal );
return retVal;
}
/** retrieves a (untyped) value with a given name
If the collection does not contain a value with the given name, an empty
Any is returned.
*/
const ::com::sun::star::uno::Any& get( const sal_Char* _pAsciiValueName ) const
{
return get( ::rtl::OUString::createFromAscii( _pAsciiValueName ) );
}
/** retrieves a (untyped) value with a given name
If the collection does not contain a value with the given name, an empty
Any is returned.
*/
const ::com::sun::star::uno::Any& get( const ::rtl::OUString& _rValueName ) const
{
return impl_get( _rValueName );
}
/// determines whether a value with a given name is present in the collection
inline bool has( const sal_Char* _pAsciiValueName ) const
{
return impl_has( ::rtl::OUString::createFromAscii( _pAsciiValueName ) );
}
/// determines whether a value with a given name is present in the collection
inline bool has( const ::rtl::OUString& _rValueName ) const
{
return impl_has( _rValueName );
}
/** puts a value into the collection
@return <TRUE/> if and only if a value was already present previously, in
which case it has been overwritten.
*/
template < typename VALUE_TYPE >
inline bool put( const sal_Char* _pAsciiValueName, const VALUE_TYPE& _rValue )
{
return impl_put( ::rtl::OUString::createFromAscii( _pAsciiValueName ), ::com::sun::star::uno::makeAny( _rValue ) );
}
/** puts a value into the collection
@return <TRUE/> if and only if a value was already present previously, in
which case it has been overwritten.
*/
template < typename VALUE_TYPE >
inline bool put( const ::rtl::OUString& _rValueName, const VALUE_TYPE& _rValue )
{
return impl_put( _rValueName, ::com::sun::star::uno::makeAny( _rValue ) );
}
inline bool put( const sal_Char* _pAsciiValueName, const ::com::sun::star::uno::Any& _rValue )
{
return impl_put( ::rtl::OUString::createFromAscii( _pAsciiValueName ), _rValue );
}
inline bool put( const ::rtl::OUString& _rValueName, const ::com::sun::star::uno::Any& _rValue )
{
return impl_put( _rValueName, _rValue );
}
/** removes the value with the given name from the collection
@return <TRUE/> if and only if a value with the given name existed in the collection.
*/
inline bool remove( const sal_Char* _pAsciiValueName )
{
return impl_remove( ::rtl::OUString::createFromAscii( _pAsciiValueName ) );
}
/** removes the value with the given name from the collection
@return <TRUE/> if and only if a value with the given name existed in the collection.
*/
inline bool remove( const ::rtl::OUString& _rValueName )
{
return impl_remove( _rValueName );
}
/** transforms the collection to a sequence of PropertyValues
@return
the number of elements in the sequence
*/
sal_Int32 operator >>= ( ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& _out_rValues ) const;
/** transforms the collection to a sequence of NamedValues
@return
the number of elements in the sequence
*/
sal_Int32 operator >>= ( ::com::sun::star::uno::Sequence< ::com::sun::star::beans::NamedValue >& _out_rValues ) const;
/** transforms the collection into a sequence of PropertyValues
*/
inline ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >
getPropertyValues() const
{
::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue > aValues;
*this >>= aValues;
return aValues;
}
/** transforms the collection into a sequence of NamedValues
*/
inline ::com::sun::star::uno::Sequence< ::com::sun::star::beans::NamedValue >
getNamedValues() const
{
::com::sun::star::uno::Sequence< ::com::sun::star::beans::NamedValue > aValues;
*this >>= aValues;
return aValues;
}
private:
void impl_assign( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& _rArguments );
void impl_assign( const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& _rArguments );
void impl_assign( const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::NamedValue >& _rArguments );
bool get_ensureType(
const ::rtl::OUString& _rValueName,
void* _pValueLocation,
const ::com::sun::star::uno::Type& _rExpectedValueType
) const;
const ::com::sun::star::uno::Any&
impl_get( const ::rtl::OUString& _rValueName ) const;
bool impl_has( const ::rtl::OUString& _rValueName ) const;
bool impl_put( const ::rtl::OUString& _rValueName, const ::com::sun::star::uno::Any& _rValue );
bool impl_remove( const ::rtl::OUString& _rValueName );
};
//........................................................................
} // namespace comphelper
//........................................................................
#endif // COMPHELPER_NAMEDVALUECOLLECTION_HXX
<|endoftext|>
|
<commit_before>/* <plugins/director/Backend.cpp>
*
* This file is part of the x0 web server project and is released under GPL-3.
* http://www.xzero.io/
*
* (c) 2009-2013 Christian Parpart <trapni@gmail.com>
*/
#include "Backend.h"
#include "BackendManager.h"
#include "Director.h"
#include "RequestNotes.h"
#include "HealthMonitor.h"
#if !defined(XZERO_NDEBUG)
# define TRACE(msg...) (this->Logging::debug(msg))
#else
# define TRACE(msg...) do {} while (0)
#endif
using namespace x0;
/**
* Initializes the backend.
*
* \param director The director object to attach this backend to.
* \param name name of this backend (must be unique within given director's backends).
* \param socketSpec backend socket spec (hostname + port, or local unix domain path).
* \param capacity number of requests this backend is capable of handling in parallel.
* \param healthMonitor specialized health-monitor instanciation, which will be owned by this backend.
*/
Backend::Backend(BackendManager* bm,
const std::string& name, const SocketSpec& socketSpec, size_t capacity, HealthMonitor* healthMonitor) :
#ifndef XZERO_NDEBUG
Logging("Backend/%s", name.c_str()),
#endif
manager_(bm),
name_(name),
capacity_(capacity),
load_(),
lock_(),
enabled_(true),
socketSpec_(socketSpec),
healthMonitor_(healthMonitor),
jsonWriteCallback_()
{
pthread_spin_init(&lock_, PTHREAD_PROCESS_PRIVATE);
}
Backend::~Backend()
{
delete healthMonitor_;
pthread_spin_destroy(&lock_);
}
void Backend::log(x0::LogMessage&& msg)
{
msg.addTag(name_);
manager_->log(std::move(msg));
}
size_t Backend::capacity() const
{
return capacity_;
}
void Backend::setCapacity(size_t value)
{
capacity_ = value;
}
void Backend::writeJSON(JsonWriter& json) const
{
static const std::string boolStr[] = { "false", "true" };
json.beginObject()
.name("name")(name_)
.name("capacity")(capacity_)
.name("enabled")(enabled_)
.name("protocol")(protocol());
if (socketSpec_.isInet()) {
json.name("hostname")(socketSpec_.ipaddr().str())
.name("port")(socketSpec_.port());
} else {
json.name("path")(socketSpec_.local());
}
json.name("load")(load_);
if (healthMonitor_) {
json.name("health")(*healthMonitor_);
}
if (jsonWriteCallback_)
jsonWriteCallback_(this, json);
json.endObject();
}
void Backend::setJsonWriteCallback(const std::function<void(const Backend*, JsonWriter&)>& callback)
{
jsonWriteCallback_ = callback;
}
void Backend::clearJsonWriteCallback()
{
jsonWriteCallback_ = std::function<void(const Backend*, JsonWriter&)>();
}
void Backend::setState(HealthState value)
{
if (healthMonitor_) {
healthMonitor_->setState(value);
}
}
/*!
* Tries to processes given request on this backend.
*
* \param r the request to be processed
*
* It only processes the request if this backend is healthy, enabled and the load has not yet reached its capacity.
* It then passes the request to the implementation specific \c process() method. If this fails to initiate
* processing, this backend gets flagged as offline automatically, otherwise the load counters are increased accordingly.
*
* \note <b>MUST</b> be invoked from within the request's worker thread.
*/
SchedulerStatus Backend::tryProcess(HttpRequest* r)
{
SchedulerStatus status = SchedulerStatus::Unavailable;
pthread_spin_lock(&lock_);
if (healthMonitor_ && !healthMonitor_->isOnline())
goto done;
if (!isEnabled())
goto done;
status = SchedulerStatus::Overloaded;
if (capacity_ && load_.current() >= capacity_)
goto done;
status = pass(r);
done:
pthread_spin_unlock(&lock_);
return status;
}
SchedulerStatus Backend::pass(x0::HttpRequest* r)
{
++load_;
r->log(Severity::info, "Processing request by director '%s' backend '%s'.", manager()->name().c_str(), name().c_str());
if (!process(r)) {
setState(HealthState::Offline);
--load_;
return SchedulerStatus::Unavailable;
}
return SchedulerStatus::Success;
}
/**
* Invoked internally when a request has been fully processed.
*
* This decrements the load-statistics, and potentially
* dequeues possibly enqueued requests to take over.
*/
void Backend::release()
{
--load_;
manager_->release(this);
}
/**
* Invoked internally when this backend could not handle this request.
*
* This decrements the load-statistics and potentially
* reschedules the request.
*/
void Backend::reject(x0::HttpRequest* r)
{
--load_;
// and set the backend's health state to offline, since it
// doesn't seem to function properly
setState(HealthState::Offline);
manager_->reject(r);
}
<commit_msg>[plugins] director: better make this log message of severity debug to avoid spamming the logs ;)<commit_after>/* <plugins/director/Backend.cpp>
*
* This file is part of the x0 web server project and is released under GPL-3.
* http://www.xzero.io/
*
* (c) 2009-2013 Christian Parpart <trapni@gmail.com>
*/
#include "Backend.h"
#include "BackendManager.h"
#include "Director.h"
#include "RequestNotes.h"
#include "HealthMonitor.h"
#if !defined(XZERO_NDEBUG)
# define TRACE(msg...) (this->Logging::debug(msg))
#else
# define TRACE(msg...) do {} while (0)
#endif
using namespace x0;
/**
* Initializes the backend.
*
* \param director The director object to attach this backend to.
* \param name name of this backend (must be unique within given director's backends).
* \param socketSpec backend socket spec (hostname + port, or local unix domain path).
* \param capacity number of requests this backend is capable of handling in parallel.
* \param healthMonitor specialized health-monitor instanciation, which will be owned by this backend.
*/
Backend::Backend(BackendManager* bm,
const std::string& name, const SocketSpec& socketSpec, size_t capacity, HealthMonitor* healthMonitor) :
#ifndef XZERO_NDEBUG
Logging("Backend/%s", name.c_str()),
#endif
manager_(bm),
name_(name),
capacity_(capacity),
load_(),
lock_(),
enabled_(true),
socketSpec_(socketSpec),
healthMonitor_(healthMonitor),
jsonWriteCallback_()
{
pthread_spin_init(&lock_, PTHREAD_PROCESS_PRIVATE);
}
Backend::~Backend()
{
delete healthMonitor_;
pthread_spin_destroy(&lock_);
}
void Backend::log(x0::LogMessage&& msg)
{
msg.addTag(name_);
manager_->log(std::move(msg));
}
size_t Backend::capacity() const
{
return capacity_;
}
void Backend::setCapacity(size_t value)
{
capacity_ = value;
}
void Backend::writeJSON(JsonWriter& json) const
{
static const std::string boolStr[] = { "false", "true" };
json.beginObject()
.name("name")(name_)
.name("capacity")(capacity_)
.name("enabled")(enabled_)
.name("protocol")(protocol());
if (socketSpec_.isInet()) {
json.name("hostname")(socketSpec_.ipaddr().str())
.name("port")(socketSpec_.port());
} else {
json.name("path")(socketSpec_.local());
}
json.name("load")(load_);
if (healthMonitor_) {
json.name("health")(*healthMonitor_);
}
if (jsonWriteCallback_)
jsonWriteCallback_(this, json);
json.endObject();
}
void Backend::setJsonWriteCallback(const std::function<void(const Backend*, JsonWriter&)>& callback)
{
jsonWriteCallback_ = callback;
}
void Backend::clearJsonWriteCallback()
{
jsonWriteCallback_ = std::function<void(const Backend*, JsonWriter&)>();
}
void Backend::setState(HealthState value)
{
if (healthMonitor_) {
healthMonitor_->setState(value);
}
}
/*!
* Tries to processes given request on this backend.
*
* \param r the request to be processed
*
* It only processes the request if this backend is healthy, enabled and the load has not yet reached its capacity.
* It then passes the request to the implementation specific \c process() method. If this fails to initiate
* processing, this backend gets flagged as offline automatically, otherwise the load counters are increased accordingly.
*
* \note <b>MUST</b> be invoked from within the request's worker thread.
*/
SchedulerStatus Backend::tryProcess(HttpRequest* r)
{
SchedulerStatus status = SchedulerStatus::Unavailable;
pthread_spin_lock(&lock_);
if (healthMonitor_ && !healthMonitor_->isOnline())
goto done;
if (!isEnabled())
goto done;
status = SchedulerStatus::Overloaded;
if (capacity_ && load_.current() >= capacity_)
goto done;
status = pass(r);
done:
pthread_spin_unlock(&lock_);
return status;
}
SchedulerStatus Backend::pass(x0::HttpRequest* r)
{
++load_;
r->log(Severity::debug, "Processing request by director '%s' backend '%s'.", manager()->name().c_str(), name().c_str());
if (!process(r)) {
setState(HealthState::Offline);
--load_;
return SchedulerStatus::Unavailable;
}
return SchedulerStatus::Success;
}
/**
* Invoked internally when a request has been fully processed.
*
* This decrements the load-statistics, and potentially
* dequeues possibly enqueued requests to take over.
*/
void Backend::release()
{
--load_;
manager_->release(this);
}
/**
* Invoked internally when this backend could not handle this request.
*
* This decrements the load-statistics and potentially
* reschedules the request.
*/
void Backend::reject(x0::HttpRequest* r)
{
--load_;
// and set the backend's health state to offline, since it
// doesn't seem to function properly
setState(HealthState::Offline);
manager_->reject(r);
}
<|endoftext|>
|
<commit_before>#include <assert.h>
#include <sstream>
#include <limits> // for epsilon
#include <cmath> // for fabs
#include "float-semiring.h"
// std::map in polynomial.h wants this constructor...
FloatSemiring::FloatSemiring()
{
this->val = 0;
}
FloatSemiring::FloatSemiring(const float val)
{
assert(val >= 0);
this->val = val;
}
FloatSemiring::~FloatSemiring()
{
}
FloatSemiring FloatSemiring::operator+(const FloatSemiring& elem) const
{
return FloatSemiring(this->val + elem.val);
}
FloatSemiring FloatSemiring::operator*(const FloatSemiring& elem) const
{
return FloatSemiring(this->val * elem.val);
}
bool FloatSemiring::operator==(const FloatSemiring& elem) const
{
// comparing floating point has to be done like this. (see Knuth TAoCP Vol.2 p. 233)
return std::fabs(this->val - elem.val) <= std::numeric_limits<float>::epsilon() * std::min(std::fabs(this->val), std::fabs(elem.val));
}
FloatSemiring FloatSemiring::star() const
{
// beware of the 1-Element (TODO: inf-Element!)
return FloatSemiring(1/(1-this->val));
}
FloatSemiring FloatSemiring::null()
{
if(!FloatSemiring::elem_null)
FloatSemiring::elem_null = std::shared_ptr<FloatSemiring>(new FloatSemiring(0));
return *FloatSemiring::elem_null;
}
FloatSemiring FloatSemiring::one()
{
if(!FloatSemiring::elem_one)
FloatSemiring::elem_one = std::shared_ptr<FloatSemiring>(new FloatSemiring(1));
return *FloatSemiring::elem_one;
}
std::string FloatSemiring::string() const
{
std::stringstream ss;
ss << this->val;
return ss.str();
}
bool FloatSemiring::is_idempotent = false;
bool FloatSemiring::is_commutative = true;
std::shared_ptr<FloatSemiring> FloatSemiring::elem_null;
std::shared_ptr<FloatSemiring> FloatSemiring::elem_one;
<commit_msg>float semiring already returns inf for 1*<commit_after>#include <assert.h>
#include <sstream>
#include <limits> // for epsilon
#include <cmath> // for fabs
#include "float-semiring.h"
// std::map in polynomial.h wants this constructor...
FloatSemiring::FloatSemiring()
{
this->val = 0;
}
FloatSemiring::FloatSemiring(const float val)
{
assert(val >= 0);
this->val = val;
}
FloatSemiring::~FloatSemiring()
{
}
FloatSemiring FloatSemiring::operator+(const FloatSemiring& elem) const
{
return FloatSemiring(this->val + elem.val);
}
FloatSemiring FloatSemiring::operator*(const FloatSemiring& elem) const
{
return FloatSemiring(this->val * elem.val);
}
bool FloatSemiring::operator==(const FloatSemiring& elem) const
{
// comparing floating point has to be done like this. (see Knuth TAoCP Vol.2 p. 233)
return std::fabs(this->val - elem.val) <= std::numeric_limits<float>::epsilon() * std::min(std::fabs(this->val), std::fabs(elem.val));
}
FloatSemiring FloatSemiring::star() const
{
// if this->val == 1 this returns inf
return FloatSemiring(1/(1-this->val));
}
FloatSemiring FloatSemiring::null()
{
if(!FloatSemiring::elem_null)
FloatSemiring::elem_null = std::shared_ptr<FloatSemiring>(new FloatSemiring(0));
return *FloatSemiring::elem_null;
}
FloatSemiring FloatSemiring::one()
{
if(!FloatSemiring::elem_one)
FloatSemiring::elem_one = std::shared_ptr<FloatSemiring>(new FloatSemiring(1));
return *FloatSemiring::elem_one;
}
std::string FloatSemiring::string() const
{
std::stringstream ss;
ss << this->val;
return ss.str();
}
bool FloatSemiring::is_idempotent = false;
bool FloatSemiring::is_commutative = true;
std::shared_ptr<FloatSemiring> FloatSemiring::elem_null;
std::shared_ptr<FloatSemiring> FloatSemiring::elem_one;
<|endoftext|>
|
<commit_before>/**
Copyright (c) 2017, Philip Deegan.
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 Philip Deegan 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.
*/
// This file is included by other files and is not in itself syntactically
// correct.
// bool kul::this_thread::main(){
const std::tr1::shared_ptr<void> hThreadSnapshot(CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0),
CloseHandle);
if (hThreadSnapshot.get() == INVALID_HANDLE_VALUE)
KEXCEPT(kul::threading::Exception, "GetMainThreadId failed");
THREADENTRY32 tEntry;
tEntry.dwSize = sizeof(THREADENTRY32);
DWORD result = 0;
DWORD currentPID = GetCurrentProcessId();
for (BOOL success = Thread32First(hThreadSnapshot.get(), &tEntry);
!result && success && GetLastError() != ERROR_NO_MORE_FILES;
success = Thread32Next(hThreadSnapshot.get(), &tEntry))
if (tEntry.th32OwnerProcessID == currentPID) result = tEntry.th32ThreadID;
std::stringstream ss;
ss << std::this_thread::get_id();
return std::to_string(result) == ss.str();
// }
<commit_msg>tr what now?<commit_after>/**
Copyright (c) 2017, Philip Deegan.
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 Philip Deegan 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.
*/
// This file is included by other files and is not in itself syntactically
// correct.
// bool kul::this_thread::main(){
const std::shared_ptr<void> hThreadSnapshot(CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0),
CloseHandle);
if (hThreadSnapshot.get() == INVALID_HANDLE_VALUE)
KEXCEPT(kul::threading::Exception, "GetMainThreadId failed");
THREADENTRY32 tEntry;
tEntry.dwSize = sizeof(THREADENTRY32);
DWORD result = 0;
DWORD currentPID = GetCurrentProcessId();
for (BOOL success = Thread32First(hThreadSnapshot.get(), &tEntry);
!result && success && GetLastError() != ERROR_NO_MORE_FILES;
success = Thread32Next(hThreadSnapshot.get(), &tEntry))
if (tEntry.th32OwnerProcessID == currentPID) result = tEntry.th32ThreadID;
std::stringstream ss;
ss << std::this_thread::get_id();
return std::to_string(result) == ss.str();
// }
<|endoftext|>
|
<commit_before>#include "stdafx.h"
#include "logging.h"
#ifndef LOG_FILE_NAME
#define LOG_FILE_NAME "output"
#endif // LOG_FILE_NAME
void InitLog() {
namespace expressions = boost::log::expressions;
namespace sinks = boost::log::sinks;
namespace keywords = boost::log::keywords;
namespace trivial = boost::log::trivial;
namespace attributes = boost::log::attributes;
boost::shared_ptr<boost::log::core> log_core_ = boost::log::core::get();
#ifdef LOG_TO_FILE
// init sink1
typedef sinks::synchronous_sink<sinks::text_file_backend> TextSink;
boost::shared_ptr<sinks::text_file_backend> backend1 =
boost::make_shared<sinks::text_file_backend>(
// log filename pattern
keywords::file_name = std::string(LOG_FILE_NAME) +
"_%Y-%m-%d_%H-%M-%S.%N.log",
// rotate log when reaching 4MiB
keywords::rotation_size = 4 * 1024 * 1024,
// or at midnight
keywords::time_based_rotation =
sinks::file::rotation_at_time_point(0, 0, 0),
// keep at least 3GiB free space
keywords::min_free_space = 3 * 1024 * 1024);
backend1->auto_flush(true);
boost::shared_ptr<TextSink> sink1(new TextSink(backend1));
sink1->set_formatter(
expressions::format("%1%\t%2%\t%3%\t%4%:\n\t%5%")
% expressions::format_date_time<boost::posix_time::ptime>("TimeStamp",
"%Y-%m-%d %H:%M:%S")
% expressions::attr<trivial::severity_level>("Severity")
% expressions::attr<attributes::current_thread_id::value_type>("ThreadID")
% expressions::format_named_scope("Scopes",
boost::log::keywords::format = "%n (%f:%l)",
boost::log::keywords::iteration = expressions::forward,
boost::log::keywords::depth = 2)
% expressions::smessage
);
//#ifdef _DEBUG
// sink1->set_filter(trivial::severity >= trivial::trace);
//#else
// sink1->set_filter(trivial::severity >= trivial::info);
//#endif
log_core_->add_sink(sink1);
#endif
// init sink2
typedef sinks::synchronous_sink<sinks::text_ostream_backend> StreamSink;
boost::shared_ptr<StreamSink> sink2 = boost::make_shared<StreamSink>();
sink2->set_formatter(
expressions::format("%1%: %2%")
% expressions::format_date_time<boost::posix_time::ptime>("TimeStamp",
"%H:%M:%S")
% expressions::smessage
);
boost::shared_ptr<std::ostream> stream(&std::clog, boost::empty_deleter());
sink2->locked_backend()->add_stream(stream);
#ifdef _DEBUG
sink2->set_filter(trivial::severity >= trivial::debug);
#else
sink2->set_filter(trivial::severity >= trivial::info);
#endif
log_core_->add_sink(sink2);
boost::log::add_common_attributes();
log_core_->add_global_attribute("Scopes", attributes::named_scope());
}
void DeInitLog() {
boost::log::core::get()->remove_all_sinks();
}
<commit_msg>log rotate size = 16MB<commit_after>#include "stdafx.h"
#include "logging.h"
#ifndef LOG_FILE_NAME
#define LOG_FILE_NAME "output"
#endif // LOG_FILE_NAME
void InitLog() {
namespace expressions = boost::log::expressions;
namespace sinks = boost::log::sinks;
namespace keywords = boost::log::keywords;
namespace trivial = boost::log::trivial;
namespace attributes = boost::log::attributes;
boost::shared_ptr<boost::log::core> log_core_ = boost::log::core::get();
#ifdef LOG_TO_FILE
// init sink1
typedef sinks::synchronous_sink<sinks::text_file_backend> TextSink;
boost::shared_ptr<sinks::text_file_backend> backend1 =
boost::make_shared<sinks::text_file_backend>(
// log filename pattern
keywords::file_name = std::string(LOG_FILE_NAME) +
"_%Y-%m-%d_%H-%M-%S.%N.log",
// rotate log when reaching 16MiB
keywords::rotation_size = 16 * 1024 * 1024,
// or at midnight
keywords::time_based_rotation =
sinks::file::rotation_at_time_point(0, 0, 0),
// keep at least 3GiB free space
keywords::min_free_space = 3 * 1024 * 1024);
backend1->auto_flush(true);
boost::shared_ptr<TextSink> sink1(new TextSink(backend1));
sink1->set_formatter(
expressions::format("%1%\t%2%\t%3%\t%4%:\n\t%5%")
% expressions::format_date_time<boost::posix_time::ptime>("TimeStamp",
"%Y-%m-%d %H:%M:%S")
% expressions::attr<trivial::severity_level>("Severity")
% expressions::attr<attributes::current_thread_id::value_type>("ThreadID")
% expressions::format_named_scope("Scopes",
boost::log::keywords::format = "%n (%f:%l)",
boost::log::keywords::iteration = expressions::forward,
boost::log::keywords::depth = 2)
% expressions::smessage
);
//#ifdef _DEBUG
// sink1->set_filter(trivial::severity >= trivial::trace);
//#else
// sink1->set_filter(trivial::severity >= trivial::info);
//#endif
log_core_->add_sink(sink1);
#endif
// init sink2
typedef sinks::synchronous_sink<sinks::text_ostream_backend> StreamSink;
boost::shared_ptr<StreamSink> sink2 = boost::make_shared<StreamSink>();
sink2->set_formatter(
expressions::format("%1%: %2%")
% expressions::format_date_time<boost::posix_time::ptime>("TimeStamp",
"%H:%M:%S")
% expressions::smessage
);
boost::shared_ptr<std::ostream> stream(&std::clog, boost::empty_deleter());
sink2->locked_backend()->add_stream(stream);
#ifdef _DEBUG
sink2->set_filter(trivial::severity >= trivial::debug);
#else
sink2->set_filter(trivial::severity >= trivial::info);
#endif
log_core_->add_sink(sink2);
boost::log::add_common_attributes();
log_core_->add_global_attribute("Scopes", attributes::named_scope());
}
void DeInitLog() {
boost::log::core::get()->remove_all_sinks();
}
<|endoftext|>
|
<commit_before>#include "cpanel.h"
#include "settings/csettings.h"
#include "settings.h"
#include "filesystemhelperfunctions.h"
#include "QtCoreIncludes"
#include <assert.h>
#include <time.h>
#include <limits>
CPanel::CPanel(Panel position) :
_panelPosition(position)
{
CSettings s;
const QStringList historyList(s.value(_panelPosition == RightPanel ? KEY_HISTORY_R : KEY_HISTORY_L).toStringList());
_history.addLatest(historyList.toVector().toStdVector());
setPath(s.value(_panelPosition == LeftPanel ? KEY_LPANEL_PATH : KEY_RPANEL_PATH, QDir::root().absolutePath()).toString(), refreshCauseOther);
}
FileOperationResultCode CPanel::setPath(const QString &path, FileListRefreshCause operation)
{
#if defined __linux__ || defined __APPLE__
const QString posixPath(path.contains("~") ? QString(path).replace("~", getenv("HOME")) : path);
#elif defined _WIN32
const QString posixPath(toPosixSeparators(path));
#else
#error "Not implemented"
#endif
_currentDisplayMode = NormalMode;
std::unique_lock<std::recursive_mutex> locker(_fileListAndCurrentDirMutex);
const QString oldPath = _currentDirObject.fullAbsolutePath();
const auto pathGraph = CFileSystemObject::pathHierarchy(posixPath);
bool pathSet = false;
for (const auto& candidatePath: pathGraph)
{
_currentDirObject.setPath(candidatePath);
pathSet = _currentDirObject.exists() && ! _currentDirObject.qDir().entryList().isEmpty(); // No dot and dotdot on Linux means the dir is not accessible
if (pathSet)
break;
}
if (!pathSet)
{
if (QFileInfo(oldPath).exists())
_currentDirObject.setPath(oldPath);
else
{
QString pathToSet;
for (auto it = history().rbegin() + (history().size() - 1 - history().currentIndex()); it != history().rend(); ++it)
{
if (QFileInfo(*it).exists())
{
pathToSet = *it;
break;
}
}
if (pathToSet.isEmpty())
pathToSet = QDir::rootPath();
_currentDirObject.setPath(pathToSet);
}
}
const QString newPath = _currentDirObject.fullAbsolutePath();
// History management
if (toPosixSeparators(_history.currentItem()) != toPosixSeparators(newPath))
{
_history.addLatest(newPath);
CSettings().setValue(_panelPosition == RightPanel ? KEY_HISTORY_R : KEY_HISTORY_L, QVariant(QStringList::fromVector(QVector<QString>::fromStdVector(_history.list()))));
}
CSettings().setValue(_panelPosition == LeftPanel ? KEY_LPANEL_PATH : KEY_RPANEL_PATH, newPath);
_watcher = std::make_shared<QFileSystemWatcher>();
#if QT_VERSION >= QT_VERSION_CHECK (5,0,0)
const QString watchPath(newPath);
#else
const QString watchPath(posixPath);
#endif
if (_watcher->addPath(watchPath) == false)
qDebug() << __FUNCTION__ << "Error adding path" << watchPath << "to QFileSystemWatcher";
connect(_watcher.get(), SIGNAL(directoryChanged(QString)), SLOT(contentsChanged(QString)));
connect(_watcher.get(), SIGNAL(fileChanged(QString)), SLOT(contentsChanged(QString)));
connect(_watcher.get(), SIGNAL(objectNameChanged(QString)), SLOT(contentsChanged(QString)));
// Finding hash of an item corresponding to path
for (const auto& item : _items)
{
const QString itemPath = toPosixSeparators(item.second.fullAbsolutePath());
if (posixPath == itemPath && toPosixSeparators(item.second.parentDirPath()) != itemPath)
{
setCurrentItemInFolder(item.second.parentDirPath(), item.second.properties().hash);
break;
}
}
locker.unlock();
refreshFileList(pathSet ? operation : refreshCauseOther);
return pathSet ? rcOk : rcDirNotAccessible;
}
// Navigates up the directory tree
void CPanel::navigateUp()
{
if (_currentDisplayMode != NormalMode)
setPath(currentDirPathPosix(), refreshCauseOther);
else
{
QDir tmpDir(currentDirPathPosix());
if (tmpDir.cdUp())
setPath(tmpDir.absolutePath(), refreshCauseCdUp);
else
sendContentsChangedNotification(refreshCauseOther);
}
}
// Go to the previous location from history
bool CPanel::navigateBack()
{
if (_currentDisplayMode != NormalMode)
return setPath(currentDirPathPosix(), refreshCauseOther) == rcOk;
else if (!_history.empty())
return setPath(_history.navigateBack(), refreshCauseOther) == rcOk;
else
return false;
}
// Go to the next location from history, if any
bool CPanel::navigateForward()
{
if (_currentDisplayMode == NormalMode && !_history.empty())
return setPath(_history.navigateForward(), refreshCauseOther) == rcOk;
return false;
}
const CHistoryList<QString>& CPanel::history() const
{
return _history;
}
void CPanel::showAllFilesFromCurrentFolderAndBelow()
{
_currentDisplayMode = AllObjectsMode;
_watcher.reset();
_refreshFileListTask.exec([this]() {
std::unique_lock<std::recursive_mutex> locker(_fileListAndCurrentDirMutex);
const QString path = _currentDirObject.fullAbsolutePath();
locker.unlock();
auto items = recurseDirectoryItems(path, false);
locker.lock();
_items.clear();
const bool showHiddenFiles = CSettings().value(KEY_INTERFACE_SHOW_HIDDEN_FILES, true).toBool();
for (const auto& item : items)
{
if (item.exists() && (showHiddenFiles || !item.isHidden()))
_items[item.hash()] = item;
}
sendContentsChangedNotification(refreshCauseOther);
});
}
// Info on the dir this panel is currently set to
QString CPanel::currentDirPathNative() const
{
std::lock_guard<std::recursive_mutex> locker(_fileListAndCurrentDirMutex);
return toNativeSeparators(_currentDirObject.fullAbsolutePath());
}
QString CPanel::currentDirPathPosix() const
{
std::lock_guard<std::recursive_mutex> locker(_fileListAndCurrentDirMutex);
return _currentDirObject.fullAbsolutePath();
}
QString CPanel::currentDirName() const
{
std::lock_guard<std::recursive_mutex> locker(_fileListAndCurrentDirMutex);
return toNativeSeparators(_currentDirObject.fullName());
}
void CPanel::setCurrentItemInFolder(const QString& dir, qulonglong currentItemHash)
{
_cursorPosForFolder[toPosixSeparators(dir)] = currentItemHash;
}
qulonglong CPanel::currentItemInFolder(const QString &dir) const
{
const auto it = _cursorPosForFolder.find(toPosixSeparators(dir));
return it == _cursorPosForFolder.end() ? 0 : it->second;
}
// Enumerates objects in the current directory
void CPanel::refreshFileList(FileListRefreshCause operation)
{
_refreshFileListTask.exec([this, operation]() {
const time_t start = clock();
QFileInfoList list;
sendItemDiscoveryProgressNotification(_currentDirObject.hash(), 0);
{
std::lock_guard<std::recursive_mutex> locker(_fileListAndCurrentDirMutex);
list = _currentDirObject.qDir().entryInfoList(QDir::Dirs | QDir::Files | QDir::NoDot | QDir::Hidden | QDir::System);
qDebug() << "Getting file list for" << _currentDirObject.fullAbsolutePath() << "(" << list.size() << "items ) took" << (clock() - start) * 1000 / CLOCKS_PER_SEC << "ms";
_items.clear();
if (list.empty())
{
setPath(_currentDirObject.fullAbsolutePath(), operation); // setPath will itself find the closest best folder to set instead
return;
}
}
sendItemDiscoveryProgressNotification(_currentDirObject.hash(), 20);
const bool showHiddenFiles = CSettings().value(KEY_INTERFACE_SHOW_HIDDEN_FILES, true).toBool();
std::vector<CFileSystemObject> objectsList;
const size_t numItemsFound = list.size();
objectsList.reserve(numItemsFound);
for (int i = 0; i < numItemsFound; ++i)
{
objectsList.emplace_back(list[i]);
sendItemDiscoveryProgressNotification(_currentDirObject.hash(), 20 + 80 * i / numItemsFound);
}
{
std::lock_guard<std::recursive_mutex> locker(_fileListAndCurrentDirMutex);
for (const auto& object : objectsList)
{
if (object.exists() && (showHiddenFiles || !object.isHidden()))
_items[object.hash()] = object;
}
qDebug() << "Directory:" << _currentDirObject.fullAbsolutePath() << "(" << _items.size() << "items ) indexed in" << (clock() - start) * 1000 / CLOCKS_PER_SEC << "ms";
}
sendItemDiscoveryProgressNotification(_currentDirObject.hash(), 100);
sendContentsChangedNotification(operation);
});
}
// Returns the current list of objects on this panel
std::map<qulonglong, CFileSystemObject> CPanel::list() const
{
std::lock_guard<std::recursive_mutex> locker(_fileListAndCurrentDirMutex);
return _items;
}
bool CPanel::itemHashExists(const qulonglong hash) const
{
std::lock_guard<std::recursive_mutex> locker(_fileListAndCurrentDirMutex);
return _items.count(hash) > 0;
}
CFileSystemObject CPanel::itemByHash(qulonglong hash) const
{
std::lock_guard<std::recursive_mutex> locker(_fileListAndCurrentDirMutex);
const auto it = _items.find(hash);
return it != _items.end() ? it->second : CFileSystemObject();
}
// Calculates total size for the specified objects
FilesystemObjectsStatistics CPanel::calculateStatistics(const std::vector<qulonglong>& hashes)
{
if (hashes.empty())
return FilesystemObjectsStatistics();
sendItemDiscoveryProgressNotification(0, 0);
FilesystemObjectsStatistics stats;
const size_t numItems = hashes.size();
for(size_t i = 0; i < numItems; ++i)
{
CFileSystemObject item = itemByHash(hashes[i]);
if (item.isDir())
{
++stats.folders;
std::vector <CFileSystemObject> objects = recurseDirectoryItems(item.fullAbsolutePath(), false);
for (auto& subItem: objects)
{
if (subItem.isFile())
++stats.files;
else if (subItem.isDir())
++stats.folders;
stats.occupiedSpace += subItem.size();
}
}
else if (item.isFile())
{
++stats.files;
stats.occupiedSpace += item.size();
}
sendItemDiscoveryProgressNotification(0, i * 100 / numItems);
}
sendItemDiscoveryProgressNotification(0, 100);
return stats;
}
// Calculates directory size, stores it in the corresponding CFileSystemObject and sends data change notification
void CPanel::displayDirSize(qulonglong dirHash)
{
std::lock_guard<std::recursive_mutex> locker(_fileListAndCurrentDirMutex);
const auto it = _items.find(dirHash);
if (it == _items.end())
{
assert(false);
return;
}
if (it->second.isDir())
{
const FilesystemObjectsStatistics stats = calculateStatistics(std::vector<qulonglong>(1, dirHash));
it->second.setDirSize(stats.occupiedSpace);
sendContentsChangedNotification(refreshCauseOther);
}
}
void CPanel::sendContentsChangedNotification(FileListRefreshCause operation) const
{
_uiThreadQueue.enqueue([this, operation]() {
for (auto listener : _panelContentsChangedListeners)
listener->panelContentsChanged(_panelPosition, operation);
}, 0);
}
void CPanel::sendItemDiscoveryProgressNotification(qulonglong itemHash, size_t progress) const
{
_uiThreadQueue.enqueue([this, itemHash, progress]() {
for (auto listener : _panelContentsChangedListeners)
listener->itemDiscoveryInProgress(_panelPosition, itemHash, progress);
}, 1);
}
// Settings have changed
void CPanel::settingsChanged()
{
}
void CPanel::uiThreadTimerTick()
{
_uiThreadQueue.exec();
}
void CPanel::contentsChanged(QString /*path*/)
{
refreshFileList(refreshCauseOther);
}
void CPanel::addPanelContentsChangedListener(PanelContentsChangedListener *listener)
{
assert(std::find(_panelContentsChangedListeners.begin(), _panelContentsChangedListeners.end(), listener) == _panelContentsChangedListeners.end()); // Why would we want to set the same listener twice? That'd probably be a mistake.
_panelContentsChangedListeners.push_back(listener);
sendContentsChangedNotification(refreshCauseOther);
}
<commit_msg>CPanel::setPath progress notifications removed<commit_after>#include "cpanel.h"
#include "settings/csettings.h"
#include "settings.h"
#include "filesystemhelperfunctions.h"
#include "QtCoreIncludes"
#include <assert.h>
#include <time.h>
#include <limits>
CPanel::CPanel(Panel position) :
_panelPosition(position)
{
CSettings s;
const QStringList historyList(s.value(_panelPosition == RightPanel ? KEY_HISTORY_R : KEY_HISTORY_L).toStringList());
_history.addLatest(historyList.toVector().toStdVector());
setPath(s.value(_panelPosition == LeftPanel ? KEY_LPANEL_PATH : KEY_RPANEL_PATH, QDir::root().absolutePath()).toString(), refreshCauseOther);
}
FileOperationResultCode CPanel::setPath(const QString &path, FileListRefreshCause operation)
{
#if defined __linux__ || defined __APPLE__
const QString posixPath(path.contains("~") ? QString(path).replace("~", getenv("HOME")) : path);
#elif defined _WIN32
const QString posixPath(toPosixSeparators(path));
#else
#error "Not implemented"
#endif
_currentDisplayMode = NormalMode;
std::unique_lock<std::recursive_mutex> locker(_fileListAndCurrentDirMutex);
const QString oldPath = _currentDirObject.fullAbsolutePath();
const auto pathGraph = CFileSystemObject::pathHierarchy(posixPath);
bool pathSet = false;
for (const auto& candidatePath: pathGraph)
{
_currentDirObject.setPath(candidatePath);
pathSet = _currentDirObject.exists() && ! _currentDirObject.qDir().entryList().isEmpty(); // No dot and dotdot on Linux means the dir is not accessible
if (pathSet)
break;
}
if (!pathSet)
{
if (QFileInfo(oldPath).exists())
_currentDirObject.setPath(oldPath);
else
{
QString pathToSet;
for (auto it = history().rbegin() + (history().size() - 1 - history().currentIndex()); it != history().rend(); ++it)
{
if (QFileInfo(*it).exists())
{
pathToSet = *it;
break;
}
}
if (pathToSet.isEmpty())
pathToSet = QDir::rootPath();
_currentDirObject.setPath(pathToSet);
}
}
const QString newPath = _currentDirObject.fullAbsolutePath();
// History management
if (toPosixSeparators(_history.currentItem()) != toPosixSeparators(newPath))
{
_history.addLatest(newPath);
CSettings().setValue(_panelPosition == RightPanel ? KEY_HISTORY_R : KEY_HISTORY_L, QVariant(QStringList::fromVector(QVector<QString>::fromStdVector(_history.list()))));
}
CSettings().setValue(_panelPosition == LeftPanel ? KEY_LPANEL_PATH : KEY_RPANEL_PATH, newPath);
_watcher = std::make_shared<QFileSystemWatcher>();
#if QT_VERSION >= QT_VERSION_CHECK (5,0,0)
const QString watchPath(newPath);
#else
const QString watchPath(posixPath);
#endif
if (_watcher->addPath(watchPath) == false)
qDebug() << __FUNCTION__ << "Error adding path" << watchPath << "to QFileSystemWatcher";
connect(_watcher.get(), SIGNAL(directoryChanged(QString)), SLOT(contentsChanged(QString)));
connect(_watcher.get(), SIGNAL(fileChanged(QString)), SLOT(contentsChanged(QString)));
connect(_watcher.get(), SIGNAL(objectNameChanged(QString)), SLOT(contentsChanged(QString)));
// Finding hash of an item corresponding to path
for (const auto& item : _items)
{
const QString itemPath = toPosixSeparators(item.second.fullAbsolutePath());
if (posixPath == itemPath && toPosixSeparators(item.second.parentDirPath()) != itemPath)
{
setCurrentItemInFolder(item.second.parentDirPath(), item.second.properties().hash);
break;
}
}
locker.unlock();
refreshFileList(pathSet ? operation : refreshCauseOther);
return pathSet ? rcOk : rcDirNotAccessible;
}
// Navigates up the directory tree
void CPanel::navigateUp()
{
if (_currentDisplayMode != NormalMode)
setPath(currentDirPathPosix(), refreshCauseOther);
else
{
QDir tmpDir(currentDirPathPosix());
if (tmpDir.cdUp())
setPath(tmpDir.absolutePath(), refreshCauseCdUp);
else
sendContentsChangedNotification(refreshCauseOther);
}
}
// Go to the previous location from history
bool CPanel::navigateBack()
{
if (_currentDisplayMode != NormalMode)
return setPath(currentDirPathPosix(), refreshCauseOther) == rcOk;
else if (!_history.empty())
return setPath(_history.navigateBack(), refreshCauseOther) == rcOk;
else
return false;
}
// Go to the next location from history, if any
bool CPanel::navigateForward()
{
if (_currentDisplayMode == NormalMode && !_history.empty())
return setPath(_history.navigateForward(), refreshCauseOther) == rcOk;
return false;
}
const CHistoryList<QString>& CPanel::history() const
{
return _history;
}
void CPanel::showAllFilesFromCurrentFolderAndBelow()
{
_currentDisplayMode = AllObjectsMode;
_watcher.reset();
_refreshFileListTask.exec([this]() {
std::unique_lock<std::recursive_mutex> locker(_fileListAndCurrentDirMutex);
const QString path = _currentDirObject.fullAbsolutePath();
locker.unlock();
auto items = recurseDirectoryItems(path, false);
locker.lock();
_items.clear();
const bool showHiddenFiles = CSettings().value(KEY_INTERFACE_SHOW_HIDDEN_FILES, true).toBool();
for (const auto& item : items)
{
if (item.exists() && (showHiddenFiles || !item.isHidden()))
_items[item.hash()] = item;
}
sendContentsChangedNotification(refreshCauseOther);
});
}
// Info on the dir this panel is currently set to
QString CPanel::currentDirPathNative() const
{
std::lock_guard<std::recursive_mutex> locker(_fileListAndCurrentDirMutex);
return toNativeSeparators(_currentDirObject.fullAbsolutePath());
}
QString CPanel::currentDirPathPosix() const
{
std::lock_guard<std::recursive_mutex> locker(_fileListAndCurrentDirMutex);
return _currentDirObject.fullAbsolutePath();
}
QString CPanel::currentDirName() const
{
std::lock_guard<std::recursive_mutex> locker(_fileListAndCurrentDirMutex);
return toNativeSeparators(_currentDirObject.fullName());
}
void CPanel::setCurrentItemInFolder(const QString& dir, qulonglong currentItemHash)
{
_cursorPosForFolder[toPosixSeparators(dir)] = currentItemHash;
}
qulonglong CPanel::currentItemInFolder(const QString &dir) const
{
const auto it = _cursorPosForFolder.find(toPosixSeparators(dir));
return it == _cursorPosForFolder.end() ? 0 : it->second;
}
// Enumerates objects in the current directory
void CPanel::refreshFileList(FileListRefreshCause operation)
{
_refreshFileListTask.exec([this, operation]() {
const time_t start = clock();
QFileInfoList list;
{
std::lock_guard<std::recursive_mutex> locker(_fileListAndCurrentDirMutex);
list = _currentDirObject.qDir().entryInfoList(QDir::Dirs | QDir::Files | QDir::NoDot | QDir::Hidden | QDir::System);
qDebug() << "Getting file list for" << _currentDirObject.fullAbsolutePath() << "(" << list.size() << "items ) took" << (clock() - start) * 1000 / CLOCKS_PER_SEC << "ms";
_items.clear();
if (list.empty())
{
setPath(_currentDirObject.fullAbsolutePath(), operation); // setPath will itself find the closest best folder to set instead
return;
}
}
const bool showHiddenFiles = CSettings().value(KEY_INTERFACE_SHOW_HIDDEN_FILES, true).toBool();
std::vector<CFileSystemObject> objectsList;
const size_t numItemsFound = list.size();
objectsList.reserve(numItemsFound);
for (int i = 0; i < numItemsFound; ++i)
{
objectsList.emplace_back(list[i]);
sendItemDiscoveryProgressNotification(_currentDirObject.hash(), 20 + 80 * i / numItemsFound);
}
{
std::lock_guard<std::recursive_mutex> locker(_fileListAndCurrentDirMutex);
for (const auto& object : objectsList)
{
if (object.exists() && (showHiddenFiles || !object.isHidden()))
_items[object.hash()] = object;
}
qDebug() << "Directory:" << _currentDirObject.fullAbsolutePath() << "(" << _items.size() << "items ) indexed in" << (clock() - start) * 1000 / CLOCKS_PER_SEC << "ms";
}
sendContentsChangedNotification(operation);
});
}
// Returns the current list of objects on this panel
std::map<qulonglong, CFileSystemObject> CPanel::list() const
{
std::lock_guard<std::recursive_mutex> locker(_fileListAndCurrentDirMutex);
return _items;
}
bool CPanel::itemHashExists(const qulonglong hash) const
{
std::lock_guard<std::recursive_mutex> locker(_fileListAndCurrentDirMutex);
return _items.count(hash) > 0;
}
CFileSystemObject CPanel::itemByHash(qulonglong hash) const
{
std::lock_guard<std::recursive_mutex> locker(_fileListAndCurrentDirMutex);
const auto it = _items.find(hash);
return it != _items.end() ? it->second : CFileSystemObject();
}
// Calculates total size for the specified objects
FilesystemObjectsStatistics CPanel::calculateStatistics(const std::vector<qulonglong>& hashes)
{
if (hashes.empty())
return FilesystemObjectsStatistics();
sendItemDiscoveryProgressNotification(0, 0);
FilesystemObjectsStatistics stats;
const size_t numItems = hashes.size();
for(size_t i = 0; i < numItems; ++i)
{
CFileSystemObject item = itemByHash(hashes[i]);
if (item.isDir())
{
++stats.folders;
std::vector <CFileSystemObject> objects = recurseDirectoryItems(item.fullAbsolutePath(), false);
for (auto& subItem: objects)
{
if (subItem.isFile())
++stats.files;
else if (subItem.isDir())
++stats.folders;
stats.occupiedSpace += subItem.size();
}
}
else if (item.isFile())
{
++stats.files;
stats.occupiedSpace += item.size();
}
sendItemDiscoveryProgressNotification(0, i * 100 / numItems);
}
sendItemDiscoveryProgressNotification(0, 100);
return stats;
}
// Calculates directory size, stores it in the corresponding CFileSystemObject and sends data change notification
void CPanel::displayDirSize(qulonglong dirHash)
{
std::lock_guard<std::recursive_mutex> locker(_fileListAndCurrentDirMutex);
const auto it = _items.find(dirHash);
if (it == _items.end())
{
assert(false);
return;
}
if (it->second.isDir())
{
const FilesystemObjectsStatistics stats = calculateStatistics(std::vector<qulonglong>(1, dirHash));
it->second.setDirSize(stats.occupiedSpace);
sendContentsChangedNotification(refreshCauseOther);
}
}
void CPanel::sendContentsChangedNotification(FileListRefreshCause operation) const
{
_uiThreadQueue.enqueue([this, operation]() {
for (auto listener : _panelContentsChangedListeners)
listener->panelContentsChanged(_panelPosition, operation);
}, 0);
}
void CPanel::sendItemDiscoveryProgressNotification(qulonglong itemHash, size_t progress) const
{
_uiThreadQueue.enqueue([this, itemHash, progress]() {
for (auto listener : _panelContentsChangedListeners)
listener->itemDiscoveryInProgress(_panelPosition, itemHash, progress);
}, 1);
}
// Settings have changed
void CPanel::settingsChanged()
{
}
void CPanel::uiThreadTimerTick()
{
_uiThreadQueue.exec();
}
void CPanel::contentsChanged(QString /*path*/)
{
refreshFileList(refreshCauseOther);
}
void CPanel::addPanelContentsChangedListener(PanelContentsChangedListener *listener)
{
assert(std::find(_panelContentsChangedListeners.begin(), _panelContentsChangedListeners.end(), listener) == _panelContentsChangedListeners.end()); // Why would we want to set the same listener twice? That'd probably be a mistake.
_panelContentsChangedListeners.push_back(listener);
sendContentsChangedNotification(refreshCauseOther);
}
<|endoftext|>
|
<commit_before>#define BOOST_TEST_MAIN
#if !defined( WIN32 )
#define BOOST_TEST_DYN_LINK
#endif
/**
* Boost.test causes the following warning under GCC
* error: base class 'struct boost::unit_test::ut_detail::nil_t' has
* a non-virtual destructor [-Werror=effc++]
*/
#if defined __GNUC__
#pragma GCC diagnostic ignored "-Weffc++"
#endif
#include <boost/test/unit_test.hpp>
#include <jsonpack.hpp>
#include <limits>
#include <ostream>
#include <iomanip>
struct TestReal
{
TestReal():
test_float(0.0f),
test_double(0.0)
{}
float test_float;
double test_double;
DEFINE_JSON_ATTRIBUTES(test_float, test_double)
};
BOOST_AUTO_TEST_CASE(pack_reals_maximum_finite_value)
{
TestReal jsonpack_real;
jsonpack_real.test_float = std::numeric_limits<float>::max();
jsonpack_real.test_double = std::numeric_limits<double>::max();
char * pack_string = jsonpack_real.json_pack();
std::ostringstream formatter;
formatter << "{\"test_float\":" << std::setprecision(17) << std::numeric_limits<float>::max()
<< ",\"test_double\":" << std::setprecision(17) << std::numeric_limits<double>::max() << "}";
BOOST_CHECK_EQUAL(pack_string, formatter.str().c_str() );
free(pack_string);
}
BOOST_AUTO_TEST_CASE(unpack_reals_maximum_finite_value)
{
TestReal jsonpack_real;
std::ostringstream formatter;
formatter << "{\"test_float\":" << std::setprecision(17) << std::numeric_limits<float>::max()
<< ",\"test_double\":" << std::setprecision(17) << std::numeric_limits<double>::max() << "}";
jsonpack_real.json_unpack(formatter.str().c_str() , formatter.str().length() );
BOOST_CHECK_EQUAL(jsonpack_real.test_float, std::numeric_limits<float>::max());
BOOST_CHECK_EQUAL(jsonpack_real.test_double, std::numeric_limits<double>::max());
}
BOOST_AUTO_TEST_CASE(pack_reals_min_finite_value)
{
TestReal jsonpack_real;
jsonpack_real.test_float = std::numeric_limits<float>::min();
jsonpack_real.test_double = std::numeric_limits<double>::min();
char * pack_string = jsonpack_real.json_pack();
std::ostringstream formatter;
formatter << "{\"test_float\":" << std::setprecision(17) << std::numeric_limits<float>::min()
<< ",\"test_double\":" << std::setprecision(17) << std::numeric_limits<double>::min() << "}";
BOOST_CHECK_EQUAL(pack_string, formatter.str().c_str() );
free(pack_string);
}
BOOST_AUTO_TEST_CASE(unpack_reals_min_finite_value)
{
TestReal jsonpack_real;
std::ostringstream formatter;
formatter << "{\"test_float\":" << std::setprecision(17) << std::numeric_limits<float>::min()
<< ",\"test_double\":" << std::setprecision(17) << std::numeric_limits<double>::min() << "}";
jsonpack_real.json_unpack(formatter.str().c_str(), formatter.str().length() );
BOOST_CHECK_EQUAL(jsonpack_real.test_float, std::numeric_limits<float>::min());
BOOST_CHECK_EQUAL(jsonpack_real.test_double, std::numeric_limits<double>::min());
}
<commit_msg>Modifing jsonpack_real test<commit_after>#define BOOST_TEST_MAIN
#if !defined( WIN32 )
#define BOOST_TEST_DYN_LINK
#endif
/**
* Boost.test causes the following warning under GCC
* error: base class 'struct boost::unit_test::ut_detail::nil_t' has
* a non-virtual destructor [-Werror=effc++]
*/
#if defined __GNUC__
#pragma GCC diagnostic ignored "-Weffc++"
#endif
#include <boost/test/unit_test.hpp>
#include <jsonpack.hpp>
#include <limits>
#include <ostream>
#include <iomanip>
struct TestReal
{
TestReal():
test_float(0.0f),
test_double(0.0)
{}
float test_float;
double test_double;
DEFINE_JSON_ATTRIBUTES(test_float, test_double)
};
BOOST_AUTO_TEST_CASE(pack_unpack_reals_maximum_finite_value)
{
TestReal jsonpack_real, output;
jsonpack_real.test_float = std::numeric_limits<float>::max();
jsonpack_real.test_double = std::numeric_limits<double>::max();
char * pack_string = jsonpack_real.json_pack();
output.json_unpack(pack_string , strlen(pack_string));
BOOST_CHECK_EQUAL(output.test_float, std::numeric_limits<float>::max());
BOOST_CHECK_EQUAL(output.test_double, std::numeric_limits<double>::max());
free(pack_string);
}
BOOST_AUTO_TEST_CASE(pack_unpack_reals_min_finite_value)
{
TestReal jsonpack_real, output;
jsonpack_real.test_float = std::numeric_limits<float>::min();
jsonpack_real.test_double = std::numeric_limits<double>::min();
char * pack_string = jsonpack_real.json_pack();
output.json_unpack(pack_string , strlen(pack_string));
BOOST_CHECK_EQUAL(output.test_float, std::numeric_limits<float>::min());
BOOST_CHECK_EQUAL(output.test_double, std::numeric_limits<double>::min());
free(pack_string);
}
<|endoftext|>
|
<commit_before>/* ptptest.cc - PLIC Test Program
* Copyright (C) 2008 Tim Janik
*
* This program 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 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
* Lesser General Public License for more details.
*
* A copy of the GNU Lesser General Public License should ship along
* with this program; if not, see http://www.gnu.org/copyleft/.
*/
#include <stdio.h>
#include <stdint.h>
/* PLIC TypePackage Parser */
#include "../PlicTypePackage.cc"
#ifndef MAX
#define MIN(a,b) ((a) <= (b) ? (a) : (b))
#define MAX(a,b) ((a) >= (b) ? (a) : (b))
#endif
/* --- option parsing --- */
static bool
parse_str_option (char **argv,
uint &i,
const char *arg,
const char **strp,
uint argc)
{
uint length = strlen (arg);
if (strncmp (argv[i], arg, length) == 0)
{
const char *equal = argv[i] + length;
if (*equal == '=') /* -x=Arg */
*strp = equal + 1;
else if (*equal) /* -xArg */
*strp = equal;
else if (i + 1 < argc) /* -x Arg */
{
argv[i++] = NULL;
*strp = argv[i];
}
argv[i] = NULL;
if (*strp)
return true;
}
return false;
}
static bool
parse_bool_option (char **argv,
uint &i,
const char *arg)
{
uint length = strlen (arg);
if (strncmp (argv[i], arg, length) == 0)
{
argv[i] = NULL;
return true;
}
return false;
}
/* --- test program --- */
int
main (int argc,
char *argv[])
{
vector<String> auxtests;
/* parse args */
for (uint i = 1; i < uint (argc); i++)
{
const char *str = NULL;
if (strcmp (argv[i], "--") == 0)
{
argv[i] = NULL;
break;
}
else if (parse_bool_option (argv, i, "--help"))
{
printf ("Usage: %s [options] TypePackage.out\n", argv[0]);
printf ("Options:\n");
printf (" --help Print usage summary\n");
printf (" --aux-test=x Find 'x' in auxillary type data\n");
exit (0);
}
else if (parse_str_option (argv, i, "--aux-test", &str, argc))
auxtests.push_back (str);
}
/* collapse parsed args */
uint e = 1;
for (uint i = 1; i < uint (argc); i++)
if (argv[i])
{
argv[e++] = argv[i];
if (i >= e)
argv[i] = NULL;
}
argc = e;
/* validate mandatory arg */
if (argc < 2)
error ("Usage: %s TypePackage.out\n", argv[0]);
/* parse input file */
int fd = open (argv[1], 0);
if (fd < 0)
error ("%s: open failed: %s", argv[1], strerror (errno));
uint8 buffer[1024 * 1024];
int l = read (fd, buffer, sizeof (buffer));
if (l < 0)
error ("%s: IO error: %s", argv[1], strerror (errno));
close (fd);
TypeRegistry tr;
String err = tr.register_type_package (l, buffer);
error_if (err != "", err);
// check for intermediate \0 in type package data
error_if (memchr (buffer, 0, l) != NULL, "embedded \\000 in type package");
/* print types and match auxtests */
vector<TypeNamespace> namespaces = tr.list_namespaces();
for (uint i = 0; i < namespaces.size(); i++)
{
vector<TypeInfo> types = namespaces[i].list_types ();
for (uint j = 0; j < types.size(); j++)
{
printf ("%c %s::%s;\n",
types[j].storage,
namespaces[i].fullname().c_str(),
types[j].name().c_str());
uint ad = types[j].n_aux_strings();
for (uint k = 0; k < ad; k++)
{
uint l = 0;
const char *s = types[j].aux_string (k, &l);
String astring = String (s, l);
uint c = ' ';
for (uint q = 0; q < auxtests.size(); q++)
if (strstr (astring.c_str(), auxtests[q].c_str()))
{
auxtests.erase (auxtests.begin() + q);
c = '*';
break;
}
printf (" %c %s\n", c, astring.c_str());
}
}
}
/* fail for unmatched auxtests */
if (auxtests.size())
fprintf (stderr, "ERROR: unmatched aux-tests:\n");
for (uint q = 0; q < auxtests.size(); q++)
fprintf (stderr, " %s\n", auxtests[q].c_str());
return auxtests.size() != 0;
}
// g++ -Wall -Os ptptest.cc && ./a.out plic.out
<commit_msg>tests/ptptest.cc: catch include omissions in PlicTypePackage.cc<commit_after>/* ptptest.cc - PLIC Test Program
* Copyright (C) 2008 Tim Janik
*
* This program 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 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
* Lesser General Public License for more details.
*
* A copy of the GNU Lesser General Public License should ship along
* with this program; if not, see http://www.gnu.org/copyleft/.
*/
/* PLIC TypePackage Parser */
#include "../PlicTypePackage.cc"
#ifndef MAX
#define MIN(a,b) ((a) <= (b) ? (a) : (b))
#define MAX(a,b) ((a) >= (b) ? (a) : (b))
#endif
/* --- option parsing --- */
static bool
parse_str_option (char **argv,
uint &i,
const char *arg,
const char **strp,
uint argc)
{
uint length = strlen (arg);
if (strncmp (argv[i], arg, length) == 0)
{
const char *equal = argv[i] + length;
if (*equal == '=') /* -x=Arg */
*strp = equal + 1;
else if (*equal) /* -xArg */
*strp = equal;
else if (i + 1 < argc) /* -x Arg */
{
argv[i++] = NULL;
*strp = argv[i];
}
argv[i] = NULL;
if (*strp)
return true;
}
return false;
}
static bool
parse_bool_option (char **argv,
uint &i,
const char *arg)
{
uint length = strlen (arg);
if (strncmp (argv[i], arg, length) == 0)
{
argv[i] = NULL;
return true;
}
return false;
}
/* --- test program --- */
int
main (int argc,
char *argv[])
{
vector<String> auxtests;
/* parse args */
for (uint i = 1; i < uint (argc); i++)
{
const char *str = NULL;
if (strcmp (argv[i], "--") == 0)
{
argv[i] = NULL;
break;
}
else if (parse_bool_option (argv, i, "--help"))
{
printf ("Usage: %s [options] TypePackage.out\n", argv[0]);
printf ("Options:\n");
printf (" --help Print usage summary\n");
printf (" --aux-test=x Find 'x' in auxillary type data\n");
exit (0);
}
else if (parse_str_option (argv, i, "--aux-test", &str, argc))
auxtests.push_back (str);
}
/* collapse parsed args */
uint e = 1;
for (uint i = 1; i < uint (argc); i++)
if (argv[i])
{
argv[e++] = argv[i];
if (i >= e)
argv[i] = NULL;
}
argc = e;
/* validate mandatory arg */
if (argc < 2)
error ("Usage: %s TypePackage.out\n", argv[0]);
/* parse input file */
int fd = open (argv[1], 0);
if (fd < 0)
error ("%s: open failed: %s", argv[1], strerror (errno));
uint8 buffer[1024 * 1024];
int l = read (fd, buffer, sizeof (buffer));
if (l < 0)
error ("%s: IO error: %s", argv[1], strerror (errno));
close (fd);
TypeRegistry tr;
String err = tr.register_type_package (l, buffer);
error_if (err != "", err);
// check for intermediate \0 in type package data
error_if (memchr (buffer, 0, l) != NULL, "embedded \\000 in type package");
/* print types and match auxtests */
vector<TypeNamespace> namespaces = tr.list_namespaces();
for (uint i = 0; i < namespaces.size(); i++)
{
vector<TypeInfo> types = namespaces[i].list_types ();
for (uint j = 0; j < types.size(); j++)
{
printf ("%c %s::%s;\n",
types[j].storage,
namespaces[i].fullname().c_str(),
types[j].name().c_str());
uint ad = types[j].n_aux_strings();
for (uint k = 0; k < ad; k++)
{
uint l = 0;
const char *s = types[j].aux_string (k, &l);
String astring = String (s, l);
uint c = ' ';
for (uint q = 0; q < auxtests.size(); q++)
if (strstr (astring.c_str(), auxtests[q].c_str()))
{
auxtests.erase (auxtests.begin() + q);
c = '*';
break;
}
printf (" %c %s\n", c, astring.c_str());
}
}
}
/* fail for unmatched auxtests */
if (auxtests.size())
fprintf (stderr, "ERROR: unmatched aux-tests:\n");
for (uint q = 0; q < auxtests.size(); q++)
fprintf (stderr, " %s\n", auxtests[q].c_str());
return auxtests.size() != 0;
}
// g++ -Wall -Os ptptest.cc && ./a.out plic.out
<|endoftext|>
|
<commit_before>/** \file fib.cpp
* Generación de la serie de Fibonacci, donde cada término es la suma de los dos anteriores.
*
* El usuario debe introducir la pareja de números iniciales y el número de iteraciones.
*
* <a href="http://es.wikipedia.org/wiki/Sucesi%C3%B3n_de_Fibonacci">Serie de Fibonacci en Wikipedia</a>
*
* \date 19 de Octubre de 2013
*/
// El archivo de cabecera "iostream" permite usar cout y cin.
#include <iostream>
//! Primer valor de la serie
int a;
//! Segundo valor de la serie
int b;
//! Número de términos de la serie a mostrar.
int limite;
//! Iteración actual.
int iter = 0;
/// Suma de los dos valores anteriores.
int suma;
//! La función principal solicita los dos números iniciales de la serie y el número de iteraciones
int main(){
std::cout << "Introduzca la pareja de números iniciales de la serie, separados por un espacio: " << std::endl;
std::cin >> a >> b;
std::cout << std::endl;
std::cout << "Introduzca el número de iteraciones en la serie: " << std::endl;
std::cin >> limite;
std::cout << a << " " << b << " ";
while (iter < limite-2) {
iter++;
suma = a + b;
std::cout << suma << " ";
a = b;
b = suma;
}
std::cout << std::endl;
return 0;
}
<commit_msg>indented<commit_after>/** \file fib.cpp
* Generación de la serie de Fibonacci, donde cada término es la suma de los dos anteriores.
*
* El usuario debe introducir la pareja de números iniciales y el número de iteraciones.
*
* <a href="http://es.wikipedia.org/wiki/Sucesi%C3%B3n_de_Fibonacci">Serie de Fibonacci en Wikipedia</a>
*
* \date 19 de Octubre de 2013
*/
// El archivo de cabecera "iostream" permite usar cout y cin.
#include <iostream>
//! Primer valor de la serie
int a;
//! Segundo valor de la serie
int b;
//! Número de términos de la serie a mostrar.
int limite;
//! Iteración actual.
int iter = 0;
/// Suma de los dos valores anteriores.
int suma;
//! La función principal solicita los dos números iniciales de la serie y el número de iteraciones
int main(){
std::cout << "Introduzca la pareja de números iniciales de la serie, separados por un espacio: " << std::endl;
std::cin >> a >> b;
std::cout << std::endl;
std::cout << "Introduzca el número de iteraciones en la serie: " << std::endl;
std::cin >> limite;
std::cout << a << " " << b << " ";
while (iter < limite-2) {
iter++;
suma = a + b;
std::cout << suma << " ";
a = b;
b = suma;
}
std::cout << std::endl;
return 0;
}
<|endoftext|>
|
<commit_before>#include "stdafx.h"
#include "vldmfc.h"
#include "vldmfcdlg.h"
// Include Visual Leak Detector
#include <vld.h>
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CMFCExampleApp
BEGIN_MESSAGE_MAP(CMFCExampleApp, CWinApp)
//{{AFX_MSG_MAP(CMFCExampleApp)
// NOTE - the ClassWizard will add and remove mapping macros here.
// DO NOT EDIT what you see in these blocks of generated code!
//}}AFX_MSG
ON_COMMAND(ID_HELP, CWinApp::OnHelp)
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CMFCExampleApp construction
CMFCExampleApp::CMFCExampleApp()
{
// TODO: add construction code here,
// Place all significant initialization in InitInstance
}
/////////////////////////////////////////////////////////////////////////////
// The one and only CMFCExampleApp object
CMFCExampleApp theApp;
/////////////////////////////////////////////////////////////////////////////
// CMFCExampleApp initialization
BOOL CMFCExampleApp::InitInstance()
{
// Standard initialization
// If you are not using these features and wish to reduce the size
// of your final executable, you should remove from the following
// the specific initialization routines you do not need.
CMFCExampleDlg dlg;
m_pMainWnd = &dlg;
INT_PTR nResponse = dlg.DoModal();
if (nResponse == IDOK)
{
// TODO: Place code here to handle when the dialog is
// dismissed with OK
CString *s = new CString("Hello World!\n");
if (!dlg.m_bLeak) {
delete s;
}
}
else if (nResponse == IDCANCEL)
{
// TODO: Place code here to handle when the dialog is
// dismissed with Cancel
}
// Since the dialog has been closed, return FALSE so that we exit the
// application, rather than start the application's message pump.
return FALSE;
}
<commit_msg>atlTraceGeneral - is extral info<commit_after>#include "stdafx.h"
#include "vldmfc.h"
#include "vldmfcdlg.h"
// Include Visual Leak Detector
#include <vld.h>
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CMFCExampleApp
BEGIN_MESSAGE_MAP(CMFCExampleApp, CWinApp)
//{{AFX_MSG_MAP(CMFCExampleApp)
// NOTE - the ClassWizard will add and remove mapping macros here.
// DO NOT EDIT what you see in these blocks of generated code!
//}}AFX_MSG
ON_COMMAND(ID_HELP, CWinApp::OnHelp)
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CMFCExampleApp construction
CMFCExampleApp::CMFCExampleApp()
{
// TODO: add construction code here,
// Place all significant initialization in InitInstance
}
/////////////////////////////////////////////////////////////////////////////
// The one and only CMFCExampleApp object
CMFCExampleApp theApp;
/////////////////////////////////////////////////////////////////////////////
// CMFCExampleApp initialization
void f(){
int * p = 0x0;
p = new int[10001]; *p = 0xfa;
p = (int*)malloc(40000); *p = 0xfb;
}
class EventMonitorPacket{
int ar[100];
};
int g_i = 0;
void ProcessEventPacket(EventMonitorPacket *pEventMonitorPacket);
void que(EventMonitorPacket *pEventMonitorPacket){
EventMonitorPacket* newMsg = new EventMonitorPacket;
ZeroMemory(newMsg, sizeof(EventMonitorPacket));
memcpy((void *)newMsg, (void *)pEventMonitorPacket, sizeof(EventMonitorPacket));
delete pEventMonitorPacket;
ProcessEventPacket(newMsg);
}
void ProcessEventPacket(EventMonitorPacket *pEventMonitorPacket)
{
EventMonitorPacket *pMsg;
pMsg = new EventMonitorPacket;
memcpy((void *)pMsg, (void *)pEventMonitorPacket, sizeof(EventMonitorPacket));
g_i++;
if ((g_i % 2) == 0){
return;
}
else
{
que(pMsg);
}
}
BOOL CMFCExampleApp::InitInstance()
{
// Standard initialization
// If you are not using these features and wish to reduce the size
// of your final executable, you should remove from the following
// the specific initialization routines you do not need.
CMFCExampleDlg dlg;
m_pMainWnd = &dlg;
INT_PTR nResponse = dlg.DoModal();
if (nResponse == IDOK)
{
// TODO: Place code here to handle when the dialog is
// dismissed with OK
f();
for (int j = 0; j < 7; j++){
EventMonitorPacket g;
ProcessEventPacket(&g);
}
CString *s = new CString("Hello World!\n");
if (!dlg.m_bLeak) {
delete s;
}
}
else if (nResponse == IDCANCEL)
{
// TODO: Place code here to handle when the dialog is
// dismissed with Cancel
}
_CrtDumpMemoryLeaks();
// Since the dialog has been closed, return FALSE so that we exit the
// application, rather than start the application's message pump.
return FALSE;
}
<|endoftext|>
|
<commit_before>#include "keilo_table.hpp"
#include <mutex>
keilo_table::keilo_table(std::string _name) : m_name(_name), m_records(std::list<keilo_record>())
{
}
keilo_table::keilo_table(std::string _name, std::list<keilo_record> _rows) : m_name(_name), m_records(_rows)
{
}
keilo_table::keilo_table(const keilo_table & _other) : m_name(_other.m_name), m_records(_other.m_records)
{
}
keilo_table keilo_table::join(keilo_table* _other)
{
std::list<keilo_record> joined_table{ get_records() };
auto other_table = _other->get_records();
for (auto& i_record : joined_table)
{
keilo_instance i_instance;
for (const auto& instance : i_record)
{
if (instance.first != "index")
continue;
i_instance = instance;
break;
}
bool found = false;
for (auto& j_record : other_table)
{
for (const auto& j_instance : j_record)
{
if (j_instance.first == "index")
{
if (i_instance.second != j_instance.second)
break;
found = true;
}
else
i_record.push_back(keilo_instance{ j_instance.first, j_instance.second });
}
if (found)
break;
}
}
return keilo_table(get_name() + "+" + _other->get_name(), joined_table);
}
keilo_record keilo_table::select_record(keilo_instance _instance)
{
std::lock_guard<std::mutex> mutex_guard(m_mutex);
for (auto record : m_records)
{
for (auto instance : record)
{
if (instance != _instance)
continue;
return record;
}
}
return keilo_record();
//throw std::exception(("Could not find record that has identifier \"" + _instance.first +"\" or value\"" + _instance.second + "\".").c_str());
}
std::string keilo_table::insert_record(keilo_record & _record)
{
std::lock_guard<std::mutex> mutex_guard(m_mutex);
int pos;
std::string index;
for (auto& i_instance : _record)
{
if (i_instance.first != "index")
continue;
for (const auto& j_record : m_records)
for (const auto& j_instance : j_record)
if (i_instance != j_instance)
continue;
else
return "Record that has index \"" + i_instance.second + "\" is already exist in table \"" + get_name() + "\".";
index = i_instance.second;
pos = atoi(index.c_str());
break;
}
auto count = 0;
std::list<keilo_record>::iterator it = m_records.begin();
while (it != m_records.end() && ++count != pos)
it++;
m_records.insert(it, _record);
return "Successfully inserted record that has index\"" + index + "\" to table \"" + get_name() + "\".";
}
std::string keilo_table::update_record(keilo_instance _where, keilo_instance _new)
{
std::lock_guard<std::mutex> mutex_guard(m_mutex);
keilo_record* found_record = nullptr;
auto found = false;
for (auto& record : m_records)
{
for (const auto& instance : record)
{
if (instance != _where)
continue;
found_record = &record;
found = true;
break;
}
if (found)
break;
}
if (!found)
return "Record that has " + _where.first + " \"" + _where.second + "\" does not exist in table \"" + get_name() + "\".";
//throw std::exception((_where.first + " \"" + _where.second + "\" does not exist in table \"" + get_name() + "\".").c_str());
auto changed = false;
for (auto& instance : *found_record)
{
if (instance.first != _new.first)
continue;
instance.second = _new.second;
changed = true;
break;
}
if (!changed)
return "Identifier \"" + _new.first + "\" does not exist in table \"" + get_name() + "\".";
//throw std::exception(("Identifier \"" + _new.first + "\" does not exist in table \"" + get_name() + "\".").c_str());
return "Successfully updated record that has " + _where.first + " \"" + _where.second +"\" in table \"" + get_name() + "\".";
}
std::string keilo_table::remove_record(keilo_instance _instance)
{
std::lock_guard<std::mutex> mutex_guard(m_mutex);
std::list<keilo_record>::iterator it;
auto found = false;
for (auto record = m_records.begin(); record != m_records.end(); ++record)
{
for (auto instance = record->begin(); instance != record->end(); ++instance)
{
if (*instance != _instance)
continue;
it = record;
found = true;
break;
}
if (found)
break;
}
if (!found)
return "Record that has" + _instance.first + " \"" + _instance.second + "\" does not exist in table \"" + get_name() + "\".";
//throw std::exception((_instance.first + " \"" + _instance.second + "\" does not exist in table \"" + get_name() + "\".").c_str());
m_records.erase(it);
return "Successfully removed record that has " + _instance.first + " \"" + _instance.second + "\" in table \"" + get_name() + "\"";
}
std::list<keilo_record> keilo_table::get_records()
{
std::lock_guard<std::mutex> mutex_guard(m_mutex);
return m_records;
}
int keilo_table::count()
{
std::lock_guard<std::mutex> mutex_guard(m_mutex);
return m_records.size();
}
std::string keilo_table::get_name() const
{
return m_name;
}
void keilo_table::set_name(std::string _name)
{
m_name = _name;
}
<commit_msg>initialize<commit_after>#include "keilo_table.hpp"
#include <mutex>
keilo_table::keilo_table(std::string _name) : m_name(_name), m_records(std::list<keilo_record>())
{
}
keilo_table::keilo_table(std::string _name, std::list<keilo_record> _rows) : m_name(_name), m_records(_rows)
{
}
keilo_table::keilo_table(const keilo_table & _other) : m_name(_other.m_name), m_records(_other.m_records)
{
}
keilo_table keilo_table::join(keilo_table* _other)
{
std::list<keilo_record> joined_table{ get_records() };
auto other_table = _other->get_records();
for (auto& i_record : joined_table)
{
keilo_instance i_instance;
for (const auto& instance : i_record)
{
if (instance.first != "index")
continue;
i_instance = instance;
break;
}
bool found = false;
for (auto& j_record : other_table)
{
for (const auto& j_instance : j_record)
{
if (j_instance.first == "index")
{
if (i_instance.second != j_instance.second)
break;
found = true;
}
else
i_record.push_back(keilo_instance{ j_instance.first, j_instance.second });
}
if (found)
break;
}
}
return keilo_table(get_name() + "+" + _other->get_name(), joined_table);
}
keilo_record keilo_table::select_record(keilo_instance _instance)
{
std::lock_guard<std::mutex> mutex_guard(m_mutex);
for (auto record : m_records)
{
for (auto instance : record)
{
if (instance != _instance)
continue;
return record;
}
}
return keilo_record();
//throw std::exception(("Could not find record that has identifier \"" + _instance.first +"\" or value\"" + _instance.second + "\".").c_str());
}
std::string keilo_table::insert_record(keilo_record & _record)
{
std::lock_guard<std::mutex> mutex_guard(m_mutex);
int pos = 0;
std::string index;
for (auto& i_instance : _record)
{
if (i_instance.first != "index")
continue;
for (const auto& j_record : m_records)
for (const auto& j_instance : j_record)
if (i_instance != j_instance)
continue;
else
return "Record that has index \"" + i_instance.second + "\" is already exist in table \"" + get_name() + "\".";
index = i_instance.second;
pos = atoi(index.c_str());
break;
}
auto count = 0;
std::list<keilo_record>::iterator it = m_records.begin();
while (it != m_records.end() && ++count != pos)
it++;
m_records.insert(it, _record);
return "Successfully inserted record that has index\"" + index + "\" to table \"" + get_name() + "\".";
}
std::string keilo_table::update_record(keilo_instance _where, keilo_instance _new)
{
std::lock_guard<std::mutex> mutex_guard(m_mutex);
keilo_record* found_record = nullptr;
auto found = false;
for (auto& record : m_records)
{
for (const auto& instance : record)
{
if (instance != _where)
continue;
found_record = &record;
found = true;
break;
}
if (found)
break;
}
if (!found)
return "Record that has " + _where.first + " \"" + _where.second + "\" does not exist in table \"" + get_name() + "\".";
//throw std::exception((_where.first + " \"" + _where.second + "\" does not exist in table \"" + get_name() + "\".").c_str());
auto changed = false;
for (auto& instance : *found_record)
{
if (instance.first != _new.first)
continue;
instance.second = _new.second;
changed = true;
break;
}
if (!changed)
return "Identifier \"" + _new.first + "\" does not exist in table \"" + get_name() + "\".";
//throw std::exception(("Identifier \"" + _new.first + "\" does not exist in table \"" + get_name() + "\".").c_str());
return "Successfully updated record that has " + _where.first + " \"" + _where.second +"\" in table \"" + get_name() + "\".";
}
std::string keilo_table::remove_record(keilo_instance _instance)
{
std::lock_guard<std::mutex> mutex_guard(m_mutex);
std::list<keilo_record>::iterator it;
auto found = false;
for (auto record = m_records.begin(); record != m_records.end(); ++record)
{
for (auto instance = record->begin(); instance != record->end(); ++instance)
{
if (*instance != _instance)
continue;
it = record;
found = true;
break;
}
if (found)
break;
}
if (!found)
return "Record that has" + _instance.first + " \"" + _instance.second + "\" does not exist in table \"" + get_name() + "\".";
//throw std::exception((_instance.first + " \"" + _instance.second + "\" does not exist in table \"" + get_name() + "\".").c_str());
m_records.erase(it);
return "Successfully removed record that has " + _instance.first + " \"" + _instance.second + "\" in table \"" + get_name() + "\"";
}
std::list<keilo_record> keilo_table::get_records()
{
std::lock_guard<std::mutex> mutex_guard(m_mutex);
return m_records;
}
int keilo_table::count()
{
std::lock_guard<std::mutex> mutex_guard(m_mutex);
return m_records.size();
}
std::string keilo_table::get_name() const
{
return m_name;
}
void keilo_table::set_name(std::string _name)
{
m_name = _name;
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <scriptzeug/ScriptContext.h>
#include <scriptzeug/Object.h>
using namespace scriptzeug;
Variant testFunction(std::string a)
{
std::cout << "Test function\n";
Variant value = Variant::Object();
value.set("a", 1);
value.set("b", 2);
value.set("c", 3);
value.set("d", "end");
return value;
}
class Counting : public Object
{
public:
Counting() : Object("counting"), m_min(0), m_max(2)
{
addProperty<int>("min", *this, &Counting::getMin, &Counting::setMin);
addProperty<int>("max", *this, &Counting::getMax, &Counting::setMax);
addFunction("count", this, &Counting::count);
}
~Counting()
{
}
void count()
{
for (int i=m_min; i<=m_max; i++) {
std::cout << "Counting " << i << " ...\n";
}
}
int getMin() const { return m_min; }
void setMin(const int &min) { m_min = min; }
int getMax() const { return m_max; }
void setMax(const int & max) { m_max = max; }
protected:
int m_min, m_max;
};
class MyInterface : public Object
{
public:
MyInterface() : Object("api"), m_prompt("Hello World")
{
// Properties
addProperty<std::string>("prompt", *this, &MyInterface::prompt, &MyInterface::setPrompt);
addGroup(new Counting);
// Functions
addFunction("test", &testFunction);
addFunction("helloWorld", this, &MyInterface::helloWorld);
addFunction("bottlesOfBeer", this, &MyInterface::bottlesOfBeer);
addFunction("dynamicTest", this, &MyInterface::dynamicTest);
}
~MyInterface()
{
}
int helloWorld()
{
std::cout << m_prompt << "\n";
return 10;
}
std::string bottlesOfBeer(int count, float a)
{
std::cout << count << " bottles of beer with a propability of " << a << "\%.\n";
return "hicks";
}
void dynamicTest(const std::vector<Variant> &args)
{
std::cout << "Number of arguments: " << args.size() << "\n";
int i=0;
for (std::vector<Variant>::const_iterator it = args.begin(); it != args.end(); ++it) {
std::cout << "- " << i << ": " << (*it).toString() << "\n";
i++;
}
}
protected:
std::string prompt() const
{
return m_prompt;
}
void setPrompt(const std::string & prompt)
{
m_prompt = prompt;
}
protected:
std::string m_prompt;
};
int main(int argc, char const *argv[])
{
MyInterface obj;
ScriptContext scripting;
scripting.registerObject(&obj);
Variant value;
value = scripting.evaluate("1 + 2");
std::cout << "--> " << value.toString() << "\n";
value = scripting.evaluate("api.prompt = 'Welcome!';");
std::cout << "--> " << value.toString() << "\n";
value = scripting.evaluate("api.helloWorld() + 1;");
std::cout << "--> " << value.toString() << "\n";
value = scripting.evaluate("api.test();");
std::cout << "--> " << value.toString() << "\n";
value = scripting.evaluate("api.bottlesOfBeer(120, 3.5, 10);");
std::cout << "--> " << value.toString() << "\n";
value = scripting.evaluate("api.bottlesOfBeer();");
std::cout << "--> " << value.toString() << "\n";
value = scripting.evaluate("api.dynamicTest([3.5, {a: 100, b: 200}, 12], \"asd\");");
std::cout << "--> " << value.toString() << "\n";
value = scripting.evaluate("api.dynamicTest();");
std::cout << "--> " << value.toString() << "\n";
value = scripting.evaluate("api.counting.min;");
std::cout << "--> " << value.toString() << "\n";
value = scripting.evaluate("api.counting.max;");
std::cout << "--> " << value.toString() << "\n";
value = scripting.evaluate("api.counting.min = 5;");
value = scripting.evaluate("api.counting.max = 10;");
value = scripting.evaluate("api.counting.count();");
std::cout << "--> " << value.toString() << "\n";
return 0;
}
<commit_msg>Remove escape sequence to please Windows<commit_after>#include <iostream>
#include <scriptzeug/ScriptContext.h>
#include <scriptzeug/Object.h>
using namespace scriptzeug;
Variant testFunction(std::string a)
{
std::cout << "Test function\n";
Variant value = Variant::Object();
value.set("a", 1);
value.set("b", 2);
value.set("c", 3);
value.set("d", "end");
return value;
}
class Counting : public Object
{
public:
Counting() : Object("counting"), m_min(0), m_max(2)
{
addProperty<int>("min", *this, &Counting::getMin, &Counting::setMin);
addProperty<int>("max", *this, &Counting::getMax, &Counting::setMax);
addFunction("count", this, &Counting::count);
}
~Counting()
{
}
void count()
{
for (int i=m_min; i<=m_max; i++) {
std::cout << "Counting " << i << " ...\n";
}
}
int getMin() const { return m_min; }
void setMin(const int &min) { m_min = min; }
int getMax() const { return m_max; }
void setMax(const int & max) { m_max = max; }
protected:
int m_min, m_max;
};
class MyInterface : public Object
{
public:
MyInterface() : Object("api"), m_prompt("Hello World")
{
// Properties
addProperty<std::string>("prompt", *this, &MyInterface::prompt, &MyInterface::setPrompt);
addGroup(new Counting);
// Functions
addFunction("test", &testFunction);
addFunction("helloWorld", this, &MyInterface::helloWorld);
addFunction("bottlesOfBeer", this, &MyInterface::bottlesOfBeer);
addFunction("dynamicTest", this, &MyInterface::dynamicTest);
}
~MyInterface()
{
}
int helloWorld()
{
std::cout << m_prompt << "\n";
return 10;
}
std::string bottlesOfBeer(int count, float a)
{
std::cout << count << " bottles of beer with " << a << "% volume.\n";
return "hicks";
}
void dynamicTest(const std::vector<Variant> &args)
{
std::cout << "Number of arguments: " << args.size() << "\n";
int i=0;
for (std::vector<Variant>::const_iterator it = args.begin(); it != args.end(); ++it) {
std::cout << "- " << i << ": " << (*it).toString() << "\n";
i++;
}
}
protected:
std::string prompt() const
{
return m_prompt;
}
void setPrompt(const std::string & prompt)
{
m_prompt = prompt;
}
protected:
std::string m_prompt;
};
int main(int argc, char const *argv[])
{
MyInterface obj;
ScriptContext scripting;
scripting.registerObject(&obj);
Variant value;
value = scripting.evaluate("1 + 2");
std::cout << "--> " << value.toString() << "\n";
value = scripting.evaluate("api.prompt = 'Welcome!';");
std::cout << "--> " << value.toString() << "\n";
value = scripting.evaluate("api.helloWorld() + 1;");
std::cout << "--> " << value.toString() << "\n";
value = scripting.evaluate("api.test();");
std::cout << "--> " << value.toString() << "\n";
value = scripting.evaluate("api.bottlesOfBeer(120, 3.5, 10);");
std::cout << "--> " << value.toString() << "\n";
value = scripting.evaluate("api.bottlesOfBeer();");
std::cout << "--> " << value.toString() << "\n";
value = scripting.evaluate("api.dynamicTest([3.5, {a: 100, b: 200}, 12], \"asd\");");
std::cout << "--> " << value.toString() << "\n";
value = scripting.evaluate("api.dynamicTest();");
std::cout << "--> " << value.toString() << "\n";
value = scripting.evaluate("api.counting.min;");
std::cout << "--> " << value.toString() << "\n";
value = scripting.evaluate("api.counting.max;");
std::cout << "--> " << value.toString() << "\n";
value = scripting.evaluate("api.counting.min = 5;");
value = scripting.evaluate("api.counting.max = 10;");
value = scripting.evaluate("api.counting.count();");
std::cout << "--> " << value.toString() << "\n";
return 0;
}
<|endoftext|>
|
<commit_before>#include "fussballstadionscene.h"
FussballStadionScene::FussballStadionScene()
{
this->initialized = false;
this->fussballFeld = NULL;
this->fussballFeldCollisionMesh = NULL;
this->fussballFeldCollisionMeshTransformation = NULL;
this->fussballFeldPhysicObject = NULL;
this->fussball = NULL;
this->fussballTransformation = NULL;
this->fussballPhysicObject = NULL;
this->tor = NULL;
this->torTransformation = NULL;
this->torPhysicObjectBack = NULL;
this->physicEngineSlot = -1;
this->physicEngine = NULL;
this->root = NULL;
}
Node* FussballStadionScene::GetRootNode()
{
return this->root;
}
void FussballStadionScene::ShootLeft()
{
//this->fussballPhysicObject->setAngularVelocity(QVector3D(-20, 0 ,0));
this->fussballPhysicObject->setLinearVelocity(QVector3D(-3.2, 0, -10));
}
void FussballStadionScene::ShootRight()
{
//this->fussballPhysicObject->setAngularVelocity(QVector3D(-20, 0 ,0));
this->fussballPhysicObject->setLinearVelocity(QVector3D(3.2, 0, -10));
}
void PrintMatrix(QMatrix4x4 m)
{
for(int row = 0; row < 4; row ++)
{
QVector4D v = m.row(row);
qDebug("%f, %f, %f, %f", v.x(), v.y(), v.z(), v.w());
}
}
void FussballStadionScene::ResetScene()
{
//this->fussballPhysicObject->setLinearVelocity(QVector3D(0, 0, 0));
//this->fussballPhysicObject->setAngularVelocity(QVector3D(0, 0, 0));
//this->fussballTransformation->ResetTrafo();
QMatrix4x4 m = this->fussballTransformation->getMMatrix();
qDebug("before manipulation");
PrintMatrix(m);
m.data()[12] = 4.0f;
m.data()[13] = 4.0f;
m.data()[14] = 4.0f;
qDebug("after manipulation");
PrintMatrix(m);
this->fussballTransformation->setMMatrix(m);
//m.setToIdentity();
//m.translate(0, 4, -31);
//this->fussballTransformation->getMMatrix()
//this->fussballTransformation->Translate(0, 4, -31);
//this->fussballPhysicObject->addToPhysicEngine();
qDebug( "Resettings Scene" );
}
void FussballStadionScene::Initialize()
{
QString path(SRCDIR);
this->root = new Node();
Texture* texture = NULL;
//Physic Engine Erzeugen und einen Pointer auf Instanz holen
this->physicEngineSlot = PhysicEngineManager::createNewPhysicEngineSlot(PhysicEngineName::BulletPhysicsLibrary);
this->physicEngine = PhysicEngineManager::getPhysicEngineBySlot(this->physicEngineSlot);
// ------------------------------------- tor --------------------------------------
this->tor = new Drawable(new TriangleMesh(QString("./../models/fussballtor.obj")));
this->tor->setTransparent(true);
texture = tor->GetProperty<Texture>();
texture->LoadPicture(QString("./../textures/tortexture.png"));
this->torTransformation = new Transformation();
this->torTransformation->Translate(0, -.01, -43.7);
this->torCollisionPlaneBack = new Drawable(new SimplePlane(6, 4));
this->torCollisionPlaneBack->I_setStaticGeometry(true);
this->torCollisionPlaneLeft = new Drawable(new SimplePlane(2.3, 4));
this->torCollisionPlaneLeft->I_setStaticGeometry(true);
this->torCollisionPlaneRight = new Drawable(new SimplePlane(2.3, 4));
this->torCollisionPlaneRight->I_setStaticGeometry(true);
this->torCollisionMeshTransformationBack = new Transformation();
this->torCollisionMeshTransformationBack->Translate(0, 0, -.9);
this->torCollisionMeshTransformationBack->AddChild(this->torCollisionPlaneBack);
this->torCollisionMeshTransformationLeft = new Transformation();
this->torCollisionMeshTransformationLeft->Translate(-3.1, 0, 0);
this->torCollisionMeshTransformationLeft->Rotate(90.0f, 0.0f, 1.0f, 0.0f);
this->torCollisionMeshTransformationLeft->AddChild(this->torCollisionPlaneLeft);
this->torCollisionMeshTransformationRight = new Transformation();
this->torCollisionMeshTransformationRight->Translate(3.1, 0, 0);
this->torCollisionMeshTransformationRight->Rotate(90.0f, 0.0f, 1.0f, 0.0f);
this->torCollisionMeshTransformationRight->AddChild(this->torCollisionPlaneRight);
this->torTransformation->AddChild(this->torCollisionMeshTransformationBack);
this->torTransformation->AddChild(this->torCollisionMeshTransformationLeft);
this->torTransformation->AddChild(this->torCollisionMeshTransformationRight);
this->torPhysicObjectBack = physicEngine->createNewPhysicObject(this->torCollisionPlaneBack);
this->torPhysicObjectLeft = physicEngine->createNewPhysicObject(this->torCollisionPlaneLeft);
this->torPhysicObjectRight = physicEngine->createNewPhysicObject(this->torCollisionPlaneRight);
PhysicObjectConstructionInfo* torConstructionInfoBack = new PhysicObjectConstructionInfo();
torConstructionInfoBack->setCollisionHull(CollisionHull::BoxAABB); //Automatische generierung einer Box aus den Vertexpunkten
torConstructionInfoBack->setRestitution(.8);
PhysicObjectConstructionInfo* torConstructionInfoLeft = new PhysicObjectConstructionInfo();
torConstructionInfoLeft->setCollisionHull(CollisionHull::BoxAABB); //Automatische generierung einer Box aus den Vertexpunkten
torConstructionInfoLeft->setRestitution(.8);
PhysicObjectConstructionInfo* torConstructionInfoRight = new PhysicObjectConstructionInfo();
torConstructionInfoRight->setCollisionHull(CollisionHull::BoxAABB); //Automatische generierung einer Box aus den Vertexpunkten
torConstructionInfoRight->setRestitution(.8);
this->torPhysicObjectBack->setConstructionInfo(torConstructionInfoBack);
this->torPhysicObjectBack->registerPhysicObject();
this->torPhysicObjectLeft->setConstructionInfo(torConstructionInfoLeft);
this->torPhysicObjectLeft->registerPhysicObject();
this->torPhysicObjectRight->setConstructionInfo(torConstructionInfoRight);
this->torPhysicObjectRight->registerPhysicObject();
// ------------------------------------- fussball --------------------------------------
this->fussball = new Drawable(new TriangleMesh(QString("./../models/fussball.obj")));
//this->fussball = new Drawable(new SimpleSphere(.5f));
texture = this->fussball->GetProperty<Texture>();
texture->LoadPicture(QString("./../textures/fussballtexture.png"));
this->fussballTransformation = new Transformation();
this->fussballRootPosition.setX(0);
this->fussballRootPosition.setY(4);
this->fussballRootPosition.setZ(-31.3);
this->fussballTransformation->Translate(this->fussballRootPosition.x(), this->fussballRootPosition.y(), this->fussballRootPosition.z());
this->fussballPhysicObject = physicEngine->createNewPhysicObject(fussball);
this->fussballPhysicObject->setAlwaysActive(false);
//Ein PhysicObjectConstructionInfo Objekt erzeugen, welches die Eigenschaften eines PhysicObjects festlegt,
//für jede Eigenschaft gibt es einen Standardwert, das Objekt wird später automatisch gelöscht
PhysicObjectConstructionInfo* physicObjectConstructionInfo = new PhysicObjectConstructionInfo();
//Optionale veränderung der Informationen
physicObjectConstructionInfo->setCollisionHull(CollisionHull::SphereRadius); //Form des Hüllkörpers festlegen
physicObjectConstructionInfo->setSphereRadius(.2f); //Radius der Sphere auf 0.5 setzen
physicObjectConstructionInfo->setLocalInertiaPoint(QVector3D(0.f,0.f,0.f)); //Schwerpunkt des Objektes angeben, Standardwert (0,0,0)
physicObjectConstructionInfo->setMass(2.f); //Gewicht des Körpers bestimmen, sollte nicht zu groß gewählt werden
physicObjectConstructionInfo->setMidpointTransformation(QMatrix4x4(1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1)); //Mittelpunkttransformation angeben falls Geometrie in seinem Koordinatensystem verschoben liegt
physicObjectConstructionInfo->setRestitution(.1f); //Elastizität des Körpers bestimmen, von 0 bis 1 definiert
physicObjectConstructionInfo->setRollingFriction(0.2f); //Rollwiderstand vorallem bei Kugeln angeben
this->fussballPhysicObject->setConstructionInfo(physicObjectConstructionInfo); //Dem PhysicObject die Konstruktionsinforaionen geben
this->fussballPhysicObject->registerPhysicObject(); //Das PhysicObject in seiner Engine Registrieren, damit die Simulation starten kann
// ------------------------------------- fussball feld --------------------------------------
this->fussballFeld = new Drawable(new TriangleMesh(QString("./../models/fussballfeld.obj")));
this->fussballFeldCollisionMesh = new Drawable(new SimplePlane(200.0f));
texture = this->fussballFeld->GetProperty<Texture>();
texture->LoadPicture(QString("./../textures/fussballfeldtexture.jpg"));
this->fussballFeldCollisionMesh->I_setStaticGeometry(true);
this->fussballFeldCollisionMeshTransformation = new Transformation();
this->fussballFeldCollisionMeshTransformation->Translate(0.0, -0.01, 0.0);
this->fussballFeldCollisionMeshTransformation->Rotate(-90.f,1.f,0.f,0.f);
this->fussballFeldPhysicObject = physicEngine->createNewPhysicObject(this->fussballFeldCollisionMesh);
PhysicObjectConstructionInfo* fussballFeldConstructionInfo = new PhysicObjectConstructionInfo();
fussballFeldConstructionInfo->setCollisionHull(CollisionHull::BoxAABB); //Automatische generierung einer Box aus den Vertexpunkten
this->fussballFeldPhysicObject->setConstructionInfo(fussballFeldConstructionInfo);
this->fussballFeldPhysicObject->registerPhysicObject();
Shader* s = new Shader(path + QString("/shader/texture.vert"), path + QString("/shader/texture.frag"));
this->tor->setShader(s);
this->fussball->setShader(s);
this->fussballFeld->setShader(s);
this->torTransformation->AddChild(this->tor);
this->fussballTransformation->AddChild(this->fussball);
this->fussballFeldCollisionMeshTransformation->AddChild(this->fussballFeldCollisionMesh);
this->root->AddChild(this->torTransformation);
this->root->AddChild(this->fussballFeld);
this->root->AddChild(this->fussballFeldCollisionMeshTransformation);
this->root->AddChild(this->fussballTransformation);
}
<commit_msg>reset der szene möglich<commit_after>#include "fussballstadionscene.h"
FussballStadionScene::FussballStadionScene()
{
this->initialized = false;
this->fussballFeld = NULL;
this->fussballFeldCollisionMesh = NULL;
this->fussballFeldCollisionMeshTransformation = NULL;
this->fussballFeldPhysicObject = NULL;
this->fussball = NULL;
this->fussballTransformation = NULL;
this->fussballPhysicObject = NULL;
this->tor = NULL;
this->torTransformation = NULL;
this->torPhysicObjectBack = NULL;
this->physicEngineSlot = -1;
this->physicEngine = NULL;
this->root = NULL;
}
Node* FussballStadionScene::GetRootNode()
{
return this->root;
}
void FussballStadionScene::ShootLeft()
{
//this->fussballPhysicObject->setAngularVelocity(QVector3D(-20, 0 ,0));
this->fussballPhysicObject->setLinearVelocity(QVector3D(-3.2, 0, -10));
}
void FussballStadionScene::ShootRight()
{
//this->fussballPhysicObject->setAngularVelocity(QVector3D(-20, 0 ,0));
this->fussballPhysicObject->setLinearVelocity(QVector3D(3.2, 0, -10));
}
void PrintMatrix(QMatrix4x4 m)
{
for(int row = 0; row < 4; row ++)
{
QVector4D v = m.row(row);
qDebug("%f, %f, %f, %f", v.x(), v.y(), v.z(), v.w());
}
}
void FussballStadionScene::ResetScene()
{
this->fussballPhysicObject->setLinearVelocity(QVector3D(0, 0, 0));
this->fussballPhysicObject->setAngularVelocity(QVector3D(0, 0, 0));
QMatrix4x4 m = this->fussballPhysicObject->getEngineModelMatrix();
qDebug("before manipulation");
PrintMatrix(m);
m.data()[12] = this->fussballRootPosition.x();
m.data()[13] = this->fussballRootPosition.y();
m.data()[14] = this->fussballRootPosition.z();
qDebug("after manipulation");
PrintMatrix(m);
this->fussballPhysicObject->setEngineModelMatrix(m);
qDebug( "Resettings Scene" );
}
void FussballStadionScene::Initialize()
{
QString path(SRCDIR);
this->root = new Node();
Texture* texture = NULL;
//Physic Engine Erzeugen und einen Pointer auf Instanz holen
this->physicEngineSlot = PhysicEngineManager::createNewPhysicEngineSlot(PhysicEngineName::BulletPhysicsLibrary);
this->physicEngine = PhysicEngineManager::getPhysicEngineBySlot(this->physicEngineSlot);
// ------------------------------------- tor --------------------------------------
this->tor = new Drawable(new TriangleMesh(QString("./../models/fussballtor.obj")));
this->tor->setTransparent(true);
texture = tor->GetProperty<Texture>();
texture->LoadPicture(QString("./../textures/tortexture.png"));
this->torTransformation = new Transformation();
this->torTransformation->Translate(0, -.01, -43.7);
this->torCollisionPlaneBack = new Drawable(new SimplePlane(6, 4));
this->torCollisionPlaneBack->I_setStaticGeometry(true);
this->torCollisionPlaneLeft = new Drawable(new SimplePlane(2.3, 4));
this->torCollisionPlaneLeft->I_setStaticGeometry(true);
this->torCollisionPlaneRight = new Drawable(new SimplePlane(2.3, 4));
this->torCollisionPlaneRight->I_setStaticGeometry(true);
this->torCollisionMeshTransformationBack = new Transformation();
this->torCollisionMeshTransformationBack->Translate(0, 0, -.9);
this->torCollisionMeshTransformationBack->AddChild(this->torCollisionPlaneBack);
this->torCollisionMeshTransformationLeft = new Transformation();
this->torCollisionMeshTransformationLeft->Translate(-3.1, 0, 0);
this->torCollisionMeshTransformationLeft->Rotate(90.0f, 0.0f, 1.0f, 0.0f);
this->torCollisionMeshTransformationLeft->AddChild(this->torCollisionPlaneLeft);
this->torCollisionMeshTransformationRight = new Transformation();
this->torCollisionMeshTransformationRight->Translate(3.1, 0, 0);
this->torCollisionMeshTransformationRight->Rotate(90.0f, 0.0f, 1.0f, 0.0f);
this->torCollisionMeshTransformationRight->AddChild(this->torCollisionPlaneRight);
this->torTransformation->AddChild(this->torCollisionMeshTransformationBack);
this->torTransformation->AddChild(this->torCollisionMeshTransformationLeft);
this->torTransformation->AddChild(this->torCollisionMeshTransformationRight);
this->torPhysicObjectBack = physicEngine->createNewPhysicObject(this->torCollisionPlaneBack);
this->torPhysicObjectLeft = physicEngine->createNewPhysicObject(this->torCollisionPlaneLeft);
this->torPhysicObjectRight = physicEngine->createNewPhysicObject(this->torCollisionPlaneRight);
PhysicObjectConstructionInfo* torConstructionInfoBack = new PhysicObjectConstructionInfo();
torConstructionInfoBack->setCollisionHull(CollisionHull::BoxAABB); //Automatische generierung einer Box aus den Vertexpunkten
torConstructionInfoBack->setRestitution(.8);
PhysicObjectConstructionInfo* torConstructionInfoLeft = new PhysicObjectConstructionInfo();
torConstructionInfoLeft->setCollisionHull(CollisionHull::BoxAABB); //Automatische generierung einer Box aus den Vertexpunkten
torConstructionInfoLeft->setRestitution(.8);
PhysicObjectConstructionInfo* torConstructionInfoRight = new PhysicObjectConstructionInfo();
torConstructionInfoRight->setCollisionHull(CollisionHull::BoxAABB); //Automatische generierung einer Box aus den Vertexpunkten
torConstructionInfoRight->setRestitution(.8);
this->torPhysicObjectBack->setConstructionInfo(torConstructionInfoBack);
this->torPhysicObjectBack->registerPhysicObject();
this->torPhysicObjectLeft->setConstructionInfo(torConstructionInfoLeft);
this->torPhysicObjectLeft->registerPhysicObject();
this->torPhysicObjectRight->setConstructionInfo(torConstructionInfoRight);
this->torPhysicObjectRight->registerPhysicObject();
// ------------------------------------- fussball --------------------------------------
this->fussball = new Drawable(new TriangleMesh(QString("./../models/fussball.obj")));
//this->fussball = new Drawable(new SimpleSphere(.5f));
texture = this->fussball->GetProperty<Texture>();
texture->LoadPicture(QString("./../textures/fussballtexture.png"));
this->fussballTransformation = new Transformation();
this->fussballRootPosition.setX(0);
this->fussballRootPosition.setY(4);
this->fussballRootPosition.setZ(-31.3);
this->fussballTransformation->Translate(this->fussballRootPosition.x(), this->fussballRootPosition.y(), this->fussballRootPosition.z());
this->fussballPhysicObject = physicEngine->createNewPhysicObject(fussball);
this->fussballPhysicObject->setAlwaysActive(false);
//Ein PhysicObjectConstructionInfo Objekt erzeugen, welches die Eigenschaften eines PhysicObjects festlegt,
//für jede Eigenschaft gibt es einen Standardwert, das Objekt wird später automatisch gelöscht
PhysicObjectConstructionInfo* physicObjectConstructionInfo = new PhysicObjectConstructionInfo();
//Optionale veränderung der Informationen
physicObjectConstructionInfo->setCollisionHull(CollisionHull::SphereRadius); //Form des Hüllkörpers festlegen
physicObjectConstructionInfo->setSphereRadius(.2f); //Radius der Sphere auf 0.5 setzen
physicObjectConstructionInfo->setLocalInertiaPoint(QVector3D(0.f,0.f,0.f)); //Schwerpunkt des Objektes angeben, Standardwert (0,0,0)
physicObjectConstructionInfo->setMass(2.f); //Gewicht des Körpers bestimmen, sollte nicht zu groß gewählt werden
physicObjectConstructionInfo->setMidpointTransformation(QMatrix4x4(1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1)); //Mittelpunkttransformation angeben falls Geometrie in seinem Koordinatensystem verschoben liegt
physicObjectConstructionInfo->setRestitution(.1f); //Elastizität des Körpers bestimmen, von 0 bis 1 definiert
physicObjectConstructionInfo->setRollingFriction(0.2f); //Rollwiderstand vorallem bei Kugeln angeben
this->fussballPhysicObject->setConstructionInfo(physicObjectConstructionInfo); //Dem PhysicObject die Konstruktionsinforaionen geben
this->fussballPhysicObject->registerPhysicObject(); //Das PhysicObject in seiner Engine Registrieren, damit die Simulation starten kann
// ------------------------------------- fussball feld --------------------------------------
this->fussballFeld = new Drawable(new TriangleMesh(QString("./../models/fussballfeld.obj")));
this->fussballFeldCollisionMesh = new Drawable(new SimplePlane(200.0f));
texture = this->fussballFeld->GetProperty<Texture>();
texture->LoadPicture(QString("./../textures/fussballfeldtexture.jpg"));
this->fussballFeldCollisionMesh->I_setStaticGeometry(true);
this->fussballFeldCollisionMeshTransformation = new Transformation();
this->fussballFeldCollisionMeshTransformation->Translate(0.0, -0.01, 0.0);
this->fussballFeldCollisionMeshTransformation->Rotate(-90.f,1.f,0.f,0.f);
this->fussballFeldPhysicObject = physicEngine->createNewPhysicObject(this->fussballFeldCollisionMesh);
PhysicObjectConstructionInfo* fussballFeldConstructionInfo = new PhysicObjectConstructionInfo();
fussballFeldConstructionInfo->setCollisionHull(CollisionHull::BoxAABB); //Automatische generierung einer Box aus den Vertexpunkten
this->fussballFeldPhysicObject->setConstructionInfo(fussballFeldConstructionInfo);
this->fussballFeldPhysicObject->registerPhysicObject();
Shader* s = new Shader(path + QString("/shader/texture.vert"), path + QString("/shader/texture.frag"));
this->tor->setShader(s);
this->fussball->setShader(s);
this->fussballFeld->setShader(s);
this->torTransformation->AddChild(this->tor);
this->fussballTransformation->AddChild(this->fussball);
this->fussballFeldCollisionMeshTransformation->AddChild(this->fussballFeldCollisionMesh);
this->root->AddChild(this->torTransformation);
this->root->AddChild(this->fussballFeld);
this->root->AddChild(this->fussballFeldCollisionMeshTransformation);
this->root->AddChild(this->fussballTransformation);
}
<|endoftext|>
|
<commit_before>#ifndef PONG_STATE_HPP
#define PONG_STATE_HPP
#include <iostream>
#include <SFML/Graphics.hpp>
using namespace std;
namespace pong {
class Application;
class State {
public:
virtual ~State() {}
virtual void enter() = 0;
virtual void exit() = 0;
virtual void update(sf::Time& time) = 0;
virtual void render(sf::RenderTarget& renderTarget) = 0;
};
class DefaultState: public State {
public:
virtual void enter() {}
virtual void exit() {}
virtual void update(sf::Time& time) {}
virtual void render(sf::RenderTarget& renderTarget) {}
};
class BaseState: public DefaultState {
public:
virtual void setup(Application* application) {}
virtual void update(sf::Time& time) {}
virtual void render(sf::RenderTarget& renderTarget) {}
};
class GameState: public BaseState {
public:
virtual void setup(Application* application);
virtual void enter();
virtual void exit();
virtual void update(sf::Time& time);
virtual void render(sf::RenderTarget& renderTarget);
};
} /* namespace pong */
#endif /* PONG_STATE_HPP */
<commit_msg>Remoção de métodos que não estavam sendo usados.<commit_after>#ifndef PONG_STATE_HPP
#define PONG_STATE_HPP
#include <iostream>
#include <SFML/Graphics.hpp>
using namespace std;
namespace pong {
class Application;
class State {
public:
virtual ~State() {}
virtual void enter() = 0;
virtual void exit() = 0;
virtual void update(sf::Time& time) = 0;
virtual void render(sf::RenderTarget& renderTarget) = 0;
};
class DefaultState: public State {
public:
virtual void enter() {}
virtual void exit() {}
virtual void update(sf::Time& time) {}
virtual void render(sf::RenderTarget& renderTarget) {}
};
class BaseState: public DefaultState {
public:
virtual void setup(Application* application) {}
};
class GameState: public BaseState {
public:
virtual void setup(Application* application);
virtual void enter();
virtual void exit();
virtual void update(sf::Time& time);
virtual void render(sf::RenderTarget& renderTarget);
};
} /* namespace pong */
#endif /* PONG_STATE_HPP */
<|endoftext|>
|
<commit_before>#include "MeshSymLoader.h"
#include "FilepathHelper.h"
#include "SymbolPool.h"
#include "JsonSerializer.h"
#include "MeshIO.h"
#include "ArrayLoader.h"
#include <simp/NodeMesh.h>
#include <simp/from_int.h>
#include <simp/SIMP_PointsMesh.h>
#include <simp/SIMP_TrianglesMesh.h>
#include <simp/SIMP_Skin2Mesh.h>
#include <simp/from_int.h>
#include <polymesh/PointsMesh.h>
#include <polymesh/TrianglesMesh.h>
#include <polymesh/Skin2Mesh.h>
#include <polymesh/MeshTransform.h>
#include <sprite2/MeshSymbol.h>
#include <sprite2/S2_Mesh.h>
#include <json/json.h>
#include <fstream>
namespace gum
{
MeshSymLoader::MeshSymLoader(s2::MeshSymbol* sym)
: m_sym(sym)
{
if (m_sym) {
m_sym->AddReference();
}
}
MeshSymLoader::~MeshSymLoader()
{
if (m_sym) {
m_sym->RemoveReference();
}
}
void MeshSymLoader::LoadJson(const std::string& filepath)
{
if (!m_sym) {
return;
}
Json::Value value;
Json::Reader reader;
std::locale::global(std::locale(""));
std::ifstream fin(filepath.c_str());
std::locale::global(std::locale("C"));
reader.parse(fin, value);
fin.close();
if (!value.isMember("base_symbol")) {
return;
}
std::string dir = FilepathHelper::Dir(filepath);
std::string base_path = FilepathHelper::Absolute(dir, value["base_symbol"].asString());
s2::Symbol* base_sym = SymbolPool::Instance()->Fetch(base_path);
std::string type = value["type"].asString();
s2::Mesh* mesh = NULL;
if (type == "strip") {
} else if (type == "network" || type == "points") {
mesh = CreatePointsMesh(value, base_sym);
}
m_sym->SetMesh(mesh);
mesh->RemoveReference();
}
void MeshSymLoader::LoadBin(const simp::NodeMesh* node)
{
if (!m_sym) {
return;
}
s2::Symbol* base_sym = SymbolPool::Instance()->Fetch(node->base_id);
s2::Mesh* mesh = NULL;
switch (node->shape->Type())
{
case simp::MESH_POINTS:
mesh = LoadPointsMesh(base_sym, static_cast<simp::PointsMesh*>(node->shape));
break;
case simp::MESH_TRIANGLES:
mesh = LoadTrianglesMesh(base_sym, static_cast<simp::TrianglesMesh*>(node->shape));
break;
case simp::MESH_SKIN2:
mesh = LoadSkin2Mesh(base_sym, static_cast<simp::Skin2Mesh*>(node->shape));
break;
default:
break;
}
m_sym->SetMesh(mesh);
}
s2::Mesh* MeshSymLoader::LoadPointsMesh(s2::Symbol* base_sym, simp::PointsMesh* node)
{
s2::Mesh* s2_mesh = new s2::Mesh(base_sym);
std::vector<sm::vec2> outline;
ArrayLoader::Load(outline, node->outline, node->outline_n, 16);
std::vector<sm::vec2> points;
ArrayLoader::Load(points, node->points, node->points_n, 16);
sm::rect r = base_sym->GetBounding();
pm::Mesh* pm_mesh = new pm::PointsMesh(outline, points, r.Width(), r.Height());
s2_mesh->SetMesh(pm_mesh);
return s2_mesh;
}
s2::Mesh* MeshSymLoader::LoadTrianglesMesh(s2::Symbol* base_sym, simp::TrianglesMesh* node)
{
s2::Mesh* s2_mesh = new s2::Mesh(base_sym);
std::vector<sm::vec2> vertices;
ArrayLoader::Load(vertices, node->vertices, node->vertices_n, 16);
std::vector<sm::vec2> texcoords;
ArrayLoader::Load(texcoords, node->texcoords, node->texcoords_n, 8192);
std::vector<int> triangles;
ArrayLoader::Load(triangles, node->triangle, node->triangle_n);
pm::Mesh* pm_mesh = new pm::TrianglesMesh(vertices, texcoords, triangles);
s2_mesh->SetMesh(pm_mesh);
return s2_mesh;
}
s2::Mesh* MeshSymLoader::LoadSkin2Mesh(s2::Symbol* base_sym, simp::Skin2Mesh* node)
{
s2::Mesh* s2_mesh = new s2::Mesh(base_sym);
std::vector<pm::Skin2Joint> joints;
int joints_n = 0;
for (int i = 0; i < node->vertices_n; ++i) {
joints_n += node->joints_n[i];
}
joints.reserve(joints_n);
for (int i = 0; i < joints_n; ++i)
{
const simp::Skin2Mesh::Joint& src = node->joints[i];
pm::Skin2Joint dst;
dst.joint = src.joint;
dst.vertex.x = simp::int2float(src.vx, 128);
dst.vertex.y = simp::int2float(src.vy, 128);
dst.offset.Set(0, 0);
dst.weight = simp::int2float(src.weight, 4096);
joints.push_back(dst);
}
std::vector<int> vertices;
vertices.reserve(node->vertices_n);
for (int i = 0; i < node->vertices_n; ++i) {
vertices.push_back(node->joints_n[i]);
}
std::vector<sm::vec2> texcoords;
ArrayLoader::Load(texcoords, node->texcoords, node->texcoords_n, 8192);
std::vector<int> triangles;
ArrayLoader::Load(triangles, node->triangle, node->triangle_n);
pm::Mesh* pm_mesh = new pm::Skin2Mesh(joints, vertices, texcoords, triangles);
s2_mesh->SetMesh(pm_mesh);
return s2_mesh;
}
s2::Mesh* MeshSymLoader::CreatePointsMesh(const Json::Value& val, const s2::Symbol* base_sym)
{
s2::Mesh* s2_mesh = new s2::Mesh(base_sym);
std::vector<sm::vec2> outline;
JsonSerializer::Load(val["shape"]["outline"], outline);
std::vector<sm::vec2> points;
JsonSerializer::Load(val["shape"]["inner"], points);
sm::rect r = base_sym->GetBounding();
pm::Mesh* pm_mesh = new pm::PointsMesh(outline, points, r.Width(), r.Height());
pm::MeshTransform trans;
MeshIO::Load(val, trans, *s2_mesh);
pm_mesh->LoadFromTransform(trans);
s2_mesh->SetMesh(pm_mesh);
return s2_mesh;
}
}<commit_msg>up from simp<commit_after>#include "MeshSymLoader.h"
#include "FilepathHelper.h"
#include "SymbolPool.h"
#include "JsonSerializer.h"
#include "MeshIO.h"
#include "ArrayLoader.h"
#include <simp/NodeMesh.h>
#include <simp/from_int.h>
#include <simp/SIMP_PointsMesh.h>
#include <simp/SIMP_TrianglesMesh.h>
#include <simp/SIMP_Skin2Mesh.h>
#include <simp/from_int.h>
#include <polymesh/PointsMesh.h>
#include <polymesh/TrianglesMesh.h>
#include <polymesh/Skin2Mesh.h>
#include <polymesh/MeshTransform.h>
#include <sprite2/MeshSymbol.h>
#include <sprite2/S2_Mesh.h>
#include <json/json.h>
#include <fstream>
namespace gum
{
MeshSymLoader::MeshSymLoader(s2::MeshSymbol* sym)
: m_sym(sym)
{
if (m_sym) {
m_sym->AddReference();
}
}
MeshSymLoader::~MeshSymLoader()
{
if (m_sym) {
m_sym->RemoveReference();
}
}
void MeshSymLoader::LoadJson(const std::string& filepath)
{
if (!m_sym) {
return;
}
Json::Value value;
Json::Reader reader;
std::locale::global(std::locale(""));
std::ifstream fin(filepath.c_str());
std::locale::global(std::locale("C"));
reader.parse(fin, value);
fin.close();
if (!value.isMember("base_symbol")) {
return;
}
std::string dir = FilepathHelper::Dir(filepath);
std::string base_path = FilepathHelper::Absolute(dir, value["base_symbol"].asString());
s2::Symbol* base_sym = SymbolPool::Instance()->Fetch(base_path);
std::string type = value["type"].asString();
s2::Mesh* mesh = NULL;
if (type == "strip") {
} else if (type == "network" || type == "points") {
mesh = CreatePointsMesh(value, base_sym);
}
m_sym->SetMesh(mesh);
mesh->RemoveReference();
}
void MeshSymLoader::LoadBin(const simp::NodeMesh* node)
{
if (!m_sym) {
return;
}
s2::Symbol* base_sym = SymbolPool::Instance()->Fetch(node->base_id);
s2::Mesh* mesh = NULL;
switch (node->shape->type)
{
case simp::MESH_POINTS:
mesh = LoadPointsMesh(base_sym, static_cast<simp::PointsMesh*>(node->shape));
break;
case simp::MESH_TRIANGLES:
mesh = LoadTrianglesMesh(base_sym, static_cast<simp::TrianglesMesh*>(node->shape));
break;
case simp::MESH_SKIN2:
mesh = LoadSkin2Mesh(base_sym, static_cast<simp::Skin2Mesh*>(node->shape));
break;
default:
break;
}
m_sym->SetMesh(mesh);
}
s2::Mesh* MeshSymLoader::LoadPointsMesh(s2::Symbol* base_sym, simp::PointsMesh* node)
{
s2::Mesh* s2_mesh = new s2::Mesh(base_sym);
std::vector<sm::vec2> outline;
ArrayLoader::Load(outline, node->outline, node->outline_n, 16);
std::vector<sm::vec2> points;
ArrayLoader::Load(points, node->points, node->points_n, 16);
sm::rect r = base_sym->GetBounding();
pm::Mesh* pm_mesh = new pm::PointsMesh(outline, points, r.Width(), r.Height());
s2_mesh->SetMesh(pm_mesh);
return s2_mesh;
}
s2::Mesh* MeshSymLoader::LoadTrianglesMesh(s2::Symbol* base_sym, simp::TrianglesMesh* node)
{
s2::Mesh* s2_mesh = new s2::Mesh(base_sym);
std::vector<sm::vec2> vertices;
ArrayLoader::Load(vertices, node->vertices, node->vertices_n, 16);
std::vector<sm::vec2> texcoords;
ArrayLoader::Load(texcoords, node->texcoords, node->texcoords_n, 8192);
std::vector<int> triangles;
ArrayLoader::Load(triangles, node->triangle, node->triangle_n);
pm::Mesh* pm_mesh = new pm::TrianglesMesh(vertices, texcoords, triangles);
s2_mesh->SetMesh(pm_mesh);
return s2_mesh;
}
s2::Mesh* MeshSymLoader::LoadSkin2Mesh(s2::Symbol* base_sym, simp::Skin2Mesh* node)
{
s2::Mesh* s2_mesh = new s2::Mesh(base_sym);
std::vector<pm::Skin2Joint> joints;
int joints_n = 0;
for (int i = 0; i < node->vertices_n; ++i) {
joints_n += node->joints_n[i];
}
joints.reserve(joints_n);
for (int i = 0; i < joints_n; ++i)
{
const simp::Skin2Mesh::Joint& src = node->joints[i];
pm::Skin2Joint dst;
dst.joint = src.joint;
dst.vertex.x = simp::int2float(src.vx, 128);
dst.vertex.y = simp::int2float(src.vy, 128);
dst.offset.Set(0, 0);
dst.weight = simp::int2float(src.weight, 4096);
joints.push_back(dst);
}
std::vector<int> vertices;
vertices.reserve(node->vertices_n);
for (int i = 0; i < node->vertices_n; ++i) {
vertices.push_back(node->joints_n[i]);
}
std::vector<sm::vec2> texcoords;
ArrayLoader::Load(texcoords, node->texcoords, node->texcoords_n, 8192);
std::vector<int> triangles;
ArrayLoader::Load(triangles, node->triangle, node->triangle_n);
pm::Mesh* pm_mesh = new pm::Skin2Mesh(joints, vertices, texcoords, triangles);
s2_mesh->SetMesh(pm_mesh);
return s2_mesh;
}
s2::Mesh* MeshSymLoader::CreatePointsMesh(const Json::Value& val, const s2::Symbol* base_sym)
{
s2::Mesh* s2_mesh = new s2::Mesh(base_sym);
std::vector<sm::vec2> outline;
JsonSerializer::Load(val["shape"]["outline"], outline);
std::vector<sm::vec2> points;
JsonSerializer::Load(val["shape"]["inner"], points);
sm::rect r = base_sym->GetBounding();
pm::Mesh* pm_mesh = new pm::PointsMesh(outline, points, r.Width(), r.Height());
pm::MeshTransform trans;
MeshIO::Load(val, trans, *s2_mesh);
pm_mesh->LoadFromTransform(trans);
s2_mesh->SetMesh(pm_mesh);
return s2_mesh;
}
}<|endoftext|>
|
<commit_before>#include "toy/file/io/Standard.hpp"
using namespace toy;
using namespace file;
using namespace io;
bool Standard::isEnd()
{
if ( feof(_file) )
{
return 1;
}
return 0;
}
bool Standard::isEmpty()
{
if ( _file==0 )
return 1;
else
return 0;
}
void Standard::close()
{
if ( _file )
{
fclose(_file);
_file = 0;
_path.clear();
}
}
bool Standard::openDir(std::string path)
{
_path = path;
return 1;
}
bool Standard::open(std::string filepath)
{
close();
_fileName = filepath;
std::string path;
if ( _path.size()==0 )
{
path=_fileName;
}
else
{
path=_path;
path+=_fileName;
}
_file = fopen(path.c_str(),"rb+");
if ( _file )
return 1;
else
return 0;
}
int Standard::read(void *file,uint32_t size)
{
#if TOY_OPTION_CHECK
if ( ! file )
{
toy::Oops(TOY_MARK);
return 0;
}
#endif
if ( isEmpty() )
return 0;
size_t result=fread(file,1,size,_file); // "fread(file,size,1,_file)" was wrong.
if ( result>size )
{
// fread() has wrong
toy::Log("(%d,%d)\n",result,size);
toy::Oops(TOY_MARK);
return 0;
}
return result;
}
bool Standard::write(void *file,uint32_t size)
{
if ( isEmpty() ) return 0;
fwrite(file,(size_t)size,1,_file);
return 1;
}
bool Standard::seek(enum Option option,int32_t offset)
{
if ( isEmpty() ) return 0;
switch (option)
{
case Base::SET:
fseek( _file, offset, SEEK_SET );
break;
case Base::END:
fseek( _file, offset, SEEK_END );
break;
case Base::CUR:
default:
fseek( _file, offset, SEEK_CUR );
break;
}
return 1;
}
void* Standard::getFilePointer()
{
return (void*)_file;
}
<commit_msg>A stupid mistake.<commit_after>#include "toy/file/io/Standard.hpp"
using namespace toy;
using namespace file;
using namespace io;
bool Standard::isEnd()
{
if ( feof(_file) )
{
return 1;
}
return 0;
}
bool Standard::isEmpty()
{
if ( _file==0 )
return 1;
else
return 0;
}
void Standard::close()
{
if ( _file )
{
fclose(_file);
_file = 0;
_path.clear();
}
}
bool Standard::openDir(std::string path)
{
_path = path;
return 1;
}
bool Standard::open(std::string filepath)
{
close();
_fileName = filepath;
std::string path;
if ( _path.size()==0 )
{
path = _fileName;
}
else
{
path = _path + "/" + _fileName;
}
_file = fopen(path.c_str(),"rb+");
if ( _file )
return 1;
else
return 0;
}
int Standard::read(void *file,uint32_t size)
{
#if TOY_OPTION_CHECK
if ( ! file )
{
toy::Oops(TOY_MARK);
return 0;
}
#endif
if ( isEmpty() )
return 0;
size_t result=fread(file,1,size,_file); // "fread(file,size,1,_file)" was wrong.
if ( result>size )
{
// fread() has wrong
toy::Log("(%d,%d)\n",result,size);
toy::Oops(TOY_MARK);
return 0;
}
return result;
}
bool Standard::write(void *file,uint32_t size)
{
if ( isEmpty() ) return 0;
fwrite(file,(size_t)size,1,_file);
return 1;
}
bool Standard::seek(enum Option option,int32_t offset)
{
if ( isEmpty() ) return 0;
switch (option)
{
case Base::SET:
fseek( _file, offset, SEEK_SET );
break;
case Base::END:
fseek( _file, offset, SEEK_END );
break;
case Base::CUR:
default:
fseek( _file, offset, SEEK_CUR );
break;
}
return 1;
}
void* Standard::getFilePointer()
{
return (void*)_file;
}
<|endoftext|>
|
<commit_before>#include "kfusion.h"
#include "helpers.h"
#include <iostream>
#include <sstream>
#include <iomanip>
#ifdef __APPLE__
#include <GLUT/glut.h>
#else
#include <GL/glut.h>
#endif
#include "perfstats.h"
using namespace std;
using namespace TooN;
#include <libfreenect.h>
#include <libfreenect-registration.h>
freenect_context *f_ctx;
freenect_device *f_dev;
bool gotDepth;
freenect_registration registration;
void depth_cb(freenect_device *dev, void *v_depth, uint32_t timestamp)
{
gotDepth = true;
}
int InitKinect( uint16_t * buffer, void * rgb_buffer ){
if (freenect_init(&f_ctx, NULL) < 0) {
cout << "freenect_init() failed" << endl;
return 1;
}
freenect_set_log_level(f_ctx, FREENECT_LOG_WARNING);
freenect_select_subdevices(f_ctx, (freenect_device_flags)(FREENECT_DEVICE_MOTOR | FREENECT_DEVICE_CAMERA));
int nr_devices = freenect_num_devices (f_ctx);
cout << "Number of devices found: " << nr_devices << endl;
if (nr_devices < 1)
return 1;
if (freenect_open_device(f_ctx, &f_dev, 0) < 0) {
cout << "Could not open device" << endl;
return 1;
}
freenect_set_depth_callback(f_dev, depth_cb);
freenect_set_depth_mode(f_dev, freenect_find_depth_mode(FREENECT_RESOLUTION_MEDIUM, FREENECT_DEPTH_REGISTERED));
freenect_set_depth_buffer(f_dev, buffer);
// freenect_set_video_callback(f_dev, rgb_cb);
freenect_set_video_mode(f_dev, freenect_find_video_mode(FREENECT_RESOLUTION_MEDIUM, FREENECT_VIDEO_RGB));
freenect_set_video_buffer(f_dev, rgb_buffer);
freenect_start_depth(f_dev);
freenect_start_video(f_dev);
registration = freenect_copy_registration(f_dev);
gotDepth = false;
return 0;
}
float GetFocalLength() {
return registration.zero_plane_info.reference_distance / (2 * registration.zero_plane_info.reference_pixel_size );
}
void CloseKinect(){
freenect_stop_depth(f_dev);
freenect_close_device(f_dev);
freenect_shutdown(f_ctx);
}
void DepthFrameKinect() {
while (!gotDepth && freenect_process_events(f_ctx) >= 0){
}
gotDepth = false;
}
KFusion kfusion;
Image<uchar4, HostDevice> lightScene, depth, lightModel, texModel;
Image<uint16_t, HostDevice> depthImage;
Image<uchar3, HostDevice> rgbImage;
const float3 light = make_float3(-2.0, -2.0, 0);
const float3 ambient = make_float3(0.1, 0.1, 0.1);
SE3<float> initPose;
int counter = 0;
int integration_rate = 2;
bool reset = true;
Image<float3, Device> pos, normals;
Image<float, Device> dep;
void display(void){
const uint2 imageSize = kfusion.configuration.inputSize;
static bool integrate = true;
glClear( GL_COLOR_BUFFER_BIT );
const double startFrame = Stats.start();
DepthFrameKinect();
const double startProcessing = Stats.sample("kinect");
kfusion.setKinectDeviceDepth(depthImage.getDeviceImage());
Stats.sample("raw to cooked");
integrate = kfusion.Track();
Stats.sample("track");
if((integrate && ((counter % integration_rate) == 0)) || reset){
kfusion.Integrate();
Stats.sample("integrate");
reset = false;
}
renderLight( lightModel.getDeviceImage(), kfusion.vertex, kfusion.normal, light, ambient);
renderLight( lightScene.getDeviceImage(), kfusion.inputVertex[0], kfusion.inputNormal[0], light, ambient );
renderTrackResult( depth.getDeviceImage(), kfusion.reduction );
static int count = 4;
if(count > 3){
renderInput( pos, normals, dep, kfusion.integration, toMatrix4(SE3<float>::exp(makeVector(1.0, 1.0, -1.0, 0, 0, 0))) * getInverseCameraMatrix(kfusion.configuration.camera), kfusion.configuration.nearPlane, kfusion.configuration.farPlane, kfusion.configuration.stepSize(), 0.75 * kfusion.configuration.mu);
count = 0;
} else
count++;
renderTexture( texModel.getDeviceImage(), pos, normals, rgbImage.getDeviceImage(), getCameraMatrix(kfusion.configuration.camera * 2) * inverse(kfusion.pose), light);
cudaDeviceSynchronize();
Stats.sample("render");
glClear(GL_COLOR_BUFFER_BIT);
glRasterPos2i(0,imageSize.y * 0);
glDrawPixels(lightScene);
glRasterPos2i(imageSize.x, imageSize.y * 0);
glDrawPixels(depth);
glRasterPos2i(0,imageSize.y * 1);
glDrawPixels(lightModel);
glRasterPos2i(imageSize.x, imageSize.y);
glDrawPixels(texModel);
const double endProcessing = Stats.sample("draw");
Stats.sample("total", endProcessing - startFrame, PerfStats::TIME);
Stats.sample("total_proc", endProcessing - startProcessing, PerfStats::TIME);
if(printCUDAError())
exit(1);
++counter;
if(counter % 50 == 0){
Stats.print();
Stats.reset();
cout << endl;
}
glutSwapBuffers();
}
void idle(void){
glutPostRedisplay();
}
void keys(unsigned char key, int x, int y){
switch(key){
case 'c':
kfusion.Reset();
kfusion.setPose(toMatrix4(initPose));
reset = true;
break;
case 'q':
exit(0);
break;
}
}
void reshape(int width, int height){
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glViewport(0, 0, width, height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glColor3f(1.0f,1.0f,1.0f);
glRasterPos2f(-1, 1);
glOrtho(-0.375, width-0.375, height-0.375, -0.375, -1 , 1); //offsets to make (0,0) the top left pixel (rather than off the display)
glPixelZoom(1,-1);
}
void exitFunc(void){
CloseKinect();
kfusion.Clear();
cudaDeviceReset();
}
int main(int argc, char ** argv) {
const float size = (argc > 1) ? atof(argv[1]) : 2.f;
KFusionConfig config;
// it is enough now to set the volume resolution once.
// everything else is derived from that.
// config.volumeSize = make_uint3(64);
config.volumeSize = make_uint3(128);
// config.volumeSize = make_uint3(256);
// these are physical dimensions in meters
config.volumeDimensions = make_float3(size);
config.nearPlane = 0.4f;
config.farPlane = 5.0f;
config.mu = 0.1;
config.combinedTrackAndReduce = false;
// change the following parameters for using 640 x 480 input images
config.inputSize = make_uint2(320,240);
// config.iterations is a vector<int>, the length determines
// the number of levels to be used in tracking
// push back more then 3 iteraton numbers to get more levels.
config.iterations[0] = 10;
config.iterations[1] = 5;
config.iterations[2] = 4;
config.dist_threshold = (argc > 2 ) ? atof(argv[2]) : config.dist_threshold;
config.normal_threshold = (argc > 3 ) ? atof(argv[3]) : config.normal_threshold;
initPose = SE3<float>(makeVector(size/2, size/2, 0, 0, 0, 0));
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE );
glutInitWindowSize(config.inputSize.x * 2, config.inputSize.y * 2);
glutCreateWindow("kfusion");
kfusion.Init(config);
if(printCUDAError()) {
cudaDeviceReset();
exit(1);
}
kfusion.setPose(toMatrix4(initPose));
lightScene.alloc(config.inputSize), depth.alloc(config.inputSize), lightModel.alloc(config.inputSize), texModel.alloc(config.inputSize);
depthImage.alloc(make_uint2(640, 480));
rgbImage.alloc(make_uint2(640, 480));
memset(depthImage.data(), 0, depthImage.size.x*depthImage.size.y * sizeof(uint16_t));
memset(rgbImage.data(), 0, rgbImage.size.x*rgbImage.size.y * sizeof(uchar3));
pos.alloc(config.inputSize), normals.alloc(config.inputSize), dep.alloc(config.inputSize);
if(InitKinect(depthImage.data(), rgbImage.data())){
cudaDeviceReset();
exit(1);
}
// get focal length from Kinect
const float focal_length = GetFocalLength();
config.camera = make_float4(focal_length/2, focal_length/2, 640/4, 480/4);
atexit(exitFunc);
glutDisplayFunc(display);
glutKeyboardFunc(keys);
glutReshapeFunc(reshape);
glutIdleFunc(idle);
glutMainLoop();
CloseKinect();
return 0;
}
<commit_msg>extra kinect thread to aquire frames<commit_after>#include "kfusion.h"
#include "helpers.h"
#include <iostream>
#include <sstream>
#include <iomanip>
#ifdef __APPLE__
#include <GLUT/glut.h>
#else
#include <GL/glut.h>
#endif
#include "perfstats.h"
using namespace std;
using namespace TooN;
#include <libfreenect.h>
#include <libfreenect-registration.h>
#include <pthread.h>
freenect_context *f_ctx;
freenect_device *f_dev;
bool gotDepth;
int depth_index;
freenect_registration registration;
pthread_t freenect_thread;
volatile bool die = false;
uint16_t * buffers[2];
void depth_cb(freenect_device *dev, void *v_depth, uint32_t timestamp)
{
gotDepth = true;
depth_index = (depth_index+1) % 2;
freenect_set_depth_buffer(dev, buffers[depth_index]);
}
void *freenect_threadfunc(void *arg)
{
while(!die){
int res = freenect_process_events(f_ctx);
if (res < 0 && res != -10) {
cout << "\nError "<< res << " received from libusb - aborting.\n";
break;
}
}
freenect_stop_depth(f_dev);
freenect_stop_video(f_dev);
freenect_close_device(f_dev);
freenect_shutdown(f_ctx);
}
int InitKinect( uint16_t * depth_buffer[2], void * rgb_buffer ){
if (freenect_init(&f_ctx, NULL) < 0) {
cout << "freenect_init() failed" << endl;
return 1;
}
freenect_set_log_level(f_ctx, FREENECT_LOG_WARNING);
freenect_select_subdevices(f_ctx, (freenect_device_flags)(FREENECT_DEVICE_MOTOR | FREENECT_DEVICE_CAMERA));
int nr_devices = freenect_num_devices (f_ctx);
cout << "Number of devices found: " << nr_devices << endl;
if (nr_devices < 1)
return 1;
if (freenect_open_device(f_ctx, &f_dev, 0) < 0) {
cout << "Could not open device" << endl;
return 1;
}
depth_index = 0;
buffers[0] = depth_buffer[0];
buffers[1] = depth_buffer[1];
freenect_set_depth_callback(f_dev, depth_cb);
freenect_set_depth_mode(f_dev, freenect_find_depth_mode(FREENECT_RESOLUTION_MEDIUM, FREENECT_DEPTH_REGISTERED));
freenect_set_depth_buffer(f_dev, buffers[depth_index]);
// freenect_set_video_callback(f_dev, rgb_cb);
freenect_set_video_mode(f_dev, freenect_find_video_mode(FREENECT_RESOLUTION_MEDIUM, FREENECT_VIDEO_RGB));
freenect_set_video_buffer(f_dev, rgb_buffer);
freenect_start_depth(f_dev);
freenect_start_video(f_dev);
registration = freenect_copy_registration(f_dev);
gotDepth = false;
int res = pthread_create(&freenect_thread, NULL, freenect_threadfunc, NULL);
if(res){
cout << "error starting kinect thread " << res << endl;
return 1;
}
return 0;
}
float GetFocalLength() {
return registration.zero_plane_info.reference_distance / (2 * registration.zero_plane_info.reference_pixel_size );
}
void CloseKinect(){
die = true;
pthread_join(freenect_thread, NULL);
}
KFusion kfusion;
Image<uchar4, HostDevice> lightScene, depth, lightModel, texModel;
Image<uint16_t, HostDevice> depthImage[2];
Image<uchar3, HostDevice> rgbImage;
const float3 light = make_float3(-2.0, -2.0, 0);
const float3 ambient = make_float3(0.1, 0.1, 0.1);
SE3<float> initPose;
int counter = 0;
int integration_rate = 2;
bool reset = true;
Image<float3, Device> pos, normals;
Image<float, Device> dep;
void display(void){
const uint2 imageSize = kfusion.configuration.inputSize;
static bool integrate = true;
glClear( GL_COLOR_BUFFER_BIT );
const double startFrame = Stats.start();
const double startProcessing = Stats.sample("kinect");
kfusion.setKinectDeviceDepth(depthImage[!depth_index].getDeviceImage());
Stats.sample("raw to cooked");
integrate = kfusion.Track();
Stats.sample("track");
if((integrate && ((counter % integration_rate) == 0)) || reset){
kfusion.Integrate();
Stats.sample("integrate");
reset = false;
}
renderLight( lightModel.getDeviceImage(), kfusion.vertex, kfusion.normal, light, ambient);
renderLight( lightScene.getDeviceImage(), kfusion.inputVertex[0], kfusion.inputNormal[0], light, ambient );
renderTrackResult( depth.getDeviceImage(), kfusion.reduction );
static int count = 4;
if(count > 3){
renderInput( pos, normals, dep, kfusion.integration, toMatrix4(SE3<float>::exp(makeVector(1.0, 1.0, -1.0, 0, 0, 0))) * getInverseCameraMatrix(kfusion.configuration.camera), kfusion.configuration.nearPlane, kfusion.configuration.farPlane, kfusion.configuration.stepSize(), 0.75 * kfusion.configuration.mu);
count = 0;
} else
count++;
renderTexture( texModel.getDeviceImage(), pos, normals, rgbImage.getDeviceImage(), getCameraMatrix(kfusion.configuration.camera * 2) * inverse(kfusion.pose), light);
cudaDeviceSynchronize();
Stats.sample("render");
glClear(GL_COLOR_BUFFER_BIT);
glRasterPos2i(0,imageSize.y * 0);
glDrawPixels(lightScene);
glRasterPos2i(imageSize.x, imageSize.y * 0);
glDrawPixels(depth);
glRasterPos2i(0,imageSize.y * 1);
glDrawPixels(lightModel);
glRasterPos2i(imageSize.x, imageSize.y);
glDrawPixels(texModel);
const double endProcessing = Stats.sample("draw");
Stats.sample("total", endProcessing - startFrame, PerfStats::TIME);
Stats.sample("total_proc", endProcessing - startProcessing, PerfStats::TIME);
if(printCUDAError())
exit(1);
++counter;
if(counter % 50 == 0){
Stats.print();
Stats.reset();
cout << endl;
}
glutSwapBuffers();
}
void idle(void){
if(gotDepth){
gotDepth = false;
glutPostRedisplay();
}
}
void keys(unsigned char key, int x, int y){
switch(key){
case 'c':
kfusion.Reset();
kfusion.setPose(toMatrix4(initPose));
reset = true;
break;
case 'q':
exit(0);
break;
}
}
void reshape(int width, int height){
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glViewport(0, 0, width, height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glColor3f(1.0f,1.0f,1.0f);
glRasterPos2f(-1, 1);
glOrtho(-0.375, width-0.375, height-0.375, -0.375, -1 , 1); //offsets to make (0,0) the top left pixel (rather than off the display)
glPixelZoom(1,-1);
}
void exitFunc(void){
CloseKinect();
kfusion.Clear();
cudaDeviceReset();
}
int main(int argc, char ** argv) {
const float size = (argc > 1) ? atof(argv[1]) : 2.f;
KFusionConfig config;
// it is enough now to set the volume resolution once.
// everything else is derived from that.
// config.volumeSize = make_uint3(64);
config.volumeSize = make_uint3(128);
// config.volumeSize = make_uint3(256);
// these are physical dimensions in meters
config.volumeDimensions = make_float3(size);
config.nearPlane = 0.4f;
config.farPlane = 5.0f;
config.mu = 0.1;
config.combinedTrackAndReduce = false;
// change the following parameters for using 640 x 480 input images
config.inputSize = make_uint2(320,240);
// config.iterations is a vector<int>, the length determines
// the number of levels to be used in tracking
// push back more then 3 iteraton numbers to get more levels.
config.iterations[0] = 10;
config.iterations[1] = 5;
config.iterations[2] = 4;
config.dist_threshold = (argc > 2 ) ? atof(argv[2]) : config.dist_threshold;
config.normal_threshold = (argc > 3 ) ? atof(argv[3]) : config.normal_threshold;
initPose = SE3<float>(makeVector(size/2, size/2, 0, 0, 0, 0));
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE );
glutInitWindowSize(config.inputSize.x * 2, config.inputSize.y * 2);
glutCreateWindow("kfusion");
kfusion.Init(config);
if(printCUDAError()) {
cudaDeviceReset();
exit(1);
}
kfusion.setPose(toMatrix4(initPose));
lightScene.alloc(config.inputSize), depth.alloc(config.inputSize), lightModel.alloc(config.inputSize), texModel.alloc(config.inputSize);
depthImage[0].alloc(make_uint2(640, 480));
depthImage[1].alloc(make_uint2(640, 480));
rgbImage.alloc(make_uint2(640, 480));
memset(depthImage[0].data(), 0, depthImage[0].size.x*depthImage[0].size.y * sizeof(uint16_t));
memset(depthImage[1].data(), 0, depthImage[1].size.x*depthImage[1].size.y * sizeof(uint16_t));
memset(rgbImage.data(), 0, rgbImage.size.x*rgbImage.size.y * sizeof(uchar3));
pos.alloc(config.inputSize), normals.alloc(config.inputSize), dep.alloc(config.inputSize);
uint16_t * buffers[2] = {depthImage[0].data(), depthImage[1].data()};
if(InitKinect(buffers, rgbImage.data())){
cudaDeviceReset();
exit(1);
}
// get focal length from Kinect
const float focal_length = GetFocalLength();
config.camera = make_float4(focal_length/2, focal_length/2, 640/4, 480/4);
atexit(exitFunc);
glutDisplayFunc(display);
glutKeyboardFunc(keys);
glutReshapeFunc(reshape);
glutIdleFunc(idle);
glutMainLoop();
CloseKinect();
return 0;
}
<|endoftext|>
|
<commit_before>#include "HECL/HECL.hpp"
namespace HECL
{
unsigned VerbosityLevel = 0;
LogVisor::LogModule LogModule("HECL");
void SanitizePath(std::string& path)
{
if (path.empty())
return;
path.erase(std::remove(path.begin(), path.end(), '\n'), path.end());
path.erase(std::remove(path.begin(), path.end(), '\r'), path.end());
std::string::iterator p1 = path.begin();
bool ic = false;
std::transform(path.begin(), path.end(), path.begin(), [&](const char a) -> char {
++p1;
if (ic)
{
ic = false;
return a;
}
static const std::string illegals {"<>?*\"|"};
if (illegals.find_first_of(a) != std::string::npos)
return '_';
if (a == '\\' && (p1 == path.end() || *p1 != '\\'))
{
ic = true;
return '/';
}
return a;
});
}
void SanitizePath(std::wstring& path)
{
if (path.empty())
return;
path.erase(std::remove(path.begin(), path.end(), L'\n'), path.end());
path.erase(std::remove(path.begin(), path.end(), L'\r'), path.end());
std::wstring::iterator p1 = path.begin();
bool ic = false;
std::transform(path.begin(), path.end(), path.begin(), [&](const wchar_t a) -> wchar_t {
++p1;
if (ic)
{
ic = false;
return a;
}
static const std::wstring illegals {L"<>?*\"|"};
if (illegals.find_first_of(a) != std::wstring::npos)
return L'_';
if (a == L'\\' && (p1 == path.end() || *p1 != L'\\'))
{
ic = true;
return L'/';
}
return a;
});
}
bool IsPathPNG(const HECL::ProjectPath& path)
{
FILE* fp = HECL::Fopen(path.getAbsolutePath().c_str(), _S("rb"));
if (!fp)
return false;
uint32_t buf;
if (fread(&buf, 1, 4, fp) != 4)
{
fclose(fp);
return false;
}
fclose(fp);
buf = HECL::SBig(buf);
if (buf == 0x89504e47)
return true;
return false;
}
bool IsPathBlend(const HECL::ProjectPath& path)
{
const SystemChar* lastCompExt = path.getLastComponentExt();
if (!lastCompExt || HECL::StrCmp(lastCompExt, _S("blend")))
return false;
FILE* fp = HECL::Fopen(path.getAbsolutePath().c_str(), _S("rb"));
if (!fp)
return false;
uint32_t buf;
if (fread(&buf, 1, 4, fp) != 4)
{
fclose(fp);
return false;
}
fclose(fp);
buf = HECL::SLittle(buf);
if (buf == 0x4e454c42 || buf == 0x88b1f)
return true;
return false;
}
bool IsPathYAML(const HECL::ProjectPath& path)
{
const SystemChar* lastCompExt = path.getLastComponentExt();
if (!lastCompExt)
return false;
if (!HECL::StrCmp(lastCompExt, _S("yaml")) ||
!HECL::StrCmp(lastCompExt, _S("yml")))
return true;
return false;
}
}
<commit_msg>Fix possible false positive<commit_after>#include "HECL/HECL.hpp"
namespace HECL
{
unsigned VerbosityLevel = 0;
LogVisor::LogModule LogModule("HECL");
void SanitizePath(std::string& path)
{
if (path.empty())
return;
path.erase(std::remove(path.begin(), path.end(), '\n'), path.end());
path.erase(std::remove(path.begin(), path.end(), '\r'), path.end());
std::string::iterator p1 = path.begin();
bool ic = false;
std::transform(path.begin(), path.end(), path.begin(), [&](const char a) -> char {
++p1;
static const std::string illegals {"<>?*\"|"};
if (illegals.find_first_of(a) != std::string::npos)
{
ic = false;
return '_';
}
if (ic)
{
ic = false;
return a;
}
if (a == '\\' && (p1 == path.end() || *p1 != '\\'))
{
ic = true;
return '/';
}
return a;
});
}
void SanitizePath(std::wstring& path)
{
if (path.empty())
return;
path.erase(std::remove(path.begin(), path.end(), L'\n'), path.end());
path.erase(std::remove(path.begin(), path.end(), L'\r'), path.end());
std::wstring::iterator p1 = path.begin();
bool ic = false;
std::transform(path.begin(), path.end(), path.begin(), [&](const wchar_t a) -> wchar_t {
++p1;
static const std::wstring illegals {L"<>?*\"|"};
if (illegals.find_first_of(a) != std::wstring::npos)
{
ic = false;
return L'_';
}
if (ic)
{
ic = false;
return a;
}
if (a == L'\\' && (p1 == path.end() || *p1 != L'\\'))
{
ic = true;
return L'/';
}
return a;
});
}
bool IsPathPNG(const HECL::ProjectPath& path)
{
FILE* fp = HECL::Fopen(path.getAbsolutePath().c_str(), _S("rb"));
if (!fp)
return false;
uint32_t buf;
if (fread(&buf, 1, 4, fp) != 4)
{
fclose(fp);
return false;
}
fclose(fp);
buf = HECL::SBig(buf);
if (buf == 0x89504e47)
return true;
return false;
}
bool IsPathBlend(const HECL::ProjectPath& path)
{
const SystemChar* lastCompExt = path.getLastComponentExt();
if (!lastCompExt || HECL::StrCmp(lastCompExt, _S("blend")))
return false;
FILE* fp = HECL::Fopen(path.getAbsolutePath().c_str(), _S("rb"));
if (!fp)
return false;
uint32_t buf;
if (fread(&buf, 1, 4, fp) != 4)
{
fclose(fp);
return false;
}
fclose(fp);
buf = HECL::SLittle(buf);
if (buf == 0x4e454c42 || buf == 0x88b1f)
return true;
return false;
}
bool IsPathYAML(const HECL::ProjectPath& path)
{
const SystemChar* lastCompExt = path.getLastComponentExt();
if (!lastCompExt)
return false;
if (!HECL::StrCmp(lastCompExt, _S("yaml")) ||
!HECL::StrCmp(lastCompExt, _S("yml")))
return true;
return false;
}
}
<|endoftext|>
|
<commit_before>// Copyright 2014 Toggl Desktop developers.
#include "../src/timeline_uploader.h"
#include <sstream>
#include <string>
#include "./const.h"
#include "./formatter.h"
#include "./https_client.h"
#include "Poco/Foundation.h"
#include "Poco/Thread.h"
#include "Poco/Util/Application.h"
#include <json/json.h> // NOLINT
namespace toggl {
Poco::Logger &TimelineUploader::logger() const {
return Poco::Logger::get("timeline_uploader");
}
void TimelineUploader::sleep() {
// Sleep in increments for faster shutdown.
for (unsigned int i = 0; i < current_upload_interval_seconds_*4; i++) {
if (uploading_.isStopped()) {
return;
}
Poco::Thread::sleep(250);
}
}
void TimelineUploader::upload_loop_activity() {
while (!uploading_.isStopped()) {
error err = process();
if (err != noError) {
logger().error(err);
}
sleep();
}
}
error TimelineUploader::process() {
{
std::stringstream out;
out << "upload_loop_activity (current interval "
<< current_upload_interval_seconds_ << "s)";
logger().debug(out.str());
}
if (uploading_.isStopped()) {
return noError;
}
TimelineBatch batch;
error err = timeline_datasource_->CreateTimelineBatch(&batch);
if (err != noError) {
return err;
}
if (!batch.Events().size()) {
return noError;
}
if (uploading_.isStopped()) {
return noError;
}
err = upload(&batch);
if (err != noError) {
backoff();
return err;
}
{
std::stringstream out;
out << "Sync of " << batch.Events().size()
<< " event(s) was successful.";
logger().debug(out.str());
}
reset_backoff();
return timeline_datasource_->DeleteTimelineBatch(batch.Events());
}
error TimelineUploader::upload(TimelineBatch *batch) {
TogglClient client;
std::stringstream out;
out << "Uploading " << batch->Events().size()
<< " event(s) of user " << batch->UserID();
logger().debug(out.str());
std::string json = convertTimelineToJSON(batch->Events(),
batch->DesktopID());
std::string response_body("");
return client.PostJSON(kTimelineUploadURL,
"/api/v8/timeline",
json,
batch->APIToken(),
"api_token",
&response_body);
}
std::string convertTimelineToJSON(
const std::vector<TimelineEvent> &timeline_events,
const std::string &desktop_id) {
Json::Value root;
for (std::vector<TimelineEvent>::const_iterator i = timeline_events.begin();
i != timeline_events.end();
++i) {
const TimelineEvent &event = *i;
// initialize new event node
Json::Value n;
// add fields to event node
if (event.idle) {
n["idle"] = true;
} else {
n["filename"] = event.filename;
n["title"] = event.title;
}
n["start_time"] = Json::Int64(event.start_time);
n["end_time"] = Json::Int64(event.end_time);
n["desktop_id"] = desktop_id;
n["created_with"] = "timeline";
// Push event node to array
root.append(n);
}
Json::StyledWriter writer;
return writer.write(root);
}
void TimelineUploader::backoff() {
logger().warning("backoff");
current_upload_interval_seconds_ *= 2;
if (current_upload_interval_seconds_ > kTimelineUploadMaxBackoffSeconds) {
logger().warning("Max upload interval reached.");
current_upload_interval_seconds_ = kTimelineUploadMaxBackoffSeconds;
}
std::stringstream out;
out << "Upload interval set to " << current_upload_interval_seconds_ << "s";
logger().debug(out.str());
}
void TimelineUploader::reset_backoff() {
logger().debug("reset_backoff");
current_upload_interval_seconds_ = kTimelineUploadIntervalSeconds;
}
error TimelineUploader::start() {
try {
uploading_.start();
} catch(const Poco::Exception& exc) {
return exc.displayText();
} catch(const std::exception& ex) {
return ex.what();
} catch(const std::string& ex) {
return ex;
}
return noError;
}
error TimelineUploader::Shutdown() {
try {
if (uploading_.isRunning()) {
uploading_.stop();
uploading_.wait();
}
} catch(const Poco::Exception& exc) {
return exc.displayText();
} catch(const std::exception& ex) {
return ex.what();
} catch(const std::string& ex) {
return ex;
}
return noError;
}
} // namespace toggl
<commit_msg>Remove useless comments<commit_after>// Copyright 2014 Toggl Desktop developers.
#include "../src/timeline_uploader.h"
#include <sstream>
#include <string>
#include "./const.h"
#include "./formatter.h"
#include "./https_client.h"
#include "Poco/Foundation.h"
#include "Poco/Thread.h"
#include "Poco/Util/Application.h"
#include <json/json.h> // NOLINT
namespace toggl {
Poco::Logger &TimelineUploader::logger() const {
return Poco::Logger::get("timeline_uploader");
}
void TimelineUploader::sleep() {
// Sleep in increments for faster shutdown.
for (unsigned int i = 0; i < current_upload_interval_seconds_*4; i++) {
if (uploading_.isStopped()) {
return;
}
Poco::Thread::sleep(250);
}
}
void TimelineUploader::upload_loop_activity() {
while (!uploading_.isStopped()) {
error err = process();
if (err != noError) {
logger().error(err);
}
sleep();
}
}
error TimelineUploader::process() {
{
std::stringstream out;
out << "upload_loop_activity (current interval "
<< current_upload_interval_seconds_ << "s)";
logger().debug(out.str());
}
if (uploading_.isStopped()) {
return noError;
}
TimelineBatch batch;
error err = timeline_datasource_->CreateTimelineBatch(&batch);
if (err != noError) {
return err;
}
if (!batch.Events().size()) {
return noError;
}
if (uploading_.isStopped()) {
return noError;
}
err = upload(&batch);
if (err != noError) {
backoff();
return err;
}
{
std::stringstream out;
out << "Sync of " << batch.Events().size()
<< " event(s) was successful.";
logger().debug(out.str());
}
reset_backoff();
return timeline_datasource_->DeleteTimelineBatch(batch.Events());
}
error TimelineUploader::upload(TimelineBatch *batch) {
TogglClient client;
std::stringstream out;
out << "Uploading " << batch->Events().size()
<< " event(s) of user " << batch->UserID();
logger().debug(out.str());
std::string json = convertTimelineToJSON(batch->Events(),
batch->DesktopID());
std::string response_body("");
return client.PostJSON(kTimelineUploadURL,
"/api/v8/timeline",
json,
batch->APIToken(),
"api_token",
&response_body);
}
std::string convertTimelineToJSON(
const std::vector<TimelineEvent> &timeline_events,
const std::string &desktop_id) {
Json::Value root;
for (std::vector<TimelineEvent>::const_iterator i = timeline_events.begin();
i != timeline_events.end();
++i) {
const TimelineEvent &event = *i;
Json::Value n;
if (event.idle) {
n["idle"] = true;
} else {
n["filename"] = event.filename;
n["title"] = event.title;
}
n["start_time"] = Json::Int64(event.start_time);
n["end_time"] = Json::Int64(event.end_time);
n["desktop_id"] = desktop_id;
n["created_with"] = "timeline";
root.append(n);
}
Json::StyledWriter writer;
return writer.write(root);
}
void TimelineUploader::backoff() {
logger().warning("backoff");
current_upload_interval_seconds_ *= 2;
if (current_upload_interval_seconds_ > kTimelineUploadMaxBackoffSeconds) {
logger().warning("Max upload interval reached.");
current_upload_interval_seconds_ = kTimelineUploadMaxBackoffSeconds;
}
std::stringstream out;
out << "Upload interval set to " << current_upload_interval_seconds_ << "s";
logger().debug(out.str());
}
void TimelineUploader::reset_backoff() {
logger().debug("reset_backoff");
current_upload_interval_seconds_ = kTimelineUploadIntervalSeconds;
}
error TimelineUploader::start() {
try {
uploading_.start();
} catch(const Poco::Exception& exc) {
return exc.displayText();
} catch(const std::exception& ex) {
return ex.what();
} catch(const std::string& ex) {
return ex;
}
return noError;
}
error TimelineUploader::Shutdown() {
try {
if (uploading_.isRunning()) {
uploading_.stop();
uploading_.wait();
}
} catch(const Poco::Exception& exc) {
return exc.displayText();
} catch(const std::exception& ex) {
return ex.what();
} catch(const std::string& ex) {
return ex;
}
return noError;
}
} // namespace toggl
<|endoftext|>
|
<commit_before>
#ifdef CPU_TIME
#include "timing_functions.h"
#include "io.h"
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
#ifdef MPI_CHOLLA
#include "mpi_routines.h"
#endif
Time::Time( void ){}
void Time::Initialize(){
n_steps = 0;
time_hydro_all = 0;
time_bound_all = 0;
time_dt_all = 0;
#ifdef GRAVITY
time_potential_all = 0;
time_bound_pot_all = 0;
#endif
#ifdef PARTICLES
time_part_dens_all = 0;
time_part_dens_transf_all = 0;
time_part_tranf_all = 0;
time_advance_particles_1_all = 0;
time_advance_particles_2_all = 0;
#endif
#ifdef COOLING_GRACKLE
time_cooling_all = 0;
#endif
chprintf( "\nTiming Functions is ON \n");
}
void Time::Start_Timer(){
time_start = get_time();
}
void Time::End_and_Record_Time( int time_var ){
time_end = get_time();
time = (time_end - time_start)*1000;
Real t_min, t_max, t_avg;
#ifdef MPI_CHOLLA
t_min = ReduceRealMin(time);
t_max = ReduceRealMax(time);
t_avg = ReduceRealAvg(time);
#else
t_min = time;
t_max = time;
t_avg = time;
#endif
if( time_var == 0 ){
time_dt_min = t_min;
time_dt_max = t_max;
time_dt_mean = t_avg;
if (n_steps > 0) time_dt_all += t_max;
}
if( time_var == 1 ){
time_hydro_min = t_min;
time_hydro_max = t_max;
time_hydro_mean = t_avg;
if (n_steps > 0) time_hydro_all += t_max;
}
if( time_var == 2 ){
time_bound_min = t_min;
time_bound_max = t_max;
time_bound_mean = t_avg;
if (n_steps > 0) time_bound_all += t_max;
}
#ifdef GRAVITY
if( time_var == 3 ){
time_potential_min = t_min;
time_potential_max = t_max;
time_potential_mean = t_avg;
if (n_steps > 0) time_potential_all += t_max;
}
if( time_var == 9 ){
time_bound_pot_min = t_min;
time_bound_pot_max = t_max;
time_bound_pot_mean = t_avg;
if (n_steps > 0) time_bound_pot_all += t_max;
}
#endif
#ifdef PARTICLES
if( time_var == 4 ){
time_part_dens_min = t_min;
time_part_dens_max = t_max;
time_part_dens_mean = t_avg;
if (n_steps > 0) time_part_dens_all += t_max;
}
if( time_var == 5 ){
time_part_dens_transf_min = t_min;
time_part_dens_transf_max = t_max;
time_part_dens_transf_mean = t_avg;
if (n_steps > 0) time_part_dens_transf_all += t_max;
}
if( time_var == 6 ){
time_advance_particles_1_min = t_min;
time_advance_particles_1_max = t_max;
time_advance_particles_1_mean = t_avg;
if (n_steps > 0) time_advance_particles_1_all += t_max;
}
if( time_var == 7 ){
time_advance_particles_2_min = t_min;
time_advance_particles_2_max = t_max;
time_advance_particles_2_mean = t_avg;
if (n_steps > 0) time_advance_particles_2_all += t_max;
}
if( time_var == 8 ){
time_part_tranf_min = t_min;
time_part_tranf_max = t_max;
time_part_tranf_mean = t_avg;
if (n_steps > 0) time_part_tranf_all += t_max;
}
#endif
#ifdef COOLING_GRACKLE
if( time_var == 10 ){
time_cooling_min = t_min;
time_cooling_max = t_max;
time_cooling_mean = t_avg;
if (n_steps > 0) time_cooling_all += t_max;
}
#endif
}
void Time::Print_Times(){
#if defined(GRAVITY_COUPLE_CPU) || defined( PARTICLES )
chprintf(" Time Calc dt min: %9.4f max: %9.4f avg: %9.4f ms\n", time_dt_min, time_dt_max, time_dt_mean);
#endif
chprintf(" Time Hydro min: %9.4f max: %9.4f avg: %9.4f ms\n", time_hydro_min, time_hydro_max, time_hydro_mean);
chprintf(" Time Boundaries min: %9.4f max: %9.4f avg: %9.4f ms\n", time_bound_min, time_bound_max, time_bound_mean);
#ifdef GRAVITY
chprintf(" Time Grav Potential min: %9.4f max: %9.4f avg: %9.4f ms\n", time_potential_min, time_potential_max, time_potential_mean);
chprintf(" Time Pot Boundaries min: %9.4f max: %9.4f avg: %9.4f ms\n", time_bound_pot_min, time_bound_pot_max, time_bound_pot_mean);
#endif
#ifdef PARTICLES
chprintf(" Time Part Density min: %9.4f max: %9.4f avg: %9.4f ms\n", time_part_dens_min, time_part_dens_max, time_part_dens_mean);
chprintf(" Time Part Boundaries min: %9.4f max: %9.4f avg: %9.4f ms\n", time_part_tranf_min, time_part_tranf_max, time_part_tranf_mean);
chprintf(" Time Part Dens Transf min: %9.4f max: %9.4f avg: %9.4f ms\n", time_part_dens_transf_min, time_part_dens_transf_max, time_part_dens_transf_mean);
chprintf(" Time Advance Part 1 min: %9.4f max: %9.4f avg: %9.4f ms\n", time_advance_particles_1_min, time_advance_particles_1_max, time_advance_particles_1_mean);
chprintf(" Time Advance Part 2 min: %9.4f max: %9.4f avg: %9.4f ms\n", time_advance_particles_2_min, time_advance_particles_2_max, time_advance_particles_2_mean);
#endif
#ifdef COOLING_GRACKLE
chprintf(" Time Cooling min: %9.4f max: %9.4f avg: %9.4f ms\n", time_cooling_min, time_cooling_max, time_cooling_mean);
#endif
}
void Time::Get_Average_Times(){
n_steps -= 1; //Ignore the first timestep
time_hydro_all /= n_steps;
time_bound_all /= n_steps;
#ifdef GRAVITY_COUPLE_CPU
time_dt_all /= n_steps;
time_bound_pot_all /= n_steps;
#endif
#ifdef GRAVITY
time_potential_all /= n_steps;
#ifdef PARTICLES
time_part_dens_all /= n_steps;
time_part_tranf_all /= n_steps;
time_part_dens_transf_all /= n_steps;
time_advance_particles_1_all /= n_steps;
time_advance_particles_2_all /= n_steps;
#endif
#endif
#ifdef COOLING_GRACKLE
time_cooling_all /= n_steps;
#endif
}
void Time::Print_Average_Times( struct parameters P ){
Real time_total;
time_total = time_hydro_all + time_bound_all;
#ifdef GRAVITY_COUPLE_CPU
time_total += time_dt_all;
time_total += time_bound_pot_all;
#endif
#ifdef GRAVITY
time_total += time_potential_all;
#ifdef PARTICLES
time_total += time_part_dens_all;
time_total += time_part_tranf_all;
time_total += time_part_dens_transf_all;
time_total += time_advance_particles_1_all;
time_total += time_advance_particles_2_all;
#endif
#endif
#ifdef COOLING_GRACKLE
time_total += time_cooling_all;
#endif
chprintf("\nAverage Times n_steps:%d\n", n_steps);
#ifdef GRAVITY_COUPLE_CPU
chprintf(" Time Calc dt avg: %9.4f ms\n", time_dt_all);
#endif
chprintf(" Time Hydro avg: %9.4f ms\n", time_hydro_all);
chprintf(" Time Boundaries avg: %9.4f ms\n", time_bound_all);
#ifdef GRAVITY
chprintf(" Time Grav Potential avg: %9.4f ms\n", time_potential_all);
chprintf(" Time Pot Boundaries avg: %9.4f ms\n", time_bound_pot_all);
#ifdef PARTICLES
chprintf(" Time Part Density avg: %9.4f ms\n", time_part_dens_all);
chprintf(" Time Part Boundaries avg: %9.4f ms\n", time_part_tranf_all);
chprintf(" Time Part Dens Transf avg: %9.4f ms\n", time_part_dens_transf_all);
chprintf(" Time Advance Part 1 avg: %9.4f ms\n", time_advance_particles_1_all);
chprintf(" Time Advance Part 2 avg: %9.4f ms\n", time_advance_particles_2_all);
#endif
#endif
#ifdef COOLING_GRACKLE
chprintf(" Time Cooling avg: %9.4f ms\n", time_cooling_all);
#endif
chprintf(" Time Total avg: %9.4f ms\n\n", time_total);
string file_name ( "run_timing.log" );
string header;
chprintf( "Writing timming values to file: %s \n", file_name.c_str());
header = "# nx ny nz n_proc n_omp n_steps ";
#ifdef GRAVITY_COUPLE_CPU
header += "dt ";
#endif
header += "hydo ";
header += "bound ";
#ifdef GRAVITY
header += "grav_pot ";
#ifdef GRAVITY_COUPLE_CPU
header += "pot_bound ";
#endif
#endif
#ifdef PARTICLES
header += "part_dens ";
header += "part_bound ";
header += "part_dens_boud ";
header += "part_adv_1 ";
header += "part_adv_2 ";
#endif
#ifdef COOLING_GRACKLE
header += "cool ";
#endif
header += "total ";
header += " \n";
bool file_exists = false;
if (FILE *file = fopen(file_name.c_str(), "r")){
file_exists = true;
chprintf( " File exists, appending values: %s \n\n", file_name.c_str() );
fclose( file );
} else{
chprintf( " Creating File: %s \n\n", file_name.c_str() );
}
#ifdef MPI_CHOLLA
if ( procID != 0 ) return;
#endif
ofstream out_file;
// Output timing values
out_file.open(file_name.c_str(), ios::app);
if ( !file_exists ) out_file << header;
out_file << P.nx << " " << P.ny << " " << P.nz << " ";
#ifdef MPI_CHOLLA
out_file << nproc << " ";
#else
out_file << 1 << " ";
#endif
#ifdef PARALLEL_OMP
out_file << N_OMP_THREADS << " ";
#else
out_file << 0 << " ";
#endif
out_file << n_steps << " ";
#ifdef GRAVITY_COUPLE_CPU
out_file << time_dt_all << " ";
#endif
out_file << time_hydro_all << " ";
out_file << time_bound_all << " ";
#ifdef GRAVITY
out_file << time_potential_all << " ";
#ifdef GRAVITY_COUPLE_CPU
out_file << time_bound_pot_all << " ";
#endif
#endif
#ifdef PARTICLES
out_file << time_part_dens_all << " ";
out_file << time_part_tranf_all << " ";
out_file << time_part_dens_transf_all << " ";
out_file << time_advance_particles_1_all << " ";
out_file << time_advance_particles_2_all << " ";
#endif
#ifdef COOLING_GRACKLE
out_file << time_cooling_all << " ";
#endif
out_file << time_total << " ";
out_file << "\n";
out_file.close();
}
#endif<commit_msg>only calc_dt timming when using gravity<commit_after>
#ifdef CPU_TIME
#include "timing_functions.h"
#include "io.h"
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
#ifdef MPI_CHOLLA
#include "mpi_routines.h"
#endif
Time::Time( void ){}
void Time::Initialize(){
n_steps = 0;
time_hydro_all = 0;
time_bound_all = 0;
#ifdef GRAVITY
time_dt_all = 0;
time_potential_all = 0;
time_bound_pot_all = 0;
#endif
#ifdef PARTICLES
time_part_dens_all = 0;
time_part_dens_transf_all = 0;
time_part_tranf_all = 0;
time_advance_particles_1_all = 0;
time_advance_particles_2_all = 0;
#endif
#ifdef COOLING_GRACKLE
time_cooling_all = 0;
#endif
chprintf( "\nTiming Functions is ON \n");
}
void Time::Start_Timer(){
time_start = get_time();
}
void Time::End_and_Record_Time( int time_var ){
time_end = get_time();
time = (time_end - time_start)*1000;
Real t_min, t_max, t_avg;
#ifdef MPI_CHOLLA
t_min = ReduceRealMin(time);
t_max = ReduceRealMax(time);
t_avg = ReduceRealAvg(time);
#else
t_min = time;
t_max = time;
t_avg = time;
#endif
#ifdef GRAVITY
if( time_var == 0 ){
time_dt_min = t_min;
time_dt_max = t_max;
time_dt_mean = t_avg;
if (n_steps > 0) time_dt_all += t_max;
}
#endif
if( time_var == 1 ){
time_hydro_min = t_min;
time_hydro_max = t_max;
time_hydro_mean = t_avg;
if (n_steps > 0) time_hydro_all += t_max;
}
if( time_var == 2 ){
time_bound_min = t_min;
time_bound_max = t_max;
time_bound_mean = t_avg;
if (n_steps > 0) time_bound_all += t_max;
}
#ifdef GRAVITY
if( time_var == 3 ){
time_potential_min = t_min;
time_potential_max = t_max;
time_potential_mean = t_avg;
if (n_steps > 0) time_potential_all += t_max;
}
if( time_var == 9 ){
time_bound_pot_min = t_min;
time_bound_pot_max = t_max;
time_bound_pot_mean = t_avg;
if (n_steps > 0) time_bound_pot_all += t_max;
}
#endif
#ifdef PARTICLES
if( time_var == 4 ){
time_part_dens_min = t_min;
time_part_dens_max = t_max;
time_part_dens_mean = t_avg;
if (n_steps > 0) time_part_dens_all += t_max;
}
if( time_var == 5 ){
time_part_dens_transf_min = t_min;
time_part_dens_transf_max = t_max;
time_part_dens_transf_mean = t_avg;
if (n_steps > 0) time_part_dens_transf_all += t_max;
}
if( time_var == 6 ){
time_advance_particles_1_min = t_min;
time_advance_particles_1_max = t_max;
time_advance_particles_1_mean = t_avg;
if (n_steps > 0) time_advance_particles_1_all += t_max;
}
if( time_var == 7 ){
time_advance_particles_2_min = t_min;
time_advance_particles_2_max = t_max;
time_advance_particles_2_mean = t_avg;
if (n_steps > 0) time_advance_particles_2_all += t_max;
}
if( time_var == 8 ){
time_part_tranf_min = t_min;
time_part_tranf_max = t_max;
time_part_tranf_mean = t_avg;
if (n_steps > 0) time_part_tranf_all += t_max;
}
#endif
#ifdef COOLING_GRACKLE
if( time_var == 10 ){
time_cooling_min = t_min;
time_cooling_max = t_max;
time_cooling_mean = t_avg;
if (n_steps > 0) time_cooling_all += t_max;
}
#endif
}
void Time::Print_Times(){
#if defined(GRAVITY_COUPLE_CPU) || defined( PARTICLES )
chprintf(" Time Calc dt min: %9.4f max: %9.4f avg: %9.4f ms\n", time_dt_min, time_dt_max, time_dt_mean);
#endif
chprintf(" Time Hydro min: %9.4f max: %9.4f avg: %9.4f ms\n", time_hydro_min, time_hydro_max, time_hydro_mean);
chprintf(" Time Boundaries min: %9.4f max: %9.4f avg: %9.4f ms\n", time_bound_min, time_bound_max, time_bound_mean);
#ifdef GRAVITY
chprintf(" Time Grav Potential min: %9.4f max: %9.4f avg: %9.4f ms\n", time_potential_min, time_potential_max, time_potential_mean);
chprintf(" Time Pot Boundaries min: %9.4f max: %9.4f avg: %9.4f ms\n", time_bound_pot_min, time_bound_pot_max, time_bound_pot_mean);
#endif
#ifdef PARTICLES
chprintf(" Time Part Density min: %9.4f max: %9.4f avg: %9.4f ms\n", time_part_dens_min, time_part_dens_max, time_part_dens_mean);
chprintf(" Time Part Boundaries min: %9.4f max: %9.4f avg: %9.4f ms\n", time_part_tranf_min, time_part_tranf_max, time_part_tranf_mean);
chprintf(" Time Part Dens Transf min: %9.4f max: %9.4f avg: %9.4f ms\n", time_part_dens_transf_min, time_part_dens_transf_max, time_part_dens_transf_mean);
chprintf(" Time Advance Part 1 min: %9.4f max: %9.4f avg: %9.4f ms\n", time_advance_particles_1_min, time_advance_particles_1_max, time_advance_particles_1_mean);
chprintf(" Time Advance Part 2 min: %9.4f max: %9.4f avg: %9.4f ms\n", time_advance_particles_2_min, time_advance_particles_2_max, time_advance_particles_2_mean);
#endif
#ifdef COOLING_GRACKLE
chprintf(" Time Cooling min: %9.4f max: %9.4f avg: %9.4f ms\n", time_cooling_min, time_cooling_max, time_cooling_mean);
#endif
}
void Time::Get_Average_Times(){
n_steps -= 1; //Ignore the first timestep
time_hydro_all /= n_steps;
time_bound_all /= n_steps;
#ifdef GRAVITY_COUPLE_CPU
time_dt_all /= n_steps;
time_bound_pot_all /= n_steps;
#endif
#ifdef GRAVITY
time_potential_all /= n_steps;
#ifdef PARTICLES
time_part_dens_all /= n_steps;
time_part_tranf_all /= n_steps;
time_part_dens_transf_all /= n_steps;
time_advance_particles_1_all /= n_steps;
time_advance_particles_2_all /= n_steps;
#endif
#endif
#ifdef COOLING_GRACKLE
time_cooling_all /= n_steps;
#endif
}
void Time::Print_Average_Times( struct parameters P ){
Real time_total;
time_total = time_hydro_all + time_bound_all;
#ifdef GRAVITY_COUPLE_CPU
time_total += time_dt_all;
time_total += time_bound_pot_all;
#endif
#ifdef GRAVITY
time_total += time_potential_all;
#ifdef PARTICLES
time_total += time_part_dens_all;
time_total += time_part_tranf_all;
time_total += time_part_dens_transf_all;
time_total += time_advance_particles_1_all;
time_total += time_advance_particles_2_all;
#endif
#endif
#ifdef COOLING_GRACKLE
time_total += time_cooling_all;
#endif
chprintf("\nAverage Times n_steps:%d\n", n_steps);
#ifdef GRAVITY_COUPLE_CPU
chprintf(" Time Calc dt avg: %9.4f ms\n", time_dt_all);
#endif
chprintf(" Time Hydro avg: %9.4f ms\n", time_hydro_all);
chprintf(" Time Boundaries avg: %9.4f ms\n", time_bound_all);
#ifdef GRAVITY
chprintf(" Time Grav Potential avg: %9.4f ms\n", time_potential_all);
chprintf(" Time Pot Boundaries avg: %9.4f ms\n", time_bound_pot_all);
#ifdef PARTICLES
chprintf(" Time Part Density avg: %9.4f ms\n", time_part_dens_all);
chprintf(" Time Part Boundaries avg: %9.4f ms\n", time_part_tranf_all);
chprintf(" Time Part Dens Transf avg: %9.4f ms\n", time_part_dens_transf_all);
chprintf(" Time Advance Part 1 avg: %9.4f ms\n", time_advance_particles_1_all);
chprintf(" Time Advance Part 2 avg: %9.4f ms\n", time_advance_particles_2_all);
#endif
#endif
#ifdef COOLING_GRACKLE
chprintf(" Time Cooling avg: %9.4f ms\n", time_cooling_all);
#endif
chprintf(" Time Total avg: %9.4f ms\n\n", time_total);
string file_name ( "run_timing.log" );
string header;
chprintf( "Writing timming values to file: %s \n", file_name.c_str());
header = "# nx ny nz n_proc n_omp n_steps ";
#ifdef GRAVITY_COUPLE_CPU
header += "dt ";
#endif
header += "hydo ";
header += "bound ";
#ifdef GRAVITY
header += "grav_pot ";
#ifdef GRAVITY_COUPLE_CPU
header += "pot_bound ";
#endif
#endif
#ifdef PARTICLES
header += "part_dens ";
header += "part_bound ";
header += "part_dens_boud ";
header += "part_adv_1 ";
header += "part_adv_2 ";
#endif
#ifdef COOLING_GRACKLE
header += "cool ";
#endif
header += "total ";
header += " \n";
bool file_exists = false;
if (FILE *file = fopen(file_name.c_str(), "r")){
file_exists = true;
chprintf( " File exists, appending values: %s \n\n", file_name.c_str() );
fclose( file );
} else{
chprintf( " Creating File: %s \n\n", file_name.c_str() );
}
#ifdef MPI_CHOLLA
if ( procID != 0 ) return;
#endif
ofstream out_file;
// Output timing values
out_file.open(file_name.c_str(), ios::app);
if ( !file_exists ) out_file << header;
out_file << P.nx << " " << P.ny << " " << P.nz << " ";
#ifdef MPI_CHOLLA
out_file << nproc << " ";
#else
out_file << 1 << " ";
#endif
#ifdef PARALLEL_OMP
out_file << N_OMP_THREADS << " ";
#else
out_file << 0 << " ";
#endif
out_file << n_steps << " ";
#ifdef GRAVITY_COUPLE_CPU
out_file << time_dt_all << " ";
#endif
out_file << time_hydro_all << " ";
out_file << time_bound_all << " ";
#ifdef GRAVITY
out_file << time_potential_all << " ";
#ifdef GRAVITY_COUPLE_CPU
out_file << time_bound_pot_all << " ";
#endif
#endif
#ifdef PARTICLES
out_file << time_part_dens_all << " ";
out_file << time_part_tranf_all << " ";
out_file << time_part_dens_transf_all << " ";
out_file << time_advance_particles_1_all << " ";
out_file << time_advance_particles_2_all << " ";
#endif
#ifdef COOLING_GRACKLE
out_file << time_cooling_all << " ";
#endif
out_file << time_total << " ";
out_file << "\n";
out_file.close();
}
#endif<|endoftext|>
|
<commit_before>#include <cstdio>
#include <vector>
#include <stack>
#include <algorithm>
#include <memory>
namespace Frogs
{
enum class Frog { None, Brown, Green };
enum class Step { None, JumpLeft, LeapLeft, JumpRight, LeapRight };
class State
{
std::vector<Frog> lilies;
int count, blankPos;
public:
State(int count): lilies(2 * count + 1), count(count), blankPos(count)
{
for (int i = 0; i < count; ++i)
{
lilies[i] = Frog::Brown;
lilies[2 * count - i] = Frog::Green;
}
lilies[blankPos] = Frog::None;
}
bool operator==(const State& other) const
{
return count == other.count && lilies == other.lilies && blankPos == other.blankPos;
}
bool IsStuckJumpLeft() const { return blankPos >= (int)lilies.size() - 1 || lilies[blankPos + 1] != Frog::Green; }
bool IsStuckLeapLeft() const { return blankPos >= (int)lilies.size() - 2 || lilies[blankPos + 2] != Frog::Green; }
bool IsStuckJumpRight() const { return blankPos < 1 || lilies[blankPos - 1] != Frog::Brown; }
bool IsStuckLeapRight() const { return blankPos < 2 || lilies[blankPos - 2] != Frog::Brown; }
bool WasTargetReached() const
{
for (int i = 0; i < count; ++i)
if (lilies[i] != Frog::Green || lilies[2 * count - i] != Frog::Brown)
return false;
return lilies[count] == Frog::None;
}
std::shared_ptr<State> Move(Step step) const
{
bool canMove = false;
auto moved = std::make_shared<State>(*this);
switch (step)
{
case Step::JumpLeft:
if (!moved->IsStuckJumpLeft())
{
moved->lilies[moved->blankPos] = Frog::Green;
moved->blankPos++;
canMove = true;
}
break;
case Step::LeapLeft:
if (!moved->IsStuckLeapLeft())
{
moved->lilies[moved->blankPos] = Frog::Green;
moved->blankPos += 2;
canMove = true;
}
break;
case Step::JumpRight:
if (!moved->IsStuckJumpRight())
{
moved->lilies[moved->blankPos] = Frog::Brown;
moved->blankPos--;
canMove = true;
}
break;
case Step::LeapRight:
if (!moved->IsStuckLeapRight())
{
moved->lilies[moved->blankPos] = Frog::Brown;
moved->blankPos -= 2;
canMove = true;
}
break;
default:
break;
}
if (canMove)
moved->lilies[moved->blankPos] = Frog::None;
return canMove ? moved : nullptr;
}
void Print() const
{
for (auto frog: lilies)
switch (frog)
{
case Frog::Brown:
printf(">");
break;
case Frog::Green:
printf("<");
break;
case Frog::None:
printf("_");
break;
}
printf("\n");
}
};
}
int main()
{
int count;
scanf("%d", &count);
if (count < 0)
return 1;
std::vector<std::shared_ptr<Frogs::State> > visited;
std::stack<std::shared_ptr<Frogs::State> > trace;
trace.push(std::make_shared<Frogs::State>(count));
while (!trace.empty() && !trace.top()->WasTargetReached())
{
auto state = trace.top();
trace.pop();
if (visited.crend() == std::find(visited.crbegin(), visited.crend(), state))
{
visited.push_back(state);
auto move = [&trace, state](Frogs::Step step)
{
auto newState = state->Move(step);
if (newState)
trace.push(newState);
};
move(Frogs::Step::JumpLeft);
move(Frogs::Step::LeapLeft);
move(Frogs::Step::JumpRight);
move(Frogs::Step::LeapRight);
state->Print();
}
}
if (!trace.empty())
trace.top()->Print();
return 0;
}
<commit_msg>frogs: made some style fixes<commit_after>#include <cstdio>
#include <vector>
#include <stack>
#include <algorithm>
#include <memory>
namespace Frogs
{
enum class Frog { None, Brown, Green };
enum class Step { None, JumpLeft, LeapLeft, JumpRight, LeapRight };
class State
{
std::vector<Frog> lilies;
int count, blankPos;
public:
State(int count): lilies(2 * count + 1), count(count), blankPos(count)
{
for (int i = 0; i < count; ++i)
{
lilies[i] = Frog::Brown;
lilies[2 * count - i] = Frog::Green;
}
lilies[blankPos] = Frog::None;
}
bool operator==(const State& other) const
{
return lilies == other.lilies && count == other.count && blankPos == other.blankPos;
}
bool IsStuckJumpLeft() const { return blankPos >= (int)lilies.size() - 1 || lilies[blankPos + 1] != Frog::Green; }
bool IsStuckLeapLeft() const { return blankPos >= (int)lilies.size() - 2 || lilies[blankPos + 2] != Frog::Green; }
bool IsStuckJumpRight() const { return blankPos < 1 || lilies[blankPos - 1] != Frog::Brown; }
bool IsStuckLeapRight() const { return blankPos < 2 || lilies[blankPos - 2] != Frog::Brown; }
bool WasTargetReached() const
{
for (int i = 0; i < count; ++i)
if (lilies[i] != Frog::Green || lilies[2 * count - i] != Frog::Brown)
return false;
return lilies[count] == Frog::None;
}
std::shared_ptr<State> Move(Step step) const
{
bool canMove = false;
auto moved = std::make_shared<State>(*this);
switch (step)
{
case Step::JumpLeft:
if (!moved->IsStuckJumpLeft())
{
moved->lilies[moved->blankPos] = Frog::Green;
moved->blankPos++;
canMove = true;
}
break;
case Step::LeapLeft:
if (!moved->IsStuckLeapLeft())
{
moved->lilies[moved->blankPos] = Frog::Green;
moved->blankPos += 2;
canMove = true;
}
break;
case Step::JumpRight:
if (!moved->IsStuckJumpRight())
{
moved->lilies[moved->blankPos] = Frog::Brown;
moved->blankPos--;
canMove = true;
}
break;
case Step::LeapRight:
if (!moved->IsStuckLeapRight())
{
moved->lilies[moved->blankPos] = Frog::Brown;
moved->blankPos -= 2;
canMove = true;
}
break;
default:
break;
}
if (canMove)
moved->lilies[moved->blankPos] = Frog::None;
return canMove ? moved : nullptr;
}
void Print() const
{
for (auto frog: lilies)
switch (frog)
{
case Frog::Brown:
printf(">");
break;
case Frog::Green:
printf("<");
break;
case Frog::None:
printf("_");
break;
}
printf("\n");
}
};
}
int main()
{
int count;
scanf("%d", &count);
if (count < 0)
return 1;
std::vector<std::shared_ptr<Frogs::State> > visited;
std::stack<std::shared_ptr<Frogs::State> > trace;
trace.push(std::make_shared<Frogs::State>(count));
while (!trace.empty() && !trace.top()->WasTargetReached())
{
auto state = trace.top();
trace.pop();
if (visited.crend() == std::find(visited.crbegin(), visited.crend(), state))
{
state->Print();
visited.push_back(state);
auto move = [&trace, state](Frogs::Step step)
{
auto newState = state->Move(step);
if (newState)
trace.push(newState);
};
move(Frogs::Step::JumpLeft);
move(Frogs::Step::LeapLeft);
move(Frogs::Step::JumpRight);
move(Frogs::Step::LeapRight);
}
}
if (!trace.empty())
trace.top()->Print();
return 0;
}
<|endoftext|>
|
<commit_before>/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
struct Item {
int level;
TreeNode* root;
};
public:
TreeNode* addOneRow(TreeNode* root, int val, int depth) {
if (depth == 1) {
TreeNode *newroot = new TreeNode(val);
if (root) {
newroot->left = root;
}
return newroot;
}
if (!root) {
return root;
}
std::queue<Item> q;
q.push(Item{1, root});
while (!q.empty()) {
Item cur = q.front();
q.pop();
if ((cur.level+1) < depth) {
if (cur.root->left) {
q.push(Item{cur.level+1, cur.root->left});
}
if (cur.root->right) {
q.push(Item{cur.level+1, cur.root->right});
}
} else if ((cur.level+1) == depth) {
// found
TreeNode *newleft = new TreeNode{val};
TreeNode *newright = new TreeNode{val};
newleft->left = cur.root->left;
newright->right = cur.root->right;
cur.root->left = newleft;
cur.root->right = newright;
} else {
break;
}
}
return root;
}
};
<commit_msg>Add One Row to Tree<commit_after>/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
struct Item {
int level;
TreeNode* root;
};
public:
TreeNode* addOneRow(TreeNode* root, int val, int depth) {
if (depth == 1) {
TreeNode *newroot = new TreeNode(val);
if (root) {
newroot->left = root;
}
return newroot;
}
if (!root) {
return root;
}
std::queue<Item> q;
q.push(Item{1, root});
while (!q.empty()) {
Item cur = q.front();
q.pop();
if ((cur.level+1) < depth) {
if (cur.root->left) {
q.push(Item{cur.level+1, cur.root->left});
}
if (cur.root->right) {
q.push(Item{cur.level+1, cur.root->right});
}
} else if ((cur.level+1) == depth) {
// found
TreeNode *newleft = new TreeNode{val};
TreeNode *newright = new TreeNode{val};
newleft->left = cur.root->left;
newright->right = cur.root->right;
cur.root->left = newleft;
cur.root->right = newright;
} else {
break;
}
}
return root;
}
};
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* addOneRow(TreeNode* root, int val, int depth) {
if (depth == 1) {
TreeNode* newroot = new TreeNode{val};
newroot->left = root;
return newroot;
}
recur(root, 2, val, depth);
return root;
}
private:
void recur(TreeNode* root, int level, int& val, int& depth) {
if (!root)
return;
if (level == depth) {
TreeNode* newleft = new TreeNode{val};
TreeNode* newright = new TreeNode{val};
if (root->left) {
auto left = root->left;
root->left = newleft;
newleft->left = left;
} else {
root->left = newleft;
}
if (root->right) {
auto right = root->right;
root->right = newright;
newright->right = right;
} else {
root->right = newright;
}
return;
}
if (level < depth) {
recur(root->left, level+1, val, depth);
recur(root->right, level+1, val, depth);
}
return;
}
};
<|endoftext|>
|
<commit_before>/*
* This file is part of buteo-syncfw package
*
* Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
*
* Contact: Sateesh Kavuri <sateesh.kavuri@nokia.com>
*
* 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., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
*/
#include "TransportTracker.h"
#if __USBMODED__
#include "USBModedProxy.h"
#endif
#include "NetworkManager.h"
#include "LogMacros.h"
#include <QMutexLocker>
#include <QDBusConnection>
#include <QDBusMessage>
#include <QDBusArgument>
using namespace Buteo;
TransportTracker::TransportTracker(QObject *aParent) :
QObject(aParent),
iUSBProxy(0),
iInternet(0)
{
FUNCTION_CALL_TRACE;
iTransportStates[Sync::CONNECTIVITY_USB] = false;
iTransportStates[Sync::CONNECTIVITY_BT] = false;
iTransportStates[Sync::CONNECTIVITY_INTERNET] = false;
#if __USBMODED__
// USB
iUSBProxy = new USBModedProxy(this);
if (!iUSBProxy->isValid())
{
LOG_CRITICAL("Failed to connect to USB moded D-Bus interface");
delete iUSBProxy;
iUSBProxy = NULL;
}
else
{
QObject::connect(iUSBProxy, SIGNAL(usbConnection(bool)), this,
SLOT(onUsbStateChanged(bool)));
iTransportStates[Sync::CONNECTIVITY_USB] =
iUSBProxy->isUSBConnected();
}
#else
// hack when not compiled with USB moded to enable USB sync there
iTransportStates[Sync::CONNECTIVITY_USB] = false;
#endif
// BT
#if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)
// Set the bluetooth state
QString adapterPath;
iTransportStates[Sync::CONNECTIVITY_BT] = btConnectivityStatus();
// Add signal to track the bluetooth state changes
QDBusConnection bus = QDBusConnection::systemBus();
if (bus.connect("org.bluez",
"",
"org.bluez.Adapter",
"PropertyChanged",
this,
SLOT(onBtStateChanged(QString, QDBusVariant)
)))
{
LOG_WARNING("Unable to connect to system bus for org.bluez.Adapter");
}
#else
iTransportStates[Sync::CONNECTIVITY_BT] = iDeviceInfo.currentBluetoothPowerState();
QObject::connect(&iDeviceInfo, SIGNAL(bluetoothStateChanged(bool)), this, SLOT(onBtStateChanged(bool)));
LOG_DEBUG("Current bluetooth power state"<<iDeviceInfo.currentBluetoothPowerState());
#endif
// Internet
// @todo: enable when internet state is reported correctly.
iInternet = new NetworkManager(this);
if (iInternet != 0)
{
iTransportStates[Sync::CONNECTIVITY_INTERNET] =
iInternet->isOnline();
connect(iInternet, SIGNAL(valueChanged(bool)),
this, SLOT(onInternetStateChanged(bool)) /*, Qt::QueuedConnection*/);
}
else
{
LOG_WARNING("Failed to listen for Internet state changes");
}
}
TransportTracker::~TransportTracker()
{
FUNCTION_CALL_TRACE;
}
bool TransportTracker::isConnectivityAvailable(Sync::ConnectivityType aType) const
{
FUNCTION_CALL_TRACE;
QMutexLocker locker(&iMutex);
return iTransportStates[aType];
}
void TransportTracker::onUsbStateChanged(bool aConnected)
{
FUNCTION_CALL_TRACE;
LOG_DEBUG("USB state changed:" << aConnected);
updateState(Sync::CONNECTIVITY_USB, aConnected);
}
#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
void TransportTracker::onBtStateChanged(bool aState)
{
FUNCTION_CALL_TRACE;
Q_UNUSED(aState);
bool btPowered = iDeviceInfo.currentBluetoothPowerState();
LOG_DEBUG("BT power state" << btPowered);
updateState(Sync::CONNECTIVITY_BT, btPowered);
}
#else
void TransportTracker::onBtStateChanged(QString aKey, QDBusVariant aValue)
{
FUNCTION_CALL_TRACE;
if (aKey == "Powered")
{
bool btPowered = aValue.variant().toBool();
LOG_DEBUG("BT power state " << btPowered);
updateState(Sync::CONNECTIVITY_BT, btPowered);
}
}
#endif
void TransportTracker::onInternetStateChanged(bool aConnected)
{
FUNCTION_CALL_TRACE;
LOG_DEBUG("Internet state changed:" << aConnected);
updateState(Sync::CONNECTIVITY_INTERNET, aConnected);
}
void TransportTracker::updateState(Sync::ConnectivityType aType,
bool aState)
{
FUNCTION_CALL_TRACE;
bool oldState = false;
{
QMutexLocker locker(&iMutex);
oldState = iTransportStates[aType];
iTransportStates[aType] = aState;
}
if(oldState != aState)
{
if (aType != Sync::CONNECTIVITY_INTERNET) {
emit connectivityStateChanged(aType, aState);
}
else {
emit networkStateChanged(aState);
}
}
}
bool TransportTracker::btConnectivityStatus()
{
FUNCTION_CALL_TRACE;
bool btOn = false;
QDBusMessage methodCallMsg = QDBusMessage::createMethodCall("org.bluez",
"/",
"org.bluez.Manager",
"DefaultAdapter");
QDBusMessage reply = QDBusConnection::systemBus().call(methodCallMsg);
if (reply.type() == QDBusMessage::ErrorMessage)
{
LOG_WARNING("This device does not have a BT adapter");
return btOn;
}
QList<QVariant> adapterList = reply.arguments();
// We will take the first adapter in the list
QString adapterPath = qdbus_cast<QDBusObjectPath>(adapterList.at(0)).path();
if (!adapterPath.isEmpty() || !adapterPath.isNull())
{
// Retrive the properties of the adapter and check for "Powered" key
methodCallMsg = QDBusMessage::createMethodCall("org.bluez",
adapterPath,
"org.bluez.Adapter",
"GetProperties");
reply = QDBusConnection::systemBus().call(methodCallMsg);
if (reply.type() == QDBusMessage::ErrorMessage)
{
LOG_WARNING("Error in retrieving bluetooth properties");
return btOn;
}
QDBusArgument arg = reply.arguments().at(0).value<QDBusArgument>();
if (arg.currentType() == QDBusArgument::MapType)
{
// Scan through the dict returned and check for "Powered" entry
QMap<QString,QVariant> dict = qdbus_cast<QMap<QString,QVariant> >(arg);
QMap<QString,QVariant>::iterator iter;
for(iter = dict.begin(); iter != dict.end(); ++iter)
{
if (iter.key() == "Powered")
{
btOn = iter.value().toBool();
LOG_DEBUG ("Bluetooth powered on? " << btOn);
break;
}
}
}
}
return btOn;
}
<commit_msg>Removed the hack to enable USB transport forcefully<commit_after>/*
* This file is part of buteo-syncfw package
*
* Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
*
* Contact: Sateesh Kavuri <sateesh.kavuri@nokia.com>
*
* 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., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
*/
#include "TransportTracker.h"
#if __USBMODED__
#include "USBModedProxy.h"
#endif
#include "NetworkManager.h"
#include "LogMacros.h"
#include <QMutexLocker>
#include <QDBusConnection>
#include <QDBusMessage>
#include <QDBusArgument>
using namespace Buteo;
TransportTracker::TransportTracker(QObject *aParent) :
QObject(aParent),
iUSBProxy(0),
iInternet(0)
{
FUNCTION_CALL_TRACE;
iTransportStates[Sync::CONNECTIVITY_USB] = false;
iTransportStates[Sync::CONNECTIVITY_BT] = false;
iTransportStates[Sync::CONNECTIVITY_INTERNET] = false;
#if __USBMODED__
// USB
iUSBProxy = new USBModedProxy(this);
if (!iUSBProxy->isValid())
{
LOG_CRITICAL("Failed to connect to USB moded D-Bus interface");
delete iUSBProxy;
iUSBProxy = NULL;
}
else
{
QObject::connect(iUSBProxy, SIGNAL(usbConnection(bool)), this,
SLOT(onUsbStateChanged(bool)));
iTransportStates[Sync::CONNECTIVITY_USB] =
iUSBProxy->isUSBConnected();
}
#endif
// BT
#if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)
// Set the bluetooth state
QString adapterPath;
iTransportStates[Sync::CONNECTIVITY_BT] = btConnectivityStatus();
// Add signal to track the bluetooth state changes
QDBusConnection bus = QDBusConnection::systemBus();
if (bus.connect("org.bluez",
"",
"org.bluez.Adapter",
"PropertyChanged",
this,
SLOT(onBtStateChanged(QString, QDBusVariant)
)))
{
LOG_WARNING("Unable to connect to system bus for org.bluez.Adapter");
}
#else
iTransportStates[Sync::CONNECTIVITY_BT] = iDeviceInfo.currentBluetoothPowerState();
QObject::connect(&iDeviceInfo, SIGNAL(bluetoothStateChanged(bool)), this, SLOT(onBtStateChanged(bool)));
LOG_DEBUG("Current bluetooth power state"<<iDeviceInfo.currentBluetoothPowerState());
#endif
// Internet
// @todo: enable when internet state is reported correctly.
iInternet = new NetworkManager(this);
if (iInternet != 0)
{
iTransportStates[Sync::CONNECTIVITY_INTERNET] =
iInternet->isOnline();
connect(iInternet, SIGNAL(valueChanged(bool)),
this, SLOT(onInternetStateChanged(bool)) /*, Qt::QueuedConnection*/);
}
else
{
LOG_WARNING("Failed to listen for Internet state changes");
}
}
TransportTracker::~TransportTracker()
{
FUNCTION_CALL_TRACE;
}
bool TransportTracker::isConnectivityAvailable(Sync::ConnectivityType aType) const
{
FUNCTION_CALL_TRACE;
QMutexLocker locker(&iMutex);
return iTransportStates[aType];
}
void TransportTracker::onUsbStateChanged(bool aConnected)
{
FUNCTION_CALL_TRACE;
LOG_DEBUG("USB state changed:" << aConnected);
updateState(Sync::CONNECTIVITY_USB, aConnected);
}
#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
void TransportTracker::onBtStateChanged(bool aState)
{
FUNCTION_CALL_TRACE;
Q_UNUSED(aState);
bool btPowered = iDeviceInfo.currentBluetoothPowerState();
LOG_DEBUG("BT power state" << btPowered);
updateState(Sync::CONNECTIVITY_BT, btPowered);
}
#else
void TransportTracker::onBtStateChanged(QString aKey, QDBusVariant aValue)
{
FUNCTION_CALL_TRACE;
if (aKey == "Powered")
{
bool btPowered = aValue.variant().toBool();
LOG_DEBUG("BT power state " << btPowered);
updateState(Sync::CONNECTIVITY_BT, btPowered);
}
}
#endif
void TransportTracker::onInternetStateChanged(bool aConnected)
{
FUNCTION_CALL_TRACE;
LOG_DEBUG("Internet state changed:" << aConnected);
updateState(Sync::CONNECTIVITY_INTERNET, aConnected);
}
void TransportTracker::updateState(Sync::ConnectivityType aType,
bool aState)
{
FUNCTION_CALL_TRACE;
bool oldState = false;
{
QMutexLocker locker(&iMutex);
oldState = iTransportStates[aType];
iTransportStates[aType] = aState;
}
if(oldState != aState)
{
if (aType != Sync::CONNECTIVITY_INTERNET) {
emit connectivityStateChanged(aType, aState);
}
else {
emit networkStateChanged(aState);
}
}
}
bool TransportTracker::btConnectivityStatus()
{
FUNCTION_CALL_TRACE;
bool btOn = false;
QDBusMessage methodCallMsg = QDBusMessage::createMethodCall("org.bluez",
"/",
"org.bluez.Manager",
"DefaultAdapter");
QDBusMessage reply = QDBusConnection::systemBus().call(methodCallMsg);
if (reply.type() == QDBusMessage::ErrorMessage)
{
LOG_WARNING("This device does not have a BT adapter");
return btOn;
}
QList<QVariant> adapterList = reply.arguments();
// We will take the first adapter in the list
QString adapterPath = qdbus_cast<QDBusObjectPath>(adapterList.at(0)).path();
if (!adapterPath.isEmpty() || !adapterPath.isNull())
{
// Retrive the properties of the adapter and check for "Powered" key
methodCallMsg = QDBusMessage::createMethodCall("org.bluez",
adapterPath,
"org.bluez.Adapter",
"GetProperties");
reply = QDBusConnection::systemBus().call(methodCallMsg);
if (reply.type() == QDBusMessage::ErrorMessage)
{
LOG_WARNING("Error in retrieving bluetooth properties");
return btOn;
}
QDBusArgument arg = reply.arguments().at(0).value<QDBusArgument>();
if (arg.currentType() == QDBusArgument::MapType)
{
// Scan through the dict returned and check for "Powered" entry
QMap<QString,QVariant> dict = qdbus_cast<QMap<QString,QVariant> >(arg);
QMap<QString,QVariant>::iterator iter;
for(iter = dict.begin(); iter != dict.end(); ++iter)
{
if (iter.key() == "Powered")
{
btOn = iter.value().toBool();
LOG_DEBUG ("Bluetooth powered on? " << btOn);
break;
}
}
}
}
return btOn;
}
<|endoftext|>
|
<commit_before>/**
* @file monin_obukhov.cpp
*
* Claculates the inverse of the Monin-Obukhov length.
*
*/
#include <boost/lexical_cast.hpp>
#include "forecast_time.h"
#include "level.h"
#include "logger_factory.h"
#include "monin_obukhov.h"
#include "metutil.h"
using namespace std;
using namespace himan::plugin;
monin_obukhov::monin_obukhov()
{
itsClearTextFormula = "1/L = -(k*g*Q)/(rho*cp*u*^3*T)";
itsLogger = logger_factory::Instance()->GetLog("monin_obukhov");
}
void monin_obukhov::Process(std::shared_ptr<const plugin_configuration> conf)
{
Init(conf);
/*
* Set target parameter properties
* - name PARM_NAME, this name is found from neons. For example: T-K
* - univ_id UNIV_ID, newbase-id, ie code table 204
* - grib1 id must be in database
* - grib2 descriptor X'Y'Z, http://www.nco.ncep.noaa.gov/pmb/docs/grib2/grib2_table4-2.shtml
*
*/
param theRequestedParam("MOL-M", 1204);
// If this param is also used as a source param for other calculations
SetParams({theRequestedParam});
Start();
}
/*
* Calculate()
*
* This function does the actual calculation.
*/
void monin_obukhov::Calculate(shared_ptr<info> myTargetInfo, unsigned short threadIndex)
{
/*
* Required source parameters
*
* eg. param PParam("P-Pa"); for pressure in pascals
*
*/
const param TParam("T-K"); // ground Temperature
const param SHFParam("FLSEN-JM2"); // accumulated surface sensible heat flux
const param LHFParam("FLLAT-JM2"); // accumulated surface latent heat flux
const param U_SParam("FRVEL-MS"); // friction velocity
const param PParam("P-PA");
// ----
auto myThreadedLogger =
logger_factory::Instance()->GetLog("monin_obukhov Thread #" + boost::lexical_cast<string>(threadIndex));
// Prev/current time and level
int paramStep = 1; // myTargetInfo->Param().Aggregation().TimeResolutionValue();
HPTimeResolution timeResolution = myTargetInfo->Time().StepResolution();
forecast_time forecastTime = myTargetInfo->Time();
forecast_time forecastTimePrev = myTargetInfo->Time();
forecastTimePrev.ValidDateTime().Adjust(timeResolution, -paramStep);
forecast_type forecastType = myTargetInfo->ForecastType();
level forecastLevel = level(himan::kHeight, 0, "Height");
myThreadedLogger->Debug("Calculating time " + static_cast<string>(forecastTime.ValidDateTime()) + " level " +
static_cast<string>(forecastLevel));
info_t TInfo = Fetch(forecastTime, forecastLevel, TParam, forecastType, false);
info_t SHFInfo = Fetch(forecastTime, forecastLevel, SHFParam, forecastType, false);
info_t PrevSHFInfo = Fetch(forecastTimePrev, forecastLevel, SHFParam, forecastType, false);
info_t LHFInfo = Fetch(forecastTime, forecastLevel, LHFParam, forecastType, false);
info_t PrevLHFInfo = Fetch(forecastTimePrev, forecastLevel, LHFParam, forecastType, false);
info_t U_SInfo = Fetch(forecastTime, forecastLevel, U_SParam, forecastType, false);
info_t PInfo = Fetch(forecastTime, forecastLevel, PParam, forecastType, false);
// determine length of forecast step to calculate surface heat flux in W/m2
double forecastStepSize;
if (itsConfiguration->SourceProducer().Id() != 199)
{
forecastStepSize = itsConfiguration->ForecastStep() * 3600; // step size in seconds
}
else
{
forecastStepSize = itsConfiguration->ForecastStep() * 60; // step size in seconds
}
if (!TInfo || !SHFInfo || !U_SInfo || !PInfo || !PrevSHFInfo || !LHFInfo || !PrevLHFInfo)
{
myThreadedLogger->Info("Skipping step " + boost::lexical_cast<string>(forecastTime.Step()) + ", level " +
static_cast<string>(forecastLevel));
return;
}
string deviceType = "CPU";
LOCKSTEP(myTargetInfo, TInfo, SHFInfo, PrevSHFInfo, LHFInfo, PrevLHFInfo, U_SInfo, PInfo)
{
double T = TInfo->Value();
double SHF = SHFInfo->Value() - PrevSHFInfo->Value();
double LHF = LHFInfo->Value() - PrevLHFInfo->Value();
double U_S = U_SInfo->Value();
double P = PInfo->Value();
double T_C = T - constants::kKelvin; // Convert Temperature to Celvins
double mol(kFloatMissing);
if (T == kFloatMissing || SHF == kFloatMissing || LHF == kFloatMissing || U_S == kFloatMissing ||
P == kFloatMissing)
{
continue;
}
SHF /= forecastStepSize; // divide by time step to obtain Watts/m2
LHF /= forecastStepSize; // divide by time step to obtain Watts/m2
/* Calculation of the inverse of Monin-Obukhov length to avoid division by 0 */
if (U_S != 0.0)
{
double rho = P / (constants::kRd * T); // Calculate density
double cp = 1.0056e3 + 0.017766 * T_C + 4.0501e-4 * pow(T_C, 2) - 1.017e-6 * pow(T_C, 3) +
1.4715e-8 * pow(T_C, 4) - 7.4022e-11 * pow(T_C, 5) +
1.2521e-13 * pow(T_C, 6); // Calculate specific heat capacity
double L = 2500800.0 - 2360.0 * T_C + 1.6 * pow(T_C, 2) - 0.06 * pow(T_C, 3); // Calculate specific latent heat of condensation of water
mol = -constants::kG * constants::kK * (SHF + 0.61 * cp * T / L * LHF) / (rho * cp * U_S * U_S * U_S * himan::metutil::VirtualTemperature_(T,P));
}
myTargetInfo->Value(mol);
}
myThreadedLogger->Info("[" + deviceType + "] Missing values: " +
boost::lexical_cast<string>(myTargetInfo->Data().MissingCount()) + "/" +
boost::lexical_cast<string>(myTargetInfo->Data().Size()));
}
<commit_msg>run clang format<commit_after>/**
* @file monin_obukhov.cpp
*
* Claculates the inverse of the Monin-Obukhov length.
*
*/
#include <boost/lexical_cast.hpp>
#include "forecast_time.h"
#include "level.h"
#include "logger_factory.h"
#include "metutil.h"
#include "monin_obukhov.h"
using namespace std;
using namespace himan::plugin;
monin_obukhov::monin_obukhov()
{
itsClearTextFormula = "1/L = -(k*g*Q)/(rho*cp*u*^3*T)";
itsLogger = logger_factory::Instance()->GetLog("monin_obukhov");
}
void monin_obukhov::Process(std::shared_ptr<const plugin_configuration> conf)
{
Init(conf);
/*
* Set target parameter properties
* - name PARM_NAME, this name is found from neons. For example: T-K
* - univ_id UNIV_ID, newbase-id, ie code table 204
* - grib1 id must be in database
* - grib2 descriptor X'Y'Z, http://www.nco.ncep.noaa.gov/pmb/docs/grib2/grib2_table4-2.shtml
*
*/
param theRequestedParam("MOL-M", 1204);
// If this param is also used as a source param for other calculations
SetParams({theRequestedParam});
Start();
}
/*
* Calculate()
*
* This function does the actual calculation.
*/
void monin_obukhov::Calculate(shared_ptr<info> myTargetInfo, unsigned short threadIndex)
{
/*
* Required source parameters
*
* eg. param PParam("P-Pa"); for pressure in pascals
*
*/
const param TParam("T-K"); // ground Temperature
const param SHFParam("FLSEN-JM2"); // accumulated surface sensible heat flux
const param LHFParam("FLLAT-JM2"); // accumulated surface latent heat flux
const param U_SParam("FRVEL-MS"); // friction velocity
const param PParam("P-PA");
// ----
auto myThreadedLogger =
logger_factory::Instance()->GetLog("monin_obukhov Thread #" + boost::lexical_cast<string>(threadIndex));
// Prev/current time and level
int paramStep = 1; // myTargetInfo->Param().Aggregation().TimeResolutionValue();
HPTimeResolution timeResolution = myTargetInfo->Time().StepResolution();
forecast_time forecastTime = myTargetInfo->Time();
forecast_time forecastTimePrev = myTargetInfo->Time();
forecastTimePrev.ValidDateTime().Adjust(timeResolution, -paramStep);
forecast_type forecastType = myTargetInfo->ForecastType();
level forecastLevel = level(himan::kHeight, 0, "Height");
myThreadedLogger->Debug("Calculating time " + static_cast<string>(forecastTime.ValidDateTime()) + " level " +
static_cast<string>(forecastLevel));
info_t TInfo = Fetch(forecastTime, forecastLevel, TParam, forecastType, false);
info_t SHFInfo = Fetch(forecastTime, forecastLevel, SHFParam, forecastType, false);
info_t PrevSHFInfo = Fetch(forecastTimePrev, forecastLevel, SHFParam, forecastType, false);
info_t LHFInfo = Fetch(forecastTime, forecastLevel, LHFParam, forecastType, false);
info_t PrevLHFInfo = Fetch(forecastTimePrev, forecastLevel, LHFParam, forecastType, false);
info_t U_SInfo = Fetch(forecastTime, forecastLevel, U_SParam, forecastType, false);
info_t PInfo = Fetch(forecastTime, forecastLevel, PParam, forecastType, false);
// determine length of forecast step to calculate surface heat flux in W/m2
double forecastStepSize;
if (itsConfiguration->SourceProducer().Id() != 199)
{
forecastStepSize = itsConfiguration->ForecastStep() * 3600; // step size in seconds
}
else
{
forecastStepSize = itsConfiguration->ForecastStep() * 60; // step size in seconds
}
if (!TInfo || !SHFInfo || !U_SInfo || !PInfo || !PrevSHFInfo || !LHFInfo || !PrevLHFInfo)
{
myThreadedLogger->Info("Skipping step " + boost::lexical_cast<string>(forecastTime.Step()) + ", level " +
static_cast<string>(forecastLevel));
return;
}
string deviceType = "CPU";
LOCKSTEP(myTargetInfo, TInfo, SHFInfo, PrevSHFInfo, LHFInfo, PrevLHFInfo, U_SInfo, PInfo)
{
double T = TInfo->Value();
double SHF = SHFInfo->Value() - PrevSHFInfo->Value();
double LHF = LHFInfo->Value() - PrevLHFInfo->Value();
double U_S = U_SInfo->Value();
double P = PInfo->Value();
double T_C = T - constants::kKelvin; // Convert Temperature to Celvins
double mol(kFloatMissing);
if (T == kFloatMissing || SHF == kFloatMissing || LHF == kFloatMissing || U_S == kFloatMissing ||
P == kFloatMissing)
{
continue;
}
SHF /= forecastStepSize; // divide by time step to obtain Watts/m2
LHF /= forecastStepSize; // divide by time step to obtain Watts/m2
/* Calculation of the inverse of Monin-Obukhov length to avoid division by 0 */
if (U_S != 0.0)
{
double rho = P / (constants::kRd * T); // Calculate density
double cp = 1.0056e3 + 0.017766 * T_C + 4.0501e-4 * pow(T_C, 2) - 1.017e-6 * pow(T_C, 3) +
1.4715e-8 * pow(T_C, 4) - 7.4022e-11 * pow(T_C, 5) +
1.2521e-13 * pow(T_C, 6); // Calculate specific heat capacity
double L = 2500800.0 - 2360.0 * T_C + 1.6 * pow(T_C, 2) -
0.06 * pow(T_C, 3); // Calculate specific latent heat of condensation of water
mol = -constants::kG * constants::kK * (SHF + 0.61 * cp * T / L * LHF) /
(rho * cp * U_S * U_S * U_S * himan::metutil::VirtualTemperature_(T, P));
}
myTargetInfo->Value(mol);
}
myThreadedLogger->Info("[" + deviceType + "] Missing values: " +
boost::lexical_cast<string>(myTargetInfo->Data().MissingCount()) + "/" +
boost::lexical_cast<string>(myTargetInfo->Data().Size()));
}
<|endoftext|>
|
<commit_before>
#include <wx/wxprec.h>
#include "iso639.h"
LanguageStruct isoLanguages[] =
{
{_T("aa"), _T("Afar")},
{_T("ab"), _T("Abkhazian")},
{_T("ae"), _T("Avestan")},
{_T("af"), _T("Afrikaans")},
{_T("am"), _T("Amharic")},
{_T("ar"), _T("Arabic")},
{_T("as"), _T("Assamese")},
{_T("ay"), _T("Aymara")},
{_T("az"), _T("Azerbaijani")},
{_T("ba"), _T("Bashkir")},
{_T("be"), _T("Byelorussian")},
{_T("bg"), _T("Bulgarian")},
{_T("bh"), _T("Bihari")},
{_T("bi"), _T("Bislama")},
{_T("bn"), _T("Bengali")},
{_T("bo"), _T("Tibetan")},
{_T("br"), _T("Breton")},
{_T("bs"), _T("Bosnian")},
{_T("ca"), _T("Catalan")},
{_T("ce"), _T("Chechen")},
{_T("ch"), _T("Chamorro")},
{_T("co"), _T("Corsican")},
{_T("cs"), _T("Czech")},
{_T("cu"), _T("Church Slavic")},
{_T("cv"), _T("Chuvash")},
{_T("cy"), _T("Welsh")},
{_T("da"), _T("Danish")},
{_T("de"), _T("German")},
{_T("dz"), _T("Dzongkha")},
{_T("el"), _T("Greek")},
{_T("en"), _T("English")},
{_T("eo"), _T("Esperanto")},
{_T("es"), _T("Spanish")},
{_T("et"), _T("Estonian")},
{_T("eu"), _T("Basque")},
{_T("fa"), _T("Persian")},
{_T("fi"), _T("Finnish")},
{_T("fj"), _T("Fijian")},
{_T("fo"), _T("Faroese")},
{_T("fr"), _T("French")},
{_T("fy"), _T("Frisian")},
{_T("ga"), _T("Irish")},
{_T("gd"), _T("Gaelic")},
{_T("gl"), _T("Gallegan")},
{_T("gn"), _T("Guarani")},
{_T("gu"), _T("Gujarati")},
{_T("ha"), _T("Hausa")},
{_T("he"), _T("Hebrew")},
{_T("hi"), _T("Hindi")},
{_T("ho"), _T("Hiri Motu")},
{_T("hr"), _T("Croatian")},
{_T("hu"), _T("Hungarian")},
{_T("hy"), _T("Armenian")},
{_T("hz"), _T("Herero")},
{_T("ia"), _T("Interlingua")},
{_T("id"), _T("Indonesian")},
{_T("ie"), _T("Interlingue")},
{_T("ik"), _T("Inupiaq")},
{_T("is"), _T("Icelandic")},
{_T("it"), _T("Italian")},
{_T("iu"), _T("Inuktitut")},
{_T("ja"), _T("Japanese")},
{_T("jw"), _T("Javanese")},
{_T("ka"), _T("Georgian")},
{_T("ki"), _T("Kikuyu")},
{_T("kj"), _T("Kuanyama")},
{_T("kk"), _T("Kazakh")},
{_T("kl"), _T("Kalaallisut")},
{_T("km"), _T("Khmer")},
{_T("kn"), _T("Kannada")},
{_T("ko"), _T("Korean")},
{_T("ks"), _T("Kashmiri")},
{_T("ku"), _T("Kurdish")},
{_T("kv"), _T("Komi")},
{_T("kw"), _T("Cornish")},
{_T("ky"), _T("Kirghiz")},
{_T("la"), _T("Latin")},
{_T("lb"), _T("Letzeburgesch")},
{_T("ln"), _T("Lingala")},
{_T("lo"), _T("Lao")},
{_T("lt"), _T("Lithuanian")},
{_T("lv"), _T("Latvian")},
{_T("mg"), _T("Malagasy")},
{_T("mh"), _T("Marshall")},
{_T("mi"), _T("Maori")},
{_T("mk"), _T("Macedonian")},
{_T("ml"), _T("Malayalam")},
{_T("mn"), _T("Mongolian")},
{_T("mo"), _T("Moldavian")},
{_T("mr"), _T("Marathi")},
{_T("ms"), _T("Malay")},
{_T("mt"), _T("Maltese")},
{_T("my"), _T("Burmese")},
{_T("na"), _T("Nauru")},
{_T("nb"), _T("Norwegian Bokml")},
{_T("ne"), _T("Nepali")},
{_T("ng"), _T("Ndonga")},
{_T("nl"), _T("Dutch")},
{_T("nn"), _T("Norwegian Nynorsk")},
{_T("no"), _T("Norwegian")},
{_T("nr"), _T("Ndebele, South")},
{_T("nv"), _T("Navajo")},
{_T("ny"), _T("Chichewa; Nyanja")},
{_T("oc"), _T("Occitan")},
{_T("om"), _T("(Afan) Oromo")},
{_T("or"), _T("Oriya")},
{_T("os"), _T("Ossetian; Ossetic")},
{_T("pa"), _T("Panjabi")},
{_T("pi"), _T("Pali")},
{_T("pl"), _T("Polish")},
{_T("ps"), _T("Pashto, Pushto")},
{_T("pt"), _T("Portuguese")},
{_T("qu"), _T("Quechua")},
{_T("rm"), _T("Rhaeto-Romance")},
{_T("rn"), _T("Rundi")},
{_T("ro"), _T("Romanian")},
{_T("ru"), _T("Russian")},
{_T("rw"), _T("Kinyarwanda")},
{_T("sa"), _T("Sanskrit")},
{_T("sc"), _T("Sardinian")},
{_T("sd"), _T("Sindhi")},
{_T("se"), _T("Northern Sami")},
{_T("sg"), _T("Sangro")},
{_T("sh"), _T("Serbo-Croatian")},
{_T("si"), _T("Sinhalese")},
{_T("sk"), _T("Slovak")},
{_T("sl"), _T("Slovenian")},
{_T("sm"), _T("Samoan")},
{_T("sn"), _T("Shona")},
{_T("so"), _T("Somali")},
{_T("sq"), _T("Albanian")},
{_T("sr"), _T("Serbian")},
{_T("ss"), _T("Siswati")},
{_T("st"), _T("Sesotho")},
{_T("su"), _T("Sundanese")},
{_T("sv"), _T("Swedish")},
{_T("sw"), _T("Swahili")},
{_T("ta"), _T("Tamil")},
{_T("te"), _T("Telugu")},
{_T("tg"), _T("Tajik")},
{_T("th"), _T("Thai")},
{_T("ti"), _T("Tigrinya")},
{_T("tk"), _T("Turkmen")},
{_T("tl"), _T("Tagalog")},
{_T("tn"), _T("Setswana")},
{_T("to"), _T("Tonga")},
{_T("tr"), _T("Turkish")},
{_T("ts"), _T("Tsonga")},
{_T("tt"), _T("Tatar")},
{_T("tw"), _T("Twi")},
{_T("ty"), _T("Tahitian")},
{_T("ug"), _T("Uighur")},
{_T("uk"), _T("Ukrainian")},
{_T("ur"), _T("Urdu")},
{_T("uz"), _T("Uzbek")},
{_T("vi"), _T("Vietnamese")},
{_T("vo"), _T("Volapuk")},
{_T("wo"), _T("Wolof")},
{_T("xh"), _T("Xhosa")},
{_T("yi"), _T("Yiddish")},
{_T("yo"), _T("Yoruba")},
{_T("za"), _T("Zhuang")},
{_T("zh_CN"), _T("Simplified Chinese")},
{_T("zh_TW"), _T("Traditional Chinese")},
{_T("zu"), _T("Zulu")},
{NULL, NULL}
};
<commit_msg>better names for Chinese<commit_after>
#include <wx/wxprec.h>
#include "iso639.h"
LanguageStruct isoLanguages[] =
{
{_T("aa"), _T("Afar")},
{_T("ab"), _T("Abkhazian")},
{_T("ae"), _T("Avestan")},
{_T("af"), _T("Afrikaans")},
{_T("am"), _T("Amharic")},
{_T("ar"), _T("Arabic")},
{_T("as"), _T("Assamese")},
{_T("ay"), _T("Aymara")},
{_T("az"), _T("Azerbaijani")},
{_T("ba"), _T("Bashkir")},
{_T("be"), _T("Byelorussian")},
{_T("bg"), _T("Bulgarian")},
{_T("bh"), _T("Bihari")},
{_T("bi"), _T("Bislama")},
{_T("bn"), _T("Bengali")},
{_T("bo"), _T("Tibetan")},
{_T("br"), _T("Breton")},
{_T("bs"), _T("Bosnian")},
{_T("ca"), _T("Catalan")},
{_T("ce"), _T("Chechen")},
{_T("ch"), _T("Chamorro")},
{_T("co"), _T("Corsican")},
{_T("cs"), _T("Czech")},
{_T("cu"), _T("Church Slavic")},
{_T("cv"), _T("Chuvash")},
{_T("cy"), _T("Welsh")},
{_T("da"), _T("Danish")},
{_T("de"), _T("German")},
{_T("dz"), _T("Dzongkha")},
{_T("el"), _T("Greek")},
{_T("en"), _T("English")},
{_T("eo"), _T("Esperanto")},
{_T("es"), _T("Spanish")},
{_T("et"), _T("Estonian")},
{_T("eu"), _T("Basque")},
{_T("fa"), _T("Persian")},
{_T("fi"), _T("Finnish")},
{_T("fj"), _T("Fijian")},
{_T("fo"), _T("Faroese")},
{_T("fr"), _T("French")},
{_T("fy"), _T("Frisian")},
{_T("ga"), _T("Irish")},
{_T("gd"), _T("Gaelic")},
{_T("gl"), _T("Gallegan")},
{_T("gn"), _T("Guarani")},
{_T("gu"), _T("Gujarati")},
{_T("ha"), _T("Hausa")},
{_T("he"), _T("Hebrew")},
{_T("hi"), _T("Hindi")},
{_T("ho"), _T("Hiri Motu")},
{_T("hr"), _T("Croatian")},
{_T("hu"), _T("Hungarian")},
{_T("hy"), _T("Armenian")},
{_T("hz"), _T("Herero")},
{_T("ia"), _T("Interlingua")},
{_T("id"), _T("Indonesian")},
{_T("ie"), _T("Interlingue")},
{_T("ik"), _T("Inupiaq")},
{_T("is"), _T("Icelandic")},
{_T("it"), _T("Italian")},
{_T("iu"), _T("Inuktitut")},
{_T("ja"), _T("Japanese")},
{_T("jw"), _T("Javanese")},
{_T("ka"), _T("Georgian")},
{_T("ki"), _T("Kikuyu")},
{_T("kj"), _T("Kuanyama")},
{_T("kk"), _T("Kazakh")},
{_T("kl"), _T("Kalaallisut")},
{_T("km"), _T("Khmer")},
{_T("kn"), _T("Kannada")},
{_T("ko"), _T("Korean")},
{_T("ks"), _T("Kashmiri")},
{_T("ku"), _T("Kurdish")},
{_T("kv"), _T("Komi")},
{_T("kw"), _T("Cornish")},
{_T("ky"), _T("Kirghiz")},
{_T("la"), _T("Latin")},
{_T("lb"), _T("Letzeburgesch")},
{_T("ln"), _T("Lingala")},
{_T("lo"), _T("Lao")},
{_T("lt"), _T("Lithuanian")},
{_T("lv"), _T("Latvian")},
{_T("mg"), _T("Malagasy")},
{_T("mh"), _T("Marshall")},
{_T("mi"), _T("Maori")},
{_T("mk"), _T("Macedonian")},
{_T("ml"), _T("Malayalam")},
{_T("mn"), _T("Mongolian")},
{_T("mo"), _T("Moldavian")},
{_T("mr"), _T("Marathi")},
{_T("ms"), _T("Malay")},
{_T("mt"), _T("Maltese")},
{_T("my"), _T("Burmese")},
{_T("na"), _T("Nauru")},
{_T("nb"), _T("Norwegian Bokml")},
{_T("ne"), _T("Nepali")},
{_T("ng"), _T("Ndonga")},
{_T("nl"), _T("Dutch")},
{_T("nn"), _T("Norwegian Nynorsk")},
{_T("no"), _T("Norwegian")},
{_T("nr"), _T("Ndebele, South")},
{_T("nv"), _T("Navajo")},
{_T("ny"), _T("Chichewa; Nyanja")},
{_T("oc"), _T("Occitan")},
{_T("om"), _T("(Afan) Oromo")},
{_T("or"), _T("Oriya")},
{_T("os"), _T("Ossetian; Ossetic")},
{_T("pa"), _T("Panjabi")},
{_T("pi"), _T("Pali")},
{_T("pl"), _T("Polish")},
{_T("ps"), _T("Pashto, Pushto")},
{_T("pt"), _T("Portuguese")},
{_T("qu"), _T("Quechua")},
{_T("rm"), _T("Rhaeto-Romance")},
{_T("rn"), _T("Rundi")},
{_T("ro"), _T("Romanian")},
{_T("ru"), _T("Russian")},
{_T("rw"), _T("Kinyarwanda")},
{_T("sa"), _T("Sanskrit")},
{_T("sc"), _T("Sardinian")},
{_T("sd"), _T("Sindhi")},
{_T("se"), _T("Northern Sami")},
{_T("sg"), _T("Sangro")},
{_T("sh"), _T("Serbo-Croatian")},
{_T("si"), _T("Sinhalese")},
{_T("sk"), _T("Slovak")},
{_T("sl"), _T("Slovenian")},
{_T("sm"), _T("Samoan")},
{_T("sn"), _T("Shona")},
{_T("so"), _T("Somali")},
{_T("sq"), _T("Albanian")},
{_T("sr"), _T("Serbian")},
{_T("ss"), _T("Siswati")},
{_T("st"), _T("Sesotho")},
{_T("su"), _T("Sundanese")},
{_T("sv"), _T("Swedish")},
{_T("sw"), _T("Swahili")},
{_T("ta"), _T("Tamil")},
{_T("te"), _T("Telugu")},
{_T("tg"), _T("Tajik")},
{_T("th"), _T("Thai")},
{_T("ti"), _T("Tigrinya")},
{_T("tk"), _T("Turkmen")},
{_T("tl"), _T("Tagalog")},
{_T("tn"), _T("Setswana")},
{_T("to"), _T("Tonga")},
{_T("tr"), _T("Turkish")},
{_T("ts"), _T("Tsonga")},
{_T("tt"), _T("Tatar")},
{_T("tw"), _T("Twi")},
{_T("ty"), _T("Tahitian")},
{_T("ug"), _T("Uighur")},
{_T("uk"), _T("Ukrainian")},
{_T("ur"), _T("Urdu")},
{_T("uz"), _T("Uzbek")},
{_T("vi"), _T("Vietnamese")},
{_T("vo"), _T("Volapuk")},
{_T("wo"), _T("Wolof")},
{_T("xh"), _T("Xhosa")},
{_T("yi"), _T("Yiddish")},
{_T("yo"), _T("Yoruba")},
{_T("za"), _T("Zhuang")},
{_T("zh_CN"), _T("Chinese (Simplified)")},
{_T("zh_TW"), _T("Chinese (Traditional)")},
{_T("zu"), _T("Zulu")},
{NULL, NULL}
};
<|endoftext|>
|
<commit_before>#include <nds.h>
#include <stdio.h>
#define LCD_W 256
#define LCD_H 192
int main(void) {
int i;
consoleDemoInit();
videoSetMode(MODE_FB0);
vramSetBankA(VRAM_A_LCD);
printf("Hello World!");
for(i = 0; i < 256 * 192; i++) {
VRAM_A[i] = RGB15(31, 0, 0);
}
while(1) {
swiWaitForVBlank();
//consoleClear();
}
return 0;
}
<commit_msg>* removed some spaces<commit_after>#include <nds.h>
#include <stdio.h>
#define LCD_W 256
#define LCD_H 192
int main(void) {
int i;
consoleDemoInit();
videoSetMode(MODE_FB0);
vramSetBankA(VRAM_A_LCD);
printf("Hello World!");
for(i = 0; i < 256 * 192; i++) {
VRAM_A[i] = RGB15(31, 0, 0);
}
while(1) {
swiWaitForVBlank();
//consoleClear();
}
return 0;
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include "reader.hpp"
#include "settings.hpp"
#include "forest.hpp"
using namespace std;
using namespace ISUE::RelocForests;
int main(int argc, char *argv[]) {
if (argc < 2) {
cout << "Usage: ./relocforests_example <path_to_association_file> (train|test) <forest_file_name>\n";
return 1;
}
// get path
string data_path(argv[1]);
Reader *reader = new Reader();
bool err = reader->Load(data_path);
if (err) {
return 1;
}
// train or test time
string shouldTrain(argv[2]);
bool train = (shouldTrain == "train");
// Get data from reader
Data *data = reader->GetData();
// settings for forest
Settings *settings = new Settings(640, 480, 5000, 525.0f, 525.0f, 319.5f, 239.5f);
Forest<ushort, cv::Vec3b> *forest = nullptr;
string forest_file_name;
if (argv[3])
forest_file_name = string(argv[3]);
else
cout << "Train and Test time requires ouput/input forest file name.\n";
if (train) {
forest = new Forest<ushort, cv::Vec3b>(data, settings);
forest->Train();
forest->Serialize(forest_file_name);
cout << "Is forest valid:" << forest->IsValid() << endl;
}
else {
// load forest
forest = new Forest<ushort, cv::Vec3b>(data, settings, "forest.rf");
// check if valid
if (forest->IsValid()) {
cout << "Forest is valid." << endl;
}
else {
cout << "Forest is not valid." << endl;
return 1;
}
// Todo: test each image in test dataset and provide relevent statistics about accuracy
// eval forest at frame
std::clock_t start;
double duration;
start = std::clock();
// test a single frame
Eigen::Affine3d pose = forest->Test(data->GetRGBImage(200), data->GetDepthImage(200));
duration = (std::clock() - start) / (double)CLOCKS_PER_SEC;
cout << "Test time: " << duration << " Seconds \n";
// compare pose to groundtruth value
auto ground_truth = data->GetPose(200);
cout << "Evaluated Pose:" << endl;
cout << pose.rotation() << endl << endl;
cout << pose.rotation().eulerAngles(0, 1, 2) * 180 / M_PI << endl;
cout << pose.translation() << endl;
cout << "Ground Truth:" << endl;
cout << ground_truth.rotation << endl;
cout << ground_truth.rotation.eulerAngles(0, 1, 2) * 180 / M_PI << endl;
cout << ground_truth.position << endl;
}
delete forest;
delete reader;
delete settings;
return 0;
}
<commit_msg>Actually read file name from command line<commit_after>#include <iostream>
#include "reader.hpp"
#include "settings.hpp"
#include "forest.hpp"
using namespace std;
using namespace ISUE::RelocForests;
int main(int argc, char *argv[]) {
if (argc < 2) {
cout << "Usage: ./relocforests_example <path_to_association_file> (train|test) <forest_file_name>\n";
return 1;
}
// get path
string data_path(argv[1]);
Reader *reader = new Reader();
bool err = reader->Load(data_path);
if (err) {
return 1;
}
// train or test time
string shouldTrain(argv[2]);
bool train = (shouldTrain == "train");
// Get data from reader
Data *data = reader->GetData();
// settings for forest
Settings *settings = new Settings(640, 480, 5000, 525.0f, 525.0f, 319.5f, 239.5f);
Forest<ushort, cv::Vec3b> *forest = nullptr;
string forest_file_name;
if (argv[3])
forest_file_name = string(argv[3]);
else
cout << "Train and Test time requires ouput/input forest file name.\n";
if (train) {
forest = new Forest<ushort, cv::Vec3b>(data, settings);
forest->Train();
forest->Serialize(forest_file_name);
cout << "Is forest valid:" << forest->IsValid() << endl;
}
else {
// load forest
forest = new Forest<ushort, cv::Vec3b>(data, settings, forest_file_name);
// check if valid
if (forest->IsValid()) {
cout << "Forest is valid." << endl;
}
else {
cout << "Forest is not valid." << endl;
return 1;
}
// Todo: test each image in test dataset and provide relevent statistics about accuracy
// eval forest at frame
std::clock_t start;
double duration;
start = std::clock();
// test a single frame
Eigen::Affine3d pose = forest->Test(data->GetRGBImage(200), data->GetDepthImage(200));
duration = (std::clock() - start) / (double)CLOCKS_PER_SEC;
cout << "Test time: " << duration << " Seconds \n";
// compare pose to groundtruth value
auto ground_truth = data->GetPose(200);
cout << "Evaluated Pose:" << endl;
cout << pose.rotation() << endl << endl;
cout << pose.rotation().eulerAngles(0, 1, 2) * 180 / M_PI << endl;
cout << pose.translation() << endl;
cout << "Ground Truth:" << endl;
cout << ground_truth.rotation << endl;
cout << ground_truth.rotation.eulerAngles(0, 1, 2) * 180 / M_PI << endl;
cout << ground_truth.position << endl;
}
delete forest;
delete reader;
delete settings;
return 0;
}
<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.