Re: [csswg-drafts] [css-color-4] Gamut mapping pseudocode is confusing (#10226)

@romainmenke It's a binary search, your first example is missing the else:

```js
                // 18.4.3. if E < JND
  if (E < JND) {
   ...
  }
                else {
                        max = chroma;
                }
```

I was responsible for the changes that helped speed up the algorithm, so I can speak to the intention of the algorithm even if the prose is confusing.

The intention was, assuming the color is out of gamut, to return a color just under the JND. Obviously, if the color starts out under the JND, the color is just clipped and returned, if not, we use a binary search to narrow down on a color just under the JND. The JND is our target, or better put, as close to the JND while not going over.

It is expensive to check if the color is in gamut on every iteration, so we stop doing it once we know the lower of the search is no longer in gamut. At that point, we can assume all iterations are out of gamut.

So we set the `min` to the current chroma if we know the lower bound is still in gamut and the current iteration is in gamut. If we ever get a color below the JND that is out of gamut, we set the `min` to chroma and we then know the minimum is no longer in gamut and we can stop doing `in_gamut` checks.

In short, once `min_inGamut` is `false`, we no longer need to check if the color is in gamut, we know it isn't. Then we can focus on bisecting to get as close to the JND as the threshold allows. Then we set `min` to chroma if we are below the JND and `max` to chroma if we are above. Once we are close enough to the JND, we kick out of the loop.

The only two exit conditions from the loop: if we get within the threshold of the JND, so `JND - E < EPSILON` or when the `min` and `max` are too close to each other `while ((max - min) > EPSILON)`. There are no other exits.



-- 
GitHub Notification of comment by facelessuser
Please view or discuss this issue at https://github.com/w3c/csswg-drafts/issues/10226#issuecomment-2065528227 using your GitHub account


-- 
Sent via github-notify-ml as configured in https://github.com/w3c/github-notify-ml-config

Received on Friday, 19 April 2024 00:22:27 UTC