Decompiled source of UnitySceneRepacker v0.2.0

UnitySceneRepacker.Addressables.dll

Decompiled 9 hours ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using UnityEngine;
using UnityEngine.AddressableAssets;
using UnityEngine.AddressableAssets.Initialization;
using UnityEngine.AddressableAssets.ResourceLocators;
using UnityEngine.ResourceManagement;
using UnityEngine.ResourceManagement.AsyncOperations;
using UnityEngine.ResourceManagement.ResourceLocations;
using UnityEngine.ResourceManagement.ResourceProviders;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")]
[assembly: AssemblyCompany("UnitySceneRepacker.Addressables")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("5.0.0.0")]
[assembly: AssemblyInformationalVersion("5.0.0+48d87d10f97d0827a048e77338593811c1a77651")]
[assembly: AssemblyProduct("UnitySceneRepacker.Addressables")]
[assembly: AssemblyTitle("UnitySceneRepacker.Addressables")]
[assembly: AssemblyVersion("5.0.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace UnitySceneRepacker
{
	public sealed class RepackedAssets(string gameDir, string cacheDir, string name, Func<IReadOnlyList<RewriteRule>>? rewriteRules = null) : IDisposable
	{
		private sealed class RepackOperation(Func<(string catalogPath, string summary)> repack) : AsyncOperationBase<string>(), IUpdateReceiver
		{
			private Task<(string catalogPath, string summary)>? task;

			private bool completed;

			protected override void Execute()
			{
				task = Task.Run(repack);
			}

			protected override bool InvokeWaitForCompletion()
			{
				((IAsyncResult)task).AsyncWaitHandle.WaitOne();
				Update(0f);
				return true;
			}

			public void Update(float unscaledDeltaTime)
			{
				if (!completed && task.IsCompleted)
				{
					completed = true;
					if (task.IsFaulted)
					{
						base.Complete((string)null, false, task.Exception.InnerException, true);
						return;
					}
					var (text, text2) = task.Result;
					Debug.Log((object)("[RepackedAssets] " + text2));
					base.Complete(text, true, (string)null);
				}
			}
		}

		private static readonly object cacheLock = new object();

		private readonly Dictionary<string, SortedSet<string>> requests = new Dictionary<string, SortedSet<string>>();

		private readonly List<AsyncOperationHandle> loaded = new List<AsyncOperationHandle>();

		private AsyncOperationHandle<RepackedCatalog> processing;

		public RepackedAsset Request(string scene, string path)
		{
			if (processing.IsValid())
			{
				throw new InvalidOperationException("can't request more from " + name + " after the first Load or Prepare");
			}
			if (!requests.TryGetValue(scene, out SortedSet<string> value))
			{
				value = (requests[scene] = new SortedSet<string>(StringComparer.Ordinal));
			}
			value.Add(path);
			return new RepackedAsset(this, (name + "/" + scene + "/" + path + ".prefab").ToLowerInvariant());
		}

		public void Prepare()
		{
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			if (processing.IsValid())
			{
				return;
			}
			IReadOnlyList<RewriteRule> rules = rewriteRules?.Invoke() ?? Array.Empty<RewriteRule>();
			ResourceManager resourceManager = Addressables.ResourceManager;
			AsyncOperationHandle<string> val = resourceManager.StartOperation<string>((AsyncOperationBase<string>)(object)new RepackOperation(delegate
			{
				lock (cacheLock)
				{
					return RepackIntoCache(rules);
				}
			}), default(AsyncOperationHandle));
			processing = resourceManager.CreateChainOperation<RepackedCatalog, string>(val, (Func<AsyncOperationHandle<string>, AsyncOperationHandle<RepackedCatalog>>)((AsyncOperationHandle<string> op) => (AsyncOperationHandle<RepackedCatalog>)(((int)op.Status != 1) ? Failed<RepackedCatalog>("repacking " + name, op.OperationException) : RepackedCatalog.Load(op.Result))));
		}

		internal AsyncOperationHandle<GameObject> Load(string key)
		{
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			Prepare();
			AsyncOperationHandle<GameObject> val = Addressables.ResourceManager.CreateChainOperation<GameObject, RepackedCatalog>(processing, (Func<AsyncOperationHandle<RepackedCatalog>, AsyncOperationHandle<GameObject>>)((AsyncOperationHandle<RepackedCatalog> op) => ((int)op.Status != 1) ? Failed<GameObject>("processing " + name, op.OperationException) : Addressables.LoadAssetAsync<GameObject>((object)key)));
			loaded.RemoveAll((AsyncOperationHandle h) => !((AsyncOperationHandle)(ref h)).IsValid());
			loaded.Add(AsyncOperationHandle<GameObject>.op_Implicit(val));
			return val;
		}

		private static AsyncOperationHandle<T> Failed<T>(string what, Exception cause)
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			return Addressables.ResourceManager.CreateCompletedOperationWithException<T>(default(T), new Exception(what + " failed", cause));
		}

		private (string catalogPath, string summary) RepackIntoCache(IReadOnlyList<RewriteRule> rewriteRules)
		{
			//IL_00e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ed: Expected O, but got Unknown
			//IL_00fa: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ff: Unknown result type (might be due to invalid IL or missing references)
			//IL_0106: Unknown result type (might be due to invalid IL or missing references)
			//IL_0118: Expected O, but got Unknown
			string depsDir = Path.Combine(cacheDir, "deps");
			InvalidateIfStale(depsDir, rewriteRules);
			string text = ToJson(requests);
			string path = Path.Combine(cacheDir, name + ".requests.json");
			string path2 = Path.Combine(cacheDir, name + ".bundle");
			string text2 = Path.Combine(cacheDir, name + ".catalog.bin");
			if (File.Exists(path) && File.ReadAllText(path) == text && File.Exists(path2) && File.Exists(text2))
			{
				return (catalogPath: text2, summary: name + " is up to date");
			}
			Stopwatch stopwatch = Stopwatch.StartNew();
			GameRepacker game = new GameRepacker(gameDir);
			try
			{
				RepackResult val = game.Repack(name, text, (RepackMode)new AssetBundle
				{
					EmitCatalog = true,
					RewriteRules = rewriteRules
				}, (Compression)2);
				TimeSpan elapsed = stopwatch.Elapsed;
				Stopwatch stopwatch2 = Stopwatch.StartNew();
				string[] array = val.DependencyFiles.Where((string file) => !File.Exists(DependencyPath(depsDir, file))).ToArray();
				Parallel.ForEach(array, delegate(string file)
				{
					WriteAtomic(DependencyPath(depsDir, file), game.BuildDependencyFileBundle(file, (Compression)2, rewriteRules));
				});
				TimeSpan elapsed2 = stopwatch2.Elapsed;
				WriteAtomic(path2, val.Bundle);
				WriteAtomic(text2, val.Catalog);
				WriteAtomic(path, Encoding.UTF8.GetBytes(text));
				string item = $"repacked {name} in {stopwatch.ElapsedMilliseconds}ms: " + $"{val.Stats.ObjectsBefore} -> {val.Stats.ObjectsAfter} objects in {elapsed.TotalMilliseconds:0}ms, " + $"built {array.Length} of {val.DependencyFiles.Length} dependencies in {elapsed2.TotalMilliseconds:0}ms";
				return (catalogPath: text2, summary: item);
			}
			finally
			{
				if (game != null)
				{
					((IDisposable)game).Dispose();
				}
			}
		}

		private static string DependencyPath(string depsDir, string file)
		{
			return Path.Combine(depsDir, file + ".bundle");
		}

		private void InvalidateIfStale(string depsDir, IReadOnlyList<RewriteRule> rewriteRules)
		{
			string path = Path.Combine(cacheDir, "fingerprint");
			string text = $"{GameRepacker.FormatVersion}\n{Path.GetFullPath(gameDir)}\n{GameRepacker.GameFingerprint(gameDir)}\n{RewriteRule.ToJson(rewriteRules)}";
			if (!File.Exists(path) || !(File.ReadAllText(path) == text))
			{
				if (Directory.Exists(cacheDir))
				{
					Directory.Delete(cacheDir, recursive: true);
				}
				Directory.CreateDirectory(depsDir);
				WriteAtomic(path, Encoding.UTF8.GetBytes(text));
			}
		}

		private static void WriteAtomic(string path, byte[] data)
		{
			string text = path + ".tmp";
			File.WriteAllBytes(text, data);
			if (File.Exists(path))
			{
				File.Delete(path);
			}
			File.Move(text, path);
		}

		private static string ToJson(Dictionary<string, SortedSet<string>> objects)
		{
			return "{" + string.Join(",", objects.Select<KeyValuePair<string, SortedSet<string>>, string>((KeyValuePair<string, SortedSet<string>> scene) => Str(scene.Key) + ": [" + string.Join(",", scene.Value.Select(Str)) + "]")) + "}";
			static string Str(string s)
			{
				return "\"" + s.Replace("\\", "\\\\").Replace("\"", "\\\"") + "\"";
			}
		}

		public void Dispose()
		{
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: Unknown result type (might be due to invalid IL or missing references)
			foreach (AsyncOperationHandle item in loaded.Where((AsyncOperationHandle h) => ((AsyncOperationHandle)(ref h)).IsValid()))
			{
				Addressables.Release(item);
			}
			loaded.Clear();
			if (processing.IsValid())
			{
				if (processing.IsDone)
				{
					ReleaseProcessing(processing);
				}
				else
				{
					processing.Completed += ReleaseProcessing;
				}
				processing = default(AsyncOperationHandle<RepackedCatalog>);
			}
			static void ReleaseProcessing(AsyncOperationHandle<RepackedCatalog> op)
			{
				//IL_0002: Unknown result type (might be due to invalid IL or missing references)
				//IL_0008: Invalid comparison between Unknown and I4
				//IL_0016: Unknown result type (might be due to invalid IL or missing references)
				if ((int)op.Status == 1)
				{
					op.Result.Dispose();
				}
				Addressables.Release<RepackedCatalog>(op);
			}
		}
	}
	public sealed class RepackedAsset
	{
		private readonly RepackedAssets owner;

		private readonly string key;

		internal RepackedAsset(RepackedAssets owner, string key)
		{
			this.owner = owner;
			this.key = key;
		}

		public AsyncOperationHandle<GameObject> Load()
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			return owner.Load(key);
		}
	}
	public sealed class RepackedCatalog : IDisposable
	{
		private sealed class LoadMonoScriptsOperation(IResourceLocator locator, string bundleName, AsyncOperationHandle<IList<IAssetBundleResource>> scripts) : AsyncOperationBase<RepackedCatalog>()
		{
			private List<AssetBundleRequest> requests = new List<AssetBundleRequest>();

			private bool finished;

			protected override void Execute()
			{
				requests = scripts.Result.Select((IAssetBundleResource bundle) => bundle.GetAssetBundle().LoadAllAssetsAsync()).ToList();
				if (requests.Count == 0)
				{
					Finish();
					return;
				}
				int pending = requests.Count;
				foreach (AssetBundleRequest request in requests)
				{
					((AsyncOperation)request).completed += delegate
					{
						if (--pending == 0)
						{
							Finish();
						}
					};
				}
			}

			protected override bool InvokeWaitForCompletion()
			{
				Finish();
				return true;
			}

			private void Finish()
			{
				//IL_004e: Unknown result type (might be due to invalid IL or missing references)
				if (!finished)
				{
					finished = true;
					List<Object> monoScripts = requests.SelectMany((AssetBundleRequest request) => request.allAssets).ToList();
					base.Complete(new RepackedCatalog(locator, bundleName, scripts, monoScripts), true, (string)null);
				}
			}
		}

		private const string MonoScriptsKey = "monoscripts";

		private readonly string bundleName;

		private readonly AsyncOperationHandle<IList<IAssetBundleResource>> scripts;

		private readonly List<Object> monoScripts;

		private const string CatalogSuffix = ".catalog.bin";

		public IResourceLocator Locator { get; }

		public IEnumerable<string> Assets => from key in Locator.Keys.OfType<string>()
			where key.StartsWith(bundleName + "/", StringComparison.Ordinal)
			select key;

		public static AsyncOperationHandle<RepackedCatalog> Load(string catalogPath)
		{
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			//IL_009c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00af: Unknown result type (might be due to invalid IL or missing references)
			catalogPath = Path.GetFullPath(catalogPath);
			string fileName = Path.GetFileName(catalogPath);
			if (!fileName.EndsWith(".catalog.bin"))
			{
				throw new ArgumentException(catalogPath + " is not a .catalog.bin file", "catalogPath");
			}
			string bundleName = fileName.Substring(0, fileName.Length - ".catalog.bin".Length);
			AddressablesRuntimeProperties.SetPropertyValue("UnitySceneRepacker." + bundleName, Path.GetDirectoryName(catalogPath));
			AsyncOperationHandle<IResourceLocator> val = Addressables.LoadContentCatalogAsync(catalogPath, (string)null);
			return Addressables.ResourceManager.CreateChainOperation<RepackedCatalog, IResourceLocator>(val, (Func<AsyncOperationHandle<IResourceLocator>, AsyncOperationHandle<RepackedCatalog>>)((AsyncOperationHandle<IResourceLocator> op) => ((int)op.Status != 1) ? Failed("loading catalog " + catalogPath, op.OperationException) : FromLocator(op.Result, bundleName)));
		}

		private static AsyncOperationHandle<RepackedCatalog> FromLocator(IResourceLocator locator, string bundleName)
		{
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			IList<IResourceLocation> list = default(IList<IResourceLocation>);
			if (!locator.Locate((object)"monoscripts", typeof(IAssetBundleResource), ref list))
			{
				list = new List<IResourceLocation>();
			}
			AsyncOperationHandle<IList<IAssetBundleResource>> val = Addressables.LoadAssetsAsync<IAssetBundleResource>(list, (Action<IAssetBundleResource>)null);
			return Addressables.ResourceManager.CreateChainOperation<RepackedCatalog, IList<IAssetBundleResource>>(val, (Func<AsyncOperationHandle<IList<IAssetBundleResource>>, AsyncOperationHandle<RepackedCatalog>>)((AsyncOperationHandle<IList<IAssetBundleResource>> op) => (AsyncOperationHandle<RepackedCatalog>)(((int)op.Status != 1) ? Failed("loading MonoScripts", op.OperationException) : Addressables.ResourceManager.StartOperation<RepackedCatalog>((AsyncOperationBase<RepackedCatalog>)(object)new LoadMonoScriptsOperation(locator, bundleName, op), AsyncOperationHandle<IList<IAssetBundleResource>>.op_Implicit(op)))));
		}

		private static AsyncOperationHandle<RepackedCatalog> Failed(string what, Exception cause)
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			return Addressables.ResourceManager.CreateCompletedOperationWithException<RepackedCatalog>((RepackedCatalog)null, new Exception(what + " failed", cause));
		}

		private RepackedCatalog(IResourceLocator locator, string bundleName, AsyncOperationHandle<IList<IAssetBundleResource>> scripts, List<Object> monoScripts)
		{
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			Locator = locator;
			this.bundleName = bundleName;
			this.scripts = scripts;
			this.monoScripts = monoScripts;
			Addressables.ResourceManager.Acquire<IList<IAssetBundleResource>>(scripts);
		}

		public void Dispose()
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			monoScripts.Clear();
			Addressables.Release<IList<IAssetBundleResource>>(scripts);
			Addressables.RemoveResourceLocator(Locator);
		}
	}
}

