0

This is segment of code of 3dcpptutorials ray tracing. Can someone explain me how this lines of code works ?

As I understand it, if it's less than 0, it stores 0 and if it's greater than 1, then 255 and if it's between, then value * 255, something like that. Am I correct ?

colorbuffer[2] = Color.r <= 0.0f ? 0 : Color.r >= 1.0 ? 255 : (BYTE)(Color.r * 255);
colorbuffer[1] = Color.g <= 0.0f ? 0 : Color.g >= 1.0 ? 255 : (BYTE)(Color.g * 255);
colorbuffer[0] = Color.b <= 0.0f ? 0 : Color.b >= 1.0 ? 255 : (BYTE)(Color.b * 255);
2
  • Yes. This operation is commonly referred to as "clamping". Commented Jan 2, 2020 at 12:54
  • The code convert each color component from floating-point value in a range of 0.0 to 1.0 to an integer value between 0 and 255. Commented Jan 2, 2020 at 13:05

1 Answer 1

1

Correct. Due to right-to-left associativity of the ?: operator, the line

colorbuffer[2] = Color.r <= 0.0f ? 
    0 : Color.r >= 1.0 ? 255 : (BYTE)(Color.r * 255);

is equivalent to this one:

colorbuffer[2] = Color.r <= 0.0f ? 
    0 : (Color.r >= 1.0 ? 255 : (BYTE)(Color.r * 255));

which in turn is equivalent to the following if-else block:

if (Color.r <= 0.0f) 
    colorbuffer[2] = 0;
else {
    if (Color.r >= 1.0) 
        colorbuffer[2] = 255;
    else
        colorbuffer[2] = (BYTE)(Color.r * 255);
}

There is the std::clamp function in the standard library to do this kind of job:

colorbuffer[2] = (BYTE)(std::clamp(Color.r, 0.f, 1.f) * 255);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.