Skip to content
0.2.0-dev Download ZIP
185 lines ·5.9 KB Raw
1using System.Buffers.Binary;
2using System.Text;
3using EvilEngine.Adapters.UnityFs;
4
5namespace EvilEngine.Adapters.Tests.Support;
6
7public sealed class UnityFsWriter
8{
9 private readonly List<(string Name, byte[] Data, uint Flags)> _nodes = [];
10
11 public UnityFsWriter Add(string name, byte[] data, uint flags = 4)
12 {
13 _nodes.Add((name, data, flags));
14 return this;
15 }
16
17 public UnityFsWriter Add(string name, string text, uint flags = 4)
18 {
19 return Add(name, Encoding.UTF8.GetBytes(text), flags);
20 }
21
22 public byte[] Build(
23 uint version = 6,
24 UnityFsCompression blocks = UnityFsCompression.None,
25 UnityFsCompression directory = UnityFsCompression.Lz4HC,
26 int blockSize = int.MaxValue,
27 bool directoryAtEnd = false,
28 bool padBlocks = false,
29 byte[]? lzmaBlock = null)
30 {
31 var data = _nodes.SelectMany(node => node.Data).ToArray();
32 var stored = new List<(int Size, byte[] Bytes)>();
33 if (blocks == UnityFsCompression.Lzma)
34 stored.Add((data.Length,
35 lzmaBlock ?? throw new ArgumentException("an LZMA bundle needs its block given", nameof(lzmaBlock))));
36 else
37 for (var at = 0; at < data.Length; at += blockSize)
38 {
39 var block = data[at..Math.Min(data.Length, at + blockSize)];
40 stored.Add((block.Length, blocks == UnityFsCompression.None ? block : Lz4Writer.Encode(block)));
41 }
42
43 var info = new MemoryStream();
44 info.Write(new byte[16]);
45 Int32(info, stored.Count);
46 foreach (var (size, bytes) in stored)
47 {
48 UInt32(info, (uint)size);
49 UInt32(info, (uint)bytes.Length);
50 UInt16(info, (ushort)blocks);
51 }
52
53 Int32(info, _nodes.Count);
54 long offset = 0;
55 foreach (var (name, nodeData, flags) in _nodes)
56 {
57 Int64(info, offset);
58 Int64(info, nodeData.Length);
59 UInt32(info, flags);
60 info.Write(Encoding.UTF8.GetBytes(name + "\0"));
61 offset += nodeData.Length;
62 }
63
64 var plain = info.ToArray();
65 var packed = directory == UnityFsCompression.None ? plain : Lz4Writer.Encode(plain);
66
67 var header = new MemoryStream();
68 header.Write("UnityFS\0"u8);
69 UInt32(header, version);
70 header.Write("5.x.x\0"u8);
71 header.Write("2019.4.18f1\0"u8);
72 var sizeAt = header.Position;
73 Int64(header, 0);
74 UInt32(header, (uint)packed.Length);
75 UInt32(header, (uint)plain.Length);
76 UInt32(header, (uint)directory | 0x40 | (directoryAtEnd ? 0x80u : 0) | (padBlocks ? 0x200u : 0));
77 if (version >= 7)
78 Pad(header);
79 if (!directoryAtEnd)
80 header.Write(packed);
81 if (padBlocks)
82 Pad(header);
83 foreach (var (_, bytes) in stored)
84 header.Write(bytes);
85 if (directoryAtEnd)
86 header.Write(packed);
87 var bundle = header.ToArray();
88 BinaryPrimitives.WriteInt64BigEndian(bundle.AsSpan((int)sizeAt), bundle.Length);
89 return bundle;
90 }
91
92 private static void Pad(MemoryStream stream)
93 {
94 while (stream.Position % 16 != 0)
95 stream.WriteByte(0);
96 }
97
98 private static void UInt16(Stream stream, ushort value)
99 {
100 Span<byte> bytes = stackalloc byte[2];
101 BinaryPrimitives.WriteUInt16BigEndian(bytes, value);
102 stream.Write(bytes);
103 }
104
105 private static void UInt32(Stream stream, uint value)
106 {
107 Span<byte> bytes = stackalloc byte[4];
108 BinaryPrimitives.WriteUInt32BigEndian(bytes, value);
109 stream.Write(bytes);
110 }
111
112 private static void Int32(Stream stream, int value)
113 {
114 UInt32(stream, (uint)value);
115 }
116
117 private static void Int64(Stream stream, long value)
118 {
119 Span<byte> bytes = stackalloc byte[8];
120 BinaryPrimitives.WriteInt64BigEndian(bytes, value);
121 stream.Write(bytes);
122 }
123}
124
125public static class Lz4Writer
126{
127 public static byte[] Encode(byte[] input)
128 {
129 var output = new MemoryStream();
130 var table = new int[4096];
131 Array.Fill(table, -1);
132 int anchor = 0, at = 0;
133 while (at + 4 <= input.Length - 5)
134 {
135 var word = BinaryPrimitives.ReadUInt32LittleEndian(input.AsSpan(at));
136 var hash = (int)((word * 2654435761u) >> 20);
137 var candidate = table[hash];
138 table[hash] = at;
139 if (candidate >= 0 && at - candidate <= 65535 &&
140 BinaryPrimitives.ReadUInt32LittleEndian(input.AsSpan(candidate)) == word)
141 {
142 var length = 4;
143 while (at + length < input.Length - 5 && input[candidate + length] == input[at + length])
144 length++;
145 Sequence(output, input.AsSpan(anchor, at - anchor), at - candidate, length);
146 at += length;
147 anchor = at;
148 }
149 else
150 {
151 at++;
152 }
153 }
154
155 Sequence(output, input.AsSpan(anchor), 0, 0);
156 return output.ToArray();
157 }
158
159 private static void Sequence(MemoryStream output, ReadOnlySpan<byte> literals, int distance, int match)
160 {
161 var extra = match == 0 ? 0 : match - 4;
162 output.WriteByte((byte)((Math.Min(literals.Length, 15) << 4) | Math.Min(extra, 15)));
163 Length(output, literals.Length);
164 output.Write(literals);
165 if (match == 0)
166 return;
167 output.WriteByte((byte)distance);
168 output.WriteByte((byte)(distance >> 8));
169 Length(output, extra);
170 }
171
172 private static void Length(MemoryStream output, int length)
173 {
174 if (length < 15)
175 return;
176 length -= 15;
177 while (length >= 255)
178 {
179 output.WriteByte(255);
180 length -= 255;
181 }
182
183 output.WriteByte((byte)length);
184 }
185}