diff --git a/.clang-format b/.clang-format new file mode 100644 index 0000000000000000000000000000000000000000..0e604820773c04698431630e32e8051bdfe2d4c5 --- /dev/null +++ b/.clang-format @@ -0,0 +1,3 @@ +--- +ColumnLimit: 80 +... diff --git a/doc/additionalDoc/debug-doc.h b/doc/additionalDoc/debug-doc.h index b26b6102f6a8220ed21a086146aa4362bc386bef..7028e278e969bef31ff68e5adfeea5e16d227ddb 100644 --- a/doc/additionalDoc/debug-doc.h +++ b/doc/additionalDoc/debug-doc.h @@ -1,15 +1,18 @@ /** \page debug Debugging -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. -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 -- If you just need to collect informations from signals (like rosbag). You can use -an entity called Tracer inside the graph:\subpage tracerdoc . <br> -A real time version exists -to write directly inside a memory buffer \subpage tracerrealtimedoc +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. 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 +- If you just need to collect informations from signals (like rosbag). You can +use an entity called Tracer inside the graph:\subpage tracerdoc . <br> A real +time version exists to write directly inside a memory buffer \subpage +tracerrealtimedoc **/ diff --git a/doc/additionalDoc/debug-logger.h b/doc/additionalDoc/debug-logger.h index c67da3078c1484323701109d53471f5af12bf2a2..18a042a6cbd112d749f1f53e47a9e25dec8faf9a 100644 --- a/doc/additionalDoc/debug-logger.h +++ b/doc/additionalDoc/debug-logger.h @@ -8,8 +8,8 @@ In order to activate the logger you need to add the following lines: \code #define ENABLE_RT_LOG -#include <dynamic-graph/real-time-logger.h> #include <dynamic-graph/logger.h> +#include <dynamic-graph/real-time-logger.h> \endcode \subsection subsec_logger_ Initialize the output stream @@ -39,14 +39,16 @@ The second line specifies at which frequency the STREAM messages should be printed.<br> The third line specifies the level of message to accept.<br> The fourth line returns the level of verbosity. -In this case, all messages are accepted and the STREAM message are displayed on the output streams once on five. <br> +In this case, all messages are accepted and the STREAM message are displayed on +the output streams once on five. <br> The full list of options are: <ul> <li>VERBOSITY_ALL: Accept all messages</li> -<li>VERBOSITY_INFO_WARNING_ERROR: Accept messages at minimum level : INFO, WARNING, ERROR</li> -<li>VERBOSITY_WARNING_ERROR: Accept messages at minimum level : WARNING, ERROR</li> -<li>VERBOSITY_ERROR: Accept messages at minimum level : ERROR</li> +<li>VERBOSITY_INFO_WARNING_ERROR: Accept messages at minimum level : INFO, +WARNING, ERROR</li> <li>VERBOSITY_WARNING_ERROR: Accept messages at minimum +level : WARNING, ERROR</li> <li>VERBOSITY_ERROR: Accept messages at minimum +level : ERROR</li> </ul> @@ -54,19 +56,23 @@ The full list of options are: Here is some example on how to display or record some information. \code - sendMsg("This is a message of level MSG_TYPE_DEBUG",MSG_TYPE_DEBUG, __FILE__,__LINE__); - sendMsg("This is a message of level MSG_TYPE_INFO",MSG_TYPE_INFO, __FILE__,__LINE__); - sendMsg("This is a message of level MSG_TYPE_WARNING",MSG_TYPE_WARNING, __FILE__,__LINE__); - sendMsg("This is a message of level MSG_TYPE_ERROR",MSG_TYPE_ERROR, __FILE__,__LINE__); - sendMsg("This is a message of level MSG_TYPE_DEBUG_STREAM",MSG_TYPE_DEBUG_STREAM, __FILE__,__LINE__); - sendMsg("This is a message of level MSG_TYPE_INFO_STREAM",MSG_TYPE_INFO_STREAM, __FILE__,__LINE__); - sendMsg("This is a message of level MSG_TYPE_WARNING_STREAM",MSG_TYPE_WARNING_STREAM, __FILE__,__LINE__); - sendMsg("This is a message of level MSG_TYPE_ERROR_STREAM",MSG_TYPE_ERROR_STREAM, __FILE__,__LINE__); + sendMsg("This is a message of level MSG_TYPE_DEBUG",MSG_TYPE_DEBUG, +__FILE__,__LINE__); sendMsg("This is a message of level +MSG_TYPE_INFO",MSG_TYPE_INFO, __FILE__,__LINE__); sendMsg("This is a message of +level MSG_TYPE_WARNING",MSG_TYPE_WARNING, __FILE__,__LINE__); sendMsg("This is a +message of level MSG_TYPE_ERROR",MSG_TYPE_ERROR, __FILE__,__LINE__); + sendMsg("This is a message of level +MSG_TYPE_DEBUG_STREAM",MSG_TYPE_DEBUG_STREAM, __FILE__,__LINE__); sendMsg("This +is a message of level MSG_TYPE_INFO_STREAM",MSG_TYPE_INFO_STREAM, +__FILE__,__LINE__); sendMsg("This is a message of level +MSG_TYPE_WARNING_STREAM",MSG_TYPE_WARNING_STREAM, __FILE__,__LINE__); + sendMsg("This is a message of level +MSG_TYPE_ERROR_STREAM",MSG_TYPE_ERROR_STREAM, __FILE__,__LINE__); 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 -the counting will be confused. +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-trace-doc.h b/doc/additionalDoc/debug-trace-doc.h index d977b79dda0a8962c9eb6236b33a3e6f729095b5..8900be96400c4044f0829d906ceeef4c7daa7dd2 100644 --- a/doc/additionalDoc/debug-trace-doc.h +++ b/doc/additionalDoc/debug-trace-doc.h @@ -3,10 +3,10 @@ \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 -is wasted in condition test. You can therefore let the debugging messages -inside the code without impact on performances. +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. \section subp_dbg_trace_set_on_macros Setting up dgDEBUG macros @@ -31,12 +31,9 @@ are written is specified by: \section subp_dbg_trace_using_macros Using dgDEBUG macros -To print that the beginning of a method is being executed use the following macros: -\code - dgDEBUGIN(5); -\endcode -5 here specifies the minimum level that you be specified by VP_DEBUG_MODE for this message -to be displayed. +To print that the beginning of a method is being executed use the following +macros: \code dgDEBUGIN(5); \endcode 5 here specifies the minimum level that you +be specified by VP_DEBUG_MODE for this message to be displayed. It will generate the following output: \code @@ -62,8 +59,8 @@ A message inside the code is written through: This generates the following output: \code -/path_to/dynamic-graph/tests/debug-trace.cpp: testDebugTrace(#52) :Here is a test -\endcode +/path_to/dynamic-graph/tests/debug-trace.cpp: testDebugTrace(#52) :Here is a +test \endcode \section subp_dbg_trace_wrk_exp Working example diff --git a/doc/additionalDoc/entity.h b/doc/additionalDoc/entity.h index f08e5a76eae4645e9e6d2c8847540de544659b6e..70b3ea87fffc497a56d9c4ea0ff09389b9451bc4 100644 --- a/doc/additionalDoc/entity.h +++ b/doc/additionalDoc/entity.h @@ -5,45 +5,57 @@ \subsection entity_definition General definition \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 +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. +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). +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). \subsection entities List of entities in this package Since most of the functionality in projects using the dynamic-graph framework -is exposed from entities, here is a short description of all the entities contained in -this package. Note that most entities are contained in a binary file that closely matches -the entities' names in the scripts; loading this file with the plugin loader will -enable creation of this entity through the factory. +is exposed from entities, here is a short description of all the entities +contained in this package. Note that most entities are contained in a binary +file that closely matches the entities' names in the scripts; loading this file +with the plugin loader will enable creation of this entity through the factory. \li \ref tracerdoc \li \ref tracerrealtimedoc \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 +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 568e3f8de7ad1446a6e92e608e14a8d0fe7b0812..f8f639bb15c1dcd80800d790979adc7fa36ddf98 100644 --- a/doc/additionalDoc/extension.h +++ b/doc/additionalDoc/extension.h @@ -5,21 +5,24 @@ \subsection use_programmatically General introduction -For control purposes the main use of this package is to create new entities and connect them through signals. +For control purposes the main use of this package is to create new entities and +connect them through signals. -Objects, which are derived from Entities (base class dynamicgraph::Entity), can be -declared within the code and compiled as shared libraries (.so/.dll files). +Objects, which are derived from Entities (base class dynamicgraph::Entity), can +be 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 +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 -(see PoolStorage documentation). Basic commands defined by entities include +register them in the Pool. From the pool they can be listed, accessed, and acted +upon (see PoolStorage documentation). Basic commands defined by entities include signal connection graph file generation, help and name print, and signals. This is usually done through a scripting language such as python (see -<a hef="https://github.com/stack-of-tasks/dynamic-graph-python">dynamic-graph-python</a>) +<a +hef="https://github.com/stack-of-tasks/dynamic-graph-python">dynamic-graph-python</a>) The singletons made available by including the corresponding headers in this module are: @@ -30,13 +33,15 @@ For an example of a program creating entities in C++, see the unit test test_pool.cpp (in your package source directory/tests). \subsection Tutorial -A tutorial is available <a href="http://stack-of-tasks.github.io/dynamic-graph-tutorial/">here</a>. -It is providing a step-by-step way of building an entity +A tutorial is available <a +href="http://stack-of-tasks.github.io/dynamic-graph-tutorial/">here</a>. It is +providing a step-by-step way of building an entity \section sec_htw_helpers Helpers -When writing entities you might use some macros which are very useful to write your class. +When writing entities you might use some macros which are very useful to write +your class. \subsection subsec_howto_typedef Entity helpers @@ -48,13 +53,13 @@ The header <b>entity-helper.h</b> is defining a type called EntityClassName <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. + 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> <b>DYNAMICGRAPH_FACTORY_ENTITY_PLUGIN(classtype,classname)</b> - 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. + 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> </ul> @@ -64,15 +69,12 @@ The header <b>entity-helper.h</b> is defining a type called EntityClassName <li> Macro for input signals <ul> <li> <b>DECLARE_SIGNAL_IN(signal_name,type)</b>: - Declare an input time dependent signal as a field of the class with the following name: - \code - m_signal_nameSIN - \endcode + Declare an input time dependent signal as a field of the class with the +following name: \code m_signal_nameSIN \endcode </li> <li> <b>CONSTRUCT_SIGNAL_IN(signal_name,type)</b>: - This macro is used in the constructor of the entity class handling this signal. - It is calling the signal constructor and set the signal name to: - \code + This macro is used in the constructor of the entity class handling this +signal. It is calling the signal constructor and set the signal name to: \code EntityClassName(entity-name)::input(type)::signal_name \endcode </ul> @@ -80,32 +82,24 @@ The header <b>entity-helper.h</b> is defining a type called EntityClassName <li> Macro for output signals <ul> <li> <b>DECLARE_SIGNAL_OUT(signal_name,type)</b>: - Declare an output time dependent signal as a field of the class with the following name: - \code - m_signal_nameSOUT - \endcode - It also declares a method with the following pattern: - \code - type signal_nameSOUT_function(type &,int) - \endcode + Declare an output time dependent signal as a field of the class with the +following name: \code m_signal_nameSOUT \endcode It also declares a method with +the following pattern: \code type signal_nameSOUT_function(type &,int) \endcode The second pattern is the time when calling the output. </li> <li> <b>CONSTRUCT_SIGNAL_OUT(signal_name,type)</b> - This macro is used in the constructor of the entity class handling this signal. - It creates the binding to the method described previously, and set the signal name to: - \code - EntityClassName(entity_name)::output(type)::signal_name + This macro is used in the constructor of the entity class handling this +signal. It creates the binding to the method described previously, and set the +signal name to: \code EntityClassName(entity_name)::output(type)::signal_name \endcode where entity_name is the name of the entity currently instanciated. </li> <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 - with the following pattern: - \code - type EntityClassName::signal_nameSOUT_function(type &, int iter) - \endcode + 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 with the following pattern: \code type +EntityClassName::signal_nameSOUT_function(type &, int iter) \endcode </li> </ul> @@ -113,8 +107,8 @@ The header <b>entity-helper.h</b> is defining a type called EntityClassName </li> Inner signals <ul> <li> <b> DECLARE_SIGNAL_INNER(signal_name,type)</b> - Inner signal are signal that depend on a state of the entity and not on input signals. - This macro declares an inner signal with the following pattern: + Inner signal are signal that depend on a state of the entity and not on +input signals. This macro declares an inner signal with the following pattern: \code m_signal_nameSINNER \endcode @@ -124,11 +118,13 @@ The header <b>entity-helper.h</b> is defining a type called EntityClassName \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 - it provides the header of the member function(i.e. method) declaration. + 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> - This macros declares the member function used to handle the access to this signal. + This macros declares the member function used to handle the access to this +signal. </li> </ul> </ul> diff --git a/doc/additionalDoc/factory.h b/doc/additionalDoc/factory.h index baa92f46f1bd709cf7651e348a7383e2dfce1b5f..8fe178fb7685094b68ab884e67b47649d6bf14f2 100644 --- a/doc/additionalDoc/factory.h +++ b/doc/additionalDoc/factory.h @@ -2,6 +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 4b013a88e2fb0e7d441d5927d2b9548a346b37ff..0d415a9f7b392b9caa78a0d77db9485fa967657e 100644 --- a/doc/additionalDoc/graph.h +++ b/doc/additionalDoc/graph.h @@ -6,14 +6,16 @@ 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. +- 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. - the instances of node are handled through a pool \subpage subp_pool 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. +See <c>dynamic-graph-python</c> for more information on binding dynamic-graph +with Python. It is possible to display the graph of entities \subpage writegraphdoc diff --git a/doc/additionalDoc/installation.h b/doc/additionalDoc/installation.h index e0e14605b369c7039885fa9f272b39751dd0c8dc..bad2f0ced8533cb7b783cd6899c126ee8e58fc5f 100644 --- a/doc/additionalDoc/installation.h +++ b/doc/additionalDoc/installation.h @@ -13,7 +13,8 @@ dynamic-graph depends on: \section sec_inst_get_src Getting the source The sources are available through github at the following URL: -<a href="https://github.com/stack-of-tasks/dynamic-graph">https://github.com/stack-of-tasks/dynamic-graph</a> +<a +href="https://github.com/stack-of-tasks/dynamic-graph">https://github.com/stack-of-tasks/dynamic-graph</a> To clone: \code diff --git a/doc/additionalDoc/introduction.h b/doc/additionalDoc/introduction.h index c24ac33aebb46581eae5bfd359dbe2af47587357..0d749619f1b0d477c782f4481d099272bc719ad1 100644 --- a/doc/additionalDoc/introduction.h +++ b/doc/additionalDoc/introduction.h @@ -3,63 +3,65 @@ \section intro_dynamicGraph Introduction The dynamic-graph package is used to connect computation nodes, "entities" -together using a graph system, akin to what Simulink does. Entities are connected -through input and output signals. -With the building blocks this package provides, you can easily create a full computation graph -for a given problem. It is the basis for the stack of tasks operation. +together using a graph system, akin to what Simulink does. Entities are +connected through input and output signals. With the building blocks this +package provides, you can easily create a full computation graph for a given +problem. It is the basis for the stack of tasks operation. \subsection controlgraph Exemple: Real-time control -<p>To give a more concrete example, the real-time control used by the Gepetto group for the humanoid robot HRP-2 -is detailled.</p> -<p> -Real-time control system are usually driven by a cyclic computational node which -needs to send a control reference value to each motors of a robot. To compute this -control reference values, sensor values need to be provided. -In the Stack-Of-Tasks special entities called Device are used to -provide an abstract interface to the hardware.</p> -A scheme of the real-time control graph used for the humanoid robot HRP-2 is depicted in the following figure: +<p>To give a more concrete example, the real-time control used by the Gepetto +group for the humanoid robot HRP-2 is detailled.</p> <p> Real-time control +system are usually driven by a cyclic computational node which needs to send a +control reference value to each motors of a robot. To compute this control +reference values, sensor values need to be provided. In the Stack-Of-Tasks +special entities called Device are used to provide an abstract interface to the +hardware.</p> A scheme of the real-time control graph used for the humanoid +robot HRP-2 is depicted in the following figure: \image html Concept-Software-Fig.png -You can find an example of a real example of control graph at \ref writegraphdoc. +You can find an example of a real example of control graph at \ref +writegraphdoc. -<p>The device therefore has a specific input which should contain the control vector. -This control vector is the result of a computation solving a control problem. -The entity in charge of solving this control problem is called "Solver" in the previous -figure. -In the SoT framework it is often cast as an optimization problem. -This optimization problem is build using a control "Task" (not to be confused with the -general word task). A control "Task" regulates the difference with a "Feature" computed -on the current robot state and a "Desired Feature". For instance when walking, the regulated -feature is the robot's Center-Of-Mass (CoM) position. The "Feature" is computed using a -library using the robot model and the sensor value. The entity making this computation is "Dyn". -A walking pattern generator using foot-steps position given in advance generates the desired -value for the CoM. -Note that the "Dyn" entity uses the sensor provided by the entity "Robot". </p> +<p>The device therefore has a specific input which should contain the control +vector. This control vector is the result of a computation solving a control +problem. The entity in charge of solving this control problem is called "Solver" +in the previous figure. In the SoT framework it is often cast as an optimization +problem. This optimization problem is build using a control "Task" (not to be +confused with the general word task). A control "Task" regulates the difference +with a "Feature" computed on the current robot state and a "Desired Feature". +For instance when walking, the regulated feature is the robot's Center-Of-Mass +(CoM) position. The "Feature" is computed using a library using the robot model +and the sensor value. The entity making this computation is "Dyn". A walking +pattern generator using foot-steps position given in advance generates the +desired value for the CoM. Note that the "Dyn" entity uses the sensor provided +by the entity "Robot". </p> <p> -From a pure computer science viewpoint we wish to avoid recomputing data such as articular Jacobians -when this is unnecessary. Therefore the data generated by an entity through signals may have two types of -dependencies: one dependency related to time and dependencies on other signals. Internally an entity -does not recompute the data if no new information is available, it is simply providing the same information -computed before. Please note that this package provides only the computational framework to realize -the data dependency and the entities. Solvers, libraries to compute mechanical quantities are provided -in different packages. +From a pure computer science viewpoint we wish to avoid recomputing data such as +articular Jacobians when this is unnecessary. Therefore the data generated by an +entity through signals may have two types of dependencies: one dependency +related to time and dependencies on other signals. Internally an entity does not +recompute the data if no new information is available, it is simply providing +the same information computed before. Please note that this package provides +only the computational framework to realize the data dependency and the +entities. Solvers, libraries to compute mechanical quantities are provided in +different packages. </p> <p> -Finally in order to dynamically create a graph, it is possible \b on-line to load classes of entities and -create instances of entities.</p> +Finally in order to dynamically create a graph, it is possible \b on-line to +load classes of entities and create instances of entities.</p> \subsection Functionnalities \li Support for extensions and modules using dynamic link libraries \li Template-based signal definition, independent \li Type-safe connection of input and output signals -\li On-demand signal computation as well as a caching system for signal values allow fast -computation of signal values, which is a critical point for real-time systems\n -See \ref scriptingabout +\li On-demand signal computation as well as a caching system for signal values +allow fast computation of signal values, which is a critical point for real-time +systems\n See \ref scriptingabout */ diff --git a/doc/additionalDoc/package.h b/doc/additionalDoc/package.h index 76dd15c696d752952b878f04da695b3cc7cd4208..1deb6be9e9f96ac2089baf099dcf5dd0d9a80037 100644 --- a/doc/additionalDoc/package.h +++ b/doc/additionalDoc/package.h @@ -22,16 +22,19 @@ The software graph structure is detailled in \subpage p_graph For debugging your entities detailed instructions are given in \subpage debug -For citing the software in your research work please refer to \subpage subp_references +For citing the software in your research work please refer to \subpage +subp_references -\namespace dynamicgraph This is the namespace where every object and class of this library is located. +\namespace dynamicgraph This is the namespace where every object and class of +this library is located. \defgroup debug Debugging \defgroup dgraph Core classes and objects @{ -Classes, entities and binaries that make up the core of the dynamic-graph library are listed here. +Classes, entities and binaries that make up the core of the dynamic-graph +library are listed here. @} \defgroup signals Signals @@ -40,11 +43,13 @@ This part provides the mechanism to transfer information from one entity to another. There are three main types of signals, all deriving from the common class dynamicgraph::SignalBase : \li dynamicgraph::Signal : a "normal" signal, passing data around \b by \b value -\li dynamicgraph::SignalPtr : a signal used for efficient passing of large data, by reference (or rather, C pointers)* -\li dynamicgraph::SignalTimeDependent : a 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. +\li dynamicgraph::SignalPtr : a signal used for efficient passing of large data, +by reference (or rather, C pointers)* \li dynamicgraph::SignalTimeDependent : a +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. -\n* Note: this may cause a problem if this package is used in a multithreaded program. +\n* Note: this may cause a problem if this package is used in a multithreaded +program. Signals can be grouped together using dynamicgraph::SignalArray. @@ -54,8 +59,8 @@ For more information, please see the individual signal pages. \b Samples -\li The following code ensures the jacobian output signal uses up-to-date values for its -computations, when accessed. +\li The following code ensures the jacobian output signal uses up-to-date values +for its computations, when accessed. \code // This signal returns the Jacobian of the current value diff --git a/doc/additionalDoc/pool.h b/doc/additionalDoc/pool.h index f9dd0e020fd9e29ecfcd114a6a4b12edb45fe6f4..71eada05a900bdda6515c8fb42f34ab4a3b33f02 100644 --- a/doc/additionalDoc/pool.h +++ b/doc/additionalDoc/pool.h @@ -1,8 +1,9 @@ /** \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 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. */ diff --git a/doc/additionalDoc/references.h b/doc/additionalDoc/references.h index 5ed2b2e4d35a888a2d9054c14358ec9b26a6bc22..77731671854336a16a1f217fdfc6cc670bc7b5bb 100644 --- a/doc/additionalDoc/references.h +++ b/doc/additionalDoc/references.h @@ -7,8 +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/doc/additionalDoc/signal.h b/doc/additionalDoc/signal.h index 69f5a24a52509a7a5103e3cfa75299e483c70ac0..65fe829a33c1d7ef6882bac18f22626c7d8ddec5 100644 --- a/doc/additionalDoc/signal.h +++ b/doc/additionalDoc/signal.h @@ -2,11 +2,10 @@ \page subp_signals Signals \section sec_sigintro Signals -Entities can output different types of signals. To guarante real-time perforamces, signals are implemented -using C++ and mecanism which have a low time foot-print. -All signals are templated by a Time -tick type parameter (which is used in the caching of signals) - usually \c int. Signals -are also templated after the type of data they accept or provide. For example: -(example) -For a more detailed programmer-oriented description of signals, please see \ref signals +Entities can output different types of signals. To guarante real-time +perforamces, signals are implemented using C++ and mecanism which have a low +time foot-print. All signals are templated by a Time tick type parameter (which +is used in the caching of signals) - usually \c int. Signals are also templated +after the type of data they accept or provide. For example: (example) For a more +detailed programmer-oriented description of signals, please see \ref signals */ diff --git a/doc/additionalDoc/tracer-real-timedoc.h b/doc/additionalDoc/tracer-real-timedoc.h index 7a9cf1b2fdaa2be814d997653ac61f753303d526..dffba997dac299ef385f4af4a16855c1a452c1d7 100644 --- a/doc/additionalDoc/tracer-real-timedoc.h +++ b/doc/additionalDoc/tracer-real-timedoc.h @@ -2,9 +2,9 @@ \page tracerrealtimedoc TracerRealTime \section tracerrealtimedoc_description Description -The \b TracerRealTime entity monitors a set of signals with real-time constraints; its -function is very similar to the Tracer, except that all traces are recorded to a -memory buffer, which can be emptied at any time. +The \b TracerRealTime entity monitors a set of signals with real-time +constraints; its function is very similar to the Tracer, except that all traces +are recorded to a memory buffer, which can be emptied at any time. \section tracerrealtimedoc_commands Commands The \b commands that this entity exposes are: diff --git a/doc/additionalDoc/tracerdoc.h b/doc/additionalDoc/tracerdoc.h index 15e0e9b3d1e494c436e9c1c9a3c8597ea0745981..4490d446a5b22c68832df4231f132a15b46acbe2 100644 --- a/doc/additionalDoc/tracerdoc.h +++ b/doc/additionalDoc/tracerdoc.h @@ -1,10 +1,11 @@ /** \page tracerdoc Tracer \section tracerdoc_description Description -The \b Tracer entity monitors a set of signals. With an input change on the entity's [trigger] signal, -the tracked signal values are recorded and traced to a file. The behavior of the trace-to-file -function can be changed, from printing to a file immediately after recording, to printing out -only when asked explicitly. +The \b Tracer entity monitors a set of signals. With an input change on the +entity's [trigger] signal, the tracked signal values are recorded and traced to +a file. The behavior of the trace-to-file function can be changed, from printing +to a file immediately after recording, to printing out only when asked +explicitly. \section tracerdoc_commands Commands The \b commands that this entity exposes are: diff --git a/doc/additionalDoc/writeGraph.h b/doc/additionalDoc/writeGraph.h index ab9b4e8bae1613c7c6a3d229a97842b118728ba2..a09c683036ec6dc9badce9882ddd52f72949a777 100644 --- a/doc/additionalDoc/writeGraph.h +++ b/doc/additionalDoc/writeGraph.h @@ -21,6 +21,7 @@ It provides the following output: \section fromdottojs Viewing in a browser To view the dot file you can simply use the view_sot_dg.html file. -Click on the "Choose File" to specify the filem and click on "Rendering" to display the graph. +Click on the "Choose File" to specify the filem and click on "Rendering" to +display the graph. */ diff --git a/include/dynamic-graph/all-commands.h b/include/dynamic-graph/all-commands.h index d32ddf374c4a1ab43e3e9dce36eb6f0084d6cc6e..7d34f8ccf52d996b676e6f6b984d69ebe92ea8a5 100644 --- a/include/dynamic-graph/all-commands.h +++ b/include/dynamic-graph/all-commands.h @@ -12,7 +12,7 @@ #include <dynamic-graph/command-direct-getter.h> #include <dynamic-graph/command-direct-setter.h> #include <dynamic-graph/command-getter.h> -#include <dynamic-graph/command.h> #include <dynamic-graph/command-setter.h> +#include <dynamic-graph/command.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 56b460c12e3fc8f9b557834b238e06e556edd4f0..d694ae3d9655cde6c9aa4e1f2bf89c283e59e3c9 100644 --- a/include/dynamic-graph/all-signals.h +++ b/include/dynamic-graph/all-signals.h @@ -8,8 +8,8 @@ // 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> -#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 0702fb2ec9e01851e32e5a26b0014868c24a83d5..2c3278fba2e54e49ba40c0f14cb3fa74814fe4a8 100644 --- a/include/dynamic-graph/command-bind.h +++ b/include/dynamic-graph/command-bind.h @@ -22,455 +22,401 @@ #include "dynamic-graph/command.h" #include <boost/assign/list_of.hpp> -#include <boost/function.hpp> #include <boost/bind.hpp> +#include <boost/function.hpp> /* --- 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 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 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 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&)> +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 + 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 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 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__ diff --git a/include/dynamic-graph/command-direct-getter.h b/include/dynamic-graph/command-direct-getter.h index d6f826ea3e6a70f715653a6aab68f81ef2fb5f57..885718ae27a0e55d7df9d89e64a23cb28c311c84 100644 --- a/include/dynamic-graph/command-direct-getter.h +++ b/include/dynamic-graph/command-direct-getter.h @@ -19,45 +19,38 @@ #include <boost/assign/list_of.hpp> /* --- 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 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__ diff --git a/include/dynamic-graph/command-direct-setter.h b/include/dynamic-graph/command-direct-setter.h index 2f04256588bac67e496d24eff34c517b134d88c2..2765fa780b6ef901ba334ddc60b0d8065257f02e 100644 --- a/include/dynamic-graph/command-direct-setter.h +++ b/include/dynamic-graph/command-direct-setter.h @@ -19,47 +19,41 @@ #include <boost/assign/list_of.hpp> /* --- 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 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__ diff --git a/include/dynamic-graph/command-getter.h b/include/dynamic-graph/command-getter.h index d0b5cda3c82fd56e6fc9f43d86ce1540d49cfea0..beee09ee167eb8a55c33192f6f2390558a489f3f 100644 --- a/include/dynamic-graph/command-getter.h +++ b/include/dynamic-graph/command-getter.h @@ -41,22 +41,21 @@ namespace command { /// \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: +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); + Getter(E &entity, GetterMethod getterMethod, const std::string &docString); - protected: +protected: virtual Value doExecute(); - private: +private: GetterMethod getterMethod_; }; -} // namespace command -} // namespace dynamicgraph +} // 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 a3e024110af05bbafd4b2ac14483f0487b08b748..767166820ab156b0f418c95d8b9d9d998088fdbc 100644 --- a/include/dynamic-graph/command-getter.t.cpp +++ b/include/dynamic-graph/command-getter.t.cpp @@ -9,28 +9,22 @@ #include <sstream> -namespace dynamicgraph -{ - 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> - Value Getter<E, T>::doExecute() - { - E& entity = static_cast<E&>(owner()); - T value = (entity.*getterMethod_)(); - return Value(value); - } - } // namespace command -} // namespace dynamicgraph +namespace dynamicgraph { +class Entity; +namespace command { -#endif // DYNAMIC_GRAPH_COMMAND_GETTER_T_CPP +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 + +#endif // DYNAMIC_GRAPH_COMMAND_GETTER_T_CPP diff --git a/include/dynamic-graph/command-setter.h b/include/dynamic-graph/command-setter.h index f7177c73b3102075635febc317cf7e789e4137db..4a20cb6fdf232533fe43cfd51463e64dc18b84e5 100644 --- a/include/dynamic-graph/command-setter.h +++ b/include/dynamic-graph/command-setter.h @@ -41,22 +41,21 @@ namespace command { /// \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: +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&); + typedef void (E::*SetterMethod)(const T &); /// Constructor - Setter(E& entity, SetterMethod setterMethod, const std::string& docString); + Setter(E &entity, SetterMethod setterMethod, const std::string &docString); - protected: +protected: virtual Value doExecute(); - private: +private: SetterMethod setterMethod_; }; -} // namespace command -} // namespace dynamicgraph +} // 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 61b3d7bd35789dad4a1d4594ac93bd82d53323c4..61a55fd7c2cd8d04e98aa8e8d5ea68dd319fad5f 100644 --- a/include/dynamic-graph/command-setter.t.cpp +++ b/include/dynamic-graph/command-setter.t.cpp @@ -7,317 +7,271 @@ #ifndef DYNAMIC_GRAPH_COMMAND_SETTER_T_CPP #define DYNAMIC_GRAPH_COMMAND_SETTER_T_CPP -#include <sstream> -#include <boost/assign/list_of.hpp> #include "dynamic-graph/linear-algebra.h" +#include <boost/assign/list_of.hpp> +#include <sstream> + +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 -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), +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, 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 +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 232405d56beabeae7fc495d28ca581f660cf1ef8..076dbf5fe2e153f729d953d866a239be27257b8c 100644 --- a/include/dynamic-graph/command.h +++ b/include/dynamic-graph/command.h @@ -7,68 +7,65 @@ #ifndef DYNAMIC_GRAPH_COMMAND_H #define DYNAMIC_GRAPH_COMMAND_H -#include <vector> -#include "dynamic-graph/value.h" #include "dynamic-graph/dynamic-graph-api.h" +#include "dynamic-graph/value.h" +#include <vector> -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; +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; +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_; +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 +public: + static const std::vector<Value::Type> EMPTY_ARG; +}; +} // namespace command +} // namespace dynamicgraph -#endif // DYNAMIC_GRAPH_COMMAND_H +#endif // DYNAMIC_GRAPH_COMMAND_H diff --git a/include/dynamic-graph/debug.h b/include/dynamic-graph/debug.h index 6b66d050bcb95ecfae0f6987d2d276f354f3f335..43a054cd06d4ac97f8ad83c773ba31bab487e46b 100644 --- a/include/dynamic-graph/debug.h +++ b/include/dynamic-graph/debug.h @@ -5,208 +5,201 @@ #ifndef DYNAMIC_GRAPH_DEBUG_HH #define DYNAMIC_GRAPH_DEBUG_HH -#include <cstdio> #include <cstdarg> +#include <cstdio> #include <fstream> #include <sstream> -#include <dynamic-graph/fwd.hh> #include <dynamic-graph/dynamic-graph-api.h> +#include <dynamic-graph/fwd.hh> #ifndef VP_DEBUG_MODE #define VP_DEBUG_MODE 0 -#endif //! VP_DEBUG_MODE +#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; \ +#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, ...) - { +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 int level = -1) - { - if (level <= traceLevel) { - outputbuffer << tmpbuffer.str(); - tmpbuffer.str(""); - } - } + tmpbuffer.str(""); + } + + inline void trace(const char *format, ...) { + DG_COMMON_TRACES; + tmpbuffer.str(""); + } - inline void traceTemplate(const int level, const char* format, ...) - { - if (level <= traceLevelTemplate) DG_COMMON_TRACES; + inline void trace(const int level = -1) { + if (level <= traceLevel) { + outputbuffer << tmpbuffer.str(); tmpbuffer.str(""); } + } - inline void traceTemplate(const char* format, ...) - { + inline void traceTemplate(const int level, const char *format, ...) { + if (level <= traceLevelTemplate) DG_COMMON_TRACES; - tmpbuffer.str(""); - } + tmpbuffer.str(""); + } - inline DebugTrace& pre(const std::ostream&) { 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); - }; + inline void traceTemplate(const char *format, ...) { + DG_COMMON_TRACES; + tmpbuffer.str(""); + } - DYNAMIC_GRAPH_DLLAPI extern DebugTrace dgDEBUGFLOW; - DYNAMIC_GRAPH_DLLAPI extern DebugTrace dgERRORFLOW; -} // end of namespace dynamicgraph + inline DebugTrace &pre(const std::ostream &) { 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); +}; + +DYNAMIC_GRAPH_DLLAPI extern DebugTrace dgDEBUGFLOW; +DYNAMIC_GRAPH_DLLAPI extern DebugTrace dgERRORFLOW; +} // end of namespace dynamicgraph #ifdef VP_DEBUG #define dgPREDEBUG __FILE__ << ": " << __FUNCTION__ << "(#" << __LINE__ << ") :" -#define dgPREERROR "\t!! " << __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 \ +#define dgDEBUGF \ + if (!dgDEBUGFLOW.outputbuffer.good()) \ + ; \ + else \ dgDEBUGFLOW.pre(dgDEBUGFLOW.tmpbuffer << dgPREDEBUG, VP_DEBUG_MODE).trace -#define dgERRORF \ - if (!dgDEBUGFLOW.outputbuffer.good()) \ - ; \ - else \ +#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); \ +#define dgDEBUGMUTE \ + (level) if (1); \ else ::dynamicgraph::__null_stream() #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() - { - // This function should never be called. With -O3, - // it should not appear in the generated binary. - static std::ostream os(NULL); - return os; - } -} // namespace dynamicgraph +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; +} +} // 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 int, const char *, ...) { return; } -inline void dgTDEBUGF(const char*, ...) { return; } +inline void dgTDEBUGF(const char *, ...) { return; } #define dgDEBUG_ENABLE(level) false #define dgTDEBUG_ENABLE(level) false -#endif //! VP_DEBUG +#endif //! VP_DEBUG #define dgDEBUGIN(level) dgDEBUG(level) << "# In {" << std::endl @@ -220,4 +213,4 @@ inline void dgTDEBUGF(const char*, ...) { return; } #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 88e281d4140c063ca18cd91a210dc6927a5750e8..70fa0b2dd2eae1392e2c1aa4d875a1ef7c531b01 100644 --- a/include/dynamic-graph/dynamic-graph-api.h +++ b/include/dynamic-graph/dynamic-graph-api.h @@ -6,4 +6,4 @@ #ifndef DYNAMIC_GRAPH_API_H #define DYNAMIC_GRAPH_API_H #include <dynamic-graph/config.hh> -#endif //! DYNAMIC_GRAPH_API_H +#endif //! DYNAMIC_GRAPH_API_H diff --git a/include/dynamic-graph/eigen-io.h b/include/dynamic-graph/eigen-io.h index e84df6e1d7b7903d96255dab6a329e7e7553afbb..1cd95f3aa3868ce4d29f11a32415774d3f296c15 100644 --- a/include/dynamic-graph/eigen-io.h +++ b/include/dynamic-graph/eigen-io.h @@ -10,9 +10,9 @@ #include <boost/format.hpp> #include <boost/numeric/conversion/cast.hpp> +#include <Eigen/Geometry> #include <dynamic-graph/exception-signal.h> #include <dynamic-graph/linear-algebra.h> -#include <Eigen/Geometry> using dynamicgraph::ExceptionSignal; @@ -24,171 +24,145 @@ using dynamicgraph::ExceptionSignal; * 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 != '[') - { +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 != '[') { + 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 >> _ch && _ch != '(') throw ExceptionSignal(ExceptionSignal::GENERIC, fmt.str()); - } - else - { - if (iss >> _size && !iss.fail()) - { - inst.resize(_size); - } - else + 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()); - 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()); - } - } } - 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)) + */ - /* \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 != '[') - { +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 { + _tmp_matrix.resize(_rowsize, _colsize); + 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()) + else { + if (iss >> _ch && _ch != '(') throw ExceptionSignal(ExceptionSignal::GENERIC, fmt.str()); - else - { - _tmp_matrix.resize(_rowsize, _colsize); - if (iss >> _ch && _ch != ']') + else { + for (unsigned int j = 0; j < _rowsize; j++) { + 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()); - } - } + 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; - } - - 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; - } - - 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; + } } + 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; +} + +/* \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)) + */ -} // namespace Eigen - -#endif // DYNAMIC_GRAPH_EIGEN_IO_H - +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; +} + +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 diff --git a/include/dynamic-graph/entity-helper.h b/include/dynamic-graph/entity-helper.h index 4be1b51f6585f581b8a0106b47b03055f2697c2a..fb7c9ce38923baa031fc139bfb9c69f6218f9123 100644 --- a/include/dynamic-graph/entity-helper.h +++ b/include/dynamic-graph/entity-helper.h @@ -8,12 +8,11 @@ namespace dynamicgraph { -template <typename Ent> -struct EntityHelper { +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 09c36cb36c25c46c162d6764aae0427e7b0bf8f5..716dd347f170da067cada9ae7a1985e2bca79a04 100644 --- a/include/dynamic-graph/entity.h +++ b/include/dynamic-graph/entity.h @@ -12,12 +12,12 @@ #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/fwd.hh> +#include <dynamic-graph/logger.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,100 +36,97 @@ /// 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 f584a699359c691b9363909c23bec934aff5525a..0da05985b752eb5a3e41ff37a1bfbcaaa329ed5f 100644 --- a/include/dynamic-graph/exception-abstract.h +++ b/include/dynamic-graph/exception-abstract.h @@ -7,93 +7,94 @@ #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> // 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__) + +#define DG_THROW \ + throw ::dynamicgraph::ExceptionAbstract::Param(__LINE__, __FUNCTION__, \ + __FILE__) + #else #define DG_THROW throw -#endif // DYNAMICGRAPH_EXCEPTION_PASSING_PARAM - -namespace dynamicgraph -{ +#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 Abstract root class for all dynamic-graph exceptions. - class DYNAMIC_GRAPH_DLLAPI ExceptionAbstract : public std::exception - { + /// \brief Class owned by exceptions to store error locations. + class Param { 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 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 = ""); + explicit ExceptionAbstract(const int &code, const std::string &msg = ""); virtual ~ExceptionAbstract() throw() {} - virtual const std::string& getExceptionName() const { return EXCEPTION_NAME; } + 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; + 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; + const char *getMessage() const; - virtual const char* what() const throw() - { return getStringMessage().c_str(); } + 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); + DYNAMIC_GRAPH_DLLAPI friend std::ostream & + operator<<(std::ostream &os, const ExceptionAbstract &err); - protected: +protected: /// \brief Error code. /// \sa ErrorCodeEnum int code; @@ -109,25 +110,23 @@ namespace dynamicgraph mutable Param p; template <class Exc> - friend const Exc& operator+(const ExceptionAbstract::Param& p, const Exc& e) - { + 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) - { + friend Exc &operator+(const ExceptionAbstract::Param &p, Exc &e) { e.p.initCopy(p); return e; } -#endif // DYNAMICGRAPH_EXCEPTION_PASSING_PARAM +#endif // DYNAMICGRAPH_EXCEPTION_PASSING_PARAM - private: +private: /// \brief Forbid the empty constructor (private). ExceptionAbstract(); }; -} // end of namespace dynamicgraph +} // 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 5faac136347967f9ea259045671cd0744866cf81..0275659b5a9447ebc78d007a534b156c21ef12dc 100644 --- a/include/dynamic-graph/exception-factory.h +++ b/include/dynamic-graph/exception-factory.h @@ -7,47 +7,43 @@ #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> +#include <dynamic-graph/fwd.hh> -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; } +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 9482cfd55093d953e222e4dc35ac84f0864dee66..a2fa44ea8cd4eb500f6b70de817cfa9ebe2970eb 100644 --- a/include/dynamic-graph/exception-signal.h +++ b/include/dynamic-graph/exception-signal.h @@ -6,44 +6,38 @@ #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> +#include <dynamic-graph/fwd.hh> -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; } +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; + + 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 +#endif //! DYNAMIC_GRAPH_EXCEPTION_SIGNAL_H diff --git a/include/dynamic-graph/exception-traces.h b/include/dynamic-graph/exception-traces.h index cd078b9810546dedecfbd001bf68b91613feb3b5..de2b8585134d5296ebf6f2b8bbb9275fe8407721 100644 --- a/include/dynamic-graph/exception-traces.h +++ b/include/dynamic-graph/exception-traces.h @@ -7,30 +7,28 @@ #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> + +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; + + 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() {} -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; - - 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 25337a7ce277c3ab650a44e78b7096bfbc9d2a20..6c09ebd5e5bde9b33406fa990e490f6e6c7507c1 100644 --- a/include/dynamic-graph/factory.h +++ b/include/dynamic-graph/factory.h @@ -11,9 +11,9 @@ #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/exception-factory.h> +#include <dynamic-graph/fwd.hh> /// \ingroup dgraph /// @@ -24,180 +24,180 @@ /// \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 +/// \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 &); + + ~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. /// - /// 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. + /// 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. /// - /// 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). + /// If the function pointer is null, an ExceptionFactory exception + /// will be raised with the code OBJECT_CONFLICT. /// - /// To achieve this, one must pass an entity name and a function pointer. + /// \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. /// - /// 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). + /// 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. /// - /// 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). + /// An instance called objname of the entity which type is classname + /// will be allocated by this method. /// - /// 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). + /// It is <b>the caller</b> responsibility to free the + /// returned object. /// - /// 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. + /// 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. /// - /// 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 + /// \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. /// - /// \brief This class automatically register an Entity to the - /// global factory at initialization and unregister it during - /// instance destruction. + /// \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. /// - /// 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 + /// 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 // LocalWords: unregister diff --git a/include/dynamic-graph/fwd.hh b/include/dynamic-graph/fwd.hh index ec7a0125065eca0047c913487df3f0d424c6a06c..165b364e7e3024c883664d5c5c540f014679f491 100644 --- a/include/dynamic-graph/fwd.hh +++ b/include/dynamic-graph/fwd.hh @@ -29,32 +29,24 @@ class SignalCastRegisterer; 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. +} // 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 c600ff1763d04305f22f5456a5f1eb1c69478ae5..7feab4902192734f0f5492cc3c976aa4979d9b67 100644 --- a/include/dynamic-graph/linear-algebra.h +++ b/include/dynamic-graph/linear-algebra.h @@ -12,6 +12,6 @@ namespace dynamicgraph { typedef Eigen::MatrixXd Matrix; typedef Eigen::VectorXd Vector; -} // namespace dynamicgraph +} // 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 95f0fe2fe7cfcf4481866861c3c3d7c8bae23943..0a62dc1626cbe77715642a86f0e8f2b33cd50a54 100644 --- a/include/dynamic-graph/logger.h +++ b/include/dynamic-graph/logger.h @@ -36,18 +36,18 @@ enum MsgType { MSG_TYPE_WARNING_STREAM = 6, MSG_TYPE_ERROR_STREAM = 7 }; -} // namespace dynamicgraph +} // namespace dynamicgraph /* --------------------------------------------------------------------- */ /* --- INCLUDE --------------------------------------------------------- */ /* --------------------------------------------------------------------- */ -#include <map> -#include <iomanip> // std::setprecision -#include <fstream> -#include <sstream> #include "boost/assign.hpp" #include <dynamic-graph/linear-algebra.h> +#include <fstream> +#include <iomanip> // std::setprecision +#include <map> +#include <sstream> namespace dynamicgraph { @@ -73,17 +73,15 @@ std::string toString(const T& v, const int precision=3, const int width=-1) }*/ template <typename T> -std::string toString(const std::vector<T>& v, - const int precision = 3, const int width = -1, - const std::string separator = ", ") { +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) + 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]; + 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; @@ -94,18 +92,15 @@ std::string toString(const std::vector<T>& v, } template <typename T> -std::string toString(const Eigen::MatrixBase<T>& v, - const int precision = 3, - const int width = -1, - const std::string separator = ", ") -{ +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]; + 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; @@ -151,7 +146,7 @@ enum LoggerVerbosity { /// /// class Logger { - public: +public: /** Constructor */ Logger(double timeSample = 0.001, double streamPrintPeriod = 1.0); @@ -167,9 +162,7 @@ class Logger { * 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 = "", + void sendMsg(std::string msg, MsgType type, const char *file = "", int line = 0); /** Set the sampling time at which the method countdown() @@ -192,38 +185,40 @@ class Logger { /** Get the verbosity level of the logger. */ LoggerVerbosity getVerbosity(); - protected: - LoggerVerbosity m_lv; /// verbosity of the logger +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_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 + /** 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) - { + 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; + 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 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 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 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; } + bool isErrorMsg(MsgType m) { + return m == MSG_TYPE_ERROR_STREAM || m == MSG_TYPE_ERROR; + } }; -} // namespace dynamicgraph +} // namespace dynamicgraph -#endif // #ifndef __sot_torque_control_logger_H__ +#endif // #ifndef __sot_torque_control_logger_H__ diff --git a/include/dynamic-graph/null-ptr.hh b/include/dynamic-graph/null-ptr.hh index d43bc471ed16dccbc01236d9ece363d2ee3b3d8d..e1715eff29390f650001be5dd2901a7a4133a459 100644 --- a/include/dynamic-graph/null-ptr.hh +++ b/include/dynamic-graph/null-ptr.hh @@ -6,21 +6,15 @@ namespace dynamicgraph { const class { - public: - template <class T> - operator T*() const { - return 0; - } +public: + template <class T> operator T *() const { return 0; } - template <class C, class T> - operator T C::*() const { - return 0; - } + template <class C, class T> operator T C::*() const { return 0; } - private: +private: void operator&() const; } nullptr = {}; -} // end of namespace dynamicgraph. +} // end of namespace dynamicgraph. -#endif //! DYNAMIC_GRAPH_NULL_PTR_HH +#endif //! DYNAMIC_GRAPH_NULL_PTR_HH diff --git a/include/dynamic-graph/pool.h b/include/dynamic-graph/pool.h index 90d9c89a84023818c7cf951b75fa0d7e3663c730..19f72aa8af59d11fd9e665946615f915d730dd57 100644 --- a/include/dynamic-graph/pool.h +++ b/include/dynamic-graph/pool.h @@ -6,13 +6,13 @@ #ifndef DYNAMIC_GRAPH_POOL_H #define DYNAMIC_GRAPH_POOL_H #include <map> -#include <string> #include <sstream> +#include <string> -#include <dynamic-graph/fwd.hh> +#include <dynamic-graph/dynamic-graph-api.h> #include <dynamic-graph/exception-factory.h> +#include <dynamic-graph/fwd.hh> #include <dynamic-graph/signal-base.h> -#include <dynamic-graph/dynamic-graph-api.h> namespace dynamicgraph { /*! @ingroup dgraph @@ -31,15 +31,15 @@ namespace dynamicgraph { */ class DYNAMIC_GRAPH_DLLAPI PoolStorage { - public: +public: /*! \name Define types to simplify the writing @{ */ /*! \brief Sorted set of entities with unique key (name). */ - typedef std::map<std::string, Entity*> Entities; + typedef std::map<std::string, Entity *> Entities; /// \brief Get unique instance of the class. - static PoolStorage* getInstance(); + static PoolStorage *getInstance(); /// \brief Destroy the unique instance of the class static void destroy(); @@ -56,49 +56,49 @@ class DYNAMIC_GRAPH_DLLAPI PoolStorage { \par[in] entname: The name of the entity, \par[in] ent: Pointer towards the entity. */ - void registerEntity(const std::string& entname, Entity* ent); + 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); + void deregisterEntity(const std::string &entname); /*! \brief Unregister an entity. \par[in] entity: iterator in the map, */ - void deregisterEntity(const Entities::iterator& entity); + 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); + Entity &getEntity(const std::string &name); /// Const access to entity map - const Entities& getEntityMap() const; + const Entities &getEntityMap() const; /*! \brief Test if the entity exists. */ - bool existEntity(const std::string& name); + 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); + 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); + 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); + 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); + void writeGraph(const std::string &aFileName); + void writeCompletionList(std::ostream &os); - protected: +protected: /*! \name Fields of the class to manage the three entities. Also the name is singular, those are true sets. @{ @@ -106,13 +106,13 @@ class DYNAMIC_GRAPH_DLLAPI PoolStorage { /*! \brief Set of basic objects of the SoT */ Entities entityMap; - private: +private: PoolStorage() {} - static PoolStorage* instance_; + static PoolStorage *instance_; }; -inline PoolStorage& g_pool() { return *PoolStorage::getInstance(); } +inline PoolStorage &g_pool() { return *PoolStorage::getInstance(); } -} // end of namespace dynamicgraph. +} // 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 ba9ea923a571fa85d56aacdd0027f0618de5ff83..6725b984570b283b82f3e8b66044b20f6f985e6a 100644 --- a/include/dynamic-graph/process-list.hh +++ b/include/dynamic-graph/process-list.hh @@ -6,170 +6,161 @@ #ifndef 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/archive/text_oarchive.hpp> #include <boost/serialization/vector.hpp> -#include <dynamic-graph/fwd.hh> #include <dynamic-graph/dynamic-graph-api.h> +#include <dynamic-graph/fwd.hh> + +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_; -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 + 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 a18c6434187de5f703a94f0956f10ced412f1461..373979f1c754752457b96be81a6c50d5079bb3f8 100644 --- a/include/dynamic-graph/real-time-logger.h +++ b/include/dynamic-graph/real-time-logger.h @@ -14,181 +14,172 @@ #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; +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 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 +#else // ENABLE_RT_LOG #define dgADD_OSTREAM_TO_RTLOG(ostr) struct __end_with_semicolon -#define dgRTLOG() \ - if (1) \ - ; \ - else \ +#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 fb7829a4153458c70581e4fd257eecfde19166d6..15ebdd55e18985b8cb0f49e5d83b165134ec421f 100644 --- a/include/dynamic-graph/signal-array.h +++ b/include/dynamic-graph/signal-array.h @@ -5,166 +5,149 @@ #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> +#include <dynamic-graph/signal-base.h> #include <stdio.h> +#include <vector> -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); - } +namespace dynamicgraph { - 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: - 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: - virtual SignalArray_const<Time>& operator<<(const SignalBase<Time>& sig) - { - addElmt(&sig); - return *this; - } +public: + static const int DEFAULT_SIZE = 20; - 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; +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); } - /// \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<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); - } + 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>(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>() {} - virtual ~SignalArray<Time>() {} - - protected: - void addElmt(SignalBase<Time>* el) - { - if (rank >= size) - { - size += DEFAULT_SIZE; - array.resize(size); - } - array[rank++] = el; +protected: + void addElmt(const SignalBase<Time> *el) { + if (rank >= size) { + size += DEFAULT_SIZE; + const_array.resize(size); } + const_array[rank++] = el; + } - public: - virtual SignalArray<Time>& operator<<(SignalBase<Time>& sig) - { - addElmt(&sig); - return *this; - } +public: + virtual SignalArray_const<Time> &operator<<(const SignalBase<Time> &sig) { + addElmt(&sig); + return *this; + } + +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; + } + + SignalArray<Time>(SignalBase<Time> &sig) + : SignalArray_const<Time>(0), array(DEFAULT_SIZE) { + size = DEFAULT_SIZE; + addElmt(&sig); + } - virtual SignalArray_const<Time> operator<< - (const SignalBase<Time>& sig) const - { - SignalArray_const<Time> res(*this); - res << sig; - return res; + 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<Time>() {} + +protected: + void addElmt(SignalBase<Time> *el) { + if (rank >= size) { + size += DEFAULT_SIZE; + array.resize(size); } + array[rank++] = el; + } - virtual SignalBase<Time>& operator[] - (const unsigned int& idx) const - { return *array[idx]; } - }; +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 3b3f9ba764915597fbd551abda024988cf48aea6..e0d83738d129dd0682a584545c6114da104670fa 100644 --- a/include/dynamic-graph/signal-base.h +++ b/include/dynamic-graph/signal-base.h @@ -6,222 +6,206 @@ #ifndef DYNAMIC_GRAPH_SIGNAL_BASE_H #define DYNAMIC_GRAPH_SIGNAL_BASE_H -#include <string> +#include <boost/noncopyable.hpp> #include <sstream> +#include <string> #include <typeinfo> -#include <boost/noncopyable.hpp> -#include <dynamic-graph/fwd.hh> #include <dynamic-graph/exception-signal.h> +#include <dynamic-graph/fwd.hh> -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; } - - virtual void setTime(const Time& t) { signalTime = t; } - - const bool& getReady() const { return ready; } - - const std::string& getName() const { return name; } - - void getClassName(std::string& aClassName) const - { aClassName = typeid(this).name(); } - - virtual void setPeriodTime(const Time&) {} - - virtual Time getPeriodTime() const { return 1; } - - /// \} - - /// \name Dependencies - /// \{ - - virtual void addDependency(const SignalBase<Time>&) {} - - virtual void removeDependency(const SignalBase<Time>&) {} - - virtual void clearDependencies() {} - - virtual bool needUpdate(const Time&) const { return ready; } - - inline void setReady(const bool sready = true) { ready = sready; } - - virtual std::ostream& writeGraph(std::ostream& os) const { return os; } - - 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; - } +namespace dynamicgraph { - /// \} - - /// \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 unplug() - { - DG_THROW ExceptionSignal - (ExceptionSignal::PLUG_IMPOSSIBLE, - "Plug-in operation not possible with this signal. ", - "(while trying to unplug %s).", this->getName().c_str()); - } +/** \brief The base class for signals: not to be used as such. - virtual bool isPlugged() const { return false; } + 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<Time>* getPluged() const { return NULL; } + virtual ~SignalBase() {} - 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 Time + /// \{ + virtual const Time &getTime() const { return signalTime; } - /// \} + virtual void setTime(const Time &t) { signalTime = t; } - /// \name Set - /// \{ + const bool &getReady() const { return ready; } - /* 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()); - } + const std::string &getName() const { return name; } - 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()); - } + void getClassName(std::string &aClassName) const { + aClassName = typeid(this).name(); + } - 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()); - } + virtual void setPeriodTime(const Time &) {} - /// \} + virtual Time getPeriodTime() const { return 1; } - /// \name Display - /// \{ + /// \} - virtual std::ostream& display(std::ostream& os) const - { - os << "Sig:" << name; - return os; - } + /// \name Dependencies + /// \{ - 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 addDependency(const SignalBase<Time> &) {} + + virtual void removeDependency(const SignalBase<Time> &) {} - /// \} + virtual void clearDependencies() {} - /// \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 bool needUpdate(const Time &) const { return ready; } + + inline void setReady(const bool sready = true) { ready = sready; } + + virtual std::ostream &writeGraph(std::ostream &os) const { return os; } + + 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; + } + + /// \} + + /// \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 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 bool isPlugged() const { return false; } + + virtual SignalBase<Time> *getPluged() const { return NULL; } + + 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 + /// \{ + + 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 + /// \{ + + 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); + } + + /// \} -#endif //! DYNAMIC_GRAPH_SIGNAL_BASE_H + /// \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 3673926c166a90c2847b56e29c572ee014f8bd72..d488985c75df6a9306afa3787ab7218fbbdaafbd 100644 --- a/include/dynamic-graph/signal-cast-helper.h +++ b/include/dynamic-graph/signal-cast-helper.h @@ -18,86 +18,88 @@ #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" +#include <dynamic-graph/dynamic-graph-api.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); -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; + static void disp(const boost::any &object, std::ostream &os) { + os << boost::any_cast<T>(object) << std::endl; } - /* --- 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 + 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 --------------------------------------------------------------- */ @@ -107,88 +109,87 @@ 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_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_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_) + +/* 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); \ + } \ + } /* 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) \ +#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; \ - }, \ +#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; \ - }, \ +#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 +#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 982ef3cafa2df09e822b3de6f23f956c3b0f68ec..7bf1103dbfabe96e4d3be0ef18412c0bed77755f 100644 --- a/include/dynamic-graph/signal-caster.h +++ b/include/dynamic-graph/signal-caster.h @@ -15,113 +15,103 @@ #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> -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; + /// 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; +private: + /// Container for the three cast functions. + typedef boost::tuple<displayer_type, caster_type, tracer_type> + cast_functions_type; - /// \brief Retrieve cast structure from its name. - cast_functions_type& getCast(const std::string& type_name); + /// \brief Retrieve cast structure from its name. + cast_functions_type &getCast(const std::string &type_name); - /// This map associates the typename of objects and the corresponding - /// using boost::function with 'compatible' syntax - std::map<std::string, cast_functions_type> functions_; + /// This map associates the typename of objects and the corresponding + /// using boost::function with 'compatible' syntax + std::map<std::string, cast_functions_type> functions_; - std::map<std::string, const std::type_info*> type_info_; + std::map<std::string, const std::type_info *> type_info_; - private: - explicit SignalCaster(); - /// Pointer to the unique instance of the class. - static SignalCaster* instance_; - }; +private: + explicit SignalCaster(); + /// Pointer to the unique instance of the class. + static SignalCaster *instance_; +}; - /// 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, +/// 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); + SignalCaster::tracer_type tracer) { + SignalCaster::getInstance()->registerCast(type, displayer, caster, tracer); } - }; +}; - /// 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); - } +/// 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> - T signal_cast(std::istringstream& iss) { - return boost::any_cast<T>(SignalCaster::getInstance()-> - cast(typeid(T), iss)); - } +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. +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 dfd22f33ae900a1461df6d792e180264e6510cd1..04bac133033843606a943b9831ee1e08db39b60a 100644 --- a/include/dynamic-graph/signal-helper.h +++ b/include/dynamic-graph/signal-helper.h @@ -12,74 +12,71 @@ /* dg signals */ #include <dynamic-graph/entity.h> +#include <dynamic-graph/linear-algebra.h> #include <dynamic-graph/signal-ptr.h> #include <dynamic-graph/signal-time-dependent.h> -#include <dynamic-graph/linear-algebra.h> /* --- MACROS ---------------------------------------------------------- */ #define SIGNAL_OUT_FUNCTION_NAME(name) name##SOUT_function -#define DECLARE_SIGNAL(name, IO, type) \ +#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 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) \ +#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 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 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 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 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 DEFINE_SIGNAL_INNER_FUNCTION(name, type) \ + type &EntityClassName::SIGNAL_INNER_FUNCTION_NAME(name)(type & s, int iter) -#define DECLARE_SIGNAL_INNER(name, type) \ - public: \ - ::dynamicgraph::SignalTimeDependent<type, int> m_##name##SINNER; \ - \ - protected: \ +#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) +#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 30894bbec9ebed2e0a6e18a69b114b8299d288aa..c5feb3f621bbc39beb61f0b51e25c0e174cc1c14 100644 --- a/include/dynamic-graph/signal-ptr.h +++ b/include/dynamic-graph/signal-ptr.h @@ -11,139 +11,127 @@ #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 +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 - +#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 d747a53d49fe16928dc1f998781e4758905df086..95bf711e2310f22f1bde3e3fe786c3e548588b99 100644 --- a/include/dynamic-graph/signal-ptr.t.cpp +++ b/include/dynamic-graph/signal-ptr.t.cpp @@ -11,279 +11,215 @@ #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)); +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); - } - - template <class T, class Time> - const Time& SignalPtr<T, Time>::getTime() const - { - if ((isAbstractPluged()) && (!autoref())) - { - return getAbstractPtr()->getTime(); - } - return Signal<T, Time>::getTime(); + 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 T& SignalPtr<T, Time>::operator()(const Time& t) - { - return access(t); + 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>::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(); + 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())) { + os << " -->-- PLUGGED"; + } else { + if (!isAbstractPluged()) + os << " UNPLUGGED"; 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())) - { - os << " -->-- PLUGGED"; - } - else - { - if (!isAbstractPluged()) - os << " UNPLUGGED"; - else if (autoref()) - os << " AUTOPLUGGED"; - } - - dgTDEBUGOUT(25); - return os; + 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 765f929dfdc93a06f1a2cf4e1dcc6575663a7f5a..c834d613d763ce2097926238eb4ba27223d289f6 100644 --- a/include/dynamic-graph/signal-time-dependent.h +++ b/include/dynamic-graph/signal-time-dependent.h @@ -8,143 +8,126 @@ #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 = ""); - +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); + 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 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 &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); - } + 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 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) +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) +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) -{ +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 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(); - } + 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) -{ +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) -{ +void SignalTimeDependent<T, Time>::removeDependency( + const SignalBase<Time> &signal) { TimeDependency<Time>::removeDependency(signal); } template <class T, class Time> -void SignalTimeDependent<T, Time>:: -clearDependencies() -{ +void SignalTimeDependent<T, Time>::clearDependencies() { TimeDependency<Time>::clearDependency(); } template <class T, class Time> -bool SignalTimeDependent<T, Time>:: -needUpdate(const Time& t) const -{ +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) -{ +void SignalTimeDependent<T, Time>::setPeriodTime(const Time &p) { TimeDependency<Time>::setPeriodTime(p); } template <class T, class Time> -Time SignalTimeDependent<T, Time>:: -getPeriodTime() const -{ +Time SignalTimeDependent<T, Time>::getPeriodTime() const { return TimeDependency<Time>::getPeriodTime(); } -} // end of namespace dynamicgraph +} // end of namespace dynamicgraph -#endif //! DYNAMIC_GRAPH_SIGNAL_TIME_DEPENDENT_H +#endif //! DYNAMIC_GRAPH_SIGNAL_TIME_DEPENDENT_H diff --git a/include/dynamic-graph/signal.h b/include/dynamic-graph/signal.h index a1f3de25f0713e36790712acda1d495da9b46ea7..5d3c3bb2e201a8a4da6699afdab539ff2697b4dc 100644 --- a/include/dynamic-graph/signal.h +++ b/include/dynamic-graph/signal.h @@ -22,107 +22,105 @@ #include <boost/thread.hpp> #endif -namespace dynamicgraph -{ - - /*! \ingroup dgraph - \brief Signals link I/O ports of entities. They can be - constant-valued signals, or copy the value of a heap variable, - or evaluated as a function. - See SignalPtr and SignalTimeDependent for other types of signals, - and SignalArray for a way of grouping them. - - There are several ways to specify the value output by a signal: - \li using the function setConstant(T) to set the value of the signal to T; - \li using the function setReference(mutex, T*) to set the value - from a pointer, whose access is restricted by a mutex; - \li using the function setFunction(boost::function2) that will be called - when the signal's value is accessed. - */ - template <class T, class Time> - class Signal : public SignalBase<Time> - { - protected: - enum SignalType { CONSTANT, REFERENCE, REFERENCE_NON_CONST, FUNCTION }; - static const SignalType SIGNAL_TYPE_DEFAULT = CONSTANT; - - SignalType signalType; - T Tcopy1, Tcopy2; - T* Tcopy; - bool copyInit; - - const T* Treference; - T* TreferenceNonConst; - boost::function2<T&, T&, Time> Tfunction; - - bool keepReference; - const static bool KEEP_REFERENCE_DEFAULT = false; - - public: +namespace dynamicgraph { + +/*! \ingroup dgraph + \brief Signals link I/O ports of entities. They can be + constant-valued signals, or copy the value of a heap variable, + or evaluated as a function. + See SignalPtr and SignalTimeDependent for other types of signals, + and SignalArray for a way of grouping them. + + There are several ways to specify the value output by a signal: + \li using the function setConstant(T) to set the value of the signal to T; + \li using the function setReference(mutex, T*) to set the value + from a pointer, whose access is restricted by a mutex; + \li using the function setFunction(boost::function2) that will be called + when the signal's value is accessed. +*/ +template <class T, class Time> class Signal : public SignalBase<Time> { +protected: + enum SignalType { CONSTANT, REFERENCE, REFERENCE_NON_CONST, FUNCTION }; + static const SignalType SIGNAL_TYPE_DEFAULT = CONSTANT; + + SignalType signalType; + T Tcopy1, Tcopy2; + T *Tcopy; + bool copyInit; + + const T *Treference; + T *TreferenceNonConst; + boost::function2<T &, T &, Time> Tfunction; + + bool keepReference; + const static bool KEEP_REFERENCE_DEFAULT = false; + +public: #ifdef HAVE_LIBBOOST_THREAD - typedef boost::try_mutex Mutex; - typedef boost::lock_error MutexError; + typedef boost::try_mutex Mutex; + typedef boost::lock_error MutexError; #else - typedef int* Mutex; - typedef int* MutexError; + typedef int *Mutex; + typedef int *MutexError; #endif - - protected: - Mutex* providerMutex; - using SignalBase<Time>::signalTime; - - public: - using SignalBase<Time>::setReady; - - public: - /* --- Constructor/destrusctor --- */ - 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; - - /* --- 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); - - 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 std::ostream& display(std::ostream& os) const; - - /* --- Operators --- */ - virtual inline const T& operator()(const Time& t) { return access(t); } - virtual Signal<T, Time>& operator=(const T& t); - inline operator const T&() const { return accessCopy(); } - virtual void getClassName(std::string& aClassName) const - { aClassName = typeid(this).name(); } - - public: - virtual void checkCompatibility() { throw Tcopy; } - - private: - const T& setTcopy(const T& t); - T& getTwork(); - const T& getTwork() const; - const T& switchTcopy(); - }; - -} // end of namespace dynamicgraph + +protected: + Mutex *providerMutex; + using SignalBase<Time>::signalTime; + +public: + using SignalBase<Time>::setReady; + +public: + /* --- Constructor/destrusctor --- */ + 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; + + /* --- 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); + + 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 std::ostream &display(std::ostream &os) const; + + /* --- Operators --- */ + virtual inline const T &operator()(const Time &t) { return access(t); } + virtual Signal<T, Time> &operator=(const T &t); + inline operator const T &() const { return accessCopy(); } + virtual void getClassName(std::string &aClassName) const { + aClassName = typeid(this).name(); + } + +public: + virtual void checkCompatibility() { throw Tcopy; } + +private: + const T &setTcopy(const T &t); + T &getTwork(); + const T &getTwork() const; + const T &switchTcopy(); +}; + +} // 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 636dad11e8905adb28b8af9e010aad4c50b603b3..2415124f40b8f6ec305d3148c97130a7eb7cb773 100644 --- a/include/dynamic-graph/signal.t.cpp +++ b/include/dynamic-graph/signal.t.cpp @@ -5,289 +5,229 @@ #ifndef DYNAMIC_GRAPH_SIGNAL_T_CPP #define DYNAMIC_GRAPH_SIGNAL_T_CPP -#include <dynamic-graph/signal.h> #include <dynamic-graph/signal-caster.h> +#include <dynamic-graph/signal.h> #undef VP_TEMPLATE_DEBUG_MODE #define VP_TEMPLATE_DEBUG_MODE 0 #include <dynamic-graph/debug.h> -#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; +#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) { + 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); +#endif 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; + signalTime = t; + return setTcopy(*Treference); + } catch (const MutexError &) { + return accessCopy(); } - } - - 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; + break; } - template <class T, class Time> - const T& Signal<T, Time>::access(const Time& t) - { - switch (signalType) - { - case REFERENCE: - case REFERENCE_NON_CONST: - { - if (NULL == providerMutex) - { - copyInit = true; - signalTime = t; - return setTcopy(*Treference); - } - else - { - try - { + case 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 - copyInit = true; - signalTime = t; - return setTcopy(*Treference); - } - catch (const MutexError&) - { - return accessCopy(); - } - } - - 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); -#endif - signalTime = t; - Tfunction(getTwork(), t); - copyInit = true; - return switchTcopy(); - } - catch (const MutexError&) - { - return accessCopy(); - } - } - break; + signalTime = t; + Tfunction(getTwork(), t); + copyInit = true; + return switchTcopy(); + } catch (const MutexError &) { + return accessCopy(); } - case CONSTANT: - default: - if (this->getReady()) - { - setReady(false); - this->setTime(t); - } - return accessCopy(); - }; + } + break; } - - 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 - { + 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. + } + } 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 +#endif //! DYNAMIC_GRAPH_SIGNAL_T_CPP diff --git a/include/dynamic-graph/time-dependency.h b/include/dynamic-graph/time-dependency.h index 025a71c92fa2a2800c901816b4f9f0fd661b7fed..755a30f1cdf4f07cdb01da9bb924e2e0eeaa61a8 100644 --- a/include/dynamic-graph/time-dependency.h +++ b/include/dynamic-graph/time-dependency.h @@ -8,71 +8,65 @@ #include <list> #include <dynamic-graph/fwd.hh> -#include <dynamic-graph/signal-base.h> #include <dynamic-graph/signal-array.h> +#include <dynamic-graph/signal-base.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 }; + + mutable Time lastAskForUpdate; + +public: + SignalBase<Time> &leader; + + 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; + + DependencyType dependencyType; + + 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() {} + + void addDependency(const SignalBase<Time> &sig); + void removeDependency(const SignalBase<Time> &sig); + void clearDependency(); + + virtual std::ostream &writeGraph(std::ostream &os) const; + std::ostream &displayDependencies(std::ostream &os, const int depth = -1, + std::string space = "", + std::string next1 = "", + std::string next2 = "") const; + + bool needUpdate(const Time &t1) const; + + void setDependencyType(DependencyType dep) { dependencyType = dep; } + + void setNeedUpdateFromAllChildren(const bool b = true) { + updateFromAllChildren = b; + } + bool getNeedUpdateFromAllChildren() const { return updateFromAllChildren; } + + void setPeriodTime(const Time &p) { periodTime = p; } + Time getPeriodTime() const { return periodTime; } +}; -namespace dynamicgraph -{ - /** \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; - - public: - SignalBase<Time>& leader; - - 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; - - DependencyType dependencyType; - - 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() {} - - void addDependency(const SignalBase<Time>& sig); - void removeDependency(const SignalBase<Time>& sig); - void clearDependency(); - - virtual std::ostream& writeGraph(std::ostream& os) const; - std::ostream& displayDependencies(std::ostream& os, - const int depth = -1, - std::string space = "", - std::string next1 = "", - std::string next2 = "") const; - - bool needUpdate(const Time& t1) const; - - void setDependencyType(DependencyType dep) - { dependencyType = dep; } - - void setNeedUpdateFromAllChildren(const bool b = true) - { updateFromAllChildren = b; } - bool getNeedUpdateFromAllChildren() const - { return updateFromAllChildren; } - - void setPeriodTime(const Time& p) { periodTime = p; } - Time getPeriodTime() const { return periodTime; } - }; - -} // end of namespace dynamicgraph +} // end of namespace dynamicgraph #include <dynamic-graph/time-dependency.t.cpp> -#endif //! DYNAMIC_GRAPH_TIME_DEPENDENCY_H +#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 fd703823d018a86006fe9a7fd8ab3cafe71f2328..5338e01a56b046c8a85189ce937925e62086790d 100644 --- a/include/dynamic-graph/time-dependency.t.cpp +++ b/include/dynamic-graph/time-dependency.t.cpp @@ -11,199 +11,165 @@ #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) +#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> +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>::addDependency(const SignalBase<Time>& sig) - { - dependencies.push_front(&sig); + 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; + } + if (lastAskForUpdate) { + dgTDEBUGOUT(15); + return true; } - template <class Time> - void TimeDependency<Time>::removeDependency(const SignalBase<Time>& sig) - { - dependencies.remove(&sig); + switch (dependencyType) { + case ALWAYS_READY: { + dgTDEBUGOUT(15); + return true; } - - template <class Time> - void TimeDependency<Time>::clearDependency() - { - dependencies.clear(); + case BOOL_DEPENDENT: + break; + case TIME_DEPENDENT: { + if (t1 < leader.getTime() + periodTime) { + dgTDEBUGOUT(15); + return false; + } + break; } + }; - template <class Time> - bool TimeDependency<Time>::needUpdate(const Time& t1) const - { - dgTDEBUG(15) << "# In {" << leader.getName() << " : (" - << leader.getReady() << ") " << t1 << " >? " - << leader.getTime() << std::endl; - - if (leader.getReady()) - { - dgTDEBUGOUT(15); - return true; - } - if (lastAskForUpdate) - { - dgTDEBUGOUT(15); - return true; - } + 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; - switch (dependencyType) - { - case ALWAYS_READY: - { - dgTDEBUGOUT(15); - return true; - } - case BOOL_DEPENDENT: + if ((sig.getTime() > leader.getTime()) || (sig.needUpdate(t1))) { + if (updateFromAllChildren) + continue; + else { + res = true; 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; - - dgTDEBUGOUT(15); - return res; + } else { + if (updateFromAllChildren) { + res = false; + break; + } else + continue; + } } + lastAskForUpdate = 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; + 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; +} - 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) +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 << ") "; + 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; - }; - 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; + } } + return os; +} -} // end of namespace dynamicgraph +} // end of namespace dynamicgraph #undef __TIME_DEPENDENCY_INIT -#endif //! DYNAMIC_GRAPH_TIME_DEPENDENCY_T_CPP +#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 6dd48ff9e8c347c1a4f2a8ba7f0e1fc7824cc5f7..5792ffb4d990aab49892fc78233027b5ea447b4d 100644 --- a/include/dynamic-graph/tracer-real-time.h +++ b/include/dynamic-graph/tracer-real-time.h @@ -7,70 +7,66 @@ #define DYNAMIC_GRAPH_TRACER_REAL_TIME_H #include <sstream> +#include <dynamic-graph/config-tracer-real-time.hh> #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 +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 4eda968aebd2dc1a5584b8d42a9cc3e978bb5029..9861b040b923bb829cbdbdcbcd140e064dfd1ef8 100644 --- a/include/dynamic-graph/tracer.h +++ b/include/dynamic-graph/tracer.h @@ -5,105 +5,100 @@ #ifndef DYNAMIC_GRAPH_TRACER_H #define DYNAMIC_GRAPH_TRACER_H -#include <string> -#include <list> #include <boost/function.hpp> +#include <list> +#include <string> +#include <dynamic-graph/entity.h> +#include <dynamic-graph/exception-traces.h> #include <dynamic-graph/signal-base.h> #include <dynamic-graph/signal-time-dependent.h> #include <dynamic-graph/time-dependency.h> -#include <dynamic-graph/entity.h> -#include <dynamic-graph/exception-traces.h> #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; +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 f15d5a6c396d1e354d845c62f41d1acefe5f83e8..240dc50bcde143edd1a34b8fa579448809094d75 100644 --- a/include/dynamic-graph/value.h +++ b/include/dynamic-graph/value.h @@ -7,114 +7,110 @@ #ifndef DYNAMIC_GRAPH_VALUE_H #define DYNAMIC_GRAPH_VALUE_H -#include <string> -#include <cassert> -#include <typeinfo> #include "dynamic-graph/dynamic-graph-api.h" +#include <cassert> #include <dynamic-graph/linear-algebra.h> +#include <string> +#include <typeinfo> + +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; -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_; - }; +private: + const Value *value_; +}; - 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; +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; - /// 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); + /// Return the value as a castable value into the approriate type + /// + /// For instance, + /// \code + /// Value v1(5.0); // v1 is of type double + /// Value v2(3); // v2 is of type int + /// double x1 = v1.value(); + /// double x2 = v2.value(); + /// \endcode + /// The first assignment will succeed, while the second one will throw + /// an exception. + const EitherType value() const; + /// Return the name of the type + static std::string typeName(Type type); - /// Output in a stream - DYNAMIC_GRAPH_DLLAPI friend std::ostream& operator<< - (std::ostream& os, const Value& value); + /// 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_; - }; +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 +/* ---- 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 +#endif // DYNAMIC_GRAPH_VALUE_H diff --git a/src/command/command.cpp b/src/command/command.cpp index 9c091520fa865728f66a1491483444b744ecd675..3b805260c619b749b019bc79a135f00c50726e31 100644 --- a/src/command/command.cpp +++ b/src/command/command.cpp @@ -4,9 +4,9 @@ // Author: Florent Lamiraux // -#include <sstream> #include "dynamic-graph/command.h" #include "dynamic-graph/exception-abstract.h" +#include <sstream> namespace dynamicgraph { namespace command { @@ -14,29 +14,28 @@ 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) +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_; } +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(); +void Command::setParameterValues(const std::vector<Value> &values) { + const std::vector<Value::Type> ¶mTypes = valueTypes(); // Check that number of parameters is correct if (values.size() != paramTypes.size()) { - throw ExceptionAbstract - (ExceptionAbstract::ABSTRACT, "wrong number of parameters"); + 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()); + ss << "argument " << iParam + << " is of wrong type: " << Value::typeName(paramTypes[iParam]) + << " expected, got " << Value::typeName(values[iParam].type()); throw ExceptionAbstract(ExceptionAbstract::TOOLS, ss.str()); } } @@ -44,12 +43,13 @@ void Command::setParameterValues(const std::vector<Value>& values) { valueVector_ = values; } -const std::vector<Value>& Command::getParameterValues() const -{ return valueVector_; } +const std::vector<Value> &Command::getParameterValues() const { + return valueVector_; +} Value Command::execute() { return doExecute(); } -Entity& Command::owner() { return owner_; } +Entity &Command::owner() { return owner_; } std::string Command::getDocstring() const { return docstring_; } -} // namespace command -} // namespace dynamicgraph +} // namespace command +} // namespace dynamicgraph diff --git a/src/command/value.cpp b/src/command/value.cpp index 869242dfa82310f4917d4dc744bb7137b51de629..f9464ab131606920987782b2c9e78e1b6a0f23c3 100644 --- a/src/command/value.cpp +++ b/src/command/value.cpp @@ -7,290 +7,271 @@ #include "dynamic-graph/value.h" #include "dynamic-graph/exception-abstract.h" -namespace dynamicgraph -{ - namespace command - { +namespace dynamicgraph { +namespace command { - static void* copyValue(const Value& value); +static void *copyValue(const Value &value); - EitherType::EitherType(const Value& value) : value_(new Value(value)) {} - - EitherType::~EitherType() - { - delete value_; - value_ = NULL; - } - - EitherType::operator bool() const { return value_->boolValue(); } - EitherType::operator unsigned() const { return value_->unsignedValue(); } - EitherType::operator 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::operator Eigen::Matrix4d() - const { return value_->matrix4dValue(); } +EitherType::EitherType(const Value &value) : value_(new Value(value)) {} - 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::~EitherType() { + delete value_; + value_ = NULL; +} - Value::~Value() { deleteValue(); } +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(); } - 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)) {} +EitherType::operator Eigen::Matrix4d() const { return value_->matrix4dValue(); } - Value::Value(const Value& value) : - type_(value.type_), value_(copyValue(value)) {} +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:; + } +} - 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() { deleteValue(); } - Value::Value() : type_(NONE), value_(NULL) {} +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::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(const Value &value) + : type_(value.type_), value_(copyValue(value)) {} - const EitherType Value::value() const { return EitherType(*this); } +void *copyValue(const Value &value) { + void *copy; + switch (value.type()) { - Value::Type Value::type() const { return 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; +} - bool Value::boolValue() const { - if (type_ == BOOL) return *((const bool*)value_); - throw ExceptionAbstract(ExceptionAbstract::TOOLS, "value is not an bool"); - } +Value::Value() : type_(NONE), value_(NULL) {} - unsigned Value::unsignedValue() const { - if (type_ == UNSIGNED) return *((const unsigned*)value_); - throw ExceptionAbstract - (ExceptionAbstract::TOOLS, - "value is not an unsigned int"); - } +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; +} - int Value::intValue() const { - if (type_ == INT) return *((const int*)value_); - throw ExceptionAbstract - (ExceptionAbstract::TOOLS, "value is not an int int"); - } +const EitherType Value::value() const { return EitherType(*this); } - float Value::floatValue() const { - float result; - if (FLOAT != type_) - throw ExceptionAbstract - (ExceptionAbstract::TOOLS, "value is not a float"); - result = *((const float*)value_); - return result; - } +Value::Type Value::type() const { return type_; } - double Value::doubleValue() const { - double result; - if (DOUBLE != type_) - throw ExceptionAbstract - (ExceptionAbstract::TOOLS, "value is not a double"); - result = *((const double*)value_); - return result; - } +bool Value::boolValue() const { + if (type_ == BOOL) + return *((const bool *)value_); + throw ExceptionAbstract(ExceptionAbstract::TOOLS, "value is not an bool"); +} - std::string Value::stringValue() const { - if (type_ == STRING) return *((const std::string*)value_); - throw ExceptionAbstract - (ExceptionAbstract::TOOLS, "value is not an string"); - } +unsigned Value::unsignedValue() const { + if (type_ == UNSIGNED) + return *((const unsigned *)value_); + throw ExceptionAbstract(ExceptionAbstract::TOOLS, + "value is not an unsigned int"); +} - Vector Value::vectorValue() const { - if (type_ == VECTOR) return *((const Vector*)value_); - throw ExceptionAbstract - (ExceptionAbstract::TOOLS, "value is not an vector"); - } +int Value::intValue() const { + if (type_ == INT) + return *((const int *)value_); + throw ExceptionAbstract(ExceptionAbstract::TOOLS, "value is not an int int"); +} - Eigen::MatrixXd Value::matrixXdValue() const { - if (type_ == MATRIX) return *((const Eigen::MatrixXd*)value_); - throw ExceptionAbstract - (ExceptionAbstract::TOOLS, "value is not a Eigen matrixXd"); - } +float Value::floatValue() const { + float result; + if (FLOAT != type_) + throw ExceptionAbstract(ExceptionAbstract::TOOLS, "value is not a float"); + result = *((const float *)value_); + return result; +} - Eigen::Matrix4d Value::matrix4dValue() const { - if (type_ == MATRIX4D) return *((const Eigen::Matrix4d*)value_); - throw ExceptionAbstract - (ExceptionAbstract::TOOLS, "value is not a Eigen matrix4d"); - } +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::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::stringValue() const { + if (type_ == STRING) + return *((const std::string *)value_); + throw ExceptionAbstract(ExceptionAbstract::TOOLS, "value is not an string"); +} - 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; - } +Vector Value::vectorValue() const { + if (type_ == VECTOR) + return *((const Vector *)value_); + throw ExceptionAbstract(ExceptionAbstract::TOOLS, "value is not an vector"); +} - 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; +Eigen::MatrixXd Value::matrixXdValue() const { + if (type_ == MATRIX) + return *((const Eigen::MatrixXd *)value_); + throw ExceptionAbstract(ExceptionAbstract::TOOLS, + "value is not a Eigen matrixXd"); +} - } // namespace command -} // namespace dynamicgraph +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::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; + +} // namespace command +} // namespace dynamicgraph diff --git a/src/debug/debug.cpp b/src/debug/debug.cpp index 1edfec93b9824fda777980a301063ed423c9aab9..7734c38e12a5ee68846459d1e8130c87af777372 100644 --- a/src/debug/debug.cpp +++ b/src/debug/debug.cpp @@ -15,10 +15,10 @@ using namespace dynamicgraph; #ifdef WIN32 const char *DebugTrace::DEBUG_FILENAME_DEFAULT = - "c:/tmp/dynamic-graph-traces.txt"; + "c:/tmp/dynamic-graph-traces.txt"; #else /*WIN32*/ const char *DebugTrace::DEBUG_FILENAME_DEFAULT = - "/tmp/dynamic-graph-traces.txt"; + "/tmp/dynamic-graph-traces.txt"; #endif /*WIN32*/ #ifdef VP_DEBUG @@ -30,9 +30,9 @@ std::ofstream dg_debugfile("/tmp/dynamic-graph-traces.txt", std::ios::trunc &std::ios::out); #endif /*WIN32*/ #else -std::ofstream dg_debugfile; +std::ofstream dg_debugfile; class dgDebug_init { - public: +public: dgDebug_init() { dg_debugfile.setstate(std::ios::failbit); } }; dgDebug_init dgDebug_initialisator; @@ -42,10 +42,11 @@ dgDebug_init dgDebug_initialisator; namespace dynamicgraph { DebugTrace dgDEBUGFLOW(dg_debugfile); DebugTrace dgERRORFLOW(dg_debugfile); -} // namespace dynamicgraph +} // namespace dynamicgraph void DebugTrace::openFile(const char *filename) { - if (dg_debugfile.good() && dg_debugfile.is_open()) dg_debugfile.close(); + if (dg_debugfile.good() && dg_debugfile.is_open()) + dg_debugfile.close(); dg_debugfile.clear(); dg_debugfile.open(filename, std::ios::trunc & std::ios::out); } @@ -56,4 +57,3 @@ void DebugTrace::closeFile(const char *) { } dg_debugfile.setstate(std::ios::failbit); } - diff --git a/src/debug/logger.cpp b/src/debug/logger.cpp index c0979bf88fa292ffef1a99420cb2f0b3c8d13779..aa3d281437238b61445667acc6fa6565bb6c9a94 100644 --- a/src/debug/logger.cpp +++ b/src/debug/logger.cpp @@ -12,93 +12,84 @@ #endif #define ENABLE_RT_LOG +#include <dynamic-graph/logger.h> +#include <iomanip> // std::setprecision +#include <iostream> #include <sstream> #include <stdio.h> -#include <iostream> -#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"; - } - - bool Logger::setTimeSample(double t) - { - if (t <= 0.0) return false; - m_timeSample = t; - return true; +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; } - - bool Logger::setStreamPrintPeriod(double s) - { - if (s <= 0.0) return false; - m_streamPrintPeriod = s; - return true; - } - - double Logger::getTimeSample() - { return m_timeSample; } - - double Logger::getStreamPrintPeriod() - { return m_streamPrintPeriod; } -} // namespace dynamicgraph + dgRTLOG() << msg.c_str() << "\n"; +} + +bool Logger::setTimeSample(double t) { + if (t <= 0.0) + return false; + m_timeSample = t; + return true; +} + +bool Logger::setStreamPrintPeriod(double s) { + if (s <= 0.0) + return false; + m_streamPrintPeriod = s; + return true; +} + +double Logger::getTimeSample() { return m_timeSample; } + +double Logger::getStreamPrintPeriod() { return m_streamPrintPeriod; } +} // namespace dynamicgraph diff --git a/src/debug/real-time-logger.cpp b/src/debug/real-time-logger.cpp index 24a662bccc2cfccff601da1a7c297cdd8723bf71..3646d1d04dcb89e575d86f7992e1d7cd4495f013 100644 --- a/src/debug/real-time-logger.cpp +++ b/src/debug/real-time-logger.cpp @@ -8,153 +8,134 @@ #include <dynamic-graph/real-time-logger.h> -#include <boost/thread/thread.hpp> #include <boost/date_time/posix_time/posix_time.hpp> +#include <boost/thread/thread.hpp> -namespace dynamicgraph -{ - RealTimeLogger::RealTimeLogger(const std::size_t& bufferSize) +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]; + nbDiscarded_(0) { + for (std::size_t i = 0; i < buffer_.size(); ++i) + buffer_[i] = new Data; +} + +RealTimeLogger::~RealTimeLogger() { + // Check that we are not spinning... + for (std::size_t i = 0; i < buffer_.size(); ++i) + delete buffer_[i]; +} + +bool RealTimeLogger::spinOnce() { + if (empty()) + return false; + Data *data = buffer_[frontIdx_]; + frontIdx_ = (frontIdx_ + 1) % buffer_.size(); + std::string str = data->buf.str(); + // It is important to pass str.c_str() and not str + // because the str object may contains a '\0' so + // str.size() may be different from strlen(str.c_str()) + for (std::size_t i = 0; i < outputs_.size(); ++i) + outputs_[i]->write(str.c_str()); + return true; +} + +RTLoggerStream RealTimeLogger::front() { + // If no output or if buffer is full, discard message. + if (outputs_.empty() || full()) { + nbDiscarded_++; + return RTLoggerStream(NULL, oss_); } - - bool 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 alone = wmutex.try_lock(); + // If someone is writting, discard message. + if (!alone) { + nbDiscarded_++; + return RTLoggerStream(NULL, 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_); + 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; - } - - 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; } + } - 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 spin(RealTimeLogger* logger) - { - // Change the thread's scheduler from real-time to normal - // and reduce its priority - - while (!requestShutdown_ || !logger->empty()) - { - // If the logger did not write anything, it means the buffer is empty. - // Do a pause - if (!logger->spinOnce()) - boost::this_thread::sleep(boost::posix_time::milliseconds(1000)); - if (changedThreadParams) changeThreadParams(); - } - } - }; - - RealTimeLogger* RealTimeLogger::instance_ = NULL; - RealTimeLogger::thread* RealTimeLogger::thread_ = NULL; - - RealTimeLogger& RealTimeLogger::instance() - { - if (instance_ == NULL) - { - instance_ = new RealTimeLogger(1000); - thread_ = new thread(instance_); - } - return *instance_; } +}; + +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_); } -} // namespace dynamicgraph + 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 1ee2bbcf502b39505ab2543d07b7013fd7906066..18e7d0dddaa2b9add8111e4bd6068fe39f04f63c 100644 --- a/src/dgraph/entity.cpp +++ b/src/dgraph/entity.cpp @@ -8,104 +8,93 @@ */ /*! Local framework includes */ +#include <dynamic-graph/command.h> +#include <dynamic-graph/debug.h> #include <dynamic-graph/entity.h> #include <dynamic-graph/pool.h> -#include <dynamic-graph/pool.h> -#include <dynamic-graph/debug.h> -#include <dynamic-graph/command.h> /*! System includes */ -#include <stdlib.h> #include <sstream> +#include <stdlib.h> using namespace std; using namespace dynamicgraph; using dynamicgraph::command::Command; -void Entity::entityRegistration() -{ +void Entity::entityRegistration() { PoolStorage::getInstance()->registerEntity(name, this); } -void Entity::entityDeregistration() -{ +void Entity::entityDeregistration() { PoolStorage::getInstance()->deregisterEntity(name); } -Entity::Entity(const string& name__) : name(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(); - } + if (name.length() == 0) { + stringstream oss; + oss << rand(); + // name = this->getClassName(); + // Cannot call a virtual function from the constructor + name += "::"; + name += oss.str(); + } entityRegistration(); } Entity::~Entity() { dgDEBUG(25) << "# In (" << name << " { " << endl; - for (std::map<const std::string, Command*>::iterator it = - commandMap.begin(); it != commandMap.end(); it++) - { - delete it->second; - } + for (std::map<const std::string, Command *>::iterator it = commandMap.begin(); + it != commandMap.end(); it++) { + delete it->second; + } dgDEBUGOUT(25); } /* -------------------------------------------------------------------------- */ /* --- SIGNALS -------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ -void Entity::signalRegistration(const SignalArray<int>& signals) -{ - for (unsigned int i = 0; i < signals.getSize(); ++i) +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 { - 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; + 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) { +void Entity::signalDeregistration(const std::string &signame) { SignalMap::iterator sigkey = signalMap.find(signame); - if (sigkey == signalMap.end()) // key does not exist + 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()); + 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 <" + dgDEBUG(10) << "Deregister signal <" << signame << "> for entity <" << getName() << "> ." << endl; signalMap.erase(signame); } @@ -116,72 +105,68 @@ std::string Entity::getDocString() const { 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()); \ - } \ +#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 -{ +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; - } + 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 -{ +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); - } + for (SignalMap::const_iterator iter = signalMap.begin(); iterend != iter; + ++iter) { + (*(iter->second)).writeGraph(os); + } return os; } -std::ostream& Entity::writeCompletionList(std::ostream& os) const -{ +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; - } + for (SignalMap::const_iterator iter = signalMap.begin(); iterend != iter; + ++iter) { + os << getName() << "." << (*(iter->second)).shortName() << std::endl; + } os << getCommandList() << std::endl; return os; } -void Entity::display(std::ostream& os) const -{ os << this->getClassName() << ": " << name; } +void Entity::display(std::ostream &os) const { + os << this->getClassName() << ": " << name; +} -std::ostream& dynamicgraph::operator<<(std::ostream& os, const Entity& ent) -{ +std::ostream &dynamicgraph::operator<<(std::ostream &os, const Entity &ent) { ent.display(os); return os; } @@ -193,35 +178,36 @@ Entity::SignalMap Entity::getSignalMap() const { return signalMap; } /* --- 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."); + " already registered in Entity."); } - std::pair<const std::string, Command*> item(inName, command); + 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) { +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."); + "> is not registered in Entity."); } return commandMap[commandName]; } -void Entity::sendMsg -(const std::string& msg, MsgType t, const char* file, int 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 0e5c75c28edf167c42646cc6378576ac6b1c63a3..514ea669c7a171623fb2828a52c98e646daa7aa6 100644 --- a/src/dgraph/factory.cpp +++ b/src/dgraph/factory.cpp @@ -10,136 +10,112 @@ using namespace std; using namespace dynamicgraph; -namespace dynamicgraph -{ - FactoryStorage* FactoryStorage::getInstance() - { - if (instance_ == 0) - { - instance_ = new FactoryStorage; - } - return instance_; +namespace dynamicgraph { +FactoryStorage *FactoryStorage::getInstance() { + if (instance_ == 0) { + instance_ = new FactoryStorage; } + return instance_; +} -void FactoryStorage::destroy() -{ +void FactoryStorage::destroy() { delete instance_; instance_ = NULL; } FactoryStorage::FactoryStorage() : entityMap() {} -FactoryStorage::~FactoryStorage() -{ +FactoryStorage::~FactoryStorage() { instance_ = 0; dgDEBUGINOUT(25); } -void FactoryStorage:: -registerEntity -(const std::string& entname, FactoryStorage::EntityConstructor_ptr ent) -{ +void FactoryStorage::registerEntity(const std::string &entname, + FactoryStorage::EntityConstructor_ptr ent) { dgDEBUGIN(25); - 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; + if (existEntity(entname)) { + DG_THROW ExceptionFactory( + ExceptionFactory::OBJECT_CONFLICT, + "Another entity class already defined with the same name. ", + "(while adding entity class <%s> inside the factory).", + entname.c_str()); + dgERRORF("Another entity class already defined with the same name. " + "(while adding entity class <%s> inside the factory).", + entname.c_str()); + } else { + if (!ent) { + // FIXME: we should have a better error code for that. + DG_THROW ExceptionFactory(ExceptionFactory::OBJECT_CONFLICT, + "Bad entity constructor."); } + + dgDEBUG(30) << "Register entity <" << entname << "> in the factory." + << std::endl; + entityMap[entname] = ent; + } dgDEBUGOUT(25); } -void FactoryStorage::deregisterEntity(const std::string& entname) -{ +void FactoryStorage::deregisterEntity(const std::string &entname) { dgDEBUGIN(25); - 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); - } + if (!existEntity(entname)) { + DG_THROW ExceptionFactory( + ExceptionFactory::OBJECT_CONFLICT, "Entity class not defined yet. ", + "(while removing entity class <%s>).", entname.c_str()); + dgERRORF(ExceptionFactory::OBJECT_CONFLICT, + "Entity class not defined yet. " + "(while removing entity class <%s>).", + entname.c_str()); + } else { + dgDEBUG(30) << "Deregister entity <" << entname << "> from the factory." + << std::endl; + entityMap.erase(entname); + } dgDEBUGOUT(25); } -Entity* FactoryStorage::newEntity -(const std::string& classname, const std::string& objname) const -{ - dgDEBUG(15) << "New <" << classname << ">Entity <" - << objname << ">" << std::endl; +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()); - } + if (entPtr == entityMap.end()) { + DG_THROW ExceptionFactory( + ExceptionFactory::UNREFERED_OBJECT, "Unknown entity.", + " (while calling new_entity <%s>)", classname.c_str()); + } 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 -{ +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 -{ +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) + BOOST_FOREACH (const iter_t &entity, entityMap) outList.push_back(entity.first); } -EntityRegisterer::EntityRegisterer -(const std::string& entityClassName, - FactoryStorage::EntityConstructor_ptr maker) - : entityName(entityClassName) -{ +EntityRegisterer::EntityRegisterer(const std::string &entityClassName, + FactoryStorage::EntityConstructor_ptr maker) + : entityName(entityClassName) { dgDEBUGIN(15); FactoryStorage::getInstance()->registerEntity(entityClassName, maker); dgDEBUGOUT(15); } -EntityRegisterer::~EntityRegisterer() -{ +EntityRegisterer::~EntityRegisterer() { dgDEBUGIN(15); FactoryStorage::getInstance()->deregisterEntity(entityName); dgDEBUGOUT(15); } // The global factory. -FactoryStorage* FactoryStorage::instance_ = NULL; -} // end of namespace dynamicgraph. +FactoryStorage *FactoryStorage::instance_ = NULL; +} // end of namespace dynamicgraph. diff --git a/src/dgraph/pool.cpp b/src/dgraph/pool.cpp index b27056f8bb65812d796abdb6de651a2575f712e9..ff5d87a1588b20ec0a0941d46bec5cc0ac729072 100644 --- a/src/dgraph/pool.cpp +++ b/src/dgraph/pool.cpp @@ -12,13 +12,13 @@ /* --------------------------------------------------------------------- */ /* --- DYNAMIC-GRAPH --- */ -#include <list> -#include <typeinfo> -#include <sstream> -#include <string> #include "dynamic-graph/pool.h" #include "dynamic-graph/debug.h" #include "dynamic-graph/entity.h" +#include <list> +#include <sstream> +#include <string> +#include <typeinfo> using namespace dynamicgraph; @@ -26,81 +26,69 @@ using namespace dynamicgraph; /* --- CLASS ----------------------------------------------------------- */ /* --------------------------------------------------------------------- */ -PoolStorage* PoolStorage::getInstance() -{ - if (instance_ == 0) - { - instance_ = new PoolStorage; - } +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(); // 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 + 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()); + 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; } - 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 + 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; + 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) -{ +Entity &PoolStorage::getEntity(const std::string &name) { dgDEBUG(25) << "Get <" << name << ">" << std::endl; Entities::iterator entPtr = entityMap.find(name); if (entPtr == entityMap.end()) { @@ -111,14 +99,15 @@ Entity& PoolStorage::getEntity 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) { + return entityMap.find(name) != entityMap.end(); +} -bool PoolStorage::existEntity(const std::string& name, Entity*& ptr) -{ +bool PoolStorage::existEntity(const std::string &name, Entity *&ptr) { Entities::iterator entPtr = entityMap.find(name); if (entPtr == entityMap.end()) return false; @@ -128,19 +117,18 @@ bool PoolStorage::existEntity(const std::string& name, Entity*& ptr) } } -void PoolStorage::clearPlugin(const std::string& name) -{ +void PoolStorage::clearPlugin(const std::string &name) { dgDEBUGIN(5); - std::list<Entity*> toDelete; + std::list<Entity *> toDelete; - for (Entities::iterator entPtr = entityMap.begin(); - entPtr != entityMap.end(); ++entPtr) + 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(); + for (std::list<Entity *>::iterator iter = toDelete.begin(); iter != toDelete.end(); ++iter) - delete (Entity*)*iter; + delete (Entity *)*iter; dgDEBUGOUT(5); } @@ -152,8 +140,7 @@ void PoolStorage::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); size_t IdxSeparatorFound = aFileName.rfind("/"); @@ -175,8 +162,7 @@ void PoolStorage::writeGraph(const std::string& aFileName) /* Opening the file and writing the first comment. */ std::ofstream GraphFile(aFileName.c_str(), std::ofstream::out); - GraphFile << "/* This graph has been automatically generated. " - << std::endl; + GraphFile << "/* This graph has been automatically generated. " << std::endl; GraphFile << " " << 1900 + ltimeformatted.tm_year << " Month: " << 1 + ltimeformatted.tm_mon << " Day: " << ltimeformatted.tm_mday @@ -187,47 +173,41 @@ void PoolStorage::writeGraph(const std::string& aFileName) 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; + << "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.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) -{ +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 + if (!cmdparse.good()) // The callback is not an object method return false; objName = buffer; @@ -237,16 +217,15 @@ static bool objectNameParser return true; } -SignalBase<int>& PoolStorage::getSignal(std::istringstream& sigpath) -{ +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); + Entity &ent = getEntity(objname); return ent.getSignal(signame); } -PoolStorage* PoolStorage::instance_ = 0; +PoolStorage *PoolStorage::instance_ = 0; diff --git a/src/exception/exception-abstract.cpp b/src/exception/exception-abstract.cpp index 3efc207dcee40b09d84b4a585508cc9fb42e0c35..2d9089c5f581d6eeb1420aa8e44774864cd2ae09 100644 --- a/src/exception/exception-abstract.cpp +++ b/src/exception/exception-abstract.cpp @@ -3,63 +3,59 @@ // #include <cstring> -#include <dynamic-graph/exception-abstract.h> #include <dynamic-graph/debug.h> +#include <dynamic-graph/exception-abstract.h> -namespace dynamicgraph -{ - const std::string ExceptionAbstract::EXCEPTION_NAME = "Abstract"; +namespace dynamicgraph { +const std::string ExceptionAbstract::EXCEPTION_NAME = "Abstract"; - ExceptionAbstract::ExceptionAbstract - (const int& _code, const std::string& _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; - - 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); +ExceptionAbstract::Param &ExceptionAbstract::Param::initCopy(const Param &p) { + if (&p == this) return *this; - } - - 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; + 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); +} + +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 78e1b8dd427b1099bfd7ce363493d24d7e561c77..f510bca5179f50beaa9cd578a8ec9de0f9e6c27f 100644 --- a/src/exception/exception-factory.cpp +++ b/src/exception/exception-factory.cpp @@ -7,10 +7,10 @@ * */ -#include <dynamic-graph/exception-factory.h> +#include <cstdio> #include <dynamic-graph/debug.h> +#include <dynamic-graph/exception-factory.h> #include <stdarg.h> -#include <cstdio> using namespace dynamicgraph; @@ -20,20 +20,17 @@ using namespace dynamicgraph; const std::string ExceptionFactory::EXCEPTION_NAME = "Factory"; -ExceptionFactory::ExceptionFactory -(const ExceptionFactory::ErrorCodeEnum& errcode, const std::string& msg) - : ExceptionAbstract(errcode, msg) -{ +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); @@ -42,8 +39,8 @@ ExceptionFactory::ExceptionFactory vsnprintf(buffer, SIZE, format, args); dgDEBUG(15) << "Created " - << " with message <" << msg << "> and buffer <" - << buffer << ">. " << std::endl; + << " with message <" << msg << "> and buffer <" << buffer << ">. " + << std::endl; message += buffer; diff --git a/src/exception/exception-signal.cpp b/src/exception/exception-signal.cpp index 7713fa5dc1b213885484f38e1cf996e852cf3569..ee80de7161801be1006310a6d1f6f19bea643e30 100644 --- a/src/exception/exception-signal.cpp +++ b/src/exception/exception-signal.cpp @@ -7,9 +7,9 @@ * */ +#include <cstdio> #include <dynamic-graph/exception-signal.h> #include <stdarg.h> -#include <cstdio> using namespace dynamicgraph; @@ -19,17 +19,14 @@ 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, - const char* format, ...) - : 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) { va_list args; va_start(args, format); diff --git a/src/exception/exception-traces.cpp b/src/exception/exception-traces.cpp index 970ae142084370e62cb0e181d286a6cae8561938..7fdb8866013e171a0f5a33fd7c9a8c878d960750 100644 --- a/src/exception/exception-traces.cpp +++ b/src/exception/exception-traces.cpp @@ -7,9 +7,9 @@ * */ +#include <cstdio> #include <dynamic-graph/exception-traces.h> #include <stdarg.h> -#include <cstdio> using namespace dynamicgraph; /* --------------------------------------------------------------------- */ @@ -18,17 +18,14 @@ using namespace dynamicgraph; const std::string ExceptionTraces::EXCEPTION_NAME = "Traces"; -ExceptionTraces::ExceptionTraces -(const ExceptionTraces::ErrorCodeEnum& errcode, - const std::string& 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); diff --git a/src/mt/process-list.cpp b/src/mt/process-list.cpp index 8b3b7aacb2ad17294b97ad1bf7e02efccf1ab6d7..307209e4e190bf0c95aa812d2e2a311d9367c000 100644 --- a/src/mt/process-list.cpp +++ b/src/mt/process-list.cpp @@ -10,24 +10,15 @@ 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) {} - -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; + : 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; aCPULine >> luser_mode_time; aCPULine >> lnice_time; @@ -46,13 +37,13 @@ void CPUData::ProcessLine(std::istringstream &aCPULine) // Compute cumulative time unsigned long long int lidle_all_time = 0, lsystem_all_time = 0, - lguest_all_time = 0, ltotal_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; + lidle_all_time + lsteal_time + lguest_all_time; // Update periodic computation. user_mode_period_ = computePeriod(luser_mode_time, user_mode_time_); @@ -131,29 +122,27 @@ void System::readProcStat() { 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 (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-cast-helper.cpp b/src/signal/signal-cast-helper.cpp index c31c565287d91054bb2b4deddb26a4b89de82de7..fd20f7e7f667c5901ba080afe12616733b117a7c 100644 --- a/src/signal/signal-cast-helper.cpp +++ b/src/signal/signal-cast-helper.cpp @@ -5,91 +5,83 @@ // Nicolas Mansard // +#include <algorithm> #include <boost/date_time/posix_time/posix_time.hpp> -#include <dynamic-graph/signal-caster.h> -#include <dynamic-graph/signal-cast-helper.h> -#include <dynamic-graph/dynamic-graph-api.h> -#include <exception> #include <boost/lambda/bind.hpp> -#include <string> -#include <sstream> -#include <algorithm> +#include <dynamic-graph/dynamic-graph-api.h> #include <dynamic-graph/exception-signal.h> #include <dynamic-graph/linear-algebra.h> +#include <dynamic-graph/signal-cast-helper.h> +#include <dynamic-graph/signal-caster.h> +#include <exception> +#include <sstream> +#include <string> -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::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::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); + } +} - /// 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 790ea6eafc4cc1ebec6978a0e32cfe02d77642d3..59835116ba757967e37d8c4e2d5618e9de363200 100644 --- a/src/signal/signal-caster.cpp +++ b/src/signal/signal-caster.cpp @@ -4,117 +4,103 @@ // Olivier Stasse // -#include <dynamic-graph/signal-caster.h> +#include <algorithm> +#include <boost/lambda/bind.hpp> #include <dynamic-graph/dynamic-graph-api.h> +#include <dynamic-graph/exception-signal.h> +#include <dynamic-graph/signal-caster.h> #include <exception> -#include <boost/lambda/bind.hpp> -#include <string> #include <sstream> -#include <algorithm> -#include <dynamic-graph/exception-signal.h> +#include <string> #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()); - } +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_[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_; + 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; +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 9a5388ee864a35c33ee2076b02b042137d844ca4..f45fec1fef291c26a1979af0d62ee479aba3a326 100644 --- a/src/traces/tracer-real-time.cpp +++ b/src/traces/tracer-real-time.cpp @@ -12,14 +12,14 @@ /* --------------------------------------------------------------------- */ /* DG */ -#include <iomanip> #include <boost/bind.hpp> +#include <iomanip> -#include <dynamic-graph/tracer-real-time.h> +#include <dynamic-graph/all-commands.h> #include <dynamic-graph/debug.h> -#include <dynamic-graph/pool.h> #include <dynamic-graph/factory.h> -#include <dynamic-graph/all-commands.h> +#include <dynamic-graph/pool.h> +#include <dynamic-graph/tracer-real-time.h> using namespace std; using namespace dynamicgraph; @@ -30,9 +30,8 @@ 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); } @@ -42,7 +41,7 @@ OutStringStream::~OutStringStream() { dgDEBUGOUT(15); } -void OutStringStream::resize(const std::streamsize& size) { +void OutStringStream::resize(const std::streamsize &size) { dgDEBUGIN(15); index = 0; @@ -55,7 +54,7 @@ void OutStringStream::resize(const std::streamsize& 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) { @@ -69,7 +68,7 @@ bool OutStringStream::addData(const char* data, const std::streamoff& size) { return true; } -void OutStringStream::dump(std::ostream& os) { +void OutStringStream::dump(std::ostream &os) { dgDEBUGIN(15); os.write(buffer, index); dgDEBUGOUT(15); @@ -86,19 +85,17 @@ void OutStringStream::empty() { /* --------------------------------------------------------------------- */ /* --------------------------------------------------------------------- */ -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)); + 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, @@ -106,7 +103,7 @@ TracerRealTime::TracerRealTime(const std::string& n) : addCommand("setBufferSize", makeDirectSetter(*this, &bufferSize, docDirectSetter("bufferSize", "int"))); - } // using namespace command + } // using namespace command dgDEBUGOUT(15); } @@ -115,10 +112,8 @@ 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()) { @@ -129,13 +124,13 @@ void TracerRealTime::openFile 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; + 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 (); + OutStringStream *newbuffer = new OutStringStream(); // std::stringstream (); newbuffer->resize(bufferSize); newbuffer->givenname = givenname; files.push_back(newbuffer); @@ -152,8 +147,8 @@ void TracerRealTime::closeFiles() { 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(); @@ -179,22 +174,22 @@ void TracerRealTime::trace() { while (files.end() != iter) { dgDEBUG(35) << "Next" << endl; - std::ostream* os = *iter; + std::ostream *os = *iter; if (NULL == os) { - DG_THROW ExceptionTraces - (ExceptionTraces::NOT_OPEN, "The buffer is null", ""); + DG_THROW ExceptionTraces(ExceptionTraces::NOT_OPEN, "The buffer is null", + ""); } // std::stringstream & file = * dynamic_cast< stringstream* >(os); - OutStringStream* file = dynamic_cast<OutStringStream*>(os); // segfault + OutStringStream *file = dynamic_cast<OutStringStream *>(os); // segfault if (NULL == file) { - DG_THROW ExceptionTraces - (ExceptionTraces::NOT_OPEN, "The buffer is not open", ""); + DG_THROW ExceptionTraces(ExceptionTraces::NOT_OPEN, + "The buffer is not open", ""); } - std::ofstream& hardFile = **hardIter; + std::ofstream &hardFile = **hardIter; if (!hardFile.good()) { - DG_THROW ExceptionTraces - (ExceptionTraces::NOT_OPEN, "The file is not open", ""); + DG_THROW ExceptionTraces(ExceptionTraces::NOT_OPEN, + "The file is not open", ""); } if ((hardFile.good()) && (NULL != file)) { @@ -232,18 +227,17 @@ void TracerRealTime::trace() { 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); } @@ -254,27 +248,26 @@ void TracerRealTime::emptyBuffers() { // 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; + 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; + dgDEBUG(35) << "Write data [" << file.tellp() << "] <" << file.str().c_str() + << "> " << endl; - } catch (ExceptionAbstract& exc) { + } catch (ExceptionAbstract &exc) { throw exc; } catch (...) { - DG_THROW ExceptionTraces - (ExceptionTraces::NOT_OPEN, "The buffer is not open", ""); + DG_THROW ExceptionTraces(ExceptionTraces::NOT_OPEN, + "The buffer is not open", ""); } dgDEBUGOUT(15); @@ -285,18 +278,19 @@ void TracerRealTime::recordSignal /* --------------------------------------------------------------------- */ /* --------------------------------------------------------------------- */ -void TracerRealTime::display(std::ostream& os) const { - os << CLASS_NAME << " " << name - << " [mode=" << (play ? "play" : "pause") << "] : " << endl +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); + const OutStringStream *file = dynamic_cast<OutStringStream *>(*iterFile); os << " -> " << (*iter)->getName(); - if (file->givenname.length()) os << " (in " << file->givenname << ")"; + if (file->givenname.length()) + os << " (in " << file->givenname << ")"; os << "\t"; if (file) { const std::streamsize PRECISION = os.precision(); @@ -316,9 +310,10 @@ void TracerRealTime::display(std::ostream& os) const { } 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)"; + << std::setprecision(2) << (((double)MSIZE + 0.0) / (1 << dec)) << unit + << "]\t"; + if (file->full) + os << "(FULL)"; os.precision(PRECISION); } os << endl; @@ -326,7 +321,7 @@ void TracerRealTime::display(std::ostream& os) const { } } -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 17d625692dea7b94d9a6938fcbed852b199d66f0..9f6dfb9470b33f655ab84a2cb6baa3b19b36efb3 100644 --- a/src/traces/tracer.cpp +++ b/src/traces/tracer.cpp @@ -12,13 +12,13 @@ /* --------------------------------------------------------------------- */ /* DG */ -#include <dynamic-graph/tracer.h> +#include <boost/bind.hpp> +#include <dynamic-graph/all-commands.h> #include <dynamic-graph/debug.h> -#include <dynamic-graph/value.h> -#include <dynamic-graph/pool.h> #include <dynamic-graph/factory.h> -#include <dynamic-graph/all-commands.h> -#include <boost/bind.hpp> +#include <dynamic-graph/pool.h> +#include <dynamic-graph/tracer.h> +#include <dynamic-graph/value.h> using namespace std; using namespace dynamicgraph; @@ -31,21 +31,11 @@ DYNAMICGRAPH_FACTORY_ENTITY_PLUGIN(Tracer, "Tracer"); /* --------------------------------------------------------------------- */ 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") -{ + : 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 --- */ @@ -53,17 +43,15 @@ Tracer::Tracer(const std::string n) using namespace dynamicgraph::command; std::string doc; - doc = docCommandVoid2("Add a new signal to trace.", - "string (signal name)", + doc = docCommandVoid2("Add a new signal to trace.", "string (signal name)", "string (filename, empty for default"); addCommand("add", - makeCommandVoid2(*this, - &Tracer::addSignalToTraceByName, doc)); + makeCommandVoid2(*this, &Tracer::addSignalToTraceByName, doc)); - doc = docCommandVoid0 - ("Remove all signals. If necessary, close open files."); - addCommand("clear", makeCommandVoid0 - (*this, &Tracer::clearSignalToTrace, doc)); + doc = + docCommandVoid0("Remove all signals. If necessary, close open files."); + addCommand("clear", + makeCommandVoid0(*this, &Tracer::clearSignalToTrace, doc)); doc = docCommandVoid3( "Gives the args for file opening, and " @@ -74,9 +62,8 @@ Tracer::Tracer(const std::string n) doc = docCommandVoid0("Close all the open files."); addCommand("close", makeCommandVoid0(*this, &Tracer::closeFiles, doc)); - doc = docCommandVoid0( - "If necessary, dump " - "(can be done automatically for some traces type)."); + 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."); @@ -91,33 +78,30 @@ Tracer::Tracer(const std::string n) addCommand("setTimeStart", makeDirectSetter(*this, &timeStart, docDirectSetter("timeStart", "int"))); - } // using namespace command + } // 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); + 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); + SignalBase<int> &sig = PoolStorage::getInstance()->getSignal(iss); addSignalToTrace(sig, filename); dgDEBUGOUT(15); } @@ -126,8 +110,7 @@ void Tracer::addSignalToTraceByName * does not modify the file list (it does not close * the files in particular. */ -void Tracer::clearSignalToTrace() -{ +void Tracer::clearSignalToTrace() { closeFiles(); toTraceSignals.clear(); triger.clearDependencies(); @@ -139,26 +122,26 @@ void Tracer::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(); rootdir = rootdir_; - if ((0 < n) & ('/' != rootdir[n - 1])) rootdir += '/'; + if ((0 < n) & ('/' != rootdir[n - 1])) + rootdir += '/'; 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; + dgDEBUG(15) << "Open <" << (*iter)->getName() << "> in <" << *iterName + << ">." << std::endl; openFile(**iter, *iterName); ++iter; ++iterName; @@ -168,10 +151,7 @@ void Tracer::openFiles 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()) { @@ -183,17 +163,16 @@ void Tracer::openFile string filename = rootdir + basename + signame + suffix; dgDEBUG(5) << "Sig <" << sig.getName() << ">: new file " << filename << endl; - std::ofstream* newfile = new std::ofstream(filename.c_str()); + 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; + std::ostream *filePtr = *iter; delete filePtr; } files.clear(); @@ -205,8 +184,7 @@ void Tracer::closeFiles() /* --------------------------------------------------------------------- */ /* --------------------------------------------------------------------- */ -void Tracer::record() -{ +void Tracer::record() { if (!play) { dgDEBUGINOUT(15); return; @@ -214,30 +192,26 @@ void Tracer::record() 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(); - 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 { @@ -246,7 +220,7 @@ void Tracer::recordSignal(std::ostream& os, const SignalBase<int>& sig) sig.trace(os); os << endl; } - } catch (ExceptionAbstract& exc) { + } catch (ExceptionAbstract &exc) { os << exc << std::endl; } catch (...) { os << "Unknown error occurred while reading signal." << std::endl; @@ -255,8 +229,7 @@ void Tracer::recordSignal(std::ostream& os, const SignalBase<int>& sig) dgDEBUGOUT(15); } -int& Tracer::recordTrigger(int& dummy, const int& time) -{ +int &Tracer::recordTrigger(int &dummy, const int &time) { dgDEBUGIN(15) << " time=" << time << endl; record(); dgDEBUGOUT(15); @@ -269,20 +242,17 @@ void Tracer::trace() {} /* --------------------------------------------------------------------- */ /* --------------------------------------------------------------------- */ -void Tracer::display(std::ostream& os) const -{ - os << CLASS_NAME << " " << name << " [mode=" - << (play ? "play" : "pause") << "] : " << 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; - } + 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 6f795f923861d4bb1b583d84be2633ca9f52813a..3a7e8518eeb0d8b6214781e2ae736ccc107f1ada 100644 --- a/tests/command-test.cpp +++ b/tests/command-test.cpp @@ -5,102 +5,98 @@ * See LICENSE file * */ -#include <sstream> -#include <iostream> -#include <dynamic-graph/entity.h> -#include <dynamic-graph/exception-factory.h> +#include "dynamic-graph/command-bind.h" #include "dynamic-graph/factory.h" #include "dynamic-graph/pool.h" -#include "dynamic-graph/command-bind.h" +#include <dynamic-graph/entity.h> +#include <dynamic-graph/exception-factory.h> +#include <iostream> +#include <sstream> #define ENABLE_RT_LOG -#include <dynamic-graph/real-time-logger.h> #include <dynamic-graph/logger.h> +#include <dynamic-graph/real-time-logger.h> #define BOOST_TEST_MODULE debug - logger -#include <boost/test/unit_test.hpp> #include <boost/test/output_test_stream.hpp> +#include <boost/test/unit_test.hpp> 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 - -BOOST_AUTO_TEST_CASE(command_test) -{ +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 + +BOOST_AUTO_TEST_CASE(command_test) { dynamicgraph::CustomEntity &entity = - *(dynamic_cast<dynamicgraph::CustomEntity *> - (dynamicgraph::FactoryStorage::getInstance()-> - newEntity("CustomEntity", "my-entity"))); + *(dynamic_cast<dynamicgraph::CustomEntity *>( + dynamicgraph::FactoryStorage::getInstance()->newEntity("CustomEntity", + "my-entity"))); std::map<const std::string, Command *> aCommandMap = - entity.getNewStyleCommandMap(); + entity.getNewStyleCommandMap(); 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_); @@ -115,7 +111,8 @@ BOOST_AUTO_TEST_CASE(command_test) for (unsigned int i = 0; i < 4; i++) { it_map = aCommandMap.find(vec_fname[i]); - if (it_map == aCommandMap.end()) BOOST_CHECK(false); + if (it_map == aCommandMap.end()) + BOOST_CHECK(false); values.push_back(aValue); it_map->second->setParameterValues(values); it_map->second->execute(); diff --git a/tests/custom-entity.cpp b/tests/custom-entity.cpp index 6cb705a7d51ede71c594db6dcb7f49a2f2b74887..896d76fd14662fc1ebed4abd584f872b39ef0c83 100644 --- a/tests/custom-entity.cpp +++ b/tests/custom-entity.cpp @@ -1,29 +1,29 @@ // Copyright 2010 Thomas Moulard. // -#include <sstream> -#include <dynamic-graph/factory.h> -#include <dynamic-graph/pool.h> #include <dynamic-graph/entity.h> #include <dynamic-graph/exception-factory.h> +#include <dynamic-graph/factory.h> +#include <dynamic-graph/pool.h> +#include <sstream> #define BOOST_TEST_MODULE customEntity -#include <boost/test/unit_test.hpp> #include <boost/test/output_test_stream.hpp> +#include <boost/test/unit_test.hpp> using boost::test_tools::output_test_stream; 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) {} virtual ~CustomEntity() {} - void display(std::ostream& os) const { os << "custom entity"; } + void display(std::ostream &os) const { os << "custom entity"; } }; DYNAMICGRAPH_FACTORY_ENTITY_PLUGIN(CustomEntity, "CustomEntity"); @@ -31,7 +31,9 @@ DYNAMICGRAPH_FACTORY_ENTITY_PLUGIN(CustomEntity, "CustomEntity"); BOOST_AUTO_TEST_CASE(constructor) { BOOST_CHECK_EQUAL(CustomEntity::CLASS_NAME, "CustomEntity"); - dynamicgraph::Entity* entity = dynamicgraph::FactoryStorage::getInstance()->newEntity("CustomEntity", "my-entity"); + 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); @@ -42,7 +44,9 @@ BOOST_AUTO_TEST_CASE(constructor) { } BOOST_AUTO_TEST_CASE(display) { - dynamicgraph::Entity* entity = dynamicgraph::FactoryStorage::getInstance()->newEntity("CustomEntity", "my-entity"); + dynamicgraph::Entity *entity = + dynamicgraph::FactoryStorage::getInstance()->newEntity("CustomEntity", + "my-entity"); output_test_stream output; diff --git a/tests/debug-logger-winit.cpp b/tests/debug-logger-winit.cpp index 156a5c9b1efe783a327ed358b34ce8e2eecd65b1..cd88551b56ba5d746d47c397615d23ed101d1ff9 100644 --- a/tests/debug-logger-winit.cpp +++ b/tests/debug-logger-winit.cpp @@ -5,33 +5,33 @@ * See LICENSE file * */ -#include <sstream> #include <iostream> +#include <sstream> #define ENABLE_RT_LOG -#include <dynamic-graph/entity.h> -#include <dynamic-graph/exception-factory.h> #include "dynamic-graph/factory.h" #include "dynamic-graph/pool.h" +#include <dynamic-graph/entity.h> +#include <dynamic-graph/exception-factory.h> -#include <dynamic-graph/real-time-logger.h> #include <dynamic-graph/logger.h> +#include <dynamic-graph/real-time-logger.h> #define BOOST_TEST_MODULE debug - logger -#include <boost/test/unit_test.hpp> #include <boost/test/output_test_stream.hpp> +#include <boost/test/unit_test.hpp> -#include <boost/thread/thread.hpp> #include <boost/date_time/posix_time/posix_time.hpp> +#include <boost/thread/thread.hpp> using boost::test_tools::output_test_stream; namespace dynamicgraph { class CustomEntity : public Entity { - public: +public: 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) { logger_.setTimeSample(0.001); logger_.setStreamPrintPeriod(0.005); @@ -46,16 +46,20 @@ class CustomEntity : public Entity { 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); + 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 +} // namespace dynamicgraph BOOST_AUTO_TEST_CASE(debug_logger_wrong_initialization) { std::ofstream of; @@ -65,8 +69,10 @@ BOOST_AUTO_TEST_CASE(debug_logger_wrong_initialization) { 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(); diff --git a/tests/debug-logger.cpp b/tests/debug-logger.cpp index 1b2eee44ed48e5b1ee3fd3c3ac398570b6ca0b08..d6b9ed91a8cf9677dc3a4f5d01ce34135fb22e81 100644 --- a/tests/debug-logger.cpp +++ b/tests/debug-logger.cpp @@ -5,29 +5,29 @@ * See LICENSE file * */ -#include <sstream> -#include <iostream> -#include <dynamic-graph/entity.h> -#include <dynamic-graph/exception-factory.h> #include "dynamic-graph/factory.h" #include "dynamic-graph/pool.h" +#include <dynamic-graph/entity.h> +#include <dynamic-graph/exception-factory.h> +#include <iostream> +#include <sstream> #define ENABLE_RT_LOG -#include <dynamic-graph/real-time-logger.h> #include <dynamic-graph/logger.h> +#include <dynamic-graph/real-time-logger.h> #define BOOST_TEST_MODULE debug - logger -#include <boost/test/unit_test.hpp> #include <boost/test/output_test_stream.hpp> +#include <boost/test/unit_test.hpp> using boost::test_tools::output_test_stream; namespace dynamicgraph { class CustomEntity : public Entity { - public: +public: 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) { logger_.setTimeSample(0.001); logger_.setStreamPrintPeriod(0.005); @@ -42,16 +42,20 @@ class CustomEntity : public Entity { 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); + 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 +} // namespace dynamicgraph BOOST_AUTO_TEST_CASE(debug_logger) { std::ofstream of; @@ -61,8 +65,10 @@ BOOST_AUTO_TEST_CASE(debug_logger) { 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); diff --git a/tests/debug-trace.cpp b/tests/debug-trace.cpp index d7e118968dc8517d801cd30bf9611e0ec09b2b34..89ab01ed75dec9823eeffedc880677e9674be2bd 100644 --- a/tests/debug-trace.cpp +++ b/tests/debug-trace.cpp @@ -3,12 +3,12 @@ * Olivier Stasse * */ -#include <sstream> -#include <iostream> -#include <dynamic-graph/entity.h> -#include <dynamic-graph/exception-factory.h> #include "dynamic-graph/factory.h" #include "dynamic-graph/pool.h" +#include <dynamic-graph/entity.h> +#include <dynamic-graph/exception-factory.h> +#include <iostream> +#include <sstream> #define VP_DEBUG 1 #define VP_DEBUG_MODE 50 @@ -18,20 +18,22 @@ #define BOOST_TEST_MODULE debug - trace -#include <boost/test/unit_test.hpp> #include <boost/test/output_test_stream.hpp> +#include <boost/test/unit_test.hpp> using boost::test_tools::output_test_stream; namespace dynamicgraph { class CustomEntity : public Entity { - public: +public: 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) { dynamicgraph::dgDEBUGFLOW.openFile("/tmp/dynamic-graph-traces.txt"); } - ~CustomEntity() { dynamicgraph::dgDEBUGFLOW.closeFile("/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); @@ -46,19 +48,22 @@ class CustomEntity : public Entity { } }; DYNAMICGRAPH_FACTORY_ENTITY_PLUGIN(CustomEntity, "CustomEntity"); -} // namespace dynamicgraph +} // 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"))); + 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; @@ -74,11 +79,10 @@ BOOST_AUTO_TEST_CASE(testDebugTrace) { 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. diff --git a/tests/debug-tracer.cpp b/tests/debug-tracer.cpp index 17889e45cddddfc370156002f052d66861a4844b..082f883042271d24d0a65eed3154508b1fe767a0 100644 --- a/tests/debug-tracer.cpp +++ b/tests/debug-tracer.cpp @@ -16,8 +16,8 @@ #define BOOST_TEST_MODULE debug - tracer -#include <boost/test/unit_test.hpp> #include <boost/test/output_test_stream.hpp> +#include <boost/test/unit_test.hpp> namespace dynamicgraph { struct MyEntity : public dynamicgraph::Entity { @@ -30,16 +30,20 @@ struct MyEntity : public dynamicgraph::Entity { 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, + 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") + 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 void display(std::ostream &os) const { + os << "Hello! My name is " << getName() << " !" << std::endl; + } virtual const std::string &getClassName() const { return CLASS_NAME; } @@ -50,14 +54,17 @@ struct MyEntity : public dynamicgraph::Entity { } }; DYNAMICGRAPH_FACTORY_ENTITY_PLUGIN(MyEntity, "MyEntity"); -} // namespace dynamicgraph +} // 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::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"); @@ -65,7 +72,8 @@ BOOST_AUTO_TEST_CASE(test_tracer) { dynamicgraph::SignalBase<int> &aSignal = entity.getSignal("out2double"); dynamicgraph::Signal<double, int> &aSignalInt = - *(dynamic_cast<dynamicgraph::Signal<double, int> *>(&entity.getSignal("in_double"))); + *(dynamic_cast<dynamicgraph::Signal<double, int> *>( + &entity.getSignal("in_double"))); /// Add trace by signal object atracer.addSignalToTrace(aSignal, "output2"); diff --git a/tests/entity.cpp b/tests/entity.cpp index 5d9fe6a10d2940e1dbdbf5e9a23ba4b9961b8ce8..09592f18c471c9b48036c720b87a799dda91b902 100644 --- a/tests/entity.cpp +++ b/tests/entity.cpp @@ -5,35 +5,36 @@ #define ENABLE_RT_LOG -#include <sstream> -#include <dynamic-graph/entity.h> -#include <dynamic-graph/exception-factory.h> #include "dynamic-graph/factory.h" #include "dynamic-graph/pool.h" +#include <dynamic-graph/entity.h> +#include <dynamic-graph/exception-factory.h> #include <dynamic-graph/real-time-logger.h> #include <dynamic-graph/signal-ptr.h> #include <dynamic-graph/signal-time-dependent.h> +#include <sstream> #define BOOST_TEST_MODULE entity -#include <boost/test/unit_test.hpp> #include <boost/test/output_test_stream.hpp> +#include <boost/test/unit_test.hpp> using boost::test_tools::output_test_stream; namespace dynamicgraph { class CustomEntity : public Entity { - public: +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; } + 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") + m_sigdTimeDepSOUT( + boost::bind(&CustomEntity::update, this, _1, _2), m_sigdSIN, + "CustomEntity(" + name + ")::input(double)::out_double") {} @@ -44,60 +45,69 @@ class CustomEntity : public Entity { signalDeregistration("out_double"); } - double& update(double& res, const int& inTime) { - const double& aDouble = m_sigdSIN(inTime); + 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 +} // 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"); + 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); + 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"); + 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); + } catch (const dynamicgraph::ExceptionFactory &exception) { + BOOST_CHECK_EQUAL(exception.getCode(), + dynamicgraph::ExceptionFactory::UNREFERED_SIGNAL); } // Const getter. try { - const dynamicgraph::Entity& entityConst = entity; + 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); + } catch (const dynamicgraph::ExceptionFactory &exception) { + BOOST_CHECK_EQUAL(exception.getCode(), + dynamicgraph::ExceptionFactory::UNREFERED_SIGNAL); } // deregistration try { - dynamicgraph::CustomEntity* customEntity = dynamic_cast<dynamicgraph::CustomEntity*>(&entity); + 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); + } 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"); + dynamicgraph::Entity &entity = + dynamicgraph::PoolStorage::getInstance()->getEntity("my-entity"); output_test_stream output; @@ -106,7 +116,8 @@ BOOST_AUTO_TEST_CASE(displaySignalList) { } BOOST_AUTO_TEST_CASE(display) { - dynamicgraph::Entity& entity = dynamicgraph::PoolStorage::getInstance()->getEntity("my-entity"); + dynamicgraph::Entity &entity = + dynamicgraph::PoolStorage::getInstance()->getEntity("my-entity"); output_test_stream output; @@ -115,13 +126,15 @@ BOOST_AUTO_TEST_CASE(display) { } BOOST_AUTO_TEST_CASE(getCommandList) { - dynamicgraph::Entity& entity = dynamicgraph::PoolStorage::getInstance()->getEntity("my-entity"); + dynamicgraph::Entity &entity = + dynamicgraph::PoolStorage::getInstance()->getEntity("my-entity"); BOOST_CHECK_EQUAL(entity.getCommandList(), "print\nsignals\nsignalDep"); } BOOST_AUTO_TEST_CASE(writeGraph) { - dynamicgraph::Entity& entity = dynamicgraph::PoolStorage::getInstance()->getEntity("my-entity"); + dynamicgraph::Entity &entity = + dynamicgraph::PoolStorage::getInstance()->getEntity("my-entity"); output_test_stream output; entity.writeGraph(output); @@ -130,7 +143,8 @@ BOOST_AUTO_TEST_CASE(writeGraph) { } BOOST_AUTO_TEST_CASE(writeCompletionList) { - dynamicgraph::Entity& entity = dynamicgraph::PoolStorage::getInstance()->getEntity("my-entity"); + dynamicgraph::Entity &entity = + dynamicgraph::PoolStorage::getInstance()->getEntity("my-entity"); output_test_stream output; entity.writeCompletionList(output); @@ -143,15 +157,18 @@ BOOST_AUTO_TEST_CASE(sendMsg) { 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; + dynamicgraph::LoggerVerbosity aLoggerVerbosityLevel = + (dynamicgraph::LoggerVerbosity)i; entity.setLoggerVerbosityLevel(aLoggerVerbosityLevel); - if (entity.getLoggerVerbosityLevel() != aLoggerVerbosityLevel) output << "Mismatch output"; + if (entity.getLoggerVerbosityLevel() != aLoggerVerbosityLevel) + output << "Mismatch output"; std::string aBaseMsg = "Auto Test Case"; std::string aMsg = aBaseMsg + " DEBUG"; @@ -171,9 +188,11 @@ BOOST_AUTO_TEST_CASE(sendMsg) { // WTF? BOOST_AUTO_TEST_CASE(wtf) { - dynamicgraph::Entity& entity = dynamicgraph::PoolStorage::getInstance()->getEntity("my-entity"); + 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 c188c55fe55d9c31851118c2fb513a6fc81dec9b..defe9e5a5bc6f47e3c0063a49fdf578baf78b7e1 100644 --- a/tests/factory.cpp +++ b/tests/factory.cpp @@ -1,47 +1,55 @@ // Copyright 2010 Thomas Moulard. // -#include <sstream> -#include <dynamic-graph/factory.h> #include <dynamic-graph/entity.h> #include <dynamic-graph/exception-factory.h> +#include <dynamic-graph/factory.h> +#include <sstream> #define BOOST_TEST_MODULE factory -#include <boost/test/unit_test.hpp> #include <boost/test/output_test_stream.hpp> +#include <boost/test/unit_test.hpp> using boost::test_tools::output_test_stream; namespace dynamicgraph { class CustomEntity : public Entity { - public: +public: 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) {} }; const std::string CustomEntity::CLASS_NAME = "CustomEntity"; -} // namespace dynamicgraph +} // namespace dynamicgraph -dynamicgraph::Entity* makeEntity(const std::string& objectName) { return new dynamicgraph::CustomEntity(objectName); } +dynamicgraph::Entity *makeEntity(const std::string &objectName) { + return new dynamicgraph::CustomEntity(objectName); +} -BOOST_AUTO_TEST_CASE(constructor) { dynamicgraph::FactoryStorage::getInstance(); } +BOOST_AUTO_TEST_CASE(constructor) { + dynamicgraph::FactoryStorage::getInstance(); +} BOOST_AUTO_TEST_CASE(registerEntity) { - dynamicgraph::FactoryStorage::getInstance()->registerEntity("myEntity", &makeEntity); + dynamicgraph::FactoryStorage::getInstance()->registerEntity("myEntity", + &makeEntity); try { - dynamicgraph::FactoryStorage::getInstance()->registerEntity("myEntity", &makeEntity); + 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); + } 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); + } catch (const dynamicgraph::ExceptionFactory &exception) { + BOOST_CHECK_EQUAL(exception.getCode(), + dynamicgraph::ExceptionFactory::OBJECT_CONFLICT); } } @@ -51,51 +59,61 @@ BOOST_AUTO_TEST_CASE(unregisterEntity) { 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); + } catch (const dynamicgraph::ExceptionFactory &exception) { + BOOST_CHECK_EQUAL(exception.getCode(), + dynamicgraph::ExceptionFactory::OBJECT_CONFLICT); } try { - dynamicgraph::FactoryStorage::getInstance()->deregisterEntity("I do not exist."); + 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); + } 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); + dynamicgraph::FactoryStorage::getInstance()->registerEntity("myEntity", + &makeEntity); { boost::shared_ptr<dynamicgraph::Entity> entity( - dynamicgraph::FactoryStorage::getInstance()->newEntity("myEntity", "foo")); + dynamicgraph::FactoryStorage::getInstance()->newEntity("myEntity", + "foo")); boost::shared_ptr<dynamicgraph::Entity> entity2( - dynamicgraph::FactoryStorage::getInstance()->newEntity("myEntity", "foo2")); + 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.", ""); + 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); + } 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); + } 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("myEntity2")); BOOST_CHECK(!dynamicgraph::FactoryStorage::getInstance()->existEntity("")); } diff --git a/tests/interpreter-tracer.cpp b/tests/interpreter-tracer.cpp index 6a759cf28bfe49a1410ea2258c705a841d1d769c..579179e9068d4cfb3b730c6b679f8d4988f86771 100644 --- a/tests/interpreter-tracer.cpp +++ b/tests/interpreter-tracer.cpp @@ -1,15 +1,15 @@ // Copyright 2010 Thomas Moulard. // -#include <sstream> #include <dynamic-graph/exception-factory.h> #include <dynamic-graph/interpreter.h> #include <dynamic-graph/plugin-loader.h> +#include <sstream> #define BOOST_TEST_MODULE tracer -#include <boost/test/unit_test.hpp> #include <boost/test/output_test_stream.hpp> +#include <boost/test/unit_test.hpp> #include "interpreter.h" diff --git a/tests/pool.cpp b/tests/pool.cpp index 190d5daa507a4a649592809d297eb55714825c55..057235e02bc314b428ac1b0c7db490c86fa43b2c 100644 --- a/tests/pool.cpp +++ b/tests/pool.cpp @@ -1,24 +1,23 @@ // Copyright 2010 Thomas Moulard. // -#include <sstream> -#include <iostream> #include <dynamic-graph/entity.h> -#include <dynamic-graph/factory.h> #include <dynamic-graph/exception-factory.h> +#include <dynamic-graph/factory.h> #include <dynamic-graph/pool.h> #include <dynamic-graph/signal-ptr.h> #include <dynamic-graph/signal-time-dependent.h> +#include <iostream> +#include <sstream> #define BOOST_TEST_MODULE pool -#include <boost/test/unit_test.hpp> #include <boost/test/output_test_stream.hpp> +#include <boost/test/unit_test.hpp> 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; @@ -29,21 +28,17 @@ struct MyEntity : public dynamicgraph::Entity 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(" + 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; } - double &update(double &res, const int &inTime) - { + double &update(double &res, const int &inTime) { const double &aDouble = m_sigdSIN(inTime); res = aDouble; return res; @@ -53,39 +48,31 @@ struct MyEntity : public dynamicgraph::Entity 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; - try - { - dg::Entity *entity2 = dg::FactoryStorage::getInstance()-> - newEntity("MyEntity", "MyEntityInst"); - - bool res2 = (entity2 == entity); - BOOST_CHECK(res2); - } - catch (const dg::ExceptionFactory &aef) - { - res = (aef.getCode() == dg::ExceptionFactory::OBJECT_CONFLICT); - } + try { + dg::Entity *entity2 = dg::FactoryStorage::getInstance()->newEntity( + "MyEntity", "MyEntityInst"); + + bool res2 = (entity2 == entity); + BOOST_CHECK(res2); + } catch (const dg::ExceptionFactory &aef) { + res = (aef.getCode() == dg::ExceptionFactory::OBJECT_CONFLICT); + } BOOST_CHECK(res); /// Test exception catching when deregistering Entity res = false; - try - { - dg::FactoryStorage::getInstance()-> - deregisterEntity("MyEntityInstFailure"); - } - catch (const dg::ExceptionFactory &aef) - { - res = (aef.getCode() == dg::ExceptionFactory::OBJECT_CONFLICT); - } + try { + dg::FactoryStorage::getInstance()->deregisterEntity("MyEntityInstFailure"); + } catch (const dg::ExceptionFactory &aef) { + res = (aef.getCode() == dg::ExceptionFactory::OBJECT_CONFLICT); + } BOOST_CHECK(res); /// Search for an entity inside the map @@ -96,34 +83,31 @@ BOOST_AUTO_TEST_CASE(pool_display) /// 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); - } + 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(); + dg::PoolStorage::getInstance()->getEntityMap(); 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\n" - "print\nsignals\nsignalDep\n")); + BOOST_CHECK( + output.is_equal("MyEntityInst.in_double\nMyEntityInst.out_double\n" + "print\nsignals\nsignalDep\n")); /// Checking the graph generated by the pool dg::PoolStorage::getInstance()->writeGraph("output.dot"); @@ -153,11 +137,11 @@ BOOST_AUTO_TEST_CASE(pool_display) 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; @@ -170,32 +154,29 @@ BOOST_AUTO_TEST_CASE(pool_display) std::istringstream an_iss("MyEntityInst.in_double"); dg::SignalBase<int> &aSignal = - dg::PoolStorage::getInstance()->getSignal(an_iss); + dg::PoolStorage::getInstance()->getSignal(an_iss); std::string aSignalName = aSignal.getName(); - testExistence = aSignalName == - "MyEntity(MyEntityInst)::input(double)::in_double"; + testExistence = + aSignalName == "MyEntity(MyEntityInst)::input(double)::in_double"; BOOST_CHECK(testExistence); /// Test name of an unvalid signal. an_iss.str("MyEntityInst.in2double"); - try - { - dg::PoolStorage::getInstance()->getSignal(an_iss); - } - catch (const dg::ExceptionFactory &aef) - { - res = (aef.getCode() == dg::ExceptionFactory::UNREFERED_SIGNAL); - } + try { + dg::PoolStorage::getInstance()->getSignal(an_iss); + } catch (const dg::ExceptionFactory &aef) { + res = (aef.getCode() == dg::ExceptionFactory::UNREFERED_SIGNAL); + } BOOST_CHECK(res); /// Deregister the entity. 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); diff --git a/tests/real-time-logger.cpp b/tests/real-time-logger.cpp index 1dd5b419543702d495be33e36096509860841d5a..15ceeb18d7eb8eede6e0778eccbf57e6cd6ba250 100644 --- a/tests/real-time-logger.cpp +++ b/tests/real-time-logger.cpp @@ -13,18 +13,19 @@ #define BOOST_TEST_MODULE real_time_logger -#include <boost/test/unit_test.hpp> #include <boost/test/output_test_stream.hpp> +#include <boost/test/unit_test.hpp> -#include <boost/thread/thread.hpp> #include <boost/date_time/posix_time/posix_time.hpp> +#include <boost/thread/thread.hpp> using namespace dynamicgraph; 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'; + for (int i = 0; i < 9; ++i) + rtl.front() << "Call number " << i << '\n'; BOOST_CHECK(rtl.full()); rtl.front() << "This call should not appear in the output" << '\n'; @@ -56,10 +57,11 @@ BOOST_AUTO_TEST_CASE(multithread) { pthread_setschedparam(pthread_self(), threadPolicy, &threadParam); } - RealTimeLogger& rtl = RealTimeLogger::instance(); + RealTimeLogger &rtl = RealTimeLogger::instance(); 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; diff --git a/tests/signal-all.cpp b/tests/signal-all.cpp index 875c14771bd3e7eacd3b612f65d6846ec0cee502..cc7bdaa3b5c4bb8fec32e2ea8694e9f65aa16abf 100644 --- a/tests/signal-all.cpp +++ b/tests/signal-all.cpp @@ -7,12 +7,12 @@ #include <dynamic-graph/debug.h> #include <dynamic-graph/factory.h> #include <dynamic-graph/signal-array.h> -#include <dynamic-graph/tracer.h> #include <dynamic-graph/signal-cast-helper.h> +#include <dynamic-graph/tracer.h> #include <assert.h> -#include <boost/test/unit_test.hpp> #include <boost/test/output_test_stream.hpp> +#include <boost/test/unit_test.hpp> #define BOOST_TEST_MODULE signal_array diff --git a/tests/signal-cast-registerer.cpp b/tests/signal-cast-registerer.cpp index 2dd972fd4280385f80b9b417366929b8764c32db..80057f2715d218907a8c020ee67f218f035a7550 100644 --- a/tests/signal-cast-registerer.cpp +++ b/tests/signal-cast-registerer.cpp @@ -9,22 +9,22 @@ #include <Eigen/Dense> #include <dynamic-graph/debug.h> +#include <dynamic-graph/eigen-io.h> #include <dynamic-graph/entity.h> #include <dynamic-graph/factory.h> -#include <dynamic-graph/pool.h> -#include <dynamic-graph/eigen-io.h> #include <dynamic-graph/linear-algebra.h> +#include <dynamic-graph/pool.h> +#include <dynamic-graph/signal-cast-helper.h> #include <dynamic-graph/signal-caster.h> #include <dynamic-graph/signal.h> -#include <dynamic-graph/signal-cast-helper.h> #include "signal-cast-registerer-libA.hh" #include "signal-cast-registerer-libB.hh" #define BOOST_TEST_MODULE signal_cast_registerer -#include <boost/test/unit_test.hpp> #include <boost/test/output_test_stream.hpp> +#include <boost/test/unit_test.hpp> #include <iostream> using boost::test_tools::output_test_stream; @@ -35,24 +35,28 @@ typedef Eigen::MatrixXd Matrix; 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; } }; @@ -61,21 +65,23 @@ 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) { + 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); + 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); + static void traceMatrix(const boost::any &object, std::ostream &os) { + const bnuMatrix &m = boost::any_cast<bnuMatrix>(object); os << m << std::endl; } }; @@ -104,7 +110,7 @@ BOOST_AUTO_TEST_CASE(standard_double_registerer) { 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) { + BOOST_FOREACH (const test_t &test, values) { // Set std::istringstream value(test.first); mySignal.set(value); diff --git a/tests/signal-ptr.cpp b/tests/signal-ptr.cpp index a43ada93758650ff1ff8d4b951d66efedd62575a..dc8a0e68abc8c9ba4c733319651bde97b517dfd4 100644 --- a/tests/signal-ptr.cpp +++ b/tests/signal-ptr.cpp @@ -6,16 +6,16 @@ #include <dynamic-graph/debug.h> #include <dynamic-graph/entity.h> #include <dynamic-graph/factory.h> +#include <dynamic-graph/pool.h> +#include <dynamic-graph/signal-base.h> #include <dynamic-graph/signal-ptr.h> #include <dynamic-graph/signal.h> -#include <dynamic-graph/signal-base.h> -#include <dynamic-graph/pool.h> #include <iostream> -#include <string> -#include <boost/test/unit_test_suite.hpp> -#include <boost/test/unit_test.hpp> #include <boost/test/output_test_stream.hpp> +#include <boost/test/unit_test.hpp> +#include <boost/test/unit_test_suite.hpp> +#include <string> using namespace dynamicgraph; using std::cout; @@ -44,7 +44,8 @@ BOOST_AUTO_TEST_CASE(normal_test) { } SignalBase<int> &sigRef = sig; - SignalBase<int> &sigPtrARef = sigPtrA, &sigPtrBRef = sigPtrB, &sigPtrAbstractRef = sigPtrAbstract; + SignalBase<int> &sigPtrARef = sigPtrA, &sigPtrBRef = sigPtrB, + &sigPtrAbstractRef = sigPtrAbstract; sigPtrARef.plug(&sigRef); sigPtrBRef.plug(&sigPtrARef); diff --git a/tests/signal-time-dependent.cpp b/tests/signal-time-dependent.cpp index cf84d31e6007b7994fabbceccad2e8a24a111a66..6beca83b7e97ebdb82b1912cc6b6a53720cf9773 100644 --- a/tests/signal-time-dependent.cpp +++ b/tests/signal-time-dependent.cpp @@ -3,44 +3,43 @@ #include <boost/foreach.hpp> -#include <dynamic-graph/signal.h> #include <dynamic-graph/signal-time-dependent.h> +#include <dynamic-graph/signal.h> #define BOOST_TEST_MODULE signal_time_dependent -#include <boost/test/unit_test.hpp> #include <boost/test/output_test_stream.hpp> +#include <boost/test/unit_test.hpp> 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; + 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; - BOOST_FOREACH (sigDouble_t* ptr, inputsig) + 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)(); 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()(); @@ -49,22 +48,17 @@ class DummyClass { int timedata; }; -template <> -double DummyClass<double>::operator()() { +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(); } -template <class T> -T DummyClass<T>::operator()() { - return this->res; -} +template <class T> T DummyClass<T>::operator()() { return this->res; } BOOST_AUTO_TEST_CASE(signaltimedependent) { DummyClass<double> pro1("pro1"), pro3("pro3"), pro5("pro5"); @@ -76,7 +70,8 @@ BOOST_AUTO_TEST_CASE(signaltimedependent) { 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)); diff --git a/tests/test-mt.cpp b/tests/test-mt.cpp index 85aee889f31f12513825339ac00efc369aecf3d8..de0ea521bd0e22f226d672f8519c561bdf14d12a 100644 --- a/tests/test-mt.cpp +++ b/tests/test-mt.cpp @@ -3,16 +3,16 @@ * Olivier Stasse * */ -#include <sstream> +#include <dynamic-graph/process-list.hh> #include <fstream> #include <iostream> +#include <sstream> #include <unistd.h> -#include <dynamic-graph/process-list.hh> #define BOOST_TEST_MODULE debug - trace -#include <boost/test/unit_test.hpp> #include <boost/test/output_test_stream.hpp> +#include <boost/test/unit_test.hpp> using boost::test_tools::output_test_stream; diff --git a/tests/value.cpp b/tests/value.cpp index 5e0a3faa4e776ea81d5a66fbe09582f4df6d3ca5..657c06934c97e0ac4a4ab135ac5fc0b652deede2 100644 --- a/tests/value.cpp +++ b/tests/value.cpp @@ -1,13 +1,13 @@ // Copyright 2011 Florent Lamiraux, Thomas Moulard. // -#include <iostream> #include "dynamic-graph/value.h" +#include <iostream> #define BOOST_TEST_MODULE value -#include <boost/test/unit_test.hpp> #include <boost/test/output_test_stream.hpp> +#include <boost/test/unit_test.hpp> using boost::test_tools::output_test_stream;