Decompiled source of SkulOrcAnimals v1.0.0

plugins/SkulOrcAnimals.dll

Decompiled a month ago
using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using BepInEx;
using BepInEx.Logging;
using Characters.Gear;
using Characters.Gear.Quintessences;
using Characters.Gear.Quintessences.Effects;
using Data;
using HarmonyLib;
using Level;
using Microsoft.CodeAnalysis;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")]
[assembly: AssemblyCompany("SkulOrcAnimals")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("SkulOrcAnimals")]
[assembly: AssemblyTitle("SkulOrcAnimals")]
[assembly: AssemblyVersion("1.0.0.0")]
[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 SkulOrcAnimals
{
	internal static class OrcPatches
	{
		private static Quintessence _inUse;

		private static bool _effectSeenDuringUse;

		private static int _passiveLogs;

		private static int _nonOrcUseLogs;

		private static int _useWithoutEffectLogs;

		private static int _orcUsesSeen;

		internal static int OrcUsesSeen => _orcUsesSeen;

		internal static void SelfCheck()
		{
			Probe.Append("self-check: 入口 = QuintessenceEffect.Invoke(只在 Quintessence.Use 期间才算); 识别 = 内部名/显示名含 orc|兽人|獸人|オーク");
		}

		internal static void BeginUse(Quintessence quintessence)
		{
			_inUse = quintessence;
			_effectSeenDuringUse = false;
		}

		internal static void EndUse(Quintessence quintessence)
		{
			try
			{
				if (_inUse == quintessence && !_effectSeenDuringUse && (LooksOrc(Normalize(((Object)quintessence).name)) || LooksOrc(SafeDisplay(quintessence))) && _useWithoutEffectLogs < 5)
				{
					_useWithoutEffectLogs++;
					Probe.Append("note: 兽人 Use() 跑了但没走到效果 Invoke(被 constraint 挡住,或这个精华没有主动效果)—— 这一次不算使用");
				}
			}
			finally
			{
				_inUse = null;
				_effectSeenDuringUse = false;
			}
		}

		internal static void OnEffect(Quintessence quintessence)
		{
			if ((Object)(object)quintessence == (Object)null)
			{
				return;
			}
			string text = Normalize(((Object)quintessence).name);
			if (_inUse != quintessence)
			{
				if (_passiveLogs < 5)
				{
					_passiveLogs++;
					Probe.Append("effect outside Use() for '" + text + "'(装备/被动路径)-> 忽略");
				}
				return;
			}
			_effectSeenDuringUse = true;
			string text2 = SafeDisplay(quintessence);
			if (!LooksOrc(text) && !LooksOrc(text2))
			{
				if (_nonOrcUseLogs < 8)
				{
					_nonOrcUseLogs++;
					Probe.Append("use: '" + text + "' display '" + text2 + "' isOrc=False(不是兽人,忽略)");
				}
			}
			else
			{
				_orcUsesSeen++;
				Probe.Append($"use: '{text}' display '{text2}' isOrc=True(第 {_orcUsesSeen} 次识别到兽人使用)");
				OrcVoice instance = OrcVoice.Instance;
				if ((Object)(object)instance == (Object)null)
				{
					Probe.Append("WARNING: OrcVoice.Instance 为空(watcher 没建起来)");
				}
				else
				{
					instance.OnOrcUsed();
				}
			}
		}

		private static string Normalize(string name)
		{
			if (string.IsNullOrEmpty(name))
			{
				return name;
			}
			if (!name.EndsWith("(Clone)", StringComparison.Ordinal))
			{
				return name;
			}
			return name.Substring(0, name.Length - "(Clone)".Length);
		}

		private static string SafeDisplay(Quintessence q)
		{
			try
			{
				return ((Gear)q).displayName;
			}
			catch (Exception ex)
			{
				Probe.Append("displayName lookup failed: " + ex.Message);
				return null;
			}
		}

		private static bool LooksOrc(string s)
		{
			if (string.IsNullOrEmpty(s))
			{
				return false;
			}
			if (s.IndexOf("兽人", StringComparison.Ordinal) >= 0)
			{
				return true;
			}
			if (s.IndexOf("獸人", StringComparison.Ordinal) >= 0)
			{
				return true;
			}
			if (s.IndexOf("オーク", StringComparison.Ordinal) >= 0)
			{
				return true;
			}
			if (s.IndexOf("orc", StringComparison.OrdinalIgnoreCase) >= 0)
			{
				return true;
			}
			return false;
		}
	}
	[HarmonyPatch(typeof(Quintessence), "Use", new Type[] { })]
	internal static class QuintessenceUsePatch
	{
		[HarmonyPrefix]
		private static void Before(Quintessence __instance)
		{
			try
			{
				OrcPatches.BeginUse(__instance);
			}
			catch (Exception e)
			{
				Probe.Error("BeforeUse failed", e);
			}
		}

		[HarmonyPostfix]
		private static void After(Quintessence __instance)
		{
			try
			{
				OrcPatches.EndUse(__instance);
			}
			catch (Exception e)
			{
				Probe.Error("AfterUse failed", e);
			}
		}
	}
	[HarmonyPatch(typeof(QuintessenceEffect), "Invoke", new Type[] { typeof(Quintessence) })]
	internal static class QuintessenceEffectInvokePatch
	{
		[HarmonyPostfix]
		private static void After(Quintessence quintessence)
		{
			try
			{
				OrcPatches.OnEffect(quintessence);
			}
			catch (Exception e)
			{
				Probe.Error("AfterEffectInvoke failed", e);
			}
		}
	}
	internal sealed class OrcVoice : MonoBehaviour
	{
		private const float VolumeScale = 1f;

		private const float DefaultVolume = 0.8f;

		private const float MutedMasterThreshold = 0.06f;

		private const float PitchStep = 0.1f;

		private const float MaxPitch = 3f;

		internal static OrcVoice Instance;

		private AudioSource _source;

		private AudioClip _clip;

		private Map _room;

		private int _useCountInRoom;

		private int _playCount;

		private bool _clipErrorLogged;

		private bool _volumeReadFailureLogged;

		private void Awake()
		{
			Instance = this;
			_source = ((Component)this).gameObject.AddComponent<AudioSource>();
			_source.playOnAwake = false;
			_source.loop = false;
			_source.spatialBlend = 0f;
			_source.dopplerLevel = 0f;
			_source.ignoreListenerPause = true;
			_source.volume = 0f;
			Probe.Append($"voice: loop=false(每次使用只播一次), 速度 = 1.0 + {0.1f:0.0}×(房间内第几次-1) 上限 {3f:0.0}x, " + $"音量 = 主音量 ×{1f:0.##}(主音量≈0 时用 {0.8f:0.##})");
			Probe.Append("voice: 换房间用 Map.Instance 变化判定(不订阅 onMapLoaded,避免被 ClearEvents 清掉)");
		}

		private void Update()
		{
			try
			{
				TrackRoom();
			}
			catch (Exception e)
			{
				Probe.Error("room tracking failed", e);
			}
		}

		private void TrackRoom()
		{
			Map instance = Map.Instance;
			if (instance != _room)
			{
				if (_useCountInRoom > 0)
				{
					Probe.Append($"room changed ('{NameOf(_room)}' -> '{NameOf(instance)}') -> 加速层数清零(上个房间共 {_useCountInRoom} 次,末速 {SpeedFor(_useCountInRoom):0.0}x)");
				}
				_room = instance;
				_useCountInRoom = 0;
			}
		}

		internal void OnOrcUsed()
		{
			TrackRoom();
			EnsureClip();
			if (!((Object)(object)_clip == (Object)null))
			{
				_useCountInRoom++;
				float num = SpeedFor(_useCountInRoom);
				float num2 = ReadVolume();
				_playCount++;
				_source.Stop();
				_source.clip = _clip;
				_source.pitch = num;
				_source.volume = num2;
				_source.Play();
				Probe.Append($"PLAY #{_playCount}: 房间内第 {_useCountInRoom} 次使用兽人 -> 速度 {num:0.0}x, 音量 {num2:0.##}, " + $"isPlaying={_source.isPlaying}, clip={_clip.length:0.00}s, 房间='{NameOf(_room)}'");
			}
		}

		private static float SpeedFor(int useCountInRoom)
		{
			return Mathf.Clamp(1f + 0.1f * (float)(useCountInRoom - 1), 0.1f, 3f);
		}

		private void EnsureClip()
		{
			if ((Object)(object)_clip != (Object)null)
			{
				return;
			}
			try
			{
				_clip = WavClip.Load();
			}
			catch (Exception e)
			{
				if (!_clipErrorLogged)
				{
					_clipErrorLogged = true;
					Probe.Error("内嵌 animals.wav 解不出来(下次使用会再试)", e);
				}
			}
		}

		private float ReadVolume()
		{
			try
			{
				float masterVolume = Settings.masterVolume;
				return Mathf.Clamp01(((masterVolume < 0.06f) ? 0.8f : masterVolume) * 1f);
			}
			catch (Exception ex)
			{
				if (!_volumeReadFailureLogged)
				{
					_volumeReadFailureLogged = true;
					Probe.Append("could not read GameData.Settings.masterVolume, falling back to 0.8: " + ex.Message);
				}
				return Mathf.Clamp01(0.8f);
			}
		}

		private static string NameOf(Map map)
		{
			if (!((Object)(object)map != (Object)null))
			{
				return "none";
			}
			return ((Object)map).name;
		}
	}
	[BepInPlugin("skulorc.animals", "Skul Orc Animals", "1.0.0")]
	public class Plugin : BaseUnityPlugin
	{
		public const string Guid = "skulorc.animals";

		public const string PluginName = "Skul Orc Animals";

		public const string Version = "1.0.0";

		internal static ManualLogSource Log;

		private void Awake()
		{
			//IL_00aa: 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)
			//IL_00b5: Expected O, but got Unknown
			//IL_00db: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e0: Unknown result type (might be due to invalid IL or missing references)
			Log = ((BaseUnityPlugin)this).Logger;
			Probe.Reset();
			Log.LogInfo((object)("[ORCANIMALS] plugin awake, version 1.0.0, asm=" + Assembly.GetExecutingAssembly().Location));
			Probe.Append("plugin-loaded v1.0.0 (BepInEx chain is alive)");
			try
			{
				AudioClip val = WavClip.Load();
				Probe.Append($"preload done: '{((Object)val).name}' {val.frequency} Hz / {val.channels} ch / {val.samples} frames ({val.length:0.00} s)");
			}
			catch (Exception e)
			{
				Probe.Error("preload failed(第一次使用时会重试)", e);
			}
			try
			{
				GameObject val2 = new GameObject("OrcAnimals");
				Object.DontDestroyOnLoad((Object)val2);
				val2.AddComponent<OrcVoice>();
				Probe.Append("voice attached on a DontDestroyOnLoad object");
			}
			catch (Exception e2)
			{
				Probe.Error("could not attach OrcVoice", e2);
			}
			try
			{
				Harmony val3 = new Harmony("skulorc.animals");
				val3.PatchAll(typeof(QuintessenceUsePatch));
				val3.PatchAll(typeof(QuintessenceEffectInvokePatch));
				Probe.Append("patches installed: Quintessence.Use + QuintessenceEffect.Invoke");
				OrcPatches.SelfCheck();
			}
			catch (Exception e3)
			{
				Probe.Error("patch FAILED", e3);
			}
		}
	}
	internal static class Probe
	{
		private static readonly string ProbePath = Path.Combine(Paths.GameRootPath, "BepInEx", "orc-animals-probe.log");

		private static readonly UTF8Encoding Utf8Bom = new UTF8Encoding(encoderShouldEmitUTF8Identifier: true);

		private static int _writeFailures;

		internal static void Reset()
		{
			_writeFailures = 0;
			try
			{
				File.WriteAllText(ProbePath, $"=== SkulOrcAnimals probe {DateTime.Now:yyyy-MM-dd HH:mm:ss} ==={Environment.NewLine}", Utf8Bom);
			}
			catch (Exception ex)
			{
				if (Plugin.Log != null)
				{
					Plugin.Log.LogError((object)("[ORCANIMALS] probe reset failed: " + ex));
				}
			}
		}

		internal static void Append(string line)
		{
			if (Plugin.Log != null)
			{
				Plugin.Log.LogInfo((object)("[ORCANIMALS] " + line));
			}
			if (_writeFailures >= 3)
			{
				return;
			}
			try
			{
				File.AppendAllText(ProbePath, $"{DateTime.Now:HH:mm:ss.fff} {line}{Environment.NewLine}", Utf8Bom);
			}
			catch (Exception ex)
			{
				_writeFailures++;
				if (Plugin.Log != null)
				{
					Plugin.Log.LogError((object)$"[ORCANIMALS] probe write failed ({_writeFailures}/3): {ex.Message}");
				}
			}
		}

		internal static void Error(string what, Exception e)
		{
			Append($"ERROR {what}: {e}");
		}
	}
	internal static class WavClip
	{
		internal const string ResourceName = "SkulOrcAnimals.animals.wav";

		private static AudioClip _clip;

		internal static AudioClip Clip => _clip;

		internal static AudioClip Load()
		{
			if ((Object)(object)_clip != (Object)null)
			{
				return _clip;
			}
			Assembly assembly = typeof(WavClip).Assembly;
			Stopwatch clock = Stopwatch.StartNew();
			using (Stream stream = assembly.GetManifestResourceStream("SkulOrcAnimals.animals.wav"))
			{
				if (stream == null)
				{
					throw new InvalidOperationException("embedded resource 'SkulOrcAnimals.animals.wav' is missing; present: " + string.Join(", ", assembly.GetManifestResourceNames()));
				}
				byte[] array = new byte[(int)stream.Length];
				int i;
				int num;
				for (i = 0; i < array.Length; i += num)
				{
					num = stream.Read(array, i, array.Length - i);
					if (num <= 0)
					{
						break;
					}
				}
				if (i != array.Length)
				{
					throw new InvalidOperationException($"short read: {i}/{array.Length} bytes");
				}
				_clip = Decode(array, clock);
			}
			return _clip;
		}

		private static AudioClip Decode(byte[] bytes, Stopwatch clock)
		{
			//IL_035b: Unknown result type (might be due to invalid IL or missing references)
			if (bytes.Length < 44)
			{
				throw new InvalidOperationException($"wav too short: {bytes.Length} bytes");
			}
			if (!IsTag(bytes, 0, "RIFF") || !IsTag(bytes, 8, "WAVE"))
			{
				throw new InvalidOperationException("not a RIFF/WAVE file");
			}
			int num = 0;
			int num2 = 0;
			int num3 = 0;
			int num4 = 0;
			int num5 = -1;
			int num6 = 0;
			int num7 = 12;
			while (num7 + 8 <= bytes.Length)
			{
				int num8 = BitConverter.ToInt32(bytes, num7 + 4);
				int num9 = num7 + 8;
				if (IsTag(bytes, num7, "fmt ") && num8 >= 16)
				{
					num = BitConverter.ToUInt16(bytes, num9);
					num2 = BitConverter.ToInt16(bytes, num9 + 2);
					num3 = BitConverter.ToInt32(bytes, num9 + 4);
					num4 = BitConverter.ToUInt16(bytes, num9 + 14);
					if (num == 65534 && num8 >= 40)
					{
						num = BitConverter.ToUInt16(bytes, num9 + 24);
					}
				}
				else if (IsTag(bytes, num7, "data"))
				{
					num5 = num9;
					num6 = Math.Min(num8, bytes.Length - num9);
				}
				if (num8 <= 0)
				{
					break;
				}
				num7 = num9 + num8 + (num8 & 1);
			}
			if (num != 1)
			{
				throw new InvalidOperationException($"expected PCM (format 1), got {num}");
			}
			if (num4 != 16)
			{
				throw new InvalidOperationException($"expected 16-bit samples, got {num4}");
			}
			if (num2 < 1 || num2 > 2)
			{
				throw new InvalidOperationException($"unsupported channel count: {num2}");
			}
			if (num3 < 8000 || num3 > 192000)
			{
				throw new InvalidOperationException($"unsupported sample rate: {num3}");
			}
			if (num5 < 0 || num6 <= 0)
			{
				throw new InvalidOperationException("no 'data' chunk");
			}
			int num10 = num2 * 2;
			int num11 = num6 / num10;
			if (num11 <= 0)
			{
				throw new InvalidOperationException("empty 'data' chunk");
			}
			float[] array = new float[num11 * num2];
			double num12 = 0.0;
			float num13 = 0f;
			int num14 = num5;
			for (int i = 0; i < array.Length; i++)
			{
				short num15 = (short)(bytes[num14] | (bytes[num14 + 1] << 8));
				num14 += 2;
				float num16 = (array[i] = (float)num15 / 32768f);
				float num17 = ((num16 < 0f) ? (0f - num16) : num16);
				if (num17 > num13)
				{
					num13 = num17;
				}
				num12 += (double)num16 * (double)num16;
			}
			double num18 = Math.Sqrt(num12 / (double)array.Length);
			double num19 = (double)num11 / (double)num3;
			AudioClip val = AudioClip.Create("OrcAnimals", num11, num2, num3, false);
			if ((Object)(object)val == (Object)null)
			{
				throw new InvalidOperationException("AudioClip.Create returned null");
			}
			if (!val.SetData(array, 0))
			{
				throw new InvalidOperationException("AudioClip.SetData failed");
			}
			clock.Stop();
			Probe.Append(string.Format("audio ready: embedded '{0}' {1:0.00} MB -> ", "SkulOrcAnimals.animals.wav", (double)bytes.Length / 1048576.0) + $"AudioClip {num3} Hz / {num2} ch / {num11} frames ({num19:0.00} s), " + $"peak {num13:0.000} rms {num18:0.000}, decoded in {clock.ElapsedMilliseconds} ms");
			Probe.Append($"audio read-back: clip.name='{((Object)val).name}' samples={val.samples} channels={val.channels} " + $"frequency={val.frequency} length={val.length:0.00}s loadState={val.loadState}");
			return val;
		}

		private static bool IsTag(byte[] b, int offset, string tag)
		{
			if (b[offset] == tag[0] && b[offset + 1] == tag[1] && b[offset + 2] == tag[2])
			{
				return b[offset + 3] == tag[3];
			}
			return false;
		}
	}
}