Heatmap and speed sorting/filtering for interactive scenes [rewrite] (#2096)

* add InteractiveSpeed to scene model
* add InteractiveHeatmapSpeedGenerator
* add GenerateInteractiveHeatmapSpeedTask
* add InteractiveHeatmapSpeedTask to GenerateJob
* add InteractiveHeatmap on sceneRoutes
* delete heatmap when scene is destroyed
* render interactive heatmap in GridCard
* render InteractiveSpeed on SceneCard
* render InteractiveSpeed in SceneFileInfoPanel
* InteractiveSpeed filters
This commit is contained in:
agentfisk
2021-12-13 03:41:07 +01:00
committed by GitHub
parent d659411c61
commit e8447c520a
58 changed files with 3889 additions and 77 deletions

101
vendor/github.com/lucasb-eyer/go-colorful/.gitignore generated vendored Normal file
View File

@@ -0,0 +1,101 @@
# Created by https://www.toptal.com/developers/gitignore/api/code,go,linux,macos,windows
# Edit at https://www.toptal.com/developers/gitignore?templates=code,go,linux,macos,windows
### Code ###
.vscode/*
!.vscode/tasks.json
!.vscode/launch.json
*.code-workspace
### Go ###
# Binaries for programs and plugins
*.exe
*.exe~
*.dll
*.so
*.dylib
# Test binary, built with `go test -c`
*.test
# Output of the go coverage tool, specifically when used with LiteIDE
*.out
# Dependency directories (remove the comment below to include it)
# vendor/
### Go Patch ###
/vendor/
/Godeps/
### Linux ###
*~
# temporary files which can be created if a process still has a handle open of a deleted file
.fuse_hidden*
# KDE directory preferences
.directory
# Linux trash folder which might appear on any partition or disk
.Trash-*
# .nfs files are created when an open file is removed but is still being accessed
.nfs*
### macOS ###
# General
.DS_Store
.AppleDouble
.LSOverride
# Icon must end with two \r
Icon
# Thumbnails
._*
# Files that might appear in the root of a volume
.DocumentRevisions-V100
.fseventsd
.Spotlight-V100
.TemporaryItems
.Trashes
.VolumeIcon.icns
.com.apple.timemachine.donotpresent
# Directories potentially created on remote AFP share
.AppleDB
.AppleDesktop
Network Trash Folder
Temporary Items
.apdisk
### Windows ###
# Windows thumbnail cache files
Thumbs.db
Thumbs.db:encryptable
ehthumbs.db
ehthumbs_vista.db
# Dump file
*.stackdump
# Folder config file
[Dd]esktop.ini
# Recycle Bin used on file shares
$RECYCLE.BIN/
# Windows Installer files
*.cab
*.msi
*.msix
*.msm
*.msp
# Windows shortcuts
*.lnk
# End of https://www.toptal.com/developers/gitignore/api/code,go,linux,macos,windows

42
vendor/github.com/lucasb-eyer/go-colorful/CHANGELOG.md generated vendored Normal file
View File

@@ -0,0 +1,42 @@
# Changelog
All notable changes to this project will be documented in this file.
This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
The format of this file is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
but only releases after v1.0.3 properly adhere to it.
## [1.2.0] - 2021-01-27
### Added
- HSLuv and HPLuv color spaces (#41, #51)
- CIE LCh(uv) color space, called `LuvLCh` in code (#51)
- JSON and envconfig serialization support for `HexColor` (#42)
- `DistanceLinearRGB` (#53)
### Fixed
- RGB to/from XYZ conversion is more accurate (#51)
- A bug in `XYZToLuvWhiteRef` that only applied to very small values was fixed (#51)
- `BlendHCL` output is clamped so that it's not invalid (#46)
- Properly documented `DistanceCIE76` (#40)
- Some small godoc fixes
## [1.0.3] - 2019-11-11
- Remove SQLMock dependency
## [1.0.2] - 2019-04-07
- Fixes SQLMock dependency
## [1.0.1] - 2019-03-24
- Adds support for Go Modules
## [1.0.0] - 2018-05-26
- API Breaking change in `MakeColor`: instead of `panic`ing when alpha is zero, it now returns a secondary, boolean return value indicating success. See [the color.Color interface](#the-colorcolor-interface) section and [this FAQ entry](#q-why-would-makecolor-ever-fail) for details.
## [0.9.0] - 2018-05-26
- Initial version number after having ignored versioning for a long time :)

7
vendor/github.com/lucasb-eyer/go-colorful/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,7 @@
Copyright (c) 2013 Lucas Beyer
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

482
vendor/github.com/lucasb-eyer/go-colorful/README.md generated vendored Normal file
View File

@@ -0,0 +1,482 @@
go-colorful
===========
[![go reportcard](https://goreportcard.com/badge/github.com/lucasb-eyer/go-colorful)](https://goreportcard.com/report/github.com/lucasb-eyer/go-colorful)
A library for playing with colors in Go. Supports Go 1.13 onwards.
Why?
====
I love games. I make games. I love detail and I get lost in detail.
One such detail popped up during the development of [Memory Which Does Not Suck](https://github.com/lucasb-eyer/mwdns/),
when we wanted the server to assign the players random colors. Sometimes
two players got very similar colors, which bugged me. The very same evening,
[I want hue](http://tools.medialab.sciences-po.fr/iwanthue/) was the top post
on HackerNews' frontpage and showed me how to Do It Right™. Last but not
least, there was no library for handling color spaces available in go. Colorful
does just that and implements Go's `color.Color` interface.
What?
=====
Go-Colorful stores colors in RGB and provides methods from converting these to various color-spaces. Currently supported colorspaces are:
- **RGB:** All three of Red, Green and Blue in [0..1].
- **HSL:** Hue in [0..360], Saturation and Luminance in [0..1]. For legacy reasons; please forget that it exists.
- **HSV:** Hue in [0..360], Saturation and Value in [0..1]. You're better off using HCL, see below.
- **Hex RGB:** The "internet" color format, as in #FF00FF.
- **Linear RGB:** See [gamma correct rendering](http://www.sjbrown.co.uk/2004/05/14/gamma-correct-rendering/).
- **CIE-XYZ:** CIE's standard color space, almost in [0..1].
- **CIE-xyY:** encodes chromacity in x and y and luminance in Y, all in [0..1]
- **CIE-L\*a\*b\*:** A *perceptually uniform* color space, i.e. distances are meaningful. L\* in [0..1] and a\*, b\* almost in [-1..1].
- **CIE-L\*u\*v\*:** Very similar to CIE-L\*a\*b\*, there is [no consensus](http://en.wikipedia.org/wiki/CIELUV#Historical_background) on which one is "better".
- **CIE-L\*C\*h° (HCL):** This is generally the [most useful](http://vis4.net/blog/posts/avoid-equidistant-hsv-colors/) one; CIE-L\*a\*b\* space in polar coordinates, i.e. a *better* HSV. H° is in [0..360], C\* almost in [-1..1] and L\* as in CIE-L\*a\*b\*.
- **CIE LCh(uv):** Called `LuvLCh` in code, this is a cylindrical transformation of the CIE-L\*u\*v\* color space. Like HCL above: H° is in [0..360], C\* almost in [-1..1] and L\* as in CIE-L\*u\*v\*.
- **HSLuv:** The better alternative to HSL, see [here](https://www.hsluv.org/) and [here](https://www.kuon.ch/post/2020-03-08-hsluv/). Hue in [0..360], Saturation and Luminance in [0..1].
- **HPLuv:** A variant of HSLuv. The color space is smoother, but only pastel colors can be included. Because the valid colors are limited, it's easy to get invalid Saturation values way above 1.0, indicating the color can't be represented in HPLuv beccause it's not pastel.
For the colorspaces where it makes sense (XYZ, Lab, Luv, HCl), the
[D65](http://en.wikipedia.org/wiki/Illuminant_D65) is used as reference white
by default but methods for using your own reference white are provided.
A coordinate being *almost in* a range means that generally it is, but for very
bright colors and depending on the reference white, it might overflow this
range slightly. For example, C\* of #0000ff is 1.338.
Unit-tests are provided.
Nice, but what's it useful for?
-------------------------------
- Converting color spaces. Some people like to do that.
- Blending (interpolating) between colors in a "natural" look by using the right colorspace.
- Generating random colors under some constraints (e.g. colors of the same shade, or shades of one color.)
- Generating gorgeous random palettes with distinct colors of a same temperature.
What not (yet)?
===============
There are a few features which are currently missing and might be useful.
I just haven't implemented them yet because I didn't have the need for it.
Pull requests welcome.
- Sorting colors (potentially using above mentioned distances)
So which colorspace should I use?
=================================
It depends on what you want to do. I think the folks from *I want hue* are
on-spot when they say that RGB fits to how *screens produce* color, CIE L\*a\*b\*
fits how *humans perceive* color and HCL fits how *humans think* colors.
Whenever you'd use HSV, rather go for CIE-L\*C\*h°. for fixed lightness L\* and
chroma C\* values, the hue angle h° rotates through colors of the same
perceived brightness and intensity.
How?
====
### Installing
Installing the library is as easy as
```bash
$ go get github.com/lucasb-eyer/go-colorful
```
The package can then be used through an
```go
import "github.com/lucasb-eyer/go-colorful"
```
### Basic usage
Create a beautiful blue color using different source space:
```go
// Any of the following should be the same
c := colorful.Color{0.313725, 0.478431, 0.721569}
c, err := colorful.Hex("#517AB8")
if err != nil {
log.Fatal(err)
}
c = colorful.Hsv(216.0, 0.56, 0.722)
c = colorful.Xyz(0.189165, 0.190837, 0.480248)
c = colorful.Xyy(0.219895, 0.221839, 0.190837)
c = colorful.Lab(0.507850, 0.040585,-0.370945)
c = colorful.Luv(0.507849,-0.194172,-0.567924)
c = colorful.Hcl(276.2440, 0.373160, 0.507849)
fmt.Printf("RGB values: %v, %v, %v", c.R, c.G, c.B)
```
And then converting this color back into various color spaces:
```go
hex := c.Hex()
h, s, v := c.Hsv()
x, y, z := c.Xyz()
x, y, Y := c.Xyy()
l, a, b := c.Lab()
l, u, v := c.Luv()
h, c, l := c.Hcl()
```
Note that, because of Go's unfortunate choice of requiring an initial uppercase,
the name of the functions relating to the xyY space are just off. If you have
any good suggestion, please open an issue. (I don't consider XyY good.)
### The `color.Color` interface
Because a `colorful.Color` implements Go's `color.Color` interface (found in the
`image/color` package), it can be used anywhere that expects a `color.Color`.
Furthermore, you can convert anything that implements the `color.Color` interface
into a `colorful.Color` using the `MakeColor` function:
```go
c, ok := colorful.MakeColor(color.Gray16{12345})
```
**Caveat:** Be aware that this latter conversion (using `MakeColor`) hits a
corner-case when alpha is exactly zero. Because `color.Color` uses pre-multiplied
alpha colors, this means the RGB values are lost (set to 0) and it's impossible
to recover them. In such a case `MakeColor` will return `false` as its second value.
### Comparing colors
In the RGB color space, the Euclidian distance between colors *doesn't* correspond
to visual/perceptual distance. This means that two pairs of colors which have the
same distance in RGB space can look much further apart. This is fixed by the
CIE-L\*a\*b\*, CIE-L\*u\*v\* and CIE-L\*C\*h° color spaces.
Thus you should only compare colors in any of these space.
(Note that the distance in CIE-L\*a\*b\* and CIE-L\*C\*h° are the same, since it's the same space but in cylindrical coordinates)
![Color distance comparison](doc/colordist/colordist.png)
The two colors shown on the top look much more different than the two shown on
the bottom. Still, in RGB space, their distance is the same.
Here is a little example program which shows the distances between the top two
and bottom two colors in RGB, CIE-L\*a\*b\* and CIE-L\*u\*v\* space. You can find it in `doc/colordist/colordist.go`.
```go
package main
import "fmt"
import "github.com/lucasb-eyer/go-colorful"
func main() {
c1a := colorful.Color{150.0 / 255.0, 10.0 / 255.0, 150.0 / 255.0}
c1b := colorful.Color{53.0 / 255.0, 10.0 / 255.0, 150.0 / 255.0}
c2a := colorful.Color{10.0 / 255.0, 150.0 / 255.0, 50.0 / 255.0}
c2b := colorful.Color{99.9 / 255.0, 150.0 / 255.0, 10.0 / 255.0}
fmt.Printf("DistanceRgb: c1: %v\tand c2: %v\n", c1a.DistanceRgb(c1b), c2a.DistanceRgb(c2b))
fmt.Printf("DistanceLab: c1: %v\tand c2: %v\n", c1a.DistanceLab(c1b), c2a.DistanceLab(c2b))
fmt.Printf("DistanceLuv: c1: %v\tand c2: %v\n", c1a.DistanceLuv(c1b), c2a.DistanceLuv(c2b))
fmt.Printf("DistanceCIE76: c1: %v\tand c2: %v\n", c1a.DistanceCIE76(c1b), c2a.DistanceCIE76(c2b))
fmt.Printf("DistanceCIE94: c1: %v\tand c2: %v\n", c1a.DistanceCIE94(c1b), c2a.DistanceCIE94(c2b))
fmt.Printf("DistanceCIEDE2000: c1: %v\tand c2: %v\n", c1a.DistanceCIEDE2000(c1b), c2a.DistanceCIEDE2000(c2b))
}
```
Running the above program shows that you should always prefer any of the CIE distances:
```bash
$ go run colordist.go
DistanceRgb: c1: 0.3803921568627451 and c2: 0.3858713931171159
DistanceLab: c1: 0.32048458312798056 and c2: 0.24397151758565272
DistanceLuv: c1: 0.5134369614199698 and c2: 0.2568692839860636
DistanceCIE76: c1: 0.32048458312798056 and c2: 0.24397151758565272
DistanceCIE94: c1: 0.19799168128511324 and c2: 0.12207136371167401
DistanceCIEDE2000: c1: 0.17274551120971166 and c2: 0.10665210031428465
```
It also shows that `DistanceLab` is more formally known as `DistanceCIE76` and
has been superseded by the slightly more accurate, but much more expensive
`DistanceCIE94` and `DistanceCIEDE2000`.
Note that `AlmostEqualRgb` is provided mainly for (unit-)testing purposes. Use
it only if you really know what you're doing. It will eat your cat.
### Blending colors
Blending is highly connected to distance, since it basically "walks through" the
colorspace thus, if the colorspace maps distances well, the walk is "smooth".
Colorful comes with blending functions in RGB, HSV and any of the LAB spaces.
Of course, you'd rather want to use the blending functions of the LAB spaces since
these spaces map distances well but, just in case, here is an example showing
you how the blendings (`#fdffcc` to `#242a42`) are done in the various spaces:
![Blending colors in different spaces.](doc/colorblend/colorblend.png)
What you see is that HSV is really bad: it adds some green, which is not present
in the original colors at all! RGB is much better, but it stays light a little
too long. LUV and LAB both hit the right lightness but LAB has a little more
color. HCL works in the same vein as HSV (both cylindrical interpolations) but
it does it right in that there is no green appearing and the lighthness changes
in a linear manner.
While this seems all good, you need to know one thing: When interpolating in any
of the CIE color spaces, you might get invalid RGB colors! This is important if
the starting and ending colors are user-input or random. An example of where this
happens is when blending between `#eeef61` and `#1e3140`:
![Invalid RGB colors may crop up when blending in CIE spaces.](doc/colorblend/invalid.png)
You can test whether a color is a valid RGB color by calling the `IsValid` method
and indeed, calling IsValid will return false for the redish colors on the bottom.
One way to "fix" this is to get a valid color close to the invalid one by calling
`Clamped`, which always returns a nearby valid color. Doing this, we get the
following result, which is satisfactory:
![Fixing invalid RGB colors by clamping them to the valid range.](doc/colorblend/clamped.png)
The following is the code creating the above three images; it can be found in `doc/colorblend/colorblend.go`
```go
package main
import "fmt"
import "github.com/lucasb-eyer/go-colorful"
import "image"
import "image/draw"
import "image/png"
import "os"
func main() {
blocks := 10
blockw := 40
img := image.NewRGBA(image.Rect(0,0,blocks*blockw,200))
c1, _ := colorful.Hex("#fdffcc")
c2, _ := colorful.Hex("#242a42")
// Use these colors to get invalid RGB in the gradient.
//c1, _ := colorful.Hex("#EEEF61")
//c2, _ := colorful.Hex("#1E3140")
for i := 0 ; i < blocks ; i++ {
draw.Draw(img, image.Rect(i*blockw, 0,(i+1)*blockw, 40), &image.Uniform{c1.BlendHsv(c2, float64(i)/float64(blocks-1))}, image.Point{}, draw.Src)
draw.Draw(img, image.Rect(i*blockw, 40,(i+1)*blockw, 80), &image.Uniform{c1.BlendLuv(c2, float64(i)/float64(blocks-1))}, image.Point{}, draw.Src)
draw.Draw(img, image.Rect(i*blockw, 80,(i+1)*blockw,120), &image.Uniform{c1.BlendRgb(c2, float64(i)/float64(blocks-1))}, image.Point{}, draw.Src)
draw.Draw(img, image.Rect(i*blockw,120,(i+1)*blockw,160), &image.Uniform{c1.BlendLab(c2, float64(i)/float64(blocks-1))}, image.Point{}, draw.Src)
draw.Draw(img, image.Rect(i*blockw,160,(i+1)*blockw,200), &image.Uniform{c1.BlendHcl(c2, float64(i)/float64(blocks-1))}, image.Point{}, draw.Src)
// This can be used to "fix" invalid colors in the gradient.
//draw.Draw(img, image.Rect(i*blockw,160,(i+1)*blockw,200), &image.Uniform{c1.BlendHcl(c2, float64(i)/float64(blocks-1)).Clamped()}, image.Point{}, draw.Src)
}
toimg, err := os.Create("colorblend.png")
if err != nil {
fmt.Printf("Error: %v", err)
return
}
defer toimg.Close()
png.Encode(toimg, img)
}
```
#### Generating color gradients
A very common reason to blend colors is creating gradients. There is an example
program in [doc/gradientgen.go](doc/gradientgen/gradientgen.go); it doesn't use any API
which hasn't been used in the previous example code, so I won't bother pasting
the code in here. Just look at that gorgeous gradient it generated in HCL space:
!["Spectral" colorbrewer gradient in HCL space.](doc/gradientgen/gradientgen.png)
### Getting random colors
It is sometimes necessary to generate random colors. You could simply do this
on your own by generating colors with random values. By restricting the random
values to a range smaller than [0..1] and using a space such as CIE-H\*C\*l° or
HSV, you can generate both random shades of a color or random colors of a
lightness:
```go
random_blue := colorful.Hcl(180.0+rand.Float64()*50.0, 0.2+rand.Float64()*0.8, 0.3+rand.Float64()*0.7)
random_dark := colorful.Hcl(rand.Float64()*360.0, rand.Float64(), rand.Float64()*0.4)
random_light := colorful.Hcl(rand.Float64()*360.0, rand.Float64(), 0.6+rand.Float64()*0.4)
```
Since getting random "warm" and "happy" colors is quite a common task, there
are some helper functions:
```go
colorful.WarmColor()
colorful.HappyColor()
colorful.FastWarmColor()
colorful.FastHappyColor()
```
The ones prefixed by `Fast` are faster but less coherent since they use the HSV
space as opposed to the regular ones which use CIE-L\*C\*h° space. The
following picture shows the warm colors in the top two rows and happy colors
in the bottom two rows. Within these, the first is the regular one and the
second is the fast one.
![Warm, fast warm, happy and fast happy random colors, respectively.](doc/colorgens/colorgens.png)
Don't forget to initialize the random seed! You can see the code used for
generating this picture in `doc/colorgens/colorgens.go`.
### Getting random palettes
As soon as you need to generate more than one random color, you probably want
them to be distinguishible. Playing against an opponent which has almost the
same blue as I do is not fun. This is where random palettes can help.
These palettes are generated using an algorithm which ensures that all colors
on the palette are as distinguishible as possible. Again, there is a `Fast`
method which works in HSV and is less perceptually uniform and a non-`Fast`
method which works in CIE spaces. For more theory on `SoftPalette`, check out
[I want hue](http://tools.medialab.sciences-po.fr/iwanthue/theory.php). Yet
again, there is a `Happy` and a `Warm` version, which do what you expect, but
now there is an additional `Soft` version, which is more configurable: you can
give a constraint on the color space in order to get colors within a certain *feel*.
Let's start with the simple methods first, all they take is the amount of
colors to generate, which could, for example, be the player count. They return
an array of `colorful.Color` objects:
```go
pal1, err1 := colorful.WarmPalette(10)
pal2 := colorful.FastWarmPalette(10)
pal3, err3 := colorful.HappyPalette(10)
pal4 := colorful.FastHappyPalette(10)
pal5, err5 := colorful.SoftPalette(10)
```
Note that the non-fast methods *may* fail if you ask for way too many colors.
Let's move on to the advanced one, namely `SoftPaletteEx`. Besides the color
count, this function takes a `SoftPaletteSettings` object as argument. The
interesting part here is its `CheckColor` member, which is a boolean function
taking three floating points as arguments: `l`, `a` and `b`. This function
should return `true` for colors which lie within the region you want and `false`
otherwise. The other members are `Iteration`, which should be within [5..100]
where higher means slower but more exact palette, and `ManySamples` which you
should set to `true` in case your `CheckColor` constraint rejects a large part
of the color space.
For example, to create a palette of 10 brownish colors, you'd call it like this:
```go
func isbrowny(l, a, b float64) bool {
h, c, L := colorful.LabToHcl(l, a, b)
return 10.0 < h && h < 50.0 && 0.1 < c && c < 0.5 && L < 0.5
}
// Since the above function is pretty restrictive, we set ManySamples to true.
brownies := colorful.SoftPaletteEx(10, colorful.SoftPaletteSettings{isbrowny, 50, true})
```
The following picture shows the palettes generated by all of these methods
(sourcecode in `doc/palettegens/palettegens.go`), in the order they were presented, i.e.
from top to bottom: `Warm`, `FastWarm`, `Happy`, `FastHappy`, `Soft`,
`SoftEx(isbrowny)`. All of them contain some randomness, so YMMV.
![All example palettes](doc/palettegens/palettegens.png)
Again, the code used for generating the above image is available as [doc/palettegens/palettegens.go](https://github.com/lucasb-eyer/go-colorful/blob/master/doc/palettegens/palettegens.go).
### Sorting colors
TODO: Sort using dist fn.
### Using linear RGB for computations
There are two methods for transforming RGB<->Linear RGB: a fast and almost precise one,
and a slow and precise one.
```go
r, g, b := colorful.Hex("#FF0000").FastLinearRgb()
```
TODO: describe some more.
### Want to use some other reference point?
```go
c := colorful.LabWhiteRef(0.507850, 0.040585,-0.370945, colorful.D50)
l, a, b := c.LabWhiteRef(colorful.D50)
```
### Reading and writing colors from databases
The type `HexColor` makes it easy to store colors as strings in a database. It
implements the [https://godoc.org/database/sql#Scanner](database/sql.Scanner)
and [database/sql/driver.Value](https://godoc.org/database/sql/driver.Value)
interfaces which provide automatic type conversion.
Example:
```go
var hc HexColor
_, err := db.QueryRow("SELECT '#ff0000';").Scan(&hc)
// hc == HexColor{R: 1, G: 0, B: 0}; err == nil
```
FAQ
===
### Q: I get all f!@#ed up values! Your library sucks!
A: You probably provided values in the wrong range. For example, RGB values are
expected to reside between 0 and 1, *not* between 0 and 255. Normalize your colors.
### Q: Lab/Luv/HCl seem broken! Your library sucks!
They look like this:
<img height="150" src="https://user-images.githubusercontent.com/3779568/28646900-6548040c-7264-11e7-8f12-81097a97c260.png">
A: You're likely trying to generate and display colors that can't be represented by RGB,
and thus monitors. When you're trying to convert, say, `HCL(190.0, 1.0, 1.0).RGB255()`,
you're asking for RGB values of `(-2105.254 300.680 286.185)`, which clearly don't exist,
and the `RGB255` function just casts these numbers to `uint8`, creating wrap-around and
what looks like a completely broken gradient. What you want to do, is either use more
reasonable values of colors which actually exist in RGB, or just `Clamp()` the resulting
color to its nearest existing one, living with the consequences:
`HCL(190.0, 1.0, 1.0).Clamp().RGB255()`. It will look something like this:
<img height="150" src="https://user-images.githubusercontent.com/1476029/29596343-9a8c62c6-8771-11e7-9026-b8eb8852cc4a.png">
[Here's an issue going in-depth about this](https://github.com/lucasb-eyer/go-colorful/issues/14),
as well as [my answer](https://github.com/lucasb-eyer/go-colorful/issues/14#issuecomment-324205385),
both with code and pretty pictures. Also note that this was somewhat covered above in the
["Blending colors" section](https://github.com/lucasb-eyer/go-colorful#blending-colors).
### Q: In a tight loop, conversion to Lab/Luv/HCl/... are slooooow!
A: Yes, they are.
This library aims for correctness, readability, and modularity; it wasn't written with speed in mind.
A large part of the slowness comes from these conversions going through `LinearRgb` which uses powers.
I implemented a fast approximation to `LinearRgb` called `FastLinearRgb` by using Taylor approximations.
The approximation is roughly 5x faster and precise up to roughly 0.5%,
the major caveat being that if the input values are outside the range 0-1, accuracy drops dramatically.
You can use these in your conversions as follows:
```go
col := // Get your color somehow
l, a, b := XyzToLab(LinearRgbToXyz(col.LinearRgb()))
```
If you need faster versions of `Distance*` and `Blend*` that make use of this fast approximation,
feel free to implement them and open a pull-request, I'll happily accept.
The derivation of these functions can be followed in [this Jupyter notebook](doc/LinearRGB Approximations.ipynb).
Here's the main figure showing the approximation quality:
![approximation quality](doc/approx-quality.png)
More speed could be gained by using SIMD instructions in many places.
You can also get more speed for specific conversions by approximating the full conversion function,
but that is outside the scope of this library.
Thanks to [@ZirconiumX](https://github.com/ZirconiumX) for starting this investigation,
see [issue #18](https://github.com/lucasb-eyer/go-colorful/issues/18) for details.
### Q: Why would `MakeColor` ever fail!?
A: `MakeColor` fails when the alpha channel is zero. In that case, the
conversion is undefined. See [issue 21](https://github.com/lucasb-eyer/go-colorful/issues/21)
as well as the short caveat note in the ["The `color.Color` interface"](README.md#the-colorcolor-interface)
section above.
Who?
====
This library was developed by Lucas Beyer with contributions from
Bastien Dejean (@baskerville), Phil Kulak (@pkulak) and Christian Muehlhaeuser (@muesli).
It is now maintained by makeworld (@makeworld-the-better-one).
## License
This repo is under the MIT license, see [LICENSE](LICENSE) for details.

55
vendor/github.com/lucasb-eyer/go-colorful/colorgens.go generated vendored Normal file
View File

@@ -0,0 +1,55 @@
// Various ways to generate single random colors
package colorful
import (
"math/rand"
)
// Creates a random dark, "warm" color through a restricted HSV space.
func FastWarmColor() Color {
return Hsv(
rand.Float64()*360.0,
0.5+rand.Float64()*0.3,
0.3+rand.Float64()*0.3)
}
// Creates a random dark, "warm" color through restricted HCL space.
// This is slower than FastWarmColor but will likely give you colors which have
// the same "warmness" if you run it many times.
func WarmColor() (c Color) {
for c = randomWarm(); !c.IsValid(); c = randomWarm() {
}
return
}
func randomWarm() Color {
return Hcl(
rand.Float64()*360.0,
0.1+rand.Float64()*0.3,
0.2+rand.Float64()*0.3)
}
// Creates a random bright, "pimpy" color through a restricted HSV space.
func FastHappyColor() Color {
return Hsv(
rand.Float64()*360.0,
0.7+rand.Float64()*0.3,
0.6+rand.Float64()*0.3)
}
// Creates a random bright, "pimpy" color through restricted HCL space.
// This is slower than FastHappyColor but will likely give you colors which
// have the same "brightness" if you run it many times.
func HappyColor() (c Color) {
for c = randomPimp(); !c.IsValid(); c = randomPimp() {
}
return
}
func randomPimp() Color {
return Hcl(
rand.Float64()*360.0,
0.5+rand.Float64()*0.3,
0.5+rand.Float64()*0.3)
}

979
vendor/github.com/lucasb-eyer/go-colorful/colors.go generated vendored Normal file
View File

@@ -0,0 +1,979 @@
// The colorful package provides all kinds of functions for working with colors.
package colorful
import (
"fmt"
"image/color"
"math"
)
// A color is stored internally using sRGB (standard RGB) values in the range 0-1
type Color struct {
R, G, B float64
}
// Implement the Go color.Color interface.
func (col Color) RGBA() (r, g, b, a uint32) {
r = uint32(col.R*65535.0 + 0.5)
g = uint32(col.G*65535.0 + 0.5)
b = uint32(col.B*65535.0 + 0.5)
a = 0xFFFF
return
}
// Constructs a colorful.Color from something implementing color.Color
func MakeColor(col color.Color) (Color, bool) {
r, g, b, a := col.RGBA()
if a == 0 {
return Color{0, 0, 0}, false
}
// Since color.Color is alpha pre-multiplied, we need to divide the
// RGB values by alpha again in order to get back the original RGB.
r *= 0xffff
r /= a
g *= 0xffff
g /= a
b *= 0xffff
b /= a
return Color{float64(r) / 65535.0, float64(g) / 65535.0, float64(b) / 65535.0}, true
}
// Might come in handy sometimes to reduce boilerplate code.
func (col Color) RGB255() (r, g, b uint8) {
r = uint8(col.R*255.0 + 0.5)
g = uint8(col.G*255.0 + 0.5)
b = uint8(col.B*255.0 + 0.5)
return
}
// Used to simplify HSLuv testing.
func (col Color) values() (float64, float64, float64) {
return col.R, col.G, col.B
}
// This is the tolerance used when comparing colors using AlmostEqualRgb.
const Delta = 1.0 / 255.0
// This is the default reference white point.
var D65 = [3]float64{0.95047, 1.00000, 1.08883}
// And another one.
var D50 = [3]float64{0.96422, 1.00000, 0.82521}
// Checks whether the color exists in RGB space, i.e. all values are in [0..1]
func (c Color) IsValid() bool {
return 0.0 <= c.R && c.R <= 1.0 &&
0.0 <= c.G && c.G <= 1.0 &&
0.0 <= c.B && c.B <= 1.0
}
// clamp01 clamps from 0 to 1.
func clamp01(v float64) float64 {
return math.Max(0.0, math.Min(v, 1.0))
}
// Returns Clamps the color into valid range, clamping each value to [0..1]
// If the color is valid already, this is a no-op.
func (c Color) Clamped() Color {
return Color{clamp01(c.R), clamp01(c.G), clamp01(c.B)}
}
func sq(v float64) float64 {
return v * v
}
func cub(v float64) float64 {
return v * v * v
}
// DistanceRgb computes the distance between two colors in RGB space.
// This is not a good measure! Rather do it in Lab space.
func (c1 Color) DistanceRgb(c2 Color) float64 {
return math.Sqrt(sq(c1.R-c2.R) + sq(c1.G-c2.G) + sq(c1.B-c2.B))
}
// DistanceLinearRGB computes the distance between two colors in linear RGB
// space. This is not useful for measuring how humans perceive color, but
// might be useful for other things, like dithering.
func (c1 Color) DistanceLinearRGB(c2 Color) float64 {
r1, g1, b1 := c1.LinearRgb()
r2, g2, b2 := c2.LinearRgb()
return math.Sqrt(sq(r1-r2) + sq(g1-g2) + sq(b1-b2))
}
// Check for equality between colors within the tolerance Delta (1/255).
func (c1 Color) AlmostEqualRgb(c2 Color) bool {
return math.Abs(c1.R-c2.R)+
math.Abs(c1.G-c2.G)+
math.Abs(c1.B-c2.B) < 3.0*Delta
}
// You don't really want to use this, do you? Go for BlendLab, BlendLuv or BlendHcl.
func (c1 Color) BlendRgb(c2 Color, t float64) Color {
return Color{c1.R + t*(c2.R-c1.R),
c1.G + t*(c2.G-c1.G),
c1.B + t*(c2.B-c1.B)}
}
// Utility used by Hxx color-spaces for interpolating between two angles in [0,360].
func interp_angle(a0, a1, t float64) float64 {
// Based on the answer here: http://stackoverflow.com/a/14498790/2366315
// With potential proof that it works here: http://math.stackexchange.com/a/2144499
delta := math.Mod(math.Mod(a1-a0, 360.0)+540, 360.0) - 180.0
return math.Mod(a0+t*delta+360.0, 360.0)
}
/// HSV ///
///////////
// From http://en.wikipedia.org/wiki/HSL_and_HSV
// Note that h is in [0..360] and s,v in [0..1]
// Hsv returns the Hue [0..360], Saturation and Value [0..1] of the color.
func (col Color) Hsv() (h, s, v float64) {
min := math.Min(math.Min(col.R, col.G), col.B)
v = math.Max(math.Max(col.R, col.G), col.B)
C := v - min
s = 0.0
if v != 0.0 {
s = C / v
}
h = 0.0 // We use 0 instead of undefined as in wp.
if min != v {
if v == col.R {
h = math.Mod((col.G-col.B)/C, 6.0)
}
if v == col.G {
h = (col.B-col.R)/C + 2.0
}
if v == col.B {
h = (col.R-col.G)/C + 4.0
}
h *= 60.0
if h < 0.0 {
h += 360.0
}
}
return
}
// Hsv creates a new Color given a Hue in [0..360], a Saturation and a Value in [0..1]
func Hsv(H, S, V float64) Color {
Hp := H / 60.0
C := V * S
X := C * (1.0 - math.Abs(math.Mod(Hp, 2.0)-1.0))
m := V - C
r, g, b := 0.0, 0.0, 0.0
switch {
case 0.0 <= Hp && Hp < 1.0:
r = C
g = X
case 1.0 <= Hp && Hp < 2.0:
r = X
g = C
case 2.0 <= Hp && Hp < 3.0:
g = C
b = X
case 3.0 <= Hp && Hp < 4.0:
g = X
b = C
case 4.0 <= Hp && Hp < 5.0:
r = X
b = C
case 5.0 <= Hp && Hp < 6.0:
r = C
b = X
}
return Color{m + r, m + g, m + b}
}
// You don't really want to use this, do you? Go for BlendLab, BlendLuv or BlendHcl.
func (c1 Color) BlendHsv(c2 Color, t float64) Color {
h1, s1, v1 := c1.Hsv()
h2, s2, v2 := c2.Hsv()
// We know that h are both in [0..360]
return Hsv(interp_angle(h1, h2, t), s1+t*(s2-s1), v1+t*(v2-v1))
}
/// HSL ///
///////////
// Hsl returns the Hue [0..360], Saturation [0..1], and Luminance (lightness) [0..1] of the color.
func (col Color) Hsl() (h, s, l float64) {
min := math.Min(math.Min(col.R, col.G), col.B)
max := math.Max(math.Max(col.R, col.G), col.B)
l = (max + min) / 2
if min == max {
s = 0
h = 0
} else {
if l < 0.5 {
s = (max - min) / (max + min)
} else {
s = (max - min) / (2.0 - max - min)
}
if max == col.R {
h = (col.G - col.B) / (max - min)
} else if max == col.G {
h = 2.0 + (col.B-col.R)/(max-min)
} else {
h = 4.0 + (col.R-col.G)/(max-min)
}
h *= 60
if h < 0 {
h += 360
}
}
return
}
// Hsl creates a new Color given a Hue in [0..360], a Saturation [0..1], and a Luminance (lightness) in [0..1]
func Hsl(h, s, l float64) Color {
if s == 0 {
return Color{l, l, l}
}
var r, g, b float64
var t1 float64
var t2 float64
var tr float64
var tg float64
var tb float64
if l < 0.5 {
t1 = l * (1.0 + s)
} else {
t1 = l + s - l*s
}
t2 = 2*l - t1
h /= 360
tr = h + 1.0/3.0
tg = h
tb = h - 1.0/3.0
if tr < 0 {
tr++
}
if tr > 1 {
tr--
}
if tg < 0 {
tg++
}
if tg > 1 {
tg--
}
if tb < 0 {
tb++
}
if tb > 1 {
tb--
}
// Red
if 6*tr < 1 {
r = t2 + (t1-t2)*6*tr
} else if 2*tr < 1 {
r = t1
} else if 3*tr < 2 {
r = t2 + (t1-t2)*(2.0/3.0-tr)*6
} else {
r = t2
}
// Green
if 6*tg < 1 {
g = t2 + (t1-t2)*6*tg
} else if 2*tg < 1 {
g = t1
} else if 3*tg < 2 {
g = t2 + (t1-t2)*(2.0/3.0-tg)*6
} else {
g = t2
}
// Blue
if 6*tb < 1 {
b = t2 + (t1-t2)*6*tb
} else if 2*tb < 1 {
b = t1
} else if 3*tb < 2 {
b = t2 + (t1-t2)*(2.0/3.0-tb)*6
} else {
b = t2
}
return Color{r, g, b}
}
/// Hex ///
///////////
// Hex returns the hex "html" representation of the color, as in #ff0080.
func (col Color) Hex() string {
// Add 0.5 for rounding
return fmt.Sprintf("#%02x%02x%02x", uint8(col.R*255.0+0.5), uint8(col.G*255.0+0.5), uint8(col.B*255.0+0.5))
}
// Hex parses a "html" hex color-string, either in the 3 "#f0c" or 6 "#ff1034" digits form.
func Hex(scol string) (Color, error) {
format := "#%02x%02x%02x"
factor := 1.0 / 255.0
if len(scol) == 4 {
format = "#%1x%1x%1x"
factor = 1.0 / 15.0
}
var r, g, b uint8
n, err := fmt.Sscanf(scol, format, &r, &g, &b)
if err != nil {
return Color{}, err
}
if n != 3 {
return Color{}, fmt.Errorf("color: %v is not a hex-color", scol)
}
return Color{float64(r) * factor, float64(g) * factor, float64(b) * factor}, nil
}
/// Linear ///
//////////////
// http://www.sjbrown.co.uk/2004/05/14/gamma-correct-rendering/
// http://www.brucelindbloom.com/Eqn_RGB_to_XYZ.html
func linearize(v float64) float64 {
if v <= 0.04045 {
return v / 12.92
}
return math.Pow((v+0.055)/1.055, 2.4)
}
// LinearRgb converts the color into the linear RGB space (see http://www.sjbrown.co.uk/2004/05/14/gamma-correct-rendering/).
func (col Color) LinearRgb() (r, g, b float64) {
r = linearize(col.R)
g = linearize(col.G)
b = linearize(col.B)
return
}
// A much faster and still quite precise linearization using a 6th-order Taylor approximation.
// See the accompanying Jupyter notebook for derivation of the constants.
func linearize_fast(v float64) float64 {
v1 := v - 0.5
v2 := v1 * v1
v3 := v2 * v1
v4 := v2 * v2
//v5 := v3*v2
return -0.248750514614486 + 0.925583310193438*v + 1.16740237321695*v2 + 0.280457026598666*v3 - 0.0757991963780179*v4 //+ 0.0437040411548932*v5
}
// FastLinearRgb is much faster than and almost as accurate as LinearRgb.
// BUT it is important to NOTE that they only produce good results for valid colors r,g,b in [0,1].
func (col Color) FastLinearRgb() (r, g, b float64) {
r = linearize_fast(col.R)
g = linearize_fast(col.G)
b = linearize_fast(col.B)
return
}
func delinearize(v float64) float64 {
if v <= 0.0031308 {
return 12.92 * v
}
return 1.055*math.Pow(v, 1.0/2.4) - 0.055
}
// LinearRgb creates an sRGB color out of the given linear RGB color (see http://www.sjbrown.co.uk/2004/05/14/gamma-correct-rendering/).
func LinearRgb(r, g, b float64) Color {
return Color{delinearize(r), delinearize(g), delinearize(b)}
}
func delinearize_fast(v float64) float64 {
// This function (fractional root) is much harder to linearize, so we need to split.
if v > 0.2 {
v1 := v - 0.6
v2 := v1 * v1
v3 := v2 * v1
v4 := v2 * v2
v5 := v3 * v2
return 0.442430344268235 + 0.592178981271708*v - 0.287864782562636*v2 + 0.253214392068985*v3 - 0.272557158129811*v4 + 0.325554383321718*v5
} else if v > 0.03 {
v1 := v - 0.115
v2 := v1 * v1
v3 := v2 * v1
v4 := v2 * v2
v5 := v3 * v2
return 0.194915592891669 + 1.55227076330229*v - 3.93691860257828*v2 + 18.0679839248761*v3 - 101.468750302746*v4 + 632.341487393927*v5
} else {
v1 := v - 0.015
v2 := v1 * v1
v3 := v2 * v1
v4 := v2 * v2
v5 := v3 * v2
// You can clearly see from the involved constants that the low-end is highly nonlinear.
return 0.0519565234928877 + 5.09316778537561*v - 99.0338180489702*v2 + 3484.52322764895*v3 - 150028.083412663*v4 + 7168008.42971613*v5
}
}
// FastLinearRgb is much faster than and almost as accurate as LinearRgb.
// BUT it is important to NOTE that they only produce good results for valid inputs r,g,b in [0,1].
func FastLinearRgb(r, g, b float64) Color {
return Color{delinearize_fast(r), delinearize_fast(g), delinearize_fast(b)}
}
// XyzToLinearRgb converts from CIE XYZ-space to Linear RGB space.
func XyzToLinearRgb(x, y, z float64) (r, g, b float64) {
r = 3.2409699419045214*x - 1.5373831775700935*y - 0.49861076029300328*z
g = -0.96924363628087983*x + 1.8759675015077207*y + 0.041555057407175613*z
b = 0.055630079696993609*x - 0.20397695888897657*y + 1.0569715142428786*z
return
}
func LinearRgbToXyz(r, g, b float64) (x, y, z float64) {
x = 0.41239079926595948*r + 0.35758433938387796*g + 0.18048078840183429*b
y = 0.21263900587151036*r + 0.71516867876775593*g + 0.072192315360733715*b
z = 0.019330818715591851*r + 0.11919477979462599*g + 0.95053215224966058*b
return
}
/// XYZ ///
///////////
// http://www.sjbrown.co.uk/2004/05/14/gamma-correct-rendering/
func (col Color) Xyz() (x, y, z float64) {
return LinearRgbToXyz(col.LinearRgb())
}
func Xyz(x, y, z float64) Color {
return LinearRgb(XyzToLinearRgb(x, y, z))
}
/// xyY ///
///////////
// http://www.brucelindbloom.com/Eqn_XYZ_to_xyY.html
// Well, the name is bad, since it's xyY but Golang needs me to start with a
// capital letter to make the method public.
func XyzToXyy(X, Y, Z float64) (x, y, Yout float64) {
return XyzToXyyWhiteRef(X, Y, Z, D65)
}
func XyzToXyyWhiteRef(X, Y, Z float64, wref [3]float64) (x, y, Yout float64) {
Yout = Y
N := X + Y + Z
if math.Abs(N) < 1e-14 {
// When we have black, Bruce Lindbloom recommends to use
// the reference white's chromacity for x and y.
x = wref[0] / (wref[0] + wref[1] + wref[2])
y = wref[1] / (wref[0] + wref[1] + wref[2])
} else {
x = X / N
y = Y / N
}
return
}
func XyyToXyz(x, y, Y float64) (X, Yout, Z float64) {
Yout = Y
if -1e-14 < y && y < 1e-14 {
X = 0.0
Z = 0.0
} else {
X = Y / y * x
Z = Y / y * (1.0 - x - y)
}
return
}
// Converts the given color to CIE xyY space using D65 as reference white.
// (Note that the reference white is only used for black input.)
// x, y and Y are in [0..1]
func (col Color) Xyy() (x, y, Y float64) {
return XyzToXyy(col.Xyz())
}
// Converts the given color to CIE xyY space, taking into account
// a given reference white. (i.e. the monitor's white)
// (Note that the reference white is only used for black input.)
// x, y and Y are in [0..1]
func (col Color) XyyWhiteRef(wref [3]float64) (x, y, Y float64) {
X, Y2, Z := col.Xyz()
return XyzToXyyWhiteRef(X, Y2, Z, wref)
}
// Generates a color by using data given in CIE xyY space.
// x, y and Y are in [0..1]
func Xyy(x, y, Y float64) Color {
return Xyz(XyyToXyz(x, y, Y))
}
/// L*a*b* ///
//////////////
// http://en.wikipedia.org/wiki/Lab_color_space#CIELAB-CIEXYZ_conversions
// For L*a*b*, we need to L*a*b*<->XYZ->RGB and the first one is device dependent.
func lab_f(t float64) float64 {
if t > 6.0/29.0*6.0/29.0*6.0/29.0 {
return math.Cbrt(t)
}
return t/3.0*29.0/6.0*29.0/6.0 + 4.0/29.0
}
func XyzToLab(x, y, z float64) (l, a, b float64) {
// Use D65 white as reference point by default.
// http://www.fredmiranda.com/forum/topic/1035332
// http://en.wikipedia.org/wiki/Standard_illuminant
return XyzToLabWhiteRef(x, y, z, D65)
}
func XyzToLabWhiteRef(x, y, z float64, wref [3]float64) (l, a, b float64) {
fy := lab_f(y / wref[1])
l = 1.16*fy - 0.16
a = 5.0 * (lab_f(x/wref[0]) - fy)
b = 2.0 * (fy - lab_f(z/wref[2]))
return
}
func lab_finv(t float64) float64 {
if t > 6.0/29.0 {
return t * t * t
}
return 3.0 * 6.0 / 29.0 * 6.0 / 29.0 * (t - 4.0/29.0)
}
func LabToXyz(l, a, b float64) (x, y, z float64) {
// D65 white (see above).
return LabToXyzWhiteRef(l, a, b, D65)
}
func LabToXyzWhiteRef(l, a, b float64, wref [3]float64) (x, y, z float64) {
l2 := (l + 0.16) / 1.16
x = wref[0] * lab_finv(l2+a/5.0)
y = wref[1] * lab_finv(l2)
z = wref[2] * lab_finv(l2-b/2.0)
return
}
// Converts the given color to CIE L*a*b* space using D65 as reference white.
func (col Color) Lab() (l, a, b float64) {
return XyzToLab(col.Xyz())
}
// Converts the given color to CIE L*a*b* space, taking into account
// a given reference white. (i.e. the monitor's white)
func (col Color) LabWhiteRef(wref [3]float64) (l, a, b float64) {
x, y, z := col.Xyz()
return XyzToLabWhiteRef(x, y, z, wref)
}
// Generates a color by using data given in CIE L*a*b* space using D65 as reference white.
// WARNING: many combinations of `l`, `a`, and `b` values do not have corresponding
// valid RGB values, check the FAQ in the README if you're unsure.
func Lab(l, a, b float64) Color {
return Xyz(LabToXyz(l, a, b))
}
// Generates a color by using data given in CIE L*a*b* space, taking
// into account a given reference white. (i.e. the monitor's white)
func LabWhiteRef(l, a, b float64, wref [3]float64) Color {
return Xyz(LabToXyzWhiteRef(l, a, b, wref))
}
// DistanceLab is a good measure of visual similarity between two colors!
// A result of 0 would mean identical colors, while a result of 1 or higher
// means the colors differ a lot.
func (c1 Color) DistanceLab(c2 Color) float64 {
l1, a1, b1 := c1.Lab()
l2, a2, b2 := c2.Lab()
return math.Sqrt(sq(l1-l2) + sq(a1-a2) + sq(b1-b2))
}
// DistanceCIE76 is the same as DistanceLab.
func (c1 Color) DistanceCIE76(c2 Color) float64 {
return c1.DistanceLab(c2)
}
// Uses the CIE94 formula to calculate color distance. More accurate than
// DistanceLab, but also more work.
func (cl Color) DistanceCIE94(cr Color) float64 {
l1, a1, b1 := cl.Lab()
l2, a2, b2 := cr.Lab()
// NOTE: Since all those formulas expect L,a,b values 100x larger than we
// have them in this library, we either need to adjust all constants
// in the formula, or convert the ranges of L,a,b before, and then
// scale the distances down again. The latter is less error-prone.
l1, a1, b1 = l1*100.0, a1*100.0, b1*100.0
l2, a2, b2 = l2*100.0, a2*100.0, b2*100.0
kl := 1.0 // 2.0 for textiles
kc := 1.0
kh := 1.0
k1 := 0.045 // 0.048 for textiles
k2 := 0.015 // 0.014 for textiles.
deltaL := l1 - l2
c1 := math.Sqrt(sq(a1) + sq(b1))
c2 := math.Sqrt(sq(a2) + sq(b2))
deltaCab := c1 - c2
// Not taking Sqrt here for stability, and it's unnecessary.
deltaHab2 := sq(a1-a2) + sq(b1-b2) - sq(deltaCab)
sl := 1.0
sc := 1.0 + k1*c1
sh := 1.0 + k2*c1
vL2 := sq(deltaL / (kl * sl))
vC2 := sq(deltaCab / (kc * sc))
vH2 := deltaHab2 / sq(kh*sh)
return math.Sqrt(vL2+vC2+vH2) * 0.01 // See above.
}
// DistanceCIEDE2000 uses the Delta E 2000 formula to calculate color
// distance. It is more expensive but more accurate than both DistanceLab
// and DistanceCIE94.
func (cl Color) DistanceCIEDE2000(cr Color) float64 {
return cl.DistanceCIEDE2000klch(cr, 1.0, 1.0, 1.0)
}
// DistanceCIEDE2000klch uses the Delta E 2000 formula with custom values
// for the weighting factors kL, kC, and kH.
func (cl Color) DistanceCIEDE2000klch(cr Color, kl, kc, kh float64) float64 {
l1, a1, b1 := cl.Lab()
l2, a2, b2 := cr.Lab()
// As with CIE94, we scale up the ranges of L,a,b beforehand and scale
// them down again afterwards.
l1, a1, b1 = l1*100.0, a1*100.0, b1*100.0
l2, a2, b2 = l2*100.0, a2*100.0, b2*100.0
cab1 := math.Sqrt(sq(a1) + sq(b1))
cab2 := math.Sqrt(sq(a2) + sq(b2))
cabmean := (cab1 + cab2) / 2
g := 0.5 * (1 - math.Sqrt(math.Pow(cabmean, 7)/(math.Pow(cabmean, 7)+math.Pow(25, 7))))
ap1 := (1 + g) * a1
ap2 := (1 + g) * a2
cp1 := math.Sqrt(sq(ap1) + sq(b1))
cp2 := math.Sqrt(sq(ap2) + sq(b2))
hp1 := 0.0
if b1 != ap1 || ap1 != 0 {
hp1 = math.Atan2(b1, ap1)
if hp1 < 0 {
hp1 += math.Pi * 2
}
hp1 *= 180 / math.Pi
}
hp2 := 0.0
if b2 != ap2 || ap2 != 0 {
hp2 = math.Atan2(b2, ap2)
if hp2 < 0 {
hp2 += math.Pi * 2
}
hp2 *= 180 / math.Pi
}
deltaLp := l2 - l1
deltaCp := cp2 - cp1
dhp := 0.0
cpProduct := cp1 * cp2
if cpProduct != 0 {
dhp = hp2 - hp1
if dhp > 180 {
dhp -= 360
} else if dhp < -180 {
dhp += 360
}
}
deltaHp := 2 * math.Sqrt(cpProduct) * math.Sin(dhp/2*math.Pi/180)
lpmean := (l1 + l2) / 2
cpmean := (cp1 + cp2) / 2
hpmean := hp1 + hp2
if cpProduct != 0 {
hpmean /= 2
if math.Abs(hp1-hp2) > 180 {
if hp1+hp2 < 360 {
hpmean += 180
} else {
hpmean -= 180
}
}
}
t := 1 - 0.17*math.Cos((hpmean-30)*math.Pi/180) + 0.24*math.Cos(2*hpmean*math.Pi/180) + 0.32*math.Cos((3*hpmean+6)*math.Pi/180) - 0.2*math.Cos((4*hpmean-63)*math.Pi/180)
deltaTheta := 30 * math.Exp(-sq((hpmean-275)/25))
rc := 2 * math.Sqrt(math.Pow(cpmean, 7)/(math.Pow(cpmean, 7)+math.Pow(25, 7)))
sl := 1 + (0.015*sq(lpmean-50))/math.Sqrt(20+sq(lpmean-50))
sc := 1 + 0.045*cpmean
sh := 1 + 0.015*cpmean*t
rt := -math.Sin(2*deltaTheta*math.Pi/180) * rc
return math.Sqrt(sq(deltaLp/(kl*sl))+sq(deltaCp/(kc*sc))+sq(deltaHp/(kh*sh))+rt*(deltaCp/(kc*sc))*(deltaHp/(kh*sh))) * 0.01
}
// BlendLab blends two colors in the L*a*b* color-space, which should result in a smoother blend.
// t == 0 results in c1, t == 1 results in c2
func (c1 Color) BlendLab(c2 Color, t float64) Color {
l1, a1, b1 := c1.Lab()
l2, a2, b2 := c2.Lab()
return Lab(l1+t*(l2-l1),
a1+t*(a2-a1),
b1+t*(b2-b1))
}
/// L*u*v* ///
//////////////
// http://en.wikipedia.org/wiki/CIELUV#XYZ_.E2.86.92_CIELUV_and_CIELUV_.E2.86.92_XYZ_conversions
// For L*u*v*, we need to L*u*v*<->XYZ<->RGB and the first one is device dependent.
func XyzToLuv(x, y, z float64) (l, a, b float64) {
// Use D65 white as reference point by default.
// http://www.fredmiranda.com/forum/topic/1035332
// http://en.wikipedia.org/wiki/Standard_illuminant
return XyzToLuvWhiteRef(x, y, z, D65)
}
func XyzToLuvWhiteRef(x, y, z float64, wref [3]float64) (l, u, v float64) {
if y/wref[1] <= 6.0/29.0*6.0/29.0*6.0/29.0 {
l = y / wref[1] * (29.0 / 3.0 * 29.0 / 3.0 * 29.0 / 3.0) / 100.0
} else {
l = 1.16*math.Cbrt(y/wref[1]) - 0.16
}
ubis, vbis := xyz_to_uv(x, y, z)
un, vn := xyz_to_uv(wref[0], wref[1], wref[2])
u = 13.0 * l * (ubis - un)
v = 13.0 * l * (vbis - vn)
return
}
// For this part, we do as R's graphics.hcl does, not as wikipedia does.
// Or is it the same?
func xyz_to_uv(x, y, z float64) (u, v float64) {
denom := x + 15.0*y + 3.0*z
if denom == 0.0 {
u, v = 0.0, 0.0
} else {
u = 4.0 * x / denom
v = 9.0 * y / denom
}
return
}
func LuvToXyz(l, u, v float64) (x, y, z float64) {
// D65 white (see above).
return LuvToXyzWhiteRef(l, u, v, D65)
}
func LuvToXyzWhiteRef(l, u, v float64, wref [3]float64) (x, y, z float64) {
//y = wref[1] * lab_finv((l + 0.16) / 1.16)
if l <= 0.08 {
y = wref[1] * l * 100.0 * 3.0 / 29.0 * 3.0 / 29.0 * 3.0 / 29.0
} else {
y = wref[1] * cub((l+0.16)/1.16)
}
un, vn := xyz_to_uv(wref[0], wref[1], wref[2])
if l != 0.0 {
ubis := u/(13.0*l) + un
vbis := v/(13.0*l) + vn
x = y * 9.0 * ubis / (4.0 * vbis)
z = y * (12.0 - 3.0*ubis - 20.0*vbis) / (4.0 * vbis)
} else {
x, y = 0.0, 0.0
}
return
}
// Converts the given color to CIE L*u*v* space using D65 as reference white.
// L* is in [0..1] and both u* and v* are in about [-1..1]
func (col Color) Luv() (l, u, v float64) {
return XyzToLuv(col.Xyz())
}
// Converts the given color to CIE L*u*v* space, taking into account
// a given reference white. (i.e. the monitor's white)
// L* is in [0..1] and both u* and v* are in about [-1..1]
func (col Color) LuvWhiteRef(wref [3]float64) (l, u, v float64) {
x, y, z := col.Xyz()
return XyzToLuvWhiteRef(x, y, z, wref)
}
// Generates a color by using data given in CIE L*u*v* space using D65 as reference white.
// L* is in [0..1] and both u* and v* are in about [-1..1]
// WARNING: many combinations of `l`, `u`, and `v` values do not have corresponding
// valid RGB values, check the FAQ in the README if you're unsure.
func Luv(l, u, v float64) Color {
return Xyz(LuvToXyz(l, u, v))
}
// Generates a color by using data given in CIE L*u*v* space, taking
// into account a given reference white. (i.e. the monitor's white)
// L* is in [0..1] and both u* and v* are in about [-1..1]
func LuvWhiteRef(l, u, v float64, wref [3]float64) Color {
return Xyz(LuvToXyzWhiteRef(l, u, v, wref))
}
// DistanceLuv is a good measure of visual similarity between two colors!
// A result of 0 would mean identical colors, while a result of 1 or higher
// means the colors differ a lot.
func (c1 Color) DistanceLuv(c2 Color) float64 {
l1, u1, v1 := c1.Luv()
l2, u2, v2 := c2.Luv()
return math.Sqrt(sq(l1-l2) + sq(u1-u2) + sq(v1-v2))
}
// BlendLuv blends two colors in the CIE-L*u*v* color-space, which should result in a smoother blend.
// t == 0 results in c1, t == 1 results in c2
func (c1 Color) BlendLuv(c2 Color, t float64) Color {
l1, u1, v1 := c1.Luv()
l2, u2, v2 := c2.Luv()
return Luv(l1+t*(l2-l1),
u1+t*(u2-u1),
v1+t*(v2-v1))
}
/// HCL ///
///////////
// HCL is nothing else than L*a*b* in cylindrical coordinates!
// (this was wrong on English wikipedia, I fixed it, let's hope the fix stays.)
// But it is widely popular since it is a "correct HSV"
// http://www.hunterlab.com/appnotes/an09_96a.pdf
// Converts the given color to HCL space using D65 as reference white.
// H values are in [0..360], C and L values are in [0..1] although C can overshoot 1.0
func (col Color) Hcl() (h, c, l float64) {
return col.HclWhiteRef(D65)
}
func LabToHcl(L, a, b float64) (h, c, l float64) {
// Oops, floating point workaround necessary if a ~= b and both are very small (i.e. almost zero).
if math.Abs(b-a) > 1e-4 && math.Abs(a) > 1e-4 {
h = math.Mod(57.29577951308232087721*math.Atan2(b, a)+360.0, 360.0) // Rad2Deg
} else {
h = 0.0
}
c = math.Sqrt(sq(a) + sq(b))
l = L
return
}
// Converts the given color to HCL space, taking into account
// a given reference white. (i.e. the monitor's white)
// H values are in [0..360], C and L values are in [0..1]
func (col Color) HclWhiteRef(wref [3]float64) (h, c, l float64) {
L, a, b := col.LabWhiteRef(wref)
return LabToHcl(L, a, b)
}
// Generates a color by using data given in HCL space using D65 as reference white.
// H values are in [0..360], C and L values are in [0..1]
// WARNING: many combinations of `h`, `c`, and `l` values do not have corresponding
// valid RGB values, check the FAQ in the README if you're unsure.
func Hcl(h, c, l float64) Color {
return HclWhiteRef(h, c, l, D65)
}
func HclToLab(h, c, l float64) (L, a, b float64) {
H := 0.01745329251994329576 * h // Deg2Rad
a = c * math.Cos(H)
b = c * math.Sin(H)
L = l
return
}
// Generates a color by using data given in HCL space, taking
// into account a given reference white. (i.e. the monitor's white)
// H values are in [0..360], C and L values are in [0..1]
func HclWhiteRef(h, c, l float64, wref [3]float64) Color {
L, a, b := HclToLab(h, c, l)
return LabWhiteRef(L, a, b, wref)
}
// BlendHcl blends two colors in the CIE-L*C*h° color-space, which should result in a smoother blend.
// t == 0 results in c1, t == 1 results in c2
func (col1 Color) BlendHcl(col2 Color, t float64) Color {
h1, c1, l1 := col1.Hcl()
h2, c2, l2 := col2.Hcl()
// We know that h are both in [0..360]
return Hcl(interp_angle(h1, h2, t), c1+t*(c2-c1), l1+t*(l2-l1)).Clamped()
}
// LuvLch
// Converts the given color to LuvLCh space using D65 as reference white.
// h values are in [0..360], C and L values are in [0..1] although C can overshoot 1.0
func (col Color) LuvLCh() (l, c, h float64) {
return col.LuvLChWhiteRef(D65)
}
func LuvToLuvLCh(L, u, v float64) (l, c, h float64) {
// Oops, floating point workaround necessary if u ~= v and both are very small (i.e. almost zero).
if math.Abs(v-u) > 1e-4 && math.Abs(u) > 1e-4 {
h = math.Mod(57.29577951308232087721*math.Atan2(v, u)+360.0, 360.0) // Rad2Deg
} else {
h = 0.0
}
l = L
c = math.Sqrt(sq(u) + sq(v))
return
}
// Converts the given color to LuvLCh space, taking into account
// a given reference white. (i.e. the monitor's white)
// h values are in [0..360], c and l values are in [0..1]
func (col Color) LuvLChWhiteRef(wref [3]float64) (l, c, h float64) {
return LuvToLuvLCh(col.LuvWhiteRef(wref))
}
// Generates a color by using data given in LuvLCh space using D65 as reference white.
// h values are in [0..360], C and L values are in [0..1]
// WARNING: many combinations of `l`, `c`, and `h` values do not have corresponding
// valid RGB values, check the FAQ in the README if you're unsure.
func LuvLCh(l, c, h float64) Color {
return LuvLChWhiteRef(l, c, h, D65)
}
func LuvLChToLuv(l, c, h float64) (L, u, v float64) {
H := 0.01745329251994329576 * h // Deg2Rad
u = c * math.Cos(H)
v = c * math.Sin(H)
L = l
return
}
// Generates a color by using data given in LuvLCh space, taking
// into account a given reference white. (i.e. the monitor's white)
// h values are in [0..360], C and L values are in [0..1]
func LuvLChWhiteRef(l, c, h float64, wref [3]float64) Color {
L, u, v := LuvLChToLuv(l, c, h)
return LuvWhiteRef(L, u, v, wref)
}
// BlendLuvLCh blends two colors in the cylindrical CIELUV color space.
// t == 0 results in c1, t == 1 results in c2
func (col1 Color) BlendLuvLCh(col2 Color, t float64) Color {
l1, c1, h1 := col1.LuvLCh()
l2, c2, h2 := col2.LuvLCh()
// We know that h are both in [0..360]
return LuvLCh(l1+t*(l2-l1), c1+t*(c2-c1), interp_angle(h1, h2, t))
}

View File

@@ -0,0 +1,25 @@
package colorful
import (
"math/rand"
)
// Uses the HSV color space to generate colors with similar S,V but distributed
// evenly along their Hue. This is fast but not always pretty.
// If you've got time to spare, use Lab (the non-fast below).
func FastHappyPalette(colorsCount int) (colors []Color) {
colors = make([]Color, colorsCount)
for i := 0; i < colorsCount; i++ {
colors[i] = Hsv(float64(i)*(360.0/float64(colorsCount)), 0.8+rand.Float64()*0.2, 0.65+rand.Float64()*0.2)
}
return
}
func HappyPalette(colorsCount int) ([]Color, error) {
pimpy := func(l, a, b float64) bool {
_, c, _ := LabToHcl(l, a, b)
return 0.3 <= c && 0.4 <= l && l <= 0.8
}
return SoftPaletteEx(colorsCount, SoftPaletteSettings{pimpy, 50, true})
}

67
vendor/github.com/lucasb-eyer/go-colorful/hexcolor.go generated vendored Normal file
View File

@@ -0,0 +1,67 @@
package colorful
import (
"database/sql/driver"
"encoding/json"
"fmt"
"reflect"
)
// A HexColor is a Color stored as a hex string "#rrggbb". It implements the
// database/sql.Scanner, database/sql/driver.Value,
// encoding/json.Unmarshaler and encoding/json.Marshaler interfaces.
type HexColor Color
type errUnsupportedType struct {
got interface{}
want reflect.Type
}
func (hc *HexColor) Scan(value interface{}) error {
s, ok := value.(string)
if !ok {
return errUnsupportedType{got: reflect.TypeOf(value), want: reflect.TypeOf("")}
}
c, err := Hex(s)
if err != nil {
return err
}
*hc = HexColor(c)
return nil
}
func (hc *HexColor) Value() (driver.Value, error) {
return Color(*hc).Hex(), nil
}
func (e errUnsupportedType) Error() string {
return fmt.Sprintf("unsupported type: got %v, want a %s", e.got, e.want)
}
func (hc *HexColor) UnmarshalJSON(data []byte) error {
var hexCode string
if err := json.Unmarshal(data, &hexCode); err != nil {
return err
}
var col, err = Hex(hexCode)
if err != nil {
return err
}
*hc = HexColor(col)
return nil
}
func (hc HexColor) MarshalJSON() ([]byte, error) {
return json.Marshal(Color(hc).Hex())
}
// Decode - deserialize function for https://github.com/kelseyhightower/envconfig
func (hc *HexColor) Decode(hexCode string) error {
var col, err = Hex(hexCode)
if err != nil {
return err
}
*hc = HexColor(col)
return nil
}

File diff suppressed because one or more lines are too long

207
vendor/github.com/lucasb-eyer/go-colorful/hsluv.go generated vendored Normal file
View File

@@ -0,0 +1,207 @@
package colorful
import "math"
// Source: https://github.com/hsluv/hsluv-go
// Under MIT License
// Modified so that Saturation and Luminance are in [0..1] instead of [0..100].
// HSLuv uses a rounded version of the D65. This has no impact on the final RGB
// values, but to keep high levels of accuracy for internal operations and when
// comparing to the test values, this modified white reference is used internally.
//
// See this GitHub thread for details on these values:
// https://github.com/hsluv/hsluv/issues/79
var hSLuvD65 = [3]float64{0.95045592705167, 1.0, 1.089057750759878}
func LuvLChToHSLuv(l, c, h float64) (float64, float64, float64) {
// [-1..1] but the code expects it to be [-100..100]
c *= 100.0
l *= 100.0
var s, max float64
if l > 99.9999999 || l < 0.00000001 {
s = 0.0
} else {
max = maxChromaForLH(l, h)
s = c / max * 100.0
}
return h, clamp01(s / 100.0), clamp01(l / 100.0)
}
func HSLuvToLuvLCh(h, s, l float64) (float64, float64, float64) {
l *= 100.0
s *= 100.0
var c, max float64
if l > 99.9999999 || l < 0.00000001 {
c = 0.0
} else {
max = maxChromaForLH(l, h)
c = max / 100.0 * s
}
// c is [-100..100], but for LCh it's supposed to be almost [-1..1]
return clamp01(l / 100.0), c / 100.0, h
}
func LuvLChToHPLuv(l, c, h float64) (float64, float64, float64) {
// [-1..1] but the code expects it to be [-100..100]
c *= 100.0
l *= 100.0
var s, max float64
if l > 99.9999999 || l < 0.00000001 {
s = 0.0
} else {
max = maxSafeChromaForL(l)
s = c / max * 100.0
}
return h, s / 100.0, l / 100.0
}
func HPLuvToLuvLCh(h, s, l float64) (float64, float64, float64) {
// [-1..1] but the code expects it to be [-100..100]
l *= 100.0
s *= 100.0
var c, max float64
if l > 99.9999999 || l < 0.00000001 {
c = 0.0
} else {
max = maxSafeChromaForL(l)
c = max / 100.0 * s
}
return l / 100.0, c / 100.0, h
}
// HSLuv creates a new Color from values in the HSLuv color space.
// Hue in [0..360], a Saturation [0..1], and a Luminance (lightness) in [0..1].
//
// The returned color values are clamped (using .Clamped), so this will never output
// an invalid color.
func HSLuv(h, s, l float64) Color {
// HSLuv -> LuvLCh -> CIELUV -> CIEXYZ -> Linear RGB -> sRGB
l, u, v := LuvLChToLuv(HSLuvToLuvLCh(h, s, l))
return LinearRgb(XyzToLinearRgb(LuvToXyzWhiteRef(l, u, v, hSLuvD65))).Clamped()
}
// HPLuv creates a new Color from values in the HPLuv color space.
// Hue in [0..360], a Saturation [0..1], and a Luminance (lightness) in [0..1].
//
// The returned color values are clamped (using .Clamped), so this will never output
// an invalid color.
func HPLuv(h, s, l float64) Color {
// HPLuv -> LuvLCh -> CIELUV -> CIEXYZ -> Linear RGB -> sRGB
l, u, v := LuvLChToLuv(HPLuvToLuvLCh(h, s, l))
return LinearRgb(XyzToLinearRgb(LuvToXyzWhiteRef(l, u, v, hSLuvD65))).Clamped()
}
// HSLuv returns the Hue, Saturation and Luminance of the color in the HSLuv
// color space. Hue in [0..360], a Saturation [0..1], and a Luminance
// (lightness) in [0..1].
func (col Color) HSLuv() (h, s, l float64) {
// sRGB -> Linear RGB -> CIEXYZ -> CIELUV -> LuvLCh -> HSLuv
return LuvLChToHSLuv(col.LuvLChWhiteRef(hSLuvD65))
}
// HPLuv returns the Hue, Saturation and Luminance of the color in the HSLuv
// color space. Hue in [0..360], a Saturation [0..1], and a Luminance
// (lightness) in [0..1].
//
// Note that HPLuv can only represent pastel colors, and so the Saturation
// value could be much larger than 1 for colors it can't represent.
func (col Color) HPLuv() (h, s, l float64) {
return LuvLChToHPLuv(col.LuvLChWhiteRef(hSLuvD65))
}
// DistanceHSLuv calculates Euclidan distance in the HSLuv colorspace. No idea
// how useful this is.
//
// The Hue value is divided by 100 before the calculation, so that H, S, and L
// have the same relative ranges.
func (c1 Color) DistanceHSLuv(c2 Color) float64 {
h1, s1, l1 := c1.HSLuv()
h2, s2, l2 := c2.HSLuv()
return math.Sqrt(sq((h1-h2)/100.0) + sq(s1-s2) + sq(l1-l2))
}
// DistanceHPLuv calculates Euclidean distance in the HPLuv colorspace. No idea
// how useful this is.
//
// The Hue value is divided by 100 before the calculation, so that H, S, and L
// have the same relative ranges.
func (c1 Color) DistanceHPLuv(c2 Color) float64 {
h1, s1, l1 := c1.HPLuv()
h2, s2, l2 := c2.HPLuv()
return math.Sqrt(sq((h1-h2)/100.0) + sq(s1-s2) + sq(l1-l2))
}
var m = [3][3]float64{
{3.2409699419045214, -1.5373831775700935, -0.49861076029300328},
{-0.96924363628087983, 1.8759675015077207, 0.041555057407175613},
{0.055630079696993609, -0.20397695888897657, 1.0569715142428786},
}
const kappa = 903.2962962962963
const epsilon = 0.0088564516790356308
func maxChromaForLH(l, h float64) float64 {
hRad := h / 360.0 * math.Pi * 2.0
minLength := math.MaxFloat64
for _, line := range getBounds(l) {
length := lengthOfRayUntilIntersect(hRad, line[0], line[1])
if length > 0.0 && length < minLength {
minLength = length
}
}
return minLength
}
func getBounds(l float64) [6][2]float64 {
var sub2 float64
var ret [6][2]float64
sub1 := math.Pow(l+16.0, 3.0) / 1560896.0
if sub1 > epsilon {
sub2 = sub1
} else {
sub2 = l / kappa
}
for i := range m {
for k := 0; k < 2; k++ {
top1 := (284517.0*m[i][0] - 94839.0*m[i][2]) * sub2
top2 := (838422.0*m[i][2]+769860.0*m[i][1]+731718.0*m[i][0])*l*sub2 - 769860.0*float64(k)*l
bottom := (632260.0*m[i][2]-126452.0*m[i][1])*sub2 + 126452.0*float64(k)
ret[i*2+k][0] = top1 / bottom
ret[i*2+k][1] = top2 / bottom
}
}
return ret
}
func lengthOfRayUntilIntersect(theta, x, y float64) (length float64) {
length = y / (math.Sin(theta) - x*math.Cos(theta))
return
}
func maxSafeChromaForL(l float64) float64 {
minLength := math.MaxFloat64
for _, line := range getBounds(l) {
m1 := line[0]
b1 := line[1]
x := intersectLineLine(m1, b1, -1.0/m1, 0.0)
dist := distanceFromPole(x, b1+x*m1)
if dist < minLength {
minLength = dist
}
}
return minLength
}
func intersectLineLine(x1, y1, x2, y2 float64) float64 {
return (y1 - y2) / (x2 - x1)
}
func distanceFromPole(x, y float64) float64 {
return math.Sqrt(math.Pow(x, 2.0) + math.Pow(y, 2.0))
}

View File

@@ -0,0 +1,185 @@
// Largely inspired by the descriptions in http://lab.medialab.sciences-po.fr/iwanthue/
// but written from scratch.
package colorful
import (
"fmt"
"math"
"math/rand"
)
// The algorithm works in L*a*b* color space and converts to RGB in the end.
// L* in [0..1], a* and b* in [-1..1]
type lab_t struct {
L, A, B float64
}
type SoftPaletteSettings struct {
// A function which can be used to restrict the allowed color-space.
CheckColor func(l, a, b float64) bool
// The higher, the better quality but the slower. Usually two figures.
Iterations int
// Use up to 160000 or 8000 samples of the L*a*b* space (and thus calls to CheckColor).
// Set this to true only if your CheckColor shapes the Lab space weirdly.
ManySamples bool
}
// Yeah, windows-stype Foo, FooEx, screw you golang...
// Uses K-means to cluster the color-space and return the means of the clusters
// as a new palette of distinctive colors. Falls back to K-medoid if the mean
// happens to fall outside of the color-space, which can only happen if you
// specify a CheckColor function.
func SoftPaletteEx(colorsCount int, settings SoftPaletteSettings) ([]Color, error) {
// Checks whether it's a valid RGB and also fulfills the potentially provided constraint.
check := func(col lab_t) bool {
c := Lab(col.L, col.A, col.B)
return c.IsValid() && (settings.CheckColor == nil || settings.CheckColor(col.L, col.A, col.B))
}
// Sample the color space. These will be the points k-means is run on.
dl := 0.05
dab := 0.1
if settings.ManySamples {
dl = 0.01
dab = 0.05
}
samples := make([]lab_t, 0, int(1.0/dl*2.0/dab*2.0/dab))
for l := 0.0; l <= 1.0; l += dl {
for a := -1.0; a <= 1.0; a += dab {
for b := -1.0; b <= 1.0; b += dab {
if check(lab_t{l, a, b}) {
samples = append(samples, lab_t{l, a, b})
}
}
}
}
// That would cause some infinite loops down there...
if len(samples) < colorsCount {
return nil, fmt.Errorf("palettegen: more colors requested (%v) than samples available (%v). Your requested color count may be wrong, you might want to use many samples or your constraint function makes the valid color space too small", colorsCount, len(samples))
} else if len(samples) == colorsCount {
return labs2cols(samples), nil // Oops?
}
// We take the initial means out of the samples, so they are in fact medoids.
// This helps us avoid infinite loops or arbitrary cutoffs with too restrictive constraints.
means := make([]lab_t, colorsCount)
for i := 0; i < colorsCount; i++ {
for means[i] = samples[rand.Intn(len(samples))]; in(means, i, means[i]); means[i] = samples[rand.Intn(len(samples))] {
}
}
clusters := make([]int, len(samples))
samples_used := make([]bool, len(samples))
// The actual k-means/medoid iterations
for i := 0; i < settings.Iterations; i++ {
// Reassing the samples to clusters, i.e. to their closest mean.
// By the way, also check if any sample is used as a medoid and if so, mark that.
for isample, sample := range samples {
samples_used[isample] = false
mindist := math.Inf(+1)
for imean, mean := range means {
dist := lab_dist(sample, mean)
if dist < mindist {
mindist = dist
clusters[isample] = imean
}
// Mark samples which are used as a medoid.
if lab_eq(sample, mean) {
samples_used[isample] = true
}
}
}
// Compute new means according to the samples.
for imean := range means {
// The new mean is the average of all samples belonging to it..
nsamples := 0
newmean := lab_t{0.0, 0.0, 0.0}
for isample, sample := range samples {
if clusters[isample] == imean {
nsamples++
newmean.L += sample.L
newmean.A += sample.A
newmean.B += sample.B
}
}
if nsamples > 0 {
newmean.L /= float64(nsamples)
newmean.A /= float64(nsamples)
newmean.B /= float64(nsamples)
} else {
// That mean doesn't have any samples? Get a new mean from the sample list!
var inewmean int
for inewmean = rand.Intn(len(samples_used)); samples_used[inewmean]; inewmean = rand.Intn(len(samples_used)) {
}
newmean = samples[inewmean]
samples_used[inewmean] = true
}
// But now we still need to check whether the new mean is an allowed color.
if nsamples > 0 && check(newmean) {
// It does, life's good (TM)
means[imean] = newmean
} else {
// New mean isn't an allowed color or doesn't have any samples!
// Switch to medoid mode and pick the closest (unused) sample.
// This should always find something thanks to len(samples) >= colorsCount
mindist := math.Inf(+1)
for isample, sample := range samples {
if !samples_used[isample] {
dist := lab_dist(sample, newmean)
if dist < mindist {
mindist = dist
newmean = sample
}
}
}
}
}
}
return labs2cols(means), nil
}
// A wrapper which uses common parameters.
func SoftPalette(colorsCount int) ([]Color, error) {
return SoftPaletteEx(colorsCount, SoftPaletteSettings{nil, 50, false})
}
func in(haystack []lab_t, upto int, needle lab_t) bool {
for i := 0; i < upto && i < len(haystack); i++ {
if haystack[i] == needle {
return true
}
}
return false
}
const LAB_DELTA = 1e-6
func lab_eq(lab1, lab2 lab_t) bool {
return math.Abs(lab1.L-lab2.L) < LAB_DELTA &&
math.Abs(lab1.A-lab2.A) < LAB_DELTA &&
math.Abs(lab1.B-lab2.B) < LAB_DELTA
}
// That's faster than using colorful's DistanceLab since we would have to
// convert back and forth for that. Here is no conversion.
func lab_dist(lab1, lab2 lab_t) float64 {
return math.Sqrt(sq(lab1.L-lab2.L) + sq(lab1.A-lab2.A) + sq(lab1.B-lab2.B))
}
func labs2cols(labs []lab_t) (cols []Color) {
cols = make([]Color, len(labs))
for k, v := range labs {
cols[k] = Lab(v.L, v.A, v.B)
}
return cols
}

View File

@@ -0,0 +1,25 @@
package colorful
import (
"math/rand"
)
// Uses the HSV color space to generate colors with similar S,V but distributed
// evenly along their Hue. This is fast but not always pretty.
// If you've got time to spare, use Lab (the non-fast below).
func FastWarmPalette(colorsCount int) (colors []Color) {
colors = make([]Color, colorsCount)
for i := 0; i < colorsCount; i++ {
colors[i] = Hsv(float64(i)*(360.0/float64(colorsCount)), 0.55+rand.Float64()*0.2, 0.35+rand.Float64()*0.2)
}
return
}
func WarmPalette(colorsCount int) ([]Color, error) {
warmy := func(l, a, b float64) bool {
_, c, _ := LabToHcl(l, a, b)
return 0.1 <= c && c <= 0.4 && 0.2 <= l && l <= 0.5
}
return SoftPaletteEx(colorsCount, SoftPaletteSettings{warmy, 50, true})
}

5
vendor/github.com/vearutop/statigz/.gitignore generated vendored Normal file
View File

@@ -0,0 +1,5 @@
/.idea
/*.coverprofile
/.vscode
/bench-*.txt
/vendor

52
vendor/github.com/vearutop/statigz/.golangci.yml generated vendored Normal file
View File

@@ -0,0 +1,52 @@
# See https://github.com/golangci/golangci-lint/blob/master/.golangci.example.yml
run:
tests: true
linters-settings:
errcheck:
check-type-assertions: true
check-blank: true
gocyclo:
min-complexity: 20
dupl:
threshold: 100
misspell:
locale: US
unused:
check-exported: false
unparam:
check-exported: true
cyclop:
max-complexity: 14
funlen:
lines: 65
linters:
enable-all: true
disable:
- lll
- maligned
- gochecknoglobals
- gomnd
- wrapcheck
- paralleltest
- forbidigo
- exhaustivestruct
- interfacer # deprecated
- forcetypeassert
- scopelint # deprecated
- ifshort # too many false positives
- golint # deprecated
issues:
exclude-use-default: false
exclude-rules:
- linters:
- gomnd
- goconst
- goerr113
- noctx
- funlen
- dupl
path: "_test.go"

39
vendor/github.com/vearutop/statigz/Makefile generated vendored Normal file
View File

@@ -0,0 +1,39 @@
#GOLANGCI_LINT_VERSION := "v1.41.1" # Optional configuration to pinpoint golangci-lint version.
# The head of Makefile determines location of dev-go to include standard targets.
GO ?= go
export GO111MODULE = on
ifneq "$(GOFLAGS)" ""
$(info GOFLAGS: ${GOFLAGS})
endif
ifneq "$(wildcard ./vendor )" ""
$(info Using vendor)
modVendor = -mod=vendor
ifeq (,$(findstring -mod,$(GOFLAGS)))
export GOFLAGS := ${GOFLAGS} ${modVendor}
endif
ifneq "$(wildcard ./vendor/github.com/bool64/dev)" ""
DEVGO_PATH := ./vendor/github.com/bool64/dev
endif
endif
ifeq ($(DEVGO_PATH),)
DEVGO_PATH := $(shell GO111MODULE=on $(GO) list ${modVendor} -f '{{.Dir}}' -m github.com/bool64/dev)
ifeq ($(DEVGO_PATH),)
$(info Module github.com/bool64/dev not found, downloading.)
DEVGO_PATH := $(shell export GO111MODULE=on && $(GO) mod tidy && $(GO) list -f '{{.Dir}}' -m github.com/bool64/dev)
endif
endif
-include $(DEVGO_PATH)/makefiles/main.mk
-include $(DEVGO_PATH)/makefiles/lint.mk
-include $(DEVGO_PATH)/makefiles/test-unit.mk
-include $(DEVGO_PATH)/makefiles/bench.mk
-include $(DEVGO_PATH)/makefiles/reset-ci.mk
# Add your custom targets here.
## Run tests
test: test-unit

BIN
vendor/github.com/vearutop/statigz/_testdata/bad.png.gz generated vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 628 B

Binary file not shown.

Binary file not shown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 628 B

View File

@@ -0,0 +1 @@
Hello, uncompressed!

Binary file not shown.

1036
vendor/github.com/vearutop/statigz/_testdata/swagger.json generated vendored Normal file

File diff suppressed because it is too large Load Diff