ColorRGBA is dangerous

Hello. Just wanted to post here something really funny & potential dangerous.
ColorRGBA is not immutable, that means that the static definitions of colors are global and also mutable. I just created a directional light and changed the light color depending on the position of the sun.

I did first color=ColorRGBA.White. Like I would do with Java’s AWT color=Color.WHITE.
Then I changed the color RGB values

color = ColorRGBA.White;
// somewhere else
color.r = calcRed(position);
color.g = calcGreen(position);
color.b = calcBlue(position);
// later
light.setColor(color);

My GUI started to look like this:

image

I was thinking that the directional light somehow changes the GUI-node.

After some testing it was clear that I have changed the color White globally.
So, yeah, don’t use the ColorRGBA#White etc. definitions.

2 Likes

This is true of all of the JME “constants”. In the interest of performance, we expect users of JME to not do some silly things.

I believe there is a some kind of debug app state you can add that checks the constants every frame to see if you’ve messed them up in some way. That’s the only way to guard against this.

ColorRGBA, Vector3f, Quaternion, etc. are mutable on purpose.

1 Like

And if you want to use one of the defined colors as a starting point, the right way to do it is:

color = new ColorRGBA(ColorRGBA.White); // unless ColorRGBA.* has been imported, then you can just use 'White'

3 Likes

Or ColorRGBA.White.clone()

2 Likes

And in JME you can mult/etc to get a new object or multLocal to modify the existing object. So ColorRGBA.White.mult(0.8f) is a new object whereas ColorRGBA.White.multLocal(0.8f) would modify ColorRGBA.White.

2 Likes