From 1c530a2ce7c461a3be5f76be7e79ccbb14e1d725 Mon Sep 17 00:00:00 2001 From: "Sascha L. Teichmann" Date: Sun, 19 Oct 2014 11:43:53 +0200 Subject: [PATCH] Sort transparent colors from colors.txt to front of lookup table. Makes it easier to determine if a color index corresponds to a transparent color. --- common/colors.go | 50 ++++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 42 insertions(+), 8 deletions(-) diff --git a/common/colors.go b/common/colors.go index 3fdb858..fa2c497 100644 --- a/common/colors.go +++ b/common/colors.go @@ -9,12 +9,33 @@ import ( "fmt" "image/color" "os" + "sort" "strings" ) type Colors struct { - Colors []color.RGBA - NameIndex map[string]int32 + Colors []color.RGBA + NameIndex map[string]int32 + Transparent int +} + +type namedColor struct { + name string + color color.RGBA +} + +type sortByAlpha []namedColor + +func (colors sortByAlpha) Less(i, j int) bool { + return colors[i].color.A < colors[j].color.A +} + +func (colors sortByAlpha) Len() int { + return len(colors) +} + +func (colors sortByAlpha) Swap(i, j int) { + colors[i], colors[j] = colors[j], colors[i] } func ParseColors(filename string) (colors *Colors, err error) { @@ -25,8 +46,7 @@ func ParseColors(filename string) (colors *Colors, err error) { } defer file.Close() - nameIndex := make(map[string]int32) - cols := make([]color.RGBA, 0, 2200) + cols := make([]namedColor, 0, 2200) scanner := bufio.NewScanner(file) for scanner.Scan() { @@ -38,12 +58,26 @@ func ParseColors(filename string) (colors *Colors, err error) { var name string if n, _ := fmt.Sscanf( line, "%s %d %d %d %d", &name, &c.R, &c.G, &c.B, &c.A); n > 0 { - idx := int32(len(cols)) - cols = append(cols, c) - nameIndex[name] = idx + cols = append(cols, namedColor{name: name, color: c}) } } err = scanner.Err() - colors = &Colors{Colors: cols, NameIndex: nameIndex} + + // Sort transparent colors to front. Makes it easier to figure out + // if an index corresponds to a transparent color (i < Transparent). + sort.Sort(sortByAlpha(cols)) + + cs := make([]color.RGBA, len(cols)) + nameIndex := make(map[string]int32, len(cols)) + + transparent := 0 + for i, nc := range cols { + if nc.color.A < 0xff { + transparent++ + } + cs[i] = nc.color + nameIndex[nc.name] = int32(i) + } + colors = &Colors{Colors: cs, NameIndex: nameIndex, Transparent: transparent} return }