diff --git a/doc/additionalDoc/debug-doc.h b/doc/additionalDoc/debug-doc.h index b31d58483201cde5714c1002d7819b5bf6e848b1..b26b6102f6a8220ed21a086146aa4362bc386bef 100644 --- a/doc/additionalDoc/debug-doc.h +++ b/doc/additionalDoc/debug-doc.h @@ -4,7 +4,7 @@ They are several ways to perform debugging in dynamic-graph depending on your needs or situation: - Programmatically inside the entity in C++ will write inside a buffer in a different thread and output in a stream (either std::cout or a file). It is detailed in \subpage subp_debug_rt_logger. -- Programmatically inside the entity in C++ using a member of the entities and the previous real-time mechanism. +- Programmatically inside the entity in C++ using a member of the entities and the previous real-time mechanism. It provides 4 levels of messags :(DEBUG,INFO, WARNING, ERROR). It is described in details here: \subpage subp_logger - Programmatically in C++ to avoid overhead with macros and handling level as an int: \subpage subp_dbg_trace diff --git a/doc/additionalDoc/debug-logger.h b/doc/additionalDoc/debug-logger.h index dce8cde54c49ba4171fc25a0e6c6e93498d38790..c67da3078c1484323701109d53471f5af12bf2a2 100644 --- a/doc/additionalDoc/debug-logger.h +++ b/doc/additionalDoc/debug-logger.h @@ -66,7 +66,7 @@ Here is some example on how to display or record some information. logger_.countdown(); \endcode -Specifying the file with __FILE__ and the line inside the file by __LINE__ are necessary for the -STREAM messages. Indeed they are indexed using the two values. As the default value are "" and 0 +Specifying the file with __FILE__ and the line inside the file by __LINE__ are necessary for the +STREAM messages. Indeed they are indexed using the two values. As the default value are "" and 0 the counting will be confused. */ diff --git a/doc/additionalDoc/debug-real-time-logger.h b/doc/additionalDoc/debug-real-time-logger.h index 2131c51bfeaaf6a8071a4b66df9400a5bf53642a..7b674ec00ca25ab7041dfb5c1b90a9d0e53ab685 100644 --- a/doc/additionalDoc/debug-real-time-logger.h +++ b/doc/additionalDoc/debug-real-time-logger.h @@ -1,20 +1,20 @@ -/** +/** \page subp_debug_rt_logger Real-time Logger It is intended to be used like this: \code #define ENABLE_RT_LOG #include <dynamic-graph/real-time-logger.h> - + // Somewhere in the main function of your executable int main (int argc, char** argv) { dgADD_OSTREAM_TO_RTLOG (std::cout); } - + // Somewhere in your library dgRTLOG() << "your message. Prefer to use \n than std::endl." \endcode - + \note Thread safety. This class expects to have: - only one reader: the one who take the log entries and write them somewhere. - one writer at a time. Writing to the logs is **never** a blocking diff --git a/doc/additionalDoc/debug-trace-doc.h b/doc/additionalDoc/debug-trace-doc.h index ba906931c83331487f6f8c8bec2377ca50f9bc51..d977b79dda0a8962c9eb6236b33a3e6f729095b5 100644 --- a/doc/additionalDoc/debug-trace-doc.h +++ b/doc/additionalDoc/debug-trace-doc.h @@ -2,9 +2,9 @@ \page subp_dbg_trace Debugging with macros and level \section subp_dbg_trace_intro Introduction -The idea of this class and collection of MACROS is to specify -a level for a message, and record the message in a stream according to this level. -In addition there are mechanisms allowing that no time +The idea of this class and collection of MACROS is to specify +a level for a message, and record the message in a stream according to this level. +In addition there are mechanisms allowing that no time is wasted in condition test. You can therefore let the debugging messages inside the code without impact on performances. @@ -42,7 +42,7 @@ It will generate the following output: \code /path_to/dynamic-graph/tests/debug-trace.cpp: testDebugTrace(#46) :# In { \endcode -The output displays the name of the source file, the name of the method, +The output displays the name of the source file, the name of the method, the line where is the macro, and the message itself. When going out of the method: diff --git a/doc/additionalDoc/entity.h b/doc/additionalDoc/entity.h index 585dba6f91df87a8adb24735e82423536563c530..f08e5a76eae4645e9e6d2c8847540de544659b6e 100644 --- a/doc/additionalDoc/entity.h +++ b/doc/additionalDoc/entity.h @@ -6,27 +6,25 @@ \image html entity.png Despite the fact that it looks very similar to a ROS node or a CORBA/OpenRTM server, an entity is simply a C++ object. -The main idea is that this entity is providing mostly a data-driven functionnality working at very high rate (\f$ 200 Hz\f$ or \f$ 1 kHz \f$) -and should have a minimal computational time foot-print. - -For this \subpage subp_signals (or ports to use a more classical terminology) are providing a time dependency between data. -To implement this, an output signal is linked with a method of the entity. The method calls input signals or use other means -to get the needed data. -It might be provided by the connection with remote computers through a middleware, or specific protocols, -but in general the external data is based upon the sensor values provided by a "Device" entity. -For this reason the signal evaluations are realized through the cascade of dependencies and start from the evaluation of an input -signal of a periodic node (in general the device). This is realized inside a \b real-time thread. - -To add flexibility to a node, it is possible to add command with arguments to modify the internal behavior of the entity -or get information from the entity. -As a command is in general asynchronous and rare with respect to the data-flow scheme for the signals the command is in general -executed in a \b none-real-time thread. +The main idea is that this entity is providing mostly a data-driven functionnality working at very high rate (\f$ 200 +Hz\f$ or \f$ 1 kHz \f$) and should have a minimal computational time foot-print. + +For this \subpage subp_signals (or ports to use a more classical terminology) are providing a time dependency between +data. To implement this, an output signal is linked with a method of the entity. The method calls input signals or use +other means to get the needed data. It might be provided by the connection with remote computers through a middleware, +or specific protocols, but in general the external data is based upon the sensor values provided by a "Device" entity. +For this reason the signal evaluations are realized through the cascade of dependencies and start from the evaluation +of an input signal of a periodic node (in general the device). This is realized inside a \b real-time thread. + +To add flexibility to a node, it is possible to add command with arguments to modify the internal behavior of the +entity or get information from the entity. As a command is in general asynchronous and rare with respect to the +data-flow scheme for the signals the command is in general executed in a \b none-real-time thread. \subsection entity_classes Entity class -Entities are implemented as C++ classes and compiled as dynamic libraries. They can be loaded and instancied dynamically. -It is therefore necessary to specify the location of their dynamical libraries. -However given the time it might take to load the library, it is not advised to do that during a control-law computation. -Entity instanciation also implies memory allocation which is also time consuming and thus not advised inside a real-time thread. +Entities are implemented as C++ classes and compiled as dynamic libraries. They can be loaded and instancied +dynamically. It is therefore necessary to specify the location of their dynamical libraries. However given the time it +might take to load the library, it is not advised to do that during a control-law computation. Entity instanciation +also implies memory allocation which is also time consuming and thus not advised inside a real-time thread. The entities will be placed in ${PREFIX}/lib/plugin (since this may change, it is advised to check the install log or the CMakeLists.txt file to check the installation path). @@ -42,9 +40,10 @@ enable creation of this entity through the factory. \subsection specific_semantics Specific semantics with entities -It is possible to derive classes and apply specific semantic for the entities. In our case we are interested in specific control semantics: -\li Tasks (more information <a href="http://stack-of-tasks.github.io/sot-core/doxygen/HEAD/a00089.html">here</a>) -\li Features (more information <a href="http://stack-of-tasks.github.io/sot-core/doxygen/HEAD/a00030.html">here</a>) -\li Solver (more information <a href="http://stack-of-tasks.github.io/sot-core/doxygen/HEAD/a00078.html">here</a>) +It is possible to derive classes and apply specific semantic for the entities. In our case we are interested in +specific control semantics: \li Tasks (more information <a +href="http://stack-of-tasks.github.io/sot-core/doxygen/HEAD/a00089.html">here</a>) \li Features (more information <a +href="http://stack-of-tasks.github.io/sot-core/doxygen/HEAD/a00030.html">here</a>) \li Solver (more information <a +href="http://stack-of-tasks.github.io/sot-core/doxygen/HEAD/a00078.html">here</a>) */ diff --git a/doc/additionalDoc/extension.h b/doc/additionalDoc/extension.h index ce76c717c8abec5de57aecdeefbfcf882891f0a6..568e3f8de7ad1446a6e92e608e14a8d0fe7b0812 100644 --- a/doc/additionalDoc/extension.h +++ b/doc/additionalDoc/extension.h @@ -11,8 +11,8 @@ Objects, which are derived from Entities (base class dynamicgraph::Entity), can declared within the code and compiled as shared libraries (.so/.dll files). These libraries can be loaded at run-time using the PluginLoader methods, and at the same time register their class names to the Factory (see the -examples in the <a href="http://projects.laas.fr/gepetto/doc/stack-of-tasks/sot-core/master/doxygen-html">sot-core documentation</a> -for advanced control examples). +examples in the <a href="http://projects.laas.fr/gepetto/doc/stack-of-tasks/sot-core/master/doxygen-html">sot-core +documentation</a> for advanced control examples). The Factory can then create instances of these objects and subsequently register them in the Pool. From the pool they can be listed, accessed, and acted upon @@ -40,19 +40,19 @@ When writing entities you might use some macros which are very useful to write y \subsection subsec_howto_typedef Entity helpers -The header <b>entity-helper.h</b> is defining a type called EntityClassName +The header <b>entity-helper.h</b> is defining a type called EntityClassName \section sec_howto_macros_helpers Macro helpers \subsection subsec_howto_macros_helpers_ent Preprocessing macros for entities -<ul> +<ul> <li> <b>DYNAMIC_GRAPH_ENTITY_DECL()</b>: This macro creates a method <b>getClassName()</b> which returns the class name.</li> This macro <b>should</b> be used in the declaration of the class. - </li> + </li> <li> <b>DYNAMICGRAPH_FACTORY_ENTITY_PLUGIN(classtype,classname)</b> - This macros creates the methods necessary to have a factory building the C++ class + This macros creates the methods necessary to have a factory building the C++ class <b>classtype</b> from the string <b>classname</b>. This macro <b>should</b> be used in the implementation of the class. </li> @@ -101,7 +101,7 @@ The header <b>entity-helper.h</b> is defining a type called EntityClassName <li> <b>DEFINE_SIGNAL_OUT_FUNCTION(signal_name, type)</b>: This macro is used when implementing the method specific to the output signal. - It is used in the main body of the entity class to declare the header of the method + It is used in the main body of the entity class to declare the header of the method with the following pattern: \code type EntityClassName::signal_nameSOUT_function(type &, int iter) @@ -109,7 +109,7 @@ The header <b>entity-helper.h</b> is defining a type called EntityClassName </li> </ul> - <li> + <li> </li> Inner signals <ul> <li> <b> DECLARE_SIGNAL_INNER(signal_name,type)</b> @@ -123,8 +123,8 @@ The header <b>entity-helper.h</b> is defining a type called EntityClassName type & EntityClassName::nameSINNER_function(signal_name)(type &, int) \endcode </li> - <li> <b>DEFINE_SIGNAL_INNER_FUNCTION(signal_name,type)</b> - This macro is used to implement the method related to signal_name. More precisely + <li> <b>DEFINE_SIGNAL_INNER_FUNCTION(signal_name,type)</b> + This macro is used to implement the method related to signal_name. More precisely it provides the header of the member function(i.e. method) declaration. </li> <li><b>DECLARE_SIGNAL_INNER_FUNCTION(signal_name,type)</b> diff --git a/doc/additionalDoc/factory.h b/doc/additionalDoc/factory.h index 07a1941b8cc927f89edc27edbcfc22577bf12239..baa92f46f1bd709cf7651e348a7383e2dfce1b5f 100644 --- a/doc/additionalDoc/factory.h +++ b/doc/additionalDoc/factory.h @@ -2,5 +2,6 @@ \page subp_factory Factory \section sec_factory Factory -The class \ref dynamicgraph::FactoryStorage is a singleton which register the entity classes and which is allowing the instancation of such classes. +The class \ref dynamicgraph::FactoryStorage is a singleton which register the entity classes and which is allowing the +instancation of such classes. */ diff --git a/doc/additionalDoc/graph.h b/doc/additionalDoc/graph.h index cf567dc8f8525d143e58623a279a3a3f3913a41f..4b013a88e2fb0e7d441d5927d2b9548a346b37ff 100644 --- a/doc/additionalDoc/graph.h +++ b/doc/additionalDoc/graph.h @@ -7,10 +7,11 @@ In this package, the graph considered are directed graphs. In dynamic-graph a graph is build with: - computational nodes which are entities \subpage subpage_entities. - directed edges which are created by connecting input and output signals \subpage subp_signals. -- managing the nodes is done through a factory \subpage subp_factory providing classes and a way to create instances from this list of classes. +- managing the nodes is done through a factory \subpage subp_factory providing classes and a way to create instances +from this list of classes. - the instances of node are handled through a pool \subpage subp_pool -We strongly recommend to use a scripting language such as Python to +We strongly recommend to use a scripting language such as Python to manage the graph. See <c>dynamic-graph-python</c> for more information on binding dynamic-graph with Python. diff --git a/doc/additionalDoc/pool.h b/doc/additionalDoc/pool.h index 73092eb5fa14636e9e38b200ee8cb172bdffa100..f9dd0e020fd9e29ecfcd114a6a4b12edb45fe6f4 100644 --- a/doc/additionalDoc/pool.h +++ b/doc/additionalDoc/pool.h @@ -2,7 +2,7 @@ \page subp_pool Pool \section pool Pool The class \ref dynamicgraph::PoolStorage keeps track of the entities instanciated with the factory. -The entities are the graph nodes. Signals are constructed during the class instanciation, they do not live independently -from the entities. Signals are the directed edges of the graph. -The pool can write a file representing the graph of entities. +The entities are the graph nodes. Signals are constructed during the class instanciation, they do not live +independently from the entities. Signals are the directed edges of the graph. The pool can write a file representing +the graph of entities. */ diff --git a/doc/additionalDoc/references.h b/doc/additionalDoc/references.h index e360c2a787721f46e09ec4f68698ba7b116bb065..5ed2b2e4d35a888a2d9054c14358ec9b26a6bc22 100644 --- a/doc/additionalDoc/references.h +++ b/doc/additionalDoc/references.h @@ -1,4 +1,4 @@ -/** +/** \page subp_references References \section sec_refer References @@ -7,7 +7,8 @@ Please when referencing the Stack-Of-Tasks use the following reference: \anchor Mansard2009 <b> <a href="https://hal-lirmm.ccsd.cnrs.fr/lirmm-00796736/document"> -"A versatile Generalized Inverted Kinematics implementation for collaborative working humanoid robots: The Stack Of Tasks"</a> +"A versatile Generalized Inverted Kinematics implementation for collaborative working humanoid robots: The Stack Of +Tasks"</a> </b>, <em>N. Mansard, O. Stasse, P. Evrard, A. Kheddar,</em> Int. Conf. on Autonomous Robots, ICAR, 2009 diff --git a/include/dynamic-graph/all-commands.h b/include/dynamic-graph/all-commands.h index 2ace540008be9da1293b7ef8b8e36f52f357075a..d32ddf374c4a1ab43e3e9dce36eb6f0084d6cc6e 100644 --- a/include/dynamic-graph/all-commands.h +++ b/include/dynamic-graph/all-commands.h @@ -4,7 +4,7 @@ // #ifndef DYNAMIC_GRAPH_ALL_COMMANDS_H -# define DYNAMIC_GRAPH_ALL_COMMANDS_H +#define DYNAMIC_GRAPH_ALL_COMMANDS_H // Utility header files including all commands headers @@ -15,4 +15,4 @@ #include <dynamic-graph/command.h> #include <dynamic-graph/command-setter.h> -#endif //! DYNAMIC_GRAPH_ALL_COMMANDS_H +#endif //! DYNAMIC_GRAPH_ALL_COMMANDS_H diff --git a/include/dynamic-graph/all-signals.h b/include/dynamic-graph/all-signals.h index 82b9957a53a220ff65295ee45f477df851f8851c..56b460c12e3fc8f9b557834b238e06e556edd4f0 100644 --- a/include/dynamic-graph/all-signals.h +++ b/include/dynamic-graph/all-signals.h @@ -4,12 +4,12 @@ // #ifndef DYNAMIC_GRAPH_ALL_SIGNALS_H -# define DYNAMIC_GRAPH_ALL_SIGNALS_H +#define DYNAMIC_GRAPH_ALL_SIGNALS_H // Utility header files including all signal headers -# include <dynamic-graph/signal.h> -# include <dynamic-graph/signal-ptr.h> -# include <dynamic-graph/signal-time-dependent.h> +#include <dynamic-graph/signal.h> +#include <dynamic-graph/signal-ptr.h> +#include <dynamic-graph/signal-time-dependent.h> -#endif //! DYNAMIC_GRAPH_ALL_SIGNALS_H +#endif //! DYNAMIC_GRAPH_ALL_SIGNALS_H diff --git a/include/dynamic-graph/command-bind.h b/include/dynamic-graph/command-bind.h index 064e7481a15fb7e437e32fc97b150088775682a0..f4387f182fc264163da363e067adeb6d40643b4d 100644 --- a/include/dynamic-graph/command-bind.h +++ b/include/dynamic-graph/command-bind.h @@ -27,465 +27,340 @@ /* --- FUNCTION 0 ARGS ------------------------------------------------------ */ namespace dynamicgraph { - namespace command { - - template <class E > - struct CommandVoid0 - : public Command - { - CommandVoid0(E& entity, boost::function<void(void)> function, - const std::string& docString) - :Command(entity, EMPTY_ARG, docString) - ,fptr(function) - {} - - protected: - virtual Value doExecute() - { - assert( getParameterValues().size() == 0 ); - fptr(); - return Value(); // void - } - private: - boost::function<void(void)> fptr; - }; - - - template <class E > - CommandVoid0<E>* makeCommandVoid0(E& entity, boost::function<void(void)> function , - const std::string& docString) - { - return new CommandVoid0<E>( entity,function,docString ); - } - - template <class E > - CommandVoid0<E>* makeCommandVoid0(E& entity, boost::function<void(E*)> function , - const std::string& docString) - { - return new CommandVoid0<E>( entity, - boost::bind(function,&entity),docString ); - } - - template <class E > - CommandVoid0<E>* makeCommandVoid0(E& entity, void (E::*function) (void), - const std::string& docString) - { - return new CommandVoid0<E>( entity, - boost::bind(function,&entity),docString ); - } - - inline std::string docCommandVoid0( const std::string& doc ) - { - return std::string("\n")+doc +"\n\nNo input.\nVoid return.\n\n"; - } - - } // namespace command -} // namespace dynamicgraph +namespace command { + +template <class E> +struct CommandVoid0 : public Command { + CommandVoid0(E& entity, boost::function<void(void)> function, const std::string& docString) + : Command(entity, EMPTY_ARG, docString), fptr(function) {} + + protected: + virtual Value doExecute() { + assert(getParameterValues().size() == 0); + fptr(); + return Value(); // void + } + + private: + boost::function<void(void)> fptr; +}; + +template <class E> +CommandVoid0<E>* makeCommandVoid0(E& entity, boost::function<void(void)> function, const std::string& docString) { + return new CommandVoid0<E>(entity, function, docString); +} + +template <class E> +CommandVoid0<E>* makeCommandVoid0(E& entity, boost::function<void(E*)> function, const std::string& docString) { + return new CommandVoid0<E>(entity, boost::bind(function, &entity), docString); +} + +template <class E> +CommandVoid0<E>* makeCommandVoid0(E& entity, void (E::*function)(void), const std::string& docString) { + return new CommandVoid0<E>(entity, boost::bind(function, &entity), docString); +} + +inline std::string docCommandVoid0(const std::string& doc) { + return std::string("\n") + doc + "\n\nNo input.\nVoid return.\n\n"; +} + +} // namespace command +} // namespace dynamicgraph /* --- FUNCTION 1 ARGS ------------------------------------------------------ */ namespace dynamicgraph { - namespace command { - - template <class E,typename T > - struct CommandVoid1 - : public Command - { - typedef boost::function<void(const T&)> function_t; - typedef boost::function<void(E*,const T&)> memberFunction_t; - typedef void (E::*memberFunction_ptr_t) (const T&); - - CommandVoid1(E& entity, function_t function, - const std::string& docString) - :Command(entity, boost::assign::list_of(ValueHelper<T>::TypeID), docString) - ,fptr(function) - {} - - protected: - virtual Value doExecute() - { - assert( getParameterValues().size() == 1 ); - T val = getParameterValues()[0].value(); - fptr(val); - return Value(); // void - } - private: - function_t fptr; - }; - - - template <class E,typename T > - CommandVoid1<E,T>* - makeCommandVoid1(E& entity, - boost::function<void(const T&)> function, - //typename CommandVoid1<E,T>::function_t function , - const std::string& docString) - { - return new CommandVoid1<E,T>( entity,function,docString ); - } - - template <class E,typename T > - CommandVoid1<E,T>* - makeCommandVoid1(E& entity, - // The following syntaxt don't compile when not specializing the template - // arg... why ??? - //typename CommandVoid1<E,T>::memberFunction_t function , - boost::function<void(E*,const T&)> function, - const std::string& docString) - { - return new CommandVoid1<E,T>( entity, - boost::bind(function,&entity,_1),docString ); - } - - template <class E,typename T > - CommandVoid1<E,T>* - makeCommandVoid1(E& entity, - void (E::*function) (const T&), - const std::string& docString) - { - return new CommandVoid1<E,T>( entity, - boost::bind(function,&entity,_1),docString ); - return NULL; - } - - inline std::string docCommandVoid1( const std::string& doc, const std::string& type ) - { - return std::string("\n")+doc +"\n\nInput:\n - A "+type+".\nVoid return.\n\n"; - } - - } // namespace command -} // namespace dynamicgraph +namespace command { + +template <class E, typename T> +struct CommandVoid1 : public Command { + typedef boost::function<void(const T&)> function_t; + typedef boost::function<void(E*, const T&)> memberFunction_t; + typedef void (E::*memberFunction_ptr_t)(const T&); + + CommandVoid1(E& entity, function_t function, const std::string& docString) + : Command(entity, boost::assign::list_of(ValueHelper<T>::TypeID), docString), fptr(function) {} + + protected: + virtual Value doExecute() { + assert(getParameterValues().size() == 1); + T val = getParameterValues()[0].value(); + fptr(val); + return Value(); // void + } + + private: + function_t fptr; +}; + +template <class E, typename T> +CommandVoid1<E, T>* makeCommandVoid1(E& entity, boost::function<void(const T&)> function, + // typename CommandVoid1<E,T>::function_t function , + const std::string& docString) { + return new CommandVoid1<E, T>(entity, function, docString); +} + +template <class E, typename T> +CommandVoid1<E, T>* makeCommandVoid1(E& entity, + // The following syntaxt don't compile when not specializing the template + // arg... why ??? + // typename CommandVoid1<E,T>::memberFunction_t function , + boost::function<void(E*, const T&)> function, const std::string& docString) { + return new CommandVoid1<E, T>(entity, boost::bind(function, &entity, _1), docString); +} + +template <class E, typename T> +CommandVoid1<E, T>* makeCommandVoid1(E& entity, void (E::*function)(const T&), const std::string& docString) { + return new CommandVoid1<E, T>(entity, boost::bind(function, &entity, _1), docString); + return NULL; +} + +inline std::string docCommandVoid1(const std::string& doc, const std::string& type) { + return std::string("\n") + doc + "\n\nInput:\n - A " + type + ".\nVoid return.\n\n"; +} + +} // namespace command +} // namespace dynamicgraph /* --- FUNCTION 2 ARGS ------------------------------------------------------ */ namespace dynamicgraph { - namespace command { - - template <class E,typename T1,typename T2 > - struct CommandVoid2 - : public Command - { - typedef boost::function<void(const T1&,const T2&)> function_t; - typedef boost::function<void(E*,const T1&,const T2&)> memberFunction_t; - typedef void (E::*memberFunction_ptr_t) (const T1&,const T2&); - - CommandVoid2(E& entity, function_t function, - const std::string& docString) - :Command(entity, - boost::assign::list_of - (ValueHelper<T1>::TypeID) - (ValueHelper<T2>::TypeID), docString) - ,fptr(function) - {} - - protected: - virtual Value doExecute() - { - assert( getParameterValues().size() == 2 ); - T1 val1 = getParameterValues()[0].value(); - T2 val2 = getParameterValues()[1].value(); - fptr(val1,val2); - return Value(); // void - } - private: - function_t fptr; - }; - - - template <class E,typename T1,typename T2 > - CommandVoid2<E,T1,T2>* - makeCommandVoid2(E& entity, - boost::function<void(const T1&,const T2&)> function, - const std::string& docString) - { - return new CommandVoid2<E,T1,T2>( entity,function,docString ); - } - - template <class E,typename T1,typename T2 > - CommandVoid2<E,T1,T2>* - makeCommandVoid2(E& entity, - // The following syntaxt don't compile when not specializing the template - // arg... why ??? - //typename CommandVoid2<E,T1,T2>::memberFunction_t function , - boost::function<void(E*,const T1&,const T2&)> function, - const std::string& docString) - { - return new CommandVoid2<E,T1,T2>( entity, - boost::bind(function,&entity,_1,_2),docString ); - } - - template <class E,typename T1,typename T2 > - CommandVoid2<E,T1,T2>* - makeCommandVoid2(E& entity, - void (E::*function) (const T1&,const T2&), - const std::string& docString) - { - return new CommandVoid2<E,T1,T2>( entity, - boost::bind(function,&entity,_1,_2), - docString ); - return NULL; - } - - inline std::string docCommandVoid2( const std::string& doc, - const std::string& type1, - const std::string& type2 ) - { - return (std::string("\n")+doc+"\n\n" - +"Input:\n - A "+type1+".\n" - +"Input:\n - A "+type2+".\n" - +"Void return.\n\n" ); - } - - } // namespace command -} // namespace dynamicgraph - +namespace command { + +template <class E, typename T1, typename T2> +struct CommandVoid2 : public Command { + typedef boost::function<void(const T1&, const T2&)> function_t; + typedef boost::function<void(E*, const T1&, const T2&)> memberFunction_t; + typedef void (E::*memberFunction_ptr_t)(const T1&, const T2&); + + CommandVoid2(E& entity, function_t function, const std::string& docString) + : Command(entity, boost::assign::list_of(ValueHelper<T1>::TypeID)(ValueHelper<T2>::TypeID), docString), + fptr(function) {} + + protected: + virtual Value doExecute() { + assert(getParameterValues().size() == 2); + T1 val1 = getParameterValues()[0].value(); + T2 val2 = getParameterValues()[1].value(); + fptr(val1, val2); + return Value(); // void + } + + private: + function_t fptr; +}; + +template <class E, typename T1, typename T2> +CommandVoid2<E, T1, T2>* makeCommandVoid2(E& entity, boost::function<void(const T1&, const T2&)> function, + const std::string& docString) { + return new CommandVoid2<E, T1, T2>(entity, function, docString); +} + +template <class E, typename T1, typename T2> +CommandVoid2<E, T1, T2>* makeCommandVoid2(E& entity, + // The following syntaxt don't compile when not specializing the template + // arg... why ??? + // typename CommandVoid2<E,T1,T2>::memberFunction_t function , + boost::function<void(E*, const T1&, const T2&)> function, + const std::string& docString) { + return new CommandVoid2<E, T1, T2>(entity, boost::bind(function, &entity, _1, _2), docString); +} + +template <class E, typename T1, typename T2> +CommandVoid2<E, T1, T2>* makeCommandVoid2(E& entity, void (E::*function)(const T1&, const T2&), + const std::string& docString) { + return new CommandVoid2<E, T1, T2>(entity, boost::bind(function, &entity, _1, _2), docString); + return NULL; +} + +inline std::string docCommandVoid2(const std::string& doc, const std::string& type1, const std::string& type2) { + return (std::string("\n") + doc + "\n\n" + "Input:\n - A " + type1 + ".\n" + "Input:\n - A " + type2 + ".\n" + + "Void return.\n\n"); +} + +} // namespace command +} // namespace dynamicgraph /* --- FUNCTION 3 ARGS ------------------------------------------------------ */ namespace dynamicgraph { - namespace command { - - template <class E,typename T1,typename T2,typename T3 > - struct CommandVoid3 - : public Command - { - typedef boost::function<void(const T1&,const T2&,const T3&)> function_t; - typedef boost::function<void(E*,const T1&,const T2&,const T3&)> memberFunction_t; - typedef void (E::*memberFunction_ptr_t) (const T1&,const T2&,const T3); - - CommandVoid3(E& entity, function_t function, - const std::string& docString) - :Command(entity, - boost::assign::list_of - (ValueHelper<T1>::TypeID) - (ValueHelper<T2>::TypeID) - (ValueHelper<T3>::TypeID), docString) - ,fptr(function) - {} - - protected: - virtual Value doExecute() - { - assert( getParameterValues().size() == 3 ); - T1 val1 = getParameterValues()[0].value(); - T2 val2 = getParameterValues()[1].value(); - T3 val3 = getParameterValues()[2].value(); - fptr(val1,val2,val3); - return Value(); // void - } - private: - function_t fptr; - }; - - - template <class E,typename T1,typename T2,typename T3 > - CommandVoid3<E,T1,T2,T3>* - makeCommandVoid3(E& entity, - typename CommandVoid3<E,T1,T2,T3>::function_t function , - const std::string& docString) - { - return new CommandVoid3<E,T1,T2,T3>( entity,function,docString ); - } - - template <class E,typename T1,typename T2,typename T3 > - CommandVoid3<E,T1,T2,T3>* - makeCommandVoid3(E& entity, - // The following syntaxt don't compile when not specializing the template - // arg... why ??? - //typename CommandVoid3<E,T1,T2>::memberFunction_t function , - boost::function<void(E*,const T1&,const T2&,const T3&)> function, - const std::string& docString) - { - return new CommandVoid3<E,T1,T2,T3>( entity, - boost::bind(function,&entity,_1,_2,_3),docString ); - } - - template <class E,typename T1,typename T2,typename T3 > - CommandVoid3<E,T1,T2,T3>* - makeCommandVoid3(E& entity, - void (E::*function) (const T1&,const T2&,const T3&), - const std::string& docString) - { - return new CommandVoid3<E,T1,T2,T3>( entity, - boost::bind(function,&entity,_1,_2,_3), - docString ); - return NULL; - } - - inline std::string docCommandVoid3( const std::string& doc, - const std::string& type1, - const std::string& type2, - const std::string& type3 ) - { - return (std::string("\n")+doc+"\n\n" - +"Input:\n - A "+type1+".\n" - +"Input:\n - A "+type2+".\n" - +"Input:\n - A "+type3+".\n" - +"Void return.\n\n" ); - } - - } // namespace command -} // namespace dynamicgraph - +namespace command { + +template <class E, typename T1, typename T2, typename T3> +struct CommandVoid3 : public Command { + typedef boost::function<void(const T1&, const T2&, const T3&)> function_t; + typedef boost::function<void(E*, const T1&, const T2&, const T3&)> memberFunction_t; + typedef void (E::*memberFunction_ptr_t)(const T1&, const T2&, const T3); + + CommandVoid3(E& entity, function_t function, const std::string& docString) + : Command(entity, + boost::assign::list_of(ValueHelper<T1>::TypeID)(ValueHelper<T2>::TypeID)(ValueHelper<T3>::TypeID), + docString), + fptr(function) {} + + protected: + virtual Value doExecute() { + assert(getParameterValues().size() == 3); + T1 val1 = getParameterValues()[0].value(); + T2 val2 = getParameterValues()[1].value(); + T3 val3 = getParameterValues()[2].value(); + fptr(val1, val2, val3); + return Value(); // void + } + + private: + function_t fptr; +}; + +template <class E, typename T1, typename T2, typename T3> +CommandVoid3<E, T1, T2, T3>* makeCommandVoid3(E& entity, typename CommandVoid3<E, T1, T2, T3>::function_t function, + const std::string& docString) { + return new CommandVoid3<E, T1, T2, T3>(entity, function, docString); +} + +template <class E, typename T1, typename T2, typename T3> +CommandVoid3<E, T1, T2, T3>* makeCommandVoid3(E& entity, + // The following syntaxt don't compile when not specializing the template + // arg... why ??? + // typename CommandVoid3<E,T1,T2>::memberFunction_t function , + boost::function<void(E*, const T1&, const T2&, const T3&)> function, + const std::string& docString) { + return new CommandVoid3<E, T1, T2, T3>(entity, boost::bind(function, &entity, _1, _2, _3), docString); +} + +template <class E, typename T1, typename T2, typename T3> +CommandVoid3<E, T1, T2, T3>* makeCommandVoid3(E& entity, void (E::*function)(const T1&, const T2&, const T3&), + const std::string& docString) { + return new CommandVoid3<E, T1, T2, T3>(entity, boost::bind(function, &entity, _1, _2, _3), docString); + return NULL; +} + +inline std::string docCommandVoid3(const std::string& doc, const std::string& type1, const std::string& type2, + const std::string& type3) { + return (std::string("\n") + doc + "\n\n" + "Input:\n - A " + type1 + ".\n" + "Input:\n - A " + type2 + ".\n" + + "Input:\n - A " + type3 + ".\n" + "Void return.\n\n"); +} + +} // namespace command +} // namespace dynamicgraph /* --- FUNCTION 4 ARGS ------------------------------------------------------ */ namespace dynamicgraph { - namespace command { - - template <class E,typename T1,typename T2,typename T3,typename T4 > - struct CommandVoid4 - : public Command - { - typedef boost::function<void(const T1&,const T2&,const T3&,const T4&)> function_t; - typedef boost::function<void(E*,const T1&,const T2&,const T3&,const T4&)> memberFunction_t; - typedef void (E::*memberFunction_ptr_t) (const T1&,const T2&,const T3&,const T4&); - - CommandVoid4(E& entity, function_t function, - const std::string& docString) - :Command(entity, - boost::assign::list_of - (ValueHelper<T1>::TypeID) - (ValueHelper<T2>::TypeID) - (ValueHelper<T3>::TypeID) - (ValueHelper<T4>::TypeID) - , docString) - ,fptr(function) - {} - - protected: - virtual Value doExecute() - { - assert( getParameterValues().size() == 4 ); - T1 val1 = getParameterValues()[0].value(); - T2 val2 = getParameterValues()[1].value(); - T3 val3 = getParameterValues()[2].value(); - T4 val4 = getParameterValues()[3].value(); - fptr(val1,val2,val3,val4); - return Value(); // void - } - private: - function_t fptr; - }; - - - template <class E,typename T1,typename T2,typename T3,typename T4 > - CommandVoid4<E,T1,T2,T3,T4>* - makeCommandVoid4(E& entity, - typename CommandVoid4<E,T1,T2,T3,T4>::function_t function , - const std::string& docString) - { - return new CommandVoid4<E,T1,T2,T3,T4>( entity,function,docString ); - } - - template <class E,typename T1,typename T2,typename T3,typename T4 > - CommandVoid4<E,T1,T2,T3,T4>* - makeCommandVoid4(E& entity, - boost::function<void(E*,const T1&,const T2&,const T3&,const T4&)> function, - const std::string& docString) - { - return new CommandVoid4<E,T1,T2,T3,T4>( entity, - boost::bind(function,&entity,_1,_2,_3,_4),docString ); - } - - template <class E,typename T1,typename T2,typename T3,typename T4 > - CommandVoid4<E,T1,T2,T3,T4>* - makeCommandVoid4(E& entity, - void (E::*function) (const T1&,const T2&,const T3&,const T4&), - const std::string& docString) - { - return new CommandVoid4<E,T1,T2,T3,T4>( entity, - boost::bind(function,&entity,_1,_2,_3,_4), - docString ); - return NULL; - } - - inline std::string docCommandVoid4( const std::string& doc, - const std::string& type1, - const std::string& type2, - const std::string& type3, - const std::string& type4 ) - { - return (std::string("\n")+doc+"\n\n" - +"Input:\n - A "+type1+".\n" - +"Input:\n - A "+type2+".\n" - +"Input:\n - A "+type3+".\n" - +"Input:\n - A "+type4+".\n" - +"Void return.\n\n" ); - } - - } // namespace command -} // namespace dynamicgraph +namespace command { + +template <class E, typename T1, typename T2, typename T3, typename T4> +struct CommandVoid4 : public Command { + typedef boost::function<void(const T1&, const T2&, const T3&, const T4&)> function_t; + typedef boost::function<void(E*, const T1&, const T2&, const T3&, const T4&)> memberFunction_t; + typedef void (E::*memberFunction_ptr_t)(const T1&, const T2&, const T3&, const T4&); + + CommandVoid4(E& entity, function_t function, const std::string& docString) + : Command(entity, + boost::assign::list_of(ValueHelper<T1>::TypeID)(ValueHelper<T2>::TypeID)(ValueHelper<T3>::TypeID)( + ValueHelper<T4>::TypeID), + docString), + fptr(function) {} + + protected: + virtual Value doExecute() { + assert(getParameterValues().size() == 4); + T1 val1 = getParameterValues()[0].value(); + T2 val2 = getParameterValues()[1].value(); + T3 val3 = getParameterValues()[2].value(); + T4 val4 = getParameterValues()[3].value(); + fptr(val1, val2, val3, val4); + return Value(); // void + } + + private: + function_t fptr; +}; + +template <class E, typename T1, typename T2, typename T3, typename T4> +CommandVoid4<E, T1, T2, T3, T4>* makeCommandVoid4(E& entity, + typename CommandVoid4<E, T1, T2, T3, T4>::function_t function, + const std::string& docString) { + return new CommandVoid4<E, T1, T2, T3, T4>(entity, function, docString); +} + +template <class E, typename T1, typename T2, typename T3, typename T4> +CommandVoid4<E, T1, T2, T3, T4>* makeCommandVoid4( + E& entity, boost::function<void(E*, const T1&, const T2&, const T3&, const T4&)> function, + const std::string& docString) { + return new CommandVoid4<E, T1, T2, T3, T4>(entity, boost::bind(function, &entity, _1, _2, _3, _4), docString); +} + +template <class E, typename T1, typename T2, typename T3, typename T4> +CommandVoid4<E, T1, T2, T3, T4>* makeCommandVoid4(E& entity, + void (E::*function)(const T1&, const T2&, const T3&, const T4&), + const std::string& docString) { + return new CommandVoid4<E, T1, T2, T3, T4>(entity, boost::bind(function, &entity, _1, _2, _3, _4), docString); + return NULL; +} + +inline std::string docCommandVoid4(const std::string& doc, const std::string& type1, const std::string& type2, + const std::string& type3, const std::string& type4) { + return (std::string("\n") + doc + "\n\n" + "Input:\n - A " + type1 + ".\n" + "Input:\n - A " + type2 + ".\n" + + "Input:\n - A " + type3 + ".\n" + "Input:\n - A " + type4 + ".\n" + "Void return.\n\n"); +} + +} // namespace command +} // namespace dynamicgraph /* --- FUNCTION VERBOSE ----------------------------------------------------- */ /* This bind a function void f( ostream& ) that display some results into * a string f( void ) that return some string results. */ namespace dynamicgraph { - namespace command { - - template <class E > - struct CommandVerbose - : public Command - { - typedef boost::function<void(std::ostream&)> function_t; - typedef boost::function<void(E*,std::ostream&)> memberFunction_t; - typedef void (E::*memberFunctionConst_ptr_t) (std::ostream&) const; - typedef void (E::*memberFunction_ptr_t) (std::ostream&); - - CommandVerbose(E& entity, function_t function, - const std::string& docString) - :Command(entity, EMPTY_ARG, docString) - ,fptr(function) - {} - - protected: - virtual Value doExecute() - { - assert( getParameterValues().size() == 0 ); - std::ostringstream oss; - fptr(oss); - return Value( oss.str() ); // return string - } - private: - function_t fptr; - }; - - template <class E > - CommandVerbose<E>* - makeCommandVerbose(E& entity, - typename CommandVerbose<E>::function_t function, - const std::string& docString) - { - return new CommandVerbose<E>( entity,function,docString ); - return NULL; - } - - template <class E > - CommandVerbose<E>* - makeCommandVerbose(E& entity, - //void (E::*function) (std::ostream&) const, - typename CommandVerbose<E>::memberFunctionConst_ptr_t function, - const std::string& docString) - { - return new CommandVerbose<E>( entity, - boost::bind(function,&entity,_1),docString ); - return NULL; - } - - template <class E > - CommandVerbose<E>* - makeCommandVerbose(E& entity, - typename CommandVerbose<E>::memberFunction_ptr_t function, - const std::string& docString) - { - return new CommandVerbose<E>( entity, - boost::bind(function,&entity,_1),docString ); - return NULL; - } - - inline std::string docCommandVerbose( const std::string& doc ) - { - return std::string("\n")+doc +"\n\nNo input.\n Return a string.\n\n"; - } - - } // namespace command -} // namespace dynamicgraph - -#endif // __dg_command_bind_h__ +namespace command { + +template <class E> +struct CommandVerbose : public Command { + typedef boost::function<void(std::ostream&)> function_t; + typedef boost::function<void(E*, std::ostream&)> memberFunction_t; + typedef void (E::*memberFunctionConst_ptr_t)(std::ostream&) const; + typedef void (E::*memberFunction_ptr_t)(std::ostream&); + + CommandVerbose(E& entity, function_t function, const std::string& docString) + : Command(entity, EMPTY_ARG, docString), fptr(function) {} + + protected: + virtual Value doExecute() { + assert(getParameterValues().size() == 0); + std::ostringstream oss; + fptr(oss); + return Value(oss.str()); // return string + } + + private: + function_t fptr; +}; + +template <class E> +CommandVerbose<E>* makeCommandVerbose(E& entity, typename CommandVerbose<E>::function_t function, + const std::string& docString) { + return new CommandVerbose<E>(entity, function, docString); + return NULL; +} + +template <class E> +CommandVerbose<E>* makeCommandVerbose(E& entity, + // void (E::*function) (std::ostream&) const, + typename CommandVerbose<E>::memberFunctionConst_ptr_t function, + const std::string& docString) { + return new CommandVerbose<E>(entity, boost::bind(function, &entity, _1), docString); + return NULL; +} + +template <class E> +CommandVerbose<E>* makeCommandVerbose(E& entity, typename CommandVerbose<E>::memberFunction_ptr_t function, + const std::string& docString) { + return new CommandVerbose<E>(entity, boost::bind(function, &entity, _1), docString); + return NULL; +} + +inline std::string docCommandVerbose(const std::string& doc) { + return std::string("\n") + doc + "\n\nNo input.\n Return a string.\n\n"; +} + +} // namespace command +} // namespace dynamicgraph + +#endif // __dg_command_bind_h__ diff --git a/include/dynamic-graph/command-direct-getter.h b/include/dynamic-graph/command-direct-getter.h index 5424c2c4c13759d7b00943e204813558d5d3fe8e..bf88612b8deab321df45667690eba0e40c2d4449 100644 --- a/include/dynamic-graph/command-direct-getter.h +++ b/include/dynamic-graph/command-direct-getter.h @@ -20,42 +20,35 @@ /* --- GETTER --------------------------------------------------------- */ namespace dynamicgraph { - namespace command { - - template <class E, typename T> - class DirectGetter - : public Command - { - public: - /// Pointer to method that sets parameter of type T - typedef T (E::*GetterMethod) () const; - - /// Constructor - DirectGetter(E& entity,T* ptr, - const std::string& docString) - : Command(entity, std::vector<Value::Type>(), docString), - T_ptr(ptr) {} - - protected: - virtual Value doExecute() { return Value(*T_ptr); } - private: - T* T_ptr; - }; - - template <class E, typename T> - DirectGetter<E,T>* - makeDirectGetter( E& entity,T* ptr, - const std::string& docString) - { return new DirectGetter<E,T>(entity,ptr,docString); } - - inline std::string docDirectGetter( const std::string& name, - const std::string& type ) - { - return std::string("\nGet the ")+name+".\n\nNo input.\nReturn an "+type+".\n\n"; - } - - } // namespace command -} // namespace dynamicgraph - - -#endif // __dg_command_direct_getter_h__ +namespace command { + +template <class E, typename T> +class DirectGetter : public Command { + public: + /// Pointer to method that sets parameter of type T + typedef T (E::*GetterMethod)() const; + + /// Constructor + DirectGetter(E& entity, T* ptr, const std::string& docString) + : Command(entity, std::vector<Value::Type>(), docString), T_ptr(ptr) {} + + protected: + virtual Value doExecute() { return Value(*T_ptr); } + + private: + T* T_ptr; +}; + +template <class E, typename T> +DirectGetter<E, T>* makeDirectGetter(E& entity, T* ptr, const std::string& docString) { + return new DirectGetter<E, T>(entity, ptr, docString); +} + +inline std::string docDirectGetter(const std::string& name, const std::string& type) { + return std::string("\nGet the ") + name + ".\n\nNo input.\nReturn an " + type + ".\n\n"; +} + +} // namespace command +} // namespace dynamicgraph + +#endif // __dg_command_direct_getter_h__ diff --git a/include/dynamic-graph/command-direct-setter.h b/include/dynamic-graph/command-direct-setter.h index dc8b9f466bb95032a17f67d29c98c5699e883b69..3c9823d71c33a7c611075bbef7544babad11f016 100644 --- a/include/dynamic-graph/command-direct-setter.h +++ b/include/dynamic-graph/command-direct-setter.h @@ -20,45 +20,36 @@ /* --- SETTER --------------------------------------------------------- */ namespace dynamicgraph { - namespace command { - - template <class E, typename T> - class DirectSetter - : public Command - { - public: - DirectSetter(E& entity,T* ptr,const std::string& docString) - :Command(entity, boost::assign::list_of(ValueHelper<T>::TypeID), docString) - ,T_ptr(ptr) - {} - - protected: - virtual Value doExecute() - { - const std::vector<Value>& values = getParameterValues(); - T val = values[0].value(); - (*T_ptr) = val; - return Value(); // void - } - private: - T* T_ptr; - }; - - template <class E, typename T> - DirectSetter<E,T>* - makeDirectSetter( E& entity,T* ptr, - const std::string& docString) - { return new DirectSetter<E,T>(entity,ptr,docString); } - - inline std::string docDirectSetter( const std::string& name, - const std::string& type ) - { - return std::string("\nSet the ")+name+".\n\nInput:\n - a " - +type+".\nVoid return.\n\n"; - } - - } // namespace command -} // namespace dynamicgraph - - -#endif // __dg_command_direct_setter_h__ +namespace command { + +template <class E, typename T> +class DirectSetter : public Command { + public: + DirectSetter(E& entity, T* ptr, const std::string& docString) + : Command(entity, boost::assign::list_of(ValueHelper<T>::TypeID), docString), T_ptr(ptr) {} + + protected: + virtual Value doExecute() { + const std::vector<Value>& values = getParameterValues(); + T val = values[0].value(); + (*T_ptr) = val; + return Value(); // void + } + + private: + T* T_ptr; +}; + +template <class E, typename T> +DirectSetter<E, T>* makeDirectSetter(E& entity, T* ptr, const std::string& docString) { + return new DirectSetter<E, T>(entity, ptr, docString); +} + +inline std::string docDirectSetter(const std::string& name, const std::string& type) { + return std::string("\nSet the ") + name + ".\n\nInput:\n - a " + type + ".\nVoid return.\n\n"; +} + +} // namespace command +} // namespace dynamicgraph + +#endif // __dg_command_direct_setter_h__ diff --git a/include/dynamic-graph/command-getter.h b/include/dynamic-graph/command-getter.h index 431972169091e24a6c6a499fc061cf03a405ac44..d0b5cda3c82fd56e6fc9f43d86ce1540d49cfea0 100644 --- a/include/dynamic-graph/command-getter.h +++ b/include/dynamic-graph/command-getter.h @@ -10,54 +10,53 @@ #include "dynamic-graph/command.h" namespace dynamicgraph { - namespace command { +namespace command { - /// - /// Command that calls a parameter getter function - /// - /// This class is templated by a type E deriving from entity and - /// a type T of data. - /// - /// Let us assume that class E has a private member of type T and a - /// public getter function for this member: - /// \code - /// class E : public Entity - /// { - /// public: - /// E (const std::string& inName) : Entity(inName) {} - /// T getParameter() const {return parameter_;} - /// private: - /// T parameter_; - /// }; - /// \endcode - /// Then the command defined by: - /// \code - /// E entity("MyEntity"); - /// Getter<E,T> command(entity, &E::getParameter) - /// \endcode - /// returns the value of <c>entity.parameter_</c> upon invocation. - /// - /// \note - /// \li T should be a type supported by class Value, - /// \li prototype of E::getParameter should be exactly as specified in this - /// example. - template <class E, typename T> - class Getter : public Command { - public: - /// Pointer to method that sets parameter of type T - typedef T (E::*GetterMethod) () const; - /// Constructor - Getter(E& entity, GetterMethod getterMethod, - const std::string& docString); +/// +/// Command that calls a parameter getter function +/// +/// This class is templated by a type E deriving from entity and +/// a type T of data. +/// +/// Let us assume that class E has a private member of type T and a +/// public getter function for this member: +/// \code +/// class E : public Entity +/// { +/// public: +/// E (const std::string& inName) : Entity(inName) {} +/// T getParameter() const {return parameter_;} +/// private: +/// T parameter_; +/// }; +/// \endcode +/// Then the command defined by: +/// \code +/// E entity("MyEntity"); +/// Getter<E,T> command(entity, &E::getParameter) +/// \endcode +/// returns the value of <c>entity.parameter_</c> upon invocation. +/// +/// \note +/// \li T should be a type supported by class Value, +/// \li prototype of E::getParameter should be exactly as specified in this +/// example. +template <class E, typename T> +class Getter : public Command { + public: + /// Pointer to method that sets parameter of type T + typedef T (E::*GetterMethod)() const; + /// Constructor + Getter(E& entity, GetterMethod getterMethod, const std::string& docString); - protected: - virtual Value doExecute(); + protected: + virtual Value doExecute(); - private: - GetterMethod getterMethod_; - }; - } // namespace command -} // namespace dynamicgraph + private: + GetterMethod getterMethod_; +}; +} // namespace command +} // namespace dynamicgraph #include "dynamic-graph/command-getter.t.cpp" -#endif //DYNAMIC_GRAPH_COMMAND_GETTER_H +#endif // DYNAMIC_GRAPH_COMMAND_GETTER_H diff --git a/include/dynamic-graph/command-getter.t.cpp b/include/dynamic-graph/command-getter.t.cpp index 032d1c018cbac16c27133255ebbd9900c96eaee1..64f94000b61a41fe3d1c6f841b043787e562ca4c 100644 --- a/include/dynamic-graph/command-getter.t.cpp +++ b/include/dynamic-graph/command-getter.t.cpp @@ -10,25 +10,20 @@ #include <sstream> namespace dynamicgraph { - class Entity; - namespace command { +class Entity; +namespace command { - template <class E, typename T> - Getter<E, T>::Getter(E& entity, GetterMethod getterMethod, - const std::string& docstring) : - Command(entity, std::vector<Value::Type>(), docstring), - getterMethod_(getterMethod) - { - } +template <class E, typename T> +Getter<E, T>::Getter(E& entity, GetterMethod getterMethod, const std::string& docstring) + : Command(entity, std::vector<Value::Type>(), docstring), getterMethod_(getterMethod) {} - template <class E, typename T> - Value Getter<E, T>::doExecute() - { - E& entity = static_cast<E&>(owner()); - T value = (entity.*getterMethod_)(); - return Value(value); - } - } // namespace command -} // namespace dynamicgraph +template <class E, typename T> +Value Getter<E, T>::doExecute() { + E& entity = static_cast<E&>(owner()); + T value = (entity.*getterMethod_)(); + return Value(value); +} +} // namespace command +} // namespace dynamicgraph -#endif // DYNAMIC_GRAPH_COMMAND_GETTER_T_CPP +#endif // DYNAMIC_GRAPH_COMMAND_GETTER_T_CPP diff --git a/include/dynamic-graph/command-setter.h b/include/dynamic-graph/command-setter.h index 4ebfaaf0ff383d30095c5c6813030e7eae86dfc0..f7177c73b3102075635febc317cf7e789e4137db 100644 --- a/include/dynamic-graph/command-setter.h +++ b/include/dynamic-graph/command-setter.h @@ -10,54 +10,53 @@ #include "dynamic-graph/command.h" namespace dynamicgraph { - namespace command { +namespace command { - /// - /// Command that calls a parameter setter function - /// - /// This class is templated by a type E deriving from entity and - /// a type T of data. - /// - /// Let us assume that class E has a private member of type T and a - /// public setter function for this member: - /// \code - /// class E : public Entity - /// { - /// public: - /// E (const std::string& inName) : Entity(inName) {} - /// void setParameter(const T& parameter) {parameter_ = parameter;} - /// private: - /// T parameter_; - /// }; - /// \endcode - /// Then the command defined by: - /// \code - /// E entity("MyEntity"); - /// Setter<E,T> command(entity, &E::getParameter) - /// \endcode - /// sets the value of <c>entity.parameter_</c> upon invocation. - /// - /// \note - /// \li T should be a type supported by class Value, - /// \li prototype of E::setParameter should be exactly as specified in this - /// example. - template <class E, typename T> - class Setter : public Command { - public: - /// Pointer to method that sets parameter of type T - typedef void (E::*SetterMethod) (const T&); - /// Constructor - Setter(E& entity, SetterMethod setterMethod, - const std::string& docString); +/// +/// Command that calls a parameter setter function +/// +/// This class is templated by a type E deriving from entity and +/// a type T of data. +/// +/// Let us assume that class E has a private member of type T and a +/// public setter function for this member: +/// \code +/// class E : public Entity +/// { +/// public: +/// E (const std::string& inName) : Entity(inName) {} +/// void setParameter(const T& parameter) {parameter_ = parameter;} +/// private: +/// T parameter_; +/// }; +/// \endcode +/// Then the command defined by: +/// \code +/// E entity("MyEntity"); +/// Setter<E,T> command(entity, &E::getParameter) +/// \endcode +/// sets the value of <c>entity.parameter_</c> upon invocation. +/// +/// \note +/// \li T should be a type supported by class Value, +/// \li prototype of E::setParameter should be exactly as specified in this +/// example. +template <class E, typename T> +class Setter : public Command { + public: + /// Pointer to method that sets parameter of type T + typedef void (E::*SetterMethod)(const T&); + /// Constructor + Setter(E& entity, SetterMethod setterMethod, const std::string& docString); - protected: - virtual Value doExecute(); + protected: + virtual Value doExecute(); - private: - SetterMethod setterMethod_; - }; - } // namespace command -} // namespace dynamicgraph + private: + SetterMethod setterMethod_; +}; +} // namespace command +} // namespace dynamicgraph #include "dynamic-graph/command-setter.t.cpp" -#endif //DYNAMIC_GRAPH_COMMAND_SETTER_H +#endif // DYNAMIC_GRAPH_COMMAND_SETTER_H diff --git a/include/dynamic-graph/command-setter.t.cpp b/include/dynamic-graph/command-setter.t.cpp index f812159aae852845dd6754737a9140a6731ef4b4..c2dba66cf3f601c454af8da87831cafdc5185517 100644 --- a/include/dynamic-graph/command-setter.t.cpp +++ b/include/dynamic-graph/command-setter.t.cpp @@ -12,314 +12,266 @@ #include "dynamic-graph/linear-algebra.h" namespace dynamicgraph { - class Entity; - namespace command { - - // - // Template specialization: bool - // - template <class E> - class Setter<E, bool> : public Command { - public: - /// Pointer to method that sets parameter of type bool - typedef void (E::*SetterMethod) (const bool&); - /// Constructor - Setter(E& entity, SetterMethod setterMethod, - const std::string& docString); - - protected: - virtual Value doExecute(); - - private: - SetterMethod setterMethod_; - }; // Class Setter - - template <class E> - Setter<E, bool>::Setter(E& entity, SetterMethod setterMethod, - const std::string& docString) : - Command(entity, boost::assign::list_of(Value::BOOL), docString), - setterMethod_(setterMethod) - { - } - - template <class E> - Value Setter<E, bool>::doExecute() - { - const std::vector<Value>& values = getParameterValues(); - // Get parameter - bool value = values[0].value(); - E& entity = static_cast<E&>(owner()); - (entity.*setterMethod_)(value); - return Value(); - } - - // - // Template specialization: unsigned - // - template <class E> - class Setter<E, unsigned> : public Command { - public: - /// Pointer to method that sets parameter of type unsigned - typedef void (E::*SetterMethod) (const unsigned&); - /// Constructor - Setter(E& entity, SetterMethod setterMethod, - const std::string& docString); - - protected: - virtual Value doExecute(); - - private: - SetterMethod setterMethod_; - }; // Class Setter - - template <class E> - Setter<E, unsigned>::Setter(E& entity, SetterMethod setterMethod, - const std::string& docString) : - Command(entity, boost::assign::list_of(Value::UNSIGNED), docString), - setterMethod_(setterMethod) - { - } - - template <class E> - Value Setter<E, unsigned>::doExecute() - { - const std::vector<Value>& values = getParameterValues(); - // Get parameter - unsigned value = values[0].value(); - E& entity = static_cast<E&>(owner()); - (entity.*setterMethod_)(value); - return Value(); - } - - // - // Template specialization: int - // - template <class E> - class Setter<E, int> : public Command { - public: - /// Pointer to method that sets parameter of type int - typedef void (E::*SetterMethod) (const int&); - /// Constructor - Setter(E& entity, SetterMethod setterMethod, - const std::string& docString); - - protected: - virtual Value doExecute(); - - private: - SetterMethod setterMethod_; - }; // Class Setter - - template <class E> - Setter<E, int>::Setter(E& entity, SetterMethod setterMethod, - const std::string& docString) : - Command(entity, boost::assign::list_of(Value::INT), docString), - setterMethod_(setterMethod) - { - } - - template <class E> - Value Setter<E, int>::doExecute() - { - const std::vector<Value>& values = getParameterValues(); - // Get parameter - int value = values[0].value(); - E& entity = static_cast<E&>(owner()); - (entity.*setterMethod_)(value); - return Value(); - } - - // - // Template specialization: float - // - template <class E> - class Setter<E, float> : public Command { - public: - /// Pointer to method that sets parameter of type float - typedef void (E::*SetterMethod) (const float&); - /// Constructor - Setter(E& entity, SetterMethod setterMethod, - const std::string& docString); - - protected: - virtual Value doExecute(); - - private: - SetterMethod setterMethod_; - }; // Class Setter - - template <class E> - Setter<E, float>::Setter(E& entity, SetterMethod setterMethod, - const std::string& docString) : - Command(entity, boost::assign::list_of(Value::FLOAT), docString), - setterMethod_(setterMethod) - { - } - - template <class E> - Value Setter<E, float>::doExecute() - { - const std::vector<Value>& values = getParameterValues(); - // Get parameter - float value = values[0].value(); - E& entity = static_cast<E&>(owner()); - (entity.*setterMethod_)(value); - return Value(); - } - - // - // Template specialization: double - // - template <class E> - class Setter<E, double> : public Command { - public: - /// Pointer to method that sets parameter of type double - typedef void (E::*SetterMethod) (const double&); - /// Constructor - Setter(E& entity, SetterMethod setterMethod, - const std::string& docString); - - protected: - virtual Value doExecute(); - - private: - SetterMethod setterMethod_; - }; // Class Setter - - template <class E> - Setter<E, double>::Setter(E& entity, SetterMethod setterMethod, - const std::string& docString) : - Command(entity, boost::assign::list_of(Value::DOUBLE), docString), - setterMethod_(setterMethod) - { - } - - template <class E> - Value Setter<E, double>::doExecute() - { - const std::vector<Value>& values = getParameterValues(); - // Get parameter - double value = values[0].value(); - E& entity = static_cast<E&>(owner()); - (entity.*setterMethod_)(value); - return Value(); - } - - // - // Template specialization: std::string - // - template <class E> - class Setter<E, std::string> : public Command { - public: - /// Pointer to method that sets parameter of type std::string - typedef void (E::*SetterMethod) (const std::string&); - /// Constructor - Setter(E& entity, SetterMethod setterMethod, - const std::string& docString); - - protected: - virtual Value doExecute(); - - private: - SetterMethod setterMethod_; - }; // Class Setter - - template <class E> - Setter<E, std::string>::Setter(E& entity, SetterMethod setterMethod, - const std::string& docString) : - Command(entity, boost::assign::list_of(Value::STRING), docString), - setterMethod_(setterMethod) - { - } - - template <class E> - Value Setter<E, std::string>::doExecute() - { - const std::vector<Value>& values = getParameterValues(); - // Get parameter - std::string value = values[0].value(); - E& entity = static_cast<E&>(owner()); - (entity.*setterMethod_)(value); - return Value(); - } - - // - // Template specialization: Vector - // - template <class E> - class Setter<E, Vector> : public Command { - public: - /// Pointer to method that sets parameter of type Vector - typedef void (E::*SetterMethod) (const Vector&); - /// Constructor - Setter(E& entity, SetterMethod setterMethod, - const std::string& docString); - - protected: - virtual Value doExecute(); - - private: - SetterMethod setterMethod_; - }; // Class Setter - - template <class E> - Setter<E, Vector>::Setter(E& entity, SetterMethod setterMethod, - const std::string& docString) : - Command(entity, boost::assign::list_of(Value::VECTOR), docString), - setterMethod_(setterMethod) - { - } - - template <class E> - Value Setter<E, Vector>::doExecute() - { - const std::vector<Value>& values = getParameterValues(); - // Get parameter - Vector value = values[0].value(); - E& entity = static_cast<E&>(owner()); - (entity.*setterMethod_)(value); - return Value(); - } - - // - // Template specialization: Matrix - // - template <class E> - class Setter<E, Matrix> : public Command { - public: - /// Pointer to method that sets parameter of type Matrix - typedef void (E::*SetterMethod) (const Matrix&); - /// Constructor - Setter(E& entity, SetterMethod setterMethod, - const std::string& docString); - - protected: - virtual Value doExecute(); - - private: - SetterMethod setterMethod_; - }; // Class Setter - - template <class E> - Setter<E, Matrix>::Setter(E& entity, SetterMethod setterMethod, - const std::string& docString) : - Command(entity, boost::assign::list_of(Value::MATRIX), docString), - setterMethod_(setterMethod) - { - } - - template <class E> - Value Setter<E, Matrix>::doExecute() - { - const std::vector<Value>& values = getParameterValues(); - // Get parameter - Matrix value = values[0].value(); - E& entity = static_cast<E&>(owner()); - (entity.*setterMethod_)(value); - return Value(); - } - - } // namespace command -} // namespace dynamicgraph - -#endif // DYNAMIC_GRAPH_COMMAND_SETTER_T_CPP +class Entity; +namespace command { + +// +// Template specialization: bool +// +template <class E> +class Setter<E, bool> : public Command { + public: + /// Pointer to method that sets parameter of type bool + typedef void (E::*SetterMethod)(const bool&); + /// Constructor + Setter(E& entity, SetterMethod setterMethod, const std::string& docString); + + protected: + virtual Value doExecute(); + + private: + SetterMethod setterMethod_; +}; // Class Setter + +template <class E> +Setter<E, bool>::Setter(E& entity, SetterMethod setterMethod, const std::string& docString) + : Command(entity, boost::assign::list_of(Value::BOOL), docString), setterMethod_(setterMethod) {} + +template <class E> +Value Setter<E, bool>::doExecute() { + const std::vector<Value>& values = getParameterValues(); + // Get parameter + bool value = values[0].value(); + E& entity = static_cast<E&>(owner()); + (entity.*setterMethod_)(value); + return Value(); +} + +// +// Template specialization: unsigned +// +template <class E> +class Setter<E, unsigned> : public Command { + public: + /// Pointer to method that sets parameter of type unsigned + typedef void (E::*SetterMethod)(const unsigned&); + /// Constructor + Setter(E& entity, SetterMethod setterMethod, const std::string& docString); + + protected: + virtual Value doExecute(); + + private: + SetterMethod setterMethod_; +}; // Class Setter + +template <class E> +Setter<E, unsigned>::Setter(E& entity, SetterMethod setterMethod, const std::string& docString) + : Command(entity, boost::assign::list_of(Value::UNSIGNED), docString), setterMethod_(setterMethod) {} + +template <class E> +Value Setter<E, unsigned>::doExecute() { + const std::vector<Value>& values = getParameterValues(); + // Get parameter + unsigned value = values[0].value(); + E& entity = static_cast<E&>(owner()); + (entity.*setterMethod_)(value); + return Value(); +} + +// +// Template specialization: int +// +template <class E> +class Setter<E, int> : public Command { + public: + /// Pointer to method that sets parameter of type int + typedef void (E::*SetterMethod)(const int&); + /// Constructor + Setter(E& entity, SetterMethod setterMethod, const std::string& docString); + + protected: + virtual Value doExecute(); + + private: + SetterMethod setterMethod_; +}; // Class Setter + +template <class E> +Setter<E, int>::Setter(E& entity, SetterMethod setterMethod, const std::string& docString) + : Command(entity, boost::assign::list_of(Value::INT), docString), setterMethod_(setterMethod) {} + +template <class E> +Value Setter<E, int>::doExecute() { + const std::vector<Value>& values = getParameterValues(); + // Get parameter + int value = values[0].value(); + E& entity = static_cast<E&>(owner()); + (entity.*setterMethod_)(value); + return Value(); +} + +// +// Template specialization: float +// +template <class E> +class Setter<E, float> : public Command { + public: + /// Pointer to method that sets parameter of type float + typedef void (E::*SetterMethod)(const float&); + /// Constructor + Setter(E& entity, SetterMethod setterMethod, const std::string& docString); + + protected: + virtual Value doExecute(); + + private: + SetterMethod setterMethod_; +}; // Class Setter + +template <class E> +Setter<E, float>::Setter(E& entity, SetterMethod setterMethod, const std::string& docString) + : Command(entity, boost::assign::list_of(Value::FLOAT), docString), setterMethod_(setterMethod) {} + +template <class E> +Value Setter<E, float>::doExecute() { + const std::vector<Value>& values = getParameterValues(); + // Get parameter + float value = values[0].value(); + E& entity = static_cast<E&>(owner()); + (entity.*setterMethod_)(value); + return Value(); +} + +// +// Template specialization: double +// +template <class E> +class Setter<E, double> : public Command { + public: + /// Pointer to method that sets parameter of type double + typedef void (E::*SetterMethod)(const double&); + /// Constructor + Setter(E& entity, SetterMethod setterMethod, const std::string& docString); + + protected: + virtual Value doExecute(); + + private: + SetterMethod setterMethod_; +}; // Class Setter + +template <class E> +Setter<E, double>::Setter(E& entity, SetterMethod setterMethod, const std::string& docString) + : Command(entity, boost::assign::list_of(Value::DOUBLE), docString), setterMethod_(setterMethod) {} + +template <class E> +Value Setter<E, double>::doExecute() { + const std::vector<Value>& values = getParameterValues(); + // Get parameter + double value = values[0].value(); + E& entity = static_cast<E&>(owner()); + (entity.*setterMethod_)(value); + return Value(); +} + +// +// Template specialization: std::string +// +template <class E> +class Setter<E, std::string> : public Command { + public: + /// Pointer to method that sets parameter of type std::string + typedef void (E::*SetterMethod)(const std::string&); + /// Constructor + Setter(E& entity, SetterMethod setterMethod, const std::string& docString); + + protected: + virtual Value doExecute(); + + private: + SetterMethod setterMethod_; +}; // Class Setter + +template <class E> +Setter<E, std::string>::Setter(E& entity, SetterMethod setterMethod, const std::string& docString) + : Command(entity, boost::assign::list_of(Value::STRING), docString), setterMethod_(setterMethod) {} + +template <class E> +Value Setter<E, std::string>::doExecute() { + const std::vector<Value>& values = getParameterValues(); + // Get parameter + std::string value = values[0].value(); + E& entity = static_cast<E&>(owner()); + (entity.*setterMethod_)(value); + return Value(); +} + +// +// Template specialization: Vector +// +template <class E> +class Setter<E, Vector> : public Command { + public: + /// Pointer to method that sets parameter of type Vector + typedef void (E::*SetterMethod)(const Vector&); + /// Constructor + Setter(E& entity, SetterMethod setterMethod, const std::string& docString); + + protected: + virtual Value doExecute(); + + private: + SetterMethod setterMethod_; +}; // Class Setter + +template <class E> +Setter<E, Vector>::Setter(E& entity, SetterMethod setterMethod, const std::string& docString) + : Command(entity, boost::assign::list_of(Value::VECTOR), docString), setterMethod_(setterMethod) {} + +template <class E> +Value Setter<E, Vector>::doExecute() { + const std::vector<Value>& values = getParameterValues(); + // Get parameter + Vector value = values[0].value(); + E& entity = static_cast<E&>(owner()); + (entity.*setterMethod_)(value); + return Value(); +} + +// +// Template specialization: Matrix +// +template <class E> +class Setter<E, Matrix> : public Command { + public: + /// Pointer to method that sets parameter of type Matrix + typedef void (E::*SetterMethod)(const Matrix&); + /// Constructor + Setter(E& entity, SetterMethod setterMethod, const std::string& docString); + + protected: + virtual Value doExecute(); + + private: + SetterMethod setterMethod_; +}; // Class Setter + +template <class E> +Setter<E, Matrix>::Setter(E& entity, SetterMethod setterMethod, const std::string& docString) + : Command(entity, boost::assign::list_of(Value::MATRIX), docString), setterMethod_(setterMethod) {} + +template <class E> +Value Setter<E, Matrix>::doExecute() { + const std::vector<Value>& values = getParameterValues(); + // Get parameter + Matrix value = values[0].value(); + E& entity = static_cast<E&>(owner()); + (entity.*setterMethod_)(value); + return Value(); +} + +} // namespace command +} // namespace dynamicgraph + +#endif // DYNAMIC_GRAPH_COMMAND_SETTER_T_CPP diff --git a/include/dynamic-graph/command.h b/include/dynamic-graph/command.h index b383be5b1f37dfe40e9b809d55a906804382a9d2..6360cf9cbf185e3e54f9633ab8f410a105b25d0c 100644 --- a/include/dynamic-graph/command.h +++ b/include/dynamic-graph/command.h @@ -12,57 +12,58 @@ #include "dynamic-graph/dynamic-graph-api.h" namespace dynamicgraph { - class Entity; - namespace command { - /// Abstract class for entity commands - /// - /// This class provide a mean to control entities from external python script. - /// - /// A command - /// \li is owned by an entity, - /// \li takes parameters of type Value, - /// \li return an instance of Value when calling Command::execute() - /// - /// At construction, the prototype of the command is defined by providing - /// a vector of Value::Type. - /// - /// Parameters are set by calling Command::setParameterValues with a - /// vector of Values the types of which should fit the vector specified - /// at construction. - class DYNAMIC_GRAPH_DLLAPI Command - { - public: - virtual ~Command(); - /// Store the owner entity and a vector of value types - /// \param entity reference to Entity owning this command. - /// \param valueTypes vector specifying the number and types of parameters - /// \param docstring documentation of the command - Command(Entity& entity, const std::vector<Value::Type>& valueTypes, - const std::string& docstring); - /// Return the value type of all parameters - const std::vector<Value::Type>& valueTypes() const; - /// Set parameter values - void setParameterValues(const std::vector<Value>& values); - /// Get parameter values - const std::vector<Value>& getParameterValues() const; - /// Execute the command after checking parameters - Value execute(); - /// Get a reference to the Entity owning this command - Entity& owner(); - /// Get documentation string - std::string getDocstring() const; - protected: - /// Specific action performed by the command - virtual Value doExecute() = 0; - private: - Entity& owner_; - std::vector<Value::Type> valueTypeVector_; - std::vector<Value> valueVector_; - std::string docstring_; - public: - static const std::vector<Value::Type> EMPTY_ARG; - }; - } // namespace command -} // namespace dynamicgraph +class Entity; +namespace command { +/// Abstract class for entity commands +/// +/// This class provide a mean to control entities from external python script. +/// +/// A command +/// \li is owned by an entity, +/// \li takes parameters of type Value, +/// \li return an instance of Value when calling Command::execute() +/// +/// At construction, the prototype of the command is defined by providing +/// a vector of Value::Type. +/// +/// Parameters are set by calling Command::setParameterValues with a +/// vector of Values the types of which should fit the vector specified +/// at construction. +class DYNAMIC_GRAPH_DLLAPI Command { + public: + virtual ~Command(); + /// Store the owner entity and a vector of value types + /// \param entity reference to Entity owning this command. + /// \param valueTypes vector specifying the number and types of parameters + /// \param docstring documentation of the command + Command(Entity& entity, const std::vector<Value::Type>& valueTypes, const std::string& docstring); + /// Return the value type of all parameters + const std::vector<Value::Type>& valueTypes() const; + /// Set parameter values + void setParameterValues(const std::vector<Value>& values); + /// Get parameter values + const std::vector<Value>& getParameterValues() const; + /// Execute the command after checking parameters + Value execute(); + /// Get a reference to the Entity owning this command + Entity& owner(); + /// Get documentation string + std::string getDocstring() const; -#endif //DYNAMIC_GRAPH_COMMAND_H + protected: + /// Specific action performed by the command + virtual Value doExecute() = 0; + + private: + Entity& owner_; + std::vector<Value::Type> valueTypeVector_; + std::vector<Value> valueVector_; + std::string docstring_; + + public: + static const std::vector<Value::Type> EMPTY_ARG; +}; +} // namespace command +} // namespace dynamicgraph + +#endif // DYNAMIC_GRAPH_COMMAND_H diff --git a/include/dynamic-graph/debug.h b/include/dynamic-graph/debug.h index 7bc3627dddca5ff80fa1e42a9953bd5054729edc..1a6545d73d07282be76fe3a7164f9cc4a3aa49da 100644 --- a/include/dynamic-graph/debug.h +++ b/include/dynamic-graph/debug.h @@ -4,259 +4,205 @@ // #ifndef DYNAMIC_GRAPH_DEBUG_HH -# define DYNAMIC_GRAPH_DEBUG_HH -# include <cstdio> -# include <cstdarg> -# include <fstream> -# include <sstream> - -# include <dynamic-graph/fwd.hh> -# include <dynamic-graph/dynamic-graph-api.h> - - -# ifndef VP_DEBUG_MODE -# define VP_DEBUG_MODE 0 -# endif //! VP_DEBUG_MODE - -# ifndef VP_TEMPLATE_DEBUG_MODE -# define VP_TEMPLATE_DEBUG_MODE 0 -# endif //! VP_TEMPLATE_DEBUG_MODE - -#define DG_COMMON_TRACES \ - do { \ - va_list arg; \ - va_start (arg, format); \ - vsnprintf (charbuffer, SIZE, format, arg); \ - va_end (arg); \ - outputbuffer << tmpbuffer.str () << charbuffer << std::endl; \ - } while(0) - -namespace dynamicgraph -{ - /// \ingroup debug - /// - /// \brief Logging class. - /// - /// This class should never be used directly, please use the - /// debugging macro instead. - class DYNAMIC_GRAPH_DLLAPI DebugTrace - { - public: - static const int SIZE = 512; - - std::stringstream tmpbuffer; - std::ostream& outputbuffer; - char charbuffer[SIZE+1]; - int traceLevel; - int traceLevelTemplate; - - DebugTrace (std::ostream& os) - : outputbuffer (os) - {} - - inline void trace (const int level, const char* format, ...) - { - if (level <= traceLevel) - DG_COMMON_TRACES; tmpbuffer.str(""); - } - - inline void trace (const char* format, ...) - { - DG_COMMON_TRACES; +#define DYNAMIC_GRAPH_DEBUG_HH +#include <cstdio> +#include <cstdarg> +#include <fstream> +#include <sstream> + +#include <dynamic-graph/fwd.hh> +#include <dynamic-graph/dynamic-graph-api.h> + +#ifndef VP_DEBUG_MODE +#define VP_DEBUG_MODE 0 +#endif //! VP_DEBUG_MODE + +#ifndef VP_TEMPLATE_DEBUG_MODE +#define VP_TEMPLATE_DEBUG_MODE 0 +#endif //! VP_TEMPLATE_DEBUG_MODE + +#define DG_COMMON_TRACES \ + do { \ + va_list arg; \ + va_start(arg, format); \ + vsnprintf(charbuffer, SIZE, format, arg); \ + va_end(arg); \ + outputbuffer << tmpbuffer.str() << charbuffer << std::endl; \ + } while (0) + +namespace dynamicgraph { +/// \ingroup debug +/// +/// \brief Logging class. +/// +/// This class should never be used directly, please use the +/// debugging macro instead. +class DYNAMIC_GRAPH_DLLAPI DebugTrace { + public: + static const int SIZE = 512; + + std::stringstream tmpbuffer; + std::ostream& outputbuffer; + char charbuffer[SIZE + 1]; + int traceLevel; + int traceLevelTemplate; + + DebugTrace(std::ostream& os) : outputbuffer(os) {} + + inline void trace(const int level, const char* format, ...) { + if (level <= traceLevel) DG_COMMON_TRACES; + tmpbuffer.str(""); + } + + inline void trace(const char* format, ...) { + DG_COMMON_TRACES; + tmpbuffer.str(""); + } + + inline void trace(const int level = -1) { + if (level <= traceLevel) { + outputbuffer << tmpbuffer.str(); tmpbuffer.str(""); } + } - inline void trace (const int level=-1) - { - if (level <= traceLevel) { - outputbuffer << tmpbuffer.str (); tmpbuffer.str(""); - } - } + inline void traceTemplate(const int level, const char* format, ...) { + if (level <= traceLevelTemplate) DG_COMMON_TRACES; + tmpbuffer.str(""); + } - inline void traceTemplate (const int level, const char* format, ...) - { - if (level <= traceLevelTemplate) - DG_COMMON_TRACES; - tmpbuffer.str(""); - } + inline void traceTemplate(const char* format, ...) { + DG_COMMON_TRACES; + tmpbuffer.str(""); + } - inline void traceTemplate (const char* format, ...) - { - DG_COMMON_TRACES; - tmpbuffer.str(""); - } + inline DebugTrace& pre(const std::ostream&) { return *this; } - inline DebugTrace& pre (const std::ostream&) - { - return *this; - } + inline DebugTrace& pre(const std::ostream&, int level) { + traceLevel = level; + return *this; + } - inline DebugTrace& pre (const std::ostream&, int level) - { - traceLevel = level; - return *this; - } + static const char* DEBUG_FILENAME_DEFAULT; + static void openFile(const char* filename = DEBUG_FILENAME_DEFAULT); + static void closeFile(const char* filename = DEBUG_FILENAME_DEFAULT); +}; - static const char* DEBUG_FILENAME_DEFAULT; - static void openFile (const char* filename = DEBUG_FILENAME_DEFAULT); - static void closeFile( const char* filename = DEBUG_FILENAME_DEFAULT); - }; +DYNAMIC_GRAPH_DLLAPI extern DebugTrace dgDEBUGFLOW; +DYNAMIC_GRAPH_DLLAPI extern DebugTrace dgERRORFLOW; +} // end of namespace dynamicgraph - DYNAMIC_GRAPH_DLLAPI extern DebugTrace dgDEBUGFLOW; - DYNAMIC_GRAPH_DLLAPI extern DebugTrace dgERRORFLOW; -} // end of namespace dynamicgraph +#ifdef VP_DEBUG -# ifdef VP_DEBUG +#define dgPREDEBUG __FILE__ << ": " << __FUNCTION__ << "(#" << __LINE__ << ") :" +#define dgPREERROR "\t!! " << __FILE__ << ": " << __FUNCTION__ << "(#" << __LINE__ << ") :" -# define dgPREDEBUG \ - __FILE__ << ": " <<__FUNCTION__ << "(#" << __LINE__ << ") :" -# define dgPREERROR \ - "\t!! "<<__FILE__ << ": " <<__FUNCTION__ << "(#" << __LINE__ << ") :" - -# define dgDEBUG(level) \ - if ((level > VP_DEBUG_MODE) || (!dgDEBUGFLOW.outputbuffer.good ())) \ - ; \ - else \ +#define dgDEBUG(level) \ + if ((level > VP_DEBUG_MODE) || (!dgDEBUGFLOW.outputbuffer.good())) \ + ; \ + else \ dgDEBUGFLOW.outputbuffer << dgPREDEBUG -# define dgDEBUGMUTE(level) \ - if ((level > VP_DEBUG_MODE) || (!dgDEBUGFLOW.outputbuffer.good ())) \ - ; \ - else \ +#define dgDEBUGMUTE(level) \ + if ((level > VP_DEBUG_MODE) || (!dgDEBUGFLOW.outputbuffer.good())) \ + ; \ + else \ dgDEBUGFLOW.outputbuffer -# define dgERROR \ - if (!dgDEBUGFLOW.outputbuffer.good ()) \ - ; \ - else \ +#define dgERROR \ + if (!dgDEBUGFLOW.outputbuffer.good()) \ + ; \ + else \ dgERRORFLOW.outputbuffer << dgPREERROR -# define dgDEBUGF \ - if (!dgDEBUGFLOW.outputbuffer.good ()) \ - ; \ - else \ - dgDEBUGFLOW.pre (dgDEBUGFLOW.tmpbuffer << dgPREDEBUG, VP_DEBUG_MODE).trace +#define dgDEBUGF \ + if (!dgDEBUGFLOW.outputbuffer.good()) \ + ; \ + else \ + dgDEBUGFLOW.pre(dgDEBUGFLOW.tmpbuffer << dgPREDEBUG, VP_DEBUG_MODE).trace -# define dgERRORF \ - if (!dgDEBUGFLOW.outputbuffer.good ()) \ - ; \ - else \ - dgERRORFLOW.pre (dgERRORFLOW.tmpbuffer << dgPREERROR).trace +#define dgERRORF \ + if (!dgDEBUGFLOW.outputbuffer.good()) \ + ; \ + else \ + dgERRORFLOW.pre(dgERRORFLOW.tmpbuffer << dgPREERROR).trace // TEMPLATE -# define dgTDEBUG(level) \ - if ((level > VP_TEMPLATE_DEBUG_MODE) || (!dgDEBUGFLOW.outputbuffer.good ())) \ - ; \ - else \ +#define dgTDEBUG(level) \ + if ((level > VP_TEMPLATE_DEBUG_MODE) || (!dgDEBUGFLOW.outputbuffer.good())) \ + ; \ + else \ dgDEBUGFLOW.outputbuffer << dgPREDEBUG -# define dgTDEBUGF \ - if (!dgDEBUGFLOW.outputbuffer.good ()) \ - ; \ - else \ - dgDEBUGFLOW.pre \ - (dgDEBUGFLOW.tmpbuffer << dgPREDEBUG, VP_TEMPLATE_DEBUG_MODE).trace +#define dgTDEBUGF \ + if (!dgDEBUGFLOW.outputbuffer.good()) \ + ; \ + else \ + dgDEBUGFLOW.pre(dgDEBUGFLOW.tmpbuffer << dgPREDEBUG, VP_TEMPLATE_DEBUG_MODE).trace -inline bool dgDEBUG_ENABLE (const int & level) -{ - return level<=VP_DEBUG_MODE; -} +inline bool dgDEBUG_ENABLE(const int& level) { return level <= VP_DEBUG_MODE; } -inline bool dgTDEBUG_ENABLE (const int & level) -{ - return level<=VP_TEMPLATE_DEBUG_MODE; -} +inline bool dgTDEBUG_ENABLE(const int& level) { return level <= VP_TEMPLATE_DEBUG_MODE; } -# else // VP_DEBUG +#else // VP_DEBUG -# define dgPREERROR \ - "\t!! "<<__FILE__ << ": " <<__FUNCTION__ << "(#" << __LINE__ << ") :" +#define dgPREERROR "\t!! " << __FILE__ << ": " << __FUNCTION__ << "(#" << __LINE__ << ") :" -# define dgDEBUG(level) \ - if (1) \ - ; \ - else \ +#define dgDEBUG(level) \ + if (1) \ + ; \ + else \ ::dynamicgraph::__null_stream() -# define dgDEBUGMUTE (level) \ - if (1) \ - ; \ - else \ - ::dynamicgraph::__null_stream() +#define dgDEBUGMUTE \ + (level) if (1); \ + else ::dynamicgraph::__null_stream() -# define dgERROR \ - dgERRORFLOW.outputbuffer << dgPREERROR +#define dgERROR dgERRORFLOW.outputbuffer << dgPREERROR -inline void dgDEBUGF (const int, const char*, ...) -{ - return; -} +inline void dgDEBUGF(const int, const char*, ...) { return; } -inline void dgDEBUGF (const char*, ...) -{ - return; -} +inline void dgDEBUGF(const char*, ...) { return; } -inline void dgERRORF (const int, const char*, ...) -{ - return; -} +inline void dgERRORF(const int, const char*, ...) { return; } -inline void dgERRORF (const char*, ...) -{ - return; -} +inline void dgERRORF(const char*, ...) { return; } -namespace dynamicgraph -{ -inline std::ostream& __null_stream () -{ +namespace dynamicgraph { +inline std::ostream& __null_stream() { // This function should never be called. With -O3, // it should not appear in the generated binary. - static std::ostream os (NULL); return os; + static std::ostream os(NULL); + return os; } -} - +} // namespace dynamicgraph // TEMPLATE -# define dgTDEBUG(level) \ - if (1) \ - ; \ - else \ +#define dgTDEBUG(level) \ + if (1) \ + ; \ + else \ ::dynamicgraph::__null_stream() -inline void dgTDEBUGF (const int, const char*, ...) -{ - return; -} - -inline void dgTDEBUGF (const char*, ...) -{ - return; -} +inline void dgTDEBUGF(const int, const char*, ...) { return; } -# define dgDEBUG_ENABLE(level) false -# define dgTDEBUG_ENABLE(level) false +inline void dgTDEBUGF(const char*, ...) { return; } -# endif //! VP_DEBUG +#define dgDEBUG_ENABLE(level) false +#define dgTDEBUG_ENABLE(level) false -# define dgDEBUGIN(level) \ - dgDEBUG(level) << "# In {" << std::endl +#endif //! VP_DEBUG -# define dgDEBUGOUT(level) \ - dgDEBUG(level) << "# Out }" << std::endl +#define dgDEBUGIN(level) dgDEBUG(level) << "# In {" << std::endl -# define dgDEBUGINOUT(level) \ - dgDEBUG(level) << "# In/Out { }" << std::endl +#define dgDEBUGOUT(level) dgDEBUG(level) << "# Out }" << std::endl +#define dgDEBUGINOUT(level) dgDEBUG(level) << "# In/Out { }" << std::endl -# define dgTDEBUGIN(level) \ - dgTDEBUG(level) << "# In {" << std::endl +#define dgTDEBUGIN(level) dgTDEBUG(level) << "# In {" << std::endl -# define dgTDEBUGOUT(level) \ - dgTDEBUG(level) << "# Out }" << std::endl +#define dgTDEBUGOUT(level) dgTDEBUG(level) << "# Out }" << std::endl -# define dgTDEBUGINOUT(level) \ - dgTDEBUG(level) << "# In/Out { }" << std::endl +#define dgTDEBUGINOUT(level) dgTDEBUG(level) << "# In/Out { }" << std::endl -#endif //! DYNAMIC_GRAPH_DEBUG_HH +#endif //! DYNAMIC_GRAPH_DEBUG_HH diff --git a/include/dynamic-graph/dynamic-graph-api.h b/include/dynamic-graph/dynamic-graph-api.h index 69dff1d9be4f30a544a7b93f7f7a54111f424440..88e281d4140c063ca18cd91a210dc6927a5750e8 100644 --- a/include/dynamic-graph/dynamic-graph-api.h +++ b/include/dynamic-graph/dynamic-graph-api.h @@ -4,6 +4,6 @@ // #ifndef DYNAMIC_GRAPH_API_H -# define DYNAMIC_GRAPH_API_H -# include <dynamic-graph/config.hh> -#endif //! DYNAMIC_GRAPH_API_H +#define DYNAMIC_GRAPH_API_H +#include <dynamic-graph/config.hh> +#endif //! DYNAMIC_GRAPH_API_H diff --git a/include/dynamic-graph/eigen-io.h b/include/dynamic-graph/eigen-io.h index 4198b52f23a3486f88b81bbf3bb484387495dec4..9184e7726ecf8e9035999354c604ae06a522f27b 100644 --- a/include/dynamic-graph/eigen-io.h +++ b/include/dynamic-graph/eigen-io.h @@ -16,148 +16,135 @@ using dynamicgraph::ExceptionSignal; -//TODO: Eigen 3.3 onwards has a global Eigen::Index definition. -//If Eigen version is updated, use Eigen::Index instead of this macro. - - - /* \brief Eigen Vector input from istream - * - * Input Vector format: [N](val1,val2,val3,...,valN) - * e.g. [5](1,23,32.2,12.12,32) - */ +// TODO: Eigen 3.3 onwards has a global Eigen::Index definition. +// If Eigen version is updated, use Eigen::Index instead of this macro. + +/* \brief Eigen Vector input from istream + * + * Input Vector format: [N](val1,val2,val3,...,valN) + * e.g. [5](1,23,32.2,12.12,32) + */ namespace Eigen { - typedef EIGEN_DEFAULT_DENSE_INDEX_TYPE eigen_index; - - inline std::istringstream& operator >> (std::istringstream &iss, - dynamicgraph::Vector &inst) { - unsigned int _size; - double _dbl_val; - char _ch; - boost::format fmt ("Failed to enter %s as vector. Reenter as [N](val1,val2,val3,...,valN)"); - fmt %iss.str(); - if(iss>> _ch && _ch != '['){ +typedef EIGEN_DEFAULT_DENSE_INDEX_TYPE eigen_index; + +inline std::istringstream &operator>>(std::istringstream &iss, dynamicgraph::Vector &inst) { + unsigned int _size; + double _dbl_val; + char _ch; + boost::format fmt("Failed to enter %s as vector. Reenter as [N](val1,val2,val3,...,valN)"); + fmt % iss.str(); + if (iss >> _ch && _ch != '[') { + throw ExceptionSignal(ExceptionSignal::GENERIC, fmt.str()); + } else { + if (iss >> _size && !iss.fail()) { + inst.resize(_size); + } else + throw ExceptionSignal(ExceptionSignal::GENERIC, fmt.str()); + if (iss >> _ch && _ch != ']') throw ExceptionSignal(ExceptionSignal::GENERIC, fmt.str()); - } else { - if(iss >> _size && !iss.fail()){ - inst.resize(_size); - } - else - throw ExceptionSignal(ExceptionSignal::GENERIC, fmt.str()); - if(iss >> _ch && _ch != ']') - throw ExceptionSignal(ExceptionSignal::GENERIC, fmt.str()); + if (iss >> _ch && _ch != '(') + throw ExceptionSignal(ExceptionSignal::GENERIC, fmt.str()); else { - if(iss>> _ch && _ch != '(') - throw ExceptionSignal(ExceptionSignal::GENERIC, fmt.str()); - else { - for (unsigned int i=0;i<_size; i++){ - iss >> _dbl_val; - if (iss.peek() == ',' || iss.peek() == ' ') - iss.ignore(); - inst(i) = _dbl_val; - } - if(iss >> _ch && _ch != ')') - throw ExceptionSignal(ExceptionSignal::GENERIC, fmt.str()); - } + for (unsigned int i = 0; i < _size; i++) { + iss >> _dbl_val; + if (iss.peek() == ',' || iss.peek() == ' ') iss.ignore(); + inst(i) = _dbl_val; + } + if (iss >> _ch && _ch != ')') throw ExceptionSignal(ExceptionSignal::GENERIC, fmt.str()); } } - return iss; } + return iss; +} - /* \brief Eigen Matrix input from istream - * - * Matrix format: [M,N]((val11,val12,val13,...,val1N),...,(valM1,valM2,...,valMN)) - * e.g. [2,5]((1 23 32.2 12.12 32),(2 32 23 92.01 19.2)) - */ - - template<typename Derived> - inline std::istringstream& operator >> (std::istringstream &iss, - DenseBase<Derived> &inst) { - unsigned int _colsize; - unsigned int _rowsize; - double _dbl_val; - char _ch; - boost::format fmt ("Failed to enter %s as matrix. Reenter as ((val11,val12,val13,...,val1N),...,(valM1,valM2,...,valMN))"); - MatrixXd _tmp_matrix; - fmt %iss.str(); - if(iss>> _ch && _ch != '['){ +/* \brief Eigen Matrix input from istream + * + * Matrix format: [M,N]((val11,val12,val13,...,val1N),...,(valM1,valM2,...,valMN)) + * e.g. [2,5]((1 23 32.2 12.12 32),(2 32 23 92.01 19.2)) + */ + +template <typename Derived> +inline std::istringstream &operator>>(std::istringstream &iss, DenseBase<Derived> &inst) { + unsigned int _colsize; + unsigned int _rowsize; + double _dbl_val; + char _ch; + boost::format fmt( + "Failed to enter %s as matrix. Reenter as ((val11,val12,val13,...,val1N),...,(valM1,valM2,...,valMN))"); + MatrixXd _tmp_matrix; + fmt % iss.str(); + if (iss >> _ch && _ch != '[') { + throw ExceptionSignal(ExceptionSignal::GENERIC, fmt.str()); + } else { + iss >> _rowsize; + if (iss.peek() == ',' || iss.peek() == ' ') iss.ignore(); + iss >> _colsize; + if (iss.fail()) throw ExceptionSignal(ExceptionSignal::GENERIC, fmt.str()); - } else { - iss >>_rowsize; - if (iss.peek() == ',' || iss.peek() == ' ') - iss.ignore(); - iss >> _colsize; - if (iss.fail()) - throw ExceptionSignal(ExceptionSignal::GENERIC,fmt.str()); + _tmp_matrix.resize(_rowsize, _colsize); + if (iss >> _ch && _ch != ']') + throw ExceptionSignal(ExceptionSignal::GENERIC, fmt.str()); else { - _tmp_matrix.resize(_rowsize,_colsize); - if(iss >> _ch && _ch != ']') - throw ExceptionSignal(ExceptionSignal::GENERIC, fmt.str()); - else { - if(iss>> _ch && _ch != '(') - throw ExceptionSignal(ExceptionSignal::GENERIC, fmt.str()); - else { - for (unsigned int j=0;j<_rowsize; j++){ - if(iss>> _ch && _ch != '(') - throw ExceptionSignal(ExceptionSignal::GENERIC, fmt.str()); - for (unsigned int i=0;i<_colsize; i++){ - iss >> _dbl_val; - if (iss.peek() == ',' || iss.peek() == ' ') - iss.ignore(); - _tmp_matrix(j,i) = _dbl_val; - } - if(iss >> _ch && _ch != ')') - throw ExceptionSignal(ExceptionSignal::GENERIC, fmt.str()); - if (iss.peek() == ',' || iss.peek() == ' ') - iss.ignore(); - } - if(iss >> _ch && _ch != ')') - throw ExceptionSignal(ExceptionSignal::GENERIC, fmt.str()); - } - } + if (iss >> _ch && _ch != '(') + throw ExceptionSignal(ExceptionSignal::GENERIC, fmt.str()); + else { + for (unsigned int j = 0; j < _rowsize; j++) { + if (iss >> _ch && _ch != '(') throw ExceptionSignal(ExceptionSignal::GENERIC, fmt.str()); + for (unsigned int i = 0; i < _colsize; i++) { + iss >> _dbl_val; + if (iss.peek() == ',' || iss.peek() == ' ') iss.ignore(); + _tmp_matrix(j, i) = _dbl_val; + } + if (iss >> _ch && _ch != ')') throw ExceptionSignal(ExceptionSignal::GENERIC, fmt.str()); + if (iss.peek() == ',' || iss.peek() == ' ') iss.ignore(); + } + if (iss >> _ch && _ch != ')') throw ExceptionSignal(ExceptionSignal::GENERIC, fmt.str()); + } } } - inst = _tmp_matrix; - return iss; } + inst = _tmp_matrix; + return iss; +} +inline std::istringstream &operator>>(std::istringstream &iss, Transform<double, 3, Affine> &inst) { + MatrixXd M; + iss >> M; + inst.matrix() = M; + return iss; +} - inline std::istringstream& operator >> (std::istringstream &iss, - Transform<double,3,Affine> &inst) { - MatrixXd M; iss >> M; inst.matrix() = M; return iss; } - - - - - /* \brief Eigen Homogeneous Matrix output - * - * Matrix format: [M,N]((val11,val12,val13,...,val1N),...,(valM1,valM2,...,valMN)) - * e.g. [2,5]((1 23 32.2 12.12 32),(2 32 23 92.01 19.2)) - */ - - inline std::ostream& operator << (std::ostream &os, - Transform<double,3,Affine> MH) { - IOFormat boostFmt(StreamPrecision, DontAlignCols, - ",", ",", - "(",")", - "(",")"); - - os << "[4,4]"<< MH.matrix().format(boostFmt); return os; } +/* \brief Eigen Homogeneous Matrix output + * + * Matrix format: [M,N]((val11,val12,val13,...,val1N),...,(valM1,valM2,...,valMN)) + * e.g. [2,5]((1 23 32.2 12.12 32),(2 32 23 92.01 19.2)) + */ +inline std::ostream &operator<<(std::ostream &os, Transform<double, 3, Affine> MH) { + IOFormat boostFmt(StreamPrecision, DontAlignCols, ",", ",", "(", ")", "(", ")"); - inline std::ostream& operator << (std::ostream &os, - AngleAxisd quat) { - VectorXd v(4); v(0) = quat.angle(); v.tail<3>() = quat.axis(); - os << v; return os; } + os << "[4,4]" << MH.matrix().format(boostFmt); + return os; +} - inline std::istringstream& operator >> (std::istringstream &iss, - AngleAxisd &inst) { - VectorXd v(4); iss >>v; - inst.angle() = v(0); inst.axis() = v.tail<3>(); - return iss; } +inline std::ostream &operator<<(std::ostream &os, AngleAxisd quat) { + VectorXd v(4); + v(0) = quat.angle(); + v.tail<3>() = quat.axis(); + os << v; + return os; +} +inline std::istringstream &operator>>(std::istringstream &iss, AngleAxisd &inst) { + VectorXd v(4); + iss >> v; + inst.angle() = v(0); + inst.axis() = v.tail<3>(); + return iss; } +} // namespace Eigen -#endif //DYNAMIC_GRAPH_EIGEN_IO_H +#endif // DYNAMIC_GRAPH_EIGEN_IO_H diff --git a/include/dynamic-graph/entity-helper.h b/include/dynamic-graph/entity-helper.h index 15fc8d8804a3f946deaaf06a056caab4a9fec6c7..4be1b51f6585f581b8a0106b47b03055f2697c2a 100644 --- a/include/dynamic-graph/entity-helper.h +++ b/include/dynamic-graph/entity-helper.h @@ -6,17 +6,14 @@ #ifndef __sot_core_entity_helper_H__ #define __sot_core_entity_helper_H__ +namespace dynamicgraph { -namespace dynamicgraph -{ +template <typename Ent> +struct EntityHelper { + typedef Ent EntityClassName; + // static const std::string CLASS_NAME; TO BE ADDED IN DG DIRECTLY +}; - template< typename Ent > - struct EntityHelper - { - typedef Ent EntityClassName; - //static const std::string CLASS_NAME; TO BE ADDED IN DG DIRECTLY - }; +} // namespace dynamicgraph -} // namespace dynamicgraph - -#endif // __sot_core_entity_helper_H__ +#endif // __sot_core_entity_helper_H__ diff --git a/include/dynamic-graph/entity.h b/include/dynamic-graph/entity.h index 1db47a3796efa14964594e79dab6bf968d5bc206..b534d9c2e07e91978af0888c35341e794950dd11 100644 --- a/include/dynamic-graph/entity.h +++ b/include/dynamic-graph/entity.h @@ -4,20 +4,20 @@ // #ifndef DYNAMIC_GRAPH_ENTITY_H -# define DYNAMIC_GRAPH_ENTITY_H -# include <iosfwd> -# include <map> -# include <sstream> -# include <string> +#define DYNAMIC_GRAPH_ENTITY_H +#include <iosfwd> +#include <map> +#include <sstream> +#include <string> -# include <boost/noncopyable.hpp> +#include <boost/noncopyable.hpp> -# include <dynamic-graph/fwd.hh> -# include <dynamic-graph/dynamic-graph-api.h> -# include <dynamic-graph/exception-factory.h> -# include <dynamic-graph/signal-array.h> -# include <dynamic-graph/signal-base.h> -# include <dynamic-graph/logger.h> +#include <dynamic-graph/fwd.hh> +#include <dynamic-graph/dynamic-graph-api.h> +#include <dynamic-graph/exception-factory.h> +#include <dynamic-graph/signal-array.h> +#include <dynamic-graph/signal-base.h> +#include <dynamic-graph/logger.h> /// \brief Helper macro for entity declaration. /// @@ -36,117 +36,92 @@ /// Caution: you *MUST* call DYNAMICGRAPH_FACTORY_ENTITY_PLUGIN in the /// associated source file to ensure that the attributes generated by /// this macro are correctly initialized. -# define DYNAMIC_GRAPH_ENTITY_DECL() \ - public: \ - virtual const std::string& getClassName () const \ - { \ - return CLASS_NAME; \ - } \ +#define DYNAMIC_GRAPH_ENTITY_DECL() \ + public: \ + virtual const std::string& getClassName() const { return CLASS_NAME; } \ static const std::string CLASS_NAME -namespace dynamicgraph -{ - /// \ingroup dgraph - /// - /// \brief This class represents an entity, i.e. a generic - /// computational unit that provides input and output signals. - /// - /// These signals link the entities together to form a complete - /// computation graph. To declare a new entity, please see the - /// DYNAMICGRAPH_FACTORY_ENTITY_PLUGIN macro in factory.h. - class DYNAMIC_GRAPH_DLLAPI Entity : private boost::noncopyable - { - public: - typedef std::map< std::string,SignalBase<int>* > SignalMap; - typedef std::map<const std::string, command::Command*> CommandMap_t; - - explicit Entity (const std::string& name); - virtual ~Entity (); - - const std::string& getName () const - { - return name; - } - virtual const std::string& getClassName () const - { - static std::string ret("Entity"); - return ret; - } - virtual std::string getDocString () const; - bool hasSignal( const std::string & signame ) const; - SignalBase<int>& getSignal (const std::string& signalName); - const SignalBase<int>& getSignal (const std::string& signalName) const; - std::ostream& displaySignalList(std::ostream& os) const; - virtual std::ostream& writeGraph (std::ostream& os) const; - virtual std::ostream& writeCompletionList (std::ostream& os) const; - - virtual void display (std::ostream& os) const; - - virtual SignalBase<int>* test () - { - return 0; - } - - virtual void test2 (SignalBase<int>*) - { - return ; - } - - const std::string& getCommandList () const; - CommandMap_t getNewStyleCommandMap(); - command::Command* getNewStyleCommand( const std::string& cmdName ); - - SignalMap getSignalMap() const; - - /** \name Logger related methods */ - /** \{*/ - /// \brief Send messages \param msg with level t. Add string file and line to message. - void sendMsg(const std::string &msg, - MsgType t=MSG_TYPE_INFO, - const char *file="", - int line=0); - - /// \brief Specify the verbosity level of the logger. - void setLoggerVerbosityLevel(LoggerVerbosity lv) - {logger_.setVerbosity(lv);} - - /// \brief Get the logger's verbosity level. - LoggerVerbosity getLoggerVerbosityLevel() - { return logger_.getVerbosity(); } - - /// \brief Set the time sample. - bool setTimeSample(double t) - { return logger_.setTimeSample(t); } - - /// \brief Get the time sample. - double getTimeSample() - { return logger_.getTimeSample();} - - /// \brief Set the period of the stream period - bool setStreamPrintPeriod(double t) - { return logger_.setStreamPrintPeriod(t); } - - /// \brief Get the period of the stream period - double getStreamPrintPeriod() - { return logger_.getStreamPrintPeriod();} - - protected: - void addCommand(const std::string& name,command::Command* command); - - void entityRegistration (); - void entityDeregistration (); - - void signalRegistration (const SignalArray<int>& signals); - void signalDeregistration (const std::string& name); - - std::string name; - SignalMap signalMap; - CommandMap_t commandMap; - Logger logger_; - }; - - DYNAMIC_GRAPH_DLLAPI std::ostream& - operator<< (std::ostream& os, const dynamicgraph::Entity& ent); -} // end of namespace dynamicgraph - -#endif //! DYNAMIC_GRAPH_ENTITY_H +namespace dynamicgraph { +/// \ingroup dgraph +/// +/// \brief This class represents an entity, i.e. a generic +/// computational unit that provides input and output signals. +/// +/// These signals link the entities together to form a complete +/// computation graph. To declare a new entity, please see the +/// DYNAMICGRAPH_FACTORY_ENTITY_PLUGIN macro in factory.h. +class DYNAMIC_GRAPH_DLLAPI Entity : private boost::noncopyable { + public: + typedef std::map<std::string, SignalBase<int>*> SignalMap; + typedef std::map<const std::string, command::Command*> CommandMap_t; + + explicit Entity(const std::string& name); + virtual ~Entity(); + + const std::string& getName() const { return name; } + virtual const std::string& getClassName() const { + static std::string ret("Entity"); + return ret; + } + virtual std::string getDocString() const; + bool hasSignal(const std::string& signame) const; + SignalBase<int>& getSignal(const std::string& signalName); + const SignalBase<int>& getSignal(const std::string& signalName) const; + std::ostream& displaySignalList(std::ostream& os) const; + virtual std::ostream& writeGraph(std::ostream& os) const; + virtual std::ostream& writeCompletionList(std::ostream& os) const; + + virtual void display(std::ostream& os) const; + + virtual SignalBase<int>* test() { return 0; } + + virtual void test2(SignalBase<int>*) { return; } + + const std::string& getCommandList() const; + CommandMap_t getNewStyleCommandMap(); + command::Command* getNewStyleCommand(const std::string& cmdName); + + SignalMap getSignalMap() const; + + /** \name Logger related methods */ + /** \{*/ + /// \brief Send messages \param msg with level t. Add string file and line to message. + void sendMsg(const std::string& msg, MsgType t = MSG_TYPE_INFO, const char* file = "", int line = 0); + + /// \brief Specify the verbosity level of the logger. + void setLoggerVerbosityLevel(LoggerVerbosity lv) { logger_.setVerbosity(lv); } + + /// \brief Get the logger's verbosity level. + LoggerVerbosity getLoggerVerbosityLevel() { return logger_.getVerbosity(); } + + /// \brief Set the time sample. + bool setTimeSample(double t) { return logger_.setTimeSample(t); } + + /// \brief Get the time sample. + double getTimeSample() { return logger_.getTimeSample(); } + + /// \brief Set the period of the stream period + bool setStreamPrintPeriod(double t) { return logger_.setStreamPrintPeriod(t); } + + /// \brief Get the period of the stream period + double getStreamPrintPeriod() { return logger_.getStreamPrintPeriod(); } + + protected: + void addCommand(const std::string& name, command::Command* command); + + void entityRegistration(); + void entityDeregistration(); + + void signalRegistration(const SignalArray<int>& signals); + void signalDeregistration(const std::string& name); + + std::string name; + SignalMap signalMap; + CommandMap_t commandMap; + Logger logger_; +}; + +DYNAMIC_GRAPH_DLLAPI std::ostream& operator<<(std::ostream& os, const dynamicgraph::Entity& ent); +} // end of namespace dynamicgraph + +#endif //! DYNAMIC_GRAPH_ENTITY_H diff --git a/include/dynamic-graph/exception-abstract.h b/include/dynamic-graph/exception-abstract.h index 3e1bf4c1540843575b6549d921fedeeff0948624..4d60e1344ed7b896d8b43d8b42976bb2a655f64e 100644 --- a/include/dynamic-graph/exception-abstract.h +++ b/include/dynamic-graph/exception-abstract.h @@ -4,154 +4,116 @@ // #ifndef DYNAMIC_GRAPH_EXCEPTION_ABSTRACT_H -# define DYNAMIC_GRAPH_EXCEPTION_ABSTRACT_H -# include <string> +#define DYNAMIC_GRAPH_EXCEPTION_ABSTRACT_H +#include <string> -# include <dynamic-graph/fwd.hh> -# include <dynamic-graph/dynamic-graph-api.h> +#include <dynamic-graph/fwd.hh> +#include <dynamic-graph/dynamic-graph-api.h> // Uncomment this macros to have lines parameter on the throw display // #define DYNAMIC-GRAPH_EXCEPTION_PASSING_PARAM -# define DG_RETHROW \ - (const ::dynamicgraph::ExceptionAbstract& err) \ - { \ - throw err; \ - } +#define DG_RETHROW \ + (const ::dynamicgraph::ExceptionAbstract& err) { throw err; } + +#ifdef DYNAMICGRAPH_EXCEPTION_PASSING_PARAM +#define DG_THROW throw ::dynamicgraph::ExceptionAbstract::Param(__LINE__, __FUNCTION__, __FILE__) + +#else +#define DG_THROW throw +#endif // DYNAMICGRAPH_EXCEPTION_PASSING_PARAM + +namespace dynamicgraph { +/// \ingroup error +/// +/// \brief Abstract root class for all dynamic-graph exceptions. +class DYNAMIC_GRAPH_DLLAPI ExceptionAbstract : public std::exception { + public: + /// \ingroup error + /// + /// \brief Class owned by exceptions to store error locations. + class Param { + public: + static const int BUFFER_SIZE = 80; + + Param(const int& _line, const char* _function, const char* _file); + Param() : functionPTR(), function(), line(), filePTR(), file(), pointersSet(false), set(false) {} + Param& initCopy(const Param& p); + + const char* functionPTR; + char function[BUFFER_SIZE]; + int line; + const char* filePTR; + char file[BUFFER_SIZE]; + bool pointersSet; + bool set; + }; + + /// \brief Categories error code. + /// + /// Each value matches categories used by a subclass of + /// ExceptionAbstract. + /// + /// This is the programmer responsibility to make sure there is + /// enough room between two categories error code. + enum ExceptionEnum { ABSTRACT = 0, SIGNAL = 100, FACTORY = 200, TRACES = 300, TOOLS = 700 }; -# ifdef DYNAMICGRAPH_EXCEPTION_PASSING_PARAM -# define DG_THROW \ - throw ::dynamicgraph::ExceptionAbstract::Param \ - (__LINE__, __FUNCTION__, __FILE__) + -# else -# define DG_THROW \ - throw -# endif // DYNAMICGRAPH_EXCEPTION_PASSING_PARAM + static const std::string EXCEPTION_NAME; + explicit ExceptionAbstract(const int& code, const std::string& msg = ""); + virtual ~ExceptionAbstract() throw() {} -namespace dynamicgraph -{ - /// \ingroup error + virtual const std::string& getExceptionName() const { return EXCEPTION_NAME; } + + /// \brief Access to the error code. + int getCode() const; + + /// \brief Reference access to the error message (can be empty). + const std::string& getStringMessage() const; + + /// \brief Access to the pointer on the array of \e char related + /// to the error string. /// - /// \brief Abstract root class for all dynamic-graph exceptions. - class DYNAMIC_GRAPH_DLLAPI ExceptionAbstract : public std::exception - { - public: - /// \ingroup error - /// - /// \brief Class owned by exceptions to store error locations. - class Param - { - public: - static const int BUFFER_SIZE = 80; - - Param (const int& _line, const char* _function, const char* _file); - Param () - : functionPTR (), - function (), - line (), - filePTR (), - file (), - pointersSet (false), - set (false) - {} - Param& initCopy (const Param& p); - - const char* functionPTR; - char function[BUFFER_SIZE]; - int line; - const char* filePTR; - char file[BUFFER_SIZE]; - bool pointersSet; - bool set; - }; - - /// \brief Categories error code. - /// - /// Each value matches categories used by a subclass of - /// ExceptionAbstract. - /// - /// This is the programmer responsibility to make sure there is - /// enough room between two categories error code. - enum ExceptionEnum - { - ABSTRACT = 0, - SIGNAL = 100, - FACTORY = 200, - TRACES = 300, - TOOLS = 700 - }; - - static const std::string EXCEPTION_NAME; - - explicit ExceptionAbstract (const int& code, const std::string& msg = ""); - virtual ~ExceptionAbstract () throw () - {} - - virtual const std::string& getExceptionName () const - { - return EXCEPTION_NAME; - } - - /// \brief Access to the error code. - int getCode () const; - - /// \brief Reference access to the error message (can be empty). - const std::string& getStringMessage () const; - - /// \brief Access to the pointer on the array of \e char related - /// to the error string. - /// - /// Cannot be \e NULL. - const char* getMessage () const; - - virtual const char* what () const throw () - { - return getStringMessage ().c_str (); - } - - /// \brief Print the error structure. - DYNAMIC_GRAPH_DLLAPI friend std::ostream& - operator << (std::ostream & os, const ExceptionAbstract & err); - - - protected: - /// \brief Error code. - /// \sa ErrorCodeEnum - int code; - - /// \brief Error message (can be empty). - std::string message; - -# ifdef DYNAMICGRAPH_EXCEPTION_PASSING_PARAM - /// \brief Optional mutable attribute to store exception location. - /// - /// Only present if DYNAMICGRAPH_EXCEPTION_PASSING_PARAM - /// preprocessor symbol exists. - mutable Param p; - - template<class Exc> - friend const Exc& - operator+ (const ExceptionAbstract::Param& p, const Exc& e) - { - e.p.initCopy(p); - return e; - } - - template<class Exc> - friend Exc& - operator+ (const ExceptionAbstract::Param& p, Exc& e) - { - e.p.initCopy (p); - return e; - } - -# endif // DYNAMICGRAPH_EXCEPTION_PASSING_PARAM - - private: - /// \brief Forbid the empty constructor (private). - ExceptionAbstract (); - }; -} // end of namespace dynamicgraph + /// Cannot be \e NULL. + const char* getMessage() const; + + virtual const char* what() const throw() { return getStringMessage().c_str(); } + + /// \brief Print the error structure. + DYNAMIC_GRAPH_DLLAPI friend std::ostream& operator<<(std::ostream& os, const ExceptionAbstract& err); + + protected: + /// \brief Error code. + /// \sa ErrorCodeEnum + int code; + + /// \brief Error message (can be empty). + std::string message; + +#ifdef DYNAMICGRAPH_EXCEPTION_PASSING_PARAM + /// \brief Optional mutable attribute to store exception location. + /// + /// Only present if DYNAMICGRAPH_EXCEPTION_PASSING_PARAM + /// preprocessor symbol exists. + mutable Param p; + + template <class Exc> + friend const Exc& operator+(const ExceptionAbstract::Param& p, const Exc& e) { + e.p.initCopy(p); + return e; + } + + template <class Exc> + friend Exc& operator+(const ExceptionAbstract::Param& p, Exc& e) { + e.p.initCopy(p); + return e; + } + +#endif // DYNAMICGRAPH_EXCEPTION_PASSING_PARAM + + private: + /// \brief Forbid the empty constructor (private). + ExceptionAbstract(); +}; +} // end of namespace dynamicgraph -#endif //! DYNAMIC_GRAPH_EXCEPTION_ABSTRACT_H +#endif //! DYNAMIC_GRAPH_EXCEPTION_ABSTRACT_H diff --git a/include/dynamic-graph/exception-factory.h b/include/dynamic-graph/exception-factory.h index 836b15a666c1efc6882651a49b3fd8869c454b45..2813a95118ecffcf07ead347627622f972e5df19 100644 --- a/include/dynamic-graph/exception-factory.h +++ b/include/dynamic-graph/exception-factory.h @@ -4,51 +4,42 @@ // #ifndef DYNAMIC_GRAPH_EXCEPTION_FACTORY_H -# define DYNAMIC_GRAPH_EXCEPTION_FACTORY_H -# include <string> - -# include <dynamic-graph/fwd.hh> -# include <dynamic-graph/dynamic-graph-api.h> -# include <dynamic-graph/exception-abstract.h> - -namespace dynamicgraph -{ - /// \ingroup error - /// - /// \brief Generic error class. - class DYNAMIC_GRAPH_DLLAPI ExceptionFactory : public ExceptionAbstract - { - public: - enum ErrorCodeEnum - { - GENERIC = ExceptionAbstract::FACTORY - ,UNREFERED_OBJECT - ,UNREFERED_SIGNAL - ,UNREFERED_FUNCTION - ,DYNAMIC_LOADING - ,SIGNAL_CONFLICT - ,FUNCTION_CONFLICT - ,OBJECT_CONFLICT - ,SYNTAX_ERROR - ,READ_FILE - }; - - static const std::string EXCEPTION_NAME; - - explicit ExceptionFactory (const ExceptionFactory::ErrorCodeEnum& errcode, - const std::string & msg = ""); - - ExceptionFactory (const ExceptionFactory::ErrorCodeEnum& errcode, - const std::string& msg, const char* format, ...); - - virtual ~ExceptionFactory () throw () - {} - - virtual const std::string& getExceptionName () const - { - return ExceptionFactory::EXCEPTION_NAME; - } +#define DYNAMIC_GRAPH_EXCEPTION_FACTORY_H +#include <string> + +#include <dynamic-graph/fwd.hh> +#include <dynamic-graph/dynamic-graph-api.h> +#include <dynamic-graph/exception-abstract.h> + +namespace dynamicgraph { +/// \ingroup error +/// +/// \brief Generic error class. +class DYNAMIC_GRAPH_DLLAPI ExceptionFactory : public ExceptionAbstract { + public: + enum ErrorCodeEnum { + GENERIC = ExceptionAbstract::FACTORY, + UNREFERED_OBJECT, + UNREFERED_SIGNAL, + UNREFERED_FUNCTION, + DYNAMIC_LOADING, + SIGNAL_CONFLICT, + FUNCTION_CONFLICT, + OBJECT_CONFLICT, + SYNTAX_ERROR, + READ_FILE }; -} // end of namespace dynamicgraph -#endif //! DYNAMIC_GRAPH_EXCEPTION_FACTORY_H + static const std::string EXCEPTION_NAME; + + explicit ExceptionFactory(const ExceptionFactory::ErrorCodeEnum& errcode, const std::string& msg = ""); + + ExceptionFactory(const ExceptionFactory::ErrorCodeEnum& errcode, const std::string& msg, const char* format, ...); + + virtual ~ExceptionFactory() throw() {} + + virtual const std::string& getExceptionName() const { return ExceptionFactory::EXCEPTION_NAME; } +}; +} // end of namespace dynamicgraph + +#endif //! DYNAMIC_GRAPH_EXCEPTION_FACTORY_H diff --git a/include/dynamic-graph/exception-signal.h b/include/dynamic-graph/exception-signal.h index abadca164561cefbe948a59d6874e2ad63beb807..b7a108c1f21c41f81613ad781c47a09c6f619c13 100644 --- a/include/dynamic-graph/exception-signal.h +++ b/include/dynamic-graph/exception-signal.h @@ -4,48 +4,40 @@ // #ifndef DYNAMIC_GRAPH_EXCEPTION_SIGNAL_H -# define DYNAMIC_GRAPH_EXCEPTION_SIGNAL_H - -# include <dynamic-graph/fwd.hh> -# include <dynamic-graph/dynamic-graph-api.h> -# include <dynamic-graph/exception-abstract.h> - -namespace dynamicgraph -{ - /// \ingroup error - /// - /// \brief Exceptions raised when an error related to signals - /// happen. - class DYNAMIC_GRAPH_DLLAPI ExceptionSignal : public ExceptionAbstract - { - public: - enum ErrorCodeEnum - { - GENERIC = ExceptionAbstract::SIGNAL - - ,READWRITE_LOCK - ,COPY_NOT_INITIALIZED - ,NOT_INITIALIZED - ,PLUG_IMPOSSIBLE - ,SET_IMPOSSIBLE - ,BAD_CAST - }; - - static const std::string EXCEPTION_NAME; - - explicit ExceptionSignal (const ExceptionSignal::ErrorCodeEnum& errcode, - const std::string & msg = "" ); - ExceptionSignal (const ExceptionSignal::ErrorCodeEnum& errcode, - const std::string & msg, const char* format, ...); - virtual ~ExceptionSignal () throw () - {} - - virtual const std::string& getExceptionName () const - { - return EXCEPTION_NAME; - } +#define DYNAMIC_GRAPH_EXCEPTION_SIGNAL_H + +#include <dynamic-graph/fwd.hh> +#include <dynamic-graph/dynamic-graph-api.h> +#include <dynamic-graph/exception-abstract.h> + +namespace dynamicgraph { +/// \ingroup error +/// +/// \brief Exceptions raised when an error related to signals +/// happen. +class DYNAMIC_GRAPH_DLLAPI ExceptionSignal : public ExceptionAbstract { + public: + enum ErrorCodeEnum { + GENERIC = ExceptionAbstract::SIGNAL + + , + READWRITE_LOCK, + COPY_NOT_INITIALIZED, + NOT_INITIALIZED, + PLUG_IMPOSSIBLE, + SET_IMPOSSIBLE, + BAD_CAST }; -} // end of namespace dynamicgraph + static const std::string EXCEPTION_NAME; -#endif //!DYNAMIC_GRAPH_EXCEPTION_SIGNAL_H + explicit ExceptionSignal(const ExceptionSignal::ErrorCodeEnum& errcode, const std::string& msg = ""); + ExceptionSignal(const ExceptionSignal::ErrorCodeEnum& errcode, const std::string& msg, const char* format, ...); + virtual ~ExceptionSignal() throw() {} + + virtual const std::string& getExceptionName() const { return EXCEPTION_NAME; } +}; + +} // end of namespace dynamicgraph + +#endif //! DYNAMIC_GRAPH_EXCEPTION_SIGNAL_H diff --git a/include/dynamic-graph/exception-traces.h b/include/dynamic-graph/exception-traces.h index 6f5c73f0ee27d76aba2b70cda0ca44639898370d..e7d559b3a8ea64dc24a65efcbafb32483c8e93e3 100644 --- a/include/dynamic-graph/exception-traces.h +++ b/include/dynamic-graph/exception-traces.h @@ -4,41 +4,29 @@ // #ifndef DYNAMIC_GRAPH_EXCEPTION_TRACES_H -# define DYNAMIC_GRAPH_EXCEPTION_TRACES_H -# include <string> +#define DYNAMIC_GRAPH_EXCEPTION_TRACES_H +#include <string> -# include <dynamic-graph/fwd.hh> -# include <dynamic-graph/dynamic-graph-api.h> -# include <dynamic-graph/exception-abstract.h> +#include <dynamic-graph/fwd.hh> +#include <dynamic-graph/dynamic-graph-api.h> +#include <dynamic-graph/exception-abstract.h> -namespace dynamicgraph -{ - /// \ingroup error - /// - /// \brief Exceptions raised when an error related to traces happen. - class DYNAMIC_GRAPH_DLLAPI ExceptionTraces : public ExceptionAbstract - { - public: - enum ErrorCodeEnum - { - GENERIC = ExceptionAbstract::TRACES - ,NOT_OPEN - }; +namespace dynamicgraph { +/// \ingroup error +/// +/// \brief Exceptions raised when an error related to traces happen. +class DYNAMIC_GRAPH_DLLAPI ExceptionTraces : public ExceptionAbstract { + public: + enum ErrorCodeEnum { GENERIC = ExceptionAbstract::TRACES, NOT_OPEN }; - static const std::string EXCEPTION_NAME; + static const std::string EXCEPTION_NAME; - explicit ExceptionTraces (const ExceptionTraces::ErrorCodeEnum& errcode, - const std::string & msg = ""); - ExceptionTraces (const ExceptionTraces::ErrorCodeEnum& errcode, - const std::string& msg, const char* format, ...); - virtual ~ExceptionTraces () throw () - {} + explicit ExceptionTraces(const ExceptionTraces::ErrorCodeEnum& errcode, const std::string& msg = ""); + ExceptionTraces(const ExceptionTraces::ErrorCodeEnum& errcode, const std::string& msg, const char* format, ...); + virtual ~ExceptionTraces() throw() {} - virtual const std::string& getExceptionName () const - { - return EXCEPTION_NAME; - } - }; -} // end of namespace dynamicgraph. + virtual const std::string& getExceptionName() const { return EXCEPTION_NAME; } +}; +} // end of namespace dynamicgraph. -#endif //! DYNAMIC_GRAPH_EXCEPTION_TRACES_H +#endif //! DYNAMIC_GRAPH_EXCEPTION_TRACES_H diff --git a/include/dynamic-graph/factory.h b/include/dynamic-graph/factory.h index 1c94fcfaa8b7fea84e9b9a45bf4e5840b8b135d9..1770689fc4b4904bc781d2ab93e163f24a0eddc5 100644 --- a/include/dynamic-graph/factory.h +++ b/include/dynamic-graph/factory.h @@ -4,16 +4,16 @@ // #ifndef DYNAMIC_GRAPH_FACTORY_HH -# define DYNAMIC_GRAPH_FACTORY_HH -# include <map> -# include <string> -# include <vector> +#define DYNAMIC_GRAPH_FACTORY_HH +#include <map> +#include <string> +#include <vector> -# include <boost/noncopyable.hpp> +#include <boost/noncopyable.hpp> -# include <dynamic-graph/fwd.hh> -# include <dynamic-graph/exception-factory.h> -# include <dynamic-graph/dynamic-graph-api.h> +#include <dynamic-graph/fwd.hh> +#include <dynamic-graph/exception-factory.h> +#include <dynamic-graph/dynamic-graph-api.h> /// \ingroup dgraph /// @@ -24,187 +24,174 @@ /// \param CLASSNAME the name of the Entity to be registered (this must /// be a std::string or a type implicitly castable into a std::string /// such as classic C string delimited by double quotes). -# define DYNAMICGRAPH_FACTORY_ENTITY_PLUGIN(CLASSTYPE, CLASSNAME) \ - const std::string CLASSTYPE::CLASS_NAME = CLASSNAME; \ - extern "C" { \ - ::dynamicgraph::Entity* \ - EntityMaker_##CLASSTYPE(const std::string& objname) \ - { \ - return new CLASSTYPE (objname); \ - } \ - ::dynamicgraph::EntityRegisterer \ - reg_##CLASSTYPE (CLASSNAME, \ - &EntityMaker_##CLASSTYPE); \ - } \ +#define DYNAMICGRAPH_FACTORY_ENTITY_PLUGIN(CLASSTYPE, CLASSNAME) \ + const std::string CLASSTYPE::CLASS_NAME = CLASSNAME; \ + extern "C" { \ + ::dynamicgraph::Entity* EntityMaker_##CLASSTYPE(const std::string& objname) { return new CLASSTYPE(objname); } \ + ::dynamicgraph::EntityRegisterer reg_##CLASSTYPE(CLASSNAME, &EntityMaker_##CLASSTYPE); \ + } \ struct e_n_d__w_i_t_h__s_e_m_i_c_o_l_o_n +namespace dynamicgraph { +/// \ingroup dgraph +/// +/// \brief Provides a way to create Entity objects from their class +/// name. +/// +/// The dynamic graph frameworks relies on entities (see Entity) +/// which defines atomic processing units. This class provides a +/// robust way to enumerate and instantiate these entities. +/// Each entity has a name (its type name) and can be instantiated. +/// Each instance also has a name. +/// +/// For instance one can define a C++ class called MyEntity which +/// inherits from dynamicgraph::Entity. This type can be registered +/// into the factory to teach the framework that: +/// - this entity exists +/// - this entity can be instantiated (and how to instantiate it). +/// +/// To achieve this, one must pass an entity name and a function pointer. +/// +/// The entity name will identify the class <b>at run-time</b> +/// (be careful: this may not be equivalent to the C++ class name +/// even if it is recommended to do so). +/// +/// The function pointer must point on a function taking a string as +/// input and returning an instance of the Entity (the concrete +/// subclass, not directly the upper Entity class). +/// +/// The instances returned by this function <b>must</b> be +/// dynamically allocated and the caller <b>must</b> get the +/// ownership of the instance (i.e. it will free it when required). +/// +/// To finish, please note that the instance name indicates to the +/// entity how the instance itself is called at run-time. This name +/// does not need to be unique and no check is done on it. It is +/// the caller responsibility to make sure that the instance name is +/// appropriate and to check for uniqueness if required. +/// +/// +/// This class is a singleton. The rationale is that each +/// unique name must identify a unique Entity. The use of a single +/// instance of this class enforces this behavior, instantiating one +/// yourself would break this property. +class DYNAMIC_GRAPH_DLLAPI FactoryStorage : private boost::noncopyable { + public: + /// \brief Function pointer providing an entity instance from its + /// name. + typedef Entity* (*EntityConstructor_ptr)(const std::string&); -namespace dynamicgraph -{ - /// \ingroup dgraph + ~FactoryStorage(); + + /// \brief Get pointer to unique object of the class + static FactoryStorage* getInstance(); + + /// \brief Destroy the unique instance of the class + static void destroy(); + + /// \brief Add a new entity to the factory. /// - /// \brief Provides a way to create Entity objects from their class - /// name. + /// It is not allowed to have several entities using the same + /// name. If this is the case, an ExceptionFactory exception will + /// be raised with the code OBJECT_CONFLICT. /// - /// The dynamic graph frameworks relies on entities (see Entity) - /// which defines atomic processing units. This class provides a - /// robust way to enumerate and instantiate these entities. - /// Each entity has a name (its type name) and can be instantiated. - /// Each instance also has a name. + /// If the function pointer is null, an ExceptionFactory exception + /// will be raised with the code OBJECT_CONFLICT. /// - /// For instance one can define a C++ class called MyEntity which - /// inherits from dynamicgraph::Entity. This type can be registered - /// into the factory to teach the framework that: - /// - this entity exists - /// - this entity can be instantiated (and how to instantiate it). + /// \param entname the name used to subscribe the entity. + /// \param ent pointer to a function allocating an entity from an + /// instance name. + void registerEntity(const std::string& entname, EntityConstructor_ptr ent); + + /// \brief Delete an entity from the factory. + /// + /// If the provided entity name does not exist in the factory, + /// an ExceptionFactory exception will be raised with the code + /// OBJECT_CONFLICT. + /// + /// \param entname the entity name (as passed to registerEntity before) + void deregisterEntity(const std::string& entname); + + /// \brief Instantiate (and allocate) an entity. /// - /// To achieve this, one must pass an entity name and a function pointer. + /// An instance called objname of the entity which type is classname + /// will be allocated by this method. /// - /// The entity name will identify the class <b>at run-time</b> - /// (be careful: this may not be equivalent to the C++ class name - /// even if it is recommended to do so). + /// It is <b>the caller</b> responsibility to free the + /// returned object. /// - /// The function pointer must point on a function taking a string as - /// input and returning an instance of the Entity (the concrete - /// subclass, not directly the upper Entity class). + /// If the class name does not exist, an ExceptionFactory + /// exception will be raised with the code UNREFERED_OBJECT. /// - /// The instances returned by this function <b>must</b> be - /// dynamically allocated and the caller <b>must</b> get the - /// ownership of the instance (i.e. it will free it when required). + /// The instance name (objname) is passed to the Entity + /// constructor and it is the caller responsibility to avoid + /// instance name conflicts if necessary. /// - /// To finish, please note that the instance name indicates to the - /// entity how the instance itself is called at run-time. This name - /// does not need to be unique and no check is done on it. It is - /// the caller responsibility to make sure that the instance name is - /// appropriate and to check for uniqueness if required. + /// \param classname the name of the Entity type + /// \param objname the instance name + /// \return Dynamically allocated instance of classname. + Entity* newEntity(const std::string& classname, const std::string& objname) const; + + /// \brief Check if an Entity associated with a particular name + /// has already been registered. /// + /// \param name entity name + /// \return Do the entity exist? + bool existEntity(const std::string& name) const; + + /// \brief List the available entities. /// - /// This class is a singleton. The rationale is that each - /// unique name must identify a unique Entity. The use of a single - /// instance of this class enforces this behavior, instantiating one - /// yourself would break this property. - class DYNAMIC_GRAPH_DLLAPI FactoryStorage : private boost::noncopyable - { - public: - /// \brief Function pointer providing an entity instance from its - /// name. - typedef Entity* (*EntityConstructor_ptr) (const std::string&); - - ~FactoryStorage (); - - /// \brief Get pointer to unique object of the class - static FactoryStorage* getInstance(); - - /// \brief Destroy the unique instance of the class - static void destroy(); - - /// \brief Add a new entity to the factory. - /// - /// It is not allowed to have several entities using the same - /// name. If this is the case, an ExceptionFactory exception will - /// be raised with the code OBJECT_CONFLICT. - /// - /// If the function pointer is null, an ExceptionFactory exception - /// will be raised with the code OBJECT_CONFLICT. - /// - /// \param entname the name used to subscribe the entity. - /// \param ent pointer to a function allocating an entity from an - /// instance name. - void registerEntity (const std::string& entname, - EntityConstructor_ptr ent); - - /// \brief Delete an entity from the factory. - /// - /// If the provided entity name does not exist in the factory, - /// an ExceptionFactory exception will be raised with the code - /// OBJECT_CONFLICT. - /// - /// \param entname the entity name (as passed to registerEntity before) - void deregisterEntity (const std::string& entname); - - /// \brief Instantiate (and allocate) an entity. - /// - /// An instance called objname of the entity which type is classname - /// will be allocated by this method. - /// - /// It is <b>the caller</b> responsibility to free the - /// returned object. - /// - /// If the class name does not exist, an ExceptionFactory - /// exception will be raised with the code UNREFERED_OBJECT. - /// - /// The instance name (objname) is passed to the Entity - /// constructor and it is the caller responsibility to avoid - /// instance name conflicts if necessary. - /// - /// \param classname the name of the Entity type - /// \param objname the instance name - /// \return Dynamically allocated instance of classname. - Entity* newEntity (const std::string& classname, - const std::string& objname) const; - - /// \brief Check if an Entity associated with a particular name - /// has already been registered. - /// - /// \param name entity name - /// \return Do the entity exist? - bool existEntity (const std::string& name) const; - - /// \brief List the available entities. - /// - /// Available entities are appended to the method argument. - /// - /// \param list Available entities will be appended to list. - void listEntities (std::vector <std::string>& list) const; - - private: - - /// \brief Constructor the factory. - /// - /// After the initialization, no entities will be available. - /// registerEntity has to be used to add new entities to the - /// object. - explicit FactoryStorage (); - - /// \brief Entity map type. - /// - /// This maps entity names to functions pointers which can be - /// used to instantiate an Entity. - typedef std::map<std::string, EntityConstructor_ptr> EntityMap; - - /// \brief The entity map storing information about how to - /// instantiate an Entity. - EntityMap entityMap; - - /// \pointer to the unique object of the class - static FactoryStorage* instance_; - }; - - /// \ingroup dgraph + /// Available entities are appended to the method argument. /// - /// \brief This class automatically register an Entity to the - /// global factory at initialization and unregister it during - /// instance destruction. + /// \param list Available entities will be appended to list. + void listEntities(std::vector<std::string>& list) const; + + private: + /// \brief Constructor the factory. /// - /// This class is mainly used by the - /// DYNAMICGRAPH_FACTORY_ENTITY_PLUGIN macro and is of little interest - /// by itself. - class DYNAMIC_GRAPH_DLLAPI EntityRegisterer : private boost::noncopyable - { - public: - /// \brief Register entity to the global factory. - explicit EntityRegisterer (const std::string& entityClassName, - FactoryStorage::EntityConstructor_ptr maker); - - /// \brief Unregister entity to the global factory. - ~EntityRegisterer (); - private: - /// \brief Name of the entity registered when the instance has - /// been initialized. - const std::string entityName; - }; + /// After the initialization, no entities will be available. + /// registerEntity has to be used to add new entities to the + /// object. + explicit FactoryStorage(); + + /// \brief Entity map type. + /// + /// This maps entity names to functions pointers which can be + /// used to instantiate an Entity. + typedef std::map<std::string, EntityConstructor_ptr> EntityMap; + + /// \brief The entity map storing information about how to + /// instantiate an Entity. + EntityMap entityMap; + + /// \pointer to the unique object of the class + static FactoryStorage* instance_; +}; + +/// \ingroup dgraph +/// +/// \brief This class automatically register an Entity to the +/// global factory at initialization and unregister it during +/// instance destruction. +/// +/// This class is mainly used by the +/// DYNAMICGRAPH_FACTORY_ENTITY_PLUGIN macro and is of little interest +/// by itself. +class DYNAMIC_GRAPH_DLLAPI EntityRegisterer : private boost::noncopyable { + public: + /// \brief Register entity to the global factory. + explicit EntityRegisterer(const std::string& entityClassName, FactoryStorage::EntityConstructor_ptr maker); + + /// \brief Unregister entity to the global factory. + ~EntityRegisterer(); + + private: + /// \brief Name of the entity registered when the instance has + /// been initialized. + const std::string entityName; +}; } // end of namespace dynamicgraph -#endif //! DYNAMIC_GRAPH_FACTORY_HH +#endif //! DYNAMIC_GRAPH_FACTORY_HH // LocalWords: unregister diff --git a/include/dynamic-graph/fwd.hh b/include/dynamic-graph/fwd.hh index 29b9b347c62cc6dd18fd934e3c53e237efe8c037..ec7a0125065eca0047c913487df3f0d424c6a06c 100644 --- a/include/dynamic-graph/fwd.hh +++ b/include/dynamic-graph/fwd.hh @@ -3,62 +3,58 @@ // #ifndef DYNAMIC_GRAPH_FWD_HH -# define DYNAMIC_GRAPH_FWD_HH +#define DYNAMIC_GRAPH_FWD_HH -namespace dynamicgraph -{ - class DebugTrace; +namespace dynamicgraph { +class DebugTrace; - class PluginRefMap; - class Entity; - class EntityRegisterer; - class ExceptionAbstract; - class ExceptionFactory; - class ExceptionSignal; - class ExceptionTraces; - class FactoryStorage; - class Interpreter; - class InterpreterHelper; - class Logger; - class OutStringStream; - class PluginLoader; - class PoolStorage; +class PluginRefMap; +class Entity; +class EntityRegisterer; +class ExceptionAbstract; +class ExceptionFactory; +class ExceptionSignal; +class ExceptionTraces; +class FactoryStorage; +class Interpreter; +class InterpreterHelper; +class Logger; +class OutStringStream; +class PluginLoader; +class PoolStorage; - class SignalCaster; - class SignalCastRegisterer; +class SignalCaster; +class SignalCastRegisterer; - class Tracer; - class TracerRealTime; +class Tracer; +class TracerRealTime; - template <typename T> - class DefaultCastRegisterer; +template <typename T> +class DefaultCastRegisterer; - template <typename T, typename Time> - class Signal; +template <typename T, typename Time> +class Signal; - template <typename Time> - class SignalArray; +template <typename Time> +class SignalArray; - template <typename Time> - class SignalArray_const; +template <typename Time> +class SignalArray_const; - template <typename Time> - class SignalBase; +template <typename Time> +class SignalBase; +template <typename T, typename Time> +class SignalPtr; +template <typename T, typename Time> +class SignalTimeDependent; +template <typename Time> +class TimeDependency; - template <typename T, typename Time> - class SignalPtr; - template <typename T, typename Time> - class SignalTimeDependent; - template <typename Time> - class TimeDependency; +namespace command { +class Command; +} // end of namespace command. - namespace command - { - class Command; - } // end of namespace command. +} // end of namespace dynamicgraph. -} // end of namespace dynamicgraph. - - -#endif //! DYNAMIC_GRAPH_FWD_HH +#endif //! DYNAMIC_GRAPH_FWD_HH diff --git a/include/dynamic-graph/linear-algebra.h b/include/dynamic-graph/linear-algebra.h index c0b3d216f4f113897ee72dbe29bfb03426fe4989..c600ff1763d04305f22f5456a5f1eb1c69478ae5 100644 --- a/include/dynamic-graph/linear-algebra.h +++ b/include/dynamic-graph/linear-algebra.h @@ -10,9 +10,8 @@ #include <Eigen/Geometry> namespace dynamicgraph { - typedef Eigen::MatrixXd Matrix; - typedef Eigen::VectorXd Vector; -} +typedef Eigen::MatrixXd Matrix; +typedef Eigen::VectorXd Vector; +} // namespace dynamicgraph - -#endif //DYNAMIC_GRAPH_LINEAR_ALGEBRA_H +#endif // DYNAMIC_GRAPH_LINEAR_ALGEBRA_H diff --git a/include/dynamic-graph/logger.h b/include/dynamic-graph/logger.h index ba102ed12159773b6c9e757b5dddcdc1e21c6ef5..94ec93b2e1ab07e7147f5dfc90b41fcace791111 100644 --- a/include/dynamic-graph/logger.h +++ b/include/dynamic-graph/logger.h @@ -12,39 +12,38 @@ /* --- API ------------------------------------------------------------- */ /* --------------------------------------------------------------------- */ -#if defined (WIN32) -# if defined (logger_EXPORTS) -# define LOGGER_EXPORT __declspec(dllexport) -# else -# define LOGGER_EXPORT __declspec(dllimport) -# endif +#if defined(WIN32) +#if defined(logger_EXPORTS) +#define LOGGER_EXPORT __declspec(dllexport) #else -# define LOGGER_EXPORT +#define LOGGER_EXPORT __declspec(dllimport) +#endif +#else +#define LOGGER_EXPORT #endif namespace dynamicgraph { - /** Enum representing the different kind of messages. - */ - enum MsgType - { - MSG_TYPE_DEBUG =0, - MSG_TYPE_INFO =1, - MSG_TYPE_WARNING =2, - MSG_TYPE_ERROR =3, - MSG_TYPE_DEBUG_STREAM =4, - MSG_TYPE_INFO_STREAM =5, - MSG_TYPE_WARNING_STREAM =6, - MSG_TYPE_ERROR_STREAM =7 - }; -} +/** Enum representing the different kind of messages. + */ +enum MsgType { + MSG_TYPE_DEBUG = 0, + MSG_TYPE_INFO = 1, + MSG_TYPE_WARNING = 2, + MSG_TYPE_ERROR = 3, + MSG_TYPE_DEBUG_STREAM = 4, + MSG_TYPE_INFO_STREAM = 5, + MSG_TYPE_WARNING_STREAM = 6, + MSG_TYPE_ERROR_STREAM = 7 +}; +} // namespace dynamicgraph /* --------------------------------------------------------------------- */ /* --- INCLUDE --------------------------------------------------------- */ /* --------------------------------------------------------------------- */ #include <map> -#include <iomanip> // std::setprecision +#include <iomanip> // std::setprecision #include <fstream> #include <sstream> #include "boost/assign.hpp" @@ -55,172 +54,155 @@ namespace dynamicgraph { //#define LOGGER_VERBOSITY_INFO_WARNING_ERROR #define LOGGER_VERBOSITY_ALL -#define SEND_MSG(msg,type) sendMsg(msg,type,__FILE__,__LINE__) - -#define SEND_DEBUG_STREAM_MSG(msg) SEND_MSG(msg,MSG_TYPE_DEBUG_STREAM) -#define SEND_INFO_STREAM_MSG(msg) SEND_MSG(msg,MSG_TYPE_INFO_STREAM) -#define SEND_WARNING_STREAM_MSG(msg) SEND_MSG(msg,MSG_TYPE_WARNING_STREAM) -#define SEND_ERROR_STREAM_MSG(msg) SEND_MSG(msg,MSG_TYPE_ERROR_STREAM) - - /*template<typename T> - std::string toString(const T& v, const int precision=3, const int width=-1) - { - std::stringstream ss; - if(width>precision) - ss<<std::fixed<<std::setw(width)<<std::setprecision(precision)<<v; - else - ss<<std::fixed<<std::setprecision(precision)<<v; - return ss.str(); - }*/ - - template<typename T> - std::string toString(const std::vector<T>& v, const int precision=3, const int width=-1, - const std::string separator=", ") - { - std::stringstream ss; - if(width>precision) - { - for(int i=0; i<v.size()-1; i++) - ss<<std::fixed<<std::setw(width)<<std::setprecision(precision)<<v[i]<<separator; - ss<<std::fixed<<std::setw(width)<<std::setprecision(precision)<<v[v.size()-1]; - } - else - { - for(int i=0; i<v.size()-1; i++) - ss<<std::fixed<<std::setprecision(precision)<<v[i]<<separator; - ss<<std::fixed<<std::setprecision(precision)<<v[v.size()-1]; - } - - return ss.str(); +#define SEND_MSG(msg, type) sendMsg(msg, type, __FILE__, __LINE__) + +#define SEND_DEBUG_STREAM_MSG(msg) SEND_MSG(msg, MSG_TYPE_DEBUG_STREAM) +#define SEND_INFO_STREAM_MSG(msg) SEND_MSG(msg, MSG_TYPE_INFO_STREAM) +#define SEND_WARNING_STREAM_MSG(msg) SEND_MSG(msg, MSG_TYPE_WARNING_STREAM) +#define SEND_ERROR_STREAM_MSG(msg) SEND_MSG(msg, MSG_TYPE_ERROR_STREAM) + +/*template<typename T> +std::string toString(const T& v, const int precision=3, const int width=-1) +{ + std::stringstream ss; + if(width>precision) + ss<<std::fixed<<std::setw(width)<<std::setprecision(precision)<<v; + else + ss<<std::fixed<<std::setprecision(precision)<<v; + return ss.str(); +}*/ + +template <typename T> +std::string toString(const std::vector<T>& v, const int precision = 3, const int width = -1, + const std::string separator = ", ") { + std::stringstream ss; + if (width > precision) { + for (int i = 0; i < v.size() - 1; i++) + ss << std::fixed << std::setw(width) << std::setprecision(precision) << v[i] << separator; + ss << std::fixed << std::setw(width) << std::setprecision(precision) << v[v.size() - 1]; + } else { + for (int i = 0; i < v.size() - 1; i++) ss << std::fixed << std::setprecision(precision) << v[i] << separator; + ss << std::fixed << std::setprecision(precision) << v[v.size() - 1]; } + return ss.str(); +} + // template<typename T, int N> // std::string toString(const Eigen::Matrix<T, N, 1, 0, N, 1>& v, const std::string separator=", ", // const int precision=3, const int width=-1) - template<typename T> - std::string toString(const Eigen::MatrixBase<T>& v, - const int precision=3, const int width=-1, const std::string separator=", ") - { - std::stringstream ss; - if(width>precision) - { - for(int i=0; i<v.size()-1; i++) - ss<<std::fixed<<std::setw(width)<<std::setprecision(precision)<<v[i]<<separator; - ss<<std::fixed<<std::setw(width)<<std::setprecision(precision)<<v[v.size()-1]; - } - else - { - for(int i=0; i<v.size()-1; i++) - ss<<std::fixed<<std::setprecision(precision)<<v[i]<<separator; - ss<<std::setprecision(precision)<<v[v.size()-1]; - } - - return ss.str(); +template <typename T> +std::string toString(const Eigen::MatrixBase<T>& v, const int precision = 3, const int width = -1, + const std::string separator = ", ") { + std::stringstream ss; + if (width > precision) { + for (int i = 0; i < v.size() - 1; i++) + ss << std::fixed << std::setw(width) << std::setprecision(precision) << v[i] << separator; + ss << std::fixed << std::setw(width) << std::setprecision(precision) << v[v.size() - 1]; + } else { + for (int i = 0; i < v.size() - 1; i++) ss << std::fixed << std::setprecision(precision) << v[i] << separator; + ss << std::setprecision(precision) << v[v.size() - 1]; + } + + return ss.str(); +} + +enum LoggerVerbosity { + VERBOSITY_ALL, + VERBOSITY_INFO_WARNING_ERROR, + VERBOSITY_WARNING_ERROR, + VERBOSITY_ERROR, + VERBOSITY_NONE +}; + +/// \ingroup debug +/// +/// \brief Class for logging messages +/// +/// It is intended to be used like this: +/// \code +/// #define ENABLE_RT_LOG +/// #include <dynamic-graph/real-time-logger.h> +/// +/// // Somewhere in the main function of your executable +/// int main (int argc, char** argv) { +/// std::ofstream of; +/// of.open("/tmp/dg-LOGS.txt",std::ofstream::out|std::ofstream::app); +/// dgADD_OSTREAM_TO_RTLOG (of); +/// } +/// +/// // Somewhere in your library +/// dynamicgraph::LoggerVerbosity aLoggerVerbosityLevel = VERBOSITY_WARNING_ERROR; +/// entity.setLoggerVerbosityLevel(aLoggerVerbosityLevel); +/// ... +/// std::string aMsg=aBaseMsg+" WARNING"; +/// entity.sendMsg(aMsg,dynamicgraph::MSG_TYPE_WARNING, __FILE__,__LINE__); +/// +/// \endcode +/// +/// +class Logger { + public: + /** Constructor */ + Logger(double timeSample = 0.001, double streamPrintPeriod = 1.0); + + /** Destructor */ + ~Logger(); + + /** Method to be called at every control iteration + * to decrement the internal Logger's counter. */ + void countdown(); + + /** Print the specified message on standard output if the verbosity level + * allows it. The file name and the line number are used to identify + * the point where sendMsg is called so that streaming messages are + * printed only every streamPrintPeriod iterations. + */ + void sendMsg(std::string msg, MsgType type, const char* file = "", int line = 0); + + /** Set the sampling time at which the method countdown() + * is going to be called. */ + bool setTimeSample(double t); + + /** Get the sampling time at which the method countdown() + * is going to be called. */ + double getTimeSample(); + + /** Set the time period for printing of streaming messages. */ + bool setStreamPrintPeriod(double s); + + /** Get the time period for printing of streaming messages. */ + double getStreamPrintPeriod(); + + /** Set the verbosity level of the logger. */ + void setVerbosity(LoggerVerbosity lv); + + /** Get the verbosity level of the logger. */ + LoggerVerbosity getVerbosity(); + + protected: + LoggerVerbosity m_lv; /// verbosity of the logger + double m_timeSample; /// specify the period of call of the countdown method + double m_streamPrintPeriod; /// specify the time period of the stream prints + double m_printCountdown; /// every time this is < 0 (i.e. every _streamPrintPeriod sec) print stuff + + /** Pointer to the dynamic structure which holds the collection of streaming messages */ + std::map<std::string, double> m_stream_msg_counters; + + bool isStreamMsg(MsgType m) { + return m == MSG_TYPE_ERROR_STREAM || m == MSG_TYPE_DEBUG_STREAM || m == MSG_TYPE_INFO_STREAM || + m == MSG_TYPE_WARNING_STREAM; } - enum LoggerVerbosity - { - VERBOSITY_ALL, - VERBOSITY_INFO_WARNING_ERROR, - VERBOSITY_WARNING_ERROR, - VERBOSITY_ERROR, - VERBOSITY_NONE - }; - - /// \ingroup debug - /// - /// \brief Class for logging messages - /// - /// It is intended to be used like this: - /// \code - /// #define ENABLE_RT_LOG - /// #include <dynamic-graph/real-time-logger.h> - /// - /// // Somewhere in the main function of your executable - /// int main (int argc, char** argv) { - /// std::ofstream of; - /// of.open("/tmp/dg-LOGS.txt",std::ofstream::out|std::ofstream::app); - /// dgADD_OSTREAM_TO_RTLOG (of); - /// } - /// - /// // Somewhere in your library - /// dynamicgraph::LoggerVerbosity aLoggerVerbosityLevel = VERBOSITY_WARNING_ERROR; - /// entity.setLoggerVerbosityLevel(aLoggerVerbosityLevel); - /// ... - /// std::string aMsg=aBaseMsg+" WARNING"; - /// entity.sendMsg(aMsg,dynamicgraph::MSG_TYPE_WARNING, __FILE__,__LINE__); - /// - /// \endcode - /// - /// - class Logger - { - public: - - /** Constructor */ - Logger(double timeSample=0.001, double streamPrintPeriod=1.0); - - /** Destructor */ - ~Logger(); - - /** Method to be called at every control iteration - * to decrement the internal Logger's counter. */ - void countdown(); - - /** Print the specified message on standard output if the verbosity level - * allows it. The file name and the line number are used to identify - * the point where sendMsg is called so that streaming messages are - * printed only every streamPrintPeriod iterations. - */ - void sendMsg(std::string msg, MsgType type, const char* file="", int line=0); - - /** Set the sampling time at which the method countdown() - * is going to be called. */ - bool setTimeSample(double t); - - /** Get the sampling time at which the method countdown() - * is going to be called. */ - double getTimeSample(); - - /** Set the time period for printing of streaming messages. */ - bool setStreamPrintPeriod(double s); - - /** Get the time period for printing of streaming messages. */ - double getStreamPrintPeriod(); - - /** Set the verbosity level of the logger. */ - void setVerbosity(LoggerVerbosity lv); - - /** Get the verbosity level of the logger. */ - LoggerVerbosity getVerbosity(); - - protected: - LoggerVerbosity m_lv; /// verbosity of the logger - double m_timeSample; /// specify the period of call of the countdown method - double m_streamPrintPeriod; /// specify the time period of the stream prints - double m_printCountdown; /// every time this is < 0 (i.e. every _streamPrintPeriod sec) print stuff - - /** Pointer to the dynamic structure which holds the collection of streaming messages */ - std::map<std::string, double> m_stream_msg_counters; - - bool isStreamMsg(MsgType m) - { return m==MSG_TYPE_ERROR_STREAM || m==MSG_TYPE_DEBUG_STREAM || m==MSG_TYPE_INFO_STREAM || m==MSG_TYPE_WARNING_STREAM; } - - bool isDebugMsg(MsgType m) - { return m==MSG_TYPE_DEBUG_STREAM || m==MSG_TYPE_DEBUG; } - - bool isInfoMsg(MsgType m) - { return m==MSG_TYPE_INFO_STREAM || m==MSG_TYPE_INFO; } - - bool isWarningMsg(MsgType m) - { return m==MSG_TYPE_WARNING_STREAM || m==MSG_TYPE_WARNING; } - - bool isErrorMsg(MsgType m) - { return m==MSG_TYPE_ERROR_STREAM || m==MSG_TYPE_ERROR; } - }; - -} // namespace dynamicgraph - - - -#endif // #ifndef __sot_torque_control_logger_H__ + bool isDebugMsg(MsgType m) { return m == MSG_TYPE_DEBUG_STREAM || m == MSG_TYPE_DEBUG; } + + bool isInfoMsg(MsgType m) { return m == MSG_TYPE_INFO_STREAM || m == MSG_TYPE_INFO; } + + bool isWarningMsg(MsgType m) { return m == MSG_TYPE_WARNING_STREAM || m == MSG_TYPE_WARNING; } + + bool isErrorMsg(MsgType m) { return m == MSG_TYPE_ERROR_STREAM || m == MSG_TYPE_ERROR; } +}; + +} // namespace dynamicgraph + +#endif // #ifndef __sot_torque_control_logger_H__ diff --git a/include/dynamic-graph/null-ptr.hh b/include/dynamic-graph/null-ptr.hh index 60ea303cb2b862ce93e9cf90a685972b020be03c..d43bc471ed16dccbc01236d9ece363d2ee3b3d8d 100644 --- a/include/dynamic-graph/null-ptr.hh +++ b/include/dynamic-graph/null-ptr.hh @@ -2,28 +2,25 @@ // #ifndef DYNAMIC_GRAPH_NULL_PTR_HH -# define DYNAMIC_GRAPH_NULL_PTR_HH +#define DYNAMIC_GRAPH_NULL_PTR_HH -namespace dynamicgraph -{ - const class - { - public: - template<class T> - operator T*() const - { - return 0; - } +namespace dynamicgraph { +const class { + public: + template <class T> + operator T*() const { + return 0; + } - template<class C, class T> - operator T C::*() const - { - return 0; - } - private: - void operator&() const; - } nullptr = {}; + template <class C, class T> + operator T C::*() const { + return 0; + } -} // end of namespace dynamicgraph. + private: + void operator&() const; +} nullptr = {}; -#endif //! DYNAMIC_GRAPH_NULL_PTR_HH +} // end of namespace dynamicgraph. + +#endif //! DYNAMIC_GRAPH_NULL_PTR_HH diff --git a/include/dynamic-graph/pool.h b/include/dynamic-graph/pool.h index 9d380e1a27022098e7018ce546c6b7d101cad435..90d9c89a84023818c7cf951b75fa0d7e3663c730 100644 --- a/include/dynamic-graph/pool.h +++ b/include/dynamic-graph/pool.h @@ -4,117 +4,115 @@ // #ifndef DYNAMIC_GRAPH_POOL_H -# define DYNAMIC_GRAPH_POOL_H -# include <map> -# include <string> -# include <sstream> +#define DYNAMIC_GRAPH_POOL_H +#include <map> +#include <string> +#include <sstream> + +#include <dynamic-graph/fwd.hh> +#include <dynamic-graph/exception-factory.h> +#include <dynamic-graph/signal-base.h> +#include <dynamic-graph/dynamic-graph-api.h> + +namespace dynamicgraph { +/*! @ingroup dgraph + \brief Singleton that keeps track of all the entities. + + This class gives access to and remembers all the entities created + during its life. + + This class provides the necessary operations to register, unregister each + instance of thoses classes. + As tasks and features derived from Entities, they should be registered + as such. + + \note From the code it is not very clear why we should not unregister + from the tasks and the features... + +*/ +class DYNAMIC_GRAPH_DLLAPI PoolStorage { + public: + /*! \name Define types to simplify the writing + @{ + */ + /*! \brief Sorted set of entities with unique key (name). */ + typedef std::map<std::string, Entity*> Entities; -# include <dynamic-graph/fwd.hh> -# include <dynamic-graph/exception-factory.h> -# include <dynamic-graph/signal-base.h> -# include <dynamic-graph/dynamic-graph-api.h> + /// \brief Get unique instance of the class. + static PoolStorage* getInstance(); -namespace dynamicgraph -{ - /*! @ingroup dgraph - \brief Singleton that keeps track of all the entities. + /// \brief Destroy the unique instance of the class + static void destroy(); - This class gives access to and remembers all the entities created - during its life. + /*! @} */ - This class provides the necessary operations to register, unregister each - instance of thoses classes. - As tasks and features derived from Entities, they should be registered - as such. + /*! \brief Default destructor */ + ~PoolStorage(); - \note From the code it is not very clear why we should not unregister - from the tasks and the features... + /*! \name Method related to the handling of entities. + @{ + */ + /*! \brief Register an entity. + \par[in] entname: The name of the entity, + \par[in] ent: Pointer towards the entity. + */ + void registerEntity(const std::string& entname, Entity* ent); + /*! \brief Unregister an entity. + \par[in] entname: The name of the entity, */ - class DYNAMIC_GRAPH_DLLAPI PoolStorage - { - public: - /*! \name Define types to simplify the writing - @{ - */ - /*! \brief Sorted set of entities with unique key (name). */ - typedef std::map< std::string,Entity* > Entities; - - /// \brief Get unique instance of the class. - static PoolStorage *getInstance(); - - /// \brief Destroy the unique instance of the class - static void destroy(); - - /*! @} */ - - /*! \brief Default destructor */ - ~PoolStorage (); - - /*! \name Method related to the handling of entities. - @{ - */ - /*! \brief Register an entity. - \par[in] entname: The name of the entity, - \par[in] ent: Pointer towards the entity. - */ - void registerEntity (const std::string& entname, Entity* ent); - - /*! \brief Unregister an entity. - \par[in] entname: The name of the entity, - */ - void deregisterEntity (const std::string& entname); - - /*! \brief Unregister an entity. - \par[in] entity: iterator in the map, - */ - void deregisterEntity( const Entities::iterator& entity ); - /*! \brief Get an entity. - \par[in] entname: The name of the entity, - \return Pointer towards the entity. - */ - Entity& getEntity (const std::string& name); - - /// Const access to entity map - const Entities& getEntityMap () const; - - /*! \brief Test if the entity exists. */ - bool existEntity (const std::string& name); - /*! \brief Test if the entity exists. If it does, return a pointer on it. */ - bool existEntity (const std::string& name, Entity*& ptr); - - /*! \brief Disallocate an entity. - \par[in] entname: The name of the entity, - */ - void clearPlugin (const std::string& name); - /*! @} */ - - /// - /// \brief Get a signal by name - /// - /// \param sigpath stream containing a string of the form "entity.signal" - SignalBase<int>& getSignal( std::istringstream& sigpath ); - - /*! \brief This method write a graph description on the file named - FileName. */ - void writeGraph (const std::string& aFileName); - void writeCompletionList (std::ostream& os); - - protected: - /*! \name Fields of the class to manage the three entities. - Also the name is singular, those are true sets. - @{ - */ - /*! \brief Set of basic objects of the SoT */ - Entities entityMap; - - private: - PoolStorage () {} - static PoolStorage* instance_; - }; - - inline PoolStorage& g_pool() { return *PoolStorage::getInstance(); } + void deregisterEntity(const std::string& entname); + + /*! \brief Unregister an entity. + \par[in] entity: iterator in the map, + */ + void deregisterEntity(const Entities::iterator& entity); + /*! \brief Get an entity. + \par[in] entname: The name of the entity, + \return Pointer towards the entity. + */ + Entity& getEntity(const std::string& name); + + /// Const access to entity map + const Entities& getEntityMap() const; + + /*! \brief Test if the entity exists. */ + bool existEntity(const std::string& name); + /*! \brief Test if the entity exists. If it does, return a pointer on it. */ + bool existEntity(const std::string& name, Entity*& ptr); + + /*! \brief Disallocate an entity. + \par[in] entname: The name of the entity, + */ + void clearPlugin(const std::string& name); + /*! @} */ + + /// + /// \brief Get a signal by name + /// + /// \param sigpath stream containing a string of the form "entity.signal" + SignalBase<int>& getSignal(std::istringstream& sigpath); + + /*! \brief This method write a graph description on the file named + FileName. */ + void writeGraph(const std::string& aFileName); + void writeCompletionList(std::ostream& os); + + protected: + /*! \name Fields of the class to manage the three entities. + Also the name is singular, those are true sets. + @{ + */ + /*! \brief Set of basic objects of the SoT */ + Entities entityMap; + + private: + PoolStorage() {} + static PoolStorage* instance_; +}; + +inline PoolStorage& g_pool() { return *PoolStorage::getInstance(); } } // end of namespace dynamicgraph. -#endif //! DYNAMIC_GRAPH_POOL_H +#endif //! DYNAMIC_GRAPH_POOL_H diff --git a/include/dynamic-graph/process-list.hh b/include/dynamic-graph/process-list.hh index 7782b82eb0a9d756d46c09374b22e5dc9b52ebfb..046d8e0d0500b7c44e2103f4a05efe592313c7e9 100644 --- a/include/dynamic-graph/process-list.hh +++ b/include/dynamic-graph/process-list.hh @@ -4,179 +4,162 @@ */ #ifndef DYNAMIC_GRAPH_PROCESS_LIST_H_ -# define DYNAMIC_GRAPH_PROCESS_LIST_H +#define DYNAMIC_GRAPH_PROCESS_LIST_H #include <boost/archive/text_oarchive.hpp> #include <boost/archive/text_iarchive.hpp> #include <boost/serialization/vector.hpp> -# include <dynamic-graph/fwd.hh> -# include <dynamic-graph/dynamic-graph-api.h> - -namespace dynamicgraph -{ - namespace CPU - { - class DYNAMIC_GRAPH_DLLAPI ProcessData - { - }; - - class DYNAMIC_GRAPH_DLLAPI ProcessList - { - public: - ProcessList(); - - }; - - /// \class This class gather information on a specific CPU. - /// - class DYNAMIC_GRAPH_DLLAPI CPUData - { - public: - - CPUData(); - int cpu_id_; - - inline unsigned long long int - computePeriod(unsigned long long int &a, - unsigned long long int &b) - { - return (a>b) ? a-b :0; - } - - /// \brief Various classes of time spend by the CPU - /// @{ - /// Total time - unsigned long long int total_time_; - /// Time spend in user mode - unsigned long long int user_mode_time_; - /// Time spend in user mode with low priority (nice mode) - unsigned long long int nice_time_; - /// Time spend in system mode - unsigned long long int system_time_; - /// Time spend in system mode - unsigned long long int system_all_time_; - /// Time spend in doing nothing. - unsigned long long int idle_time_; - /// Time spend in doing nothing. - unsigned long long int idle_all_time_; - /// Time spend in waiting an input/output to complete. - unsigned long long int iowait_time_; - /// Time spend in servicing hardware interrupts. - unsigned long long int irq_time_; - /// Time spend in servicing software interrupts. - unsigned long long int softirq_time_; - /// Time spend in other operating systems in a virtualized environments - /// Never doing this for control ! - unsigned long long int steal_time_; - /// Time spend running a virtual CPU for guest operating systems - /// under the control of the Linux kernel - unsigned long long int guest_time_; - /// Time spent running a niced guest - /// (virtual CPU for guest operating systems under the - /// control of the Linux kernel) - unsigned long long int guest_nice_time_; - /// @} - - /// \brief Various classes of time spend by the CPU by period - /// @{ - /// Total time - unsigned long long int total_period_; - /// Time spend in user mode - unsigned long long int user_mode_period_; - /// Time spend in user mode with low priority (nice mode) - unsigned long long int nice_period_; - /// Time spend in system mode - unsigned long long int system_period_; - /// Time spend in all system mode - unsigned long long int system_all_period_; - /// Time spend in doing nothing. - unsigned long long int idle_period_; - /// Time spend in doing nothing. - unsigned long long int idle_all_period_; - /// Time spend in waiting an input/output to complete. - unsigned long long int iowait_period_; - /// Time spend in servicing hardware interrupts. - unsigned long long int irq_period_; - /// Time spend in servicing software interrupts. - unsigned long long int softirq_period_; - /// Time spend in other operating systems in a virtualized environments - /// Never doing this for control ! - unsigned long long int steal_period_; - /// Time spend running a virtual CPU for guest operating systems - /// under the control of the Linux kernel - unsigned long long int guest_period_; - /// @} - - double percent_; - void ProcessLine(std::istringstream &aCPULine); - - friend class boost::serialization::access; - - template<class Archive> - void serialize(Archive & ar, const unsigned int version) - { - ar & version; - ar & total_time_; - ar & user_mode_time_; - ar & nice_time_; - ar & system_time_; - ar & system_all_time_; - ar & idle_time_; - ar & idle_all_time_; - ar & iowait_time_; - ar & irq_time_; - ar & softirq_time_; - ar & steal_time_; - ar & guest_time_; - ar & guest_nice_time_; - ar & percent_; - } - - }; - - /// \class This class gathers information on a computer. - /// This includes a list of CPU - class DYNAMIC_GRAPH_DLLAPI System - { - private: - bool init_; - - public: - System(); - - /// Read /proc/state file to extract CPU count. - void init(); - - /// Update CPU data information from /proc/stat - void readProcStat(); - - /// Friend class for serialization. - friend class boost::serialization::access; - - /// Number of CPU. - unsigned int cpuNb_; - - void ProcessCPULine(unsigned int cpunb, - std::istringstream &aCPULine); - - /// \brief Vector of CPU informations. - std::vector<CPUData> vCPUData_; - - /// \brief Global CPU information. - CPUData gCPUData_; - - template<class Archive> - void serialize(Archive & ar, const unsigned int version) - { - ar & version; - ar & cpuNb_; - ar & gCPUData_; - ar & vCPUData_; - } - - }; +#include <dynamic-graph/fwd.hh> +#include <dynamic-graph/dynamic-graph-api.h> + +namespace dynamicgraph { +namespace CPU { +class DYNAMIC_GRAPH_DLLAPI ProcessData {}; + +class DYNAMIC_GRAPH_DLLAPI ProcessList { + public: + ProcessList(); +}; + +/// \class This class gather information on a specific CPU. +/// +class DYNAMIC_GRAPH_DLLAPI CPUData { + public: + CPUData(); + int cpu_id_; + + inline unsigned long long int computePeriod(unsigned long long int &a, unsigned long long int &b) { + return (a > b) ? a - b : 0; + } + + /// \brief Various classes of time spend by the CPU + /// @{ + /// Total time + unsigned long long int total_time_; + /// Time spend in user mode + unsigned long long int user_mode_time_; + /// Time spend in user mode with low priority (nice mode) + unsigned long long int nice_time_; + /// Time spend in system mode + unsigned long long int system_time_; + /// Time spend in system mode + unsigned long long int system_all_time_; + /// Time spend in doing nothing. + unsigned long long int idle_time_; + /// Time spend in doing nothing. + unsigned long long int idle_all_time_; + /// Time spend in waiting an input/output to complete. + unsigned long long int iowait_time_; + /// Time spend in servicing hardware interrupts. + unsigned long long int irq_time_; + /// Time spend in servicing software interrupts. + unsigned long long int softirq_time_; + /// Time spend in other operating systems in a virtualized environments + /// Never doing this for control ! + unsigned long long int steal_time_; + /// Time spend running a virtual CPU for guest operating systems + /// under the control of the Linux kernel + unsigned long long int guest_time_; + /// Time spent running a niced guest + /// (virtual CPU for guest operating systems under the + /// control of the Linux kernel) + unsigned long long int guest_nice_time_; + /// @} + + /// \brief Various classes of time spend by the CPU by period + /// @{ + /// Total time + unsigned long long int total_period_; + /// Time spend in user mode + unsigned long long int user_mode_period_; + /// Time spend in user mode with low priority (nice mode) + unsigned long long int nice_period_; + /// Time spend in system mode + unsigned long long int system_period_; + /// Time spend in all system mode + unsigned long long int system_all_period_; + /// Time spend in doing nothing. + unsigned long long int idle_period_; + /// Time spend in doing nothing. + unsigned long long int idle_all_period_; + /// Time spend in waiting an input/output to complete. + unsigned long long int iowait_period_; + /// Time spend in servicing hardware interrupts. + unsigned long long int irq_period_; + /// Time spend in servicing software interrupts. + unsigned long long int softirq_period_; + /// Time spend in other operating systems in a virtualized environments + /// Never doing this for control ! + unsigned long long int steal_period_; + /// Time spend running a virtual CPU for guest operating systems + /// under the control of the Linux kernel + unsigned long long int guest_period_; + /// @} + + double percent_; + void ProcessLine(std::istringstream &aCPULine); + + friend class boost::serialization::access; + + template <class Archive> + void serialize(Archive &ar, const unsigned int version) { + ar &version; + ar &total_time_; + ar &user_mode_time_; + ar &nice_time_; + ar &system_time_; + ar &system_all_time_; + ar &idle_time_; + ar &idle_all_time_; + ar &iowait_time_; + ar &irq_time_; + ar &softirq_time_; + ar &steal_time_; + ar &guest_time_; + ar &guest_nice_time_; + ar &percent_; + } +}; + +/// \class This class gathers information on a computer. +/// This includes a list of CPU +class DYNAMIC_GRAPH_DLLAPI System { + private: + bool init_; + + public: + System(); + + /// Read /proc/state file to extract CPU count. + void init(); + + /// Update CPU data information from /proc/stat + void readProcStat(); + + /// Friend class for serialization. + friend class boost::serialization::access; + + /// Number of CPU. + unsigned int cpuNb_; + + void ProcessCPULine(unsigned int cpunb, std::istringstream &aCPULine); + + /// \brief Vector of CPU informations. + std::vector<CPUData> vCPUData_; + + /// \brief Global CPU information. + CPUData gCPUData_; + + template <class Archive> + void serialize(Archive &ar, const unsigned int version) { + ar &version; + ar &cpuNb_; + ar &gCPUData_; + ar &vCPUData_; } -} +}; +} // namespace CPU +} // namespace dynamicgraph #endif /* DYNAMIC_GRAPH_PROCESS_LIST_H_ */ diff --git a/include/dynamic-graph/real-time-logger.h b/include/dynamic-graph/real-time-logger.h index 8049e8848c8ada172d0cb7369a1edf87e04242af..a2f6130d8641f60cd28731cd39d12ef28a853723 100644 --- a/include/dynamic-graph/real-time-logger.h +++ b/include/dynamic-graph/real-time-logger.h @@ -3,170 +3,172 @@ // #ifndef DYNAMIC_GRAPH_LOGGER_REAL_TIME_H -# define DYNAMIC_GRAPH_LOGGER_REAL_TIME_H -# include <sstream> -# include <vector> - -# include <boost/circular_buffer.hpp> -# include <boost/shared_ptr.hpp> -# include <boost/thread/mutex.hpp> - -# include <dynamic-graph/config.hh> -# include <dynamic-graph/debug.h> - - -namespace dynamicgraph -{ - /// \ingroup debug - /// - /// \brief Stream for the real-time logger. - /// - /// You should inherit from this class in order to redirect the logs where you - /// want. - /// \sa LoggerIOStream - class LoggerStream - { - public: - virtual void write (const char* c) = 0; +#define DYNAMIC_GRAPH_LOGGER_REAL_TIME_H +#include <sstream> +#include <vector> + +#include <boost/circular_buffer.hpp> +#include <boost/shared_ptr.hpp> +#include <boost/thread/mutex.hpp> + +#include <dynamic-graph/config.hh> +#include <dynamic-graph/debug.h> + +namespace dynamicgraph { +/// \ingroup debug +/// +/// \brief Stream for the real-time logger. +/// +/// You should inherit from this class in order to redirect the logs where you +/// want. +/// \sa LoggerIOStream +class LoggerStream { + public: + virtual void write(const char* c) = 0; +}; + +/// Write to an ostream object. +/// +/// The easieast is to use the macro \ref dgADD_OSTREAM_TO_RTLOG(ostr) where +/// `ostr` can be `std::cout` or an std::ofstream... +class LoggerIOStream : public LoggerStream { + public: + LoggerIOStream(std::ostream& os) : os_(os) {} + virtual void write(const char* c) { os_ << c; } + + private: + std::ostream& os_; +}; +typedef boost::shared_ptr<LoggerStream> LoggerStreamPtr_t; + +class RealTimeLogger; + +/// \cond DEVEL +/// \brief write entries to intenal buffer. +/// +/// The entry starts when an instance is created and ends when is is deleted. +/// This class is only used by RealTimeLogger. +class RTLoggerStream { + public: + RTLoggerStream(RealTimeLogger* logger, std::ostream& os) : logger_(logger), os_(os) {} + template <typename T> + inline RTLoggerStream& operator<<(T t) { + if (logger_ != NULL) os_ << t; + return *this; + } + inline RTLoggerStream& operator<<(std::ostream& (*pf)(std::ostream&)) { + if (logger_ != NULL) os_ << pf; + return *this; + } + + ~RTLoggerStream(); + + private: + RealTimeLogger* logger_; + std::ostream& os_; +}; +/// \endcond DEVEL + +/// \ingroup debug +/// +/// \brief Main class of the real-time logger. +/// +/// It is intended to be used like this: +/// \code +/// #define ENABLE_RT_LOG +/// #include <dynamic-graph/real-time-logger.h> +/// +/// // Somewhere in the main function of your executable +/// int main (int argc, char** argv) { +/// dgADD_OSTREAM_TO_RTLOG (std::cout); +/// } +/// +/// // Somewhere in your library +/// dgRTLOG() << "your message. Prefer to use \n than std::endl." +/// \endcode +/// +/// \note Thread safety. This class expects to have: +/// - only one reader: the one who take the log entries and write them somewhere. +/// - one writer at a time. Writing to the logs is **never** a blocking +/// operation. If the resource is busy, the log entry is discarded. +class DYNAMIC_GRAPH_DLLAPI RealTimeLogger { + public: + static RealTimeLogger& instance(); + + static void destroy(); + + /// \todo add an argument to preallocate the internal string to a given size. + RealTimeLogger(const std::size_t& bufferSize); + + inline void clearOutputStreams() { outputs_.clear(); } + + inline void addOutputStream(const LoggerStreamPtr_t& os) { outputs_.push_back(os); } + + /// Write next message to output. + /// It does nothing if the buffer is empty. + /// \return true if it wrote something + bool spinOnce(); + + /// Return an object onto which a real-time thread can write. + /// The message is considered finished when the object is destroyed. + RTLoggerStream front(); + + inline void frontReady() { + backIdx_ = (backIdx_ + 1) % buffer_.size(); + wmutex.unlock(); + } + + inline bool empty() const { return frontIdx_ == backIdx_; } + + inline bool full() const { return ((backIdx_ + 1) % buffer_.size()) == frontIdx_; } + + inline std::size_t size() const { + if (frontIdx_ <= backIdx_) + return backIdx_ - frontIdx_; + else + return backIdx_ + buffer_.size() - frontIdx_; + } + + inline std::size_t getBufferSize() { return buffer_.size(); } + + ~RealTimeLogger(); + + private: + struct Data { + std::stringbuf buf; }; - /// Write to an ostream object. - /// - /// The easieast is to use the macro \ref dgADD_OSTREAM_TO_RTLOG(ostr) where - /// `ostr` can be `std::cout` or an std::ofstream... - class LoggerIOStream : public LoggerStream - { - public: - LoggerIOStream (std::ostream& os) : os_ (os) {} - virtual void write (const char* c) { os_ << c; } - private: - std::ostream& os_; - }; - typedef boost::shared_ptr <LoggerStream> LoggerStreamPtr_t; - - class RealTimeLogger; - - /// \cond DEVEL - /// \brief write entries to intenal buffer. - /// - /// The entry starts when an instance is created and ends when is is deleted. - /// This class is only used by RealTimeLogger. - class RTLoggerStream - { - public: - RTLoggerStream (RealTimeLogger* logger, std::ostream& os) : logger_(logger), os_ (os) {} - template <typename T> inline RTLoggerStream& operator<< (T t) { if (logger_!=NULL) os_ << t; return *this; } - inline RTLoggerStream& operator<< (std::ostream& (*pf)(std::ostream&)) { if (logger_!=NULL) os_ << pf; return *this; } - - ~RTLoggerStream(); - private: - - RealTimeLogger* logger_; - std::ostream& os_; - }; - /// \endcond DEVEL - - /// \ingroup debug - /// - /// \brief Main class of the real-time logger. - /// - /// It is intended to be used like this: - /// \code - /// #define ENABLE_RT_LOG - /// #include <dynamic-graph/real-time-logger.h> - /// - /// // Somewhere in the main function of your executable - /// int main (int argc, char** argv) { - /// dgADD_OSTREAM_TO_RTLOG (std::cout); - /// } - /// - /// // Somewhere in your library - /// dgRTLOG() << "your message. Prefer to use \n than std::endl." - /// \endcode - /// - /// \note Thread safety. This class expects to have: - /// - only one reader: the one who take the log entries and write them somewhere. - /// - one writer at a time. Writing to the logs is **never** a blocking - /// operation. If the resource is busy, the log entry is discarded. - class DYNAMIC_GRAPH_DLLAPI RealTimeLogger - { - public: - static RealTimeLogger& instance(); - - static void destroy(); - - /// \todo add an argument to preallocate the internal string to a given size. - RealTimeLogger (const std::size_t& bufferSize); - - inline void clearOutputStreams () { outputs_.clear(); } - - inline void addOutputStream (const LoggerStreamPtr_t& os) { outputs_.push_back(os); } - - /// Write next message to output. - /// It does nothing if the buffer is empty. - /// \return true if it wrote something - bool spinOnce (); - - /// Return an object onto which a real-time thread can write. - /// The message is considered finished when the object is destroyed. - RTLoggerStream front(); - - inline void frontReady() { backIdx_ = (backIdx_+1) % buffer_.size(); wmutex.unlock(); } - - inline bool empty () const - { - return frontIdx_ == backIdx_; - } - - inline bool full () const - { - return ((backIdx_ + 1) % buffer_.size()) == frontIdx_; - } - - inline std::size_t size () const - { - if (frontIdx_ <= backIdx_) - return backIdx_ - frontIdx_; - else - return backIdx_ + buffer_.size() - frontIdx_; - } - - inline std::size_t getBufferSize () { return buffer_.size(); } - - ~RealTimeLogger (); - - private: - - struct Data { - std::stringbuf buf; - }; - - std::vector<LoggerStreamPtr_t> outputs_; - std::vector<Data*> buffer_; - /// Index of the next value to be read. - std::size_t frontIdx_; - /// Index of the slot where to write next value (does not contain valid data). - std::size_t backIdx_; - std::ostream oss_; - - /// The writer mutex. - boost::mutex wmutex; - std::size_t nbDiscarded_; - - struct thread; - - static RealTimeLogger* instance_; - static thread* thread_; - }; -} // end of namespace dynamicgraph + std::vector<LoggerStreamPtr_t> outputs_; + std::vector<Data*> buffer_; + /// Index of the next value to be read. + std::size_t frontIdx_; + /// Index of the slot where to write next value (does not contain valid data). + std::size_t backIdx_; + std::ostream oss_; + + /// The writer mutex. + boost::mutex wmutex; + std::size_t nbDiscarded_; + + struct thread; + + static RealTimeLogger* instance_; + static thread* thread_; +}; +} // end of namespace dynamicgraph #ifdef ENABLE_RT_LOG -# define dgADD_OSTREAM_TO_RTLOG(ostr) ::dynamicgraph::RealTimeLogger::instance() \ - .addOutputStream(::dynamicgraph::LoggerStreamPtr_t(new ::dynamicgraph::LoggerIOStream(ostr))) -# define dgRTLOG() ::dynamicgraph::RealTimeLogger::instance().front() -#else // ENABLE_RT_LOG -# define dgADD_OSTREAM_TO_RTLOG(ostr) struct __end_with_semicolon -# define dgRTLOG() if (1) ; else __null_stream() +#define dgADD_OSTREAM_TO_RTLOG(ostr) \ + ::dynamicgraph::RealTimeLogger::instance().addOutputStream( \ + ::dynamicgraph::LoggerStreamPtr_t(new ::dynamicgraph::LoggerIOStream(ostr))) +#define dgRTLOG() ::dynamicgraph::RealTimeLogger::instance().front() +#else // ENABLE_RT_LOG +#define dgADD_OSTREAM_TO_RTLOG(ostr) struct __end_with_semicolon +#define dgRTLOG() \ + if (1) \ + ; \ + else \ + __null_stream() #endif -#endif //! DYNAMIC_GRAPH_LOGGER_REAL_TIME_H +#endif //! DYNAMIC_GRAPH_LOGGER_REAL_TIME_H diff --git a/include/dynamic-graph/signal-array.h b/include/dynamic-graph/signal-array.h index 6900b9b470f5f8fdee47261c1adf891806957d45..1b4b2827bef7a2724786f4d77155fc43fa0a9dfc 100644 --- a/include/dynamic-graph/signal-array.h +++ b/include/dynamic-graph/signal-array.h @@ -4,188 +4,135 @@ // #ifndef DYNAMIC_GRAPH_SIGNAL_ARRAY_H -# define DYNAMIC_GRAPH_SIGNAL_ARRAY_H -# include <dynamic-graph/signal-base.h> -# include <dynamic-graph/dynamic-graph-api.h> -# include <vector> +#define DYNAMIC_GRAPH_SIGNAL_ARRAY_H +#include <dynamic-graph/signal-base.h> +#include <dynamic-graph/dynamic-graph-api.h> +#include <vector> #include <stdio.h> -namespace dynamicgraph -{ - - /// \ingroup dgraph - /// - /// \brief TODO - template<class Time> - class SignalArray_const - { - public: - static const int DEFAULT_SIZE = 20; - - protected: - std::vector< const SignalBase<Time>* > const_array; - unsigned int size,rank; - - public: - SignalArray_const<Time> (const unsigned int& sizeARG = DEFAULT_SIZE) - : const_array (sizeARG), - size (sizeARG), - rank (0) - {} - - SignalArray_const<Time> (const SignalBase<Time>& sig) - : const_array (DEFAULT_SIZE), - size (DEFAULT_SIZE), - rank (0) - { - addElmt(&sig); - } - - SignalArray_const<Time> (const SignalArray<Time>& siga) - : const_array (siga.getSize()), - size (siga.getSize ()), - rank (siga.getSize ()) - { - for (unsigned int i = 0; i < rank; ++i) - const_array[i] = &siga[i]; - } - - SignalArray_const<Time> (const SignalArray_const<Time>& siga) - : const_array(siga.getSize ()), - size(siga.getSize ()), - rank(siga.getSize ()) - { - for (unsigned int i = 0; i < rank; ++i) - const_array[i] = &siga[i]; - } - - virtual ~SignalArray_const<Time> (){} - - protected: +namespace dynamicgraph { - void addElmt (const SignalBase<Time>* el) - { - if (rank >= size) - { - size += DEFAULT_SIZE; - const_array.resize(size); - } - const_array[rank++] = el; - } +/// \ingroup dgraph +/// +/// \brief TODO +template <class Time> +class SignalArray_const { + public: + static const int DEFAULT_SIZE = 20; - public: - virtual SignalArray_const<Time>& operator<< (const SignalBase<Time>& sig) - { - addElmt (&sig); - return *this; - } + protected: + std::vector<const SignalBase<Time>*> const_array; + unsigned int size, rank; - public: - virtual const SignalBase<Time>& operator[] (const unsigned int& idx) const - { - return *const_array[idx]; - } - virtual unsigned int getSize () const - { - return rank; - } - }; + public: + SignalArray_const<Time>(const unsigned int& sizeARG = DEFAULT_SIZE) : const_array(sizeARG), size(sizeARG), rank(0) {} + SignalArray_const<Time>(const SignalBase<Time>& sig) : const_array(DEFAULT_SIZE), size(DEFAULT_SIZE), rank(0) { + addElmt(&sig); + } - template<class Time> - SignalArray_const<Time> operator<< (const SignalBase<Time>& sig1, - const SignalBase<Time>& sig2) - { - SignalArray_const<Time> res(sig1); - res<<sig2; - return res; + SignalArray_const<Time>(const SignalArray<Time>& siga) + : const_array(siga.getSize()), size(siga.getSize()), rank(siga.getSize()) { + for (unsigned int i = 0; i < rank; ++i) const_array[i] = &siga[i]; } - /// \ingroup dgraph - /// - /// \brief TODO - template<class Time> - class SignalArray : public SignalArray_const<Time> - { - public: - using SignalArray_const<Time>::DEFAULT_SIZE; - using SignalArray_const<Time>::size; - using SignalArray_const<Time>::rank; - protected: - mutable std::vector< SignalBase<Time>* > array; - - public: - SignalArray<Time> (const unsigned int& sizeARG = DEFAULT_SIZE) - : SignalArray_const<Time> (0), - array(sizeARG) - { - size=sizeARG; - } + SignalArray_const<Time>(const SignalArray_const<Time>& siga) + : const_array(siga.getSize()), size(siga.getSize()), rank(siga.getSize()) { + for (unsigned int i = 0; i < rank; ++i) const_array[i] = &siga[i]; + } - SignalArray<Time> (SignalBase<Time>& sig) - : SignalArray_const<Time> (0), - array(DEFAULT_SIZE) - { - size=DEFAULT_SIZE; - addElmt(&sig); - } + virtual ~SignalArray_const<Time>() {} - SignalArray<Time> (const SignalArray<Time>& siga) - : SignalArray_const<Time> (siga.getSize()), - array (siga.getSize()) - { - rank = siga.getSize (); - for (unsigned int i = 0; i < rank; ++i) - array[i]=&siga[i]; + protected: + void addElmt(const SignalBase<Time>* el) { + if (rank >= size) { + size += DEFAULT_SIZE; + const_array.resize(size); } + const_array[rank++] = el; + } - virtual ~SignalArray<Time> (){} + public: + virtual SignalArray_const<Time>& operator<<(const SignalBase<Time>& sig) { + addElmt(&sig); + return *this; + } - protected: + public: + virtual const SignalBase<Time>& operator[](const unsigned int& idx) const { return *const_array[idx]; } + virtual unsigned int getSize() const { return rank; } +}; + +template <class Time> +SignalArray_const<Time> operator<<(const SignalBase<Time>& sig1, const SignalBase<Time>& sig2) { + SignalArray_const<Time> res(sig1); + res << sig2; + return res; +} + +/// \ingroup dgraph +/// +/// \brief TODO +template <class Time> +class SignalArray : public SignalArray_const<Time> { + public: + using SignalArray_const<Time>::DEFAULT_SIZE; + using SignalArray_const<Time>::size; + using SignalArray_const<Time>::rank; + + protected: + mutable std::vector<SignalBase<Time>*> array; + + public: + SignalArray<Time>(const unsigned int& sizeARG = DEFAULT_SIZE) : SignalArray_const<Time>(0), array(sizeARG) { + size = sizeARG; + } - void addElmt (SignalBase<Time>* el) - { - if (rank >= size) - { - size += DEFAULT_SIZE; - array.resize(size); - } - array[rank++] = el; - } + SignalArray<Time>(SignalBase<Time>& sig) : SignalArray_const<Time>(0), array(DEFAULT_SIZE) { + size = DEFAULT_SIZE; + addElmt(&sig); + } - public: - virtual SignalArray<Time>& operator<< (SignalBase<Time>& sig) - { - addElmt(&sig); - return *this; - } + SignalArray<Time>(const SignalArray<Time>& siga) : SignalArray_const<Time>(siga.getSize()), array(siga.getSize()) { + rank = siga.getSize(); + for (unsigned int i = 0; i < rank; ++i) array[i] = &siga[i]; + } - virtual SignalArray_const<Time> - operator<< (const SignalBase<Time>& sig) const - { - SignalArray_const<Time> res (*this); - res << sig; - return res; - } + virtual ~SignalArray<Time>() {} - virtual SignalBase<Time>& operator[] (const unsigned int& idx) const - { - return *array[idx]; + protected: + void addElmt(SignalBase<Time>* el) { + if (rank >= size) { + size += DEFAULT_SIZE; + array.resize(size); } - }; + array[rank++] = el; + } + public: + virtual SignalArray<Time>& operator<<(SignalBase<Time>& sig) { + addElmt(&sig); + return *this; + } - template<class Time> - SignalArray<Time> operator<< (SignalBase<Time>& sig1, - SignalBase<Time>& sig2) - { - SignalArray<Time> res (sig1); - res << sig2; + virtual SignalArray_const<Time> operator<<(const SignalBase<Time>& sig) const { + SignalArray_const<Time> res(*this); + res << sig; return res; } - DYNAMIC_GRAPH_DLLAPI extern SignalArray<int> sotNOSIGNAL; + virtual SignalBase<Time>& operator[](const unsigned int& idx) const { return *array[idx]; } +}; + +template <class Time> +SignalArray<Time> operator<<(SignalBase<Time>& sig1, SignalBase<Time>& sig2) { + SignalArray<Time> res(sig1); + res << sig2; + return res; +} + +DYNAMIC_GRAPH_DLLAPI extern SignalArray<int> sotNOSIGNAL; -} // end of namespace dynamicgraph. +} // end of namespace dynamicgraph. -#endif //! DYNAMIC_GRAPH_SIGNAL_ARRAY_H +#endif //! DYNAMIC_GRAPH_SIGNAL_ARRAY_H diff --git a/include/dynamic-graph/signal-base.h b/include/dynamic-graph/signal-base.h index df8f1910c9ed27faf9cf87439372436faae99638..9d41c1cd52c89721b7598a94b46093ecedbf0c59 100644 --- a/include/dynamic-graph/signal-base.h +++ b/include/dynamic-graph/signal-base.h @@ -4,272 +4,183 @@ // #ifndef DYNAMIC_GRAPH_SIGNAL_BASE_H -# define DYNAMIC_GRAPH_SIGNAL_BASE_H -# include <string> -# include <sstream> -# include <typeinfo> -# include <boost/noncopyable.hpp> - -# include <dynamic-graph/fwd.hh> -# include <dynamic-graph/exception-signal.h> - - -namespace dynamicgraph -{ - - /** \brief The base class for signals: not to be used as such. - - Signal values can be accessed programmatically using the access - () or accessCopy () methods; the former directly accesses the - value of the signal, which can involve an extra computation, - while the latter accesses a cached value, or 'copy'. - */ - template<class Time> - class SignalBase : public boost::noncopyable - { - public: - explicit SignalBase(std::string name = "") - : name (name), - signalTime (0), - ready (false) - {} - - virtual ~SignalBase () - {} - - /// \name Time - /// \{ - virtual const Time& getTime () const - { - return signalTime; - } +#define DYNAMIC_GRAPH_SIGNAL_BASE_H +#include <string> +#include <sstream> +#include <typeinfo> +#include <boost/noncopyable.hpp> - virtual void setTime (const Time& t) - { - signalTime = t; - } +#include <dynamic-graph/fwd.hh> +#include <dynamic-graph/exception-signal.h> - const bool& getReady () const - { - return ready; - } +namespace dynamicgraph { - const std::string& getName () const - { - return name; - } +/** \brief The base class for signals: not to be used as such. - void getClassName(std::string & aClassName) const - { aClassName = typeid(this).name(); } + Signal values can be accessed programmatically using the access + () or accessCopy () methods; the former directly accesses the + value of the signal, which can involve an extra computation, + while the latter accesses a cached value, or 'copy'. +*/ +template <class Time> +class SignalBase : public boost::noncopyable { + public: + explicit SignalBase(std::string name = "") : name(name), signalTime(0), ready(false) {} - virtual void setPeriodTime (const Time&) - {} + virtual ~SignalBase() {} - virtual Time getPeriodTime () const - { - return 1; - } + /// \name Time + /// \{ + virtual const Time& getTime() const { return signalTime; } - /// \} + virtual void setTime(const Time& t) { signalTime = t; } - /// \name Dependencies - /// \{ + const bool& getReady() const { return ready; } - virtual void addDependency (const SignalBase<Time>&) - {} + const std::string& getName() const { return name; } - virtual void removeDependency (const SignalBase<Time>&) - {} + void getClassName(std::string& aClassName) const { aClassName = typeid(this).name(); } - virtual void clearDependencies () - {} + virtual void setPeriodTime(const Time&) {} - virtual bool needUpdate (const Time&) const - { - return ready; - } + virtual Time getPeriodTime() const { return 1; } - inline void setReady (const bool sready = true) - { - ready = sready; - } + /// \} - virtual std::ostream& - writeGraph (std::ostream& os ) const - { - return os; - } + /// \name Dependencies + /// \{ - virtual std::ostream& - displayDependencies (std::ostream& os, - const int = -1, - std::string space = "", - std::string next1 = "", - std::string = "" ) const - { - os << space << next1 << "-- "; - display(os); - return os; - } + virtual void addDependency(const SignalBase<Time>&) {} - /// \} - - /// \name Plug - /// \{ - - /* Plug the arg-signal on the <this> object. Plug-in is always - * a descending operation (the actual <this> object will call the arg-signal - * and not the opposite). - */ - virtual void plug (SignalBase<Time>* sigarg) - { - DG_THROW ExceptionSignal - (ExceptionSignal::PLUG_IMPOSSIBLE, - "Plug-in operation not possible with this signal. ", - "(while trying to plug %s on %s).", - sigarg->getName ().c_str (), - this->getName ().c_str () ); - } + virtual void removeDependency(const SignalBase<Time>&) {} - virtual void unplug () - { - DG_THROW ExceptionSignal - (ExceptionSignal::PLUG_IMPOSSIBLE, - "Plug-in operation not possible with this signal. ", - "(while trying to unplug %s).",this->getName ().c_str ()); - } + virtual void clearDependencies() {} - virtual bool isPlugged () const - { - return false; - } + virtual bool needUpdate(const Time&) const { return ready; } - virtual SignalBase<Time>* getPluged () const - { - return NULL; - } + inline void setReady(const bool sready = true) { ready = sready; } - virtual void setConstantDefault () - { - DG_THROW ExceptionSignal - (ExceptionSignal::PLUG_IMPOSSIBLE, - "Plug-in operation not possible with this signal. ", - "(while trying to save %s).", - this->getName ().c_str ()); - } + virtual std::ostream& writeGraph(std::ostream& os) const { return os; } - /// \} - - /// \name Set - /// \{ - - /* Generic set function. Should be reimplemented by the specific - * Signal. Sets a signal value - */ - virtual void set (std::istringstream&) - { - DG_THROW ExceptionSignal - (ExceptionSignal::SET_IMPOSSIBLE, - "Set operation not possible with this signal. ", - "(while trying to set %s).", - this->getName ().c_str () ); - } + virtual std::ostream& displayDependencies(std::ostream& os, const int = -1, std::string space = "", + std::string next1 = "", std::string = "") const { + os << space << next1 << "-- "; + display(os); + return os; + } - virtual void get (std::ostream&) const - { - DG_THROW ExceptionSignal - (ExceptionSignal::SET_IMPOSSIBLE, - "Get operation not possible with this signal. ", - "(while trying to get %s).", - this->getName ().c_str ()); - } + /// \} - virtual inline void recompute (const Time &) - { - DG_THROW ExceptionSignal - (ExceptionSignal::SET_IMPOSSIBLE, - "Recompute operation not possible with this signal. ", - "(while trying to recompute %s).", - this->getName ().c_str ()); - } + /// \name Plug + /// \{ - virtual void trace (std::ostream&) const - { - DG_THROW ExceptionSignal - (ExceptionSignal::SET_IMPOSSIBLE, - "Trace operation not possible with this signal. ", - "(while trying to trace %s).", - this->getName ().c_str () ); - } + /* Plug the arg-signal on the <this> object. Plug-in is always + * a descending operation (the actual <this> object will call the arg-signal + * and not the opposite). + */ + virtual void plug(SignalBase<Time>* sigarg) { + DG_THROW ExceptionSignal(ExceptionSignal::PLUG_IMPOSSIBLE, "Plug-in operation not possible with this signal. ", + "(while trying to plug %s on %s).", sigarg->getName().c_str(), this->getName().c_str()); + } - /// \} + virtual void unplug() { + DG_THROW ExceptionSignal(ExceptionSignal::PLUG_IMPOSSIBLE, "Plug-in operation not possible with this signal. ", + "(while trying to unplug %s).", this->getName().c_str()); + } - /// \name Display - /// \{ + virtual bool isPlugged() const { return false; } - virtual std::ostream& display (std::ostream& os) const - { - os << "Sig:" << name; - return os; - } + virtual SignalBase<Time>* getPluged() const { return NULL; } - std::string shortName () const - { - std::istringstream iss (name); - const int SIZE = 128; - char buffer[SIZE]; - while (iss.good ()) - { - iss.getline(buffer,SIZE,':'); - } - const std::string res (buffer); - return res; - } - /// \} - - /// \name Information providers - /// \{ - - virtual void ExtractNodeAndLocalNames (std::string& LocalName, - std::string & NodeName) const - { - std::string fullname = this->getName (); - - size_t IdxPosLocalName = fullname.rfind (":"); - LocalName = fullname.substr (IdxPosLocalName + 1, - fullname.length () - IdxPosLocalName + 1); - size_t IdxPosNodeNameStart = fullname.find ("("); - size_t IdxPosNodeNameEnd = fullname.find (")"); - NodeName = fullname.substr (IdxPosNodeNameStart + 1, - IdxPosNodeNameEnd - IdxPosNodeNameStart - 1); - } + virtual void setConstantDefault() { + DG_THROW ExceptionSignal(ExceptionSignal::PLUG_IMPOSSIBLE, "Plug-in operation not possible with this signal. ", + "(while trying to save %s).", this->getName().c_str()); + } + + /// \} + + /// \name Set + /// \{ + + /* Generic set function. Should be reimplemented by the specific + * Signal. Sets a signal value + */ + virtual void set(std::istringstream&) { + DG_THROW ExceptionSignal(ExceptionSignal::SET_IMPOSSIBLE, "Set operation not possible with this signal. ", + "(while trying to set %s).", this->getName().c_str()); + } + + virtual void get(std::ostream&) const { + DG_THROW ExceptionSignal(ExceptionSignal::SET_IMPOSSIBLE, "Get operation not possible with this signal. ", + "(while trying to get %s).", this->getName().c_str()); + } + + virtual inline void recompute(const Time&) { + DG_THROW ExceptionSignal(ExceptionSignal::SET_IMPOSSIBLE, "Recompute operation not possible with this signal. ", + "(while trying to recompute %s).", this->getName().c_str()); + } + + virtual void trace(std::ostream&) const { + DG_THROW ExceptionSignal(ExceptionSignal::SET_IMPOSSIBLE, "Trace operation not possible with this signal. ", + "(while trying to trace %s).", this->getName().c_str()); + } + + /// \} + + /// \name Display + /// \{ - /// \} - - /// \name Test - /// \{ - virtual void checkCompatibility () - { - DG_THROW ExceptionSignal - (ExceptionSignal::PLUG_IMPOSSIBLE, - "Abstract signal not compatible with anything.", - "(while trying to plug <%s>).", - this->getName ().c_str ()); + virtual std::ostream& display(std::ostream& os) const { + os << "Sig:" << name; + return os; + } + + std::string shortName() const { + std::istringstream iss(name); + const int SIZE = 128; + char buffer[SIZE]; + while (iss.good()) { + iss.getline(buffer, SIZE, ':'); } - /// \} - - protected: - std::string name; - Time signalTime; - bool ready; - }; - - /// Forward to a virtual fonction. - template<class Time> - std::ostream& operator<< (std::ostream& os, const SignalBase<Time>& sig) - { - return sig.display(os); + const std::string res(buffer); + return res; } -} // end of namespace dynamicgraph. + /// \} + + /// \name Information providers + /// \{ -#endif //! DYNAMIC_GRAPH_SIGNAL_BASE_H + virtual void ExtractNodeAndLocalNames(std::string& LocalName, std::string& NodeName) const { + std::string fullname = this->getName(); + + size_t IdxPosLocalName = fullname.rfind(":"); + LocalName = fullname.substr(IdxPosLocalName + 1, fullname.length() - IdxPosLocalName + 1); + size_t IdxPosNodeNameStart = fullname.find("("); + size_t IdxPosNodeNameEnd = fullname.find(")"); + NodeName = fullname.substr(IdxPosNodeNameStart + 1, IdxPosNodeNameEnd - IdxPosNodeNameStart - 1); + } + + /// \} + + /// \name Test + /// \{ + virtual void checkCompatibility() { + DG_THROW ExceptionSignal(ExceptionSignal::PLUG_IMPOSSIBLE, "Abstract signal not compatible with anything.", + "(while trying to plug <%s>).", this->getName().c_str()); + } + /// \} + + protected: + std::string name; + Time signalTime; + bool ready; +}; + +/// Forward to a virtual fonction. +template <class Time> +std::ostream& operator<<(std::ostream& os, const SignalBase<Time>& sig) { + return sig.display(os); +} +} // end of namespace dynamicgraph. + +#endif //! DYNAMIC_GRAPH_SIGNAL_BASE_H diff --git a/include/dynamic-graph/signal-cast-helper.h b/include/dynamic-graph/signal-cast-helper.h index ac10a3a93e33d08c93a378acaac409a0c1b45480..89784ae587417342f391a0f4ccf751621259a693 100644 --- a/include/dynamic-graph/signal-cast-helper.h +++ b/include/dynamic-graph/signal-cast-helper.h @@ -3,110 +3,91 @@ // #ifndef DYNAMIC_GRAPH_SIGNAL_CASTER_HELPER_HH -# define DYNAMIC_GRAPH_SIGNAL_CASTER_HELPER_HH -# include <map> -# include <typeinfo> -# include <vector> - -# include <boost/any.hpp> -# include <boost/format.hpp> -# include <boost/function/function1.hpp> -# include <boost/function/function2.hpp> -# include <boost/lexical_cast.hpp> -# include <boost/tuple/tuple.hpp> +#define DYNAMIC_GRAPH_SIGNAL_CASTER_HELPER_HH +#include <map> +#include <typeinfo> +#include <vector> + +#include <boost/any.hpp> +#include <boost/format.hpp> +#include <boost/function/function1.hpp> +#include <boost/function/function2.hpp> +#include <boost/lexical_cast.hpp> +#include <boost/tuple/tuple.hpp> #include <dynamic-graph/eigen-io.h> -# include <dynamic-graph/dynamic-graph-api.h> -# include "dynamic-graph/exception-signal.h" -# include "dynamic-graph/signal-caster.h" - -namespace dynamicgraph -{ - - /* --- NON GENERIC CASTER ------------------------------------------------- */ - - /// This class can be used to register default casts, i.e. casts - /// already supported by the object to an std::iostream through the - /// operators >> and << . - template<typename T> - class DefaultCastRegisterer : public SignalCastRegisterer - { - public: - DefaultCastRegisterer () - : SignalCastRegisterer (typeid(T), disp, cast, trace) - {} - - static boost::any cast (std::istringstream& iss); - - static void disp (const boost::any& object, std::ostream& os) - { - os << boost::any_cast<T> (object) << std::endl; - } - - static void trace (const boost::any& object, std::ostream& os) - { - disp(object,os); - } - }; - - /// A default version of the caster, to serialize directly from - /// std::in. - template <typename T> - boost::any - DefaultCastRegisterer<T>::cast (std::istringstream& iss) - { - T inst; - iss >> inst; - if (iss.fail ()) - { - boost::format fmt ("failed to serialize %s "); - fmt % iss.str (); - throw ExceptionSignal(ExceptionSignal::GENERIC, fmt.str ()); - } - return inst; - } - - - /* --- GENERIC CASTER ----------------------------------------------------- */ - /*! - * This class is only used to group together static functions who differ by - * a template parameter. It is never actually instanced (the private constructor - * makes sure of that). - * Typical use of this class is to add the caster in the dg graph: - * dynamicgraph::SignalCastRegisterer sotCastRegisterer_TYPE - * (typeid(TYPE), - * SignalCast<TYPE>::disp_, - * SignalCast<TYPE>::cast_, - * SignalCast<TYPE>::trace_); - - * NMSD: I don't really understand the use of this additional class. IMHO - * (comme on dit), it should be possible to rewrite the same-spec macros - * using specialization of the template class DefaultCastRegisterer. No? - */ - template< class T > - class SignalCast - { - public: - static T cast( std::istringstream& ) { throw 1;} - static void disp( const T&,std::ostream&) { throw 1; } - static void trace( const T& t,std::ostream& os ) { disp(t,os); } - public: - // adapter functions for SignalCast - static boost::any cast_( std::istringstream& stringValue ) { - return boost::any_cast<T>(cast(stringValue)); - } - static void disp_( const boost::any& t,std::ostream& os ) { - disp(boost::any_cast<T>(t), os); - } - static void trace_( const boost::any& t,std::ostream& os ) { - trace(boost::any_cast<T>(t),os); - } - private: - SignalCast() {} - }; - -} // namespace dynamicgraph +#include <dynamic-graph/dynamic-graph-api.h> +#include "dynamic-graph/exception-signal.h" +#include "dynamic-graph/signal-caster.h" + +namespace dynamicgraph { + +/* --- NON GENERIC CASTER ------------------------------------------------- */ + +/// This class can be used to register default casts, i.e. casts +/// already supported by the object to an std::iostream through the +/// operators >> and << . +template <typename T> +class DefaultCastRegisterer : public SignalCastRegisterer { + public: + DefaultCastRegisterer() : SignalCastRegisterer(typeid(T), disp, cast, trace) {} + + static boost::any cast(std::istringstream& iss); + + static void disp(const boost::any& object, std::ostream& os) { os << boost::any_cast<T>(object) << std::endl; } + + static void trace(const boost::any& object, std::ostream& os) { disp(object, os); } +}; + +/// A default version of the caster, to serialize directly from +/// std::in. +template <typename T> +boost::any DefaultCastRegisterer<T>::cast(std::istringstream& iss) { + T inst; + iss >> inst; + if (iss.fail()) { + boost::format fmt("failed to serialize %s "); + fmt % iss.str(); + throw ExceptionSignal(ExceptionSignal::GENERIC, fmt.str()); + } + return inst; +} + +/* --- GENERIC CASTER ----------------------------------------------------- */ +/*! + * This class is only used to group together static functions who differ by + * a template parameter. It is never actually instanced (the private constructor + * makes sure of that). + * Typical use of this class is to add the caster in the dg graph: + * dynamicgraph::SignalCastRegisterer sotCastRegisterer_TYPE + * (typeid(TYPE), + * SignalCast<TYPE>::disp_, + * SignalCast<TYPE>::cast_, + * SignalCast<TYPE>::trace_); + + * NMSD: I don't really understand the use of this additional class. IMHO + * (comme on dit), it should be possible to rewrite the same-spec macros + * using specialization of the template class DefaultCastRegisterer. No? + */ +template <class T> +class SignalCast { + public: + static T cast(std::istringstream&) { throw 1; } + static void disp(const T&, std::ostream&) { throw 1; } + static void trace(const T& t, std::ostream& os) { disp(t, os); } + + public: + // adapter functions for SignalCast + static boost::any cast_(std::istringstream& stringValue) { return boost::any_cast<T>(cast(stringValue)); } + static void disp_(const boost::any& t, std::ostream& os) { disp(boost::any_cast<T>(t), os); } + static void trace_(const boost::any& t, std::ostream& os) { trace(boost::any_cast<T>(t), os); } + + private: + SignalCast() {} +}; + +} // namespace dynamicgraph /* -------------------------------------------------------------------------- */ /* --- MACROS --------------------------------------------------------------- */ @@ -116,88 +97,79 @@ namespace dynamicgraph * order for casts to be registered. */ -#define DG_SIGNAL_CAST_DECLARATION(TYPE) \ - ::dynamicgraph::SignalCastRegisterer sotCastRegisterer_##TYPE \ - (typeid(TYPE), \ - SignalCast<TYPE>::disp_, \ - SignalCast<TYPE>::cast_, \ - SignalCast<TYPE>::trace_) +#define DG_SIGNAL_CAST_DECLARATION(TYPE) \ + ::dynamicgraph::SignalCastRegisterer sotCastRegisterer_##TYPE(typeid(TYPE), SignalCast<TYPE>::disp_, \ + SignalCast<TYPE>::cast_, SignalCast<TYPE>::trace_) -#define DG_SIGNAL_CAST_DECLARATION_NAMED(TYPE,NAME) \ - ::dynamicgraph::SignalCastRegisterer sotCastRegisterer_##NAME \ - (typeid(TYPE), \ - SignalCast<TYPE>::disp_, \ - SignalCast<TYPE>::cast_, \ - SignalCast<TYPE>::trace_) +#define DG_SIGNAL_CAST_DECLARATION_NAMED(TYPE, NAME) \ + ::dynamicgraph::SignalCastRegisterer sotCastRegisterer_##NAME(typeid(TYPE), SignalCast<TYPE>::disp_, \ + SignalCast<TYPE>::cast_, SignalCast<TYPE>::trace_) /* Standard definition macros: the three functions can be specified * in the macros. To define then in the cpp, just put ';' in the args. */ -#define DG_SIGNAL_CAST_FULL_DEFINITION(TYPE,CAST,DISP,TRACE) \ -template<> \ - class SignalCast<TYPE> \ -{ \ -public: \ - static TYPE cast( std::istringstream& iss ) CAST \ - static void disp( TYPE const& t,std::ostream& os ) DISP \ - static void trace( TYPE const& t,std::ostream& os ) TRACE \ -public: \ - static boost::any cast_( std::istringstream& stringValue ) { \ - return boost::any_cast<TYPE>(cast(stringValue)); \ - } \ - static void disp_( const boost::any& t,std::ostream& os ) { \ - disp(boost::any_cast<TYPE>(t), os); \ - } \ - static void trace_( const boost::any& t,std::ostream& os ) { \ - trace(boost::any_cast<TYPE>(t),os); \ - } \ -} +#define DG_SIGNAL_CAST_FULL_DEFINITION(TYPE, CAST, DISP, TRACE) \ + template <> \ + class SignalCast<TYPE> { \ + public: \ + static TYPE cast(std::istringstream& iss) CAST static void disp(TYPE const& t, std::ostream& os) DISP \ + static void trace(TYPE const& t, std::ostream& os) TRACE public : static boost::any \ + cast_(std::istringstream& stringValue) { \ + return boost::any_cast<TYPE>(cast(stringValue)); \ + } \ + static void disp_(const boost::any& t, std::ostream& os) { disp(boost::any_cast<TYPE>(t), os); } \ + static void trace_(const boost::any& t, std::ostream& os) { trace(boost::any_cast<TYPE>(t), os); } \ + } /* Standard definition macros: the functions <cast> and <disp> have * to be implemented in the cpp files. The function <trace> is * implemented as a proxy on <disp>. */ -#define DG_SIGNAL_CAST_DEFINITION_HPP(TYPE) \ - DG_SIGNAL_CAST_FULL_DEFINITION(TYPE,;,;,{ disp(t,os); }) +#define DG_SIGNAL_CAST_DEFINITION_HPP(TYPE) DG_SIGNAL_CAST_FULL_DEFINITION(TYPE, ;, ;, { disp(t, os); }) /* Lazy definition: <cast> and <disp> are to proxys on the standard * std input (>>) and output (<<). The function <trace> has to be * implemented in the cpp. */ -#define DG_SIGNAL_CAST_DEFINITION_TRACE_HPP(TYPE,TRACE) \ - DG_SIGNAL_CAST_FULL_DEFINITION(TYPE, \ - {TYPE res; iss >> res; return res; }, \ - { os << t <<std::endl; }, \ - TRACE ) +#define DG_SIGNAL_CAST_DEFINITION_TRACE_HPP(TYPE, TRACE) \ + DG_SIGNAL_CAST_FULL_DEFINITION(TYPE, \ + { \ + TYPE res; \ + iss >> res; \ + return res; \ + }, \ + { os << t << std::endl; }, TRACE) /* Lazy lazy definition: the three functions are implemented as * proxys on std::io operation. */ -#define DG_SIGNAL_CAST_DEFINITION(TYPE) \ - DG_SIGNAL_CAST_FULL_DEFINITION(TYPE, \ - {TYPE res; iss >> res; return res; }, \ - { os << t <<std::endl; }, \ - { disp(t,os); }) +#define DG_SIGNAL_CAST_DEFINITION(TYPE) \ + DG_SIGNAL_CAST_FULL_DEFINITION(TYPE, \ + { \ + TYPE res; \ + iss >> res; \ + return res; \ + }, \ + { os << t << std::endl; }, { disp(t, os); }) /* Lazy definition of <cast> and <disp> with implementation of * <trace> in the cpp. */ -#define DG_SIGNAL_CAST_DEFINITION_TRACE(TYPE) \ - DG_SIGNAL_CAST_FULL_DEFINITION(TYPE, \ - {TYPE res; iss >> res; return res; }, \ - { os << t <<std::endl; }, \ - ;) +#define DG_SIGNAL_CAST_DEFINITION_TRACE(TYPE) \ + DG_SIGNAL_CAST_FULL_DEFINITION(TYPE, \ + { \ + TYPE res; \ + iss >> res; \ + return res; \ + }, \ + { os << t << std::endl; }, \ + ;) /* Macro to add the define SignalCast in the dg graph. Typical use is: * DG_ADD_CASTER( Matrix,matrix ) */ -#define DG_ADD_CASTER(TYPE,ID) \ - ::dynamicgraph::SignalCastRegisterer sotCastRegisterer_##ID \ - (typeid(TYPE), \ - SignalCast<TYPE>::disp_, \ - SignalCast<TYPE>::cast_, \ - SignalCast<TYPE>::trace_) - - +#define DG_ADD_CASTER(TYPE, ID) \ + ::dynamicgraph::SignalCastRegisterer sotCastRegisterer_##ID(typeid(TYPE), SignalCast<TYPE>::disp_, \ + SignalCast<TYPE>::cast_, SignalCast<TYPE>::trace_) #endif // #ifndef DYNAMIC_GRAPH_SIGNAL_CASTER_HELPER_HH diff --git a/include/dynamic-graph/signal-caster.h b/include/dynamic-graph/signal-caster.h index 9bbf6cb355667872ac02ccafe3e7b486404c53b6..35ce044d56d711406f00e4be9b7c7be48b43f444 100644 --- a/include/dynamic-graph/signal-caster.h +++ b/include/dynamic-graph/signal-caster.h @@ -3,127 +3,112 @@ // #ifndef DYNAMIC_GRAPH_SIGNAL_CASTER_HH -# define DYNAMIC_GRAPH_SIGNAL_CASTER_HH -# include <map> -# include <typeinfo> -# include <vector> +#define DYNAMIC_GRAPH_SIGNAL_CASTER_HH +#include <map> +#include <typeinfo> +#include <vector> -# include <boost/any.hpp> -# include <boost/format.hpp> -# include <boost/function/function1.hpp> -# include <boost/function/function2.hpp> -# include <boost/lexical_cast.hpp> -# include <boost/tuple/tuple.hpp> +#include <boost/any.hpp> +#include <boost/format.hpp> +#include <boost/function/function1.hpp> +#include <boost/function/function2.hpp> +#include <boost/lexical_cast.hpp> +#include <boost/tuple/tuple.hpp> -# include <dynamic-graph/dynamic-graph-api.h> -# include "dynamic-graph/exception-signal.h" +#include <dynamic-graph/dynamic-graph-api.h> +#include "dynamic-graph/exception-signal.h" -namespace dynamicgraph -{ - /// This singleton class allows serialization of a number of objects into - /// (disp) and from (cast) std i/o streams. - /// - /// The transformation is done at run-time, i.e. SignalCaster - /// doesn't know about the type of objects it casts to. - /// - /// It also allows registering of user-defined casts. A cast is - /// identified by the compiler. The mapping from a type to a - /// serialization function is dynamic, hence it is more complex than - /// a typical template-based compile-time resolve. So disp, cast and - /// trace are costly functions and should be used as such. - class DYNAMIC_GRAPH_DLLAPI SignalCaster - { - public: - virtual ~SignalCaster (); - /// Destroy the unique instance. - static void destroy(); - /// Typedef of displayer functions that take an encapsulated 'any' - /// object and displays, cast, or trace it on an output stream - /// (serialization). - typedef boost::function2<void, const boost::any&, std::ostream&> - displayer_type; - typedef boost::function1<boost::any, std::istringstream&> caster_type; - typedef boost::function2<void, const boost::any&, std::ostream&> - tracer_type; +namespace dynamicgraph { +/// This singleton class allows serialization of a number of objects into +/// (disp) and from (cast) std i/o streams. +/// +/// The transformation is done at run-time, i.e. SignalCaster +/// doesn't know about the type of objects it casts to. +/// +/// It also allows registering of user-defined casts. A cast is +/// identified by the compiler. The mapping from a type to a +/// serialization function is dynamic, hence it is more complex than +/// a typical template-based compile-time resolve. So disp, cast and +/// trace are costly functions and should be used as such. +class DYNAMIC_GRAPH_DLLAPI SignalCaster { + public: + virtual ~SignalCaster(); + /// Destroy the unique instance. + static void destroy(); + /// Typedef of displayer functions that take an encapsulated 'any' + /// object and displays, cast, or trace it on an output stream + /// (serialization). + typedef boost::function2<void, const boost::any&, std::ostream&> displayer_type; + typedef boost::function1<boost::any, std::istringstream&> caster_type; + typedef boost::function2<void, const boost::any&, std::ostream&> tracer_type; - /// Get a reference to the unique object of the class. - static SignalCaster* getInstance(void); - /// Displays an object using a registered displayer function. - void disp (const boost::any& object, std::ostream& os); - /// Traces an object using a registered trace function. - void trace (const boost::any& object, std::ostream& os); - /// Casts an object using a registered cast function. - boost::any cast (const std::type_info&, std::istringstream& iss); - /// Registers a cast. - void registerCast (const std::type_info& type, displayer_type displayer, - caster_type caster, tracer_type tracer); - /// Unregister a cast. - void unregisterCast (const std::type_info& type); - /// Checks if there is a displayer registered with type_name. - bool existsCast (const std::type_info& type) const; - /// Return the list of type names registered. - std::vector<std::string> listTypenames () const; - private: - /// Container for the three cast functions. - typedef boost::tuple<displayer_type, caster_type, tracer_type> - cast_functions_type; + /// Get a reference to the unique object of the class. + static SignalCaster* getInstance(void); + /// Displays an object using a registered displayer function. + void disp(const boost::any& object, std::ostream& os); + /// Traces an object using a registered trace function. + void trace(const boost::any& object, std::ostream& os); + /// Casts an object using a registered cast function. + boost::any cast(const std::type_info&, std::istringstream& iss); + /// Registers a cast. + void registerCast(const std::type_info& type, displayer_type displayer, caster_type caster, tracer_type tracer); + /// Unregister a cast. + void unregisterCast(const std::type_info& type); + /// Checks if there is a displayer registered with type_name. + bool existsCast(const std::type_info& type) const; + /// Return the list of type names registered. + std::vector<std::string> listTypenames() const; - /// \brief Retrieve cast structure from its name. - cast_functions_type& getCast (const std::string& type_name); + private: + /// Container for the three cast functions. + typedef boost::tuple<displayer_type, caster_type, tracer_type> cast_functions_type; - /// This map associates the typename of objects and the corresponding - /// using boost::function with 'compatible' syntax - std::map<std::string, cast_functions_type> functions_; + /// \brief Retrieve cast structure from its name. + cast_functions_type& getCast(const std::string& type_name); - std::map<std::string, const std::type_info*> type_info_; + /// This map associates the typename of objects and the corresponding + /// using boost::function with 'compatible' syntax + std::map<std::string, cast_functions_type> functions_; - private: - explicit SignalCaster (); - /// Pointer to the unique instance of the class. - static SignalCaster* instance_; - }; + std::map<std::string, const std::type_info*> type_info_; - ///The SignalCast registerer class. Can be used to automatically - /// register a cast when instanced somewhere in a cpp file. Pass the - /// typeid () of the type you want to register a cast to as the first - /// argument. The code is provided here so the class does not need - /// to be exported. - class DYNAMIC_GRAPH_DLLAPI SignalCastRegisterer - { - public: - inline SignalCastRegisterer (const std::type_info& type, - SignalCaster::displayer_type displayer, - SignalCaster::caster_type caster, - SignalCaster::tracer_type tracer) - { - SignalCaster::getInstance()->registerCast(type, displayer, - caster, tracer); - } - }; + private: + explicit SignalCaster(); + /// Pointer to the unique instance of the class. + static SignalCaster* instance_; +}; - - /// Global signal cast template (helper) functions - /// - /// Using these avoid using the typeid () operator and keeps the - /// implementation details hidden. - template<typename T> - void signal_disp (const T& value, std::ostream& os) - { - SignalCaster::getInstance()->disp(value, os); +/// The SignalCast registerer class. Can be used to automatically +/// register a cast when instanced somewhere in a cpp file. Pass the +/// typeid () of the type you want to register a cast to as the first +/// argument. The code is provided here so the class does not need +/// to be exported. +class DYNAMIC_GRAPH_DLLAPI SignalCastRegisterer { + public: + inline SignalCastRegisterer(const std::type_info& type, SignalCaster::displayer_type displayer, + SignalCaster::caster_type caster, SignalCaster::tracer_type tracer) { + SignalCaster::getInstance()->registerCast(type, displayer, caster, tracer); } +}; - template<typename T> - T signal_cast(std::istringstream& iss) - { - return boost::any_cast<T>(SignalCaster::getInstance()->cast(typeid(T), - iss)); - } +/// Global signal cast template (helper) functions +/// +/// Using these avoid using the typeid () operator and keeps the +/// implementation details hidden. +template <typename T> +void signal_disp(const T& value, std::ostream& os) { + SignalCaster::getInstance()->disp(value, os); +} - template<typename T> - void signal_trace (const T& value, std::ostream& os) - { - SignalCaster::getInstance()->trace(value, os); - } -} // end of namespace dynamicgraph. +template <typename T> +T signal_cast(std::istringstream& iss) { + return boost::any_cast<T>(SignalCaster::getInstance()->cast(typeid(T), iss)); +} + +template <typename T> +void signal_trace(const T& value, std::ostream& os) { + SignalCaster::getInstance()->trace(value, os); +} +} // end of namespace dynamicgraph. -#endif //! DYNAMIC_GRAPH_SIGNAL_CASTER_HH +#endif //! DYNAMIC_GRAPH_SIGNAL_CASTER_HH diff --git a/include/dynamic-graph/signal-helper.h b/include/dynamic-graph/signal-helper.h index a8d814dce4e399a8a057dd801b589b64cc1cae0e..db69bb2230bd0ef53cfee3f19c2dcaa76fa38ba6 100644 --- a/include/dynamic-graph/signal-helper.h +++ b/include/dynamic-graph/signal-helper.h @@ -19,55 +19,55 @@ /* --- MACROS ---------------------------------------------------------- */ #define SIGNAL_OUT_FUNCTION_NAME(name) name##SOUT_function -#define DECLARE_SIGNAL( name,IO,type ) ::dynamicgraph::Signal<type,int> m_##name##S##IO -#define CONSTRUCT_SIGNAL( name,IO,type ) m_##name##S##IO( getClassName()+"("+getName()+")::"+#IO+"put("+#type+")::"+#name ) -#define BIND_SIGNAL_TO_FUNCTION(name,IO,type) m_##name##S##IO.setFunction(boost::bind(&EntityClassName::SIGNAL_OUT_FUNCTION_NAME(name),this,_1,_2)); +#define DECLARE_SIGNAL(name, IO, type) ::dynamicgraph::Signal<type, int> m_##name##S##IO +#define CONSTRUCT_SIGNAL(name, IO, type) \ + m_##name##S##IO(getClassName() + "(" + getName() + ")::" + #IO + "put(" + #type + ")::" + #name) +#define BIND_SIGNAL_TO_FUNCTION(name, IO, type) \ + m_##name##S##IO.setFunction(boost::bind(&EntityClassName::SIGNAL_OUT_FUNCTION_NAME(name), this, _1, _2)); /**/ -#define DECLARE_SIGNAL_IN( name,type ) ::dynamicgraph::SignalPtr<type,int> m_##name##SIN -#define CONSTRUCT_SIGNAL_IN( name,type ) m_##name##SIN( NULL,getClassName()+"("+getName()+")::input("+#type+")::"+#name ) +#define DECLARE_SIGNAL_IN(name, type) ::dynamicgraph::SignalPtr<type, int> m_##name##SIN +#define CONSTRUCT_SIGNAL_IN(name, type) \ + m_##name##SIN(NULL, getClassName() + "(" + getName() + ")::input(" + #type + ")::" + #name) /**/ -#define DECLARE_SIGNAL_OUT_FUNCTION(name,type) \ - type& SIGNAL_OUT_FUNCTION_NAME(name)(type&,int) +#define DECLARE_SIGNAL_OUT_FUNCTION(name, type) type& SIGNAL_OUT_FUNCTION_NAME(name)(type&, int) -#define DEFINE_SIGNAL_OUT_FUNCTION(name,type) \ - type& EntityClassName::SIGNAL_OUT_FUNCTION_NAME(name)(type& s,int iter) +#define DEFINE_SIGNAL_OUT_FUNCTION(name, type) \ + type& EntityClassName::SIGNAL_OUT_FUNCTION_NAME(name)(type & s, int iter) -#define SIGNAL_OUT_FUNCTION( name ) name##SOUT_function - -#define DECLARE_SIGNAL_OUT( name,type ) \ - public: \ - ::dynamicgraph::SignalTimeDependent<type,int> m_##name##SOUT; \ - protected: \ - type& SIGNAL_OUT_FUNCTION(name)( type&,int ) - -#define CONSTRUCT_SIGNAL_OUT( name,type,dep ) \ - m_##name##SOUT( boost::bind(& EntityClassName::name##SOUT_function,this,_1,_2), \ - dep,getClassName()+"("+getName()+")::output("+#type+")::"+#name ) +#define SIGNAL_OUT_FUNCTION(name) name##SOUT_function +#define DECLARE_SIGNAL_OUT(name, type) \ + public: \ + ::dynamicgraph::SignalTimeDependent<type, int> m_##name##SOUT; \ + \ + protected: \ + type& SIGNAL_OUT_FUNCTION(name)(type&, int) +#define CONSTRUCT_SIGNAL_OUT(name, type, dep) \ + m_##name##SOUT(boost::bind(&EntityClassName::name##SOUT_function, this, _1, _2), dep, \ + getClassName() + "(" + getName() + ")::output(" + #type + ")::" + #name) /**************** INNER SIGNALS *******************/ #define SIGNAL_INNER_FUNCTION_NAME(name) name##SINNER_function -#define DECLARE_SIGNAL_INNER_FUNCTION(name,type) \ - type& SIGNAL_INNER_FUNCTION_NAME(name)(type&,int) - -#define DEFINE_SIGNAL_INNER_FUNCTION(name,type) \ - type& EntityClassName::SIGNAL_INNER_FUNCTION_NAME(name)(type& s,int iter) +#define DECLARE_SIGNAL_INNER_FUNCTION(name, type) type& SIGNAL_INNER_FUNCTION_NAME(name)(type&, int) -#define DECLARE_SIGNAL_INNER(name,type) \ - public: \ - ::dynamicgraph::SignalTimeDependent<type,int> m_##name##SINNER;\ - protected: \ - DECLARE_SIGNAL_INNER_FUNCTION(name,type) +#define DEFINE_SIGNAL_INNER_FUNCTION(name, type) \ + type& EntityClassName::SIGNAL_INNER_FUNCTION_NAME(name)(type & s, int iter) -#define CONSTRUCT_SIGNAL_INNER( name,type,dep ) \ - m_##name##SINNER( boost::bind(&EntityClassName::name##SINNER_function,this,_1,_2), \ - dep,getClassName()+"("+getName()+")::inner("+#type+")::"+#name ) +#define DECLARE_SIGNAL_INNER(name, type) \ + public: \ + ::dynamicgraph::SignalTimeDependent<type, int> m_##name##SINNER; \ + \ + protected: \ + DECLARE_SIGNAL_INNER_FUNCTION(name, type) +#define CONSTRUCT_SIGNAL_INNER(name, type, dep) \ + m_##name##SINNER(boost::bind(&EntityClassName::name##SINNER_function, this, _1, _2), dep, \ + getClassName() + "(" + getName() + ")::inner(" + #type + ")::" + #name) -#endif // __dynamic_graph_signal_helper_H__ +#endif // __dynamic_graph_signal_helper_H__ diff --git a/include/dynamic-graph/signal-ptr.h b/include/dynamic-graph/signal-ptr.h index 69296f972bf330dccb35a9ec8d195f75875235fe..e4759472ee22190a774dfba2be2090b5cc5c91db 100644 --- a/include/dynamic-graph/signal-ptr.h +++ b/include/dynamic-graph/signal-ptr.h @@ -6,137 +6,129 @@ #ifndef DYNAMIC_GRAPH_SIGNAL_PTR_H #define DYNAMIC_GRAPH_SIGNAL_PTR_H -# include <dynamic-graph/exception-signal.h> -# include <dynamic-graph/signal.h> - -# include <dynamic-graph/deprecated.hh> - -namespace dynamicgraph -{ - /// \ingroup dgraph - /// - /// \brief This is the only type of signal that can be plugged to, - /// using the plug () command. - /// - /// In that sense, when plugged into, it acts as a "pointer" to the - /// input signal, hence the name. Operator -> is also overloaded and - /// can be used to access the pointed signal. - template<class T, class Time> - class SignalPtr : public virtual Signal<T,Time> - { - public: - using SignalBase<Time>::getName; - - protected: - Signal<T,Time>* signalPtr; - bool modeNoThrow; - bool transmitAbstract; - SignalBase<Time> * abstractTransmitter; - T* transmitAbstractData; - - inline bool autoref () const - { - return signalPtr == this; - } - - public: /* --- CONSTRUCTORS --- */ - - SignalPtr (Signal<T,Time>* ptr, std::string name="") - : Signal<T,Time> (name), - signalPtr (ptr), - modeNoThrow (false), - transmitAbstract (false), - abstractTransmitter (NULL) - {} - - virtual ~SignalPtr () - { - signalPtr = NULL; - } - - public: /* --- PLUG-IN OPERATION --- */ - - Signal<T,Time>* getPtr (); // throw - const Signal<T,Time>* getPtr () const; // throw - SignalBase<Time>* getAbstractPtr (); // throw - const SignalBase<Time>* getAbstractPtr () const; // throw - virtual void plug( SignalBase<Time>* ref ); - - virtual void unplug () { plug(NULL); } - - virtual bool isPlugged () const { return (NULL!=signalPtr); } - virtual SignalBase<Time>* getPluged () const { return signalPtr; } - virtual bool isAbstractPluged () const; - virtual const Time& getTime () const; - - /* Equivalent operator-like definitions. */ - inline Signal<T,Time>* operator-> () { return getPtr (); } - inline const Signal<T,Time>* operator-> () const { return getPtr (); } - inline Signal<T,Time>& operator* () { return *getPtr (); } - inline const Signal<T,Time>& operator* () const { return *getPtr (); } - inline operator bool () const { return isPlugged (); } - - public: /* --- INHERITANCE --- */ - - virtual bool needUpdate( const Time& t ) const ; - virtual std::ostream& writeGraph(std::ostream& os) const; - virtual std::ostream& display( std::ostream& os ) const; - - /* For compatibility, .access () is equivalent to ->access (). For explicit - * pointer dereference : - * Prefere -> () to () - */ - virtual const T& operator ()( const Time & t ); - /* Similarly, Prefere ->access to .access - */ - virtual const T& access( const Time & t ); - virtual const T& accessCopy () const; - - inline void setConstantDefault( const T& t ) - { Signal<T,Time>::setConstant(t); modeNoThrow = true; } - virtual inline void setConstantDefault () - { setConstantDefault( accessCopy () ); } - inline void unsetConstantDefault (){ modeNoThrow = false; } - - virtual void checkCompatibility(); - - public: /* --- INHERITANCE --- */ - - /* SignalPtr could be used as a classical signal, through the normal - * setting functions. The behavior is to plugged the signalPtr on - * the classical mother Signal layer of the object. - */ - virtual void setConstant( const T& t ) - { plug(this); Signal<T,Time>::setConstant(t); } - virtual void setReference( const T* t,typename Signal<T,Time>::Mutex *m=NULL ) - { plug(this); Signal<T,Time>::setReference(t,m); } - virtual void setFunction( boost::function2<T&,T&,Time> t,typename Signal<T,Time>::Mutex *m=NULL ) - { plug(this); Signal<T,Time>::setFunction(t,m); } - - /* template< class Provider > */ - /* void setFunction( T& (Provider::*fun)(Time,T&),Provider& obj, */ - /* boost::try_mutex *mutexref=NULL ) */ - /* { plug(this); Signal<T,Time>::setFunction(fun,obj,mutexref); } */ - - virtual inline Signal<T,Time>& operator= ( const T& t ) - { setConstant( t ); return *this; } - - - virtual std::ostream& displayDependencies( std::ostream& os,const int depth=-1, - std::string space="", - std::string next1="", - std::string next2="" ) const; - - protected: // Interdiction of the rest of the heritage - using Signal<T,Time>::addDependency; - virtual void addDependency () {} - using Signal<T,Time>::removeDependency; - virtual void removeDependency () {} - virtual void clearDependencies () {} - - }; - -} // end of namespace dynamicgraph - -# include <dynamic-graph/signal-ptr.t.cpp> -#endif //! DYNAMIC_GRAPH_SIGNAL_PTR_H +#include <dynamic-graph/exception-signal.h> +#include <dynamic-graph/signal.h> + +#include <dynamic-graph/deprecated.hh> + +namespace dynamicgraph { +/// \ingroup dgraph +/// +/// \brief This is the only type of signal that can be plugged to, +/// using the plug () command. +/// +/// In that sense, when plugged into, it acts as a "pointer" to the +/// input signal, hence the name. Operator -> is also overloaded and +/// can be used to access the pointed signal. +template <class T, class Time> +class SignalPtr : public virtual Signal<T, Time> { + public: + using SignalBase<Time>::getName; + + protected: + Signal<T, Time>* signalPtr; + bool modeNoThrow; + bool transmitAbstract; + SignalBase<Time>* abstractTransmitter; + T* transmitAbstractData; + + inline bool autoref() const { return signalPtr == this; } + + public: /* --- CONSTRUCTORS --- */ + SignalPtr(Signal<T, Time>* ptr, std::string name = "") + : Signal<T, Time>(name), + signalPtr(ptr), + modeNoThrow(false), + transmitAbstract(false), + abstractTransmitter(NULL) {} + + virtual ~SignalPtr() { signalPtr = NULL; } + + public: /* --- PLUG-IN OPERATION --- */ + Signal<T, Time>* getPtr(); // throw + const Signal<T, Time>* getPtr() const; // throw + SignalBase<Time>* getAbstractPtr(); // throw + const SignalBase<Time>* getAbstractPtr() const; // throw + virtual void plug(SignalBase<Time>* ref); + + virtual void unplug() { plug(NULL); } + + virtual bool isPlugged() const { return (NULL != signalPtr); } + virtual SignalBase<Time>* getPluged() const { return signalPtr; } + virtual bool isAbstractPluged() const; + virtual const Time& getTime() const; + + /* Equivalent operator-like definitions. */ + inline Signal<T, Time>* operator->() { return getPtr(); } + inline const Signal<T, Time>* operator->() const { return getPtr(); } + inline Signal<T, Time>& operator*() { return *getPtr(); } + inline const Signal<T, Time>& operator*() const { return *getPtr(); } + inline operator bool() const { return isPlugged(); } + + public: /* --- INHERITANCE --- */ + virtual bool needUpdate(const Time& t) const; + virtual std::ostream& writeGraph(std::ostream& os) const; + virtual std::ostream& display(std::ostream& os) const; + + /* For compatibility, .access () is equivalent to ->access (). For explicit + * pointer dereference : + * Prefere -> () to () + */ + virtual const T& operator()(const Time& t); + /* Similarly, Prefere ->access to .access + */ + virtual const T& access(const Time& t); + virtual const T& accessCopy() const; + + inline void setConstantDefault(const T& t) { + Signal<T, Time>::setConstant(t); + modeNoThrow = true; + } + virtual inline void setConstantDefault() { setConstantDefault(accessCopy()); } + inline void unsetConstantDefault() { modeNoThrow = false; } + + virtual void checkCompatibility(); + + public: /* --- INHERITANCE --- */ + /* SignalPtr could be used as a classical signal, through the normal + * setting functions. The behavior is to plugged the signalPtr on + * the classical mother Signal layer of the object. + */ + virtual void setConstant(const T& t) { + plug(this); + Signal<T, Time>::setConstant(t); + } + virtual void setReference(const T* t, typename Signal<T, Time>::Mutex* m = NULL) { + plug(this); + Signal<T, Time>::setReference(t, m); + } + virtual void setFunction(boost::function2<T&, T&, Time> t, typename Signal<T, Time>::Mutex* m = NULL) { + plug(this); + Signal<T, Time>::setFunction(t, m); + } + + /* template< class Provider > */ + /* void setFunction( T& (Provider::*fun)(Time,T&),Provider& obj, */ + /* boost::try_mutex *mutexref=NULL ) */ + /* { plug(this); Signal<T,Time>::setFunction(fun,obj,mutexref); } */ + + virtual inline Signal<T, Time>& operator=(const T& t) { + setConstant(t); + return *this; + } + + virtual std::ostream& displayDependencies(std::ostream& os, const int depth = -1, std::string space = "", + std::string next1 = "", std::string next2 = "") const; + + protected: // Interdiction of the rest of the heritage + using Signal<T, Time>::addDependency; + virtual void addDependency() {} + using Signal<T, Time>::removeDependency; + virtual void removeDependency() {} + virtual void clearDependencies() {} +}; + +} // end of namespace dynamicgraph + +#include <dynamic-graph/signal-ptr.t.cpp> +#endif //! DYNAMIC_GRAPH_SIGNAL_PTR_H diff --git a/include/dynamic-graph/signal-ptr.t.cpp b/include/dynamic-graph/signal-ptr.t.cpp index 5df9d637755ffb417d3d798cbf1d62d33ef07906..3644833a4dd7a3faef8f5b7784d0752c35792aae 100644 --- a/include/dynamic-graph/signal-ptr.t.cpp +++ b/include/dynamic-graph/signal-ptr.t.cpp @@ -4,260 +4,212 @@ // #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 -# define VP_TEMPLATE_DEBUG_MODE 0 -# include <dynamic-graph/debug.h> - -namespace dynamicgraph -{ - template< class T,class Time > - bool SignalPtr<T,Time>:: - isAbstractPluged () const - { - return ( (NULL!=signalPtr)||(abstractTransmitter) ); +#define DYNAMIC_GRAPH_SIGNAL_PTR_T_CPP +#include <dynamic-graph/signal-ptr.h> + +#undef VP_TEMPLATE_DEBUG_MODE +#define VP_TEMPLATE_DEBUG_MODE 0 +#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> +Signal<T, Time>* SignalPtr<T, Time>::getPtr() { + dgTDEBUGIN(25); + if (!isPlugged()) + DG_THROW ExceptionSignal(ExceptionSignal::NOT_INITIALIZED, "In SignalPtr: SIN ptr not set.", " (in signal <%s>)", + getName().c_str()); + dgTDEBUGOUT(25); + return signalPtr; +} + +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 (!isPlugged()) { + DG_THROW ExceptionSignal(ExceptionSignal::NOT_INITIALIZED, "In SignalPtr: SIN ptr not set.", " (in signal <%s>)", + getName().c_str()); } - - - template< class T,class Time > - Signal<T,Time>* SignalPtr<T,Time>:: - getPtr () - { - dgTDEBUGIN(25); - if(! isPlugged () ) - DG_THROW ExceptionSignal( ExceptionSignal::NOT_INITIALIZED, - "In SignalPtr: SIN ptr not set.", - " (in signal <%s>)",getName ().c_str ()); - dgTDEBUGOUT(25); - return signalPtr; + dgTDEBUGOUT(25); + return signalPtr; +} + +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()); } - - 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(! isPlugged () ) - { DG_THROW ExceptionSignal( ExceptionSignal::NOT_INITIALIZED, - "In SignalPtr: SIN ptr not set.", - " (in signal <%s>)",getName ().c_str ()); } - dgTDEBUGOUT(25); + 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()); } - - 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 () 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 ) - { - 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>)" - " 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; - } + if (NULL != signalPtr) + return signalPtr; + else + return abstractTransmitter; +} + +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; } - 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(); + 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>)" + " 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; } - - 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); + dgTDEBUGOUT(5); +} + +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> +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(); } - - template< class T,class Time > - const Time& SignalPtr<T,Time>::getTime () const - { - if( (isAbstractPluged ())&&(!autoref ()) ){ return getAbstractPtr ()->getTime ();} - return Signal<T,Time>::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>::access(const Time& t) { + dgTDEBUGIN(15); + 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>:: - operator ()( const Time & t ) - { - return access(t); - } - - template< class T,class Time > - const T& SignalPtr<T,Time>:: - access( const Time & t ) - { - dgTDEBUGIN(15); - 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() 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 { + 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; } - 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 - { - 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; - - } - return 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 ()) ) - { - // 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; + return 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())) { + // dgTDEBUG(25) << "Display pointed."<<std::endl; + // getPtr ()->display(os<<"PTR->"); + os << " -->-- PLUGGED"; + } else { + if (!isAbstractPluged()) + os << " UNPLUGGED"; + else if (autoref()) + os << " AUTOPLUGGED"; } - 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); - } - dgTDEBUGOUT(25); - return os; + 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 { + dgTDEBUGIN(25); + 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; +} -} // end of namespace dynamicgraph. +} // end of namespace dynamicgraph. -#endif //! DYNAMIC_GRAPH_SIGNAL_PTR_T_CPP +#endif //! DYNAMIC_GRAPH_SIGNAL_PTR_T_CPP diff --git a/include/dynamic-graph/signal-time-dependent.h b/include/dynamic-graph/signal-time-dependent.h index 0beb6483e8e12c0f8af8c0f9f9aad32bc0d42c46..40c91de0395abb10880284486fca0318be7affe5 100644 --- a/include/dynamic-graph/signal-time-dependent.h +++ b/include/dynamic-graph/signal-time-dependent.h @@ -4,139 +4,112 @@ // #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 addDependency function. On access (calling the signal S operator () or access(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 access ()'ed to bring them up-to-date. Thus, the value of dependent - signals can be accessed \b quickly and \b repeatedly through the accessCopy () function. - */ - template< class T,class Time > - class SignalTimeDependent - : public virtual Signal<T,Time> - , public TimeDependency<Time> - { - - //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 () {} - - 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; - - }; - - - /* -------------------------------------------- */ - - - 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> - 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 () const - { return TimeDependency<Time>::getPeriodTime (); } - -} // end of namespace dynamicgraph - -#endif //! 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 addDependency function. On access (calling the signal S operator () or access(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 access ()'ed to bring them up-to-date. Thus, the value of dependent + signals can be accessed \b quickly and \b repeatedly through the accessCopy () function. +*/ +template <class T, class Time> +class SignalTimeDependent : public virtual Signal<T, Time>, public TimeDependency<Time> { + // 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() {} + + 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; +}; + +/* -------------------------------------------- */ + +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> +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() const { + return TimeDependency<Time>::getPeriodTime(); +} + +} // end of namespace dynamicgraph + +#endif //! DYNAMIC_GRAPH_SIGNAL_TIME_DEPENDENT_H diff --git a/include/dynamic-graph/signal.h b/include/dynamic-graph/signal.h index 18d25d389b6b887002e867a0d57de7851a3de1ba..842a69fa9c7490f2ef530fbc7ce9fe52fb974ece 100644 --- a/include/dynamic-graph/signal.h +++ b/include/dynamic-graph/signal.h @@ -38,29 +38,20 @@ namespace dynamicgraph { \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> -{ +template <class T, class Time> +class Signal : public SignalBase<Time> { protected: - - enum SignalType - { - CONSTANT - ,REFERENCE - ,REFERENCE_NON_CONST - ,FUNCTION - }; + enum SignalType { CONSTANT, REFERENCE, REFERENCE_NON_CONST, FUNCTION }; static const SignalType SIGNAL_TYPE_DEFAULT = CONSTANT; SignalType signalType; - T Tcopy1,Tcopy2; + T Tcopy1, Tcopy2; T* Tcopy; bool copyInit; const T* Treference; T* TreferenceNonConst; - boost::function2<T&,T&,Time> Tfunction; + boost::function2<T&, T&, Time> Tfunction; bool keepReference; const static bool KEEP_REFERENCE_DEFAULT = false; @@ -74,65 +65,60 @@ class Signal typedef int* MutexError; #endif -protected: - Mutex *providerMutex; + protected: + Mutex* providerMutex; using SignalBase<Time>::signalTime; public: using SignalBase<Time>::setReady; public: - /* --- Constructor/destrusctor --- */ - Signal( std::string name ); - virtual ~Signal () {} + 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 (){ 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 () const; + virtual const T& access(const Time& t); + virtual inline void recompute(const Time& t) { access(t); } + virtual const T& accessCopy() const; - virtual std::ostream& display( std::ostream& os ) const; + 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(); } - + 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 () { throw Tcopy; } + virtual void checkCompatibility() { throw Tcopy; } private: - const T& setTcopy( const T& t ); - T& getTwork (); - const T& getTwork () const ; - const T& switchTcopy (); - + const T& setTcopy(const T& t); + T& getTwork(); + const T& getTwork() const; + const T& switchTcopy(); }; -} // end of namespace dynamicgraph +} // end of namespace dynamicgraph #include <dynamic-graph/signal.t.cpp> -#endif // #ifndef __SIGNAL_HH +#endif // #ifndef __SIGNAL_HH /* * Local variables: diff --git a/include/dynamic-graph/signal.t.cpp b/include/dynamic-graph/signal.t.cpp index 1b0470560a8803a3664f0a1e39cd46a20f8b1a19..79a74edb0cbca32839bfba85481dc3d9dd5ae617 100644 --- a/include/dynamic-graph/signal.t.cpp +++ b/include/dynamic-graph/signal.t.cpp @@ -4,296 +4,232 @@ // #ifndef DYNAMIC_GRAPH_SIGNAL_T_CPP -# define DYNAMIC_GRAPH_SIGNAL_T_CPP -# include <dynamic-graph/signal.h> -# include <dynamic-graph/signal-caster.h> - -# undef VP_TEMPLATE_DEBUG_MODE -# define VP_TEMPLATE_DEBUG_MODE 0 -# include <dynamic-graph/debug.h> - -# 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,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>:: - get( std::ostream& os ) const - { - signal_disp<T>( 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 > - 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 () - { - if( Tcopy==&Tcopy1 ) return Tcopy2; else return Tcopy1; - } - - template< class T,class Time > - const T& Signal<T,Time>:: - getTwork () const - { - if( Tcopy==&Tcopy1 ) return Tcopy2; else 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); - setReady (); - } - - - 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 ) - { - signalType = REFERENCE_NON_CONST; - 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 ) - { - signalType = FUNCTION; - Tfunction = t; - providerMutex = mutexref; - copyInit = false; - setReady (); - } - - 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 ) - { - case REFERENCE: - case REFERENCE_NON_CONST: - { - if( NULL==providerMutex ) - { - copyInit=true; - signalTime = t; - return setTcopy( *Treference ); - } - else - { - try - { +#define DYNAMIC_GRAPH_SIGNAL_T_CPP +#include <dynamic-graph/signal.h> +#include <dynamic-graph/signal-caster.h> + +#undef VP_TEMPLATE_DEBUG_MODE +#define VP_TEMPLATE_DEBUG_MODE 0 +#include <dynamic-graph/debug.h> + +#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, 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>::get(std::ostream& os) const { + signal_disp<T>(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> +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() { + if (Tcopy == &Tcopy1) + return Tcopy2; + else + return Tcopy1; +} + +template <class T, class Time> +const T& Signal<T, Time>::getTwork() const { + if (Tcopy == &Tcopy1) + return Tcopy2; + else + 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); + setReady(); +} + +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) { + signalType = REFERENCE_NON_CONST; + 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) { + signalType = FUNCTION; + Tfunction = t; + providerMutex = mutexref; + copyInit = false; + setReady(); +} + +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) { + case REFERENCE: + 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(const MutexError&) - { 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(const MutexError&) - { return accessCopy (); } - } - break; - } - case CONSTANT: - default: - 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 - { + signalTime = t; + Tfunction(getTwork(), t); + copyInit = true; + return switchTcopy(); + } catch (const MutexError&) { + return accessCopy(); + } + } + break; + } + case CONSTANT: + default: + 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 { #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(const MutexError&) - { /* TODO ERROR */ } - } + setTcopy(t); + (*TreferenceNonConst) = t; + } catch (const MutexError&) { /* 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; - } - return os<<")"; - } - -} // end of namespace dynamicgraph. - -# undef __SIGNAL_INIT -#endif //! DYNAMIC_GRAPH_SIGNAL_T_CPP + } + } 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 diff --git a/include/dynamic-graph/time-dependency.h b/include/dynamic-graph/time-dependency.h index 1505e90e1602bf42a46c49311afd0b2cc20007f2..e7516c637c4f62eb0056d1708c95a07c2efc2748 100644 --- a/include/dynamic-graph/time-dependency.h +++ b/include/dynamic-graph/time-dependency.h @@ -4,79 +4,65 @@ // #ifndef DYNAMIC_GRAPH_TIME_DEPENDENCY_H -# define DYNAMIC_GRAPH_TIME_DEPENDENCY_H -# include <list> +#define DYNAMIC_GRAPH_TIME_DEPENDENCY_H +#include <list> -# include <dynamic-graph/fwd.hh> -# include <dynamic-graph/signal-base.h> -# include <dynamic-graph/signal-array.h> +#include <dynamic-graph/fwd.hh> +#include <dynamic-graph/signal-base.h> +#include <dynamic-graph/signal-array.h> -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 - }; +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 }; - mutable Time lastAskForUpdate; + mutable Time lastAskForUpdate; - public: + public: + SignalBase<Time>& leader; - SignalBase< Time >& leader; + typedef std::list<const SignalBase<Time>*> Dependencies; + static const DependencyType DEPENDENCY_TYPE_DEFAULT = TIME_DEPENDENT; - typedef std::list< const SignalBase<Time> * > Dependencies; - static const DependencyType DEPENDENCY_TYPE_DEFAULT = TIME_DEPENDENT; + Dependencies dependencies; + bool updateFromAllChildren; + static const bool ALL_READY_DEFAULT = false; - Dependencies dependencies; - bool updateFromAllChildren; - static const bool ALL_READY_DEFAULT = false; + DependencyType dependencyType; - DependencyType dependencyType; + Time periodTime; + static const Time PERIOD_TIME_DEFAULT = 1; - Time periodTime; - 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); + virtual ~TimeDependency() {} - public: + void addDependency(const SignalBase<Time>& sig); + void removeDependency(const SignalBase<Time>& sig); + void clearDependency(); - 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 () {} + 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; - void addDependency( const SignalBase<Time>& sig ); - void removeDependency( const SignalBase<Time>& sig ); - void clearDependency (); + bool needUpdate(const Time& t1) const; + void setDependencyType(DependencyType dep) { dependencyType = dep; } - 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; + void setNeedUpdateFromAllChildren(const bool b = true) { updateFromAllChildren = b; } + bool getNeedUpdateFromAllChildren() const { return updateFromAllChildren; } - bool needUpdate( const Time& t1 ) const; + void setPeriodTime(const Time& p) { periodTime = p; } + Time getPeriodTime() const { return periodTime; } +}; - void setDependencyType( DependencyType dep ) { dependencyType = dep; } +} // end of namespace dynamicgraph - 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; } - - }; - -} // end of namespace dynamicgraph - -# include <dynamic-graph/time-dependency.t.cpp> -#endif //! DYNAMIC_GRAPH_TIME_DEPENDENCY_H +#include <dynamic-graph/time-dependency.t.cpp> +#endif //! DYNAMIC_GRAPH_TIME_DEPENDENCY_H diff --git a/include/dynamic-graph/time-dependency.t.cpp b/include/dynamic-graph/time-dependency.t.cpp index f9689574baaccb26f7dc2cb23bbc4ebf9725533c..0b2c1fb406700cf4dc3bbcdc411fe843006472a7 100644 --- a/include/dynamic-graph/time-dependency.t.cpp +++ b/include/dynamic-graph/time-dependency.t.cpp @@ -4,162 +4,161 @@ // #ifndef DYNAMIC_GRAPH_TIME_DEPENDENCY_T_CPP -# define DYNAMIC_GRAPH_TIME_DEPENDENCY_T_CPP -# include <dynamic-graph/time-dependency.h> - -# 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) - - - -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) - { - for( unsigned int i=0;i<ar.getSize ();++i ) - {addDependency( ar[i] ); } - - return ; - } - - /* -------------------------------------------------------------------------- */ - template<class Time> - void TimeDependency<Time>:: - addDependency( const SignalBase<Time>& sig ) - { - dependencies.push_front(&sig); +#define DYNAMIC_GRAPH_TIME_DEPENDENCY_T_CPP +#include <dynamic-graph/time-dependency.h> + +#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) + +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) { + for (unsigned int i = 0; i < ar.getSize(); ++i) { + addDependency(ar[i]); } - template<class Time> - void TimeDependency<Time>:: - removeDependency( const SignalBase<Time>& sig ) - { - dependencies.remove(&sig); - } - template<class Time> - void TimeDependency<Time>:: - clearDependency () - { - dependencies.clear (); + return; +} + +/* -------------------------------------------------------------------------- */ +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>::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; } - - 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; } - } - lastAskForUpdate = res; - + if (lastAskForUpdate) { dgTDEBUGOUT(15); - return res; + return true; } - - 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; - } + 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; } - return os; + } else { + if (updateFromAllChildren) { + res = false; + break; + } else + continue; + } } - - 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<<") " ; - 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; } + 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; } - return os; } + 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 << ") "; + 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; +} -} // end of namespace dynamicgraph +} // end of namespace dynamicgraph -# undef __TIME_DEPENDENCY_INIT -#endif //! DYNAMIC_GRAPH_TIME_DEPENDENCY_T_CPP +#undef __TIME_DEPENDENCY_INIT +#endif //! DYNAMIC_GRAPH_TIME_DEPENDENCY_T_CPP diff --git a/include/dynamic-graph/tracer-real-time.h b/include/dynamic-graph/tracer-real-time.h index b39b8a79b67ff2e05b1615f97277a7d18fab85fa..af3e3530eff7e0ef565e389760666e07559e6153 100644 --- a/include/dynamic-graph/tracer-real-time.h +++ b/include/dynamic-graph/tracer-real-time.h @@ -4,79 +4,67 @@ // #ifndef DYNAMIC_GRAPH_TRACER_REAL_TIME_H -# define DYNAMIC_GRAPH_TRACER_REAL_TIME_H -# include <sstream> - -# include <dynamic-graph/fwd.hh> -# include <dynamic-graph/tracer.h> -# include <dynamic-graph/config-tracer-real-time.hh> - -namespace dynamicgraph -{ - /// \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 (); - ~OutStringStream (); - - void resize (const std::streamsize& size); - bool addData (const char * data, const std::streamoff& size); - void dump (std::ostream& os); - void empty (); - }; - - /// \ingroup plugin - /// - /// \brief Main class of the tracer real-time plug-in. - class DG_TRACERREALTIME_DLLAPI TracerRealTime : public Tracer - { - DYNAMIC_GRAPH_ENTITY_DECL (); - public: - TracerRealTime (const std::string & n); - virtual ~TracerRealTime () - {} - - virtual void closeFiles (); - virtual void trace (); - - void display (std::ostream& os) const; - DG_TRACERREALTIME_DLLAPI friend std::ostream& operator<< - (std::ostream& os, const TracerRealTime& t); - - 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 setBufferSize (const int& SIZE) - { - bufferSize=SIZE; - } - - const int& getBufferSize () - { - return bufferSize; - } - - 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 +#define DYNAMIC_GRAPH_TRACER_REAL_TIME_H +#include <sstream> + +#include <dynamic-graph/fwd.hh> +#include <dynamic-graph/tracer.h> +#include <dynamic-graph/config-tracer-real-time.hh> + +namespace dynamicgraph { +/// \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(); + ~OutStringStream(); + + void resize(const std::streamsize& size); + bool addData(const char* data, const std::streamoff& size); + void dump(std::ostream& os); + void empty(); +}; + +/// \ingroup plugin +/// +/// \brief Main class of the tracer real-time plug-in. +class DG_TRACERREALTIME_DLLAPI TracerRealTime : public Tracer { + DYNAMIC_GRAPH_ENTITY_DECL(); + + public: + TracerRealTime(const std::string& n); + virtual ~TracerRealTime() {} + + virtual void closeFiles(); + virtual void trace(); + + void display(std::ostream& os) const; + DG_TRACERREALTIME_DLLAPI friend std::ostream& operator<<(std::ostream& os, const TracerRealTime& t); + + 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 setBufferSize(const int& SIZE) { bufferSize = SIZE; } + + const int& getBufferSize() { return bufferSize; } + + 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 diff --git a/include/dynamic-graph/tracer.h b/include/dynamic-graph/tracer.h index 61a7f06bede65bb0ffe78095251ad3df97d0bc11..d4016c339d2a824659b96ae1e35a60691d5fb7ae 100644 --- a/include/dynamic-graph/tracer.h +++ b/include/dynamic-graph/tracer.h @@ -4,99 +4,93 @@ // #ifndef DYNAMIC_GRAPH_TRACER_H -# define DYNAMIC_GRAPH_TRACER_H -# include <string> -# include <list> -# include <boost/function.hpp> - -# 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> - -# include <dynamic-graph/config-tracer.hh> - -namespace dynamicgraph -{ - /// \ingroup plugin - /// - /// \brief Tracer plug-in main class. - class DG_TRACER_DLLAPI Tracer : public Entity - { - DYNAMIC_GRAPH_ENTITY_DECL (); - protected: - typedef std::list< const SignalBase<int>* > SignalList; - SignalList toTraceSignals; - 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; - - std::string basename; - std::string suffix; - std::string rootdir; - bool namesSet; - typedef std::list< std::ostream* > FileList; - FileList files; - typedef std::list< std::string > NameList; - NameList names; - bool play; - int timeStart; - - public: - 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 ); - - public: - void setTraceStyle( const TraceStyle& style ){ traceStyle = style; } - TraceStyle getTraceStyle (){ return traceStyle; } - - void setFrenquency( const double& frqu ){ frequency = frqu; } - double getFrequency (){ return frequency; } - - 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; - - /* --- DISPLAY ------------------------------------------------------------ */ - DG_TRACER_DLLAPI friend std::ostream& operator<< - (std::ostream& os,const Tracer& t); - - /* --- PARAMS --- */ - void display( std::ostream& os ) const; - +#define DYNAMIC_GRAPH_TRACER_H +#include <string> +#include <list> +#include <boost/function.hpp> + +#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> + +#include <dynamic-graph/config-tracer.hh> + +namespace dynamicgraph { +/// \ingroup plugin +/// +/// \brief Tracer plug-in main class. +class DG_TRACER_DLLAPI Tracer : public Entity { + DYNAMIC_GRAPH_ENTITY_DECL(); + + protected: + typedef std::list<const SignalBase<int>*> SignalList; + SignalList toTraceSignals; + + 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 () ). }; - -} // end of namespace dynamicgraph - -#endif //! DYNAMIC_GRAPH_TRACER_H + TraceStyle traceStyle; + static const TraceStyle TRACE_STYLE_DEFAULT = EACH_TIME; + double frequency; + + std::string basename; + std::string suffix; + std::string rootdir; + bool namesSet; + typedef std::list<std::ostream*> FileList; + FileList files; + typedef std::list<std::string> NameList; + NameList names; + bool play; + int timeStart; + + public: + 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); + + public: + void setTraceStyle(const TraceStyle& style) { traceStyle = style; } + TraceStyle getTraceStyle() { return traceStyle; } + + void setFrenquency(const double& frqu) { frequency = frqu; } + double getFrequency() { return frequency; } + + 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; + + /* --- DISPLAY ------------------------------------------------------------ */ + DG_TRACER_DLLAPI friend std::ostream& operator<<(std::ostream& os, const Tracer& t); + + /* --- PARAMS --- */ + void display(std::ostream& os) const; +}; + +} // end of namespace dynamicgraph + +#endif //! DYNAMIC_GRAPH_TRACER_H diff --git a/include/dynamic-graph/value.h b/include/dynamic-graph/value.h index 13898666e3485578cc1c7b469d61675b441808e3..caf35f9529238f8530b00349e60cf20836ae92ad 100644 --- a/include/dynamic-graph/value.h +++ b/include/dynamic-graph/value.h @@ -14,102 +14,91 @@ #include <dynamic-graph/linear-algebra.h> namespace dynamicgraph { - namespace command { - class Value; - class DYNAMIC_GRAPH_DLLAPI EitherType { - public: - EitherType(const Value& value); - ~EitherType(); - operator bool () const; - operator unsigned () const; - operator int () const; - operator float () const; - operator double () const; - operator std::string () const; - operator Vector () const; - operator Eigen::MatrixXd () const; - operator Eigen::Matrix4d () const; - private: - const Value* value_; - }; +namespace command { +class Value; +class DYNAMIC_GRAPH_DLLAPI EitherType { + public: + EitherType(const Value& value); + ~EitherType(); + operator bool() const; + operator unsigned() const; + operator int() const; + operator float() const; + operator double() const; + operator std::string() const; + operator Vector() const; + operator Eigen::MatrixXd() const; + operator Eigen::Matrix4d() const; - class DYNAMIC_GRAPH_DLLAPI Value { - public: - enum Type { - NONE, - BOOL, - UNSIGNED, - INT, - FLOAT, - DOUBLE, - STRING, - VECTOR, - MATRIX, - MATRIX4D, - NB_TYPES - }; - ~Value(); - void deleteValue (); - explicit Value(const bool& value); - explicit Value(const unsigned& value); - explicit Value(const 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); - /// Copy constructor - Value(const Value& value); - // Construct an empty value (None) - explicit Value(); - // operator assignement - Value operator=(const Value& value); - /// Return the type of the value - Type type() const; + private: + const Value* value_; +}; - /// 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); +class DYNAMIC_GRAPH_DLLAPI Value { + public: + enum Type { NONE, BOOL, UNSIGNED, INT, FLOAT, DOUBLE, STRING, VECTOR, MATRIX, MATRIX4D, NB_TYPES }; + ~Value(); + void deleteValue(); + explicit Value(const bool& value); + explicit Value(const unsigned& value); + explicit Value(const 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); + /// Copy constructor + Value(const Value& value); + // Construct an empty value (None) + explicit Value(); + // operator assignement + Value operator=(const Value& value); + /// Return the type of the value + Type type() const; - /// 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; - int intValue() const; - float floatValue() const; - double doubleValue() const; - std::string stringValue() const; - Vector vectorValue() const; - Eigen::MatrixXd matrixXdValue() const; - Eigen::Matrix4d matrix4dValue() const; - Type type_; - const void* const value_; - }; + /// 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); - /* ---- 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 + /// Output in a stream + DYNAMIC_GRAPH_DLLAPI friend std::ostream& operator<<(std::ostream& os, const Value& value); -#endif //DYNAMIC_GRAPH_VALUE_H + public: + friend class EitherType; + bool boolValue() const; + unsigned unsignedValue() const; + int intValue() const; + float floatValue() const; + double doubleValue() const; + std::string stringValue() const; + Vector vectorValue() const; + Eigen::MatrixXd matrixXdValue() const; + Eigen::Matrix4d matrix4dValue() 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 diff --git a/src/command/command.cpp b/src/command/command.cpp index d38eddc271b5faed7a2a9f367e29d9b6e22eef7a..6f6cb0ebc2e3a83dc45473db8cb41b9cd7d0e1b6 100644 --- a/src/command/command.cpp +++ b/src/command/command.cpp @@ -9,63 +9,40 @@ #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) - { +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::Type>& Command::valueTypes() const - { - return valueTypeVector_; - } +const std::vector<Value>& Command::getParameterValues() const { return valueVector_; } - 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; - } +Value Command::execute() { return doExecute(); } - 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 +Entity& Command::owner() { return owner_; } +std::string Command::getDocstring() const { return docstring_; } +} // namespace command +} // namespace dynamicgraph diff --git a/src/command/value.cpp b/src/command/value.cpp index 2dde1c3224d8c7cfdb4397c62184f517499446d3..3407622b47792e03c95ae7098ef26ca7c452ce2c 100644 --- a/src/command/value.cpp +++ b/src/command/value.cpp @@ -4,359 +4,262 @@ // Author: Florent Lamiraux // - #include "dynamic-graph/value.h" #include "dynamic-graph/exception-abstract.h" namespace dynamicgraph { - namespace command { - - static void* copyValue(const Value& value); +namespace command { - EitherType::EitherType(const Value& value) : value_(new Value(value)) - { - } +static void* copyValue(const Value& value); - EitherType::~EitherType() - { - delete value_; - value_ = NULL; - } +EitherType::EitherType(const Value& value) : value_(new Value(value)) {} - EitherType::operator bool() const - { - return value_->boolValue(); - } - EitherType::operator unsigned() const - { - return value_->unsignedValue(); - } - EitherType::operator int() const - { - return value_->intValue(); - } - 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::~EitherType() { + delete value_; + value_ = NULL; +} - EitherType::operator Eigen::Matrix4d() const - { - return value_->matrix4dValue(); - } +EitherType::operator bool() const { return value_->boolValue(); } +EitherType::operator unsigned() const { return value_->unsignedValue(); } +EitherType::operator int() const { return value_->intValue(); } +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(); } - void Value::deleteValue () - { - switch(type_) { - case BOOL: - delete(const bool*)value_; - break; - case UNSIGNED: - delete(const unsigned*)value_; - break; - case INT: - delete(const 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; - default:; - } - } +EitherType::operator Eigen::Matrix4d() const { return value_->matrix4dValue(); } - Value::~Value() - { - deleteValue (); - } +void Value::deleteValue() { + switch (type_) { + case BOOL: + delete (const bool*)value_; + break; + case UNSIGNED: + delete (const unsigned*)value_; + break; + case INT: + delete (const 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; + default:; + } +} - 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 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() { 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 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 Value& value) : type_(value.type_), - value_(copyValue(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::INT: - copy = new int(value.intValue()); - 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; - default: - abort(); - } - return copy; - } +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::INT: + copy = new int(value.intValue()); + 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; + default: + abort(); + } + return copy; +} - Value::Value() : type_(NONE), value_(NULL) - { - } +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; - } +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; +} - const EitherType Value::value() const - { - return EitherType(*this); - } +const EitherType Value::value() const { return EitherType(*this); } - Value::Type Value::type() const - { - return type_; - } +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"); - } +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 Value::unsignedValue() const { + if (type_ == UNSIGNED) return *((const unsigned*)value_); + throw ExceptionAbstract(ExceptionAbstract::TOOLS, "value is not an unsigned int"); +} - int Value::intValue() const - { - if(type_ == INT) - return *((const int*)value_); - throw ExceptionAbstract(ExceptionAbstract::TOOLS, - "value is not an int int"); - } +int Value::intValue() const { + if (type_ == INT) return *((const int*)value_); + throw ExceptionAbstract(ExceptionAbstract::TOOLS, "value is not an int 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; - } +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; - } +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"); - } +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"); - } +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::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"); - } +Eigen::Matrix4d Value::matrix4dValue() const { + if (type_ == MATRIX4D) return *((const Eigen::Matrix4d*)value_); + throw ExceptionAbstract(ExceptionAbstract::TOOLS, "value is not a Eigen matrix4d"); +} - std::string Value::typeName(Type type) - { - switch(type) { - case BOOL: - return std::string("bool"); - case UNSIGNED: - return std::string("unsigned 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"); - default: - return std::string("unknown"); - } - } +std::string Value::typeName(Type type) { + switch (type) { + case BOOL: + return std::string("bool"); + case UNSIGNED: + return std::string("unsigned 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"); + 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::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; - default: - return os; - } +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::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; + 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<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<bool>::TypeID = Value::BOOL; +template <> +const Value::Type ValueHelper<unsigned>::TypeID = Value::UNSIGNED; +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; - } // namespace command -} //namespace dynamicgraph +} // namespace command +} // namespace dynamicgraph diff --git a/src/debug/debug.cpp b/src/debug/debug.cpp index 4e3828c7bad8bd09a24121b68a5de2f7c48bb5f4..d00085a01ed8d1c8c1526a76cfed444bc3fabde7 100644 --- a/src/debug/debug.cpp +++ b/src/debug/debug.cpp @@ -14,50 +14,45 @@ 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; //( "/dev/null", std::ios::trunc&std::ios::out ); +class dgDebug_init { public: - dgDebug_init () - { dg_debugfile.setstate( std::ios::failbit ) ; /* dg_debugfile.close (); */ } - }; - dgDebug_init dgDebug_initialisator; + dgDebug_init() { dg_debugfile.setstate(std::ios::failbit); /* dg_debugfile.close (); */ } +}; +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(); + 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; } -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; +void DebugTrace::closeFile(const char *) { + 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); +// DebugTrace dgDebugFLOW(std::cout); +// DebugTrace dgERRORFLOW(std::cerr); diff --git a/src/debug/logger.cpp b/src/debug/logger.cpp index 44f8f710d15d9b8261c148e4d8233c33e524f8a0..0289f4e341bd925d663cd475f3a980d4cc7b874c 100644 --- a/src/debug/logger.cpp +++ b/src/debug/logger.cpp @@ -15,106 +15,75 @@ #include <sstream> #include <stdio.h> #include <iostream> -#include <iomanip> // std::setprecision +#include <iomanip> // std::setprecision #include <dynamic-graph/logger.h> #include <dynamic-graph/real-time-logger.h> -namespace dynamicgraph -{ - - using namespace std; - - 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(string msg, MsgType type, const char* file, int line) - { - if(m_lv==VERBOSITY_NONE || - (m_lv==VERBOSITY_ERROR && !isErrorMsg(type)) || - (m_lv==VERBOSITY_WARNING_ERROR && !(isWarningMsg(type) || isErrorMsg(type))) || - (m_lv==VERBOSITY_INFO_WARNING_ERROR && isDebugMsg(type))) - return; - - // if print is allowed by current verbosity level - if( isStreamMsg(type)) - { - // check whether counter already exists - std::ostringstream oss; - oss << file << line; - std::string id (oss.str()); - map<string,double>::iterator it = m_stream_msg_counters.find(id); - if(it == m_stream_msg_counters.end()) - { - // if counter doesn't exist then add one - m_stream_msg_counters.insert(make_pair(id, 0.0)); - it = m_stream_msg_counters.find(id); - } - - // if counter is greater than 0 then decrement it and do not print - if(it->second>0.0) - { - it->second -= m_timeSample; - if (it->second<=0.0) - it->second = m_streamPrintPeriod; - else - return; - } - else // otherwise reset counter and print - it->second = m_streamPrintPeriod; - } - dgRTLOG() << msg.c_str() << "\n"; +namespace dynamicgraph { + +using namespace std; + +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(string msg, MsgType type, const char* file, int line) { + if (m_lv == VERBOSITY_NONE || (m_lv == VERBOSITY_ERROR && !isErrorMsg(type)) || + (m_lv == VERBOSITY_WARNING_ERROR && !(isWarningMsg(type) || isErrorMsg(type))) || + (m_lv == VERBOSITY_INFO_WARNING_ERROR && isDebugMsg(type))) + return; + + // if print is allowed by current verbosity level + if (isStreamMsg(type)) { + // check whether counter already exists + std::ostringstream oss; + oss << file << line; + std::string id(oss.str()); + map<string, double>::iterator it = m_stream_msg_counters.find(id); + if (it == m_stream_msg_counters.end()) { + // if counter doesn't exist then add one + m_stream_msg_counters.insert(make_pair(id, 0.0)); + it = m_stream_msg_counters.find(id); + } + + // if counter is greater than 0 then decrement it and do not print + if (it->second > 0.0) { + it->second -= m_timeSample; + if (it->second <= 0.0) + it->second = m_streamPrintPeriod; + else + return; + } else // otherwise reset counter and print + it->second = m_streamPrintPeriod; } + dgRTLOG() << msg.c_str() << "\n"; +} - bool Logger::setTimeSample(double t) - { - if(t<=0.0) - return false; - m_timeSample = t; - return true; - } +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; - } +bool Logger::setStreamPrintPeriod(double s) { + if (s <= 0.0) return false; + m_streamPrintPeriod = s; + return true; +} - double Logger::getTimeSample() - { - return m_timeSample; - } +double Logger::getTimeSample() { return m_timeSample; } - double Logger::getStreamPrintPeriod() - { - return m_streamPrintPeriod; - } -} // namespace dynamicgraph +double Logger::getStreamPrintPeriod() { return m_streamPrintPeriod; } +} // namespace dynamicgraph diff --git a/src/debug/real-time-logger.cpp b/src/debug/real-time-logger.cpp index c3278435c163713a863f58d39289c63292e21467..c0940f7cf4360873eac22b2b3d5cf3c3d3b47f5c 100644 --- a/src/debug/real-time-logger.cpp +++ b/src/debug/real-time-logger.cpp @@ -11,151 +11,124 @@ #include <boost/thread/thread.hpp> #include <boost/date_time/posix_time/posix_time.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; - } +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]; - } +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; +} - 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_); +} - 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_); +RTLoggerStream::~RTLoggerStream() { + os_ << std::ends; + if (logger_ != NULL) logger_->frontReady(); +} + +struct RealTimeLogger::thread { + bool requestShutdown_; + int threadPolicy_; + int threadPriority_; + bool changedThreadParams; + boost::thread t_; + + 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; } - RTLoggerStream::~RTLoggerStream() - { - os_ << std::ends; - if (logger_ != NULL) logger_->frontReady(); + void setPriority(int priority) { + threadPriority_ = priority; + changedThreadParams = true; } - struct RealTimeLogger::thread - { - bool requestShutdown_; - int threadPolicy_; - int threadPriority_; - bool changedThreadParams; - boost::thread t_; - - 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; - - } + int getThreadPolicy() { return threadPolicy_; } + int getThreadPriority() { return threadPriority_; } - 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(); - } + 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; } - }; + } - RealTimeLogger* RealTimeLogger::instance_ = NULL; - RealTimeLogger::thread* RealTimeLogger::thread_ = NULL; + void spin(RealTimeLogger* logger) { + // Change the thread's scheduler from real-time to normal + // and reduce its priority - RealTimeLogger& RealTimeLogger::instance() - { - if (instance_ == NULL) { - instance_ = new RealTimeLogger (1000); - thread_ = new thread (instance_); + 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(); } - return *instance_; } +}; + +RealTimeLogger* RealTimeLogger::instance_ = NULL; +RealTimeLogger::thread* RealTimeLogger::thread_ = NULL; - void RealTimeLogger::destroy () - { - if (instance_ == NULL) return; - thread_->requestShutdown_ = true; - thread_->t_.join(); - delete instance_; - delete thread_; +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 diff --git a/src/dgraph/entity.cpp b/src/dgraph/entity.cpp index eb5bf597b060161b49110308e7a3c9ffa4f06941..a13d290ee3672ae227c957c302920752c479942d 100644 --- a/src/dgraph/entity.cpp +++ b/src/dgraph/entity.cpp @@ -18,46 +18,30 @@ #include <stdlib.h> #include <sstream> - using namespace std; using namespace dynamicgraph; using dynamicgraph::command::Command; -void Entity:: -entityRegistration () -{ - - PoolStorage::getInstance()->registerEntity(name,this); -} +void Entity::entityRegistration() { PoolStorage::getInstance()->registerEntity(name, this); } -void Entity:: -entityDeregistration () -{ - PoolStorage::getInstance()->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 = this->getClassName(); Cannot call a virtual function from the constructor - 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 (); + entityRegistration(); } -Entity:: -~Entity () -{ +Entity::~Entity() { dgDEBUG(25) << "# In (" << name << " { " << endl; - for (std::map<const std::string, Command*>::iterator it = - commandMap.begin(); it != commandMap.end(); it++) { + for (std::map<const std::string, Command*>::iterator it = commandMap.begin(); it != commandMap.end(); it++) { delete it->second; } dgDEBUGOUT(25); @@ -66,201 +50,136 @@ Entity:: /* -------------------------------------------------------------------------- */ /* --- 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); + } +} -std::string Entity::getDocString () const -{ - std::string docString ("No header documentation."); +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) ; +#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())); } -bool Entity:: -hasSignal( const string & signame ) const -{ - return (!(signalMap.find(signame) == signalMap.end ())); -} +SignalBase<int>& Entity::getSignal(const string& signame) { __DG_ENTITY_GET_SIGNAL__(iterator); } -SignalBase<int>& Entity:: -getSignal( const string & signame ) -{ - __DG_ENTITY_GET_SIGNAL__(iterator); -} +const SignalBase<int>& Entity::getSignal(const string& signame) const { __DG_ENTITY_GET_SIGNAL__(const_iterator); } -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; + 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; -} +Entity::SignalMap Entity::getSignalMap() const { return signalMap; } /* --- PARAMS --------------------------------------------------------------- */ /* --- PARAMS --------------------------------------------------------------- */ /* --- PARAMS --------------------------------------------------------------- */ static std::string Entity_COMMAND_LIST = "print\nsignals\nsignalDep"; -const std::string& Entity:: -getCommandList () const -{ - return Entity_COMMAND_LIST; -} +const std::string& Entity::getCommandList() const { return Entity_COMMAND_LIST; } /// Add a command to Entity -void Entity:: -addCommand(const std::string& inName, Command* command) -{ +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."); + "Command " + inName + " already registered in Entity."); } std::pair<const std::string, Command*> item(inName, command); commandMap.insert(item); } /// Return the list of command objects -std::map<const std::string, Command*> Entity:: -getNewStyleCommandMap() -{ - return commandMap; -} +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."); - } +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 char *file, - int line) -{ - logger_.sendMsg("["+name+"]"+msg,t,file,line); +void Entity::sendMsg(const std::string& msg, MsgType t, const char* file, int line) { + logger_.sendMsg("[" + name + "]" + msg, t, file, line); } diff --git a/src/dgraph/factory.cpp b/src/dgraph/factory.cpp index 9c10a6c9f77f0f5afd61d7b81fb782cc8849ac99..326f137a8c10d2aabbfb1344a020424d1dc901db 100644 --- a/src/dgraph/factory.cpp +++ b/src/dgraph/factory.cpp @@ -10,145 +10,102 @@ using namespace std; using namespace dynamicgraph; -namespace dynamicgraph -{ - FactoryStorage* FactoryStorage::getInstance () - { - if (instance_ == 0) { - instance_ = new FactoryStorage; - } - return instance_; - } - - 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) - { - dgDEBUGIN (25); - 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) - { - dgDEBUGIN (25); - 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); +namespace dynamicgraph { +FactoryStorage* FactoryStorage::getInstance() { + if (instance_ == 0) { + instance_ = new FactoryStorage; } + return instance_; +} + +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) { + dgDEBUGIN(25); + 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."); + } - 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); + dgDEBUG(30) << "Register entity <" << entname << "> in the factory." << std::endl; + entityMap[entname] = ent; } - - - // 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)); + dgDEBUGOUT(25); +} + +void FactoryStorage::deregisterEntity(const std::string& entname) { + dgDEBUGIN(25); + 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); +} - //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); - } +Entity* FactoryStorage::newEntity(const std::string& classname, const std::string& objname) const { + dgDEBUG(15) << "New <" << classname << ">Entity <" << objname << ">" << std::endl; - EntityRegisterer::EntityRegisterer - (const std::string& entityClassName, FactoryStorage::EntityConstructor_ptr maker) - : entityName (entityClassName) - { - dgDEBUGIN (15); - FactoryStorage::getInstance()->registerEntity (entityClassName, maker); - dgDEBUGOUT (15); + 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()); } - - EntityRegisterer::~EntityRegisterer () - { - dgDEBUGIN(15); - FactoryStorage::getInstance()->deregisterEntity (entityName); - dgDEBUGOUT (15); - } - - - // The global factory. - FactoryStorage* FactoryStorage::instance_ = NULL; -} // end of namespace dynamicgraph. + return entPtr->second(objname); +} + +// 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)); +} + +// 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); +} + +EntityRegisterer::EntityRegisterer(const std::string& entityClassName, FactoryStorage::EntityConstructor_ptr maker) + : entityName(entityClassName) { + dgDEBUGIN(15); + FactoryStorage::getInstance()->registerEntity(entityClassName, maker); + dgDEBUGOUT(15); +} + +EntityRegisterer::~EntityRegisterer() { + dgDEBUGIN(15); + FactoryStorage::getInstance()->deregisterEntity(entityName); + dgDEBUGOUT(15); +} + +// The global factory. +FactoryStorage* FactoryStorage::instance_ = NULL; +} // end of namespace dynamicgraph. diff --git a/src/dgraph/pool.cpp b/src/dgraph/pool.cpp index 0d240cfe0784f564b2b72b607cb62e35f42eed92..0d1973851bae618a789491758cea3db8e6bd71db 100644 --- a/src/dgraph/pool.cpp +++ b/src/dgraph/pool.cpp @@ -26,144 +26,95 @@ using namespace dynamicgraph; /* --- CLASS ----------------------------------------------------------- */ /* --------------------------------------------------------------------- */ -PoolStorage* PoolStorage:: -getInstance() -{ +PoolStorage* PoolStorage::getInstance() { if (instance_ == 0) { instance_ = new PoolStorage; } return instance_; } -void PoolStorage:: -destroy() -{ +void PoolStorage::destroy() { delete instance_; instance_ = NULL; } -PoolStorage:: -~PoolStorage () -{ +PoolStorage::~PoolStorage() { dgDEBUGIN(15); - for( Entities::iterator iter=entityMap.begin (); iter!=entityMap.end (); + for (Entities::iterator iter = entityMap.begin(); iter != entityMap.end(); // Here, this is normal that the next iteration is at the beginning // of the map as deregisterEntity remove the element iter from the map. - iter=entityMap.begin()) - { - dgDEBUG(15) << "Delete \"" - << (iter->first) <<"\""<<std::endl; - Entity* entity = iter->second; - deregisterEntity(iter); - delete (entity); - } + iter = entityMap.begin()) { + dgDEBUG(15) << "Delete \"" << (iter->first) << "\"" << std::endl; + Entity* entity = iter->second; + deregisterEntity(iter); + delete (entity); + } instance_ = 0; dgDEBUGOUT(15); } - - /* --------------------------------------------------------------------- */ -void PoolStorage:: -registerEntity( const std::string& entname,Entity* ent ) -{ +void PoolStorage::registerEntity(const std::string& entname, Entity* ent) { Entities::iterator entkey = entityMap.find(entname); - if( entkey != entityMap.end () ) // key does exist - { - throw ExceptionFactory( ExceptionFactory::OBJECT_CONFLICT, - "Another entity already defined with the same name. ", - "Entity name is <%s>.",entname.c_str () ); - } - else - { - dgDEBUG(10) << "Register entity <"<< entname - << "> in the pool." <<std::endl; - entityMap[entname] = ent; - } + if (entkey != entityMap.end()) // key does exist + { + throw ExceptionFactory(ExceptionFactory::OBJECT_CONFLICT, "Another entity already defined with the same name. ", + "Entity name is <%s>.", entname.c_str()); + } else { + dgDEBUG(10) << "Register entity <" << entname << "> in the pool." << std::endl; + entityMap[entname] = ent; + } } -void PoolStorage:: -deregisterEntity( const std::string& entname ) -{ +void PoolStorage::deregisterEntity(const std::string& entname) { Entities::iterator entkey = entityMap.find(entname); - if( entkey == entityMap.end () ) // key doesnot exist - { - throw ExceptionFactory( ExceptionFactory::OBJECT_CONFLICT, - "Entity not defined yet. ", - "Entity name is <%s>.",entname.c_str () ); - } - else - { - dgDEBUG(10) << "Deregister entity <"<< entname - << "> from the pool." <<std::endl; - deregisterEntity(entkey); - } + if (entkey == entityMap.end()) // key doesnot exist + { + throw ExceptionFactory(ExceptionFactory::OBJECT_CONFLICT, "Entity not defined yet. ", "Entity name is <%s>.", + entname.c_str()); + } else { + dgDEBUG(10) << "Deregister entity <" << entname << "> from the pool." << std::endl; + deregisterEntity(entkey); + } } -void PoolStorage:: -deregisterEntity( const Entities::iterator& entity ) -{ - entityMap.erase( entity ); -} +void PoolStorage::deregisterEntity(const Entities::iterator& entity) { entityMap.erase(entity); } -Entity& PoolStorage:: -getEntity( const std::string& name ) -{ - dgDEBUG(25) << "Get <" << name << ">"<<std::endl; - Entities::iterator entPtr = entityMap.find( name ); - if( entPtr == entityMap.end () ) - { - DG_THROW ExceptionFactory( ExceptionFactory::UNREFERED_OBJECT, - "Unknown entity."," (while calling <%s>)", - name.c_str () ); - } - else return *entPtr->second; +Entity& PoolStorage::getEntity(const std::string& name) { + dgDEBUG(25) << "Get <" << name << ">" << std::endl; + Entities::iterator entPtr = entityMap.find(name); + if (entPtr == entityMap.end()) { + DG_THROW ExceptionFactory(ExceptionFactory::UNREFERED_OBJECT, "Unknown entity.", " (while calling <%s>)", + name.c_str()); + } else + return *entPtr->second; } -const PoolStorage::Entities& PoolStorage:: -getEntityMap () const -{ - return entityMap; -} +const PoolStorage::Entities& PoolStorage::getEntityMap() const { return entityMap; } -bool PoolStorage:: -existEntity (const std::string& name) -{ - return entityMap.find( name ) != entityMap.end(); -} -bool PoolStorage:: -existEntity (const std::string& name, Entity*& ptr) -{ - Entities::iterator entPtr = entityMap.find( name ); - if( entPtr == entityMap.end () ) return false; - else - { - ptr = entPtr->second; - return true; - } +bool PoolStorage::existEntity(const std::string& name) { return entityMap.find(name) != entityMap.end(); } +bool PoolStorage::existEntity(const std::string& name, Entity*& ptr) { + Entities::iterator entPtr = entityMap.find(name); + if (entPtr == entityMap.end()) + return false; + else { + ptr = entPtr->second; + return true; + } } - -void PoolStorage:: -clearPlugin( const std::string& name ) -{ +void PoolStorage::clearPlugin(const std::string& name) { dgDEBUGIN(5); std::list<Entity*> toDelete; - for (Entities::iterator entPtr = entityMap.begin (); - entPtr != entityMap.end (); ++entPtr) - if (entPtr->second->getClassName () == name) - toDelete.push_back (entPtr->second); + for (Entities::iterator entPtr = entityMap.begin(); entPtr != entityMap.end(); ++entPtr) + if (entPtr->second->getClassName() == name) toDelete.push_back(entPtr->second); - for (std::list< Entity* >::iterator iter = toDelete.begin (); - iter != toDelete.end (); ++iter) - delete (Entity*) *iter; + for (std::list<Entity*>::iterator iter = toDelete.begin(); iter != toDelete.end(); ++iter) delete (Entity*)*iter; dgDEBUGOUT(5); } - - /* --------------------------------------------------------------------- */ #include <dynamic-graph/entity.h> @@ -172,15 +123,13 @@ clearPlugin( const std::string& name ) #include <time.h> #endif /*WIN32*/ -void PoolStorage:: -writeGraph(const std::string &aFileName) -{ +void PoolStorage::writeGraph(const std::string& aFileName) { size_t IdxPointFound = aFileName.rfind("."); - std::string tmp1 = aFileName.substr(0,IdxPointFound); + std::string tmp1 = aFileName.substr(0, IdxPointFound); size_t IdxSeparatorFound = aFileName.rfind("/"); std::string GenericName; - if (IdxSeparatorFound!=std::string::npos) - GenericName = tmp1.substr(IdxSeparatorFound,tmp1.length ()); + if (IdxSeparatorFound != std::string::npos) + GenericName = tmp1.substr(IdxSeparatorFound, tmp1.length()); else GenericName = tmp1; @@ -189,86 +138,69 @@ writeGraph(const std::string &aFileName) ltime = time(NULL); struct tm ltimeformatted; #ifdef WIN32 - localtime_s(<imeformatted,<ime); + localtime_s(<imeformatted, <ime); #else - localtime_r(<ime,<imeformatted); + localtime_r(<ime, <imeformatted); #endif /*WIN32*/ /* Opening the file and writing the first comment. */ - std::ofstream GraphFile (aFileName.c_str (),std::ofstream::out); + std::ofstream GraphFile(aFileName.c_str(), std::ofstream::out); GraphFile << "/* This graph has been automatically generated. " << std::endl; - GraphFile << " " << 1900+ltimeformatted.tm_year - << " Month: " << 1+ltimeformatted.tm_mon - << " Day: " << ltimeformatted.tm_mday - << " Time: " << ltimeformatted.tm_hour - << ":" << ltimeformatted.tm_min; + GraphFile << " " << 1900 + ltimeformatted.tm_year << " Month: " << 1 + ltimeformatted.tm_mon + << " Day: " << ltimeformatted.tm_mday << " Time: " << ltimeformatted.tm_hour << ":" + << ltimeformatted.tm_min; GraphFile << " */" << std::endl; GraphFile << "digraph \"" << GenericName << "\" { "; GraphFile << "\t graph [ label=\"" << GenericName << "\" bgcolor = white rankdir=LR ]" << std::endl - << "\t node [ fontcolor = black, color = black, fillcolor = gold1, style=filled, shape=box ] ; " << std::endl; + << "\t node [ fontcolor = black, color = black, fillcolor = gold1, style=filled, shape=box ] ; " + << std::endl; GraphFile << "\tsubgraph cluster_Entities { " << std::endl; GraphFile << "\t} " << std::endl; - for( Entities::iterator iter=entityMap.begin (); - iter!=entityMap.end (); ++iter) - { - Entity* ent = iter->second; - GraphFile << "\"" << ent->getName () << "\"" - <<" [ label = \"" << ent->getName () << "\" ," << std::endl - <<" fontcolor = black, color = black, fillcolor=cyan, style=filled, shape=box ]" << std::endl; - ent->writeGraph(GraphFile); - } - + for (Entities::iterator iter = entityMap.begin(); iter != entityMap.end(); ++iter) { + Entity* ent = iter->second; + GraphFile << "\"" << ent->getName() << "\"" + << " [ label = \"" << ent->getName() << "\" ," << std::endl + << " fontcolor = black, color = black, fillcolor=cyan, style=filled, shape=box ]" << std::endl; + ent->writeGraph(GraphFile); + } - GraphFile << "}"<< std::endl; + GraphFile << "}" << std::endl; - GraphFile.close (); + GraphFile.close(); } -void PoolStorage:: -writeCompletionList(std::ostream& os) -{ - for( Entities::iterator iter=entityMap.begin (); - iter!=entityMap.end (); ++iter) - { - Entity* ent = iter->second; - ent->writeCompletionList(os); - } - - +void PoolStorage::writeCompletionList(std::ostream& os) { + for (Entities::iterator iter = entityMap.begin(); iter != entityMap.end(); ++iter) { + Entity* ent = iter->second; + ent->writeCompletionList(os); + } } -static bool -objectNameParser( std::istringstream& cmdparse, - std::string& objName, - std::string& funName ) -{ - const int SIZE=128; +static bool objectNameParser(std::istringstream& cmdparse, std::string& objName, std::string& funName) { + const int SIZE = 128; char buffer[SIZE]; cmdparse >> std::ws; - cmdparse.getline( buffer,SIZE,'.' ); - if(! cmdparse.good () ) // The callback is not an object method + cmdparse.getline(buffer, SIZE, '.'); + if (!cmdparse.good()) // The callback is not an object method return false; objName = buffer; - //cmdparse.getline( buffer,SIZE ); - //funName = buffer; + // cmdparse.getline( buffer,SIZE ); + // funName = buffer; cmdparse >> funName; return true; } -SignalBase<int>& -PoolStorage:: -getSignal( std::istringstream& sigpath ) -{ - std::string objname,signame; - if(! objectNameParser( sigpath,objname,signame ) ) - { DG_THROW ExceptionFactory( ExceptionFactory::UNREFERED_SIGNAL, - "Parse error in signal name" ); } - - Entity& ent = getEntity( objname ); - return ent.getSignal( signame ); +SignalBase<int>& PoolStorage::getSignal(std::istringstream& sigpath) { + std::string objname, signame; + if (!objectNameParser(sigpath, objname, signame)) { + DG_THROW ExceptionFactory(ExceptionFactory::UNREFERED_SIGNAL, "Parse error in signal name"); + } + + Entity& ent = getEntity(objname); + return ent.getSignal(signame); } PoolStorage* PoolStorage::instance_ = 0; diff --git a/src/exception/exception-abstract.cpp b/src/exception/exception-abstract.cpp index f1eb90dd0ed428c587d1c09372b4fb6a6503e04f..31fe603a067ca5941110a6399e0738f3d28c28d3 100644 --- a/src/exception/exception-abstract.cpp +++ b/src/exception/exception-abstract.cpp @@ -7,79 +7,46 @@ #include <dynamic-graph/debug.h> namespace dynamicgraph { - const std::string ExceptionAbstract::EXCEPTION_NAME = "Abstract"; +const std::string ExceptionAbstract::EXCEPTION_NAME = "Abstract"; +ExceptionAbstract::ExceptionAbstract(const int& _code, const std::string& _msg) : code(_code), message(_msg) {} - ExceptionAbstract::ExceptionAbstract (const int& _code, - const std::string& _msg) - : code (_code), - message (_msg) - {} +const char* ExceptionAbstract::getMessage() const { return (this->message).c_str(); } - const char* - ExceptionAbstract::getMessage () const - { - return (this->message) .c_str (); - } +const std::string& ExceptionAbstract::getStringMessage() const { return this->message; } - const std::string& - ExceptionAbstract::getStringMessage () const - { - return this->message; - } +int ExceptionAbstract::getCode() const { return this->code; } - int - ExceptionAbstract::getCode () const - { - return this->code; - } +ExceptionAbstract::Param& ExceptionAbstract::Param::initCopy(const Param& p) { + if (&p == this) return *this; - ExceptionAbstract::Param& - ExceptionAbstract::Param::initCopy (const Param& p) - { - if (&p == this) - return *this; + dgDEBUGIN(25); + if (p.pointersSet) { + strncpy(function, p.functionPTR, BUFFER_SIZE); + strncpy(file, p.filePTR, BUFFER_SIZE); + line = p.line; + pointersSet = false; + set = true; + } else + set = false; + dgDEBUGOUT(25); + return *this; +} - dgDEBUGIN(25); - if (p.pointersSet) - { - strncpy (function,p.functionPTR, BUFFER_SIZE); - strncpy (file,p.filePTR, BUFFER_SIZE); - line = p.line; - pointersSet = false; - set = true; - } - else - set = false; - dgDEBUGOUT(25); - return *this; - } +ExceptionAbstract::Param::Param(const int& _line, const char* _function, const char* _file) + : functionPTR(_function), line(_line), filePTR(_file), pointersSet(true) { + dgDEBUGINOUT(25); +} - ExceptionAbstract::Param::Param (const int& _line, - const char* _function, - const char* _file) - : functionPTR (_function), - line (_line), - filePTR (_file), - pointersSet (true) - { - dgDEBUGINOUT(25); - } - - std::ostream& - operator << (std::ostream& os, - const ExceptionAbstract& error) - { - os << error.getExceptionName () - << "Error [#" << error.code << "]: " << error.message << std::endl; +std::ostream& operator<<(std::ostream& os, const ExceptionAbstract& error) { + os << error.getExceptionName() << "Error [#" << error.code << "]: " << error.message << std::endl; #ifdef DYNAMICGRAPH_EXCEPTION_PASSING_PARAM - if (error.p.set) - os << "Thrown from " << error.p.file << ": " << error.p.function - <<" (#" << error.p.line << ")"<< std::endl; -#endif // DYNAMICGRAPH_EXCEPTION_PASSING_PARAM + if (error.p.set) + os << "Thrown from " << error.p.file << ": " << error.p.function << " (#" << error.p.line << ")" << std::endl; +#endif // DYNAMICGRAPH_EXCEPTION_PASSING_PARAM - return os; - } + return os; +} -} // end of namespace dynamicgraph. +} // end of namespace dynamicgraph. diff --git a/src/exception/exception-factory.cpp b/src/exception/exception-factory.cpp index 96e925710c2de866b445eb599746c1c605c3c01c..4469f05e2289bd1dc2449a6344cc840949a06b96 100644 --- a/src/exception/exception-factory.cpp +++ b/src/exception/exception-factory.cpp @@ -20,40 +20,33 @@ using namespace dynamicgraph; const std::string ExceptionFactory::EXCEPTION_NAME = "Factory"; -ExceptionFactory:: -ExceptionFactory ( const ExceptionFactory::ErrorCodeEnum& errcode, - const std::string & msg ) - :ExceptionAbstract(errcode,msg) -{ - dgDEBUGF( 15,"Created with message <%s>.",msg.c_str ()); - dgDEBUG( 1) <<"Created with message <%s>."<<msg<<std::endl; +ExceptionFactory::ExceptionFactory(const ExceptionFactory::ErrorCodeEnum& errcode, const std::string& msg) + : ExceptionAbstract(errcode, msg) { + dgDEBUGF(15, "Created with message <%s>.", msg.c_str()); + dgDEBUG(1) << "Created with message <%s>." << msg << std::endl; } -ExceptionFactory:: -ExceptionFactory ( const ExceptionFactory::ErrorCodeEnum& errcode, - const std::string & msg,const char* format, ... ) - :ExceptionAbstract(errcode,msg) -{ +ExceptionFactory::ExceptionFactory(const ExceptionFactory::ErrorCodeEnum& errcode, const std::string& msg, + const char* format, ...) + : ExceptionAbstract(errcode, msg) { va_list args; - va_start(args,format); + va_start(args, format); const unsigned int SIZE = 256; - char buffer[SIZE]; - vsnprintf(buffer,SIZE,format,args); + char buffer[SIZE]; + vsnprintf(buffer, SIZE, format, args); - dgDEBUG(15) <<"Created "<<" with message <" - <<msg<<"> and buffer <"<<buffer<<">. "<<std::endl; + dgDEBUG(15) << "Created " + << " with message <" << msg << "> and buffer <" << buffer << ">. " << std::endl; message += buffer; va_end(args); - dgDEBUG(1) << "Throw exception " << EXCEPTION_NAME << "[#" << errcode<<"]: " - <<"<"<< message << ">."<<std::endl; - + dgDEBUG(1) << "Throw exception " << EXCEPTION_NAME << "[#" << errcode << "]: " + << "<" << message << ">." << std::endl; } - /* * Local variables: * c-basic-offset: 2 diff --git a/src/exception/exception-signal.cpp b/src/exception/exception-signal.cpp index 44ab17d7109e4d8a19485dddd3a49b90d651c27e..1fa5c2331a6571bc021059d2b46e2be4f53f5a86 100644 --- a/src/exception/exception-signal.cpp +++ b/src/exception/exception-signal.cpp @@ -19,32 +19,24 @@ using namespace dynamicgraph; const std::string ExceptionSignal::EXCEPTION_NAME = "Signal"; -ExceptionSignal:: -ExceptionSignal ( const ExceptionSignal::ErrorCodeEnum& errcode, - const std::string & msg ) - :ExceptionAbstract(errcode,msg) -{ -} +ExceptionSignal::ExceptionSignal(const ExceptionSignal::ErrorCodeEnum& errcode, const std::string& msg) + : ExceptionAbstract(errcode, msg) {} -ExceptionSignal:: -ExceptionSignal ( const ExceptionSignal::ErrorCodeEnum& errcode, - const std::string & msg,const char* format, ... ) - :ExceptionAbstract(errcode,msg) -{ +ExceptionSignal::ExceptionSignal(const ExceptionSignal::ErrorCodeEnum& errcode, const std::string& msg, + const char* format, ...) + : ExceptionAbstract(errcode, msg) { va_list args; - va_start(args,format); + va_start(args, format); const unsigned int SIZE = 256; - char buffer[SIZE]; - vsnprintf(buffer,SIZE,format,args); + char buffer[SIZE]; + vsnprintf(buffer, SIZE, format, args); message += buffer; va_end(args); } - - /* * Local variables: * c-basic-offset: 2 diff --git a/src/exception/exception-traces.cpp b/src/exception/exception-traces.cpp index a02858182e5873c009b241d3e94973960261635f..a97d81b85fea6633dd5fbc728ac1e5ee1afa4769 100644 --- a/src/exception/exception-traces.cpp +++ b/src/exception/exception-traces.cpp @@ -11,7 +11,6 @@ #include <stdarg.h> #include <cstdio> - using namespace dynamicgraph; /* --------------------------------------------------------------------- */ /* --- CLASS ----------------------------------------------------------- */ @@ -19,32 +18,24 @@ using namespace dynamicgraph; const std::string ExceptionTraces::EXCEPTION_NAME = "Traces"; -ExceptionTraces:: -ExceptionTraces ( const ExceptionTraces::ErrorCodeEnum& errcode, - const std::string & msg ) - :ExceptionAbstract(errcode,msg) -{ -} +ExceptionTraces::ExceptionTraces(const ExceptionTraces::ErrorCodeEnum& errcode, const std::string& msg) + : ExceptionAbstract(errcode, msg) {} -ExceptionTraces:: -ExceptionTraces ( const ExceptionTraces::ErrorCodeEnum& errcode, - const std::string & msg,const char* format, ... ) - :ExceptionAbstract(errcode,msg) -{ +ExceptionTraces::ExceptionTraces(const ExceptionTraces::ErrorCodeEnum& errcode, const std::string& msg, + const char* format, ...) + : ExceptionAbstract(errcode, msg) { va_list args; - va_start(args,format); + va_start(args, format); const unsigned int SIZE = 256; - char buffer[SIZE]; - vsnprintf(buffer,SIZE,format,args); + char buffer[SIZE]; + vsnprintf(buffer, SIZE, format, args); message += buffer; va_end(args); } - - /* * Local variables: * c-basic-offset: 2 diff --git a/src/mt/process-list.cpp b/src/mt/process-list.cpp index 711e8dd1dd15d36023e7681758f1d97c4db92ee4..94dbdad5029a06d6acc438521a978623ecc248d5 100644 --- a/src/mt/process-list.cpp +++ b/src/mt/process-list.cpp @@ -9,28 +9,23 @@ #include <dynamic-graph/process-list.hh> using namespace dynamicgraph::CPU; -CPUData::CPUData(): - user_mode_time_(0), - nice_time_(0), - system_time_(0), - idle_time_(0), - iowait_time_(0), - irq_time_(0), - softirq_time_(0), - steal_time_(0), - guest_time_(0), - guest_nice_time_(0), - percent_(0.0) -{ -} +CPUData::CPUData() + : user_mode_time_(0), + nice_time_(0), + system_time_(0), + idle_time_(0), + iowait_time_(0), + irq_time_(0), + softirq_time_(0), + steal_time_(0), + guest_time_(0), + guest_nice_time_(0), + percent_(0.0) {} + +void CPUData::ProcessLine(std::istringstream &aCPULine) { + unsigned long long int luser_mode_time = 0, lnice_time = 0, lsystem_time = 0, lidle_time = 0, liowait_time = 0, + lirq_time = 0, lsoftirq_time = 0, lsteal_time = 0, lguest_time = 0, lguest_nice_time; -void CPUData::ProcessLine(std::istringstream &aCPULine) -{ - unsigned long long int luser_mode_time=0, - lnice_time=0, lsystem_time=0, lidle_time=0, - liowait_time=0, lirq_time=0, lsoftirq_time=0, - lsteal_time=0,lguest_time=0, lguest_nice_time; - aCPULine >> luser_mode_time; aCPULine >> lnice_time; aCPULine >> lsystem_time; @@ -47,128 +42,109 @@ void CPUData::ProcessLine(std::istringstream &aCPULine) lnice_time -= lguest_nice_time; // Compute cumulative time - unsigned long long int lidle_all_time=0, - lsystem_all_time=0, lguest_all_time=0, ltotal_time=0; + unsigned long long int lidle_all_time = 0, lsystem_all_time = 0, lguest_all_time = 0, ltotal_time = 0; lidle_all_time = lidle_time + liowait_time; lsystem_all_time = lsystem_time + lirq_time + lsoftirq_time; lguest_all_time = lguest_time + lguest_nice_time; - ltotal_time = luser_mode_time + lnice_time + lsystem_all_time + - lidle_all_time + lsteal_time + lguest_all_time; - + ltotal_time = luser_mode_time + lnice_time + lsystem_all_time + lidle_all_time + lsteal_time + lguest_all_time; // Update periodic computation. - user_mode_period_ = computePeriod(luser_mode_time, user_mode_time_); - nice_period_ = computePeriod(lnice_time, nice_time_); - system_period_ = computePeriod(lsystem_time, system_time_); - system_all_period_ = computePeriod(lsystem_all_time,system_all_time_); - idle_period_ = computePeriod(lidle_time, idle_time_); - idle_all_period_ = computePeriod(lidle_all_time, idle_all_time_); - iowait_period_ = computePeriod(liowait_time, idle_time_); - irq_period_ = computePeriod(lirq_time, irq_time_); - softirq_period_ = computePeriod(lsoftirq_time, softirq_time_); - steal_period_ = computePeriod(lsteal_time, steal_time_); - guest_period_ = computePeriod(lguest_all_time, guest_time_); - total_period_ = computePeriod(ltotal_time, total_time_); + user_mode_period_ = computePeriod(luser_mode_time, user_mode_time_); + nice_period_ = computePeriod(lnice_time, nice_time_); + system_period_ = computePeriod(lsystem_time, system_time_); + system_all_period_ = computePeriod(lsystem_all_time, system_all_time_); + idle_period_ = computePeriod(lidle_time, idle_time_); + idle_all_period_ = computePeriod(lidle_all_time, idle_all_time_); + iowait_period_ = computePeriod(liowait_time, idle_time_); + irq_period_ = computePeriod(lirq_time, irq_time_); + softirq_period_ = computePeriod(lsoftirq_time, softirq_time_); + steal_period_ = computePeriod(lsteal_time, steal_time_); + guest_period_ = computePeriod(lguest_all_time, guest_time_); + total_period_ = computePeriod(ltotal_time, total_time_); /// Update time. - user_mode_time_ = luser_mode_time; - nice_time_ = lnice_time; - system_time_ = lsystem_time; + user_mode_time_ = luser_mode_time; + nice_time_ = lnice_time; + system_time_ = lsystem_time; system_all_time_ = lsystem_all_time; - idle_time_ = lidle_time; - idle_all_time_ = lidle_all_time; - iowait_time_ = liowait_time; - irq_time_ = lirq_time; - softirq_time_ = lsoftirq_time; - steal_time_ = lsteal_time; - guest_time_ = lguest_all_time; - total_time_ = ltotal_time; - - if (total_period_!=0) - { - percent_ = (double)(user_mode_period_)/(double)(total_period_) * 100.0; - percent_ += (double)( nice_period_)/(double)(total_period_) * 100.0; - percent_ += (double)( system_period_)/(double)(total_period_) * 100.0; - percent_ += (double)( irq_period_)/(double)(total_period_) * 100.0; - percent_ += (double)( softirq_period_)/(double)(total_period_) * 100.0; - percent_ += (double)( steal_period_)/(double)(total_period_) * 100.0; - percent_ += (double)( iowait_period_)/(double)(total_period_) * 100.0; - } + idle_time_ = lidle_time; + idle_all_time_ = lidle_all_time; + iowait_time_ = liowait_time; + irq_time_ = lirq_time; + softirq_time_ = lsoftirq_time; + steal_time_ = lsteal_time; + guest_time_ = lguest_all_time; + total_time_ = ltotal_time; + + if (total_period_ != 0) { + percent_ = (double)(user_mode_period_) / (double)(total_period_)*100.0; + percent_ += (double)(nice_period_) / (double)(total_period_)*100.0; + percent_ += (double)(system_period_) / (double)(total_period_)*100.0; + percent_ += (double)(irq_period_) / (double)(total_period_)*100.0; + percent_ += (double)(softirq_period_) / (double)(total_period_)*100.0; + percent_ += (double)(steal_period_) / (double)(total_period_)*100.0; + percent_ += (double)(iowait_period_) / (double)(total_period_)*100.0; + } } -System::System() -{ +System::System() { vCPUData_.clear(); init(); } -void System::init() -{ +void System::init() { init_ = false; readProcStat(); init_ = true; } -void System::ProcessCPULine(unsigned int cpunb, - std::istringstream &aCPULine) -{ +void System::ProcessCPULine(unsigned int cpunb, std::istringstream &aCPULine) { vCPUData_[cpunb].ProcessLine(aCPULine); } -void System::readProcStat() -{ +void System::readProcStat() { std::ifstream aif; cpuNb_ = 1; - - aif.open("/proc/stat",std::ifstream::in); + + aif.open("/proc/stat", std::ifstream::in); std::string aline; aline.clear(); - while (std::getline(aif,aline)) - { - // Read on line of the file - std::istringstream anISSLine(aline); - std::string line_hdr; - anISSLine >> line_hdr; - - // Check if the line start with cpu - std::size_t pos = line_hdr.find("cpu"); - std::string str_cpunbr = line_hdr.substr(pos+3); - - // Check if this is the first line - if (pos==0 and str_cpunbr.empty()) - { - gCPUData_.ProcessLine(anISSLine); - gCPUData_.cpu_id_=-1; - } - else - { - // If not then check if there is a CPU number - if (pos==0) - { - std::istringstream iss(str_cpunbr); - unsigned int lcpunb; - iss >> lcpunb; - // If we did not initialize - if (!init_) - { - // Count the number of CPU. - if (lcpunb>cpuNb_) - cpuNb_ = lcpunb; - } - else - // Otherwise process the line. - ProcessCPULine(lcpunb,anISSLine); - } - } + while (std::getline(aif, aline)) { + // Read on line of the file + std::istringstream anISSLine(aline); + std::string line_hdr; + anISSLine >> line_hdr; + + // Check if the line start with cpu + std::size_t pos = line_hdr.find("cpu"); + std::string str_cpunbr = line_hdr.substr(pos + 3); + + // Check if this is the first line + if (pos == 0 and str_cpunbr.empty()) { + gCPUData_.ProcessLine(anISSLine); + gCPUData_.cpu_id_ = -1; + } else { + // If not then check if there is a CPU number + if (pos == 0) { + std::istringstream iss(str_cpunbr); + unsigned int lcpunb; + iss >> lcpunb; + // If we did not initialize + if (!init_) { + // Count the number of CPU. + if (lcpunb > cpuNb_) cpuNb_ = lcpunb; + } else + // Otherwise process the line. + ProcessCPULine(lcpunb, anISSLine); + } } + } - if (!init_) - { - /// The number of CPU has been detected by going through /proc/stat. - vCPUData_.resize(cpuNb_+1); - for(int i=0;i<(int)cpuNb_;i++) - vCPUData_[i].cpu_id_ = i; - } + if (!init_) { + /// The number of CPU has been detected by going through /proc/stat. + vCPUData_.resize(cpuNb_ + 1); + for (int i = 0; i < (int)cpuNb_; i++) vCPUData_[i].cpu_id_ = i; + } aif.close(); } diff --git a/src/signal/signal-array.cpp b/src/signal/signal-array.cpp index 02e8a00cee5631177ed7d504a46044908c3ffd42..f0c9961d78415b018667d4cbd72d3596c5ff54c1 100644 --- a/src/signal/signal-array.cpp +++ b/src/signal/signal-array.cpp @@ -5,10 +5,10 @@ * * CNRS/AIST * -*/ + */ #include <dynamic-graph/signal-array.h> namespace dynamicgraph { - SignalArray<int> sotNOSIGNAL(0); +SignalArray<int> sotNOSIGNAL(0); } diff --git a/src/signal/signal-cast-helper.cpp b/src/signal/signal-cast-helper.cpp index dc3d9bca45ea526ede9041599990b96f46b6515f..73de6ddbcb6f646ce697c438b6aa8afffbf0e71f 100644 --- a/src/signal/signal-cast-helper.cpp +++ b/src/signal/signal-cast-helper.cpp @@ -14,80 +14,68 @@ #include <dynamic-graph/exception-signal.h> #include <dynamic-graph/linear-algebra.h> -namespace dynamicgraph -{ +namespace dynamicgraph { - // Define a custom implementation of the DefaultCastRegisterer - // to workaround the limitations of the stream based approach. - // When dealing with double: displaying a double on a stream - // is *NOT* the opposite of reading a double from a stream. - // - // In practice, it means that there is no way to read - // a NaN, +inf, -inf from a stream! - // - // To workaround this problem, parse special values manually - // (the strings used are the one produces by displaying special - // values on a stream). +// Define a custom implementation of the DefaultCastRegisterer +// to workaround the limitations of the stream based approach. +// When dealing with double: displaying a double on a stream +// is *NOT* the opposite of reading a double from a stream. +// +// In practice, it means that there is no way to read +// a NaN, +inf, -inf from a stream! +// +// To workaround this problem, parse special values manually +// (the strings used are the one produces by displaying special +// values on a stream). - template <> - inline boost::any - DefaultCastRegisterer<double>::cast (std::istringstream& iss) - { - std::string tmp; - iss >> tmp; +template <> +inline boost::any DefaultCastRegisterer<double>::cast(std::istringstream& iss) { + std::string tmp; + iss >> tmp; - if (tmp == "nan") - return std::numeric_limits<double>::quiet_NaN (); - else if (tmp == "inf" || tmp == "+inf") - return std::numeric_limits<double>::infinity (); - else if (tmp == "-inf") - return -1. * std::numeric_limits<double>::infinity (); + if (tmp == "nan") + return std::numeric_limits<double>::quiet_NaN(); + else if (tmp == "inf" || tmp == "+inf") + return std::numeric_limits<double>::infinity(); + else if (tmp == "-inf") + return -1. * std::numeric_limits<double>::infinity(); - try - { - return boost::lexical_cast<double> (tmp); - } - catch (boost::bad_lexical_cast&) - { - boost::format fmt ("failed to serialize %s (to double)"); - fmt % tmp; - throw ExceptionSignal(ExceptionSignal::GENERIC, fmt.str ()); - } - } + try { + return boost::lexical_cast<double>(tmp); + } catch (boost::bad_lexical_cast&) { + boost::format fmt("failed to serialize %s (to double)"); + fmt % tmp; + throw ExceptionSignal(ExceptionSignal::GENERIC, fmt.str()); + } +} - /* Specialize Matrix and Vector traces. */ +/* Specialize Matrix and Vector traces. */ - template <> - void - DefaultCastRegisterer<dynamicgraph::Vector>:: - trace(const boost::any& object, std::ostream& os) - { - const dynamicgraph::Vector & v = boost::any_cast<dynamicgraph::Vector> (object); - for( int i=0;i<v.size();++i ) - { os << "\t" << v(i); } +template <> +void DefaultCastRegisterer<dynamicgraph::Vector>::trace(const boost::any& object, std::ostream& os) { + const dynamicgraph::Vector& v = boost::any_cast<dynamicgraph::Vector>(object); + for (int i = 0; i < v.size(); ++i) { + os << "\t" << v(i); } - template <> - void - DefaultCastRegisterer<dynamicgraph::Matrix>:: - trace(const boost::any& object, std::ostream& os) - { - const dynamicgraph::Matrix & m = boost::any_cast<dynamicgraph::Matrix> (object); - for(int i=0;i<m.rows();++i ) - for(int j=0;j<m.cols();++j ) - { os << "\t" << m(i,j); } - } - +} +template <> +void DefaultCastRegisterer<dynamicgraph::Matrix>::trace(const boost::any& object, std::ostream& os) { + const dynamicgraph::Matrix& m = boost::any_cast<dynamicgraph::Matrix>(object); + for (int i = 0; i < m.rows(); ++i) + for (int j = 0; j < m.cols(); ++j) { + os << "\t" << m(i, j); + } +} - /// Registers useful casts - namespace - { - DefaultCastRegisterer<double> double_reg; - DefaultCastRegisterer<int> int_reg; - DefaultCastRegisterer<unsigned int> uint_reg; - DefaultCastRegisterer<bool> bool_reg; - DefaultCastRegisterer<dynamicgraph::Vector> vectorCastRegisterer; - DefaultCastRegisterer<dynamicgraph::Matrix> matrixCastRegisterer; - DefaultCastRegisterer <boost::posix_time::ptime> ptimeCastRegisterer; - } // end of anonymous namespace. +/// Registers useful casts +namespace { +DefaultCastRegisterer<double> double_reg; +DefaultCastRegisterer<int> int_reg; +DefaultCastRegisterer<unsigned int> uint_reg; +DefaultCastRegisterer<bool> bool_reg; +DefaultCastRegisterer<dynamicgraph::Vector> vectorCastRegisterer; +DefaultCastRegisterer<dynamicgraph::Matrix> matrixCastRegisterer; +DefaultCastRegisterer<boost::posix_time::ptime> ptimeCastRegisterer; +} // end of anonymous namespace. -} // namespace dynamicgraph +} // namespace dynamicgraph diff --git a/src/signal/signal-caster.cpp b/src/signal/signal-caster.cpp index b8cac844f1e28dd6e64a64f7fbe77951606f3197..abdc732f42ee33b4fed5f8c4fdc5c81cb8457aae 100644 --- a/src/signal/signal-caster.cpp +++ b/src/signal/signal-caster.cpp @@ -13,114 +13,84 @@ #include <dynamic-graph/linear-algebra.h> -namespace dynamicgraph -{ - - SignalCaster::SignalCaster () - {} - - SignalCaster::~SignalCaster () - {} - - void SignalCaster::destroy() - { - delete instance_; - instance_ = 0; - } - - void - SignalCaster::registerCast (const std::type_info& type, - SignalCaster::displayer_type displayer, - SignalCaster::caster_type caster, - SignalCaster::tracer_type tracer) - { - if (existsCast (type)) - { - // If type name has already been registered for same type, do not throw. - if (type_info_[type.name()] != &type) - { - std::string typeName(type.name()); - std::ostringstream os; - os << "cast already registered for typename " << typeName << "\n" - << "and types differ: " << &type << " != " - << type_info_[type.name()] - << ".\n" - << "A possible reason is that the dynamic" - << " library defining this type\n" - << "has been loaded several times, defining different symbols" - << " for the same type."; - throw ExceptionSignal(ExceptionSignal::GENERIC, - os.str()); - } - } - functions_[type.name()] = cast_functions_type(displayer,caster, tracer); - type_info_[type.name()] = &type; - } - - void - SignalCaster::unregisterCast (const std::type_info& type) - { - size_t n = functions_.erase(type.name ()); - if (0 == n) // erase did not find element - // TODO: throw Cast not registered exception - throw ExceptionSignal(ExceptionSignal::GENERIC); - } - - bool - SignalCaster::existsCast (const std::type_info& type) const - { - return functions_.find (type.name ()) != functions_.end (); - } - - SignalCaster::cast_functions_type& - SignalCaster::getCast (const std::string& type_name) - { - std::map<std::string, cast_functions_type>::iterator it = - functions_.find(type_name); - - if (it == functions_.end ()) - //TODO: throw "cast not registered" exception - throw ExceptionSignal(ExceptionSignal::BAD_CAST, "Cast not registered"); - return it->second; - } - - void SignalCaster::disp (const boost::any& object, std::ostream& os) - { - getCast(object.type ().name ()).get<0> () (object, os); - - - } - - void - SignalCaster::trace(const boost::any& object, std::ostream& os) - { - getCast(object.type ().name ()).get<2> () (object, os); - } - - std::vector<std::string> - SignalCaster::listTypenames() const - { - std::vector<std::string> typeList; - for (std::map<std::string, cast_functions_type>::const_iterator iter = - functions_.begin(); iter != functions_.end(); iter++) - typeList.push_back(iter->first); - return typeList; - } - - boost::any - SignalCaster::cast (const std::type_info& type, std::istringstream& iss) - { - return getCast(type.name ()).get<1> () (iss); - } - - /// Singleton on the library-wide instance of SignalCaster - SignalCaster* SignalCaster::getInstance(void) - { - if (instance_ == 0) { - instance_ = new SignalCaster; +namespace dynamicgraph { + +SignalCaster::SignalCaster() {} + +SignalCaster::~SignalCaster() {} + +void SignalCaster::destroy() { + delete instance_; + instance_ = 0; +} + +void SignalCaster::registerCast(const std::type_info& type, SignalCaster::displayer_type displayer, + SignalCaster::caster_type caster, SignalCaster::tracer_type tracer) { + if (existsCast(type)) { + // If type name has already been registered for same type, do not throw. + if (type_info_[type.name()] != &type) { + std::string typeName(type.name()); + std::ostringstream os; + os << "cast already registered for typename " << typeName << "\n" + << "and types differ: " << &type << " != " << type_info_[type.name()] << ".\n" + << "A possible reason is that the dynamic" + << " library defining this type\n" + << "has been loaded several times, defining different symbols" + << " for the same type."; + throw ExceptionSignal(ExceptionSignal::GENERIC, os.str()); } - return instance_; } - SignalCaster* SignalCaster::instance_ = 0; + functions_[type.name()] = cast_functions_type(displayer, caster, tracer); + type_info_[type.name()] = &type; +} + +void SignalCaster::unregisterCast(const std::type_info& type) { + size_t n = functions_.erase(type.name()); + if (0 == n) // erase did not find element + // TODO: throw Cast not registered exception + throw ExceptionSignal(ExceptionSignal::GENERIC); +} + +bool SignalCaster::existsCast(const std::type_info& type) const { + return functions_.find(type.name()) != functions_.end(); +} + +SignalCaster::cast_functions_type& SignalCaster::getCast(const std::string& type_name) { + std::map<std::string, cast_functions_type>::iterator it = functions_.find(type_name); + + if (it == functions_.end()) + // TODO: throw "cast not registered" exception + throw ExceptionSignal(ExceptionSignal::BAD_CAST, "Cast not registered"); + return it->second; +} + +void SignalCaster::disp(const boost::any& object, std::ostream& os) { + getCast(object.type().name()).get<0>()(object, os); +} + +void SignalCaster::trace(const boost::any& object, std::ostream& os) { + getCast(object.type().name()).get<2>()(object, os); +} + +std::vector<std::string> SignalCaster::listTypenames() const { + std::vector<std::string> typeList; + for (std::map<std::string, cast_functions_type>::const_iterator iter = functions_.begin(); iter != functions_.end(); + iter++) + typeList.push_back(iter->first); + return typeList; +} + +boost::any SignalCaster::cast(const std::type_info& type, std::istringstream& iss) { + return getCast(type.name()).get<1>()(iss); +} + +/// Singleton on the library-wide instance of SignalCaster +SignalCaster* SignalCaster::getInstance(void) { + if (instance_ == 0) { + instance_ = new SignalCaster; + } + return instance_; +} +SignalCaster* SignalCaster::instance_ = 0; -} // namespace dynamicgraph +} // namespace dynamicgraph diff --git a/src/traces/tracer-real-time.cpp b/src/traces/tracer-real-time.cpp index cc7abf083ae7c319749fc563a773d4161e7f408c..505e97c389a72100a2a65bab0567d307c31edf5f 100644 --- a/src/traces/tracer-real-time.cpp +++ b/src/traces/tracer-real-time.cpp @@ -24,104 +24,78 @@ using namespace std; using namespace dynamicgraph; -DYNAMICGRAPH_FACTORY_ENTITY_PLUGIN(TracerRealTime,"TracerRealTime"); +DYNAMICGRAPH_FACTORY_ENTITY_PLUGIN(TracerRealTime, "TracerRealTime"); /* --------------------------------------------------------------------- */ /* --- DGOUTSTRINGSTREAM ---------------------------------------------- */ /* --------------------------------------------------------------------- */ -OutStringStream:: -OutStringStream () - : std::ostringstream () - ,buffer( 0 ),index(0),bufferSize(0),full(false) -{ +OutStringStream::OutStringStream() : std::ostringstream(), buffer(0), index(0), bufferSize(0), full(false) { dgDEBUGINOUT(15); } -OutStringStream:: -~OutStringStream () -{ +OutStringStream::~OutStringStream() { dgDEBUGIN(15); delete[] buffer; dgDEBUGOUT(15); } -void OutStringStream:: -resize (const std::streamsize& size) -{ +void OutStringStream::resize(const std::streamsize& size) { dgDEBUGIN(15); - index=0; + index = 0; bufferSize = size; - full=false; + full = false; delete[] buffer; - buffer = new char[static_cast<size_t> (size)]; + buffer = new char[static_cast<size_t>(size)]; dgDEBUGOUT(15); } -bool OutStringStream:: -addData (const char * data, const std::streamoff& size) -{ +bool OutStringStream::addData(const char* data, const std::streamoff& size) { dgDEBUGIN(15); - std::streamsize towrite = static_cast<std::streamsize> (size); - if (index + towrite > bufferSize) - { - dgDEBUGOUT(15); - full = true; - return false; - } - memcpy (buffer + index, data, static_cast<size_t> (towrite)); + std::streamsize towrite = static_cast<std::streamsize>(size); + if (index + towrite > bufferSize) { + dgDEBUGOUT(15); + full = true; + return false; + } + memcpy(buffer + index, data, static_cast<size_t>(towrite)); index += towrite; dgDEBUGOUT(15); return true; } -void OutStringStream:: -dump( std::ostream& os ) -{ +void OutStringStream::dump(std::ostream& os) { dgDEBUGIN(15); - os.write( buffer,index ); + os.write(buffer, index); dgDEBUGOUT(15); } -void OutStringStream:: -empty () -{ +void OutStringStream::empty() { dgDEBUGIN(15); - index=0; full=false; + index = 0; + full = false; dgDEBUGOUT(15); } - - /* --------------------------------------------------------------------- */ /* --------------------------------------------------------------------- */ /* --------------------------------------------------------------------- */ - -TracerRealTime::TracerRealTime( const std::string & n ) - :Tracer(n) - ,bufferSize( BUFFER_SIZE_DEFAULT ) -{ +TracerRealTime::TracerRealTime(const std::string& n) : Tracer(n), bufferSize(BUFFER_SIZE_DEFAULT) { dgDEBUGINOUT(15); /* --- Commands --- */ { using namespace dynamicgraph::command; - std::string doc - = docCommandVoid0("Trash the current content of the buffers, without saving it."); - addCommand("empty", - makeCommandVoid0(*this,&TracerRealTime::emptyBuffers,doc )); - - addCommand("getBufferSize", - makeDirectGetter(*this,&bufferSize, - docDirectGetter("bufferSize","int"))); - addCommand("setBufferSize", - makeDirectSetter(*this,&bufferSize, - docDirectSetter("bufferSize","int"))); - } // using namespace command + std::string doc = docCommandVoid0("Trash the current content of the buffers, without saving it."); + addCommand("empty", makeCommandVoid0(*this, &TracerRealTime::emptyBuffers, doc)); + + addCommand("getBufferSize", makeDirectGetter(*this, &bufferSize, docDirectGetter("bufferSize", "int"))); + addCommand("setBufferSize", makeDirectSetter(*this, &bufferSize, docDirectSetter("bufferSize", "int"))); + } // using namespace command dgDEBUGOUT(15); } @@ -130,227 +104,201 @@ TracerRealTime::TracerRealTime( const std::string & n ) /* --------------------------------------------------------------------- */ /* --------------------------------------------------------------------- */ - -void TracerRealTime:: -openFile( const SignalBase<int> & sig, - const std::string& givenname ) -{ +void TracerRealTime::openFile(const SignalBase<int>& sig, const std::string& givenname) { dgDEBUGIN(15); string signame; - if( givenname.length () ) - { signame = givenname; } else { signame = sig.shortName (); } + if (givenname.length()) { + signame = givenname; + } else { + signame = sig.shortName(); + } string filename = rootdir + basename + signame + suffix; - dgDEBUG(5) << "Sig <"<<sig.getName () - << ">: new file "<< filename << endl; - std::ofstream * newfile = new std::ofstream( filename.c_str () ); - dgDEBUG(5) << "Newfile:" << (void*) newfile << endl; - hardFiles.push_back( newfile ); + dgDEBUG(5) << "Sig <" << sig.getName() << ">: new file " << filename << endl; + std::ofstream* newfile = new std::ofstream(filename.c_str()); + dgDEBUG(5) << "Newfile:" << (void*)newfile << endl; + hardFiles.push_back(newfile); dgDEBUG(5) << "Creating Outstringstream" << endl; - //std::stringstream * newbuffer = new std::stringstream (); - OutStringStream * newbuffer = new OutStringStream (); // std::stringstream (); - newbuffer->resize( bufferSize ); + // std::stringstream * newbuffer = new std::stringstream (); + OutStringStream* newbuffer = new OutStringStream(); // std::stringstream (); + newbuffer->resize(bufferSize); newbuffer->givenname = givenname; - files.push_back( newbuffer ); + files.push_back(newbuffer); dgDEBUGOUT(15); } - -void TracerRealTime:: -closeFiles () -{ +void TracerRealTime::closeFiles() { dgDEBUGIN(15); - FileList::iterator iter = files.begin (); - HardFileList::iterator hardIter = hardFiles.begin (); + FileList::iterator iter = files.begin(); + HardFileList::iterator hardIter = hardFiles.begin(); - while( files.end ()!=iter ) - { - dgDEBUG(25) << "Close the files." << endl; + while (files.end() != iter) { + dgDEBUG(25) << "Close the files." << endl; - std::stringstream * file = dynamic_cast< stringstream* >(*iter); - std::ofstream * hardFile = *hardIter; + std::stringstream* file = dynamic_cast<stringstream*>(*iter); + std::ofstream* hardFile = *hardIter; - (*hardFile) <<flush; hardFile->close (); - delete file; - delete hardFile; + (*hardFile) << flush; + hardFile->close(); + delete file; + delete hardFile; - ++iter; ++hardIter; - } + ++iter; + ++hardIter; + } dgDEBUG(25) << "Clear the lists." << endl; - files.clear (); - hardFiles.clear (); + files.clear(); + hardFiles.clear(); dgDEBUGOUT(15); } -void TracerRealTime:: -trace () -{ +void TracerRealTime::trace() { dgDEBUGIN(15); - FileList::iterator iter = files.begin (); - HardFileList::iterator hardIter = hardFiles.begin (); - - while( files.end ()!=iter ) - { - dgDEBUG(35) << "Next" << endl; - std::ostream * os = *iter; - if( NULL==os ) - { DG_THROW ExceptionTraces( ExceptionTraces::NOT_OPEN, - "The buffer is null",""); } - //std::stringstream & file = * dynamic_cast< stringstream* >(os); - OutStringStream * file = dynamic_cast< OutStringStream* >(os); // segfault - if( NULL==file ) - { DG_THROW ExceptionTraces( ExceptionTraces::NOT_OPEN, - "The buffer is not open",""); } - - std::ofstream & hardFile = **hardIter; - if(! hardFile.good () ) - { DG_THROW ExceptionTraces( ExceptionTraces::NOT_OPEN, - "The file is not open",""); } - - if( (hardFile.good ())&&(NULL!=file) ) - { - -// const unsigned int SIZE = 1024*8; -// char buffer[SIZE]; -// streambuf * pbuf = file.rdbuf (); -// pbuf->pubseekpos(0); -// const unsigned int NB_BYTE = pbuf->in_avail (); -// dgDEBUG(35) << "Bytes in buffer: " << NB_BYTE << endl; -// //dgDEBUG(35) << "Copie" <<endl<<file.str ()<< endl; - -// for( unsigned int index=0;index<NB_BYTE;index+=SIZE ) -// { -// pbuf->pubseekpos( index ); -// int nget = pbuf->sgetn( buffer,SIZE ); -// dgDEBUG(35) << "Copie ["<<nget<<"] " <<buffer<<endl; -// hardFile.write( buffer,nget ); -// } - //hardFile << file.str () << flush; - //file.seekp(0); - - file->dump( hardFile ); - file->empty (); - hardFile.flush (); - - //file.str(""); - } - - ++iter; ++hardIter; + FileList::iterator iter = files.begin(); + HardFileList::iterator hardIter = hardFiles.begin(); + + while (files.end() != iter) { + dgDEBUG(35) << "Next" << endl; + std::ostream* os = *iter; + if (NULL == os) { + DG_THROW ExceptionTraces(ExceptionTraces::NOT_OPEN, "The buffer is null", ""); + } + // std::stringstream & file = * dynamic_cast< stringstream* >(os); + OutStringStream* file = dynamic_cast<OutStringStream*>(os); // segfault + if (NULL == file) { + DG_THROW ExceptionTraces(ExceptionTraces::NOT_OPEN, "The buffer is not open", ""); + } + + std::ofstream& hardFile = **hardIter; + if (!hardFile.good()) { + DG_THROW ExceptionTraces(ExceptionTraces::NOT_OPEN, "The file is not open", ""); + } + + if ((hardFile.good()) && (NULL != file)) { + // const unsigned int SIZE = 1024*8; + // char buffer[SIZE]; + // streambuf * pbuf = file.rdbuf (); + // pbuf->pubseekpos(0); + // const unsigned int NB_BYTE = pbuf->in_avail (); + // dgDEBUG(35) << "Bytes in buffer: " << NB_BYTE << endl; + // //dgDEBUG(35) << "Copie" <<endl<<file.str ()<< endl; + + // for( unsigned int index=0;index<NB_BYTE;index+=SIZE ) + // { + // pbuf->pubseekpos( index ); + // int nget = pbuf->sgetn( buffer,SIZE ); + // dgDEBUG(35) << "Copie ["<<nget<<"] " <<buffer<<endl; + // hardFile.write( buffer,nget ); + // } + // hardFile << file.str () << flush; + // file.seekp(0); + + file->dump(hardFile); + file->empty(); + hardFile.flush(); + + // file.str(""); } + ++iter; + ++hardIter; + } + dgDEBUGOUT(15); } -void TracerRealTime:: -emptyBuffers () -{ +void TracerRealTime::emptyBuffers() { dgDEBUGIN(15); - for( FileList::iterator iter = files.begin ();files.end ()!=iter;++iter ) - { - //std::stringstream & file = * dynamic_cast< stringstream* >(*iter); - try { - OutStringStream & file = * dynamic_cast< OutStringStream* >(*iter); - file.empty (); - //file.str(""); - } - catch( ... ) { DG_THROW ExceptionTraces( ExceptionTraces::NOT_OPEN, - "The buffer is not open",""); } + for (FileList::iterator iter = files.begin(); files.end() != iter; ++iter) { + // std::stringstream & file = * dynamic_cast< stringstream* >(*iter); + try { + OutStringStream& file = *dynamic_cast<OutStringStream*>(*iter); + file.empty(); + // file.str(""); + } catch (...) { + DG_THROW ExceptionTraces(ExceptionTraces::NOT_OPEN, "The buffer is not open", ""); } + } dgDEBUGOUT(15); } - // void TracerRealTime:: // emptyBuffer( std::stringstream & file ) // { // streambuf * pbuf = file.rdbuf (); // pbuf->file.rdbuf () ->pubsetbuf( fileBuffer,10 ); - - // } -void TracerRealTime:: -recordSignal( std::ostream& os, - const SignalBase<int>& sig ) -{ +void TracerRealTime::recordSignal(std::ostream& os, const SignalBase<int>& sig) { dgDEBUGIN(15); try { - - OutStringStream & file = dynamic_cast< OutStringStream& >(os); + OutStringStream& file = dynamic_cast<OutStringStream&>(os); file.str(""); - dgDEBUG(45) << "Empty file [" << file.tellp () - << "] <" << file.str ().c_str () <<"> " <<endl; - - Tracer::recordSignal( file,sig ); - file.addData( file.str ().c_str (),file.tellp () ); - dgDEBUG(35) << "Write data [" << file.tellp () - << "] <" << file.str ().c_str () <<"> " <<endl; - - } catch( ExceptionAbstract & exc ) { throw exc; } - catch( ... ) { - DG_THROW ExceptionTraces( ExceptionTraces::NOT_OPEN, - "The buffer is not open",""); - } + dgDEBUG(45) << "Empty file [" << file.tellp() << "] <" << file.str().c_str() << "> " << endl; + Tracer::recordSignal(file, sig); + file.addData(file.str().c_str(), file.tellp()); + dgDEBUG(35) << "Write data [" << file.tellp() << "] <" << file.str().c_str() << "> " << endl; + + } catch (ExceptionAbstract& exc) { + throw exc; + } catch (...) { + DG_THROW ExceptionTraces(ExceptionTraces::NOT_OPEN, "The buffer is not open", ""); + } dgDEBUGOUT(15); - return ; + return; } - - /* --------------------------------------------------------------------- */ /* --------------------------------------------------------------------- */ /* --------------------------------------------------------------------- */ -void TracerRealTime:: -display( std::ostream& os ) const -{ - os << CLASS_NAME << " " << name << " [mode=" << (play?"play":"pause") - << "] : "<< endl - << " - Dep list: "<<endl; - - FileList::const_iterator iterFile = files.begin (); - for( SignalList::const_iterator iter = toTraceSignals.begin (); - toTraceSignals.end ()!=iter;++iter ) - { - dgDEBUG(35) << "Next" << endl; - const OutStringStream * file = dynamic_cast< OutStringStream* >(*iterFile); - os << " -> "<<(*iter)->getName (); - if( file->givenname.length () ) os << " (in " << file->givenname << ")" ; - os << "\t"; - if( file ) - { - const std::streamsize PRECISION = os.precision (); - const std::streamsize SIZE = file->index; - const std::streamsize MSIZE = file->bufferSize; - unsigned int dec=0; std::string unit =""; - if( (SIZE>>30)||(MSIZE>>30) ) { dec = 30; unit="Go"; } - else if( (SIZE>>20)||(MSIZE>>20) ) { dec = 20; unit="Mo"; } - else if( (SIZE>>10)||(MSIZE>>10) ) { dec = 10; unit="Ko"; } - os << "[" << std::setw(1)<<std::setprecision(1) - << (((double)SIZE+0.0)/(1<<dec)) << unit << "/" - << std::setprecision(2)<<(((double)MSIZE+0.0)/(1<<dec)) - << unit << "]\t"; - if( file->full ) os << "(FULL)"; - os.precision(PRECISION); - } - os<<endl; - iterFile++; +void TracerRealTime::display(std::ostream& os) const { + os << CLASS_NAME << " " << name << " [mode=" << (play ? "play" : "pause") << "] : " << endl + << " - Dep list: " << endl; + + FileList::const_iterator iterFile = files.begin(); + for (SignalList::const_iterator iter = toTraceSignals.begin(); toTraceSignals.end() != iter; ++iter) { + dgDEBUG(35) << "Next" << endl; + const OutStringStream* file = dynamic_cast<OutStringStream*>(*iterFile); + os << " -> " << (*iter)->getName(); + if (file->givenname.length()) os << " (in " << file->givenname << ")"; + os << "\t"; + if (file) { + const std::streamsize PRECISION = os.precision(); + const std::streamsize SIZE = file->index; + const std::streamsize MSIZE = file->bufferSize; + unsigned int dec = 0; + std::string unit = ""; + if ((SIZE >> 30) || (MSIZE >> 30)) { + dec = 30; + unit = "Go"; + } else if ((SIZE >> 20) || (MSIZE >> 20)) { + dec = 20; + unit = "Mo"; + } else if ((SIZE >> 10) || (MSIZE >> 10)) { + dec = 10; + unit = "Ko"; + } + os << "[" << std::setw(1) << std::setprecision(1) << (((double)SIZE + 0.0) / (1 << dec)) << unit << "/" + << std::setprecision(2) << (((double)MSIZE + 0.0) / (1 << dec)) << unit << "]\t"; + if (file->full) os << "(FULL)"; + os.precision(PRECISION); } - + os << endl; + iterFile++; + } } - -std::ostream& operator<< ( std::ostream& os,const TracerRealTime& t ) -{ +std::ostream& operator<<(std::ostream& os, const TracerRealTime& t) { t.display(os); return os; } diff --git a/src/traces/tracer.cpp b/src/traces/tracer.cpp index 3d2b97825f5cc9ff7dd0714dcdbe4d5c5eb2e4a2..84deaa91938a2d22f8cb7819b35f9ab5e6afca85 100644 --- a/src/traces/tracer.cpp +++ b/src/traces/tracer.cpp @@ -24,103 +24,83 @@ using namespace std; using namespace dynamicgraph; using namespace dynamicgraph::command; -DYNAMICGRAPH_FACTORY_ENTITY_PLUGIN(Tracer,"Tracer"); +DYNAMICGRAPH_FACTORY_ENTITY_PLUGIN(Tracer, "Tracer"); /* --------------------------------------------------------------------- */ /* --- CLASS ----------------------------------------------------------- */ /* --------------------------------------------------------------------- */ -Tracer::Tracer( const std::string n ) - :Entity(n) - ,toTraceSignals () - ,traceStyle(TRACE_STYLE_DEFAULT) - ,frequency(1) - ,basename () - ,suffix(".dat") - ,rootdir () - ,namesSet( false ) - ,files () - ,names () - ,play(false) - ,timeStart(0) - ,triger( boost::bind(&Tracer::recordTrigger,this,_1,_2), - sotNOSIGNAL, - "Tracer("+n+")::triger" ) -{ - signalRegistration( triger ); - +Tracer::Tracer(const std::string n) + : Entity(n), + toTraceSignals(), + traceStyle(TRACE_STYLE_DEFAULT), + frequency(1), + basename(), + suffix(".dat"), + rootdir(), + namesSet(false), + files(), + names(), + play(false), + timeStart(0), + triger(boost::bind(&Tracer::recordTrigger, this, _1, _2), sotNOSIGNAL, "Tracer(" + n + ")::triger") { + signalRegistration(triger); /* --- Commands --- */ { using namespace dynamicgraph::command; std::string doc; - doc = docCommandVoid2("Add a new signal to trace.", - "string (signal name)","string (filename, empty for default"); - addCommand("add", - makeCommandVoid2(*this,&Tracer::addSignalToTraceByName,doc )); + doc = docCommandVoid2("Add a new signal to trace.", "string (signal name)", "string (filename, empty for default"); + addCommand("add", makeCommandVoid2(*this, &Tracer::addSignalToTraceByName, doc)); doc = docCommandVoid0("Remove all signals. If necessary, close open files."); - addCommand("clear", - makeCommandVoid0(*this,&Tracer::clearSignalToTrace,doc )); + addCommand("clear", makeCommandVoid0(*this, &Tracer::clearSignalToTrace, doc)); - doc = docCommandVoid3("Gives the args for file opening, and " - "if signals have been set, open the corresponding files.", - "string (dirname)","string (prefix)","string (suffix)"); - addCommand("open", - makeCommandVoid3(*this,&Tracer::openFiles,doc )); + doc = docCommandVoid3( + "Gives the args for file opening, and " + "if signals have been set, open the corresponding files.", + "string (dirname)", "string (prefix)", "string (suffix)"); + addCommand("open", makeCommandVoid3(*this, &Tracer::openFiles, doc)); doc = docCommandVoid0("Close all the open files."); - addCommand("close", - makeCommandVoid0(*this,&Tracer::closeFiles,doc )); + addCommand("close", makeCommandVoid0(*this, &Tracer::closeFiles, doc)); - doc = docCommandVoid0("If necessary, dump " - "(can be done automatically for some traces type)."); - addCommand("dump", - makeCommandVoid0(*this,&Tracer::trace,doc )); + doc = docCommandVoid0( + "If necessary, dump " + "(can be done automatically for some traces type)."); + addCommand("dump", makeCommandVoid0(*this, &Tracer::trace, doc)); doc = docCommandVoid0("Start the tracing process."); - addCommand("start", - makeCommandVoid0(*this,&Tracer::start,doc )); + addCommand("start", makeCommandVoid0(*this, &Tracer::start, doc)); doc = docCommandVoid0("Stop temporarily the tracing process."); - addCommand("stop", - makeCommandVoid0(*this,&Tracer::stop,doc )); - - addCommand("getTimeStart", - makeDirectGetter(*this,&timeStart, - docDirectGetter("timeStart","int"))); - addCommand("setTimeStart", - makeDirectSetter(*this,&timeStart, - docDirectSetter("timeStart","int"))); - } // using namespace command + addCommand("stop", makeCommandVoid0(*this, &Tracer::stop, doc)); + + addCommand("getTimeStart", makeDirectGetter(*this, &timeStart, docDirectGetter("timeStart", "int"))); + addCommand("setTimeStart", makeDirectSetter(*this, &timeStart, docDirectSetter("timeStart", "int"))); + } // using namespace command } /* --------------------------------------------------------------------- */ /* --------------------------------------------------------------------- */ /* --------------------------------------------------------------------- */ - -void Tracer:: -addSignalToTrace( const SignalBase<int>& sig, - const string& filename ) -{ +void Tracer::addSignalToTrace(const SignalBase<int>& sig, const string& filename) { dgDEBUGIN(15); - toTraceSignals.push_back( &sig ); dgDEBUGF(15,"%p",&sig); - names.push_back( filename ); - if( namesSet ) openFile( sig,filename ); - triger.addDependency( sig ); + toTraceSignals.push_back(&sig); + dgDEBUGF(15, "%p", &sig); + names.push_back(filename); + if (namesSet) openFile(sig, filename); + triger.addDependency(sig); dgDEBUGOUT(15); } -void Tracer:: -addSignalToTraceByName( const string& signame, - const string& filename ) -{ +void Tracer::addSignalToTraceByName(const string& signame, const string& filename) { dgDEBUGIN(15); - istringstream iss( signame ); - SignalBase<int> &sig = PoolStorage::getInstance()->getSignal(iss); - addSignalToTrace(sig,filename); + istringstream iss(signame); + SignalBase<int>& sig = PoolStorage::getInstance()->getSignal(iss); + addSignalToTrace(sig, filename); dgDEBUGOUT(15); } @@ -128,12 +108,10 @@ addSignalToTraceByName( const string& signame, * does not modify the file list (it does not close * the files in particular. */ -void Tracer:: -clearSignalToTrace () -{ - closeFiles (); - toTraceSignals.clear (); - triger.clearDependencies (); +void Tracer::clearSignalToTrace() { + closeFiles(); + toTraceSignals.clear(); + triger.clearDependencies(); } // void Tracer:: @@ -142,63 +120,55 @@ clearSignalToTrace () // triger.parasite(sig); // } -void Tracer:: -openFiles( const std::string& rootdir_, const std::string& basename_, - const std::string& suffix_ ) -{ +void Tracer::openFiles(const std::string& rootdir_, const std::string& basename_, const std::string& suffix_) { dgDEBUGIN(15); - std::basic_string<char>::size_type n = rootdir_.length (); + std::basic_string<char>::size_type n = rootdir_.length(); rootdir = rootdir_; - if( (0<n)&('/'!=rootdir[n-1]) ) rootdir+='/'; + if ((0 < n) & ('/' != rootdir[n - 1])) rootdir += '/'; - basename=basename_; - suffix=suffix_; + basename = basename_; + suffix = suffix_; - if( files.size () ) closeFiles (); + if (files.size()) closeFiles(); - SignalList::const_iterator iter = toTraceSignals.begin (); - NameList::const_iterator iterName = names.begin (); - while( toTraceSignals.end ()!=iter ) - { - dgDEBUG(15) << "Open <" << (*iter)->getName () - << "> in <" << *iterName << ">." << std::endl; - openFile( **iter,*iterName ); - ++iter; ++iterName; - } + SignalList::const_iterator iter = toTraceSignals.begin(); + NameList::const_iterator iterName = names.begin(); + while (toTraceSignals.end() != iter) { + dgDEBUG(15) << "Open <" << (*iter)->getName() << "> in <" << *iterName << ">." << std::endl; + openFile(**iter, *iterName); + ++iter; + ++iterName; + } namesSet = true; dgDEBUGOUT(15); } -void Tracer:: -openFile( const SignalBase<int> & sig, - const string& givenname ) -{ +void Tracer::openFile(const SignalBase<int>& sig, const string& givenname) { dgDEBUGIN(15); string signame; - if( givenname.length () ) - { signame = givenname; } else { signame = sig.shortName (); } + if (givenname.length()) { + signame = givenname; + } else { + signame = sig.shortName(); + } string filename = rootdir + basename + signame + suffix; - dgDEBUG(5) << "Sig <"<< sig.getName () << ">: new file "<< filename << endl; - std::ofstream * newfile = new std::ofstream( filename.c_str () ); - files.push_back( newfile ); + dgDEBUG(5) << "Sig <" << sig.getName() << ">: new file " << filename << endl; + std::ofstream* newfile = new std::ofstream(filename.c_str()); + files.push_back(newfile); dgDEBUGOUT(15); } - -void Tracer:: -closeFiles () -{ +void Tracer::closeFiles() { dgDEBUGIN(15); - for( FileList::iterator iter = files.begin ();files.end ()!=iter;++iter ) - { - std::ostream * filePtr = *iter; - delete filePtr; - } - files.clear (); + for (FileList::iterator iter = files.begin(); files.end() != iter; ++iter) { + std::ostream* filePtr = *iter; + delete filePtr; + } + files.clear(); dgDEBUGOUT(15); } @@ -207,85 +177,71 @@ closeFiles () /* --------------------------------------------------------------------- */ /* --------------------------------------------------------------------- */ -void Tracer:: -record () -{ - if(! play) { dgDEBUGINOUT(15); return;} +void Tracer::record() { + if (!play) { + dgDEBUGINOUT(15); + return; + } dgDEBUGIN(15); - if( files.size ()!=toTraceSignals.size () ) - { DG_THROW ExceptionTraces( ExceptionTraces::NOT_OPEN, - "No files open for tracing"," (file=%d != %d=sig).", - files.size (),toTraceSignals.size ()); } + if (files.size() != toTraceSignals.size()) { + DG_THROW ExceptionTraces(ExceptionTraces::NOT_OPEN, "No files open for tracing", " (file=%d != %d=sig).", + files.size(), toTraceSignals.size()); + } - FileList::iterator iterFile = files.begin (); - SignalList::iterator iterSig = toTraceSignals.begin (); + FileList::iterator iterFile = files.begin(); + SignalList::iterator iterSig = toTraceSignals.begin(); - while( toTraceSignals.end ()!=iterSig ) - { - dgDEBUG(45) << "Try..." <<endl; - recordSignal( **iterFile,**iterSig ); - ++iterSig; ++iterFile; - } + while (toTraceSignals.end() != iterSig) { + dgDEBUG(45) << "Try..." << endl; + recordSignal(**iterFile, **iterSig); + ++iterSig; + ++iterFile; + } dgDEBUGOUT(15); } -void Tracer:: -recordSignal( std::ostream& os, - const SignalBase<int>& sig ) -{ +void Tracer::recordSignal(std::ostream& os, const SignalBase<int>& sig) { dgDEBUGIN(15); try { - if( sig.getTime ()>timeStart ) - { - os<< sig.getTime () << "\t"; - sig.trace(os); os<<endl; - } + if (sig.getTime() > timeStart) { + os << sig.getTime() << "\t"; + sig.trace(os); + os << endl; + } + } catch (ExceptionAbstract& exc) { + os << exc << std::endl; + } catch (...) { + os << "Unknown error occurred while reading signal." << std::endl; } - catch( ExceptionAbstract& exc ) { os << exc << std::endl; } - catch( ... ) { os << "Unknown error occurred while reading signal." << std::endl; } - - dgDEBUGOUT(15); + dgDEBUGOUT(15); } - -int& Tracer:: -recordTrigger( int& dummy, const int& time ) -{ - dgDEBUGIN(15) << " time="<<time <<endl; - record (); +int& Tracer::recordTrigger(int& dummy, const int& time) { + dgDEBUGIN(15) << " time=" << time << endl; + record(); dgDEBUGOUT(15); return dummy; } - -void Tracer:: -trace () -{ -} +void Tracer::trace() {} /* --------------------------------------------------------------------- */ /* --------------------------------------------------------------------- */ /* --------------------------------------------------------------------- */ - -void Tracer:: -display( std::ostream& os ) const -{ - os << CLASS_NAME << " " << name << " [mode=" << (play?"play":"pause") - << "] : "<< endl - << " - Dep list: "<<endl; - for( SignalList::const_iterator iter = toTraceSignals.begin (); - toTraceSignals.end ()!=iter;++iter ) - { os << " -> "<<(*iter)->getName ()<<endl; } +void Tracer::display(std::ostream& os) const { + os << CLASS_NAME << " " << name << " [mode=" << (play ? "play" : "pause") << "] : " << endl + << " - Dep list: " << endl; + for (SignalList::const_iterator iter = toTraceSignals.begin(); toTraceSignals.end() != iter; ++iter) { + os << " -> " << (*iter)->getName() << endl; + } } - -std::ostream& operator<< ( std::ostream& os,const Tracer& t ) -{ +std::ostream& operator<<(std::ostream& os, const Tracer& t) { t.display(os); return os; } diff --git a/tests/command-test.cpp b/tests/command-test.cpp index 3c04780cad31b09ecd8dce2966b1fe9c6c59015b..1d224fa5d49b3c26fb97dfda65744b0e5e06153f 100644 --- a/tests/command-test.cpp +++ b/tests/command-test.cpp @@ -17,7 +17,7 @@ #include <dynamic-graph/real-time-logger.h> #include <dynamic-graph/logger.h> -#define BOOST_TEST_MODULE debug-logger +#define BOOST_TEST_MODULE debug - logger #include <boost/test/unit_test.hpp> #include <boost/test/output_test_stream.hpp> @@ -26,141 +26,84 @@ using boost::test_tools::output_test_stream; using namespace dynamicgraph::command; -namespace dynamicgraph -{ - class CustomEntity : public Entity - { - public: - static const std::string CLASS_NAME; - bool test_zero_arg_; - bool test_one_arg_; - bool test_two_args_; - bool test_three_args_; - bool test_four_args_; - - virtual const std::string& getClassName () const - { - return CLASS_NAME; - } - CustomEntity (const std::string n) - : Entity (n) - { - test_zero_arg_ = false; - test_one_arg_ = false; - test_two_args_ = false; - test_three_args_ = false; - test_four_args_ = false; - - addCommand("0_arg", - makeCommandVoid0(*this, &CustomEntity::zero_arg, - docCommandVoid0("zero arg"))); - - addCommand("1_arg", - makeCommandVoid1(*this, &CustomEntity::one_arg, - docCommandVoid1("one arg", - "int"))); - - addCommand("2_args", - makeCommandVoid2(*this, &CustomEntity::two_args, - docCommandVoid2("two args", - "int", - "int"))); - - addCommand("3_args", - makeCommandVoid3(*this, &CustomEntity::three_args, - docCommandVoid3("three args", - "int","int","int"))); - - addCommand("4_args", - makeCommandVoid4(*this, &CustomEntity::four_args, - docCommandVoid4("four args", - "int", - "int", - "int", - "int"))); - - } - - ~CustomEntity() - { - } - - void zero_arg() - { - test_zero_arg_ = true; - } - - void one_arg(const int & ) - { - test_one_arg_ = true; - } - - void two_args(const int & , - const int & ) - { - test_two_args_ = true; - } - - void three_args(const int & , - const int & , - const int & ) - { - test_three_args_ = true; - } - - void four_args(const int & , - const int & , - const int & , - const int & ) - { - test_four_args_ = true; - } - - }; - DYNAMICGRAPH_FACTORY_ENTITY_PLUGIN (CustomEntity,"CustomEntity"); -} +namespace dynamicgraph { +class CustomEntity : public Entity { + public: + static const std::string CLASS_NAME; + bool test_zero_arg_; + bool test_one_arg_; + bool test_two_args_; + bool test_three_args_; + bool test_four_args_; + + virtual const std::string &getClassName() const { return CLASS_NAME; } + CustomEntity(const std::string n) : Entity(n) { + test_zero_arg_ = false; + test_one_arg_ = false; + test_two_args_ = false; + test_three_args_ = false; + test_four_args_ = false; + + addCommand("0_arg", makeCommandVoid0(*this, &CustomEntity::zero_arg, docCommandVoid0("zero arg"))); + + addCommand("1_arg", makeCommandVoid1(*this, &CustomEntity::one_arg, docCommandVoid1("one arg", "int"))); + + addCommand("2_args", makeCommandVoid2(*this, &CustomEntity::two_args, docCommandVoid2("two args", "int", "int"))); + + addCommand("3_args", + makeCommandVoid3(*this, &CustomEntity::three_args, docCommandVoid3("three args", "int", "int", "int"))); + + addCommand("4_args", makeCommandVoid4(*this, &CustomEntity::four_args, + docCommandVoid4("four args", "int", "int", "int", "int"))); + } + + ~CustomEntity() {} + void zero_arg() { test_zero_arg_ = true; } -BOOST_AUTO_TEST_CASE(command_test) -{ - dynamicgraph::CustomEntity& entity = - *(dynamic_cast<dynamicgraph::CustomEntity *> - (dynamicgraph::FactoryStorage::getInstance()->newEntity("CustomEntity", - "my-entity"))); + void one_arg(const int &) { test_one_arg_ = true; } - std::map<const std::string,Command *> aCommandMap = - entity.getNewStyleCommandMap(); + void two_args(const int &, const int &) { test_two_args_ = true; } + + void three_args(const int &, const int &, const int &) { test_three_args_ = true; } + + void four_args(const int &, const int &, const int &, const int &) { test_four_args_ = true; } +}; +DYNAMICGRAPH_FACTORY_ENTITY_PLUGIN(CustomEntity, "CustomEntity"); +} // namespace dynamicgraph + +BOOST_AUTO_TEST_CASE(command_test) { + dynamicgraph::CustomEntity &entity = *(dynamic_cast<dynamicgraph::CustomEntity *>( + dynamicgraph::FactoryStorage::getInstance()->newEntity("CustomEntity", "my-entity"))); + + std::map<const std::string, Command *> aCommandMap = entity.getNewStyleCommandMap(); + + std::map<const std::string, Command *>::iterator it_map; - std::map<const std::string,Command *>::iterator it_map; - it_map = aCommandMap.find("0_arg"); - if (it_map==aCommandMap.end()) - BOOST_CHECK(false); + if (it_map == aCommandMap.end()) BOOST_CHECK(false); it_map->second->execute(); BOOST_CHECK(entity.test_zero_arg_); - int first_arg=1; + int first_arg = 1; Value aValue(first_arg); std::vector<std::string> vec_fname(4); - vec_fname[0]="1_arg"; - vec_fname[1]="2_args"; - vec_fname[2]="3_args"; - vec_fname[3]="4_args"; + vec_fname[0] = "1_arg"; + vec_fname[1] = "2_args"; + vec_fname[2] = "3_args"; + vec_fname[3] = "4_args"; std::vector<Value> values; - - for (unsigned int i=0;i<4;i++) - { - it_map = aCommandMap.find(vec_fname[i]); - if (it_map==aCommandMap.end()) - BOOST_CHECK(false); - values.push_back(aValue); - it_map->second->setParameterValues(values); - it_map->second->execute(); - } - - BOOST_CHECK(entity.test_one_arg_); + + for (unsigned int i = 0; i < 4; i++) { + it_map = aCommandMap.find(vec_fname[i]); + if (it_map == aCommandMap.end()) BOOST_CHECK(false); + values.push_back(aValue); + it_map->second->setParameterValues(values); + it_map->second->execute(); + } + + BOOST_CHECK(entity.test_one_arg_); BOOST_CHECK(entity.test_two_args_); BOOST_CHECK(entity.test_three_args_); BOOST_CHECK(entity.test_four_args_); - } diff --git a/tests/custom-entity.cpp b/tests/custom-entity.cpp index f2c2066a2817e2e6ae94622d3aed552ff3e88773..6cb705a7d51ede71c594db6dcb7f49a2f2b74887 100644 --- a/tests/custom-entity.cpp +++ b/tests/custom-entity.cpp @@ -14,59 +14,40 @@ using boost::test_tools::output_test_stream; -struct CustomEntity : public dynamicgraph::Entity -{ +struct CustomEntity : public dynamicgraph::Entity { static const std::string CLASS_NAME; - virtual const std::string& getClassName () const - { - return CLASS_NAME; - } + virtual const std::string& getClassName() const { return CLASS_NAME; } - CustomEntity (const std::string n) - : Entity (n) - { - } + CustomEntity(const std::string n) : Entity(n) {} - virtual ~CustomEntity() - { - } - - void display (std::ostream& os) const - { - os << "custom entity"; - } + virtual ~CustomEntity() {} + void display(std::ostream& os) const { os << "custom entity"; } }; -DYNAMICGRAPH_FACTORY_ENTITY_PLUGIN (CustomEntity,"CustomEntity"); - +DYNAMICGRAPH_FACTORY_ENTITY_PLUGIN(CustomEntity, "CustomEntity"); -BOOST_AUTO_TEST_CASE (constructor) -{ - BOOST_CHECK_EQUAL (CustomEntity::CLASS_NAME, "CustomEntity"); +BOOST_AUTO_TEST_CASE(constructor) { + BOOST_CHECK_EQUAL(CustomEntity::CLASS_NAME, "CustomEntity"); - dynamicgraph::Entity* entity = - dynamicgraph::FactoryStorage::getInstance()-> - newEntity("CustomEntity", "my-entity"); - BOOST_CHECK_EQUAL (entity->getName (), "my-entity"); - BOOST_CHECK_EQUAL (entity->Entity::getClassName (), "Entity"); - BOOST_CHECK_EQUAL (entity->getClassName (), CustomEntity::CLASS_NAME); + dynamicgraph::Entity* entity = dynamicgraph::FactoryStorage::getInstance()->newEntity("CustomEntity", "my-entity"); + BOOST_CHECK_EQUAL(entity->getName(), "my-entity"); + BOOST_CHECK_EQUAL(entity->Entity::getClassName(), "Entity"); + BOOST_CHECK_EQUAL(entity->getClassName(), CustomEntity::CLASS_NAME); - //CustomEntity entity2 (""); + // CustomEntity entity2 (""); // Deregister entities before destroying them dynamicgraph::PoolStorage::destroy(); } -BOOST_AUTO_TEST_CASE (display) -{ - dynamicgraph::Entity* entity = dynamicgraph::FactoryStorage::getInstance()-> - newEntity("CustomEntity", "my-entity"); +BOOST_AUTO_TEST_CASE(display) { + dynamicgraph::Entity* entity = dynamicgraph::FactoryStorage::getInstance()->newEntity("CustomEntity", "my-entity"); output_test_stream output; entity->display(output); - BOOST_CHECK (output.is_equal ("custom entity")); + BOOST_CHECK(output.is_equal("custom entity")); // Deregister entities before destroying them dynamicgraph::PoolStorage::destroy(); } diff --git a/tests/debug-logger-winit.cpp b/tests/debug-logger-winit.cpp index d043b5396972fe10821726194280d30130d21913..156a5c9b1efe783a327ed358b34ce8e2eecd65b1 100644 --- a/tests/debug-logger-winit.cpp +++ b/tests/debug-logger-winit.cpp @@ -17,8 +17,7 @@ #include <dynamic-graph/real-time-logger.h> #include <dynamic-graph/logger.h> - -#define BOOST_TEST_MODULE debug-logger +#define BOOST_TEST_MODULE debug - logger #include <boost/test/unit_test.hpp> #include <boost/test/output_test_stream.hpp> @@ -28,65 +27,50 @@ using boost::test_tools::output_test_stream; - -namespace dynamicgraph -{ - class CustomEntity : public Entity - { - public: - static const std::string CLASS_NAME; - virtual const std::string& getClassName () const - { - return CLASS_NAME; - } - CustomEntity (const std::string n) - : Entity (n) - { - logger_.setTimeSample(0.001); - logger_.setStreamPrintPeriod(0.005); - logger_.setVerbosity(VERBOSITY_ALL); - LoggerVerbosity alv = logger_.getVerbosity(); - BOOST_CHECK(alv==VERBOSITY_ALL); - } - - ~CustomEntity() - { - } - void testDebugTrace() - { - sendMsg("This is a message of level MSG_TYPE_DEBUG",MSG_TYPE_DEBUG); - sendMsg("This is a message of level MSG_TYPE_INFO",MSG_TYPE_INFO); - sendMsg("This is a message of level MSG_TYPE_WARNING",MSG_TYPE_WARNING); - sendMsg("This is a message of level MSG_TYPE_ERROR",MSG_TYPE_ERROR); - sendMsg("This is a message of level MSG_TYPE_DEBUG_STREAM",MSG_TYPE_DEBUG_STREAM); - sendMsg("This is a message of level MSG_TYPE_INFO_STREAM",MSG_TYPE_INFO_STREAM); - sendMsg("This is a message of level MSG_TYPE_WARNING_STREAM",MSG_TYPE_WARNING_STREAM); - sendMsg("This is a message of level MSG_TYPE_ERROR_STREAM",MSG_TYPE_ERROR_STREAM); - - logger_.countdown(); - - } - }; - DYNAMICGRAPH_FACTORY_ENTITY_PLUGIN (CustomEntity,"CustomEntity"); -} - -BOOST_AUTO_TEST_CASE(debug_logger_wrong_initialization) -{ +namespace dynamicgraph { +class CustomEntity : public Entity { + public: + static const std::string CLASS_NAME; + virtual const std::string& getClassName() const { return CLASS_NAME; } + CustomEntity(const std::string n) : Entity(n) { + logger_.setTimeSample(0.001); + logger_.setStreamPrintPeriod(0.005); + logger_.setVerbosity(VERBOSITY_ALL); + LoggerVerbosity alv = logger_.getVerbosity(); + BOOST_CHECK(alv == VERBOSITY_ALL); + } + + ~CustomEntity() {} + void testDebugTrace() { + sendMsg("This is a message of level MSG_TYPE_DEBUG", MSG_TYPE_DEBUG); + sendMsg("This is a message of level MSG_TYPE_INFO", MSG_TYPE_INFO); + sendMsg("This is a message of level MSG_TYPE_WARNING", MSG_TYPE_WARNING); + sendMsg("This is a message of level MSG_TYPE_ERROR", MSG_TYPE_ERROR); + sendMsg("This is a message of level MSG_TYPE_DEBUG_STREAM", MSG_TYPE_DEBUG_STREAM); + sendMsg("This is a message of level MSG_TYPE_INFO_STREAM", MSG_TYPE_INFO_STREAM); + sendMsg("This is a message of level MSG_TYPE_WARNING_STREAM", MSG_TYPE_WARNING_STREAM); + sendMsg("This is a message of level MSG_TYPE_ERROR_STREAM", MSG_TYPE_ERROR_STREAM); + + logger_.countdown(); + } +}; +DYNAMICGRAPH_FACTORY_ENTITY_PLUGIN(CustomEntity, "CustomEntity"); +} // namespace dynamicgraph + +BOOST_AUTO_TEST_CASE(debug_logger_wrong_initialization) { std::ofstream of; dynamicgraph::RealTimeLogger::instance(); - //of.open("/tmp/dg-LOGS.txt",std::ofstream::out|std::ofstream::app); + // of.open("/tmp/dg-LOGS.txt",std::ofstream::out|std::ofstream::app); // dgADD_OSTREAM_TO_RTLOG (of); - BOOST_CHECK_EQUAL (dynamicgraph::CustomEntity::CLASS_NAME, "CustomEntity"); + BOOST_CHECK_EQUAL(dynamicgraph::CustomEntity::CLASS_NAME, "CustomEntity"); - dynamicgraph::CustomEntity& entity = *(dynamic_cast<dynamicgraph::CustomEntity *>( - dynamicgraph::FactoryStorage::getInstance()->newEntity("CustomEntity", - "my-entity-2"))); + dynamicgraph::CustomEntity& entity = *(dynamic_cast<dynamicgraph::CustomEntity*>( + dynamicgraph::FactoryStorage::getInstance()->newEntity("CustomEntity", "my-entity-2"))); - for(unsigned int i=0;i<1000;i++) - { - entity.testDebugTrace(); - } + for (unsigned int i = 0; i < 1000; i++) { + entity.testDebugTrace(); + } dynamicgraph::RealTimeLogger::destroy(); } diff --git a/tests/debug-logger.cpp b/tests/debug-logger.cpp index 7499e0b100922d97b517b691f294cab3a16857c7..1b2eee44ed48e5b1ee3fd3c3ac398570b6ca0b08 100644 --- a/tests/debug-logger.cpp +++ b/tests/debug-logger.cpp @@ -16,77 +16,62 @@ #include <dynamic-graph/real-time-logger.h> #include <dynamic-graph/logger.h> -#define BOOST_TEST_MODULE debug-logger +#define BOOST_TEST_MODULE debug - logger #include <boost/test/unit_test.hpp> #include <boost/test/output_test_stream.hpp> using boost::test_tools::output_test_stream; +namespace dynamicgraph { +class CustomEntity : public Entity { + public: + static const std::string CLASS_NAME; + virtual const std::string& getClassName() const { return CLASS_NAME; } + CustomEntity(const std::string n) : Entity(n) { + logger_.setTimeSample(0.001); + logger_.setStreamPrintPeriod(0.005); + logger_.setVerbosity(VERBOSITY_ALL); + LoggerVerbosity alv = logger_.getVerbosity(); + BOOST_CHECK(alv == VERBOSITY_ALL); + } -namespace dynamicgraph -{ - class CustomEntity : public Entity - { - public: - static const std::string CLASS_NAME; - virtual const std::string& getClassName () const - { - return CLASS_NAME; - } - CustomEntity (const std::string n) - : Entity (n) - { - logger_.setTimeSample(0.001); - logger_.setStreamPrintPeriod(0.005); - logger_.setVerbosity(VERBOSITY_ALL); - LoggerVerbosity alv = logger_.getVerbosity(); - BOOST_CHECK(alv==VERBOSITY_ALL); - } + ~CustomEntity() {} + void testDebugTrace() { + sendMsg("This is a message of level MSG_TYPE_DEBUG", MSG_TYPE_DEBUG); + sendMsg("This is a message of level MSG_TYPE_INFO", MSG_TYPE_INFO); + sendMsg("This is a message of level MSG_TYPE_WARNING", MSG_TYPE_WARNING); + sendMsg("This is a message of level MSG_TYPE_ERROR", MSG_TYPE_ERROR); + sendMsg("This is a message of level MSG_TYPE_DEBUG_STREAM", MSG_TYPE_DEBUG_STREAM); + sendMsg("This is a message of level MSG_TYPE_INFO_STREAM", MSG_TYPE_INFO_STREAM); + sendMsg("This is a message of level MSG_TYPE_WARNING_STREAM", MSG_TYPE_WARNING_STREAM); + sendMsg("This is a message of level MSG_TYPE_ERROR_STREAM", MSG_TYPE_ERROR_STREAM); - ~CustomEntity() - { - } - void testDebugTrace() - { - sendMsg("This is a message of level MSG_TYPE_DEBUG",MSG_TYPE_DEBUG); - sendMsg("This is a message of level MSG_TYPE_INFO",MSG_TYPE_INFO); - sendMsg("This is a message of level MSG_TYPE_WARNING",MSG_TYPE_WARNING); - sendMsg("This is a message of level MSG_TYPE_ERROR",MSG_TYPE_ERROR); - sendMsg("This is a message of level MSG_TYPE_DEBUG_STREAM",MSG_TYPE_DEBUG_STREAM); - sendMsg("This is a message of level MSG_TYPE_INFO_STREAM",MSG_TYPE_INFO_STREAM); - sendMsg("This is a message of level MSG_TYPE_WARNING_STREAM",MSG_TYPE_WARNING_STREAM); - sendMsg("This is a message of level MSG_TYPE_ERROR_STREAM",MSG_TYPE_ERROR_STREAM); + logger_.countdown(); + } +}; +DYNAMICGRAPH_FACTORY_ENTITY_PLUGIN(CustomEntity, "CustomEntity"); +} // namespace dynamicgraph - logger_.countdown(); - - } - }; - DYNAMICGRAPH_FACTORY_ENTITY_PLUGIN (CustomEntity,"CustomEntity"); -} - -BOOST_AUTO_TEST_CASE(debug_logger) -{ +BOOST_AUTO_TEST_CASE(debug_logger) { std::ofstream of; dynamicgraph::RealTimeLogger::instance(); - of.open("/tmp/dg-LOGS.txt",std::ofstream::out|std::ofstream::app); - dgADD_OSTREAM_TO_RTLOG (of); + of.open("/tmp/dg-LOGS.txt", std::ofstream::out | std::ofstream::app); + dgADD_OSTREAM_TO_RTLOG(of); - BOOST_CHECK_EQUAL (dynamicgraph::CustomEntity::CLASS_NAME, "CustomEntity"); + BOOST_CHECK_EQUAL(dynamicgraph::CustomEntity::CLASS_NAME, "CustomEntity"); - dynamicgraph::CustomEntity& entity = *(dynamic_cast<dynamicgraph::CustomEntity *>( - dynamicgraph::FactoryStorage::getInstance()->newEntity("CustomEntity", - "my-entity"))); + dynamicgraph::CustomEntity& entity = *(dynamic_cast<dynamicgraph::CustomEntity*>( + dynamicgraph::FactoryStorage::getInstance()->newEntity("CustomEntity", "my-entity"))); entity.setTimeSample(0.002); - BOOST_CHECK_EQUAL(entity.getTimeSample(),0.002); + BOOST_CHECK_EQUAL(entity.getTimeSample(), 0.002); entity.setStreamPrintPeriod(0.004); - BOOST_CHECK_EQUAL(entity.getStreamPrintPeriod(),0.004); + BOOST_CHECK_EQUAL(entity.getStreamPrintPeriod(), 0.004); - for(unsigned int i=0;i<10000;i++) - { - entity.testDebugTrace(); - } + for (unsigned int i = 0; i < 10000; i++) { + entity.testDebugTrace(); + } dynamicgraph::RealTimeLogger::destroy(); } diff --git a/tests/debug-trace.cpp b/tests/debug-trace.cpp index a3907849801bd466f5beab6aed3338b61b9dd993..d7e118968dc8517d801cd30bf9611e0ec09b2b34 100644 --- a/tests/debug-trace.cpp +++ b/tests/debug-trace.cpp @@ -14,94 +14,75 @@ #define VP_DEBUG_MODE 50 #define VP_TEMPLATE_DEBUG_MODE 50 - #include <dynamic-graph/debug.h> -#define BOOST_TEST_MODULE debug-trace +#define BOOST_TEST_MODULE debug - trace #include <boost/test/unit_test.hpp> #include <boost/test/output_test_stream.hpp> using boost::test_tools::output_test_stream; - -namespace dynamicgraph -{ - class CustomEntity : public Entity - { - public: - static const std::string CLASS_NAME; - virtual const std::string& getClassName () const - { - return CLASS_NAME; - } - CustomEntity (const std::string n) - : Entity (n) - { - dynamicgraph::dgDEBUGFLOW.openFile("/tmp/dynamic-graph-traces.txt"); - } - ~CustomEntity() - { - dynamicgraph::dgDEBUGFLOW.closeFile("/tmp/dynamic-graph-traces.txt"); - } - void testDebugTrace() - { - /// Test debugging information when entering the code. - dgDEBUGIN(5); - - /// Intermediate test. - dgDEBUGINOUT(5); - - dgDEBUG(5) << "Here is a test" << std::endl; - - /// Test debugging information when going out of the code. - dgDEBUGOUT(5); - } - }; - DYNAMICGRAPH_FACTORY_ENTITY_PLUGIN (CustomEntity,"CustomEntity"); -} - -BOOST_AUTO_TEST_CASE(testDebugTrace) -{ - - - BOOST_CHECK_EQUAL (dynamicgraph::CustomEntity::CLASS_NAME, "CustomEntity"); - - dynamicgraph::CustomEntity& entity = *(dynamic_cast<dynamicgraph::CustomEntity *>( - dynamicgraph::FactoryStorage::getInstance()->newEntity("CustomEntity", - "my-entity"))); +namespace dynamicgraph { +class CustomEntity : public Entity { + public: + static const std::string CLASS_NAME; + virtual const std::string& getClassName() const { return CLASS_NAME; } + CustomEntity(const std::string n) : Entity(n) { + dynamicgraph::dgDEBUGFLOW.openFile("/tmp/dynamic-graph-traces.txt"); + } + ~CustomEntity() { dynamicgraph::dgDEBUGFLOW.closeFile("/tmp/dynamic-graph-traces.txt"); } + void testDebugTrace() { + /// Test debugging information when entering the code. + dgDEBUGIN(5); + + /// Intermediate test. + dgDEBUGINOUT(5); + + dgDEBUG(5) << "Here is a test" << std::endl; + + /// Test debugging information when going out of the code. + dgDEBUGOUT(5); + } +}; +DYNAMICGRAPH_FACTORY_ENTITY_PLUGIN(CustomEntity, "CustomEntity"); +} // namespace dynamicgraph + +BOOST_AUTO_TEST_CASE(testDebugTrace) { + BOOST_CHECK_EQUAL(dynamicgraph::CustomEntity::CLASS_NAME, "CustomEntity"); + + dynamicgraph::CustomEntity& entity = *(dynamic_cast<dynamicgraph::CustomEntity*>( + dynamicgraph::FactoryStorage::getInstance()->newEntity("CustomEntity", "my-entity"))); entity.testDebugTrace(); /// Copy the debug file into the oss_debug_file output_test_stream output; std::fstream the_debug_file; - the_debug_file.open(dynamicgraph::DebugTrace::DEBUG_FILENAME_DEFAULT, - std::ios::in ); + the_debug_file.open(dynamicgraph::DebugTrace::DEBUG_FILENAME_DEFAULT, std::ios::in); // Extract the filename and this source file from the output std::string astr; std::ostringstream oss_debug_file; - while(std::getline(the_debug_file,astr)) - { - std::size_t found=astr.find(":"); - std::string asubstr = astr.substr(found+1,astr.length()); - found = asubstr.find(":"); - std::string asubstr2 = asubstr.substr(found+1,astr.length()); - oss_debug_file << asubstr2; - } + while (std::getline(the_debug_file, astr)) { + std::size_t found = astr.find(":"); + std::string asubstr = astr.substr(found + 1, astr.length()); + found = asubstr.find(":"); + std::string asubstr2 = asubstr.substr(found + 1, astr.length()); + oss_debug_file << asubstr2; + } the_debug_file.close(); // Compare with the strings put inside this source file - std::string str_to_test = "# In {" - "# In/Out { }" - "Here is a test" - "# Out }"; + std::string str_to_test = + "# In {" + "# In/Out { }" + "Here is a test" + "# Out }"; bool two_sub_string_identical; // Make comparisons. two_sub_string_identical = str_to_test == oss_debug_file.str(); BOOST_CHECK(two_sub_string_identical); - } diff --git a/tests/debug-tracer.cpp b/tests/debug-tracer.cpp index 8bf547d538434172ab0880d1ff025c6941218117..17889e45cddddfc370156002f052d66861a4844b 100644 --- a/tests/debug-tracer.cpp +++ b/tests/debug-tracer.cpp @@ -14,84 +14,61 @@ #include <dynamic-graph/signal-time-dependent.h> #include <dynamic-graph/tracer.h> -#define BOOST_TEST_MODULE debug-tracer +#define BOOST_TEST_MODULE debug - tracer #include <boost/test/unit_test.hpp> #include <boost/test/output_test_stream.hpp> -namespace dynamicgraph -{ - struct MyEntity : public dynamicgraph::Entity +namespace dynamicgraph { +struct MyEntity : public dynamicgraph::Entity { + static const std::string CLASS_NAME; + + dynamicgraph::Signal<double, int> m_sigdSIN; + dynamicgraph::SignalTimeDependent<double, int> m_sigdTimeDepSOUT; + dynamicgraph::SignalTimeDependent<double, int> m_sigdTwoTimeDepSOUT; + + MyEntity(const std::string &name) + : Entity(name), + m_sigdSIN("MyEntity(" + name + ")::input(double)::in_double"), + m_sigdTimeDepSOUT(boost::bind(&MyEntity::update, this, _1, _2), m_sigdSIN, + "MyEntity(" + name + ")::input(double)::out_double"), + m_sigdTwoTimeDepSOUT(boost::bind(&MyEntity::update, this, _1, _2), m_sigdSIN, + "MyEntity(" + name + ")::input(double)::out2double") + { - static const std::string CLASS_NAME; - - dynamicgraph::Signal<double, int> m_sigdSIN; - dynamicgraph::SignalTimeDependent<double, int> m_sigdTimeDepSOUT; - dynamicgraph::SignalTimeDependent<double, int> m_sigdTwoTimeDepSOUT; - - MyEntity (const std::string& name) - : Entity (name) - ,m_sigdSIN("MyEntity("+name+")::input(double)::in_double") - ,m_sigdTimeDepSOUT(boost::bind(&MyEntity::update,this,_1,_2), - m_sigdSIN, - "MyEntity("+name+")::input(double)::out_double") - ,m_sigdTwoTimeDepSOUT(boost::bind(&MyEntity::update,this,_1,_2), - m_sigdSIN, - "MyEntity("+name+")::input(double)::out2double") - - { - signalRegistration(m_sigdSIN - << m_sigdTimeDepSOUT - << m_sigdTwoTimeDepSOUT); - } - - virtual void display (std::ostream& os) const - { - os << "Hello! My name is " << getName () << " !" << std::endl; - } - - virtual const std::string& getClassName () const - { - return CLASS_NAME; - } - - double & update(double &res, const int &inTime) - { - const double &aDouble = m_sigdSIN(inTime); - res = aDouble; - return res; - } - - }; - DYNAMICGRAPH_FACTORY_ENTITY_PLUGIN (MyEntity,"MyEntity"); -} + signalRegistration(m_sigdSIN << m_sigdTimeDepSOUT << m_sigdTwoTimeDepSOUT); + } -BOOST_AUTO_TEST_CASE(test_tracer) -{ + virtual void display(std::ostream &os) const { os << "Hello! My name is " << getName() << " !" << std::endl; } + virtual const std::string &getClassName() const { return CLASS_NAME; } + + double &update(double &res, const int &inTime) { + const double &aDouble = m_sigdSIN(inTime); + res = aDouble; + return res; + } +}; +DYNAMICGRAPH_FACTORY_ENTITY_PLUGIN(MyEntity, "MyEntity"); +} // namespace dynamicgraph + +BOOST_AUTO_TEST_CASE(test_tracer) { // Creates a tracer. - dynamicgraph::Tracer & atracer = - *dynamic_cast<dynamicgraph::Tracer *> - (dynamicgraph::FactoryStorage::getInstance()->newEntity("Tracer", - "my-tracer")); + dynamicgraph::Tracer &atracer = *dynamic_cast<dynamicgraph::Tracer *>( + dynamicgraph::FactoryStorage::getInstance()->newEntity("Tracer", "my-tracer")); - dynamicgraph::Entity & entity = - *dynamicgraph::FactoryStorage::getInstance()->newEntity("MyEntity", - "my-entity"); + dynamicgraph::Entity &entity = *dynamicgraph::FactoryStorage::getInstance()->newEntity("MyEntity", "my-entity"); /// Add trace by name - atracer.addSignalToTraceByName("my-entity.out_double","output"); - + atracer.addSignalToTraceByName("my-entity.out_double", "output"); - dynamicgraph::SignalBase<int> & aSignal = - entity.getSignal("out2double"); + dynamicgraph::SignalBase<int> &aSignal = entity.getSignal("out2double"); - dynamicgraph::Signal<double,int> & aSignalInt = - *(dynamic_cast<dynamicgraph::Signal<double,int> *> - (& entity.getSignal("in_double"))); + dynamicgraph::Signal<double, int> &aSignalInt = + *(dynamic_cast<dynamicgraph::Signal<double, int> *>(&entity.getSignal("in_double"))); /// Add trace by signal object - atracer.addSignalToTrace(aSignal,"output2"); + atracer.addSignalToTrace(aSignal, "output2"); aSignalInt.setConstant(1.5); @@ -100,16 +77,15 @@ BOOST_AUTO_TEST_CASE(test_tracer) std::string suffix(".dat"); /// Test openfiles - atracer.openFiles(rootdir,basename,suffix); + atracer.openFiles(rootdir, basename, suffix); atracer.start(); - for(int i=0;i<1000;i++) - { - aSignal.setTime(i); - aSignalInt.setTime(i); - atracer.recordTrigger(i,i); - } + for (int i = 0; i < 1000; i++) { + aSignal.setTime(i); + aSignalInt.setTime(i); + atracer.recordTrigger(i, i); + } atracer.stop(); diff --git a/tests/entity.cpp b/tests/entity.cpp index 7e4a5d091496b34e31ef71a2091e3e5713b16dc6..5d9fe6a10d2940e1dbdbf5e9a23ba4b9961b8ce8 100644 --- a/tests/entity.cpp +++ b/tests/entity.cpp @@ -21,213 +21,159 @@ using boost::test_tools::output_test_stream; -namespace dynamicgraph -{ - class CustomEntity : public Entity - { - public: - dynamicgraph::SignalPtr<double, int> m_sigdSIN; - dynamicgraph::SignalTimeDependent<double, int> m_sigdTimeDepSOUT; - - static const std::string CLASS_NAME; - virtual const std::string& getClassName () const - { - return CLASS_NAME; - } - CustomEntity (const std::string n) - : Entity (n) - ,m_sigdSIN(NULL,"CustomEntity("+name+")::input(double)::in_double") - ,m_sigdTimeDepSOUT(boost::bind(&CustomEntity::update,this,_1,_2), - m_sigdSIN, - "CustomEntity("+name+")::input(double)::out_double") - - { - } - - void addSignal() - { - signalRegistration(m_sigdSIN << m_sigdTimeDepSOUT); - } - - void rmValidSignal() - { - signalDeregistration("in_double"); - signalDeregistration("out_double"); - } - - double & update(double &res, const int &inTime) - { - const double &aDouble = m_sigdSIN(inTime); - res = aDouble; - return res; - } - - }; - DYNAMICGRAPH_FACTORY_ENTITY_PLUGIN (CustomEntity,"CustomEntity"); -} - - -BOOST_AUTO_TEST_CASE (constructor) -{ - BOOST_CHECK_EQUAL (dynamicgraph::CustomEntity::CLASS_NAME, "CustomEntity"); - - dynamicgraph::Entity& entity = - *dynamicgraph::FactoryStorage::getInstance()->newEntity("CustomEntity", - "my-entity"); - BOOST_CHECK_EQUAL (entity.getName (), "my-entity"); - BOOST_CHECK_EQUAL (entity.getClassName (), - dynamicgraph::CustomEntity::CLASS_NAME); - - dynamicgraph::CustomEntity entity2 (""); +namespace dynamicgraph { +class CustomEntity : public Entity { + public: + dynamicgraph::SignalPtr<double, int> m_sigdSIN; + dynamicgraph::SignalTimeDependent<double, int> m_sigdTimeDepSOUT; + + static const std::string CLASS_NAME; + virtual const std::string& getClassName() const { return CLASS_NAME; } + CustomEntity(const std::string n) + : Entity(n), + m_sigdSIN(NULL, "CustomEntity(" + name + ")::input(double)::in_double"), + m_sigdTimeDepSOUT(boost::bind(&CustomEntity::update, this, _1, _2), m_sigdSIN, + "CustomEntity(" + name + ")::input(double)::out_double") + + {} + + void addSignal() { signalRegistration(m_sigdSIN << m_sigdTimeDepSOUT); } + + void rmValidSignal() { + signalDeregistration("in_double"); + signalDeregistration("out_double"); + } + + double& update(double& res, const int& inTime) { + const double& aDouble = m_sigdSIN(inTime); + res = aDouble; + return res; + } +}; +DYNAMICGRAPH_FACTORY_ENTITY_PLUGIN(CustomEntity, "CustomEntity"); +} // namespace dynamicgraph + +BOOST_AUTO_TEST_CASE(constructor) { + BOOST_CHECK_EQUAL(dynamicgraph::CustomEntity::CLASS_NAME, "CustomEntity"); + + dynamicgraph::Entity& entity = *dynamicgraph::FactoryStorage::getInstance()->newEntity("CustomEntity", "my-entity"); + BOOST_CHECK_EQUAL(entity.getName(), "my-entity"); + BOOST_CHECK_EQUAL(entity.getClassName(), dynamicgraph::CustomEntity::CLASS_NAME); + + dynamicgraph::CustomEntity entity2(""); } -BOOST_AUTO_TEST_CASE (signal) -{ - dynamicgraph::Entity& entity = - dynamicgraph::PoolStorage::getInstance()->getEntity("my-entity"); +BOOST_AUTO_TEST_CASE(signal) { + dynamicgraph::Entity& entity = dynamicgraph::PoolStorage::getInstance()->getEntity("my-entity"); // Non const getter. - try - { - entity.getSignal ("I do not exist"); - BOOST_ERROR ("Should never happen."); - } - catch (const dynamicgraph::ExceptionFactory& exception) - { - BOOST_CHECK_EQUAL (exception.getCode (), - dynamicgraph::ExceptionFactory::UNREFERED_SIGNAL); - } + try { + entity.getSignal("I do not exist"); + BOOST_ERROR("Should never happen."); + } catch (const dynamicgraph::ExceptionFactory& exception) { + BOOST_CHECK_EQUAL(exception.getCode(), dynamicgraph::ExceptionFactory::UNREFERED_SIGNAL); + } // Const getter. - try - { - const dynamicgraph::Entity& entityConst = entity; - entityConst.getSignal ("I do not exist"); - BOOST_ERROR ("Should never happen."); - } - catch (const dynamicgraph::ExceptionFactory& exception) - { - BOOST_CHECK_EQUAL (exception.getCode (), - dynamicgraph::ExceptionFactory::UNREFERED_SIGNAL); - } + try { + const dynamicgraph::Entity& entityConst = entity; + entityConst.getSignal("I do not exist"); + BOOST_ERROR("Should never happen."); + } catch (const dynamicgraph::ExceptionFactory& exception) { + BOOST_CHECK_EQUAL(exception.getCode(), dynamicgraph::ExceptionFactory::UNREFERED_SIGNAL); + } // deregistration - try - { - dynamicgraph::CustomEntity * customEntity = - dynamic_cast<dynamicgraph::CustomEntity *>(&entity); - customEntity->addSignal(); - // Removing signals is working the first time - customEntity->rmValidSignal(); - // Removing signals generates an exception the second time. - customEntity->rmValidSignal(); - BOOST_ERROR ("Should never happen."); - } - catch (const dynamicgraph::ExceptionFactory& exception) - { - BOOST_CHECK_EQUAL (exception.getCode (), - dynamicgraph::ExceptionFactory::UNREFERED_SIGNAL); - } + try { + dynamicgraph::CustomEntity* customEntity = dynamic_cast<dynamicgraph::CustomEntity*>(&entity); + customEntity->addSignal(); + // Removing signals is working the first time + customEntity->rmValidSignal(); + // Removing signals generates an exception the second time. + customEntity->rmValidSignal(); + BOOST_ERROR("Should never happen."); + } catch (const dynamicgraph::ExceptionFactory& exception) { + BOOST_CHECK_EQUAL(exception.getCode(), dynamicgraph::ExceptionFactory::UNREFERED_SIGNAL); + } } -BOOST_AUTO_TEST_CASE (displaySignalList) -{ - dynamicgraph::Entity& entity = - dynamicgraph::PoolStorage::getInstance()->getEntity("my-entity"); +BOOST_AUTO_TEST_CASE(displaySignalList) { + dynamicgraph::Entity& entity = dynamicgraph::PoolStorage::getInstance()->getEntity("my-entity"); output_test_stream output; entity.displaySignalList(output); - BOOST_CHECK (output.is_equal ("--- <my-entity> signal list: \n")); + BOOST_CHECK(output.is_equal("--- <my-entity> signal list: \n")); } -BOOST_AUTO_TEST_CASE (display) -{ - dynamicgraph::Entity& entity = - dynamicgraph::PoolStorage::getInstance()->getEntity("my-entity"); +BOOST_AUTO_TEST_CASE(display) { + dynamicgraph::Entity& entity = dynamicgraph::PoolStorage::getInstance()->getEntity("my-entity"); output_test_stream output; entity.display(output); - BOOST_CHECK (output.is_equal ("CustomEntity: my-entity")); + BOOST_CHECK(output.is_equal("CustomEntity: my-entity")); } -BOOST_AUTO_TEST_CASE (getCommandList) -{ - dynamicgraph::Entity& entity = - dynamicgraph::PoolStorage::getInstance()->getEntity("my-entity"); +BOOST_AUTO_TEST_CASE(getCommandList) { + dynamicgraph::Entity& entity = dynamicgraph::PoolStorage::getInstance()->getEntity("my-entity"); - BOOST_CHECK_EQUAL (entity.getCommandList (), "print\nsignals\nsignalDep"); + BOOST_CHECK_EQUAL(entity.getCommandList(), "print\nsignals\nsignalDep"); } -BOOST_AUTO_TEST_CASE (writeGraph) -{ - dynamicgraph::Entity& entity = - dynamicgraph::PoolStorage::getInstance()->getEntity("my-entity"); +BOOST_AUTO_TEST_CASE(writeGraph) { + dynamicgraph::Entity& entity = dynamicgraph::PoolStorage::getInstance()->getEntity("my-entity"); output_test_stream output; - entity.writeGraph (output); + entity.writeGraph(output); - BOOST_CHECK (output.is_equal ("")); + BOOST_CHECK(output.is_equal("")); } -BOOST_AUTO_TEST_CASE (writeCompletionList) -{ - dynamicgraph::Entity& entity = - dynamicgraph::PoolStorage::getInstance()->getEntity("my-entity"); +BOOST_AUTO_TEST_CASE(writeCompletionList) { + dynamicgraph::Entity& entity = dynamicgraph::PoolStorage::getInstance()->getEntity("my-entity"); output_test_stream output; - entity.writeCompletionList (output); + entity.writeCompletionList(output); - BOOST_CHECK (output.is_equal ("print\nsignals\nsignalDep\n")); + BOOST_CHECK(output.is_equal("print\nsignals\nsignalDep\n")); } -BOOST_AUTO_TEST_CASE (sendMsg) -{ +BOOST_AUTO_TEST_CASE(sendMsg) { std::ofstream of; - of.open("/tmp/dg-LOGS.txt",std::ofstream::out|std::ofstream::app); + of.open("/tmp/dg-LOGS.txt", std::ofstream::out | std::ofstream::app); dgADD_OSTREAM_TO_RTLOG(of); - dynamicgraph::Entity& entity = - dynamicgraph::PoolStorage::getInstance()->getEntity("my-entity"); + dynamicgraph::Entity& entity = dynamicgraph::PoolStorage::getInstance()->getEntity("my-entity"); output_test_stream output; - for(unsigned int i=0; - i<4; - i++) - { - for(unsigned int j=0;j<2000;j++) - { - dynamicgraph::LoggerVerbosity aLoggerVerbosityLevel= - (dynamicgraph::LoggerVerbosity) i; - entity.setLoggerVerbosityLevel(aLoggerVerbosityLevel); - if (entity.getLoggerVerbosityLevel()!=aLoggerVerbosityLevel) - output << "Mismatch output"; - - std::string aBaseMsg="Auto Test Case"; - std::string aMsg=aBaseMsg+" DEBUG"; - entity.sendMsg(aMsg, dynamicgraph::MSG_TYPE_DEBUG, __FILE__, __LINE__); - aMsg=aBaseMsg+" INFO"; - entity.sendMsg(aMsg, dynamicgraph::MSG_TYPE_INFO, __FILE__, __LINE__); - aMsg=aBaseMsg+" WARNING"; - entity.sendMsg(aMsg, dynamicgraph::MSG_TYPE_WARNING, __FILE__, __LINE__); - aMsg=aBaseMsg+" DEBUG"; - entity.sendMsg(aMsg, dynamicgraph::MSG_TYPE_ERROR, __FILE__, __LINE__); - }; + for (unsigned int i = 0; i < 4; i++) { + for (unsigned int j = 0; j < 2000; j++) { + dynamicgraph::LoggerVerbosity aLoggerVerbosityLevel = (dynamicgraph::LoggerVerbosity)i; + entity.setLoggerVerbosityLevel(aLoggerVerbosityLevel); + if (entity.getLoggerVerbosityLevel() != aLoggerVerbosityLevel) output << "Mismatch output"; + + std::string aBaseMsg = "Auto Test Case"; + std::string aMsg = aBaseMsg + " DEBUG"; + entity.sendMsg(aMsg, dynamicgraph::MSG_TYPE_DEBUG, __FILE__, __LINE__); + aMsg = aBaseMsg + " INFO"; + entity.sendMsg(aMsg, dynamicgraph::MSG_TYPE_INFO, __FILE__, __LINE__); + aMsg = aBaseMsg + " WARNING"; + entity.sendMsg(aMsg, dynamicgraph::MSG_TYPE_WARNING, __FILE__, __LINE__); + aMsg = aBaseMsg + " DEBUG"; + entity.sendMsg(aMsg, dynamicgraph::MSG_TYPE_ERROR, __FILE__, __LINE__); }; + }; - BOOST_CHECK (output.is_equal ("")); + BOOST_CHECK(output.is_equal("")); dynamicgraph::RealTimeLogger::destroy(); } // WTF? -BOOST_AUTO_TEST_CASE (wtf) -{ - dynamicgraph::Entity& entity = - dynamicgraph::PoolStorage::getInstance()->getEntity("my-entity"); +BOOST_AUTO_TEST_CASE(wtf) { + dynamicgraph::Entity& entity = dynamicgraph::PoolStorage::getInstance()->getEntity("my-entity"); - BOOST_CHECK_EQUAL (entity.test (), - static_cast<dynamicgraph::SignalBase<int>*> (0)); + BOOST_CHECK_EQUAL(entity.test(), static_cast<dynamicgraph::SignalBase<int>*>(0)); - entity.test2 (static_cast<dynamicgraph::SignalBase<int>*> (0)); + entity.test2(static_cast<dynamicgraph::SignalBase<int>*>(0)); } diff --git a/tests/factory.cpp b/tests/factory.cpp index 45a23722aa299387459d04bd254f1b6707e7f643..c188c55fe55d9c31851118c2fb513a6fc81dec9b 100644 --- a/tests/factory.cpp +++ b/tests/factory.cpp @@ -13,147 +13,89 @@ using boost::test_tools::output_test_stream; - - -namespace dynamicgraph -{ - class CustomEntity : public Entity - { - public: - static const std::string CLASS_NAME; - virtual const std::string& getClassName () const - { - return CLASS_NAME; - } - CustomEntity (const std::string n) - : Entity (n) - { - } - }; - const std::string CustomEntity::CLASS_NAME = "CustomEntity"; -} - - -dynamicgraph::Entity* makeEntity(const std::string& objectName) -{ - return new dynamicgraph::CustomEntity (objectName); -} - - -BOOST_AUTO_TEST_CASE (constructor) -{ - dynamicgraph::FactoryStorage::getInstance(); -} - -BOOST_AUTO_TEST_CASE (registerEntity) -{ - dynamicgraph::FactoryStorage::getInstance()->registerEntity - ("myEntity", &makeEntity); - - try - { - dynamicgraph::FactoryStorage::getInstance()->registerEntity - ("myEntity", &makeEntity); - BOOST_ERROR ("Should never happen."); - } - catch (const dynamicgraph::ExceptionFactory& exception) - { - BOOST_CHECK_EQUAL (exception.getCode (), - dynamicgraph::ExceptionFactory::OBJECT_CONFLICT); - } - - try - { - dynamicgraph::FactoryStorage::getInstance()->registerEntity - ("myEntity", 0); - BOOST_ERROR ("Should never happen."); - } - catch (const dynamicgraph::ExceptionFactory& exception) - { - BOOST_CHECK_EQUAL (exception.getCode (), - dynamicgraph::ExceptionFactory::OBJECT_CONFLICT); - } +namespace dynamicgraph { +class CustomEntity : public Entity { + public: + static const std::string CLASS_NAME; + virtual const std::string& getClassName() const { return CLASS_NAME; } + CustomEntity(const std::string n) : Entity(n) {} +}; +const std::string CustomEntity::CLASS_NAME = "CustomEntity"; +} // namespace dynamicgraph + +dynamicgraph::Entity* makeEntity(const std::string& objectName) { return new dynamicgraph::CustomEntity(objectName); } + +BOOST_AUTO_TEST_CASE(constructor) { dynamicgraph::FactoryStorage::getInstance(); } + +BOOST_AUTO_TEST_CASE(registerEntity) { + dynamicgraph::FactoryStorage::getInstance()->registerEntity("myEntity", &makeEntity); + + try { + dynamicgraph::FactoryStorage::getInstance()->registerEntity("myEntity", &makeEntity); + BOOST_ERROR("Should never happen."); + } catch (const dynamicgraph::ExceptionFactory& exception) { + BOOST_CHECK_EQUAL(exception.getCode(), dynamicgraph::ExceptionFactory::OBJECT_CONFLICT); + } + + try { + dynamicgraph::FactoryStorage::getInstance()->registerEntity("myEntity", 0); + BOOST_ERROR("Should never happen."); + } catch (const dynamicgraph::ExceptionFactory& exception) { + BOOST_CHECK_EQUAL(exception.getCode(), dynamicgraph::ExceptionFactory::OBJECT_CONFLICT); + } } -BOOST_AUTO_TEST_CASE (unregisterEntity) -{ - dynamicgraph::FactoryStorage::getInstance()->deregisterEntity ("myEntity"); - - try - { - dynamicgraph::FactoryStorage::getInstance()->deregisterEntity("myEntity"); - BOOST_ERROR ("Should never happen."); - } - catch (const dynamicgraph::ExceptionFactory& exception) - { - BOOST_CHECK_EQUAL (exception.getCode (), - dynamicgraph::ExceptionFactory::OBJECT_CONFLICT); - } - - try - { - dynamicgraph::FactoryStorage::getInstance()->deregisterEntity - ("I do not exist."); - BOOST_ERROR ("Should never happen."); - } - catch (const dynamicgraph::ExceptionFactory& exception) - { - BOOST_CHECK_EQUAL (exception.getCode (), - dynamicgraph::ExceptionFactory::OBJECT_CONFLICT); - } +BOOST_AUTO_TEST_CASE(unregisterEntity) { + dynamicgraph::FactoryStorage::getInstance()->deregisterEntity("myEntity"); + + try { + dynamicgraph::FactoryStorage::getInstance()->deregisterEntity("myEntity"); + BOOST_ERROR("Should never happen."); + } catch (const dynamicgraph::ExceptionFactory& exception) { + BOOST_CHECK_EQUAL(exception.getCode(), dynamicgraph::ExceptionFactory::OBJECT_CONFLICT); + } + + try { + dynamicgraph::FactoryStorage::getInstance()->deregisterEntity("I do not exist."); + BOOST_ERROR("Should never happen."); + } catch (const dynamicgraph::ExceptionFactory& exception) { + BOOST_CHECK_EQUAL(exception.getCode(), dynamicgraph::ExceptionFactory::OBJECT_CONFLICT); + } } -BOOST_AUTO_TEST_CASE (newEntity) -{ - dynamicgraph::FactoryStorage::getInstance()->registerEntity - ("myEntity", &makeEntity); - - { - boost::shared_ptr<dynamicgraph::Entity> entity - (dynamicgraph::FactoryStorage::getInstance()->newEntity - ("myEntity", "foo")); - - boost::shared_ptr<dynamicgraph::Entity> entity2 - (dynamicgraph::FactoryStorage::getInstance()->newEntity - ("myEntity", "foo2")); - - boost::shared_ptr<dynamicgraph::Entity> entity3 - (dynamicgraph::FactoryStorage::getInstance()->newEntity - ("myEntity", "")); - } - - try - { - dynamicgraph::FactoryStorage::getInstance()->newEntity - ("I do not exist.", ""); - BOOST_ERROR ("Should never happen."); - } - catch (const dynamicgraph::ExceptionFactory& exception) - { - BOOST_CHECK_EQUAL (exception.getCode (), - dynamicgraph::ExceptionFactory::UNREFERED_OBJECT); - } - - try - { - dynamicgraph::FactoryStorage::getInstance()->destroy(); - dynamicgraph::FactoryStorage::getInstance()->existEntity("myEntity"); - //BOOST_ERROR ("Should never happen."); - } - catch (const dynamicgraph::ExceptionFactory& exception) - { - BOOST_CHECK_EQUAL (exception.getCode (), - dynamicgraph::ExceptionFactory::UNREFERED_OBJECT); - } - +BOOST_AUTO_TEST_CASE(newEntity) { + dynamicgraph::FactoryStorage::getInstance()->registerEntity("myEntity", &makeEntity); + + { + boost::shared_ptr<dynamicgraph::Entity> entity( + dynamicgraph::FactoryStorage::getInstance()->newEntity("myEntity", "foo")); + + boost::shared_ptr<dynamicgraph::Entity> entity2( + dynamicgraph::FactoryStorage::getInstance()->newEntity("myEntity", "foo2")); + + boost::shared_ptr<dynamicgraph::Entity> entity3( + dynamicgraph::FactoryStorage::getInstance()->newEntity("myEntity", "")); + } + + try { + dynamicgraph::FactoryStorage::getInstance()->newEntity("I do not exist.", ""); + BOOST_ERROR("Should never happen."); + } catch (const dynamicgraph::ExceptionFactory& exception) { + BOOST_CHECK_EQUAL(exception.getCode(), dynamicgraph::ExceptionFactory::UNREFERED_OBJECT); + } + + try { + dynamicgraph::FactoryStorage::getInstance()->destroy(); + dynamicgraph::FactoryStorage::getInstance()->existEntity("myEntity"); + // BOOST_ERROR ("Should never happen."); + } catch (const dynamicgraph::ExceptionFactory& exception) { + BOOST_CHECK_EQUAL(exception.getCode(), dynamicgraph::ExceptionFactory::UNREFERED_OBJECT); + } } -BOOST_AUTO_TEST_CASE (existEntity) -{ - //BOOST_CHECK (dynamicgraph::FactoryStorage::getInstance()->existEntity - // ("myEntity")); - BOOST_CHECK (!dynamicgraph::FactoryStorage::getInstance()->existEntity - ("myEntity2")); - BOOST_CHECK (!dynamicgraph::FactoryStorage::getInstance()->existEntity ("")); - +BOOST_AUTO_TEST_CASE(existEntity) { + // BOOST_CHECK (dynamicgraph::FactoryStorage::getInstance()->existEntity + // ("myEntity")); + BOOST_CHECK(!dynamicgraph::FactoryStorage::getInstance()->existEntity("myEntity2")); + BOOST_CHECK(!dynamicgraph::FactoryStorage::getInstance()->existEntity("")); } diff --git a/tests/interpreter-tracer.cpp b/tests/interpreter-tracer.cpp index f514b87e984f5bd0e2b3354cd031d8d658152b24..6a759cf28bfe49a1410ea2258c705a841d1d769c 100644 --- a/tests/interpreter-tracer.cpp +++ b/tests/interpreter-tracer.cpp @@ -16,23 +16,22 @@ using boost::test_tools::output_test_stream; // Check that plug-in loading/unloading is working. -BOOST_AUTO_TEST_CASE (cmd_tracer) -{ +BOOST_AUTO_TEST_CASE(cmd_tracer) { dynamicgraph::PluginLoader pl; // Push paths. { - RUN_COMMAND ("pushImportPaths", TESTS_DATADIR); - BOOST_CHECK (output.is_empty ()); + RUN_COMMAND("pushImportPaths", TESTS_DATADIR); + BOOST_CHECK(output.is_empty()); } { - RUN_COMMAND ("pushImportPaths", TESTS_PLUGINDIR); - BOOST_CHECK (output.is_empty ()); + RUN_COMMAND("pushImportPaths", TESTS_PLUGINDIR); + BOOST_CHECK(output.is_empty()); } // Import tracer.dg { - RUN_COMMAND ("import", "interpreter-tracer.dg"); - BOOST_CHECK (output.is_empty ()); + RUN_COMMAND("import", "interpreter-tracer.dg"); + BOOST_CHECK(output.is_empty()); } } diff --git a/tests/pool.cpp b/tests/pool.cpp index 9ea3b2da88211e4df5fb7fd1a2ea95f042944f9b..3b6b46e26fb05e8ff9ee9ef8ef474b43a8e213f4 100644 --- a/tests/pool.cpp +++ b/tests/pool.cpp @@ -17,117 +17,88 @@ using boost::test_tools::output_test_stream; -struct MyEntity : public dynamicgraph::Entity -{ +struct MyEntity : public dynamicgraph::Entity { static const std::string CLASS_NAME; dynamicgraph::SignalPtr<double, int> m_sigdSIN; dynamicgraph::SignalTimeDependent<double, int> m_sigdTimeDepSOUT; - MyEntity (const std::string& name) - : Entity (name) - ,m_sigdSIN(NULL,"MyEntity("+name+")::input(double)::in_double") - ,m_sigdTimeDepSOUT(boost::bind(&MyEntity::update,this,_1,_2), - m_sigdSIN, - "MyEntity("+name+")::input(double)::out_double") - { + MyEntity(const std::string &name) + : Entity(name), + m_sigdSIN(NULL, "MyEntity(" + name + ")::input(double)::in_double"), + m_sigdTimeDepSOUT(boost::bind(&MyEntity::update, this, _1, _2), m_sigdSIN, + "MyEntity(" + name + ")::input(double)::out_double") { signalRegistration(m_sigdSIN << m_sigdTimeDepSOUT); } - virtual void display (std::ostream& os) const - { - os << "Hello! My name is " << getName () << " !" << std::endl; - } + virtual void display(std::ostream &os) const { os << "Hello! My name is " << getName() << " !" << std::endl; } - virtual const std::string& getClassName () const - { - return CLASS_NAME; - } + virtual const std::string &getClassName() const { return CLASS_NAME; } - double & update(double &res, const int &inTime) - { + double &update(double &res, const int &inTime) { const double &aDouble = m_sigdSIN(inTime); res = aDouble; return res; } - }; -DYNAMICGRAPH_FACTORY_ENTITY_PLUGIN (MyEntity, "MyEntity"); +DYNAMICGRAPH_FACTORY_ENTITY_PLUGIN(MyEntity, "MyEntity"); namespace dg = dynamicgraph; -BOOST_AUTO_TEST_CASE (pool_display) -{ +BOOST_AUTO_TEST_CASE(pool_display) { /// Create Entity - dg::Entity* entity = - dg::FactoryStorage::getInstance()-> - newEntity("MyEntity", "MyEntityInst"); + dg::Entity *entity = dg::FactoryStorage::getInstance()->newEntity("MyEntity", "MyEntityInst"); /// Test exception catching when registering Entity - bool res=false; + bool res = false; try { - dg::Entity* entity2 = - dg::FactoryStorage::getInstance()-> - newEntity("MyEntity", "MyEntityInst"); + dg::Entity *entity2 = dg::FactoryStorage::getInstance()->newEntity("MyEntity", "MyEntityInst"); - bool res2 = (entity2==entity); + bool res2 = (entity2 == entity); BOOST_CHECK(res2); + } catch (const dg::ExceptionFactory &aef) { + res = (aef.getCode() == dg::ExceptionFactory::OBJECT_CONFLICT); } - catch (const dg::ExceptionFactory &aef) - { - res =(aef.getCode()==dg::ExceptionFactory::OBJECT_CONFLICT); - } BOOST_CHECK(res); /// Test exception catching when deregistering Entity - res=false; + res = false; try { - dg::FactoryStorage::getInstance()-> - deregisterEntity("MyEntityInstFailure"); + dg::FactoryStorage::getInstance()->deregisterEntity("MyEntityInstFailure"); + } catch (const dg::ExceptionFactory &aef) { + res = (aef.getCode() == dg::ExceptionFactory::OBJECT_CONFLICT); } - catch (const dg::ExceptionFactory &aef) - { - res =(aef.getCode()==dg::ExceptionFactory::OBJECT_CONFLICT); - } BOOST_CHECK(res); /// Search for an entity inside the map output_test_stream output; - dg::Entity& e = dg::PoolStorage::getInstance()->getEntity - ("MyEntityInst"); + dg::Entity &e = dg::PoolStorage::getInstance()->getEntity("MyEntityInst"); e.display(output); - BOOST_CHECK (output.is_equal ("Hello! My name is MyEntityInst !\n")); + BOOST_CHECK(output.is_equal("Hello! My name is MyEntityInst !\n")); /// Search for an entity inside the map - res=false; - try - { - dg::PoolStorage::getInstance()->getEntity - ("MyEntityInstFailure"); - } - catch (const dg::ExceptionFactory &aef) - { - res =(aef.getCode()==dg::ExceptionFactory::UNREFERED_OBJECT); - } - BOOST_CHECK (res); + res = false; + try { + dg::PoolStorage::getInstance()->getEntity("MyEntityInstFailure"); + } catch (const dg::ExceptionFactory &aef) { + res = (aef.getCode() == dg::ExceptionFactory::UNREFERED_OBJECT); + } + BOOST_CHECK(res); /// Testing entityMap - const dg::PoolStorage::Entities& anEntityMap = - dg::PoolStorage::getInstance()->getEntityMap(); + const dg::PoolStorage::Entities &anEntityMap = dg::PoolStorage::getInstance()->getEntityMap(); - bool testExistence = anEntityMap.find("MyEntityInst")==anEntityMap.end(); + bool testExistence = anEntityMap.find("MyEntityInst") == anEntityMap.end(); BOOST_CHECK(!testExistence); /// Testing the existence of an entity - testExistence = dg::PoolStorage::getInstance()->existEntity - ("MyEntityInst",entity); + testExistence = dg::PoolStorage::getInstance()->existEntity("MyEntityInst", entity); BOOST_CHECK(testExistence); /// Testing the completion list of pool storage - dg::PoolStorage::getInstance()->writeCompletionList - (output); - BOOST_CHECK (output.is_equal ("MyEntityInst.in_double\nMyEntityInst.out_double\nprint\nsignals\nsignalDep\n")); + dg::PoolStorage::getInstance()->writeCompletionList(output); + BOOST_CHECK(output.is_equal("MyEntityInst.in_double\nMyEntityInst.out_double\nprint\nsignals\nsignalDep\n")); /// Checking the graph generated by the pool dg::PoolStorage::getInstance()->writeGraph("output.dot"); @@ -138,38 +109,38 @@ BOOST_AUTO_TEST_CASE (pool_display) the_debug_file.close(); /// Use a predefined output - std::string str_to_test="/* This graph has been automatically generated.\n" - " 2019 Month: 2 Day: 28 Time: 11:28 */\n" - "digraph \"output\" { graph [ label=\"output\" bgcolor = white rankdir=LR ]\n" - "\t node [ fontcolor = black, color = black, fillcolor = gold1, style=filled, shape=box ] ; \n" - "\tsubgraph cluster_Entities { \n" - "\t} \n" - "\"MyEntityInst\" [ label = \"MyEntityInst\" ,\n" - " fontcolor = black, color = black, fillcolor=cyan, style=filled, shape=box ]\n" - "}\n"; + std::string str_to_test = + "/* This graph has been automatically generated.\n" + " 2019 Month: 2 Day: 28 Time: 11:28 */\n" + "digraph \"output\" { graph [ label=\"output\" bgcolor = white rankdir=LR ]\n" + "\t node [ fontcolor = black, color = black, fillcolor = gold1, style=filled, shape=box ] ; \n" + "\tsubgraph cluster_Entities { \n" + "\t} \n" + "\"MyEntityInst\" [ label = \"MyEntityInst\" ,\n" + " fontcolor = black, color = black, fillcolor=cyan, style=filled, shape=box ]\n" + "}\n"; /// Check the two substring (remove the date) - std::string s_output_wgph = oss_output_wgph.str(); - std::string s_crmk="*/"; + std::string s_crmk = "*/"; std::size_t find_s_output_wgph = s_output_wgph.find(s_crmk); - std::string sub_s_output_wgph =s_output_wgph.substr(find_s_output_wgph, s_output_wgph.length()); + std::string sub_s_output_wgph = s_output_wgph.substr(find_s_output_wgph, s_output_wgph.length()); std::size_t find_str_to_test = str_to_test.find(s_crmk); - std::string sub_str_to_test =str_to_test.substr(find_str_to_test, str_to_test.length()); + std::string sub_str_to_test = str_to_test.substr(find_str_to_test, str_to_test.length()); bool two_sub_string_identical; - two_sub_string_identical=sub_str_to_test==sub_s_output_wgph; + two_sub_string_identical = sub_str_to_test == sub_s_output_wgph; BOOST_CHECK(two_sub_string_identical); /// Test name of a valid signal. std::istringstream an_iss("MyEntityInst.in_double"); - dg::SignalBase<int> &aSignal= - dg::PoolStorage::getInstance()->getSignal(an_iss); + dg::SignalBase<int> &aSignal = dg::PoolStorage::getInstance()->getSignal(an_iss); - std::string aSignalName=aSignal.getName(); - testExistence = aSignalName=="MyEntity(MyEntityInst)::input(double)::in_double"; + std::string aSignalName = aSignal.getName(); + testExistence = aSignalName == "MyEntity(MyEntityInst)::input(double)::in_double"; BOOST_CHECK(testExistence); /// Test name of an unvalid signal. @@ -177,28 +148,22 @@ BOOST_AUTO_TEST_CASE (pool_display) try { dg::PoolStorage::getInstance()->getSignal(an_iss); + } catch (const dg::ExceptionFactory &aef) { + res = (aef.getCode() == dg::ExceptionFactory::UNREFERED_SIGNAL); } - catch(const dg::ExceptionFactory &aef) - { - res =(aef.getCode()==dg::ExceptionFactory::UNREFERED_SIGNAL); - } BOOST_CHECK(res); - /// Deregister the entity. - dg::PoolStorage::getInstance()->deregisterEntity - (entity->getName()); + dg::PoolStorage::getInstance()->deregisterEntity(entity->getName()); /// Testing the existance of an entity - testExistence = dg::PoolStorage::getInstance()->existEntity - ("MyEntityInst",entity); + testExistence = dg::PoolStorage::getInstance()->existEntity("MyEntityInst", entity); BOOST_CHECK(!testExistence); /// Create Entity std::string name_entity("MyEntityInst2"); - dg::PoolStorage::getInstance()-> - clearPlugin(name_entity); + dg::PoolStorage::getInstance()->clearPlugin(name_entity); dg::PoolStorage::destroy(); } diff --git a/tests/real-time-logger.cpp b/tests/real-time-logger.cpp index ac9b38cc1f664abb6217176517e9e918dc6fb23a..1dd5b419543702d495be33e36096509860841d5a 100644 --- a/tests/real-time-logger.cpp +++ b/tests/real-time-logger.cpp @@ -21,28 +21,28 @@ using namespace dynamicgraph; -BOOST_AUTO_TEST_CASE (monothread) -{ - RealTimeLogger rtl (10); - rtl.addOutputStream (LoggerStreamPtr_t (new LoggerIOStream(std::cout))); +BOOST_AUTO_TEST_CASE(monothread) { + RealTimeLogger rtl(10); + rtl.addOutputStream(LoggerStreamPtr_t(new LoggerIOStream(std::cout))); for (int i = 0; i < 9; ++i) rtl.front() << "Call number " << i << '\n'; - BOOST_CHECK (rtl.full()); + BOOST_CHECK(rtl.full()); rtl.front() << "This call should not appear in the output" << '\n'; rtl.spinOnce(); - BOOST_CHECK (!rtl.full()); + BOOST_CHECK(!rtl.full()); rtl.front() << "This call should appear in the output" << '\n'; int spinNb = 0; - while (rtl.spinOnce()) { spinNb++; } + while (rtl.spinOnce()) { + spinNb++; + } BOOST_CHECK_EQUAL(spinNb, 9); rtl.front() << "This msg should be short." << '\n'; rtl.spinOnce(); } -BOOST_AUTO_TEST_CASE (multithread) -{ +BOOST_AUTO_TEST_CASE(multithread) { // The part of the code changing priority will only be effective // if this test is run as root. Otherwise it behaves like a classical thread. // Test confirms that in this case, it runs with a priority -51 @@ -50,22 +50,20 @@ BOOST_AUTO_TEST_CASE (multithread) // with a nice priority (20). int threadPolicy; struct sched_param threadParam; - if (pthread_getschedparam (pthread_self(), &threadPolicy, &threadParam)==0) - { - threadPolicy = SCHED_RR; - threadParam.sched_priority = 50; - pthread_setschedparam (pthread_self(), threadPolicy, &threadParam); - } + if (pthread_getschedparam(pthread_self(), &threadPolicy, &threadParam) == 0) { + threadPolicy = SCHED_RR; + threadParam.sched_priority = 50; + pthread_setschedparam(pthread_self(), threadPolicy, &threadParam); + } RealTimeLogger& rtl = RealTimeLogger::instance(); - dgADD_OSTREAM_TO_RTLOG (std::cout); + dgADD_OSTREAM_TO_RTLOG(std::cout); - for (std::size_t i = 0; i < rtl.getBufferSize()-1; ++i) - dgRTLOG() << "Call number " << i << '\n'; + for (std::size_t i = 0; i < rtl.getBufferSize() - 1; ++i) dgRTLOG() << "Call number " << i << '\n'; for (std::size_t i = 0; i < 12; ++i) { boost::this_thread::sleep(boost::posix_time::milliseconds(20)); dgRTLOG() << "Call number " << i << std::endl; - BOOST_CHECK (!rtl.full()); + BOOST_CHECK(!rtl.full()); } dgRTLOG() << "This call should appear in the output" << '\n'; diff --git a/tests/signal-all.cpp b/tests/signal-all.cpp index ff5d98299811a4669fcf019ff18b85c0e28438b3..875c14771bd3e7eacd3b612f65d6846ec0cee502 100644 --- a/tests/signal-all.cpp +++ b/tests/signal-all.cpp @@ -14,11 +14,8 @@ #include <boost/test/unit_test.hpp> #include <boost/test/output_test_stream.hpp> - #define BOOST_TEST_MODULE signal_array - - using boost::test_tools::output_test_stream; dynamicgraph::SignalArray_const<double> sig; @@ -27,46 +24,43 @@ using namespace std; using namespace dynamicgraph; using namespace dynamicgraph::command; - -BOOST_AUTO_TEST_CASE (test_array) { - SignalBase<int> sigBa("add test"); - SignalArray_const<int> sigArr_C(1); - sigArr_C.operator<<(sigBa); - sigArr_C.operator<<(sigBa); - BOOST_CHECK_EQUAL(2, sigArr_C.getSize()); - - SignalArray<int> sigArr(1); - sigArr.operator<<(sigBa); - sigArr.operator<<(sigBa); - BOOST_CHECK_EQUAL(2,sigArr.getSize()); - - SignalBase<int> sigB("constructor test"); - SignalArray<int> sigA(2); - sigA << sigB; - sigA.operator<<(sigB); - SignalArray_const<int> sig_C(sigA); - BOOST_CHECK_EQUAL(sigA.getSize(),sig_C.getSize()); +BOOST_AUTO_TEST_CASE(test_array) { + SignalBase<int> sigBa("add test"); + SignalArray_const<int> sigArr_C(1); + sigArr_C.operator<<(sigBa); + sigArr_C.operator<<(sigBa); + BOOST_CHECK_EQUAL(2, sigArr_C.getSize()); + + SignalArray<int> sigArr(1); + sigArr.operator<<(sigBa); + sigArr.operator<<(sigBa); + BOOST_CHECK_EQUAL(2, sigArr.getSize()); + + SignalBase<int> sigB("constructor test"); + SignalArray<int> sigA(2); + sigA << sigB; + sigA.operator<<(sigB); + SignalArray_const<int> sig_C(sigA); + BOOST_CHECK_EQUAL(sigA.getSize(), sig_C.getSize()); } -BOOST_AUTO_TEST_CASE(test_base) -{ - SignalBase<int> sigB("test"); - sigB.setReady(); - BOOST_CHECK_EQUAL(true,sigB.getReady()); +BOOST_AUTO_TEST_CASE(test_base) { + SignalBase<int> sigB("test"); + sigB.setReady(); + BOOST_CHECK_EQUAL(true, sigB.getReady()); } -BOOST_AUTO_TEST_CASE(test_cast_helper) -{ - DefaultCastRegisterer<int> defaultCR; - std::istringstream iss; - iss.str("1"); - defaultCR.cast(iss); - - try{ - std::istringstream iss_fail; - iss.str("test"); - defaultCR.cast(iss_fail); - } catch(ExceptionSignal e){ - //Take int, not string - } +BOOST_AUTO_TEST_CASE(test_cast_helper) { + DefaultCastRegisterer<int> defaultCR; + std::istringstream iss; + iss.str("1"); + defaultCR.cast(iss); + + try { + std::istringstream iss_fail; + iss.str("test"); + defaultCR.cast(iss_fail); + } catch (ExceptionSignal e) { + // Take int, not string + } } \ No newline at end of file diff --git a/tests/signal-cast-registerer.cpp b/tests/signal-cast-registerer.cpp index 006f0e6080a01f274b35804f8c9879c598b76da1..2dd972fd4280385f80b9b417366929b8764c32db 100644 --- a/tests/signal-cast-registerer.cpp +++ b/tests/signal-cast-registerer.cpp @@ -29,73 +29,55 @@ using boost::test_tools::output_test_stream; - typedef Eigen::VectorXd Vector; typedef Eigen::MatrixXd Matrix; - -struct EigenCastRegisterer_V : public dynamicgraph::SignalCastRegisterer -{ +struct EigenCastRegisterer_V : public dynamicgraph::SignalCastRegisterer { typedef Vector bnuVector; - EigenCastRegisterer_V () : - SignalCastRegisterer - (typeid(bnuVector), dispVector, castVector, traceVector) - {} + EigenCastRegisterer_V() : SignalCastRegisterer(typeid(bnuVector), dispVector, castVector, traceVector) {} - static boost::any castVector (std::istringstream& iss) - { + static boost::any castVector(std::istringstream& iss) { bnuVector res; iss >> res; return res; } - static void dispVector (const boost::any& object, std::ostream& os) - { - const bnuVector& v = boost::any_cast<bnuVector> (object); + static void dispVector(const boost::any& object, std::ostream& os) { + const bnuVector& v = boost::any_cast<bnuVector>(object); os << "[ "; - for (int i = 0; i < v.size (); ++i) - os << v(i) << " "; + for (int i = 0; i < v.size(); ++i) os << v(i) << " "; os << " ];" << std::endl; } - static void traceVector (const boost::any& object, std::ostream& os) - { - const bnuVector& v = boost::any_cast<bnuVector> (object); - for (int i = 0; i < v.size (); ++i) - os << v(i) << " "; + static void traceVector(const boost::any& object, std::ostream& os) { + const bnuVector& v = boost::any_cast<bnuVector>(object); + for (int i = 0; i < v.size(); ++i) os << v(i) << " "; os << std::endl; } }; -template<typename Derived> -struct EigenCastRegisterer_M : public dynamicgraph::SignalCastRegisterer -{ - typedef Matrix bnuMatrix; +template <typename Derived> +struct EigenCastRegisterer_M : public dynamicgraph::SignalCastRegisterer { + typedef Matrix bnuMatrix; - EigenCastRegisterer_M () : - SignalCastRegisterer - (typeid(bnuMatrix), dispMatrix, castMatrix, traceMatrix) - {} + EigenCastRegisterer_M() : SignalCastRegisterer(typeid(bnuMatrix), dispMatrix, castMatrix, traceMatrix) {} - static boost::any castMatrix (std::istringstream& iss) - { - bnuMatrix res; - iss >> res; - return res; - } + static boost::any castMatrix(std::istringstream& iss) { + bnuMatrix res; + iss >> res; + return res; + } - static void dispMatrix (const boost::any& object, std::ostream& os) - { - const bnuMatrix& m = boost::any_cast<bnuMatrix> (object); - os << m << std::endl; - } + static void dispMatrix(const boost::any& object, std::ostream& os) { + const bnuMatrix& m = boost::any_cast<bnuMatrix>(object); + os << m << std::endl; + } - static void traceMatrix (const boost::any& object, std::ostream& os) - { - const bnuMatrix& m = boost::any_cast<bnuMatrix> (object); - os << m << std::endl; - } + static void traceMatrix(const boost::any& object, std::ostream& os) { + const bnuMatrix& m = boost::any_cast<bnuMatrix>(object); + os << m << std::endl; + } }; EigenCastRegisterer_V myVectorCast; @@ -105,251 +87,237 @@ EigenCastRegisterer_M<int> myMatrixCast; // and from it (this could be automated with macros). dynamicgraph::DefaultCastRegisterer<bool> myBooleanCast; - // Check standard double cast registerer. -BOOST_AUTO_TEST_CASE (standard_double_registerer) -{ +BOOST_AUTO_TEST_CASE(standard_double_registerer) { dynamicgraph::Signal<double, int> mySignal("out"); typedef std::pair<std::string, std::string> test_t; std::vector<test_t> values; - values.push_back (std::make_pair ("42.0", "42\n")); - values.push_back (std::make_pair ("42.5", "42.5\n")); - values.push_back (std::make_pair ("-12.", "-12\n")); + values.push_back(std::make_pair("42.0", "42\n")); + values.push_back(std::make_pair("42.5", "42.5\n")); + values.push_back(std::make_pair("-12.", "-12\n")); // Double special values. // FIXME: these tests are failing :( - values.push_back (std::make_pair ("inf", "inf\n")); - values.push_back (std::make_pair ("-inf", "-inf\n")); - values.push_back (std::make_pair ("nan", "nan\n")); + values.push_back(std::make_pair("inf", "inf\n")); + values.push_back(std::make_pair("-inf", "-inf\n")); + values.push_back(std::make_pair("nan", "nan\n")); + + BOOST_FOREACH (const test_t& test, values) { + // Set + std::istringstream value(test.first); + mySignal.set(value); - BOOST_FOREACH(const test_t& test, values) + // Get { - // Set - std::istringstream value (test.first); - mySignal.set (value); - - // Get - { - output_test_stream output; - mySignal.get (output); - BOOST_CHECK (output.is_equal (test.second)); - } - - // Trace - { - output_test_stream output; - mySignal.trace (output); - BOOST_CHECK (output.is_equal (test.second)); - - } + output_test_stream output; + mySignal.get(output); + BOOST_CHECK(output.is_equal(test.second)); } + // Trace + { + output_test_stream output; + mySignal.trace(output); + BOOST_CHECK(output.is_equal(test.second)); + } + } + // Check invalid values. // FIXME: this test is failing for now. - std::istringstream value ("This is not a valid double."); - BOOST_CHECK_THROW (mySignal.set (value), std::exception); + std::istringstream value("This is not a valid double."); + BOOST_CHECK_THROW(mySignal.set(value), std::exception); } - // Check a custom cast registerer for Boost uBLAS vectors. -BOOST_AUTO_TEST_CASE (custom_vector_registerer) -{ - +BOOST_AUTO_TEST_CASE(custom_vector_registerer) { dynamicgraph::Signal<dynamicgraph::Vector, int> myVectorSignal("vector"); // Print the signal name. { output_test_stream output; output << myVectorSignal; - BOOST_CHECK (output.is_equal ("Sig:vector (Type Cst)")); + BOOST_CHECK(output.is_equal("Sig:vector (Type Cst)")); } - for (unsigned int i = 0; i < 5; ++i) - { - Vector v = Vector::Unit(5,i) ; - std::ostringstream os; - os << v; - std::istringstream ss ("[5]("+os.str ()+")"); + for (unsigned int i = 0; i < 5; ++i) { + Vector v = Vector::Unit(5, i); + std::ostringstream os; + os << v; + std::istringstream ss("[5](" + os.str() + ")"); - // Set signal value. - myVectorSignal.set (ss); + // Set signal value. + myVectorSignal.set(ss); - // Print out signal value. - output_test_stream output; - myVectorSignal.get (output); + // Print out signal value. + output_test_stream output; + myVectorSignal.get(output); - boost::format fmt ("[ %d %d %d %d %d ];\n"); - fmt - % (i == 0) - % (i == 1) - % (i == 2) - % (i == 3) - % (i == 4); + boost::format fmt("[ %d %d %d %d %d ];\n"); + fmt % (i == 0) % (i == 1) % (i == 2) % (i == 3) % (i == 4); - BOOST_CHECK (output.is_equal (fmt.str ())); - } + BOOST_CHECK(output.is_equal(fmt.str())); + } - //Catch Exception of ss (not good input) + // Catch Exception of ss (not good input) - //ss[0] != "[" + // ss[0] != "[" try { - std::istringstream ss ("test"); - myVectorSignal.set (ss); - } catch(ExceptionSignal e) { - std::cout << "Test passed : ss[0] != \"[\""; + std::istringstream ss("test"); + myVectorSignal.set(ss); + } catch (ExceptionSignal e) { + std::cout << "Test passed : ss[0] != \"[\""; } - //ss[1] != %i - try { - std::istringstream ss ("[test"); - myVectorSignal.set (ss); - } catch(ExceptionSignal e) { - std::cout << "Test passed : ss[1] != %i"; - } + // ss[1] != %i + try { + std::istringstream ss("[test"); + myVectorSignal.set(ss); + } catch (ExceptionSignal e) { + std::cout << "Test passed : ss[1] != %i"; + } - //ss[2] != "]" - try { - std::istringstream ss ("[5["); - myVectorSignal.set (ss); - } catch(ExceptionSignal e) { - std::cout << "Test passed : ss[2] != \"]\""; - } + // ss[2] != "]" + try { + std::istringstream ss("[5["); + myVectorSignal.set(ss); + } catch (ExceptionSignal e) { + std::cout << "Test passed : ss[2] != \"]\""; + } - //ss[3] != "(" - try { - std::istringstream ss ("[5]test"); - myVectorSignal.set (ss); - } catch(ExceptionSignal e) { - std::cout << "Test passed : ss[3] != \"(\""; - } + // ss[3] != "(" + try { + std::istringstream ss("[5]test"); + myVectorSignal.set(ss); + } catch (ExceptionSignal e) { + std::cout << "Test passed : ss[3] != \"(\""; + } - //ss[4] != ' ' || ',' - try { - std::istringstream ss ("[5](1, "); - myVectorSignal.set (ss); - } catch(ExceptionSignal e) { - BOOST_ERROR("Can't happened"); - } + // ss[4] != ' ' || ',' + try { + std::istringstream ss("[5](1, "); + myVectorSignal.set(ss); + } catch (ExceptionSignal e) { + BOOST_ERROR("Can't happened"); + } - //ss[-1] != ")" - try { - std::istringstream ss ("[5](1,2,3,4,5]"); - myVectorSignal.set (ss); - } catch(ExceptionSignal e) { - std::cout << "Test passed : ss[-1] != \")\""; - } + // ss[-1] != ")" + try { + std::istringstream ss("[5](1,2,3,4,5]"); + myVectorSignal.set(ss); + } catch (ExceptionSignal e) { + std::cout << "Test passed : ss[-1] != \")\""; + } } -BOOST_AUTO_TEST_CASE (custom_matrix_registerer) { - - dynamicgraph::Signal<dynamicgraph::Matrix, int> myMatrixSignal("matrix"); +BOOST_AUTO_TEST_CASE(custom_matrix_registerer) { + dynamicgraph::Signal<dynamicgraph::Matrix, int> myMatrixSignal("matrix"); - // Print the signal name. - { - output_test_stream output; - output << myMatrixSignal; - BOOST_CHECK (output.is_equal ("Sig:matrix (Type Cst)")); - } + // Print the signal name. + { + output_test_stream output; + output << myMatrixSignal; + BOOST_CHECK(output.is_equal("Sig:matrix (Type Cst)")); + } - //Catch Exception of ss (not good input) + // Catch Exception of ss (not good input) - //ss[0] != "[" - try { - std::istringstream ss("test"); - myMatrixSignal.set(ss); - } catch (ExceptionSignal e) { - std::cout << "Test passed : ss[0] != \"[\""; - } + // ss[0] != "[" + try { + std::istringstream ss("test"); + myMatrixSignal.set(ss); + } catch (ExceptionSignal e) { + std::cout << "Test passed : ss[0] != \"[\""; + } - //ss[1] != %i - try { - std::istringstream ss("[test"); - myMatrixSignal.set(ss); - } catch (ExceptionSignal e) { - std::cout << "Test passed : ss[1] != %i"; - } + // ss[1] != %i + try { + std::istringstream ss("[test"); + myMatrixSignal.set(ss); + } catch (ExceptionSignal e) { + std::cout << "Test passed : ss[1] != %i"; + } - //ss[2] != "," - try { - std::istringstream ss("[5["); - myMatrixSignal.set(ss); - } catch (ExceptionSignal e) { - std::cout << "Test passed : ss[2] != \",\""; - } + // ss[2] != "," + try { + std::istringstream ss("[5["); + myMatrixSignal.set(ss); + } catch (ExceptionSignal e) { + std::cout << "Test passed : ss[2] != \",\""; + } - //ss[3] != %i - try { - std::istringstream ss("[5,c"); - myMatrixSignal.set(ss); - } catch (ExceptionSignal e) { - std::cout << "Test passed : ss[3] != %i"; - } + // ss[3] != %i + try { + std::istringstream ss("[5,c"); + myMatrixSignal.set(ss); + } catch (ExceptionSignal e) { + std::cout << "Test passed : ss[3] != %i"; + } - //ss[4] != "]" - try { - std::istringstream ss("[5,3["); - myMatrixSignal.set(ss); - } catch (ExceptionSignal e) { - std::cout << "Test passed : ss[4] != \"]\""; - } + // ss[4] != "]" + try { + std::istringstream ss("[5,3["); + myMatrixSignal.set(ss); + } catch (ExceptionSignal e) { + std::cout << "Test passed : ss[4] != \"]\""; + } - //ss[5] != "(" - try { - std::istringstream ss("[5,3]test"); - myMatrixSignal.set(ss); - } catch (ExceptionSignal e) { - std::cout << "Test passed : ss[5] != \"(\""; - } + // ss[5] != "(" + try { + std::istringstream ss("[5,3]test"); + myMatrixSignal.set(ss); + } catch (ExceptionSignal e) { + std::cout << "Test passed : ss[5] != \"(\""; + } - //ss[6] != "(" - try { - std::istringstream ss("[5,3](test"); - myMatrixSignal.set(ss); - } catch (ExceptionSignal e) { - std::cout << "Test passed : ss[6] != \"(\""; - } + // ss[6] != "(" + try { + std::istringstream ss("[5,3](test"); + myMatrixSignal.set(ss); + } catch (ExceptionSignal e) { + std::cout << "Test passed : ss[6] != \"(\""; + } - //ss[8] != " " || "," - try { - std::istringstream ss("[5,3]((1,"); - myMatrixSignal.set(ss); - } catch (ExceptionSignal e) { - BOOST_ERROR("Can't happened"); - } + // ss[8] != " " || "," + try { + std::istringstream ss("[5,3]((1,"); + myMatrixSignal.set(ss); + } catch (ExceptionSignal e) { + BOOST_ERROR("Can't happened"); + } - //ss[6+n] != ")" - try { - std::istringstream ss("[5,3]((1,2,3]"); - myMatrixSignal.set(ss); - } catch (ExceptionSignal e) { - std::cout << ("ss[6+n] != \")\""); - } + // ss[6+n] != ")" + try { + std::istringstream ss("[5,3]((1,2,3]"); + myMatrixSignal.set(ss); + } catch (ExceptionSignal e) { + std::cout << ("ss[6+n] != \")\""); + } - //ss[-3] != ")" - try { - std::istringstream ss("[5,1]((1)(2)(3["); - myMatrixSignal.set(ss); - } catch (ExceptionSignal e) { - std::cout << "Test passed : ss[5] != \")\""; - } + // ss[-3] != ")" + try { + std::istringstream ss("[5,1]((1)(2)(3["); + myMatrixSignal.set(ss); + } catch (ExceptionSignal e) { + std::cout << "Test passed : ss[5] != \")\""; + } - //ss[-3] != ")" - try { - std::istringstream ss("[5,1]((1)(2)(3)["); - myMatrixSignal.set(ss); - } catch (ExceptionSignal e) { - std::cout << "Test passed : ss[5] != \")\""; - } + // ss[-3] != ")" + try { + std::istringstream ss("[5,1]((1)(2)(3)["); + myMatrixSignal.set(ss); + } catch (ExceptionSignal e) { + std::cout << "Test passed : ss[5] != \")\""; + } - //ss[-1]!= ")" - try { - std::istringstream ss("[3,1]((1)(2),(3)["); - myMatrixSignal.set(ss); - } catch (ExceptionSignal e) { - std::cout << "Test passed : ss[5] != \")\" and ignore \",\""; - } + // ss[-1]!= ")" + try { + std::istringstream ss("[3,1]((1)(2),(3)["); + myMatrixSignal.set(ss); + } catch (ExceptionSignal e) { + std::cout << "Test passed : ss[5] != \")\" and ignore \",\""; + } - //[...]((...)) + //[...]((...)) } diff --git a/tests/signal-ptr.cpp b/tests/signal-ptr.cpp index b3a18cda3b44b6d6be7d21ab1a558d7711854ce0..a43ada93758650ff1ff8d4b951d66efedd62575a 100644 --- a/tests/signal-ptr.cpp +++ b/tests/signal-ptr.cpp @@ -20,66 +20,68 @@ using namespace dynamicgraph; using std::cout; -BOOST_AUTO_TEST_CASE(normal_test) -{ - Signal<double,int> sig("sig"); - SignalPtr<double,int> sigPtrA(NULL,"sigPtrA"),sigPtrB(NULL,"sigPtrB"); - SignalPtr<double,int> sigNotPlug(NULL,"sigNotPlug"); - SignalPtr<double,int> sigPtrAbstract(NULL,"sigPtrAbstract"); +BOOST_AUTO_TEST_CASE(normal_test) { + Signal<double, int> sig("sig"); + SignalPtr<double, int> sigPtrA(NULL, "sigPtrA"), sigPtrB(NULL, "sigPtrB"); + SignalPtr<double, int> sigNotPlug(NULL, "sigNotPlug"); + SignalPtr<double, int> sigPtrAbstract(NULL, "sigPtrAbstract"); try { - sigNotPlug.getPtr(); - } catch (ExceptionSignal e){ - cout << "Error catch" << std::endl; + sigNotPlug.getPtr(); + } catch (ExceptionSignal e) { + cout << "Error catch" << std::endl; } - sig.setConstant( 1.56 ); + sig.setConstant(1.56); sig.recompute(2); std::string name = "sig"; sig.getClassName(name); std::string test = "test"; try { - sig.getClassName(test); + sig.getClassName(test); } catch (ExceptionSignal e) { - e.getExceptionName(); + e.getExceptionName(); } + SignalBase<int> &sigRef = sig; + SignalBase<int> &sigPtrARef = sigPtrA, &sigPtrBRef = sigPtrB, &sigPtrAbstractRef = sigPtrAbstract; + sigPtrARef.plug(&sigRef); + sigPtrBRef.plug(&sigPtrARef); - - SignalBase<int> & sigRef = sig; - SignalBase<int> & sigPtrARef = sigPtrA, & sigPtrBRef = sigPtrB, & sigPtrAbstractRef = sigPtrAbstract; - sigPtrARef.plug( & sigRef ); - sigPtrBRef.plug( & sigPtrARef ); - - - //TODO here - sigPtrAbstractRef.plug( & sigRef); + // TODO here + sigPtrAbstractRef.plug(&sigRef); sigPtrA.getPtr(); sigPtrA.getPluged(); sigPtrB.getPtr(); sigPtrAbstract.getAbstractPtr(); - assert(sigRef.isPlugged()!=true); + assert(sigRef.isPlugged() != true); SignalBase<int> *t = sigRef.getPluged(); - //assert(sigPtrA.get()=false); + // assert(sigPtrA.get()=false); - //TODO Can't check if the constant change + // TODO Can't check if the constant change sigPtrA.setConstantDefault(1.2); - //getconstant + // getconstant sigPtrA.setConstantDefault(); - //getconstant + // getconstant sigPtrA.setConstant(3.4); - //getconstant + // getconstant double tab_D[2]; tab_D[0] = 1.2; tab_D[1] = 3.4; - sigPtrA.setReference(tab_D,NULL); - //getreference + sigPtrA.setReference(tab_D, NULL); + // getreference sigPtrA.operator=(1.2); - //getconstant + // getconstant - cout << t << std::endl; - cout << "Sig = "; sigRef.get(cout); cout << std::endl; - cout << "SigPtrA = "; sigPtrARef.get(cout); cout << std::endl; - cout << "SigPtrB = "; sigPtrBRef.get(cout); cout << std::endl; + cout << t << std::endl; + cout << "Sig = "; + sigRef.get(cout); + cout << std::endl; + cout << "SigPtrA = "; + sigPtrARef.get(cout); + cout << std::endl; + cout << "SigPtrB = "; + sigPtrBRef.get(cout); + cout << std::endl; } diff --git a/tests/signal-time-dependent.cpp b/tests/signal-time-dependent.cpp index 2f9efd7c593fb112421a998d7294c99a3110ac9f..cf84d31e6007b7994fabbceccad2e8a24a111a66 100644 --- a/tests/signal-time-dependent.cpp +++ b/tests/signal-time-dependent.cpp @@ -16,96 +16,73 @@ using boost::test_tools::output_test_stream; typedef dynamicgraph::SignalTimeDependent<double, int> sigDouble_t; typedef dynamicgraph::SignalTimeDependent<std::string, int> sigString_t; -template<class T> -class DummyClass -{ -public: - +template <class T> +class DummyClass { + public: std::string proname; std::list<sigDouble_t*> inputsig; std::list<sigString_t*> inputsigV; - DummyClass (const std::string& n) - : proname (n), - res (), - call (), - timedata () - {} + DummyClass(const std::string& n) : proname(n), res(), call(), timedata() {} - T& fun (T& res, int t) - { + T& fun(T& res, int t) { ++call; - timedata=t; + timedata = t; BOOST_FOREACH (sigDouble_t* ptr, inputsig) ptr->access(timedata); - BOOST_FOREACH (sigString_t* ptr, - inputsigV) + BOOST_FOREACH (sigString_t* ptr, inputsigV) ptr->access(timedata); - res = (*this) (); + res = (*this)(); return res; } - void add (sigDouble_t& sig) - { - inputsig.push_back (&sig); - } - void add (sigString_t& sig) - { - inputsigV.push_back (&sig); - } + void add(sigDouble_t& sig) { inputsig.push_back(&sig); } + void add(sigString_t& sig) { inputsigV.push_back(&sig); } - T operator() (); + T operator()(); T res; int call; int timedata; }; -template<> -double -DummyClass<double>::operator() () -{ - res=call * timedata; +template <> +double DummyClass<double>::operator()() { + res = call * timedata; return res; } -template<> -std::string -DummyClass<std::string>::operator() () -{ +template <> +std::string DummyClass<std::string>::operator()() { std::ostringstream oss; oss << call * timedata; - return oss.str (); + return oss.str(); } -template< class T > -T DummyClass<T>::operator() () -{ +template <class T> +T DummyClass<T>::operator()() { return this->res; } -BOOST_AUTO_TEST_CASE (signaltimedependent) -{ - DummyClass<double> pro1 ("pro1"), pro3 ("pro3"), pro5 ("pro5"); - DummyClass<std::string> pro2 ("pro2"), pro4 ("pro4"), pro6 ("pro6"); +BOOST_AUTO_TEST_CASE(signaltimedependent) { + DummyClass<double> pro1("pro1"), pro3("pro3"), pro5("pro5"); + DummyClass<std::string> pro2("pro2"), pro4("pro4"), pro6("pro6"); - sigDouble_t sig5 ("Sig5"); - sigString_t sig6 ("Sig6"); + sigDouble_t sig5("Sig5"); + sigString_t sig6("Sig6"); sigString_t sig4(sig5, "Sig4"); sigString_t sig2(sig4 << sig4 << sig4 << sig6, "Sig2"); sigDouble_t sig3(sig2 << sig5 << sig6, "Sig3"); - sigDouble_t sig1 - (boost::bind (&DummyClass<double>::fun, &pro1, _1, _2), - sig2 << sig3, "Sig1"); + sigDouble_t sig1(boost::bind(&DummyClass<double>::fun, &pro1, _1, _2), sig2 << sig3, "Sig1"); - sig2.setFunction (boost::bind (&DummyClass<std::string>::fun,&pro2, _1, _2)); - sig3.setFunction (boost::bind (&DummyClass<double>::fun,&pro3, _1, _2)); - sig4.setFunction (boost::bind (&DummyClass<std::string>::fun,&pro4, _1, _2)); - sig5.setFunction (boost::bind (&DummyClass<double>::fun,&pro5, _1, _2)); - sig6.setFunction (boost::bind (&DummyClass<std::string>::fun,&pro6, _1, _2)); + sig2.setFunction(boost::bind(&DummyClass<std::string>::fun, &pro2, _1, _2)); + sig3.setFunction(boost::bind(&DummyClass<double>::fun, &pro3, _1, _2)); + sig4.setFunction(boost::bind(&DummyClass<std::string>::fun, &pro4, _1, _2)); + sig5.setFunction(boost::bind(&DummyClass<double>::fun, &pro5, _1, _2)); + sig6.setFunction(boost::bind(&DummyClass<std::string>::fun, &pro6, _1, _2)); pro1.add(sig2); pro1.add(sig3); @@ -118,8 +95,8 @@ BOOST_AUTO_TEST_CASE (signaltimedependent) pro3.add(sig5); pro3.add(sig6); - sig5.setDependencyType (dynamicgraph::TimeDependency<int>::ALWAYS_READY); - sig6.setDependencyType (dynamicgraph::TimeDependency<int>::BOOL_DEPENDENT); + sig5.setDependencyType(dynamicgraph::TimeDependency<int>::ALWAYS_READY); + sig6.setDependencyType(dynamicgraph::TimeDependency<int>::BOOL_DEPENDENT); sig5.setPeriodTime(3); assert(sig5.getPeriodTime() == 3); @@ -128,120 +105,113 @@ BOOST_AUTO_TEST_CASE (signaltimedependent) { output_test_stream output; - sig1.displayDependencies (output); - BOOST_CHECK (output.is_equal - ("-- Sig:Sig1 (Type Fun) (t=0 (/1) )\n" - " |-- Sig:Sig3 (Type Fun) (t=0 (/1) )\n" - " | |-- Sig:Sig6 (Type Fun) (ready=TRUE)\n" - " | |-- Sig:Sig5 (Type Fun) (A)\n" - " | `-- Sig:Sig2 (Type Fun) (t=0 (/1) )\n" - " | |-- Sig:Sig6 (Type Fun) (ready=TRUE)\n" - " | |-- Sig:Sig4 (Type Fun) (t=0 (/1) )\n" - " | | `-- Sig:Sig5 (Type Fun) (A)\n" - " | |-- Sig:Sig4 (Type Fun) (t=0 (/1) )\n" - " | | `-- Sig:Sig5 (Type Fun) (A)\n" - " | `-- Sig:Sig4 (Type Fun) (t=0 (/1) )\n" - " | `-- Sig:Sig5 (Type Fun) (A)\n" - " `-- Sig:Sig2 (Type Fun) (t=0 (/1) )\n" - " |-- Sig:Sig6 (Type Fun) (ready=TRUE)\n" - " |-- Sig:Sig4 (Type Fun) (t=0 (/1) )\n" - " | `-- Sig:Sig5 (Type Fun) (A)\n" - " |-- Sig:Sig4 (Type Fun) (t=0 (/1) )\n" - " | `-- Sig:Sig5 (Type Fun) (A)\n" - " `-- Sig:Sig4 (Type Fun) (t=0 (/1) )\n" - " `-- Sig:Sig5 (Type Fun) (A)" - )); + sig1.displayDependencies(output); + BOOST_CHECK( + output.is_equal("-- Sig:Sig1 (Type Fun) (t=0 (/1) )\n" + " |-- Sig:Sig3 (Type Fun) (t=0 (/1) )\n" + " | |-- Sig:Sig6 (Type Fun) (ready=TRUE)\n" + " | |-- Sig:Sig5 (Type Fun) (A)\n" + " | `-- Sig:Sig2 (Type Fun) (t=0 (/1) )\n" + " | |-- Sig:Sig6 (Type Fun) (ready=TRUE)\n" + " | |-- Sig:Sig4 (Type Fun) (t=0 (/1) )\n" + " | | `-- Sig:Sig5 (Type Fun) (A)\n" + " | |-- Sig:Sig4 (Type Fun) (t=0 (/1) )\n" + " | | `-- Sig:Sig5 (Type Fun) (A)\n" + " | `-- Sig:Sig4 (Type Fun) (t=0 (/1) )\n" + " | `-- Sig:Sig5 (Type Fun) (A)\n" + " `-- Sig:Sig2 (Type Fun) (t=0 (/1) )\n" + " |-- Sig:Sig6 (Type Fun) (ready=TRUE)\n" + " |-- Sig:Sig4 (Type Fun) (t=0 (/1) )\n" + " | `-- Sig:Sig5 (Type Fun) (A)\n" + " |-- Sig:Sig4 (Type Fun) (t=0 (/1) )\n" + " | `-- Sig:Sig5 (Type Fun) (A)\n" + " `-- Sig:Sig4 (Type Fun) (t=0 (/1) )\n" + " `-- Sig:Sig5 (Type Fun) (A)")); } - BOOST_CHECK (sig1.needUpdate (2)); - sig1.access (2); + BOOST_CHECK(sig1.needUpdate(2)); + sig1.access(2); { output_test_stream output; - sig1.displayDependencies (output); - BOOST_CHECK (output.is_equal - ( - "-- Sig:Sig1 (Type Fun) (t=2 (/1) )\n" - " |-- Sig:Sig3 (Type Fun) (t=2 (/1) )\n" - " | |-- Sig:Sig6 (Type Fun) (ready=FALSE)\n" - " | |-- Sig:Sig5 (Type Fun) (A)\n" - " | `-- Sig:Sig2 (Type Fun) (t=2 (/1) )\n" - " | |-- Sig:Sig6 (Type Fun) (ready=FALSE)\n" - " | |-- Sig:Sig4 (Type Fun) (t=2 (/1) )\n" - " | | `-- Sig:Sig5 (Type Fun) (A)\n" - " | |-- Sig:Sig4 (Type Fun) (t=2 (/1) )\n" - " | | `-- Sig:Sig5 (Type Fun) (A)\n" - " | `-- Sig:Sig4 (Type Fun) (t=2 (/1) )\n" - " | `-- Sig:Sig5 (Type Fun) (A)\n" - " `-- Sig:Sig2 (Type Fun) (t=2 (/1) )\n" - " |-- Sig:Sig6 (Type Fun) (ready=FALSE)\n" - " |-- Sig:Sig4 (Type Fun) (t=2 (/1) )\n" - " | `-- Sig:Sig5 (Type Fun) (A)\n" - " |-- Sig:Sig4 (Type Fun) (t=2 (/1) )\n" - " | `-- Sig:Sig5 (Type Fun) (A)\n" - " `-- Sig:Sig4 (Type Fun) (t=2 (/1) )\n" - " `-- Sig:Sig5 (Type Fun) (A)" - )); + sig1.displayDependencies(output); + BOOST_CHECK( + output.is_equal("-- Sig:Sig1 (Type Fun) (t=2 (/1) )\n" + " |-- Sig:Sig3 (Type Fun) (t=2 (/1) )\n" + " | |-- Sig:Sig6 (Type Fun) (ready=FALSE)\n" + " | |-- Sig:Sig5 (Type Fun) (A)\n" + " | `-- Sig:Sig2 (Type Fun) (t=2 (/1) )\n" + " | |-- Sig:Sig6 (Type Fun) (ready=FALSE)\n" + " | |-- Sig:Sig4 (Type Fun) (t=2 (/1) )\n" + " | | `-- Sig:Sig5 (Type Fun) (A)\n" + " | |-- Sig:Sig4 (Type Fun) (t=2 (/1) )\n" + " | | `-- Sig:Sig5 (Type Fun) (A)\n" + " | `-- Sig:Sig4 (Type Fun) (t=2 (/1) )\n" + " | `-- Sig:Sig5 (Type Fun) (A)\n" + " `-- Sig:Sig2 (Type Fun) (t=2 (/1) )\n" + " |-- Sig:Sig6 (Type Fun) (ready=FALSE)\n" + " |-- Sig:Sig4 (Type Fun) (t=2 (/1) )\n" + " | `-- Sig:Sig5 (Type Fun) (A)\n" + " |-- Sig:Sig4 (Type Fun) (t=2 (/1) )\n" + " | `-- Sig:Sig5 (Type Fun) (A)\n" + " `-- Sig:Sig4 (Type Fun) (t=2 (/1) )\n" + " `-- Sig:Sig5 (Type Fun) (A)")); } - sig2.access (4); + sig2.access(4); { output_test_stream output; - sig1.displayDependencies (output); - BOOST_CHECK (output.is_equal - ( - "-- Sig:Sig1 (Type Fun) (t=2 (/1) )\n" - " |-- Sig:Sig3 (Type Fun) (t=2 (/1) )\n" - " | |-- Sig:Sig6 (Type Fun) (ready=FALSE)\n" - " | |-- Sig:Sig5 (Type Fun) (A)\n" - " | `-- Sig:Sig2 (Type Fun) (t=4 (/1) )\n" - " | |-- Sig:Sig6 (Type Fun) (ready=FALSE)\n" - " | |-- Sig:Sig4 (Type Fun) (t=4 (/1) )\n" - " | | `-- Sig:Sig5 (Type Fun) (A)\n" - " | |-- Sig:Sig4 (Type Fun) (t=4 (/1) )\n" - " | | `-- Sig:Sig5 (Type Fun) (A)\n" - " | `-- Sig:Sig4 (Type Fun) (t=4 (/1) )\n" - " | `-- Sig:Sig5 (Type Fun) (A)\n" - " `-- Sig:Sig2 (Type Fun) (t=4 (/1) )\n" - " |-- Sig:Sig6 (Type Fun) (ready=FALSE)\n" - " |-- Sig:Sig4 (Type Fun) (t=4 (/1) )\n" - " | `-- Sig:Sig5 (Type Fun) (A)\n" - " |-- Sig:Sig4 (Type Fun) (t=4 (/1) )\n" - " | `-- Sig:Sig5 (Type Fun) (A)\n" - " `-- Sig:Sig4 (Type Fun) (t=4 (/1) )\n" - " `-- Sig:Sig5 (Type Fun) (A)" - )); + sig1.displayDependencies(output); + BOOST_CHECK( + output.is_equal("-- Sig:Sig1 (Type Fun) (t=2 (/1) )\n" + " |-- Sig:Sig3 (Type Fun) (t=2 (/1) )\n" + " | |-- Sig:Sig6 (Type Fun) (ready=FALSE)\n" + " | |-- Sig:Sig5 (Type Fun) (A)\n" + " | `-- Sig:Sig2 (Type Fun) (t=4 (/1) )\n" + " | |-- Sig:Sig6 (Type Fun) (ready=FALSE)\n" + " | |-- Sig:Sig4 (Type Fun) (t=4 (/1) )\n" + " | | `-- Sig:Sig5 (Type Fun) (A)\n" + " | |-- Sig:Sig4 (Type Fun) (t=4 (/1) )\n" + " | | `-- Sig:Sig5 (Type Fun) (A)\n" + " | `-- Sig:Sig4 (Type Fun) (t=4 (/1) )\n" + " | `-- Sig:Sig5 (Type Fun) (A)\n" + " `-- Sig:Sig2 (Type Fun) (t=4 (/1) )\n" + " |-- Sig:Sig6 (Type Fun) (ready=FALSE)\n" + " |-- Sig:Sig4 (Type Fun) (t=4 (/1) )\n" + " | `-- Sig:Sig5 (Type Fun) (A)\n" + " |-- Sig:Sig4 (Type Fun) (t=4 (/1) )\n" + " | `-- Sig:Sig5 (Type Fun) (A)\n" + " `-- Sig:Sig4 (Type Fun) (t=4 (/1) )\n" + " `-- Sig:Sig5 (Type Fun) (A)")); } - sig1.access (4); + sig1.access(4); { output_test_stream output; - sig1.displayDependencies (output); - BOOST_CHECK (output.is_equal - ( - "-- Sig:Sig1 (Type Fun) (t=4 (/1) )\n" - " |-- Sig:Sig3 (Type Fun) (t=4 (/1) )\n" - " | |-- Sig:Sig6 (Type Fun) (ready=FALSE)\n" - " | |-- Sig:Sig5 (Type Fun) (A)\n" - " | `-- Sig:Sig2 (Type Fun) (t=4 (/1) )\n" - " | |-- Sig:Sig6 (Type Fun) (ready=FALSE)\n" - " | |-- Sig:Sig4 (Type Fun) (t=4 (/1) )\n" - " | | `-- Sig:Sig5 (Type Fun) (A)\n" - " | |-- Sig:Sig4 (Type Fun) (t=4 (/1) )\n" - " | | `-- Sig:Sig5 (Type Fun) (A)\n" - " | `-- Sig:Sig4 (Type Fun) (t=4 (/1) )\n" - " | `-- Sig:Sig5 (Type Fun) (A)\n" - " `-- Sig:Sig2 (Type Fun) (t=4 (/1) )\n" - " |-- Sig:Sig6 (Type Fun) (ready=FALSE)\n" - " |-- Sig:Sig4 (Type Fun) (t=4 (/1) )\n" - " | `-- Sig:Sig5 (Type Fun) (A)\n" - " |-- Sig:Sig4 (Type Fun) (t=4 (/1) )\n" - " | `-- Sig:Sig5 (Type Fun) (A)\n" - " `-- Sig:Sig4 (Type Fun) (t=4 (/1) )\n" - " `-- Sig:Sig5 (Type Fun) (A)" - )); + sig1.displayDependencies(output); + BOOST_CHECK( + output.is_equal("-- Sig:Sig1 (Type Fun) (t=4 (/1) )\n" + " |-- Sig:Sig3 (Type Fun) (t=4 (/1) )\n" + " | |-- Sig:Sig6 (Type Fun) (ready=FALSE)\n" + " | |-- Sig:Sig5 (Type Fun) (A)\n" + " | `-- Sig:Sig2 (Type Fun) (t=4 (/1) )\n" + " | |-- Sig:Sig6 (Type Fun) (ready=FALSE)\n" + " | |-- Sig:Sig4 (Type Fun) (t=4 (/1) )\n" + " | | `-- Sig:Sig5 (Type Fun) (A)\n" + " | |-- Sig:Sig4 (Type Fun) (t=4 (/1) )\n" + " | | `-- Sig:Sig5 (Type Fun) (A)\n" + " | `-- Sig:Sig4 (Type Fun) (t=4 (/1) )\n" + " | `-- Sig:Sig5 (Type Fun) (A)\n" + " `-- Sig:Sig2 (Type Fun) (t=4 (/1) )\n" + " |-- Sig:Sig6 (Type Fun) (ready=FALSE)\n" + " |-- Sig:Sig4 (Type Fun) (t=4 (/1) )\n" + " | `-- Sig:Sig5 (Type Fun) (A)\n" + " |-- Sig:Sig4 (Type Fun) (t=4 (/1) )\n" + " | `-- Sig:Sig5 (Type Fun) (A)\n" + " `-- Sig:Sig4 (Type Fun) (t=4 (/1) )\n" + " `-- Sig:Sig5 (Type Fun) (A)")); } - sig1.needUpdate (6); - sig1.needUpdate (6); + sig1.needUpdate(6); + sig1.needUpdate(6); } diff --git a/tests/test-mt.cpp b/tests/test-mt.cpp index 059ea2a456d6bcacb2465116a9568208a68b6635..85aee889f31f12513825339ac00efc369aecf3d8 100644 --- a/tests/test-mt.cpp +++ b/tests/test-mt.cpp @@ -9,27 +9,23 @@ #include <unistd.h> #include <dynamic-graph/process-list.hh> -#define BOOST_TEST_MODULE debug-trace +#define BOOST_TEST_MODULE debug - trace #include <boost/test/unit_test.hpp> #include <boost/test/output_test_stream.hpp> using boost::test_tools::output_test_stream; - -BOOST_AUTO_TEST_CASE(testMt) -{ +BOOST_AUTO_TEST_CASE(testMt) { dynamicgraph::CPU::System aSystem; - + // create and open a character archive for output std::ofstream ofs("cpu_state.dat"); boost::archive::text_oarchive oa(ofs); oa << aSystem; - - for(unsigned int i=0;i<10;i++) - { - usleep(100000); - aSystem.readProcStat(); - } -} + for (unsigned int i = 0; i < 10; i++) { + usleep(100000); + aSystem.readProcStat(); + } +} diff --git a/tests/value.cpp b/tests/value.cpp index ca4855c9192da292121562c5b0c16771be5d533b..5e0a3faa4e776ea81d5a66fbe09582f4df6d3ca5 100644 --- a/tests/value.cpp +++ b/tests/value.cpp @@ -11,8 +11,7 @@ using boost::test_tools::output_test_stream; -BOOST_AUTO_TEST_CASE (value_string) -{ +BOOST_AUTO_TEST_CASE(value_string) { using dynamicgraph::command::Value; std::string str1("value #1"); @@ -22,13 +21,13 @@ BOOST_AUTO_TEST_CASE (value_string) { output_test_stream output; output << value1; - BOOST_CHECK (output.is_equal ("Type=string, value=value #1")); + BOOST_CHECK(output.is_equal("Type=string, value=value #1")); } { output_test_stream output; output << value; - BOOST_CHECK (output.is_equal ("Type=string, value=value #1")); + BOOST_CHECK(output.is_equal("Type=string, value=value #1")); } std::string str2("value #2"); @@ -38,12 +37,12 @@ BOOST_AUTO_TEST_CASE (value_string) { output_test_stream output; output << value2; - BOOST_CHECK (output.is_equal ("Type=string, value=value #2")); + BOOST_CHECK(output.is_equal("Type=string, value=value #2")); } { output_test_stream output; output << value; - BOOST_CHECK (output.is_equal ("Type=string, value=value #2")); + BOOST_CHECK(output.is_equal("Type=string, value=value #2")); } }