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

Tile.cs « NesTiler - github.com/ClusterM/NesTiler.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: d5e80e867ab1069ae42da891b1ec570421666c1f (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
61
62
63
64
using System;
using System.IO.Hashing;
using System.Linq;

namespace com.clusterrr.Famicom.NesTiler
{
    sealed record Tile : IEquatable<Tile>
    {
        public readonly byte[] Pixels;
        public readonly int Width;
        public readonly int Height;
        private int? hash;
        private byte[] data = null;

        public Tile(byte[] data, int width, int height)
        {
            (Pixels, Width, Height) = (data, width, height);
        }

        public byte[] GetAsTileData()
        {
            if (data != null) return data;
            data = new byte[Width * Height / 8 * 2];
            lock (data)
            {
                int pixel = 0;
                byte bit = 7;
                for (int y = 0; y < Height; y++)
                {
                    for (int x = 0; x < Width; x++)
                    {
                        if ((Pixels[(y * Width) + x] & 1) != 0)
                            data[(pixel / 64 * 2) + y] |= (byte)(1 << bit);
                        if ((Pixels[(y * Width) + x] & 2) != 0)
                            data[(pixel / 64 * 2) + y + 8] |= (byte)(1 << bit);
                        pixel++;
                        bit = (byte)((byte)(bit - 1) % 8);
                    }
                }
            }
            return data;
        }

        public bool Equals(Tile other)
        {
            var hash1 = GetHashCode();
            var hash2 = other.GetHashCode();
            if (hash1 != hash2) return false;
            var data1 = GetAsTileData();
            var data2 = other.GetAsTileData();
            return Enumerable.SequenceEqual(data1, data2);
        }

        public override int GetHashCode()
        {
            if (hash != null) return hash.Value;
            var crc = new Crc32();
            crc.Append(GetAsTileData());
            var hashBytes = crc.GetCurrentHash();
            hash = BitConverter.ToInt32(hashBytes, 0);
            return hash.Value;
        }
    }
}