Welcome to mirror list, hosted at ThFree Co, Russian Federation.

ColorsFinder.cs « NesTiler - github.com/ClusterM/NesTiler.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 2772f69f470e835601f0ed1018cdd5ea1075ec26 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace com.clusterrr.Famicom.NesTiler
{
    class ColorsFinder 
    {
        private readonly Dictionary<byte, Color> colors;
        private readonly Dictionary<Color, byte> cache = new();

        public ColorsFinder(Dictionary<byte, Color> colors)
        {
            this.colors = colors;
        }

        public byte FindSimilarColor(Color color)
        {
            if (cache.ContainsKey(color))
                return cache[color];
            byte result = byte.MaxValue;
            double minDelta = double.MaxValue;
            Color c = Color.Transparent;
            foreach (var index in colors.Keys)
            {
                var delta = color.GetDelta(colors[index]);
                if (delta < minDelta)
                {
                    minDelta = delta;
                    result = index;
                    c = colors[index];
                }
            }
            if (result == byte.MaxValue)
                throw new KeyNotFoundException($"Invalid color: {color}.");
            if (cache != null)
                cache[color] = result;
            return result;
        }

        public Color FindSimilarColor(IEnumerable<Color> colors, Color color)
        {
            Color result = Color.Black;
            double minDelta = double.MaxValue;
            foreach (var c in colors)
            {
                var delta = color.GetDelta(c);
                if (delta < minDelta)
                {
                    minDelta = delta;
                    result = c;
                }
            }
            return result;
        }
    }
}