Please disclose if any significant portion of your mod was created using AI tools by adding the 'AI Generated' category. Failing to do so may result in the mod being removed from Thunderstore.
Decompiled source of BeastGohan v1.1.11
plugins/BeastGohan.dll
Decompiled 2 hours ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; 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 BepInEx; using BepInEx.Bootstrap; using BepInEx.Configuration; using BepInEx.Logging; using EntityStates; using EntityStates.AI.Walker; using EntityStates.Commando; using EntityStates.Commando.CommandoWeapon; using HG; using HG.BlendableTypes; using HenryMod.Modules; using HenryMod.Modules.Achievements; using HenryMod.Modules.BaseStates; using HenryMod.Modules.Characters; using HenryMod.Survivors.Gohan; using HenryMod.Survivors.Gohan.Components; using HenryMod.Survivors.Gohan.SkillStates; using HenryMod.Survivors.Henry.Components; using HenryMod.Survivors.Henry.SkillStates; using KinematicCharacterController; using On.RoR2; using On.RoR2.UI; using R2API; using R2API.Utils; using RoR2; using RoR2.Achievements; using RoR2.Audio; using RoR2.CharacterAI; using RoR2.ContentManagement; using RoR2.Projectile; using RoR2.Skills; using RoR2.UI; using TMPro; using UnityEngine; using UnityEngine.Networking; using UnityEngine.Rendering; using UnityEngine.UI; [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("BeastGohan")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0")] [assembly: AssemblyProduct("BeastGohan")] [assembly: AssemblyTitle("BeastGohan")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.0.0.0")] [module: UnverifiableCode] namespace HenryMod { [NetworkCompatibility(/*Could not decode attribute arguments.*/)] [BepInPlugin("com.gabe.BeastGohan", "BeastGohan", "1.0.0")] public class HenryPlugin : BaseUnityPlugin { public const string MODUID = "com.gabe.BeastGohan"; public const string MODNAME = "BeastGohan"; public const string MODVERSION = "1.0.0"; public const string DEVELOPER_PREFIX = "GABE"; public static HenryPlugin instance; private void Awake() { instance = this; Log.Init(((BaseUnityPlugin)this).Logger); GohanIntroAudio.RestoreGameVolume(); Language.Init(); new ContentPacks().Initialize(); } } internal static class Log { internal static ManualLogSource _logSource; internal static void Init(ManualLogSource logSource) { _logSource = logSource; } internal static void Debug(object data) { _logSource.LogDebug(data); } internal static void Error(object data) { _logSource.LogError(data); } internal static void ErrorAssetBundle(string assetName, string bundleName) { Error("failed to load asset, " + assetName + ", because it does not exist in asset bundle, " + bundleName); } internal static void Fatal(object data) { _logSource.LogFatal(data); } internal static void Info(object data) { _logSource.LogInfo(data); } internal static void Message(object data) { _logSource.LogMessage(data); } internal static void Warning(object data) { _logSource.LogWarning(data); } } } namespace HenryMod.Modules { internal static class Asset { internal static Dictionary<string, AssetBundle> loadedBundles = new Dictionary<string, AssetBundle>(); internal static AssetBundle LoadAssetBundle(string bundleName) { if (bundleName == "myassetbundle") { Log.Error("AssetBundle name hasn't been changed. not loading any assets to avoid conflicts.\nMake sure to rename your assetbundle filename and rename the AssetBundleName field in your character setup code "); return null; } if (loadedBundles.ContainsKey(bundleName)) { return loadedBundles[bundleName]; } AssetBundle val = null; try { string path = Path.Combine(Path.GetDirectoryName(((BaseUnityPlugin)HenryPlugin.instance).Info.Location), "AssetBundles"); string text = Path.Combine(path, bundleName + ".bundle"); if (!File.Exists(text)) { text = Path.Combine(path, bundleName); } if (!File.Exists(text)) { Log.Error("Asset bundle file was not found at " + text); } else { byte[] array = File.ReadAllBytes(text); bool flag = array.Length > 8 && array[0] == 85 && array[1] == 110 && array[2] == 105 && array[3] == 116 && array[4] == 121 && array[5] == 70 && array[6] == 83; Log.Info("Loading asset bundle " + text + " (" + array.Length + " bytes, unityfs=" + flag + ")"); if (!flag) { int num = Math.Min(16, array.Length); Log.Error("That file is not a Unity asset bundle. First bytes: " + BitConverter.ToString(array, 0, num)); } else { val = AssetBundle.LoadFromMemory(array); Log.Info(((Object)(object)val != (Object)null) ? "Asset bundle loaded." : "Asset bundle file was not loaded."); } } } catch (Exception arg) { Log.Error($"Error loading asset bundle, {bundleName}. Your asset bundle must be in a folder next to your mod dll called 'AssetBundles'. Follow the guide to build and install your mod correctly!\n{arg}"); } loadedBundles[bundleName] = val; return val; } internal static GameObject CloneTracer(string originalTracerName, string newTracerName) { if ((Object)(object)LegacyResourcesAPI.Load<GameObject>("Prefabs/Effects/Tracers/" + originalTracerName) == (Object)null) { return null; } GameObject val = PrefabAPI.InstantiateClone(LegacyResourcesAPI.Load<GameObject>("Prefabs/Effects/Tracers/" + originalTracerName), newTracerName, true); if (!Object.op_Implicit((Object)(object)val.GetComponent<EffectComponent>())) { val.AddComponent<EffectComponent>(); } if (!Object.op_Implicit((Object)(object)val.GetComponent<VFXAttributes>())) { val.AddComponent<VFXAttributes>(); } if (!Object.op_Implicit((Object)(object)val.GetComponent<NetworkIdentity>())) { val.AddComponent<NetworkIdentity>(); } val.GetComponent<Tracer>().speed = 250f; val.GetComponent<Tracer>().length = 50f; Content.CreateAndAddEffectDef(val); return val; } internal static void ConvertAllRenderersToHopooShader(GameObject objectToConvert) { if (!Object.op_Implicit((Object)(object)objectToConvert)) { return; } MeshRenderer[] componentsInChildren = objectToConvert.GetComponentsInChildren<MeshRenderer>(); foreach (MeshRenderer val in componentsInChildren) { if (Object.op_Implicit((Object)(object)val) && Object.op_Implicit((Object)(object)((Renderer)val).sharedMaterial)) { ((Renderer)val).sharedMaterial.ConvertDefaultShaderToHopoo(); } } SkinnedMeshRenderer[] componentsInChildren2 = objectToConvert.GetComponentsInChildren<SkinnedMeshRenderer>(); foreach (SkinnedMeshRenderer val2 in componentsInChildren2) { if (Object.op_Implicit((Object)(object)val2) && Object.op_Implicit((Object)(object)((Renderer)val2).sharedMaterial)) { ((Renderer)val2).sharedMaterial.ConvertDefaultShaderToHopoo(); } } } internal static GameObject LoadCrosshair(string crosshairName) { GameObject val = LegacyResourcesAPI.Load<GameObject>("Prefabs/Crosshair/" + crosshairName + "Crosshair"); if ((Object)(object)val == (Object)null) { Log.Error("could not load crosshair with the name " + crosshairName + ". defaulting to Standard"); return LegacyResourcesAPI.Load<GameObject>("Prefabs/Crosshair/StandardCrosshair"); } return val; } internal static GameObject LoadEffect(this AssetBundle assetBundle, string resourceName, bool parentToTransform) { return assetBundle.LoadEffect(resourceName, "", parentToTransform); } internal static GameObject LoadEffect(this AssetBundle assetBundle, string resourceName, string soundName = "", bool parentToTransform = false) { //IL_003c: Unknown result type (might be due to invalid IL or missing references) //IL_0050: Unknown result type (might be due to invalid IL or missing references) GameObject val = assetBundle.LoadAsset<GameObject>(resourceName); if (!Object.op_Implicit((Object)(object)val)) { Log.ErrorAssetBundle(resourceName, ((Object)assetBundle).name); return null; } val.AddComponent<DestroyOnTimer>().duration = 12f; val.AddComponent<NetworkIdentity>(); val.AddComponent<VFXAttributes>().vfxPriority = (VFXPriority)2; EffectComponent obj = val.AddComponent<EffectComponent>(); obj.applyScale = false; obj.effectIndex = (EffectIndex)(-1); obj.parentToReferencedTransform = parentToTransform; obj.positionAtReferencedTransform = true; obj.soundName = soundName; Content.CreateAndAddEffectDef(val); return val; } internal static GameObject CreateProjectileGhostPrefab(this AssetBundle assetBundle, string ghostName) { GameObject val = assetBundle.LoadAsset<GameObject>(ghostName); if ((Object)(object)val == (Object)null) { Log.Error("Failed to load ghost prefab " + ghostName); } if (!Object.op_Implicit((Object)(object)val.GetComponent<NetworkIdentity>())) { val.AddComponent<NetworkIdentity>(); } if (!Object.op_Implicit((Object)(object)val.GetComponent<ProjectileGhostController>())) { val.AddComponent<ProjectileGhostController>(); } ConvertAllRenderersToHopooShader(val); return val; } internal static GameObject CloneProjectilePrefab(string prefabName, string newPrefabName) { return PrefabAPI.InstantiateClone(LegacyResourcesAPI.Load<GameObject>("Prefabs/Projectiles/" + prefabName), newPrefabName); } internal static GameObject LoadAndAddProjectilePrefab(this AssetBundle assetBundle, string newPrefabName) { GameObject val = assetBundle.LoadAsset<GameObject>(newPrefabName); if ((Object)(object)val == (Object)null) { Log.ErrorAssetBundle(newPrefabName, ((Object)assetBundle).name); return null; } Content.AddProjectilePrefab(val); return val; } } public static class Config { public static ConfigFile MyConfig = ((BaseUnityPlugin)HenryPlugin.instance).Config; public static ConfigEntry<bool> CharacterEnableConfig(string section, string characterName, string description = "", bool enabledByDefault = true) { if (string.IsNullOrEmpty(description)) { description = "Set to false to disable this character and as much of its code and content as possible"; } return BindAndOptions(section, "Enable " + characterName, enabledByDefault, description, restartRequired: true); } public static ConfigEntry<T> BindAndOptions<T>(string section, string name, T defaultValue, string description = "", bool restartRequired = false) { return BindAndOptions(section, name, defaultValue, 0f, 20f, description, restartRequired); } public static ConfigEntry<T> BindAndOptions<T>(string section, string name, T defaultValue, float min, float max, string description = "", bool restartRequired = false) { if (string.IsNullOrEmpty(description)) { description = name; } if (restartRequired) { description += " (restart required)"; } ConfigEntry<T> result = MyConfig.Bind<T>(section, name, defaultValue, description); Chainloader.PluginInfos.ContainsKey("com.rune580.riskofoptions"); return result; } public static ConfigEntry<float> BindAndOptionsSlider(string section, string name, float defaultValue, string description, float min = 0f, float max = 20f, bool restartRequired = false) { return BindAndOptions(section, name, defaultValue, min, max, description, restartRequired); } [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)] private static void TryRegisterOption<T>(ConfigEntry<T> entry, float min, float max, bool restartRequired) { } public static bool GetKeyPressed(KeyboardShortcut entry) { //IL_0010: 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) foreach (KeyCode modifier in ((KeyboardShortcut)(ref entry)).Modifiers) { if (!Input.GetKey(modifier)) { return false; } } return Input.GetKeyDown(((KeyboardShortcut)(ref entry)).MainKey); } } internal class Content { internal static void AddCharacterBodyPrefab(GameObject bprefab) { ContentPacks.bodyPrefabs.Add(bprefab); } internal static void AddMasterPrefab(GameObject prefab) { ContentPacks.masterPrefabs.Add(prefab); } internal static void AddProjectilePrefab(GameObject prefab) { ContentPacks.projectilePrefabs.Add(prefab); } internal static void AddSurvivorDef(SurvivorDef survivorDef) { ContentPacks.survivorDefs.Add(survivorDef); } internal static void CreateSurvivor(GameObject bodyPrefab, GameObject displayPrefab, Color charColor, string tokenPrefix) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) CreateSurvivor(bodyPrefab, displayPrefab, charColor, tokenPrefix, null, 100f); } internal static void CreateSurvivor(GameObject bodyPrefab, GameObject displayPrefab, Color charColor, string tokenPrefix, float sortPosition) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) CreateSurvivor(bodyPrefab, displayPrefab, charColor, tokenPrefix, null, sortPosition); } internal static void CreateSurvivor(GameObject bodyPrefab, GameObject displayPrefab, Color charColor, string tokenPrefix, UnlockableDef unlockableDef) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) CreateSurvivor(bodyPrefab, displayPrefab, charColor, tokenPrefix, unlockableDef, 100f); } internal static void CreateSurvivor(GameObject bodyPrefab, GameObject displayPrefab, Color charColor, string tokenPrefix, UnlockableDef unlockableDef, float sortPosition) { //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Unknown result type (might be due to invalid IL or missing references) SurvivorDef obj = ScriptableObject.CreateInstance<SurvivorDef>(); obj.bodyPrefab = bodyPrefab; obj.displayPrefab = displayPrefab; obj.primaryColor = charColor; obj.cachedName = ((Object)bodyPrefab).name.Replace("Body", ""); obj.displayNameToken = tokenPrefix + "NAME"; obj.descriptionToken = tokenPrefix + "DESCRIPTION"; obj.outroFlavorToken = tokenPrefix + "OUTRO_FLAVOR"; obj.mainEndingEscapeFailureFlavorToken = tokenPrefix + "OUTRO_FAILURE"; obj.desiredSortPosition = sortPosition; obj.unlockableDef = unlockableDef; AddSurvivorDef(obj); } internal static void AddUnlockableDef(UnlockableDef unlockableDef) { ContentPacks.unlockableDefs.Add(unlockableDef); } internal static UnlockableDef CreateAndAddUnlockbleDef(string identifier, string nameToken, Sprite achievementIcon) { UnlockableDef obj = ScriptableObject.CreateInstance<UnlockableDef>(); obj.cachedName = identifier; obj.nameToken = nameToken; obj.achievementIcon = achievementIcon; AddUnlockableDef(obj); return obj; } internal static void AddSkillDef(SkillDef skillDef) { ContentPacks.skillDefs.Add(skillDef); } internal static void AddSkillFamily(SkillFamily skillFamily) { ContentPacks.skillFamilies.Add(skillFamily); } internal static void AddEntityState(Type entityState) { ContentPacks.entityStates.Add(entityState); } internal static void AddBuffDef(BuffDef buffDef) { ContentPacks.buffDefs.Add(buffDef); } internal static BuffDef CreateAndAddBuff(string buffName, Sprite buffIcon, Color buffColor, bool canStack, bool isDebuff) { //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Unknown result type (might be due to invalid IL or missing references) BuffDef obj = ScriptableObject.CreateInstance<BuffDef>(); ((Object)obj).name = buffName; obj.buffColor = buffColor; obj.canStack = canStack; obj.isDebuff = isDebuff; obj.eliteDef = null; obj.iconSprite = buffIcon; AddBuffDef(obj); return obj; } internal static void AddEffectDef(EffectDef effectDef) { ContentPacks.effectDefs.Add(effectDef); } internal static EffectDef CreateAndAddEffectDef(GameObject effectPrefab) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Expected O, but got Unknown //IL_000d: Expected O, but got Unknown EffectDef val = new EffectDef(effectPrefab); AddEffectDef(val); return val; } internal static void AddNetworkSoundEventDef(NetworkSoundEventDef networkSoundEventDef) { ContentPacks.networkSoundEventDefs.Add(networkSoundEventDef); } internal static NetworkSoundEventDef CreateAndAddNetworkSoundEventDef(string eventName) { NetworkSoundEventDef obj = ScriptableObject.CreateInstance<NetworkSoundEventDef>(); obj.akId = AkSoundEngine.GetIDFromString(eventName); obj.eventName = eventName; AddNetworkSoundEventDef(obj); return obj; } } internal class ContentPacks : IContentPackProvider { internal ContentPack contentPack = new ContentPack(); public static List<GameObject> bodyPrefabs = new List<GameObject>(); public static List<GameObject> masterPrefabs = new List<GameObject>(); public static List<GameObject> projectilePrefabs = new List<GameObject>(); public static List<SurvivorDef> survivorDefs = new List<SurvivorDef>(); public static List<UnlockableDef> unlockableDefs = new List<UnlockableDef>(); public static List<SkillFamily> skillFamilies = new List<SkillFamily>(); public static List<SkillDef> skillDefs = new List<SkillDef>(); public static List<Type> entityStates = new List<Type>(); public static List<BuffDef> buffDefs = new List<BuffDef>(); public static List<EffectDef> effectDefs = new List<EffectDef>(); public static List<NetworkSoundEventDef> networkSoundEventDefs = new List<NetworkSoundEventDef>(); private static bool survivorReady; public string identifier => "com.gabe.BeastGohan"; public void Initialize() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Expected O, but got Unknown ContentManager.collectContentPackProviders += new CollectContentPackProvidersDelegate(ContentManager_collectContentPackProviders); } private void ContentManager_collectContentPackProviders(AddContentPackProviderDelegate addContentPackProvider) { addContentPackProvider.Invoke((IContentPackProvider)(object)this); } public IEnumerator LoadStaticContentAsync(LoadStaticContentAsyncArgs args) { contentPack.identifier = identifier; if (!survivorReady) { args.ReportProgress(0.1f); IEnumerator preload = VanillaAssets.Preload(); while (preload.MoveNext()) { yield return null; } survivorReady = true; args.ReportProgress(0.6f); try { Log.Info("Loading Beast Gohan."); new GohanSurvivor().Initialize(); Log.Info("Beast Gohan loaded."); } catch (Exception data) { Log.Error("Beast Gohan failed to load. The game will continue without the survivor."); Log.Error(data); } } contentPack.bodyPrefabs.Add(bodyPrefabs.ToArray()); contentPack.masterPrefabs.Add(masterPrefabs.ToArray()); contentPack.projectilePrefabs.Add(projectilePrefabs.ToArray()); contentPack.survivorDefs.Add(survivorDefs.ToArray()); contentPack.unlockableDefs.Add(unlockableDefs.ToArray()); contentPack.skillDefs.Add(skillDefs.ToArray()); contentPack.skillFamilies.Add(skillFamilies.ToArray()); contentPack.entityStateTypes.Add(entityStates.ToArray()); contentPack.buffDefs.Add(buffDefs.ToArray()); contentPack.effectDefs.Add(effectDefs.ToArray()); contentPack.networkSoundEventDefs.Add(networkSoundEventDefs.ToArray()); args.ReportProgress(1f); } public IEnumerator GenerateContentPackAsync(GetContentPackAsyncArgs args) { ContentPack.Copy(contentPack, args.output); args.ReportProgress(1f); yield break; } public IEnumerator FinalizeAsync(FinalizeAsyncArgs args) { args.ReportProgress(1f); yield break; } } internal static class ItemDisplayCheck { public static List<Object> allDisplayedItems; public static void PrintUnused(ItemDisplayRuleSet itemDisplayRuleSet, string bodyName = "") { PrintUnused((IEnumerable<KeyAssetRuleGroup>)itemDisplayRuleSet.keyAssetRuleGroups.ToList(), bodyName); } public static void PrintUnused(IEnumerable<KeyAssetRuleGroup> ruleSet = null, string bodyName = "") { //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Unknown result type (might be due to invalid IL or missing references) //IL_003d: 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_004d: 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_0064: Unknown result type (might be due to invalid IL or missing references) string text = "generating item displays for " + bodyName; if (allDisplayedItems == null) { LazyGatherAllItems(); } List<Object> list = new List<Object>(allDisplayedItems); string text2 = ""; if (ruleSet != null) { foreach (KeyAssetRuleGroup item in ruleSet) { if (item.displayRuleGroup.rules.Length != 0) { list.Remove(item.keyAsset); if (string.IsNullOrEmpty(text2)) { text2 = item.displayRuleGroup.rules[0].childName; } } } } if (string.IsNullOrEmpty(text2)) { text2 = "Chest"; } foreach (Object item2 in list) { string text3 = ""; if (ItemDisplays.KeyAssetDisplayPrefabs.ContainsKey(item2)) { text3 += SpitOutNewRule(item2, text2, ItemDisplays.KeyAssetDisplayPrefabs[item2]); } else { Log.Error($"COULD NOT FIND DISPLAY PREFABS FOR KEYASSET {item2}"); } text += text3; } Log.Message(text); } private static void LazyGatherAllItems() { allDisplayedItems = new List<Object>(ItemDisplays.KeyAssetDisplayPrefabs.Keys); allDisplayedItems.Sort(delegate(Object item1, Object item2) { if (item1 is ItemDef && item2 is ItemDef) { return item1.name.CompareTo(item2.name); } if (item1 is EquipmentDef && item2 is EquipmentDef) { return item1.name.CompareTo(item2.name); } if (item1 is ItemDef && item2 is EquipmentDef) { return -1; } return (item1 is EquipmentDef && item2 is ItemDef) ? 1 : 0; }); } private static string SpitOutNewRule(Object asset, string firstCompatibleChild, ItemDisplayRule[] displayRules) { //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_008c: Unknown result type (might be due to invalid IL or missing references) if (displayRules.Length == 0) { return $"\n[NO DISPLAY RULES FOUND FOR THE KEYASSET {asset}"; } string text = "\n itemDisplayRules.Add(ItemDisplays.CreateDisplayRuleGroupWithRules(ItemDisplays.KeyAssets[\"" + asset.name + "\"]"; for (int i = 0; i < displayRules.Length; i++) { text = (((int)displayRules[i].limbMask != 0) ? (text + ",\n" + $" ItemDisplays.CreateLimbMaskDisplayRule(LimbFlags.{displayRules[i].limbMask})") : (text + ",\n ItemDisplays.CreateDisplayRule(ItemDisplays.LoadDisplay(\"" + ((Object)displayRules[i].followerPrefab).name + "\"),\n \"" + firstCompatibleChild + "\",\n new Vector3(2, 2, 2),\n new Vector3(0, 0, 0),\n new Vector3(1, 1, 1)\n )")); } return text + "\n ));"; } } internal static class ItemDisplays { private static Dictionary<string, GameObject> itemDisplayPrefabs = new Dictionary<string, GameObject>(); public static Dictionary<Object, ItemDisplayRule[]> KeyAssetDisplayPrefabs = new Dictionary<Object, ItemDisplayRule[]>(); public static Dictionary<string, Object> KeyAssets = new Dictionary<string, Object>(); public static int queuedDisplays; public static bool initialized = false; public static void LazyInit() { if (!initialized) { initialized = true; PopulateDisplays(); } } internal static void DisposeWhenDone() { queuedDisplays--; if (queuedDisplays <= 0 && initialized) { initialized = false; itemDisplayPrefabs = null; KeyAssetDisplayPrefabs = null; KeyAssets = null; } } internal static void PopulateDisplays() { PopulateFromBody("LoaderBody"); } private static void PopulateFromBody(string bodyName) { KeyAssetRuleGroup[] keyAssetRuleGroups = ((Component)LegacyResourcesAPI.Load<GameObject>("Prefabs/CharacterBodies/" + bodyName).GetComponent<ModelLocator>().modelTransform).GetComponent<CharacterModel>().itemDisplayRuleSet.keyAssetRuleGroups; for (int i = 0; i < keyAssetRuleGroups.Length; i++) { ItemDisplayRule[] rules = keyAssetRuleGroups[i].displayRuleGroup.rules; KeyAssetDisplayPrefabs[keyAssetRuleGroups[i].keyAsset] = rules; KeyAssets[keyAssetRuleGroups[i].keyAsset.name] = keyAssetRuleGroups[i].keyAsset; for (int j = 0; j < rules.Length; j++) { GameObject followerPrefab = rules[j].followerPrefab; if (Object.op_Implicit((Object)(object)followerPrefab)) { string key = ((Object)followerPrefab).name?.ToLowerInvariant(); if (!itemDisplayPrefabs.ContainsKey(key)) { itemDisplayPrefabs[key] = followerPrefab; } } } } } private static void PopulateCustomLightningArm() { GameObject val = PrefabAPI.InstantiateClone(itemDisplayPrefabs["displaylightningarmright"], "DisplayLightningCustom", false); LimbMatcher component = val.GetComponent<LimbMatcher>(); component.limbPairs[0].targetChildLimb = "LightningArm1"; component.limbPairs[1].targetChildLimb = "LightningArm2"; component.limbPairs[2].targetChildLimb = "LightningArmEnd"; itemDisplayPrefabs["displaylightningarmcustom"] = val; } public static GameObject LoadDisplay(string name) { if (itemDisplayPrefabs.ContainsKey(name.ToLowerInvariant()) && Object.op_Implicit((Object)(object)itemDisplayPrefabs[name.ToLowerInvariant()])) { return itemDisplayPrefabs[name.ToLowerInvariant()]; } Log.Error("item display " + name + " returned null"); return null; } public static KeyAssetRuleGroup CreateDisplayRuleGroupWithRules(string itemName, params ItemDisplayRule[] rules) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return CreateDisplayRuleGroupWithRules(GetKeyAssetFromString(itemName), rules); } public static KeyAssetRuleGroup CreateDisplayRuleGroupWithRules(Object keyAsset_, params ItemDisplayRule[] rules) { //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_0035: 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_003b: Unknown result type (might be due to invalid IL or missing references) if (keyAsset_ == (Object)null) { Log.Error("could not find keyasset"); } return new KeyAssetRuleGroup { keyAsset = keyAsset_, displayRuleGroup = new DisplayRuleGroup { rules = rules } }; } public static ItemDisplayRule CreateDisplayRule(string prefabName, string childName, Vector3 position, Vector3 rotation, Vector3 scale) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) return CreateDisplayRule(LoadDisplay(prefabName), childName, position, rotation, scale); } public static ItemDisplayRule CreateDisplayRule(GameObject itemPrefab, string childName, Vector3 position, Vector3 rotation, Vector3 scale) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Unknown result type (might be due to invalid IL or missing references) return new ItemDisplayRule { ruleType = (ItemDisplayRuleType)0, childName = childName, followerPrefab = itemPrefab, limbMask = (LimbFlags)0, localPos = position, localAngles = rotation, localScale = scale }; } public static ItemDisplayRule CreateLimbMaskDisplayRule(LimbFlags limb) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Unknown result type (might be due to invalid IL or missing references) return new ItemDisplayRule { ruleType = (ItemDisplayRuleType)1, limbMask = limb, childName = "", followerPrefab = null }; } private static Object GetKeyAssetFromString(string itemName) { Object val = (Object)(object)LegacyResourcesAPI.Load<ItemDef>("ItemDefs/" + itemName); if (val == (Object)null) { val = (Object)(object)LegacyResourcesAPI.Load<EquipmentDef>("EquipmentDefs/" + itemName); } if (val == (Object)null) { Log.Error("Could not load keyasset for " + itemName); } return val; } } internal static class Language { public static string TokensOutput = ""; public static bool usingLanguageFolder = false; public static bool printingEnabled = false; public static void Init() { if (usingLanguageFolder) { Language.collectLanguageRootFolders += Language_collectLanguageRootFolders; } } private static void Language_collectLanguageRootFolders(List<string> obj) { string text = Path.Combine(Path.GetDirectoryName(((BaseUnityPlugin)HenryPlugin.instance).Info.Location), "Language"); if (Directory.Exists(text)) { obj.Add(text); } } public static void Add(string token, string text) { if (!usingLanguageFolder) { LanguageAPI.Add(token, text); } if (printingEnabled) { TokensOutput = TokensOutput + "\n \"" + token + "\" : \"" + text.Replace(Environment.NewLine, "\\n").Replace("\n", "\\n") + "\","; } } public static void PrintOutput(string fileName = "") { if (printingEnabled) { string text = "{\n strings:\n {" + TokensOutput + "\n }\n}"; Log.Message(fileName + ": \n" + text); if (!string.IsNullOrEmpty(fileName)) { File.WriteAllText(Path.Combine(Directory.GetParent(((BaseUnityPlugin)HenryPlugin.instance).Info.Location).FullName, "Language", "en", fileName), text); } TokensOutput = ""; } } } internal static class Materials { private static List<Material> cachedMaterials = new List<Material>(); internal static Shader hotpoo; public static Material LoadMaterial(this AssetBundle assetBundle, string materialName) { return assetBundle.CreateHopooMaterialFromBundle(materialName); } public static Material CreateHopooMaterialFromBundle(this AssetBundle assetBundle, string materialName) { //IL_0089: Unknown result type (might be due to invalid IL or missing references) //IL_008f: Expected O, but got Unknown materialName = materialName.Replace(" (Instance)", ""); Material val = cachedMaterials.Find((Material mat) => ((Object)mat).name.Replace(" (Instance)", "") == materialName); if (Object.op_Implicit((Object)(object)val)) { Log.Debug(((Object)val).name + " has already been loaded. returning cached"); return val; } val = assetBundle.LoadAsset<Material>(materialName); if (!Object.op_Implicit((Object)(object)val)) { Log.ErrorAssetBundle(materialName, ((Object)assetBundle).name); return new Material(hotpoo); } return val.ConvertDefaultShaderToHopoo(); } public static Material SetHopooMaterial(this Material tempMat) { return tempMat.ConvertDefaultShaderToHopoo(); } public static Material ConvertDefaultShaderToHopoo(this Material tempMat) { //IL_00d8: Unknown result type (might be due to invalid IL or missing references) //IL_0179: Unknown result type (might be due to invalid IL or missing references) if (!Object.op_Implicit((Object)(object)tempMat)) { return tempMat; } if (!Object.op_Implicit((Object)(object)tempMat.shader)) { Log.Error(((Object)tempMat).name + " has no shader, so it was left unchanged."); return tempMat; } if (cachedMaterials.Contains(tempMat)) { Log.Debug(((Object)tempMat).name + " has already been converted. returning cached"); return tempMat; } string text = ((Object)tempMat.shader).name.ToLowerInvariant(); if (!text.StartsWith("standard") && !text.StartsWith("autodesk")) { Log.Debug(((Object)tempMat).name + " is not unity standard shader. aborting material conversion"); return tempMat; } float? num = null; Color? val = null; if (tempMat.IsKeywordEnabled("_NORMALMAP")) { num = tempMat.GetFloat("_BumpScale"); } if (tempMat.IsKeywordEnabled("_EMISSION")) { val = tempMat.GetColor("_EmissionColor"); } if (!Object.op_Implicit((Object)(object)hotpoo)) { Log.Error("HGStandard was not loaded, so " + ((Object)tempMat).name + " kept its imported shader."); return tempMat; } tempMat.shader = hotpoo; tempMat.SetTexture("_EmTex", tempMat.GetTexture("_EmissionMap")); tempMat.EnableKeyword("DITHER"); if (num.HasValue) { tempMat.SetFloat("_NormalStrength", num.Value); tempMat.SetTexture("_NormalTex", tempMat.GetTexture("_BumpMap")); } if (val.HasValue) { tempMat.SetColor("_EmColor", val.Value); tempMat.SetFloat("_EmPower", 1f); } if (tempMat.IsKeywordEnabled("NOCULL")) { tempMat.SetInt("_Cull", 0); } if (tempMat.IsKeywordEnabled("LIMBREMOVAL")) { tempMat.SetInt("_LimbRemovalOn", 1); } cachedMaterials.Add(tempMat); return tempMat; } public static Material MakeUnique(this Material material) { //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Expected O, but got Unknown if (cachedMaterials.Contains(material)) { return new Material(material); } return material; } public static Material SetColor(this Material material, Color color) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) material.SetColor("_Color", color); return material; } public static Material SetNormal(this Material material, float normalStrength = 1f) { material.SetFloat("_NormalStrength", normalStrength); return material; } public static Material SetEmission(this Material material) { return material.SetEmission(1f); } public static Material SetEmission(this Material material, float emission) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) return material.SetEmission(emission, Color.white); } public static Material SetEmission(this Material material, float emission, Color emissionColor) { //IL_0012: Unknown result type (might be due to invalid IL or missing references) material.SetFloat("_EmPower", emission); material.SetColor("_EmColor", emissionColor); return material; } public static Material SetCull(this Material material, bool cull = false) { material.SetInt("_Cull", cull ? 1 : 0); return material; } public static Material SetSpecular(this Material material, float strength) { material.SetFloat("_SpecularStrength", strength); return material; } public static Material SetSpecular(this Material material, float strength, float exponent) { material.SetFloat("_SpecularStrength", strength); material.SetFloat("SpecularExponent", exponent); return material; } } internal static class Prefabs { private static PhysicMaterial ragdollMaterial; public static GameObject CreateDisplayPrefab(AssetBundle assetBundle, string displayPrefabName, GameObject prefab) { GameObject val = assetBundle.LoadAsset<GameObject>(displayPrefabName); if ((Object)(object)val == (Object)null) { Log.Error("could not load display prefab " + displayPrefabName + ". Make sure this prefab exists in assetbundle " + ((Object)assetBundle).name); return null; } CharacterModel val2 = val.GetComponent<CharacterModel>(); if (!Object.op_Implicit((Object)(object)val2)) { val2 = val.AddComponent<CharacterModel>(); } CharacterModel val3 = (((Object)(object)prefab != (Object)null) ? prefab.GetComponentInChildren<CharacterModel>() : null); if (Object.op_Implicit((Object)(object)val3)) { val2.baseRendererInfos = val3.baseRendererInfos; } Asset.ConvertAllRenderersToHopooShader(val); return val; } public static GameObject LoadCharacterModel(AssetBundle assetBundle, string modelName) { if (!Object.op_Implicit((Object)(object)assetBundle)) { Log.Error("could not load model prefab " + modelName + " because the asset bundle did not load."); return null; } GameObject val = assetBundle.LoadAsset<GameObject>(modelName); if ((Object)(object)val == (Object)null) { Log.Error("could not load model prefab " + modelName + ". Make sure this prefab exists in assetbundle " + ((Object)assetBundle).name); return null; } return val; } public static GameObject LoadCharacterBody(AssetBundle assetBundle, string bodyName) { GameObject val = assetBundle.LoadAsset<GameObject>(bodyName); if ((Object)(object)val == (Object)null) { Log.Error("could not load body prefab " + bodyName + ". Make sure this prefab exists in assetbundle " + ((Object)assetBundle).name); return null; } return val; } public static GameObject CloneCharacterBody(BodyInfo bodyInfo) { GameObject val = ((bodyInfo.bodyNameToClone == "Commando") ? VanillaAssets.commandoBody : null); if (!Object.op_Implicit((Object)(object)val) && bodyInfo.bodyNameToClone != "Commando") { val = LegacyResourcesAPI.Load<GameObject>("Prefabs/CharacterBodies/" + bodyInfo.bodyNameToClone + "Body"); } if (!Object.op_Implicit((Object)(object)val)) { Log.Error(bodyInfo.bodyNameToClone + " Body to clone is not a valid body, character creation failed"); return null; } GameObject val2 = PrefabAPI.InstantiateClone(val, bodyInfo.bodyName); for (int num = val2.transform.childCount - 1; num >= 0; num--) { Object.DestroyImmediate((Object)(object)((Component)val2.transform.GetChild(num)).gameObject); } return val2; } public static GameObject CreateBodyPrefab(AssetBundle assetBundle, string modelPrefabName, BodyInfo bodyInfo) { return CreateBodyPrefab(LoadCharacterModel(assetBundle, modelPrefabName), bodyInfo); } public static GameObject CreateBodyPrefab(GameObject model, BodyInfo bodyInfo) { return CreateBodyPrefab(CloneCharacterBody(bodyInfo), model, bodyInfo); } public static GameObject CreateBodyPrefab(GameObject newBodyPrefab, AssetBundle assetBundle, string modelName, BodyInfo bodyInfo) { return CreateBodyPrefab(newBodyPrefab, LoadCharacterModel(assetBundle, modelName), bodyInfo); } public static GameObject CreateBodyPrefab(AssetBundle assetBundle, string bodyPrefabName, string modelPrefabName, BodyInfo bodyInfo) { return CreateBodyPrefab(LoadCharacterBody(assetBundle, bodyPrefabName), LoadCharacterModel(assetBundle, modelPrefabName), bodyInfo); } public static GameObject CreateBodyPrefab(GameObject newBodyPrefab, GameObject model, BodyInfo bodyInfo) { if ((Object)(object)model == (Object)null || (Object)(object)newBodyPrefab == (Object)null) { Log.Error($"Character creation failed. Model: {model}, Body: {newBodyPrefab}"); return null; } SetupCharacterBody(newBodyPrefab, bodyInfo); Transform modelBaseTransform = AddCharacterModelToSurvivorBody(newBodyPrefab, model.transform, bodyInfo); SetupModelLocator(newBodyPrefab, modelBaseTransform, model.transform); SetupCharacterDirection(newBodyPrefab, modelBaseTransform, model.transform); SetupCameraTargetParams(newBodyPrefab, bodyInfo); SetupCapsuleCollider(newBodyPrefab); Content.AddCharacterBodyPrefab(newBodyPrefab); return newBodyPrefab; } private static void SetupCharacterBody(GameObject newBodyPrefab, BodyInfo bodyInfo) { //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_01f6: Unknown result type (might be due to invalid IL or missing references) //IL_0204: Unknown result type (might be due to invalid IL or missing references) CharacterBody component = newBodyPrefab.GetComponent<CharacterBody>(); component.baseNameToken = bodyInfo.bodyNameToken; component.subtitleNameToken = bodyInfo.subtitleNameToken; component.portraitIcon = bodyInfo.characterPortrait; component.bodyColor = bodyInfo.bodyColor; component._defaultCrosshairPrefab = bodyInfo.crosshair; component.hideCrosshair = false; component.preferredPodPrefab = bodyInfo.podPrefab; component.baseMaxHealth = bodyInfo.maxHealth; component.baseRegen = bodyInfo.healthRegen; component.baseArmor = bodyInfo.armor; component.baseMaxShield = bodyInfo.shield; component.baseDamage = bodyInfo.damage; component.baseAttackSpeed = bodyInfo.attackSpeed; component.baseCrit = bodyInfo.crit; component.baseMoveSpeed = bodyInfo.moveSpeed; component.baseJumpPower = bodyInfo.jumpPower; component.autoCalculateLevelStats = bodyInfo.autoCalculateLevelStats; if (bodyInfo.autoCalculateLevelStats) { component.levelMaxHealth = Mathf.Round(component.baseMaxHealth * 0.3f); component.levelMaxShield = Mathf.Round(component.baseMaxShield * 0.3f); component.levelRegen = component.baseRegen * 0.2f; component.levelMoveSpeed = 0f; component.levelJumpPower = 0f; component.levelDamage = component.baseDamage * 0.2f; component.levelAttackSpeed = 0f; component.levelCrit = 0f; component.levelArmor = 0f; } else { component.levelMaxHealth = bodyInfo.healthGrowth; component.levelMaxShield = bodyInfo.shieldGrowth; component.levelRegen = bodyInfo.regenGrowth; component.levelMoveSpeed = bodyInfo.moveSpeedGrowth; component.levelJumpPower = bodyInfo.jumpPowerGrowth; component.levelDamage = bodyInfo.damageGrowth; component.levelAttackSpeed = bodyInfo.attackSpeedGrowth; component.levelCrit = bodyInfo.critGrowth; component.levelArmor = bodyInfo.armorGrowth; } component.baseAcceleration = bodyInfo.acceleration; component.baseJumpCount = bodyInfo.jumpCount; component.sprintingSpeedMultiplier = 1.45f; component.bodyFlags = (BodyFlags)16; component.rootMotionInMainState = false; component.hullClassification = (HullClassification)0; component.isChampion = false; } private static Transform AddCharacterModelToSurvivorBody(GameObject bodyPrefab, Transform modelTransform, BodyInfo bodyInfo) { //IL_005a: 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_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_0043: Unknown result type (might be due to invalid IL or missing references) //IL_008c: Unknown result type (might be due to invalid IL or missing references) //IL_00a4: Unknown result type (might be due to invalid IL or missing references) //IL_00ae: Unknown result type (might be due to invalid IL or missing references) //IL_00d7: Unknown result type (might be due to invalid IL or missing references) //IL_00f0: Unknown result type (might be due to invalid IL or missing references) //IL_00fb: Unknown result type (might be due to invalid IL or missing references) Transform val = bodyPrefab.transform.Find("ModelBase"); if ((Object)(object)val == (Object)null) { val = new GameObject("ModelBase").transform; val.parent = bodyPrefab.transform; val.localPosition = bodyInfo.modelBasePosition; val.localRotation = Quaternion.identity; } modelTransform.parent = ((Component)val).transform; modelTransform.localPosition = Vector3.zero; modelTransform.localRotation = Quaternion.identity; if ((Object)(object)bodyPrefab.transform.Find("CameraPivot") == (Object)null) { Transform transform = new GameObject("CameraPivot").transform; transform.parent = bodyPrefab.transform; transform.localPosition = bodyInfo.cameraPivotPosition; transform.localRotation = Quaternion.identity; } Transform val2 = bodyPrefab.transform.Find("AimOrigin"); if ((Object)(object)val2 == (Object)null) { val2 = new GameObject("AimOrigin").transform; val2.parent = bodyPrefab.transform; val2.localPosition = bodyInfo.aimOriginPosition; val2.localRotation = Quaternion.identity; } bodyPrefab.GetComponent<CharacterBody>().aimOriginTransform = val2; return ((Component)val).transform; } private static void SetupCharacterDirection(GameObject prefab, Transform modelBaseTransform, Transform modelTransform) { if (Object.op_Implicit((Object)(object)prefab.GetComponent<CharacterDirection>())) { CharacterDirection component = prefab.GetComponent<CharacterDirection>(); component.targetTransform = modelBaseTransform; component.overrideAnimatorForwardTransform = null; component.rootMotionAccumulator = null; component.modelAnimator = ((Component)modelTransform).GetComponent<Animator>(); component.driveFromRootRotation = false; component.turnSpeed = 720f; } } private static void SetupCameraTargetParams(GameObject prefab, BodyInfo bodyInfo) { CameraTargetParams component = prefab.GetComponent<CameraTargetParams>(); component.cameraParams = bodyInfo.cameraParams; component.cameraPivotTransform = prefab.transform.Find("CameraPivot"); } private static void SetupModelLocator(GameObject prefab, Transform modelBaseTransform, Transform modelTransform) { ModelLocator component = prefab.GetComponent<ModelLocator>(); component.modelTransform = modelTransform; component.modelBaseTransform = modelBaseTransform; } private static void SetupCapsuleCollider(GameObject prefab) { //IL_0016: Unknown result type (might be due to invalid IL or missing references) CapsuleCollider component = prefab.GetComponent<CapsuleCollider>(); component.center = new Vector3(0f, 0f, 0f); component.radius = 0.5f; component.height = 1.82f; component.direction = 1; } public static CharacterModel SetupCharacterModel(GameObject bodyPrefab, CustomRendererInfo[] customInfos = null) { CharacterModel val = ((Component)bodyPrefab.GetComponent<ModelLocator>().modelTransform).gameObject.GetComponent<CharacterModel>(); bool num = (Object)(object)val != (Object)null; if (!num) { val = ((Component)bodyPrefab.GetComponent<ModelLocator>().modelTransform).gameObject.AddComponent<CharacterModel>(); } val.body = bodyPrefab.GetComponent<CharacterBody>(); val.autoPopulateLightInfos = true; val.invisibilityCount = 0; val.temporaryOverlays = new List<TemporaryOverlayInstance>(); if (!num) { SetupCustomRendererInfos(val, customInfos); } else { SetupPreAttachedRendererInfos(val); } SetupHurtboxGroup(bodyPrefab, ((Component)val).gameObject); SetupAimAnimator(bodyPrefab, ((Component)val).gameObject); SetupFootstepController(((Component)val).gameObject); SetupRagdoll(((Component)val).gameObject); return val; } public static void SetupPreAttachedRendererInfos(CharacterModel characterModel) { for (int i = 0; i < characterModel.baseRendererInfos.Length; i++) { if ((Object)(object)characterModel.baseRendererInfos[i].defaultMaterial == (Object)null) { characterModel.baseRendererInfos[i].defaultMaterial = characterModel.baseRendererInfos[i].renderer.sharedMaterial; } if ((Object)(object)characterModel.baseRendererInfos[i].defaultMaterial == (Object)null) { Log.Error($"no material for rendererinfo of this renderer: {characterModel.baseRendererInfos[i].renderer}"); } characterModel.baseRendererInfos[i].defaultMaterial.ConvertDefaultShaderToHopoo(); } } public static void SetupCustomRendererInfos(CharacterModel characterModel, CustomRendererInfo[] customInfos) { //IL_00d1: Unknown result type (might be due to invalid IL or missing references) //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) ChildLocator component = ((Component)characterModel).GetComponent<ChildLocator>(); if (!Object.op_Implicit((Object)(object)component)) { Log.Error("Failed CharacterModel setup: ChildLocator component does not exist on the model"); return; } List<RendererInfo> list = new List<RendererInfo>(); for (int i = 0; i < customInfos.Length; i++) { if (!Object.op_Implicit((Object)(object)component.FindChild(customInfos[i].childName))) { Log.Error("Trying to add a RendererInfo for a renderer that does not exist: " + customInfos[i].childName); continue; } Renderer component2 = ((Component)component.FindChild(customInfos[i].childName)).GetComponent<Renderer>(); if (!Object.op_Implicit((Object)(object)component2)) { continue; } Material val = customInfos[i].material; if ((Object)(object)val == (Object)null) { if (!Object.op_Implicit((Object)(object)component2.sharedMaterial)) { Log.Error("Renderer has no material: " + ((Object)component2).name); continue; } val = (customInfos[i].dontHotpoo ? component2.sharedMaterial : component2.sharedMaterial.ConvertDefaultShaderToHopoo()); } list.Add(new RendererInfo { renderer = component2, defaultMaterial = val, ignoreOverlays = customInfos[i].ignoreOverlays, defaultShadowCastingMode = (ShadowCastingMode)1 }); } characterModel.baseRendererInfos = list.ToArray(); } private static void SetupHurtboxGroup(GameObject bodyPrefab, GameObject model) { SetupMainHurtboxesFromChildLocator(bodyPrefab, model); SetHurtboxesHealthComponents(bodyPrefab); } private static void SetupMainHurtboxesFromChildLocator(GameObject bodyPrefab, GameObject model) { //IL_0110: 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) if ((Object)(object)bodyPrefab.GetComponent<HurtBoxGroup>() != (Object)null) { Log.Debug("Hitboxgroup already exists on model prefab. aborting code setup"); return; } ChildLocator component = model.GetComponent<ChildLocator>(); if (!Object.op_Implicit((Object)(object)component)) { Log.Error("Could not set up main hurtbox: the model has no ChildLocator."); return; } if (string.IsNullOrEmpty(component.FindChildNameInsensitive("MainHurtbox"))) { Log.Error("Could not set up main hurtbox: make sure you have a transform pair in your prefab's ChildLocator called 'MainHurtbox'"); return; } HurtBoxGroup val = model.AddComponent<HurtBoxGroup>(); HurtBox val2 = null; GameObject val3 = component.FindChildGameObjectInsensitive("HeadHurtbox"); if (Object.op_Implicit((Object)(object)val3)) { Log.Debug("HeadHurtboxFound. Setting up"); val2 = val3.AddComponent<HurtBox>(); ((Component)val2).gameObject.layer = LayerIndex.entityPrecise.intVal; val2.healthComponent = bodyPrefab.GetComponent<HealthComponent>(); val2.isBullseye = false; val2.isSniperTarget = true; val2.damageModifier = (DamageModifier)0; val2.hurtBoxGroup = val; val2.indexInGroup = 1; } HurtBox val4 = component.FindChildGameObjectInsensitive("MainHurtbox").AddComponent<HurtBox>(); ((Component)val4).gameObject.layer = LayerIndex.entityPrecise.intVal; val4.healthComponent = bodyPrefab.GetComponent<HealthComponent>(); val4.isBullseye = true; val4.isSniperTarget = (Object)(object)val2 == (Object)null; val4.damageModifier = (DamageModifier)0; val4.hurtBoxGroup = val; val4.indexInGroup = 0; if (Object.op_Implicit((Object)(object)val2)) { val.hurtBoxes = (HurtBox[])(object)new HurtBox[2] { val4, val2 }; } else { val.hurtBoxes = (HurtBox[])(object)new HurtBox[1] { val4 }; } val.mainHurtBox = val4; val.bullseyeCount = 1; } private static string FindChildNameInsensitive(this ChildLocator childLocator, string child) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) return childLocator.transformPairs.Where((NameTransformPair pair) => pair.name.ToLowerInvariant() == child.ToLowerInvariant()).FirstOrDefault().name; } private static Transform FindChildInsensitive(this ChildLocator childLocator, string child) { return childLocator.FindChild(childLocator.FindChildNameInsensitive(child)); } private static GameObject FindChildGameObjectInsensitive(this ChildLocator childLocator, string child) { return childLocator.FindChildGameObject(childLocator.FindChildNameInsensitive(child)); } public static void SetHurtboxesHealthComponents(GameObject bodyPrefab) { HealthComponent component = bodyPrefab.GetComponent<HealthComponent>(); HurtBoxGroup[] componentsInChildren = bodyPrefab.GetComponentsInChildren<HurtBoxGroup>(); foreach (HurtBoxGroup val in componentsInChildren) { val.mainHurtBox.healthComponent = component; for (int j = 0; j < val.hurtBoxes.Length; j++) { val.hurtBoxes[j].healthComponent = component; } } } private static void SetupFootstepController(GameObject model) { FootstepHandler obj = model.AddComponent<FootstepHandler>(); obj.baseFootstepString = "Play_player_footstep"; obj.sprintFootstepOverrideString = ""; obj.footstepDustPrefab = VanillaAssets.footstepDust; obj.enableFootstepDust = Object.op_Implicit((Object)(object)obj.footstepDustPrefab); } private static void SetupRagdoll(GameObject model) { RagdollController component = model.GetComponent<RagdollController>(); if (!Object.op_Implicit((Object)(object)component)) { return; } if ((Object)(object)ragdollMaterial == (Object)null) { ragdollMaterial = ((Component)LegacyResourcesAPI.Load<GameObject>("Prefabs/CharacterBodies/CommandoBody").GetComponentInChildren<RagdollController>().bones[1]).GetComponent<Collider>().material; } Transform[] bones = component.bones; foreach (Transform val in bones) { if (Object.op_Implicit((Object)(object)val)) { ((Component)val).gameObject.layer = LayerIndex.ragdoll.intVal; Collider component2 = ((Component)val).GetComponent<Collider>(); if (Object.op_Implicit((Object)(object)component2)) { component2.sharedMaterial = ragdollMaterial; } else { Log.Error($"Ragdoll bone {((Component)val).gameObject} doesn't have a collider. Ragdoll will break."); } } } } private static void SetupAimAnimator(GameObject prefab, GameObject model) { AimAnimator obj = model.AddComponent<AimAnimator>(); obj.directionComponent = prefab.GetComponent<CharacterDirection>(); obj.pitchRangeMax = 60f; obj.pitchRangeMin = -60f; obj.yawRangeMin = -80f; obj.yawRangeMax = 80f; obj.pitchGiveupRange = 30f; obj.yawGiveupRange = 10f; obj.giveupDuration = 3f; obj.inputBank = prefab.GetComponent<InputBankTest>(); } public static void CreateGenericDoppelganger(GameObject bodyPrefab, string masterName, string masterToCopy) { CloneDopplegangerMaster(bodyPrefab, masterName, masterToCopy); } public static GameObject CloneDopplegangerMaster(GameObject bodyPrefab, string masterName, string masterToCopy) { GameObject obj = PrefabAPI.InstantiateClone(LegacyResourcesAPI.Load<GameObject>("Prefabs/CharacterMasters/" + masterToCopy + "MonsterMaster"), masterName, true); obj.GetComponent<CharacterMaster>().bodyPrefab = bodyPrefab; Content.AddMasterPrefab(obj); return obj; } public static GameObject CreateBlankMasterPrefab(GameObject bodyPrefab, string masterName) { GameObject val = PrefabAPI.InstantiateClone(LegacyResourcesAPI.Load<GameObject>("Prefabs/CharacterMasters/CommandoMonsterMaster"), masterName, true); ContentPacks.masterPrefabs.Add(val); val.GetComponent<CharacterMaster>().bodyPrefab = bodyPrefab; AISkillDriver[] components = val.GetComponents<AISkillDriver>(); for (int i = 0; i < components.Length; i++) { Object.Destroy((Object)(object)components[i]); } return val; } public static GameObject LoadMaster(this AssetBundle assetBundle, GameObject bodyPrefab, string assetName) { //IL_0040: 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) GameObject val = assetBundle.LoadAsset<GameObject>(assetName); BaseAI val2 = val.GetComponent<BaseAI>(); if ((Object)(object)val2 == (Object)null) { val2 = val.AddComponent<BaseAI>(); val2.aimVectorDampTime = 0.1f; val2.aimVectorMaxSpeed = 360f; } val2.scanState = new SerializableEntityStateType(typeof(Wander)); EntityStateMachine component = val.GetComponent<EntityStateMachine>(); if ((Object)(object)component == (Object)null) { AddEntityStateMachine(val, "AI", typeof(Wander), typeof(Wander)); } val2.stateMachine = component; CharacterMaster val3 = val.GetComponent<CharacterMaster>(); if ((Object)(object)val3 == (Object)null) { val3 = val.AddComponent<CharacterMaster>(); } val3.bodyPrefab = bodyPrefab; val3.teamIndex = (TeamIndex)2; Content.AddMasterPrefab(val); return val; } public static void ClearEntityStateMachines(GameObject bodyPrefab) { EntityStateMachine[] components = bodyPrefab.GetComponents<EntityStateMachine>(); for (int num = components.Length - 1; num >= 0; num--) { Object.DestroyImmediate((Object)(object)components[num]); } bodyPrefab.GetComponent<NetworkStateMachine>().stateMachines = Array.Empty<EntityStateMachine>(); CharacterDeathBehavior component = bodyPrefab.GetComponent<CharacterDeathBehavior>(); if (Object.op_Implicit((Object)(object)component)) { component.idleStateMachine = Array.Empty<EntityStateMachine>(); } SetStateOnHurt component2 = bodyPrefab.GetComponent<SetStateOnHurt>(); if (Object.op_Implicit((Object)(object)component2)) { component2.idleStateMachine = Array.Empty<EntityStateMachine>(); } CharacterBody component3 = bodyPrefab.GetComponent<CharacterBody>(); if (Object.op_Implicit((Object)(object)component3)) { component3.vehicleIdleStateMachine = Array.Empty<EntityStateMachine>(); } } public static EntityStateMachine AddEntityStateMachine(GameObject prefab, string machineName, Type mainStateType = null, Type initalStateType = null, bool addToHurt = true, bool addToDeath = true) { //IL_004d: 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) //IL_006e: 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) EntityStateMachine val = EntityStateMachine.FindByCustomName(prefab, machineName); if ((Object)(object)val == (Object)null) { val = prefab.AddComponent<EntityStateMachine>(); } else { Log.Message("An Entity State Machine already exists with the name " + machineName + ". replacing."); } val.customName = machineName; if (mainStateType == null) { mainStateType = typeof(Idle); } val.mainStateType = new SerializableEntityStateType(mainStateType); if (initalStateType == null) { initalStateType = typeof(Idle); } val.initialStateType = new SerializableEntityStateType(initalStateType); NetworkStateMachine component = prefab.GetComponent<NetworkStateMachine>(); if (Object.op_Implicit((Object)(object)component)) { component.stateMachines = component.stateMachines.Append(val).ToArray(); } CharacterDeathBehavior component2 = prefab.GetComponent<CharacterDeathBehavior>(); if (Object.op_Implicit((Object)(object)component2) && addToDeath) { component2.idleStateMachine = component2.idleStateMachine.Append(val).ToArray(); } SetStateOnHurt component3 = prefab.GetComponent<SetStateOnHurt>(); if (Object.op_Implicit((Object)(object)component3) && addToHurt) { component3.idleStateMachine = component3.idleStateMachine.Append(val).ToArray(); } CharacterBody component4 = prefab.GetComponent<CharacterBody>(); if (Object.op_Implicit((Object)(object)component4)) { component4.vehicleIdleStateMachine = component4.vehicleIdleStateMachine.Append(val).ToArray(); } return val; } public static EntityStateMachine AddMainEntityStateMachine(GameObject bodyPrefab, string machineName = "Body", Type mainStateType = null, Type initalStateType = null) { //IL_004d: 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) //IL_006e: 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) EntityStateMachine val = EntityStateMachine.FindByCustomName(bodyPrefab, machineName); if ((Object)(object)val == (Object)null) { val = bodyPrefab.AddComponent<EntityStateMachine>(); } else { Log.Message("An Entity State Machine already exists with the name " + machineName + ". replacing."); } val.customName = machineName; if (mainStateType == null) { mainStateType = typeof(GenericCharacterMain); } val.mainStateType = new SerializableEntityStateType(mainStateType); if (initalStateType == null) { initalStateType = typeof(SpawnTeleporterState); } val.initialStateType = new SerializableEntityStateType(initalStateType); NetworkStateMachine component = bodyPrefab.GetComponent<NetworkStateMachine>(); if (Object.op_Implicit((Object)(object)component)) { component.stateMachines = component.stateMachines.Append(val).ToArray(); } CharacterDeathBehavior component2 = bodyPrefab.GetComponent<CharacterDeathBehavior>(); if (Object.op_Implicit((Object)(object)component2)) { component2.deathStateMachine = val; } SetStateOnHurt component3 = bodyPrefab.GetComponent<SetStateOnHurt>(); if (Object.op_Implicit((Object)(object)component3)) { component3.targetStateMachine = val; } return val; } public static void SetupHitBoxGroup(GameObject modelPrefab, string hitBoxGroupName, params string[] hitboxChildNames) { ChildLocator component = modelPrefab.GetComponent<ChildLocator>(); Transform[] array = (Transform[])(object)new Transform[hitboxChildNames.Length]; for (int i = 0; i < hitboxChildNames.Length; i++) { array[i] = component.FindChild(hitboxChildNames[i]); if ((Object)(object)array[i] == (Object)null) { Log.Error("missing hitbox for " + hitboxChildNames[i]); } } SetupHitBoxGroup(modelPrefab, hitBoxGroupName, array); } public static void SetupHitBoxGroup(GameObject prefab, string hitBoxGroupName, params Transform[] hitBoxTransforms) { List<HitBox> list = new List<HitBox>(); foreach (Transform val in hitBoxTransforms) { if ((Object)(object)val == (Object)null) { Log.Error("Error setting up hitboxGroup for " + hitBoxGroupName + ": hitbox transform was null"); continue; } HitBox item = ((Component)val).gameObject.AddComponent<HitBox>(); ((Component)val).gameObject.layer = LayerIndex.projectile.intVal; list.Add(item); } if (list.Count == 0) { Log.Error("No hitboxes were set up. aborting setting up hitboxGroup for " + hitBoxGroupName); return; } HitBoxGroup obj = prefab.AddComponent<HitBoxGroup>(); obj.hitBoxes = list.ToArray(); obj.groupName = hitBoxGroupName; } } public class CustomRendererInfo { public string childName; public Material material; public bool dontHotpoo; public bool ignoreOverlays; } internal static class Skills { public static void CreateSkillFamilies(GameObject targetPrefab) { SkillSlot[] array = new SkillSlot[4]; RuntimeHelpers.InitializeArray(array, (RuntimeFieldHandle)/*OpCode not supported: LdMemberToken*/); CreateSkillFamilies(targetPrefab, (SkillSlot[])(object)array); } public static void CreateSkillFamilies(GameObject targetPrefab, params SkillSlot[] slots) { //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Expected I4, but got Unknown SkillLocator component = targetPrefab.GetComponent<SkillLocator>(); foreach (SkillSlot val in slots) { switch (val - -1) { case 1: component.primary = CreateGenericSkillWithSkillFamily(targetPrefab, "Primary"); break; case 2: component.secondary = CreateGenericSkillWithSkillFamily(targetPrefab, "Secondary"); break; case 3: component.utility = CreateGenericSkillWithSkillFamily(targetPrefab, "Utility"); break; case 4: component.special = CreateGenericSkillWithSkillFamily(targetPrefab, "Special"); break; } } } public static void ClearGenericSkills(GameObject targetPrefab) { GenericSkill[] componentsInChildren = targetPrefab.GetComponentsInChildren<GenericSkill>(); for (int i = 0; i < componentsInChildren.Length; i++) { Object.DestroyImmediate((Object)(object)componentsInChildren[i]); } } public static GenericSkill CreateGenericSkillWithSkillFamily(GameObject targetPrefab, SkillSlot skillSlot, bool hidden = false) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Expected I4, but got Unknown SkillLocator component = targetPrefab.GetComponent<SkillLocator>(); switch (skillSlot - -1) { case 1: return component.primary = CreateGenericSkillWithSkillFamily(targetPrefab, "Primary", hidden); case 2: return component.secondary = CreateGenericSkillWithSkillFamily(targetPrefab, "Secondary", hidden); case 3: return component.utility = CreateGenericSkillWithSkillFamily(targetPrefab, "Utility", hidden); case 4: return component.special = CreateGenericSkillWithSkillFamily(targetPrefab, "Special", hidden); case 0: Log.Error("Failed to create GenericSkill with skillslot None. If making a GenericSkill outside of the main 4, specify a familyName, and optionally a genericSkillName"); return null; default: return null; } } public static GenericSkill CreateGenericSkillWithSkillFamily(GameObject targetPrefab, string familyName, bool hidden = false) { return CreateGenericSkillWithSkillFamily(targetPrefab, familyName, familyName, hidden); } public static GenericSkill CreateGenericSkillWithSkillFamily(GameObject targetPrefab, string genericSkillName, string familyName, bool hidden = false) { GenericSkill obj = targetPrefab.AddComponent<GenericSkill>(); obj.skillName = genericSkillName; obj.hideInCharacterSelect = hidden; SkillFamily val = ScriptableObject.CreateInstance<SkillFamily>(); ((Object)val).name = ((Object)targetPrefab).name + familyName + "Family"; val.variants = (Variant[])(object)new Variant[0]; obj._skillFamily = val; Content.AddSkillFamily(val); return obj; } public static void AddSkillToFamily(SkillFamily skillFamily, SkillDef skillDef, UnlockableDef unlockableDef = null) { //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_0051: Expected O, but got Unknown //IL_0051: 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) Array.Resize(ref skillFamily.variants, skillFamily.variants.Length + 1); Variant[] variants = skillFamily.variants; int num = skillFamily.variants.Length - 1; Variant val = new Variant { skillDef = skillDef, unlockableDef = unlockableDef }; ((Variant)(ref val)).viewableNode = new Node(skillDef.skillNameToken, false, (Node)null); variants[num] = val; } public static void AddSkillsToFamily(SkillFamily skillFamily, params SkillDef[] skillDefs) { foreach (SkillDef skillDef in skillDefs) { AddSkillToFamily(skillFamily, skillDef); } } public static void AddPrimarySkills(GameObject targetPrefab, params SkillDef[] skillDefs) { AddSkillsToFamily(targetPrefab.GetComponent<SkillLocator>().primary.skillFamily, skillDefs); } public static void AddSecondarySkills(GameObject targetPrefab, params SkillDef[] skillDefs) { AddSkillsToFamily(targetPrefab.GetComponent<SkillLocator>().secondary.skillFamily, skillDefs); } public static void AddUtilitySkills(GameObject targetPrefab, params SkillDef[] skillDefs) { AddSkillsToFamily(targetPrefab.GetComponent<SkillLocator>().utility.skillFamily, skillDefs); } public static void AddSpecialSkills(GameObject targetPrefab, params SkillDef[] skillDefs) { AddSkillsToFamily(targetPrefab.GetComponent<SkillLocator>().special.skillFamily, skillDefs); } public static void AddUnlockablesToFamily(SkillFamily skillFamily, params UnlockableDef[] unlockableDefs) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Unknown result type (might be due to invalid IL or missing references) for (int i = 0; i < unlockableDefs.Length; i++) { Variant val = skillFamily.variants[i]; val.unlockableDef = unlockableDefs[i]; skillFamily.variants[i] = val; } } public static SkillDef CreateSkillDef(SkillDefInfo skillDefInfo) { return Skills.CreateSkillDef<SkillDef>(skillDefInfo); } public static T CreateSkillDef<T>(SkillDefInfo skillDefInfo) where T : SkillDef { //IL_0061: Unknown result type (might be due to invalid IL or missing references) //IL_0066: Unknown result type (might be due to invalid IL or missing references) //IL_0083: Unknown result type (might be due to invalid IL or missing references) //IL_0088: Unknown result type (might be due to invalid IL or missing references) T val = ScriptableObject.CreateInstance<T>(); ((SkillDef)val).skillName = skillDefInfo.skillName; ((Object)(object)val).name = skillDefInfo.skillName; ((SkillDef)val).skillNameToken = skillDefInfo.skillNameToken; ((SkillDef)val).skillDescriptionToken = skillDefInfo.skillDescriptionToken; ((SkillDef)val).icon = skillDefInfo.skillIcon; ((SkillDef)val).activationState = skillDefInfo.activationState; ((SkillDef)val).activationStateMachineName = skillDefInfo.activationStateMachineName; ((SkillDef)val).interruptPriority = skillDefInfo.interruptPriority; ((SkillDef)val).baseMaxStock = skillDefInfo.baseMaxStock; ((SkillDef)val).baseRechargeInterval = skillDefInfo.baseRechargeInterval; ((SkillDef)val).rechargeStock = skillDefInfo.rechargeStock; ((SkillDef)val).requiredStock = skillDefInfo.requiredStock; ((SkillDef)val).stockToConsume = skillDefInfo.stockToConsume; ((SkillDef)val).dontAllowPastMaxStocks = skillDefInfo.dontAllowPastMaxStocks; ((SkillDef)val).beginSkillCooldownOnSkillEnd = skillDefInfo.beginSkillCooldownOnSkillEnd; ((SkillDef)val).canceledFromSprinting = skillDefInfo.canceledFromSprinting; ((SkillDef)val).forceSprintDuringState = skillDefInfo.forceSprintDuringState; ((SkillDef)val).fullRestockOnAssign = skillDefInfo.fullRestockOnAssign; ((SkillDef)val).resetCooldownTimerOnUse = skillDefInfo.resetCooldownTimerOnUse; ((SkillDef)val).isCombatSkill = skillDefInfo.isCombatSkill; ((SkillDef)val).mustKeyPress = skillDefInfo.mustKeyPress; ((SkillDef)val).cancelSprintingOnActivation = skillDefInfo.cancelSprintingOnActivation; ((SkillDef)val).keywordTokens = skillDefInfo.keywordTokens; Content.AddSkillDef((SkillDef)(object)val); return val; } } internal class SkillDefInfo { public string skillName; public string skillNameToken; public string skillDescriptionToken; public string[] keywordTokens = Array.Empty<string>(); public Sprite skillIcon; public SerializableEntityStateType activationState; public string activationStateMachineName; public InterruptPriority interruptPriority; public float baseRechargeInterval; public int baseMaxStock = 1; public int rechargeStock = 1; public int requiredStock = 1; public int stockToConsume = 1; public bool resetCooldownTimerOnUse; public bool fullRestockOnAssign = true; public bool dontAllowPastMaxStocks; public bool beginSkillCooldownOnSkillEnd; public bool mustKeyPress; public bool isCombatSkill = true; public bool canceledFromSprinting; public bool cancelSprintingOnActivation = true; public bool forceSprintDuringState; public SkillDefInfo() { } public SkillDefInfo(string skillName, string skillNameToken, string skillDescriptionToken, Sprite skillIcon, SerializableEntityStateType activationState, string activationStateMachineName = "Weapon", bool agile = false) { //IL_0060: 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_0094: Unknown result type (might be due to invalid IL or missing references) this.skillName = skillName; this.skillNameToken = skillNameToken; this.skillDescriptionToken = skillDescriptionToken; this.skillIcon = skillIcon; this.activationState = activationState; this.activationStateMachineName = activationStateMachineName; cancelSprintingOnActivation = !agile; if (agile) { keywordTokens = new string[1] { "KEYWORD_AGILE" }; } interruptPriority = (InterruptPriority)0; isCombatSkill = true; baseRechargeInterval = 0f; requiredStock = 0; stockToConsume = 0; } } internal static class Skins { internal struct SkinDefInfo { internal SkinDef[] BaseSkins; internal Sprite Icon; internal string NameToken; internal UnlockableDef UnlockableDef; internal GameObject RootObject; internal RendererInfo[] RendererInfos; internal MeshReplacement[] MeshReplacements; internal GameObjectActivation[] GameObjectActivations; internal ProjectileGhostReplacement[] ProjectileGhostReplacements; internal MinionSkinReplacement[] MinionSkinReplacements; internal string Name; } internal static SkinDef CreateSkinDef(string skinName, Sprite skinIcon, RendererInfo[] defaultRendererInfos, GameObject root, UnlockableDef unlockableDef = null) { //IL_0089: Unknown result type (might be due to invalid IL or missing references) //IL_0093: Expected O, but got Unknown //IL_0130: Unknown result type (might be due to invalid IL or missing references) //IL_013a: Expected O, but got Unknown SkinDefInfo skinDefInfo = new SkinDefInfo { BaseSkins = Array.Empty<SkinDef>(), GameObjectActivations = (GameObjectActivation[])(object)new GameObjectActivation[0], Icon = skinIcon, MeshReplacements = (MeshReplacement[])(object)new MeshReplacement[0], MinionSkinReplacements = (MinionSkinReplacement[])(object)new MinionSkinReplacement[0], Name = skinName, NameToken = skinName, ProjectileGhostReplacements = (ProjectileGhostReplacement[])(object)new ProjectileGhostReplacement[0], RendererInfos = (RendererInfo[])(object)new RendererInfo[defaultRendererInfos.Length], RootObject = root, UnlockableDef = unlockableDef }; SkinDef.Awake += new hook_Awake(DoNothing); SkinDef obj = ScriptableObject.CreateInstance<SkinDef>(); obj.baseSkins = skinDefInfo.BaseSkins; obj.icon = skinDefInfo.Icon; obj.unlockableDef = skinDefInfo.UnlockableDef; obj.rootObject = skinDefInfo.RootObject; defaultRendererInfos.CopyTo(skinDefInfo.RendererInfos, 0); obj.rendererInfos = skinDefInfo.RendererInfos; obj.gameObjectActivations = skinDefInfo.GameObjectActivations; obj.meshReplacements = skinDefInfo.MeshReplacements; obj.projectileGhostReplacements = skinDefInfo.ProjectileGhostReplacements; obj.minionSkinReplacements = skinDefInfo.MinionSkinReplacements; obj.nameToken = skinDefInfo.NameToken; ((Object)obj).name = skinDefInfo.Name; SkinDef.Awake -= new hook_Awake(DoNothing); return obj; } private static void DoNothing(orig_Awake orig, SkinDef self) { } private static RendererInfo[] getRendererMaterials(RendererInfo[] defaultRenderers, params Material[] materials) { RendererInfo[] array = (RendererInfo[])(object)new RendererInfo[defaultRenderers.Length]; defaultRenderers.CopyTo(array, 0); for (int i = 0; i < array.Length; i++) { try { array[i].defaultMaterial = materials[i]; } catch { Log.Error("error adding skin rendererinfo material. make sure you're not passing in too many"); } } return array; } internal static MeshReplacement[] getMeshReplacements(AssetBundle assetBundle, RendererInfo[] defaultRendererInfos, params string[] meshes) { //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Unknown result type (might be due to invalid IL or missing references) List<MeshReplacement> list = new List<MeshReplacement>(); for (int i = 0; i < defaultRendererInfos.Length; i++) { if (!string.IsNullOrEmpty(meshes[i])) { list.Add(new MeshReplacement { renderer = defaultRendererInfos[i].renderer, mesh = assetBundle.LoadAsset<Mesh>(meshes[i]) }); } } return list.ToArray(); } } internal static class Tokens { public const string agilePrefix = "<style=cIsUtility>Agile.</style>"; public static string DamageText(string text) { return "<style=cIsDamage>" + text + "</style>"; } public static string DamageValueText(float value) { return $"<style=cIsDamage>{value * 100f}% damage</style>"; } public static string UtilityText(string text) { return "<style=cIsUtility>" + text + "</style>"; } public static string RedText(string text) { return HealthText(text); } public static string HealthText(string text) { return "<style=cIsHealth>" + text + "</style>"; } public static string KeywordText(string keyword, string sub) { return "<style=cKeywordName>" + keyword + "</style><style=cSub>" + sub + "</style>"; } public static string ScepterDescription(string desc) { return "\n<color=#d299ff>SCEPTER: " + desc + "</color>"; } public static string GetAchievementNameToken(string identifier) { return "ACHIEVEMENT_" + identifier.ToUpperInvariant() + "_NAME"; } public static string GetAchievementDescriptionToken(string identifier) { return "ACHIEVEMENT_" + identifier.ToUpperInvariant() + "_DESCRIPTION"; } } internal static class VanillaAssets { private class Request { public string address; public Type type; public Action<Object> assign; public object handle; public bool done; } private const float TimeoutSeconds = 90f; internal static GameObject commandoBody; internal static GameObject mercMaster; internal static GameObject lightningBomb; internal static GameObject survivorPod; internal static GameObject crosshair; internal static GameObject tracer; internal static GameObject explosion; internal static GameObject footstepDust; internal static GameObject punchSwing; internal static GameObject punchImpact; internal static GameObject beamTracer; internal static GameObject beamImpact; internal static GameObject rushBurst; internal static GameObject masenkoCharge; internal static GameObject masenkoMuzzle; internal static GameObject beamCharge; internal static GameObject guardFlash; public static IEnumerator Preload() { List<Request> requests = new List<Request>(); Add("RoR2/Base/Commando/CommandoBody.prefab", delegate(GameObject v) { commandoBody = v; }); Add("RoR2/Base/Merc/MercMonsterMaster.prefab", delegate(GameObject v) { mercMaster = v; }); Add("RoR2/Base/Mage/MageLightningBombProjectile.prefab", delegate(GameObject v) { lightningBomb = v; }); Add("RoR2/Base/SurvivorPod/SurvivorPod.prefab", delegate(GameObject v) { survivorPod = v; }); Add("RoR2/Base/UI/StandardCrosshair.prefab", delegate(GameObject v) { crosshair = v; }); Add("RoR2/Base/Golem/TracerGolem.prefab", delegate(GameObject v) { tracer = v; }); Add("RoR2/Base/Common/VFX/OmniExplosionVFX.prefab", delegate(GameObject v) { explosion = v; }); Add("RoR2/Base/Common/VFX/GenericFootstepDust.prefab", delegate(GameObject v) { footstepDust = v; }); Add("RoR2/Base/Loader/LoaderSwingBasic.prefab", delegate(GameObject v) { punchSwing = v; }); Add("RoR2/Base/Loader/OmniImpactVFXLoader.prefab", delegate(GameObject v) { punchImpact = v; }); Add("RoR2/DLC1/Railgunner/TracerRailgunSuper.prefab", delegate(GameObject v) { beamTracer = v; }); Add("RoR2/DLC1/Railgunner/ImpactRailgun.prefab", delegate(GameObject v) { beamImpact = v; }); Add("RoR2/Base/Loader/LoaderGroundSlam.prefab", delegate(GameObject v) { rushBurst = v; }); Add("RoR2/Base/Mage/ChargeMageLightningBomb.prefab", delegate(GameObject v) { masenkoCharge = v; }); Add("RoR2/Base/Mage/MuzzleflashMageLightningLarge.prefab", delegate(GameObject v) { masenkoMuzzle = v; }); Add("RoR2/Base/Golem/ChargeGolem.prefab", delegate(GameObject v) { beamCharge = v; }); Add("RoR2/Base/Loader/OmniImpactVFXLoaderLightning.prefab", delegate(GameObject v) { guardFlash = v; }); requests.Add(new Request { address = "RoR2/Base/Shaders/HGStandard.shader", type = typeof(Shader), assign = delegate(Object o) { Materials.hotpoo = (Shader)(object)((o is Shader) ? o : null); } }); foreach (Request item in requests) { item.handle = StartLoad(item.address, item.type); if (item.handle == null) { item.done = true; item.assign(null); } } float start = Time.realtimeSinceStartup; while (true) { bool flag = false; foreach (Request item2 in requests) { if (!item2.done) { if (IsDone(item2.handle)) { item2.done = true; item2.assign(Result(item2.handle, item2.address)); } else { flag = true; } } } if (!flag) { break; } if (Time.realtimeSinceStartup - start > 90f) { foreach (Request item3 in requests) { if (!item3.done) { Log.Error("Timed out loading " + item3.address); item3.assign(null); } } break; } yield return null; } if (!Object.op_Implicit((Object)(object)beamTracer)) { beamTracer = tracer; } if (!Object.op_Implicit((Object)(object)beamImpact)) { beamImpact = explosion; } if (!Object.op_Implicit((Object)(object)rushBurst)) { rushBurst = explosion; } Log.Info("Vanilla assets ready in " + (Time.realtimeSinceStartup - start).ToString("0.0") + "s. body=" + ((Object)(object)commandoBody != (Object)null) + " master=" + ((Object)(object)mercMaster != (Object)null) + " bomb=" + ((Object)(object)lightningBomb != (Object)null) + " pod=" + ((Object)(object)survivorPod != (Object)null) + " crosshair=" + ((Object)(object)crosshair != (Object)null) + " swing=" + ((Object)(object)punchSwing != (Object)null) + " impact=" + ((Object)(object)punchImpact != (Object)null) + " beam=" + ((Object)(object)beamTracer != (Object)null) + " shader=" + ((Object)(object)Materials.hotpoo != (Object)null)); void Add(string address, Action<GameObject> assign) { requests.Add(new Request { address = address, type = typeof(GameObject), assign = delegate(Object o) { assign((GameObject)(object)((o is GameObject) ? o : null)); } }); } } private static object StartLoad(string address, Type assetType) { Type type = Type.GetType("UnityEngine.AddressableAssets.Addressables, Unity.Addressables"); if (type == null) { Log.Error("Unity.Addressables is not loaded, so " + address + " was skipped."); return null; } MethodInfo methodInfo = null; MethodInfo[] methods = type.GetMethods(BindingFlags.Static | BindingFlags.Public); foreach (MethodInfo methodInfo2 in methods) { if (!(methodInfo2.Name != "LoadAssetAsync") && methodInfo2.IsGenericMethodDefinition) { ParameterInfo[] parameters = methodInfo2.GetParameters(); if (parameters.Length == 1 && (parameters[0].ParameterType == typeof(object) || parameters[0].ParameterType == typeof(string))) { methodInfo = methodInfo2; break; } } } if (methodInfo == null) { Log.Error("Addressables.LoadAssetAsync was not found."); return null; } try { return methodInfo.MakeGenericMethod(assetType).Invoke(null, new object[1] { address }); } catch (Exception ex) { Log.Error("Could not start loading " + address + ": " + (ex.InnerException ?? ex)); return null; } } private static bool IsDone(object handle) { try { PropertyInfo property = handle.GetType().GetProperty("IsDone"); return property == null || (bool)property.GetValue(handle, null); } catch { return true; } } private static Object Result(object handle, string address) { try { PropertyInfo property = handle.GetType().GetProperty("Status"); object obj = ((property != null) ? property.GetValue(handle, null) : null); if (obj != null && obj.ToString() != "Succeeded") { PropertyInfo property2 = handle.GetType().GetProperty("OperationException"); object obj2 = ((property2 != null) ? property2.GetValue(handle, null) : null); Log.Error("Failed to load " + address + ": " + obj?.ToString() + ((obj2 != null) ? (" " + obj2) : "")); return null; } object? value = handle.GetType().GetProperty("Result").GetValue(handle, null); return (Object)((value is Object) ? value : null); } catch (Exception ex) { Log.Error("Failed to load " + address + ": " + (ex.InnerException ?? ex)); return null; } } } } namespace HenryMod.Modules.Characters { public abstract class CharacterBase<T> where T : CharacterBase<T>, new() { public abstract string assetBundleName { get; } public abstract string bodyName { get; } public abstract string modelPrefabName { get; } public abstract BodyInfo bodyInfo { get; } public virtual CustomRendererInfo[] customRendererInfos { get; } public virtual ItemDisplaysBase itemDisplays { get; } public static T instance { get; private set; } public abstract AssetBundle assetBundle { get; protected set; } public abstract GameObject bodyPrefab { get; protected set; } public abstract CharacterBody prefabCharacterBody { get; protected set; } public abstract GameObject characterModelObject { get; protected set; } public abstract CharacterModel prefabCharacterModel { get; protected set; } public virtual void Initialize() { instance = this as T; assetBundle = Asset.LoadAssetBundle(assetBundleName); InitializeCharacter(); } public virtual void InitializeCharacter() { InitializeCharacterBodyPrefab(); InitializeItemDisplays(); } protected virtual void InitializeCharacterBodyPrefab() { characterModelObject = Prefabs.LoadCharacterModel(assetBundle, modelPrefabName); if (!Object.op_Implicit((Object)(object)characterModelObject) && Object.op_Implicit((Object)(object)assetBundle)) { Log.Error("Asset bundle contains: " + string.Join(", ", assetBundle.GetAllAssetNames())); } bodyPrefab = Prefabs.CreateBodyPrefab(characterModelObject, bodyInfo); if (!Object.op_Implicit((Object)(object)bodyPrefab)) { Log.Error(bodyName + " body was not created."); return; } prefabCharacterBody = bodyPrefab.GetComponent<CharacterBody>(); prefabCharacterModel = Prefabs.SetupCharacterModel(bodyPrefab, customRendererInfos); } public virtual void InitializeItemDisplays() { if (!Object.op_Implicit((Object)(object)prefabCharacterModel)) { Log.Error(bodyName + " has no character model, so item displays were skipped."); return; } ItemDisplayRuleSet val = ScriptableObject.CreateInstance<ItemDisplayRuleSet>(); ((Object)val).name = "idrs" + bodyName; prefabCharacterModel.itemDisplayRuleSet = val; if (itemDisplays != null) { ItemDisplays.queuedDisplays++; ContentManager.onContentPacksAssigned += SetItemDisplays; } } public void SetItemDisplays(ReadOnlyArray<ReadOnlyContentPack> obj) { itemDisplays.SetItemDisplays(prefabCharacterModel.itemDisplayRuleSet); } public abstract void InitializeEntityStateMachines(); public abstract void InitializeSkills(); public abstract void InitializeSkins(); public abstract void InitializeCharacterMaster(); } public class BodyInfo { public string bodyName = ""; public string bodyNameToken = ""; public string subtitleNameToken = ""; public string bodyNameToClone = "Commando"; public Color bodyColor = Color.white; public Texture characterPortrait; public float sortPosition = 100f; public GameObject crosshair; public GameObject podPrefab; public float maxHealth = 100f; public float healthRegen = 1f; public float armor; public float shield; public int jumpCount = 1; public float damage = 12f; public float attackSpeed = 1f; public float crit = 1f; public float moveSpeed = 7f; public float acceleration = 80f; public float jumpPower = 15f; public bool autoCalculateLevelStats = true; public float healthGrowth = 30.000002f; public float regenGrowth = 0.2f; public float armorGrowth; public float shieldGrowth; public float damageGrowth = 2.4f; public float attackSpeedGrowth; public float critGrowth; public float moveSpeedGrowth; public float jumpPowerGrowth; public Vector3 aimOriginPosition = new Vector3(0f, 1.6f, 0f); public Vector3 modelBasePosition = new Vector3(0f, -0.92f, 0f); public Vector3 cameraPivotPosition = new Vector3(0f, 0.8f, 0f); public float cameraParamsVerticalOffset = 1.37f; public float cameraParamsDepth = -10f; private CharacterCameraParams _cameraParams; public CharacterCameraParams cameraParams { get { //IL_002c: 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_0046: Unknown result type (might be due to invalid IL or missing references) //IL_004b: Unknown result type (might be due to invalid IL or missing references) //IL_0060: 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_007b: Unknown result type (might be due to invalid IL or missing references) //IL_0080: Unknown result type (might be due to invalid IL or missing references) //IL_00a0: Unknown result type (might be due to invalid IL or missing references) //IL_00a5: Unknown result type (might be due to invalid IL or missing references) //IL_00aa: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)_cameraParams == (Object)null) { _cameraParams = ScriptableObject.CreateInstance<CharacterCameraParams>(); _cameraParams.data.minPitch = BlendableFloat.op_Implicit(-70f); _cameraParams.data.maxPitch = BlendableFloat.op_Implicit(70f); _cameraParams.data.wallCushion = BlendableFloat.op_Implicit(0.1f); _cameraParams.data.pivotVerticalOffset = BlendableFloat.op_Implicit(cameraParamsVerticalOffset); _cameraParams.data.idealLocalCameraPos = BlendableVector3.op_Implicit(new Vector3(0f, 0f, cameraParamsDepth)); } return _cameraParams; } set { _cameraParams = value; } } } public abstract class ItemDisplaysBase { public void SetItemDisplays(ItemDisplayRuleSet itemDisplayRuleSet) { List<KeyAssetRuleGroup> list = new List<KeyAssetRuleGroup>(); ItemDisplays.LazyInit(); SetItemDisplayRules(list); itemDisplayRuleSet.keyAssetRuleGroups = list.ToArray(); ItemDisplays.DisposeWhenDone(); } protected abstract void SetItemDisplayRules(List<KeyAssetRuleGroup> itemDisplayRules); } public abstract class SurvivorBase<T> : CharacterBase<T> where T : SurvivorBase<T>, new() { public abstract string masterName { get; } public abstract string displayPrefabName { get; } public abstract string survivorTokenPrefix { get; } public abstract UnlockableDef characterUnlockableDef { get; } public abstract GameObject displayPrefab { get; protected set; } public override void InitializeCharacter() { base.InitializeCharacter(); try { InitializeDisplayPrefab(); } catch (Exception data) { Log.Error("Display prefab setup failed. The survivor will still be registered."); Log.Error(data); } if (!Object.op_Implicit((Object)(object)bodyPrefab)) { Log.Error(bodyName + " has no body prefab, so it will not be added to character select."); return; } if (!Object.op_Implicit((Object)(object)displayPrefab)) { displayPrefab = bodyPrefab; Log.Error(bodyName + " display prefab was missing. Using the body prefab so character select can list him."); } InitializeSurvivor(); Log.Info(bodyName + " added to character select."); } protected virtual void InitializeDisplayPrefab() { displayPrefab = Prefabs.CreateDisplayPrefab(assetBundle, displayPrefabName, bodyPrefab); } protected virtual void InitializeSurvivor() { //IL_0012: Unknown result type (might be due to invalid IL or missing references) Content.CreateSurvivor(bodyPrefab, displayPrefab, bodyInfo.bodyColor, survivorTokenPrefix, characterUnlockableDef, bodyInfo.sortPosition); } protected virtual void AddCssPreviewSkill(int indexFromEditor, SkillFamily skillFamily, SkillDef skillDef) { CharacterSelectSurvivorPreviewDisplayController component = displayPrefab.GetComponent<CharacterSelectSurvivorPreviewDisplayController>(); if (!Object.op_Implicit((Object)(object)component)) { Log.Error("trying to add skillChangeResponse to null CharacterSelectSurvivorPreviewDisplayController.\nMake sure you created one on your Display prefab in editor"); return; } component.skillChangeResponses[indexFromEditor].triggerSkillFamily = skillFamily; component.skillChangeResponses[indexFromEditor].triggerSkill = skillDef; } protected virtual void AddCssPreviewSkin(int indexFromEditor, SkinDef skinDef) { CharacterSelectSurvivorPreviewDisplayController component = displayPrefab.GetComponent<CharacterSelectSurvivorPreviewDisplayController>(); if (!Object.op_Implicit((Object)(object)component)) { Log.Error("trying to add skinChangeResponse to null CharacterSelectSurvivorPreviewDisplayController.\nMake sure you created one on your Display prefab in editor"); } else { component.skinChangeResponses[indexFromEditor].triggerSkin = skinDef; } } protected virtual void FinalizeCSSPreviewDisplayController() { //IL_005a: Unknown result type (might be due to invalid IL or missing references) if (!Object.op_Implicit((Object)(object)displayPrefab)) { return; } CharacterSelectSurvivorPreviewDisplayController component = displayPrefab.GetComponent<CharacterSelectSurvivorPreviewDisplayController>(); if (!Object.op_Implicit((Object)(object)component)) { return; } component.bodyPrefab = bodyPrefab; List<SkillChangeResponse> list = new List<SkillChangeResponse>(); for (int i = 0; i < component.skillChangeResponses.Length; i++) { if ((Object)(object)component.skillChangeResponses[i].triggerSkillFamily != (Object)null) { list.Add(component.skillChangeResponses[i]); } } component.skillChangeResponses = list.ToArray(); } } } namespace HenryMod.Modules.BaseStates { public abstract class BaseMeleeAttack : BaseSkillState, IStepSetter { public int swingIndex; protected string hitboxGroupName = "SwordGroup"; protected DamageTypeCombo damageType = DamageTypeCombo.op_Implicit((DamageType)0); protected float damageCoefficient = 3.5f; protected float procCoefficient = 1f; protected float pushForce = 300f; protected Vector3 bonusForce = Vector3.zero; protected float baseDuration = 1f; protected float attackStartPercentTime = 0.2f; protected float attackEndPercentTime = 0.4f; protected float earlyExitPercentTime = 0.4f; protected float hitStopDuration = 0.012f; protected float attackRecoil = 0.75f; protected float hitHopVelocity = 4f; protected string swingSoundString = ""; protected string hitSoundString = ""; protected string muzzleString = "SwingCenter"; protected string playbackRateParam = "Slash.playbackRate"; protected GameObject swingEffectPrefab; protected GameObject hitEffectPrefab; protected NetworkSoundEventIndex impactSound = (NetworkSoundEventIndex)(-1); protected OverlapAttack attack; public float duration; private bool hasFired; private float hitPauseTimer; protected bool inHitPause; private bool hasHopped; protected float stopwatch; protected Animator animator; private HitStopCachedState hitStopCachedState; private Vector3 storedVelocity; public override void OnEnter() { //IL_003f: Unknown result type (might be due to invalid IL or missing references) //IL_0049: Expected O, but got Unknown //IL_0050: Unknown result type (might be due to invalid IL or missing references) //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_0083: Unknown result type (might be due to invalid IL or missing references) //IL_0088: Unknown result type (might be due to invalid IL or missing references) //IL_00ce: Unknown result type (might be due to invalid IL or missing references) //IL_00d3: Unknown result type (might be due to invalid IL or missing references) //IL_0118: Unknown result type (might be due to invalid IL or missing references) //IL_011d: Unknown result type (might be due to invalid IL or missing references) ((BaseState)this).OnEnter(); duration = baseDuration / ((BaseState)this).attackSpeedStat; animator = ((EntityState)this).GetModelAnimator(); ((BaseState)this).StartAimMode(0.5f + duration, false); PlayAttackAnimation(); attack = new OverlapAttack(); attack.damageType = damageType; attack.attacker = ((EntityState)this).gameObject; attack.inflictor = ((EntityState)this).gameObject; attack.teamIndex = ((BaseState)this).GetTeam(); attack.damage = damageCoefficient * ((BaseState)this).damageStat; attack.procCoefficient = procCoefficient; attack.hitEffectPrefab = hitEffectPrefab; attack.forceVector = bonusForce; attack.pushAwayForce = pushForce; attack.hitBoxGroup = ((BaseState)this).FindHitBoxGroup(hitboxGroupName); attack.isCrit = ((BaseState)this).RollCrit(); attack.impactSound = impactSound; ModifyOverlapAttack(attack); } protected virtual void ModifyOverlapAttack(OverlapAttack attack) { } protected virtual void PlayAttackAnimation() { ((EntityState)this).PlayCrossfade("Gesture, Override", "Slash" + (1 + swingIndex), playbackRateParam, duration, 0.05f); } public ove
plugins/BeastGohanIcons.dll
Decompiled 2 hours agousing System; using System.Diagnostics; using System.IO; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using BepInEx; using RoR2; using RoR2.Skills; using UnityEngine; [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("BeastGohanIcons")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0")] [assembly: AssemblyProduct("BeastGohanIcons")] [assembly: AssemblyTitle("BeastGohanIcons")] [assembly: AssemblyVersion("1.0.0.0")] namespace BeastGohanIcons; [BepInPlugin("com.gabe.BeastGohanIcons", "Beast Gohan Ability Icons", "1.0.4")] [BepInDependency(/*Could not decode attribute arguments.*/)] public sealed class Icons : BaseUnityPlugin { private void Awake() { RoR2Application.onLoad = (Action)Delegate.Combine(RoR2Application.onLoad, new Action(Apply)); } private void OnDestroy() { RoR2Application.onLoad = (Action)Delegate.Remove(RoR2Application.onLoad, new Action(Apply)); } private void Apply() { GameObject val = BodyCatalog.FindBodyPrefab("BeastGohanBody"); SkillLocator val2 = (Object.op_Implicit((Object)(object)val) ? val.GetComponent<SkillLocator>() : null); if (!Object.op_Implicit((Object)(object)val2)) { ((BaseUnityPlugin)this).Logger.LogWarning((object)"BeastGohanBody skill slots were unavailable."); return; } SetIcon(val2.primary, "GABE_GOHAN_PRIMARY_COMBO_NAME", "Combo"); SetIcon(val2.secondary, "GABE_GOHAN_SECONDARY_KICK_NAME", "Kick"); SetIcon(val2.utility, "GABE_GOHAN_UTILITY_GUARD_NAME", "Guard"); SetIcon(val2.special, "GABE_GOHAN_SPECIAL_BEAM_NAME", "Beam"); val2.passiveSkill.icon = LoadIcon("Rage"); } private void SetIcon(GenericSkill slot, string token, string art) { //IL_0027: Unknown result type (might be due to invalid IL or missing references) if (Object.op_Implicit((Object)(object)slot) && Object.op_Implicit((Object)(object)slot.skillFamily)) { Variant[] variants = slot.skillFamily.variants; for (int i = 0; i < variants.Length; i++) { SkillDef skillDef = variants[i].skillDef; if (Object.op_Implicit((Object)(object)skillDef) && skillDef.skillNameToken == token) { skillDef.icon = LoadIcon(art); return; } } } ((BaseUnityPlugin)this).Logger.LogWarning((object)("Could not locate skill " + token)); } private static Sprite LoadIcon(string name) { //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Expected O, but got Unknown //IL_0084: Unknown result type (might be due to invalid IL or missing references) //IL_0093: Unknown result type (might be due to invalid IL or missing references) using Stream stream = typeof(Icons).Assembly.GetManifestResourceStream("Art." + name + ".png"); using BinaryReader binaryReader = new BinaryReader(stream); Texture2D val = new Texture2D(2, 2, (TextureFormat)4, false); if (!ImageConversion.LoadImage(val, binaryReader.ReadBytes((int)stream.Length), true)) { throw new InvalidDataException("Could not decode icon " + name); } ((Texture)val).wrapMode = (TextureWrapMode)1; ((Texture)val).filterMode = (FilterMode)1; Sprite obj = Sprite.Create(val, new Rect(0f, 0f, (float)((Texture)val).width, (float)((Texture)val).height), new Vector2(0.5f, 0.5f), 100f, 0u, (SpriteMeshType)0); ((Object)obj).name = "BeastGohan" + name + "Icon"; return obj; } }
plugins/BeastGohanVoice.dll
Decompiled 2 hours agousing System; using System.Collections.Generic; using System.Diagnostics; using System.IO; 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 BepInEx; using BepInEx.Bootstrap; using BepInEx.Configuration; using EntityStates; using HarmonyLib; using Microsoft.CodeAnalysis; using RoR2; using RoR2.UI; using UnityEngine; using UnityEngine.Networking; [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("BeastGohanVoice")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0")] [assembly: AssemblyProduct("BeastGohanVoice")] [assembly: AssemblyTitle("BeastGohanVoice")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.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.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace BeastGohanVoice { internal sealed class CombatAudio { private readonly MeleeOutput melee = new MeleeOutput(); private readonly MeleeOutput flight = new MeleeOutput(); private readonly string folder; private readonly string cache = Path.Combine(Path.GetTempPath(), "GohanEffects-" + Guid.NewGuid().ToString("N")); private readonly Dictionary<string, int> open = new Dictionary<string, int>(); private readonly HashSet<string> messages = new HashSet<string>(); private readonly Action<string> report; private readonly CuePool swings = new CuePool("PunchSwing1", "PunchSwing2", "PunchSwing3"); private readonly CuePool hits = new CuePool("PunchHit1", "PunchHit2", "PunchHit3"); private readonly Random random = new Random(); [DllImport("winmm.dll", CharSet = CharSet.Unicode, ExactSpelling = true)] private static extern uint mciSendStringW(string command, StringBuilder result, int size, IntPtr callback); internal void StartFlight(int volume) { if (volume <= 0) { return; } try { flight.Play("FlightWind", folder, volume, loop: true); LogOnce("Submitted Gohan flight loop"); } catch (Exception ex) { LogOnce("Failed Gohan flight loop: " + ex.Message); } } internal void StopFlight() { flight.Collect(stop: true); } internal void Update() { melee.Collect(stop: false); } internal CombatAudio(string folder, Action<string> report) { this.folder = folder; this.report = report; } private void LogOnce(string message) { if (messages.Add(message)) { report(message); } } private static void Command(string command) { uint num = mciSendStringW(command, null, 0, IntPtr.Zero); if (num != 0) { throw new IOException("Windows MCI error " + num); } } internal void Play(string cue, int volume) { if (volume <= 0) { return; } string text = ((cue == "PunchSwing") ? swings.Draw(random) : ((cue == "PunchHit") ? hits.Draw(random) : cue)); string text2 = "bgfx" + text; try { if (cue.StartsWith("Punch", StringComparison.Ordinal) || cue.StartsWith("Kick", StringComparison.Ordinal)) { melee.Play(text, folder, volume); LogOnce("Submitted Gohan melee audio: " + cue); return; } if (!open.TryGetValue(text, out var value) || value != volume) { if (open.ContainsKey(text)) { Command("close " + text2); open.Remove(text); } Directory.CreateDirectory(cache); string path = text + ".wav"; string text3 = Path.Combine(cache, path); File.WriteAllBytes(text3, VoiceMix.Scale(File.ReadAllBytes(Path.Combine(folder, path)), volume)); Command("open \"" + text3 + "\" type waveaudio alias " + text2); open.Add(text, volume); } Command("play " + text2 + " from 0"); LogOnce("Started Gohan effect: " + cue); } catch (Exception ex) { LogOnce("Failed Gohan effect " + text + ": " + ex.Message); } } internal void StopCharge() { if (open.ContainsKey("BeamCharge")) { mciSendStringW("stop bgfxBeamCharge", null, 0, IntPtr.Zero); } } internal void Dispose() { StopFlight(); melee.Collect(stop: true); foreach (string key in open.Keys) { mciSendStringW("close bgfx" + key, null, 0, IntPtr.Zero); } try { if (Directory.Exists(cache)) { Directory.Delete(cache, recursive: true); } } catch (IOException ex) { report(ex.Message); } catch (UnauthorizedAccessException ex2) { report(ex2.Message); } } } internal sealed class DamageReaction { private float nextHurt; private float hitAt = float.NegativeInfinity; private float lossAt = float.NegativeInfinity; private float previousHealth = -1f; private float previousMax; internal bool Dead { get; private set; } internal static bool IsChunk(float loss, float maximum, int percent) { if (maximum > 0f && loss > 0f) { return loss >= maximum * ((float)percent / 100f); } return false; } internal bool Hurt(float now) { if (Dead || now < nextHurt) { return false; } nextHurt = now + 4f; return true; } internal void NoteLargeHit(float now) { hitAt = now; } internal bool Observe(float health, float maximum, int percent, float now) { if (previousHealth >= 0f && previousMax == maximum && IsChunk(previousHealth - health, maximum, percent)) { lossAt = now; } previousHealth = health; previousMax = maximum; if (now - hitAt > 0.4f || now - lossAt > 0.4f) { return false; } hitAt = (lossAt = float.NegativeInfinity); return Hurt(now); } internal bool Die() { if (Dead) { return false; } Dead = true; return true; } } internal sealed class MeleeOutput { [StructLayout(LayoutKind.Sequential, Pack = 2)] private struct Format { public ushort tag; public ushort channels; public uint rate; public uint byteRate; public ushort align; public ushort bits; public ushort extra; } private struct Header { public IntPtr data; public uint length; public uint recorded; public UIntPtr user; public uint flags; public uint loops; public IntPtr next; public UIntPtr reserved; } private sealed class Shot { internal IntPtr device; internal IntPtr header; internal GCHandle pcm; internal bool prepared; } private static readonly uint headerSize = (uint)Marshal.SizeOf<Header>(); private readonly List<Shot> active = new List<Shot>(); private readonly Dictionary<string, (Format format, byte[] pcm, int gain)> clips = new Dictionary<string, (Format, byte[], int)>(); [DllImport("winmm.dll")] private static extern uint waveOutOpen(out IntPtr handle, uint device, ref Format format, IntPtr callback, IntPtr instance, uint flags); [DllImport("winmm.dll")] private static extern uint waveOutPrepareHeader(IntPtr handle, IntPtr header, uint size); [DllImport("winmm.dll")] private static extern uint waveOutWrite(IntPtr handle, IntPtr header, uint size); [DllImport("winmm.dll")] private static extern uint waveOutUnprepareHeader(IntPtr handle, IntPtr header, uint size); [DllImport("winmm.dll")] private static extern uint waveOutReset(IntPtr handle); [DllImport("winmm.dll")] private static extern uint waveOutClose(IntPtr handle); private static void Check(uint result) { if (result != 0) { throw new IOException("Windows waveOut error " + result); } } internal void Play(string key, string folder, int gain, bool loop = false) { if (!clips.TryGetValue(key, out (Format, byte[], int) value) || value.Item3 != gain) { string text = Path.Combine(folder, key + ".wav"); using Stream stream = (File.Exists(text) ? File.OpenRead(text) : typeof(MeleeOutput).Assembly.GetManifestResourceStream("Melee." + key + ".wav")); if (stream == null) { throw new FileNotFoundException("Missing effect", text); } using MemoryStream memoryStream = new MemoryStream(); stream.CopyTo(memoryStream); using BinaryReader binaryReader = new BinaryReader(new MemoryStream(VoiceMix.Scale(memoryStream.ToArray(), gain))); Format item = default(Format); binaryReader.BaseStream.Position = 12L; int num; while (true) { string text2 = Encoding.ASCII.GetString(binaryReader.ReadBytes(4)); num = binaryReader.ReadInt32(); long num2 = binaryReader.BaseStream.Position + num; if (num < 0 || num2 > binaryReader.BaseStream.Length) { throw new InvalidDataException("Invalid WAV size"); } if (text2 == "fmt ") { item.tag = binaryReader.ReadUInt16(); item.channels = binaryReader.ReadUInt16(); item.rate = binaryReader.ReadUInt32(); item.byteRate = binaryReader.ReadUInt32(); item.align = binaryReader.ReadUInt16(); item.bits = binaryReader.ReadUInt16(); } if (text2 == "data") { break; } binaryReader.BaseStream.Position = num2 + (num & 1); } value = (item, binaryReader.ReadBytes(num), gain); clips[key] = value; } Collect(stop: false); if (active.Count >= 24) { return; } Shot shot = new Shot(); Check(waveOutOpen(out shot.device, uint.MaxValue, ref value.Item1, IntPtr.Zero, IntPtr.Zero, 0u)); active.Add(shot); try { shot.pcm = GCHandle.Alloc(value.Item2, GCHandleType.Pinned); shot.header = Marshal.AllocHGlobal((int)headerSize); Marshal.StructureToPtr(new Header { data = shot.pcm.AddrOfPinnedObject(), length = (uint)value.Item2.Length, flags = (loop ? 12u : 0u), loops = (loop ? uint.MaxValue : 0u) }, shot.header, fDeleteOld: false); Check(waveOutPrepareHeader(shot.device, shot.header, headerSize)); shot.prepared = true; Check(waveOutWrite(shot.device, shot.header, headerSize)); } catch { CollectOne(active.Count - 1, stop: true); throw; } } internal void Collect(bool stop) { for (int num = active.Count - 1; num >= 0; num--) { CollectOne(num, stop); } } private void CollectOne(int index, bool stop) { Shot shot = active[index]; if (stop) { waveOutReset(shot.device); } else if ((Marshal.PtrToStructure<Header>(shot.header).flags & 1) == 0) { return; } if (!shot.prepared || waveOutUnprepareHeader(shot.device, shot.header, headerSize) == 0) { if (shot.pcm.IsAllocated) { shot.pcm.Free(); } if (shot.header != IntPtr.Zero) { Marshal.FreeHGlobal(shot.header); } waveOutClose(shot.device); active.RemoveAt(index); } } } [BepInPlugin("com.gabe.BeastGohanVoice", "Beast Gohan English Voice", "1.0.24")] [BepInDependency(/*Could not decode attribute arguments.*/)] public sealed class Voice : BaseUnityPlugin { private const string Id = "com.gabe.BeastGohanVoice"; private const string Survivor = "com.gabe.BeastGohan"; private const string States = "HenryMod.Survivors.Gohan.SkillStates."; private static Voice instance; private readonly HashSet<string> firstPlayback = new HashSet<string>(); private Harmony harmony; private ConfigEntry<bool> voicesEnabled; private string root; private string mixDirectory; private int gain; private ConfigEntry<int> hurtPercent; private DamageReaction reaction = new DamageReaction(); private readonly CuePool hurtLines = new CuePool("Hurt", "Hurt2", "Hurt3"); private readonly Random voiceRandom = new Random(); private readonly PrimaryTiming primaryTiming = new PrimaryTiming(); private readonly CuePool grunts = new CuePool("Combo", "Combo2", "Combo3", "Combo4", "Combo5", "Combo6"); private readonly CuePool selectLines = new CuePool("Select", "Select2", "Select3", "Select4"); private readonly CuePool jumps = new CuePool("Combo", "Combo2", "Combo3"); private readonly CuePool unleashLines = new CuePool("Unleash", "Unleash2"); private readonly CuePool kickLines = new CuePool("Kick", "Kick2", "Kick3", "Kick4"); private readonly CuePool finisherLines = new CuePool("Finisher", "Finisher2"); private int lastJumpCount; private float nextJumpGrunt; private bool flying; private CombatAudio combat; private readonly Queue<string> meleeEffects = new Queue<string>(); private ConfigEntry<int> effectsVolume; private Type comboType; private EntityState lastPunchHit; private string current; private Type firingType; private Type chargeType; private Type guardType; private EntityState lastSpecial; private EntityState lastUtility; private CharacterSelectController selectionScreen; private bool gohanSelected; private float busyUntil; private int priority; private CharacterBody owner; private bool counter; private bool awakened; private BuffIndex counterIndex = (BuffIndex)(-1); private BuffIndex awakenIndex = (BuffIndex)(-1); private readonly HashSet<string> warnings = new HashSet<string>(); private float lastSelectLine = -10f; [DllImport("winmm.dll", CharSet = CharSet.Unicode, ExactSpelling = true)] private static extern bool PlaySoundW(string file, IntPtr module, uint flags); private void Awake() { //IL_007a: Unknown result type (might be due to invalid IL or missing references) //IL_0084: Expected O, but got Unknown //IL_00b3: Unknown result type (might be due to invalid IL or missing references) //IL_00bd: Expected O, but got Unknown //IL_00e7: Unknown result type (might be due to invalid IL or missing references) //IL_00f1: Expected O, but got Unknown //IL_013f: Unknown result type (might be due to invalid IL or missing references) //IL_014d: Expected O, but got Unknown //IL_01ce: Unknown result type (might be due to invalid IL or missing references) //IL_01db: Expected O, but got Unknown //IL_0200: Unknown result type (might be due to invalid IL or missing references) //IL_020d: Expected O, but got Unknown //IL_024d: Unknown result type (might be due to invalid IL or missing references) //IL_025a: Expected O, but got Unknown //IL_029a: Unknown result type (might be due to invalid IL or missing references) //IL_02a7: Expected O, but got Unknown //IL_02cd: Unknown result type (might be due to invalid IL or missing references) //IL_02d7: Expected O, but got Unknown if (Environment.OSVersion.Platform == PlatformID.Win32NT) { instance = this; voicesEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>("Playback", "Enabled", true, "Play English cues for your local Beast Gohan."); root = Path.Combine(Path.GetDirectoryName(((BaseUnityPlugin)this).Info.Location), "Voices"); gain = ((BaseUnityPlugin)this).Config.Bind<int>("Playback", "VoiceVolumePercent", 25, new ConfigDescription("Voice gain relative to 1.0.5. Restart the game after changing it.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 100), Array.Empty<object>())).Value; hurtPercent = ((BaseUnityPlugin)this).Config.Bind<int>("Playback", "HeavyHitPercent", 20, new ConfigDescription("Health plus shield lost to a single hit, as a percent of the maximum, to trigger a hurt grunt.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 100), Array.Empty<object>())); Assembly assembly = ((object)Chainloader.PluginInfos["com.gabe.BeastGohan"].Instance).GetType().Assembly; harmony = new Harmony("com.gabe.BeastGohanVoice"); GlobalEventManager.onServerDamageDealt += ServerHit; GlobalEventManager.onClientDamageNotified += ClientHit; harmony.Patch((MethodBase)AccessTools.Method(typeof(CharacterBody), "OnDeathStart", (Type[])null, (Type[])null), new HarmonyMethod(typeof(Voice), "DeathStarted", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); chargeType = assembly.GetType("HenryMod.Survivors.Gohan.SkillStates.ChargeBeamCannon"); guardType = assembly.GetType("HenryMod.Survivors.Gohan.SkillStates.BeastGuard"); firingType = assembly.GetType("HenryMod.Survivors.Gohan.SkillStates.FireBeamCannon"); if (firingType == null) { ((BaseUnityPlugin)this).Logger.LogWarning((object)"FireBeamCannon state unavailable for voice playback."); } Type typeFromHandle = typeof(CharacterSelectController); harmony.Patch((MethodBase)AccessTools.Method(typeFromHandle, "OnEnable", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(Voice), "SelectionOpened", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); harmony.Patch((MethodBase)AccessTools.Method(typeFromHandle, "OnDisable", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(Voice), "SelectionClosed", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); harmony.Patch((MethodBase)AccessTools.Method(typeof(CharacterBody), "OnSkillActivated", new Type[1] { typeof(GenericSkill) }, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(Voice), "SkillActivated", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); harmony.Patch((MethodBase)AccessTools.Method(typeof(EntityStateMachine), "SetState", new Type[1] { typeof(EntityState) }, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(Voice), "StateChanged", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); effectsVolume = ((BaseUnityPlugin)this).Config.Bind<int>("Playback", "CombatEffectsVolumePercent", 26, new ConfigDescription("Local attack and impact effects volume.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 100), Array.Empty<object>())); combat = new CombatAudio(Path.Combine(Path.GetDirectoryName(((BaseUnityPlugin)this).Info.Location), "Effects"), delegate(string message) { ((BaseUnityPlugin)this).Logger.LogInfo((object)message); }); comboType = assembly.GetType("HenryMod.Survivors.Gohan.SkillStates.BeastCombo"); Hook(assembly, "HenryMod.Modules.BaseStates.BaseMeleeAttack", "OnHitEnemyAuthority", "PunchHit"); Hook(assembly, "HenryMod.Survivors.Gohan.SkillStates.BeastKick", "OnHit", "KickHit"); if (assembly.GetType("HenryMod.Survivors.Gohan.SkillStates.BeastKickFlip") != null) { Hook(assembly, "HenryMod.Survivors.Gohan.SkillStates.BeastKickFlip", "OnEnter", "KickFlip"); } if (assembly.GetType("HenryMod.Survivors.Gohan.SkillStates.BeastGuardCounter")?.GetMethod("SZVanish", BindingFlags.Instance | BindingFlags.NonPublic) != null) { Hook(assembly, "HenryMod.Survivors.Gohan.SkillStates.BeastGuardCounter", "SZVanish", "CounterVanish"); Hook(assembly, "HenryMod.Survivors.Gohan.SkillStates.BeastGuardCounter", "SZDive", "CounterDive"); Hook(assembly, "HenryMod.Survivors.Gohan.SkillStates.BeastGuardCounter", "SZSmash", "CounterSmash"); } Hook(assembly, "HenryMod.Survivors.Gohan.Components.GohanFlightController", "TakeOff", "TakeOff"); Hook(assembly, "HenryMod.Survivors.Gohan.SkillStates.BeastUnleash", "SZUnleash", "UnleashStarted"); Hook(assembly, "HenryMod.Survivors.Gohan.SkillStates.BeastFinisher", "SZCutIn", "FinisherCutIn"); Hook(assembly, "HenryMod.Survivors.Gohan.SkillStates.BeastFinisher", "SZBlast", "FinisherBlast"); Hook(assembly, "HenryMod.Survivors.Gohan.Components.GohanTension", "SZReady", "BeastReady"); Hook(assembly, "HenryMod.Survivors.Gohan.Components.GohanTension", "SZExhausted", "BeastExhausted"); Hook(assembly, "HenryMod.Survivors.Gohan.Components.GohanFlightController", "Land", "Landed"); Hook(assembly, "HenryMod.Survivors.Gohan.Components.GohanMenuIdle", "PlantedFeet", "MenuLanded"); } } private void Hook(Assembly assembly, string typeName, string name, string callback) { //IL_0052: Unknown result type (might be due to invalid IL or missing references) //IL_005f: Expected O, but got Unknown MethodInfo methodInfo = assembly.GetType(typeName)?.GetMethod(name, BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); if (methodInfo == null) { ((BaseUnityPlugin)this).Logger.LogWarning((object)("Missing voice trigger " + typeName + "." + name)); } else { harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, new HarmonyMethod(typeof(Voice), callback, (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } } private static void SelectionOpened(CharacterSelectController __instance) { instance.selectionScreen = __instance; instance.gohanSelected = false; } private static void SelectionClosed(CharacterSelectController __instance) { if (!((Object)(object)instance.selectionScreen != (Object)(object)__instance)) { instance.selectionScreen = null; instance.gohanSelected = false; if (instance.current == "Select") { instance.StopClip(); } } } private static void MenuLanded(Component __instance) { if (Object.op_Implicit((Object)(object)instance) && instance.voicesEnabled.Value && Object.op_Implicit((Object)(object)instance.selectionScreen) && ((Behaviour)instance.selectionScreen).isActiveAndEnabled) { instance.UpdateSelection(); float realtimeSinceStartup = Time.realtimeSinceStartup; if (instance.gohanSelected && !(realtimeSinceStartup - instance.lastSelectLine < 4f) && instance.StartClip("Select", 1)) { instance.lastSelectLine = realtimeSinceStartup; } } } private void UpdateSelection() { LocalUser firstLocalUser = LocalUserManager.GetFirstLocalUser(); NetworkUser val = ((firstLocalUser != null) ? firstLocalUser.currentNetworkUser : null); SurvivorDef val2 = (Object.op_Implicit((Object)(object)val) ? val.GetSurvivorPreference() : null); bool flag = Object.op_Implicit((Object)(object)val2) && Object.op_Implicit((Object)(object)val2.bodyPrefab) && ((Object)val2.bodyPrefab).name == "BeastGohanBody"; if ((!flag || !voicesEnabled.Value) && current == "Select") { StopClip(); } gohanSelected = flag; } private static CharacterBody LocalBody() { LocalUser firstLocalUser = LocalUserManager.GetFirstLocalUser(); if (firstLocalUser == null) { return null; } return firstLocalUser.cachedBody; } private static void SkillActivated(CharacterBody __instance, GenericSkill __0) { if (!Object.op_Implicit((Object)(object)__instance) || !Object.op_Implicit((Object)(object)__0) || __instance.baseNameToken != "GABE_GOHAN_NAME" || (Object)(object)__instance != (Object)(object)LocalBody()) { return; } SkillLocator skillLocator = __instance.skillLocator; if (Object.op_Implicit((Object)(object)skillLocator)) { if ((Object)(object)__0 == (Object)(object)skillLocator.primary) { instance.Play(__instance, "Combo"); } else if ((Object)(object)__0 == (Object)(object)skillLocator.secondary) { instance.Play(__instance, "Kick"); } } } private static bool IsLocalState(EntityState state) { CharacterBody val = LocalBody(); if (Object.op_Implicit((Object)(object)val) && state != null && Object.op_Implicit((Object)(object)state.outer)) { return (Object)(object)((Component)val).gameObject == (Object)(object)((Component)state.outer).gameObject; } return false; } private static void Effect(EntityState state, string cue) { if (IsLocalState(state)) { instance.meleeEffects.Enqueue(cue); } } private static void UnleashStarted(EntityState __instance) { if (IsLocalState(__instance)) { instance.combat.Play("UnleashBurst", instance.effectsVolume.Value); instance.Play(LocalBody(), "Unleash"); } } private static void FinisherCutIn(EntityState __instance) { if (IsLocalState(__instance)) { instance.combat.Play("FinisherCutIn", instance.effectsVolume.Value); instance.Play(LocalBody(), "Finisher"); } } private static void FinisherBlast(EntityState __instance) { if (IsLocalState(__instance)) { instance.combat.Play("FinisherBlast", instance.effectsVolume.Value); } } private static bool IsLocalComponent(Component component) { CharacterBody val = LocalBody(); if (Object.op_Implicit((Object)(object)val) && Object.op_Implicit((Object)(object)component) && (Object)(object)((Component)val).gameObject == (Object)(object)component.gameObject && Object.op_Implicit((Object)(object)val.healthComponent)) { return val.healthComponent.alive; } return false; } private static void BeastReady(Component __instance) { if (IsLocalComponent(__instance)) { instance.combat.Play("BeastReady", instance.effectsVolume.Value); } } private static void BeastExhausted(Component __instance) { if (IsLocalComponent(__instance)) { instance.combat.Play("UnleashEnd", instance.effectsVolume.Value); instance.Play(LocalBody(), "Exhausted"); } } private static void KickFlip(EntityState __instance) { Effect(__instance, "KickFlip"); } private static void KickHit(EntityState __instance) { Effect(__instance, "KickHit"); } private static void CounterVanish(EntityState __instance) { Effect(__instance, "KickCounterVanish"); } private static void CounterDive(EntityState __instance) { Effect(__instance, "KickCounterDive"); } private static void CounterSmash(EntityState __instance) { Effect(__instance, "KickCounterSmash"); } private static void PunchHit(EntityState __instance) { if (!(((object)__instance).GetType() != instance.comboType) && instance.lastPunchHit != __instance && IsLocalState(__instance)) { instance.lastPunchHit = __instance; instance.meleeEffects.Enqueue("PunchHit"); } } private static EntityState CurrentState(GenericSkill skill) { if (!Object.op_Implicit((Object)(object)skill) || !Object.op_Implicit((Object)(object)skill.stateMachine)) { return null; } return skill.stateMachine.state; } private void ObserveGuardAndBeam(CharacterBody body) { SkillLocator skillLocator = body.skillLocator; if (!Object.op_Implicit((Object)(object)skillLocator)) { return; } EntityState val = CurrentState(skillLocator.utility); if (val != lastUtility) { lastUtility = val; if (val != null && ((object)val).GetType() == guardType) { combat.Play("GuardBlink", effectsVolume.Value); Play(body, "Guard"); } } EntityState val2 = CurrentState(skillLocator.special); if (val2 == lastSpecial) { return; } if (lastSpecial != null && ((object)lastSpecial).GetType() == chargeType) { combat.StopCharge(); } lastSpecial = val2; if (val2 != null) { if (((object)val2).GetType() == chargeType) { combat.Play("BeamCharge", effectsVolume.Value); Play(body, "BeamStart"); } if (((object)val2).GetType() == firingType) { combat.Play("BeamFire", effectsVolume.Value); Play(body, "BeamCannon"); } } } private static void StateChanged(EntityStateMachine __instance) { CharacterBody val = LocalBody(); if (!Object.op_Implicit((Object)(object)val) || val.baseNameToken != "GABE_GOHAN_NAME" || (Object)(object)((Component)__instance).gameObject != (Object)(object)((Component)val).gameObject) { return; } SkillLocator skillLocator = val.skillLocator; EntityState state = __instance.state; if (Object.op_Implicit((Object)(object)skillLocator) && state != null) { Type type = ((object)state).GetType(); if (IsActivation(skillLocator.primary, __instance, type)) { instance.meleeEffects.Enqueue("PunchSwing"); instance.Play(val, "Combo"); } else if (IsActivation(skillLocator.secondary, __instance, type)) { instance.meleeEffects.Enqueue("KickSwing"); instance.Play(val, "Kick"); } } } private static bool IsActivation(GenericSkill skill, EntityStateMachine machine, Type type) { //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Unknown result type (might be due to invalid IL or missing references) if (Object.op_Implicit((Object)(object)skill) && (Object)(object)skill.stateMachine == (Object)(object)machine) { SerializableEntityStateType activationState = skill.activationState; return ((SerializableEntityStateType)(ref activationState)).stateType == type; } return false; } private static void TakeOff(Component __instance) { CharacterBody val = LocalBody(); if (Object.op_Implicit((Object)(object)val) && !((Object)(object)((Component)val).gameObject != (Object)(object)__instance.gameObject) && Object.op_Implicit((Object)(object)val.healthComponent) && val.healthComponent.alive) { if ((Object)(object)val != (Object)(object)instance.owner) { instance.ResetOwner(val); } if (!instance.flying) { instance.flying = true; instance.combat.StartFlight(instance.effectsVolume.Value); instance.Play(val, "Flight"); } } } private static void Landed(Component __instance) { if (Object.op_Implicit((Object)(object)instance.owner) && (Object)(object)((Component)instance.owner).gameObject == (Object)(object)__instance.gameObject) { instance.StopWind(); } } private void StopWind() { if (flying) { flying = false; combat?.StopFlight(); } } private bool Track(CharacterBody body) { if (!voicesEnabled.Value || !Object.op_Implicit((Object)(object)body) || body.baseNameToken != "GABE_GOHAN_NAME") { return false; } CharacterBody val = LocalBody(); if (Object.op_Implicit((Object)(object)val) ? ((Object)(object)body != (Object)(object)val) : ((Object)(object)body != (Object)(object)owner)) { return false; } if ((Object)(object)body != (Object)(object)owner) { ResetOwner(body); } return true; } private void ServerHit(DamageReport report) { CharacterBody victimBody = report.victimBody; if (!Track(victimBody) || !Object.op_Implicit((Object)(object)report.victim)) { return; } HealthComponent victim = report.victim; if (!victim.alive) { Die(); return; } float val = report.combinedHealthBeforeDamage - victim.combinedHealth; if (DamageReaction.IsChunk(Math.Min(report.damageDealt, val), victim.fullCombinedHealth, hurtPercent.Value) && reaction.Hurt(Time.realtimeSinceStartup)) { Play(victimBody, "Hurt"); } } private void ClientHit(DamageDealtMessage msg) { if (!NetworkServer.active && Object.op_Implicit((Object)(object)msg.victim)) { CharacterBody val = LocalBody(); if (Object.op_Implicit((Object)(object)val) && !((Object)(object)msg.victim != (Object)(object)((Component)val).gameObject) && Track(val) && Object.op_Implicit((Object)(object)val.healthComponent) && DamageReaction.IsChunk(msg.damage, val.healthComponent.fullCombinedHealth, hurtPercent.Value)) { reaction.NoteLargeHit(Time.realtimeSinceStartup); } } } private static void DeathStarted(CharacterBody __instance) { if (instance.Track(__instance)) { instance.Die(); } } private void Die() { StopWind(); combat?.StopCharge(); if (reaction.Die()) { StartClip("Death", 10); } } private void Update() { //IL_01e4: Unknown result type (might be due to invalid IL or missing references) //IL_01ea: Invalid comparison between Unknown and I4 //IL_01fd: Unknown result type (might be due to invalid IL or missing references) //IL_0203: Invalid comparison between Unknown and I4 //IL_01f2: Unknown result type (might be due to invalid IL or missing references) //IL_01f7: Unknown result type (might be due to invalid IL or missing references) //IL_0216: Unknown result type (might be due to invalid IL or missing references) //IL_021c: Invalid comparison between Unknown and I4 //IL_020b: Unknown result type (might be due to invalid IL or missing references) //IL_0210: Unknown result type (might be due to invalid IL or missing references) //IL_0220: Unknown result type (might be due to invalid IL or missing references) //IL_022f: Unknown result type (might be due to invalid IL or missing references) //IL_0235: Invalid comparison between Unknown and I4 //IL_0239: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)instance != (Object)(object)this) { return; } combat?.Update(); if (Object.op_Implicit((Object)(object)selectionScreen) && ((Behaviour)selectionScreen).isActiveAndEnabled) { StopWind(); UpdateSelection(); return; } CharacterBody val = LocalBody(); if ((Object)(object)owner != (Object)(object)val || (!Object.op_Implicit((Object)(object)val) && current != null && current != "Death")) { ResetOwner(val); } if (Object.op_Implicit((Object)(object)val) && val.baseNameToken == "GABE_GOHAN_NAME" && Object.op_Implicit((Object)(object)val.healthComponent) && val.healthComponent.alive) { while (meleeEffects.Count > 0) { combat.Play(meleeEffects.Dequeue(), effectsVolume.Value); } ObserveGuardAndBeam(val); } else { meleeEffects.Clear(); StopWind(); } if (!voicesEnabled.Value) { StopClip(); } else { if (!Object.op_Implicit((Object)(object)val) || val.baseNameToken != "GABE_GOHAN_NAME" || !Object.op_Implicit((Object)(object)val.healthComponent)) { return; } HealthComponent healthComponent = val.healthComponent; if (!healthComponent.alive) { Die(); } else { if (reaction.Dead) { return; } CharacterMotor characterMotor = val.characterMotor; if (Object.op_Implicit((Object)(object)characterMotor)) { int jumpCount = characterMotor.jumpCount; if (jumpCount > lastJumpCount && !characterMotor.isGrounded && !flying) { Play(val, "Jump"); } lastJumpCount = jumpCount; } if (!NetworkServer.active && reaction.Observe(healthComponent.combinedHealth, healthComponent.fullCombinedHealth, hurtPercent.Value, Time.realtimeSinceStartup)) { Play(val, "Hurt"); } if ((int)counterIndex == -1) { counterIndex = BuffCatalog.FindBuffIndex("GohanGuardCountered"); } if ((int)awakenIndex == -1) { awakenIndex = BuffCatalog.FindBuffIndex("GohanAwakened"); } bool flag = (int)counterIndex != -1 && val.HasBuff(counterIndex); bool flag2 = (int)awakenIndex != -1 && val.HasBuff(awakenIndex); if (flag && !counter) { Play(val, "Counter"); } if (flag2 && !awakened) { Play(val, "Awakening"); combat.Play("AwakenBurst", effectsVolume.Value); } counter = flag; awakened = flag2; } } } private void ResetOwner(CharacterBody body) { if (Object.op_Implicit((Object)(object)body) || current != "Death") { StopClip(); } reaction = new DamageReaction(); StopWind(); combat?.StopCharge(); lastUtility = (lastSpecial = (lastPunchHit = null)); lastJumpCount = 0; nextJumpGrunt = 0f; owner = body; counter = (awakened = false); } private void Play(CharacterBody body, string cue) { if (!voicesEnabled.Value) { return; } if ((Object)(object)body != (Object)(object)owner) { ResetOwner(body); } if (reaction.Dead) { return; } int num; switch (cue) { default: num = 2; break; case "Awakening": case "Hurt": num = 3; break; case "Counter": num = 4; break; case "Unleash": num = 4; break; case "BeamGame": case "BeamStart": case "BeamCannon": case "Finisher": num = 5; break; case "Combo": case "Jump": case "Flight": num = 1; break; } int num2 = num; float realtimeSinceStartup = Time.realtimeSinceStartup; if ((!(realtimeSinceStartup < busyUntil) || num2 > priority || num2 == 5 || (priority == 1 && cue == "Flight" && current == "Jump")) && (!(cue == "Combo") || primaryTiming.Ready(realtimeSinceStartup)) && (!(cue == "Jump") || (!(realtimeSinceStartup < nextJumpGrunt) && voiceRandom.Next(5) == 0)) && StartClip(cue, num2)) { if (cue == "Jump") { nextJumpGrunt = realtimeSinceStartup + 12f; } if (cue == "Combo") { primaryTiming.Played(realtimeSinceStartup, voiceRandom); } } } private bool StartClip(string cue, int rank) { if (gain == 0) { return false; } string text = cue switch { "Hurt" => hurtLines.Draw(voiceRandom), "Finisher" => finisherLines.Draw(voiceRandom), "Kick" => kickLines.Draw(voiceRandom), "Unleash" => unleashLines.Draw(voiceRandom), "Select" => selectLines.Draw(voiceRandom), "Jump" => jumps.Draw(voiceRandom), "Combo" => grunts.Draw(voiceRandom), _ => cue, }; string text2 = Path.Combine(root, text + ".wav"); if (gain != 100) { try { if (mixDirectory == null) { mixDirectory = Path.Combine(Path.GetTempPath(), "BeastGohanVoice-" + Guid.NewGuid().ToString("N")); Directory.CreateDirectory(mixDirectory); } string text3 = Path.Combine(mixDirectory, text + ".wav"); if (!File.Exists(text3)) { File.WriteAllBytes(text3, VoiceMix.Scale(File.ReadAllBytes(text2), gain)); } text2 = text3; } catch (Exception ex) { if (warnings.Add(text)) { ((BaseUnityPlugin)this).Logger.LogWarning((object)("Could not mix " + text + ": " + ex.Message)); } return false; } } if (!File.Exists(text2) || !PlaySoundW(text2, IntPtr.Zero, 131075u)) { if (warnings.Add(cue)) { ((BaseUnityPlugin)this).Logger.LogWarning((object)("Could not play " + text2)); } return false; } current = cue; if (firstPlayback.Add(cue)) { ((BaseUnityPlugin)this).Logger.LogInfo((object)("Started Gohan voice: " + cue)); } priority = rank; busyUntil = Time.realtimeSinceStartup + cue switch { "Exhausted" => 2.6f, "Finisher" => 1.4f, "Unleash" => 2.2f, "Kick" => 1.06f, "BeamCannon" => 1.21f, "BeamStart" => 1.41f, "BeamGame" => 2.62f, "Counter" => 1.42f, "Combo" => 0.8f, _ => 1.2f, }; return true; } private void StopClip() { if (current != null) { PlaySoundW(null, IntPtr.Zero, 0u); current = null; busyUntil = 0f; } } private void OnDestroy() { if ((Object)(object)instance != (Object)(object)this) { return; } GlobalEventManager.onServerDamageDealt -= ServerHit; GlobalEventManager.onClientDamageNotified -= ClientHit; Harmony obj = harmony; if (obj != null) { obj.UnpatchSelf(); } StopWind(); combat?.Dispose(); StopClip(); if (mixDirectory != null && Directory.Exists(mixDirectory)) { try { Directory.Delete(mixDirectory, recursive: true); } catch (IOException ex) { ((BaseUnityPlugin)this).Logger.LogDebug((object)ex.Message); } catch (UnauthorizedAccessException ex2) { ((BaseUnityPlugin)this).Logger.LogDebug((object)ex2.Message); } } instance = null; } } internal sealed class CuePool { private readonly string[] clips; private int next; private string previous; internal CuePool(params string[] clips) { this.clips = clips; next = clips.Length; } internal string Draw(Random random) { if (next == clips.Length) { for (int num = clips.Length - 1; num > 0; num--) { int b = random.Next(num + 1); Swap(num, b); } if (clips.Length > 1 && clips[0] == previous) { Swap(0, random.Next(1, clips.Length)); } next = 0; } previous = clips[next++]; return previous; } private void Swap(int a, int b) { string text = clips[a]; clips[a] = clips[b]; clips[b] = text; } } internal sealed class PrimaryTiming { private float nextAllowed; internal bool Ready(float now) { return now >= nextAllowed; } internal void Played(float now, Random random) { nextAllowed = now + 5f + (float)random.NextDouble() * 4f; } } internal static class VoiceMix { internal static byte[] Scale(byte[] wav, int percent) { if (percent < 0 || percent > 100) { throw new ArgumentOutOfRangeException("percent"); } using (MemoryStream memoryStream = new MemoryStream(wav)) { using BinaryReader binaryReader = new BinaryReader(memoryStream); if (binaryReader.ReadUInt32() != 1179011410) { throw new InvalidDataException("Expected RIFF."); } binaryReader.ReadUInt32(); if (binaryReader.ReadUInt32() != 1163280727) { throw new InvalidDataException("Expected WAVE."); } bool flag = false; while (memoryStream.Position + 8 <= memoryStream.Length) { uint num = binaryReader.ReadUInt32(); uint num2 = binaryReader.ReadUInt32(); long position = memoryStream.Position; if (position + num2 > memoryStream.Length) { throw new InvalidDataException("Invalid WAV chunk."); } if (num == 544501094 && num2 >= 16) { bool num3 = binaryReader.ReadUInt16() == 1; memoryStream.Position = position + 14; flag = num3 && binaryReader.ReadUInt16() == 16; } if (num == 1635017060) { if (!flag || num2 % 2 != 0) { throw new InvalidDataException("Expected 16-bit PCM audio."); } for (int i = (int)position; i < position + num2; i += 2) { int num4 = (short)(wav[i] | (wav[i + 1] << 8)) * percent / 100; wav[i] = (byte)num4; wav[i + 1] = (byte)(num4 >> 8); } return wav; } memoryStream.Position = position + num2 + num2 % 2; } } throw new InvalidDataException("Missing WAV data."); } } }
plugins/GohanCoop.dll
Decompiled 2 hours agousing System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Text; using BeastGohanVoice; using BepInEx; using BepInEx.Bootstrap; using BepInEx.Configuration; using HarmonyLib; using RoR2; using UnityEngine; using UnityEngine.Networking; [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("GohanCoop")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0")] [assembly: AssemblyProduct("GohanCoop")] [assembly: AssemblyTitle("GohanCoop")] [assembly: AssemblyVersion("1.0.0.0")] namespace BeastGohanVoice { internal sealed class MeleeOutput { [StructLayout(LayoutKind.Sequential, Pack = 2)] private struct Format { public ushort tag; public ushort channels; public uint rate; public uint byteRate; public ushort align; public ushort bits; public ushort extra; } private struct Header { public IntPtr data; public uint length; public uint recorded; public UIntPtr user; public uint flags; public uint loops; public IntPtr next; public UIntPtr reserved; } private sealed class Shot { internal IntPtr device; internal IntPtr header; internal GCHandle pcm; internal bool prepared; } private static readonly uint headerSize = (uint)Marshal.SizeOf<Header>(); private readonly List<Shot> active = new List<Shot>(); private readonly Dictionary<string, (Format format, byte[] pcm, int gain)> clips = new Dictionary<string, (Format, byte[], int)>(); [DllImport("winmm.dll")] private static extern uint waveOutOpen(out IntPtr handle, uint device, ref Format format, IntPtr callback, IntPtr instance, uint flags); [DllImport("winmm.dll")] private static extern uint waveOutPrepareHeader(IntPtr handle, IntPtr header, uint size); [DllImport("winmm.dll")] private static extern uint waveOutWrite(IntPtr handle, IntPtr header, uint size); [DllImport("winmm.dll")] private static extern uint waveOutUnprepareHeader(IntPtr handle, IntPtr header, uint size); [DllImport("winmm.dll")] private static extern uint waveOutReset(IntPtr handle); [DllImport("winmm.dll")] private static extern uint waveOutClose(IntPtr handle); private static void Check(uint result) { if (result != 0) { throw new IOException("Windows waveOut error " + result); } } internal void Play(string key, string folder, int gain, bool loop = false) { if (!clips.TryGetValue(key, out (Format, byte[], int) value) || value.Item3 != gain) { string text = Path.Combine(folder, key + ".wav"); using Stream stream = (File.Exists(text) ? File.OpenRead(text) : typeof(MeleeOutput).Assembly.GetManifestResourceStream("Melee." + key + ".wav")); if (stream == null) { throw new FileNotFoundException("Missing effect", text); } using MemoryStream memoryStream = new MemoryStream(); stream.CopyTo(memoryStream); using BinaryReader binaryReader = new BinaryReader(new MemoryStream(VoiceMix.Scale(memoryStream.ToArray(), gain))); Format item = default(Format); binaryReader.BaseStream.Position = 12L; int num; while (true) { string text2 = Encoding.ASCII.GetString(binaryReader.ReadBytes(4)); num = binaryReader.ReadInt32(); long num2 = binaryReader.BaseStream.Position + num; if (num < 0 || num2 > binaryReader.BaseStream.Length) { throw new InvalidDataException("Invalid WAV size"); } if (text2 == "fmt ") { item.tag = binaryReader.ReadUInt16(); item.channels = binaryReader.ReadUInt16(); item.rate = binaryReader.ReadUInt32(); item.byteRate = binaryReader.ReadUInt32(); item.align = binaryReader.ReadUInt16(); item.bits = binaryReader.ReadUInt16(); } if (text2 == "data") { break; } binaryReader.BaseStream.Position = num2 + (num & 1); } value = (item, binaryReader.ReadBytes(num), gain); clips[key] = value; } Collect(stop: false); if (active.Count >= 24) { return; } Shot shot = new Shot(); Check(waveOutOpen(out shot.device, uint.MaxValue, ref value.Item1, IntPtr.Zero, IntPtr.Zero, 0u)); active.Add(shot); try { shot.pcm = GCHandle.Alloc(value.Item2, GCHandleType.Pinned); shot.header = Marshal.AllocHGlobal((int)headerSize); Marshal.StructureToPtr(new Header { data = shot.pcm.AddrOfPinnedObject(), length = (uint)value.Item2.Length, flags = (loop ? 12u : 0u), loops = (loop ? uint.MaxValue : 0u) }, shot.header, fDeleteOld: false); Check(waveOutPrepareHeader(shot.device, shot.header, headerSize)); shot.prepared = true; Check(waveOutWrite(shot.device, shot.header, headerSize)); } catch { CollectOne(active.Count - 1, stop: true); throw; } } internal void Collect(bool stop) { for (int num = active.Count - 1; num >= 0; num--) { CollectOne(num, stop); } } private void CollectOne(int index, bool stop) { Shot shot = active[index]; if (stop) { waveOutReset(shot.device); } else if ((Marshal.PtrToStructure<Header>(shot.header).flags & 1) == 0) { return; } if (!shot.prepared || waveOutUnprepareHeader(shot.device, shot.header, headerSize) == 0) { if (shot.pcm.IsAllocated) { shot.pcm.Free(); } if (shot.header != IntPtr.Zero) { Marshal.FreeHGlobal(shot.header); } waveOutClose(shot.device); active.RemoveAt(index); } } } internal static class VoiceMix { internal static byte[] Scale(byte[] wav, int percent) { if (percent < 0 || percent > 100) { throw new ArgumentOutOfRangeException("percent"); } using (MemoryStream memoryStream = new MemoryStream(wav)) { using BinaryReader binaryReader = new BinaryReader(memoryStream); if (binaryReader.ReadUInt32() != 1179011410) { throw new InvalidDataException("Expected RIFF."); } binaryReader.ReadUInt32(); if (binaryReader.ReadUInt32() != 1163280727) { throw new InvalidDataException("Expected WAVE."); } bool flag = false; while (memoryStream.Position + 8 <= memoryStream.Length) { uint num = binaryReader.ReadUInt32(); uint num2 = binaryReader.ReadUInt32(); long position = memoryStream.Position; if (position + num2 > memoryStream.Length) { throw new InvalidDataException("Invalid WAV chunk."); } if (num == 544501094 && num2 >= 16) { bool num3 = binaryReader.ReadUInt16() == 1; memoryStream.Position = position + 14; flag = num3 && binaryReader.ReadUInt16() == 16; } if (num == 1635017060) { if (!flag || num2 % 2 != 0) { throw new InvalidDataException("Expected 16-bit PCM audio."); } for (int i = (int)position; i < position + num2; i += 2) { int num4 = (short)(wav[i] | (wav[i + 1] << 8)) * percent / 100; wav[i] = (byte)num4; wav[i + 1] = (byte)(num4 >> 8); } return wav; } memoryStream.Position = position + num2 + num2 % 2; } } throw new InvalidDataException("Missing WAV data."); } } } namespace GohanCoop { [BepInPlugin("com.gabe.BeastGohanCoop", "Beast Gohan Multiplayer", "1.0.1")] [BepInDependency(/*Could not decode attribute arguments.*/)] public class Coop : BaseUnityPlugin { internal static Coop Mod; internal static string Folder; internal static readonly string[] Clips = new string[49] { "", "Awakening", "BeamCannon", "BeamGame", "BeamStart", "Combo", "Combo2", "Combo3", "Combo4", "Combo5", "Combo6", "Counter", "Death", "Exhausted", "Finisher", "Finisher2", "Flight", "Guard", "Hurt", "Hurt2", "Hurt3", "Intro", "Kick", "Kick2", "Kick3", "Kick4", "Unleash", "Unleash2", "AwakenBurst", "BeamCharge", "BeamFire", "BeastReady", "FinisherBlast", "FinisherCutIn", "GuardBlink", "KickCounterDive", "KickCounterSmash", "KickCounterVanish", "KickFlip", "KickHit", "KickSwing", "PunchHit1", "PunchHit2", "PunchHit3", "PunchSwing1", "PunchSwing2", "PunchSwing3", "UnleashBurst", "UnleashEnd" }; internal static readonly int FirstEffect = Array.IndexOf(Clips, "AwakenBurst"); internal const byte Pose = 0; internal const byte StopCharge = 250; internal const byte StopVoice = 251; private const short MessageId = 27561; internal static ConfigEntry<int> VoiceVolume; internal static ConfigEntry<int> EffectsVolume; internal static ConfigEntry<bool> Enabled; private static NetworkClient client; private static bool serverRegistered; private static Harmony patch; internal static MethodInfo FlightGetter; private void Awake() { //IL_0076: Unknown result type (might be due to invalid IL or missing references) //IL_0080: Expected O, but got Unknown //IL_0148: Unknown result type (might be due to invalid IL or missing references) //IL_0156: Expected O, but got Unknown //IL_00fb: Unknown result type (might be due to invalid IL or missing references) //IL_0107: Expected O, but got Unknown //IL_022d: Unknown result type (might be due to invalid IL or missing references) //IL_0239: Expected O, but got Unknown Mod = this; PluginInfo obj = Chainloader.PluginInfos["com.gabe.BeastGohanVoice"]; Folder = Path.GetDirectoryName(obj.Location); ConfigFile config = obj.Instance.Config; config.TryGetEntry<int>("Playback", "VoiceVolumePercent", ref VoiceVolume); config.TryGetEntry<int>("Playback", "CombatEffectsVolumePercent", ref EffectsVolume); config.TryGetEntry<bool>("Playback", "Enabled", ref Enabled); patch = new Harmony("com.gabe.BeastGohanCoop"); Assembly assembly = ((object)obj.Instance).GetType().Assembly; Type type = ((object)obj.Instance).GetType(); Type type2 = assembly.GetType("BeastGohanVoice.CombatAudio", throwOnError: true); Type[] array = new Type[2] { type, type2 }; foreach (Type type3 in array) { patch.Patch((MethodBase)AccessTools.Method(type3, (type3 == type) ? "StartClip" : "Play", (Type[])null, (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(typeof(Coop), "CaptureClip", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null); } Hook(type2, "StopCharge", "ChargeStopped"); patch.Patch((MethodBase)AccessTools.Method(type, "StopClip", (Type[])null, (Type[])null), new HarmonyMethod(typeof(Coop), "VoiceStopped", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); Assembly assembly2 = ((object)Chainloader.PluginInfos["com.gabe.BeastGohan"].Instance).GetType().Assembly; Hook(assembly2.GetType("HenryMod.Survivors.Gohan.Components.GohanAnimationDriver", throwOnError: true), "LateUpdate", "Animate"); FlightGetter = AccessTools.PropertyGetter(assembly2.GetType("HenryMod.Survivors.Gohan.Components.GohanFlightController", throwOnError: true), "isFlying"); (string, string)[] array2 = new(string, string)[2] { ("GohanKiAura", "Update"), ("GohanSZAura", "LateUpdate") }; for (int i = 0; i < array2.Length; i++) { (string, string) tuple = array2[i]; patch.Patch((MethodBase)AccessTools.Method(assembly2.GetType("HenryMod.Survivors.Gohan.Components." + tuple.Item1, throwOnError: true), tuple.Item2, (Type[])null, (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(typeof(Coop), "AuraFlightReads", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null); } } private static IEnumerable<CodeInstruction> AuraFlightReads(IEnumerable<CodeInstruction> input) { foreach (CodeInstruction instruction in input) { yield return instruction; if (CodeInstructionExtensions.Calls(instruction, FlightGetter)) { yield return new CodeInstruction(OpCodes.Ldarg_0, (object)null); yield return new CodeInstruction(OpCodes.Call, (object)AccessTools.Method(typeof(Coop), "AuraFlying", (Type[])null, (Type[])null)); } } } private static bool AuraFlying(bool original, Component aura) { RemoteTrack componentInParent = aura.GetComponentInParent<RemoteTrack>(); if (!Object.op_Implicit((Object)(object)componentInParent) || !componentInParent.HasRecentPose) { return original; } return componentInParent.RemoteFlying; } private static void Hook(Type type, string name, string callback) { //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Expected O, but got Unknown patch.Patch((MethodBase)AccessTools.Method(type, name, (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(Coop), callback, (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } private static IEnumerable<CodeInstruction> CaptureClip(IEnumerable<CodeInstruction> input) { bool found = false; foreach (CodeInstruction item in input) { yield return item; if (!found && !(item.opcode != OpCodes.Stloc_0)) { found = true; yield return new CodeInstruction(OpCodes.Ldloc_0, (object)null); yield return new CodeInstruction(OpCodes.Call, (object)AccessTools.Method(typeof(Coop), "SendClip", (Type[])null, (Type[])null)); } } if (!found) { throw new InvalidOperationException("Gohan audio method layout differs from 1.1.6"); } } private static void SendClip(string clip) { int num = Array.IndexOf(Clips, clip); if (num > 0) { Cue((byte)num); } } private static void ChargeStopped() { Cue(250); } private static void VoiceStopped(string ___current) { if (___current != null) { Cue(251); } } internal static CharacterBody Local() { LocalUser firstLocalUser = LocalUserManager.GetFirstLocalUser(); if (firstLocalUser == null) { return null; } return firstLocalUser.cachedBody; } private static void Cue(byte code) { //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Unknown result type (might be due to invalid IL or missing references) CharacterBody val = Local(); if (Object.op_Implicit((Object)(object)val) && val.baseNameToken == "GABE_GOHAN_NAME") { Send(new Packet { id = ((NetworkBehaviour)val).netId, kind = code }); } } internal static void Send(Packet p) { if (client != null && client.isConnected && ClientScene.ready && !RoR2Application.isInSinglePlayer) { client.Send((short)27561, (MessageBase)(object)p); } } private void Update() { //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Expected O, but got Unknown //IL_0072: Unknown result type (might be due to invalid IL or missing references) //IL_007c: Expected O, but got Unknown if (!NetworkServer.active) { serverRegistered = false; } else if (!serverRegistered) { NetworkServer.RegisterHandler((short)27561, new NetworkMessageDelegate(Relay)); serverRegistered = true; } NetworkClient val = (Object.op_Implicit((Object)(object)NetworkManager.singleton) ? NetworkManager.singleton.client : null); if (client != val) { client = val; if (client != null) { client.RegisterHandler((short)27561, new NetworkMessageDelegate(Receive)); } } } private static void Relay(NetworkMessage m) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) Packet packet = m.ReadMessage<Packet>(); GameObject val = NetworkServer.FindLocalObject(packet.id); CharacterBody val2 = (Object.op_Implicit((Object)(object)val) ? val.GetComponent<CharacterBody>() : null); if (!Object.op_Implicit((Object)(object)val2) || val2.baseNameToken != "GABE_GOHAN_NAME" || !Object.op_Implicit((Object)(object)val2.master)) { return; } PlayerCharacterMasterController playerCharacterMasterController = val2.master.playerCharacterMasterController; NetworkUser val3 = ((playerCharacterMasterController != null) ? playerCharacterMasterController.networkUser : null); if (!Object.op_Implicit((Object)(object)val3) || ((NetworkBehaviour)val3).connectionToClient != m.conn || !packet.Valid()) { return; } foreach (NetworkConnection connection in NetworkServer.connections) { if (connection != null && connection != m.conn && connection.isReady) { connection.Send((short)27561, (MessageBase)(object)packet); } } } private static void Receive(NetworkMessage m) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) Packet packet = m.ReadMessage<Packet>(); GameObject val = ClientScene.FindLocalObject(packet.id); if (Object.op_Implicit((Object)(object)val) && packet.Valid()) { CharacterBody component = val.GetComponent<CharacterBody>(); if (Object.op_Implicit((Object)(object)component) && !((Object)(object)component == (Object)(object)Local()) && !(component.baseNameToken != "GABE_GOHAN_NAME")) { (val.GetComponent<RemoteTrack>() ?? val.AddComponent<RemoteTrack>()).Accept(packet); } } } private static void Animate(Component __instance, Animator ___animator, CharacterBody ___body, Component ___flight) { if (Object.op_Implicit((Object)(object)___animator) && Object.op_Implicit((Object)(object)___body) && ((Behaviour)___animator).isActiveAndEnabled && client != null && !RoR2Application.isInSinglePlayer) { (((Component)___body).GetComponent<RemoteTrack>() ?? ((Component)___body).gameObject.AddComponent<RemoteTrack>()).Animate(___animator, ___body, ___flight); } } } public class Packet : MessageBase { public NetworkInstanceId id; public byte kind; public byte flags; public float[] values; public int[] states; public float[] times; public bool Valid() { if (kind != 0) { if (kind >= Coop.Clips.Length && kind != 250) { return kind == 251; } return true; } float[] array = values; foreach (float num in array) { if (float.IsNaN(num) || Math.Abs(num) > 10000f) { return false; } } array = times; foreach (float num2 in array) { if (float.IsNaN(num2) || Math.Abs(num2) > 1000000f) { return false; } } return true; } public override void Serialize(NetworkWriter w) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) w.Write(id); w.Write(kind); if (kind == 0) { w.Write(flags); float[] array = values; foreach (float num in array) { w.Write(num); } for (int j = 0; j < states.Length; j++) { w.Write(states[j]); w.Write(times[j]); } } } public override void Deserialize(NetworkReader r) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) id = r.ReadNetworkId(); kind = r.ReadByte(); if (kind == 0) { flags = r.ReadByte(); values = new float[RemoteTrack.FloatNames.Length]; for (int i = 0; i < values.Length; i++) { values[i] = r.ReadSingle(); } states = new int[2]; times = new float[2]; for (int j = 0; j < 2; j++) { states[j] = r.ReadInt32(); times[j] = r.ReadSingle(); } } } } public class RemoteTrack : MonoBehaviour { internal static readonly string[] FloatNames = new string[7] { "groundSpeed", "groundPlayback", "upSpeed", "flyUp", "flyForward", "Slash.playbackRate", "Menu.playbackRate" }; private static readonly string[] BoolNames = new string[3] { "isMoving", "isGrounded", "isFlying" }; private readonly HashSet<string> parameters = new HashSet<string>(); private readonly MeleeOutput voice = new MeleeOutput(); private readonly MeleeOutput fx = new MeleeOutput(); private readonly MeleeOutput wind = new MeleeOutput(); private readonly MeleeOutput charge = new MeleeOutput(); private Animator animator; private int[] layers; private Packet latest; private bool pending; private bool looping; private float nextSend; private float received; internal bool HasRecentPose { get { if (latest != null) { return Time.unscaledTime - received <= 1f; } return false; } } internal bool RemoteFlying => (latest.flags & 4) != 0; internal void Animate(Animator a, CharacterBody b, Component flight) { //IL_00a9: Unknown result type (might be due to invalid IL or missing references) //IL_00ae: Unknown result type (might be due to invalid IL or missing references) //IL_01c0: Unknown result type (might be due to invalid IL or missing references) //IL_01c5: Unknown result type (might be due to invalid IL or missing references) //IL_0311: Unknown result type (might be due to invalid IL or missing references) //IL_0316: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)animator != (Object)(object)a) { animator = a; parameters.Clear(); AnimatorControllerParameter[] array = a.parameters; foreach (AnimatorControllerParameter val in array) { parameters.Add(val.name); } layers = new int[2] { a.GetLayerIndex("Gesture, Override"), a.GetLayerIndex("FullBody, Override") }; } if ((Object)(object)b == (Object)(object)Coop.Local()) { if (Time.unscaledTime < nextSend) { return; } nextSend = Time.unscaledTime + 0.08f; Packet packet = new Packet { id = ((NetworkBehaviour)b).netId, values = new float[FloatNames.Length], states = new int[2], times = new float[2] }; for (int j = 0; j < BoolNames.Length; j++) { if (parameters.Contains(BoolNames[j]) && a.GetBool(BoolNames[j])) { packet.flags |= (byte)(1 << j); } } if (Object.op_Implicit((Object)(object)flight)) { bool flag = (bool)Coop.FlightGetter.Invoke(flight, null); packet.flags = (byte)((packet.flags & -5) | (flag ? 4 : 0)); } for (int k = 0; k < FloatNames.Length; k++) { if (parameters.Contains(FloatNames[k])) { packet.values[k] = a.GetFloat(FloatNames[k]); } } for (int l = 0; l < 2; l++) { if (layers[l] >= 0) { AnimatorStateInfo val2 = State(a, layers[l]); packet.states[l] = ((AnimatorStateInfo)(ref val2)).fullPathHash; packet.times[l] = ((AnimatorStateInfo)(ref val2)).normalizedTime; } } Coop.Send(packet); } else { if (latest == null || Time.unscaledTime - received > 1f) { return; } for (int m = 0; m < BoolNames.Length; m++) { if (parameters.Contains(BoolNames[m])) { a.SetBool(BoolNames[m], (latest.flags & (1 << m)) != 0); } } for (int n = 0; n < FloatNames.Length; n++) { if (parameters.Contains(FloatNames[n])) { a.SetFloat(FloatNames[n], latest.values[n]); } } if (!pending) { return; } pending = false; for (int num = 0; num < 2; num++) { if (layers[num] >= 0 && latest.states[num] != 0 && a.HasState(layers[num], latest.states[num])) { AnimatorStateInfo val3 = State(a, layers[num]); if (((AnimatorStateInfo)(ref val3)).fullPathHash != latest.states[num] || (!((AnimatorStateInfo)(ref val3)).loop && Mathf.Abs(Mathf.Clamp01(((AnimatorStateInfo)(ref val3)).normalizedTime) - Mathf.Clamp01(latest.times[num])) > 0.45f)) { a.CrossFade(latest.states[num], 0.07f, layers[num], latest.times[num]); } } } } } private static AnimatorStateInfo State(Animator a, int layer) { //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) if (!a.IsInTransition(layer)) { return a.GetCurrentAnimatorStateInfo(layer); } return a.GetNextAnimatorStateInfo(layer); } internal void Accept(Packet p) { if (p.kind == 0) { latest = p; received = Time.unscaledTime; pending = true; bool flag = (p.flags & 4) != 0; if (looping != flag) { looping = flag; if (flag) { Play(wind, "FlightWind", line: false, loop: true); } else { wind.Collect(stop: true); } } } else if (p.kind == 250) { charge.Collect(stop: true); } else if (p.kind == 251) { voice.Collect(stop: true); } else { string text = Coop.Clips[p.kind]; bool flag2 = p.kind < Coop.FirstEffect; MeleeOutput meleeOutput = (flag2 ? voice : ((text == "BeamCharge") ? charge : fx)); if (meleeOutput != fx) { meleeOutput.Collect(stop: true); } Play(meleeOutput, text, flag2, loop: false); } } private void Play(MeleeOutput output, string key, bool line, bool loop) { //IL_003d: Unknown result type (might be due to invalid IL or missing references) //IL_0048: Unknown result type (might be due to invalid IL or missing references) if (Environment.OSVersion.Platform != PlatformID.Win32NT) { return; } if (line) { ConfigEntry<bool> enabled = Coop.Enabled; if (enabled != null && !enabled.Value) { return; } } CharacterBody val = Coop.Local(); float num = (Object.op_Implicit((Object)(object)val) ? Vector3.Distance(val.corePosition, ((Component)this).transform.position) : 0f); float num2 = 1f / (1f + Mathf.Max(0f, num - 12f) / 32f); switch (key) { case "KickSwing": case "KickHit": case "KickFlip": num2 *= 0.35f; break; } int num3 = Mathf.RoundToInt(num2 * (float)((!line) ? (Coop.EffectsVolume?.Value ?? 26) : (Coop.VoiceVolume?.Value ?? 25))); if (num3 <= 0) { return; } try { output.Play(key, Path.Combine(Coop.Folder, line ? "Voices" : "Effects"), num3, loop); } catch (Exception ex) { Debug.LogWarning((object)("Gohan multiplayer audio " + key + ": " + ex.Message)); } } private void Update() { voice.Collect(stop: false); fx.Collect(stop: false); charge.Collect(stop: false); if (looping && Time.unscaledTime - received > 1f) { wind.Collect(stop: true); looping = false; } } private void OnDestroy() { voice.Collect(stop: true); fx.Collect(stop: true); wind.Collect(stop: true); charge.Collect(stop: true); } } }