UnitySceneRepacker.Bindings.dll

Decompiled 9 hours ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using Microsoft.CodeAnalysis;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")]
[assembly: AssemblyCompany("Jakob Hellermann")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyDescription("Bindings for unity-scene-repacker")]
[assembly: AssemblyFileVersion("5.0.0.0")]
[assembly: AssemblyInformationalVersion("5.0.0+48d87d10f97d0827a048e77338593811c1a77651")]
[assembly: AssemblyProduct("UnitySceneRepacker.Bindings")]
[assembly: AssemblyTitle("UnitySceneRepacker.Bindings")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/jakobhellermann/unity-scene-repacker")]
[assembly: InternalsVisibleTo("UnitySceneRepacker.Addressables")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("5.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace UnitySceneRepacker
{
	public enum Compression : byte
	{
		None = 0,
		Lz4 = 2
	}
	public sealed class RepackException : Exception
	{
		public RepackException(string message)
			: base(message)
		{
		}
	}
	public sealed class RewriteRule
	{
		private readonly string json;

		private RewriteRule(string assembly, string script, string actionJson)
		{
			json = "{\"assembly\":" + Str(assembly) + ",\"script\":" + Str(script) + "," + actionJson + "}";
		}

		public static RewriteRule SetField(string assembly, string script, string field, bool value)
		{
			return new RewriteRule(assembly, script, "\"field\":" + Str(field) + ",\"value\":" + (value ? "true" : "false"));
		}

		public static RewriteRule SetField(string assembly, string script, string field, long value)
		{
			return new RewriteRule(assembly, script, "\"field\":" + Str(field) + ",\"value\":" + value.ToString(CultureInfo.InvariantCulture));
		}

		public static RewriteRule RemapScript(string assembly, string script, string toAssembly, string toScript)
		{
			return new RewriteRule(assembly, script, "\"remap\":{\"assembly\":" + Str(toAssembly) + ",\"script\":" + Str(toScript) + "}");
		}

		internal static string? ToJson(IReadOnlyList<RewriteRule> rules)
		{
			if (rules.Count == 0)
			{
				return null;
			}
			return "[" + string.Join(",", rules.Select((RewriteRule rule) => rule.json)) + "]";
		}

		private static string Str(string s)
		{
			return "\"" + s.Replace("\\", "\\\\").Replace("\"", "\\\"") + "\"";
		}
	}
	public abstract class RepackMode
	{
		public sealed class SceneBundle : RepackMode
		{
			public bool DisableRoots { get; set; }

			internal override RepackOptions ToOptions(Compression compression)
			{
				return new RepackOptions
				{
					mode = 0,
					compression = (byte)compression,
					disable_roots = DisableRoots
				};
			}
		}

		public sealed class AssetBundle : RepackMode
		{
			public bool DisableRoots { get; set; }

			public bool WriteTypetrees { get; set; }

			public bool EmitCatalog { get; set; }

			public IReadOnlyList<RewriteRule> RewriteRules { get; set; } = Array.Empty<RewriteRule>();

			internal override RepackOptions ToOptions(Compression compression)
			{
				return new RepackOptions
				{
					mode = 1,
					compression = (byte)compression,
					disable_roots = DisableRoots,
					write_typetrees = WriteTypetrees,
					emit_catalog = EmitCatalog
				};
			}
		}

		public sealed class ShallowAssetBundle : RepackMode
		{
			internal override RepackOptions ToOptions(Compression compression)
			{
				return new RepackOptions
				{
					mode = 2,
					compression = (byte)compression
				};
			}
		}

		private RepackMode()
		{
		}

		internal abstract RepackOptions ToOptions(Compression compression);
	}
	public sealed class RepackStats(int objectsBefore, int objectsAfter)
	{
		public int ObjectsBefore { get; } = objectsBefore;

		public int ObjectsAfter { get; } = objectsAfter;
	}
	public sealed class RepackResult(byte[] bundle, byte[]? catalog, string[] dependencyFiles, RepackStats stats)
	{
		public byte[] Bundle { get; } = bundle;

		public byte[]? Catalog { get; } = catalog;

		public string[] DependencyFiles { get; } = dependencyFiles;

		public RepackStats Stats { get; } = stats;
	}
	public sealed class GameRepacker : IDisposable
	{
		private unsafe Game* game;

		public static uint FormatVersion => NativeMethods.format_version();

		public unsafe GameRepacker(string gameDir)
		{
			byte* error = null;
			fixed (byte* game_dir = Utf8(gameDir))
			{
				game = NativeMethods.game_open(game_dir, &error);
			}
			ThrowIfError(error);
		}

		public unsafe RepackResult Repack(string name, string objectsJson, RepackMode mode, Compression compression = Compression.Lz4)
		{
			Game* intPtr = Handle();
			RepackOptions repackOptions = mode.ToOptions(compression);
			string? value = ((mode is RepackMode.AssetBundle assetBundle) ? RewriteRule.ToJson(assetBundle.RewriteRules) : null);
			byte* error = null;
			CStats cStats = default(CStats);
			int size = default(int);
			byte* data = default(byte*);
			int size2 = default(int);
			byte* ptr = default(byte*);
			byte* ptr2 = default(byte*);
			fixed (byte* name2 = Utf8(name))
			{
				fixed (byte* objects_json = Utf8(objectsJson))
				{
					fixed (byte* rewrite_rules = Utf8OrNull(value))
					{
						repackOptions.rewrite_rules = rewrite_rules;
						NativeMethods.repack(intPtr, name2, objects_json, &repackOptions, &error, &cStats, &size, &data, &size2, &ptr, &ptr2);
					}
				}
			}
			ThrowIfError(error);
			byte[] bundle = TakeArray(size, data);
			byte[] catalog = ((ptr == null) ? null : TakeArray(size2, ptr));
			string[] dependencyFiles = ((ptr2 == null) ? Array.Empty<string>() : TakeString(ptr2).Split(new char[1] { '\n' }, StringSplitOptions.RemoveEmptyEntries));
			return new RepackResult(bundle, catalog, dependencyFiles, new RepackStats(cStats.objects_before, cStats.objects_after));
		}

		public unsafe byte[] BuildDependencyFileBundle(string file, Compression compression = Compression.Lz4, IReadOnlyList<RewriteRule>? rewriteRules = null)
		{
			Game* intPtr = Handle();
			byte* error = null;
			int size = default(int);
			byte* data = default(byte*);
			fixed (byte* file2 = Utf8(file))
			{
				fixed (byte* rewrite_rules = Utf8OrNull(RewriteRule.ToJson(rewriteRules ?? Array.Empty<RewriteRule>())))
				{
					NativeMethods.dependency_file_bundle(intPtr, file2, (byte)compression, rewrite_rules, &error, &size, &data);
				}
			}
			ThrowIfError(error);
			return TakeArray(size, data);
		}

		private unsafe Game* Handle()
		{
			if (game == null)
			{
				throw new ObjectDisposedException("GameRepacker");
			}
			return game;
		}

		internal unsafe static string GameFingerprint(string gameDir)
		{
			byte* error = null;
			byte* str;
			fixed (byte* game_dir = Utf8(gameDir))
			{
				str = NativeMethods.game_fingerprint(game_dir, &error);
			}
			ThrowIfError(error);
			return TakeString(str);
		}

		public void Dispose()
		{
			Free();
			GC.SuppressFinalize(this);
		}

		~GameRepacker()
		{
			Free();
		}

		private unsafe void Free()
		{
			if (game != null)
			{
				NativeMethods.game_free(game);
				game = null;
			}
		}

		private static byte[] Utf8(string value)
		{
			return Encoding.UTF8.GetBytes(value + "\0");
		}

		private static byte[]? Utf8OrNull(string? value)
		{
			if (value != null)
			{
				return Utf8(value);
			}
			return null;
		}

		private unsafe static byte[] TakeArray(int size, byte* data)
		{
			byte[] array = new byte[size];
			Marshal.Copy((IntPtr)data, array, 0, size);
			NativeMethods.free_array(size, data);
			return array;
		}

		private unsafe static string TakeString(byte* str)
		{
			int i;
			for (i = 0; str[i] != 0; i++)
			{
			}
			string result = Encoding.UTF8.GetString(str, i);
			NativeMethods.free_str(str);
			return result;
		}

		private unsafe static void ThrowIfError(byte* error)
		{
			if (error == null)
			{
				return;
			}
			throw new RepackException(TakeString(error));
		}
	}
	internal static class NativeMethods
	{
		private const string __DllName = "unityscenerepacker";

		[DllImport("unityscenerepacker", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
		internal unsafe static extern Game* game_open(byte* game_dir, byte** error);

		[DllImport("unityscenerepacker", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
		internal unsafe static extern void game_free(Game* game);

		[DllImport("unityscenerepacker", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
		internal unsafe static extern void repack(Game* game, byte* name, byte* objects_json, RepackOptions* options, byte** error, CStats* stats, int* bundle_size, byte** bundle_data, int* catalog_size, byte** catalog_data, byte** dependencies);

		[DllImport("unityscenerepacker", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
		internal unsafe static extern void dependency_file_bundle(Game* game, byte* file, byte compression, byte* rewrite_rules, byte** error, int* bundle_size, byte** bundle_data);

		[DllImport("unityscenerepacker", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
		internal unsafe static extern byte* game_fingerprint(byte* game_dir, byte** error);

		[DllImport("unityscenerepacker", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
		internal static extern uint format_version();

		[DllImport("unityscenerepacker", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
		internal unsafe static extern void free_str(byte* cstr);

		[DllImport("unityscenerepacker", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
		internal unsafe static extern void free_array(int len, byte* data);
	}
	internal struct CStats
	{
		public int objects_before;

		public int objects_after;
	}
	internal struct Game
	{
	}
	internal struct RepackOptions
	{
		public byte mode;

		public byte compression;

		[MarshalAs(UnmanagedType.U1)]
		public bool disable_roots;

		[MarshalAs(UnmanagedType.U1)]
		public bool write_typetrees;

		[MarshalAs(UnmanagedType.U1)]
		public bool emit_catalog;

		public unsafe byte* rewrite_rules;
	}
}

UnitySceneRepacker.Plugin.dll

Decompiled 9 hours ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Logging;
using JetBrains.Annotations;
using Microsoft.CodeAnalysis;
using UnityEngine;
using UnitySceneRepacker.Source;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("UnitySceneRepacker.Plugin")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("0.2.0.0")]
[assembly: AssemblyInformationalVersion("0.2.0+3aafa3af894438010e4bd342a75fedb273afaa14")]
[assembly: AssemblyProduct("UnitySceneRepacker.Plugin")]
[assembly: AssemblyTitle("UnitySceneRepacker")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/jakobhellermann/UnitySceneRepacker")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("0.2.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
[DebuggerDisplay("Count = {System.Collections.ICollection.Count}")]
[CompilerGenerated]
internal sealed class <>z__ReadOnlyArray<T> : IEnumerable, ICollection, IList, IEnumerable<T>, IReadOnlyCollection<T>, IReadOnlyList<T>, ICollection<T>, IList<T>
{
	int ICollection.Count => _items.Length;

	bool ICollection.IsSynchronized => false;

	object ICollection.SyncRoot => this;

	object IList.this[int index]
	{
		get
		{
			return _items[index];
		}
		set
		{
			throw new NotSupportedException();
		}
	}

	bool IList.IsFixedSize => true;

	bool IList.IsReadOnly => true;

	int IReadOnlyCollection<T>.Count => _items.Length;

	T IReadOnlyList<T>.this[int index] => _items[index];

	int ICollection<T>.Count => _items.Length;

	bool ICollection<T>.IsReadOnly => true;

	T IList<T>.this[int index]
	{
		get
		{
			return _items[index];
		}
		set
		{
			throw new NotSupportedException();
		}
	}

	public <>z__ReadOnlyArray(T[] items)
	{
		_items = items;
	}

	IEnumerator IEnumerable.GetEnumerator()
	{
		return ((IEnumerable)_items).GetEnumerator();
	}

	void ICollection.CopyTo(Array array, int index)
	{
		((ICollection)_items).CopyTo(array, index);
	}

	int IList.Add(object value)
	{
		throw new NotSupportedException();
	}

	void IList.Clear()
	{
		throw new NotSupportedException();
	}

	bool IList.Contains(object value)
	{
		return ((IList)_items).Contains(value);
	}

	int IList.IndexOf(object value)
	{
		return ((IList)_items).IndexOf(value);
	}

	void IList.Insert(int index, object value)
	{
		throw new NotSupportedException();
	}

	void IList.Remove(object value)
	{
		throw new NotSupportedException();
	}

	void IList.RemoveAt(int index)
	{
		throw new NotSupportedException();
	}

	IEnumerator<T> IEnumerable<T>.GetEnumerator()
	{
		return ((IEnumerable<T>)_items).GetEnumerator();
	}

	void ICollection<T>.Add(T item)
	{
		throw new NotSupportedException();
	}

	void ICollection<T>.Clear()
	{
		throw new NotSupportedException();
	}

	bool ICollection<T>.Contains(T item)
	{
		return ((ICollection<T>)_items).Contains(item);
	}

	void ICollection<T>.CopyTo(T[] array, int arrayIndex)
	{
		((ICollection<T>)_items).CopyTo(array, arrayIndex);
	}

	bool ICollection<T>.Remove(T item)
	{
		throw new NotSupportedException();
	}

	int IList<T>.IndexOf(T item)
	{
		return ((IList<T>)_items).IndexOf(item);
	}

	void IList<T>.Insert(int index, T item)
	{
		throw new NotSupportedException();
	}

	void IList<T>.RemoveAt(int index)
	{
		throw new NotSupportedException();
	}
}
[DebuggerDisplay("Count = {System.Collections.ICollection.Count}")]
[CompilerGenerated]
internal sealed class <>z__ReadOnlyList<T> : IEnumerable, ICollection, IList, IEnumerable<T>, IReadOnlyCollection<T>, IReadOnlyList<T>, ICollection<T>, IList<T>
{
	int ICollection.Count => _items.Count;

	bool ICollection.IsSynchronized => false;

	object ICollection.SyncRoot => this;

	object IList.this[int index]
	{
		get
		{
			return _items[index];
		}
		set
		{
			throw new NotSupportedException();
		}
	}

	bool IList.IsFixedSize => true;

	bool IList.IsReadOnly => true;

	int IReadOnlyCollection<T>.Count => _items.Count;

	T IReadOnlyList<T>.this[int index] => _items[index];

	int ICollection<T>.Count => _items.Count;

	bool ICollection<T>.IsReadOnly => true;

	T IList<T>.this[int index]
	{
		get
		{
			return _items[index];
		}
		set
		{
			throw new NotSupportedException();
		}
	}

	public <>z__ReadOnlyList(List<T> items)
	{
		_items = items;
	}

	IEnumerator IEnumerable.GetEnumerator()
	{
		return ((IEnumerable)_items).GetEnumerator();
	}

	void ICollection.CopyTo(Array array, int index)
	{
		((ICollection)_items).CopyTo(array, index);
	}

	int IList.Add(object value)
	{
		throw new NotSupportedException();
	}

	void IList.Clear()
	{
		throw new NotSupportedException();
	}

	bool IList.Contains(object value)
	{
		return ((IList)_items).Contains(value);
	}

	int IList.IndexOf(object value)
	{
		return ((IList)_items).IndexOf(value);
	}

	void IList.Insert(int index, object value)
	{
		throw new NotSupportedException();
	}

	void IList.Remove(object value)
	{
		throw new NotSupportedException();
	}

	void IList.RemoveAt(int index)
	{
		throw new NotSupportedException();
	}

	IEnumerator<T> IEnumerable<T>.GetEnumerator()
	{
		return ((IEnumerable<T>)_items).GetEnumerator();
	}

	void ICollection<T>.Add(T item)
	{
		throw new NotSupportedException();
	}

	void ICollection<T>.Clear()
	{
		throw new NotSupportedException();
	}

	bool ICollection<T>.Contains(T item)
	{
		return _items.Contains(item);
	}

	void ICollection<T>.CopyTo(T[] array, int arrayIndex)
	{
		_items.CopyTo(array, arrayIndex);
	}

	bool ICollection<T>.Remove(T item)
	{
		throw new NotSupportedException();
	}

	int IList<T>.IndexOf(T item)
	{
		return _items.IndexOf(item);
	}

	void IList<T>.Insert(int index, T item)
	{
		throw new NotSupportedException();
	}

	void IList<T>.RemoveAt(int index)
	{
		throw new NotSupportedException();
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace BepInEx
{
	[AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = false)]
	[Conditional("CodeGeneration")]
	[Embedded]
	internal sealed class BepInAutoPluginAttribute : Attribute
	{
		public BepInAutoPluginAttribute(string? id = null, string? name = null, string? version = null)
		{
		}
	}
}
namespace BepInEx.Preloader.Core.Patching
{
	[AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = false)]
	[Conditional("CodeGeneration")]
	[Embedded]
	internal sealed class PatcherAutoPluginAttribute : Attribute
	{
		public PatcherAutoPluginAttribute(string? id = null, string? name = null, string? version = null)
		{
		}
	}
}
namespace Microsoft.CodeAnalysis
{
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace UnitySceneRepacker
{
	[BepInPlugin("io.github.jakobhellermann.unityscenerepacker", "UnitySceneRepacker", "0.2.0")]
	public class UnitySceneRepackerPlugin : BaseUnityPlugin
	{
		private static readonly IReadOnlyList<RewriteRule> playMakerRules = new <>z__ReadOnlyArray<RewriteRule>((RewriteRule[])(object)new RewriteRule[2]
		{
			RewriteRule.SetField("PlayMaker", "PlayMakerFSM", "fsm.preprocessed", false),
			RewriteRule.SetField("PlayMaker", "PlayMakerFSM", "eventHandlerComponentsAdded", false)
		});

		private static readonly SortedDictionary<(string assembly, string script), (string assembly, string script)> remaps = new SortedDictionary<(string, string), (string, string)>();

		private static IReadOnlyList<RewriteRule>? rewriteRules;

		public const string Id = "io.github.jakobhellermann.unityscenerepacker";

		public static string CacheDir { get; } = Path.Combine(Paths.CachePath, "unity-scene-repacker");

		public static string Name => "UnitySceneRepacker";

		public static string Version => "0.2.0";

		public static RepackedAssets RepackedAssets(string gameDir, string name)
		{
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Expected O, but got Unknown
			return new RepackedAssets(gameDir, GameCacheDir(gameDir), name, (Func<IReadOnlyList<RewriteRule>>)RewriteRules);
		}

		public static void RemapScript(string assembly, string script, string toAssembly, string toScript)
		{
			if (remaps.TryGetValue((assembly, script), out (string, string) value))
			{
				(string, string) tuple = value;
				if (tuple.Item1 != toAssembly || tuple.Item2 != toScript)
				{
					throw new InvalidOperationException(assembly + ":" + script + " is already remapped to " + value.Item1 + ":" + value.Item2 + ", not " + toAssembly + ":" + toScript);
				}
			}
			else
			{
				if (rewriteRules != null)
				{
					throw new InvalidOperationException("can't remap " + assembly + ":" + script + " after assets were prepared or loaded, remap in Awake instead");
				}
				remaps[(assembly, script)] = (toAssembly, toScript);
			}
		}

		public static void RemapScript(string assembly, string script, Type to)
		{
			if (!typeof(MonoBehaviour).IsAssignableFrom(to))
			{
				throw new ArgumentException($"{to} is not a MonoBehaviour", "to");
			}
			if (to.IsNested)
			{
				throw new ArgumentException($"{to} is nested in {to.DeclaringType}", "to");
			}
			RemapScript(assembly, script, to.Assembly.GetName().Name, to.FullName);
		}

		private static IReadOnlyList<RewriteRule> RewriteRules()
		{
			IReadOnlyList<RewriteRule>? readOnlyList = rewriteRules;
			if (readOnlyList == null)
			{
				List<RewriteRule> list = new List<RewriteRule>();
				list.AddRange(playMakerRules);
				list.AddRange(remaps.Select<KeyValuePair<(string, string), (string, string)>, RewriteRule>((KeyValuePair<(string assembly, string script), (string assembly, string script)> remap) => RewriteRule.RemapScript(remap.Key.assembly, remap.Key.script, remap.Value.assembly, remap.Value.script)));
				readOnlyList = (rewriteRules = new <>z__ReadOnlyList<RewriteRule>(list));
			}
			return readOnlyList;
		}

		private static string GameCacheDir(string gameDir)
		{
			gameDir = Path.GetFullPath(gameDir).TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
			return Path.Combine(CacheDir, $"{Path.GetFileName(gameDir)}-{StableHash(gameDir):x8}");
		}

		private static uint StableHash(string s)
		{
			uint num = 2166136261u;
			foreach (char c in s)
			{
				num = (num ^ c) * 16777619;
			}
			return num;
		}

		public static string NextToThisGame(string installDirName)
		{
			string directoryName = Path.GetDirectoryName(Application.dataPath);
			if (directoryName.EndsWith(".app", StringComparison.OrdinalIgnoreCase))
			{
				directoryName = Path.GetDirectoryName(directoryName);
			}
			return Path.Combine(Path.GetDirectoryName(directoryName), installDirName);
		}

		private void Awake()
		{
			Log.Init(((BaseUnityPlugin)this).Logger);
			Assembly assembly = typeof(GameRepacker).Assembly;
			Log.Info($"Plugin has loaded {assembly.GetName().Name} {assembly.GetName().Version} (format version {GameRepacker.FormatVersion})");
		}
	}
}
namespace UnitySceneRepacker.Source
{
	[PublicAPI]
	internal static class Log
	{
		private static ManualLogSource? logSource;

		internal static void Init(ManualLogSource logSource)
		{
			Log.logSource = logSource;
		}

		internal static void Debug(object data)
		{
			ManualLogSource? obj = logSource;
			if (obj != null)
			{
				obj.LogDebug(data);
			}
		}

		internal static void Error(object data)
		{
			ManualLogSource? obj = logSource;
			if (obj != null)
			{
				obj.LogError(data);
			}
		}

		internal static void Fatal(object data)
		{
			ManualLogSource? obj = logSource;
			if (obj != null)
			{
				obj.LogFatal(data);
			}
		}

		internal static void Info(object data)
		{
			ManualLogSource? obj = logSource;
			if (obj != null)
			{
				obj.LogInfo(data);
			}
		}

		internal static void Message(object data)
		{
			ManualLogSource? obj = logSource;
			if (obj != null)
			{
				obj.LogMessage(data);
			}
		}

		internal static void Warning(object data)
		{
			ManualLogSource? obj = logSource;
			if (obj != null)
			{
				obj.LogWarning(data);
			}
		}
	}
}