Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found
Select Git revision
  • devel
  • master
  • pr/123
  • pre-commit-ci-update-config
  • 2.5.6
  • v1.1
  • v1.2.0
  • v1.2.1
  • v2.5
  • v2.5.1
  • v2.5.2
  • v2.5.3
  • v2.5.4
  • v2.5.5
  • v2.5.7
  • v3.0.0
  • v3.0.1
  • v3.1.0
  • v3.2.0
  • v3.2.1
  • v3.2.2
  • v3.3.0
  • v3.4.0
  • v3.5.0
  • v3.6.0
  • v3.7.0
  • v3.7.1
  • v3.7.2
  • v3.7.3
  • v3.8.0
  • v3.8.1
  • v3.8.2
  • v4.0.0
  • v4.1.0
  • v4.2.0
  • v4.2.1
  • v4.2.2
  • v4.3.0
  • v4.3.1
  • v4.3.2
  • v4.3.3
  • v4.3.4
  • v4.4.0
  • v4.4.1
  • v4.4.2
  • v4.4.3
46 results

Target

Select target project
  • cberge/dynamic-graph
  • ostasse/dynamic-graph
  • gsaurel/dynamic-graph
  • stack-of-tasks/dynamic-graph
4 results
Select Git revision
  • coverage
  • devel
  • master
  • topic/boost_python
  • topic/delete-shell
  • 2.5.6
  • v1.1
  • v1.2.0
  • v2.5
  • v2.5.1
  • v2.5.2
  • v2.5.3
  • v2.5.4
  • v2.5.5
  • v2.5.7
  • v3.0.1
  • v3.1.0
  • v3.2.0
  • v3.2.1
  • v3.2.2
  • v3.3.0
  • v3.4.0
  • v3.5.0
  • v3.6.0
  • v3.7.0
  • v3.7.1
  • v3.7.2
  • v3.7.3
  • v3.8.0
  • v3.8.1
  • v3.8.2
  • v4.0.0
  • v4.1.0
  • v4.2.0
  • v4.2.1
  • v4.2.2
  • v4.3.0
  • v4.3.1
  • v4.3.2
  • v4.3.3
  • v4.3.4
  • v4.4.0
  • v4.4.1
  • v4.4.2
  • v4.4.3
