blob: 123ecc955d226f65ed126b26317e80fc4eb525aa (
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.IO.Hashing;
using System.Linq;
namespace com.clusterrr.Famicom.NesTiler
{
sealed record Tile : IEquatable<Tile>
{
public readonly byte[] Pixels;
public const int Width = 8;
public readonly int Height;
private byte[]? data = null;
public Tile(byte[] data, int height)
{
(Pixels, Height) = (data, height);
}
public byte[] GetAsPatternData()
{
if (data != null) return data;
data = new byte[Height * 2]; // two bits per pixel
lock (data)
{
int pixel = 0; // total pixels counter
byte bit = 7; // bit number
for (int y = 0; y < Height; y++)
{
for (int x = 0; x < Width; x++)
{
// for each pixel
if ((Pixels[(y * Width) + x] & 1) != 0) // check bit 0
data[(y / 8 * 16) + (y % 8)] |= (byte)(1 << bit);
if ((Pixels[(y * Width) + x] & 2) != 0) // check bit 1
data[(y / 8 * 16) + (y % 8) + 8] |= (byte)(1 << bit);
pixel++;
bit = unchecked((byte)((byte)(bit - 1) % 8)); // decrease bit number, wrap around if need
}
}
}
return data;
}
public bool Equals(Tile? other)
{
if (other == null) return false;
var data1 = GetAsPatternData();
var data2 = other.GetAsPatternData();
return Enumerable.SequenceEqual(data1, data2);
}
public override int GetHashCode()
{
var crc = new Crc32();
crc.Append(GetAsPatternData());
var hashBytes = crc.GetCurrentHash();
return BitConverter.ToInt32(hashBytes, 0);
}
}
}
|