◐ Shell
clean mode source ↗

Added hsb() and rgb() helper functions by brownian-motion · Pull Request #6021 · processing/processing

@brownian-motion

When using Processing, I frequently find myself wanting to create a color with a specific hue, saturation, or brightness while in RGB mode. For example, when creating random colors, I often found myself writing something like:

color c = color(255 * (float) Math.random(), 255 * (float) Math.random(), 255 * (float) Math.random());

but this produces bright and dark colors, as well as vibrant and dull colors. What I really wanted was
a color with a random hue, like so:

color c = hsv(255 * (float) Math.random(), 200, 200);

but frequently had to achieve this by "switching modes" halfway through a program:

colorMode(HSV);
color c = color(255 * (float) Math.random(), 200, 200);
colorMode(RGB);

This PR adds the helper functions I've wanted for so long, to be able to create an arbitrary color in either color space, without having to switch color modes before/after the call.

@jeremydouglass

Neat idea!

If something like this was exposed (which I personally like, but I believe Ben is the decider on expanding the API) then personally I think it would make more sense to use signature overloading.

That could be:

color c;
c = hsb(h, s, b);
c = hsb(h, s, b, a);
c = rgb(r, g, b);
c = rgb(r, g, b, a);

...but honestly, for consistency with the API I would instead have expected it to be a five-argument form of color() that uses the existing RGB and HSB built-in keywords to indicate the mode:

color c;
c = color(r, g, b, a, RGB);
c = color(h, s, b, a, HSB);

You can't have a 4-argument form for color, as those signatures for taken, but it would be simple and clear, and not require four new function names with four new references pages et cetera.

It also might make sense to propose for Processing4 ....

@brownian-motion

Thanks for the comment, @jeremydouglass ! I thought about signature overloading (favoring hsb() over hsba()), and I agree that it's appealing. If @benfry agrees, I would be happy to edit the PR to incorporate that suggestion. (EDIT: I decided to go ahead and do this. d437bc6 has this overloaded API.)

I also strongly considered color(r, g, b, a, RGB), but I wanted a way to specify the color space without also specifying the alpha channel. For example, with the proposed API you can specify color c = rgb(100, 200, 250);, but overloading color() instead would require users to write color c = color(100, 200, 250, 255, RGB);, and that didn't seem as ergonomic to me. Again, I would happily yield to the judgement of @benfry and push an alternative that better fits the Processing project.

for creating HSB and RGB colors in any color mode.