Compare commits

..
Author SHA1 Message Date
Pietro420 fecdd9f4f7 optimization and caching
most of the caching stuff here can likely be removed
2026-04-15 22:13:26 -03:00
23 changed files with 1000 additions and 138 deletions

No files matched your search

+2 -2
View File
@@ -1,8 +1,8 @@
<Project>
<ItemGroup>
<PackageReference Include="Reactor" Version="2.5.0-ci.371" />
<PackageReference Include="Reactor" Version="2.3.1" />
<PackageReference Include="BepInEx.Unity.IL2CPP" Version="6.0.0-be.735" Private="false" ExcludeAssets="runtime;native" />
<PackageReference Include="AmongUs.GameLibs.Steam" Version="2026.3.31" PrivateAssets="all" />
<PackageReference Include="AmongUs.GameLibs.Steam" Version="2025.10.14" PrivateAssets="all" />
<PackageReference Include="BepInEx.AutoPlugin" Version="1.1.0" PrivateAssets="all" />
<PackageReference Include="BepInEx.IL2CPP.MSBuild" Version="2.1.0-rc.1" PrivateAssets="all" ExcludeAssets="runtime" />
+1 -1
View File
@@ -8,7 +8,7 @@
<RestorePackagesWithLockFile>true</RestorePackagesWithLockFile>
<VersionPrefix>0.4.0</VersionPrefix>
<VersionPrefix>0.3.8</VersionPrefix>
<VersionSuffix>dev</VersionSuffix>
<Authors>All Of Us, XtraCube, Angxl</Authors>
+24 -6
View File
@@ -21,6 +21,8 @@ namespace MiraAPI.GameOptions;
public static class ModdedOptionsManager
{
private static readonly Dictionary<PropertyInfo, ModdedOptionAttribute> OptionAttributes = [];
private static readonly Dictionary<MethodBase, ModdedOptionAttribute> SetterAttributes = [];
private static readonly Dictionary<MethodBase, ModdedOptionAttribute> GetterAttributes = [];
private static readonly Dictionary<Type, AbstractOptionGroup> TypeToGroup = [];
internal static readonly Dictionary<OptionBehaviour, ModdedPlayerOption> CreatedPlayerOptions = [];
@@ -100,12 +102,20 @@ public static class ModdedOptionsManager
}
var setterOriginal = property.GetSetMethod();
var setterPatch = typeof(ModdedOptionsManager).GetMethod(nameof(PropertySetterPatch));
PluginSingleton<MiraApiPlugin>.Instance.Harmony.Patch(setterOriginal, postfix: new HarmonyMethod(setterPatch));
if (setterOriginal != null)
{
var setterPatch = typeof(ModdedOptionsManager).GetMethod(nameof(PropertySetterPatch));
PluginSingleton<MiraApiPlugin>.Instance.Harmony.Patch(setterOriginal, postfix: new HarmonyMethod(setterPatch));
SetterAttributes[setterOriginal] = attribute;
}
var getterOriginal = property.GetGetMethod();
var getterPatch = typeof(ModdedOptionsManager).GetMethod(nameof(PropertyGetterPatch));
PluginSingleton<MiraApiPlugin>.Instance.Harmony.Patch(getterOriginal, prefix: new HarmonyMethod(getterPatch));
if (getterOriginal != null)
{
var getterPatch = typeof(ModdedOptionsManager).GetMethod(nameof(PropertyGetterPatch));
PluginSingleton<MiraApiPlugin>.Instance.Harmony.Patch(getterOriginal, prefix: new HarmonyMethod(getterPatch));
GetterAttributes[getterOriginal] = attribute;
}
OptionAttributes.Add(property, attribute);
attribute.HolderOption = option;
@@ -183,7 +193,11 @@ public static class ModdedOptionsManager
public static void PropertySetterPatch(MethodBase __originalMethod, object value)
#pragma warning restore CA1707
{
var attribute = OptionAttributes.First(pair => pair.Key.GetSetMethod() == __originalMethod).Value;
if (!SetterAttributes.TryGetValue(__originalMethod, out var attribute))
{
return;
}
attribute.SetValue(value);
}
@@ -198,7 +212,11 @@ public static class ModdedOptionsManager
public static bool PropertyGetterPatch(MethodBase __originalMethod, ref object __result)
#pragma warning restore CA1707
{
var attribute = OptionAttributes.First(pair => pair.Key.GetGetMethod() == __originalMethod).Value;
if (!GetterAttributes.TryGetValue(__originalMethod, out var attribute))
{
return true;
}
__result = attribute.GetValue();
return false;
}
+1 -12
View File
@@ -93,21 +93,11 @@ public static class CustomMurderRpc
beforeMurderEvent.Cancel();
}
if (target.ProtectedByGa())
{
beforeMurderEvent.Cancel();
murderResultFlags = MurderResultFlags.FailedProtected;
}
else if (beforeMurderEvent.IsCancelled)
if (beforeMurderEvent.IsCancelled)
{
murderResultFlags = MurderResultFlags.FailedError;
}
if (beforeMurderEvent.IsCancelled && source.AmOwner)
{
source.isKilling = true;
}
if (!PlayerControl.LocalPlayer.IsHost())
{
return;
@@ -151,7 +141,6 @@ public static class CustomMurderRpc
{
if (LobbyBehaviour.Instance || !host.IsHost() || target.Data.IsDead || target.Data.Disconnected)
{
source.isKilling = false;
return;
}
+6 -6
View File
@@ -52,7 +52,12 @@ public static class HudManagerPatches
continue;
}
if (aspect.gameObject.name.Contains("TopRight"))
if (aspect.gameObject.transform.parent.name == "TopRight")
{
continue;
}
if (aspect.gameObject.transform.parent.transform.parent.name == "TopRight")
{
continue;
}
@@ -84,11 +89,6 @@ public static class HudManagerPatches
continue;
}
if (arrange.gameObject.name.Contains("TopRight"))
{
continue;
}
arrange.gameObject.SetActive(!arrange.isActiveAndEnabled);
arrange.CellSize = new Vector2(scaleFactor, scaleFactor);
arrange.gameObject.SetActive(!arrange.isActiveAndEnabled);
@@ -16,15 +16,8 @@ public static class OptionsMenuBehaviourPatch
private static void OpenPostfix(OptionsMenuBehaviour __instance)
{
_remap_rollover = GameObject.Find("Remap Controls")?.GetComponent<ButtonRolloverHandler>()!;
try
{
_remap_background = _remap_rollover.transform.FindChild("Background").GetComponent<SpriteRenderer>();
_remap_background.color = _conflicts ? Color.red : Color.white;
}
catch
{
// ignored, this normally breaks when on mobile since there's no remap button screen.
}
_remap_background = _remap_rollover.transform.FindChild("Background").GetComponent<SpriteRenderer>();
_remap_background.color = _conflicts ? Color.red : Color.white;
}
[HarmonyPostfix]
+163
View File
@@ -0,0 +1,163 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using AmongUs.Data;
using HarmonyLib;
using MiraAPI.Utilities;
using MiraAPI.Utilities.Assets;
using Reactor.Utilities;
using Reactor.Utilities.Extensions;
using TMPro;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;
using Object = UnityEngine.Object;
namespace MiraAPI.Patches.Menu;
[HarmonyPatch(typeof(HatsTab))]
public static class HatsTabPatches
{
private static SortedList<string, List<HatData>> sortedHats = [];
private static int currentPage;
private static void PreviousPage(HatsTab hatsTab)
{
currentPage--;
currentPage = currentPage < 0 ? sortedHats.Count - 1 : currentPage;
GenerateHats(hatsTab, currentPage);
}
private static void NextPage(HatsTab hatsTab)
{
currentPage++;
currentPage = currentPage > sortedHats.Count - 1 ? 0 : currentPage;
GenerateHats(hatsTab, currentPage);
}
[HarmonyPatch(nameof(HatsTab.OnEnable))]
[HarmonyPrefix]
public static bool OnEnablePrefix(HatsTab __instance)
{
__instance.currentHat = HatManager.Instance.GetHatById(DataManager.Player.Customization.Hat);
var allHats = HatManager.Instance.GetUnlockedHats().ToImmutableList();
if (sortedHats.Count == 0)
{
var comparer = new ControllableComparer<string>(["vanilla"], [], StringComparer.InvariantCulture);
sortedHats = new SortedList<string, List<HatData>>(comparer);
foreach (var hat in allHats)
{
if (!sortedHats.ContainsKey(hat.StoreName)) sortedHats[hat.StoreName] = [];
sortedHats[hat.StoreName].Add(hat);
}
}
InventoryUtility.CreateNextBackButtons(__instance, PreviousPage, NextPage);
GenerateHats(__instance, currentPage);
return false;
}
[HarmonyPatch(typeof(HatsTab), nameof(HatsTab.Update))]
[HarmonyPrefix]
public static void UpdatePrefix(HatsTab __instance)
{
if (sortedHats.Count == 0) return;
if (Input.GetKeyDown(KeyCode.LeftControl) || Input.GetKeyDown(KeyCode.RightControl) || Input.GetKeyDown(KeyCode.LeftArrow))
{
PreviousPage(__instance);
}
else if (Input.GetKeyDown(KeyCode.Tab) || Input.GetKeyDown(KeyCode.RightArrow))
{
NextPage(__instance);
}
}
private static IEnumerator? loadRoutine;
private static int hatIndex;
private static void GenerateHats(HatsTab __instance, int page)
{
if (loadRoutine != null) Coroutines.Stop(loadRoutine);
hatIndex = 0;
foreach (var instanceColorChip in __instance.ColorChips) instanceColorChip.gameObject.Destroy();
__instance.ColorChips.Clear();
__instance.scroller.Inner.GetComponentsInChildren<TextMeshPro>().Do(x => x.gameObject.Destroy());
var groupNameText = __instance.GetComponentInChildren<TextMeshPro>(false);
var (groupName, hats) = sortedHats.ToArray()[page];
var text = Object.Instantiate(groupNameText, __instance.scroller.Inner);
text.enabled = true;
text.gameObject.transform.localScale = Vector3.one;
text.GetComponent<TextTranslatorTMP>().Destroy();
text.EnableStencilMasking();
text.text = $"{groupName} ({currentPage + 1}/{sortedHats.Count})";
text.alignment = TextAlignmentOptions.Center;
text.fontSize = 5f;
text.fontSizeMax = 5f;
text.fontSizeMin = 0f;
var xLerp = __instance.XRange.Lerp(0.5f);
var yLerp = __instance.YStart - hatIndex / __instance.NumPerRow * __instance.YOffset;
text.transform.localPosition = new Vector3(xLerp, yLerp, -1f);
hatIndex += 5;
loadRoutine = Coroutines.Start(CoGenerateChips(__instance, hats));
}
private static IEnumerator CoGenerateChips(HatsTab __instance, List<HatData> hats)
{
__instance.scroller.ScrollToTop();
var batchSize = 5;
for (var i = 0; i < hats.Count; i += batchSize)
{
var batch = hats.Skip(i).Take(batchSize).ToList();
foreach (var hat in batch.OrderBy(HatManager.Instance.allHats.IndexOf))
{
var hatXposition = __instance.XRange.Lerp(hatIndex % __instance.NumPerRow / (__instance.NumPerRow - 1f));
var hatYposition = __instance.YStart - hatIndex / __instance.NumPerRow * __instance.YOffset;
GenerateColorChip(__instance, new Vector2(hatXposition, hatYposition), hat);
hatIndex += 1;
yield return null;
}
__instance.SetScrollerBounds();
yield return new WaitForSeconds(0.01f);
}
__instance.currentHatIsEquipped = true;
loadRoutine = null;
}
private static void GenerateColorChip(HatsTab __instance, Vector2 position, HatData hat)
{
var colorChip = Object.Instantiate(__instance.ColorTabPrefab, __instance.scroller.Inner);
colorChip.gameObject.name = hat.ProductId;
if (ActiveInputManager.currentControlType == ActiveInputManager.InputType.Keyboard)
{
colorChip.Button.OnClick.AddListener((Action)__instance.ClickEquip);
colorChip.Button.OnMouseOver.AddListener((Action)(() => __instance.SelectHat(hat)));
colorChip.Button.OnMouseOut.AddListener((Action)(() => __instance.SelectHat(HatManager.Instance.GetHatById(DataManager.Player.Customization.Hat))));
}
else
{
colorChip.Button.OnClick.AddListener((Action)(() => __instance.SelectHat(hat)));
}
colorChip.Inner.SetHat(hat, __instance.HasLocalPlayer() ? PlayerControl.LocalPlayer.Data.DefaultOutfit.ColorId : DataManager.Player.Customization.Color);
colorChip.Button.ClickMask = __instance.scroller.Hitbox;
colorChip.SelectionHighlight.gameObject.SetActive(false);
__instance.UpdateMaterials(colorChip.Inner.FrontLayer, hat);
colorChip.Inner.SetMaskType(PlayerMaterial.MaskType.SimpleUI);
colorChip.transform.localPosition = new Vector3(position.x, position.y, -1f);
colorChip.Inner.transform.localPosition = hat.ChipOffset + new Vector2(0f, -0.3f);
colorChip.Tag = hat;
__instance.ColorChips.Add(colorChip);
}
}
+54
View File
@@ -0,0 +1,54 @@
using System;
using MiraAPI.Utilities.Assets;
using TMPro;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;
using Object = UnityEngine.Object;
namespace MiraAPI.Patches.Menu;
public static class InventoryUtility
{
public static void CreateNextBackButtons<T>(T tab, Action<T> previousPage, Action<T> nextPage) where T : InventoryTab
{
var title = tab.transform.FindChild("Text");
title.localPosition = new Vector3(.9123f, -.23f, -55);
title.GetComponent<TextMeshPro>().alignment = TextAlignmentOptions.Center;
tab.scroller.Hitbox.transform.localScale -= new Vector3(0, 0.1f, 0);
tab.scroller.Hitbox.transform.localPosition -= new Vector3(0, 0.1f, 0);
var leftButtonElement = Object.Instantiate(PlayerCustomizationMenu.Instance.BackButton.gameObject, tab.transform);
var leftSpriteRenderer = leftButtonElement.GetComponent<SpriteRenderer>();
var leftButton = leftButtonElement.GetComponent<PassiveButton>();
leftButtonElement.transform.localPosition = new Vector3(-1.1f, -0.2f, -55);
leftSpriteRenderer.sprite = MiraAssets.NextButton.LoadAsset();
leftSpriteRenderer.flipX = true;
leftButton.OnMouseOver = new UnityEvent();
leftButton.OnMouseOver.AddListener((Action)(() => leftSpriteRenderer.sprite = MiraAssets.NextButtonActive.LoadAsset()));
leftButton.OnMouseOut = new UnityEvent();
leftButton.OnMouseOut.AddListener((Action)(() => leftSpriteRenderer.sprite = MiraAssets.NextButton.LoadAsset()));
leftButton.OnClick = new Button.ButtonClickedEvent();
leftButton.OnClick.AddListener((Action)(() => previousPage(tab)));
var rightButtonElement = Object.Instantiate(leftButtonElement, tab.transform);
var rightSpriteRenderer = rightButtonElement.GetComponent<SpriteRenderer>();
var rightButton = rightButtonElement.GetComponent<PassiveButton>();
rightButtonElement.transform.localPosition = new Vector3(2.8f, -0.2f, -55);
rightSpriteRenderer.sprite = MiraAssets.NextButton.LoadAsset();
rightSpriteRenderer.flipX = false;
rightButton.OnMouseOver = new UnityEvent();
rightButton.OnMouseOver.AddListener((Action)(() => rightSpriteRenderer.sprite = MiraAssets.NextButtonActive.LoadAsset()));
rightButton.OnMouseOut = new UnityEvent();
rightButton.OnMouseOut.AddListener((Action)(() => rightSpriteRenderer.sprite = MiraAssets.NextButton.LoadAsset()));
rightButton.OnClick = new Button.ButtonClickedEvent();
rightButton.OnClick.AddListener((Action)(() => nextPage(tab)));
}
}
+2 -11
View File
@@ -1,8 +1,6 @@
using System.Collections;
using HarmonyLib;
using HarmonyLib;
using MiraAPI.LocalSettings;
using MiraAPI.Utilities.Assets;
using Reactor.Utilities;
using UnityEngine;
namespace MiraAPI.Patches.Menu;
@@ -20,14 +18,7 @@ public static class MainMenuManagerPatches
[HarmonyPostfix]
public static void AwakePostfix()
{
Coroutines.Start(SetFps());
}
private static IEnumerator SetFps()
{
Application.targetFrameRate = (int)LocalSettingsTabSingleton<MiraApiSettings>.Instance.SetFpsSlider.Value;
yield return new WaitForSeconds(1f);
AddressablesLoader.LoadAll();
Application.targetFrameRate = (int)LocalSettingsTabSingleton<MiraApiSettings>.Instance.SetFpsSlider.Value;
}
}
@@ -0,0 +1,142 @@
using AmongUs.Data;
using HarmonyLib;
using Innersloth.Assets;
using MiraAPI.Utilities;
using Reactor.Utilities.Extensions;
using System;
using System.Collections.Generic;
using System.Linq;
using TMPro;
using UnityEngine;
using Object = UnityEngine.Object;
namespace MiraAPI.Patches.Menu;
[HarmonyPatch(typeof(NameplatesTab))]
public static class NameplatesTabPatches
{
private static readonly SortedList<string, List<NamePlateData>> SortedNameplates = new(new ControllableComparer<string>(["vanilla"], [], StringComparer.InvariantCulture));
private static int currentPage;
internal static void AddRange(IEnumerable<(string Key, NamePlateData Visor)> data)
{
foreach (var item in data)
{
if (!SortedNameplates.ContainsKey(item.Key)) SortedNameplates.Add(item.Key, []);
SortedNameplates[item.Key].Add(item.Visor);
}
}
private static void PreviousPage(NameplatesTab tab)
{
currentPage--;
currentPage = currentPage < 0 ? SortedNameplates.Count - 1 : currentPage;
GenerateHats(tab, currentPage);
}
private static void NextPage(NameplatesTab tab)
{
currentPage++;
currentPage = currentPage > SortedNameplates.Count - 1 ? 0 : currentPage;
GenerateHats(tab, currentPage);
}
[HarmonyPatch(nameof(NameplatesTab.OnEnable))]
[HarmonyPrefix]
public static bool OnEnablePrefix(NameplatesTab __instance)
{
__instance.plateId = HatManager.Instance.GetNamePlateById(DataManager.Player.Customization.namePlate).ProdId;
if (!SortedNameplates.ContainsKey("Vanilla")) AddRange(DestroyableSingleton<HatManager>.Instance.GetUnlockedNamePlates().Select(x => ("Vanilla", x)));
InventoryUtility.CreateNextBackButtons(__instance, PreviousPage, NextPage);
GenerateHats(__instance, currentPage);
return false;
}
[HarmonyPatch(typeof(NameplatesTab), nameof(NameplatesTab.Update))]
[HarmonyPrefix]
public static void UpdatePrefix(NameplatesTab __instance)
{
if (Input.GetKeyDown(KeyCode.LeftControl) || Input.GetKeyDown(KeyCode.RightControl) || Input.GetKeyDown(KeyCode.LeftArrow))
{
PreviousPage(__instance);
}
else if (Input.GetKeyDown(KeyCode.Tab) || Input.GetKeyDown(KeyCode.RightArrow))
{
NextPage(__instance);
}
}
private static void GenerateHats(NameplatesTab __instance, int page)
{
foreach (ColorChip instanceColorChip in __instance.ColorChips) instanceColorChip.gameObject.Destroy();
__instance.ColorChips.Clear();
__instance.scroller.Inner.GetComponentsInChildren<TextMeshPro>().Do(x => x.gameObject.Destroy());
var groupNameText = __instance.GetComponentInChildren<TextMeshPro>(false);
int hatIndex = 0;
var (groupName, nameplates) = SortedNameplates.ToArray()[page];
var text = Object.Instantiate(groupNameText, __instance.scroller.Inner);
text.enabled = true;
text.gameObject.transform.localScale = Vector3.one;
text.GetComponent<TextTranslatorTMP>().Destroy();
text.EnableStencilMasking();
text.text = $"{groupName} ({currentPage + 1}/{SortedNameplates.Count})";
text.alignment = TextAlignmentOptions.Center;
text.fontSize = 5f;
text.fontSizeMax = 5f;
text.fontSizeMin = 0f;
float xLerp = __instance.XRange.Lerp(0.5f);
float yLerp = __instance.YStart - hatIndex / __instance.NumPerRow * __instance.YOffset;
text.transform.localPosition = new Vector3(xLerp, yLerp, -1f);
hatIndex += 2;
foreach (var visor in nameplates.OrderBy(HatManager.Instance.allNamePlates.IndexOf))
{
float hatXposition = __instance.XRange.Lerp(hatIndex % __instance.NumPerRow / (__instance.NumPerRow - 1f));
float hatYposition = __instance.YStart - hatIndex / __instance.NumPerRow * __instance.YOffset;
GenerateColorChip(__instance, new Vector2(hatXposition, hatYposition), visor);
hatIndex += 1;
}
__instance.SetScrollerBounds();
__instance.currentNameplateIsEquipped = true;
}
private static void GenerateColorChip(NameplatesTab __instance, Vector2 position, NamePlateData namePlate)
{
var colorChip = Object.Instantiate(__instance.ColorTabPrefab, __instance.scroller.Inner);
colorChip.gameObject.name = namePlate.ProductId;
if (ActiveInputManager.currentControlType == ActiveInputManager.InputType.Keyboard)
{
colorChip.Button.OnClick.AddListener((Action)__instance.ClickEquip);
colorChip.Button.OnMouseOver.AddListener((Action)(() => __instance.SelectNameplate(namePlate)));
colorChip.Button.OnMouseOut.AddListener(
(Action)(() => __instance.SelectNameplate(
HatManager.Instance.GetNamePlateById(DataManager.Player.Customization.NamePlate))));
}
else
{
colorChip.Button.OnClick.AddListener((Action)(() => __instance.SelectNameplate(namePlate)));
}
colorChip.Button.ClickMask = __instance.scroller.Hitbox;
colorChip.ProductId = namePlate.ProdId;
var x = (NamePlateViewData viewdata) =>
{
colorChip.transform.GetChild(1).GetComponent<SpriteRenderer>().sprite = viewdata?.Image;
// (colorChip as NameplateChip).image.sprite = viewdata?.Image;
};
__instance.StartCoroutine(AddressableAssetExtensions.CoLoadAssetAsync<NamePlateViewData>(__instance, namePlate.GetAssetReference(), x));
colorChip.transform.localPosition = new Vector3(position.x, position.y, -1f);
colorChip.Tag = namePlate;
__instance.ColorChips.Add(colorChip);
}
}
+139
View File
@@ -0,0 +1,139 @@
using AmongUs.Data;
using HarmonyLib;
using MiraAPI.Utilities;
using Reactor.Utilities.Extensions;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using TMPro;
using UnityEngine;
using Object = UnityEngine.Object;
namespace MiraAPI.Patches.Menu;
[HarmonyPatch(typeof(SkinsTab))]
public static class SkinsTabPatches
{
private static SortedList<string, List<SkinData>> sortedSkins = [];
private static int currentPage;
private static void PreviousPage(SkinsTab tab)
{
currentPage--;
currentPage = currentPage < 0 ? sortedSkins.Count - 1 : currentPage;
GenerateHats(tab, currentPage);
}
private static void NextPage(SkinsTab tab)
{
currentPage++;
currentPage = currentPage > sortedSkins.Count - 1 ? 0 : currentPage;
GenerateHats(tab, currentPage);
}
[HarmonyPatch(nameof(SkinsTab.OnEnable))]
[HarmonyPrefix]
public static bool OnEnablePrefix(SkinsTab __instance)
{
__instance.skinId = HatManager.Instance.GetSkinById(DataManager.Player.Customization.Skin).ProdId;
var allSkins = HatManager.Instance.GetUnlockedSkins().ToImmutableList();
if (sortedSkins.Count == 0)
{
var comparer = new ControllableComparer<string>(["vanilla"], [], StringComparer.InvariantCulture);
sortedSkins = new SortedList<string, List<SkinData>>(comparer);
foreach (var skin in allSkins)
{
if (!sortedSkins.ContainsKey(skin.StoreName)) sortedSkins[skin.StoreName] = [];
sortedSkins[skin.StoreName].Add(skin);
}
}
InventoryUtility.CreateNextBackButtons(__instance, PreviousPage, NextPage);
GenerateHats(__instance, currentPage);
return false;
}
[HarmonyPatch(typeof(SkinsTab), nameof(SkinsTab.Update))]
[HarmonyPrefix]
public static void UpdatePrefix(SkinsTab __instance)
{
if (Input.GetKeyDown(KeyCode.LeftControl) || Input.GetKeyDown(KeyCode.RightControl) || Input.GetKeyDown(KeyCode.LeftArrow))
{
PreviousPage(__instance);
}
else if (Input.GetKeyDown(KeyCode.Tab) || Input.GetKeyDown(KeyCode.RightArrow))
{
NextPage(__instance);
}
}
private static void GenerateHats(SkinsTab __instance, int page)
{
foreach (ColorChip instanceColorChip in __instance.ColorChips) instanceColorChip.gameObject.Destroy();
__instance.ColorChips.Clear();
__instance.scroller.Inner.GetComponentsInChildren<TextMeshPro>().Do(x => x.gameObject.Destroy());
var groupNameText = __instance.GetComponentInChildren<TextMeshPro>(false);
int hatIndex = 0;
var (groupName, skins) = sortedSkins.ToArray()[page];
var text = Object.Instantiate(groupNameText, __instance.scroller.Inner);
text.enabled = true;
text.gameObject.transform.localScale = Vector3.one;
text.GetComponent<TextTranslatorTMP>().Destroy();
text.EnableStencilMasking();
text.text = $"{groupName} ({currentPage + 1}/{sortedSkins.Count})";
text.alignment = TextAlignmentOptions.Center;
text.fontSize = 5f;
text.fontSizeMax = 5f;
text.fontSizeMin = 0f;
float xLerp = __instance.XRange.Lerp(0.5f);
float yLerp = __instance.YStart - hatIndex / __instance.NumPerRow * __instance.YOffset;
text.transform.localPosition = new Vector3(xLerp, yLerp, -1f);
hatIndex += 5;
foreach (var skin in skins.OrderBy(HatManager.Instance.allSkins.IndexOf))
{
float hatXposition = __instance.XRange.Lerp(hatIndex % __instance.NumPerRow / (__instance.NumPerRow - 1f));
float hatYposition = __instance.YStart - hatIndex / __instance.NumPerRow * __instance.YOffset;
GenerateColorChip(__instance, new Vector2(hatXposition, hatYposition), skin);
hatIndex += 1;
}
__instance.SetScrollerBounds();
__instance.currentSkinIsEquipped = true;
}
private static void GenerateColorChip(SkinsTab __instance, Vector2 position, SkinData skin)
{
var colorChip = Object.Instantiate(__instance.ColorTabPrefab, __instance.scroller.Inner);
colorChip.gameObject.name = skin.ProductId;
if (ActiveInputManager.currentControlType == ActiveInputManager.InputType.Keyboard)
{
colorChip.Button.OnClick.AddListener((Action)__instance.ClickEquip);
colorChip.Button.OnMouseOver.AddListener((Action)(() => __instance.SelectSkin(skin)));
colorChip.Button.OnMouseOut.AddListener(
(Action)(() =>
__instance.SelectSkin(HatManager.Instance.GetSkinById(DataManager.Player.Customization.Skin))));
}
else
{
colorChip.Button.OnClick.AddListener((Action)(() => __instance.SelectSkin(skin)));
}
colorChip.Button.ClickMask = __instance.scroller.Hitbox;
colorChip.ProductId = skin.ProductId;
colorChip.SelectionHighlight.gameObject.SetActive(false);
__instance.UpdateMaterials(colorChip.Inner.FrontLayer, skin);
skin.SetPreview(colorChip.Inner.FrontLayer, __instance.HasLocalPlayer() ? PlayerControl.LocalPlayer.Data.DefaultOutfit.ColorId : DataManager.Player.Customization.Color);
colorChip.transform.localPosition = new Vector3(position.x, position.y, -1f);
colorChip.Inner.transform.localPosition = skin.ChipOffset + new Vector2(0f, -0.3f);
colorChip.Tag = skin;
__instance.ColorChips.Add(colorChip);
}
}
+139
View File
@@ -0,0 +1,139 @@
using AmongUs.Data;
using HarmonyLib;
using MiraAPI.Utilities;
using Reactor.Utilities.Extensions;
using System;
using System.Collections.Generic;
using System.Linq;
using TMPro;
using UnityEngine;
using Object = UnityEngine.Object;
namespace MiraAPI.Patches.Menu;
[HarmonyPatch(typeof(VisorsTab))]
public static class VisorsTabPatches
{
private static readonly SortedList<string, List<VisorData>> SortedVisors = new(new ControllableComparer<string>(["vanilla"], [], StringComparer.InvariantCulture));
private static int currentPage;
internal static void AddRange(IEnumerable<(string Key, VisorData Visor)> data)
{
foreach (var item in data)
{
if (!SortedVisors.ContainsKey(item.Key)) SortedVisors.Add(item.Key, []);
SortedVisors[item.Key].Add(item.Visor);
}
}
private static void PreviousPage(VisorsTab tab)
{
currentPage--;
currentPage = currentPage < 0 ? SortedVisors.Count - 1 : currentPage;
GenerateHats(tab, currentPage);
}
private static void NextPage(VisorsTab tab)
{
currentPage++;
currentPage = currentPage > SortedVisors.Count - 1 ? 0 : currentPage;
GenerateHats(tab, currentPage);
}
[HarmonyPatch(nameof(VisorsTab.OnEnable))]
[HarmonyPrefix]
public static bool OnEnablePrefix(VisorsTab __instance)
{
__instance.visorId = HatManager.Instance.GetVisorById(DataManager.Player.Customization.Visor).ProdId;
if (!SortedVisors.ContainsKey("Vanilla")) AddRange(DestroyableSingleton<HatManager>.Instance.GetUnlockedVisors().Select(x => ("Vanilla", x)));
InventoryUtility.CreateNextBackButtons(__instance, PreviousPage, NextPage);
GenerateHats(__instance, currentPage);
return false;
}
[HarmonyPatch(typeof(VisorsTab), nameof(VisorsTab.Update))]
[HarmonyPrefix]
public static void UpdatePrefix(VisorsTab __instance)
{
if (Input.GetKeyDown(KeyCode.LeftControl) || Input.GetKeyDown(KeyCode.RightControl) || Input.GetKeyDown(KeyCode.LeftArrow))
{
PreviousPage(__instance);
}
else if (Input.GetKeyDown(KeyCode.Tab) || Input.GetKeyDown(KeyCode.RightArrow))
{
NextPage(__instance);
}
}
private static void GenerateHats(VisorsTab __instance, int page)
{
foreach (ColorChip instanceColorChip in __instance.ColorChips) instanceColorChip.gameObject.Destroy();
__instance.ColorChips.Clear();
__instance.scroller.Inner.GetComponentsInChildren<TextMeshPro>().Do(x => x.gameObject.Destroy());
var groupNameText = __instance.GetComponentInChildren<TextMeshPro>(false);
int hatIndex = 0;
var (groupName, visors) = SortedVisors.ToArray()[page];
var text = Object.Instantiate(groupNameText, __instance.scroller.Inner);
text.enabled = true;
text.gameObject.transform.localScale = Vector3.one;
text.GetComponent<TextTranslatorTMP>().Destroy();
text.EnableStencilMasking();
text.text = $"{groupName} ({currentPage + 1}/{SortedVisors.Count})";
text.alignment = TextAlignmentOptions.Center;
text.fontSize = 5f;
text.fontSizeMax = 5f;
text.fontSizeMin = 0f;
float xLerp = __instance.XRange.Lerp(0.5f);
float yLerp = __instance.YStart - hatIndex / __instance.NumPerRow * __instance.YOffset;
text.transform.localPosition = new Vector3(xLerp, yLerp, -1f);
hatIndex += 5;
foreach (var visor in visors.OrderBy(HatManager.Instance.allVisors.IndexOf))
{
float hatXposition = __instance.XRange.Lerp(hatIndex % __instance.NumPerRow / (__instance.NumPerRow - 1f));
float hatYposition = __instance.YStart - hatIndex / __instance.NumPerRow * __instance.YOffset;
GenerateColorChip(__instance, new Vector2(hatXposition, hatYposition), visor);
hatIndex += 1;
}
__instance.SetScrollerBounds();
__instance.currentVisorIsEquipped = true;
}
private static void GenerateColorChip(VisorsTab __instance, Vector2 position, VisorData visor)
{
var colorChip = Object.Instantiate(__instance.ColorTabPrefab, __instance.scroller.Inner);
colorChip.gameObject.name = visor.ProductId;
if (ActiveInputManager.currentControlType == ActiveInputManager.InputType.Keyboard)
{
colorChip.Button.OnClick.AddListener((Action)__instance.ClickEquip);
colorChip.Button.OnMouseOver.AddListener((Action)(() => __instance.SelectVisor(visor)));
colorChip.Button.OnMouseOut.AddListener(
(Action)(() =>
__instance.SelectVisor(HatManager.Instance.GetVisorById(DataManager.Player.Customization.Visor))));
}
else
{
colorChip.Button.OnClick.AddListener((Action)(() => __instance.SelectVisor(visor)));
}
colorChip.Button.ClickMask = __instance.scroller.Hitbox;
colorChip.ProductId = visor.ProductId;
colorChip.SelectionHighlight.gameObject.SetActive(false);
__instance.UpdateMaterials(colorChip.Inner.FrontLayer, visor);
visor.SetPreview(colorChip.Inner.FrontLayer, __instance.HasLocalPlayer() ? PlayerControl.LocalPlayer.Data.DefaultOutfit.ColorId : DataManager.Player.Customization.Color);
colorChip.transform.localPosition = new Vector3(position.x, position.y, -1f);
colorChip.Inner.transform.localPosition = visor.ChipOffset + new Vector2(0f, -0.3f);
colorChip.Tag = visor;
__instance.ColorChips.Add(colorChip);
}
}
@@ -5,7 +5,6 @@ using HarmonyLib;
using MiraAPI.GameOptions;
using MiraAPI.Modifiers;
using MiraAPI.PluginLoading;
using MiraAPI.Presets;
using MiraAPI.Utilities.Assets;
using Reactor.Utilities.Extensions;
using TMPro;
@@ -352,11 +351,6 @@ internal static class GameSettingMenuPatches
_modifierBtnOgPos = _modifiersButton.transform.localPosition;
foreach (var plugin in MiraPluginManager.Instance.RegisteredPlugins)
{
PresetManager.LoadPresets(plugin);
}
UpdateText(__instance, __instance.GameSettingsTab, __instance.RoleSettingsTab);
}
@@ -29,6 +29,7 @@ public static class RoleSettingMenuPatches
private static Dictionary<RoleOptionsGroup, bool> RoleGroupHidden { get; set; } = [];
private static List<GameObject> Headers { get; set; } = [];
private static List<RoleOptionSetting> RoleOptionSettings { get; set; } = [];
private static Dictionary<RoleBehaviour, Sprite> RoleScreenshotSprites { get; } = [];
private static float ScrollerNum { get; set; } = 0.522f;
@@ -506,11 +507,17 @@ public static class RoleSettingMenuPatches
__instance.roleDescriptionText.transform.parent.localScale = new Vector3(0.0675f, 0.1494f, 0.5687f);
labelBg.transform.localPosition = new Vector3(1.082f, 0.1054f, -2.5f);
__instance.roleScreenshot.sprite = Sprite.Create(
role.RoleScreenshot.texture,
new Rect(0, 0, 370, 230),
Vector2.one / 2,
100);
if (!RoleScreenshotSprites.TryGetValue(role, out var screenshotSprite) || screenshotSprite == null)
{
screenshotSprite = Sprite.Create(
role.RoleScreenshot.texture,
new Rect(0, 0, 370, 230),
Vector2.one / 2,
100);
RoleScreenshotSprites[role] = screenshotSprite;
}
__instance.roleScreenshot.sprite = screenshotSprite;
__instance.roleScreenshot.drawMode = SpriteDrawMode.Sliced;
}
+68 -39
View File
@@ -1,12 +1,13 @@
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using BepInEx.Configuration;
using BepInEx.Unity.IL2CPP;
using HarmonyLib;
using MiraAPI.Colors;
using MiraAPI.Events;
using MiraAPI.GameEnd;
@@ -22,6 +23,7 @@ using MiraAPI.Roles;
using MiraAPI.Utilities;
using Reactor.Networking;
using Reactor.Utilities;
using Rewired;
namespace MiraAPI.PluginLoading;
@@ -30,6 +32,9 @@ namespace MiraAPI.PluginLoading;
/// </summary>
public sealed class MiraPluginManager
{
private const BindingFlags DeclaredInstanceMembers = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly;
private const BindingFlags DeclaredStaticMembers = BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly;
private readonly Dictionary<Assembly, MiraPluginInfo> _registeredPlugins = [];
internal MiraPluginInfo[] RegisteredPlugins { get; private set; } = null!;
@@ -49,41 +54,24 @@ public sealed class MiraPluginManager
var info = new MiraPluginInfo(miraPlugin, pluginInfo);
var roles = new List<Type>();
var registrationTimer = Stopwatch.StartNew();
var oldConfigSetting = info.PluginConfig.SaveOnConfigSet;
info.PluginConfig.SaveOnConfigSet = false;
foreach (var type in assembly.GetTypes())
foreach (var type in GetAssemblyTypes(assembly))
{
if (type == null)
{
continue;
}
if (type.GetCustomAttribute<MiraIgnoreAttribute>() != null)
{
continue;
}
foreach (var method in AccessTools.GetDeclaredMethods(type))
{
var eventAttribute = method.GetCustomAttribute<RegisterEventAttribute>();
if (eventAttribute == null)
{
continue;
}
if (!method.IsStatic)
{
Error($"Event method {method.Name} in {type.Name} must be static.");
continue;
}
var parameters = method.GetParameters();
if (parameters.Length != 1 || !parameters[0].ParameterType.IsSubclassOf(typeof(MiraEvent)))
{
Error($"Invalid event registration method {method.Name} in {type.Name}");
continue;
}
var paramType = parameters[0].ParameterType;
MiraEventManager.RegisterEventHandler(paramType, method, eventAttribute.Priority);
}
RegisterEvents(type);
if (RegisterModifier(type, info))
{
@@ -131,7 +119,9 @@ public sealed class MiraPluginManager
info.SavePublicCollections();
PresetManager.CreateDefaultPreset(info);
PresetManager.LoadPresets(info);
Info($"Registering mod {pluginInfo.Metadata.GUID} with Mira API.");
registrationTimer.Stop();
Info($"Registering mod {pluginInfo.Metadata.GUID} with Mira API in {registrationTimer.ElapsedMilliseconds}ms.");
};
IL2CPPChainloader.Instance.Finished += PaletteManager.RegisterAllColors;
IL2CPPChainloader.Instance.Finished += () =>
@@ -159,6 +149,45 @@ public sealed class MiraPluginManager
return Instance._registeredPlugins.Values.FirstOrDefault(plugin => plugin.PluginId == pluginId);
}
private static void RegisterEvents(Type type)
{
foreach (var method in type.GetMethods(DeclaredStaticMembers))
{
var eventAttribute = method.GetCustomAttribute<RegisterEventAttribute>();
if (eventAttribute == null)
{
continue;
}
var parameters = method.GetParameters();
if (parameters.Length != 1 || !typeof(MiraEvent).IsAssignableFrom(parameters[0].ParameterType))
{
Error($"Invalid event registration method {method.Name} in {type.Name}");
continue;
}
MiraEventManager.RegisterEventHandler(parameters[0].ParameterType, method, eventAttribute.Priority);
}
}
private static Type?[] GetAssemblyTypes(Assembly assembly)
{
try
{
return assembly.GetTypes();
}
catch (ReflectionTypeLoadException exception)
{
return exception.Types;
}
}
private static bool IsAutoPropertyBackingField(FieldInfo field)
{
return field.IsDefined(typeof(CompilerGeneratedAttribute), false) &&
field.Name.Contains("k__BackingField", StringComparison.Ordinal);
}
private static bool RegisterGameOver(Type type)
{
try
@@ -186,7 +215,7 @@ public sealed class MiraPluginManager
return false;
}
foreach (var property in type.GetProperties())
foreach (var property in type.GetProperties(DeclaredInstanceMembers))
{
if (property.GetMethod?.IsStatic == true)
{
@@ -209,7 +238,7 @@ public sealed class MiraPluginManager
ModdedOptionsManager.RegisterAttributeOption(type, attribute, property, pluginInfo);
}
foreach (var field in type.GetFields().Where(f => f.FieldType.IsAssignableTo(typeof(IModdedOption))))
foreach (var field in type.GetFields(DeclaredInstanceMembers).Where(f => !IsAutoPropertyBackingField(f) && f.FieldType.IsAssignableTo(typeof(IModdedOption))))
{
Error($"{field.Name} is a field, not a property. Use properties for options.");
}
@@ -264,7 +293,7 @@ public sealed class MiraPluginManager
return;
}
foreach (var property in type.GetProperties())
foreach (var property in type.GetProperties(DeclaredStaticMembers))
{
if (property.PropertyType != typeof(CustomColor))
{
@@ -280,7 +309,7 @@ public sealed class MiraPluginManager
PaletteManager.CustomColors.Add(color);
}
foreach (var field in type.GetFields().Where(f => f.FieldType.IsAssignableTo(typeof(CustomColor))))
foreach (var field in type.GetFields(DeclaredStaticMembers).Where(f => !IsAutoPropertyBackingField(f) && f.FieldType.IsAssignableTo(typeof(CustomColor))))
{
Error($"{field.Name} is a field, not a property. Use properties for colors.");
}
@@ -332,13 +361,13 @@ public sealed class MiraPluginManager
return false;
}
foreach (var property in type.GetProperties())
if (!LocalSettingsManager.TypeToTab.TryGetValue(type, out var tabInstance))
{
if (LocalSettingsManager.TypeToTab[type] is not { } tabInstance)
{
continue;
}
return false;
}
foreach (var property in type.GetProperties(DeclaredInstanceMembers))
{
if (property.GetCustomAttribute<LocalSettingsButtonAttribute>() != null &&
property.PropertyType.IsAssignableTo(typeof(LocalSettingsButton)))
{
@@ -374,7 +403,7 @@ public sealed class MiraPluginManager
attribute.CreateSetting(type, configEntry);
}
foreach (var field in type.GetFields().Where(f => f.FieldType.IsAssignableTo(typeof(ConfigEntryBase)) && f.GetCustomAttribute<LocalSettingAttribute>() != null))
foreach (var field in type.GetFields(DeclaredInstanceMembers).Where(f => !IsAutoPropertyBackingField(f) && f.FieldType.IsAssignableTo(typeof(ConfigEntryBase)) && f.GetCustomAttribute<LocalSettingAttribute>() != null))
{
Error($"{field.Name} is a field, not a property. Use properties for local settings.");
}
@@ -404,7 +433,7 @@ public sealed class MiraPluginManager
return;
}
foreach (var property in type.GetProperties())
foreach (var property in type.GetProperties(DeclaredStaticMembers))
{
if (property.PropertyType != typeof(MiraKeybind))
{
@@ -428,7 +457,7 @@ public sealed class MiraPluginManager
}
}
foreach (var field in type.GetFields().Where(f => f.FieldType.IsAssignableTo(typeof(MiraKeybind))))
foreach (var field in type.GetFields(DeclaredStaticMembers).Where(f => !IsAutoPropertyBackingField(f) && f.FieldType.IsAssignableTo(typeof(MiraKeybind))))
{
Error($"{field.Name} is a field, not a property. Use properties for keybinds.");
}
-6
View File
@@ -4,7 +4,6 @@ using System.Linq;
using BepInEx.Configuration;
using MiraAPI.PluginLoading;
using MiraAPI.Roles;
using Reactor.Utilities;
using UnityEngine;
namespace MiraAPI.Presets;
@@ -79,8 +78,6 @@ public static class PresetManager
foreach (var file in Directory.GetFiles(pluginPresetPath, "*.cfg"))
{
var fileName = Path.GetFileName(file);
Info($"Loading preset file {fileName}");
var presetName = Path.GetFileNameWithoutExtension(file);
var presetConfig = new ConfigFile(file, false)
{
@@ -131,9 +128,6 @@ public static class PresetManager
foreach (var file in Directory.GetFiles(pluginPresetPath, "*.cfg"))
{
var fileName = Path.GetFileName(file);
Info($"Loading preset file {fileName}");
var presetName = Path.GetFileNameWithoutExtension(file);
var presetConfig = new ConfigFile(file, false)
{
SaveOnConfigSet = false,
+164 -6
View File
@@ -10,10 +10,20 @@ using UnityEngine.ResourceManagement.AsyncOperations;
namespace MiraAPI.Utilities.Assets;
/// <summary>
/// The component for loading Addressables, and cosmetics. This is deprecated in favor of Corsac Cosmetics.
/// The component for loading Addressables, and cosmetics.
/// </summary>
public static class AddressablesLoader
{
private static bool _isInitialized;
private static readonly List<(string Location, string ProviderSuffix)> CatalogLocations = [];
private static readonly List<string> LoadedLocations = [];
private static readonly List<string> RegisteredHatKeys = [];
private static readonly List<(string, string)> RegisteredVisorKeys = [];
private static readonly List<(string, string)> RegisteredNameplateKeys = [];
private static readonly List<string> RegisteredSkinKeys = [];
/// <summary>
/// Registers a specific addressables package to load asynchronously at the start of the game, when possible.
/// </summary>
@@ -21,7 +31,13 @@ public static class AddressablesLoader
/// <param name="providerSuffix">The suffix of the provider for an addressables package.</param>
public static void RegisterCatalog(string location, string providerSuffix = "")
{
Error("Catalogs are no longer possible to load in MiraAPI! Please use Corsac Cosmetics instead.");
if (_isInitialized)
{
Error("AddressablesLoader has already been initialized, cannot register more catalogs.");
return;
}
CatalogLocations.Add((location, providerSuffix));
}
/// <summary>
@@ -30,7 +46,13 @@ public static class AddressablesLoader
/// <param name="addressablesKey">The key/label/group for a List <see cref="HatData"/>.</param>
public static void RegisterHats(string addressablesKey)
{
Error("Hats are no longer possible to load in MiraAPI! Please use Corsac Cosmetics instead.");
if (_isInitialized)
{
Error("AddressablesLoader has already been initialized, cannot register more keys for hats.");
return;
}
RegisteredHatKeys.Add(addressablesKey);
}
/// <summary>
@@ -39,7 +61,13 @@ public static class AddressablesLoader
/// <param name="addressablesKey">The key/label/group for a List <see cref="SkinData"/>.</param>
public static void RegisterSkins(string addressablesKey)
{
Error("Skins are no longer possible to load in MiraAPI! Please use Corsac Cosmetics instead.");
if (_isInitialized)
{
Error("AddressablesLoader has already been initialized, cannot register more keys for skins.");
return;
}
RegisteredSkinKeys.Add(addressablesKey);
}
/// <summary>
@@ -49,7 +77,13 @@ public static class AddressablesLoader
/// /// <param name="groupTitle">The title of the group for visors.</param>
public static void RegisterNameplates(string addressablesKey, string groupTitle)
{
Error("Nameplates are no longer possible to load in MiraAPI! Please use Corsac Cosmetics instead.");
if (_isInitialized)
{
Error("AddressablesLoader has already been initialized, cannot register more keys for nameplates.");
return;
}
RegisteredNameplateKeys.Add((addressablesKey, groupTitle));
}
/// <summary>
@@ -59,6 +93,130 @@ public static class AddressablesLoader
/// <param name="groupTitle">The title of the group for visors.</param>
public static void RegisterVisors(string addressablesKey, string groupTitle)
{
Error("Visors are no longer possible to load in MiraAPI! Please use Corsac Cosmetics instead.");
if (_isInitialized)
{
Error("AddressablesLoader has already been initialized, cannot register more keys for visors.");
return;
}
RegisteredVisorKeys.Add((addressablesKey, groupTitle));
}
internal static void LoadAll()
{
if (_isInitialized)
{
Error("AddressablesLoader has already been initialized.");
return;
}
_isInitialized = true;
foreach (var (location, providerSuffix) in CatalogLocations)
{
Coroutines.Start(CoLoadAddressables(location, providerSuffix));
}
Coroutines.Start(LoadCosmetics());
}
internal static IEnumerator CoLoadAddressables(string location, string suffix = "")
{
while (!AmongUsClient.Instance) yield return null;
// Load the local/remote content catalog
var catalogOperation = Addressables.LoadContentCatalog(location, suffix);
yield return catalogOperation;
// Check for errors
if (catalogOperation.Status != AsyncOperationStatus.Succeeded)
{
Error($"Failed to load catalog {location}.");
}
Info($"Loaded addressables {location}.");
LoadedLocations.Add(location);
}
[HideFromIl2Cpp]
internal static IEnumerator LoadCosmetics()
{
while (!AmongUsClient.Instance || CatalogLocations.Select(x=>x.Location).Any(x=>!LoadedLocations.Contains(x))) yield return null;
var hatBehaviours = DiscoverData<HatData>(RegisteredHatKeys);
var skinBehaviours = DiscoverData<SkinData>(RegisteredSkinKeys);
var namePlateBehaviours = DiscoverAndReportData<NamePlateData>(RegisteredNameplateKeys);
var visorBehaviours = DiscoverAndReportData<VisorData>(RegisteredVisorKeys);
var hatData = new List<HatData>();
hatData.AddRange(DestroyableSingleton<HatManager>.Instance.allHats);
hatData.ForEach(x => x.StoreName = "Vanilla");
DestroyableSingleton<HatManager>.Instance.allHats = PrepareArray(hatData, hatBehaviours);
var skinData = new List<SkinData>();
skinData.AddRange(DestroyableSingleton<HatManager>.Instance.allSkins);
skinData.ForEach(x => x.StoreName = "Vanilla");
DestroyableSingleton<HatManager>.Instance.allSkins = PrepareArray(skinData, skinBehaviours);
var visorData = new List<VisorData>();
visorData.AddRange(DestroyableSingleton<HatManager>.Instance.allVisors);
VisorsTabPatches.AddRange(visorBehaviours);
DestroyableSingleton<HatManager>.Instance.allVisors = PrepareArray(visorData, visorBehaviours.Select(x=>x.Data).ToList());
var namePlateData = new List<NamePlateData>();
namePlateData.AddRange(DestroyableSingleton<HatManager>.Instance.allNamePlates);
NameplatesTabPatches.AddRange(namePlateBehaviours);
DestroyableSingleton<HatManager>.Instance.allNamePlates = PrepareArray(namePlateData, namePlateBehaviours.Select(x => x.Data).ToList());
}
private static T[] PrepareArray<T>(List<T> data, List<T> behaviours) where T : CosmeticData
{
var count = data.Count;
for (int i = 0; i < behaviours.Count; i++)
{
behaviours[i].displayOrder = count + i;
data.Add(behaviours[i]);
}
return data.ToArray();
}
private static List<T> DiscoverData<T>(List<string> tags)
{
var behaviours = new List<T>();
foreach (var tag in tags)
{
try
{
var allLocations = Addressables.LoadResourceLocationsAsync(tag).WaitForCompletion();
var assets = Addressables.LoadAssetsAsync<T>(allLocations, null, false).WaitForCompletion();
var array = new Il2CppSystem.Collections.Generic.List<T>(assets.Pointer);
behaviours.AddRange(array.ToArray());
}
catch
{
Error($"Failed to find tag {tag}");
}
}
return behaviours;
}
private static List<(string Category, T Data)> DiscoverAndReportData<T>(List<(string Tag, string Category)> tags)
{
var behaviours = new List<(string, T)>();
foreach (var tag in tags)
{
try
{
var allLocations = Addressables.LoadResourceLocationsAsync(tag.Tag).WaitForCompletion();
var assets = Addressables.LoadAssetsAsync<T>(allLocations, null, false).WaitForCompletion();
var array = new Il2CppSystem.Collections.Generic.List<T>(assets.Pointer);
behaviours.AddRange(array.ToArray().Select(x => (tag.Category, x)));
}
catch
{
Error($"Failed to find tag {tag}");
}
}
return behaviours;
}
}
@@ -1,4 +1,5 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Resources;
@@ -13,6 +14,8 @@ namespace MiraAPI.Utilities.Assets;
/// <param name="path">The path of the wave file.</param>
public class LoadableAudioResourceAsset(string path) : LoadableAsset<AudioClip>
{
private static readonly object CacheLock = new();
private static readonly Dictionary<(Assembly Assembly, string Path), AudioClip> AudioClipCache = [];
private readonly Assembly _assembly = Assembly.GetCallingAssembly();
/// <summary>
@@ -23,6 +26,20 @@ public class LoadableAudioResourceAsset(string path) : LoadableAsset<AudioClip>
/// <exception cref="MissingManifestResourceException">Stream failed to load. Check if the name of your asset was correct.</exception>
public override AudioClip LoadAsset()
{
if (LoadedAsset != null)
{
return LoadedAsset;
}
lock (CacheLock)
{
if (AudioClipCache.TryGetValue((_assembly, path), out var cachedClip) && cachedClip != null)
{
LoadedAsset = cachedClip;
return cachedClip;
}
}
using var assetStream = _assembly.GetManifestResourceStream(path)
?? throw new MissingManifestResourceException($"Stream failed to load. Check if the asset name is correct: {path}");
@@ -92,6 +109,13 @@ public class LoadableAudioResourceAsset(string path) : LoadableAsset<AudioClip>
var audioClip = AudioClip.Create(path, samples.Length / channels, channels, sampleRate, false);
audioClip.SetData(samples, 0);
LoadedAsset = audioClip;
lock (CacheLock)
{
AudioClipCache[(_assembly, path)] = audioClip;
}
return audioClip;
}
@@ -1,4 +1,5 @@
using System;
using System;
using System.Collections.Generic;
using Reactor.Utilities.Extensions;
using UnityEngine;
@@ -12,6 +13,9 @@ namespace MiraAPI.Utilities.Assets;
/// <typeparam name="T">The type of the asset to be loaded.</typeparam>
public class LoadableBundleAsset<T>(string name, AssetBundle bundle) : LoadableAsset<T> where T : UnityEngine.Object
{
private static readonly object CacheLock = new();
private static readonly Dictionary<(int BundleId, Type AssetType, string Name), UnityEngine.Object> BundleAssetCache = [];
/// <summary>
/// Loads the asset from the asset bundle.
/// </summary>
@@ -24,6 +28,16 @@ public class LoadableBundleAsset<T>(string name, AssetBundle bundle) : LoadableA
return LoadedAsset;
}
var cacheKey = (bundle.GetInstanceID(), typeof(T), name);
lock (CacheLock)
{
if (BundleAssetCache.TryGetValue(cacheKey, out var cachedAsset) && cachedAsset is T typedAsset)
{
LoadedAsset = typedAsset;
return typedAsset;
}
}
LoadedAsset = bundle.LoadAsset<T>(name);
if (LoadedAsset == null)
@@ -31,6 +45,11 @@ public class LoadableBundleAsset<T>(string name, AssetBundle bundle) : LoadableA
throw new InvalidOperationException($"INVALID ASSET: {name}");
}
lock (CacheLock)
{
BundleAssetCache[cacheKey] = LoadedAsset;
}
return LoadedAsset;
}
}
+36 -2
View File
@@ -1,4 +1,5 @@
using System;
using System;
using System.Collections.Generic;
using System.Reflection;
using Reactor.Utilities.Extensions;
using UnityEngine;
@@ -10,6 +11,10 @@ namespace MiraAPI.Utilities.Assets;
/// </summary>
public static class SpriteTools
{
private static readonly object CacheLock = new();
private static readonly Dictionary<(Assembly Assembly, string ResourcePath), Texture2D> TextureCache = [];
private static readonly Dictionary<(Assembly Assembly, string ResourcePath, float PixelsPerUnit), Sprite> SpriteCache = [];
/// <summary>
/// Loads and returns a texture from a resource path using the specified assembly.
/// </summary>
@@ -19,11 +24,20 @@ public static class SpriteTools
/// <exception cref="ArgumentException">Thrown when the resource cannot be found in the specified assembly.</exception>
public static Texture2D LoadTextureFromResourcePath(string resourcePath, Assembly assembly)
{
lock (CacheLock)
{
if (TextureCache.TryGetValue((assembly, resourcePath), out var cachedTexture) && cachedTexture != null)
{
return cachedTexture;
}
}
var tex = new Texture2D(1, 1, TextureFormat.ARGB32, false)
{
wrapMode = TextureWrapMode.Clamp,
};
var myStream = assembly.GetManifestResourceStream(resourcePath);
using var myStream = assembly.GetManifestResourceStream(resourcePath);
if (myStream != null)
{
var buttonTexture = myStream.ReadFully();
@@ -35,6 +49,12 @@ public static class SpriteTools
}
tex.name = resourcePath;
lock (CacheLock)
{
TextureCache[(assembly, resourcePath)] = tex;
}
return tex;
}
@@ -47,9 +67,23 @@ public static class SpriteTools
/// <returns>A <see cref="Sprite"/> object created from the texture loaded from the specified resource path.</returns>
public static Sprite LoadSpriteFromPath(string resourcePath, Assembly assembly, float pixelsPerUnit)
{
lock (CacheLock)
{
if (SpriteCache.TryGetValue((assembly, resourcePath, pixelsPerUnit), out var cachedSprite) && cachedSprite != null)
{
return cachedSprite;
}
}
var tex = LoadTextureFromResourcePath(resourcePath, assembly);
var sprite = Sprite.Create(tex, new Rect(0, 0, tex.width, tex.height), new Vector2(0.5f, 0.5f), pixelsPerUnit);
sprite.name = resourcePath;
lock (CacheLock)
{
SpriteCache[(assembly, resourcePath, pixelsPerUnit)] = sprite;
}
return sprite;
}
}
-10
View File
@@ -181,16 +181,6 @@ public static class Extensions
return TutorialManager.InstanceExists || AmongUsClient.Instance.HostId == playerControl.OwnerId;
}
/// <summary>
/// Checks if a PlayerControl is protected by a Guardian Angel.
/// </summary>
/// <param name="playerControl">The player you're checking for.</param>
/// <returns>If the player is protected, true, else false.</returns>
public static bool ProtectedByGa(this PlayerControl playerControl)
{
return playerControl.protectedByGuardianId > -1;
}
/// <summary>
/// Used to convert a System.Collections.Generic.List to Il2cppSystem.
/// </summary>
+1 -16
View File
@@ -3,7 +3,6 @@ using System.Collections.Generic;
using System.Reflection;
using HarmonyLib;
using Il2CppInterop.Runtime.InteropTypes;
using Object = Il2CppSystem.Object;
namespace MiraAPI.Utilities;
@@ -18,7 +17,6 @@ public class StateMachineWrapper<T> where T : Il2CppObjectBase
// normally it is fields, but IL2CPP turns them into properties
private readonly PropertyInfo _thisProperty;
private readonly PropertyInfo _stateProperty;
private readonly PropertyInfo _currentProperty;
private readonly Dictionary<string, PropertyInfo> _propertyCache;
private T? _parentInstance;
@@ -39,9 +37,8 @@ public class StateMachineWrapper<T> where T : Il2CppObjectBase
var type = _stateMachine.GetType();
_thisProperty = AccessTools.Property(type, "__4__this");
_stateProperty = AccessTools.Property(type, "__1__state");
_currentProperty = AccessTools.Property(type, "__2__current");
if (_thisProperty == null || _stateProperty == null || _currentProperty == null)
if (_thisProperty == null || _stateProperty == null)
{
throw new MissingMemberException($"Could not find required properties in type '{type}'.");
}
@@ -55,18 +52,6 @@ public class StateMachineWrapper<T> where T : Il2CppObjectBase
/// <returns>The current state as an integer.</returns>
public int GetState() => (int)_stateProperty.GetValue(_stateMachine)!;
/// <summary>
/// Sets the current state of the state machine.
/// </summary>
/// <param name="newState">The new state to use.</param>
public void SetState(int newState) => _stateProperty.SetValue(_stateMachine, newState);
/// <summary>
/// Sets the newest yield return of the state machine.
/// </summary>
/// <param name="newReturn">The new return to use.</param>
public void SetRecentReturn(Object newReturn) => _currentProperty.SetValue(_stateMachine, newReturn);
/// <summary>
/// Gets a parameter from the state machine by its name.
/// </summary>
Binary file not shown.