footbot_light_rotzonly_sensor.cpp
Go to the documentation of this file.
1 
7 #include <argos3/core/simulator/simulator.h>
8 #include <argos3/core/simulator/entity/embodied_entity.h>
9 #include <argos3/core/simulator/entity/composable_entity.h>
10 #include <argos3/plugins/simulator/entities/light_entity.h>
11 #include <argos3/plugins/simulator/entities/light_sensor_equipped_entity.h>
12 
14 
15 namespace argos {
16 
17  /****************************************/
18  /****************************************/
19 
20  static CRange<Real> SENSOR_RANGE(0.0f, 1.0f);
21  static CRadians SENSOR_SPACING = CRadians(ARGOS_PI / 12.0f);
22  static CRadians SENSOR_HALF_SPACING = SENSOR_SPACING * 0.5;
23 
24  /****************************************/
25  /****************************************/
26 
27  static SInt32 Modulo(SInt32 n_value, SInt32 un_modulo) {
28  while(n_value < 0) n_value += un_modulo;
29  while(n_value >= un_modulo) n_value -= un_modulo;
30  return n_value;
31  }
32 
33  static Real ComputeReading(Real f_distance) {
34  if(f_distance > 2.5f) {
35  return 0.0f;
36  }
37  else {
38  return ::exp(-f_distance * 2.0f);
39  }
40  }
41 
42  static Real ScaleReading(const CRadians& c_angular_distance) {
43  if(c_angular_distance > CRadians::PI_OVER_TWO) {
44  return 0.0f;
45  }
46  else {
47  return (1.0f - 2.0f * c_angular_distance / CRadians::PI);
48  }
49  }
50 
51  /****************************************/
52  /****************************************/
53 
55  m_pcEmbodiedEntity(NULL),
56  m_bShowRays(false),
57  m_pcRNG(NULL),
58  m_bAddNoise(false),
59  m_cSpace(CSimulator::GetInstance().GetSpace()) {}
60 
61  /****************************************/
62  /****************************************/
63 
65  try {
66  m_pcEmbodiedEntity = &(c_entity.GetComponent<CEmbodiedEntity>("body"));
67  m_pcControllableEntity = &(c_entity.GetComponent<CControllableEntity>("controller"));
68  m_pcLightEntity = &(c_entity.GetComponent<CLightSensorEquippedEntity>("light_sensors"));
70  }
71  catch(CARGoSException& ex) {
72  THROW_ARGOSEXCEPTION_NESTED("Can't set robot for the foot-bot light default sensor", ex);
73  }
74  }
75 
76  /****************************************/
77  /****************************************/
78 
80  try {
81  /* Show rays? */
82  GetNodeAttributeOrDefault(t_tree, "show_rays", m_bShowRays, m_bShowRays);
83  /* Parse noise level */
84  Real fNoiseLevel = 0.0f;
85  GetNodeAttributeOrDefault(t_tree, "noise_level", fNoiseLevel, fNoiseLevel);
86  if(fNoiseLevel < 0.0f) {
87  THROW_ARGOSEXCEPTION("Can't specify a negative value for the noise level of the light sensor");
88  }
89  else if(fNoiseLevel > 0.0f) {
90  m_bAddNoise = true;
91  m_cNoiseRange.Set(-fNoiseLevel, fNoiseLevel);
92  m_pcRNG = CRandom::CreateRNG("argos");
93  }
95  }
96  catch(CARGoSException& ex) {
97  THROW_ARGOSEXCEPTION_NESTED("Initialization error in rot_z_only light sensor", ex);
98  }
99  }
100 
101  /****************************************/
102  /****************************************/
103 
105  /* Erase readings */
106  for(size_t i = 0; i < m_tReadings.size(); ++i) {
107  m_tReadings[i].Value = 0.0f;
108  }
109  /* Get foot-bot orientation */
110  CRadians cTmp1, cTmp2, cOrientationZ;
111  m_pcEmbodiedEntity->GetOriginAnchor().Orientation.ToEulerAngles(cOrientationZ, cTmp1, cTmp2);
112  /* Ray used for scanning the environment for obstacles */
113  CRay3 cOcclusionCheckRay;
114  cOcclusionCheckRay.SetStart(m_pcEmbodiedEntity->GetOriginAnchor().Position);
115  CVector3 cRobotToLight;
116  /* Buffer for the angle of the light wrt to the foot-bot */
117  CRadians cAngleLightWrtFootbot;
118  /* Buffers to contain data about the intersection */
119  SEmbodiedEntityIntersectionItem sIntersection;
120  /* List of light entities */
121  CSpace::TMapPerTypePerId::iterator itLights = m_cSpace.GetEntityMapPerTypePerId().find("light");
122  if (itLights != m_cSpace.GetEntityMapPerTypePerId().end()) {
123  CSpace::TMapPerType& mapLights = itLights->second;
124  /*
125  * 1. go through the list of light entities in the scene
126  * 2. check if a light is occluded
127  * 3. if it isn't, distribute the reading across the sensors
128  * NOTE: the readings are additive
129  * 4. go through the sensors and clamp their values
130  */
131  for(CSpace::TMapPerType::iterator it = mapLights.begin();
132  it != mapLights.end();
133  ++it) {
134  /* Get a reference to the light */
135  CLightEntity& cLight = *(any_cast<CLightEntity*>(it->second));
136  /* Consider the light only if it has non zero intensity */
137  if(cLight.GetIntensity() > 0.0f) {
138  /* Set the ray end */
139  cOcclusionCheckRay.SetEnd(cLight.GetPosition());
140  /* Check occlusion between the foot-bot and the light */
141  if(! GetClosestEmbodiedEntityIntersectedByRay(sIntersection,
142  cOcclusionCheckRay,
143  *m_pcEmbodiedEntity)) {
144  /* The light is not occluded */
145  if(m_bShowRays) {
146  m_pcControllableEntity->AddCheckedRay(false, cOcclusionCheckRay);
147  }
148  /* Get the distance between the light and the foot-bot */
149  cOcclusionCheckRay.ToVector(cRobotToLight);
150  /*
151  * Linearly scale the distance with the light intensity
152  * The greater the intensity, the smaller the distance
153  */
154  cRobotToLight /= cLight.GetIntensity();
155  /* Get the angle wrt to foot-bot rotation */
156  cAngleLightWrtFootbot = cRobotToLight.GetZAngle();
157  cAngleLightWrtFootbot -= cOrientationZ;
158  /*
159  * Find closest sensor index to point at which ray hits footbot body
160  * Rotate whole body by half a sensor spacing (corresponding to placement of first sensor)
161  * Division says how many sensor spacings there are between first sensor and point at which ray hits footbot body
162  * Increase magnitude of result of division to ensure correct rounding
163  */
164  Real fIdx = (cAngleLightWrtFootbot - SENSOR_HALF_SPACING) / SENSOR_SPACING;
165  SInt32 nReadingIdx = (fIdx > 0) ? fIdx + 0.5f : fIdx - 0.5f;
166  /* Set the actual readings */
167  Real fReading = cRobotToLight.Length();
168  /*
169  * Take 6 readings before closest sensor and 6 readings after - thus we
170  * process sensors that are with 180 degrees of intersection of light
171  * ray with robot body
172  */
173  for(SInt32 nIndexOffset = -6; nIndexOffset < 7; ++nIndexOffset) {
174  UInt32 unIdx = Modulo(nReadingIdx + nIndexOffset, 24);
175  CRadians cAngularDistanceFromOptimalLightReceptionPoint = Abs((cAngleLightWrtFootbot - m_tReadings[unIdx].Angle).SignedNormalize());
176  /*
177  * ComputeReading gives value as if sensor was perfectly in line with
178  * light ray. We then linearly decrease actual reading from 1 (dist
179  * 0) to 0 (dist PI/2)
180  */
181  m_tReadings[unIdx].Value += ComputeReading(fReading) * ScaleReading(cAngularDistanceFromOptimalLightReceptionPoint);
182  }
183  }
184  else {
185  /* The ray is occluded */
186  if(m_bShowRays) {
187  m_pcControllableEntity->AddCheckedRay(true, cOcclusionCheckRay);
188  m_pcControllableEntity->AddIntersectionPoint(cOcclusionCheckRay, sIntersection.TOnRay);
189  }
190  }
191  }
192  }
193  /* Apply noise to the sensors */
194  if(m_bAddNoise) {
195  for(size_t i = 0; i < 24; ++i) {
197  }
198  }
199  /* Trunc the reading between 0 and 1 */
200  for(size_t i = 0; i < 24; ++i) {
201  SENSOR_RANGE.TruncValue(m_tReadings[i].Value);
202  }
203  }
204  else {
205  /* There are no lights in the environment */
206  if(m_bAddNoise) {
207  /* Go through the sensors */
208  for(UInt32 i = 0; i < m_tReadings.size(); ++i) {
209  /* Apply noise to the sensor */
211  /* Trunc the reading between 0 and 1 */
212  SENSOR_RANGE.TruncValue(m_tReadings[i].Value);
213  }
214  }
215  }
216  }
217 
218  /****************************************/
219  /****************************************/
220 
222  for(UInt32 i = 0; i < GetReadings().size(); ++i) {
223  m_tReadings[i].Value = 0.0f;
224  }
225  }
226 
227  /****************************************/
228  /****************************************/
229 
231  "footbot_light", "rot_z_only",
232  "Carlo Pinciroli [ilpincy@gmail.com]",
233  "1.0",
234  "The foot-bot light sensor (optimized for 2D).",
235  "This sensor accesses a set of light sensors. The sensors all return a value\n"
236  "between 0 and 1, where 0 means nothing within range and 1 means the perceived\n"
237  "light saturates the sensor. Values between 0 and 1 depend on the distance of\n"
238  "the perceived light. Each reading R is calculated with R=(I/x)^2, where x is the\n"
239  "distance between a sensor and the light, and I is the reference intensity of the\n"
240  "perceived light. The reference intensity corresponds to the minimum distance at\n"
241  "which the light saturates a sensor. The reference intensity depends on the\n"
242  "individual light, and it is set with the \"intensity\" attribute of the light\n"
243  "entity. In case multiple lights are present in the environment, each sensor\n"
244  "reading is calculated as the sum of the individual readings due to each light.\n"
245  "In other words, light wave interference is not taken into account. In\n"
246  "controllers, you must include the ci_light_sensor.h header.\n\n"
247  "REQUIRED XML CONFIGURATION\n\n"
248  " <controllers>\n"
249  " ...\n"
250  " <my_controller ...>\n"
251  " ...\n"
252  " <sensors>\n"
253  " ...\n"
254  " <footbot_light implementation=\"rot_z_only\" />\n"
255  " ...\n"
256  " </sensors>\n"
257  " ...\n"
258  " </my_controller>\n"
259  " ...\n"
260  " </controllers>\n\n"
261  "OPTIONAL XML CONFIGURATION\n\n"
262  "It is possible to draw the rays shot by the light sensor in the OpenGL\n"
263  "visualization. This can be useful for sensor debugging but also to understand\n"
264  "what's wrong in your controller. In OpenGL, the rays are drawn in cyan when\n"
265  "they are not obstructed and in purple when they are. In case a ray is\n"
266  "obstructed, a black dot is drawn where the intersection occurred.\n"
267  "To turn this functionality on, add the attribute \"show_rays\" as in this\n"
268  "example:\n\n"
269  " <controllers>\n"
270  " ...\n"
271  " <my_controller ...>\n"
272  " ...\n"
273  " <sensors>\n"
274  " ...\n"
275  " <footbot_light implementation=\"rot_z_only\"\n"
276  " show_rays=\"true\" />\n"
277  " ...\n"
278  " </sensors>\n"
279  " ...\n"
280  " </my_controller>\n"
281  " ...\n"
282  " </controllers>\n\n"
283  "It is possible to add uniform noise to the sensors, thus matching the\n"
284  "characteristics of a real robot better. This can be done with the attribute\n"
285  "\"noise_level\", whose allowed range is in [-1,1] and is added to the calculated\n"
286  "reading. The final sensor reading is always normalized in the [0-1] range.\n\n"
287  " <controllers>\n"
288  " ...\n"
289  " <my_controller ...>\n"
290  " ...\n"
291  " <sensors>\n"
292  " ...\n"
293  " <footbot_light implementation=\"rot_z_only\"\n"
294  " noise_level=\"0.1\" />\n"
295  " ...\n"
296  " </sensors>\n"
297  " ...\n"
298  " </my_controller>\n"
299  " ...\n"
300  " </controllers>\n\n"
301  "OPTIONAL XML CONFIGURATION\n\n"
302  "None.\n",
303  "Usable"
304  );
305 
306 }
signed int SInt32
32-bit signed integer.
Definition: datatypes.h:93
An entity that contains a pointer to the user-defined controller.
A 3D vector class.
Definition: vector3.h:29
virtual void Reset()
Resets the sensor to the state it had just after Init().
void GetNodeAttributeOrDefault(TConfigurationNode &t_node, const std::string &str_attribute, T &t_buffer, const T &t_default)
Returns the value of a node's attribute, or the passed default value.
virtual void SetRobot(CComposableEntity &c_entity)
Sets the entity associated to this sensor.
float Real
Collects all ARGoS code.
Definition: datatypes.h:39
#define THROW_ARGOSEXCEPTION(message)
This macro throws an ARGoS exception with the passed message.
void TruncValue(T &t_value) const
Definition: range.h:97
void Set(const T &t_min, const T &t_max)
Definition: range.h:68
T Abs(const T &t_v)
Returns the absolute value of the passed argument.
Definition: general.h:25
CSpace & m_cSpace
Reference to the space.
virtual void Init(TConfigurationNode &t_tree)
Initializes the sensor from the XML configuration tree.
CQuaternion Orientation
The orientation of the anchor wrt the global coordinate system.
Definition: physics_model.h:53
ticpp::Element TConfigurationNode
The ARGoS configuration XML node.
TMapPerTypePerId & GetEntityMapPerTypePerId()
Returns a nested map of entities, ordered by type and by id.
Definition: space.h:191
virtual void Update()
Updates the state of the entity associated to this sensor.
This entity is a link to a body in the physics engine.
#define THROW_ARGOSEXCEPTION_NESTED(message, nested)
This macro throws an ARGoS exception with the passed message and nesting the passed exception...
const CVector3 & GetPosition() const
It defines the basic type CRadians, used to store an angle value in radians.
Definition: angles.h:42
T * any_cast(CAny *pc_any)
Performs a cast on the any type to the desired type, when the any type is passed by non-const pointer...
Definition: any.h:148
Real Length() const
Returns the length of this vector.
Definition: vector3.h:205
Real GetIntensity() const
Definition: light_entity.h:37
void SetEnd(const CVector3 &c_end)
Definition: ray3.h:57
unsigned int UInt32
32-bit unsigned integer.
Definition: datatypes.h:97
CRadians Uniform(const CRange< CRadians > &c_range)
Returns a random value from a uniform distribution.
Definition: rng.cpp:87
bool m_bShowRays
Flag to show rays in the simulator.
Basic class for an entity that contains other entities.
CRandom::CRNG * m_pcRNG
Random number generator.
std::map< std::string, CAny, std::less< std::string > > TMapPerType
A map of entities indexed by type description.
Definition: space.h:53
static const CRadians PI
The PI constant.
Definition: angles.h:49
void ToEulerAngles(CRadians &c_z_angle, CRadians &c_y_angle, CRadians &c_x_angle) const
Definition: quaternion.h:172
void AddIntersectionPoint(const CRay3 &c_ray, Real f_t_on_ray)
Adds an intersection point to the list.
void SetStart(const CVector3 &c_start)
Definition: ray3.h:53
The exception that wraps all errors in ARGoS.
CControllableEntity * m_pcControllableEntity
Reference to controllable entity associated to this sensor.
bool GetClosestEmbodiedEntityIntersectedByRay(SEmbodiedEntityIntersectionItem &s_item, const CRay3 &c_ray)
Returns the closest intersection with an embodied entity to the ray start.
CVector3 & ToVector(CVector3 &c_buffer) const
Definition: ray3.h:100
bool m_bAddNoise
Whether to add noise or not.
CEmbodiedEntity * m_pcEmbodiedEntity
Reference to embodied entity associated to this sensor.
CVector3 Position
The position of the anchor wrt the global coordinate system.
Definition: physics_model.h:51
static CRNG * CreateRNG(const std::string &str_category)
Creates a new RNG inside the given category.
Definition: rng.cpp:326
CLightSensorEquippedEntity * m_pcLightEntity
Reference to light sensor equipped entity associated to this sensor.
void AddCheckedRay(bool b_obstructed, const CRay3 &c_ray)
Adds a ray to the list of checked rays.
#define ARGOS_PI
To be used when initializing static variables.
Definition: angles.h:32
The namespace containing all the ARGoS related code.
Definition: ci_actuator.h:12
const TReadings & GetReadings() const
Returns the readings of this sensor.
The core class of ARGOS.
Definition: simulator.h:62
static const CRadians PI_OVER_TWO
Set to PI / 2.
Definition: angles.h:59
CRadians GetZAngle() const
Returns the angle between this vector and the z axis.
Definition: vector3.h:339
const SAnchor & GetOriginAnchor() const
Returns a const reference to the origin anchor associated to this entity.
CEntity & GetComponent(const std::string &str_component)
Returns the component with the passed string label.
REGISTER_SENSOR(CEyeBotLightRotZOnlySensor,"eyebot_light","rot_z_only","Carlo Pinciroli [ilpincy@gmail.com]","1.0","The eye-bot light sensor (optimized for 2D).","This sensor accesses a set of light sensors. The sensors all return a value\n""between 0 and 1, where 0 means nothing within range and 1 means the perceived\n""light saturates the sensor. Values between 0 and 1 depend on the distance of\n""the perceived light. Each reading R is calculated with R=(I/x)^2, where x is the\n""distance between a sensor and the light, and I is the reference intensity of the\n""perceived light. The reference intensity corresponds to the minimum distance at\n""which the light saturates a sensor. The reference intensity depends on the\n""individual light, and it is set with the \"intensity\" attribute of the light\n""entity. In case multiple lights are present in the environment, each sensor\n""reading is calculated as the sum of the individual readings due to each light.\n""In other words, light wave interference is not taken into account. In\n""controllers, you must include the ci_light_sensor.h header.\n\n""REQUIRED XML CONFIGURATION\n\n"" <controllers>\n"" ...\n"" <my_controller ...>\n"" ...\n"" <sensors>\n"" ...\n"" <eyebot_light implementation=\"rot_z_only\" />\n"" ...\n"" </sensors>\n"" ...\n"" </my_controller>\n"" ...\n"" </controllers>\n\n""OPTIONAL XML CONFIGURATION\n\n""It is possible to draw the rays shot by the light sensor in the OpenGL\n""visualization. This can be useful for sensor debugging but also to understand\n""what's wrong in your controller. In OpenGL, the rays are drawn in cyan when\n""they are not obstructed and in purple when they are. In case a ray is\n""obstructed, a black dot is drawn where the intersection occurred.\n""To turn this functionality on, add the attribute \"show_rays\" as in this\n""example:\n\n"" <controllers>\n"" ...\n"" <my_controller ...>\n"" ...\n"" <sensors>\n"" ...\n"" <eyebot_light implementation=\"rot_z_only\"\n"" show_rays=\"true\" />\n"" ...\n"" </sensors>\n"" ...\n"" </my_controller>\n"" ...\n"" </controllers>\n\n""It is possible to add uniform noise to the sensors, thus matching the\n""characteristics of a real robot better. This can be done with the attribute\n""\"noise_level\", whose allowed range is in [-1,1] and is added to the calculated\n""reading. The final sensor reading is always normalized in the [0-1] range.\n\n"" <controllers>\n"" ...\n"" <my_controller ...>\n"" ...\n"" <sensors>\n"" ...\n"" <eyebot_light implementation=\"rot_z_only\"\n"" noise_level=\"0.1\" />\n"" ...\n"" </sensors>\n"" ...\n"" </my_controller>\n"" ...\n"" </controllers>\n\n""OPTIONAL XML CONFIGURATION\n\n""None.\n","Usable")