0.2.0-dev Download ZIP
248 lines ·9.1 KB Raw
| 1 | using System.Buffers.Binary; |
| 2 | using System.Text; |
| 3 | using System.Text.Json; |
| 4 | using EvilEngine.Adapters.Addressables; |
| 5 | |
| 6 | namespace EvilEngine.Adapters.Tests.Support; |
| 7 | |
| 8 | public sealed class CatalogWriter |
| 9 | { |
| 10 | public const string BundledAssetProvider = "UnityEngine.ResourceManagement.ResourceProviders.BundledAssetProvider"; |
| 11 | |
| 12 | private static readonly CatalogType BundleResource = |
| 13 | new("Unity.ResourceManager, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", |
| 14 | "UnityEngine.ResourceManagement.ResourceProviders.IAssetBundleResource"); |
| 15 | |
| 16 | private static readonly CatalogType GameObject = |
| 17 | new("UnityEngine.CoreModule, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "UnityEngine.GameObject"); |
| 18 | |
| 19 | private static readonly CatalogType Options = |
| 20 | new("Unity.ResourceManager, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", |
| 21 | "UnityEngine.ResourceManagement.ResourceProviders.AssetBundleRequestOptions"); |
| 22 | |
| 23 | private readonly List<List<int>> _buckets = []; |
| 24 | |
| 25 | private readonly Dictionary<string, int> _bundles = new(StringComparer.Ordinal); |
| 26 | |
| 27 | private readonly |
| 28 | List<(string InternalId, string Provider, int DependencyKey, object? Data, int PrimaryKey, CatalogType Type)> |
| 29 | _entries = []; |
| 30 | |
| 31 | private readonly List<object> _keys = []; |
| 32 | |
| 33 | private int _dependencyKeys = 1000; |
| 34 | |
| 35 | public string Folder { get; init; } = "StandaloneWindows64"; |
| 36 | |
| 37 | public char Separator { get; init; } = '\\'; |
| 38 | |
| 39 | public int Key(object key) |
| 40 | { |
| 41 | var index = _keys.FindIndex(existing => existing.Equals(key)); |
| 42 | if (index >= 0) |
| 43 | return index; |
| 44 | _keys.Add(key); |
| 45 | _buckets.Add([]); |
| 46 | return _keys.Count - 1; |
| 47 | } |
| 48 | |
| 49 | public int Entry(string internalId, string provider, int dependencyKey, object? data, CatalogType type, |
| 50 | params object[] keys) |
| 51 | { |
| 52 | var primary = Key(keys[0]); |
| 53 | _entries.Add((internalId, provider, dependencyKey, data, primary, type)); |
| 54 | var index = _entries.Count - 1; |
| 55 | foreach (var key in keys) |
| 56 | _buckets[Key(key)].Add(index); |
| 57 | return index; |
| 58 | } |
| 59 | |
| 60 | public CatalogWriter Bundle(string file, long size, string hash = "", params string[] dependsOn) |
| 61 | { |
| 62 | var options = JsonSerializer.Serialize(new Dictionary<string, object> |
| 63 | { |
| 64 | ["m_Hash"] = hash, ["m_Crc"] = 0, ["m_Timeout"] = 0, ["m_ChunkedTransfer"] = false, |
| 65 | ["m_RedirectLimit"] = -1, ["m_RetryCount"] = 0, |
| 66 | ["m_BundleName"] = Convert.ToHexStringLower(Encoding.UTF8.GetBytes(file))[..Math.Min(32, file.Length * 2)], |
| 67 | ["m_AssetLoadMode"] = 0, ["m_BundleSize"] = size |
| 68 | }); |
| 69 | _bundles[file] = Entry( |
| 70 | $"{Catalog.RuntimePath}{Separator}{Folder}{Separator}{file}", |
| 71 | Catalog.AssetBundleProvider, |
| 72 | Dependencies(dependsOn), |
| 73 | new CatalogJson(Options, options), |
| 74 | BundleResource, |
| 75 | file); |
| 76 | return this; |
| 77 | } |
| 78 | |
| 79 | public CatalogWriter Asset(string address, string? guid, params string[] bundles) |
| 80 | { |
| 81 | object[] keys = guid is null ? [address] : [address, guid]; |
| 82 | Entry(address, BundledAssetProvider, Dependencies(bundles), null, GameObject, keys); |
| 83 | return this; |
| 84 | } |
| 85 | |
| 86 | public CatalogWriter Resource(string address) |
| 87 | { |
| 88 | Entry(address, Catalog.LegacyResourcesProvider, -1, null, GameObject, address); |
| 89 | return this; |
| 90 | } |
| 91 | |
| 92 | public byte[] Build(string version = "1.19.11", IReadOnlyList<string>? prefixes = null, |
| 93 | Func<string, string>? internalId = null) |
| 94 | { |
| 95 | var keyData = new MemoryStream(); |
| 96 | var keyOffsets = _keys.Select(key => Write(keyData, key)).ToArray(); |
| 97 | var extra = new MemoryStream(); |
| 98 | var bucketData = new MemoryStream(); |
| 99 | Int32(bucketData, _keys.Count); |
| 100 | for (var index = 0; index < _keys.Count; index++) |
| 101 | { |
| 102 | Int32(bucketData, keyOffsets[index]); |
| 103 | Int32(bucketData, _buckets[index].Count); |
| 104 | foreach (var entry in _buckets[index]) |
| 105 | Int32(bucketData, entry); |
| 106 | } |
| 107 | |
| 108 | var internalIds = new List<string>(); |
| 109 | var providers = new List<string>(); |
| 110 | var types = new List<CatalogType>(); |
| 111 | var entryData = new MemoryStream(); |
| 112 | Int32(entryData, _entries.Count); |
| 113 | foreach (var entry in _entries) |
| 114 | { |
| 115 | Int32(entryData, Index(internalIds, internalId?.Invoke(entry.InternalId) ?? entry.InternalId)); |
| 116 | Int32(entryData, Index(providers, entry.Provider)); |
| 117 | Int32(entryData, entry.DependencyKey); |
| 118 | Int32(entryData, 0); |
| 119 | Int32(entryData, entry.Data is null ? -1 : Write(extra, entry.Data)); |
| 120 | Int32(entryData, entry.PrimaryKey); |
| 121 | Int32(entryData, Index(types, entry.Type)); |
| 122 | } |
| 123 | |
| 124 | var catalog = new Dictionary<string, object> |
| 125 | { |
| 126 | ["m_LocatorId"] = "AddressablesMainContentCatalog", |
| 127 | ["m_ProviderIds"] = providers, |
| 128 | ["m_InternalIds"] = internalIds, |
| 129 | ["m_KeyDataString"] = Convert.ToBase64String(keyData.ToArray()), |
| 130 | ["m_BucketDataString"] = Convert.ToBase64String(bucketData.ToArray()), |
| 131 | ["m_EntryDataString"] = Convert.ToBase64String(entryData.ToArray()), |
| 132 | ["m_ExtraDataString"] = Convert.ToBase64String(extra.ToArray()), |
| 133 | ["m_resourceTypes"] = types.Select(type => new Dictionary<string, string> |
| 134 | { ["m_AssemblyName"] = type.Assembly, ["m_ClassName"] = type.Class }).ToArray(), |
| 135 | ["m_InternalIdPrefixes"] = prefixes ?? [] |
| 136 | }; |
| 137 | if (!version.StartsWith("1.19", StringComparison.Ordinal)) |
| 138 | catalog["m_BuildResultHash"] = "f2efe611a456712672772b4c90775733"; |
| 139 | return JsonSerializer.SerializeToUtf8Bytes(catalog); |
| 140 | } |
| 141 | |
| 142 | public static byte[] Settings(string buildTarget = "StandaloneWindows64", string version = "1.19.11") |
| 143 | { |
| 144 | return JsonSerializer.SerializeToUtf8Bytes(new Dictionary<string, object> |
| 145 | { |
| 146 | ["m_buildTarget"] = buildTarget, |
| 147 | ["m_CatalogLocations"] = new[] |
| 148 | { |
| 149 | new Dictionary<string, object> |
| 150 | { |
| 151 | ["m_Keys"] = new[] { "AddressablesMainContentCatalog" }, |
| 152 | ["m_InternalId"] = $"{Catalog.RuntimePath}/catalog.json" |
| 153 | } |
| 154 | }, |
| 155 | ["m_AddressablesVersion"] = version |
| 156 | }); |
| 157 | } |
| 158 | |
| 159 | private int Dependencies(string[] bundles) |
| 160 | { |
| 161 | if (bundles.Length == 0) |
| 162 | return -1; |
| 163 | var key = Key(_dependencyKeys++); |
| 164 | foreach (var bundle in bundles) |
| 165 | _buckets[key].Add(_bundles[bundle]); |
| 166 | return key; |
| 167 | } |
| 168 | |
| 169 | private static int Index<T>(List<T> list, T item) where T : notnull |
| 170 | { |
| 171 | var index = list.IndexOf(item); |
| 172 | if (index >= 0) |
| 173 | return index; |
| 174 | list.Add(item); |
| 175 | return list.Count - 1; |
| 176 | } |
| 177 | |
| 178 | private static int Write(MemoryStream stream, object value) |
| 179 | { |
| 180 | var at = (int)stream.Position; |
| 181 | switch (value) |
| 182 | { |
| 183 | case string text when text.All(char.IsAscii): |
| 184 | stream.WriteByte(0); |
| 185 | Bytes(stream, Encoding.ASCII.GetBytes(text)); |
| 186 | break; |
| 187 | case string text: |
| 188 | stream.WriteByte(1); |
| 189 | Bytes(stream, Encoding.Unicode.GetBytes(text)); |
| 190 | break; |
| 191 | case ushort small: |
| 192 | stream.WriteByte(2); |
| 193 | Span<byte> two = stackalloc byte[2]; |
| 194 | BinaryPrimitives.WriteUInt16LittleEndian(two, small); |
| 195 | stream.Write(two); |
| 196 | break; |
| 197 | case uint large: |
| 198 | stream.WriteByte(3); |
| 199 | Span<byte> four = stackalloc byte[4]; |
| 200 | BinaryPrimitives.WriteUInt32LittleEndian(four, large); |
| 201 | stream.Write(four); |
| 202 | break; |
| 203 | case int number: |
| 204 | stream.WriteByte(4); |
| 205 | Int32(stream, number); |
| 206 | break; |
| 207 | case CatalogHash hash: |
| 208 | stream.WriteByte(5); |
| 209 | Short(stream, hash.Value); |
| 210 | break; |
| 211 | case CatalogType type: |
| 212 | stream.WriteByte(6); |
| 213 | Short(stream, type.Assembly); |
| 214 | Short(stream, type.Class); |
| 215 | break; |
| 216 | case CatalogJson json: |
| 217 | stream.WriteByte(7); |
| 218 | Short(stream, json.Type.Assembly); |
| 219 | Short(stream, json.Type.Class); |
| 220 | Bytes(stream, Encoding.Unicode.GetBytes(json.Text)); |
| 221 | break; |
| 222 | default: |
| 223 | throw new ArgumentException($"A catalog can't hold a {value.GetType().Name}.", nameof(value)); |
| 224 | } |
| 225 | |
| 226 | return at; |
| 227 | } |
| 228 | |
| 229 | private static void Short(MemoryStream stream, string text) |
| 230 | { |
| 231 | var bytes = Encoding.ASCII.GetBytes(text); |
| 232 | stream.WriteByte((byte)bytes.Length); |
| 233 | stream.Write(bytes); |
| 234 | } |
| 235 | |
| 236 | private static void Bytes(MemoryStream stream, byte[] bytes) |
| 237 | { |
| 238 | Int32(stream, bytes.Length); |
| 239 | stream.Write(bytes); |
| 240 | } |
| 241 | |
| 242 | private static void Int32(MemoryStream stream, int value) |
| 243 | { |
| 244 | Span<byte> bytes = stackalloc byte[4]; |
| 245 | BinaryPrimitives.WriteInt32LittleEndian(bytes, value); |
| 246 | stream.Write(bytes); |
| 247 | } |
| 248 | } |