Decompiled source of Unholy Rites v0.1.0

UnholyRites.dll

Decompiled 2 days ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Text;
using System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using I2.Loc;
using Microsoft.CodeAnalysis;
using PerfectRandom.Sulfur.Core;
using PerfectRandom.Sulfur.Core.Audio;
using PerfectRandom.Sulfur.Core.CharacterStats;
using PerfectRandom.Sulfur.Core.DataStorage;
using PerfectRandom.Sulfur.Core.DevTools;
using PerfectRandom.Sulfur.Core.Effects;
using PerfectRandom.Sulfur.Core.Items;
using PerfectRandom.Sulfur.Core.Movement;
using PerfectRandom.Sulfur.Core.Stats;
using PerfectRandom.Sulfur.Core.UI;
using PerfectRandom.Sulfur.Core.UI.Inventory;
using PerfectRandom.Sulfur.Core.UI.ItemDescription;
using PerfectRandom.Sulfur.Core.Units;
using PerfectRandom.Sulfur.Core.Weapons;
using PerfectRandom.Sulfur.Core.World;
using PerfectRandom.Sulfur.Gameplay;
using PerfectRandom.Sulfur.Gameplay.Input;
using Ryuka.Sulfur.ContentLib;
using SULFURTogether.Api;
using Sonity;
using Sonity.Internal;
using TMPro;
using UnholyRites.Combat;
using UnholyRites.Content;
using UnholyRites.Dev;
using UnholyRites.Hud;
using UnholyRites.Localization;
using UnholyRites.Net;
using UnholyRites.Patches;
using UnholyRites.Rendering;
using UnholyRites.Spells;
using UnholyRites.Spells.Casting;
using UnholyRites.Spells.Runtime;
using UnholyRites.Staves;
using Unity.Collections;
using Unity.Jobs;
using Unity.Mathematics;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.Controls;
using UnityEngine.Rendering;
using UnityEngine.Rendering.Universal;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyCompany("UnholyRites")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+3afbebe615b427af729b6f83e8ac4b7129af7780")]
[assembly: AssemblyProduct("UnholyRites")]
[assembly: AssemblyTitle("UnholyRites")]
[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 UnholyRites
{
	public static class ModInfo
	{
		public const string Id = "ryuka.sulfur.unholy_rites";

		public const string Name = "Unholy Rites";

		public const string Version = "0.1.0";
	}
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInPlugin("ryuka.sulfur.unholy_rites", "Unholy Rites", "0.1.0")]
	public sealed class Plugin : BaseUnityPlugin
	{
		private Harmony harmony;

		internal static ManualLogSource Log { get; private set; }

		internal static Plugin Behaviour { get; private set; }

		internal static ConfigEntry<int> ProbeInstanceCount { get; private set; }

		internal static ConfigEntry<float> ProbeInstanceScale { get; private set; }

		internal static ConfigEntry<float> ProbeRadius { get; private set; }

		internal static ConfigEntry<string> TestStaffProgram { get; private set; }

		internal static ConfigEntry<string> ExportPlayerDocs { get; private set; }

		internal static ConfigEntry<float> VoxelDensity { get; private set; }

		internal static ConfigEntry<bool> SelfDamage { get; private set; }

		internal static ConfigEntry<string> ManaDrainOrder { get; private set; }

		internal static ConfigEntry<string> StaffModelPosition { get; private set; }

		internal static ConfigEntry<string> StaffModelRotation { get; private set; }

		internal static ConfigEntry<float> StaffModelScale { get; private set; }

		internal static ConfigEntry<bool> DeveloperMode { get; private set; }

		internal static ConfigEntry<int> SoundBrowseFrom { get; private set; }

		internal static ConfigEntry<float> SoundPowerScaling { get; private set; }

		internal static SpellSession Session { get; private set; }

		private void Awake()
		{
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Expected O, but got Unknown
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Expected O, but got Unknown
			//IL_00b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bb: Expected O, but got Unknown
			//IL_015f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0169: Expected O, but got Unknown
			//IL_0313: Unknown result type (might be due to invalid IL or missing references)
			//IL_031d: Expected O, but got Unknown
			Log = ((BaseUnityPlugin)this).Logger;
			Behaviour = this;
			ProbeInstanceCount = ((BaseUnityPlugin)this).Config.Bind<int>("RenderProbe", "InstanceCount", 0, new ConfigDescription("Development probe for the rendering slice. Draws this many instances in front of the camera and logs frame, fill and upload timings every two seconds. 0 disables it. Safe to change while the game is running.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 300000), Array.Empty<object>()));
			ProbeInstanceScale = ((BaseUnityPlugin)this).Config.Bind<float>("RenderProbe", "InstanceScale", 0.15f, new ConfigDescription("Size of a single probe instance, in metres.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.01f, 2f), Array.Empty<object>()));
			ProbeRadius = ((BaseUnityPlugin)this).Config.Bind<float>("RenderProbe", "Radius", 6f, new ConfigDescription("Radius of the probe cloud, in metres.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.5f, 50f), Array.Empty<object>()));
			TestStaffProgram = ((BaseUnityPlugin)this).Config.Bind<string>("Testing", "StaffProgram", "fireball > split > empower", "Used only when no staff is held; a staff in hand always decides what it casts. Spell keys separated by '>' or ','. Available: fireball, frostbolt, venom, meteor, sigil, lightning, split, empower, skyfall, ritual, onhit, onmiss, else, pulse, pierce, concussion, gather, next, brand, hex, stone, sanctuary, radiance, blood, raise, grave_goods. Recompiles when changed.");
			ExportPlayerDocs = ((BaseUnityPlugin)this).Config.Bind<string>("Testing", "ExportPlayerDocs", string.Empty, "Development aid: set to a folder to write the players' reference pages there (Markdown, English and Chinese, from the mod's own data). Empties itself when done. Needs DeveloperMode.");
			ExportPlayerDocs.SettingChanged += delegate
			{
				PlayerDocsExport.OnRequested();
			};
			VoxelDensity = ((BaseUnityPlugin)this).Config.Bind<float>("Testing", "VoxelDensity", 1f, new ConfigDescription("Multiplies how many voxels make up each projectile. Raise it if a projectile looks sparse or full of holes; tens of thousands of voxels are affordable.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.1f, 8f), Array.Empty<object>()));
			SelfDamage = ((BaseUnityPlugin)this).Config.Bind<bool>("Gameplay", "SelfDamage", true, "Whether your own spells can hurt you. On by default: a spell that can kill you limits absurd staff programs in a way mana cost cannot, which is what lets the system stay this permissive about what may be combined.");
			ManaDrainOrder = ((BaseUnityPlugin)this).Config.Bind<string>("Gameplay", "ManaDrainOrder", "level", "How the mana vessel empties: 'level' drains like a liquid, 'spiral' burns from the outside in the way a drum magazine empties.");
			StaffModelPosition = ((BaseUnityPlugin)this).Config.Bind<string>("Staff", "ModelPosition", "0, 0, 0", "Where the staff model sits relative to the hand, as 'x, y, z' in metres. Takes effect immediately, so it can be tuned with the game running.");
			StaffModelRotation = ((BaseUnityPlugin)this).Config.Bind<string>("Staff", "ModelRotation", "-90, 0, 0", "How the staff model is turned, as 'x, y, z' in degrees, measured from the direction the weapon points rather than from the bone it hangs on — a bone's axes are whatever its rigger found convenient. The default stands it upright: a gun points forward, a staff is carried.");
			StaffModelScale = ((BaseUnityPlugin)this).Config.Bind<float>("Staff", "ModelScale", 0.4f, "Multiplier on the staff's authored size. The staff is mounted where a lighter was held, which is close to the face, so a full-length one fills the screen; the honest fix is to push it away with ModelPosition rather than shrink it, and this default is the placeholder answer until the model is redone.");
			DeveloperMode = ((BaseUnityPlugin)this).Config.Bind<bool>("Developer", "DeveloperMode", false, "Arms the development tooling: the debug keys and the sound workbench. Also requires the save to have been started with cheats enabled, which is the game's own mark for a run that does not count. Not meant for playing with.");
			SoundBrowseFrom = ((BaseUnityPlugin)this).Config.Bind<int>("Testing", "SoundBrowseFrom", -1, "Index for the sound browser to resume from the next time the browse key is pressed. -1 continues from wherever it had got to. The browser logs an index for every sound it plays, and the numbering is stable for a given game version.");
			SoundPowerScaling = ((BaseUnityPlugin)this).Config.Bind<float>("Sound", "PowerScaling", 1f, "How strongly a spell's cost changes what it sounds like: louder, lower and audible from further away as it gets more expensive. 0 plays every spell exactly as the game authored it; 1 is the intended curve; above 1 exaggerates it. Takes effect immediately.");
			SpellText.Language = SystemLanguageGuess();
			try
			{
				SpellContent.Declare(ContentBootstrap.Catalog);
				Acquisition.Register();
				try
				{
					SpellLocalization.GiveContentTexts();
				}
				catch (Exception arg)
				{
					((BaseUnityPlugin)this).Logger.LogError((object)$"Item and enchantment texts were not given; they will show in English: {arg}");
				}
				ContentManifest.Sealed += ContentBootstrap.OnContentSealed;
				if (ContentManifest.IsFaulted)
				{
					((BaseUnityPlugin)this).Logger.LogError((object)"SULFUR Content Lib faulted while starting; see its own log lines. The staff and scrolls will not be built in this session.");
				}
			}
			catch (Exception arg2)
			{
				((BaseUnityPlugin)this).Logger.LogError((object)$"Spell content was not declared; there will be no staff or scrolls: {arg2}");
			}
			harmony = new Harmony("ryuka.sulfur.unholy_rites");
			try
			{
				harmony.PatchAll();
			}
			catch (Exception ex)
			{
				((BaseUnityPlugin)this).Logger.LogError((object)("Some patches did not apply; parts of the mod will not work: " + ex.Message));
			}
			try
			{
				LanguageSourcesLoadedPatch.Apply(harmony);
			}
			catch (Exception ex2)
			{
				((BaseUnityPlugin)this).Logger.LogError((object)("Localization was not hooked; names will stay in English: " + ex2.Message));
			}
			try
			{
				Session = new SpellSession();
			}
			catch (Exception arg3)
			{
				((BaseUnityPlugin)this).Logger.LogError((object)$"The spell session could not be created; nothing will cast: {arg3}");
			}
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Unholy Rites loaded. Developer tooling is behind Developer/DeveloperMode in the configuration and a save started with cheats enabled; it says so when it arms.");
		}

		private static SpellLanguage SystemLanguageGuess()
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0005: 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_0008: Invalid comparison between Unknown and I4
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Invalid comparison between Unknown and I4
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Invalid comparison between Unknown and I4
			SystemLanguage systemLanguage = Application.systemLanguage;
			if ((int)systemLanguage != 6 && (int)systemLanguage != 40)
			{
				if ((int)systemLanguage == 41)
				{
					return SpellLanguage.TraditionalChinese;
				}
				return SpellLanguage.English;
			}
			return SpellLanguage.Chinese;
		}

		private void Update()
		{
			if (Session != null)
			{
				float time = Time.time;
				Session.Tick(time, Time.deltaTime);
				DevTools.Tick();
				bool trigger = !DevTools.CapturingInput && (HeldStaff.Equipped ? HeldStaff.TriggerHeld : DevTools.DebugCastHeld());
				bool second = !DevTools.CapturingInput && HeldStaff.AltHeld;
				Session.UpdateCast(trigger, second, time);
			}
		}

		private void OnGUI()
		{
			DevTools.Draw();
		}

		private void OnDestroy()
		{
			ContentManifest.Sealed -= ContentBootstrap.OnContentSealed;
			SpellLocalization.Unregister();
			StaffManaHud.Release();
			Session?.Dispose();
			Session = null;
			VoxelRenderProbe.Dispose();
			VoxelMeshes.Release();
			if (harmony != null)
			{
				harmony.UnpatchSelf();
			}
		}
	}
	internal sealed class SpellSession : IDisposable
	{
		private readonly SpellCatalog _catalog = SpellCatalog.CreateSample();

		private readonly SpellRuntime _runtime = new SpellRuntime();

		private readonly SpellVoxelRenderer _renderer = new SpellVoxelRenderer(65536);

		private readonly SpellHitResolver _hits = new SpellHitResolver();

		private readonly PayloadTable _payloads = new PayloadTable();

		private readonly SpellNetwork _network;

		private ManaPool _castPool;

		private StaffDefinition _castStaff = StaffDefinitions.Bench;

		private InventoryItem _castItem;

		private bool _reportedPayloadOverflow;

		private string _compiledFrom;

		private CastPlan _plan = CastPlan.Empty;

		private SpellSegments _segments;

		private int _segment;

		private InventoryItem _segmentsOwner;

		private float _nextCastTime;

		private uint _castCounter;

		private string _presetProgram;

		private string _configAtPresetTime;

		private int _presetIndex = -1;

		private BeamChannel _beam;

		private float _nextBeamAim;

		private float _beamSpent;

		private float _beamStart;

		private bool _channelling;

		private float _channelStart;

		private bool _chantStands;

		private Vector3 _chantLast;

		private Vector3 _chantWalked;

		private readonly Dictionary<string, float> _alertShown = new Dictionary<string, float>();

		private bool _awaitRelease;

		private int _awaitHand;

		private const float StandTolerance = 0.6f;

		private const float AlertRepeat = 2.5f;

		private uint _channelSeed;

		private int _channelGroup;

		private CastTarget _channelTarget;

		private readonly Dictionary<uint, InventoryItem> _castFrom = new Dictionary<uint, InventoryItem>();

		private readonly Queue<uint> _castFromOrder = new Queue<uint>();

		internal bool IsChannelling => _channelling;

		internal float ChantMoveFactor => _castStaff.ChantMoveFactor;

		internal ManaPool Mana => StaffMana.For(HeldStaff.Item, Time.time);

		internal CastPlan Plan => _plan;

		internal int PresetIndex => _presetIndex;

		internal string CurrentProgram => _presetProgram ?? Plugin.TestStaffProgram.Value ?? string.Empty;

		internal static Unit LocalPlayer => LocalUnit();

		internal SpellSession()
		{
			_network = new SpellNetwork(_catalog, _runtime, _hits, _payloads);
			SpellHitResolver.KillCredited += OnKillCredited;
		}

		private void NoteCastFrom(uint seed, InventoryItem staff)
		{
			if (!((Object)(object)staff == (Object)null) && ManaChambers.Of(staff) == ChamberKind.Reaping)
			{
				_castFrom[seed] = staff;
				_castFromOrder.Enqueue(seed);
				while (_castFromOrder.Count > 128)
				{
					_castFrom.Remove(_castFromOrder.Dequeue());
				}
			}
		}

		private void OnKillCredited(uint castSeed, float maxHealth)
		{
			if (_castFrom.TryGetValue(castSeed, out var value))
			{
				ManaChambers.Reap(value, maxHealth, Time.time);
			}
		}

		internal void Tick(float now, float deltaTime)
		{
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_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)
			EnsureCompiled();
			_hits.Resolve(_runtime, _payloads, now, deltaTime, _network.FriendlyFire);
			if (_runtime.HasFollowers)
			{
				Camera main = Camera.main;
				if ((Object)(object)main != (Object)null)
				{
					Vector3 position = ((Component)main).transform.position;
					_runtime.MoveFollowers(CastTrace.Below(position, 3.5f, position + Vector3.down * 1.6f));
				}
			}
			_network.Tick(now);
			_renderer.Build(_runtime, now);
			SpellAmbience.Sync(_runtime, now);
			if (_payloads.Overflowed && !_reportedPayloadOverflow)
			{
				_reportedPayloadOverflow = true;
				Plugin.Log.LogWarning((object)($"The payload table reached its {512}-entry ceiling. " + "Programs compiled from here on will cast without what they carry. This means payloads are being registered per cast rather than per compiled plan."));
			}
			EndowedPuppets.Tick(now);
			PoisonFountain.Tick(now, _network.ResolvesOwnDamage);
			StaffManaHud.Tick(StaffMana.For(HeldStaff.Item, now), now, (_segments != null && _segments.Count > 1 && !_segments.Hands) ? $"{_segment % _segments.Count + 1}/{_segments.Count}" : null);
		}

		internal void Draw(ScriptableRenderContext context, Camera camera)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			_renderer.Draw(context, camera);
		}

		internal void CyclePreset()
		{
			SelectPreset(_presetIndex + 1);
		}

		internal void SelectPreset(int index)
		{
			if (CanReplaceProgram())
			{
				int num = SpellPresets.All.Length;
				_presetIndex = (index % num + num) % num;
				_presetProgram = SpellPresets.All[_presetIndex].Program;
				_configAtPresetTime = Plugin.TestStaffProgram.Value ?? string.Empty;
				EnsureCompiled();
				Plugin.Log.LogInfo((object)(string.Format("{0} {1}/{2}: ", SpellText.Get("cast.preset", "Preset"), _presetIndex + 1, num) + SpellPresets.Describe(_presetIndex)));
			}
		}

		internal void SetProgram(string program)
		{
			if (CanReplaceProgram())
			{
				_presetIndex = -1;
				_presetProgram = program ?? string.Empty;
				_configAtPresetTime = Plugin.TestStaffProgram.Value ?? string.Empty;
				EnsureCompiled();
			}
		}

		private bool CanReplaceProgram()
		{
			if (!HeldStaff.Equipped)
			{
				return true;
			}
			Plugin.Log.LogInfo((object)SpellText.Get("cast.staff_in_hand", "A staff is equipped; it decides what is cast. Put it away to use the test programs."));
			return false;
		}

		private void EnsureCompiled()
		{
			HeldStaff.Refresh();
			if (_channelling || _beam != null)
			{
				return;
			}
			SpellSegments spellSegments = StaffProgram.For(HeldStaff.Item);
			if (spellSegments != null)
			{
				if (_segments != spellSegments)
				{
					bool num = _segmentsOwner == HeldStaff.Item && _segments != null && string.Equals(_segments.Key, spellSegments.Key, StringComparison.Ordinal);
					_segments = spellSegments;
					_segmentsOwner = HeldStaff.Item;
					_compiledFrom = null;
					if (!num)
					{
						_segment = 0;
						Plugin.Log.LogInfo((object)(SpellText.Get("cast.compiled", "Staff ready") + "\n" + _segments.Summary));
					}
				}
				_plan = _segments.Plans[_segment % _segments.Count];
			}
			else
			{
				CompileFromConfig();
			}
		}

		private void CompileFromConfig()
		{
			string text = Plugin.TestStaffProgram.Value ?? string.Empty;
			if (_presetProgram != null && !string.Equals(text, _configAtPresetTime, StringComparison.Ordinal))
			{
				_presetProgram = null;
				_presetIndex = -1;
			}
			string text2 = _presetProgram ?? text;
			if (string.Equals(text2, _compiledFrom, StringComparison.Ordinal) && _segments != null)
			{
				_plan = _segments.Plans[_segment % _segments.Count];
				return;
			}
			_compiledFrom = text2;
			List<SpellDefinition> list = new List<SpellDefinition>();
			List<string> list2 = new List<string>();
			string[] array = text2.Split(new char[2] { '>', ',' }, StringSplitOptions.RemoveEmptyEntries);
			for (int i = 0; i < array.Length; i++)
			{
				string text3 = array[i].Trim();
				if (text3.Length != 0)
				{
					SpellDefinition spellDefinition = _catalog.Get(text3);
					if (spellDefinition == null)
					{
						list2.Add(text3);
					}
					else
					{
						list.Add(spellDefinition);
					}
				}
			}
			_segments = SpellSegments.Compile(list, _catalog);
			_segmentsOwner = null;
			_segment = 0;
			_plan = _segments.Plans[0];
			if (list2.Count > 0)
			{
				Plugin.Log.LogWarning((object)("Test staff skipped unknown spells: " + string.Join(", ", list2) + "."));
			}
			Plugin.Log.LogInfo((object)(SpellText.Get("cast.compiled", "Test staff ready") + " [" + text2 + "]\n" + _segments.Summary));
		}

		internal void UpdateCast(bool trigger, bool second, float now)
		{
			if (_awaitRelease)
			{
				if (!((_awaitHand == 0) ? trigger : second))
				{
					_awaitRelease = false;
				}
				else if (_awaitHand == 0)
				{
					trigger = false;
				}
				else
				{
					second = false;
				}
			}
			bool holding = trigger;
			if (_segments != null && _segments.Hands)
			{
				if (!_channelling && _beam == null)
				{
					bool flag = _segments.Plans[0].EmissionCount > 0;
					bool flag2 = _segments.Plans[1].EmissionCount > 0;
					int num = ((!trigger || (!flag && second && flag2)) ? ((second && flag2) ? 1 : (-1)) : 0);
					if (num < 0)
					{
						UpdateCastFor(holding: false, now);
						return;
					}
					_segment = num;
					_plan = _segments.Plans[num];
				}
				holding = ((_segment == 0) ? trigger : second);
			}
			UpdateCastFor(holding, now);
		}

		private void UpdateCastFor(bool holding, float now)
		{
			if (_beam != null)
			{
				if (!holding)
				{
					EndBeam("released");
				}
				else
				{
					DriveBeam(now);
				}
				return;
			}
			if (!_channelling)
			{
				if (holding)
				{
					TryBegin(now);
				}
				return;
			}
			if (_chantStands && MovedOffAnchor())
			{
				CancelChannel();
				_awaitRelease = true;
				_awaitHand = ((_segments != null && _segments.Hands) ? _segment : 0);
				Plugin.Log.LogInfo((object)SpellText.Get("cast.ritual_moved", "The ritual broke: you moved while chanting."));
				Alert("UnholyRites/RitualBroken", SpellTerms.RitualBroken, now);
				return;
			}
			StaffMana.MarkActive(_castItem, now);
			if (!holding)
			{
				CancelChannel();
				if (HeldStaff.Equipped)
				{
					Alert("UnholyRites/ChantReleased", SpellTerms.ChantReleased, now);
				}
			}
			else
			{
				TrackChannel();
				if (now - _channelStart >= _plan.CastTime)
				{
					Resolve(now);
				}
			}
		}

		private void TrackChannel()
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			if (ResolveTarget(out var target))
			{
				target.Point = _channelTarget.Point;
				target.HasPoint = _channelTarget.HasPoint;
				_channelTarget = target;
			}
		}

		private void TryBegin(float now)
		{
			//IL_0220: Unknown result type (might be due to invalid IL or missing references)
			//IL_0213: Unknown result type (might be due to invalid IL or missing references)
			//IL_0225: Unknown result type (might be due to invalid IL or missing references)
			//IL_022b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0230: Unknown result type (might be due to invalid IL or missing references)
			//IL_028f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0282: Unknown result type (might be due to invalid IL or missing references)
			if (now < _nextCastTime || !ResolveTarget(out _channelTarget))
			{
				return;
			}
			if (_plan == null || _plan.EmissionCount == 0)
			{
				_nextCastTime = now + 0.5f;
				ReportNothingToCast(now);
				return;
			}
			_castPool = StaffMana.For(HeldStaff.Item, now);
			_castStaff = StaffDefinitions.Of(HeldStaff.Item);
			_castItem = HeldStaff.Item;
			ManaChambers.CoverShortfall(_castItem, _castPool, _plan.ManaCost, LocalUnit());
			float num = OathOwes();
			if (num <= 0f && !_castPool.CanAfford(_plan.ManaCost))
			{
				_nextCastTime = now + 0.5f;
				Plugin.Log.LogInfo((object)(SpellText.Get("cast.not_enough", "Not enough mana: need") + " " + string.Format("{0:0.#}, {1} {2:0.#}", _plan.ManaCost, SpellText.Get("cast.have", "have"), _castPool.Current)));
				Alert("UnholyRites/ManaShort", SpellTerms.ManaShort, now);
			}
			else
			{
				if (!RefuseBlood(now, num))
				{
					return;
				}
				StaffMana.MarkActive(_castItem, now);
				if (_plan.Targeting == TargetingKind.Point)
				{
					SigilStake.TryTakeOver(ref _channelTarget, now);
				}
				_channelSeed = (uint)(Environment.TickCount * -1640531535) ^ ++_castCounter;
				NoteCastFrom(_channelSeed, _castItem);
				if (!_plan.IsRitual)
				{
					_channelStart = now;
					if (_plan.IsBeam)
					{
						BeginBeam(now);
					}
					else
					{
						Resolve(now);
					}
					return;
				}
				_channelling = true;
				_channelStart = now;
				_channelGroup = SpellGroups.Next();
				Unit val = LocalUnit();
				_chantStands = (Object)(object)val != (Object)null && PlanStands(_plan);
				_chantLast = (((Object)(object)val != (Object)null) ? ((Component)val).transform.position : Vector3.zero);
				_chantWalked = Vector3.zero;
				SpellCaster.BeginWindup(_plan, _runtime, in _channelTarget, _channelSeed, now, _channelGroup, followsCaster: true, Plugin.VoxelDensity.Value);
				SpellAudio.Chant(_plan.Element, _channelTarget.HasPoint ? _channelTarget.Point : _channelTarget.Caster, SpellScale.Power(_plan.TotalCost));
				_network.Announce(SpellMessageKind.WindupBegin, in _channelTarget, _channelSeed, _plan.Program);
				Plugin.Log.LogInfo((object)(string.Format("{0} {1:0.#}", SpellText.Get("cast.channel_start", "Chanting"), _plan.CastTime) + SpellText.Get("ui.seconds", "s")));
			}
		}

		private void BeginBeam(float now)
		{
			_beamSpent = 0f;
			_beamStart = now;
			_nextBeamAim = now + 0.1f;
			_beam = new BeamChannel(_plan, _runtime, _hits, in _channelTarget, _channelSeed, _network.OwnAuthority, now, Plugin.VoxelDensity.Value);
			bool flag = _network.Announce(SpellMessageKind.BeamBegin, in _channelTarget, _channelSeed, _plan.Program);
			Plugin.Log.LogInfo((object)(SpellText.Get("cast.beam_open", "Beam open") + ": " + $"{_plan.Emissions.Count} x {_plan.BeamArchetype.Damage:0.#}" + $" / {_plan.BeamArchetype.TickInterval:0.##}" + SpellText.Get("ui.seconds", "s") + ", " + string.Format("{0:0.#} {1}/", _plan.TotalCost, SpellText.Get("ui.mana", "mana")) + SpellText.Get("ui.per_second", "s") + " [" + (flag ? "announced" : ((_network.Role == SpellSessionRole.Offline) ? "offline" : "NOT ANNOUNCED")) + "]"));
			if (_beam.Figures < _plan.EmissionCount)
			{
				Plugin.Log.LogWarning((object)($"The runtime was full, so only {_beam.Figures} of {_plan.EmissionCount} " + "beam figures could be drawn."));
			}
		}

		private void DriveBeam(float now)
		{
			if (!ResolveTarget(out var target))
			{
				return;
			}
			_channelTarget = target;
			float num = _plan.ManaCost * Time.deltaTime;
			_castPool.CatchUp(now);
			ManaChambers.CoverShortfall(_castItem, _castPool, num, LocalUnit());
			StaffMana.MarkActive(_castItem, now);
			if (!_castPool.TryConsume(num))
			{
				EndBeam("out of mana");
				return;
			}
			_beamSpent += num;
			_beam.Aim(in target);
			_beam.Drive(now);
			if (now >= _nextBeamAim)
			{
				_nextBeamAim = now + 0.1f;
				_network.AnnounceBeamAim(in target, _channelSeed);
			}
		}

		private void AdvanceSegment()
		{
			if (_segments != null && _segments.Count > 1 && !_segments.Hands)
			{
				_segment = (_segment + 1) % _segments.Count;
				_plan = _segments.Plans[_segment];
				Plugin.Log.LogInfo((object)string.Format(CultureInfo.InvariantCulture, SpellText.Get("cast.next_segment", "Next: segment {0} of {1}"), _segment + 1, _segments.Count));
			}
		}

		internal void ResetSegments()
		{
			if (_segments != null && _segments.Count > 1 && !_segments.Hands && _segment != 0 && !_channelling && _beam == null)
			{
				_segment = 0;
				_plan = _segments.Plans[0];
				Plugin.Log.LogInfo((object)string.Format(CultureInfo.InvariantCulture, SpellText.Get("cast.next_segment", "Next: segment {0} of {1}"), 1, _segments.Count));
			}
		}

		private void EndBeam(string why)
		{
			_beam.Close();
			_beam = null;
			_nextCastTime = Time.time + _castStaff.Cooldown;
			_network.AnnounceBeamEnd();
			Plugin.Log.LogInfo((object)(SpellText.Get("cast.beam_close", "Beam closed") + " (" + why + "): " + string.Format("{0:0.#}{1}, ", Time.time - _beamStart, SpellText.Get("ui.seconds", "s")) + string.Format("{0:0.#} {1}, ", _beamSpent, SpellText.Get("ui.mana", "mana")) + string.Format("{0} {1:0}/{2:0}", SpellText.Get("cast.left", "left"), _castPool.Current, _castPool.Capacity)));
			_beamSpent = 0f;
			AdvanceSegment();
		}

		private static bool PlanStands(CastPlan plan)
		{
			return (plan.Flags & CastFlags.Stands) != 0;
		}

		private bool MovedOffAnchor()
		{
			//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)
			//IL_001d: 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_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: 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_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_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			Unit val = LocalUnit();
			if ((Object)(object)val == (Object)null)
			{
				return false;
			}
			Vector3 position = ((Component)val).transform.position;
			Vector3 val2 = position - _chantLast;
			val2.y = 0f;
			_chantLast = position;
			if (AskingToMove())
			{
				_chantWalked += val2;
			}
			return ((Vector3)(ref _chantWalked)).sqrMagnitude > 0.36f;
		}

		private static bool AskingToMove()
		{
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: 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_003a: Unknown result type (might be due to invalid IL or missing references)
			GameManager instance = StaticInstance<GameManager>.Instance;
			if ((Object)(object)instance == (Object)null || instance.InputActions == null || instance.HasLock((PlayerLocks)8))
			{
				return false;
			}
			OnFootActions onFoot = instance.InputActions.OnFoot;
			Vector2 val = ((OnFootActions)(ref onFoot)).Movement.ReadValue<Vector2>();
			return ((Vector2)(ref val)).sqrMagnitude > 0.01f;
		}

		private void ReportNothingToCast(float now)
		{
			InventoryItem item = HeldStaff.Item;
			if ((Object)(object)item != (Object)null && item.enchantments != null && item.enchantments.Count > 0)
			{
				Plugin.Log.LogInfo((object)SpellText.Get("cast.all_left_out", "None of the staff's spells can be cast."));
				Alert("UnholyRites/AllLeftOut", SpellTerms.AllLeftOut, now);
				return;
			}
			Plugin.Log.LogInfo((object)SpellText.Get("cast.empty", "The staff has no spells."));
			if ((Object)(object)item != (Object)null)
			{
				Alert("UnholyRites/StaffEmpty", SpellTerms.StaffEmpty, now);
			}
		}

		private void Alert(string term, SpellTerms.Entry fallback, float now)
		{
			if (!_alertShown.TryGetValue(term, out var value) || !(now - value < 2.5f))
			{
				_alertShown[term] = now;
				UIManager instance = StaticInstance<UIManager>.Instance;
				if ((Object)(object)instance != (Object)null)
				{
					instance.ShowSmallAlert(LocalizationManager.GetTermTranslation(term, true, 0, true, false, (GameObject)null, (string)null, true) ?? fallback.English, 2.5f, (UISounds)0);
				}
			}
		}

		private void CancelChannel()
		{
			_channelling = false;
			_runtime.RetireGroup(_channelGroup);
			_channelGroup = 0;
			_nextCastTime = 0f;
			_network.AnnounceCancel();
			Plugin.Log.LogInfo((object)SpellText.Get("cast.channel_cancel", "Chant interrupted."));
		}

		private void Resolve(float now)
		{
			//IL_017a: Unknown result type (might be due to invalid IL or missing references)
			if (!_plan.IsBeam)
			{
				ManaChambers.CoverShortfall(_castItem, _castPool, _plan.ManaCost, LocalUnit());
			}
			float num = OathOwes();
			if (!BloodPrice.CanPay(_plan, num, LocalUnit(), out var _))
			{
				if (_channelling)
				{
					CancelChannel();
				}
				RefuseBlood(now, num);
				return;
			}
			bool channelling = _channelling;
			_channelling = false;
			_runtime.RetireGroup(_channelGroup);
			_channelGroup = 0;
			if (channelling)
			{
				SpellCaster.Culminate(_plan, _runtime, in _channelTarget, _channelSeed, now, followsCaster: true, Plugin.VoxelDensity.Value);
			}
			if (_plan.IsBeam)
			{
				BeginBeam(now);
				return;
			}
			StaffMana.MarkActive(_castItem, now);
			ManaPool mana = _castPool;
			float num2 = 0f;
			if (num > 0f)
			{
				num2 = _castPool.Current;
				_castPool.TryConsume(num2);
				mana = null;
			}
			CastResult castResult = SpellCaster.Cast(_plan, _runtime, mana, _payloads, in _channelTarget, _channelSeed, now, Plugin.VoxelDensity.Value, _network.OwnAuthority);
			if (castResult != CastResult.Fired && num2 > 0f)
			{
				_castPool.Add(num2);
			}
			if (castResult == CastResult.Fired)
			{
				BloodPrice.Pay(_plan, num, LocalUnit());
				SpellAudio.Cast(_plan.Element, _channelTarget.Origin, SpellScale.Power(_plan.TotalCost));
				SpellSelfFlash.AfterCast(_plan, LocalUnit());
				_network.Announce(SpellMessageKind.Cast, in _channelTarget, _channelSeed, _plan.Program);
			}
			switch (castResult)
			{
			case CastResult.Fired:
				_nextCastTime = now + _castStaff.Cooldown;
				Plugin.Log.LogInfo((object)(string.Format("{0}: {1} ", SpellText.Get("cast.fired", "Cast"), _plan.EmissionCount) + SpellText.Get("ui.emissions", "effects") + ", " + string.Format("{0:0.#} {1}, ", _plan.ManaCost, SpellText.Get("ui.mana", "mana")) + string.Format("{0} {1:0}/{2:0}", SpellText.Get("cast.left", "left"), _castPool.Current, _castPool.Capacity) + ((_plan.BloodCost > 0f || num > 0f) ? string.Format(", {0} -{1:0.#}", SpellText.Get("ui.health", "health"), BloodPrice.HealthFor(_plan, num)) : string.Empty)));
				AdvanceSegment();
				break;
			case CastResult.NotEnoughMana:
				Plugin.Log.LogInfo((object)(SpellText.Get("cast.not_enough", "Not enough mana: need") + " " + string.Format("{0:0.#}, {1} {2:0.#}", _plan.ManaCost, SpellText.Get("cast.have", "have"), _castPool.Current)));
				Alert("UnholyRites/ManaShort", SpellTerms.ManaShort, now);
				break;
			case CastResult.NothingToCast:
				ReportNothingToCast(now);
				break;
			}
		}

		private bool ResolveTarget(out CastTarget target)
		{
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: 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_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: 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_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_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_0079: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_009c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c6: Unknown result type (might be due to invalid IL or missing references)
			target = default(CastTarget);
			Camera main = Camera.main;
			if ((Object)(object)main == (Object)null)
			{
				return false;
			}
			Transform transform = ((Component)main).transform;
			float3 val = (target.Direction = float3.op_Implicit(transform.forward));
			target.Origin = float3.op_Implicit(transform.position) + val * 1.2f;
			target.Caster = CastTrace.Below(transform.position, 3.5f, transform.position + Vector3.down * 1.6f);
			if (_plan == null || _plan.Targeting != TargetingKind.Point)
			{
				return true;
			}
			CastTrace.Forward(transform.position, transform.forward, 80f, LocalUnit(), out var point);
			target.Point = CastTrace.Below(point, 40f, point);
			target.HasPoint = true;
			return true;
		}

		internal void PlantStake(Vector3 point)
		{
			//IL_0038: 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_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_0042: 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_004e: 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_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Unknown result type (might be due to invalid IL or missing references)
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			//IL_0087: 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_0119: Unknown result type (might be due to invalid IL or missing references)
			SpellDefinition spellDefinition = _catalog.Get("stake");
			if (spellDefinition != null)
			{
				float time = Time.time;
				Camera main = Camera.main;
				float3 val = (((Object)(object)main != (Object)null) ? float3.op_Implicit(((Component)main).transform.position) : float3.op_Implicit(point));
				CastTarget target = new CastTarget
				{
					Origin = val,
					Direction = math.normalizesafe(float3.op_Implicit(point) - val, new float3(0f, 0f, 1f)),
					Point = float3.op_Implicit(point),
					HasPoint = true
				};
				CastPlan castPlan = SpellCompiler.Compile(new SpellDefinition[1] { spellDefinition }, _catalog);
				uint seed = (uint)(Environment.TickCount * -1640531535) ^ ++_castCounter;
				SpellCaster.Cast(castPlan, _runtime, null, _payloads, in target, seed, time, Plugin.VoxelDensity.Value, _network.OwnAuthority);
				_network.Announce(SpellMessageKind.Cast, in target, seed, castPlan.Program);
				SigilStake.Plant(float3.op_Implicit(point), time);
			}
		}

		internal bool ThrowVial(SealedVials.Kind vial)
		{
			//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00de: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f8: Unknown result type (might be due to invalid IL or missing references)
			//IL_0191: Unknown result type (might be due to invalid IL or missing references)
			Camera main = Camera.main;
			if (vial == null || (Object)(object)main == (Object)null)
			{
				return false;
			}
			SpellDefinition[] array = new SpellDefinition[vial.Program.Length];
			for (int i = 0; i < array.Length; i++)
			{
				array[i] = _catalog.Get(vial.Program[i]);
				if (array[i] == null)
				{
					Plugin.Log.LogError((object)("Sealed vial '" + vial.ItemKey + "' names no spell '" + vial.Program[i] + "'."));
					return false;
				}
			}
			float time = Time.time;
			Transform transform = ((Component)main).transform;
			float3 val = math.normalizesafe(float3.op_Implicit(transform.forward), new float3(0f, 0f, 1f));
			CastTarget target = new CastTarget
			{
				Origin = float3.op_Implicit(transform.position) + val * 1.2f,
				Direction = val
			};
			CastPlan castPlan = SpellCompiler.Compile(array, _catalog);
			uint seed = (uint)(Environment.TickCount * -1640531535) ^ ++_castCounter;
			CastResult castResult = SpellCaster.Cast(castPlan, _runtime, null, _payloads, in target, seed, time, Plugin.VoxelDensity.Value, _network.OwnAuthority);
			if (castResult != CastResult.Fired)
			{
				Plugin.Log.LogWarning((object)$"Sealed vial '{vial.ItemKey}' cast nothing ({castResult}); it was not spent.");
				return false;
			}
			SpellAudio.Cast(castPlan.Element, target.Origin, SpellScale.Power(castPlan.TotalCost));
			_network.Announce(SpellMessageKind.Cast, in target, seed, castPlan.Program);
			Plugin.Log.LogInfo((object)("Sealed vial thrown: " + string.Join(" > ", vial.Program) + "."));
			return true;
		}

		internal bool CastLastRites()
		{
			//IL_00ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0176: Unknown result type (might be due to invalid IL or missing references)
			Unit val = LocalUnit();
			bool flag = _segments != null && _segments.Hands;
			if ((Object)(object)val == (Object)null || !HeldStaff.Equipped || _plan == null || (!flag && (_plan.EmissionCount == 0 || _plan.IsBeam)))
			{
				return false;
			}
			if (_channelling)
			{
				CancelChannel();
			}
			CastPlan castPlan = _plan;
			if (_segments != null && _segments.Hands)
			{
				castPlan = null;
				for (int i = 0; i < _segments.Count; i++)
				{
					if (castPlan != null)
					{
						break;
					}
					CastPlan castPlan2 = _segments.Plans[i];
					if (castPlan2 != null && castPlan2.EmissionCount > 0 && !castPlan2.IsBeam)
					{
						castPlan = castPlan2;
					}
				}
				if (castPlan == null)
				{
					return false;
				}
			}
			CastPlan castPlan3 = Spared(castPlan);
			if (castPlan3 == null || !ResolveTarget(out var target))
			{
				return false;
			}
			target.Point = float3.op_Implicit(((Component)val).transform.position);
			target.HasPoint = true;
			float time = Time.time;
			uint seed = (uint)(Environment.TickCount * -1640531535) ^ ++_castCounter;
			if (SpellCaster.Cast(castPlan3, _runtime, null, _payloads, in target, seed, time, Plugin.VoxelDensity.Value, _network.OwnAuthority) != CastResult.Fired)
			{
				return false;
			}
			NoteCastFrom(seed, HeldStaff.Item);
			SpellAudio.Cast(castPlan3.Element, target.Origin, SpellScale.Power(castPlan3.TotalCost));
			_network.Announce(SpellMessageKind.Cast, in target, seed, castPlan3.Program);
			return true;
		}

		private CastPlan Spared(CastPlan plan)
		{
			List<SpellDefinition> list = new List<SpellDefinition>(plan.Program.Length + 1);
			for (int i = 0; i < plan.Program.Length; i++)
			{
				if (!_catalog.TryGet(plan.Program[i], out var definition) || definition == null)
				{
					return null;
				}
				list.Add(definition);
			}
			list.Add(_catalog.Get("spare"));
			CastPlan castPlan = SpellCompiler.Compile(list, _catalog);
			if (castPlan.EmissionCount <= 0)
			{
				return null;
			}
			return castPlan;
		}

		private float OathOwes()
		{
			if (_plan == null || _castPool == null || _plan.IsBeam || (_plan.Flags & CastFlags.BloodRite) == 0 || (_plan.Flags & CastFlags.Stands) == 0 || (Object)(object)LocalUnit() == (Object)null)
			{
				return 0f;
			}
			float num = _plan.ManaCost - _castPool.Current;
			if (!(num > 0f))
			{
				return 0f;
			}
			return num;
		}

		private bool RefuseBlood(float now, float owed)
		{
			if (BloodPrice.CanPay(_plan, owed, LocalUnit(), out var why))
			{
				return true;
			}
			_nextCastTime = now + 0.5f;
			Plugin.Log.LogInfo((object)(SpellText.Get(why, (why == "cast.blood_spent") ? "This floor's blood price is spent" : "Not enough health to pay the blood price") + ": " + $"{BloodPrice.HealthFor(_plan, owed):0.#}"));
			if (why == "cast.blood_spent")
			{
				Alert("UnholyRites/BloodSpent", SpellTerms.BloodSpent, now);
			}
			else
			{
				Alert("UnholyRites/BloodShort", SpellTerms.BloodShort, now);
			}
			return false;
		}

		private static Unit LocalUnit()
		{
			GameManager instance = StaticInstance<GameManager>.Instance;
			if (!((Object)(object)instance != (Object)null))
			{
				return null;
			}
			return instance.PlayerUnit;
		}

		public void Dispose()
		{
			SpellAmbience.StopAll();
			if (_beam != null)
			{
				EndBeam("session ended");
			}
			SpellHitResolver.KillCredited -= OnKillCredited;
			_network?.Dispose();
			_renderer.Dispose();
			_runtime.Dispose();
			_payloads.Clear();
			RecentCasts.Clear();
			Offerings.Clear();
			EndowedPuppets.Clear();
			PoisonFountain.Clear();
			SpellFire.Clear();
		}
	}
}
namespace UnholyRites.Staves
{
	internal static class HeldStaff
	{
		private static Weapon _weapon;

		private static bool _triggerHeld;

		private static bool _altPressed;

		private static int _altFrame = -10;

		private static bool _altNeedsRelease = true;

		internal static Weapon Weapon => _weapon;

		internal static bool TriggerHeld
		{
			get
			{
				if ((Object)(object)_weapon != (Object)null)
				{
					return _triggerHeld;
				}
				return false;
			}
		}

		internal static InventoryItem Item
		{
			get
			{
				if (!((Object)(object)_weapon != (Object)null))
				{
					return null;
				}
				return ((Holdable)_weapon).inventoryItem;
			}
		}

		internal static bool AltHeld
		{
			get
			{
				if ((Object)(object)_weapon == (Object)null || !_altPressed || _altNeedsRelease || Time.frameCount - _altFrame > 1 || StaffDefinitions.Of(Item).HandSlots <= 0)
				{
					return false;
				}
				InventoryItem item = Item;
				GameManager instance = StaticInstance<GameManager>.Instance;
				if ((Object)(object)item != (Object)null && !item.IsBroken && (Object)(object)instance != (Object)null)
				{
					return !instance.HasLock((PlayerLocks)4);
				}
				return false;
			}
		}

		internal static bool Equipped => (Object)(object)_weapon != (Object)null;

		internal static bool OnAimButton(bool pressed)
		{
			bool flag = _altPressed && Time.frameCount - _altFrame <= 1;
			_altPressed = pressed;
			_altFrame = Time.frameCount;
			if (!pressed)
			{
				_altNeedsRelease = false;
			}
			if (pressed && !flag && AltHeld && (Object)(object)_weapon.weaponDefinition != (Object)null)
			{
				return _weapon.weaponDefinition.interuptSprintOnTriggerPull;
			}
			return false;
		}

		internal static bool IsStaff(Weapon weapon)
		{
			if ((Object)(object)weapon != (Object)null && (Object)(object)((Holdable)weapon).inventoryItem != (Object)null)
			{
				return SpellContent.IsStaff(((Holdable)weapon).inventoryItem.itemDefinition);
			}
			return false;
		}

		internal static void OnTrigger(Weapon weapon, bool state)
		{
			if (!IsStaff(weapon))
			{
				_triggerHeld = false;
				return;
			}
			_weapon = weapon;
			_triggerHeld = state;
		}

		internal static void Refresh()
		{
			Weapon val = CurrentWeapon();
			if (!IsStaff(val))
			{
				_weapon = null;
				_triggerHeld = false;
			}
			else if (_weapon != val)
			{
				_weapon = val;
				_triggerHeld = false;
				_altNeedsRelease = true;
				Acquisition.OnStaffDrawn();
				Acquisition.OfferStarterSpell(((Holdable)val).inventoryItem);
			}
		}

		private static Weapon CurrentWeapon()
		{
			GameManager instance = StaticInstance<GameManager>.Instance;
			EquipmentManager val = (((Object)(object)instance != (Object)null) ? instance.EquipmentManager : null);
			if (!((Object)(object)val != (Object)null))
			{
				return null;
			}
			Holdable currentHoldable = val.CurrentHoldable;
			return (Weapon)(object)((currentHoldable is Weapon) ? currentHoldable : null);
		}
	}
	internal enum ChamberKind
	{
		None,
		Resting,
		Battery,
		Reload,
		Reaping
	}
	internal static class ManaChambers
	{
		internal const string RestingKey = "ryuka.sulfur.unholy_rites:chamber_rest";

		internal const string BatteryKey = "ryuka.sulfur.unholy_rites:chamber_cell";

		internal const string ReloadKey = "ryuka.sulfur.unholy_rites:chamber_breech";

		internal const string ReapingKey = "ryuka.sulfur.unholy_rites:chamber_reap";

		internal static readonly string[] Keys = new string[4] { "ryuka.sulfur.unholy_rites:chamber_rest", "ryuka.sulfur.unholy_rites:chamber_cell", "ryuka.sulfur.unholy_rites:chamber_breech", "ryuka.sulfur.unholy_rites:chamber_reap" };

		internal const float ReapShare = 0.5f;

		internal const float ReapCeiling = 0.5f;

		internal const float TrickleRate = 30f;

		internal const float RestingRate = 150f;

		internal const float RestingDelay = 2.5f;

		internal const float ManaPerCoin = 2f;

		private static readonly Dictionary<WorldResources, int> Returned = new Dictionary<WorldResources, int>();

		private static readonly Dictionary<WorldResources, float> Prices = new Dictionary<WorldResources, float>();

		internal static ChamberKind Of(InventoryItem staff)
		{
			if ((Object)(object)staff == (Object)null || staff.attachments == null)
			{
				return ChamberKind.None;
			}
			for (int i = 0; i < staff.attachments.Count; i++)
			{
				ChamberKind chamberKind = KindOf(staff.attachments[i]);
				if (chamberKind != ChamberKind.None)
				{
					return chamberKind;
				}
			}
			return ChamberKind.None;
		}

		internal static ChamberKind KindOf(ItemDefinition item)
		{
			return SpellContent.ItemKeyOf(item) switch
			{
				"ryuka.sulfur.unholy_rites:chamber_rest" => ChamberKind.Resting, 
				"ryuka.sulfur.unholy_rites:chamber_cell" => ChamberKind.Battery, 
				"ryuka.sulfur.unholy_rites:chamber_breech" => ChamberKind.Reload, 
				"ryuka.sulfur.unholy_rites:chamber_reap" => ChamberKind.Reaping, 
				_ => ChamberKind.None, 
			};
		}

		internal static float RateOf(ChamberKind kind)
		{
			return kind switch
			{
				ChamberKind.None => 30f, 
				ChamberKind.Resting => 150f, 
				_ => 0f, 
			};
		}

		internal static void CoverShortfall(InventoryItem staff, ManaPool pool, float needed, Unit caster)
		{
			if (pool == null || pool.Current >= needed || Of(staff) != ChamberKind.Battery || (Object)(object)caster == (Object)null || caster.Stats == null)
			{
				return;
			}
			float num = UnitPrice((WorldResources)6) * 2f;
			if (!(num <= 0f) && !(needed > pool.Capacity))
			{
				int num2 = Mathf.CeilToInt((needed - pool.Current) / num);
				int worldResource = caster.Stats.GetWorldResource((WorldResources)6);
				if (num2 > 0 && worldResource >= num2)
				{
					caster.Stats.ModifyWorldResource((WorldResources)6, -num2, (object)"Unholy Rites battery chamber");
					pool.Add((float)num2 * num);
				}
			}
		}

		internal static void OnAmmoTaken(WorldResources resource, int taken, float now)
		{
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			GameManager instance = StaticInstance<GameManager>.Instance;
			if (taken > 0 && !((Object)(object)instance == (Object)null) && !((Object)(object)instance.EquipmentManager == (Object)null))
			{
				Returned.TryGetValue(resource, out var value);
				int num = ((value < taken) ? value : taken);
				Returned[resource] = value - num;
				taken -= num;
				float num2 = (float)taken * UnitPrice(resource) * 2f;
				if (!(num2 <= 0f))
				{
					Dictionary<InventorySlot, InventoryItem> equippedItems = instance.EquipmentManager.EquippedItems;
					Credit(equippedItems, (InventorySlot)4, num2, now);
					Credit(equippedItems, (InventorySlot)5, num2, now);
				}
			}
		}

		private static bool AnyBreechEquipped()
		{
			GameManager instance = StaticInstance<GameManager>.Instance;
			Dictionary<InventorySlot, InventoryItem> equipped = (((Object)(object)instance != (Object)null && (Object)(object)instance.EquipmentManager != (Object)null) ? instance.EquipmentManager.EquippedItems : null);
			if (!IsBreech(equipped, (InventorySlot)4))
			{
				return IsBreech(equipped, (InventorySlot)5);
			}
			return true;
		}

		private static bool IsBreech(Dictionary<InventorySlot, InventoryItem> equipped, InventorySlot slot)
		{
			//IL_0004: Unknown result type (might be due to invalid IL or missing references)
			if (equipped != null && equipped.TryGetValue(slot, out var value) && (Object)(object)value != (Object)null && SpellContent.IsStaff(value.itemDefinition))
			{
				return Of(value) == ChamberKind.Reload;
			}
			return false;
		}

		private static void Credit(Dictionary<InventorySlot, InventoryItem> equipped, InventorySlot slot, float mana, float now)
		{
			//IL_0004: Unknown result type (might be due to invalid IL or missing references)
			if (equipped != null && equipped.TryGetValue(slot, out var value) && (Object)(object)value != (Object)null && SpellContent.IsStaff(value.itemDefinition) && Of(value) == ChamberKind.Reload)
			{
				StaffMana.For(value, now).Add(mana);
			}
		}

		internal static void Reap(InventoryItem staff, float maxHealth, float now)
		{
			if (!((Object)(object)staff == (Object)null) && !(maxHealth <= 0f) && !float.IsNaN(maxHealth) && Of(staff) == ChamberKind.Reaping)
			{
				ManaPool manaPool = StaffMana.For(staff, now);
				float num = Mathf.Min(maxHealth * 0.5f, manaPool.Capacity * 0.5f);
				manaPool.Add(num);
				Plugin.Log.LogInfo((object)$"Reaping chamber: a kill gave back {num:0.#} mana ({manaPool.Current:0}/{manaPool.Capacity:0}).");
			}
		}

		internal static void OnAmmoReturned(WorldResources resource, int returned)
		{
			//IL_0011: 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)
			if (returned > 0 && AnyBreechEquipped())
			{
				Returned.TryGetValue(resource, out var value);
				Returned[resource] = value + returned;
			}
		}

		internal static float UnitPrice(WorldResources resource)
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f8: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_009a: Unknown result type (might be due to invalid IL or missing references)
			//IL_009f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			if (Prices.TryGetValue(resource, out var value))
			{
				return value;
			}
			float num = 0f;
			AsyncAssetLoading instance = StaticInstance<AsyncAssetLoading>.Instance;
			List<ItemDefinition> list = (((Object)(object)instance != (Object)null && (Object)(object)instance.itemDatabase != (Object)null) ? instance.itemDatabase.GetRawList() : null);
			if (list == null)
			{
				return 0f;
			}
			for (int i = 0; i < list.Count; i++)
			{
				ItemDefinition val = list[i];
				if ((Object)(object)val == (Object)null || val.resourceOnConsume == null || val.resourceOnConsume.Count == 0 || val.basePrice <= 0)
				{
					continue;
				}
				WorldResourceModifierContainer val2 = val.resourceOnConsume[0];
				if (val2.resource == resource && val2.amount > 0)
				{
					float num2 = (float)val.basePrice / (float)val2.amount;
					if (num <= 0f || num2 < num)
					{
						num = num2;
					}
				}
			}
			Prices[resource] = num;
			Plugin.Log.LogInfo((object)$"Chamber price of {resource}: {num:0.##} a unit, {num * 2f:0.##} mana.");
			return num;
		}
	}
	internal static class MartyrBeads
	{
		internal const string Key = "ryuka.sulfur.unholy_rites:martyr_beads";

		internal const float UntouchableSeconds = 4f;

		private static readonly InventorySlot[] PassiveSlots;

		private static InventoryItem Worn()
		{
			GameManager instance = StaticInstance<GameManager>.Instance;
			Dictionary<InventorySlot, InventoryItem> dictionary = (((Object)(object)instance != (Object)null && (Object)(object)instance.EquipmentManager != (Object)null) ? instance.EquipmentManager.EquippedItems : null);
			if (dictionary == null)
			{
				return null;
			}
			for (int i = 0; i < PassiveSlots.Length; i++)
			{
				if (dictionary.TryGetValue(PassiveSlots[i], out var value) && (Object)(object)value != (Object)null && SpellContent.ItemKeyOf(value.itemDefinition) == "ryuka.sulfur.unholy_rites:martyr_beads")
				{
					return value;
				}
			}
			return null;
		}

		internal static bool TryRescue(Unit player)
		{
			if ((Object)(object)player == (Object)null || player.Stats == null)
			{
				return false;
			}
			float num = default(float);
			if (player.Stats.TryGetAttribute((EntityAttributes)109, ref num) && num > 0f)
			{
				return false;
			}
			InventoryItem val = Worn();
			if ((Object)(object)val == (Object)null)
			{
				return false;
			}
			player.Stats.SetStatus((EntityAttributes)92, 1f, false);
			player.Stats.SetStatus((EntityAttributes)19, 0f, false);
			player.Stats.SetStatus((EntityAttributes)28, 0f, false);
			player.Stats.SetStatus((EntityAttributes)102, 0f, false);
			player.SetInvulnerableForDuration(4f);
			val.GetConsumedByExternalFactor(((Component)player).gameObject);
			bool flag = false;
			try
			{
				flag = Plugin.Session != null && Plugin.Session.CastLastRites();
			}
			catch (Exception ex)
			{
				Plugin.Log.LogError((object)("Martyr's beads: the last rite failed: " + ex.Message));
			}
			Plugin.Log.LogInfo((object)("Martyr's beads: a fatal blow left one health; the last rite " + (flag ? "was cast" : "was not cast") + "."));
			return true;
		}

		static MartyrBeads()
		{
			InventorySlot[] array = new InventorySlot[4];
			RuntimeHelpers.InitializeArray(array, (RuntimeFieldHandle)/*OpCode not supported: LdMemberToken*/);
			PassiveSlots = (InventorySlot[])(object)array;
		}
	}
	internal static class Oaths
	{
		internal const string CatalystKey = "ryuka.sulfur.unholy_rites:oath_catalyst";

		internal const string VigilKey = "ryuka.sulfur.unholy_rites:oath_vigil";

		internal const string NailKey = "ryuka.sulfur.unholy_rites:oath_nail";

		internal const string SutureKey = "ryuka.sulfur.unholy_rites:oath_suture";

		internal const string BloodKey = "ryuka.sulfur.unholy_rites:oath_blood";

		internal static readonly string[] Keys = new string[5] { "ryuka.sulfur.unholy_rites:oath_catalyst", "ryuka.sulfur.unholy_rites:oath_vigil", "ryuka.sulfur.unholy_rites:oath_nail", "ryuka.sulfur.unholy_rites:oath_suture", "ryuka.sulfur.unholy_rites:oath_blood" };

		private static readonly InventorySlot[] PassiveSlots;

		internal static string Active()
		{
			GameManager instance = StaticInstance<GameManager>.Instance;
			Dictionary<InventorySlot, InventoryItem> dictionary = (((Object)(object)instance != (Object)null && (Object)(object)instance.EquipmentManager != (Object)null) ? instance.EquipmentManager.EquippedItems : null);
			if (dictionary == null)
			{
				return null;
			}
			for (int i = 0; i < PassiveSlots.Length; i++)
			{
				if (dictionary.TryGetValue(PassiveSlots[i], out var value) && !((Object)(object)value == (Object)null) && !value.IsBroken)
				{
					string text = SpellContent.ItemKeyOf(value.itemDefinition);
					if (text != null && Array.IndexOf(Keys, text) >= 0)
					{
						return text;
					}
				}
			}
			return null;
		}

		internal static string RowOf(string oathKey)
		{
			return oathKey switch
			{
				"ryuka.sulfur.unholy_rites:oath_catalyst" => "catalyst", 
				"ryuka.sulfur.unholy_rites:oath_vigil" => "vigil", 
				"ryuka.sulfur.unholy_rites:oath_suture" => "stitch", 
				"ryuka.sulfur.unholy_rites:oath_blood" => "bloodrite", 
				"ryuka.sulfur.unholy_rites:oath_nail" => "nail", 
				_ => null, 
			};
		}

		static Oaths()
		{
			InventorySlot[] array = new InventorySlot[4];
			RuntimeHelpers.InitializeArray(array, (RuntimeFieldHandle)/*OpCode not supported: LdMemberToken*/);
			PassiveSlots = (InventorySlot[])(object)array;
		}
	}
	internal static class PenitentRobe
	{
		internal const string Key = "ryuka.sulfur.unholy_rites:penitent_robe";

		internal const float ManaPerHealth = 2f;

		internal const float BankSeconds = 4f;

		internal const float LevelCeiling = 3f;

		private static float _allowance;

		private static float _allowanceAt;

		private static float _givenThisLevel;

		private static long _level = long.MinValue;

		private static int _reported;

		internal static bool Worn()
		{
			GameManager instance = StaticInstance<GameManager>.Instance;
			if ((Object)(object)instance == (Object)null || (Object)(object)instance.EquipmentManager == (Object)null || !instance.EquipmentManager.EquippedItems.TryGetValue((InventorySlot)1, out var value) || (Object)(object)value == (Object)null || value.IsBroken)
			{
				return false;
			}
			return SpellContent.ItemKeyOf(value.itemDefinition) == "ryuka.sulfur.unholy_rites:penitent_robe";
		}

		internal static void OnStruck(Unit player, float taken, in DamageSourceData source, float now)
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Invalid comparison between Unknown and I4
			if (taken <= 0f || float.IsNaN(taken) || !Worn() || (int)source.sourceEffect != 0 || (int)source.damageType == 14)
			{
				return;
			}
			Unit sourceUnit = source.sourceUnit;
			if ((Object)(object)sourceUnit != (Object)null && ((Object)(object)sourceUnit == (Object)(object)player || sourceUnit.isPlayer || !sourceUnit.IsHostileTo((FactionIds)16)))
			{
				return;
			}
			InventoryItem item = HeldStaff.Item;
			if ((Object)(object)item == (Object)null)
			{
				return;
			}
			long num = CurrentLevel();
			if (num != _level)
			{
				_level = num;
				_givenThisLevel = 0f;
			}
			_allowance = Mathf.Min(_allowance + (now - _allowanceAt) * 30f, 120f);
			_allowanceAt = now;
			ManaPool manaPool = StaffMana.For(item, now);
			float num2 = manaPool.Capacity * 3f - _givenThisLevel;
			float num3 = Mathf.Min(taken * 2f, Mathf.Min(_allowance, num2));
			if (!(num3 <= 0f))
			{
				_allowance -= num3;
				_givenThisLevel += num3;
				manaPool.Add(num3);
				if (_reported < 3)
				{
					_reported++;
					Plugin.Log.LogInfo((object)$"Penitent robe: a blow took {taken:0.#} health and gave {num3:0.#} mana ({manaPool.Current:0}/{manaPool.Capacity:0}).");
				}
			}
		}

		private static long CurrentLevel()
		{
			GameManager instance = StaticInstance<GameManager>.Instance;
			if (!((Object)(object)instance != (Object)null))
			{
				return 0L;
			}
			return instance.currentSeed ^ ((long)instance.currentLevelIndex << 48);
		}
	}
	[HarmonyPatch(typeof(ItemDescription), "Setup", new Type[] { typeof(InventoryItem) })]
	internal static class ScrollPreviewPatch
	{
		private static MethodInfo _addText;

		private static bool _resolved;

		private static readonly InventorySlot[] WeaponSlots = (InventorySlot[])(object)new InventorySlot[2]
		{
			(InventorySlot)4,
			(InventorySlot)5
		};

		private static void Postfix(ItemDescription __instance, InventoryItem inventoryItem)
		{
			try
			{
				if ((Object)(object)__instance == (Object)null || !__instance.isPrimary || (Object)(object)inventoryItem == (Object)null)
				{
					return;
				}
				SpellDefinition spellDefinition = SpellOf(inventoryItem.itemDefinition);
				InventoryItem val = ((spellDefinition != null) ? CarriedStaff() : null);
				if ((Object)(object)val == (Object)null)
				{
					return;
				}
				string text = Preview(val, spellDefinition);
				if (text != null)
				{
					if (!_resolved)
					{
						_resolved = true;
						_addText = AccessTools.Method(typeof(ItemDescription), "AddDescriptionText", new Type[2]
						{
							typeof(string),
							typeof(int).MakeByRefType()
						}, (Type[])null);
					}
					_addText?.Invoke(__instance, new object[2] { text, 999 });
				}
			}
			catch (Exception ex)
			{
				Plugin.Log.LogError((object)("A scroll's preview was not shown: " + ex.Message));
			}
		}

		private static string Preview(InventoryItem staff, SpellDefinition spell)
		{
			string localizedDisplayName = staff.itemDefinition.LocalizedDisplayName;
			if (staff.enchantments.Count >= StaffDefinitions.Of(staff).Slots)
			{
				return "<color=#A0A0A0>" + string.Format(SpellText.Get("preview.full", "{0} has no room for another spell"), localizedDisplayName) + "</color>";
			}
			SpellSegments spellSegments = StaffProgram.For(staff);
			SpellSegments spellSegments2 = StaffProgram.CompileWith(staff, spell);
			if (spellSegments == null || spellSegments2 == null)
			{
				return null;
			}
			float num = StaffProgram.TotalCost(spellSegments);
			float num2 = StaffProgram.TotalCost(spellSegments2);
			float num3 = StaffProgram.ChantOf(spellSegments);
			float num4 = StaffProgram.ChantOf(spellSegments2);
			bool flag = Math.Abs(num4 - num3) > 0.05f;
			List<string> list = new List<string>(2);
			if (Math.Abs(num2 - num) > 0.05f || flag)
			{
				string text = string.Format(SpellText.Get("preview.cost", "On {0}: mana {1} → {2}"), localizedDisplayName, Number(num), Number(num2));
				if (flag)
				{
					text += string.Format(SpellText.Get("preview.chant", ", chant {0}s → {1}s"), Number(num3), Number(num4));
				}
				list.Add(text);
			}
			if (StaffProgram.SameEffect(spellSegments, spellSegments2, out var chantDiffers))
			{
				bool flag2 = spell.Category == SpellCategory.Payload || spell.Category == SpellCategory.Segment;
				list.Add(flag2 ? string.Format(SpellText.Get("preview.waits", "On {0} nothing follows it yet: inscribe it, then the spells it should carry"), localizedDisplayName) : string.Format(SpellText.Get("preview.idle", "Inscribed there it would do nothing: {0}"), StaffProgram.IdleReason(spell, chantDiffers)));
			}
			if (list.Count != 0)
			{
				return "<color=#A0A0A0>" + string.Join("<br>", list) + "</color>";
			}
			return null;
		}

		private static string Number(float value)
		{
			return value.ToString("0.#", CultureInfo.InvariantCulture);
		}

		private static SpellDefinition SpellOf(ItemDefinition item)
		{
			string text = (((Object)(object)item != (Object)null) ? SpellContent.ItemKeyOf(item) : null);
			int num = text?.IndexOf(":scroll_", StringComparison.Ordinal) ?? (-1);
			if (num < 0)
			{
				return null;
			}
			if (!ContentBootstrap.Catalog.TryGet(new SpellKey(text.Substring(num + ":scroll_".Length)), out var definition))
			{
				return null;
			}
			return definition;
		}

		private static InventoryItem CarriedStaff()
		{
			InventoryItem item = HeldStaff.Item;
			if ((Object)(object)item != (Object)null)
			{
				return item;
			}
			GameManager instance = StaticInstance<GameManager>.Instance;
			Dictionary<InventorySlot, InventoryItem> dictionary = (((Object)(object)instance != (Object)null && (Object)(object)instance.EquipmentManager != (Object)null) ? instance.EquipmentManager.EquippedItems : null);
			if (dictionary == null)
			{
				return null;
			}
			for (int i = 0; i < WeaponSlots.Length; i++)
			{
				if (dictionary.TryGetValue(WeaponSlots[i], out var value) && (Object)(object)value != (Object)null && SpellContent.IsStaff(value.itemDefinition))
				{
					return value;
				}
			}
			return null;
		}
	}
	internal static class SealedVials
	{
		internal sealed class Kind
		{
			internal string ItemKey;

			internal string Spell;

			internal string[] Program;
		}

		internal static readonly Kind[] All = new Kind[3]
		{
			new Kind
			{
				ItemKey = "ryuka.sulfur.unholy_rites:vial_sigil",
				Spell = "sigil",
				Program = new string[5] { "vial", "onhit", "sigil", "else", "sigil" }
			},
			new Kind
			{
				ItemKey = "ryuka.sulfur.unholy_rites:vial_venom",
				Spell = "venom",
				Program = new string[1] { "venom" }
			},
			new Kind
			{
				ItemKey = "ryuka.sulfur.unholy_rites:vial_frostbolt",
				Spell = "frostbolt",
				Program = new string[5] { "vial", "onhit", "frostbolt", "else", "frostbolt" }
			}
		};

		internal const int PerScroll = 2;

		private static readonly InventorySlot[] GadgetSlots;

		internal static Kind Find(string itemKey)
		{
			for (int i = 0; i < All.Length; i++)
			{
				if (All[i].ItemKey == itemKey)
				{
					return All[i];
				}
			}
			return null;
		}

		internal static Kind Usable()
		{
			GameManager instance = StaticInstance<GameManager>.Instance;
			Dictionary<InventorySlot, InventoryItem> dictionary = (((Object)(object)instance != (Object)null && (Object)(object)instance.EquipmentManager != (Object)null) ? instance.EquipmentManager.EquippedItems : null);
			if (dictionary == null)
			{
				return null;
			}
			for (int i = 0; i < GadgetSlots.Length; i++)
			{
				if (dictionary.TryGetValue(GadgetSlots[i], out var value) && !((Object)(object)value == (Object)null))
				{
					Kind kind = Find(SpellContent.ItemKeyOf(value.itemDefinition));
					if (kind != null)
					{
						return kind;
					}
				}
			}
			return null;
		}

		static SealedVials()
		{
			InventorySlot[] array = new InventorySlot[3];
			RuntimeHelpers.InitializeArray(array, (RuntimeFieldHandle)/*OpCode not supported: LdMemberToken*/);
			GadgetSlots = (InventorySlot[])(object)array;
		}
	}
	internal static class StaffAssets
	{
		internal const string FileName = "unholyrites-staff.bundle";

		private const string MeshName = "UnholyRites_Staff_Mesh";

		private const string PaletteName = "UnholyRites_Staff_Palette";

		private static AssetBundle _bundle;

		private static bool _attempted;

		internal static Mesh Mesh { get; private set; }

		internal static Texture2D Palette { get; private set; }

		internal static string FailureReason { get; private set; }

		internal static bool TryLoad()
		{
			//IL_0173: Unknown result type (might be due to invalid IL or missing references)
			//IL_0178: Unknown result type (might be due to invalid IL or missing references)
			//IL_017b: Unknown result type (might be due to invalid IL or missing references)
			//IL_018f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0194: Unknown result type (might be due to invalid IL or missing references)
			//IL_0197: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bd: 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)
			if (_attempted)
			{
				return (Object)(object)Mesh != (Object)null;
			}
			_attempted = true;
			string text = ResolvePath();
			if (text == null)
			{
				FailureReason = "'unholyrites-staff.bundle' was not found next to the plugin. Build it from UnityProject (Unholy Rites ▸ Build staff AssetBundle) and copy it into the plugin folder.";
				return false;
			}
			try
			{
				_bundle = AssetBundle.LoadFromFile(text);
			}
			catch (Exception ex)
			{
				FailureReason = "'" + text + "' could not be opened: " + ex.Message;
				return false;
			}
			if ((Object)(object)_bundle == (Object)null)
			{
				FailureReason = "'" + text + "' was found but did not load. It is most likely built with a different Unity version than the game runs.";
				return false;
			}
			Mesh = _bundle.LoadAsset<Mesh>("UnholyRites_Staff_Mesh");
			Palette = _bundle.LoadAsset<Texture2D>("UnholyRites_Staff_Palette");
			if ((Object)(object)Mesh == (Object)null)
			{
				FailureReason = "'" + text + "' loaded but holds no mesh named 'UnholyRites_Staff_Mesh'. Assets found: " + string.Join(", ", _bundle.GetAllAssetNames() ?? new string[0]) + ".";
				return false;
			}
			if ((Object)(object)Palette == (Object)null)
			{
				Plugin.Log.LogWarning((object)"The staff bundle holds no palette named 'UnholyRites_Staff_Palette', so the staff keeps the colours of the material it borrowed.");
			}
			ManualLogSource log = Plugin.Log;
			string[] obj = new string[9]
			{
				"Staff bundle loaded from '",
				text,
				"': mesh '",
				((Object)Mesh).name,
				"' ",
				null,
				null,
				null,
				null
			};
			object arg = Mesh.vertexCount;
			Bounds bounds = Mesh.bounds;
			object arg2 = ((Bounds)(ref bounds)).size.x;
			bounds = Mesh.bounds;
			obj[5] = $"({arg} verts, {arg2:0.##}x{((Bounds)(ref bounds)).size.y:0.##}x";
			bounds = Mesh.bounds;
			obj[6] = $"{((Bounds)(ref bounds)).size.z:0.##} m), palette ";
			obj[7] = (((Object)(object)Palette != (Object)null) ? $"{((Texture)Palette).width}x{((Texture)Palette).height}" : "none");
			obj[8] = ".";
			log.LogInfo((object)string.Concat(obj));
			return true;
		}

		private static string ResolvePath()
		{
			string directoryName;
			try
			{
				directoryName = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
			}
			catch (Exception ex)
			{
				FailureReason = "The plugin folder could not be determined: " + ex.Message;
				return null;
			}
			if (string.IsNullOrEmpty(directoryName))
			{
				return null;
			}
			string text = Path.Combine(directoryName, "unholyrites-staff.bundle");
			if (!File.Exists(text))
			{
				return null;
			}
			return text;
		}
	}
	internal sealed class StaffDefinition
	{
		internal string ItemKey;

		internal ItemId Body;

		internal int BasePrice;

		internal ItemQuality Quality;

		internal bool ClearBodyAttributes;

		internal Vector3 ModelOffset;

		internal int Slots;

		internal float ManaCapacity;

		internal float Cooldown;

		internal float ChantMoveFactor;

		internal string LockedRow;

		internal int HandSlots;

		internal bool NoAim;

		internal string MountBone;
	}
	internal static class StaffDefinitions
	{
		internal static readonly StaffDefinition Ember = new StaffDefinition
		{
			ItemKey = "ryuka.sulfur.unholy_rites:staff",
			Body = ItemIds.Weapon_FlickerZip,
			BasePrice = 2000,
			Quality = (ItemQuality)1,
			Slots = 5,
			ManaCapacity = 1200f,
			Cooldown = 0.35f,
			ChantMoveFactor = 0.45f
		};

		internal static readonly StaffDefinition LongStaff = new StaffDefinition
		{
			ItemKey = "ryuka.sulfur.unholy_rites:longstaff",
			Body = ItemIds.Weapon_Longboy,
			BasePrice = 3000,
			Quality = (ItemQuality)2,
			ClearBodyAttributes = true,
			ModelOffset = new Vector3(0f, 0f, -0.15f),
			Slots = 8,
			ManaCapacity = 1800f,
			Cooldown = 1f,
			ChantMoveFactor = 1f
		};

		internal static readonly StaffDefinition Gravekeeper = new StaffDefinition
		{
			ItemKey = "ryuka.sulfur.unholy_rites:gravekeeper",
			Body = ItemIds.Weapon_Gravekeeper,
			BasePrice = 3000,
			Quality = (ItemQuality)2,
			ClearBodyAttributes = true,
			Slots = 5,
			ManaCapacity = 1500f,
			Cooldown = 0.6f,
			ChantMoveFactor = 0.45f,
			LockedRow = "raise"
		};

		internal static readonly StaffDefinition Twin = new StaffDefinition
		{
			ItemKey = "ryuka.sulfur.unholy_rites:twinstaff",
			Body = ItemIds.Weapon_StarAndWitness,
			BasePrice = 3000,
			Quality = (ItemQuality)2,
			ClearBodyAttributes = true,
			Slots = 8,
			HandSlots = 4,
			NoAim = true,
			MountBone = "SGripBone",
			ManaCapacity = 1500f,
			Cooldown = 0.5f,
			ChantMoveFactor = 0.45f
		};

		internal static readonly StaffDefinition[] All = new StaffDefinition[4] { Ember, LongStaff, Gravekeeper, Twin };

		internal static StaffDefinition Bench => Ember;

		internal static StaffDefinition Find(ItemDefinition definition)
		{
			string text = SpellContent.ItemKeyOf(definition);
			if (text == null)
			{
				return null;
			}
			return FindByKey(text);
		}

		internal static StaffDefinition FindByKey(string key)
		{
			for (int i = 0; i < All.Length; i++)
			{
				if (All[i].ItemKey == key)
				{
					return All[i];
				}
			}
			return null;
		}

		internal static StaffDefinition Of(InventoryItem staff)
		{
			return (((Object)(object)staff != (Object)null) ? Find(staff.itemDefinition) : null) ?? Bench;
		}
	}
	internal static class StaffDropCaret
	{
		private const int Size = 11;

		private static RectTransform _caret;

		private static Sprite _sprite;

		internal static void ShowAt(RectTransform anyRow, Vector3 worldPoint)
		{
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			RectTransform val = (RectTransform)(((Object)(object)anyRow != (Object)null) ? /*isinst with value type is only supported in some contexts*/: null);
			if ((Object)(object)val == (Object)null)
			{
				Hide();
				return;
			}
			Ensure(val);
			if ((Object)(object)((Transform)_caret).parent != (Object)(object)val)
			{
				((Transform)_caret).SetParent((Transform)(object)val, false);
			}
			((Transform)_caret).position = worldPoint;
			((Component)_caret).gameObject.SetActive(true);
			((Transform)_caret).SetAsLastSibling();
		}

		internal static void Hide()
		{
			if ((Object)(object)_caret != (Object)null)
			{
				((Component)_caret).gameObject.SetActive(false);
			}
		}

		private static void Ensure(RectTransform parent)
		{
			//IL_0026: 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_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Expected O, but got Unknown
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bd: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)_caret != (Object)null))
			{
				GameObject val = new GameObject("UnholyRites_DropCaret", new Type[1] { typeof(RectTransform) });
				_caret = (RectTransform)val.transform;
				((Transform)_caret).SetParent((Transform)(object)parent, false);
				_caret.anchorMin = Vector2.zero;
				_caret.anchorMax = Vector2.zero;
				_caret.pivot = new Vector2(0f, 0.5f);
				_caret.sizeDelta = new Vector2(11f, 11f);
				Image obj = val.AddComponent<Image>();
				obj.sprite = Triangle();
				((Graphic)obj).color = new Color(1f, 0.92f, 0.6f, 0.95f);
				((Graphic)obj).raycastTarget = false;
				val.AddComponent<LayoutElement>().ignoreLayout = true;
			}
		}

		private static Sprite Triangle()
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: 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)
			//IL_0035: Expected O, but got Unknown
			//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)_sprite != (Object)null)
			{
				return _sprite;
			}
			Texture2D val = new Texture2D(11, 11, (TextureFormat)4, false)
			{
				filterMode = (FilterMode)1,
				wrapMode = (TextureWrapMode)1,
				hideFlags = (HideFlags)61
			};
			for (int i = 0; i < 11; i++)
			{
				float num = (1f - Mathf.Abs((float)i - 5f) / 5f) * 10f;
				for (int j = 0; j < 11; j++)
				{
					float num2 = Mathf.Clamp01(num - (float)j + 1f);
					val.SetPixel(j, i, new Color(1f, 1f, 1f, num2));
				}
			}
			val.Apply();
			_sprite = Sprite.Create(val, new Rect(0f, 0f, 11f, 11f), new Vector2(0f, 0.5f));
			((Object)_sprite).hideFlags = (HideFlags)61;
			return _sprite;
		}
	}
	internal static class StaffMana
	{
		private static readonly ConditionalWeakTable<InventoryItem, ManaPool> Pools = new ConditionalWeakTable<InventoryItem, ManaPool>();

		private static readonly ManaPool Bench = new ManaPool(StaffDefinitions.Bench.ManaCapacity, 150f);

		internal static ManaPool For(InventoryItem staff, float now)
		{
			ManaPool manaPool = (((Object)(object)staff != (Object)null) ? Pools.GetValue(staff, NewPool) : Bench);
			if ((Object)(object)staff != (Object)null)
			{
				manaPool.CatchUp(now);
				manaPool.Configure(StaffDefinitions.Of(staff).ManaCapacity, ManaChambers.RateOf(ManaChambers.Of(staff)));
				return manaPool;
			}
			manaPool.CatchUp(now);
			return manaPool;
		}

		internal static void MarkActive(InventoryItem staff, float now)
		{
			if (!((Object)(object)staff == (Object)null) && ManaChambers.Of(staff) == ChamberKind.Resting)
			{
				For(staff, now).Hush(now + 2.5f);
			}
		}

		private static ManaPool NewPool(InventoryItem staff)
		{
			return new ManaPool(StaffDefinitions.Of(staff).ManaCapacity, ManaChambers.RateOf(ManaChambers.Of(staff)));
		}
	}
	internal static class StaffPanel
	{
		private static FieldInfo _rowsField;

		private static bool _resolved;

		private static bool _loggedAttach;

		private static MethodInfo _clearMethod;

		private static bool _clearResolved;

		private static MethodInfo _addText;

		private static bool _addTextResolved;

		private static readonly List<RectTransform> Movable = new List<RectTransform>();

		internal static void AttachTo(ItemDescription description, InventoryItem item)
		{
			//IL_0125: Unknown result type (might be due to invalid IL or missing references)
			//IL_012f: Expected O, but got Unknown
			if ((Object)(object)description == (Object)null || (Object)(object)item == (Object)null || !SpellContent.IsStaff(item.itemDefinition))
			{
				return;
			}
			List<ItemDescriptionText> list = Rows(description);
			if (list == null)
			{
				return;
			}
			int count = item.enchantments.Count;
			int num = 0;
			Movable.Clear();
			HashSet<int> hashSet = new HashSet<int>();
			foreach (StaffProgram.IdleRow item2 in StaffProgram.IdleRows(item))
			{
				hashSet.Add(item2.Index);
			}
			for (int i = 0; i < list.Count; i++)
			{
				ItemDescriptionText val = list[i];
				if (!((Object)(object)val == (Object)null))
				{
					if (i < count && hashSet.Contains(i) && (Object)(object)val.textComp != (Object)null)
					{
						((TMP_Text)val.textComp).text = "<color=#7A7A7A>" + ((TMP_Text)val.textComp).text + "</color>";
					}
					(((Component)val).GetComponent<StaffRowDrag>() ?? ((Component)val).gameObject.AddComponent<StaffRowDrag>()).Bind(item, i, i < count);
					num++;
					if (i < count)
					{
						Movable.Add((RectTransform)((Component)val).transform);
					}
				}
			}
			if (!_loggedAttach)
			{
				_loggedAttach = true;
				Plugin.Log.LogInfo((object)($"Staff panel: {list.Count} rows found, {count} inscribed, {num} bound. " + "Hold Ctrl and drag a row to rearrange."));
			}
			AddSummary(description, item, list);
		}

		private static void AddSummary(ItemDescription description, InventoryItem item, List<ItemDescriptionText> rows)
		{
			if (item.enchantments.Count == 0)
			{
				return;
			}
			if (!_addTextResolved)
			{
				_addTextResolved = true;
				_addText = AccessTools.Method(typeof(ItemDescription), "AddDescriptionText", new Type[2]
				{
					typeof(string),
					typeof(int).MakeByRefType()
				}, (Type[])null);
				if (_addText == null)
				{
					Plugin.Log.LogWarning((object)"The description's text row is not where it was; a staff's summary will not show.");
				}
			}
			SpellSegments spellSegments = StaffProgram.For(item);
			if (_addText == null || spellSegments == null || string.IsNullOrEmpty(spellSegments.Summary))
			{
				return;
			}
			int num = -1;
			for (int i = 0; i < rows.Count; i++)
			{
				if ((Object)(object)rows[i] != (Object)null)
				{
					num = Math.Max(num, ((Component)rows[i]).transform.GetSiblingIndex());
				}
			}
			if (num >= 0)
			{
				string text = SpellText.Get("ui.staff_casts", "This staff casts:") + "<br>" + spellSegments.Summary.Replace("\r\n", "\n").Replace("\n", "<br>");
				List<StaffProgram.IdleRow> list = StaffProgram.IdleRows(item);
				for (int j = 0; j < list.Count; j++)
				{
					StaffProgram.IdleRow idleRow = list[j];
					string arg = SpellText.Spell(idleRow.Spell, idleRow.Name);
					text = text + "<br><color=#A0A0A0>" + string.Format(SpellText.Get("idle.row", "{0} does nothing here: {1}"), arg, idleRow.Reason) + "</color>";
				}
				_addText.Invoke(description, new object[2]
				{
					text,
					num + 1
				});
			}
		}

		private static List<ItemDescriptionText> Rows(ItemDescription description)
		{
			if (!_resolved)
			{
				_resolved = true;
				_rowsField = AccessTools.Field(typeof(ItemDescription), "enchantmentInUse");
				if (_rowsField == null)
				{
					Plugin.Log.LogWarning((object)"The description's enchantment row list is not where it was; staff rearranging is unavailable.");
				}
			}
			return _rowsField?.GetValue(description) as List<ItemDescriptionText>;
		}

		internal static bool TryResolveBoundary(Vector2 screenPoint, out int boundary, out Vector3 worldPoint)
		{
			//IL_0004: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00de: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ec: Unknown result type (might be due to invalid IL or missing references)
			boundary = 0;
			worldPoint = default(Vector3);
			if (Movable.Count == 0)
			{
				return false;
			}
			Camera val = CameraFor(Movable[0]);
			Vector3[] array = (Vector3[])(object)new Vector3[4];
			for (int i = 0; i < Movable.Count; i++)
			{
				RectTransform val2 = Movable[i];
				if (!((Object)(object)val2 == (Object)null))
				{
					val2.GetWorldCorners(array);
					float y = RectTransformUtility.WorldToScreenPoint(val, (array[0] + array[1]) * 0.5f).y;
					if (screenPoint.y >= y)
					{
						break;
					}
					boundary = i + 1;
				}
			}
			RectTransform val3 = Movable[Mathf.Min(boundary, Movable.Count - 1)];
			if ((Object)(object)val3 == (Object)null)
			{
				return false;
			}
			val3.GetWorldCorners(array);
			worldPoint = ((boundary >= Movable.Count) ? array[0] : array[1]);
			return true;
		}

		private static Camera CameraFor(RectTransform row)
		{
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			Canvas val = (((Object)(object)row != (Object)null) ? ((Component)row).GetComponentInParent<Canvas>() : null);
			if ((Object)(object)val == (Object)null)
			{
				return null;
			}
			val = val.rootCanvas;
			if ((int)val.renderMode != 0)
			{
				return val.worldCamera;
			}
			return null;
		}

		internal static void MoveToBoundary(InventoryItem staff, int from, int boundary)
		{
			Move(staff, from, (boundary > from) ? (boundary - 1) : boundary);
		}

		internal static void Move(InventoryItem staff, int from, int to)
		{
			if (!((Object)(object)staff == (Object)null))
			{
				List<EnchantmentDefinition> enchantments = staff.enchantments;
				if (enchantments != null && from != to && from >= 0 && from < enchantments.Count && to >= 0 && to < enchantments.Count)
				{
					EnchantmentDefinition item = enchantments[from];
					enchantments.RemoveAt(from);
					enchantments.Insert(to, item);
					StaffProgram.Invalidate();
					Rebuild(staff);
				}
			}
		}

		internal static void Rebuild(InventoryItem staff)
		{
			try
			{
				UIManager instance = StaticInstance<UIManager>.Instance;
				object obj;
				if (instance == null)
				{
					obj = null;
				}
				else
				{
					InventoryUI inventoryUI = instance.InventoryUI;
					obj = ((inventoryUI != null) ? inventoryUI.itemDescription : null);
				}
				ItemDescription val = (ItemDescription)obj;
				if (!((Object)(object)val == (Object)null) && !((Object)(object)staff == (Object)null))
				{
					Clear(val);
					val.Setup(staff);
				}
			}
			catch (Exception arg)
			{
				Plugin.Log.LogError((object)$"Could not redraw the staff panel: {arg}");
			}
		}

		private static void Clear(ItemDescription panel)
		{
			if (!_clearResolved)
			{
				_clearResolved = true;
				_clearMethod = AccessTools.Method(typeof(ItemDescription), "ClearDescription", (Type[])null, (Type[])null);
				if (_clearMethod == null)
				{
					Plugin.Log.LogWarning((object)"The description's clear step is not where it was; rearranging would duplicate the panel, so it is disabled.");
				}
			}
			_clearMethod?.Invoke(panel, null);
		}
	}
	internal static class StaffPrefab
	{
		private static readonly string[] BodyRenderers = new string[2] { "Arm.", "Hand." };

		private static GameObject _holder;

		internal static GameObject Build(GameObject donor, Vector3 offset, string mountBone = null)
		{
			//IL_009e: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)donor == (Object)null)
			{
				return null;
			}
			if (!StaffAssets.TryLoad())
			{
				Plugin.Log.LogWarning((object)("The staff keeps the model it was cloned from: " + StaffAssets.FailureReason));
				return null;
			}
			GameObject val = Object.Instantiate<GameObject>(donor, Holder().transform);
			((Object)val).name = "UnholyRites_Staff_Held";
			int kept;
			int hidden;
			Material donorMaterial = HideWeaponGeometry(val, out kept, out hidden);
			if (kept == 0)
			{
				Plugin.Log.LogError((object)($"None of the {hidden + kept} renderers on '{((Object)donor).name}' looked like arms or " + "hands, so the staff model was not fitted. The vanilla weapon prefab layout has probably changed."));
				Object.DestroyImmediate((Object)(object)val);
				return null;
			}
			Transform val2 = ResolveMount(val, mountBone);
			Attach(val, val2, donorMaterial, BodyRenderer(val), offset);
			Plugin.Log.LogInfo((object)($"Staff model fitted to a copy of '{((Object)donor).name}': kept {kept} body renderer(s), " + $"emptied {hidden} weapon renderer(s), mounted on '{((Object)val2).name}'."));
			return val;
		}

		private static GameObject Holder()
		{
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Expected O, but got Unknown
			if ((Object)(object)_holder != (Object)null)
			{
				return _holder;
			}
			_holder = new GameObject("UnholyRites Prefabs");
			_holder.SetActive(false);
			Object.DontDestroyOnLoad((Object)(object)_holder);
			return _holder;
		}

		private static Material HideWeaponGeometry(GameObject template, out int kept, out int hidden)
		{
			Renderer[] componentsInChildren = template.GetComponentsInChildren<Renderer>(true);
			Material val = null;
			kept = 0;
			hidden = 0;
			foreach (Renderer val2 in componentsInChildren)
			{
				if ((Object)(object)val2 == (Object)null)
				{
					continue;
				}
				if (IsBody(((Object)((Component)val2).transform).name))
				{
					kept++;
					continue;
				}
				if ((Object)(object)val == (Object)null && (Object)(object)val2.sharedMaterial != (Object)null)
				{
					val = val2.sharedMaterial;
				}
				if (Empty(val2))
				{
					hidden++;
				}
			}
			return val;
		}

		private static bool Empty(Renderer renderer)
		{
			SkinnedMeshRenderer val = (SkinnedMeshRenderer)(object)((renderer is SkinnedMeshRenderer) ? renderer : null);
			if (val != null)
			{
				if ((Object)(object)val.sharedMesh == (Object)null)
				{
					return false;
				}
				val.sharedMesh = null;
				return true;
			}
			MeshFilter component = ((Component)renderer).GetComponent<MeshFilter>();
			if ((Object)(object)component == (Object)null || (Object)(object)component.sharedMesh == (Object)null)
			{
				return false;
			}
			component.sharedMesh = null;
			return true;
		}

		private static bool IsBody(string name)
		{
			for (int i = 0; i < BodyRenderers.Length; i++)
			{
				if (name.StartsWith(BodyRenderers[i], StringComparison.Ordinal))
				{
					return true;
				}
			}
			return false;
		}

		private static Transform ResolveMount(GameObject template, string preferred)
		{
			Transform[] componentsInChildren = template.GetComponentsInChildren<Transform>(true);
			if (!string.IsNullOrEmpty(preferred))
			{
				for (int i = 0; i < componentsInChildren.Length; i++)
				{
					if (((Object)componentsInChildren[i]).name == preferred)
					{
						return componentsInChildren[i];
					}
				}
				Plugin.Log.LogWarning((object)("The bone '" + preferred + "' a staff is held by was not found; looking for the gun root instead."));
			}
			for (int j = 0; j < componentsInChildren.Length; j++)
			{
				string name = ((Object)componentsInChildren[j]).name;
				if (name.Length > "RootBone".Length && name.EndsWith("RootBone", StringComparison.Ordinal))
				{
					return componentsInChildren[j];
				}
			}
			List<string> list = new List<string>();
			for (int k = 0; k < componentsInChildren.Length; k++)
			{
				if (list.Count >= 40)
				{
					break;
				}
				string name2 = ((Object)componentsInChildren[k]).name;
				if (name2.IndexOf("Bone", StringComparison.OrdinalIgnoreCase) >= 0 || name2.IndexOf("Hand", StringComparison.OrdinalIgnoreCase) >= 0)
				{
					list.Add(name2);
				}
			}
			Plugin.Log.LogWarning((object)("No weapon root bone was found on the donor prefab, so the staff is mounted on the prefab root and will not follow the hand. Bones and hands it has: [" + string.Join(", ", list) + "]."));
			return template.transform;
		}

		private static Renderer BodyRenderer(GameObject template)
		{
			Renderer[] componentsInChildren = template.GetComponentsInChildren<Renderer>(true);
			for (int i = 0; i < componentsInChildren.Length; i++)
			{
				if ((Object)(object)componentsInChildren[i] != (Object)null && IsBody(((Object)((Component)componentsInChildren[i]).transform).name))
				{
					return componentsInChildren[i];
				}
			}
			return null;
		}

		private static void Attach(GameObject template, Transform mount, Material donorMaterial, Renderer body, Vector3 offset)
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			//IL_0092: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = new GameObject("UnholyRites_Staff_Model");
			val.transform.SetParent(mount, false);
			val.layer = (((Object)(object)body != (Object)null) ? ((Component)body).gameObject.layer : template.layer);
			val.AddComponent<MeshFilter>().sharedMesh = StaffAssets.Mesh;
			MeshRenderer val2 = val.AddComponent<MeshRenderer>();
			((Renderer)val2).sharedMaterial = BuildMaterial(donorMaterial);
			((Renderer)val2).shadowCastingMode = (ShadowCastingMode)0;
			((Renderer)val2).receiveShadows = false;
			if ((Object)(object)body != (Object)null)
			{
				((Renderer)val2).renderingLayerMask = body.renderingLayerMask;
			}
			StaffModelTransform staffModelTransform = val.AddComponent<StaffModelTransform>();
			staffModelTransform.Root = template.transform;
			staffModelTransform.Offset = offset;
		}

		private static Material BuildMaterial(Material donorMaterial)
		{
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Expected O, but got Unknown
			//IL_0046: Expected O, but got Unknown
			//IL_0022: 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_002d: Expected O, but got Unknown
			//IL_002e: Expected O, but got Unknown
			if ((Object)(object)donorMaterial == (Object)null)
			{
				Plugin.Log.LogWarning((object)"The donor weapon carried no material, so the staff falls back to a plain one and will not match the game's weapon shading.");
				Material val = new Material(Shader.Find("Universal Render Pipeline/Lit"));
				ApplyPalette(val);
				return val;
			}
			Material val2 = new Material(donorMaterial)
			{
				name = "UnholyRites_Staff"
			};
			ApplyPalette(val2);
			return val2;
		}

		private static void ApplyPalette(Material material)
		{
			if (!((Object)(object)StaffAssets.Palette == (Object)null))
			{
				if (material.HasProperty("_MainTex"))
				{
					material.SetTexture("_MainTex", (Texture)(object)StaffAssets.Palette);
				}
				if (material.HasProperty("_BaseMap"))
				{
					material.SetTexture("_BaseMap", (Texture)(object)StaffAssets.Palette);
				}
			}
		}
	}
	internal sealed class StaffModelTransform : MonoBehaviour
	{
		internal Transform Root;

		public Vector3 Offset;

		private string _appliedPosition;

		private string _appliedRotation;

		private float _appliedScale = float.NaN;

		private Vector3 _appliedParentScale = Vector3.zero;

		private bool _reported;

		private void OnEnable()
		{
			Apply();
		}

		private void LateUpdate()
		{
			Apply();
		}

		internal void Apply()
		{
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: 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_009c: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b1: Unknown result type (might be due to i