45 results
Show changes
Showing
with 2032 additions and 1698 deletions
/*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
* Copyright Projet JRL-Japan, 2007
*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
*
* File: SignalPtr.t.cpp
* Project: DYNAMIC-GRAPH
* Author: Nicolas Mansard
*
* Version control
* ===============
*
* $Id$
*
* Description
* ============
*
*
* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
#ifndef __SIGNAL_PTR_TCPP
#define __SIGNAL_PTR_TCPP
// -*- mode: c++ -*-
// Copyright 2010, François Bleibel, Thomas Moulard, Olivier Stasse,
// JRL, CNRS/AIST.
//
#ifndef DYNAMIC_GRAPH_SIGNAL_PTR_T_CPP
#define DYNAMIC_GRAPH_SIGNAL_PTR_T_CPP
#include <dynamic-graph/signal-ptr.h>
#undef VP_TEMPLATE_DEBUG_MODE
......@@ -30,245 +12,218 @@
#include <dynamic-graph/debug.h>
namespace dynamicgraph {
template <class T, class Time>
bool SignalPtr<T, Time>::isAbstractPluged() const {
return ((NULL != signalPtr) || (abstractTransmitter));
}
template< class T,class Time >
bool SignalPtr<T,Time>::
isAbstractPluged( void ) const
{
return ( (NULL!=signalPtr)||(abstractTransmitter) );
}
template< class T,class Time >
Signal<T,Time>* SignalPtr<T,Time>::
getPtr ( void )
{
template <class T, class Time>
Signal<T, Time> *SignalPtr<T, Time>::getPtr() {
dgTDEBUGIN(25);
if(! isPluged() )
DG_THROW ExceptionSignal( ExceptionSignal::NOT_INITIALIZED,
"In SignalPtr: SIN ptr not set.",
" (in signal <%s>)",getName().c_str());
if (!isPlugged()) DG_THROW
ExceptionSignal(ExceptionSignal::NOT_INITIALIZED,
"In SignalPtr: SIN ptr not set.", " (in signal <%s>)",
getName().c_str());
dgTDEBUGOUT(25);
return signalPtr;
return signalPtr;
}
template< class T,class Time >
const Signal<T,Time>* SignalPtr<T,Time>::
getPtr ( void ) const
{
dgTDEBUGIN(25) << SignalBase<Time>::name <<"("<< isPluged() <<")"
<< this << "->"<<signalPtr <<std::endl;
template <class T, class Time>
const Signal<T, Time> *SignalPtr<T, Time>::getPtr() const {
dgTDEBUGIN(25) << SignalBase<Time>::name << "(" << isPlugged() << ")" << this
<< "->" << signalPtr << std::endl;
dgTDEBUGIN(25);
if(! isPluged() )
{ DG_THROW ExceptionSignal( ExceptionSignal::NOT_INITIALIZED,
"In SignalPtr: SIN ptr not set.",
" (in signal <%s>)",getName().c_str()); }
if (!isPlugged()) {
DG_THROW ExceptionSignal(ExceptionSignal::NOT_INITIALIZED,
"In SignalPtr: SIN ptr not set.",
" (in signal <%s>)", getName().c_str());
}
dgTDEBUGOUT(25);
return signalPtr;
return signalPtr;
}
template< class T,class Time >
SignalBase<Time>* SignalPtr<T,Time>::
getAbstractPtr ( void )
{
if(! isAbstractPluged() )
{ DG_THROW ExceptionSignal( ExceptionSignal::NOT_INITIALIZED,
"In SignalPtr: SIN ptr not set.",
" (in signal <%s>)",getName().c_str()); }
if( NULL!=signalPtr ) return signalPtr;
else return abstractTransmitter;
template <class T, class Time>
SignalBase<Time> *SignalPtr<T, Time>::getAbstractPtr() {
if (!isAbstractPluged()) {
DG_THROW ExceptionSignal(ExceptionSignal::NOT_INITIALIZED,
"In SignalPtr: SIN ptr not set.",
" (in signal <%s>)", getName().c_str());
}
if (NULL != signalPtr)
return signalPtr;
else
return abstractTransmitter;
}
template< class T,class Time >
const SignalBase<Time>* SignalPtr<T,Time>::
getAbstractPtr ( void ) const
{
if(! isAbstractPluged() )
{ DG_THROW ExceptionSignal( ExceptionSignal::NOT_INITIALIZED,
"In SignalPtr: SIN ptr not set.",
" (in signal <%s>)",getName().c_str()); }
if( NULL!=signalPtr ) return signalPtr;
else return abstractTransmitter;
template <class T, class Time>
const SignalBase<Time> *SignalPtr<T, Time>::getAbstractPtr() const {
if (!isAbstractPluged()) {
DG_THROW ExceptionSignal(ExceptionSignal::NOT_INITIALIZED,
"In SignalPtr: SIN ptr not set.",
" (in signal <%s>)", getName().c_str());
}
if (NULL != signalPtr)
return signalPtr;
else
return abstractTransmitter;
}
template< class T,class Time >
void SignalPtr<T,Time>::
plug( SignalBase<Time>* unknown_ref )
{
template <class T, class Time>
void SignalPtr<T, Time>::plug(SignalBase<Time> *unknown_ref) {
dgTDEBUGIN(5);
if(! unknown_ref )
{
signalPtr = NULL;
transmitAbstract = false;
dgTDEBUGOUT(5);
return;
}
dgTDEBUG(5) << "# In T = "<< getName() <<" ="
<<typeid( Signal<T,Time>::Tcopy1 ) .name() << "{ "<<std::endl;
Signal<T,Time> * ref = dynamic_cast< Signal<T,Time>* > (unknown_ref);
if( NULL==ref )
{
try {
unknown_ref->checkCompatibility();
}
catch( T* t )
{
dgTDEBUG(25) << "Cast THROW ok."<< std::endl;
Signal<T,Time>::setReference( t );
transmitAbstract = true; abstractTransmitter = unknown_ref;
transmitAbstractData = t;
}
catch(...)
{
dgTDEBUG(25) << "Fatal error."<< std::endl;
transmitAbstract = false;
DG_THROW ExceptionSignal( ExceptionSignal::PLUG_IMPOSSIBLE,
"Compl. Uncompatible types for plugin.",
"(while trying to plug <%s> on <%s>).",
unknown_ref->getName().c_str(),
this->getName().c_str());
}
}
else
{
dgTDEBUG(25) << "Cast ok."<< std::endl;
if (!unknown_ref) {
signalPtr = NULL;
transmitAbstract = false;
dgTDEBUGOUT(5);
return;
}
dgTDEBUG(5) << "# In T = " << getName() << " ="
<< typeid(Signal<T, Time>::Tcopy1).name() << "{ " << std::endl;
Signal<T, Time> *ref = dynamic_cast<Signal<T, Time> *>(unknown_ref);
if (NULL == ref) {
try {
unknown_ref->checkCompatibility();
} catch (T *t) {
dgTDEBUG(25) << "Cast THROW ok." << std::endl;
Signal<T, Time>::setReference(t);
transmitAbstract = true;
abstractTransmitter = unknown_ref;
transmitAbstractData = t;
} catch (...) {
dgTDEBUG(25) << "Fatal error." << std::endl;
transmitAbstract = false;
signalPtr = ref;
DG_THROW ExceptionSignal(ExceptionSignal::PLUG_IMPOSSIBLE,
"Compl. Uncompatible types for plugin.",
"(while trying to plug <%s> on <%s>)"
" with types <%s> on <%s>.",
unknown_ref->getName().c_str(),
this->getName().c_str(), typeid(T).name(),
typeid(unknown_ref).name());
}
} else {
dgTDEBUG(25) << "Cast ok." << std::endl;
transmitAbstract = false;
signalPtr = ref;
}
dgTDEBUGOUT(5);
}
template< class T,class Time >
bool SignalPtr<T,Time>::
needUpdate( const Time& t ) const
{
if( (isAbstractPluged())&&(!autoref()) ){ return getAbstractPtr()->needUpdate(t);}
else return Signal<T,Time>::needUpdate(t);
template <class T, class Time>
void SignalPtr<T, Time>::checkCompatibility() {
if (isPlugged() && (!autoref())) {
getPtr()->checkCompatibility();
} else if (isAbstractPluged() && (!autoref())) {
abstractTransmitter->checkCompatibility();
} else
Signal<T, Time>::checkCompatibility();
}
template< class T,class Time >
const Time& SignalPtr<T,Time>::getTime( void ) const
{
if( (isAbstractPluged())&&(!autoref()) ){ return getAbstractPtr()->getTime();}
return Signal<T,Time>::getTime();
template <class T, class Time>
bool SignalPtr<T, Time>::needUpdate(const Time &t) const {
if ((isAbstractPluged()) && (!autoref())) {
return getAbstractPtr()->needUpdate(t);
} else
return Signal<T, Time>::needUpdate(t);
}
template <class T, class Time>
const Time &SignalPtr<T, Time>::getTime() const {
if ((isAbstractPluged()) && (!autoref())) {
return getAbstractPtr()->getTime();
}
return Signal<T, Time>::getTime();
}
template< class T,class Time >
const T& SignalPtr<T,Time>::
operator()( const Time & t )
{
return access(t);
template <class T, class Time>
const T &SignalPtr<T, Time>::operator()(const Time &t) {
return access(t);
}
template< class T,class Time >
const T& SignalPtr<T,Time>::
access( const Time & t )
{
template <class T, class Time>
const T &SignalPtr<T, Time>::access(const Time &t) {
dgTDEBUGIN(15);
if( modeNoThrow&&(! isPluged())&&Signal<T,Time>::copyInit )
{
dgTDEBUGOUT(15);
return Signal<T,Time>::accessCopy();
}
else if( autoref() )
{
dgTDEBUGOUT(15);
return Signal<T,Time>::access(t);
}
else if( transmitAbstract )
{
abstractTransmitter->recompute(t);
dgTDEBUGOUT(15);
return *transmitAbstractData;
}
else
{
dgTDEBUGOUT(15);
return getPtr()->access(t);
}
if (modeNoThrow && (!isPlugged()) && Signal<T, Time>::copyInit) {
dgTDEBUGOUT(15);
return Signal<T, Time>::accessCopy();
} else if (autoref()) {
dgTDEBUGOUT(15);
return Signal<T, Time>::access(t);
} else if (transmitAbstract) {
abstractTransmitter->recompute(t);
dgTDEBUGOUT(15);
return *transmitAbstractData;
} else {
dgTDEBUGOUT(15);
return getPtr()->access(t);
}
}
template< class T,class Time >
const T& SignalPtr<T,Time>::
accessCopy( void ) const
{
if( modeNoThrow&&(! isPluged())&&Signal<T,Time>::copyInit )
return Signal<T,Time>::accessCopy();
else if( autoref() ) return Signal<T,Time>::accessCopy();
else if( transmitAbstract ) return *transmitAbstractData;
else return getPtr()->accessCopy();
template <class T, class Time>
const T &SignalPtr<T, Time>::accessCopy() const {
if (modeNoThrow && (!isPlugged()) && Signal<T, Time>::copyInit)
return Signal<T, Time>::accessCopy();
else if (autoref())
return Signal<T, Time>::accessCopy();
else if (transmitAbstract)
return *transmitAbstractData;
else
return getPtr()->accessCopy();
}
template< class T, class Time>
std::ostream & SignalPtr<T,Time>::
writeGraph(std::ostream &os) const
{
template <class T, class Time>
std::ostream &SignalPtr<T, Time>::writeGraph(std::ostream &os) const {
std::string LeaderLocalName;
std::string LeaderNodeName;
Signal<T,Time>::ExtractNodeAndLocalNames(LeaderLocalName,LeaderNodeName);
if ( isAbstractPluged() && !autoref())
{
std::string itLocalName,itNodeName;
getAbstractPtr()->ExtractNodeAndLocalNames(itLocalName,itNodeName);
os << "\t\"" << itNodeName << "\" -> \"" << LeaderNodeName << "\"" << std::endl
<< "\t [ headlabel = \"" << LeaderLocalName
<< "\" , taillabel = \"" << itLocalName
<< "\", fontsize=7, fontcolor=red ]" << std::endl;
}
Signal<T, Time>::ExtractNodeAndLocalNames(LeaderLocalName, LeaderNodeName);
if (isAbstractPluged() && !autoref()) {
std::string itLocalName, itNodeName;
getAbstractPtr()->ExtractNodeAndLocalNames(itLocalName, itNodeName);
os << "\t\"" << itNodeName << "\" -> \"" << LeaderNodeName << "\""
<< std::endl
<< "\t [ headlabel = \"" << LeaderLocalName << "\" , taillabel = \""
<< itLocalName << "\", fontsize=7, fontcolor=red ]" << std::endl;
}
return os;
}
template< class T,class Time >
std::ostream& SignalPtr<T,Time>::
display( std::ostream& os ) const
{
dgTDEBUGIN(25) << SignalBase<Time>::name << this << "||" << isPluged() << "||"<<signalPtr;
{ Signal<T,Time>::display(os); }
template <class T, class Time>
std::ostream &SignalPtr<T, Time>::display(std::ostream &os) const {
dgTDEBUGIN(25) << SignalBase<Time>::name << this << "||" << isPlugged()
<< "||" << signalPtr;
{ Signal<T, Time>::display(os); }
if ((isAbstractPluged()) && (!autoref())) {
os << " -->-- PLUGGED";
} else {
if (!isAbstractPluged())
os << " UNPLUGGED";
else if (autoref())
os << " AUTOPLUGGED";
}
if( (isAbstractPluged())&&(!autoref()) )
{
// dgTDEBUG(25) << "Display pointed."<<std::endl;
// getPtr()->display(os<<"PTR->");
os << " -->-- PLUGGED";
}
else
{
if(! isAbstractPluged()) os << " UNPLUGGED";
else if(autoref()) os << " AUTOPLUGGED";
}
dgTDEBUGOUT(25);
return os;
}
template< class T,class Time >
std::ostream& SignalPtr<T,Time>::
displayDependencies( std::ostream& os,const int depth,
std::string space,
std::string next1,std::string next2 ) const
{
template <class T, class Time>
std::ostream &SignalPtr<T, Time>::displayDependencies(std::ostream &os,
const int depth,
std::string space,
std::string next1,
std::string next2) const {
dgTDEBUGIN(25);
if( (isAbstractPluged())&&(!autoref()) )
{ getAbstractPtr()->displayDependencies(os,depth,space,next1+"-- "
+SignalBase<Time>::name+" -->",next2); }
else
{
SignalBase<Time>::displayDependencies(os,depth,space,next1,next2);
}
if ((isAbstractPluged()) && (!autoref())) {
getAbstractPtr()->displayDependencies(
os, depth, space, next1 + "-- " + SignalBase<Time>::name + " -->",
next2);
} else {
SignalBase<Time>::displayDependencies(os, depth, space, next1, next2);
}
dgTDEBUGOUT(25);
return os;
}
} // namespace dynamicgraph
#endif // #ifndef __SIGNAL_PTR_TCPP
/*
* Local variables:
* c-basic-offset: 2
* End:
*/
} // end of namespace dynamicgraph.
#endif //! DYNAMIC_GRAPH_SIGNAL_PTR_T_CPP
/*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
* Copyright Projet JRL-Japan, 2007
*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
*
* File: signal-time-dependent.h
* Project: DYNAMIC-GRAPH
* Author: Nicolas Mansard
*
* Version control
* ===============
*
* $Id$
*
* Description
* ============
*
*
* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
#ifndef __DEPENDENT_SIGNAL_HH
#define __DEPENDENT_SIGNAL_HH
// -*- mode: c++ -*-
// Copyright 2010, François Bleibel, Thomas Moulard, Olivier Stasse,
// JRL, CNRS/AIST.
//
#ifndef DYNAMIC_GRAPH_SIGNAL_TIME_DEPENDENT_H
#define DYNAMIC_GRAPH_SIGNAL_TIME_DEPENDENT_H
#include <dynamic-graph/signal.h>
#include <dynamic-graph/time-dependency.h>
namespace dynamicgraph {
/*! \brief A type of signal that enforces a time dependency between other
signals,
making sure its inputs are up to date on access, using a incrementing time
tick as reference.
It works this way. For a given SignalTimeDependent S,
- the user manually adds dependent signals through the use of the
SignalTimeDependent::addDependency function.
- On access (calling the signal S SignalTimeDependent::operator()(const Time&)
or SignalTimeDependent::access(const Time&) function), if the dependent
signals are not up-to-date, i.e. if their [last update] time is less than the
current time, their value will be SignalTimeDependent::access ()'ed to bring
them up-to-date.
Thus, the value of dependent signals can be accessed \b quickly and
\b repeatedly through the Signal::accessCopy () function.
An example:
\code
class MyEntity : public Entity {
public:
// Some signal dependencies
SignalPtr<T,int> dep1, dep2;
SignalTimeDependent<T,int> signal;
MyEntity (const std::string& name)
: Entity (name)
, signal (
// Set the function that computes the signal value
boost::bind (&Entity::computeSignal, this, _1, _2),
// Declare the dependencies
dep1 << dep2,
"signalname")
{}
T& computeSignal (T& res, int time)
{
// The accesses below update the signal if necessary.
dep1(time);
dep1.access(time);
dep1.recompute(time);
// If dep1 and dep2 are already up-to-date, for a faster access, use
dep1.accessCopy();
dep2.accessCopy();
// Compute res
return res;
}
\endcode
*/
template <class T, class Time>
class SignalTimeDependent : public virtual Signal<T, Time>,
public TimeDependency<Time> {
// TimeDependency<Time> timeDependency;
template< class T,class Time >
class SignalTimeDependent
: public virtual Signal<T,Time>
, public TimeDependency<Time>
{
public:
SignalTimeDependent(std::string name = "");
SignalTimeDependent(const SignalArray_const<Time> &arr,
std::string name = "");
SignalTimeDependent(boost::function2<T &, T &, Time> t,
const SignalArray_const<Time> &sig,
std::string name = "");
virtual ~SignalTimeDependent() {}
inline const T &operator()(const Time &t1) { return access(t1); }
const T &access(const Time &t1);
virtual void addDependency(const SignalBase<Time> &signal);
virtual void removeDependency(const SignalBase<Time> &signal);
virtual void clearDependencies();
std::ostream &writeGraph(std::ostream &os) const { return os; }
std::ostream &displayDependencies(std::ostream &os, const int depth = -1,
std::string space = "",
std::string next1 = "",
std::string next2 = "") const {
return TimeDependency<Time>::displayDependencies(os, depth, space, next1,
next2);
}
virtual bool needUpdate(const Time &t) const;
virtual void setPeriodTime(const Time &p);
virtual Time getPeriodTime() const;
};
//TimeDependency<Time> timeDependency;
/* -------------------------------------------- */
public:
SignalTimeDependent( std::string name = "" );
SignalTimeDependent( const SignalArray_const<Time> & arr
,std::string name = "" );
SignalTimeDependent( boost::function2<T&,T&,Time> t
,const SignalArray_const<Time> & sig
,std::string name = "" );
virtual ~SignalTimeDependent( void ) {}
inline const T& operator() ( const Time& t1 ){ return access(t1); }
const T& access( const Time& t1 );
virtual void addDependency( const SignalBase<Time>& signal ) ;
virtual void removeDependency( const SignalBase<Time>& signal ) ;
virtual void clearDependencies( void );
std::ostream& writeGraph(std::ostream &os) const
{ return os;}
std::ostream& displayDependencies( std::ostream& os,const int depth=-1,
std::string space="",
std::string next1="",std::string next2="" ) const
{ return TimeDependency<Time>::displayDependencies( os,depth,space,next1,next2 ); }
virtual bool needUpdate( const Time& t ) const;
virtual void setPeriodTime( const Time& p ) ;
virtual Time getPeriodTime( void ) const;
template <class T, class Time>
SignalTimeDependent<T, Time>::SignalTimeDependent(std::string name)
: Signal<T, Time>(name), TimeDependency<Time>(this) {}
template <class T, class Time>
SignalTimeDependent<T, Time>::SignalTimeDependent(
const SignalArray_const<Time> &arr, std::string name)
: Signal<T, Time>(name), TimeDependency<Time>(this, arr) {}
template <class T, class Time>
SignalTimeDependent<T, Time>::SignalTimeDependent(
boost::function2<T &, T &, Time> t, const SignalArray_const<Time> &sig,
std::string name)
: Signal<T, Time>(name), TimeDependency<Time>(this, sig) {
this->setFunction(t);
}
};
template <class T, class Time>
const T &SignalTimeDependent<T, Time>::access(const Time &t1) {
const bool up = TimeDependency<Time>::needUpdate(t1);
// SignalBase<Time>::setReady(false);
/* std::cout << "Time before: "<< signalTime << " -- " */
/* << t1<< " -> Up: "<<up <<std::endl ; */
if (up) {
TimeDependency<Time>::lastAskForUpdate = false;
const T &Tres = Signal<T, Time>::access(t1);
SignalBase<Time>::setReady(false);
return Tres;
} else {
return Signal<T, Time>::accessCopy();
}
}
template <class T, class Time>
void SignalTimeDependent<T, Time>::addDependency(
const SignalBase<Time> &signal) {
TimeDependency<Time>::addDependency(signal);
}
/* -------------------------------------------- */
template <class T, class Time>
void SignalTimeDependent<T, Time>::removeDependency(
const SignalBase<Time> &signal) {
TimeDependency<Time>::removeDependency(signal);
}
template <class T, class Time>
void SignalTimeDependent<T, Time>::clearDependencies() {
TimeDependency<Time>::clearDependency();
}
template < class T,class Time >
SignalTimeDependent<T,Time>::
SignalTimeDependent( std::string name )
:Signal<T,Time>(name)
,TimeDependency<Time>(this)
{}
template< class T,class Time>
SignalTimeDependent<T,Time>::
SignalTimeDependent( const SignalArray_const<Time> & arr
,std::string name )
:Signal<T,Time>(name)
,TimeDependency<Time>(this,arr)
{}
template< class T,class Time>
SignalTimeDependent<T,Time>::
SignalTimeDependent( boost::function2<T&,T&,Time> t
,const SignalArray_const<Time> & sig
,std::string name )
:Signal<T,Time>(name)
,TimeDependency<Time>(this,sig)
{ setFunction(t); }
template< class T,class Time>
const T& SignalTimeDependent<T,Time>::
access( const Time& t1 )
{
const bool up = TimeDependency<Time>::needUpdate(t1);
//SignalBase<Time>::setReady(false);
/* std::cout << "Time before: "<< signalTime << " -- " */
/* << t1<< " -> Up: "<<up <<std::endl ; */
if( up )
{
TimeDependency<Time>::lastAskForUpdate = false;
const T& Tres = Signal<T,Time>::access(t1);
SignalBase<Time>::setReady(false);
return Tres;
}
else { return Signal<T,Time>::accessCopy(); }
}
template< class T,class Time>
void SignalTimeDependent<T,Time>::
addDependency( const SignalBase<Time>& signal )
{ TimeDependency<Time>::addDependency(signal); }
template< class T,class Time>
void SignalTimeDependent<T,Time>::
removeDependency( const SignalBase<Time>& signal )
{ TimeDependency<Time>::removeDependency(signal); }
template< class T,class Time>
void SignalTimeDependent<T,Time>::
clearDependencies( void )
{ TimeDependency<Time>::clearDependency(); }
template< class T,class Time>
bool SignalTimeDependent<T,Time>::
needUpdate( const Time& t ) const
{
return TimeDependency<Time>::needUpdate(t);
template <class T, class Time>
bool SignalTimeDependent<T, Time>::needUpdate(const Time &t) const {
return TimeDependency<Time>::needUpdate(t);
}
template< class T,class Time>
void SignalTimeDependent<T,Time>::
setPeriodTime( const Time& p )
{ TimeDependency<Time>::setPeriodTime( p ); }
template< class T,class Time>
Time SignalTimeDependent<T,Time>::
getPeriodTime( void ) const
{ return TimeDependency<Time>::getPeriodTime(); }
template <class T, class Time>
void SignalTimeDependent<T, Time>::setPeriodTime(const Time &p) {
TimeDependency<Time>::setPeriodTime(p);
}
template <class T, class Time>
Time SignalTimeDependent<T, Time>::getPeriodTime() const {
return TimeDependency<Time>::getPeriodTime();
}
} // namespace dynamicgraph
} // end of namespace dynamicgraph
#endif /* #ifndef __DEPENDENT_SIGNAL_HH */
#endif //! DYNAMIC_GRAPH_SIGNAL_TIME_DEPENDENT_H
/*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
* Copyright Projet JRL-Japan, 2007
*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
*
* File: Signal.h
* Project: DYNAMIC-GRAPH
* Author: Nicolas Mansard
*
* Version control
* ===============
*
* $Id$
*
* Description
* ============
/*
* Copyright 2010,
* François Bleibel,
* Olivier Stasse,
*
* CNRS/AIST
*
* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
*/
#ifndef __SIGNAL_HH
#define __SIGNAL_HH
#include <boost/bind.hpp>
#include <boost/function.hpp>
#include <string>
#include <iostream>
#include <dynamic-graph/exception-signal.h>
#include <dynamic-graph/signal-base.h>
#include <boost/bind.hpp>
#include <boost/function.hpp>
#include <string>
#ifdef HAVE_LIBBOOST_THREAD
#include <boost/thread.hpp>
......@@ -45,30 +29,28 @@ namespace dynamicgraph {
or evaluated as a function.
See SignalPtr and SignalTimeDependent for other types of signals,
and SignalArray for a way of grouping them.
*/
template< class T,class Time >
class Signal
: public SignalBase<Time>
{
protected:
enum SignalType
{
CONSTANT
,REFERENCE
,REFERENCE_NON_CONST
,FUNCTION
};
There are several ways to specify the value output by a signal:
\li using the function setConstant(T) to set the value of the signal to T;
\li using the function setReference(mutex, T*) to set the value
from a pointer, whose access is restricted by a mutex;
\li using the function setFunction(boost::function2) that will be called
when the signal's value is accessed.
*/
template <class T, class Time>
class Signal : public SignalBase<Time> {
protected:
enum SignalType { CONSTANT, REFERENCE, REFERENCE_NON_CONST, FUNCTION };
static const SignalType SIGNAL_TYPE_DEFAULT = CONSTANT;
SignalType signalType;
T Tcopy1,Tcopy2;
T* Tcopy;
T Tcopy1, Tcopy2;
T *Tcopy;
bool copyInit;
const T* Treference;
T* TreferenceNonConst;
boost::function2<T&,T&,Time> Tfunction;
const T *Treference;
T *TreferenceNonConst;
boost::function2<T &, T &, Time> Tfunction;
bool keepReference;
const static bool KEEP_REFERENCE_DEFAULT = false;
......@@ -78,11 +60,11 @@ class Signal
typedef boost::try_mutex Mutex;
typedef boost::lock_error MutexError;
#else
typedef int* Mutex;
typedef int* MutexError;
typedef int *Mutex;
typedef int *MutexError;
#endif
protected:
protected:
Mutex *providerMutex;
using SignalBase<Time>::signalTime;
......@@ -90,59 +72,60 @@ protected:
using SignalBase<Time>::setReady;
public:
/* --- Constructor/destrusctor --- */
Signal( std::string name );
virtual ~Signal( void ) {}
Signal(std::string name);
virtual ~Signal() {}
/* --- Generic In/Out function --- */
virtual void get( std::ostream& value ) const;
virtual void set( std::istringstream& value ) ;
virtual void trace( std::ostream& os ) const;
virtual void get(std::ostream &value) const;
virtual void set(std::istringstream &value);
virtual void trace(std::ostream &os) const;
/* --- Generic Set function --- */
virtual void setConstant( const T& t );
virtual void setReference( const T* t,Mutex *mutexref=NULL );
virtual void setReferenceNonConstant( T* t,Mutex *mutexref=NULL );
virtual void setFunction( boost::function2<T&,T&,Time> t,
Mutex *mutexref=NULL);
virtual void setConstant(const T &t);
virtual void setReference(const T *t, Mutex *mutexref = NULL);
virtual void setReferenceNonConstant(T *t, Mutex *mutexref = NULL);
virtual void setFunction(boost::function2<T &, T &, Time> t,
Mutex *mutexref = NULL);
inline bool getKeepReference( void ){ return keepReference; }
inline void setKeepReference( const bool& b ){ keepReference=b; }
inline bool getKeepReference() { return keepReference; }
inline void setKeepReference(const bool &b) { keepReference = b; }
/* --- Signal computation --- */
virtual const T& access( const Time & t );
virtual inline void recompute( const Time & t ) { access(t); }
virtual const T& accessCopy( void ) const;
virtual std::ostream& display( std::ostream& os ) const;
virtual const T &access(const Time &t);
virtual inline void recompute(const Time &t) { access(t); }
virtual const T &accessCopy() const;
/* --- Operators --- */
virtual inline const T& operator()( const Time & t ){ return access(t); }
virtual Signal<T,Time>& operator= ( const T& t );
inline operator const T& ( void ) const { return accessCopy(); }
virtual std::ostream &display(std::ostream &os) const;
/* --- Operators --- */
virtual inline const T &operator()(const Time &t) { return access(t); }
virtual Signal<T, Time> &operator=(const T &t);
inline operator const T &() const { return accessCopy(); }
virtual void getClassName(std::string &aClassName) const {
aClassName = typeid(this).name();
}
public:
virtual void checkCompatibility( void ) { throw Tcopy; }
/// checkCompatibility is used to get the object contained in the
/// signal. This used to verify if a dynamic cast is possible or not.
virtual void checkCompatibility() { throw Tcopy; }
private:
const T& setTcopy( const T& t );
T& getTwork( void );
const T& getTwork( void ) const ;
const T& switchTcopy( void );
const T &setTcopy(const T &t);
T &getTwork();
const T &getTwork() const;
const T &switchTcopy();
};
} // namespace dynamicgraph
} // end of namespace dynamicgraph
#include <dynamic-graph/signal.t.cpp>
#endif // #ifndef __SIGNAL_HH
#endif // #ifndef __SIGNAL_HH
/*
* Local variables:
* c-basic-offset: 4
* End:
*/
/*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
* Copyright Projet JRL-Japan, 2007
*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
*
* File: Signal.t.cpp
* Project: DYNAMIC-GRAPH
* Author: Nicolas Mansard
*
* Version control
* ===============
*
* $Id$
*
* Description
* ============
*
*
* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
// -*- mode: c++ -*-
// Copyright 2010, François Bleibel, Thomas Moulard, Olivier Stasse,
// JRL, CNRS/AIST.
//
#ifndef __SIGNAL_TEMPLATE
#define __SIGNAL_TEMPLATE
#include <dynamic-graph/signal.h>
#ifndef DYNAMIC_GRAPH_SIGNAL_T_CPP
#define DYNAMIC_GRAPH_SIGNAL_T_CPP
#include <dynamic-graph/signal-caster.h>
#include <dynamic-graph/signal.h>
#undef VP_TEMPLATE_DEBUG_MODE
#define VP_TEMPLATE_DEBUG_MODE 0
#include <dynamic-graph/debug.h>
namespace dynamicgraph {
#define __SIGNAL_INIT(name, Tcpy, Tref, TrefNC, mutex) \
SignalBase<Time>(name), signalType(SIGNAL_TYPE_DEFAULT), Tcopy1(Tcpy), \
Tcopy2(Tcpy), Tcopy(&Tcopy1), Treference(Tref), \
TreferenceNonConst(TrefNC), Tfunction(), \
keepReference(KEEP_REFERENCE_DEFAULT), providerMutex(mutex)
#define __SIGNAL_INIT(name,Tcpy,Tref,TrefNC,mutex) \
SignalBase<Time>(name) \
,signalType(SIGNAL_TYPE_DEFAULT) \
,Tcopy1(Tcpy) \
,Tcopy2(Tcpy) \
,Tcopy(&Tcopy1) \
,Treference(Tref) \
,TreferenceNonConst(TrefNC) \
,Tfunction() \
,keepReference( KEEP_REFERENCE_DEFAULT ) \
,providerMutex(mutex)
namespace dynamicgraph {
template< class T,class Time >
Signal<T,Time>::
Signal( std::string name )
:__SIGNAL_INIT(name,,NULL,NULL,NULL)
{
template <class T, class Time>
Signal<T, Time>::Signal(std::string name)
: __SIGNAL_INIT(name, T(), NULL, NULL, NULL) {
return;
}
/* -------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------ */
template< class T,class Time >
void Signal<T,Time>::
set( std::istringstream& stringValue )
{
(*this) = signal_cast<T>( stringValue );
template <class T, class Time>
void Signal<T, Time>::set(std::istringstream &stringValue) {
(*this) = signal_io<T>::cast(stringValue);
}
template< class T,class Time >
void Signal<T,Time>::
get( std::ostream& os ) const
{
signal_disp<T>( this->accessCopy(),os );
template <class T, class Time>
void Signal<T, Time>::get(std::ostream &os) const {
signal_io<T>::disp(this->accessCopy(), os);
}
template< class T,class Time >
void Signal<T,Time>::
trace( std::ostream& os ) const
{
try { signal_trace<T>( this->accessCopy(),os ); }
catch DG_RETHROW
catch (...)
{ DG_THROW ExceptionSignal( ExceptionSignal::SET_IMPOSSIBLE,
"TRACE operation not possible with this signal. ",
"(bad cast while getting value from %s).",
SignalBase<Time>::getName().c_str());
}
template <class T, class Time>
void Signal<T, Time>::trace(std::ostream &os) const {
try {
signal_io<T>::trace(this->accessCopy(), os);
} catch DG_RETHROW catch (...) {
DG_THROW ExceptionSignal(ExceptionSignal::SET_IMPOSSIBLE,
"TRACE operation not possible with this signal. ",
"(bad cast while getting value from %s).",
SignalBase<Time>::getName().c_str());
}
}
/* ------------------------------------------------------------------------ */
/* -------------------------------------------------------------------------- */
template< class T,class Time >
const T& Signal<T,Time>::
setTcopy( const T& t )
{
if( Tcopy==&Tcopy1 )
{
Tcopy2 = t;
copyInit = true;
Tcopy = &Tcopy2;
return Tcopy2;
}
else
{
Tcopy1 = t;
copyInit = true;
Tcopy = &Tcopy1;
return Tcopy1;
}
}
template< class T,class Time >
T& Signal<T,Time>::
getTwork( void )
{
if( Tcopy==&Tcopy1 ) return Tcopy2; else return Tcopy1;
template <class T, class Time>
const T &Signal<T, Time>::setTcopy(const T &t) {
if (Tcopy == &Tcopy1) {
Tcopy2 = t;
copyInit = true;
Tcopy = &Tcopy2;
return Tcopy2;
} else {
Tcopy1 = t;
copyInit = true;
Tcopy = &Tcopy1;
return Tcopy1;
}
}
template< class T,class Time >
const T& Signal<T,Time>::
getTwork( void ) const
{
if( Tcopy==&Tcopy1 ) return Tcopy2; else return Tcopy1;
template <class T, class Time>
T &Signal<T, Time>::getTwork() {
if (Tcopy == &Tcopy1)
return Tcopy2;
else
return Tcopy1;
}
template< class T,class Time >
const T& Signal<T,Time>::
switchTcopy( void )
{
if( Tcopy==&Tcopy1 )
{
Tcopy = &Tcopy2;
return Tcopy2;
}
template <class T, class Time>
const T &Signal<T, Time>::getTwork() const {
if (Tcopy == &Tcopy1)
return Tcopy2;
else
{
Tcopy = &Tcopy1;
return Tcopy1;
}
return Tcopy1;
}
template <class T, class Time>
const T &Signal<T, Time>::switchTcopy() {
if (Tcopy == &Tcopy1) {
Tcopy = &Tcopy2;
return Tcopy2;
} else {
Tcopy = &Tcopy1;
return Tcopy1;
}
}
template< class T,class Time >
void Signal<T,Time>::
setConstant( const T& t )
{
signalType = CONSTANT; setTcopy(t);
template <class T, class Time>
void Signal<T, Time>::setConstant(const T &t) {
signalType = CONSTANT;
setTcopy(t);
setReady();
}
template< class T,class Time >
void Signal<T,Time>::
setReference( const T* t,Mutex *mutexref )
{
signalType = REFERENCE; Treference = t;
template <class T, class Time>
void Signal<T, Time>::setReference(const T *t, Mutex *mutexref) {
signalType = REFERENCE;
Treference = t;
providerMutex = mutexref;
copyInit = false;
setReady();
}
template< class T,class Time >
void Signal<T,Time>::
setReferenceNonConstant( T* t,Mutex *mutexref )
{
template <class T, class Time>
void Signal<T, Time>::setReferenceNonConstant(T *t, Mutex *mutexref) {
signalType = REFERENCE_NON_CONST;
Treference = t;
TreferenceNonConst = t;
Treference = t;
TreferenceNonConst = t;
providerMutex = mutexref;
copyInit = false;
setReady();
}
template< class T,class Time >
void Signal<T,Time>::
setFunction( boost::function2<T&,T&,Time> t,Mutex *mutexref )
{
template <class T, class Time>
void Signal<T, Time>::setFunction(boost::function2<T &, T &, Time> t,
Mutex *mutexref) {
signalType = FUNCTION;
Tfunction = t;
providerMutex = mutexref;
......@@ -182,140 +130,111 @@ setFunction( boost::function2<T&,T&,Time> t,Mutex *mutexref )
setReady();
}
template< class T,class Time >
const T& Signal<T,Time>::
accessCopy( void ) const
{
return *Tcopy;
template <class T, class Time>
const T &Signal<T, Time>::accessCopy() const {
return *Tcopy;
}
template< class T,class Time >
const T& Signal<T,Time>::
access(const Time& t)
{
//dgTDEBUG(20) << "# In (" << SignalBase<Time>::name <<")"<<std::endl;
switch( signalType )
{
template <class T, class Time>
const T &Signal<T, Time>::access(const Time &t) {
switch (signalType) {
case REFERENCE:
case REFERENCE_NON_CONST:
{
if( NULL==providerMutex )
{
copyInit=true;
signalTime = t;
return setTcopy( *Treference );
}
else
{
try
{
case REFERENCE_NON_CONST: {
if (NULL == providerMutex) {
copyInit = true;
signalTime = t;
return setTcopy(*Treference);
} else {
try {
#ifdef HAVE_LIBBOOST_THREAD
boost::try_mutex::scoped_try_lock lock(*providerMutex);
boost::try_mutex::scoped_try_lock lock(*providerMutex);
#endif
copyInit = true;
signalTime = t;
return setTcopy(*Treference);
}
catch( MutexError le )
{ return accessCopy(); }
}
break;
copyInit = true;
signalTime = t;
return setTcopy(*Treference);
} catch (const MutexError &) {
return accessCopy();
}
}
case FUNCTION:
{
if( NULL==providerMutex )
{
signalTime = t;
Tfunction(getTwork(),t);
copyInit=true;
return switchTcopy();
}
else
{
try
{
break;
}
case FUNCTION: {
if (NULL == providerMutex) {
signalTime = t;
Tfunction(getTwork(), t);
copyInit = true;
return switchTcopy();
} else {
try {
#ifdef HAVE_LIBBOOST_THREAD
boost::try_mutex::scoped_try_lock lock(*providerMutex);
boost::try_mutex::scoped_try_lock lock(*providerMutex);
#endif
signalTime = t;
Tfunction(getTwork(),t);
copyInit = true;
return switchTcopy();
}
catch( MutexError le )
{ return accessCopy(); }
}
break;
signalTime = t;
Tfunction(getTwork(), t);
copyInit = true;
return switchTcopy();
} catch (const MutexError &) {
return accessCopy();
}
}
case CONSTANT:
break;
}
case CONSTANT:
default:
if( this->getReady() )
{
setReady(false);
setTime(t);
}
if (this->getReady()) {
setReady(false);
this->setTime(t);
}
return accessCopy();
};
}
template< class T,class Time >
Signal<T,Time>& Signal<T,Time>::operator= ( const T& t )
{
if( keepReference&&(REFERENCE_NON_CONST==signalType)&&(NULL!=TreferenceNonConst) )
{
if( NULL==providerMutex )
{
setTcopy( t );
(*TreferenceNonConst)=t;
}
else
{
try
{
};
}
template <class T, class Time>
Signal<T, Time> &Signal<T, Time>::operator=(const T &t) {
if (keepReference && (REFERENCE_NON_CONST == signalType) &&
(NULL != TreferenceNonConst)) {
if (NULL == providerMutex) {
setTcopy(t);
(*TreferenceNonConst) = t;
} else {
try {
#ifdef HAVE_LIBBOOST_THREAD
boost::try_mutex::scoped_try_lock lock(*providerMutex);
boost::try_mutex::scoped_try_lock lock(*providerMutex);
#endif
setTcopy(t);
(*TreferenceNonConst)=t;
}
catch( MutexError le )
{ /* TODO ERROR */ }
}
}
else
{ setConstant( t ); }
return *this;
}
template< class T,class Time >
std::ostream& Signal<T,Time>::
display (std::ostream& os) const
{
os<<"Sig:"<<this->name<<" (Type ";
switch( this->signalType )
{
case Signal<T,Time>::CONSTANT: os<< "Cst";break;
case Signal<T,Time>::REFERENCE: os<<"Ref"; break;
case Signal<T,Time>::REFERENCE_NON_CONST: os<<"RefNonCst"; break;
case Signal<T,Time>::FUNCTION: os<<"Fun"; break;
setTcopy(t);
(*TreferenceNonConst) = t;
} catch (const MutexError &) { /* TODO ERROR */
}
}
return os<<")";
}
} // namespace dynamicgraph
#endif // #ifndef __SIGNAL_TEMPLATE
/*
* Local variables:
* c-basic-offset: 2
* End:
*/
} else {
setConstant(t);
}
return *this;
}
template <class T, class Time>
std::ostream &Signal<T, Time>::display(std::ostream &os) const {
os << "Sig:" << this->name << " (Type ";
switch (this->signalType) {
case Signal<T, Time>::CONSTANT:
os << "Cst";
break;
case Signal<T, Time>::REFERENCE:
os << "Ref";
break;
case Signal<T, Time>::REFERENCE_NON_CONST:
os << "RefNonCst";
break;
case Signal<T, Time>::FUNCTION:
os << "Fun";
break;
}
return os << ")";
}
} // end of namespace dynamicgraph.
#undef __SIGNAL_INIT
#endif //! DYNAMIC_GRAPH_SIGNAL_T_CPP
/*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
* Copyright Projet JRL-Japan, 2007
*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
*
* File: TimeDependency.h
* Project: DYNAMIC-GRAPH
* Author: Nicolas Mansard
*
* Version control
* ===============
*
* $Id$
*
* Description
* ============
*
*
* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
#ifndef __TIME_DEPENDENCY_HH
#define __TIME_DEPENDENCY_HH
// -*- mode: c++ -*-
// Copyright 2010, François Bleibel, Thomas Moulard, Olivier Stasse,
// JRL, CNRS/AIST.
//
#include <list>
#include <iostream>
#include <dynamic-graph/signal-base.h>
#ifndef DYNAMIC_GRAPH_TIME_DEPENDENCY_H
#define DYNAMIC_GRAPH_TIME_DEPENDENCY_H
#include <dynamic-graph/signal-array.h>
#include <dynamic-graph/signal-base.h>
namespace dynamicgraph {
#include <dynamic-graph/fwd.hh>
#include <list>
template< class Time >
class TimeDependency
{
namespace dynamicgraph {
/** \brief A helper class for setting and specifying dependencies
between signals.
*/
template <class Time>
class TimeDependency {
public:
enum DependencyType
{
TIME_DEPENDENT,
BOOL_DEPENDENT,
ALWAYS_READY
};
enum DependencyType { TIME_DEPENDENT, BOOL_DEPENDENT, ALWAYS_READY };
mutable Time lastAskForUpdate;
// protected:
public:
SignalBase<Time> &leader;
SignalBase< Time >& leader;
typedef std::list< const SignalBase<Time> * > Dependencies;
typedef std::list<const SignalBase<Time> *> Dependencies;
static const DependencyType DEPENDENCY_TYPE_DEFAULT = TIME_DEPENDENT;
Dependencies dependencies;
......@@ -63,39 +38,37 @@ class TimeDependency
static const Time PERIOD_TIME_DEFAULT = 1;
public:
TimeDependency( SignalBase<Time>* sig,
const DependencyType dep = DEPENDENCY_TYPE_DEFAULT );
TimeDependency( SignalBase<Time>* sig,
const SignalArray_const<Time>& arr,
const DependencyType dep = DEPENDENCY_TYPE_DEFAULT );
~TimeDependency( void ) {}
void addDependency( const SignalBase<Time>& sig );
void removeDependency( const SignalBase<Time>& sig );
void clearDependency( void );
virtual std::ostream & writeGraph(std::ostream &os) const;
std::ostream& displayDependencies( std::ostream& os,const int depth=-1,
std::string space="",
std::string next1="",std::string next2="" ) const;
bool needUpdate( const Time& t1 ) const;
void setDependencyType( DependencyType dep ) { dependencyType = dep; }
void setNeedUpdateFromAllChildren( const bool b = true ){ updateFromAllChildren=b; }
bool getNeedUpdateFromAllChildren( void ) const { return updateFromAllChildren; }
void setPeriodTime( const Time& p ) { periodTime = p; }
Time getPeriodTime( void ) const { return periodTime; }
TimeDependency(SignalBase<Time> *sig,
const DependencyType dep = DEPENDENCY_TYPE_DEFAULT);
TimeDependency(SignalBase<Time> *sig, const SignalArray_const<Time> &arr,
const DependencyType dep = DEPENDENCY_TYPE_DEFAULT);
virtual ~TimeDependency() {}
void addDependencies(const SignalArray_const<Time> &arr);
void addDependency(const SignalBase<Time> &sig);
void removeDependency(const SignalBase<Time> &sig);
void clearDependency();
virtual std::ostream &writeGraph(std::ostream &os) const;
std::ostream &displayDependencies(std::ostream &os, const int depth = -1,
std::string space = "",
std::string next1 = "",
std::string next2 = "") const;
bool needUpdate(const Time &t1) const;
void setDependencyType(DependencyType dep) { dependencyType = dep; }
void setNeedUpdateFromAllChildren(const bool b = true) {
updateFromAllChildren = b;
}
bool getNeedUpdateFromAllChildren() const { return updateFromAllChildren; }
void setPeriodTime(const Time &p) { periodTime = p; }
Time getPeriodTime() const { return periodTime; }
};
} // namespace dynamicgraph
} // end of namespace dynamicgraph
#include <dynamic-graph/time-dependency.t.cpp>
#endif /* #ifndef __TIME_DEPENDENCY_HH */
#endif //! DYNAMIC_GRAPH_TIME_DEPENDENCY_H
/*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
* Copyright Projet JRL-Japan, 2007
*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
*
* File: TimeDependency.t.cpp
* Project: DYNAMIC-GRAPH
* Author: Nicolas Mansard
*
* Version control
* ===============
*
* $Id$
*
* Description
* ============
*
*
* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
#ifndef __TIME_DEPENDENCY_TCPP
#define __TIME_DEPENDENCY_TCPP
// -*- mode: c++ -*-
// Copyright 2010, François Bleibel, Thomas Moulard, Olivier Stasse,
// JRL, CNRS/AIST.
//
#ifndef DYNAMIC_GRAPH_TIME_DEPENDENCY_T_CPP
#define DYNAMIC_GRAPH_TIME_DEPENDENCY_T_CPP
#include <dynamic-graph/time-dependency.h>
namespace dynamicgraph {
#undef VP_TEMPLATE_DEBUG_MODE
#define VP_TEMPLATE_DEBUG_MODE 0
#include <dynamic-graph/debug.h>
#define __TIME_DEPENDENCY_INIT(sig,dep) \
leader(*sig) \
,dependencies() \
,updateFromAllChildren(ALL_READY_DEFAULT) \
,dependencyType(dep) \
,periodTime(PERIOD_TIME_DEFAULT)
template< class Time >
TimeDependency<Time>::
TimeDependency( SignalBase<Time> *sig
,const DependencyType dep )
:__TIME_DEPENDENCY_INIT(sig,dep)
{}
template< class Time >
TimeDependency<Time>::
TimeDependency( SignalBase<Time> * sig
,const SignalArray_const<Time>& ar
,const DependencyType dep )
:__TIME_DEPENDENCY_INIT(sig,dep)
{
for( unsigned int i=0;i<ar.getSize();++i )
{addDependency( ar[i] ); }
return ;
#define __TIME_DEPENDENCY_INIT(sig, dep) \
leader(*sig), dependencies(), updateFromAllChildren(ALL_READY_DEFAULT), \
dependencyType(dep), periodTime(PERIOD_TIME_DEFAULT)
namespace dynamicgraph {
template <class Time>
TimeDependency<Time>::TimeDependency(SignalBase<Time> *sig,
const DependencyType dep)
: __TIME_DEPENDENCY_INIT(sig, dep) {}
template <class Time>
TimeDependency<Time>::TimeDependency(SignalBase<Time> *sig,
const SignalArray_const<Time> &ar,
const DependencyType dep)
: __TIME_DEPENDENCY_INIT(sig, dep) {
addDependencies(ar);
return;
}
/* ------------------------------------------------------------------------ */
template <class Time>
void TimeDependency<Time>::addDependencies(const SignalArray_const<Time> &ar) {
for (unsigned int i = 0; i < ar.getSize(); ++i) {
addDependency(ar[i]);
}
}
/* -------------------------------------------------------------------------- */
template< class Time >
void TimeDependency<Time>::
addDependency( const SignalBase<Time>& sig )
{
dependencies.push_front(&sig);
template <class Time>
void TimeDependency<Time>::addDependency(const SignalBase<Time> &sig) {
dependencies.push_front(&sig);
}
template< class Time >
void TimeDependency<Time>::
removeDependency( const SignalBase<Time>& sig )
{
dependencies.remove(&sig);
template <class Time>
void TimeDependency<Time>::removeDependency(const SignalBase<Time> &sig) {
dependencies.remove(&sig);
}
template< class Time >
void TimeDependency<Time>::
clearDependency( void )
{
dependencies.clear();
template <class Time>
void TimeDependency<Time>::clearDependency() {
dependencies.clear();
}
template< class Time >
bool TimeDependency<Time>::
needUpdate( const Time& t1 ) const
{
dgTDEBUG(15) << "# In {" << leader.getName() << " : ("<< leader.getReady()<<") "
<< t1 << " >? " << leader.getTime() << std::endl;
if( leader.getReady() ) { dgTDEBUGOUT(15);return true; }
if( lastAskForUpdate ) { dgTDEBUGOUT(15);return true; }
switch( dependencyType )
{
case ALWAYS_READY:
{ dgTDEBUGOUT(15);return true; }
case BOOL_DEPENDENT: break;
case TIME_DEPENDENT:
{
if( t1<leader.getTime()+periodTime )
{ dgTDEBUGOUT(15);return false; }
break;
template <class Time>
bool TimeDependency<Time>::needUpdate(const Time &t1) const {
dgTDEBUG(15) << "# In {" << leader.getName() << " : (" << leader.getReady()
<< ") " << t1 << " >? " << leader.getTime() << std::endl;
if (leader.getReady()) {
dgTDEBUGOUT(15);
return true;
}
if (lastAskForUpdate) {
dgTDEBUGOUT(15);
return true;
}
switch (dependencyType) {
case ALWAYS_READY: {
dgTDEBUGOUT(15);
return true;
}
case BOOL_DEPENDENT:
break;
case TIME_DEPENDENT: {
if (t1 < leader.getTime() + periodTime) {
dgTDEBUGOUT(15);
return false;
}
};
break;
}
};
bool res = updateFromAllChildren;
const typename Dependencies::const_iterator itend=dependencies.end();
for( typename Dependencies::const_iterator it=dependencies.begin();it!=itend;++it )
{
const SignalBase<Time> &sig = **it;
dgTDEBUG(15)<< "Ask update for "<< sig <<std::endl;
if( (sig.getTime()>leader.getTime()) || (sig.needUpdate(t1)) )
{ if(updateFromAllChildren) continue; else {res=true; break;} }
else { if(updateFromAllChildren) {res=false; break;} else continue; }
const typename Dependencies::const_iterator itend = dependencies.end();
for (typename Dependencies::const_iterator it = dependencies.begin();
it != itend; ++it) {
const SignalBase<Time> &sig = **it;
dgTDEBUG(15) << "Ask update for " << sig << std::endl;
if ((sig.getTime() > leader.getTime()) || (sig.needUpdate(t1))) {
if (updateFromAllChildren)
continue;
else {
res = true;
break;
}
} else {
if (updateFromAllChildren) {
res = false;
break;
} else
continue;
}
}
lastAskForUpdate = res;
dgTDEBUGOUT(15);
return res;
}
template< class Time >
std::ostream& TimeDependency<Time>::
writeGraph( std::ostream & os) const
{
std::string LeaderLocalName;
std::string LeaderNodeName;
leader.ExtractNodeAndLocalNames(LeaderLocalName,LeaderNodeName);
if (dependencies.size()!=0)
{
const typename Dependencies::const_iterator itend=dependencies.end();
for( typename Dependencies::const_iterator it=dependencies.begin();it!=itend;++it )
{
std::string itLocalName,itNodeName;
(*it)->ExtractNodeAndLocalNames(itLocalName,itNodeName);
os << "\"" << itNodeName << "\" -> \"" << LeaderNodeName << "\"" << std::endl
<< " [ headlabel = \"" << LeaderLocalName << "\" , taillabel = \"" << itLocalName << "\" ]" << std::endl;
}
}
template <class Time>
std::ostream &TimeDependency<Time>::writeGraph(std::ostream &os) const {
return os;
}
template< class Time >
std::ostream& TimeDependency<Time>::
displayDependencies( std::ostream& os,const int depth,
std::string space,
std::string next1,std::string next2 ) const
{
leader.SignalBase<Time>::displayDependencies(os,depth,space,next1,next2)<<" (";
switch( dependencyType )
{
case ALWAYS_READY: os<<"A"; break;
case BOOL_DEPENDENT: os << "ready=" << ((leader.getReady())?"TRUE":"FALSE"); break;
case TIME_DEPENDENT:
os <<"t="<<leader.getTime() <<" (/"<<periodTime<<") " ;
template <class Time>
std::ostream &TimeDependency<Time>::displayDependencies(
std::ostream &os, const int depth, std::string space, std::string next1,
std::string next2) const {
leader.SignalBase<Time>::displayDependencies(os, depth, space, next1, next2)
<< " (";
switch (dependencyType) {
case ALWAYS_READY:
os << "A";
break;
};
os<<")"; //<<std::endl;
{
const typename Dependencies::const_iterator itend=dependencies.end();
for( typename Dependencies::const_iterator it=dependencies.begin();it!=itend;++it )
if( depth!=0 )
{
os<<std::endl;
std::string ajout = "|";
std::string ajout2 = "|";
typename Dependencies::const_iterator it2=it; it2++;
if( it2==dependencies.end() ) { ajout = "`"; ajout2= " "; }
(*it)->displayDependencies( os,depth-1,space+next2+" ",ajout,ajout2 );
}
else
{ os<<std::endl<<space<<" `-- ..."; break; }
}
case BOOL_DEPENDENT:
os << "ready=" << ((leader.getReady()) ? "TRUE" : "FALSE");
break;
case TIME_DEPENDENT:
os << "t=" << leader.getTime() << " (/" << periodTime << ") ";
break;
};
os << ")"; //<<std::endl;
{
const typename Dependencies::const_iterator itend = dependencies.end();
for (typename Dependencies::const_iterator it = dependencies.begin();
it != itend; ++it)
if (depth != 0) {
os << std::endl;
std::string ajout = "|";
std::string ajout2 = "|";
typename Dependencies::const_iterator it2 = it;
++it2;
if (it2 == dependencies.end()) {
ajout = "`";
ajout2 = " ";
}
(*it)->displayDependencies(os, depth - 1, space + next2 + " ", ajout,
ajout2);
} else {
os << std::endl << space << " `-- ...";
break;
}
}
return os;
}
} // namespace dynamicgraph
#endif /* #ifndef __TIME_DEPENDENCY_TCPP */
} // end of namespace dynamicgraph
#undef __TIME_DEPENDENCY_INIT
#endif //! DYNAMIC_GRAPH_TIME_DEPENDENCY_T_CPP
/*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
* Copyright Projet JRL-Japan, 2007
*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
*
* File: Tracer.h
* Project: DG
* Author: Nicolas Mansard
*
* Version control
* ===============
*
* $Id$
*
* Description
* ============
*
*
* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
#ifndef __TRACER_RT_H__
#define __TRACER_RT_H__
/* --------------------------------------------------------------------- */
/* --- INCLUDE --------------------------------------------------------- */
/* --------------------------------------------------------------------- */
/* STD */
#include <sstream>
// -*- mode: c++ -*-
// Copyright 2010, François Bleibel, Thomas Moulard, Olivier Stasse,
// JRL, CNRS/AIST.
//
/* DG */
#ifndef DYNAMIC_GRAPH_TRACER_REAL_TIME_H
#define DYNAMIC_GRAPH_TRACER_REAL_TIME_H
#include <dynamic-graph/tracer.h>
/* --------------------------------------------------------------------- */
/* --- API ------------------------------------------------------------- */
/* --------------------------------------------------------------------- */
#if defined (WIN32)
# if defined (tracer_real_time_EXPORTS)
# define DGTRACERREALTIME_EXPORT __declspec(dllexport)
# else
# define DGTRACERREALTIME_EXPORT __declspec(dllimport)
# endif
#else
# define DGTRACERREALTIME_EXPORT
#endif
/* --------------------------------------------------------------------- */
/* --- TRACER ---------------------------------------------------------- */
/* --------------------------------------------------------------------- */
#include <dynamic-graph/config-tracer-real-time.hh>
#include <dynamic-graph/fwd.hh>
#include <sstream>
namespace dynamicgraph {
class DGTRACERREALTIME_EXPORT OutStringStream
: public std::ostringstream
{
public:
char * buffer;
unsigned int index;
unsigned int bufferSize;
/// \ingroup plugin
///
/// \brief Stream for the tracer real-time.
class DG_TRACERREALTIME_DLLAPI OutStringStream : public std::ostringstream {
public:
char *buffer;
std::streamsize index;
std::streamsize bufferSize;
bool full;
std::string givenname;
public:
OutStringStream( void );
~OutStringStream( void );
public:
OutStringStream();
~OutStringStream();
void resize( const unsigned int & size );
bool addData( const char * data, const unsigned int & size );
void dump( std::ostream& os );
void empty( void );
void resize(const std::streamsize &size);
bool addData(const char *data, const std::streamoff &size);
void dump(std::ostream &os);
void empty();
};
class DGTRACERREALTIME_EXPORT TracerRealTime
: public Tracer
{
public:
static const std::string CLASS_NAME;
virtual const std::string& getClassName( void ) { return CLASS_NAME; }
protected:
int bufferSize;
static const int BUFFER_SIZE_DEFAULT = 1048576; // 1Mo
typedef std::list< std::ofstream* > HardFileList;
HardFileList hardFiles;
public:
TracerRealTime( const std::string n );
virtual ~TracerRealTime( void ){ }
/// \ingroup plugin
///
/// \brief Main class of the tracer real-time plug-in.
class DG_TRACERREALTIME_DLLAPI TracerRealTime : public Tracer {
DYNAMIC_GRAPH_ENTITY_DECL();
public:
virtual void closeFiles( void );
virtual void trace( void );
protected:
virtual void openFile( const SignalBase<int> & sig,
const std::string& filename );
virtual void recordSignal( std::ostream& os,
const SignalBase<int>& sig );
void emptyBuffers( void );
TracerRealTime(const std::string &n);
virtual ~TracerRealTime() {}
public:
void setBufferSize( const int & SIZE ) { bufferSize=SIZE; }
const int & getBufferSize( void ) { return bufferSize; }
virtual void closeFiles();
virtual void trace();
public:
void display(std::ostream &os) const;
DG_TRACERREALTIME_DLLAPI friend std::ostream &operator<<(
std::ostream &os, const TracerRealTime &t);
/* --- DISPLAY ------------------------------------------------------------ */
void display( std::ostream& os ) const;
DGTRACERREALTIME_EXPORT friend std::ostream& operator<< ( std::ostream& os,const TracerRealTime& t );
void emptyBuffers();
/* --- PARAMS --- */
virtual void commandLine( const std::string& cmdLine
,std::istringstream& cmdArgs
,std::ostream& os );
};
void setBufferSize(const int &SIZE) { bufferSize = SIZE; }
const int &getBufferSize() { return bufferSize; }
} // namespace dynamicgraph
protected:
virtual void openFile(const SignalBase<int> &sig,
const std::string &filename);
virtual void recordSignal(std::ostream &os, const SignalBase<int> &sig);
#endif /* #ifndef __TRACER_RT_H__ */
typedef std::list<std::ofstream *> HardFileList;
static const int BUFFER_SIZE_DEFAULT = 1048576; // 1Mo
int bufferSize;
HardFileList hardFiles;
};
} // end of namespace dynamicgraph
#endif //! DYNAMIC_GRAPH_TRACER_REAL_TIME_H
/*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
* Copyright Projet JRL-Japan, 2007
*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
*
* File: Tracer.h
* Project: DG
* Author: Nicolas Mansard
*
* Version control
* ===============
*
* $Id$
*
* Description
* ============
*
*
* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
#ifndef __TRACER_H__
#define __TRACER_H__
/* --------------------------------------------------------------------- */
/* --- INCLUDE --------------------------------------------------------- */
/* --------------------------------------------------------------------- */
/* STD */
#include <string>
#include <list>
#include <boost/function.hpp>
// -*- mode: c++ -*-
// Copyright 2010, François Bleibel, Thomas Moulard, Olivier Stasse,
// JRL, CNRS/AIST.
//
/* DG */
#ifndef DYNAMIC_GRAPH_TRACER_H
#define DYNAMIC_GRAPH_TRACER_H
#include <dynamic-graph/entity.h>
#include <dynamic-graph/exception-traces.h>
#include <dynamic-graph/signal-base.h>
#include <dynamic-graph/signal-time-dependent.h>
#include <dynamic-graph/time-dependency.h>
#include <dynamic-graph/entity.h>
#include <dynamic-graph/exception-traces.h>
/* --------------------------------------------------------------------- */
/* --- API ------------------------------------------------------------- */
/* --------------------------------------------------------------------- */
#if defined (WIN32)
# if defined (tracer_EXPORTS)
# define DGTRACER_EXPORT __declspec(dllexport)
# else
# define DGTRACER_EXPORT __declspec(dllimport)
# endif
#else
# define DGTRACER_EXPORT
#endif
/* --------------------------------------------------------------------- */
/* --- TRACER ---------------------------------------------------------- */
/* --------------------------------------------------------------------- */
#include <boost/function.hpp>
#include <dynamic-graph/config-tracer.hh>
#include <list>
#include <mutex>
#include <string>
namespace dynamicgraph {
/// \ingroup plugin
///
/// \brief Tracer plug-in main class.
class DG_TRACER_DLLAPI Tracer : public Entity {
DYNAMIC_GRAPH_ENTITY_DECL();
class DGTRACER_EXPORT Tracer
: public Entity
{
protected:
typedef std::list< const SignalBase<int>* > SignalList;
typedef std::list<const SignalBase<int> *> SignalList;
SignalList toTraceSignals;
std::mutex files_mtx;
public:
static const std::string CLASS_NAME;
virtual const std::string& getClassName( void ) { return CLASS_NAME; }
public:
enum TraceStyle
{
WHEN_SAID /// Record, then trace to file only when said to.
,EACH_TIME /// Record and trace to file immediately.
,FREQUENTLY /// Record X time then trace (X is tuned by setFrenquence() ).
};
public:
enum TraceStyle {
WHEN_SAID
/// Record, then trace to file only when said to.
,
EACH_TIME
/// Record and trace to file immediately.
,
FREQUENTLY
/// Record X time then trace (X is tuned by setFrenquence () ).
};
TraceStyle traceStyle;
static const TraceStyle TRACE_STYLE_DEFAULT = EACH_TIME;
double frequency;
......@@ -85,61 +48,58 @@ class DGTRACER_EXPORT Tracer
std::string suffix;
std::string rootdir;
bool namesSet;
typedef std::list< std::ostream* > FileList;
typedef std::list<std::ostream *> FileList;
FileList files;
typedef std::list< std::string > NameList;
typedef std::list<std::string> NameList;
NameList names;
bool play;
int timeStart;
public:
Tracer( const std::string n );
virtual ~Tracer( void ){ closeFiles(); }
void addSignalToTrace( const SignalBase<int>& sig,
const std::string& filename="" );
void clearSignalToTrace( void );
//void parasite( SignalBase<int>& sig );
void openFiles( const std::string& rootdir, const std::string& basename,
const std::string& suffix );
virtual void closeFiles( void );
Tracer(const std::string n);
virtual ~Tracer() { closeFiles(); }
void addSignalToTrace(const SignalBase<int> &sig,
const std::string &filename = "");
void addSignalToTraceByName(const std::string &signame,
const std::string &filename = "");
void clearSignalToTrace();
// void parasite( SignalBase<int>& sig );
void openFiles(const std::string &rootdir, const std::string &basename,
const std::string &suffix);
virtual void closeFiles();
protected:
virtual void openFile( const SignalBase<int> & sig,
const std::string& filename );
virtual void openFile(const SignalBase<int> &sig,
const std::string &filename);
public:
void setTraceStyle( const TraceStyle& style ){ traceStyle = style; }
TraceStyle getTraceStyle( void ){ return traceStyle; }
void setFrenquency( const double& frqu ){ frequency = frqu; }
double getFrequency( void ){ return frequency; }
void setTraceStyle(const TraceStyle &style) { traceStyle = style; }
TraceStyle getTraceStyle() { return traceStyle; }
void record( void );
virtual void recordSignal( std::ostream& os,
const SignalBase<int>& sig );
int& recordTrigger( int& dummy, const int& time );
void setFrenquency(const double &frqu) { frequency = frqu; }
double getFrequency() { return frequency; }
virtual void trace( void );
void record();
virtual void recordSignal(std::ostream &os, const SignalBase<int> &sig);
int &recordTrigger(int &dummy, const int &time);
virtual void trace();
void start() { play = true; }
void stop() { play = false; }
public:
//SignalTrigerer<int> triger;
SignalTimeDependent<int,int> triger;
// SignalTrigerer<int> triger;
SignalTimeDependent<int, int> triger;
/* --- DISPLAY ------------------------------------------------------------ */
DGTRACER_EXPORT friend std::ostream& operator<< ( std::ostream& os,const Tracer& t );
/* --- DISPLAY --------------------------------------------------------- */
DG_TRACER_DLLAPI friend std::ostream &operator<<(std::ostream &os,
const Tracer &t);
/* --- PARAMS --- */
void display( std::ostream& os ) const;
virtual void commandLine( const std::string& cmdLine
,std::istringstream& cmdArgs
,std::ostream& os );
void display(std::ostream &os) const;
};
} // end of namespace dynamicgraph
} // namespace dynamicgraph
#endif /* #ifndef __TRACER_H__ */
#endif //! DYNAMIC_GRAPH_TRACER_H
//
// Copyright 2010 CNRS
//
// Author: Florent Lamiraux
//
#ifndef DYNAMIC_GRAPH_VALUE_H
#define DYNAMIC_GRAPH_VALUE_H
#include <dynamic-graph/linear-algebra.h>
#include <cassert>
#include <string>
#include <typeinfo>
#include <vector>
#include "dynamic-graph/dynamic-graph-api.h"
namespace dynamicgraph {
namespace command {
class Value;
typedef std::vector<Value> Values;
class DYNAMIC_GRAPH_DLLAPI EitherType {
public:
EitherType(const Value &value);
~EitherType();
operator bool() const;
operator unsigned() const;
operator unsigned long int() const;
operator int() const;
operator long int() const;
operator float() const;
operator double() const;
operator std::string() const;
operator Vector() const;
operator Eigen::MatrixXd() const;
operator Eigen::Matrix4d() const;
operator Values() const;
private:
const Value *value_;
};
/** \ingroup dgraph
\brief This class implements a variant design pattern to handle basic types
in Command.
*/
class DYNAMIC_GRAPH_DLLAPI Value {
public:
enum Type {
NONE,
BOOL,
UNSIGNED,
UNSIGNEDLONGINT,
INT,
LONGINT,
FLOAT,
DOUBLE,
STRING,
VECTOR,
MATRIX,
MATRIX4D,
VALUES,
NB_TYPES
};
~Value();
void deleteValue();
explicit Value(const bool &value);
explicit Value(const unsigned &value);
explicit Value(const unsigned long int &value);
explicit Value(const int &value);
explicit Value(const long int &value);
explicit Value(const float &value);
explicit Value(const double &value);
explicit Value(const std::string &value);
explicit Value(const Vector &value);
explicit Value(const Eigen::MatrixXd &value);
explicit Value(const Eigen::Matrix4d &value);
explicit Value(const Values &value);
/// Copy constructor
Value(const Value &value);
// Construct an empty value (None)
explicit Value();
// operator assignement
Value operator=(const Value &value);
// Equality operator
bool operator==(const Value &other) const;
/// Return the type of the value
Type type() const;
/// Return the value as a castable value into the approriate type
///
/// For instance,
/// \code
/// Value v1(5.0); // v1 is of type double
/// Value v2(3); // v2 is of type int
/// double x1 = v1.value();
/// double x2 = v2.value();
/// \endcode
/// The first assignment will succeed, while the second one will throw
/// an exception.
const EitherType value() const;
/// Return the name of the type
static std::string typeName(Type type);
/// Output in a stream
DYNAMIC_GRAPH_DLLAPI friend std::ostream &operator<<(std::ostream &os,
const Value &value);
public:
friend class EitherType;
bool boolValue() const;
unsigned unsignedValue() const;
unsigned long int unsignedlongintValue() const;
int intValue() const;
long int longintValue() const;
float floatValue() const;
double doubleValue() const;
std::string stringValue() const;
Vector vectorValue() const;
Eigen::MatrixXd matrixXdValue() const;
Eigen::Matrix4d matrix4dValue() const;
Values valuesValue() const;
const Values &constValuesValue() const;
Type type_;
const void *const value_;
};
/* ---- HELPER ---------------------------------------------------------- */
// Note: to ensure the WIN32 compatibility, it is necessary to export
// the template specialization. Also, it is forbidden to do the template
// specialization declaration in the header file, for the same reason.
template <typename T>
struct DYNAMIC_GRAPH_DLLAPI ValueHelper {
static const Value::Type TypeID;
};
} // namespace command
} // namespace dynamicgraph
#endif // DYNAMIC_GRAPH_VALUE_H
<html>
<body>
<script src="https://github.com/mdaines/viz.js/releases/download/v2.1.2/viz.js"></script>
<script src="https://github.com/mdaines/viz.js/releases/download/v2.1.2/full.render.js"></script>
<script>
function renderDOTFile() {
var fileInputElement = document.getElementById("fileInputElement");
var reader = new FileReader();
var graphtextres = ""
reader.onloadend = function(e) {
graphtextres = e.target.result
var viz = new Viz();
viz.renderSVGElement(graphtextres)
.then(function(element) {
elementToRemove=document.getElementById("displaysvgzone")
if (elementToRemove != null)
{
document.body.removeChild(elementToRemove)
}
document.body.appendChild(element)
element.id="displaysvgzone"
})
.catch(error => {
// Create a new Viz instance (@see Caveats page for more info)
viz = new Viz();
// Possibly display the error
console.error(error);
});
}
reader.readAsText(fileInputElement.files[0]);
};
</script>
<input type="file" id="fileInputElement">
<input id="Rendering" type="button" value="Rendering" onclick="renderDOTFile();" />
<script>
var el = document.getElementById("Rendering");
if (el.addEventListener)
el.addEventListener("click", renderDOTFile, false);
else if (el.attachEvent)
el.attachEvent('onclick', renderDOTFile);
</script>
</body>
</html>
<?xml version="1.0"?>
<package format="3">
<name>dynamic-graph</name>
<version>4.4.3</version>
<description>
Dynamic graph library
</description>
<maintainer email="guilhem.saurel@laas.fr">Guilhem saurel</maintainer>
<license>BSD</license>
<url>http://github.com/stack-of-tasks/dynamic-graph</url>
<author>Nicolas Mansard</author>
<author>Olivier Stasse</author>
<build_depend>git</build_depend>
<build_depend>doxygen</build_depend>
<!-- The following tags are recommended by REP-136 -->
<exec_depend condition="$ROS_VERSION == 1">catkin</exec_depend>
<exec_depend condition="$ROS_VERSION == 2">ament_cmake</exec_depend>
<depend>eigen</depend>
<depend>boost</depend>
<depend>graphviz</depend>
<buildtool_depend>cmake</buildtool_depend>
<export>
<build_type>cmake</build_type>
</export>
</package>
####################################
### Main Library
####################################
SET(LIBRARY_NAME ${PROJECT_NAME})
set(CMAKE_BUILD_WITH_INSTALL_RPATH TRUE)
INCLUDE_DIRECTORIES(
${CMAKE_CURRENT_SOURCE_DIR}/../include
)
set(plugins traces/tracer traces/tracer-real-time)
# Verbosity level
set(tracer-real-time_deps tracer)
IF (NOT (\"${CMAKE_VERBOSITY_LEVEL}\" STREQUAL \"\"))
ADD_DEFINITIONS(-DVP_DEBUG_MODE=${CMAKE_VERBOSITY_LEVEL} -DVP_DEBUG)
ENDIF (NOT (\"${CMAKE_VERBOSITY_LEVEL}\" STREQUAL \"\"))
foreach(plugin ${plugins})
get_filename_component(LIBRARY_NAME ${plugin} NAME)
add_library(${LIBRARY_NAME} SHARED "${plugin}.cpp")
ADD_LIBRARY(${LIBRARY_NAME}
SHARED
debug/debug.cpp
if(SUFFIX_SO_VERSION)
set_target_properties(${LIBRARY_NAME} PROPERTIES SOVERSION
${PROJECT_VERSION})
endif(SUFFIX_SO_VERSION)
set_target_properties(${LIBRARY_NAME} PROPERTIES INSTALL_RPATH $ORIGIN)
dgraph/entity.cpp
dgraph/factory.cpp
dgraph/interpreter.cpp
dgraph/interpreter-helper.cpp
dgraph/plugin-loader.cpp
dgraph/pool.cpp
target_link_libraries(${LIBRARY_NAME} PUBLIC ${PROJECT_NAME}
${${LIBRARY_NAME}_deps})
exception/exception-abstract.cpp
exception/exception-factory.cpp
exception/exception-signal.cpp
exception/exception-traces.cpp
shell/functions.cpp
signal/signal-array.cpp
signal/signal-caster.cpp
)
SET_TARGET_PROPERTIES(${LIBRARY_NAME}
PROPERTIES
SOVERSION ${PROJECT_VERSION}
INSTALL_RPATH ${CMAKE_INSTALL_PREFIX}/lib)
SET_TARGET_PROPERTIES(${LIBRARY_NAME}
PROPERTIES
LINK_FLAGS "${${PROJECT_NAME}_src_LDFLAGS}"
)
IF (UNIX)
TARGET_LINK_LIBRARIES(${LIBRARY_NAME} dl pthread)
ENDIF (UNIX)
TARGET_LINK_LIBRARIES(${LIBRARY_NAME} ${Boost_LIBRARIES})
INSTALL(TARGETS ${LIBRARY_NAME}
DESTINATION lib)
####################################
### Plugins
####################################
SET(plugins_list
plugins/shell-procedure
plugins/shell-functions
debug/contiifstream
traces/tracer
traces/tracer-real-time
)
SET(tracer-real-time_dependancy tracer)
FOREACH(plugin_file ${plugins_list})
GET_FILENAME_COMPONENT(plugin ${plugin_file} NAME)
ADD_LIBRARY(${plugin}
SHARED
"${plugin_file}.cpp")
TARGET_LINK_LIBRARIES(${plugin}
${PROJECT_NAME} ${${plugin}_dependancy}
${Boost_LIBRARIES})
SET_TARGET_PROPERTIES(${plugin}
PROPERTIES
COMPILE_FLAGS "${${PROJECT_NAME}_CXXFLAGS}"
PREFIX ""
LIBRARY_OUTPUT_DIRECTORY "${${PROJECT_NAME}_BINARY_DIR}/lib/plugin")
INSTALL(TARGETS ${plugin}
DESTINATION lib/plugin)
ENDFOREACH(plugin_file)
\ No newline at end of file
install(
TARGETS ${LIBRARY_NAME}
EXPORT ${TARGETS_EXPORT_NAME}
DESTINATION ${DYNAMIC_GRAPH_PLUGINDIR})
endforeach(plugin)
//
// Copyright 2010 CNRS
//
// Author: Florent Lamiraux
//
#include "dynamic-graph/command.h"
#include <sstream>
#include "dynamic-graph/exception-abstract.h"
namespace dynamicgraph {
namespace command {
const std::vector<Value::Type> Command::EMPTY_ARG = std::vector<Value::Type>();
Command::~Command() {}
Command::Command(Entity &entity, const std::vector<Value::Type> &valueTypes,
const std::string &docstring)
: owner_(entity), valueTypeVector_(valueTypes), docstring_(docstring) {}
const std::vector<Value::Type> &Command::valueTypes() const {
return valueTypeVector_;
}
void Command::setParameterValues(const std::vector<Value> &values) {
const std::vector<Value::Type> &paramTypes = valueTypes();
// Check that number of parameters is correct
if (values.size() != paramTypes.size()) {
throw ExceptionAbstract(ExceptionAbstract::ABSTRACT,
"wrong number of parameters");
}
// Check that each parameter is of correct type
for (unsigned int iParam = 0; iParam < values.size(); iParam++) {
if (values[iParam].type() != paramTypes[iParam]) {
std::stringstream ss;
ss << "argument " << iParam
<< " is of wrong type: " << Value::typeName(paramTypes[iParam])
<< " expected, got " << Value::typeName(values[iParam].type());
throw ExceptionAbstract(ExceptionAbstract::TOOLS, ss.str());
}
}
// Copy vector of values in private part
valueVector_ = values;
}
const std::vector<Value> &Command::getParameterValues() const {
return valueVector_;
}
Value Command::execute() { return doExecute(); }
Entity &Command::owner() { return owner_; }
std::string Command::getDocstring() const { return docstring_; }
} // namespace command
} // namespace dynamicgraph
//
// Copyright 2010 CNRS
//
// Author: Florent Lamiraux
//
#include "dynamic-graph/value.h"
#include "dynamic-graph/exception-abstract.h"
namespace dynamicgraph {
namespace command {
static void *copyValue(const Value &value);
EitherType::EitherType(const Value &value) : value_(new Value(value)) {}
EitherType::~EitherType() {
delete value_;
value_ = NULL;
}
EitherType::operator bool() const { return value_->boolValue(); }
EitherType::operator unsigned() const { return value_->unsignedValue(); }
EitherType::operator unsigned long int() const {
return value_->unsignedlongintValue();
}
EitherType::operator int() const { return value_->intValue(); }
EitherType::operator long int() const { return value_->longintValue(); }
EitherType::operator float() const { return value_->floatValue(); }
EitherType::operator double() const { return value_->doubleValue(); }
EitherType::operator std::string() const { return value_->stringValue(); }
EitherType::operator Vector() const { return value_->vectorValue(); }
EitherType::operator Eigen::MatrixXd() const { return value_->matrixXdValue(); }
EitherType::operator Eigen::Matrix4d() const { return value_->matrix4dValue(); }
EitherType::operator Values() const { return value_->valuesValue(); }
void Value::deleteValue() {
switch (type_) {
case BOOL:
delete (const bool *)value_;
break;
case UNSIGNED:
delete (const unsigned *)value_;
break;
case UNSIGNEDLONGINT:
delete (const unsigned long int *)value_;
break;
case INT:
delete (const int *)value_;
break;
case LONGINT:
delete (const long int *)value_;
break;
case FLOAT:
delete (const float *)value_;
break;
case DOUBLE:
delete (const double *)value_;
break;
case STRING:
delete (const std::string *)value_;
break;
case VECTOR:
delete (const Vector *)value_;
break;
case MATRIX:
delete (const Eigen::MatrixXd *)value_;
break;
case MATRIX4D:
delete (const Eigen::Matrix4d *)value_;
break;
case VALUES:
delete (const Values *)value_;
break;
case NONE: /* Equivalent to void */
break;
default:
throw "Value::deleteValue : Undefined type";
;
}
}
Value::~Value() { deleteValue(); }
Value::Value(const bool &value) : type_(BOOL), value_(new bool(value)) {}
Value::Value(const unsigned &value)
: type_(UNSIGNED), value_(new unsigned(value)) {}
Value::Value(const unsigned long int &value)
: type_(UNSIGNEDLONGINT), value_(new unsigned long int(value)) {}
Value::Value(const int &value) : type_(INT), value_(new int(value)) {}
Value::Value(const float &value) : type_(FLOAT), value_(new float(value)) {}
Value::Value(const double &value) : type_(DOUBLE), value_(new double(value)) {}
Value::Value(const std::string &value)
: type_(STRING), value_(new std::string(value)) {}
Value::Value(const Vector &value) : type_(VECTOR), value_(new Vector(value)) {}
Value::Value(const Eigen::MatrixXd &value)
: type_(MATRIX), value_(new Eigen::MatrixXd(value)) {}
Value::Value(const Eigen::Matrix4d &value)
: type_(MATRIX4D), value_(new Eigen::Matrix4d(value)) {}
Value::Value(const Values &value) : type_(VALUES), value_(new Values(value)) {}
Value::Value(const Value &value)
: type_(value.type_), value_(copyValue(value)) {}
void *copyValue(const Value &value) {
void *copy;
switch (value.type()) {
case Value::NONE:
copy = NULL;
break;
case Value::BOOL:
copy = new bool(value.boolValue());
break;
case Value::UNSIGNED:
copy = new unsigned(value.unsignedValue());
break;
case Value::UNSIGNEDLONGINT:
copy = new unsigned long int(value.unsignedlongintValue());
break;
case Value::INT:
copy = new int(value.intValue());
break;
case Value::LONGINT:
copy = new long int(value.longintValue());
break;
case Value::FLOAT:
copy = new float(value.floatValue());
break;
case Value::DOUBLE:
copy = new double(value.doubleValue());
break;
case Value::STRING:
copy = new std::string(value.stringValue());
break;
case Value::VECTOR:
copy = new Vector(value.vectorValue());
break;
case Value::MATRIX:
copy = new Eigen::MatrixXd(value.matrixXdValue());
break;
case Value::MATRIX4D:
copy = new Eigen::Matrix4d(value.matrix4dValue());
break;
case Value::VALUES:
copy = new Values(value.valuesValue());
break;
default:
abort();
}
return copy;
}
Value::Value() : type_(NONE), value_(NULL) {}
Value Value::operator=(const Value &value) {
if (&value != this) {
if (value_ != 0x0) deleteValue();
type_ = value.type_;
void **ptValue = const_cast<void **>(&value_);
*ptValue = copyValue(value);
}
return *this;
}
bool Value::operator==(const Value &other) const {
if (type_ != other.type_) return false;
switch (type_) {
case Value::BOOL:
return boolValue() == other.boolValue();
case Value::UNSIGNED:
return unsignedValue() == other.unsignedValue();
case Value::UNSIGNEDLONGINT:
return unsignedlongintValue() == other.unsignedlongintValue();
case Value::INT:
return intValue() == other.intValue();
case Value::DOUBLE:
return doubleValue() == other.doubleValue();
case Value::FLOAT:
return floatValue() == other.floatValue();
case Value::STRING:
return stringValue() == other.stringValue();
case Value::VECTOR:
return vectorValue() == other.vectorValue();
case Value::MATRIX:
return matrixXdValue() == other.matrixXdValue();
case Value::MATRIX4D:
return matrix4dValue() == other.matrix4dValue();
case Value::VALUES:
return constValuesValue() == other.constValuesValue();
case Value::NONE:
break;
default:
break;
}
return false;
}
const EitherType Value::value() const { return EitherType(*this); }
Value::Type Value::type() const { return type_; }
bool Value::boolValue() const {
if (type_ == BOOL) return *((const bool *)value_);
throw ExceptionAbstract(ExceptionAbstract::TOOLS, "value is not an bool");
}
unsigned Value::unsignedValue() const {
if (type_ == UNSIGNED) return *((const unsigned *)value_);
throw ExceptionAbstract(ExceptionAbstract::TOOLS,
"value is not an unsigned int");
}
unsigned long int Value::unsignedlongintValue() const {
if (type_ == UNSIGNEDLONGINT) return *((const unsigned long int *)value_);
throw ExceptionAbstract(ExceptionAbstract::TOOLS,
"value is not an unsigned long int");
}
long int Value::longintValue() const {
if (type_ == LONGINT) return *((const long int *)value_);
throw ExceptionAbstract(ExceptionAbstract::TOOLS, "value is not an long int");
}
int Value::intValue() const {
if (type_ == INT) return *((const int *)value_);
throw ExceptionAbstract(ExceptionAbstract::TOOLS, "value is not an int");
}
float Value::floatValue() const {
float result;
if (FLOAT != type_)
throw ExceptionAbstract(ExceptionAbstract::TOOLS, "value is not a float");
result = *((const float *)value_);
return result;
}
double Value::doubleValue() const {
double result;
if (DOUBLE != type_)
throw ExceptionAbstract(ExceptionAbstract::TOOLS, "value is not a double");
result = *((const double *)value_);
return result;
}
std::string Value::stringValue() const {
if (type_ == STRING) return *((const std::string *)value_);
throw ExceptionAbstract(ExceptionAbstract::TOOLS, "value is not an string");
}
Vector Value::vectorValue() const {
if (type_ == VECTOR) return *((const Vector *)value_);
throw ExceptionAbstract(ExceptionAbstract::TOOLS, "value is not an vector");
}
Eigen::MatrixXd Value::matrixXdValue() const {
if (type_ == MATRIX) return *((const Eigen::MatrixXd *)value_);
throw ExceptionAbstract(ExceptionAbstract::TOOLS,
"value is not a Eigen matrixXd");
}
Eigen::Matrix4d Value::matrix4dValue() const {
if (type_ == MATRIX4D) return *((const Eigen::Matrix4d *)value_);
throw ExceptionAbstract(ExceptionAbstract::TOOLS,
"value is not a Eigen matrix4d");
}
Values Value::valuesValue() const {
if (type_ == VALUES) return *((const Values *)value_);
throw ExceptionAbstract(ExceptionAbstract::TOOLS,
"value is not a vector of Value");
}
const Values &Value::constValuesValue() const {
if (type_ == VALUES) return *((const Values *)value_);
throw ExceptionAbstract(ExceptionAbstract::TOOLS,
"value is not a vector of Value");
}
std::string Value::typeName(Type type) {
switch (type) {
case BOOL:
return std::string("bool");
case UNSIGNED:
return std::string("unsigned int");
case UNSIGNEDLONGINT:
return std::string("unsigned long int");
case INT:
return std::string("int");
case FLOAT:
return std::string("float");
case DOUBLE:
return std::string("double");
case STRING:
return std::string("string");
case VECTOR:
return std::string("vector");
case MATRIX:
return std::string("matrixXd");
case MATRIX4D:
return std::string("matrix4d");
case VALUES:
return std::string("values");
default:
return std::string("unknown");
}
}
std::ostream &operator<<(std::ostream &os, const Value &value) {
os << "Type=" << Value::typeName(value.type_) << ", value=";
switch (value.type_) {
case Value::BOOL:
os << value.boolValue();
break;
case Value::UNSIGNED:
os << value.unsignedValue();
break;
case Value::UNSIGNEDLONGINT:
os << value.unsignedlongintValue();
break;
case Value::INT:
os << value.intValue();
break;
case Value::DOUBLE:
os << value.doubleValue();
break;
case Value::FLOAT:
os << value.floatValue();
break;
case Value::STRING:
os << value.stringValue();
break;
case Value::VECTOR:
os << value.vectorValue();
break;
case Value::MATRIX:
os << value.matrixXdValue();
break;
case Value::MATRIX4D:
os << value.matrix4dValue();
break;
case Value::VALUES: {
const std::vector<Value> &vals = value.constValuesValue();
os << "[ ";
for (std::size_t i = 0; i < vals.size(); ++i)
os << "Value(" << vals[i] << "), ";
os << "]";
} break;
default:
return os;
}
return os;
}
template <>
const Value::Type ValueHelper<bool>::TypeID = Value::BOOL;
template <>
const Value::Type ValueHelper<unsigned>::TypeID = Value::UNSIGNED;
template <>
const Value::Type ValueHelper<unsigned long int>::TypeID =
Value::UNSIGNEDLONGINT;
template <>
const Value::Type ValueHelper<int>::TypeID = Value::INT;
template <>
const Value::Type ValueHelper<float>::TypeID = Value::FLOAT;
template <>
const Value::Type ValueHelper<double>::TypeID = Value::DOUBLE;
template <>
const Value::Type ValueHelper<std::string>::TypeID = Value::STRING;
template <>
const Value::Type ValueHelper<Vector>::TypeID = Value::VECTOR;
template <>
const Value::Type ValueHelper<Eigen::MatrixXd>::TypeID = Value::MATRIX;
template <>
const Value::Type ValueHelper<Eigen::Matrix4d>::TypeID = Value::MATRIX4D;
template <>
const Value::Type ValueHelper<Values>::TypeID = Value::VALUES;
} // namespace command
} // namespace dynamicgraph
/*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
* Copyright Projet JRL-Japan, 2007
*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
*
* File: Contiifstream.cpp
* Project: DYNAMIC-GRAPH
* Author: Nicolas Mansard
*
* Version control
* ===============
*
* $Id$
*
* Description
* ============
*
*
* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
#include <dynamic-graph/contiifstream.h>
#include <dynamic-graph/debug.h>
using namespace dynamicgraph;
Contiifstream::
Contiifstream( const std::string& n )
:filename(n),cursor(0),first(true) {}
Contiifstream::
~Contiifstream( void )
{
dgDEBUGINOUT(5);
}
bool Contiifstream::
loop( void )
{
dgDEBUGIN(25);
bool res=false;
std::fstream file( filename.c_str() );
file.seekg(cursor);
file.sync();
while(1)
{
file.get(buffer,BUFFER_SIZE);
if( file.gcount() )
{
res=true;
std::string line(buffer);
if(! first) reader.push_back(line);
cursor=file.tellg(); cursor++;
file.get(*buffer); // get the last char ( = '\n')
dgDEBUG(15) << "line: "<< line<<std::endl;
}
else { break; }
}
first=false;
dgDEBUGOUT(25);
return res;
}
std::string
Contiifstream::next( void )
{
std::string res = *reader.begin();
reader.pop_front();
return res;
}
/*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
* Copyright Projet Lagadic, 2005
*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
/*
* Copyright 2010,
* François Bleibel,
* Olivier Stasse,
*
* File: dgDebug.h
* Project: STack of Tasks
* Author: Nicolas Mansard
* CNRS/AIST
*
* Version control
* ===============
*
* $Id$
*
* Description
* ============
*
* Macro de trace et de debugage
*
* - TRACAGE: TRACE et ERROR_TRACE fonctionnent comme des printf
* avec retour chariot en fin de fonction.
* CERROR et CTRACE fonctionnent comme les flux de sortie
* C++ cout et cerr.
* - DEBUGAGE: DEBUG_TRACE(niv, et DERROR_TRACE(niv, fonctionnent
* comme des printf, n'imprimant que si le niveau de trace 'niv' est
* superieur au mode de debugage VP_DEBUG_MODE.
* CDEBUG(niv) fonctionne comme le flux de sortie C++ cout.
* DEBUG_ENABLE(niv) vaut 1 ssi le niveau de tracage 'niv'
* est superieur au mode de debugage DEBUG_MODE. Il vaut 0 sinon.
* - PROG DEFENSIVE: DEFENSIF(a) vaut a ssi le mode defensif est active,
* et vaut 0 sinon.
*
* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
*/
#include <dynamic-graph/debug.h>
#include <fstream>
#include <ios>
using namespace dynamicgraph;
#ifdef WIN32
const char * DebugTrace::DEBUG_FILENAME_DEFAULT = "c:/tmp/dynamic-graph-traces.txt";
#else /*WIN32*/
const char * DebugTrace::DEBUG_FILENAME_DEFAULT = "/tmp/dynamic-graph-traces.txt";
#endif /*WIN32*/
const char *DebugTrace::DEBUG_FILENAME_DEFAULT =
"c:/tmp/dynamic-graph-traces.txt";
#else /*WIN32*/
const char *DebugTrace::DEBUG_FILENAME_DEFAULT =
"/tmp/dynamic-graph-traces.txt";
#endif /*WIN32*/
#ifdef VP_DEBUG
#ifdef WIN32
std::ofstream dg_debugfile( "C:/tmp/dynamic-graph-traces.txt", std::ios::trunc&std::ios::out );
#else /*WIN32*/
std::ofstream dg_debugfile( "/tmp/dynamic-graph-traces.txt", std::ios::trunc&std::ios::out );
#endif /*WIN32*/
#ifdef WIN32
std::ofstream dg_debugfile("C:/tmp/dynamic-graph-traces.txt",
std::ios::trunc &std::ios::out);
#else /*WIN32*/
std::ofstream dg_debugfile("/tmp/dynamic-graph-traces.txt",
std::ios::trunc &std::ios::out);
#endif /*WIN32*/
#else
std::ofstream dg_debugfile; //( "/dev/null", std::ios::trunc&std::ios::out );
class dgDebug_init
{
std::ofstream dg_debugfile;
class dgDebug_init {
public:
dgDebug_init( void )
{ dg_debugfile.setstate( std::ios::failbit ) ; /* dg_debugfile.close(); */ }
};
dgDebug_init dgDebug_initialisator;
dgDebug_init() { dg_debugfile.setstate(std::ios::failbit); }
};
dgDebug_init dgDebug_initialisator;
#endif
namespace dynamicgraph {
DebugTrace dgDEBUGFLOW(dg_debugfile);
DebugTrace dgERRORFLOW(dg_debugfile);
}
DebugTrace dgDEBUGFLOW(dg_debugfile);
DebugTrace dgERRORFLOW(dg_debugfile);
} // namespace dynamicgraph
void DebugTrace::openFile( const char * filename )
{
if( dg_debugfile.good()&&dg_debugfile.is_open() ) dg_debugfile.close();
void DebugTrace::openFile(const char *filename) {
if (dg_debugfile.good() && dg_debugfile.is_open()) dg_debugfile.close();
dg_debugfile.clear();
dg_debugfile.open( filename, std::ios::trunc&std::ios::out );
//std::cout << filename << dg_debugfile.good() << dg_debugfile.is_open() << std::endl;
dg_debugfile.open(filename, std::ios::trunc & std::ios::out);
}
void DebugTrace::closeFile( const char * filename )
{
if( dg_debugfile.good()&&dg_debugfile.is_open() ) { dg_debugfile.close(); }
dg_debugfile.setstate( std::ios::failbit ) ;
void DebugTrace::closeFile(const char *) {
if (dg_debugfile.good() && dg_debugfile.is_open()) {
dg_debugfile.close();
}
dg_debugfile.setstate(std::ios::failbit);
}
//DebugTrace dgDebugFLOW(std::cout);
//DebugTrace dgERRORFLOW(std::cerr);
/*
* Copyright 2015, 2019
* LAAS-CNRS
* Andrea Del Prete, François Bailly, Olivier Stasse
*
*/
#ifndef WIN32
#include <sys/time.h>
#else
#include <Windows.h>
#endif
#define ENABLE_RT_LOG
#include <dynamic-graph/logger.h>
#include <dynamic-graph/real-time-logger.h>
#include <stdio.h>
#include <iomanip> // std::setprecision
#include <iostream>
#include <sstream>
namespace dynamicgraph {
Logger::Logger(double timeSample, double streamPrintPeriod)
: m_timeSample(timeSample),
m_streamPrintPeriod(streamPrintPeriod),
m_printCountdown(0.0) {
m_lv = VERBOSITY_ERROR;
}
Logger::~Logger() {}
void Logger::setVerbosity(LoggerVerbosity lv) { m_lv = lv; }
LoggerVerbosity Logger::getVerbosity() { return m_lv; }
void Logger::countdown() {
if (m_printCountdown < 0.0) m_printCountdown = m_streamPrintPeriod;
m_printCountdown -= m_timeSample;
}
void Logger::sendMsg(std::string msg, MsgType type, const std::string &lineId) {
stream(type, lineId) << msg << '\n';
}
void Logger::sendMsg(std::string msg, MsgType type, const std::string &file,
int line) {
std::ostringstream oss;
oss << file << line;
stream(type, oss.str()) << msg << '\n';
}
bool Logger::setTimeSample(double t) {
if (t <= 0.0) return false;
m_timeSample = t;
return true;
}
bool Logger::setStreamPrintPeriod(double s) {
if (s <= 0.0) return false;
m_streamPrintPeriod = s;
return true;
}
double Logger::getTimeSample() { return m_timeSample; }
double Logger::getStreamPrintPeriod() { return m_streamPrintPeriod; }
bool Logger::checkStreamPeriod(const std::string &lineId) {
// insert element with value 0 if it does not exist.
// otherwise, return a counter to the existing one.
std::pair<StreamCounterMap_t::iterator, bool> result =
m_stream_msg_counters.insert(std::make_pair(lineId, 0.));
// if counter is greater than 0 then decrement it and do not print
double &counter = result.first->second;
counter -= m_timeSample;
if (counter > 0.0) {
return false;
} else // otherwise reset counter and print
counter = m_streamPrintPeriod;
return true;
}
} // namespace dynamicgraph
/*
* Copyright 2018,
* Joseph Mirabel
*
* LAAS-CNRS
*
*/
#include <dynamic-graph/real-time-logger.h>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/thread/thread.hpp>
namespace dynamicgraph {
RealTimeLogger::RealTimeLogger(const std::size_t &bufferSize)
: buffer_(bufferSize, NULL),
frontIdx_(0),
backIdx_(0),
oss_(NULL),
nbDiscarded_(0) {
for (std::size_t i = 0; i < buffer_.size(); ++i) buffer_[i] = new Data;
}
RealTimeLogger::~RealTimeLogger() {
// Check that we are not spinning...
for (std::size_t i = 0; i < buffer_.size(); ++i) delete buffer_[i];
}
bool RealTimeLogger::spinOnce() {
if (empty()) return false;
Data *data = buffer_[frontIdx_];
frontIdx_ = (frontIdx_ + 1) % buffer_.size();
std::string str = data->buf.str();
// It is important to pass str.c_str() and not str
// because the str object may contains a '\0' so
// str.size() may be different from strlen(str.c_str())
for (std::size_t i = 0; i < outputs_.size(); ++i)
outputs_[i]->write(str.c_str());
return true;
}
RTLoggerStream RealTimeLogger::front() {
// If no output or if buffer is full, discard message.
if (outputs_.empty() || full()) {
nbDiscarded_++;
return RTLoggerStream(NULL, oss_);
}
bool alone = wmutex.try_lock();
// If someone is writting, discard message.
if (!alone) {
nbDiscarded_++;
return RTLoggerStream(NULL, oss_);
}
Data *data = buffer_[backIdx_];
// backIdx_ = (backIdx_+1) % buffer_.size();
// Reset position of cursor
data->buf.pubseekpos(0);
oss_.rdbuf(&data->buf);
return RTLoggerStream(this, oss_);
}
struct RealTimeLogger::thread {
bool requestShutdown_;
int threadPolicy_;
int threadPriority_;
bool changedThreadParams;
boost::thread t_;
explicit thread(RealTimeLogger *logger)
: requestShutdown_(false),
threadPolicy_(SCHED_OTHER),
threadPriority_(0),
changedThreadParams(true),
t_(&thread::spin, this, logger) {}
// void setThreadPolicy(int policy) {
// threadPolicy_ = policy;
// changedThreadParams = true;
// }
// void setPriority(int priority) {
// threadPriority_ = priority;
// changedThreadParams = true;
// }
// int getThreadPolicy() { return threadPolicy_; }
// int getThreadPriority() { return threadPriority_; }
void changeThreadParams() {
int threadPolicy;
struct sched_param threadParam;
if (pthread_getschedparam(pthread_self(), &threadPolicy, &threadParam) ==
0) {
threadPolicy = threadPolicy_;
threadParam.sched_priority = threadPriority_;
if (threadParam.sched_priority < sched_get_priority_min(threadPolicy))
threadParam.sched_priority = sched_get_priority_min(threadPolicy);
pthread_setschedparam(pthread_self(), threadPolicy, &threadParam);
changedThreadParams = false;
}
}
void spin(RealTimeLogger *logger) {
// Change the thread's scheduler from real-time to normal
// and reduce its priority
while (!requestShutdown_ || !logger->empty()) {
// If the logger did not write anything, it means the buffer is empty.
// Do a pause
if (!logger->spinOnce())
boost::this_thread::sleep(boost::posix_time::milliseconds(1000));
if (changedThreadParams) changeThreadParams();
}
}
};
RealTimeLogger *RealTimeLogger::instance_ = NULL;
RealTimeLogger::thread *RealTimeLogger::thread_ = NULL;
RealTimeLogger &RealTimeLogger::instance() {
if (instance_ == NULL) {
instance_ = new RealTimeLogger(1000);
thread_ = new thread(instance_);
}
return *instance_;
}
void RealTimeLogger::destroy() {
if (instance_ == NULL) return;
thread_->requestShutdown_ = true;
thread_->t_.join();
delete instance_;
delete thread_;
}
} // namespace dynamicgraph
/*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
* Copyright Projet JRL-Japan, 2007
*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
/*
* Copyright 2010,
* François Bleibel,
* Olivier Stasse,
*
* File: entity.cpp
* Project: DYNAMIC-GRAPH
* Author: François Bleibel (from Nicolas Mansard)
* CNRS/AIST
*
* Version control
* ===============
*
* $Id$
*
* Description
* ============
*
*
* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
*/
/*! Local framework includes */
#include <dynamic-graph/command.h>
#include <dynamic-graph/debug.h>
#include <dynamic-graph/entity.h>
#include <dynamic-graph/pool.h>
#include <dynamic-graph/pool.h>
#include <dynamic-graph/debug.h>
/*! System includes */
#include <stdlib.h>
#include <sstream>
#include <sstream>
using namespace std;
using namespace dynamicgraph;
using dynamicgraph::command::Command;
const std::string Entity::CLASS_NAME = "Entity";
void Entity::
entityRegistration( void )
{
//sotPool.entity[name] = this;
g_pool.registerEntity(name,this);
void Entity::entityRegistration() {
PoolStorage::getInstance()->registerEntity(name, this);
}
void Entity::
entityDeregistration( void )
{
g_pool.deregisterEntity(name);
void Entity::entityDeregistration() {
PoolStorage::getInstance()->deregisterEntity(name);
}
Entity::
Entity( const string& name__ )
: name(name__)
{
dgDEBUG(15) << "New entity <"<<name__<<">"<<endl;
if( name.length()==0 )
{
stringstream oss; oss << rand();
name = CLASS_NAME;
name+="::";
name+=oss.str();
}
Entity::Entity(const string &name__) : name(name__) {
dgDEBUG(15) << "New entity <" << name__ << ">" << endl;
if (name.length() == 0) {
stringstream oss;
oss << rand();
// name = this->getClassName();
// Cannot call a virtual function from the constructor
name += "::";
name += oss.str();
}
entityRegistration();
}
Entity::
~Entity( void )
{
Entity::~Entity() {
dgDEBUG(25) << "# In (" << name << " { " << endl;
entityDeregistration();
for (std::map<const std::string, Command *>::iterator it = commandMap.begin();
it != commandMap.end(); ++it) {
delete it->second;
}
dgDEBUGOUT(25);
}
/* -------------------------------------------------------------------------- */
/* --- SIGNALS -------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
void Entity::
signalRegistration( const SignalArray<int>& signals )
{
for( unsigned int i=0;i<signals.getSize();++i )
{
SignalBase<int>& sig = signals[i];
//const string& signame = sig.getName();
istringstream iss( sig.getName() );
const int SIZE = 128;
char buffer[SIZE];
while( iss.good() )
{ iss.getline(buffer,SIZE,':'); }
const string& signame( buffer );
SignalMap::iterator sigkey = signalMap.find(signame);
if( sigkey != signalMap.end() ) // key does exist
{
dgERRORF( "Key %s already exist in the signalMap.",signame.c_str() );
if( sigkey->second!=&sig )
{
throw ExceptionFactory( ExceptionFactory::SIGNAL_CONFLICT,
"Another signal already defined with the same name. ",
"Signame is <%s>.",signame.c_str() );
}
}
else
{
dgDEBUG(10) << "Register signal <"<< signame << "> for entity <"
<< getName() << "> ."<<endl;
signalMap[signame] = &sig;
}
void Entity::signalRegistration(const SignalArray<int> &signals) {
for (unsigned int i = 0; i < signals.getSize(); ++i) {
SignalBase<int> &sig = signals[i];
// const string& signame = sig.getName ();
istringstream iss(sig.getName());
const int SIZE = 128;
char buffer[SIZE];
while (iss.good()) {
iss.getline(buffer, SIZE, ':');
}
}
const string &signame(buffer);
void Entity::
signalDeregistration( const std::string& signame )
{
SignalMap::iterator sigkey = signalMap.find(signame);
if( sigkey == signalMap.end() ) // key does not exist
{
dgERRORF( "Key %s does not exist in the signalMap.",signame.c_str() );
throw ExceptionFactory( ExceptionFactory::UNREFERED_SIGNAL,
"No signal defined with the given name. ",
" (while erasing <%s>).",signame.c_str() );
}
else
SignalMap::iterator sigkey = signalMap.find(signame);
if (sigkey != signalMap.end()) // key does exist
{
dgDEBUG(10) << "Deregister signal <"<< signame << "> for entity <"
<< getName() << "> ."<<endl;
signalMap.erase(signame);
dgERRORF("Key %s already exist in the signalMap.", signame.c_str());
if (sigkey->second != &sig) {
throw ExceptionFactory(
ExceptionFactory::SIGNAL_CONFLICT,
"Another signal already defined with the same name. ",
"Signame is <%s>.", signame.c_str());
}
} else {
dgDEBUG(10) << "Register signal <" << signame << "> for entity <"
<< getName() << "> ." << endl;
signalMap[signame] = &sig;
}
}
}
void Entity::signalDeregistration(const std::string &signame) {
SignalMap::iterator sigkey = signalMap.find(signame);
if (sigkey == signalMap.end()) // key does not exist
{
dgERRORF("Key %s does not exist in the signalMap.", signame.c_str());
throw ExceptionFactory(ExceptionFactory::UNREFERED_SIGNAL,
"No signal defined with the given name. ",
" (while erasing <%s>).", signame.c_str());
} else {
dgDEBUG(10) << "Deregister signal <" << signame << "> for entity <"
<< getName() << "> ." << endl;
signalMap.erase(signame);
}
}
#define __DG_ENTITY_GET_SIGNAL__(ITER_TYPE) \
SignalMap::ITER_TYPE sigkey = signalMap.find(signame); \
if( sigkey == signalMap.end() ) /* key does NOT exist */ \
{ \
throw ExceptionFactory( ExceptionFactory::UNREFERED_SIGNAL,\
"The requested signal is not registered",\
": %s",signame.c_str() );\
}\
return *(sigkey ->second) ;
std::string Entity::getDocString() const {
std::string docString("No header documentation.");
return docString;
}
#define __DG_ENTITY_GET_SIGNAL__(ITER_TYPE) \
SignalMap::ITER_TYPE sigkey = signalMap.find(signame); \
if (sigkey == signalMap.end()) /* key does NOT exist */ \
{ \
throw ExceptionFactory(ExceptionFactory::UNREFERED_SIGNAL, \
"The requested signal is not registered", ": %s", \
signame.c_str()); \
} \
return *(sigkey->second);
bool Entity::hasSignal(const string &signame) const {
return (!(signalMap.find(signame) == signalMap.end()));
}
SignalBase<int>& Entity::
getSignal( const string & signame )
{
SignalBase<int> &Entity::getSignal(const string &signame) {
__DG_ENTITY_GET_SIGNAL__(iterator);
}
const SignalBase<int>& Entity::
getSignal( const string & signame ) const
{
const SignalBase<int> &Entity::getSignal(const string &signame) const {
__DG_ENTITY_GET_SIGNAL__(const_iterator);
}
std::ostream& Entity::
displaySignalList( std::ostream& os ) const
{
os << "--- <" << getName() << "> signal list: "<<endl;
const SignalMap::const_iterator iterend=signalMap.end();
for( SignalMap::const_iterator iter = signalMap.begin();iterend!=iter;++iter )
{
os << " "; if( (++iter)--==iterend ) os << "`"; else os <<"|";
os << "-- <" << *(iter->second) << endl;
}
std::ostream &Entity::displaySignalList(std::ostream &os) const {
os << "--- <" << getName() << "> signal list: " << endl;
const SignalMap::const_iterator iterend = signalMap.end();
for (SignalMap::const_iterator iter = signalMap.begin(); iterend != iter;
++iter) {
os << " ";
if ((++iter)-- == iterend)
os << "`";
else
os << "|";
os << "-- <" << *(iter->second) << endl;
}
return os;
}
std::ostream& Entity::
writeGraph( std::ostream& os ) const
{
const SignalMap::const_iterator iterend=signalMap.end();
for( SignalMap::const_iterator iter = signalMap.begin();iterend!=iter;++iter )
{
(*(iter->second)).writeGraph(os);
}
std::ostream &Entity::writeGraph(std::ostream &os) const {
const SignalMap::const_iterator iterend = signalMap.end();
for (SignalMap::const_iterator iter = signalMap.begin(); iterend != iter;
++iter) {
(*(iter->second)).writeGraph(os);
}
return os;
}
std::ostream& Entity::
writeCompletionList( std::ostream& os ) const
{
const SignalMap::const_iterator iterend=signalMap.end();
for( SignalMap::const_iterator iter = signalMap.begin();iterend!=iter;++iter )
{
os << getName() << "." << (*(iter->second)).shortName() << std::endl;
}
std::ostream &Entity::writeCompletionList(std::ostream &os) const {
const SignalMap::const_iterator iterend = signalMap.end();
for (SignalMap::const_iterator iter = signalMap.begin(); iterend != iter;
++iter) {
os << getName() << "." << (*(iter->second)).shortName() << std::endl;
}
os << getCommandList() << std::endl;
return os;
}
void Entity::
display( std::ostream& os ) const
{
os<<this->getClassName()<<": "<<name;
void Entity::display(std::ostream &os) const {
os << this->getClassName() << ": " << name;
}
std::ostream& dynamicgraph::operator<< (std::ostream& os, const Entity& ent )
{
std::ostream &dynamicgraph::operator<<(std::ostream &os, const Entity &ent) {
ent.display(os);
return os;
}
Entity::SignalMap Entity::getSignalMap() const { return signalMap; }
/* --- PARAMS --------------------------------------------------------------- */
/* --- PARAMS --------------------------------------------------------------- */
/* --- PARAMS --------------------------------------------------------------- */
static std::string Entity_COMMAND_LIST = "print\nsignals\nsignalDep";
const std::string& Entity::
getCommandList( void ) const
{
return Entity_COMMAND_LIST;
const std::string &Entity::getCommandList() const {
return Entity_COMMAND_LIST;
}
void Entity::
commandLine( const std::string& cmdLine,std::istringstream& cmdArgs,std::ostream& os )
{
if( cmdLine == "help" )
{
os << "Entity : " << std::endl
<< " - print\t\t\tWhat d'you think?"<<endl
<< " - signals\t\t\tDisplay the signals list."<<endl
<< " - signalDep <signame> \tDisplay the dependency graph for signal signame."<<endl;
}
else if( cmdLine == "print")
{
os << *this << std::endl;
}
else if( cmdLine == "signals")
{ displaySignalList(os); }
else if( cmdLine == "signalDep")
{
string sig; cmdArgs>>sig;
cmdArgs >> ws; int depth=-1;
if( cmdArgs.good() ) { cmdArgs >> depth; }
getSignal(sig) .displayDependencies( os,depth ); os<<endl;
}
else
{
try{
SignalBase<int> & sig = getSignal( cmdLine );
/// Add a command to Entity
void Entity::addCommand(const std::string &inName, Command *command) {
if (commandMap.count(inName) != 0) {
DG_THROW ExceptionFactory(
ExceptionFactory::OBJECT_CONFLICT,
"Command " + inName + " already registered in Entity.");
}
std::pair<const std::string, Command *> item(inName, command);
commandMap.insert(item);
}
int time; cmdArgs>>ws;
if( cmdArgs.good() )
{cmdArgs >> time;} else {time=0;}
sig.recompute( time );
os << cmdLine << " = "; sig.get( os );
} catch( ExceptionFactory& e ) {
switch( e.getCode() )
{
case ExceptionFactory::UNREFERED_SIGNAL:
DG_THROW ExceptionFactory( ExceptionFactory::UNREFERED_FUNCTION,
"The requested function/signal :","<%s> is "
"not registered.",cmdLine.c_str() );
break;
default:
throw;
}
} catch( ... ) { throw; }
}
/// Return the list of command objects
std::map<const std::string, Command *> Entity::getNewStyleCommandMap() {
return commandMap;
}
Command *Entity::getNewStyleCommand(const std::string &commandName) {
if (commandMap.count(commandName) != 1) {
DG_THROW ExceptionFactory(
ExceptionFactory::UNREFERED_FUNCTION,
"Command <" + commandName + "> is not registered in Entity.");
}
return commandMap[commandName];
}
void Entity::sendMsg(const std::string &msg, MsgType t,
const std::string &lineId) {
logger_.stream(t, lineId) << "[" << name << "]" << msg << '\n';
}
/*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
* Copyright Projet JRL-Japan, 2007
*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
*
* File: factory.cpp
* Project: DYNAMIC-GRAPH
* Author: François Bleibel, Nicolas Mansard
*
* Version control
* ===============
*
* $Id$
*
* Description
* ============
*
*
* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
/* --------------------------------------------------------------------- */
/* --- INCLUDE --------------------------------------------------------- */
/* --------------------------------------------------------------------- */
/* --- DYNAMIC-GRAPH --- */
#include <dynamic-graph/debug.h>
#include <dynamic-graph/factory.h>
// Copyright 2010, François Bleibel, Thomas Moulard, Olivier Stasse,
// JRL, CNRS/AIST.
//
#include "dynamic-graph/factory.h"
#include <boost/foreach.hpp>
#include "dynamic-graph/debug.h"
using namespace std;
using namespace dynamicgraph;
/* --------------------------------------------------------------------- */
/* --- CLASS ----------------------------------------------------------- */
/* --------------------------------------------------------------------- */
namespace dynamicgraph {
FactoryStorage *FactoryStorage::getInstance() {
if (instance_ == 0) {
instance_ = new FactoryStorage;
}
return instance_;
}
FactoryStorage::
~FactoryStorage( void )
{
dgDEBUGINOUT(25);
void FactoryStorage::destroy() {
delete instance_;
instance_ = NULL;
}
FactoryStorage::FactoryStorage() : entityMap() {}
FactoryStorage::~FactoryStorage() {
instance_ = 0;
dgDEBUGINOUT(25);
}
/* --------------------------------------------------------------------- */
void FactoryStorage::
registerEntity( const std::string& entname,FactoryStorage::EntityConstructor_ptr ent )
{
void FactoryStorage::registerEntity(const std::string &entname,
FactoryStorage::EntityConstructor_ptr ent) {
dgDEBUGIN(25);
EntityMap::iterator entkey;
if( existEntity(entname,entkey) ) // key does exist
{
// DG_THROW ExceptionFactory( ExceptionFactory::OBJECT_CONFLICT,
// "Another entity class already defined with the same name. ",
// "(while adding entity class <%s> inside the g_factory).",
// entname.c_str() );
dgERRORF("Another entity class already defined with the same name. "
"(while adding entity class <%s> inside the factory).",
entname.c_str() );
}
else
{
dgDEBUG(30) << "Register entity <"<< entname
<< "> in the factory." <<std::endl;
entityMap[entname] = ent;
if (existEntity(entname)) {
DG_THROW ExceptionFactory(
ExceptionFactory::OBJECT_CONFLICT,
"Another entity class already defined with the same name. ",
"(while adding entity class <%s> inside the factory).",
entname.c_str());
dgERRORF(
"Another entity class already defined with the same name. "
"(while adding entity class <%s> inside the factory).",
entname.c_str());
} else {
if (!ent) {
// FIXME: we should have a better error code for that.
DG_THROW ExceptionFactory(ExceptionFactory::OBJECT_CONFLICT,
"Bad entity constructor.");
}
dgDEBUG(30) << "Register entity <" << entname << "> in the factory."
<< std::endl;
entityMap[entname] = ent;
}
dgDEBUGOUT(25);
}
void FactoryStorage::
deregisterEntity( const std::string& entname )
{
void FactoryStorage::deregisterEntity(const std::string &entname) {
dgDEBUGIN(25);
EntityMap::iterator entkey;
if(! existEntity(entname,entkey) ) // key does not exist
{
DG_THROW ExceptionFactory( ExceptionFactory::OBJECT_CONFLICT,
"Entity class not defined yet. ",
"(while removing entity class <%s>).",
entname.c_str() );
dgERRORF(ExceptionFactory::OBJECT_CONFLICT,
"Entity class not defined yet. "
"(while removing entity class <%s>).",
entname.c_str() );
}
else
{
dgDEBUG(30) << "Deregister entity <"<< entname
<< "> from the factory." <<std::endl;
entityMap.erase( entkey );
}
if (!existEntity(entname)) {
DG_THROW ExceptionFactory(
ExceptionFactory::OBJECT_CONFLICT, "Entity class not defined yet. ",
"(while removing entity class <%s>).", entname.c_str());
dgERRORF(ExceptionFactory::OBJECT_CONFLICT,
"Entity class not defined yet. "
"(while removing entity class <%s>).",
entname.c_str());
} else {
dgDEBUG(30) << "Deregister entity <" << entname << "> from the factory."
<< std::endl;
entityMap.erase(entname);
}
dgDEBUGOUT(25);
}
Entity* FactoryStorage::
newEntity( const std::string& classname,const std::string& objname )
{
dgDEBUG(15) << "New <"<<classname<<">Entity <"<<objname<<">"<<std::endl;
EntityMap::iterator entPtr;
if(! existEntity(classname,entPtr) )
{
DG_THROW ExceptionFactory( ExceptionFactory::UNREFERED_OBJECT,
"Unknown entity."," (while calling new_entity <%s>)",
classname.c_str() );
}
Entity *FactoryStorage::newEntity(const std::string &classname,
const std::string &objname) const {
dgDEBUG(15) << "New <" << classname << ">Entity <" << objname << ">"
<< std::endl;
EntityMap::const_iterator entPtr = entityMap.find(classname);
if (entPtr == entityMap.end()) {
DG_THROW ExceptionFactory(
ExceptionFactory::UNREFERED_OBJECT, "Unknown entity.",
" (while calling new_entity <%s>)", classname.c_str());
}
return entPtr->second(objname);
}
bool FactoryStorage::
existEntity( const std::string& name, EntityMap::iterator& entPtr )
{
entPtr = entityMap .find( name );
return ( entPtr != entityMap.end() );
// This checks efficiently if a key exists in an STL map using the
// approach suggested by Scott Meyer's Effective STL (item 24).
bool FactoryStorage::existEntity(const std::string &name) const {
EntityMap::const_iterator lb = entityMap.lower_bound(name);
return lb != entityMap.end() && !(entityMap.key_comp()(name, lb->first));
}
bool FactoryStorage::
existEntity( const std::string& name )
{
EntityMap::iterator entPtr;return existEntity( name,entPtr );
// FIXME: this should be removed at some point.
void FactoryStorage::listEntities(std::vector<std::string> &outList) const {
typedef std::pair<std::string, EntityConstructor_ptr> iter_t;
BOOST_FOREACH (const iter_t &entity, entityMap)
outList.push_back(entity.first);
}
/* --------------------------------------------------------------------- */
/* --- REGISTERERS ----------------------------------------------------- */
/* --------------------------------------------------------------------- */
EntityRegisterer::
EntityRegisterer( const std::string& entityClassName,
FactoryStorage::EntityConstructor_ptr maker)
:entityName( entityClassName )
{
EntityRegisterer::EntityRegisterer(const std::string &entityClassName,
FactoryStorage::EntityConstructor_ptr maker)
: entityName(entityClassName) {
dgDEBUGIN(15);
g_factory.registerEntity(entityClassName,maker);
FactoryStorage::getInstance()->registerEntity(entityClassName, maker);
dgDEBUGOUT(15);
}
EntityRegisterer::
~EntityRegisterer( void )
{
EntityRegisterer::~EntityRegisterer() {
dgDEBUGIN(15);
g_factory.deregisterEntity(entityName);
FactoryStorage::getInstance()->deregisterEntity(entityName);
dgDEBUGOUT(15);
}
/* --------------------------------------------------------------------- */
/* --- COMMAND LINE ---------------------------------------------------- */
/* --------------------------------------------------------------------- */
void FactoryStorage::
commandLine( const std::string& cmdLine,std::istringstream& cmdArgs,
std::ostream& os )
{
if( cmdLine == "help" )
{
os<< "factory ";
string cmd2; cmdArgs >> cmd2;
if(! cmdArgs.good())
os << " <arg>\t\t\t\taccess to the factory (help <arg> for more detail)" <<endl;
else if( cmd2 == "list" )
os << "list\t\t:List all available entities." << endl;
else if( cmd2 == "listEntities" )
os <<"listEntities\t:List available entities." << endl;
}
else if( cmdLine == "list" )
{
commandLine("listEntities",cmdArgs,os);
}
else if( cmdLine == "listEntities" )
{
os <<" List of available entities:" << endl;
for( EntityMap::iterator iter = entityMap.begin();iter!=entityMap.end();++iter )
{ os << " - " << iter->first << endl; }
}
return;
}
namespace dynamicgraph {
//! The global g_factory object.
FactoryStorage g_factory;
}
// The global factory.
FactoryStorage *FactoryStorage::instance_ = NULL;
} // end of namespace dynamicgraph.