github.com/Seikaijyu/gio@v0.0.1/internal/f32color/f32colorgen/main.go (about)

     1  // SPDX-License-Identifier: Unlicense OR MIT
     2  
     3  package main
     4  
     5  import (
     6  	"bytes"
     7  	"flag"
     8  	"fmt"
     9  	"go/format"
    10  	"math"
    11  	"os"
    12  )
    13  
    14  func main() {
    15  	out := flag.String("out", "", "output file")
    16  	flag.Parse()
    17  
    18  	var b bytes.Buffer
    19  	printf := func(content string, args ...interface{}) {
    20  		fmt.Fprintf(&b, content, args...)
    21  	}
    22  
    23  	printf("// SPDX-License-Identifier: Unlicense OR MIT\n\n")
    24  	printf("// Code generated by f32colorgen. DO NOT EDIT.\n")
    25  	printf("\n")
    26  	printf("package f32color\n\n")
    27  
    28  	printf("// table corresponds to sRGBToLinear(float32(index)/0xff)\n")
    29  	printf("var srgb8ToLinear = [...]float32{")
    30  	for b := 0; b <= 0xFF; b++ {
    31  		if b%0x10 == 0 {
    32  			printf("\n\t")
    33  		}
    34  		v := sRGBToLinear(float32(b) / 0xff)
    35  		printf("%#v,", v)
    36  	}
    37  	printf("\n}\n")
    38  
    39  	data, err := format.Source(b.Bytes())
    40  	if err != nil {
    41  		fmt.Fprint(os.Stderr, b.String())
    42  		panic(err)
    43  	}
    44  
    45  	err = os.WriteFile(*out, data, 0755)
    46  	if err != nil {
    47  		panic(err)
    48  	}
    49  }
    50  
    51  // sRGBToLinear transforms color value from sRGB to linear.
    52  func sRGBToLinear(c float32) float32 {
    53  	// Formula from EXT_sRGB.
    54  	if c <= 0.04045 {
    55  		return c / 12.92
    56  	} else {
    57  		return float32(math.Pow(float64((c+0.055)/1.055), 2.4))
    58  	}
    59  }