Gazebo Sim

API Reference

8.7.0
Light config

This tutorial gives an introduction to Gazebo Sim's service /world/<world name>/light_config. This service will allow to modify lights in the scene.

Modifying lights

To modify lights inside the scene we need to use the service /world/<world name>/light_config and fill the message gz::msgs::Light.

This tutorial describes the code in the examples/standalone/light_control example.

First we create a point light with the function createLight():

gz::msgs::EntityFactory entityFactoryRequest;
entityFactoryRequest.mutable_light()->set_name("point");
entityFactoryRequest.mutable_light()->set_range(4);
entityFactoryRequest.mutable_light()->set_intensity(1);
entityFactoryRequest.mutable_light()->set_attenuation_linear(0.5);
entityFactoryRequest.mutable_light()->set_attenuation_constant(0.2);
entityFactoryRequest.mutable_light()->set_attenuation_quadratic(0.01);
entityFactoryRequest.mutable_light()->set_cast_shadows(false);
entityFactoryRequest.mutable_light()->set_type(gz::msgs::Light::POINT);
entityFactoryRequest.mutable_light()->mutable_direction(),
gz::math::Vector3d(directionX, directionY, directionZ));
gz::msgs::Set(entityFactoryRequest.mutable_light()->mutable_pose(),
gz::math::Pose3d(0.0, 0, 3.0, 0.0, 0.0, 0.0));

NOTE:: You can check the entity creation tutorial to learn how to include models and lights in the scene.

As you can see in the snippet below, we then modify the specular and diffuse colors of the point light in the scene.

lightRequest.set_name("point");
lightRequest.set_range(4);
lightRequest.set_intensity(1);
lightRequest.set_attenuation_linear(0.5);
lightRequest.set_attenuation_constant(0.2);
lightRequest.set_attenuation_quadratic(0.01);
lightRequest.set_cast_shadows(false);
lightRequest.set_type(gz::msgs::Light::POINT);
// direction field only affects spot / directional lights
gz::msgs::Set(lightRequest.mutable_direction(),
gz::math::Vector3d(directionX, directionY, directionZ));
gz::msgs::Set(lightRequest.mutable_pose(),
gz::math::Pose3d(0.0, -1.5, 3.0, 0.0, 0.0, 0.0));
gz::msgs::Set(lightRequest.mutable_diffuse(),
gz::math::Color(r, g, b, 1));
gz::msgs::Set(lightRequest.mutable_specular(),
gz::math::Color(r, g, b, 1));

The r, g, b components of the light diffuse and specular colors are randomly generated and constantly changing:

while (m < epsilon)
{
r = distr(twister);
g = distr(twister);
b = distr(twister);
m = std::sqrt(r*r + b*b + g*g);
}
r /= m;
g /= m;
b /= m;

Run the example

To run this example you should cd into examples/standalone/light_control and build the code:

mkdir build
cd build
cmake ..
make

Then you should open two terminals and run:

  • Terminal one:
    gz sim -r -v 4 empty.sdf
  • Terminal two:
    ./light_control